lang
stringclasses 2
values | license
stringclasses 13
values | stderr
stringlengths 0
343
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 6
87.7k
| new_contents
stringlengths 0
6.23M
| new_file
stringlengths 3
311
| old_contents
stringlengths 0
6.23M
| message
stringlengths 6
9.1k
| old_file
stringlengths 3
311
| subject
stringlengths 0
4k
| git_diff
stringlengths 0
6.31M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
Java | mit | 7dfdd7b3276b08773e5db3697e0467acf70ed1ed | 0 | Dimensions/Solar | package dimensions.solar.plugin;
import dimensions.solar.command.CommandContainer;
import java.util.ArrayList;
import java.util.List;
public class PluginContainer
{
public String pluginId;
public String name = pluginId;
public String version = "1.0.0";
public List<String> dependencies = new ArrayList<String>();
public List<CommandContainer> commands = new ArrayList<String>();
}
| src/dimensions/solar/plugin/PluginContainer.java | package dimensions.solar.plugin;
import dimensions.solar.command.CommandContainer;
import java.util.ArrayList;
import java.util.List;
public class PluginContainer
{
public String pluginId;
public String name = pluginId;
public String version = "1.0.0";
public List<String> dependencies = new ArrayList<>();
public List<CommandContainer> commands = new ArrayList<>();
}
| Fix ArrayLists | src/dimensions/solar/plugin/PluginContainer.java | Fix ArrayLists | <ide><path>rc/dimensions/solar/plugin/PluginContainer.java
<ide> public String pluginId;
<ide> public String name = pluginId;
<ide> public String version = "1.0.0";
<del> public List<String> dependencies = new ArrayList<>();
<del> public List<CommandContainer> commands = new ArrayList<>();
<add> public List<String> dependencies = new ArrayList<String>();
<add> public List<CommandContainer> commands = new ArrayList<String>();
<ide> } |
|
Java | mit | c9fab433b010ba911283227df169751831a9f334 | 0 | typetools/annotation-tools,eisop/annotation-tools,typetools/annotation-tools,typetools/annotation-tools,eisop/annotation-tools,eisop/annotation-tools | package annotator.specification;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.objectweb.asm.ClassReader;
import plume.FileIOException;
import plume.Pair;
import type.DeclaredType;
import type.Type;
import annotations.Annotation;
import annotations.el.ABlock;
import annotations.el.AClass;
import annotations.el.AElement;
import annotations.el.AExpression;
import annotations.el.AField;
import annotations.el.AMethod;
import annotations.el.AScene;
import annotations.el.ATypeElement;
import annotations.el.ATypeElementWithType;
import annotations.el.AnnotationDef;
import annotations.el.BoundLocation;
import annotations.el.InnerTypeLocation;
import annotations.el.LocalLocation;
import annotations.el.RelativeLocation;
import annotations.el.TypeIndexLocation;
import annotations.field.AnnotationFieldType;
import annotations.io.ASTPath;
import annotations.io.IndexFileParser;
import annotations.util.coll.VivifyingMap;
import annotator.find.AnnotationInsertion;
import annotator.find.CastInsertion;
import annotator.find.ConstructorInsertion;
import annotator.find.CloseParenthesisInsertion;
import annotator.find.Criteria;
import annotator.find.GenericArrayLocationCriterion;
import annotator.find.Insertion;
import annotator.find.NewInsertion;
import annotator.find.ReceiverInsertion;
import annotator.scanner.MethodOffsetClassVisitor;
import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.Multimap;
import com.sun.source.tree.Tree;
public class IndexFileSpecification implements Specification {
private final Multimap<Insertion, Annotation> insertionSources =
LinkedHashMultimap.<Insertion, Annotation>create();
private final List<Insertion> insertions = new ArrayList<Insertion>();
private final AScene scene;
private final String indexFileName;
// If set, do not attempt to read class files with Asm.
// Mostly for debugging and workarounds.
public static boolean noAsm = false;
private static boolean debug = false;
private ConstructorInsertion cons = null;
public IndexFileSpecification(String indexFileName) {
this.indexFileName = indexFileName;
scene = new AScene();
}
@Override
public List<Insertion> parse() throws FileIOException {
try {
IndexFileParser.parseFile(indexFileName, scene);
} catch(FileIOException e) {
throw e;
} catch(Exception e) {
throw new RuntimeException("Exception while parsing index file", e);
}
if (debug) {
System.out.printf("Scene parsed from %s:%n", indexFileName);
System.out.println(scene.unparse());
}
parseScene();
// debug("---------------------------------------------------------");
return this.insertions;
}
public Map<String, Set<String>> annotationImports() {
return scene.imports;
}
public Multimap<Insertion, Annotation> insertionSources() {
return insertionSources;
}
private void addInsertionSource(Insertion ins, Annotation anno) {
insertionSources.put(ins, anno);
}
private static void debug(String s) {
if (debug) {
System.out.println(s);
}
}
/*
private static void debug(String s, Object... args) {
if (debug) {
System.out.printf(s, args);
}
}
*/
public AScene getScene() { return scene; }
/** Fill in this.insertions with insertion pairs. */
private void parseScene() {
debug("parseScene()");
// Empty criterion to work from.
CriterionList clist = new CriterionList();
VivifyingMap<String, AElement> packages = scene.packages;
for (Map.Entry<String, AElement> entry : packages.entrySet()) {
parsePackage(clist, entry.getKey(), entry.getValue());
}
VivifyingMap<String, AClass> classes = scene.classes;
for (Map.Entry<String, AClass> entry : classes.entrySet()) {
parseClass(clist, entry.getKey(), entry.getValue());
}
}
// There is no .class file corresponding to the package-info.java file.
private void parsePackage(CriterionList clist, String packageName, AElement element) {
// There is no Tree.Kind.PACKAGE, only Tree.Kind.COMPILATION_UNIT.
// CompilationUnitTree has getPackageName and getPackageAnnotations
CriterionList packageClist = clist.add(Criteria.packageDecl(packageName));
parseElement(packageClist, element);
}
/** Fill in this.insertions with insertion pairs.
* @param className is fully qualified
*/
private void parseClass(CriterionList clist, String className, AClass clazz) {
cons = null; // 0 or 1 per class
if (! noAsm) {
// load extra info using asm
debug("parseClass(" + className + ")");
try {
ClassReader classReader = new ClassReader(className);
MethodOffsetClassVisitor cv = new MethodOffsetClassVisitor();
classReader.accept(cv, false);
debug("Done reading " + className + ".class");
} catch (IOException e) {
// If .class file not found, still proceed, in case
// user only wants method signature annotations.
// (TODO: It would be better to store which classes could not be
// found, then issue a warning only if an attempt is made to use
// the (missing) information. See
// https://code.google.com/p/annotation-tools/issues/detail?id=34 .)
System.out.println("Warning: IndexFileSpecification did not find classfile for: " + className);
// throw new RuntimeException("IndexFileSpecification.parseClass: " + e);
} catch (RuntimeException e) {
System.err.println("IndexFileSpecification had a problem reading class: " + className);
throw e;
} catch (Error e) {
System.err.println("IndexFileSpecification had a problem reading class: " + className);
throw e;
}
}
CriterionList clistSansClass = clist;
clist = clist.add(Criteria.inClass(className, true));
CriterionList classClist = clistSansClass.add(Criteria.is(Tree.Kind.CLASS, className));
parseElement(classClist, clazz);
VivifyingMap<BoundLocation, ATypeElement> bounds = clazz.bounds;
for (Entry<BoundLocation, ATypeElement> entry : bounds.entrySet()) {
BoundLocation boundLoc = entry.getKey();
ATypeElement bound = entry.getValue();
CriterionList boundList = clist.add(Criteria.classBound(className, boundLoc));
for (Entry<InnerTypeLocation, ATypeElement> innerEntry : bound.innerTypes.entrySet()) {
InnerTypeLocation innerLoc = innerEntry.getKey();
AElement ae = innerEntry.getValue();
CriterionList innerBoundList = boundList.add(Criteria.atLocation(innerLoc));
parseElement(innerBoundList, ae);
}
CriterionList outerClist = boundList.add(Criteria.atLocation());
parseElement(outerClist, bound);
}
clist = clist.add(Criteria.inClass(className, /*exactMatch=*/ false));
VivifyingMap<TypeIndexLocation, ATypeElement> extimpl = clazz.extendsImplements;
for (Entry<TypeIndexLocation, ATypeElement> entry : extimpl.entrySet()) {
TypeIndexLocation eiLoc = entry.getKey();
ATypeElement ei = entry.getValue();
CriterionList eiList = clist.add(Criteria.atExtImplsLocation(className, eiLoc));
for (Entry<InnerTypeLocation, ATypeElement> innerEntry : ei.innerTypes.entrySet()) {
InnerTypeLocation innerLoc = innerEntry.getKey();
AElement ae = innerEntry.getValue();
CriterionList innerBoundList = eiList.add(Criteria.atLocation(innerLoc));
parseElement(innerBoundList, ae);
}
CriterionList outerClist = eiList.add(Criteria.atLocation());
parseElement(outerClist, ei);
}
parseASTInsertions(clist, clazz.insertAnnotations, clazz.insertTypecasts);
for (Map.Entry<String, AField> entry : clazz.fields.entrySet()) {
// clist = clist.add(Criteria.notInMethod()); // TODO: necessary? what is in class but not in method?
parseField(clist, entry.getKey(), entry.getValue());
}
for (Map.Entry<String, AMethod> entry : clazz.methods.entrySet()) {
parseMethod(clist, className, entry.getKey(), entry.getValue());
}
for (Map.Entry<Integer, ABlock> entry : clazz.staticInits.entrySet()) {
parseStaticInit(clist, entry.getKey(), entry.getValue());
}
for (Map.Entry<Integer, ABlock> entry : clazz.instanceInits.entrySet()) {
parseInstanceInit(clist, entry.getKey(), entry.getValue());
}
for (Map.Entry<String, AExpression> entry : clazz.fieldInits.entrySet()) {
parseFieldInit(clist, entry.getKey(), entry.getValue());
}
debug("parseClass(" + className + "): done");
}
/** Fill in this.insertions with insertion pairs. */
private void parseField(CriterionList clist, String fieldName, AField field) {
clist = clist.add(Criteria.field(fieldName));
// parse declaration annotations
parseElement(clist, field);
parseInnerAndOuterElements(clist, field.type);
parseASTInsertions(clist, field.insertAnnotations, field.insertTypecasts);
}
private void parseStaticInit(CriterionList clist, int blockID, ABlock block) {
clist = clist.add(Criteria.inStaticInit(blockID));
// the method name argument is not used for static initializers, which are only used
// in source specifications. Same for instance and field initializers.
// the empty () are there to prevent the whole string to be removed in later parsing.
parseBlock(clist, "static init number " + blockID + "()", block);
}
private void parseInstanceInit(CriterionList clist, int blockID, ABlock block) {
clist = clist.add(Criteria.inInstanceInit(blockID));
parseBlock(clist, "instance init number " + blockID + "()", block);
}
// keep the descriptive strings for field initializers and static inits consistent
// with text used in NewCriterion.
private void parseFieldInit(CriterionList clist, String fieldName, AExpression exp) {
clist = clist.add(Criteria.inFieldInit(fieldName));
parseExpression(clist, "init for field " + fieldName + "()", exp);
}
/**
* Fill in this.insertions with insertion pairs.
* @param clist The criteria specifying the location of the insertions.
* @param element Holds the annotations to be inserted.
* @return A list of the {@link AnnotationInsertion}s that are created.
*/
private List<Insertion> parseElement(CriterionList clist, AElement element) {
return parseElement(clist, element, new ArrayList<Insertion>(), false);
}
/**
* Fill in this.insertions with insertion pairs.
* @param clist The criteria specifying the location of the insertions.
* @param element Holds the annotations to be inserted.
* @param isCastInsertion {@code true} if this for a cast insertion, {@code false}
* otherwise.
* @return A list of the {@link AnnotationInsertion}s that are created.
*/
private List<Insertion> parseElement(CriterionList clist, AElement element,
boolean isCastInsertion) {
return parseElement(clist, element, new ArrayList<Insertion>(), isCastInsertion);
}
/**
* Fill in this.insertions with insertion pairs.
* @param clist The criteria specifying the location of the insertions.
* @param element Holds the annotations to be inserted.
* @param add {@code true} if the create {@link AnnotationInsertion}s should
* be added to {@link #insertions}, {@code false} otherwise.
* @return A list of the {@link AnnotationInsertion}s that are created.
*/
private List<Insertion> parseElement(CriterionList clist, AElement element,
List<Insertion> innerTypeInsertions) {
return parseElement(clist, element, innerTypeInsertions, false);
}
/**
* Fill in this.insertions with insertion pairs.
* @param clist The criteria specifying the location of the insertions.
* @param element Holds the annotations to be inserted.
* @param innerTypeInsertions The insertions on the inner type of this
* element. This is only used for receiver and "new" insertions.
* See {@link ReceiverInsertion} for more details.
* @param isCastInsertion {@code true} if this for a cast insertion, {@code false}
* otherwise.
* @return A list of the {@link AnnotationInsertion}s that are created.
*/
private List<Insertion> parseElement(CriterionList clist, AElement element,
List<Insertion> innerTypeInsertions, boolean isCastInsertion) {
// Use at most one receiver and one cast insertion and add all of the
// annotations to the one insertion.
ReceiverInsertion receiver = null;
NewInsertion neu = null;
CastInsertion cast = null;
CloseParenthesisInsertion closeParen = null;
List<Insertion> annotationInsertions = new ArrayList<Insertion>();
Set<Pair<String, Annotation>> elementAnnotations = getElementAnnotations(element);
if (elementAnnotations.isEmpty()) {
Criteria criteria = clist.criteria();
if (element instanceof ATypeElementWithType) {
// Still insert even if it's a cast insertion with no outer
// annotations to just insert a cast, or insert a cast with
// annotations on the compound types.
Pair<CastInsertion, CloseParenthesisInsertion> pair =
createCastInsertion(((ATypeElementWithType) element).getType(),
null, innerTypeInsertions, criteria);
cast = pair.a;
closeParen = pair.b;
} else if (!innerTypeInsertions.isEmpty()) {
if (isOnReceiver(criteria)) {
receiver = new ReceiverInsertion(new DeclaredType(),
criteria, innerTypeInsertions);
} else if (isOnNew(criteria)) {
neu = new NewInsertion(new DeclaredType(),
criteria, innerTypeInsertions);
}
}
}
for (Pair<String, Annotation> p : elementAnnotations) {
List<Insertion> elementInsertions = new ArrayList<Insertion>();
String annotationString = p.a;
Annotation annotation = p.b;
Boolean isDeclarationAnnotation = !annotation.def.isTypeAnnotation();
Criteria criteria = clist.criteria();
if (noTypePath(criteria) && isOnReceiver(criteria)) {
if (receiver == null) {
DeclaredType type = new DeclaredType();
type.addAnnotation(annotationString);
receiver = new ReceiverInsertion(type, criteria, innerTypeInsertions);
elementInsertions.add(receiver);
} else {
receiver.getType().addAnnotation(annotationString);
}
addInsertionSource(receiver, annotation);
} else if (noTypePath(criteria) && isOnNew(criteria)) {
if (neu == null) {
DeclaredType type = new DeclaredType();
type.addAnnotation(annotationString);
neu = new NewInsertion(type, criteria, innerTypeInsertions);
elementInsertions.add(neu);
} else {
neu.getType().addAnnotation(annotationString);
}
addInsertionSource(neu, annotation);
} else if (element instanceof ATypeElementWithType) {
if (cast == null) {
Pair<CastInsertion, CloseParenthesisInsertion> insertions = createCastInsertion(
((ATypeElementWithType) element).getType(), annotationString,
innerTypeInsertions, criteria);
cast = insertions.a;
closeParen = insertions.b;
elementInsertions.add(cast);
elementInsertions.add(closeParen);
// no addInsertionSource, as closeParen is not explicit in scene
} else {
cast.getType().addAnnotation(annotationString);
}
addInsertionSource(cast, annotation);
} else {
Insertion ins = new AnnotationInsertion(annotationString, criteria,
isDeclarationAnnotation);
debug("parsed: " + ins);
if (!isCastInsertion) {
// Annotations on compound types of a cast insertion will be
// inserted directly on the cast insertion.
//this.insertions.add(ins);
elementInsertions.add(ins);
}
annotationInsertions.add(ins);
addInsertionSource(ins, annotation);
}
this.insertions.addAll(elementInsertions);
// exclude expression annotations
if (noTypePath(criteria) && isOnNullaryConstructor(criteria)) {
if (cons == null) {
DeclaredType type = new DeclaredType(criteria.getClassName());
cons = new ConstructorInsertion(type, criteria,
new ArrayList<Insertion>());
this.insertions.add(cons);
}
// no addInsertionSource, as cons is not explicit in scene
for (Insertion i : elementInsertions) {
if (i.getKind() == Insertion.Kind.RECEIVER) {
cons.addReceiverInsertion((ReceiverInsertion) i);
} else if (criteria.isOnReturnType()) {
((DeclaredType) cons.getType()).addAnnotation(annotationString);
} else if (isDeclarationAnnotation) {
cons.addDeclarationInsertion(i);
i.setInserted(true);
} else {
annotationInsertions.add(i);
}
}
}
elementInsertions.clear();
}
if (receiver != null) {
this.insertions.add(receiver);
}
if (neu != null) {
this.insertions.add(neu);
}
if (cast != null) {
this.insertions.add(cast);
this.insertions.add(closeParen);
}
return annotationInsertions;
}
private boolean noTypePath(Criteria criteria) {
GenericArrayLocationCriterion galc =
criteria.getGenericArrayLocation();
return galc == null || galc.getLocation().isEmpty();
}
public static boolean isOnReceiver(Criteria criteria) {
ASTPath astPath = criteria.getASTPath();
if (astPath == null) { return criteria.isOnReceiver(); }
if (astPath.isEmpty()) { return false; }
ASTPath.ASTEntry entry = astPath.get(-1);
return entry.childSelectorIs(ASTPath.PARAMETER)
&& entry.getArgument() < 0;
}
public static boolean isOnNew(Criteria criteria) {
ASTPath astPath = criteria.getASTPath();
if (astPath == null || astPath.isEmpty()) { return criteria.isOnNew(); }
ASTPath.ASTEntry entry = astPath.get(-1);
Tree.Kind kind = entry.getTreeKind();
return (kind == Tree.Kind.NEW_ARRAY || kind == Tree.Kind.NEW_CLASS)
&& entry.childSelectorIs(ASTPath.TYPE) && entry.getArgument() == 0;
}
private static boolean isOnNullaryConstructor(Criteria criteria) {
if (criteria.isOnMethod("<init>()V")) {
ASTPath astPath = criteria.getASTPath();
if (astPath == null || astPath.isEmpty()) {
return !criteria.isOnNew(); // exclude expression annotations
}
ASTPath.ASTEntry entry = astPath.get(0);
return entry.getTreeKind() == Tree.Kind.METHOD
&& entry.childSelectorIs(ASTPath.TYPE);
}
return false;
}
/**
* Creates the {@link CastInsertion} and {@link CloseParenthesisInsertion}
* for a cast insertion.
*
* @param type The cast type to insert.
* @param annotationString The annotation on the outermost type, or
* {@code null} if none. With no outermost annotation this cast
* insertion will either be a cast without any annotations or a cast
* with annotations only on the compound types.
* @param innerTypeInsertions The annotations on the inner types.
* @param criteria The criteria for the location of this insertion.
* @return The {@link CastInsertion} and {@link CloseParenthesisInsertion}.
*/
private Pair<CastInsertion, CloseParenthesisInsertion> createCastInsertion(
Type type, String annotationString, List<Insertion> innerTypeInsertions,
Criteria criteria) {
if (annotationString != null) {
type.addAnnotation(annotationString);
}
Insertion.decorateType(innerTypeInsertions, type, criteria.getASTPath());
CastInsertion cast = new CastInsertion(criteria, type);
CloseParenthesisInsertion closeParen = new CloseParenthesisInsertion(
criteria, cast.getSeparateLine());
return new Pair<CastInsertion, CloseParenthesisInsertion>(cast, closeParen);
}
/**
* Fill in this.insertions with insertion pairs for the outer and inner types.
* @param clist The criteria specifying the location of the insertions.
* @param typeElement Holds the annotations to be inserted.
*/
private void parseInnerAndOuterElements(CriterionList clist, ATypeElement typeElement) {
parseInnerAndOuterElements(clist, typeElement, false);
}
/**
* Fill in this.insertions with insertion pairs for the outer and inner types.
* @param clist The criteria specifying the location of the insertions.
* @param typeElement Holds the annotations to be inserted.
* @param isCastInsertion {@code true} if this for a cast insertion, {@code false}
* otherwise.
*/
private void parseInnerAndOuterElements(CriterionList clist,
ATypeElement typeElement, boolean isCastInsertion) {
List<Insertion> innerInsertions = new ArrayList<Insertion>();
for (Entry<InnerTypeLocation, ATypeElement> innerEntry: typeElement.innerTypes.entrySet()) {
InnerTypeLocation innerLoc = innerEntry.getKey();
AElement innerElement = innerEntry.getValue();
CriterionList innerClist = clist.add(Criteria.atLocation(innerLoc));
innerInsertions.addAll(parseElement(innerClist, innerElement, isCastInsertion));
}
CriterionList outerClist = clist;
if (!isCastInsertion) {
// Cast insertion is never on an existing type.
outerClist = clist.add(Criteria.atLocation());
}
parseElement(outerClist, typeElement, innerInsertions);
}
// Returns a string representation of the annotations at the element.
private Set<Pair<String, Annotation>>
getElementAnnotations(AElement element) {
Set<Pair<String, Annotation>> result =
new LinkedHashSet<Pair<String, Annotation>>(
element.tlAnnotationsHere.size());
for (Annotation a : element.tlAnnotationsHere) {
AnnotationDef adef = a.def;
String annotationString = "@" + adef.name;
if (a.fieldValues.size() == 1 && a.fieldValues.containsKey("value")) {
annotationString += "(" + formatFieldValue(a, "value") + ")";
} else if (a.fieldValues.size() > 0) {
annotationString += "(";
boolean first = true;
for (String field : a.fieldValues.keySet()) {
// parameters of the annotation
if (!first) {
annotationString += ", ";
}
annotationString += field + "=" + formatFieldValue(a, field);
first = false;
}
annotationString += ")";
}
// annotationString += " ";
result.add(new Pair<String, Annotation>(annotationString, a));
}
return result;
}
private String formatFieldValue(Annotation a, String field) {
AnnotationFieldType fieldType = a.def.fieldTypes.get(field);
assert fieldType != null;
return fieldType.format(a.fieldValues.get(field));
}
private void parseMethod(CriterionList clist, String className, String methodName, AMethod method) {
// Being "in" a method refers to being somewhere in the
// method's tree, which includes return types, parameters, receiver, and
// elements inside the method body.
clist = clist.add(Criteria.inMethod(methodName));
// parse declaration annotations
parseElement(clist, method);
// parse receiver
CriterionList receiverClist = clist.add(Criteria.receiver(methodName));
parseInnerAndOuterElements(receiverClist, method.receiver.type);
// parse return type
CriterionList returnClist = clist.add(Criteria.returnType(className, methodName));
parseInnerAndOuterElements(returnClist, method.returnType);
// parse bounds of method
for (Entry<BoundLocation, ATypeElement> entry : method.bounds.entrySet()) {
BoundLocation boundLoc = entry.getKey();
ATypeElement bound = entry.getValue();
CriterionList boundClist = clist.add(Criteria.methodBound(methodName, boundLoc));
parseInnerAndOuterElements(boundClist, bound);
}
// parse parameters of method
for (Entry<Integer, AField> entry : method.parameters.entrySet()) {
Integer index = entry.getKey();
AField param = entry.getValue();
CriterionList paramClist = clist.add(Criteria.param(methodName, index));
// parse declaration annotations
parseField(paramClist, index.toString(), param);
parseInnerAndOuterElements(paramClist, param.type);
}
// parse insert annotations/typecasts of method
parseASTInsertions(clist, method.insertAnnotations, method.insertTypecasts);
parseBlock(clist, methodName, method.body);
}
private void parseBlock(CriterionList clist, String methodName, ABlock block) {
// parse locals of method
for (Entry<LocalLocation, AField> entry : block.locals.entrySet()) {
LocalLocation loc = entry.getKey();
AElement var = entry.getValue();
CriterionList varClist = clist.add(Criteria.local(methodName, loc));
// parse declaration annotations
parseElement(varClist, var); // TODO: _?_
parseInnerAndOuterElements(varClist, var.type);
}
parseExpression(clist, methodName, block);
}
private void parseExpression(CriterionList clist, String methodName, AExpression exp) {
// parse typecasts of method
for (Entry<RelativeLocation, ATypeElement> entry : exp.typecasts.entrySet()) {
RelativeLocation loc = entry.getKey();
ATypeElement cast = entry.getValue();
CriterionList castClist = clist.add(Criteria.cast(methodName, loc));
parseInnerAndOuterElements(castClist, cast);
}
// parse news (object creation) of method
for (Entry<RelativeLocation, ATypeElement> entry : exp.news.entrySet()) {
RelativeLocation loc = entry.getKey();
ATypeElement newObject = entry.getValue();
CriterionList newClist = clist.add(Criteria.newObject(methodName, loc));
parseInnerAndOuterElements(newClist, newObject);
}
// parse instanceofs of method
for (Entry<RelativeLocation, ATypeElement> entry : exp.instanceofs.entrySet()) {
RelativeLocation loc = entry.getKey();
ATypeElement instanceOf = entry.getValue();
CriterionList instanceOfClist = clist.add(Criteria.instanceOf(methodName, loc));
parseInnerAndOuterElements(instanceOfClist, instanceOf);
}
}
private void parseASTInsertions(CriterionList clist,
VivifyingMap<ASTPath, ATypeElement> insertAnnotations,
VivifyingMap<ASTPath, ATypeElementWithType> insertTypecasts) {
for (Entry<ASTPath, ATypeElement> entry : insertAnnotations.entrySet()) {
ASTPath astPath = entry.getKey();
ATypeElement insertAnnotation = entry.getValue();
CriterionList insertAnnotationClist =
clist.add(Criteria.astPath(astPath));
parseInnerAndOuterElements(insertAnnotationClist,
insertAnnotation, true);
}
for (Entry<ASTPath, ATypeElementWithType> entry : insertTypecasts.entrySet()) {
ASTPath astPath = entry.getKey();
ATypeElementWithType insertTypecast = entry.getValue();
CriterionList insertTypecastClist = clist.add(Criteria.astPath(astPath));
parseInnerAndOuterElements(insertTypecastClist, insertTypecast, true);
}
}
}
| annotation-file-utilities/src/annotator/specification/IndexFileSpecification.java | package annotator.specification;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.objectweb.asm.ClassReader;
import plume.FileIOException;
import plume.Pair;
import type.DeclaredType;
import type.Type;
import annotations.Annotation;
import annotations.el.ABlock;
import annotations.el.AClass;
import annotations.el.AElement;
import annotations.el.AExpression;
import annotations.el.AField;
import annotations.el.AMethod;
import annotations.el.AScene;
import annotations.el.ATypeElement;
import annotations.el.ATypeElementWithType;
import annotations.el.AnnotationDef;
import annotations.el.BoundLocation;
import annotations.el.InnerTypeLocation;
import annotations.el.LocalLocation;
import annotations.el.RelativeLocation;
import annotations.el.TypeIndexLocation;
import annotations.field.AnnotationFieldType;
import annotations.io.ASTPath;
import annotations.io.IndexFileParser;
import annotations.util.coll.VivifyingMap;
import annotator.find.AnnotationInsertion;
import annotator.find.CastInsertion;
import annotator.find.ConstructorInsertion;
import annotator.find.CloseParenthesisInsertion;
import annotator.find.Criteria;
import annotator.find.GenericArrayLocationCriterion;
import annotator.find.Insertion;
import annotator.find.NewInsertion;
import annotator.find.ReceiverInsertion;
import annotator.scanner.MethodOffsetClassVisitor;
import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.Multimap;
import com.sun.source.tree.Tree;
public class IndexFileSpecification implements Specification {
private final Multimap<Insertion, Annotation> insertionSources =
LinkedHashMultimap.<Insertion, Annotation>create();
private final List<Insertion> insertions = new ArrayList<Insertion>();
private final AScene scene;
private final String indexFileName;
// If set, do not attempt to read class files with Asm.
// Mostly for debugging and workarounds.
public static boolean noAsm = false;
private static boolean debug = false;
private ConstructorInsertion cons = null;
public IndexFileSpecification(String indexFileName) {
this.indexFileName = indexFileName;
scene = new AScene();
}
@Override
public List<Insertion> parse() throws FileIOException {
try {
IndexFileParser.parseFile(indexFileName, scene);
} catch(FileIOException e) {
throw e;
} catch(Exception e) {
throw new RuntimeException("Exception while parsing index file", e);
}
if (debug) {
System.out.printf("Scene parsed from %s:%n", indexFileName);
System.out.println(scene.unparse());
}
parseScene();
// debug("---------------------------------------------------------");
return this.insertions;
}
public Map<String, Set<String>> annotationImports() {
return scene.imports;
}
public Multimap<Insertion, Annotation> insertionSources() {
return insertionSources;
}
private void addInsertionSource(Insertion ins, Annotation anno) {
insertionSources.put(ins, anno);
}
private static void debug(String s) {
if (debug) {
System.out.println(s);
}
}
/*
private static void debug(String s, Object... args) {
if (debug) {
System.out.printf(s, args);
}
}
*/
public AScene getScene() { return scene; }
/** Fill in this.insertions with insertion pairs. */
private void parseScene() {
debug("parseScene()");
// Empty criterion to work from.
CriterionList clist = new CriterionList();
VivifyingMap<String, AElement> packages = scene.packages;
for (Map.Entry<String, AElement> entry : packages.entrySet()) {
parsePackage(clist, entry.getKey(), entry.getValue());
}
VivifyingMap<String, AClass> classes = scene.classes;
for (Map.Entry<String, AClass> entry : classes.entrySet()) {
parseClass(clist, entry.getKey(), entry.getValue());
}
}
// There is no .class file corresponding to the package-info.java file.
private void parsePackage(CriterionList clist, String packageName, AElement element) {
// There is no Tree.Kind.PACKAGE, only Tree.Kind.COMPILATION_UNIT.
// CompilationUnitTree has getPackageName and getPackageAnnotations
CriterionList packageClist = clist.add(Criteria.packageDecl(packageName));
parseElement(packageClist, element);
}
/** Fill in this.insertions with insertion pairs.
* @param className is fully qualified
*/
private void parseClass(CriterionList clist, String className, AClass clazz) {
cons = null; // 0 or 1 per class
if (! noAsm) {
// load extra info using asm
debug("parseClass(" + className + ")");
try {
ClassReader classReader = new ClassReader(className);
MethodOffsetClassVisitor cv = new MethodOffsetClassVisitor();
classReader.accept(cv, false);
debug("Done reading " + className + ".class");
} catch (IOException e) {
// If .class file not found, still proceed, in case
// user only wants method signature annotations.
// (TODO: It would be better to store which classes could not be
// found, then issue a warning only if an attempt is made to use
// the (missing) information. See
// https://code.google.com/p/annotation-tools/issues/detail?id=34 .)
System.out.println("Warning: IndexFileSpecification did not find classfile for: " + className);
// throw new RuntimeException("IndexFileSpecification.parseClass: " + e);
} catch (RuntimeException e) {
System.err.println("IndexFileSpecification had a problem reading class: " + className);
throw e;
} catch (Error e) {
System.err.println("IndexFileSpecification had a problem reading class: " + className);
throw e;
}
}
CriterionList clistSansClass = clist;
clist = clist.add(Criteria.inClass(className, true));
CriterionList classClist = clistSansClass.add(Criteria.is(Tree.Kind.CLASS, className));
parseElement(classClist, clazz);
VivifyingMap<BoundLocation, ATypeElement> bounds = clazz.bounds;
for (Entry<BoundLocation, ATypeElement> entry : bounds.entrySet()) {
BoundLocation boundLoc = entry.getKey();
ATypeElement bound = entry.getValue();
CriterionList boundList = clist.add(Criteria.classBound(className, boundLoc));
for (Entry<InnerTypeLocation, ATypeElement> innerEntry : bound.innerTypes.entrySet()) {
InnerTypeLocation innerLoc = innerEntry.getKey();
AElement ae = innerEntry.getValue();
CriterionList innerBoundList = boundList.add(Criteria.atLocation(innerLoc));
parseElement(innerBoundList, ae);
}
CriterionList outerClist = boundList.add(Criteria.atLocation());
parseElement(outerClist, bound);
}
clist = clist.add(Criteria.inClass(className, /*exactMatch=*/ false));
VivifyingMap<TypeIndexLocation, ATypeElement> extimpl = clazz.extendsImplements;
for (Entry<TypeIndexLocation, ATypeElement> entry : extimpl.entrySet()) {
TypeIndexLocation eiLoc = entry.getKey();
ATypeElement ei = entry.getValue();
CriterionList eiList = clist.add(Criteria.atExtImplsLocation(className, eiLoc));
for (Entry<InnerTypeLocation, ATypeElement> innerEntry : ei.innerTypes.entrySet()) {
InnerTypeLocation innerLoc = innerEntry.getKey();
AElement ae = innerEntry.getValue();
CriterionList innerBoundList = eiList.add(Criteria.atLocation(innerLoc));
parseElement(innerBoundList, ae);
}
CriterionList outerClist = eiList.add(Criteria.atLocation());
parseElement(outerClist, ei);
}
parseASTInsertions(clist, clazz.insertAnnotations, clazz.insertTypecasts);
for (Map.Entry<String, AField> entry : clazz.fields.entrySet()) {
// clist = clist.add(Criteria.notInMethod()); // TODO: necessary? what is in class but not in method?
parseField(clist, entry.getKey(), entry.getValue());
}
for (Map.Entry<String, AMethod> entry : clazz.methods.entrySet()) {
parseMethod(clist, className, entry.getKey(), entry.getValue());
}
for (Map.Entry<Integer, ABlock> entry : clazz.staticInits.entrySet()) {
parseStaticInit(clist, entry.getKey(), entry.getValue());
}
for (Map.Entry<Integer, ABlock> entry : clazz.instanceInits.entrySet()) {
parseInstanceInit(clist, entry.getKey(), entry.getValue());
}
for (Map.Entry<String, AExpression> entry : clazz.fieldInits.entrySet()) {
parseFieldInit(clist, entry.getKey(), entry.getValue());
}
debug("parseClass(" + className + "): done");
}
/** Fill in this.insertions with insertion pairs. */
private void parseField(CriterionList clist, String fieldName, AField field) {
clist = clist.add(Criteria.field(fieldName));
// parse declaration annotations
parseElement(clist, field);
parseInnerAndOuterElements(clist, field.type);
parseASTInsertions(clist, field.insertAnnotations, field.insertTypecasts);
}
private void parseStaticInit(CriterionList clist, int blockID, ABlock block) {
clist = clist.add(Criteria.inStaticInit(blockID));
// the method name argument is not used for static initializers, which are only used
// in source specifications. Same for instance and field initializers.
// the empty () are there to prevent the whole string to be removed in later parsing.
parseBlock(clist, "static init number " + blockID + "()", block);
}
private void parseInstanceInit(CriterionList clist, int blockID, ABlock block) {
clist = clist.add(Criteria.inInstanceInit(blockID));
parseBlock(clist, "instance init number " + blockID + "()", block);
}
// keep the descriptive strings for field initializers and static inits consistent
// with text used in NewCriterion.
private void parseFieldInit(CriterionList clist, String fieldName, AExpression exp) {
clist = clist.add(Criteria.inFieldInit(fieldName));
parseExpression(clist, "init for field " + fieldName + "()", exp);
}
/**
* Fill in this.insertions with insertion pairs.
* @param clist The criteria specifying the location of the insertions.
* @param element Holds the annotations to be inserted.
* @return A list of the {@link AnnotationInsertion}s that are created.
*/
private List<Insertion> parseElement(CriterionList clist, AElement element) {
return parseElement(clist, element, new ArrayList<Insertion>(), false);
}
/**
* Fill in this.insertions with insertion pairs.
* @param clist The criteria specifying the location of the insertions.
* @param element Holds the annotations to be inserted.
* @param isCastInsertion {@code true} if this for a cast insertion, {@code false}
* otherwise.
* @return A list of the {@link AnnotationInsertion}s that are created.
*/
private List<Insertion> parseElement(CriterionList clist, AElement element,
boolean isCastInsertion) {
return parseElement(clist, element, new ArrayList<Insertion>(), isCastInsertion);
}
/**
* Fill in this.insertions with insertion pairs.
* @param clist The criteria specifying the location of the insertions.
* @param element Holds the annotations to be inserted.
* @param add {@code true} if the create {@link AnnotationInsertion}s should
* be added to {@link #insertions}, {@code false} otherwise.
* @return A list of the {@link AnnotationInsertion}s that are created.
*/
private List<Insertion> parseElement(CriterionList clist, AElement element,
List<Insertion> innerTypeInsertions) {
return parseElement(clist, element, innerTypeInsertions, false);
}
/**
* Fill in this.insertions with insertion pairs.
* @param clist The criteria specifying the location of the insertions.
* @param element Holds the annotations to be inserted.
* @param innerTypeInsertions The insertions on the inner type of this
* element. This is only used for receiver and "new" insertions.
* See {@link ReceiverInsertion} for more details.
* @param isCastInsertion {@code true} if this for a cast insertion, {@code false}
* otherwise.
* @return A list of the {@link AnnotationInsertion}s that are created.
*/
private List<Insertion> parseElement(CriterionList clist, AElement element,
List<Insertion> innerTypeInsertions, boolean isCastInsertion) {
// Use at most one receiver and one cast insertion and add all of the
// annotations to the one insertion.
ReceiverInsertion receiver = null;
NewInsertion neu = null;
CastInsertion cast = null;
CloseParenthesisInsertion closeParen = null;
List<Insertion> annotationInsertions = new ArrayList<Insertion>();
Set<Pair<String, Annotation>> elementAnnotations = getElementAnnotations(element);
if (element instanceof ATypeElementWithType && elementAnnotations.isEmpty()) {
// Still insert even if it's a cast insertion with no outer annotations to
// just insert a cast, or insert a cast with annotations on the compound
// types.
Pair<CastInsertion, CloseParenthesisInsertion> insertions = createCastInsertion(
((ATypeElementWithType) element).getType(), null,
innerTypeInsertions, clist.criteria());
cast = insertions.a;
closeParen = insertions.b;
}
for (Pair<String, Annotation> p : elementAnnotations) {
List<Insertion> elementInsertions = new ArrayList<Insertion>();
String annotationString = p.a;
Annotation annotation = p.b;
Boolean isDeclarationAnnotation = !annotation.def.isTypeAnnotation();
Criteria criteria = clist.criteria();
if (isOnReceiver(criteria)) {
if (receiver == null) {
DeclaredType type = new DeclaredType();
type.addAnnotation(annotationString);
receiver = new ReceiverInsertion(type, criteria, innerTypeInsertions);
elementInsertions.add(receiver);
} else {
receiver.getType().addAnnotation(annotationString);
}
addInsertionSource(receiver, annotation);
} else if (isOnNew(criteria)) {
if (neu == null) {
DeclaredType type = new DeclaredType();
type.addAnnotation(annotationString);
neu = new NewInsertion(type, criteria, innerTypeInsertions);
elementInsertions.add(neu);
} else {
neu.getType().addAnnotation(annotationString);
}
addInsertionSource(neu, annotation);
} else if (element instanceof ATypeElementWithType) {
if (cast == null) {
Pair<CastInsertion, CloseParenthesisInsertion> insertions = createCastInsertion(
((ATypeElementWithType) element).getType(), annotationString,
innerTypeInsertions, criteria);
cast = insertions.a;
closeParen = insertions.b;
elementInsertions.add(cast);
elementInsertions.add(closeParen);
// no addInsertionSource, as closeParen is not explicit in scene
} else {
cast.getType().addAnnotation(annotationString);
}
addInsertionSource(cast, annotation);
} else {
Insertion ins = new AnnotationInsertion(annotationString, criteria,
isDeclarationAnnotation);
debug("parsed: " + ins);
if (!isCastInsertion) {
// Annotations on compound types of a cast insertion will be
// inserted directly on the cast insertion.
//this.insertions.add(ins);
elementInsertions.add(ins);
}
annotationInsertions.add(ins);
addInsertionSource(ins, annotation);
}
this.insertions.addAll(elementInsertions);
// exclude expression annotations
if (isOnNullaryConstructor(criteria)) {
if (cons == null) {
DeclaredType type = new DeclaredType(criteria.getClassName());
cons = new ConstructorInsertion(type, criteria,
new ArrayList<Insertion>());
this.insertions.add(cons);
}
// no addInsertionSource, as cons is not explicit in scene
for (Insertion i : elementInsertions) {
if (i.getKind() == Insertion.Kind.RECEIVER) {
cons.addReceiverInsertion((ReceiverInsertion) i);
} else if (criteria.isOnReturnType()) {
((DeclaredType) cons.getType()).addAnnotation(annotationString);
} else if (isDeclarationAnnotation) {
cons.addDeclarationInsertion(i);
i.setInserted(true);
} else {
annotationInsertions.add(i);
}
}
}
elementInsertions.clear();
}
if (receiver != null) {
this.insertions.add(receiver);
}
if (neu != null) {
this.insertions.add(neu);
}
if (cast != null) {
this.insertions.add(cast);
this.insertions.add(closeParen);
}
return annotationInsertions;
}
public static boolean isOnReceiver(Criteria criteria) {
GenericArrayLocationCriterion galc = criteria.getGenericArrayLocation();
if (galc == null || galc.getLocation().isEmpty()) {
ASTPath astPath = criteria.getASTPath();
if (astPath == null) {
return criteria.isOnReceiver();
} else if (!astPath.isEmpty()) {
ASTPath.ASTEntry entry = astPath.get(-1); // 0?
return entry.childSelectorIs(ASTPath.PARAMETER)
&& entry.getArgument() < 0;
}
}
return false;
}
public static boolean isOnNew(Criteria criteria) {
GenericArrayLocationCriterion galc =
criteria.getGenericArrayLocation();
if (galc == null || galc.getLocation().isEmpty()) {
ASTPath astPath = criteria.getASTPath();
if (astPath == null || astPath.isEmpty()) {
return criteria.isOnNew();
} else {
ASTPath.ASTEntry entry = astPath.get(-1);
Tree.Kind kind = entry.getTreeKind();
return (kind == Tree.Kind.NEW_ARRAY
|| kind == Tree.Kind.NEW_CLASS)
&& entry.childSelectorIs(ASTPath.TYPE)
&& entry.getArgument() == 0;
}
}
return false;
}
private boolean isOnNullaryConstructor(Criteria criteria) {
if (!criteria.isOnMethod("<init>()V")) { return false; }
GenericArrayLocationCriterion galc =
criteria.getGenericArrayLocation();
if (galc == null || galc.getLocation().isEmpty()) {
ASTPath astPath = criteria.getASTPath();
if (astPath == null || astPath.isEmpty()) {
return criteria.isOnMethod("<init>()V")
&& !criteria.isOnNew(); // exclude expression annotations
} else {
ASTPath.ASTEntry entry = astPath.get(0);
return entry.getTreeKind() == Tree.Kind.METHOD
&& entry.childSelectorIs(ASTPath.TYPE);
}
}
return false;
}
/**
* Creates the {@link CastInsertion} and {@link CloseParenthesisInsertion}
* for a cast insertion.
*
* @param type The cast type to insert.
* @param annotationString The annotation on the outermost type, or
* {@code null} if none. With no outermost annotation this cast
* insertion will either be a cast without any annotations or a cast
* with annotations only on the compound types.
* @param innerTypeInsertions The annotations on the inner types.
* @param criteria The criteria for the location of this insertion.
* @return The {@link CastInsertion} and {@link CloseParenthesisInsertion}.
*/
private Pair<CastInsertion, CloseParenthesisInsertion> createCastInsertion(
Type type, String annotationString, List<Insertion> innerTypeInsertions,
Criteria criteria) {
if (annotationString != null) {
type.addAnnotation(annotationString);
}
Insertion.decorateType(innerTypeInsertions, type, criteria.getASTPath());
CastInsertion cast = new CastInsertion(criteria, type);
CloseParenthesisInsertion closeParen = new CloseParenthesisInsertion(
criteria, cast.getSeparateLine());
return new Pair<CastInsertion, CloseParenthesisInsertion>(cast, closeParen);
}
/**
* Fill in this.insertions with insertion pairs for the outer and inner types.
* @param clist The criteria specifying the location of the insertions.
* @param typeElement Holds the annotations to be inserted.
*/
private void parseInnerAndOuterElements(CriterionList clist, ATypeElement typeElement) {
parseInnerAndOuterElements(clist, typeElement, false);
}
/**
* Fill in this.insertions with insertion pairs for the outer and inner types.
* @param clist The criteria specifying the location of the insertions.
* @param typeElement Holds the annotations to be inserted.
* @param isCastInsertion {@code true} if this for a cast insertion, {@code false}
* otherwise.
*/
private void parseInnerAndOuterElements(CriterionList clist,
ATypeElement typeElement, boolean isCastInsertion) {
List<Insertion> innerInsertions = new ArrayList<Insertion>();
for (Entry<InnerTypeLocation, ATypeElement> innerEntry: typeElement.innerTypes.entrySet()) {
InnerTypeLocation innerLoc = innerEntry.getKey();
AElement innerElement = innerEntry.getValue();
CriterionList innerClist = clist.add(Criteria.atLocation(innerLoc));
innerInsertions.addAll(parseElement(innerClist, innerElement, isCastInsertion));
}
CriterionList outerClist = clist;
if (!isCastInsertion) {
// Cast insertion is never on an existing type.
outerClist = clist.add(Criteria.atLocation());
}
parseElement(outerClist, typeElement, innerInsertions);
}
// Returns a string representation of the annotations at the element.
private Set<Pair<String, Annotation>>
getElementAnnotations(AElement element) {
Set<Pair<String, Annotation>> result =
new LinkedHashSet<Pair<String, Annotation>>(
element.tlAnnotationsHere.size());
for (Annotation a : element.tlAnnotationsHere) {
AnnotationDef adef = a.def;
String annotationString = "@" + adef.name;
if (a.fieldValues.size() == 1 && a.fieldValues.containsKey("value")) {
annotationString += "(" + formatFieldValue(a, "value") + ")";
} else if (a.fieldValues.size() > 0) {
annotationString += "(";
boolean first = true;
for (String field : a.fieldValues.keySet()) {
// parameters of the annotation
if (!first) {
annotationString += ", ";
}
annotationString += field + "=" + formatFieldValue(a, field);
first = false;
}
annotationString += ")";
}
// annotationString += " ";
result.add(new Pair<String, Annotation>(annotationString, a));
}
return result;
}
private String formatFieldValue(Annotation a, String field) {
AnnotationFieldType fieldType = a.def.fieldTypes.get(field);
assert fieldType != null;
return fieldType.format(a.fieldValues.get(field));
}
private void parseMethod(CriterionList clist, String className, String methodName, AMethod method) {
// Being "in" a method refers to being somewhere in the
// method's tree, which includes return types, parameters, receiver, and
// elements inside the method body.
clist = clist.add(Criteria.inMethod(methodName));
// parse declaration annotations
parseElement(clist, method);
// parse receiver
CriterionList receiverClist = clist.add(Criteria.receiver(methodName));
parseInnerAndOuterElements(receiverClist, method.receiver.type);
// parse return type
CriterionList returnClist = clist.add(Criteria.returnType(className, methodName));
parseInnerAndOuterElements(returnClist, method.returnType);
// parse bounds of method
for (Entry<BoundLocation, ATypeElement> entry : method.bounds.entrySet()) {
BoundLocation boundLoc = entry.getKey();
ATypeElement bound = entry.getValue();
CriterionList boundClist = clist.add(Criteria.methodBound(methodName, boundLoc));
parseInnerAndOuterElements(boundClist, bound);
}
// parse parameters of method
for (Entry<Integer, AField> entry : method.parameters.entrySet()) {
Integer index = entry.getKey();
AField param = entry.getValue();
CriterionList paramClist = clist.add(Criteria.param(methodName, index));
// parse declaration annotations
parseField(paramClist, index.toString(), param);
parseInnerAndOuterElements(paramClist, param.type);
}
// parse insert annotations/typecasts of method
parseASTInsertions(clist, method.insertAnnotations, method.insertTypecasts);
parseBlock(clist, methodName, method.body);
}
private void parseBlock(CriterionList clist, String methodName, ABlock block) {
// parse locals of method
for (Entry<LocalLocation, AField> entry : block.locals.entrySet()) {
LocalLocation loc = entry.getKey();
AElement var = entry.getValue();
CriterionList varClist = clist.add(Criteria.local(methodName, loc));
// parse declaration annotations
parseElement(varClist, var); // TODO: _?_
parseInnerAndOuterElements(varClist, var.type);
}
parseExpression(clist, methodName, block);
}
private void parseExpression(CriterionList clist, String methodName, AExpression exp) {
// parse typecasts of method
for (Entry<RelativeLocation, ATypeElement> entry : exp.typecasts.entrySet()) {
RelativeLocation loc = entry.getKey();
ATypeElement cast = entry.getValue();
CriterionList castClist = clist.add(Criteria.cast(methodName, loc));
parseInnerAndOuterElements(castClist, cast);
}
// parse news (object creation) of method
for (Entry<RelativeLocation, ATypeElement> entry : exp.news.entrySet()) {
RelativeLocation loc = entry.getKey();
ATypeElement newObject = entry.getValue();
CriterionList newClist = clist.add(Criteria.newObject(methodName, loc));
parseInnerAndOuterElements(newClist, newObject);
}
// parse instanceofs of method
for (Entry<RelativeLocation, ATypeElement> entry : exp.instanceofs.entrySet()) {
RelativeLocation loc = entry.getKey();
ATypeElement instanceOf = entry.getValue();
CriterionList instanceOfClist = clist.add(Criteria.instanceOf(methodName, loc));
parseInnerAndOuterElements(instanceOfClist, instanceOf);
}
}
private void parseASTInsertions(CriterionList clist,
VivifyingMap<ASTPath, ATypeElement> insertAnnotations,
VivifyingMap<ASTPath, ATypeElementWithType> insertTypecasts) {
for (Entry<ASTPath, ATypeElement> entry : insertAnnotations.entrySet()) {
ASTPath astPath = entry.getKey();
ATypeElement insertAnnotation = entry.getValue();
CriterionList insertAnnotationClist =
clist.add(Criteria.astPath(astPath));
parseInnerAndOuterElements(insertAnnotationClist,
insertAnnotation, true);
}
for (Entry<ASTPath, ATypeElementWithType> entry : insertTypecasts.entrySet()) {
ASTPath astPath = entry.getKey();
ATypeElementWithType insertTypecast = entry.getValue();
CriterionList insertTypecastClist = clist.add(Criteria.astPath(astPath));
parseInnerAndOuterElements(insertTypecastClist, insertTypecast, true);
}
}
}
| Factors out notion of a "top-level" type from isOn*() methods as new private method noTypePath().
| annotation-file-utilities/src/annotator/specification/IndexFileSpecification.java | Factors out notion of a "top-level" type from isOn*() methods as new private method noTypePath(). | <ide><path>nnotation-file-utilities/src/annotator/specification/IndexFileSpecification.java
<ide> CloseParenthesisInsertion closeParen = null;
<ide> List<Insertion> annotationInsertions = new ArrayList<Insertion>();
<ide> Set<Pair<String, Annotation>> elementAnnotations = getElementAnnotations(element);
<del> if (element instanceof ATypeElementWithType && elementAnnotations.isEmpty()) {
<del> // Still insert even if it's a cast insertion with no outer annotations to
<del> // just insert a cast, or insert a cast with annotations on the compound
<del> // types.
<del> Pair<CastInsertion, CloseParenthesisInsertion> insertions = createCastInsertion(
<del> ((ATypeElementWithType) element).getType(), null,
<del> innerTypeInsertions, clist.criteria());
<del> cast = insertions.a;
<del> closeParen = insertions.b;
<add> if (elementAnnotations.isEmpty()) {
<add> Criteria criteria = clist.criteria();
<add> if (element instanceof ATypeElementWithType) {
<add> // Still insert even if it's a cast insertion with no outer
<add> // annotations to just insert a cast, or insert a cast with
<add> // annotations on the compound types.
<add> Pair<CastInsertion, CloseParenthesisInsertion> pair =
<add> createCastInsertion(((ATypeElementWithType) element).getType(),
<add> null, innerTypeInsertions, criteria);
<add> cast = pair.a;
<add> closeParen = pair.b;
<add> } else if (!innerTypeInsertions.isEmpty()) {
<add> if (isOnReceiver(criteria)) {
<add> receiver = new ReceiverInsertion(new DeclaredType(),
<add> criteria, innerTypeInsertions);
<add> } else if (isOnNew(criteria)) {
<add> neu = new NewInsertion(new DeclaredType(),
<add> criteria, innerTypeInsertions);
<add> }
<add> }
<ide> }
<ide>
<ide> for (Pair<String, Annotation> p : elementAnnotations) {
<ide> Annotation annotation = p.b;
<ide> Boolean isDeclarationAnnotation = !annotation.def.isTypeAnnotation();
<ide> Criteria criteria = clist.criteria();
<del> if (isOnReceiver(criteria)) {
<add> if (noTypePath(criteria) && isOnReceiver(criteria)) {
<ide> if (receiver == null) {
<ide> DeclaredType type = new DeclaredType();
<ide> type.addAnnotation(annotationString);
<ide> receiver.getType().addAnnotation(annotationString);
<ide> }
<ide> addInsertionSource(receiver, annotation);
<del> } else if (isOnNew(criteria)) {
<add> } else if (noTypePath(criteria) && isOnNew(criteria)) {
<ide> if (neu == null) {
<ide> DeclaredType type = new DeclaredType();
<ide> type.addAnnotation(annotationString);
<ide> this.insertions.addAll(elementInsertions);
<ide>
<ide> // exclude expression annotations
<del> if (isOnNullaryConstructor(criteria)) {
<add> if (noTypePath(criteria) && isOnNullaryConstructor(criteria)) {
<ide> if (cons == null) {
<ide> DeclaredType type = new DeclaredType(criteria.getClassName());
<ide> cons = new ConstructorInsertion(type, criteria,
<ide> return annotationInsertions;
<ide> }
<ide>
<add> private boolean noTypePath(Criteria criteria) {
<add> GenericArrayLocationCriterion galc =
<add> criteria.getGenericArrayLocation();
<add> return galc == null || galc.getLocation().isEmpty();
<add> }
<add>
<ide> public static boolean isOnReceiver(Criteria criteria) {
<del> GenericArrayLocationCriterion galc = criteria.getGenericArrayLocation();
<del> if (galc == null || galc.getLocation().isEmpty()) {
<del> ASTPath astPath = criteria.getASTPath();
<del> if (astPath == null) {
<del> return criteria.isOnReceiver();
<del> } else if (!astPath.isEmpty()) {
<del> ASTPath.ASTEntry entry = astPath.get(-1); // 0?
<del> return entry.childSelectorIs(ASTPath.PARAMETER)
<del> && entry.getArgument() < 0;
<del> }
<del> }
<del> return false;
<add> ASTPath astPath = criteria.getASTPath();
<add> if (astPath == null) { return criteria.isOnReceiver(); }
<add> if (astPath.isEmpty()) { return false; }
<add> ASTPath.ASTEntry entry = astPath.get(-1);
<add> return entry.childSelectorIs(ASTPath.PARAMETER)
<add> && entry.getArgument() < 0;
<ide> }
<ide>
<ide> public static boolean isOnNew(Criteria criteria) {
<del> GenericArrayLocationCriterion galc =
<del> criteria.getGenericArrayLocation();
<del> if (galc == null || galc.getLocation().isEmpty()) {
<del> ASTPath astPath = criteria.getASTPath();
<del> if (astPath == null || astPath.isEmpty()) {
<del> return criteria.isOnNew();
<del> } else {
<del> ASTPath.ASTEntry entry = astPath.get(-1);
<del> Tree.Kind kind = entry.getTreeKind();
<del> return (kind == Tree.Kind.NEW_ARRAY
<del> || kind == Tree.Kind.NEW_CLASS)
<del> && entry.childSelectorIs(ASTPath.TYPE)
<del> && entry.getArgument() == 0;
<del> }
<del> }
<del> return false;
<del> }
<del>
<del> private boolean isOnNullaryConstructor(Criteria criteria) {
<del> if (!criteria.isOnMethod("<init>()V")) { return false; }
<del> GenericArrayLocationCriterion galc =
<del> criteria.getGenericArrayLocation();
<del> if (galc == null || galc.getLocation().isEmpty()) {
<del> ASTPath astPath = criteria.getASTPath();
<del> if (astPath == null || astPath.isEmpty()) {
<del> return criteria.isOnMethod("<init>()V")
<del> && !criteria.isOnNew(); // exclude expression annotations
<del> } else {
<del> ASTPath.ASTEntry entry = astPath.get(0);
<del> return entry.getTreeKind() == Tree.Kind.METHOD
<del> && entry.childSelectorIs(ASTPath.TYPE);
<del> }
<del> }
<del> return false;
<add> ASTPath astPath = criteria.getASTPath();
<add> if (astPath == null || astPath.isEmpty()) { return criteria.isOnNew(); }
<add> ASTPath.ASTEntry entry = astPath.get(-1);
<add> Tree.Kind kind = entry.getTreeKind();
<add> return (kind == Tree.Kind.NEW_ARRAY || kind == Tree.Kind.NEW_CLASS)
<add> && entry.childSelectorIs(ASTPath.TYPE) && entry.getArgument() == 0;
<add> }
<add>
<add> private static boolean isOnNullaryConstructor(Criteria criteria) {
<add> if (criteria.isOnMethod("<init>()V")) {
<add> ASTPath astPath = criteria.getASTPath();
<add> if (astPath == null || astPath.isEmpty()) {
<add> return !criteria.isOnNew(); // exclude expression annotations
<add> }
<add> ASTPath.ASTEntry entry = astPath.get(0);
<add> return entry.getTreeKind() == Tree.Kind.METHOD
<add> && entry.childSelectorIs(ASTPath.TYPE);
<add> }
<add> return false;
<ide> }
<ide>
<ide> /**
<ide> }
<ide>
<ide> private void parseBlock(CriterionList clist, String methodName, ABlock block) {
<del>
<ide> // parse locals of method
<ide> for (Entry<LocalLocation, AField> entry : block.locals.entrySet()) {
<ide> LocalLocation loc = entry.getKey(); |
|
Java | mit | 2ef2f58a02cb3315e5f791f4465ac795a658d3d4 | 0 | Bammerbom/UltimateCore | /*
* This file is part of UltimateCore, licensed under the MIT License (MIT).
*
* Copyright (c) Bammerbom
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package bammerbom.ultimatecore.bukkit.api;
import bammerbom.ultimatecore.bukkit.UltimateFileLoader;
import bammerbom.ultimatecore.bukkit.configuration.Config;
import bammerbom.ultimatecore.bukkit.r;
import bammerbom.ultimatecore.bukkit.resources.utils.InventoryUtil;
import bammerbom.ultimatecore.bukkit.resources.utils.LocationUtil;
import java.io.File;
import java.util.*;
import org.bukkit.*;
import org.bukkit.BanList.Type;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
public class UPlayer {
static Random ra = new Random();
String name = null;
UUID uuid = null;
Location lastLocation = null;
Boolean banned = null;
Long bantime = null;
String banreason = null;
Boolean deaf = null;
Long deaftime = null;
Boolean freeze = null;
Long freezetime = null;
Boolean god = null;
Long godtime = null;
HashMap<String, Location> homes = null;
boolean onlineInv = false;
boolean offlineInv = false;
Boolean jailed = null;
Long jailtime = null;
String jail = null;
UUID reply = null;
Boolean spy = null;
Boolean mute = null;
Long mutetime = null;
String nickname = null;
Boolean pte = null;
HashMap<Material, List<String>> pts = null;
Boolean inRecipeView = false;
Boolean vanish = null;
Long vanishtime = null;
//Last connect
Long lastconnect = null;
Boolean inTeleportMenu = false;
Boolean inCmdEnchantingtable = false;
Boolean teleportEnabled = null;
//Afk
boolean afk = false;
long lastaction = System.currentTimeMillis();
public UPlayer(OfflinePlayer p) {
name = p.getName();
uuid = p.getUniqueId();
}
public UPlayer(UUID uuid) {
OfflinePlayer p = r.searchOfflinePlayer(uuid);
name = p.getName();
this.uuid = p.getUniqueId();
}
private void save() {
UC.uplayers.remove(this);
UC.uplayers.add(this);
}
public OfflinePlayer getPlayer() {
return Bukkit.getOfflinePlayer(uuid);
}
public Player getOnlinePlayer() {
return Bukkit.getPlayer(uuid);
}
public long getLastConnectMillis() {
if (lastconnect != null) {
return lastconnect;
}
final Config conf = getPlayerConfig();
if (conf.get("lastconnect") != null) {
lastconnect = conf.getLong("lastconnect");
save();
return conf.getLong("lastconnect");
} else {
lastconnect = getPlayer().getLastPlayed();
save();
return getPlayer().getLastPlayed();
}
}
public void updateLastConnectMillis() {
lastconnect = System.currentTimeMillis();
final Config conf = getPlayerConfig();
conf.set("lastconnect", System.currentTimeMillis());
conf.save();
save();
}
public void updateLastConnectMillis(Long millis) {
lastconnect = millis;
final Config conf = getPlayerConfig();
conf.set("lastconnect", millis);
conf.save();
save();
}
//Configuration
public Config getPlayerConfig() {
return UltimateFileLoader.getPlayerConfig(getPlayer());
}
public File getPlayerFile() {
return UltimateFileLoader.getPlayerFile(getPlayer());
}
public void setLastLocation() {
if (!getPlayer().isOnline()) {
return;
}
setLastLocation(getOnlinePlayer().getLocation());
}
public Location getLastLocation() {
if (lastLocation == null) {
Location loc = LocationUtil.convertStringToLocation(getPlayerConfig().getString("lastlocation"));
lastLocation = loc;
save();
return loc;
}
return lastLocation;
}
public void setLastLocation(Location loc) {
lastLocation = loc;
Config conf = getPlayerConfig();
conf.set("lastlocation", loc == null ? null : LocationUtil.convertLocationToString(loc));
conf.save();
save();
}
public boolean isBanned() {
if (!getPlayerConfig().contains("banned")) {
banned = false;
return false;
}
if (getBanTime() >= 1 && getBanTimeLeft() <= 1 && getPlayerConfig().getBoolean("banned")) {
unban();
return false;
}
if (banned != null) {
return banned;
}
BanList list = Bukkit.getBanList(Type.NAME);
if (getPlayer() == null || getPlayer().getName() == null) {
return false;
}
banned = getPlayerConfig().getBoolean("banned") || list.isBanned(getPlayer().getName());
return getPlayerConfig().getBoolean("banned") || list.isBanned(getPlayer().getName());
}
public Long getBanTime() {
if (bantime != null) {
return bantime;
}
if (!getPlayerConfig().contains("bantime")) {
return 0L;
}
bantime = getPlayerConfig().getLong("bantime");
save();
return getPlayerConfig().getLong("bantime");
}
public Long getBanTimeLeft() {
return getBanTime() - System.currentTimeMillis();
}
public String getBanReason() {
if (banreason != null) {
return banreason;
}
if (!getPlayerConfig().contains("banreason")) {
return "";
}
banreason = getPlayerConfig().getString("banreason");
save();
return getPlayerConfig().getString("banreason");
}
public void unban() {
banned = false;
bantime = 0L;
banreason = "";
save();
Config conf = getPlayerConfig();
conf.set("banned", false);
conf.set("bantime", null);
conf.set("banreason", null);
conf.save();
BanList list = Bukkit.getBanList(Type.NAME);
if (list.isBanned(getPlayer().getName())) {
list.pardon(getPlayer().getName());
}
}
public void ban(Long time, String reason) {
Config conf = getPlayerConfig();
if (time == null || time == 0L) {
time = -1L;
}
if (reason == null) {
reason = r.mes("banDefaultReason");
}
if (time >= 1) {
time = time + System.currentTimeMillis();
}
conf.set("banned", true);
conf.set("bantime", time);
conf.set("banreason", reason);
conf.save();
BanList list = Bukkit.getBanList(Type.NAME);
list.addBan(getPlayer().getName(), reason, null, "");
banned = true;
bantime = time;
banreason = reason;
save();
}
public void ban(Long time) {
ban(time, null);
}
public void ban(String reason) {
ban(null, reason);
}
public void ban() {
ban(null, null);
}
public boolean isDeaf() {
if (!getPlayerConfig().contains("deaf")) {
deaf = false;
return false;
}
if (getDeafTime() >= 1 && getDeafTimeLeft() <= 1 && getPlayerConfig().getBoolean("deaf")) {
setDeaf(false);
if (getPlayer().isOnline()) {
r.sendMes(getOnlinePlayer(), "undeafTarget");
}
return false;
}
if (deaf != null) {
return deaf;
}
deaf = getPlayerConfig().getBoolean("deaf");
save();
return getPlayerConfig().getBoolean("deaf");
}
public void setDeaf(Boolean deaf) {
setDeaf(deaf, -1L);
}
public Long getDeafTime() {
if (deaftime != null) {
return deaftime;
}
if (!getPlayerConfig().contains("deaftime")) {
return 0L;
}
deaftime = getPlayerConfig().getLong("deaftime");
save();
return getPlayerConfig().getLong("deaftime");
}
public Long getDeafTimeLeft() {
return getDeafTime() - System.currentTimeMillis();
}
public void setDeaf(Boolean dea, Long time) {
Config conf = getPlayerConfig();
if (deaftime == null || deaftime == 0L) {
deaftime = -1L;
}
if (time >= 1) {
time = time + System.currentTimeMillis();
}
conf.set("deaf", dea);
conf.set("deaftime", time);
conf.save();
deaf = dea;
deaftime = deaf ? time : 0L;
save();
}
public boolean isFrozen() {
if (!getPlayerConfig().contains("freeze")) {
freeze = false;
return false;
}
if (getFrozenTime() >= 1 && getFrozenTimeLeft() <= 1 && getPlayerConfig().getBoolean("freeze")) {
setFrozen(false);
if (getPlayer().isOnline()) {
r.sendMes(getOnlinePlayer(), "unfreezeTarget");
}
return false;
}
if (freeze != null) {
return freeze;
}
freeze = getPlayerConfig().getBoolean("freeze");
save();
return getPlayerConfig().getBoolean("freeze");
}
public void setFrozen(Boolean fr) {
setFrozen(fr, -1L);
}
public Long getFrozenTime() {
if (freezetime != null) {
return freezetime;
}
if (!getPlayerConfig().contains("freezetime")) {
return 0L;
}
freezetime = getPlayerConfig().getLong("freezetime");
save();
return getPlayerConfig().getLong("freezetime");
}
public Long getFrozenTimeLeft() {
return getFrozenTime() - System.currentTimeMillis();
}
public void setFrozen(Boolean fr, Long time) {
Config conf = getPlayerConfig();
if (freezetime == null || freezetime == 0L) {
freezetime = -1L;
}
if (time >= 1) {
time = time + System.currentTimeMillis();
}
conf.set("freeze", fr);
conf.set("freezetime", time);
conf.save();
freeze = fr;
freezetime = fr ? time : 0L;
save();
}
public boolean isGod() {
if (!getPlayerConfig().contains("god")) {
god = false;
return false;
}
if (getGodTime() >= 1 && getGodTimeLeft() <= 1 && getPlayerConfig().getBoolean("god")) {
setGod(false);
if (getPlayer().isOnline()) {
r.sendMes(getOnlinePlayer(), "ungodTarget");
}
return false;
}
if (god != null) {
return god;
}
god = getPlayerConfig().getBoolean("god");
save();
return getPlayerConfig().getBoolean("god");
}
public void setGod(Boolean fr) {
setGod(fr, -1L);
}
public Long getGodTime() {
if (godtime != null) {
return godtime;
}
if (!getPlayerConfig().contains("godtime")) {
return 0L;
}
godtime = getPlayerConfig().getLong("godtime");
save();
return getPlayerConfig().getLong("godtime");
}
public Long getGodTimeLeft() {
return getGodTime() - System.currentTimeMillis();
}
public void setGod(Boolean fr, Long time) {
Config conf = getPlayerConfig();
if (godtime == null || godtime == 0L) {
godtime = -1L;
}
if (time >= 1) {
time = time + System.currentTimeMillis();
}
conf.set("god", fr);
conf.set("godtime", time);
conf.save();
god = fr;
godtime = fr ? time : 0L;
save();
}
public HashMap<String, Location> getHomes() {
if (homes != null) {
return homes;
}
homes = new HashMap<>();
Config conf = getPlayerConfig();
if (!conf.contains("homes")) {
return homes;
}
for (String hname : conf.getConfigurationSection("homes").getKeys(false)) {
homes.put(hname, LocationUtil.convertStringToLocation(conf.getString("homes." + hname)));
}
save();
return homes;
}
public void setHomes(HashMap<String, Location> nh) {
homes = nh;
save();
Config conf = getPlayerConfig();
conf.set("homes", null);
for (String s : nh.keySet()) {
conf.set("homes." + s, LocationUtil.convertLocationToString(nh.get(s.toLowerCase())));
}
conf.save();
}
public ArrayList<String> getHomeNames() {
ArrayList<String> h = new ArrayList<>();
h.addAll(getHomes().keySet());
return h;
}
public void addHome(String s, Location l) {
HashMap<String, Location> h = getHomes();
h.put(s.toLowerCase(), l);
setHomes(h);
}
public void removeHome(String s) {
HashMap<String, Location> h = getHomes();
h.remove(s.toLowerCase());
setHomes(h);
}
public Location getHome(String s) {
return getHomes().get(s.toLowerCase());
}
public void clearHomes() {
setHomes(new HashMap<String, Location>());
}
public boolean isInOnlineInventory() {
return onlineInv;
}
public void setInOnlineInventory(Boolean b) {
onlineInv = b;
save();
}
public boolean isInOfflineInventory() {
return offlineInv;
}
public void setInOfflineInventory(Boolean b) {
offlineInv = b;
save();
}
public void updateLastInventory() {
Config conf = getPlayerConfig();
conf.set("lastinventory", InventoryUtil.convertInventoryToString(getOnlinePlayer().getInventory()));
conf.save();
}
public Inventory getLastInventory() {
Config conf = getPlayerConfig();
if (!conf.contains("lastinventory")) {
return null;
}
return InventoryUtil.convertStringToInventory(conf.getString("lastinventory"), r.mes("inventoryOfflineTitle", "%Name", name));
}
public void jail() {
jail(null, null);
}
public void jail(String n) {
jail(n, null);
}
public void jail(Long l) {
jail(new ArrayList<>(UC.getServer().getJails().keySet()).get(ra.nextInt(UC.getServer().getJails().keySet().size())), l);
}
public void jail(String n, Long l) {
jailed = true;
jail = n;
if (l >= 1) {
l = l + System.currentTimeMillis();
}
jailtime = l;
Config conf = getPlayerConfig();
conf.set("jailed", true);
conf.set("jail", n);
conf.set("jailtime", l == null ? 0L : l);
conf.save();
save();
}
public void unjail() {
jailed = false;
jail = null;
jailtime = null;
Config conf = getPlayerConfig();
conf.set("jailed", false);
conf.set("jail", null);
conf.set("jailtime", null);
conf.save();
save();
}
public boolean isJailed() {
if (!getPlayerConfig().contains("jailed")) {
return false;
}
if (getJailTimeLeft() <= 1 && getPlayerConfig().getBoolean("jailed") && !(getJailTimeLeft() <= -1)) {
unjail();
if (getPlayer().isOnline()) {
r.sendMes(getOnlinePlayer(), "unjailTarget");
unjail();
}
return false;
}
if (jailed != null) {
return jailed;
}
jailed = getPlayerConfig().getBoolean("jailed");
save();
return getPlayerConfig().getBoolean("jailed");
}
public Long getJailTime() {
if (jailtime != null) {
return jailtime;
}
if (!getPlayerConfig().contains("jailtime")) {
return 0L;
}
jailtime = getPlayerConfig().getLong("jailtime");
save();
return getPlayerConfig().getLong("jailtime");
}
public Long getJailTimeLeft() {
return getJailTime() - System.currentTimeMillis();
}
public String getJail() {
if (jail != null) {
return jail;
}
if (!isJailed()) {
return null;
}
return getPlayerConfig().getString("jail");
}
public Player getReply() {
if (reply != null) {
return Bukkit.getPlayer(reply);
}
if (!getPlayerConfig().contains("reply")) {
return null;
}
return Bukkit.getPlayer(UUID.fromString(getPlayerConfig().getString("reply")));
}
public void setReply(Player pl) {
reply = pl.getUniqueId();
Config conf = getPlayerConfig();
conf.set("reply", pl.getUniqueId().toString());
conf.save();
save();
}
public boolean isSpy() {
if (spy != null) {
return spy;
}
if (!getPlayerConfig().contains("spy")) {
return false;
}
spy = getPlayerConfig().getBoolean("spy");
save();
return spy;
}
public void setSpy(Boolean sp) {
spy = sp;
Config conf = getPlayerConfig();
conf.set("spy", sp);
conf.save();
save();
}
public boolean isMuted() {
if (!getPlayerConfig().contains("mute")) {
mute = false;
return false;
}
if (getMuteTime() >= 1 && getMuteTimeLeft() <= 1 && getPlayerConfig().getBoolean("mute")) {
setMuted(false);
if (getPlayer().isOnline()) {
r.sendMes(getOnlinePlayer(), "unmuteTarget");
}
return false;
}
if (mute != null) {
return mute;
}
mute = getPlayerConfig().getBoolean("mute");
save();
return getPlayerConfig().getBoolean("mute");
}
public void setMuted(Boolean fr) {
setMuted(fr, -1L);
}
public Long getMuteTime() {
if (mutetime != null) {
return mutetime;
}
if (!getPlayerConfig().contains("mutetime")) {
return 0L;
}
mutetime = getPlayerConfig().getLong("mutetime");
save();
return getPlayerConfig().getLong("mutetime");
}
public Long getMuteTimeLeft() {
return getMuteTime() - System.currentTimeMillis();
}
public void setMuted(Boolean fr, Long time) {
Config conf = getPlayerConfig();
if (mutetime == null || mutetime == 0L) {
mutetime = -1L;
}
if (time >= 1) {
time = time + System.currentTimeMillis();
}
conf.set("mute", fr);
conf.set("mutetime", time);
conf.save();
mute = fr;
mutetime = fr ? time : -1L;
save();
}
public String getDisplayName() {
if (getNick() != null) {
return getNick();
}
if (getPlayer().isOnline()) {
if (getOnlinePlayer().getCustomName() != null) {
return getOnlinePlayer().getCustomName();
}
if (getOnlinePlayer().getDisplayName() != null) {
return getOnlinePlayer().getDisplayName();
}
}
return getPlayer().getName();
}
public String getNick() {
if (nickname != null) {
return nickname;
}
Config data = getPlayerConfig();
if (data.get("nick") == null) {
return null;
}
String nick = ChatColor.translateAlternateColorCodes('&', data.getString("nick"));
if (getPlayer().isOnline()) {
getPlayer().getPlayer().setDisplayName(nickname.replace("&y", ""));
}
if (getPlayer().isOnline() && r.perm((CommandSender) getPlayer(), "uc.chat.rainbow", false, false)) {
nick = nick.replaceAll("&y", r.getRandomChatColor() + "");
}
nickname = nick + ChatColor.RESET;
save();
return nick + ChatColor.RESET;
}
public void setNick(String str) {
nickname = str == null ? null : str + ChatColor.RESET;
save();
if (str != null) {
if (getPlayer().isOnline()) {
getPlayer().getPlayer().setDisplayName(nickname.replace("&y", ""));
}
} else {
if (getPlayer().isOnline()) {
getPlayer().getPlayer().setDisplayName(getPlayer().getPlayer().getName());
}
}
Config data = getPlayerConfig();
data.set("nick", str);
data.save(UltimateFileLoader.getPlayerFile(getPlayer()));
}
public void clearAllPowertools() {
for (Material mat : pts.keySet()) {
clearPowertool(mat);
}
if (pts != null) {
pts.clear(); //Just to make sure
}
save();
}
public void clearPowertool(Material mat) {
if (pts == null) {
Config data = getPlayerConfig();
pts = new HashMap<>();
if (data.contains("powertool")) {
for (String s : data.getConfigurationSection("powertool").getValues(false).keySet()) {
ArrayList<String> l = (ArrayList<String>) data.getStringList("powertool." + s);
pts.put(Material.getMaterial(s), l);
}
}
}
pts.remove(mat);
Config data = getPlayerConfig();
data.set("powertool." + mat.toString(), null);
data.save();
save();
}
public List<String> getPowertools(Material mat) {
if (mat == null || mat == Material.AIR) {
return null;
}
if (pts == null) {
Config data = getPlayerConfig();
pts = new HashMap<>();
if (data.contains("powertool")) {
for (String s : data.getConfigurationSection("powertool").getValues(false).keySet()) {
ArrayList<String> l = (ArrayList<String>) data.getStringList("powertool." + s);
pts.put(Material.getMaterial(s), l);
}
}
}
save();
if (pts.containsKey(mat)) {
return new ArrayList<>(pts.get(mat));
}
return null;
}
public boolean hasPowertools() {
if (pts == null) {
Config data = getPlayerConfig();
pts = new HashMap<>();
if (data.contains("powertool")) {
for (String s : data.getConfigurationSection("powertool").getValues(false).keySet()) {
ArrayList<String> l = (ArrayList<String>) data.getStringList("powertool." + s);
pts.put(Material.getMaterial(s), l);
}
}
save();
}
return !pts.isEmpty();
}
public boolean hasPowertool(Material mat) {
if (pts == null) {
Config data = getPlayerConfig();
pts = new HashMap<>();
if (data.contains("powertool")) {
for (String s : data.getConfigurationSection("powertool").getValues(false).keySet()) {
ArrayList<String> l = (ArrayList<String>) data.getStringList("powertool." + s);
pts.put(Material.getMaterial(s), l);
}
}
save();
}
return pts.containsKey(mat);
}
public void setPowertool(Material mat, List<String> cmds) {
Config data = getPlayerConfig();
if (pts == null) {
pts = new HashMap<>();
if (data.contains("powertool")) {
for (String s : data.getConfigurationSection("powertool").getValues(false).keySet()) {
ArrayList<String> l = (ArrayList<String>) data.getStringList("powertool." + s);
pts.put(Material.getMaterial(s), l);
}
}
}
pts.put(mat, cmds);
data.set("powertool." + mat.toString(), cmds);
data.save();
save();
}
public void addPowertool(Material mat, String c) {
List<String> ps = getPowertools(mat);
ps.add(c);
setPowertool(mat, ps);
}
public void removePowertool(Material mat, String c) {
List<String> ps = getPowertools(mat);
if (!ps.contains(c)) {
return;
}
ps.add(c);
setPowertool(mat, ps);
}
public boolean isInRecipeView() {
return inRecipeView;
}
public void setInRecipeView(Boolean b) {
inRecipeView = b;
save();
}
public boolean isInTeleportMenu() {
return inTeleportMenu;
}
public void setInTeleportMenu(Boolean b) {
inTeleportMenu = b;
save();
}
public boolean isInCommandEnchantingtable() {
return inCmdEnchantingtable;
}
public void setInCommandEnchantingtable(Boolean b) {
inCmdEnchantingtable = b;
save();
}
public boolean hasTeleportEnabled() {
if (teleportEnabled != null) {
return teleportEnabled;
}
if (!getPlayerConfig().contains("teleportenabled")) {
return true;
}
teleportEnabled = getPlayerConfig().getBoolean("teleportenabled");
save();
return teleportEnabled;
}
public void setTeleportEnabled(Boolean tpe) {
teleportEnabled = tpe;
Config conf = getPlayerConfig();
conf.set("teleportenabled", tpe);
conf.save();
save();
}
public boolean isVanish() {
if (!getPlayerConfig().contains("vanish")) {
vanish = false;
return false;
}
if (getVanishTime() >= 1 && getVanishTimeLeft() <= 1 && getPlayerConfig().getBoolean("vanish")) {
setVanish(false);
if (getPlayer().isOnline()) {
r.sendMes(getOnlinePlayer(), "unvanishTarget");
}
return false;
}
if (vanish != null) {
return vanish;
}
vanish = getPlayerConfig().getBoolean("vanish");
save();
return getPlayerConfig().getBoolean("vanish");
}
public void setVanish(Boolean fr) {
setVanish(fr, -1L);
}
public Long getVanishTime() {
if (vanishtime != null) {
return vanishtime;
}
if (!getPlayerConfig().contains("vanishtime")) {
return 0L;
}
vanishtime = getPlayerConfig().getLong("vanishtime");
save();
return getPlayerConfig().getLong("vanishtime");
}
public Long getVanishTimeLeft() {
return getVanishTime() - System.currentTimeMillis();
}
public void setVanish(Boolean fr, Long time) {
Config conf = getPlayerConfig();
if (vanishtime == null || vanishtime == 0L) {
vanishtime = -1L;
}
if (time >= 1) {
time = time + System.currentTimeMillis();
}
conf.set("vanish", fr);
conf.set("vanishtime", time);
conf.save();
vanish = fr;
vanishtime = fr ? time : 0L;
if (getOnlinePlayer() != null) {
for (Player pl : r.getOnlinePlayers()) {
pl.hidePlayer(getOnlinePlayer());
}
}
save();
}
public boolean isAfk() {
return afk;
}
public void setAfk(boolean news) {
afk = news;
save();
}
public long getLastActivity() {
return lastaction;
}
public void setLastActivity(Long last) {
lastaction = last;
save();
}
public void updateLastActivity() {
setLastActivity(System.currentTimeMillis());
if (isAfk()) {
setAfk(false);
Bukkit.broadcastMessage(r.mes("afkUnafk", "%Player", UC.getPlayer(getPlayer()).getDisplayName()));
}
}
}
| src/main/java/bammerbom/ultimatecore/bukkit/api/UPlayer.java | /*
* This file is part of UltimateCore, licensed under the MIT License (MIT).
*
* Copyright (c) Bammerbom
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package bammerbom.ultimatecore.bukkit.api;
import bammerbom.ultimatecore.bukkit.UltimateFileLoader;
import bammerbom.ultimatecore.bukkit.configuration.Config;
import bammerbom.ultimatecore.bukkit.r;
import bammerbom.ultimatecore.bukkit.resources.utils.InventoryUtil;
import bammerbom.ultimatecore.bukkit.resources.utils.LocationUtil;
import java.io.File;
import java.util.*;
import org.bukkit.*;
import org.bukkit.BanList.Type;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
public class UPlayer {
static Random ra = new Random();
String name = null;
UUID uuid = null;
Location lastLocation = null;
Boolean banned = null;
Long bantime = null;
String banreason = null;
Boolean deaf = null;
Long deaftime = null;
Boolean freeze = null;
Long freezetime = null;
Boolean god = null;
Long godtime = null;
HashMap<String, Location> homes = null;
boolean onlineInv = false;
boolean offlineInv = false;
Boolean jailed = null;
Long jailtime = null;
String jail = null;
UUID reply = null;
Boolean spy = null;
Boolean mute = null;
Long mutetime = null;
String nickname = null;
Boolean pte = null;
HashMap<Material, List<String>> pts = null;
Boolean inRecipeView = false;
Boolean vanish = null;
Long vanishtime = null;
//Last connect
Long lastconnect = null;
Boolean inTeleportMenu = false;
Boolean inCmdEnchantingtable = false;
Boolean teleportEnabled = null;
//Afk
boolean afk = false;
long lastaction = System.currentTimeMillis();
public UPlayer(OfflinePlayer p) {
name = p.getName();
uuid = p.getUniqueId();
}
public UPlayer(UUID uuid) {
OfflinePlayer p = r.searchOfflinePlayer(uuid);
name = p.getName();
this.uuid = p.getUniqueId();
}
private void save() {
UC.uplayers.remove(this);
UC.uplayers.add(this);
}
public OfflinePlayer getPlayer() {
return Bukkit.getOfflinePlayer(uuid);
}
public Player getOnlinePlayer() {
return Bukkit.getPlayer(uuid);
}
public long getLastConnectMillis() {
if (lastconnect != null) {
return lastconnect;
}
final Config conf = getPlayerConfig();
if (conf.get("lastconnect") != null) {
lastconnect = conf.getLong("lastconnect");
save();
return conf.getLong("lastconnect");
} else {
lastconnect = getPlayer().getLastPlayed();
save();
return getPlayer().getLastPlayed();
}
}
public void updateLastConnectMillis() {
lastconnect = System.currentTimeMillis();
final Config conf = getPlayerConfig();
conf.set("lastconnect", System.currentTimeMillis());
conf.save();
save();
}
public void updateLastConnectMillis(Long millis) {
lastconnect = millis;
final Config conf = getPlayerConfig();
conf.set("lastconnect", millis);
conf.save();
save();
}
//Configuration
public Config getPlayerConfig() {
return UltimateFileLoader.getPlayerConfig(getPlayer());
}
public File getPlayerFile() {
return UltimateFileLoader.getPlayerFile(getPlayer());
}
public void setLastLocation() {
if (!getPlayer().isOnline()) {
return;
}
setLastLocation(getOnlinePlayer().getLocation());
}
public Location getLastLocation() {
if (lastLocation == null) {
Location loc = LocationUtil.convertStringToLocation(getPlayerConfig().getString("lastlocation"));
lastLocation = loc;
save();
return loc;
}
return lastLocation;
}
public void setLastLocation(Location loc) {
lastLocation = loc;
Config conf = getPlayerConfig();
conf.set("lastlocation", loc == null ? null : LocationUtil.convertLocationToString(loc));
conf.save();
save();
}
public boolean isBanned() {
if (!getPlayerConfig().contains("banned")) {
banned = false;
return false;
}
if (getBanTime() >= 1 && getBanTimeLeft() <= 1 && getPlayerConfig().getBoolean("banned")) {
unban();
return false;
}
if (banned != null) {
return banned;
}
BanList list = Bukkit.getBanList(Type.NAME);
if (getPlayer() == null || getPlayer().getName() == null) {
return false;
}
banned = getPlayerConfig().getBoolean("banned") || list.isBanned(getPlayer().getName());
return getPlayerConfig().getBoolean("banned") || list.isBanned(getPlayer().getName());
}
public Long getBanTime() {
if (bantime != null) {
return bantime;
}
if (!getPlayerConfig().contains("bantime")) {
return 0L;
}
bantime = getPlayerConfig().getLong("bantime");
save();
return getPlayerConfig().getLong("bantime");
}
public Long getBanTimeLeft() {
return getBanTime() - System.currentTimeMillis();
}
public String getBanReason() {
if (banreason != null) {
return banreason;
}
if (!getPlayerConfig().contains("banreason")) {
return "";
}
banreason = getPlayerConfig().getString("banreason");
save();
return getPlayerConfig().getString("banreason");
}
public void unban() {
banned = false;
bantime = 0L;
banreason = "";
save();
Config conf = getPlayerConfig();
conf.set("banned", false);
conf.set("bantime", null);
conf.set("banreason", null);
conf.save();
BanList list = Bukkit.getBanList(Type.NAME);
if (list.isBanned(getPlayer().getName())) {
list.pardon(getPlayer().getName());
}
}
public void ban(Long time, String reason) {
Config conf = getPlayerConfig();
if (time == null || time == 0L) {
time = -1L;
}
if (reason == null) {
reason = r.mes("banDefaultReason");
}
if (time >= 1) {
time = time + System.currentTimeMillis();
}
conf.set("banned", true);
conf.set("bantime", time);
conf.set("banreason", reason);
conf.save();
BanList list = Bukkit.getBanList(Type.NAME);
list.addBan(getPlayer().getName(), reason, null, "");
banned = true;
bantime = time;
banreason = reason;
save();
}
public void ban(Long time) {
ban(time, null);
}
public void ban(String reason) {
ban(null, reason);
}
public void ban() {
ban(null, null);
}
public boolean isDeaf() {
if (!getPlayerConfig().contains("deaf")) {
deaf = false;
return false;
}
if (getDeafTime() >= 1 && getDeafTimeLeft() <= 1 && getPlayerConfig().getBoolean("deaf")) {
setDeaf(false);
if (getPlayer().isOnline()) {
r.sendMes(getOnlinePlayer(), "undeafTarget");
}
return false;
}
if (deaf != null) {
return deaf;
}
deaf = getPlayerConfig().getBoolean("deaf");
save();
return getPlayerConfig().getBoolean("deaf");
}
public void setDeaf(Boolean deaf) {
setDeaf(deaf, -1L);
}
public Long getDeafTime() {
if (deaftime != null) {
return deaftime;
}
if (!getPlayerConfig().contains("deaftime")) {
return 0L;
}
deaftime = getPlayerConfig().getLong("deaftime");
save();
return getPlayerConfig().getLong("deaftime");
}
public Long getDeafTimeLeft() {
return getDeafTime() - System.currentTimeMillis();
}
public void setDeaf(Boolean dea, Long time) {
Config conf = getPlayerConfig();
if (deaftime == null || deaftime == 0L) {
deaftime = -1L;
}
if (time >= 1) {
time = time + System.currentTimeMillis();
}
conf.set("deaf", dea);
conf.set("deaftime", time);
conf.save();
deaf = dea;
deaftime = deaf ? time : 0L;
save();
}
public boolean isFrozen() {
if (!getPlayerConfig().contains("freeze")) {
freeze = false;
return false;
}
if (getFrozenTime() >= 1 && getFrozenTimeLeft() <= 1 && getPlayerConfig().getBoolean("freeze")) {
setFrozen(false);
if (getPlayer().isOnline()) {
r.sendMes(getOnlinePlayer(), "unfreezeTarget");
}
return false;
}
if (freeze != null) {
return freeze;
}
freeze = getPlayerConfig().getBoolean("freeze");
save();
return getPlayerConfig().getBoolean("freeze");
}
public void setFrozen(Boolean fr) {
setFrozen(fr, -1L);
}
public Long getFrozenTime() {
if (freezetime != null) {
return freezetime;
}
if (!getPlayerConfig().contains("freezetime")) {
return 0L;
}
freezetime = getPlayerConfig().getLong("freezetime");
save();
return getPlayerConfig().getLong("freezetime");
}
public Long getFrozenTimeLeft() {
return getFrozenTime() - System.currentTimeMillis();
}
public void setFrozen(Boolean fr, Long time) {
Config conf = getPlayerConfig();
if (freezetime == null || freezetime == 0L) {
freezetime = -1L;
}
if (time >= 1) {
time = time + System.currentTimeMillis();
}
conf.set("freeze", fr);
conf.set("freezetime", time);
conf.save();
freeze = fr;
freezetime = fr ? time : 0L;
save();
}
public boolean isGod() {
if (!getPlayerConfig().contains("god")) {
god = false;
return false;
}
if (getGodTime() >= 1 && getGodTimeLeft() <= 1 && getPlayerConfig().getBoolean("god")) {
setGod(false);
if (getPlayer().isOnline()) {
r.sendMes(getOnlinePlayer(), "ungodTarget");
}
return false;
}
if (god != null) {
return god;
}
god = getPlayerConfig().getBoolean("god");
save();
return getPlayerConfig().getBoolean("god");
}
public void setGod(Boolean fr) {
setGod(fr, -1L);
}
public Long getGodTime() {
if (godtime != null) {
return godtime;
}
if (!getPlayerConfig().contains("godtime")) {
return 0L;
}
godtime = getPlayerConfig().getLong("godtime");
save();
return getPlayerConfig().getLong("godtime");
}
public Long getGodTimeLeft() {
return getGodTime() - System.currentTimeMillis();
}
public void setGod(Boolean fr, Long time) {
Config conf = getPlayerConfig();
if (godtime == null || godtime == 0L) {
godtime = -1L;
}
if (time >= 1) {
time = time + System.currentTimeMillis();
}
conf.set("god", fr);
conf.set("godtime", time);
conf.save();
god = fr;
godtime = fr ? time : 0L;
save();
}
public HashMap<String, Location> getHomes() {
if (homes != null) {
return homes;
}
homes = new HashMap<>();
Config conf = getPlayerConfig();
if (!conf.contains("homes")) {
return homes;
}
for (String hname : conf.getConfigurationSection("homes").getKeys(false)) {
homes.put(hname, LocationUtil.convertStringToLocation(conf.getString("homes." + hname)));
}
save();
return homes;
}
public void setHomes(HashMap<String, Location> nh) {
homes = nh;
save();
Config conf = getPlayerConfig();
conf.set("homes", null);
for (String s : nh.keySet()) {
conf.set("homes." + s, LocationUtil.convertLocationToString(nh.get(s.toLowerCase())));
}
conf.save();
}
public ArrayList<String> getHomeNames() {
ArrayList<String> h = new ArrayList<>();
h.addAll(getHomes().keySet());
return h;
}
public void addHome(String s, Location l) {
HashMap<String, Location> h = getHomes();
h.put(s.toLowerCase(), l);
setHomes(h);
}
public void removeHome(String s) {
HashMap<String, Location> h = getHomes();
h.remove(s.toLowerCase());
setHomes(h);
}
public Location getHome(String s) {
return getHomes().get(s.toLowerCase());
}
public void clearHomes() {
setHomes(new HashMap<String, Location>());
}
public boolean isInOnlineInventory() {
return onlineInv;
}
public void setInOnlineInventory(Boolean b) {
onlineInv = b;
save();
}
public boolean isInOfflineInventory() {
return offlineInv;
}
public void setInOfflineInventory(Boolean b) {
offlineInv = b;
save();
}
public void updateLastInventory() {
Config conf = getPlayerConfig();
conf.set("lastinventory", InventoryUtil.convertInventoryToString(getOnlinePlayer().getInventory()));
conf.save();
}
public Inventory getLastInventory() {
Config conf = getPlayerConfig();
if (!conf.contains("lastinventory")) {
return null;
}
return InventoryUtil.convertStringToInventory(conf.getString("lastinventory"), r.mes("inventoryOfflineTitle", "%Name", name));
}
public void jail() {
jail(null, null);
}
public void jail(String n) {
jail(n, null);
}
public void jail(Long l) {
jail(new ArrayList<>(UC.getServer().getJails().keySet()).get(ra.nextInt(UC.getServer().getJails().keySet().size())), l);
}
public void jail(String n, Long l) {
jailed = true;
jail = n;
if (l >= 1) {
l = l + System.currentTimeMillis();
}
jailtime = l;
Config conf = getPlayerConfig();
conf.set("jailed", true);
conf.set("jail", n);
conf.set("jailtime", l == null ? 0L : l);
conf.save();
save();
}
public void unjail() {
jailed = false;
jail = null;
jailtime = null;
Config conf = getPlayerConfig();
conf.set("jailed", false);
conf.set("jail", null);
conf.set("jailtime", null);
conf.save();
save();
}
public boolean isJailed() {
if (!getPlayerConfig().contains("jailed")) {
return false;
}
if (getJailTimeLeft() <= 1 && getPlayerConfig().getBoolean("jailed") && !(getJailTimeLeft() <= -1)) {
unjail();
if (getPlayer().isOnline()) {
r.sendMes(getOnlinePlayer(), "unjailTarget");
unjail();
}
return false;
}
if (jailed != null) {
return jailed;
}
jailed = getPlayerConfig().getBoolean("jailed");
save();
return getPlayerConfig().getBoolean("jailed");
}
public Long getJailTime() {
if (jailtime != null) {
return jailtime;
}
if (!getPlayerConfig().contains("jailtime")) {
return 0L;
}
jailtime = getPlayerConfig().getLong("jailtime");
save();
return getPlayerConfig().getLong("jailtime");
}
public Long getJailTimeLeft() {
return getJailTime() - System.currentTimeMillis();
}
public String getJail() {
if (jail != null) {
return jail;
}
if (!isJailed()) {
return null;
}
return getPlayerConfig().getString("jail");
}
public Player getReply() {
if (reply != null) {
return Bukkit.getPlayer(reply);
}
if (!getPlayerConfig().contains("reply")) {
return null;
}
return Bukkit.getPlayer(UUID.fromString(getPlayerConfig().getString("reply")));
}
public void setReply(Player pl) {
reply = pl.getUniqueId();
Config conf = getPlayerConfig();
conf.set("reply", pl.getUniqueId().toString());
conf.save();
save();
}
public boolean isSpy() {
if (spy != null) {
return spy;
}
if (!getPlayerConfig().contains("spy")) {
return false;
}
spy = getPlayerConfig().getBoolean("spy");
save();
return spy;
}
public void setSpy(Boolean sp) {
spy = sp;
Config conf = getPlayerConfig();
conf.set("spy", sp);
conf.save();
save();
}
public boolean isMuted() {
if (!getPlayerConfig().contains("mute")) {
mute = false;
return false;
}
if (getMuteTime() >= 1 && getMuteTimeLeft() <= 1 && getPlayerConfig().getBoolean("mute")) {
setMuted(false);
if (getPlayer().isOnline()) {
r.sendMes(getOnlinePlayer(), "unmuteTarget");
}
return false;
}
if (mute != null) {
return mute;
}
mute = getPlayerConfig().getBoolean("mute");
save();
return getPlayerConfig().getBoolean("mute");
}
public void setMuted(Boolean fr) {
setMuted(fr, -1L);
}
public Long getMuteTime() {
if (mutetime != null) {
return mutetime;
}
if (!getPlayerConfig().contains("mutetime")) {
return 0L;
}
mutetime = getPlayerConfig().getLong("mutetime");
save();
return getPlayerConfig().getLong("mutetime");
}
public Long getMuteTimeLeft() {
return getMuteTime() - System.currentTimeMillis();
}
public void setMuted(Boolean fr, Long time) {
Config conf = getPlayerConfig();
if (mutetime == null || mutetime == 0L) {
mutetime = -1L;
}
if (time >= 1) {
time = time + System.currentTimeMillis();
}
conf.set("mute", fr);
conf.set("mutetime", time);
conf.save();
mute = fr;
mutetime = fr ? time : -1L;
save();
}
public String getDisplayName() {
if (getNick() != null) {
return getNick();
}
if (getPlayer().isOnline()) {
if (getOnlinePlayer().getCustomName() != null) {
return getOnlinePlayer().getCustomName();
}
if (getOnlinePlayer().getDisplayName() != null) {
return getOnlinePlayer().getDisplayName();
}
}
return getPlayer().getName();
}
public String getNick() {
if (nickname != null) {
return nickname;
}
Config data = getPlayerConfig();
if (data.get("nick") == null) {
return null;
}
String nick = ChatColor.translateAlternateColorCodes('&', data.getString("nick"));
if (getPlayer().isOnline()) {
getPlayer().getPlayer().setDisplayName(nickname.replace("&y", ""));
}
if (getPlayer().isOnline() && r.perm((CommandSender) getPlayer(), "uc.chat.rainbow", false, false)) {
nick = nick.replaceAll("&y", r.getRandomChatColor() + "");
}
nickname = nick + ChatColor.RESET;
save();
return nick + ChatColor.RESET;
}
public void setNick(String str) {
nickname = str == null ? null : str + ChatColor.RESET;
save();
if (str != null) {
if (getPlayer().isOnline()) {
getPlayer().getPlayer().setDisplayName(nickname.replace("&y", ""));
}
}
Config data = getPlayerConfig();
data.set("nick", str);
data.save(UltimateFileLoader.getPlayerFile(getPlayer()));
}
public void clearAllPowertools() {
for (Material mat : pts.keySet()) {
clearPowertool(mat);
}
if (pts != null) {
pts.clear(); //Just to make sure
}
save();
}
public void clearPowertool(Material mat) {
if (pts == null) {
Config data = getPlayerConfig();
pts = new HashMap<>();
if (data.contains("powertool")) {
for (String s : data.getConfigurationSection("powertool").getValues(false).keySet()) {
ArrayList<String> l = (ArrayList<String>) data.getStringList("powertool." + s);
pts.put(Material.getMaterial(s), l);
}
}
}
pts.remove(mat);
Config data = getPlayerConfig();
data.set("powertool." + mat.toString(), null);
data.save();
save();
}
public List<String> getPowertools(Material mat) {
if (mat == null || mat == Material.AIR) {
return null;
}
if (pts == null) {
Config data = getPlayerConfig();
pts = new HashMap<>();
if (data.contains("powertool")) {
for (String s : data.getConfigurationSection("powertool").getValues(false).keySet()) {
ArrayList<String> l = (ArrayList<String>) data.getStringList("powertool." + s);
pts.put(Material.getMaterial(s), l);
}
}
}
save();
if (pts.containsKey(mat)) {
return new ArrayList<>(pts.get(mat));
}
return null;
}
public boolean hasPowertools() {
if (pts == null) {
Config data = getPlayerConfig();
pts = new HashMap<>();
if (data.contains("powertool")) {
for (String s : data.getConfigurationSection("powertool").getValues(false).keySet()) {
ArrayList<String> l = (ArrayList<String>) data.getStringList("powertool." + s);
pts.put(Material.getMaterial(s), l);
}
}
save();
}
return !pts.isEmpty();
}
public boolean hasPowertool(Material mat) {
if (pts == null) {
Config data = getPlayerConfig();
pts = new HashMap<>();
if (data.contains("powertool")) {
for (String s : data.getConfigurationSection("powertool").getValues(false).keySet()) {
ArrayList<String> l = (ArrayList<String>) data.getStringList("powertool." + s);
pts.put(Material.getMaterial(s), l);
}
}
save();
}
return pts.containsKey(mat);
}
public void setPowertool(Material mat, List<String> cmds) {
Config data = getPlayerConfig();
if (pts == null) {
pts = new HashMap<>();
if (data.contains("powertool")) {
for (String s : data.getConfigurationSection("powertool").getValues(false).keySet()) {
ArrayList<String> l = (ArrayList<String>) data.getStringList("powertool." + s);
pts.put(Material.getMaterial(s), l);
}
}
}
pts.put(mat, cmds);
data.set("powertool." + mat.toString(), cmds);
data.save();
save();
}
public void addPowertool(Material mat, String c) {
List<String> ps = getPowertools(mat);
ps.add(c);
setPowertool(mat, ps);
}
public void removePowertool(Material mat, String c) {
List<String> ps = getPowertools(mat);
if (!ps.contains(c)) {
return;
}
ps.add(c);
setPowertool(mat, ps);
}
public boolean isInRecipeView() {
return inRecipeView;
}
public void setInRecipeView(Boolean b) {
inRecipeView = b;
save();
}
public boolean isInTeleportMenu() {
return inTeleportMenu;
}
public void setInTeleportMenu(Boolean b) {
inTeleportMenu = b;
save();
}
public boolean isInCommandEnchantingtable() {
return inCmdEnchantingtable;
}
public void setInCommandEnchantingtable(Boolean b) {
inCmdEnchantingtable = b;
save();
}
public boolean hasTeleportEnabled() {
if (teleportEnabled != null) {
return teleportEnabled;
}
if (!getPlayerConfig().contains("teleportenabled")) {
return true;
}
teleportEnabled = getPlayerConfig().getBoolean("teleportenabled");
save();
return teleportEnabled;
}
public void setTeleportEnabled(Boolean tpe) {
teleportEnabled = tpe;
Config conf = getPlayerConfig();
conf.set("teleportenabled", tpe);
conf.save();
save();
}
public boolean isVanish() {
if (!getPlayerConfig().contains("vanish")) {
vanish = false;
return false;
}
if (getVanishTime() >= 1 && getVanishTimeLeft() <= 1 && getPlayerConfig().getBoolean("vanish")) {
setVanish(false);
if (getPlayer().isOnline()) {
r.sendMes(getOnlinePlayer(), "unvanishTarget");
}
return false;
}
if (vanish != null) {
return vanish;
}
vanish = getPlayerConfig().getBoolean("vanish");
save();
return getPlayerConfig().getBoolean("vanish");
}
public void setVanish(Boolean fr) {
setVanish(fr, -1L);
}
public Long getVanishTime() {
if (vanishtime != null) {
return vanishtime;
}
if (!getPlayerConfig().contains("vanishtime")) {
return 0L;
}
vanishtime = getPlayerConfig().getLong("vanishtime");
save();
return getPlayerConfig().getLong("vanishtime");
}
public Long getVanishTimeLeft() {
return getVanishTime() - System.currentTimeMillis();
}
public void setVanish(Boolean fr, Long time) {
Config conf = getPlayerConfig();
if (vanishtime == null || vanishtime == 0L) {
vanishtime = -1L;
}
if (time >= 1) {
time = time + System.currentTimeMillis();
}
conf.set("vanish", fr);
conf.set("vanishtime", time);
conf.save();
vanish = fr;
vanishtime = fr ? time : 0L;
if (getOnlinePlayer() != null) {
for (Player pl : r.getOnlinePlayers()) {
pl.hidePlayer(getOnlinePlayer());
}
}
save();
}
public boolean isAfk() {
return afk;
}
public void setAfk(boolean news) {
afk = news;
save();
}
public long getLastActivity() {
return lastaction;
}
public void setLastActivity(Long last) {
lastaction = last;
save();
}
public void updateLastActivity() {
setLastActivity(System.currentTimeMillis());
if (isAfk()) {
setAfk(false);
Bukkit.broadcastMessage(r.mes("afkUnafk", "%Player", UC.getPlayer(getPlayer()).getDisplayName()));
}
}
}
| Bug fix: /nick off doesnt update nickname
| src/main/java/bammerbom/ultimatecore/bukkit/api/UPlayer.java | Bug fix: /nick off doesnt update nickname | <ide><path>rc/main/java/bammerbom/ultimatecore/bukkit/api/UPlayer.java
<ide> if (getPlayer().isOnline()) {
<ide> getPlayer().getPlayer().setDisplayName(nickname.replace("&y", ""));
<ide> }
<add> } else {
<add> if (getPlayer().isOnline()) {
<add> getPlayer().getPlayer().setDisplayName(getPlayer().getPlayer().getName());
<add> }
<ide> }
<ide> Config data = getPlayerConfig();
<ide> data.set("nick", str); |
|
Java | apache-2.0 | 96f5d8d004863776de29e791b3ef390ecfc59df6 | 0 | christophd/camel,tadayosi/camel,adessaigne/camel,adessaigne/camel,cunningt/camel,tadayosi/camel,cunningt/camel,christophd/camel,adessaigne/camel,adessaigne/camel,tadayosi/camel,cunningt/camel,christophd/camel,adessaigne/camel,apache/camel,apache/camel,tadayosi/camel,christophd/camel,tadayosi/camel,apache/camel,cunningt/camel,apache/camel,cunningt/camel,cunningt/camel,christophd/camel,tadayosi/camel,apache/camel,adessaigne/camel,apache/camel,christophd/camel | /*
* 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.
*/
//CHECKSTYLE:OFF
/**
* Generated by Camel build tools - do NOT edit this file!
*/
package org.apache.camel.xml.in;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.apache.camel.model.*;
import org.apache.camel.model.cloud.*;
import org.apache.camel.model.config.BatchResequencerConfig;
import org.apache.camel.model.config.ResequencerConfig;
import org.apache.camel.model.config.StreamResequencerConfig;
import org.apache.camel.model.dataformat.*;
import org.apache.camel.model.language.*;
import org.apache.camel.model.loadbalancer.*;
import org.apache.camel.model.rest.*;
import org.apache.camel.model.transformer.*;
import org.apache.camel.model.validator.*;
import org.apache.camel.xml.io.XmlPullParserException;
@SuppressWarnings("unused")
public class ModelParser extends BaseParser {
public ModelParser(
org.apache.camel.spi.Resource input)
throws IOException, XmlPullParserException {
super(input);
}
public ModelParser(
org.apache.camel.spi.Resource input,
String namespace)
throws IOException, XmlPullParserException {
super(input, namespace);
}
public ModelParser(
InputStream input)
throws IOException, XmlPullParserException {
super(input);
}
public ModelParser(Reader reader) throws IOException, XmlPullParserException {
super(reader);
}
public ModelParser(
InputStream input,
String namespace)
throws IOException, XmlPullParserException {
super(input, namespace);
}
public ModelParser(
Reader reader,
String namespace)
throws IOException, XmlPullParserException {
super(reader, namespace);
}
protected AggregateDefinition doParseAggregateDefinition() throws IOException, XmlPullParserException {
return doParse(new AggregateDefinition(), (def, key, val) -> {
switch (key) {
case "aggregateControllerRef": def.setAggregateControllerRef(val); break;
case "aggregationRepositoryRef": def.setAggregationRepositoryRef(val); break;
case "closeCorrelationKeyOnCompletion": def.setCloseCorrelationKeyOnCompletion(val); break;
case "completeAllOnStop": def.setCompleteAllOnStop(val); break;
case "completionFromBatchConsumer": def.setCompletionFromBatchConsumer(val); break;
case "completionInterval": def.setCompletionInterval(val); break;
case "completionOnNewCorrelationGroup": def.setCompletionOnNewCorrelationGroup(val); break;
case "completionSize": def.setCompletionSize(val); break;
case "completionTimeout": def.setCompletionTimeout(val); break;
case "completionTimeoutCheckerInterval": def.setCompletionTimeoutCheckerInterval(val); break;
case "discardOnAggregationFailure": def.setDiscardOnAggregationFailure(val); break;
case "discardOnCompletionTimeout": def.setDiscardOnCompletionTimeout(val); break;
case "eagerCheckCompletion": def.setEagerCheckCompletion(val); break;
case "executorServiceRef": def.setExecutorServiceRef(val); break;
case "forceCompletionOnStop": def.setForceCompletionOnStop(val); break;
case "ignoreInvalidCorrelationKeys": def.setIgnoreInvalidCorrelationKeys(val); break;
case "optimisticLocking": def.setOptimisticLocking(val); break;
case "parallelProcessing": def.setParallelProcessing(val); break;
case "strategyMethodAllowNull": def.setStrategyMethodAllowNull(val); break;
case "strategyMethodName": def.setStrategyMethodName(val); break;
case "strategyRef": def.setStrategyRef(val); break;
case "timeoutCheckerExecutorServiceRef": def.setTimeoutCheckerExecutorServiceRef(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, (def, key) -> {
switch (key) {
case "completionPredicate": def.setCompletionPredicate(doParseExpressionSubElementDefinition()); break;
case "completionSizeExpression": def.setCompletionSizeExpression(doParseExpressionSubElementDefinition()); break;
case "completionTimeoutExpression": def.setCompletionTimeoutExpression(doParseExpressionSubElementDefinition()); break;
case "correlationExpression": def.setCorrelationExpression(doParseExpressionSubElementDefinition()); break;
case "optimisticLockRetryPolicy": def.setOptimisticLockRetryPolicyDefinition(doParseOptimisticLockRetryPolicyDefinition()); break;
default: return outputDefinitionElementHandler().accept(def, key);
}
return true;
}, noValueHandler());
}
protected ExpressionSubElementDefinition doParseExpressionSubElementDefinition() throws IOException, XmlPullParserException {
return doParse(new ExpressionSubElementDefinition(),
noAttributeHandler(), (def, key) -> {
ExpressionDefinition v = doParseExpressionDefinitionRef(key);
if (v != null) {
def.setExpressionType(v);
return true;
}
return false;
}, noValueHandler());
}
protected OptimisticLockRetryPolicyDefinition doParseOptimisticLockRetryPolicyDefinition() throws IOException, XmlPullParserException {
return doParse(new OptimisticLockRetryPolicyDefinition(), (def, key, val) -> {
switch (key) {
case "exponentialBackOff": def.setExponentialBackOff(val); break;
case "maximumRetries": def.setMaximumRetries(val); break;
case "maximumRetryDelay": def.setMaximumRetryDelay(val); break;
case "randomBackOff": def.setRandomBackOff(val); break;
case "retryDelay": def.setRetryDelay(val); break;
default: return false;
}
return true;
}, noElementHandler(), noValueHandler());
}
protected <T extends OutputDefinition> ElementHandler<T> outputDefinitionElementHandler() {
return (def, key) -> {
ProcessorDefinition v = doParseProcessorDefinitionRef(key);
if (v != null) {
doAdd(v, def.getOutputs(), def::setOutputs);
return true;
}
return optionalIdentifiedDefinitionElementHandler().accept(def, key);
};
}
protected OutputDefinition doParseOutputDefinition() throws IOException, XmlPullParserException {
return doParse(new OutputDefinition(),
processorDefinitionAttributeHandler(), outputDefinitionElementHandler(), noValueHandler());
}
protected <T extends ProcessorDefinition> AttributeHandler<T> processorDefinitionAttributeHandler() {
return (def, key, val) -> {
if ("inheritErrorHandler".equals(key)) {
def.setInheritErrorHandler(Boolean.valueOf(val));
return true;
}
return optionalIdentifiedDefinitionAttributeHandler().accept(def, key, val);
};
}
protected <T extends OptionalIdentifiedDefinition> AttributeHandler<T> optionalIdentifiedDefinitionAttributeHandler() {
return (def, key, val) -> {
switch (key) {
case "customId": def.setCustomId(Boolean.valueOf(val)); break;
case "id": def.setId(val); break;
default: return false;
}
return true;
};
}
protected <T extends OptionalIdentifiedDefinition> ElementHandler<T> optionalIdentifiedDefinitionElementHandler() {
return (def, key) -> {
switch (key) {
case "description": def.setDescription(doParseDescriptionDefinition()); break;
case "generatedId": def.setGeneratedId(doParseText()); break;
default: return false;
}
return true;
};
}
protected DescriptionDefinition doParseDescriptionDefinition() throws IOException, XmlPullParserException {
return doParse(new DescriptionDefinition(), (def, key, val) -> {
if ("lang".equals(key)) {
def.setLang(val);
return true;
}
return false;
}, noElementHandler(), (def, val) -> def.setText(val));
}
protected BeanDefinition doParseBeanDefinition() throws IOException, XmlPullParserException {
return doParse(new BeanDefinition(), (def, key, val) -> {
switch (key) {
case "beanType": def.setBeanType(val); break;
case "cache": def.setCache(val); break;
case "method": def.setMethod(val); break;
case "ref": def.setRef(val); break;
case "scope": def.setScope(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected CatchDefinition doParseCatchDefinition() throws IOException, XmlPullParserException {
return doParse(new CatchDefinition(),
processorDefinitionAttributeHandler(), (def, key) -> {
switch (key) {
case "exception": doAdd(doParseText(), def.getExceptions(), def::setExceptions); break;
case "onWhen": def.setOnWhen(doParseWhenDefinition()); break;
default: return outputDefinitionElementHandler().accept(def, key);
}
return true;
}, noValueHandler());
}
protected WhenDefinition doParseWhenDefinition() throws IOException, XmlPullParserException {
return doParse(new WhenDefinition(),
processorDefinitionAttributeHandler(), outputExpressionNodeElementHandler(), noValueHandler());
}
protected <T extends ChoiceDefinition> ElementHandler<T> choiceDefinitionElementHandler() {
return (def, key) -> {
switch (key) {
case "when": doAdd(doParseWhenDefinition(), def.getWhenClauses(), def::setWhenClauses); break;
case "otherwise": def.setOtherwise(doParseOtherwiseDefinition()); break;
default: return optionalIdentifiedDefinitionElementHandler().accept(def, key);
}
return true;
};
}
protected ChoiceDefinition doParseChoiceDefinition() throws IOException, XmlPullParserException {
return doParse(new ChoiceDefinition(),
processorDefinitionAttributeHandler(), choiceDefinitionElementHandler(), noValueHandler());
}
protected OtherwiseDefinition doParseOtherwiseDefinition() throws IOException, XmlPullParserException {
return doParse(new OtherwiseDefinition(),
processorDefinitionAttributeHandler(), outputDefinitionElementHandler(), noValueHandler());
}
protected CircuitBreakerDefinition doParseCircuitBreakerDefinition() throws IOException, XmlPullParserException {
return doParse(new CircuitBreakerDefinition(), (def, key, val) -> {
if ("configurationRef".equals(key)) {
def.setConfigurationRef(val);
return true;
}
return processorDefinitionAttributeHandler().accept(def, key, val);
}, (def, key) -> {
switch (key) {
case "faultToleranceConfiguration": def.setFaultToleranceConfiguration(doParseFaultToleranceConfigurationDefinition()); break;
case "hystrixConfiguration": def.setHystrixConfiguration(doParseHystrixConfigurationDefinition()); break;
case "resilience4jConfiguration": def.setResilience4jConfiguration(doParseResilience4jConfigurationDefinition()); break;
default: return outputDefinitionElementHandler().accept(def, key);
}
return true;
}, noValueHandler());
}
protected HystrixConfigurationDefinition doParseHystrixConfigurationDefinition() throws IOException, XmlPullParserException {
return doParse(new HystrixConfigurationDefinition(),
hystrixConfigurationCommonAttributeHandler(), noElementHandler(), noValueHandler());
}
protected Resilience4jConfigurationDefinition doParseResilience4jConfigurationDefinition() throws IOException, XmlPullParserException {
return doParse(new Resilience4jConfigurationDefinition(),
resilience4jConfigurationCommonAttributeHandler(), resilience4jConfigurationCommonElementHandler(), noValueHandler());
}
protected FaultToleranceConfigurationDefinition doParseFaultToleranceConfigurationDefinition() throws IOException, XmlPullParserException {
return doParse(new FaultToleranceConfigurationDefinition(),
faultToleranceConfigurationCommonAttributeHandler(), noElementHandler(), noValueHandler());
}
protected ClaimCheckDefinition doParseClaimCheckDefinition() throws IOException, XmlPullParserException {
return doParse(new ClaimCheckDefinition(), (def, key, val) -> {
switch (key) {
case "filter": def.setFilter(val); break;
case "key": def.setKey(val); break;
case "operation": def.setOperation(val); break;
case "strategyMethodName": def.setAggregationStrategyMethodName(val); break;
case "strategyRef": def.setAggregationStrategyRef(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected ContextScanDefinition doParseContextScanDefinition() throws IOException, XmlPullParserException {
return doParse(new ContextScanDefinition(), (def, key, val) -> {
if ("includeNonSingletons".equals(key)) {
def.setIncludeNonSingletons(val);
return true;
}
return false;
}, (def, key) -> {
switch (key) {
case "excludes": doAdd(doParseText(), def.getExcludes(), def::setExcludes); break;
case "includes": doAdd(doParseText(), def.getIncludes(), def::setIncludes); break;
default: return false;
}
return true;
}, noValueHandler());
}
protected ConvertBodyDefinition doParseConvertBodyDefinition() throws IOException, XmlPullParserException {
return doParse(new ConvertBodyDefinition(), (def, key, val) -> {
switch (key) {
case "charset": def.setCharset(val); break;
case "mandatory": def.setMandatory(val); break;
case "type": def.setType(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected DataFormatDefinition doParseDataFormatDefinition() throws IOException, XmlPullParserException {
return doParse(new DataFormatDefinition(),
identifiedTypeAttributeHandler(), noElementHandler(), noValueHandler());
}
protected <T extends IdentifiedType> AttributeHandler<T> identifiedTypeAttributeHandler() {
return (def, key, val) -> {
if ("id".equals(key)) {
def.setId(val);
return true;
}
return false;
};
}
protected DelayDefinition doParseDelayDefinition() throws IOException, XmlPullParserException {
return doParse(new DelayDefinition(), (def, key, val) -> {
switch (key) {
case "asyncDelayed": def.setAsyncDelayed(val); break;
case "callerRunsWhenRejected": def.setCallerRunsWhenRejected(val); break;
case "executorServiceRef": def.setExecutorServiceRef(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, expressionNodeElementHandler(), noValueHandler());
}
protected <T extends ExpressionNode> ElementHandler<T> expressionNodeElementHandler() {
return (def, key) -> {
ExpressionDefinition v = doParseExpressionDefinitionRef(key);
if (v != null) {
def.setExpression(v);
return true;
}
return optionalIdentifiedDefinitionElementHandler().accept(def, key);
};
}
protected <T extends ExpressionDefinition> AttributeHandler<T> expressionDefinitionAttributeHandler() {
return (def, key, val) -> {
switch (key) {
case "id": def.setId(val); break;
case "trim": def.setTrim(val); break;
default: return false;
}
return true;
};
}
protected ExpressionDefinition doParseExpressionDefinition() throws IOException, XmlPullParserException {
return doParse(new ExpressionDefinition(), expressionDefinitionAttributeHandler(), noElementHandler(), expressionDefinitionValueHandler());
}
protected DynamicRouterDefinition doParseDynamicRouterDefinition() throws IOException, XmlPullParserException {
return doParse(new DynamicRouterDefinition(), (def, key, val) -> {
switch (key) {
case "cacheSize": def.setCacheSize(val); break;
case "ignoreInvalidEndpoints": def.setIgnoreInvalidEndpoints(val); break;
case "uriDelimiter": def.setUriDelimiter(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, expressionNodeElementHandler(), noValueHandler());
}
protected EnrichDefinition doParseEnrichDefinition() throws IOException, XmlPullParserException {
return doParse(new EnrichDefinition(), (def, key, val) -> {
switch (key) {
case "aggregateOnException": def.setAggregateOnException(val); break;
case "allowOptimisedComponents": def.setAllowOptimisedComponents(val); break;
case "cacheSize": def.setCacheSize(val); break;
case "ignoreInvalidEndpoint": def.setIgnoreInvalidEndpoint(val); break;
case "shareUnitOfWork": def.setShareUnitOfWork(val); break;
case "strategyMethodAllowNull": def.setAggregationStrategyMethodAllowNull(val); break;
case "strategyMethodName": def.setAggregationStrategyMethodName(val); break;
case "strategyRef": def.setAggregationStrategyRef(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, expressionNodeElementHandler(), noValueHandler());
}
protected <T extends FaultToleranceConfigurationCommon> AttributeHandler<T> faultToleranceConfigurationCommonAttributeHandler() {
return (def, key, val) -> {
switch (key) {
case "bulkheadEnabled": def.setBulkheadEnabled(val); break;
case "bulkheadExecutorServiceRef": def.setBulkheadExecutorServiceRef(val); break;
case "bulkheadMaxConcurrentCalls": def.setBulkheadMaxConcurrentCalls(val); break;
case "bulkheadWaitingTaskQueue": def.setBulkheadWaitingTaskQueue(val); break;
case "circuitBreakerRef": def.setCircuitBreakerRef(val); break;
case "delay": def.setDelay(val); break;
case "failureRatio": def.setFailureRatio(val); break;
case "requestVolumeThreshold": def.setRequestVolumeThreshold(val); break;
case "successThreshold": def.setSuccessThreshold(val); break;
case "timeoutDuration": def.setTimeoutDuration(val); break;
case "timeoutEnabled": def.setTimeoutEnabled(val); break;
case "timeoutPoolSize": def.setTimeoutPoolSize(val); break;
case "timeoutScheduledExecutorServiceRef": def.setTimeoutScheduledExecutorServiceRef(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
};
}
protected FaultToleranceConfigurationCommon doParseFaultToleranceConfigurationCommon() throws IOException, XmlPullParserException {
return doParse(new FaultToleranceConfigurationCommon(), faultToleranceConfigurationCommonAttributeHandler(), noElementHandler(), noValueHandler());
}
protected FilterDefinition doParseFilterDefinition() throws IOException, XmlPullParserException {
return doParse(new FilterDefinition(), (def, key, val) -> {
if ("statusPropertyName".equals(key)) {
def.setStatusPropertyName(val);
return true;
}
return processorDefinitionAttributeHandler().accept(def, key, val);
}, outputExpressionNodeElementHandler(), noValueHandler());
}
protected <T extends OutputExpressionNode> ElementHandler<T> outputExpressionNodeElementHandler() {
return (def, key) -> {
ProcessorDefinition v = doParseProcessorDefinitionRef(key);
if (v != null) {
doAdd(v, def.getOutputs(), def::setOutputs);
return true;
}
return expressionNodeElementHandler().accept(def, key);
};
}
protected FinallyDefinition doParseFinallyDefinition() throws IOException, XmlPullParserException {
return doParse(new FinallyDefinition(),
processorDefinitionAttributeHandler(), outputDefinitionElementHandler(), noValueHandler());
}
protected FromDefinition doParseFromDefinition() throws IOException, XmlPullParserException {
return doParse(new FromDefinition(), (def, key, val) -> {
if ("uri".equals(key)) {
def.setUri(val);
return true;
}
return optionalIdentifiedDefinitionAttributeHandler().accept(def, key, val);
}, optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected GlobalOptionDefinition doParseGlobalOptionDefinition() throws IOException, XmlPullParserException {
return doParse(new GlobalOptionDefinition(), (def, key, val) -> {
switch (key) {
case "key": def.setKey(val); break;
case "value": def.setValue(val); break;
default: return false;
}
return true;
}, noElementHandler(), noValueHandler());
}
protected GlobalOptionsDefinition doParseGlobalOptionsDefinition() throws IOException, XmlPullParserException {
return doParse(new GlobalOptionsDefinition(),
noAttributeHandler(), (def, key) -> {
if ("globalOption".equals(key)) {
doAdd(doParseGlobalOptionDefinition(), def.getGlobalOptions(), def::setGlobalOptions);
return true;
}
return false;
}, noValueHandler());
}
protected <T extends HystrixConfigurationCommon> AttributeHandler<T> hystrixConfigurationCommonAttributeHandler() {
return (def, key, val) -> {
switch (key) {
case "allowMaximumSizeToDivergeFromCoreSize": def.setAllowMaximumSizeToDivergeFromCoreSize(val); break;
case "circuitBreakerEnabled": def.setCircuitBreakerEnabled(val); break;
case "circuitBreakerErrorThresholdPercentage": def.setCircuitBreakerErrorThresholdPercentage(val); break;
case "circuitBreakerForceClosed": def.setCircuitBreakerForceClosed(val); break;
case "circuitBreakerForceOpen": def.setCircuitBreakerForceOpen(val); break;
case "circuitBreakerRequestVolumeThreshold": def.setCircuitBreakerRequestVolumeThreshold(val); break;
case "circuitBreakerSleepWindowInMilliseconds": def.setCircuitBreakerSleepWindowInMilliseconds(val); break;
case "corePoolSize": def.setCorePoolSize(val); break;
case "executionIsolationSemaphoreMaxConcurrentRequests": def.setExecutionIsolationSemaphoreMaxConcurrentRequests(val); break;
case "executionIsolationStrategy": def.setExecutionIsolationStrategy(val); break;
case "executionIsolationThreadInterruptOnTimeout": def.setExecutionIsolationThreadInterruptOnTimeout(val); break;
case "executionTimeoutEnabled": def.setExecutionTimeoutEnabled(val); break;
case "executionTimeoutInMilliseconds": def.setExecutionTimeoutInMilliseconds(val); break;
case "fallbackEnabled": def.setFallbackEnabled(val); break;
case "fallbackIsolationSemaphoreMaxConcurrentRequests": def.setFallbackIsolationSemaphoreMaxConcurrentRequests(val); break;
case "groupKey": def.setGroupKey(val); break;
case "keepAliveTime": def.setKeepAliveTime(val); break;
case "maxQueueSize": def.setMaxQueueSize(val); break;
case "maximumSize": def.setMaximumSize(val); break;
case "metricsHealthSnapshotIntervalInMilliseconds": def.setMetricsHealthSnapshotIntervalInMilliseconds(val); break;
case "metricsRollingPercentileBucketSize": def.setMetricsRollingPercentileBucketSize(val); break;
case "metricsRollingPercentileEnabled": def.setMetricsRollingPercentileEnabled(val); break;
case "metricsRollingPercentileWindowBuckets": def.setMetricsRollingPercentileWindowBuckets(val); break;
case "metricsRollingPercentileWindowInMilliseconds": def.setMetricsRollingPercentileWindowInMilliseconds(val); break;
case "metricsRollingStatisticalWindowBuckets": def.setMetricsRollingStatisticalWindowBuckets(val); break;
case "metricsRollingStatisticalWindowInMilliseconds": def.setMetricsRollingStatisticalWindowInMilliseconds(val); break;
case "queueSizeRejectionThreshold": def.setQueueSizeRejectionThreshold(val); break;
case "requestLogEnabled": def.setRequestLogEnabled(val); break;
case "threadPoolKey": def.setThreadPoolKey(val); break;
case "threadPoolRollingNumberStatisticalWindowBuckets": def.setThreadPoolRollingNumberStatisticalWindowBuckets(val); break;
case "threadPoolRollingNumberStatisticalWindowInMilliseconds": def.setThreadPoolRollingNumberStatisticalWindowInMilliseconds(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
};
}
protected HystrixConfigurationCommon doParseHystrixConfigurationCommon() throws IOException, XmlPullParserException {
return doParse(new HystrixConfigurationCommon(), hystrixConfigurationCommonAttributeHandler(), noElementHandler(), noValueHandler());
}
protected IdempotentConsumerDefinition doParseIdempotentConsumerDefinition() throws IOException, XmlPullParserException {
return doParse(new IdempotentConsumerDefinition(), (def, key, val) -> {
switch (key) {
case "completionEager": def.setCompletionEager(val); break;
case "eager": def.setEager(val); break;
case "messageIdRepositoryRef": def.setMessageIdRepositoryRef(val); break;
case "removeOnFailure": def.setRemoveOnFailure(val); break;
case "skipDuplicate": def.setSkipDuplicate(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, outputExpressionNodeElementHandler(), noValueHandler());
}
protected InOnlyDefinition doParseInOnlyDefinition() throws IOException, XmlPullParserException {
return doParse(new InOnlyDefinition(),
sendDefinitionAttributeHandler(), optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected <T extends SendDefinition> AttributeHandler<T> sendDefinitionAttributeHandler() {
return (def, key, val) -> {
if ("uri".equals(key)) {
def.setUri(val);
return true;
}
return processorDefinitionAttributeHandler().accept(def, key, val);
};
}
protected InOutDefinition doParseInOutDefinition() throws IOException, XmlPullParserException {
return doParse(new InOutDefinition(),
sendDefinitionAttributeHandler(), optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected InputTypeDefinition doParseInputTypeDefinition() throws IOException, XmlPullParserException {
return doParse(new InputTypeDefinition(), (def, key, val) -> {
switch (key) {
case "urn": def.setUrn(val); break;
case "validate": def.setValidate(val); break;
default: return optionalIdentifiedDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected InterceptDefinition doParseInterceptDefinition() throws IOException, XmlPullParserException {
return doParse(new InterceptDefinition(),
processorDefinitionAttributeHandler(), outputDefinitionElementHandler(), noValueHandler());
}
protected InterceptFromDefinition doParseInterceptFromDefinition() throws IOException, XmlPullParserException {
return doParse(new InterceptFromDefinition(), (def, key, val) -> {
if ("uri".equals(key)) {
def.setUri(val);
return true;
}
return processorDefinitionAttributeHandler().accept(def, key, val);
}, outputDefinitionElementHandler(), noValueHandler());
}
protected InterceptSendToEndpointDefinition doParseInterceptSendToEndpointDefinition() throws IOException, XmlPullParserException {
return doParse(new InterceptSendToEndpointDefinition(), (def, key, val) -> {
switch (key) {
case "afterUri": def.setAfterUri(val); break;
case "skipSendToOriginalEndpoint": def.setSkipSendToOriginalEndpoint(val); break;
case "uri": def.setUri(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, outputDefinitionElementHandler(), noValueHandler());
}
protected KameletDefinition doParseKameletDefinition() throws IOException, XmlPullParserException {
return doParse(new KameletDefinition(), (def, key, val) -> {
if ("name".equals(key)) {
def.setName(val);
return true;
}
return processorDefinitionAttributeHandler().accept(def, key, val);
}, outputDefinitionElementHandler(), noValueHandler());
}
protected LoadBalanceDefinition doParseLoadBalanceDefinition() throws IOException, XmlPullParserException {
return doParse(new LoadBalanceDefinition(),
processorDefinitionAttributeHandler(), (def, key) -> {
switch (key) {
case "failover": def.setLoadBalancerType(doParseFailoverLoadBalancerDefinition()); break;
case "random": def.setLoadBalancerType(doParseRandomLoadBalancerDefinition()); break;
case "customLoadBalancer": def.setLoadBalancerType(doParseCustomLoadBalancerDefinition()); break;
case "roundRobin": def.setLoadBalancerType(doParseRoundRobinLoadBalancerDefinition()); break;
case "sticky": def.setLoadBalancerType(doParseStickyLoadBalancerDefinition()); break;
case "topic": def.setLoadBalancerType(doParseTopicLoadBalancerDefinition()); break;
case "weighted": def.setLoadBalancerType(doParseWeightedLoadBalancerDefinition()); break;
default: return outputDefinitionElementHandler().accept(def, key);
}
return true;
}, noValueHandler());
}
protected LoadBalancerDefinition doParseLoadBalancerDefinition() throws IOException, XmlPullParserException {
return doParse(new LoadBalancerDefinition(),
identifiedTypeAttributeHandler(), noElementHandler(), noValueHandler());
}
protected LogDefinition doParseLogDefinition() throws IOException, XmlPullParserException {
return doParse(new LogDefinition(), (def, key, val) -> {
switch (key) {
case "logName": def.setLogName(val); break;
case "loggerRef": def.setLoggerRef(val); break;
case "loggingLevel": def.setLoggingLevel(val); break;
case "marker": def.setMarker(val); break;
case "message": def.setMessage(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected LoopDefinition doParseLoopDefinition() throws IOException, XmlPullParserException {
return doParse(new LoopDefinition(), (def, key, val) -> {
switch (key) {
case "breakOnShutdown": def.setBreakOnShutdown(val); break;
case "copy": def.setCopy(val); break;
case "doWhile": def.setDoWhile(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, outputExpressionNodeElementHandler(), noValueHandler());
}
protected MarshalDefinition doParseMarshalDefinition() throws IOException, XmlPullParserException {
return doParse(new MarshalDefinition(),
processorDefinitionAttributeHandler(), (def, key) -> {
DataFormatDefinition v = doParseDataFormatDefinitionRef(key);
if (v != null) {
def.setDataFormatType(v);
return true;
}
return optionalIdentifiedDefinitionElementHandler().accept(def, key);
}, noValueHandler());
}
protected MulticastDefinition doParseMulticastDefinition() throws IOException, XmlPullParserException {
return doParse(new MulticastDefinition(), (def, key, val) -> {
switch (key) {
case "executorServiceRef": def.setExecutorServiceRef(val); break;
case "onPrepareRef": def.setOnPrepareRef(val); break;
case "parallelAggregate": def.setParallelAggregate(val); break;
case "parallelProcessing": def.setParallelProcessing(val); break;
case "shareUnitOfWork": def.setShareUnitOfWork(val); break;
case "stopOnAggregateException": def.setStopOnAggregateException(val); break;
case "stopOnException": def.setStopOnException(val); break;
case "strategyMethodAllowNull": def.setStrategyMethodAllowNull(val); break;
case "strategyMethodName": def.setStrategyMethodName(val); break;
case "strategyRef": def.setStrategyRef(val); break;
case "streaming": def.setStreaming(val); break;
case "timeout": def.setTimeout(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, outputDefinitionElementHandler(), noValueHandler());
}
protected OnCompletionDefinition doParseOnCompletionDefinition() throws IOException, XmlPullParserException {
return doParse(new OnCompletionDefinition(), (def, key, val) -> {
switch (key) {
case "executorServiceRef": def.setExecutorServiceRef(val); break;
case "mode": def.setMode(val); break;
case "onCompleteOnly": def.setOnCompleteOnly(val); break;
case "onFailureOnly": def.setOnFailureOnly(val); break;
case "parallelProcessing": def.setParallelProcessing(val); break;
case "useOriginalMessage": def.setUseOriginalMessage(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, (def, key) -> {
if ("onWhen".equals(key)) {
def.setOnWhen(doParseWhenDefinition());
return true;
}
return outputDefinitionElementHandler().accept(def, key);
}, noValueHandler());
}
protected OnExceptionDefinition doParseOnExceptionDefinition() throws IOException, XmlPullParserException {
return doParse(new OnExceptionDefinition(), (def, key, val) -> {
switch (key) {
case "onExceptionOccurredRef": def.setOnExceptionOccurredRef(val); break;
case "onRedeliveryRef": def.setOnRedeliveryRef(val); break;
case "redeliveryPolicyRef": def.setRedeliveryPolicyRef(val); break;
case "useOriginalBody": def.setUseOriginalBody(val); break;
case "useOriginalMessage": def.setUseOriginalMessage(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, (def, key) -> {
switch (key) {
case "continued": def.setContinued(doParseExpressionSubElementDefinition()); break;
case "exception": doAdd(doParseText(), def.getExceptions(), def::setExceptions); break;
case "handled": def.setHandled(doParseExpressionSubElementDefinition()); break;
case "onWhen": def.setOnWhen(doParseWhenDefinition()); break;
case "redeliveryPolicy": def.setRedeliveryPolicyType(doParseRedeliveryPolicyDefinition()); break;
case "retryWhile": def.setRetryWhile(doParseExpressionSubElementDefinition()); break;
default: return outputDefinitionElementHandler().accept(def, key);
}
return true;
}, noValueHandler());
}
protected RedeliveryPolicyDefinition doParseRedeliveryPolicyDefinition() throws IOException, XmlPullParserException {
return doParse(new RedeliveryPolicyDefinition(), (def, key, val) -> {
switch (key) {
case "allowRedeliveryWhileStopping": def.setAllowRedeliveryWhileStopping(val); break;
case "asyncDelayedRedelivery": def.setAsyncDelayedRedelivery(val); break;
case "backOffMultiplier": def.setBackOffMultiplier(val); break;
case "collisionAvoidanceFactor": def.setCollisionAvoidanceFactor(val); break;
case "delayPattern": def.setDelayPattern(val); break;
case "disableRedelivery": def.setDisableRedelivery(val); break;
case "exchangeFormatterRef": def.setExchangeFormatterRef(val); break;
case "logContinued": def.setLogContinued(val); break;
case "logExhausted": def.setLogExhausted(val); break;
case "logExhaustedMessageBody": def.setLogExhaustedMessageBody(val); break;
case "logExhaustedMessageHistory": def.setLogExhaustedMessageHistory(val); break;
case "logHandled": def.setLogHandled(val); break;
case "logNewException": def.setLogNewException(val); break;
case "logRetryAttempted": def.setLogRetryAttempted(val); break;
case "logRetryStackTrace": def.setLogRetryStackTrace(val); break;
case "logStackTrace": def.setLogStackTrace(val); break;
case "maximumRedeliveries": def.setMaximumRedeliveries(val); break;
case "maximumRedeliveryDelay": def.setMaximumRedeliveryDelay(val); break;
case "redeliveryDelay": def.setRedeliveryDelay(val); break;
case "retriesExhaustedLogLevel": def.setRetriesExhaustedLogLevel(val); break;
case "retryAttemptedLogInterval": def.setRetryAttemptedLogInterval(val); break;
case "retryAttemptedLogLevel": def.setRetryAttemptedLogLevel(val); break;
case "useCollisionAvoidance": def.setUseCollisionAvoidance(val); break;
case "useExponentialBackOff": def.setUseExponentialBackOff(val); break;
default: return false;
}
return true;
}, noElementHandler(), noValueHandler());
}
protected OnFallbackDefinition doParseOnFallbackDefinition() throws IOException, XmlPullParserException {
return doParse(new OnFallbackDefinition(), (def, key, val) -> {
if ("fallbackViaNetwork".equals(key)) {
def.setFallbackViaNetwork(val);
return true;
}
return processorDefinitionAttributeHandler().accept(def, key, val);
}, outputDefinitionElementHandler(), noValueHandler());
}
protected OutputTypeDefinition doParseOutputTypeDefinition() throws IOException, XmlPullParserException {
return doParse(new OutputTypeDefinition(), (def, key, val) -> {
switch (key) {
case "urn": def.setUrn(val); break;
case "validate": def.setValidate(val); break;
default: return optionalIdentifiedDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected PackageScanDefinition doParsePackageScanDefinition() throws IOException, XmlPullParserException {
return doParse(new PackageScanDefinition(),
noAttributeHandler(), (def, key) -> {
switch (key) {
case "excludes": doAdd(doParseText(), def.getExcludes(), def::setExcludes); break;
case "includes": doAdd(doParseText(), def.getIncludes(), def::setIncludes); break;
case "package": doAdd(doParseText(), def.getPackages(), def::setPackages); break;
default: return false;
}
return true;
}, noValueHandler());
}
protected PipelineDefinition doParsePipelineDefinition() throws IOException, XmlPullParserException {
return doParse(new PipelineDefinition(),
processorDefinitionAttributeHandler(), outputDefinitionElementHandler(), noValueHandler());
}
protected PolicyDefinition doParsePolicyDefinition() throws IOException, XmlPullParserException {
return doParse(new PolicyDefinition(), (def, key, val) -> {
if ("ref".equals(key)) {
def.setRef(val);
return true;
}
return processorDefinitionAttributeHandler().accept(def, key, val);
}, outputDefinitionElementHandler(), noValueHandler());
}
protected PollEnrichDefinition doParsePollEnrichDefinition() throws IOException, XmlPullParserException {
return doParse(new PollEnrichDefinition(), (def, key, val) -> {
switch (key) {
case "aggregateOnException": def.setAggregateOnException(val); break;
case "cacheSize": def.setCacheSize(val); break;
case "ignoreInvalidEndpoint": def.setIgnoreInvalidEndpoint(val); break;
case "strategyMethodAllowNull": def.setAggregationStrategyMethodAllowNull(val); break;
case "strategyMethodName": def.setAggregationStrategyMethodName(val); break;
case "strategyRef": def.setAggregationStrategyRef(val); break;
case "timeout": def.setTimeout(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, expressionNodeElementHandler(), noValueHandler());
}
protected ProcessDefinition doParseProcessDefinition() throws IOException, XmlPullParserException {
return doParse(new ProcessDefinition(), (def, key, val) -> {
if ("ref".equals(key)) {
def.setRef(val);
return true;
}
return processorDefinitionAttributeHandler().accept(def, key, val);
}, optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected PropertyDefinition doParsePropertyDefinition() throws IOException, XmlPullParserException {
return doParse(new PropertyDefinition(), (def, key, val) -> {
switch (key) {
case "key": def.setKey(val); break;
case "value": def.setValue(val); break;
default: return false;
}
return true;
}, noElementHandler(), noValueHandler());
}
protected PropertyDefinitions doParsePropertyDefinitions() throws IOException, XmlPullParserException {
return doParse(new PropertyDefinitions(),
noAttributeHandler(), (def, key) -> {
if ("properties".equals(key)) {
doAdd(doParsePropertyDefinition(), def.getProperties(), def::setProperties);
return true;
}
return false;
}, noValueHandler());
}
protected PropertyExpressionDefinition doParsePropertyExpressionDefinition() throws IOException, XmlPullParserException {
return doParse(new PropertyExpressionDefinition(), (def, key, val) -> {
if ("key".equals(key)) {
def.setKey(val);
return true;
}
return false;
}, (def, key) -> {
ExpressionDefinition v = doParseExpressionDefinitionRef(key);
if (v != null) {
def.setExpression(v);
return true;
}
return false;
}, noValueHandler());
}
protected RecipientListDefinition doParseRecipientListDefinition() throws IOException, XmlPullParserException {
return doParse(new RecipientListDefinition(), (def, key, val) -> {
switch (key) {
case "cacheSize": def.setCacheSize(val); break;
case "delimiter": def.setDelimiter(val); break;
case "executorServiceRef": def.setExecutorServiceRef(val); break;
case "ignoreInvalidEndpoints": def.setIgnoreInvalidEndpoints(val); break;
case "onPrepareRef": def.setOnPrepareRef(val); break;
case "parallelAggregate": def.setParallelAggregate(val); break;
case "parallelProcessing": def.setParallelProcessing(val); break;
case "shareUnitOfWork": def.setShareUnitOfWork(val); break;
case "stopOnAggregateException": def.setStopOnAggregateException(val); break;
case "stopOnException": def.setStopOnException(val); break;
case "strategyMethodAllowNull": def.setStrategyMethodAllowNull(val); break;
case "strategyMethodName": def.setStrategyMethodName(val); break;
case "strategyRef": def.setStrategyRef(val); break;
case "streaming": def.setStreaming(val); break;
case "timeout": def.setTimeout(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, expressionNodeElementHandler(), noValueHandler());
}
protected RemoveHeaderDefinition doParseRemoveHeaderDefinition() throws IOException, XmlPullParserException {
return doParse(new RemoveHeaderDefinition(), (def, key, val) -> {
if ("name".equals(key)) {
def.setName(val);
return true;
}
return processorDefinitionAttributeHandler().accept(def, key, val);
}, optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected RemoveHeadersDefinition doParseRemoveHeadersDefinition() throws IOException, XmlPullParserException {
return doParse(new RemoveHeadersDefinition(), (def, key, val) -> {
switch (key) {
case "excludePattern": def.setExcludePattern(val); break;
case "pattern": def.setPattern(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected RemovePropertiesDefinition doParseRemovePropertiesDefinition() throws IOException, XmlPullParserException {
return doParse(new RemovePropertiesDefinition(), (def, key, val) -> {
switch (key) {
case "excludePattern": def.setExcludePattern(val); break;
case "pattern": def.setPattern(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected RemovePropertyDefinition doParseRemovePropertyDefinition() throws IOException, XmlPullParserException {
return doParse(new RemovePropertyDefinition(), (def, key, val) -> {
if ("name".equals(key)) {
def.setName(val);
return true;
}
return processorDefinitionAttributeHandler().accept(def, key, val);
}, optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected ResequenceDefinition doParseResequenceDefinition() throws IOException, XmlPullParserException {
return doParse(new ResequenceDefinition(),
processorDefinitionAttributeHandler(), (def, key) -> {
switch (key) {
case "batch-config": def.setResequencerConfig(doParseBatchResequencerConfig()); break;
case "stream-config": def.setResequencerConfig(doParseStreamResequencerConfig()); break;
default:
ExpressionDefinition v = doParseExpressionDefinitionRef(key);
if (v != null) {
def.setExpression(v);
return true;
}
return outputDefinitionElementHandler().accept(def, key);
}
return true;
}, noValueHandler());
}
protected <T extends Resilience4jConfigurationCommon> AttributeHandler<T> resilience4jConfigurationCommonAttributeHandler() {
return (def, key, val) -> {
switch (key) {
case "automaticTransitionFromOpenToHalfOpenEnabled": def.setAutomaticTransitionFromOpenToHalfOpenEnabled(val); break;
case "circuitBreakerRef": def.setCircuitBreakerRef(val); break;
case "configRef": def.setConfigRef(val); break;
case "failureRateThreshold": def.setFailureRateThreshold(val); break;
case "minimumNumberOfCalls": def.setMinimumNumberOfCalls(val); break;
case "permittedNumberOfCallsInHalfOpenState": def.setPermittedNumberOfCallsInHalfOpenState(val); break;
case "slidingWindowSize": def.setSlidingWindowSize(val); break;
case "slidingWindowType": def.setSlidingWindowType(val); break;
case "slowCallDurationThreshold": def.setSlowCallDurationThreshold(val); break;
case "slowCallRateThreshold": def.setSlowCallRateThreshold(val); break;
case "waitDurationInOpenState": def.setWaitDurationInOpenState(val); break;
case "writableStackTraceEnabled": def.setWritableStackTraceEnabled(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
};
}
protected <T extends Resilience4jConfigurationCommon> ElementHandler<T> resilience4jConfigurationCommonElementHandler() {
return (def, key) -> {
switch (key) {
case "bulkheadEnabled": def.setBulkheadEnabled(doParseText()); break;
case "bulkheadMaxConcurrentCalls": def.setBulkheadMaxConcurrentCalls(doParseText()); break;
case "bulkheadMaxWaitDuration": def.setBulkheadMaxWaitDuration(doParseText()); break;
case "timeoutCancelRunningFuture": def.setTimeoutCancelRunningFuture(doParseText()); break;
case "timeoutDuration": def.setTimeoutDuration(doParseText()); break;
case "timeoutEnabled": def.setTimeoutEnabled(doParseText()); break;
case "timeoutExecutorServiceRef": def.setTimeoutExecutorServiceRef(doParseText()); break;
default: return false;
}
return true;
};
}
protected Resilience4jConfigurationCommon doParseResilience4jConfigurationCommon() throws IOException, XmlPullParserException {
return doParse(new Resilience4jConfigurationCommon(), resilience4jConfigurationCommonAttributeHandler(), resilience4jConfigurationCommonElementHandler(), noValueHandler());
}
protected RestContextRefDefinition doParseRestContextRefDefinition() throws IOException, XmlPullParserException {
return doParse(new RestContextRefDefinition(), (def, key, val) -> {
if ("ref".equals(key)) {
def.setRef(val);
return true;
}
return false;
}, noElementHandler(), noValueHandler());
}
protected RollbackDefinition doParseRollbackDefinition() throws IOException, XmlPullParserException {
return doParse(new RollbackDefinition(), (def, key, val) -> {
switch (key) {
case "markRollbackOnly": def.setMarkRollbackOnly(val); break;
case "markRollbackOnlyLast": def.setMarkRollbackOnlyLast(val); break;
case "message": def.setMessage(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected RouteBuilderDefinition doParseRouteBuilderDefinition() throws IOException, XmlPullParserException {
return doParse(new RouteBuilderDefinition(), (def, key, val) -> {
if ("ref".equals(key)) {
def.setRef(val);
return true;
}
return identifiedTypeAttributeHandler().accept(def, key, val);
}, noElementHandler(), noValueHandler());
}
protected RouteConfigurationContextRefDefinition doParseRouteConfigurationContextRefDefinition() throws IOException, XmlPullParserException {
return doParse(new RouteConfigurationContextRefDefinition(), (def, key, val) -> {
if ("ref".equals(key)) {
def.setRef(val);
return true;
}
return false;
}, noElementHandler(), noValueHandler());
}
protected RouteConfigurationDefinition doParseRouteConfigurationDefinition() throws IOException, XmlPullParserException {
return doParse(new RouteConfigurationDefinition(),
optionalIdentifiedDefinitionAttributeHandler(), (def, key) -> {
switch (key) {
case "interceptFrom": doAdd(doParseInterceptFromDefinition(), def.getInterceptFroms(), def::setInterceptFroms); break;
case "interceptSendToEndpoint": doAdd(doParseInterceptSendToEndpointDefinition(), def.getInterceptSendTos(), def::setInterceptSendTos); break;
case "intercept": doAdd(doParseInterceptDefinition(), def.getIntercepts(), def::setIntercepts); break;
case "onCompletion": doAdd(doParseOnCompletionDefinition(), def.getOnCompletions(), def::setOnCompletions); break;
case "onException": doAdd(doParseOnExceptionDefinition(), def.getOnExceptions(), def::setOnExceptions); break;
default: return optionalIdentifiedDefinitionElementHandler().accept(def, key);
}
return true;
}, noValueHandler());
}
public Optional<RouteConfigurationsDefinition> parseRouteConfigurationsDefinition()
throws IOException, XmlPullParserException {
String tag = getNextTag("routeConfigurations", "routeConfiguration");
if (tag != null) {
switch (tag) {
case "routeConfigurations" : return Optional.of(doParseRouteConfigurationsDefinition());
case "routeConfiguration" : return parseSingleRouteConfigurationsDefinition();
}
}
return Optional.empty();
}
private Optional<RouteConfigurationsDefinition> parseSingleRouteConfigurationsDefinition()
throws IOException, XmlPullParserException {
Optional<RouteConfigurationDefinition> single = Optional.of(doParseRouteConfigurationDefinition());
if (single.isPresent()) {
List<RouteConfigurationDefinition> list = new ArrayList<>();
list.add(single.get());
RouteConfigurationsDefinition def = new RouteConfigurationsDefinition();
def.setRouteConfigurations(list);
return Optional.of(def);
}
return Optional.empty();
}
protected RouteConfigurationsDefinition doParseRouteConfigurationsDefinition() throws IOException, XmlPullParserException {
return doParse(new RouteConfigurationsDefinition(),
noAttributeHandler(), (def, key) -> {
if ("routeConfiguration".equals(key)) {
doAdd(doParseRouteConfigurationDefinition(), def.getRouteConfigurations(), def::setRouteConfigurations);
return true;
}
return false;
}, noValueHandler());
}
protected RouteContextRefDefinition doParseRouteContextRefDefinition() throws IOException, XmlPullParserException {
return doParse(new RouteContextRefDefinition(), (def, key, val) -> {
if ("ref".equals(key)) {
def.setRef(val);
return true;
}
return false;
}, noElementHandler(), noValueHandler());
}
protected RouteDefinition doParseRouteDefinition() throws IOException, XmlPullParserException {
return doParse(new RouteDefinition(), (def, key, val) -> {
switch (key) {
case "autoStartup": def.setAutoStartup(val); break;
case "delayer": def.setDelayer(val); break;
case "errorHandlerRef": def.setErrorHandlerRef(val); break;
case "group": def.setGroup(val); break;
case "logMask": def.setLogMask(val); break;
case "messageHistory": def.setMessageHistory(val); break;
case "routeConfigurationId": def.setRouteConfigurationId(val); break;
case "routePolicyRef": def.setRoutePolicyRef(val); break;
case "shutdownRoute": def.setShutdownRoute(val); break;
case "shutdownRunningTask": def.setShutdownRunningTask(val); break;
case "startupOrder": def.setStartupOrder(Integer.valueOf(val)); break;
case "streamCache": def.setStreamCache(val); break;
case "trace": def.setTrace(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, (def, key) -> {
switch (key) {
case "from": def.setInput(doParseFromDefinition()); break;
case "inputType": def.setInputType(doParseInputTypeDefinition()); break;
case "outputType": def.setOutputType(doParseOutputTypeDefinition()); break;
case "rest": def.setRest(Boolean.valueOf(doParseText())); break;
case "routeProperty": doAdd(doParsePropertyDefinition(), def.getRouteProperties(), def::setRouteProperties); break;
case "template": def.setTemplate(Boolean.valueOf(doParseText())); break;
default: return outputDefinitionElementHandler().accept(def, key);
}
return true;
}, noValueHandler());
}
protected RestDefinition doParseRestDefinition() throws IOException, XmlPullParserException {
return doParse(new RestDefinition(), (def, key, val) -> {
switch (key) {
case "apiDocs": def.setApiDocs(val); break;
case "bindingMode": def.setBindingMode(val); break;
case "clientRequestValidation": def.setClientRequestValidation(val); break;
case "consumes": def.setConsumes(val); break;
case "enableCORS": def.setEnableCORS(val); break;
case "path": def.setPath(val); break;
case "produces": def.setProduces(val); break;
case "skipBindingOnErrorCode": def.setSkipBindingOnErrorCode(val); break;
case "tag": def.setTag(val); break;
default: return optionalIdentifiedDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, (def, key) -> {
switch (key) {
case "delete": doAdd(doParseDeleteDefinition(), def.getVerbs(), def::setVerbs); break;
case "get": doAdd(doParseGetDefinition(), def.getVerbs(), def::setVerbs); break;
case "head": doAdd(doParseHeadDefinition(), def.getVerbs(), def::setVerbs); break;
case "patch": doAdd(doParsePatchDefinition(), def.getVerbs(), def::setVerbs); break;
case "post": doAdd(doParsePostDefinition(), def.getVerbs(), def::setVerbs); break;
case "put": doAdd(doParsePutDefinition(), def.getVerbs(), def::setVerbs); break;
case "securityDefinitions": def.setSecurityDefinitions(doParseRestSecuritiesDefinition()); break;
case "securityRequirements": def.setSecurityRequirements(doParseRestSecuritiesRequirement()); break;
default: return optionalIdentifiedDefinitionElementHandler().accept(def, key);
}
return true;
}, noValueHandler());
}
protected RestBindingDefinition doParseRestBindingDefinition() throws IOException, XmlPullParserException {
return doParse(new RestBindingDefinition(), (def, key, val) -> {
switch (key) {
case "bindingMode": def.setBindingMode(val); break;
case "clientRequestValidation": def.setClientRequestValidation(val); break;
case "component": def.setComponent(val); break;
case "consumes": def.setConsumes(val); break;
case "enableCORS": def.setEnableCORS(val); break;
case "outType": def.setOutType(val); break;
case "produces": def.setProduces(val); break;
case "skipBindingOnErrorCode": def.setSkipBindingOnErrorCode(val); break;
case "type": def.setType(val); break;
default: return optionalIdentifiedDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected RouteTemplateBeanDefinition doParseRouteTemplateBeanDefinition() throws IOException, XmlPullParserException {
return doParse(new RouteTemplateBeanDefinition(),
beanFactoryDefinitionAttributeHandler(), beanFactoryDefinitionElementHandler(), noValueHandler());
}
protected <T extends BeanFactoryDefinition> AttributeHandler<T> beanFactoryDefinitionAttributeHandler() {
return (def, key, val) -> {
switch (key) {
case "beanType": def.setBeanType(val); break;
case "name": def.setName(val); break;
case "type": def.setType(val); break;
default: return false;
}
return true;
};
}
protected <T extends BeanFactoryDefinition> ElementHandler<T> beanFactoryDefinitionElementHandler() {
return (def, key) -> {
switch (key) {
case "property": doAdd(doParsePropertyDefinition(), def.getProperties(), def::setProperties); break;
case "script": def.setScript(doParseText()); break;
default: return false;
}
return true;
};
}
protected RouteTemplateContextRefDefinition doParseRouteTemplateContextRefDefinition() throws IOException, XmlPullParserException {
return doParse(new RouteTemplateContextRefDefinition(), (def, key, val) -> {
if ("ref".equals(key)) {
def.setRef(val);
return true;
}
return false;
}, noElementHandler(), noValueHandler());
}
protected RouteTemplateDefinition doParseRouteTemplateDefinition() throws IOException, XmlPullParserException {
return doParse(new RouteTemplateDefinition(),
optionalIdentifiedDefinitionAttributeHandler(), (def, key) -> {
switch (key) {
case "route": def.setRoute(doParseRouteDefinition()); break;
case "templateBean": doAdd(doParseRouteTemplateBeanDefinition(), def.getTemplateBeans(), def::setTemplateBeans); break;
case "templateParameter": doAdd(doParseRouteTemplateParameterDefinition(), def.getTemplateParameters(), def::setTemplateParameters); break;
default: return optionalIdentifiedDefinitionElementHandler().accept(def, key);
}
return true;
}, noValueHandler());
}
protected RouteTemplateParameterDefinition doParseRouteTemplateParameterDefinition() throws IOException, XmlPullParserException {
return doParse(new RouteTemplateParameterDefinition(), (def, key, val) -> {
switch (key) {
case "defaultValue": def.setDefaultValue(val); break;
case "description": def.setDescription(val); break;
case "name": def.setName(val); break;
case "required": def.setRequired(Boolean.valueOf(val)); break;
default: return false;
}
return true;
}, noElementHandler(), noValueHandler());
}
public Optional<RouteTemplatesDefinition> parseRouteTemplatesDefinition()
throws IOException, XmlPullParserException {
String tag = getNextTag("routeTemplates", "routeTemplate");
if (tag != null) {
switch (tag) {
case "routeTemplates" : return Optional.of(doParseRouteTemplatesDefinition());
case "routeTemplate" : return parseSingleRouteTemplatesDefinition();
}
}
return Optional.empty();
}
private Optional<RouteTemplatesDefinition> parseSingleRouteTemplatesDefinition()
throws IOException, XmlPullParserException {
Optional<RouteTemplateDefinition> single = Optional.of(doParseRouteTemplateDefinition());
if (single.isPresent()) {
List<RouteTemplateDefinition> list = new ArrayList<>();
list.add(single.get());
RouteTemplatesDefinition def = new RouteTemplatesDefinition();
def.setRouteTemplates(list);
return Optional.of(def);
}
return Optional.empty();
}
protected RouteTemplatesDefinition doParseRouteTemplatesDefinition() throws IOException, XmlPullParserException {
return doParse(new RouteTemplatesDefinition(),
optionalIdentifiedDefinitionAttributeHandler(), (def, key) -> {
if ("routeTemplate".equals(key)) {
doAdd(doParseRouteTemplateDefinition(), def.getRouteTemplates(), def::setRouteTemplates);
return true;
}
return optionalIdentifiedDefinitionElementHandler().accept(def, key);
}, noValueHandler());
}
public Optional<RoutesDefinition> parseRoutesDefinition()
throws IOException, XmlPullParserException {
String tag = getNextTag("routes", "route");
if (tag != null) {
switch (tag) {
case "routes" : return Optional.of(doParseRoutesDefinition());
case "route" : return parseSingleRoutesDefinition();
}
}
return Optional.empty();
}
private Optional<RoutesDefinition> parseSingleRoutesDefinition()
throws IOException, XmlPullParserException {
Optional<RouteDefinition> single = Optional.of(doParseRouteDefinition());
if (single.isPresent()) {
List<RouteDefinition> list = new ArrayList<>();
list.add(single.get());
RoutesDefinition def = new RoutesDefinition();
def.setRoutes(list);
return Optional.of(def);
}
return Optional.empty();
}
protected RoutesDefinition doParseRoutesDefinition() throws IOException, XmlPullParserException {
return doParse(new RoutesDefinition(),
optionalIdentifiedDefinitionAttributeHandler(), (def, key) -> {
if ("route".equals(key)) {
doAdd(doParseRouteDefinition(), def.getRoutes(), def::setRoutes);
return true;
}
return optionalIdentifiedDefinitionElementHandler().accept(def, key);
}, noValueHandler());
}
protected RoutingSlipDefinition doParseRoutingSlipDefinition() throws IOException, XmlPullParserException {
return doParse(new RoutingSlipDefinition(), (def, key, val) -> {
switch (key) {
case "cacheSize": def.setCacheSize(val); break;
case "ignoreInvalidEndpoints": def.setIgnoreInvalidEndpoints(val); break;
case "uriDelimiter": def.setUriDelimiter(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, expressionNodeElementHandler(), noValueHandler());
}
protected SagaDefinition doParseSagaDefinition() throws IOException, XmlPullParserException {
return doParse(new SagaDefinition(), (def, key, val) -> {
switch (key) {
case "completionMode": def.setCompletionMode(val); break;
case "propagation": def.setPropagation(val); break;
case "sagaServiceRef": def.setSagaServiceRef(val); break;
case "timeout": def.setTimeout(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, (def, key) -> {
switch (key) {
case "compensation": def.setCompensation(doParseSagaActionUriDefinition()); break;
case "completion": def.setCompletion(doParseSagaActionUriDefinition()); break;
case "option": doAdd(doParsePropertyExpressionDefinition(), def.getOptions(), def::setOptions); break;
default: return outputDefinitionElementHandler().accept(def, key);
}
return true;
}, noValueHandler());
}
protected SagaActionUriDefinition doParseSagaActionUriDefinition() throws IOException, XmlPullParserException {
return doParse(new SagaActionUriDefinition(),
sendDefinitionAttributeHandler(), optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected SamplingDefinition doParseSamplingDefinition() throws IOException, XmlPullParserException {
return doParse(new SamplingDefinition(), (def, key, val) -> {
switch (key) {
case "messageFrequency": def.setMessageFrequency(val); break;
case "samplePeriod": def.setSamplePeriod(val); break;
case "units": def.setUnits(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected ScriptDefinition doParseScriptDefinition() throws IOException, XmlPullParserException {
return doParse(new ScriptDefinition(),
processorDefinitionAttributeHandler(), expressionNodeElementHandler(), noValueHandler());
}
protected SetBodyDefinition doParseSetBodyDefinition() throws IOException, XmlPullParserException {
return doParse(new SetBodyDefinition(),
processorDefinitionAttributeHandler(), expressionNodeElementHandler(), noValueHandler());
}
protected SetExchangePatternDefinition doParseSetExchangePatternDefinition() throws IOException, XmlPullParserException {
return doParse(new SetExchangePatternDefinition(), (def, key, val) -> {
if ("pattern".equals(key)) {
def.setPattern(val);
return true;
}
return processorDefinitionAttributeHandler().accept(def, key, val);
}, optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected SetHeaderDefinition doParseSetHeaderDefinition() throws IOException, XmlPullParserException {
return doParse(new SetHeaderDefinition(), (def, key, val) -> {
if ("name".equals(key)) {
def.setName(val);
return true;
}
return processorDefinitionAttributeHandler().accept(def, key, val);
}, expressionNodeElementHandler(), noValueHandler());
}
protected SetPropertyDefinition doParseSetPropertyDefinition() throws IOException, XmlPullParserException {
return doParse(new SetPropertyDefinition(), (def, key, val) -> {
if ("name".equals(key)) {
def.setName(val);
return true;
}
return processorDefinitionAttributeHandler().accept(def, key, val);
}, expressionNodeElementHandler(), noValueHandler());
}
protected SortDefinition doParseSortDefinition() throws IOException, XmlPullParserException {
return doParse(new SortDefinition(), (def, key, val) -> {
if ("comparatorRef".equals(key)) {
def.setComparatorRef(val);
return true;
}
return processorDefinitionAttributeHandler().accept(def, key, val);
}, expressionNodeElementHandler(), noValueHandler());
}
protected SplitDefinition doParseSplitDefinition() throws IOException, XmlPullParserException {
return doParse(new SplitDefinition(), (def, key, val) -> {
switch (key) {
case "delimiter": def.setDelimiter(val); break;
case "executorServiceRef": def.setExecutorServiceRef(val); break;
case "onPrepareRef": def.setOnPrepareRef(val); break;
case "parallelAggregate": def.setParallelAggregate(val); break;
case "parallelProcessing": def.setParallelProcessing(val); break;
case "shareUnitOfWork": def.setShareUnitOfWork(val); break;
case "stopOnAggregateException": def.setStopOnAggregateException(val); break;
case "stopOnException": def.setStopOnException(val); break;
case "strategyMethodAllowNull": def.setStrategyMethodAllowNull(val); break;
case "strategyMethodName": def.setStrategyMethodName(val); break;
case "strategyRef": def.setStrategyRef(val); break;
case "streaming": def.setStreaming(val); break;
case "timeout": def.setTimeout(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, outputExpressionNodeElementHandler(), noValueHandler());
}
protected StepDefinition doParseStepDefinition() throws IOException, XmlPullParserException {
return doParse(new StepDefinition(),
processorDefinitionAttributeHandler(), outputDefinitionElementHandler(), noValueHandler());
}
protected StopDefinition doParseStopDefinition() throws IOException, XmlPullParserException {
return doParse(new StopDefinition(),
processorDefinitionAttributeHandler(), optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected SwitchDefinition doParseSwitchDefinition() throws IOException, XmlPullParserException {
return doParse(new SwitchDefinition(),
processorDefinitionAttributeHandler(), choiceDefinitionElementHandler(), noValueHandler());
}
protected TemplatedRouteBeanDefinition doParseTemplatedRouteBeanDefinition() throws IOException, XmlPullParserException {
return doParse(new TemplatedRouteBeanDefinition(),
beanFactoryDefinitionAttributeHandler(), beanFactoryDefinitionElementHandler(), noValueHandler());
}
protected TemplatedRouteDefinition doParseTemplatedRouteDefinition() throws IOException, XmlPullParserException {
return doParse(new TemplatedRouteDefinition(), (def, key, val) -> {
switch (key) {
case "routeId": def.setRouteId(val); break;
case "routeTemplateRef": def.setRouteTemplateRef(val); break;
default: return false;
}
return true;
}, (def, key) -> {
switch (key) {
case "bean": doAdd(doParseTemplatedRouteBeanDefinition(), def.getBeans(), def::setBeans); break;
case "parameter": doAdd(doParseTemplatedRouteParameterDefinition(), def.getParameters(), def::setParameters); break;
default: return false;
}
return true;
}, noValueHandler());
}
protected TemplatedRouteParameterDefinition doParseTemplatedRouteParameterDefinition() throws IOException, XmlPullParserException {
return doParse(new TemplatedRouteParameterDefinition(), (def, key, val) -> {
switch (key) {
case "name": def.setName(val); break;
case "value": def.setValue(val); break;
default: return false;
}
return true;
}, noElementHandler(), noValueHandler());
}
public Optional<TemplatedRoutesDefinition> parseTemplatedRoutesDefinition()
throws IOException, XmlPullParserException {
String tag = getNextTag("templatedRoutes", "templatedRoute");
if (tag != null) {
switch (tag) {
case "templatedRoutes" : return Optional.of(doParseTemplatedRoutesDefinition());
case "templatedRoute" : return parseSingleTemplatedRoutesDefinition();
}
}
return Optional.empty();
}
private Optional<TemplatedRoutesDefinition> parseSingleTemplatedRoutesDefinition()
throws IOException, XmlPullParserException {
Optional<TemplatedRouteDefinition> single = Optional.of(doParseTemplatedRouteDefinition());
if (single.isPresent()) {
List<TemplatedRouteDefinition> list = new ArrayList<>();
list.add(single.get());
TemplatedRoutesDefinition def = new TemplatedRoutesDefinition();
def.setTemplatedRoutes(list);
return Optional.of(def);
}
return Optional.empty();
}
protected TemplatedRoutesDefinition doParseTemplatedRoutesDefinition() throws IOException, XmlPullParserException {
return doParse(new TemplatedRoutesDefinition(),
optionalIdentifiedDefinitionAttributeHandler(), (def, key) -> {
if ("templatedRoute".equals(key)) {
doAdd(doParseTemplatedRouteDefinition(), def.getTemplatedRoutes(), def::setTemplatedRoutes);
return true;
}
return optionalIdentifiedDefinitionElementHandler().accept(def, key);
}, noValueHandler());
}
protected ThreadPoolProfileDefinition doParseThreadPoolProfileDefinition() throws IOException, XmlPullParserException {
return doParse(new ThreadPoolProfileDefinition(), (def, key, val) -> {
switch (key) {
case "allowCoreThreadTimeOut": def.setAllowCoreThreadTimeOut(val); break;
case "defaultProfile": def.setDefaultProfile(val); break;
case "keepAliveTime": def.setKeepAliveTime(val); break;
case "maxPoolSize": def.setMaxPoolSize(val); break;
case "maxQueueSize": def.setMaxQueueSize(val); break;
case "poolSize": def.setPoolSize(val); break;
case "rejectedPolicy": def.setRejectedPolicy(val); break;
case "timeUnit": def.setTimeUnit(val); break;
default: return optionalIdentifiedDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected ThreadsDefinition doParseThreadsDefinition() throws IOException, XmlPullParserException {
return doParse(new ThreadsDefinition(), (def, key, val) -> {
switch (key) {
case "allowCoreThreadTimeOut": def.setAllowCoreThreadTimeOut(val); break;
case "callerRunsWhenRejected": def.setCallerRunsWhenRejected(val); break;
case "executorServiceRef": def.setExecutorServiceRef(val); break;
case "keepAliveTime": def.setKeepAliveTime(val); break;
case "maxPoolSize": def.setMaxPoolSize(val); break;
case "maxQueueSize": def.setMaxQueueSize(val); break;
case "poolSize": def.setPoolSize(val); break;
case "rejectedPolicy": def.setRejectedPolicy(val); break;
case "threadName": def.setThreadName(val); break;
case "timeUnit": def.setTimeUnit(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected ThrottleDefinition doParseThrottleDefinition() throws IOException, XmlPullParserException {
return doParse(new ThrottleDefinition(), (def, key, val) -> {
switch (key) {
case "asyncDelayed": def.setAsyncDelayed(val); break;
case "callerRunsWhenRejected": def.setCallerRunsWhenRejected(val); break;
case "executorServiceRef": def.setExecutorServiceRef(val); break;
case "rejectExecution": def.setRejectExecution(val); break;
case "timePeriodMillis": def.setTimePeriodMillis(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, (def, key) -> {
if ("correlationExpression".equals(key)) {
def.setCorrelationExpression(doParseExpressionSubElementDefinition());
return true;
}
return expressionNodeElementHandler().accept(def, key);
}, noValueHandler());
}
protected ThrowExceptionDefinition doParseThrowExceptionDefinition() throws IOException, XmlPullParserException {
return doParse(new ThrowExceptionDefinition(), (def, key, val) -> {
switch (key) {
case "exceptionType": def.setExceptionType(val); break;
case "message": def.setMessage(val); break;
case "ref": def.setRef(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected ToDefinition doParseToDefinition() throws IOException, XmlPullParserException {
return doParse(new ToDefinition(), (def, key, val) -> {
if ("pattern".equals(key)) {
def.setPattern(val);
return true;
}
return sendDefinitionAttributeHandler().accept(def, key, val);
}, optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected <T extends ToDynamicDefinition> AttributeHandler<T> toDynamicDefinitionAttributeHandler() {
return (def, key, val) -> {
switch (key) {
case "allowOptimisedComponents": def.setAllowOptimisedComponents(val); break;
case "autoStartComponents": def.setAutoStartComponents(val); break;
case "cacheSize": def.setCacheSize(val); break;
case "ignoreInvalidEndpoint": def.setIgnoreInvalidEndpoint(val); break;
case "pattern": def.setPattern(val); break;
case "uri": def.setUri(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
};
}
protected ToDynamicDefinition doParseToDynamicDefinition() throws IOException, XmlPullParserException {
return doParse(new ToDynamicDefinition(), toDynamicDefinitionAttributeHandler(), optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected TransactedDefinition doParseTransactedDefinition() throws IOException, XmlPullParserException {
return doParse(new TransactedDefinition(), (def, key, val) -> {
if ("ref".equals(key)) {
def.setRef(val);
return true;
}
return processorDefinitionAttributeHandler().accept(def, key, val);
}, outputDefinitionElementHandler(), noValueHandler());
}
protected TransformDefinition doParseTransformDefinition() throws IOException, XmlPullParserException {
return doParse(new TransformDefinition(),
processorDefinitionAttributeHandler(), expressionNodeElementHandler(), noValueHandler());
}
protected TryDefinition doParseTryDefinition() throws IOException, XmlPullParserException {
return doParse(new TryDefinition(),
processorDefinitionAttributeHandler(), outputDefinitionElementHandler(), noValueHandler());
}
protected UnmarshalDefinition doParseUnmarshalDefinition() throws IOException, XmlPullParserException {
return doParse(new UnmarshalDefinition(),
processorDefinitionAttributeHandler(), (def, key) -> {
DataFormatDefinition v = doParseDataFormatDefinitionRef(key);
if (v != null) {
def.setDataFormatType(v);
return true;
}
return optionalIdentifiedDefinitionElementHandler().accept(def, key);
}, noValueHandler());
}
protected ValidateDefinition doParseValidateDefinition() throws IOException, XmlPullParserException {
return doParse(new ValidateDefinition(), (def, key, val) -> {
if ("predicateExceptionFactory".equals(key)) {
def.setPredicateExceptionFactory(val);
return true;
}
return processorDefinitionAttributeHandler().accept(def, key, val);
}, expressionNodeElementHandler(), noValueHandler());
}
protected WireTapDefinition doParseWireTapDefinition() throws IOException, XmlPullParserException {
return doParse(new WireTapDefinition(), (def, key, val) -> {
switch (key) {
case "copy": def.setCopy(val); break;
case "dynamicUri": def.setDynamicUri(val); break;
case "executorServiceRef": def.setExecutorServiceRef(val); break;
case "onPrepareRef": def.setOnPrepareRef(val); break;
default: return toDynamicDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected BlacklistServiceCallServiceFilterConfiguration doParseBlacklistServiceCallServiceFilterConfiguration() throws IOException, XmlPullParserException {
return doParse(new BlacklistServiceCallServiceFilterConfiguration(),
identifiedTypeAttributeHandler(), (def, key) -> {
if ("servers".equals(key)) {
doAdd(doParseText(), def.getServers(), def::setServers);
return true;
}
return serviceCallConfigurationElementHandler().accept(def, key);
}, noValueHandler());
}
protected ServiceCallServiceFilterConfiguration doParseServiceCallServiceFilterConfiguration() throws IOException, XmlPullParserException {
return doParse(new ServiceCallServiceFilterConfiguration(),
identifiedTypeAttributeHandler(), serviceCallConfigurationElementHandler(), noValueHandler());
}
protected <T extends ServiceCallConfiguration> ElementHandler<T> serviceCallConfigurationElementHandler() {
return (def, key) -> {
if ("properties".equals(key)) {
doAdd(doParsePropertyDefinition(), def.getProperties(), def::setProperties);
return true;
}
return false;
};
}
protected CachingServiceCallServiceDiscoveryConfiguration doParseCachingServiceCallServiceDiscoveryConfiguration() throws IOException, XmlPullParserException {
return doParse(new CachingServiceCallServiceDiscoveryConfiguration(), (def, key, val) -> {
switch (key) {
case "timeout": def.setTimeout(val); break;
case "units": def.setUnits(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, (def, key) -> {
switch (key) {
case "consulServiceDiscovery": def.setServiceDiscoveryConfiguration(doParseConsulServiceCallServiceDiscoveryConfiguration()); break;
case "dnsServiceDiscovery": def.setServiceDiscoveryConfiguration(doParseDnsServiceCallServiceDiscoveryConfiguration()); break;
case "etcdServiceDiscovery": def.setServiceDiscoveryConfiguration(doParseEtcdServiceCallServiceDiscoveryConfiguration()); break;
case "kubernetesServiceDiscovery": def.setServiceDiscoveryConfiguration(doParseKubernetesServiceCallServiceDiscoveryConfiguration()); break;
case "combinedServiceDiscovery": def.setServiceDiscoveryConfiguration(doParseCombinedServiceCallServiceDiscoveryConfiguration()); break;
case "staticServiceDiscovery": def.setServiceDiscoveryConfiguration(doParseStaticServiceCallServiceDiscoveryConfiguration()); break;
default: return serviceCallConfigurationElementHandler().accept(def, key);
}
return true;
}, noValueHandler());
}
protected ServiceCallServiceDiscoveryConfiguration doParseServiceCallServiceDiscoveryConfiguration() throws IOException, XmlPullParserException {
return doParse(new ServiceCallServiceDiscoveryConfiguration(),
identifiedTypeAttributeHandler(), serviceCallConfigurationElementHandler(), noValueHandler());
}
protected CombinedServiceCallServiceDiscoveryConfiguration doParseCombinedServiceCallServiceDiscoveryConfiguration() throws IOException, XmlPullParserException {
return doParse(new CombinedServiceCallServiceDiscoveryConfiguration(),
identifiedTypeAttributeHandler(), (def, key) -> {
switch (key) {
case "consulServiceDiscovery": doAdd(doParseConsulServiceCallServiceDiscoveryConfiguration(), def.getServiceDiscoveryConfigurations(), def::setServiceDiscoveryConfigurations); break;
case "dnsServiceDiscovery": doAdd(doParseDnsServiceCallServiceDiscoveryConfiguration(), def.getServiceDiscoveryConfigurations(), def::setServiceDiscoveryConfigurations); break;
case "etcdServiceDiscovery": doAdd(doParseEtcdServiceCallServiceDiscoveryConfiguration(), def.getServiceDiscoveryConfigurations(), def::setServiceDiscoveryConfigurations); break;
case "kubernetesServiceDiscovery": doAdd(doParseKubernetesServiceCallServiceDiscoveryConfiguration(), def.getServiceDiscoveryConfigurations(), def::setServiceDiscoveryConfigurations); break;
case "staticServiceDiscovery": doAdd(doParseStaticServiceCallServiceDiscoveryConfiguration(), def.getServiceDiscoveryConfigurations(), def::setServiceDiscoveryConfigurations); break;
case "cachingServiceDiscovery": doAdd(doParseCachingServiceCallServiceDiscoveryConfiguration(), def.getServiceDiscoveryConfigurations(), def::setServiceDiscoveryConfigurations); break;
default: return serviceCallConfigurationElementHandler().accept(def, key);
}
return true;
}, noValueHandler());
}
protected CombinedServiceCallServiceFilterConfiguration doParseCombinedServiceCallServiceFilterConfiguration() throws IOException, XmlPullParserException {
return doParse(new CombinedServiceCallServiceFilterConfiguration(),
identifiedTypeAttributeHandler(), (def, key) -> {
switch (key) {
case "blacklistServiceFilter": doAdd(doParseBlacklistServiceCallServiceFilterConfiguration(), def.getServiceFilterConfigurations(), def::setServiceFilterConfigurations); break;
case "customServiceFilter": doAdd(doParseCustomServiceCallServiceFilterConfiguration(), def.getServiceFilterConfigurations(), def::setServiceFilterConfigurations); break;
case "healthyServiceFilter": doAdd(doParseHealthyServiceCallServiceFilterConfiguration(), def.getServiceFilterConfigurations(), def::setServiceFilterConfigurations); break;
case "passThroughServiceFilter": doAdd(doParsePassThroughServiceCallServiceFilterConfiguration(), def.getServiceFilterConfigurations(), def::setServiceFilterConfigurations); break;
default: return serviceCallConfigurationElementHandler().accept(def, key);
}
return true;
}, noValueHandler());
}
protected ConsulServiceCallServiceDiscoveryConfiguration doParseConsulServiceCallServiceDiscoveryConfiguration() throws IOException, XmlPullParserException {
return doParse(new ConsulServiceCallServiceDiscoveryConfiguration(), (def, key, val) -> {
switch (key) {
case "aclToken": def.setAclToken(val); break;
case "blockSeconds": def.setBlockSeconds(val); break;
case "connectTimeoutMillis": def.setConnectTimeoutMillis(val); break;
case "datacenter": def.setDatacenter(val); break;
case "password": def.setPassword(val); break;
case "readTimeoutMillis": def.setReadTimeoutMillis(val); break;
case "url": def.setUrl(val); break;
case "userName": def.setUserName(val); break;
case "writeTimeoutMillis": def.setWriteTimeoutMillis(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, serviceCallConfigurationElementHandler(), noValueHandler());
}
protected CustomServiceCallServiceFilterConfiguration doParseCustomServiceCallServiceFilterConfiguration() throws IOException, XmlPullParserException {
return doParse(new CustomServiceCallServiceFilterConfiguration(), (def, key, val) -> {
if ("ref".equals(key)) {
def.setServiceFilterRef(val);
return true;
}
return identifiedTypeAttributeHandler().accept(def, key, val);
}, serviceCallConfigurationElementHandler(), noValueHandler());
}
protected DefaultServiceCallServiceLoadBalancerConfiguration doParseDefaultServiceCallServiceLoadBalancerConfiguration() throws IOException, XmlPullParserException {
return doParse(new DefaultServiceCallServiceLoadBalancerConfiguration(),
identifiedTypeAttributeHandler(), serviceCallConfigurationElementHandler(), noValueHandler());
}
protected ServiceCallServiceLoadBalancerConfiguration doParseServiceCallServiceLoadBalancerConfiguration() throws IOException, XmlPullParserException {
return doParse(new ServiceCallServiceLoadBalancerConfiguration(),
identifiedTypeAttributeHandler(), serviceCallConfigurationElementHandler(), noValueHandler());
}
protected DnsServiceCallServiceDiscoveryConfiguration doParseDnsServiceCallServiceDiscoveryConfiguration() throws IOException, XmlPullParserException {
return doParse(new DnsServiceCallServiceDiscoveryConfiguration(), (def, key, val) -> {
switch (key) {
case "domain": def.setDomain(val); break;
case "proto": def.setProto(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, serviceCallConfigurationElementHandler(), noValueHandler());
}
protected EtcdServiceCallServiceDiscoveryConfiguration doParseEtcdServiceCallServiceDiscoveryConfiguration() throws IOException, XmlPullParserException {
return doParse(new EtcdServiceCallServiceDiscoveryConfiguration(), (def, key, val) -> {
switch (key) {
case "password": def.setPassword(val); break;
case "servicePath": def.setServicePath(val); break;
case "timeout": def.setTimeout(val); break;
case "type": def.setType(val); break;
case "uris": def.setUris(val); break;
case "userName": def.setUserName(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, serviceCallConfigurationElementHandler(), noValueHandler());
}
protected HealthyServiceCallServiceFilterConfiguration doParseHealthyServiceCallServiceFilterConfiguration() throws IOException, XmlPullParserException {
return doParse(new HealthyServiceCallServiceFilterConfiguration(),
identifiedTypeAttributeHandler(), serviceCallConfigurationElementHandler(), noValueHandler());
}
protected KubernetesServiceCallServiceDiscoveryConfiguration doParseKubernetesServiceCallServiceDiscoveryConfiguration() throws IOException, XmlPullParserException {
return doParse(new KubernetesServiceCallServiceDiscoveryConfiguration(), (def, key, val) -> {
switch (key) {
case "apiVersion": def.setApiVersion(val); break;
case "caCertData": def.setCaCertData(val); break;
case "caCertFile": def.setCaCertFile(val); break;
case "clientCertData": def.setClientCertData(val); break;
case "clientCertFile": def.setClientCertFile(val); break;
case "clientKeyAlgo": def.setClientKeyAlgo(val); break;
case "clientKeyData": def.setClientKeyData(val); break;
case "clientKeyFile": def.setClientKeyFile(val); break;
case "clientKeyPassphrase": def.setClientKeyPassphrase(val); break;
case "dnsDomain": def.setDnsDomain(val); break;
case "lookup": def.setLookup(val); break;
case "masterUrl": def.setMasterUrl(val); break;
case "namespace": def.setNamespace(val); break;
case "oauthToken": def.setOauthToken(val); break;
case "password": def.setPassword(val); break;
case "portName": def.setPortName(val); break;
case "portProtocol": def.setPortProtocol(val); break;
case "trustCerts": def.setTrustCerts(val); break;
case "username": def.setUsername(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, serviceCallConfigurationElementHandler(), noValueHandler());
}
protected PassThroughServiceCallServiceFilterConfiguration doParsePassThroughServiceCallServiceFilterConfiguration() throws IOException, XmlPullParserException {
return doParse(new PassThroughServiceCallServiceFilterConfiguration(),
identifiedTypeAttributeHandler(), serviceCallConfigurationElementHandler(), noValueHandler());
}
protected RibbonServiceCallServiceLoadBalancerConfiguration doParseRibbonServiceCallServiceLoadBalancerConfiguration() throws IOException, XmlPullParserException {
return doParse(new RibbonServiceCallServiceLoadBalancerConfiguration(), (def, key, val) -> {
switch (key) {
case "clientName": def.setClientName(val); break;
case "namespace": def.setNamespace(val); break;
case "password": def.setPassword(val); break;
case "username": def.setUsername(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, serviceCallConfigurationElementHandler(), noValueHandler());
}
protected ServiceCallConfigurationDefinition doParseServiceCallConfigurationDefinition() throws IOException, XmlPullParserException {
return doParse(new ServiceCallConfigurationDefinition(), (def, key, val) -> {
switch (key) {
case "component": def.setComponent(val); break;
case "expressionRef": def.setExpressionRef(val); break;
case "loadBalancerRef": def.setLoadBalancerRef(val); break;
case "pattern": def.setPattern(val); break;
case "serviceChooserRef": def.setServiceChooserRef(val); break;
case "serviceDiscoveryRef": def.setServiceDiscoveryRef(val); break;
case "serviceFilterRef": def.setServiceFilterRef(val); break;
case "uri": def.setUri(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, (def, key) -> {
switch (key) {
case "ribbonLoadBalancer": def.setLoadBalancerConfiguration(doParseRibbonServiceCallServiceLoadBalancerConfiguration()); break;
case "defaultLoadBalancer": def.setLoadBalancerConfiguration(doParseDefaultServiceCallServiceLoadBalancerConfiguration()); break;
case "cachingServiceDiscovery": def.setServiceDiscoveryConfiguration(doParseCachingServiceCallServiceDiscoveryConfiguration()); break;
case "combinedServiceDiscovery": def.setServiceDiscoveryConfiguration(doParseCombinedServiceCallServiceDiscoveryConfiguration()); break;
case "consulServiceDiscovery": def.setServiceDiscoveryConfiguration(doParseConsulServiceCallServiceDiscoveryConfiguration()); break;
case "dnsServiceDiscovery": def.setServiceDiscoveryConfiguration(doParseDnsServiceCallServiceDiscoveryConfiguration()); break;
case "etcdServiceDiscovery": def.setServiceDiscoveryConfiguration(doParseEtcdServiceCallServiceDiscoveryConfiguration()); break;
case "kubernetesServiceDiscovery": def.setServiceDiscoveryConfiguration(doParseKubernetesServiceCallServiceDiscoveryConfiguration()); break;
case "staticServiceDiscovery": def.setServiceDiscoveryConfiguration(doParseStaticServiceCallServiceDiscoveryConfiguration()); break;
case "zookeeperServiceDiscovery": def.setServiceDiscoveryConfiguration(doParseZooKeeperServiceCallServiceDiscoveryConfiguration()); break;
case "blacklistServiceFilter": def.setServiceFilterConfiguration(doParseBlacklistServiceCallServiceFilterConfiguration()); break;
case "combinedServiceFilter": def.setServiceFilterConfiguration(doParseCombinedServiceCallServiceFilterConfiguration()); break;
case "customServiceFilter": def.setServiceFilterConfiguration(doParseCustomServiceCallServiceFilterConfiguration()); break;
case "healthyServiceFilter": def.setServiceFilterConfiguration(doParseHealthyServiceCallServiceFilterConfiguration()); break;
case "passThroughServiceFilter": def.setServiceFilterConfiguration(doParsePassThroughServiceCallServiceFilterConfiguration()); break;
case "expression": def.setExpressionConfiguration(doParseServiceCallExpressionConfiguration()); break;
default: return false;
}
return true;
}, noValueHandler());
}
protected ServiceCallExpressionConfiguration doParseServiceCallExpressionConfiguration() throws IOException, XmlPullParserException {
return doParse(new ServiceCallExpressionConfiguration(), (def, key, val) -> {
switch (key) {
case "hostHeader": def.setHostHeader(val); break;
case "portHeader": def.setPortHeader(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, (def, key) -> {
ExpressionDefinition v = doParseExpressionDefinitionRef(key);
if (v != null) {
def.setExpressionType(v);
return true;
}
return serviceCallConfigurationElementHandler().accept(def, key);
}, noValueHandler());
}
protected ServiceCallDefinition doParseServiceCallDefinition() throws IOException, XmlPullParserException {
return doParse(new ServiceCallDefinition(), (def, key, val) -> {
switch (key) {
case "component": def.setComponent(val); break;
case "configurationRef": def.setConfigurationRef(val); break;
case "expressionRef": def.setExpressionRef(val); break;
case "loadBalancerRef": def.setLoadBalancerRef(val); break;
case "name": def.setName(val); break;
case "pattern": def.setPattern(val); break;
case "serviceChooserRef": def.setServiceChooserRef(val); break;
case "serviceDiscoveryRef": def.setServiceDiscoveryRef(val); break;
case "serviceFilterRef": def.setServiceFilterRef(val); break;
case "uri": def.setUri(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, (def, key) -> {
switch (key) {
case "ribbonLoadBalancer": def.setLoadBalancerConfiguration(doParseRibbonServiceCallServiceLoadBalancerConfiguration()); break;
case "defaultLoadBalancer": def.setLoadBalancerConfiguration(doParseDefaultServiceCallServiceLoadBalancerConfiguration()); break;
case "cachingServiceDiscovery": def.setServiceDiscoveryConfiguration(doParseCachingServiceCallServiceDiscoveryConfiguration()); break;
case "combinedServiceDiscovery": def.setServiceDiscoveryConfiguration(doParseCombinedServiceCallServiceDiscoveryConfiguration()); break;
case "consulServiceDiscovery": def.setServiceDiscoveryConfiguration(doParseConsulServiceCallServiceDiscoveryConfiguration()); break;
case "dnsServiceDiscovery": def.setServiceDiscoveryConfiguration(doParseDnsServiceCallServiceDiscoveryConfiguration()); break;
case "etcdServiceDiscovery": def.setServiceDiscoveryConfiguration(doParseEtcdServiceCallServiceDiscoveryConfiguration()); break;
case "kubernetesServiceDiscovery": def.setServiceDiscoveryConfiguration(doParseKubernetesServiceCallServiceDiscoveryConfiguration()); break;
case "staticServiceDiscovery": def.setServiceDiscoveryConfiguration(doParseStaticServiceCallServiceDiscoveryConfiguration()); break;
case "zookeeperServiceDiscovery": def.setServiceDiscoveryConfiguration(doParseZooKeeperServiceCallServiceDiscoveryConfiguration()); break;
case "blacklistServiceFilter": def.setServiceFilterConfiguration(doParseBlacklistServiceCallServiceFilterConfiguration()); break;
case "combinedServiceFilter": def.setServiceFilterConfiguration(doParseCombinedServiceCallServiceFilterConfiguration()); break;
case "customServiceFilter": def.setServiceFilterConfiguration(doParseCustomServiceCallServiceFilterConfiguration()); break;
case "healthyServiceFilter": def.setServiceFilterConfiguration(doParseHealthyServiceCallServiceFilterConfiguration()); break;
case "passThroughServiceFilter": def.setServiceFilterConfiguration(doParsePassThroughServiceCallServiceFilterConfiguration()); break;
case "expression": def.setExpressionConfiguration(doParseServiceCallExpressionConfiguration()); break;
default: return optionalIdentifiedDefinitionElementHandler().accept(def, key);
}
return true;
}, noValueHandler());
}
protected ServiceCallServiceChooserConfiguration doParseServiceCallServiceChooserConfiguration() throws IOException, XmlPullParserException {
return doParse(new ServiceCallServiceChooserConfiguration(),
identifiedTypeAttributeHandler(), serviceCallConfigurationElementHandler(), noValueHandler());
}
protected StaticServiceCallServiceDiscoveryConfiguration doParseStaticServiceCallServiceDiscoveryConfiguration() throws IOException, XmlPullParserException {
return doParse(new StaticServiceCallServiceDiscoveryConfiguration(),
identifiedTypeAttributeHandler(), (def, key) -> {
if ("servers".equals(key)) {
doAdd(doParseText(), def.getServers(), def::setServers);
return true;
}
return serviceCallConfigurationElementHandler().accept(def, key);
}, noValueHandler());
}
protected ZooKeeperServiceCallServiceDiscoveryConfiguration doParseZooKeeperServiceCallServiceDiscoveryConfiguration() throws IOException, XmlPullParserException {
return doParse(new ZooKeeperServiceCallServiceDiscoveryConfiguration(), (def, key, val) -> {
switch (key) {
case "basePath": def.setBasePath(val); break;
case "connectionTimeout": def.setConnectionTimeout(val); break;
case "namespace": def.setNamespace(val); break;
case "nodes": def.setNodes(val); break;
case "reconnectBaseSleepTime": def.setReconnectBaseSleepTime(val); break;
case "reconnectMaxRetries": def.setReconnectMaxRetries(val); break;
case "reconnectMaxSleepTime": def.setReconnectMaxSleepTime(val); break;
case "sessionTimeout": def.setSessionTimeout(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, serviceCallConfigurationElementHandler(), noValueHandler());
}
protected BatchResequencerConfig doParseBatchResequencerConfig() throws IOException, XmlPullParserException {
return doParse(new BatchResequencerConfig(), (def, key, val) -> {
switch (key) {
case "allowDuplicates": def.setAllowDuplicates(val); break;
case "batchSize": def.setBatchSize(val); break;
case "batchTimeout": def.setBatchTimeout(val); break;
case "ignoreInvalidExchanges": def.setIgnoreInvalidExchanges(val); break;
case "reverse": def.setReverse(val); break;
default: return false;
}
return true;
}, noElementHandler(), noValueHandler());
}
protected StreamResequencerConfig doParseStreamResequencerConfig() throws IOException, XmlPullParserException {
return doParse(new StreamResequencerConfig(), (def, key, val) -> {
switch (key) {
case "capacity": def.setCapacity(val); break;
case "comparatorRef": def.setComparatorRef(val); break;
case "deliveryAttemptInterval": def.setDeliveryAttemptInterval(val); break;
case "ignoreInvalidExchanges": def.setIgnoreInvalidExchanges(val); break;
case "rejectOld": def.setRejectOld(val); break;
case "timeout": def.setTimeout(val); break;
default: return false;
}
return true;
}, noElementHandler(), noValueHandler());
}
protected ASN1DataFormat doParseASN1DataFormat() throws IOException, XmlPullParserException {
return doParse(new ASN1DataFormat(), (def, key, val) -> {
switch (key) {
case "unmarshalType": def.setUnmarshalTypeName(val); break;
case "usingIterator": def.setUsingIterator(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected Any23DataFormat doParseAny23DataFormat() throws IOException, XmlPullParserException {
return doParse(new Any23DataFormat(), (def, key, val) -> {
switch (key) {
case "baseUri": def.setBaseUri(val); break;
case "outputFormat": def.setOutputFormat(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, (def, key) -> {
switch (key) {
case "configuration": doAdd(doParsePropertyDefinition(), def.getConfiguration(), def::setConfiguration); break;
case "extractors": doAdd(doParseText(), def.getExtractors(), def::setExtractors); break;
default: return false;
}
return true;
}, noValueHandler());
}
protected AvroDataFormat doParseAvroDataFormat() throws IOException, XmlPullParserException {
return doParse(new AvroDataFormat(), (def, key, val) -> {
switch (key) {
case "allowJmsType": def.setAllowJmsType(val); break;
case "allowUnmarshallType": def.setAllowUnmarshallType(val); break;
case "autoDiscoverObjectMapper": def.setAutoDiscoverObjectMapper(val); break;
case "autoDiscoverSchemaResolver": def.setAutoDiscoverSchemaResolver(val); break;
case "collectionType": def.setCollectionTypeName(val); break;
case "contentTypeHeader": def.setContentTypeHeader(val); break;
case "disableFeatures": def.setDisableFeatures(val); break;
case "enableFeatures": def.setEnableFeatures(val); break;
case "include": def.setInclude(val); break;
case "instanceClassName": def.setInstanceClassName(val); break;
case "jsonView": def.setJsonViewTypeName(val); break;
case "library": def.setLibrary(AvroLibrary.valueOf(val)); break;
case "moduleClassNames": def.setModuleClassNames(val); break;
case "moduleRefs": def.setModuleRefs(val); break;
case "objectMapper": def.setObjectMapper(val); break;
case "schemaResolver": def.setSchemaResolver(val); break;
case "timezone": def.setTimezone(val); break;
case "unmarshalType": def.setUnmarshalTypeName(val); break;
case "useDefaultObjectMapper": def.setUseDefaultObjectMapper(val); break;
case "useList": def.setUseList(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected BarcodeDataFormat doParseBarcodeDataFormat() throws IOException, XmlPullParserException {
return doParse(new BarcodeDataFormat(), (def, key, val) -> {
switch (key) {
case "barcodeFormat": def.setBarcodeFormat(val); break;
case "height": def.setHeight(val); break;
case "imageType": def.setImageType(val); break;
case "width": def.setWidth(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected Base64DataFormat doParseBase64DataFormat() throws IOException, XmlPullParserException {
return doParse(new Base64DataFormat(), (def, key, val) -> {
switch (key) {
case "lineLength": def.setLineLength(val); break;
case "lineSeparator": def.setLineSeparator(val); break;
case "urlSafe": def.setUrlSafe(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected BeanioDataFormat doParseBeanioDataFormat() throws IOException, XmlPullParserException {
return doParse(new BeanioDataFormat(), (def, key, val) -> {
switch (key) {
case "beanReaderErrorHandlerType": def.setBeanReaderErrorHandlerType(val); break;
case "encoding": def.setEncoding(val); break;
case "ignoreInvalidRecords": def.setIgnoreInvalidRecords(val); break;
case "ignoreUnexpectedRecords": def.setIgnoreUnexpectedRecords(val); break;
case "ignoreUnidentifiedRecords": def.setIgnoreUnidentifiedRecords(val); break;
case "mapping": def.setMapping(val); break;
case "streamName": def.setStreamName(val); break;
case "unmarshalSingleObject": def.setUnmarshalSingleObject(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected BindyDataFormat doParseBindyDataFormat() throws IOException, XmlPullParserException {
return doParse(new BindyDataFormat(), (def, key, val) -> {
switch (key) {
case "allowEmptyStream": def.setAllowEmptyStream(val); break;
case "classType": def.setClassType(val); break;
case "locale": def.setLocale(val); break;
case "type": def.setType(val); break;
case "unwrapSingleInstance": def.setUnwrapSingleInstance(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected CBORDataFormat doParseCBORDataFormat() throws IOException, XmlPullParserException {
return doParse(new CBORDataFormat(), (def, key, val) -> {
switch (key) {
case "allowJmsType": def.setAllowJmsType(val); break;
case "allowUnmarshallType": def.setAllowUnmarshallType(val); break;
case "collectionType": def.setCollectionTypeName(val); break;
case "disableFeatures": def.setDisableFeatures(val); break;
case "enableFeatures": def.setEnableFeatures(val); break;
case "objectMapper": def.setObjectMapper(val); break;
case "prettyPrint": def.setPrettyPrint(val); break;
case "unmarshalType": def.setUnmarshalTypeName(val); break;
case "useDefaultObjectMapper": def.setUseDefaultObjectMapper(val); break;
case "useList": def.setUseList(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected CryptoDataFormat doParseCryptoDataFormat() throws IOException, XmlPullParserException {
return doParse(new CryptoDataFormat(), (def, key, val) -> {
switch (key) {
case "algorithm": def.setAlgorithm(val); break;
case "algorithmParameterRef": def.setAlgorithmParameterRef(val); break;
case "buffersize": def.setBuffersize(val); break;
case "cryptoProvider": def.setCryptoProvider(val); break;
case "initVectorRef": def.setInitVectorRef(val); break;
case "inline": def.setInline(val); break;
case "keyRef": def.setKeyRef(val); break;
case "macAlgorithm": def.setMacAlgorithm(val); break;
case "shouldAppendHMAC": def.setShouldAppendHMAC(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected CsvDataFormat doParseCsvDataFormat() throws IOException, XmlPullParserException {
return doParse(new CsvDataFormat(), (def, key, val) -> {
switch (key) {
case "allowMissingColumnNames": def.setAllowMissingColumnNames(val); break;
case "captureHeaderRecord": def.setCaptureHeaderRecord(val); break;
case "commentMarker": def.setCommentMarker(val); break;
case "commentMarkerDisabled": def.setCommentMarkerDisabled(val); break;
case "delimiter": def.setDelimiter(val); break;
case "escape": def.setEscape(val); break;
case "escapeDisabled": def.setEscapeDisabled(val); break;
case "formatName": def.setFormatName(val); break;
case "formatRef": def.setFormatRef(val); break;
case "headerDisabled": def.setHeaderDisabled(val); break;
case "ignoreEmptyLines": def.setIgnoreEmptyLines(val); break;
case "ignoreHeaderCase": def.setIgnoreHeaderCase(val); break;
case "ignoreSurroundingSpaces": def.setIgnoreSurroundingSpaces(val); break;
case "lazyLoad": def.setLazyLoad(val); break;
case "marshallerFactoryRef": def.setMarshallerFactoryRef(val); break;
case "nullString": def.setNullString(val); break;
case "nullStringDisabled": def.setNullStringDisabled(val); break;
case "quote": def.setQuote(val); break;
case "quoteDisabled": def.setQuoteDisabled(val); break;
case "quoteMode": def.setQuoteMode(val); break;
case "recordConverterRef": def.setRecordConverterRef(val); break;
case "recordSeparator": def.setRecordSeparator(val); break;
case "recordSeparatorDisabled": def.setRecordSeparatorDisabled(val); break;
case "skipHeaderRecord": def.setSkipHeaderRecord(val); break;
case "trailingDelimiter": def.setTrailingDelimiter(val); break;
case "trim": def.setTrim(val); break;
case "useMaps": def.setUseMaps(val); break;
case "useOrderedMaps": def.setUseOrderedMaps(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, (def, key) -> {
if ("header".equals(key)) {
doAdd(doParseText(), def.getHeader(), def::setHeader);
return true;
}
return false;
}, noValueHandler());
}
protected CustomDataFormat doParseCustomDataFormat() throws IOException, XmlPullParserException {
return doParse(new CustomDataFormat(), (def, key, val) -> {
if ("ref".equals(key)) {
def.setRef(val);
return true;
}
return identifiedTypeAttributeHandler().accept(def, key, val);
}, noElementHandler(), noValueHandler());
}
protected DataFormatsDefinition doParseDataFormatsDefinition() throws IOException, XmlPullParserException {
return doParse(new DataFormatsDefinition(),
noAttributeHandler(), (def, key) -> {
DataFormatDefinition v = doParseDataFormatDefinitionRef(key);
if (v != null) {
doAdd(v, def.getDataFormats(), def::setDataFormats);
return true;
}
return false;
}, noValueHandler());
}
protected FhirJsonDataFormat doParseFhirJsonDataFormat() throws IOException, XmlPullParserException {
return doParse(new FhirJsonDataFormat(),
fhirDataformatAttributeHandler(), noElementHandler(), noValueHandler());
}
protected <T extends FhirDataformat> AttributeHandler<T> fhirDataformatAttributeHandler() {
return (def, key, val) -> {
switch (key) {
case "contentTypeHeader": def.setContentTypeHeader(val); break;
case "dontEncodeElements": def.setDontEncodeElements(asStringSet(val)); break;
case "dontStripVersionsFromReferencesAtPaths": def.setDontStripVersionsFromReferencesAtPaths(asStringList(val)); break;
case "encodeElements": def.setEncodeElements(asStringSet(val)); break;
case "encodeElementsAppliesToChildResourcesOnly": def.setEncodeElementsAppliesToChildResourcesOnly(val); break;
case "fhirVersion": def.setFhirVersion(val); break;
case "omitResourceId": def.setOmitResourceId(val); break;
case "overrideResourceIdWithBundleEntryFullUrl": def.setOverrideResourceIdWithBundleEntryFullUrl(val); break;
case "prettyPrint": def.setPrettyPrint(val); break;
case "serverBaseUrl": def.setServerBaseUrl(val); break;
case "stripVersionsFromReferences": def.setStripVersionsFromReferences(val); break;
case "summaryMode": def.setSummaryMode(val); break;
case "suppressNarratives": def.setSuppressNarratives(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
};
}
protected FhirXmlDataFormat doParseFhirXmlDataFormat() throws IOException, XmlPullParserException {
return doParse(new FhirXmlDataFormat(),
fhirDataformatAttributeHandler(), noElementHandler(), noValueHandler());
}
protected FlatpackDataFormat doParseFlatpackDataFormat() throws IOException, XmlPullParserException {
return doParse(new FlatpackDataFormat(), (def, key, val) -> {
switch (key) {
case "allowShortLines": def.setAllowShortLines(val); break;
case "definition": def.setDefinition(val); break;
case "delimiter": def.setDelimiter(val); break;
case "fixed": def.setFixed(val); break;
case "ignoreExtraColumns": def.setIgnoreExtraColumns(val); break;
case "ignoreFirstRecord": def.setIgnoreFirstRecord(val); break;
case "parserFactoryRef": def.setParserFactoryRef(val); break;
case "textQualifier": def.setTextQualifier(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected GrokDataFormat doParseGrokDataFormat() throws IOException, XmlPullParserException {
return doParse(new GrokDataFormat(), (def, key, val) -> {
switch (key) {
case "allowMultipleMatchesPerLine": def.setAllowMultipleMatchesPerLine(val); break;
case "flattened": def.setFlattened(val); break;
case "namedOnly": def.setNamedOnly(val); break;
case "pattern": def.setPattern(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected GzipDeflaterDataFormat doParseGzipDeflaterDataFormat() throws IOException, XmlPullParserException {
return doParse(new GzipDeflaterDataFormat(),
identifiedTypeAttributeHandler(), noElementHandler(), noValueHandler());
}
protected HL7DataFormat doParseHL7DataFormat() throws IOException, XmlPullParserException {
return doParse(new HL7DataFormat(), (def, key, val) -> {
if ("validate".equals(key)) {
def.setValidate(val);
return true;
}
return identifiedTypeAttributeHandler().accept(def, key, val);
}, noElementHandler(), noValueHandler());
}
protected IcalDataFormat doParseIcalDataFormat() throws IOException, XmlPullParserException {
return doParse(new IcalDataFormat(), (def, key, val) -> {
if ("validating".equals(key)) {
def.setValidating(val);
return true;
}
return identifiedTypeAttributeHandler().accept(def, key, val);
}, noElementHandler(), noValueHandler());
}
protected JacksonXMLDataFormat doParseJacksonXMLDataFormat() throws IOException, XmlPullParserException {
return doParse(new JacksonXMLDataFormat(), (def, key, val) -> {
switch (key) {
case "allowJmsType": def.setAllowJmsType(val); break;
case "allowUnmarshallType": def.setAllowUnmarshallType(val); break;
case "collectionType": def.setCollectionTypeName(val); break;
case "contentTypeHeader": def.setContentTypeHeader(val); break;
case "disableFeatures": def.setDisableFeatures(val); break;
case "enableFeatures": def.setEnableFeatures(val); break;
case "enableJaxbAnnotationModule": def.setEnableJaxbAnnotationModule(val); break;
case "include": def.setInclude(val); break;
case "jsonView": def.setJsonViewTypeName(val); break;
case "moduleClassNames": def.setModuleClassNames(val); break;
case "moduleRefs": def.setModuleRefs(val); break;
case "prettyPrint": def.setPrettyPrint(val); break;
case "unmarshalType": def.setUnmarshalTypeName(val); break;
case "useList": def.setUseList(val); break;
case "xmlMapper": def.setXmlMapper(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected JaxbDataFormat doParseJaxbDataFormat() throws IOException, XmlPullParserException {
return doParse(new JaxbDataFormat(), (def, key, val) -> {
switch (key) {
case "contentTypeHeader": def.setContentTypeHeader(val); break;
case "contextPath": def.setContextPath(val); break;
case "contextPathIsClassName": def.setContextPathIsClassName(val); break;
case "encoding": def.setEncoding(val); break;
case "filterNonXmlChars": def.setFilterNonXmlChars(val); break;
case "fragment": def.setFragment(val); break;
case "ignoreJAXBElement": def.setIgnoreJAXBElement(val); break;
case "jaxbProviderProperties": def.setJaxbProviderProperties(val); break;
case "mustBeJAXBElement": def.setMustBeJAXBElement(val); break;
case "namespacePrefixRef": def.setNamespacePrefixRef(val); break;
case "noNamespaceSchemaLocation": def.setNoNamespaceSchemaLocation(val); break;
case "objectFactory": def.setObjectFactory(val); break;
case "partClass": def.setPartClass(val); break;
case "partNamespace": def.setPartNamespace(val); break;
case "prettyPrint": def.setPrettyPrint(val); break;
case "schema": def.setSchema(val); break;
case "schemaLocation": def.setSchemaLocation(val); break;
case "schemaSeverityLevel": def.setSchemaSeverityLevel(val); break;
case "xmlStreamWriterWrapper": def.setXmlStreamWriterWrapper(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected JsonApiDataFormat doParseJsonApiDataFormat() throws IOException, XmlPullParserException {
return doParse(new JsonApiDataFormat(), (def, key, val) -> {
switch (key) {
case "dataFormatTypes": def.setDataFormatTypes(asClassArray(val)); break;
case "mainFormatType": def.setMainFormatType(asClass(val)); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected JsonDataFormat doParseJsonDataFormat() throws IOException, XmlPullParserException {
return doParse(new JsonDataFormat(), (def, key, val) -> {
switch (key) {
case "allowJmsType": def.setAllowJmsType(val); break;
case "allowUnmarshallType": def.setAllowUnmarshallType(val); break;
case "autoDiscoverObjectMapper": def.setAutoDiscoverObjectMapper(val); break;
case "autoDiscoverSchemaResolver": def.setAutoDiscoverSchemaResolver(val); break;
case "collectionType": def.setCollectionTypeName(val); break;
case "contentTypeHeader": def.setContentTypeHeader(val); break;
case "disableFeatures": def.setDisableFeatures(val); break;
case "dropRootNode": def.setDropRootNode(val); break;
case "enableFeatures": def.setEnableFeatures(val); break;
case "include": def.setInclude(val); break;
case "jsonView": def.setJsonViewTypeName(val); break;
case "library": def.setLibrary(JsonLibrary.valueOf(val)); break;
case "moduleClassNames": def.setModuleClassNames(val); break;
case "moduleRefs": def.setModuleRefs(val); break;
case "namingStrategy": def.setNamingStrategy(val); break;
case "objectMapper": def.setObjectMapper(val); break;
case "permissions": def.setPermissions(val); break;
case "prettyPrint": def.setPrettyPrint(val); break;
case "schemaResolver": def.setSchemaResolver(val); break;
case "timezone": def.setTimezone(val); break;
case "unmarshalType": def.setUnmarshalTypeName(val); break;
case "useDefaultObjectMapper": def.setUseDefaultObjectMapper(val); break;
case "useList": def.setUseList(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected LZFDataFormat doParseLZFDataFormat() throws IOException, XmlPullParserException {
return doParse(new LZFDataFormat(), (def, key, val) -> {
if ("usingParallelCompression".equals(key)) {
def.setUsingParallelCompression(val);
return true;
}
return identifiedTypeAttributeHandler().accept(def, key, val);
}, noElementHandler(), noValueHandler());
}
protected MimeMultipartDataFormat doParseMimeMultipartDataFormat() throws IOException, XmlPullParserException {
return doParse(new MimeMultipartDataFormat(), (def, key, val) -> {
switch (key) {
case "binaryContent": def.setBinaryContent(val); break;
case "headersInline": def.setHeadersInline(val); break;
case "includeHeaders": def.setIncludeHeaders(val); break;
case "multipartSubType": def.setMultipartSubType(val); break;
case "multipartWithoutAttachment": def.setMultipartWithoutAttachment(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected PGPDataFormat doParsePGPDataFormat() throws IOException, XmlPullParserException {
return doParse(new PGPDataFormat(), (def, key, val) -> {
switch (key) {
case "algorithm": def.setAlgorithm(val); break;
case "armored": def.setArmored(val); break;
case "compressionAlgorithm": def.setCompressionAlgorithm(val); break;
case "hashAlgorithm": def.setHashAlgorithm(val); break;
case "integrity": def.setIntegrity(val); break;
case "keyFileName": def.setKeyFileName(val); break;
case "keyUserid": def.setKeyUserid(val); break;
case "password": def.setPassword(val); break;
case "provider": def.setProvider(val); break;
case "signatureKeyFileName": def.setSignatureKeyFileName(val); break;
case "signatureKeyRing": def.setSignatureKeyRing(val); break;
case "signatureKeyUserid": def.setSignatureKeyUserid(val); break;
case "signaturePassword": def.setSignaturePassword(val); break;
case "signatureVerificationOption": def.setSignatureVerificationOption(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected ProtobufDataFormat doParseProtobufDataFormat() throws IOException, XmlPullParserException {
return doParse(new ProtobufDataFormat(), (def, key, val) -> {
switch (key) {
case "allowJmsType": def.setAllowJmsType(val); break;
case "allowUnmarshallType": def.setAllowUnmarshallType(val); break;
case "autoDiscoverObjectMapper": def.setAutoDiscoverObjectMapper(val); break;
case "autoDiscoverSchemaResolver": def.setAutoDiscoverSchemaResolver(val); break;
case "collectionType": def.setCollectionTypeName(val); break;
case "contentTypeFormat": def.setContentTypeFormat(val); break;
case "contentTypeHeader": def.setContentTypeHeader(val); break;
case "disableFeatures": def.setDisableFeatures(val); break;
case "enableFeatures": def.setEnableFeatures(val); break;
case "include": def.setInclude(val); break;
case "instanceClass": def.setInstanceClass(val); break;
case "jsonView": def.setJsonViewTypeName(val); break;
case "library": def.setLibrary(ProtobufLibrary.valueOf(val)); break;
case "moduleClassNames": def.setModuleClassNames(val); break;
case "moduleRefs": def.setModuleRefs(val); break;
case "objectMapper": def.setObjectMapper(val); break;
case "schemaResolver": def.setSchemaResolver(val); break;
case "timezone": def.setTimezone(val); break;
case "unmarshalType": def.setUnmarshalTypeName(val); break;
case "useDefaultObjectMapper": def.setUseDefaultObjectMapper(val); break;
case "useList": def.setUseList(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected RssDataFormat doParseRssDataFormat() throws IOException, XmlPullParserException {
return doParse(new RssDataFormat(),
identifiedTypeAttributeHandler(), noElementHandler(), noValueHandler());
}
protected SoapDataFormat doParseSoapDataFormat() throws IOException, XmlPullParserException {
return doParse(new SoapDataFormat(), (def, key, val) -> {
switch (key) {
case "contextPath": def.setContextPath(val); break;
case "elementNameStrategyRef": def.setElementNameStrategyRef(val); break;
case "encoding": def.setEncoding(val); break;
case "namespacePrefixRef": def.setNamespacePrefixRef(val); break;
case "schema": def.setSchema(val); break;
case "version": def.setVersion(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected SyslogDataFormat doParseSyslogDataFormat() throws IOException, XmlPullParserException {
return doParse(new SyslogDataFormat(),
identifiedTypeAttributeHandler(), noElementHandler(), noValueHandler());
}
protected TarFileDataFormat doParseTarFileDataFormat() throws IOException, XmlPullParserException {
return doParse(new TarFileDataFormat(), (def, key, val) -> {
switch (key) {
case "allowEmptyDirectory": def.setAllowEmptyDirectory(val); break;
case "maxDecompressedSize": def.setMaxDecompressedSize(val); break;
case "preservePathElements": def.setPreservePathElements(val); break;
case "usingIterator": def.setUsingIterator(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected ThriftDataFormat doParseThriftDataFormat() throws IOException, XmlPullParserException {
return doParse(new ThriftDataFormat(), (def, key, val) -> {
switch (key) {
case "contentTypeFormat": def.setContentTypeFormat(val); break;
case "contentTypeHeader": def.setContentTypeHeader(val); break;
case "instanceClass": def.setInstanceClass(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected TidyMarkupDataFormat doParseTidyMarkupDataFormat() throws IOException, XmlPullParserException {
return doParse(new TidyMarkupDataFormat(), (def, key, val) -> {
switch (key) {
case "dataObjectType": def.setDataObjectTypeName(val); break;
case "omitXmlDeclaration": def.setOmitXmlDeclaration(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected UniVocityCsvDataFormat doParseUniVocityCsvDataFormat() throws IOException, XmlPullParserException {
return doParse(new UniVocityCsvDataFormat(), (def, key, val) -> {
switch (key) {
case "delimiter": def.setDelimiter(val); break;
case "quote": def.setQuote(val); break;
case "quoteAllFields": def.setQuoteAllFields(val); break;
case "quoteEscape": def.setQuoteEscape(val); break;
default: return uniVocityAbstractDataFormatAttributeHandler().accept(def, key, val);
}
return true;
}, uniVocityAbstractDataFormatElementHandler(), noValueHandler());
}
protected <T extends UniVocityAbstractDataFormat> AttributeHandler<T> uniVocityAbstractDataFormatAttributeHandler() {
return (def, key, val) -> {
switch (key) {
case "asMap": def.setAsMap(val); break;
case "comment": def.setComment(val); break;
case "emptyValue": def.setEmptyValue(val); break;
case "headerExtractionEnabled": def.setHeaderExtractionEnabled(val); break;
case "headersDisabled": def.setHeadersDisabled(val); break;
case "ignoreLeadingWhitespaces": def.setIgnoreLeadingWhitespaces(val); break;
case "ignoreTrailingWhitespaces": def.setIgnoreTrailingWhitespaces(val); break;
case "lazyLoad": def.setLazyLoad(val); break;
case "lineSeparator": def.setLineSeparator(val); break;
case "normalizedLineSeparator": def.setNormalizedLineSeparator(val); break;
case "nullValue": def.setNullValue(val); break;
case "numberOfRecordsToRead": def.setNumberOfRecordsToRead(val); break;
case "skipEmptyLines": def.setSkipEmptyLines(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
};
}
protected <T extends UniVocityAbstractDataFormat> ElementHandler<T> uniVocityAbstractDataFormatElementHandler() {
return (def, key) -> {
if ("univocityHeader".equals(key)) {
doAdd(doParseUniVocityHeader(), def.getHeaders(), def::setHeaders);
return true;
}
return false;
};
}
protected UniVocityHeader doParseUniVocityHeader() throws IOException, XmlPullParserException {
return doParse(new UniVocityHeader(), (def, key, val) -> {
if ("length".equals(key)) {
def.setLength(val);
return true;
}
return false;
}, noElementHandler(), (def, val) -> def.setName(val));
}
protected UniVocityFixedDataFormat doParseUniVocityFixedDataFormat() throws IOException, XmlPullParserException {
return doParse(new UniVocityFixedDataFormat(), (def, key, val) -> {
switch (key) {
case "padding": def.setPadding(val); break;
case "recordEndsOnNewline": def.setRecordEndsOnNewline(val); break;
case "skipTrailingCharsUntilNewline": def.setSkipTrailingCharsUntilNewline(val); break;
default: return uniVocityAbstractDataFormatAttributeHandler().accept(def, key, val);
}
return true;
}, uniVocityAbstractDataFormatElementHandler(), noValueHandler());
}
protected UniVocityTsvDataFormat doParseUniVocityTsvDataFormat() throws IOException, XmlPullParserException {
return doParse(new UniVocityTsvDataFormat(), (def, key, val) -> {
if ("escapeChar".equals(key)) {
def.setEscapeChar(val);
return true;
}
return uniVocityAbstractDataFormatAttributeHandler().accept(def, key, val);
}, uniVocityAbstractDataFormatElementHandler(), noValueHandler());
}
protected XMLSecurityDataFormat doParseXMLSecurityDataFormat() throws IOException, XmlPullParserException {
return doParse(new XMLSecurityDataFormat(), (def, key, val) -> {
switch (key) {
case "addKeyValueForEncryptedKey": def.setAddKeyValueForEncryptedKey(val); break;
case "digestAlgorithm": def.setDigestAlgorithm(val); break;
case "keyCipherAlgorithm": def.setKeyCipherAlgorithm(val); break;
case "keyOrTrustStoreParametersRef": def.setKeyOrTrustStoreParametersRef(val); break;
case "keyPassword": def.setKeyPassword(val); break;
case "mgfAlgorithm": def.setMgfAlgorithm(val); break;
case "passPhrase": def.setPassPhrase(val); break;
case "passPhraseByte": def.setPassPhraseByte(asByteArray(val)); break;
case "recipientKeyAlias": def.setRecipientKeyAlias(val); break;
case "secureTag": def.setSecureTag(val); break;
case "secureTagContents": def.setSecureTagContents(val); break;
case "xmlCipherAlgorithm": def.setXmlCipherAlgorithm(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected XStreamDataFormat doParseXStreamDataFormat() throws IOException, XmlPullParserException {
return doParse(new XStreamDataFormat(), (def, key, val) -> {
switch (key) {
case "contentTypeHeader": def.setContentTypeHeader(val); break;
case "driver": def.setDriver(val); break;
case "driverRef": def.setDriverRef(val); break;
case "encoding": def.setEncoding(val); break;
case "mode": def.setMode(val); break;
case "permissions": def.setPermissions(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, (def, key) -> {
switch (key) {
case "aliases": doAdd(doParsePropertyDefinition(), def.getAliases(), def::setAliases); break;
case "converters": doAdd(doParsePropertyDefinition(), def.getConverters(), def::setConverters); break;
case "implicitCollections": doAdd(doParsePropertyDefinition(), def.getImplicitCollections(), def::setImplicitCollections); break;
case "omitFields": doAdd(doParsePropertyDefinition(), def.getOmitFields(), def::setOmitFields); break;
default: return false;
}
return true;
}, noValueHandler());
}
protected YAMLDataFormat doParseYAMLDataFormat() throws IOException, XmlPullParserException {
return doParse(new YAMLDataFormat(), (def, key, val) -> {
switch (key) {
case "allowAnyType": def.setAllowAnyType(val); break;
case "allowRecursiveKeys": def.setAllowRecursiveKeys(val); break;
case "constructor": def.setConstructor(val); break;
case "dumperOptions": def.setDumperOptions(val); break;
case "library": def.setLibrary(YAMLLibrary.valueOf(val)); break;
case "maxAliasesForCollections": def.setMaxAliasesForCollections(val); break;
case "prettyFlow": def.setPrettyFlow(val); break;
case "representer": def.setRepresenter(val); break;
case "resolver": def.setResolver(val); break;
case "unmarshalType": def.setUnmarshalTypeName(val); break;
case "useApplicationContextClassLoader": def.setUseApplicationContextClassLoader(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, (def, key) -> {
if ("typeFilter".equals(key)) {
doAdd(doParseYAMLTypeFilterDefinition(), def.getTypeFilters(), def::setTypeFilters);
return true;
}
return false;
}, noValueHandler());
}
protected YAMLTypeFilterDefinition doParseYAMLTypeFilterDefinition() throws IOException, XmlPullParserException {
return doParse(new YAMLTypeFilterDefinition(), (def, key, val) -> {
switch (key) {
case "type": def.setType(val); break;
case "value": def.setValue(val); break;
default: return false;
}
return true;
}, noElementHandler(), noValueHandler());
}
protected ZipDeflaterDataFormat doParseZipDeflaterDataFormat() throws IOException, XmlPullParserException {
return doParse(new ZipDeflaterDataFormat(), (def, key, val) -> {
if ("compressionLevel".equals(key)) {
def.setCompressionLevel(val);
return true;
}
return identifiedTypeAttributeHandler().accept(def, key, val);
}, noElementHandler(), noValueHandler());
}
protected ZipFileDataFormat doParseZipFileDataFormat() throws IOException, XmlPullParserException {
return doParse(new ZipFileDataFormat(), (def, key, val) -> {
switch (key) {
case "allowEmptyDirectory": def.setAllowEmptyDirectory(val); break;
case "maxDecompressedSize": def.setMaxDecompressedSize(val); break;
case "preservePathElements": def.setPreservePathElements(val); break;
case "usingIterator": def.setUsingIterator(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected CSimpleExpression doParseCSimpleExpression() throws IOException, XmlPullParserException {
return doParse(new CSimpleExpression(), (def, key, val) -> {
if ("resultType".equals(key)) {
def.setResultTypeName(val);
return true;
}
return expressionDefinitionAttributeHandler().accept(def, key, val);
}, noElementHandler(), expressionDefinitionValueHandler());
}
protected ConstantExpression doParseConstantExpression() throws IOException, XmlPullParserException {
return doParse(new ConstantExpression(), (def, key, val) -> {
if ("resultType".equals(key)) {
def.setResultTypeName(val);
return true;
}
return expressionDefinitionAttributeHandler().accept(def, key, val);
}, noElementHandler(), expressionDefinitionValueHandler());
}
protected DatasonnetExpression doParseDatasonnetExpression() throws IOException, XmlPullParserException {
return doParse(new DatasonnetExpression(), (def, key, val) -> {
switch (key) {
case "bodyMediaType": def.setBodyMediaType(val); break;
case "outputMediaType": def.setOutputMediaType(val); break;
case "resultType": def.setResultTypeName(val); break;
default: return expressionDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), expressionDefinitionValueHandler());
}
protected ExchangePropertyExpression doParseExchangePropertyExpression() throws IOException, XmlPullParserException {
return doParse(new ExchangePropertyExpression(),
expressionDefinitionAttributeHandler(), noElementHandler(), expressionDefinitionValueHandler());
}
protected GroovyExpression doParseGroovyExpression() throws IOException, XmlPullParserException {
return doParse(new GroovyExpression(),
expressionDefinitionAttributeHandler(), noElementHandler(), expressionDefinitionValueHandler());
}
protected HeaderExpression doParseHeaderExpression() throws IOException, XmlPullParserException {
return doParse(new HeaderExpression(),
expressionDefinitionAttributeHandler(), noElementHandler(), expressionDefinitionValueHandler());
}
protected Hl7TerserExpression doParseHl7TerserExpression() throws IOException, XmlPullParserException {
return doParse(new Hl7TerserExpression(),
expressionDefinitionAttributeHandler(), noElementHandler(), expressionDefinitionValueHandler());
}
protected JoorExpression doParseJoorExpression() throws IOException, XmlPullParserException {
return doParse(new JoorExpression(), (def, key, val) -> {
switch (key) {
case "preCompile": def.setPreCompile(val); break;
case "resultType": def.setResultTypeName(val); break;
case "singleQuotes": def.setSingleQuotes(val); break;
default: return expressionDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), expressionDefinitionValueHandler());
}
protected JsonPathExpression doParseJsonPathExpression() throws IOException, XmlPullParserException {
return doParse(new JsonPathExpression(), (def, key, val) -> {
switch (key) {
case "allowEasyPredicate": def.setAllowEasyPredicate(val); break;
case "allowSimple": def.setAllowSimple(val); break;
case "headerName": def.setHeaderName(val); break;
case "option": def.setOption(val); break;
case "resultType": def.setResultTypeName(val); break;
case "suppressExceptions": def.setSuppressExceptions(val); break;
case "writeAsString": def.setWriteAsString(val); break;
default: return expressionDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), expressionDefinitionValueHandler());
}
protected LanguageExpression doParseLanguageExpression() throws IOException, XmlPullParserException {
return doParse(new LanguageExpression(), (def, key, val) -> {
if ("language".equals(key)) {
def.setLanguage(val);
return true;
}
return expressionDefinitionAttributeHandler().accept(def, key, val);
}, noElementHandler(), expressionDefinitionValueHandler());
}
protected MethodCallExpression doParseMethodCallExpression() throws IOException, XmlPullParserException {
return doParse(new MethodCallExpression(), (def, key, val) -> {
switch (key) {
case "beanType": def.setBeanTypeName(val); break;
case "method": def.setMethod(val); break;
case "ref": def.setRef(val); break;
case "scope": def.setScope(val); break;
default: return expressionDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), expressionDefinitionValueHandler());
}
protected MvelExpression doParseMvelExpression() throws IOException, XmlPullParserException {
return doParse(new MvelExpression(),
expressionDefinitionAttributeHandler(), noElementHandler(), expressionDefinitionValueHandler());
}
protected OgnlExpression doParseOgnlExpression() throws IOException, XmlPullParserException {
return doParse(new OgnlExpression(),
expressionDefinitionAttributeHandler(), noElementHandler(), expressionDefinitionValueHandler());
}
protected RefExpression doParseRefExpression() throws IOException, XmlPullParserException {
return doParse(new RefExpression(),
expressionDefinitionAttributeHandler(), noElementHandler(), expressionDefinitionValueHandler());
}
protected SimpleExpression doParseSimpleExpression() throws IOException, XmlPullParserException {
return doParse(new SimpleExpression(), (def, key, val) -> {
if ("resultType".equals(key)) {
def.setResultTypeName(val);
return true;
}
return expressionDefinitionAttributeHandler().accept(def, key, val);
}, noElementHandler(), expressionDefinitionValueHandler());
}
protected SpELExpression doParseSpELExpression() throws IOException, XmlPullParserException {
return doParse(new SpELExpression(),
expressionDefinitionAttributeHandler(), noElementHandler(), expressionDefinitionValueHandler());
}
protected TokenizerExpression doParseTokenizerExpression() throws IOException, XmlPullParserException {
return doParse(new TokenizerExpression(), (def, key, val) -> {
switch (key) {
case "endToken": def.setEndToken(val); break;
case "group": def.setGroup(val); break;
case "groupDelimiter": def.setGroupDelimiter(val); break;
case "headerName": def.setHeaderName(val); break;
case "includeTokens": def.setIncludeTokens(val); break;
case "inheritNamespaceTagName": def.setInheritNamespaceTagName(val); break;
case "regex": def.setRegex(val); break;
case "skipFirst": def.setSkipFirst(val); break;
case "token": def.setToken(val); break;
case "xml": def.setXml(val); break;
default: return expressionDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), expressionDefinitionValueHandler());
}
protected XMLTokenizerExpression doParseXMLTokenizerExpression() throws IOException, XmlPullParserException {
return doParse(new XMLTokenizerExpression(), (def, key, val) -> {
switch (key) {
case "group": def.setGroup(val); break;
case "headerName": def.setHeaderName(val); break;
case "mode": def.setMode(val); break;
default: return expressionDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), expressionDefinitionValueHandler());
}
protected XPathExpression doParseXPathExpression() throws IOException, XmlPullParserException {
return doParse(new XPathExpression(), (def, key, val) -> {
switch (key) {
case "documentType": def.setDocumentTypeName(val); break;
case "factoryRef": def.setFactoryRef(val); break;
case "headerName": def.setHeaderName(val); break;
case "logNamespaces": def.setLogNamespaces(val); break;
case "objectModel": def.setObjectModel(val); break;
case "preCompile": def.setPreCompile(val); break;
case "resultType": def.setResultTypeName(val); break;
case "saxon": def.setSaxon(val); break;
case "threadSafety": def.setThreadSafety(val); break;
default: return expressionDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), expressionDefinitionValueHandler());
}
protected XQueryExpression doParseXQueryExpression() throws IOException, XmlPullParserException {
return doParse(new XQueryExpression(), (def, key, val) -> {
switch (key) {
case "configurationRef": def.setConfigurationRef(val); break;
case "headerName": def.setHeaderName(val); break;
case "type": def.setType(val); break;
default: return expressionDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), expressionDefinitionValueHandler());
}
protected CustomLoadBalancerDefinition doParseCustomLoadBalancerDefinition() throws IOException, XmlPullParserException {
return doParse(new CustomLoadBalancerDefinition(), (def, key, val) -> {
if ("ref".equals(key)) {
def.setRef(val);
return true;
}
return identifiedTypeAttributeHandler().accept(def, key, val);
}, noElementHandler(), noValueHandler());
}
protected FailoverLoadBalancerDefinition doParseFailoverLoadBalancerDefinition() throws IOException, XmlPullParserException {
return doParse(new FailoverLoadBalancerDefinition(), (def, key, val) -> {
switch (key) {
case "maximumFailoverAttempts": def.setMaximumFailoverAttempts(val); break;
case "roundRobin": def.setRoundRobin(val); break;
case "sticky": def.setSticky(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, (def, key) -> {
if ("exception".equals(key)) {
doAdd(doParseText(), def.getExceptions(), def::setExceptions);
return true;
}
return false;
}, noValueHandler());
}
protected RandomLoadBalancerDefinition doParseRandomLoadBalancerDefinition() throws IOException, XmlPullParserException {
return doParse(new RandomLoadBalancerDefinition(),
identifiedTypeAttributeHandler(), noElementHandler(), noValueHandler());
}
protected RoundRobinLoadBalancerDefinition doParseRoundRobinLoadBalancerDefinition() throws IOException, XmlPullParserException {
return doParse(new RoundRobinLoadBalancerDefinition(),
identifiedTypeAttributeHandler(), noElementHandler(), noValueHandler());
}
protected StickyLoadBalancerDefinition doParseStickyLoadBalancerDefinition() throws IOException, XmlPullParserException {
return doParse(new StickyLoadBalancerDefinition(),
identifiedTypeAttributeHandler(), (def, key) -> {
if ("correlationExpression".equals(key)) {
def.setCorrelationExpression(doParseExpressionSubElementDefinition());
return true;
}
return false;
}, noValueHandler());
}
protected TopicLoadBalancerDefinition doParseTopicLoadBalancerDefinition() throws IOException, XmlPullParserException {
return doParse(new TopicLoadBalancerDefinition(),
identifiedTypeAttributeHandler(), noElementHandler(), noValueHandler());
}
protected WeightedLoadBalancerDefinition doParseWeightedLoadBalancerDefinition() throws IOException, XmlPullParserException {
return doParse(new WeightedLoadBalancerDefinition(), (def, key, val) -> {
switch (key) {
case "distributionRatio": def.setDistributionRatio(val); break;
case "distributionRatioDelimiter": def.setDistributionRatioDelimiter(val); break;
case "roundRobin": def.setRoundRobin(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected DeleteDefinition doParseDeleteDefinition() throws IOException, XmlPullParserException {
return doParse(new DeleteDefinition(),
verbDefinitionAttributeHandler(), verbDefinitionElementHandler(), noValueHandler());
}
protected <T extends VerbDefinition> AttributeHandler<T> verbDefinitionAttributeHandler() {
return (def, key, val) -> {
switch (key) {
case "apiDocs": def.setApiDocs(val); break;
case "bindingMode": def.setBindingMode(val); break;
case "clientRequestValidation": def.setClientRequestValidation(val); break;
case "consumes": def.setConsumes(val); break;
case "deprecated": def.setDeprecated(Boolean.valueOf(val)); break;
case "enableCORS": def.setEnableCORS(val); break;
case "outType": def.setOutType(val); break;
case "produces": def.setProduces(val); break;
case "routeId": def.setRouteId(val); break;
case "skipBindingOnErrorCode": def.setSkipBindingOnErrorCode(val); break;
case "type": def.setType(val); break;
case "uri": def.setUri(val); break;
default: return optionalIdentifiedDefinitionAttributeHandler().accept(def, key, val);
}
return true;
};
}
protected <T extends VerbDefinition> ElementHandler<T> verbDefinitionElementHandler() {
return (def, key) -> {
switch (key) {
case "param": doAdd(doParseRestOperationParamDefinition(), def.getParams(), def::setParams); break;
case "responseMessage": doAdd(doParseRestOperationResponseMsgDefinition(), def.getResponseMsgs(), def::setResponseMsgs); break;
case "security": doAdd(doParseSecurityDefinition(), def.getSecurity(), def::setSecurity); break;
case "to": def.setToOrRoute(doParseToDefinition()); break;
case "toD": def.setToOrRoute(doParseToDynamicDefinition()); break;
case "route": def.setToOrRoute(doParseRouteDefinition()); break;
default: return optionalIdentifiedDefinitionElementHandler().accept(def, key);
}
return true;
};
}
protected RestOperationParamDefinition doParseRestOperationParamDefinition() throws IOException, XmlPullParserException {
return doParse(new RestOperationParamDefinition(), (def, key, val) -> {
switch (key) {
case "arrayType": def.setArrayType(val); break;
case "collectionFormat": def.setCollectionFormat(CollectionFormat.valueOf(val)); break;
case "dataFormat": def.setDataFormat(val); break;
case "dataType": def.setDataType(val); break;
case "defaultValue": def.setDefaultValue(val); break;
case "description": def.setDescription(val); break;
case "name": def.setName(val); break;
case "required": def.setRequired(Boolean.valueOf(val)); break;
case "type": def.setType(RestParamType.valueOf(val)); break;
default: return false;
}
return true;
}, (def, key) -> {
switch (key) {
case "value": doAdd(doParseText(), def.getAllowableValues(), def::setAllowableValues); break;
case "examples": doAdd(doParseRestPropertyDefinition(), def.getExamples(), def::setExamples); break;
default: return false;
}
return true;
}, noValueHandler());
}
protected RestOperationResponseMsgDefinition doParseRestOperationResponseMsgDefinition() throws IOException, XmlPullParserException {
return doParse(new RestOperationResponseMsgDefinition(), (def, key, val) -> {
switch (key) {
case "code": def.setCode(val); break;
case "message": def.setMessage(val); break;
case "responseModel": def.setResponseModel(val); break;
default: return false;
}
return true;
}, (def, key) -> {
switch (key) {
case "examples": doAdd(doParseRestPropertyDefinition(), def.getExamples(), def::setExamples); break;
case "header": doAdd(doParseRestOperationResponseHeaderDefinition(), def.getHeaders(), def::setHeaders); break;
default: return false;
}
return true;
}, noValueHandler());
}
protected SecurityDefinition doParseSecurityDefinition() throws IOException, XmlPullParserException {
return doParse(new SecurityDefinition(), (def, key, val) -> {
switch (key) {
case "key": def.setKey(val); break;
case "scopes": def.setScopes(val); break;
default: return false;
}
return true;
}, noElementHandler(), noValueHandler());
}
protected GetDefinition doParseGetDefinition() throws IOException, XmlPullParserException {
return doParse(new GetDefinition(),
verbDefinitionAttributeHandler(), verbDefinitionElementHandler(), noValueHandler());
}
protected HeadDefinition doParseHeadDefinition() throws IOException, XmlPullParserException {
return doParse(new HeadDefinition(),
verbDefinitionAttributeHandler(), verbDefinitionElementHandler(), noValueHandler());
}
protected PatchDefinition doParsePatchDefinition() throws IOException, XmlPullParserException {
return doParse(new PatchDefinition(),
verbDefinitionAttributeHandler(), verbDefinitionElementHandler(), noValueHandler());
}
protected PostDefinition doParsePostDefinition() throws IOException, XmlPullParserException {
return doParse(new PostDefinition(),
verbDefinitionAttributeHandler(), verbDefinitionElementHandler(), noValueHandler());
}
protected PutDefinition doParsePutDefinition() throws IOException, XmlPullParserException {
return doParse(new PutDefinition(),
verbDefinitionAttributeHandler(), verbDefinitionElementHandler(), noValueHandler());
}
protected RestConfigurationDefinition doParseRestConfigurationDefinition() throws IOException, XmlPullParserException {
return doParse(new RestConfigurationDefinition(), (def, key, val) -> {
switch (key) {
case "apiComponent": def.setApiComponent(val); break;
case "apiContextIdPattern": def.setApiContextIdPattern(val); break;
case "apiContextListing": def.setApiContextListing(Boolean.valueOf(val)); break;
case "apiContextPath": def.setApiContextPath(val); break;
case "apiContextRouteId": def.setApiContextRouteId(val); break;
case "apiHost": def.setApiHost(val); break;
case "apiVendorExtension": def.setApiVendorExtension(Boolean.valueOf(val)); break;
case "bindingMode": def.setBindingMode(RestBindingMode.valueOf(val)); break;
case "clientRequestValidation": def.setClientRequestValidation(Boolean.valueOf(val)); break;
case "component": def.setComponent(val); break;
case "contextPath": def.setContextPath(val); break;
case "enableCORS": def.setEnableCORS(Boolean.valueOf(val)); break;
case "host": def.setHost(val); break;
case "hostNameResolver": def.setHostNameResolver(RestHostNameResolver.valueOf(val)); break;
case "jsonDataFormat": def.setJsonDataFormat(val); break;
case "port": def.setPort(val); break;
case "producerApiDoc": def.setProducerApiDoc(val); break;
case "producerComponent": def.setProducerComponent(val); break;
case "scheme": def.setScheme(val); break;
case "skipBindingOnErrorCode": def.setSkipBindingOnErrorCode(Boolean.valueOf(val)); break;
case "useXForwardHeaders": def.setUseXForwardHeaders(Boolean.valueOf(val)); break;
case "xmlDataFormat": def.setXmlDataFormat(val); break;
default: return false;
}
return true;
}, (def, key) -> {
switch (key) {
case "apiProperty": doAdd(doParseRestPropertyDefinition(), def.getApiProperties(), def::setApiProperties); break;
case "componentProperty": doAdd(doParseRestPropertyDefinition(), def.getComponentProperties(), def::setComponentProperties); break;
case "consumerProperty": doAdd(doParseRestPropertyDefinition(), def.getConsumerProperties(), def::setConsumerProperties); break;
case "corsHeaders": doAdd(doParseRestPropertyDefinition(), def.getCorsHeaders(), def::setCorsHeaders); break;
case "dataFormatProperty": doAdd(doParseRestPropertyDefinition(), def.getDataFormatProperties(), def::setDataFormatProperties); break;
case "endpointProperty": doAdd(doParseRestPropertyDefinition(), def.getEndpointProperties(), def::setEndpointProperties); break;
default: return false;
}
return true;
}, noValueHandler());
}
protected RestPropertyDefinition doParseRestPropertyDefinition() throws IOException, XmlPullParserException {
return doParse(new RestPropertyDefinition(), (def, key, val) -> {
switch (key) {
case "key": def.setKey(val); break;
case "value": def.setValue(val); break;
default: return false;
}
return true;
}, noElementHandler(), noValueHandler());
}
protected RestSecuritiesDefinition doParseRestSecuritiesDefinition() throws IOException, XmlPullParserException {
return doParse(new RestSecuritiesDefinition(),
noAttributeHandler(), (def, key) -> {
switch (key) {
case "apiKey": doAdd(doParseRestSecurityApiKey(), def.getSecurityDefinitions(), def::setSecurityDefinitions); break;
case "basicAuth": doAdd(doParseRestSecurityBasicAuth(), def.getSecurityDefinitions(), def::setSecurityDefinitions); break;
case "bearer": doAdd(doParseRestSecurityBearerToken(), def.getSecurityDefinitions(), def::setSecurityDefinitions); break;
case "oauth2": doAdd(doParseRestSecurityOAuth2(), def.getSecurityDefinitions(), def::setSecurityDefinitions); break;
case "openIdConnect": doAdd(doParseRestSecurityOpenIdConnect(), def.getSecurityDefinitions(), def::setSecurityDefinitions); break;
case "mutualTLS": doAdd(doParseRestSecurityMutualTLS(), def.getSecurityDefinitions(), def::setSecurityDefinitions); break;
default: return false;
}
return true;
}, noValueHandler());
}
protected RestSecuritiesRequirement doParseRestSecuritiesRequirement() throws IOException, XmlPullParserException {
return doParse(new RestSecuritiesRequirement(),
noAttributeHandler(), (def, key) -> {
if ("securityRequirement".equals(key)) {
doAdd(doParseSecurityDefinition(), def.getSecurityRequirements(), def::setSecurityRequirements);
return true;
}
return false;
}, noValueHandler());
}
protected RestOperationResponseHeaderDefinition doParseRestOperationResponseHeaderDefinition() throws IOException, XmlPullParserException {
return doParse(new RestOperationResponseHeaderDefinition(), (def, key, val) -> {
switch (key) {
case "arrayType": def.setArrayType(val); break;
case "collectionFormat": def.setCollectionFormat(CollectionFormat.valueOf(val)); break;
case "dataFormat": def.setDataFormat(val); break;
case "dataType": def.setDataType(val); break;
case "description": def.setDescription(val); break;
case "example": def.setExample(val); break;
case "name": def.setName(val); break;
default: return false;
}
return true;
}, (def, key) -> {
if ("value".equals(key)) {
doAdd(doParseText(), def.getAllowableValues(), def::setAllowableValues);
return true;
}
return false;
}, noValueHandler());
}
protected <T extends RestSecurityDefinition> AttributeHandler<T> restSecurityDefinitionAttributeHandler() {
return (def, key, val) -> {
switch (key) {
case "description": def.setDescription(val); break;
case "key": def.setKey(val); break;
default: return false;
}
return true;
};
}
protected RestSecurityApiKey doParseRestSecurityApiKey() throws IOException, XmlPullParserException {
return doParse(new RestSecurityApiKey(), (def, key, val) -> {
switch (key) {
case "inCookie": def.setInCookie(val); break;
case "inHeader": def.setInHeader(val); break;
case "inQuery": def.setInQuery(val); break;
case "name": def.setName(val); break;
default: return restSecurityDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected RestSecurityBasicAuth doParseRestSecurityBasicAuth() throws IOException, XmlPullParserException {
return doParse(new RestSecurityBasicAuth(),
restSecurityDefinitionAttributeHandler(), noElementHandler(), noValueHandler());
}
protected RestSecurityBearerToken doParseRestSecurityBearerToken() throws IOException, XmlPullParserException {
return doParse(new RestSecurityBearerToken(), (def, key, val) -> {
if ("format".equals(key)) {
def.setFormat(val);
return true;
}
return restSecurityDefinitionAttributeHandler().accept(def, key, val);
}, noElementHandler(), noValueHandler());
}
protected RestSecurityMutualTLS doParseRestSecurityMutualTLS() throws IOException, XmlPullParserException {
return doParse(new RestSecurityMutualTLS(),
restSecurityDefinitionAttributeHandler(), noElementHandler(), noValueHandler());
}
protected RestSecurityOAuth2 doParseRestSecurityOAuth2() throws IOException, XmlPullParserException {
return doParse(new RestSecurityOAuth2(), (def, key, val) -> {
switch (key) {
case "authorizationUrl": def.setAuthorizationUrl(val); break;
case "flow": def.setFlow(val); break;
case "refreshUrl": def.setRefreshUrl(val); break;
case "tokenUrl": def.setTokenUrl(val); break;
default: return restSecurityDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, (def, key) -> {
if ("scopes".equals(key)) {
doAdd(doParseRestPropertyDefinition(), def.getScopes(), def::setScopes);
return true;
}
return false;
}, noValueHandler());
}
protected RestSecurityOpenIdConnect doParseRestSecurityOpenIdConnect() throws IOException, XmlPullParserException {
return doParse(new RestSecurityOpenIdConnect(), (def, key, val) -> {
if ("url".equals(key)) {
def.setUrl(val);
return true;
}
return restSecurityDefinitionAttributeHandler().accept(def, key, val);
}, noElementHandler(), noValueHandler());
}
public Optional<RestsDefinition> parseRestsDefinition()
throws IOException, XmlPullParserException {
String tag = getNextTag("rests", "rest");
if (tag != null) {
switch (tag) {
case "rests" : return Optional.of(doParseRestsDefinition());
case "rest" : return parseSingleRestsDefinition();
}
}
return Optional.empty();
}
private Optional<RestsDefinition> parseSingleRestsDefinition()
throws IOException, XmlPullParserException {
Optional<RestDefinition> single = Optional.of(doParseRestDefinition());
if (single.isPresent()) {
List<RestDefinition> list = new ArrayList<>();
list.add(single.get());
RestsDefinition def = new RestsDefinition();
def.setRests(list);
return Optional.of(def);
}
return Optional.empty();
}
protected RestsDefinition doParseRestsDefinition() throws IOException, XmlPullParserException {
return doParse(new RestsDefinition(),
optionalIdentifiedDefinitionAttributeHandler(), (def, key) -> {
if ("rest".equals(key)) {
doAdd(doParseRestDefinition(), def.getRests(), def::setRests);
return true;
}
return optionalIdentifiedDefinitionElementHandler().accept(def, key);
}, noValueHandler());
}
protected CustomTransformerDefinition doParseCustomTransformerDefinition() throws IOException, XmlPullParserException {
return doParse(new CustomTransformerDefinition(), (def, key, val) -> {
switch (key) {
case "className": def.setClassName(val); break;
case "ref": def.setRef(val); break;
default: return transformerDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected <T extends TransformerDefinition> AttributeHandler<T> transformerDefinitionAttributeHandler() {
return (def, key, val) -> {
switch (key) {
case "fromType": def.setFromType(val); break;
case "scheme": def.setScheme(val); break;
case "toType": def.setToType(val); break;
default: return false;
}
return true;
};
}
protected DataFormatTransformerDefinition doParseDataFormatTransformerDefinition() throws IOException, XmlPullParserException {
return doParse(new DataFormatTransformerDefinition(), (def, key, val) -> {
if ("ref".equals(key)) {
def.setRef(val);
return true;
}
return transformerDefinitionAttributeHandler().accept(def, key, val);
}, (def, key) -> {
DataFormatDefinition v = doParseDataFormatDefinitionRef(key);
if (v != null) {
def.setDataFormatType(v);
return true;
}
return false;
}, noValueHandler());
}
protected EndpointTransformerDefinition doParseEndpointTransformerDefinition() throws IOException, XmlPullParserException {
return doParse(new EndpointTransformerDefinition(), (def, key, val) -> {
switch (key) {
case "ref": def.setRef(val); break;
case "uri": def.setUri(val); break;
default: return transformerDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected TransformersDefinition doParseTransformersDefinition() throws IOException, XmlPullParserException {
return doParse(new TransformersDefinition(),
noAttributeHandler(), (def, key) -> {
switch (key) {
case "dataFormatTransformer": doAdd(doParseDataFormatTransformerDefinition(), def.getTransformers(), def::setTransformers); break;
case "endpointTransformer": doAdd(doParseEndpointTransformerDefinition(), def.getTransformers(), def::setTransformers); break;
case "customTransformer": doAdd(doParseCustomTransformerDefinition(), def.getTransformers(), def::setTransformers); break;
default: return false;
}
return true;
}, noValueHandler());
}
protected CustomValidatorDefinition doParseCustomValidatorDefinition() throws IOException, XmlPullParserException {
return doParse(new CustomValidatorDefinition(), (def, key, val) -> {
switch (key) {
case "className": def.setClassName(val); break;
case "ref": def.setRef(val); break;
default: return validatorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected <T extends ValidatorDefinition> AttributeHandler<T> validatorDefinitionAttributeHandler() {
return (def, key, val) -> {
if ("type".equals(key)) {
def.setType(val);
return true;
}
return false;
};
}
protected EndpointValidatorDefinition doParseEndpointValidatorDefinition() throws IOException, XmlPullParserException {
return doParse(new EndpointValidatorDefinition(), (def, key, val) -> {
switch (key) {
case "ref": def.setRef(val); break;
case "uri": def.setUri(val); break;
default: return validatorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected PredicateValidatorDefinition doParsePredicateValidatorDefinition() throws IOException, XmlPullParserException {
return doParse(new PredicateValidatorDefinition(),
validatorDefinitionAttributeHandler(), (def, key) -> {
ExpressionDefinition v = doParseExpressionDefinitionRef(key);
if (v != null) {
def.setExpression(v);
return true;
}
return false;
}, noValueHandler());
}
protected ValidatorsDefinition doParseValidatorsDefinition() throws IOException, XmlPullParserException {
return doParse(new ValidatorsDefinition(),
noAttributeHandler(), (def, key) -> {
switch (key) {
case "endpointValidator": doAdd(doParseEndpointValidatorDefinition(), def.getValidators(), def::setValidators); break;
case "predicateValidator": doAdd(doParsePredicateValidatorDefinition(), def.getValidators(), def::setValidators); break;
case "customValidator": doAdd(doParseCustomValidatorDefinition(), def.getValidators(), def::setValidators); break;
default: return false;
}
return true;
}, noValueHandler());
}
protected ProcessorDefinition doParseProcessorDefinitionRef(String key) throws IOException, XmlPullParserException {
switch (key) {
case "aggregate": return doParseAggregateDefinition();
case "bean": return doParseBeanDefinition();
case "doCatch": return doParseCatchDefinition();
case "when": return doParseWhenDefinition();
case "choice": return doParseChoiceDefinition();
case "otherwise": return doParseOtherwiseDefinition();
case "circuitBreaker": return doParseCircuitBreakerDefinition();
case "claimCheck": return doParseClaimCheckDefinition();
case "convertBodyTo": return doParseConvertBodyDefinition();
case "delay": return doParseDelayDefinition();
case "dynamicRouter": return doParseDynamicRouterDefinition();
case "enrich": return doParseEnrichDefinition();
case "filter": return doParseFilterDefinition();
case "doFinally": return doParseFinallyDefinition();
case "idempotentConsumer": return doParseIdempotentConsumerDefinition();
case "inOnly": return doParseInOnlyDefinition();
case "inOut": return doParseInOutDefinition();
case "intercept": return doParseInterceptDefinition();
case "interceptFrom": return doParseInterceptFromDefinition();
case "interceptSendToEndpoint": return doParseInterceptSendToEndpointDefinition();
case "kamelet": return doParseKameletDefinition();
case "loadBalance": return doParseLoadBalanceDefinition();
case "log": return doParseLogDefinition();
case "loop": return doParseLoopDefinition();
case "marshal": return doParseMarshalDefinition();
case "multicast": return doParseMulticastDefinition();
case "onCompletion": return doParseOnCompletionDefinition();
case "onException": return doParseOnExceptionDefinition();
case "onFallback": return doParseOnFallbackDefinition();
case "pipeline": return doParsePipelineDefinition();
case "policy": return doParsePolicyDefinition();
case "pollEnrich": return doParsePollEnrichDefinition();
case "process": return doParseProcessDefinition();
case "recipientList": return doParseRecipientListDefinition();
case "removeHeader": return doParseRemoveHeaderDefinition();
case "removeHeaders": return doParseRemoveHeadersDefinition();
case "removeProperties": return doParseRemovePropertiesDefinition();
case "removeProperty": return doParseRemovePropertyDefinition();
case "resequence": return doParseResequenceDefinition();
case "rollback": return doParseRollbackDefinition();
case "route": return doParseRouteDefinition();
case "routingSlip": return doParseRoutingSlipDefinition();
case "saga": return doParseSagaDefinition();
case "sample": return doParseSamplingDefinition();
case "script": return doParseScriptDefinition();
case "setBody": return doParseSetBodyDefinition();
case "setExchangePattern": return doParseSetExchangePatternDefinition();
case "setHeader": return doParseSetHeaderDefinition();
case "setProperty": return doParseSetPropertyDefinition();
case "sort": return doParseSortDefinition();
case "split": return doParseSplitDefinition();
case "step": return doParseStepDefinition();
case "stop": return doParseStopDefinition();
case "doSwitch": return doParseSwitchDefinition();
case "threads": return doParseThreadsDefinition();
case "throttle": return doParseThrottleDefinition();
case "throwException": return doParseThrowExceptionDefinition();
case "to": return doParseToDefinition();
case "toD": return doParseToDynamicDefinition();
case "transacted": return doParseTransactedDefinition();
case "transform": return doParseTransformDefinition();
case "doTry": return doParseTryDefinition();
case "unmarshal": return doParseUnmarshalDefinition();
case "validate": return doParseValidateDefinition();
case "wireTap": return doParseWireTapDefinition();
case "serviceCall": return doParseServiceCallDefinition();
default: return null;
}
}
protected ExpressionDefinition doParseExpressionDefinitionRef(String key) throws IOException, XmlPullParserException {
switch (key) {
case "expressionDefinition": return doParseExpressionDefinition();
case "csimple": return doParseCSimpleExpression();
case "constant": return doParseConstantExpression();
case "datasonnet": return doParseDatasonnetExpression();
case "exchangeProperty": return doParseExchangePropertyExpression();
case "groovy": return doParseGroovyExpression();
case "header": return doParseHeaderExpression();
case "hl7terser": return doParseHl7TerserExpression();
case "joor": return doParseJoorExpression();
case "jsonpath": return doParseJsonPathExpression();
case "language": return doParseLanguageExpression();
case "method": return doParseMethodCallExpression();
case "mvel": return doParseMvelExpression();
case "ognl": return doParseOgnlExpression();
case "ref": return doParseRefExpression();
case "simple": return doParseSimpleExpression();
case "spel": return doParseSpELExpression();
case "tokenize": return doParseTokenizerExpression();
case "xtokenize": return doParseXMLTokenizerExpression();
case "xpath": return doParseXPathExpression();
case "xquery": return doParseXQueryExpression();
default: return null;
}
}
protected DataFormatDefinition doParseDataFormatDefinitionRef(String key) throws IOException, XmlPullParserException {
switch (key) {
case "asn1": return doParseASN1DataFormat();
case "any23": return doParseAny23DataFormat();
case "avro": return doParseAvroDataFormat();
case "barcode": return doParseBarcodeDataFormat();
case "base64": return doParseBase64DataFormat();
case "beanio": return doParseBeanioDataFormat();
case "bindy": return doParseBindyDataFormat();
case "cbor": return doParseCBORDataFormat();
case "crypto": return doParseCryptoDataFormat();
case "csv": return doParseCsvDataFormat();
case "custom": return doParseCustomDataFormat();
case "fhirJson": return doParseFhirJsonDataFormat();
case "fhirXml": return doParseFhirXmlDataFormat();
case "flatpack": return doParseFlatpackDataFormat();
case "grok": return doParseGrokDataFormat();
case "gzipDeflater": return doParseGzipDeflaterDataFormat();
case "hl7": return doParseHL7DataFormat();
case "ical": return doParseIcalDataFormat();
case "jacksonXml": return doParseJacksonXMLDataFormat();
case "jaxb": return doParseJaxbDataFormat();
case "jsonApi": return doParseJsonApiDataFormat();
case "json": return doParseJsonDataFormat();
case "lzf": return doParseLZFDataFormat();
case "mimeMultipart": return doParseMimeMultipartDataFormat();
case "pgp": return doParsePGPDataFormat();
case "protobuf": return doParseProtobufDataFormat();
case "rss": return doParseRssDataFormat();
case "soap": return doParseSoapDataFormat();
case "syslog": return doParseSyslogDataFormat();
case "tarFile": return doParseTarFileDataFormat();
case "thrift": return doParseThriftDataFormat();
case "tidyMarkup": return doParseTidyMarkupDataFormat();
case "univocityCsv": return doParseUniVocityCsvDataFormat();
case "univocityFixed": return doParseUniVocityFixedDataFormat();
case "univocityTsv": return doParseUniVocityTsvDataFormat();
case "xmlSecurity": return doParseXMLSecurityDataFormat();
case "xstream": return doParseXStreamDataFormat();
case "yaml": return doParseYAMLDataFormat();
case "zipDeflater": return doParseZipDeflaterDataFormat();
case "zipFile": return doParseZipFileDataFormat();
default: return null;
}
}
}
//CHECKSTYLE:ON
| core/camel-xml-io/src/generated/java/org/apache/camel/xml/in/ModelParser.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//CHECKSTYLE:OFF
/**
* Generated by Camel build tools - do NOT edit this file!
*/
package org.apache.camel.xml.in;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.apache.camel.model.*;
import org.apache.camel.model.cloud.*;
import org.apache.camel.model.config.BatchResequencerConfig;
import org.apache.camel.model.config.ResequencerConfig;
import org.apache.camel.model.config.StreamResequencerConfig;
import org.apache.camel.model.dataformat.*;
import org.apache.camel.model.language.*;
import org.apache.camel.model.loadbalancer.*;
import org.apache.camel.model.rest.*;
import org.apache.camel.model.transformer.*;
import org.apache.camel.model.validator.*;
import org.apache.camel.xml.io.XmlPullParserException;
@SuppressWarnings("unused")
public class ModelParser extends BaseParser {
public ModelParser(
org.apache.camel.spi.Resource input)
throws IOException, XmlPullParserException {
super(input);
}
public ModelParser(
org.apache.camel.spi.Resource input,
String namespace)
throws IOException, XmlPullParserException {
super(input, namespace);
}
public ModelParser(
InputStream input)
throws IOException, XmlPullParserException {
super(input);
}
public ModelParser(Reader reader) throws IOException, XmlPullParserException {
super(reader);
}
public ModelParser(
InputStream input,
String namespace)
throws IOException, XmlPullParserException {
super(input, namespace);
}
public ModelParser(
Reader reader,
String namespace)
throws IOException, XmlPullParserException {
super(reader, namespace);
}
protected AggregateDefinition doParseAggregateDefinition() throws IOException, XmlPullParserException {
return doParse(new AggregateDefinition(), (def, key, val) -> {
switch (key) {
case "aggregateControllerRef": def.setAggregateControllerRef(val); break;
case "aggregationRepositoryRef": def.setAggregationRepositoryRef(val); break;
case "closeCorrelationKeyOnCompletion": def.setCloseCorrelationKeyOnCompletion(val); break;
case "completeAllOnStop": def.setCompleteAllOnStop(val); break;
case "completionFromBatchConsumer": def.setCompletionFromBatchConsumer(val); break;
case "completionInterval": def.setCompletionInterval(val); break;
case "completionOnNewCorrelationGroup": def.setCompletionOnNewCorrelationGroup(val); break;
case "completionSize": def.setCompletionSize(val); break;
case "completionTimeout": def.setCompletionTimeout(val); break;
case "completionTimeoutCheckerInterval": def.setCompletionTimeoutCheckerInterval(val); break;
case "discardOnAggregationFailure": def.setDiscardOnAggregationFailure(val); break;
case "discardOnCompletionTimeout": def.setDiscardOnCompletionTimeout(val); break;
case "eagerCheckCompletion": def.setEagerCheckCompletion(val); break;
case "executorServiceRef": def.setExecutorServiceRef(val); break;
case "forceCompletionOnStop": def.setForceCompletionOnStop(val); break;
case "ignoreInvalidCorrelationKeys": def.setIgnoreInvalidCorrelationKeys(val); break;
case "optimisticLocking": def.setOptimisticLocking(val); break;
case "parallelProcessing": def.setParallelProcessing(val); break;
case "strategyMethodAllowNull": def.setStrategyMethodAllowNull(val); break;
case "strategyMethodName": def.setStrategyMethodName(val); break;
case "strategyRef": def.setStrategyRef(val); break;
case "timeoutCheckerExecutorServiceRef": def.setTimeoutCheckerExecutorServiceRef(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, (def, key) -> {
switch (key) {
case "completionPredicate": def.setCompletionPredicate(doParseExpressionSubElementDefinition()); break;
case "completionSizeExpression": def.setCompletionSizeExpression(doParseExpressionSubElementDefinition()); break;
case "completionTimeoutExpression": def.setCompletionTimeoutExpression(doParseExpressionSubElementDefinition()); break;
case "correlationExpression": def.setCorrelationExpression(doParseExpressionSubElementDefinition()); break;
case "optimisticLockRetryPolicy": def.setOptimisticLockRetryPolicyDefinition(doParseOptimisticLockRetryPolicyDefinition()); break;
default: return outputDefinitionElementHandler().accept(def, key);
}
return true;
}, noValueHandler());
}
protected ExpressionSubElementDefinition doParseExpressionSubElementDefinition() throws IOException, XmlPullParserException {
return doParse(new ExpressionSubElementDefinition(),
noAttributeHandler(), (def, key) -> {
ExpressionDefinition v = doParseExpressionDefinitionRef(key);
if (v != null) {
def.setExpressionType(v);
return true;
}
return false;
}, noValueHandler());
}
protected OptimisticLockRetryPolicyDefinition doParseOptimisticLockRetryPolicyDefinition() throws IOException, XmlPullParserException {
return doParse(new OptimisticLockRetryPolicyDefinition(), (def, key, val) -> {
switch (key) {
case "exponentialBackOff": def.setExponentialBackOff(val); break;
case "maximumRetries": def.setMaximumRetries(val); break;
case "maximumRetryDelay": def.setMaximumRetryDelay(val); break;
case "randomBackOff": def.setRandomBackOff(val); break;
case "retryDelay": def.setRetryDelay(val); break;
default: return false;
}
return true;
}, noElementHandler(), noValueHandler());
}
protected <T extends OutputDefinition> ElementHandler<T> outputDefinitionElementHandler() {
return (def, key) -> {
ProcessorDefinition v = doParseProcessorDefinitionRef(key);
if (v != null) {
doAdd(v, def.getOutputs(), def::setOutputs);
return true;
}
return optionalIdentifiedDefinitionElementHandler().accept(def, key);
};
}
protected OutputDefinition doParseOutputDefinition() throws IOException, XmlPullParserException {
return doParse(new OutputDefinition(),
processorDefinitionAttributeHandler(), outputDefinitionElementHandler(), noValueHandler());
}
protected <T extends ProcessorDefinition> AttributeHandler<T> processorDefinitionAttributeHandler() {
return (def, key, val) -> {
if ("inheritErrorHandler".equals(key)) {
def.setInheritErrorHandler(Boolean.valueOf(val));
return true;
}
return optionalIdentifiedDefinitionAttributeHandler().accept(def, key, val);
};
}
protected <T extends OptionalIdentifiedDefinition> AttributeHandler<T> optionalIdentifiedDefinitionAttributeHandler() {
return (def, key, val) -> {
switch (key) {
case "customId": def.setCustomId(Boolean.valueOf(val)); break;
case "id": def.setId(val); break;
default: return false;
}
return true;
};
}
protected <T extends OptionalIdentifiedDefinition> ElementHandler<T> optionalIdentifiedDefinitionElementHandler() {
return (def, key) -> {
switch (key) {
case "description": def.setDescription(doParseDescriptionDefinition()); break;
case "generatedId": def.setGeneratedId(doParseText()); break;
default: return false;
}
return true;
};
}
protected DescriptionDefinition doParseDescriptionDefinition() throws IOException, XmlPullParserException {
return doParse(new DescriptionDefinition(), (def, key, val) -> {
if ("lang".equals(key)) {
def.setLang(val);
return true;
}
return false;
}, noElementHandler(), (def, val) -> def.setText(val));
}
protected BeanDefinition doParseBeanDefinition() throws IOException, XmlPullParserException {
return doParse(new BeanDefinition(), (def, key, val) -> {
switch (key) {
case "beanType": def.setBeanType(val); break;
case "cache": def.setCache(val); break;
case "method": def.setMethod(val); break;
case "ref": def.setRef(val); break;
case "scope": def.setScope(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected CatchDefinition doParseCatchDefinition() throws IOException, XmlPullParserException {
return doParse(new CatchDefinition(),
processorDefinitionAttributeHandler(), (def, key) -> {
switch (key) {
case "exception": doAdd(doParseText(), def.getExceptions(), def::setExceptions); break;
case "onWhen": def.setOnWhen(doParseWhenDefinition()); break;
default: return outputDefinitionElementHandler().accept(def, key);
}
return true;
}, noValueHandler());
}
protected WhenDefinition doParseWhenDefinition() throws IOException, XmlPullParserException {
return doParse(new WhenDefinition(),
processorDefinitionAttributeHandler(), outputExpressionNodeElementHandler(), noValueHandler());
}
protected <T extends ChoiceDefinition> ElementHandler<T> choiceDefinitionElementHandler() {
return (def, key) -> {
switch (key) {
case "when": doAdd(doParseWhenDefinition(), def.getWhenClauses(), def::setWhenClauses); break;
case "otherwise": def.setOtherwise(doParseOtherwiseDefinition()); break;
default: return optionalIdentifiedDefinitionElementHandler().accept(def, key);
}
return true;
};
}
protected ChoiceDefinition doParseChoiceDefinition() throws IOException, XmlPullParserException {
return doParse(new ChoiceDefinition(),
processorDefinitionAttributeHandler(), choiceDefinitionElementHandler(), noValueHandler());
}
protected OtherwiseDefinition doParseOtherwiseDefinition() throws IOException, XmlPullParserException {
return doParse(new OtherwiseDefinition(),
processorDefinitionAttributeHandler(), outputDefinitionElementHandler(), noValueHandler());
}
protected CircuitBreakerDefinition doParseCircuitBreakerDefinition() throws IOException, XmlPullParserException {
return doParse(new CircuitBreakerDefinition(), (def, key, val) -> {
if ("configurationRef".equals(key)) {
def.setConfigurationRef(val);
return true;
}
return processorDefinitionAttributeHandler().accept(def, key, val);
}, (def, key) -> {
switch (key) {
case "faultToleranceConfiguration": def.setFaultToleranceConfiguration(doParseFaultToleranceConfigurationDefinition()); break;
case "hystrixConfiguration": def.setHystrixConfiguration(doParseHystrixConfigurationDefinition()); break;
case "resilience4jConfiguration": def.setResilience4jConfiguration(doParseResilience4jConfigurationDefinition()); break;
default: return outputDefinitionElementHandler().accept(def, key);
}
return true;
}, noValueHandler());
}
protected HystrixConfigurationDefinition doParseHystrixConfigurationDefinition() throws IOException, XmlPullParserException {
return doParse(new HystrixConfigurationDefinition(),
hystrixConfigurationCommonAttributeHandler(), noElementHandler(), noValueHandler());
}
protected Resilience4jConfigurationDefinition doParseResilience4jConfigurationDefinition() throws IOException, XmlPullParserException {
return doParse(new Resilience4jConfigurationDefinition(),
resilience4jConfigurationCommonAttributeHandler(), resilience4jConfigurationCommonElementHandler(), noValueHandler());
}
protected FaultToleranceConfigurationDefinition doParseFaultToleranceConfigurationDefinition() throws IOException, XmlPullParserException {
return doParse(new FaultToleranceConfigurationDefinition(),
faultToleranceConfigurationCommonAttributeHandler(), noElementHandler(), noValueHandler());
}
protected ClaimCheckDefinition doParseClaimCheckDefinition() throws IOException, XmlPullParserException {
return doParse(new ClaimCheckDefinition(), (def, key, val) -> {
switch (key) {
case "filter": def.setFilter(val); break;
case "key": def.setKey(val); break;
case "operation": def.setOperation(val); break;
case "strategyMethodName": def.setAggregationStrategyMethodName(val); break;
case "strategyRef": def.setAggregationStrategyRef(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected ContextScanDefinition doParseContextScanDefinition() throws IOException, XmlPullParserException {
return doParse(new ContextScanDefinition(), (def, key, val) -> {
if ("includeNonSingletons".equals(key)) {
def.setIncludeNonSingletons(val);
return true;
}
return false;
}, (def, key) -> {
switch (key) {
case "excludes": doAdd(doParseText(), def.getExcludes(), def::setExcludes); break;
case "includes": doAdd(doParseText(), def.getIncludes(), def::setIncludes); break;
default: return false;
}
return true;
}, noValueHandler());
}
protected ConvertBodyDefinition doParseConvertBodyDefinition() throws IOException, XmlPullParserException {
return doParse(new ConvertBodyDefinition(), (def, key, val) -> {
switch (key) {
case "charset": def.setCharset(val); break;
case "mandatory": def.setMandatory(val); break;
case "type": def.setType(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected DataFormatDefinition doParseDataFormatDefinition() throws IOException, XmlPullParserException {
return doParse(new DataFormatDefinition(),
identifiedTypeAttributeHandler(), noElementHandler(), noValueHandler());
}
protected <T extends IdentifiedType> AttributeHandler<T> identifiedTypeAttributeHandler() {
return (def, key, val) -> {
if ("id".equals(key)) {
def.setId(val);
return true;
}
return false;
};
}
protected DelayDefinition doParseDelayDefinition() throws IOException, XmlPullParserException {
return doParse(new DelayDefinition(), (def, key, val) -> {
switch (key) {
case "asyncDelayed": def.setAsyncDelayed(val); break;
case "callerRunsWhenRejected": def.setCallerRunsWhenRejected(val); break;
case "executorServiceRef": def.setExecutorServiceRef(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, expressionNodeElementHandler(), noValueHandler());
}
protected <T extends ExpressionNode> ElementHandler<T> expressionNodeElementHandler() {
return (def, key) -> {
ExpressionDefinition v = doParseExpressionDefinitionRef(key);
if (v != null) {
def.setExpression(v);
return true;
}
return optionalIdentifiedDefinitionElementHandler().accept(def, key);
};
}
protected <T extends ExpressionDefinition> AttributeHandler<T> expressionDefinitionAttributeHandler() {
return (def, key, val) -> {
switch (key) {
case "id": def.setId(val); break;
case "trim": def.setTrim(val); break;
default: return false;
}
return true;
};
}
protected ExpressionDefinition doParseExpressionDefinition() throws IOException, XmlPullParserException {
return doParse(new ExpressionDefinition(), expressionDefinitionAttributeHandler(), noElementHandler(), expressionDefinitionValueHandler());
}
protected DynamicRouterDefinition doParseDynamicRouterDefinition() throws IOException, XmlPullParserException {
return doParse(new DynamicRouterDefinition(), (def, key, val) -> {
switch (key) {
case "cacheSize": def.setCacheSize(val); break;
case "ignoreInvalidEndpoints": def.setIgnoreInvalidEndpoints(val); break;
case "uriDelimiter": def.setUriDelimiter(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, expressionNodeElementHandler(), noValueHandler());
}
protected EnrichDefinition doParseEnrichDefinition() throws IOException, XmlPullParserException {
return doParse(new EnrichDefinition(), (def, key, val) -> {
switch (key) {
case "aggregateOnException": def.setAggregateOnException(val); break;
case "allowOptimisedComponents": def.setAllowOptimisedComponents(val); break;
case "cacheSize": def.setCacheSize(val); break;
case "ignoreInvalidEndpoint": def.setIgnoreInvalidEndpoint(val); break;
case "shareUnitOfWork": def.setShareUnitOfWork(val); break;
case "strategyMethodAllowNull": def.setAggregationStrategyMethodAllowNull(val); break;
case "strategyMethodName": def.setAggregationStrategyMethodName(val); break;
case "strategyRef": def.setAggregationStrategyRef(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, expressionNodeElementHandler(), noValueHandler());
}
protected <T extends FaultToleranceConfigurationCommon> AttributeHandler<T> faultToleranceConfigurationCommonAttributeHandler() {
return (def, key, val) -> {
switch (key) {
case "bulkheadEnabled": def.setBulkheadEnabled(val); break;
case "bulkheadExecutorServiceRef": def.setBulkheadExecutorServiceRef(val); break;
case "bulkheadMaxConcurrentCalls": def.setBulkheadMaxConcurrentCalls(val); break;
case "bulkheadWaitingTaskQueue": def.setBulkheadWaitingTaskQueue(val); break;
case "circuitBreakerRef": def.setCircuitBreakerRef(val); break;
case "delay": def.setDelay(val); break;
case "failureRatio": def.setFailureRatio(val); break;
case "requestVolumeThreshold": def.setRequestVolumeThreshold(val); break;
case "successThreshold": def.setSuccessThreshold(val); break;
case "timeoutDuration": def.setTimeoutDuration(val); break;
case "timeoutEnabled": def.setTimeoutEnabled(val); break;
case "timeoutPoolSize": def.setTimeoutPoolSize(val); break;
case "timeoutScheduledExecutorServiceRef": def.setTimeoutScheduledExecutorServiceRef(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
};
}
protected FaultToleranceConfigurationCommon doParseFaultToleranceConfigurationCommon() throws IOException, XmlPullParserException {
return doParse(new FaultToleranceConfigurationCommon(), faultToleranceConfigurationCommonAttributeHandler(), noElementHandler(), noValueHandler());
}
protected FilterDefinition doParseFilterDefinition() throws IOException, XmlPullParserException {
return doParse(new FilterDefinition(), (def, key, val) -> {
if ("statusPropertyName".equals(key)) {
def.setStatusPropertyName(val);
return true;
}
return processorDefinitionAttributeHandler().accept(def, key, val);
}, outputExpressionNodeElementHandler(), noValueHandler());
}
protected <T extends OutputExpressionNode> ElementHandler<T> outputExpressionNodeElementHandler() {
return (def, key) -> {
ProcessorDefinition v = doParseProcessorDefinitionRef(key);
if (v != null) {
doAdd(v, def.getOutputs(), def::setOutputs);
return true;
}
return expressionNodeElementHandler().accept(def, key);
};
}
protected FinallyDefinition doParseFinallyDefinition() throws IOException, XmlPullParserException {
return doParse(new FinallyDefinition(),
processorDefinitionAttributeHandler(), outputDefinitionElementHandler(), noValueHandler());
}
protected FromDefinition doParseFromDefinition() throws IOException, XmlPullParserException {
return doParse(new FromDefinition(), (def, key, val) -> {
if ("uri".equals(key)) {
def.setUri(val);
return true;
}
return optionalIdentifiedDefinitionAttributeHandler().accept(def, key, val);
}, optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected GlobalOptionDefinition doParseGlobalOptionDefinition() throws IOException, XmlPullParserException {
return doParse(new GlobalOptionDefinition(), (def, key, val) -> {
switch (key) {
case "key": def.setKey(val); break;
case "value": def.setValue(val); break;
default: return false;
}
return true;
}, noElementHandler(), noValueHandler());
}
protected GlobalOptionsDefinition doParseGlobalOptionsDefinition() throws IOException, XmlPullParserException {
return doParse(new GlobalOptionsDefinition(),
noAttributeHandler(), (def, key) -> {
if ("globalOption".equals(key)) {
doAdd(doParseGlobalOptionDefinition(), def.getGlobalOptions(), def::setGlobalOptions);
return true;
}
return false;
}, noValueHandler());
}
protected <T extends HystrixConfigurationCommon> AttributeHandler<T> hystrixConfigurationCommonAttributeHandler() {
return (def, key, val) -> {
switch (key) {
case "allowMaximumSizeToDivergeFromCoreSize": def.setAllowMaximumSizeToDivergeFromCoreSize(val); break;
case "circuitBreakerEnabled": def.setCircuitBreakerEnabled(val); break;
case "circuitBreakerErrorThresholdPercentage": def.setCircuitBreakerErrorThresholdPercentage(val); break;
case "circuitBreakerForceClosed": def.setCircuitBreakerForceClosed(val); break;
case "circuitBreakerForceOpen": def.setCircuitBreakerForceOpen(val); break;
case "circuitBreakerRequestVolumeThreshold": def.setCircuitBreakerRequestVolumeThreshold(val); break;
case "circuitBreakerSleepWindowInMilliseconds": def.setCircuitBreakerSleepWindowInMilliseconds(val); break;
case "corePoolSize": def.setCorePoolSize(val); break;
case "executionIsolationSemaphoreMaxConcurrentRequests": def.setExecutionIsolationSemaphoreMaxConcurrentRequests(val); break;
case "executionIsolationStrategy": def.setExecutionIsolationStrategy(val); break;
case "executionIsolationThreadInterruptOnTimeout": def.setExecutionIsolationThreadInterruptOnTimeout(val); break;
case "executionTimeoutEnabled": def.setExecutionTimeoutEnabled(val); break;
case "executionTimeoutInMilliseconds": def.setExecutionTimeoutInMilliseconds(val); break;
case "fallbackEnabled": def.setFallbackEnabled(val); break;
case "fallbackIsolationSemaphoreMaxConcurrentRequests": def.setFallbackIsolationSemaphoreMaxConcurrentRequests(val); break;
case "groupKey": def.setGroupKey(val); break;
case "keepAliveTime": def.setKeepAliveTime(val); break;
case "maxQueueSize": def.setMaxQueueSize(val); break;
case "maximumSize": def.setMaximumSize(val); break;
case "metricsHealthSnapshotIntervalInMilliseconds": def.setMetricsHealthSnapshotIntervalInMilliseconds(val); break;
case "metricsRollingPercentileBucketSize": def.setMetricsRollingPercentileBucketSize(val); break;
case "metricsRollingPercentileEnabled": def.setMetricsRollingPercentileEnabled(val); break;
case "metricsRollingPercentileWindowBuckets": def.setMetricsRollingPercentileWindowBuckets(val); break;
case "metricsRollingPercentileWindowInMilliseconds": def.setMetricsRollingPercentileWindowInMilliseconds(val); break;
case "metricsRollingStatisticalWindowBuckets": def.setMetricsRollingStatisticalWindowBuckets(val); break;
case "metricsRollingStatisticalWindowInMilliseconds": def.setMetricsRollingStatisticalWindowInMilliseconds(val); break;
case "queueSizeRejectionThreshold": def.setQueueSizeRejectionThreshold(val); break;
case "requestLogEnabled": def.setRequestLogEnabled(val); break;
case "threadPoolKey": def.setThreadPoolKey(val); break;
case "threadPoolRollingNumberStatisticalWindowBuckets": def.setThreadPoolRollingNumberStatisticalWindowBuckets(val); break;
case "threadPoolRollingNumberStatisticalWindowInMilliseconds": def.setThreadPoolRollingNumberStatisticalWindowInMilliseconds(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
};
}
protected HystrixConfigurationCommon doParseHystrixConfigurationCommon() throws IOException, XmlPullParserException {
return doParse(new HystrixConfigurationCommon(), hystrixConfigurationCommonAttributeHandler(), noElementHandler(), noValueHandler());
}
protected IdempotentConsumerDefinition doParseIdempotentConsumerDefinition() throws IOException, XmlPullParserException {
return doParse(new IdempotentConsumerDefinition(), (def, key, val) -> {
switch (key) {
case "completionEager": def.setCompletionEager(val); break;
case "eager": def.setEager(val); break;
case "messageIdRepositoryRef": def.setMessageIdRepositoryRef(val); break;
case "removeOnFailure": def.setRemoveOnFailure(val); break;
case "skipDuplicate": def.setSkipDuplicate(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, outputExpressionNodeElementHandler(), noValueHandler());
}
protected InOnlyDefinition doParseInOnlyDefinition() throws IOException, XmlPullParserException {
return doParse(new InOnlyDefinition(),
sendDefinitionAttributeHandler(), optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected <T extends SendDefinition> AttributeHandler<T> sendDefinitionAttributeHandler() {
return (def, key, val) -> {
if ("uri".equals(key)) {
def.setUri(val);
return true;
}
return processorDefinitionAttributeHandler().accept(def, key, val);
};
}
protected InOutDefinition doParseInOutDefinition() throws IOException, XmlPullParserException {
return doParse(new InOutDefinition(),
sendDefinitionAttributeHandler(), optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected InputTypeDefinition doParseInputTypeDefinition() throws IOException, XmlPullParserException {
return doParse(new InputTypeDefinition(), (def, key, val) -> {
switch (key) {
case "urn": def.setUrn(val); break;
case "validate": def.setValidate(val); break;
default: return optionalIdentifiedDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected InterceptDefinition doParseInterceptDefinition() throws IOException, XmlPullParserException {
return doParse(new InterceptDefinition(),
processorDefinitionAttributeHandler(), outputDefinitionElementHandler(), noValueHandler());
}
protected InterceptFromDefinition doParseInterceptFromDefinition() throws IOException, XmlPullParserException {
return doParse(new InterceptFromDefinition(), (def, key, val) -> {
if ("uri".equals(key)) {
def.setUri(val);
return true;
}
return processorDefinitionAttributeHandler().accept(def, key, val);
}, outputDefinitionElementHandler(), noValueHandler());
}
protected InterceptSendToEndpointDefinition doParseInterceptSendToEndpointDefinition() throws IOException, XmlPullParserException {
return doParse(new InterceptSendToEndpointDefinition(), (def, key, val) -> {
switch (key) {
case "afterUri": def.setAfterUri(val); break;
case "skipSendToOriginalEndpoint": def.setSkipSendToOriginalEndpoint(val); break;
case "uri": def.setUri(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, outputDefinitionElementHandler(), noValueHandler());
}
protected KameletDefinition doParseKameletDefinition() throws IOException, XmlPullParserException {
return doParse(new KameletDefinition(), (def, key, val) -> {
if ("name".equals(key)) {
def.setName(val);
return true;
}
return processorDefinitionAttributeHandler().accept(def, key, val);
}, outputDefinitionElementHandler(), noValueHandler());
}
protected LoadBalanceDefinition doParseLoadBalanceDefinition() throws IOException, XmlPullParserException {
return doParse(new LoadBalanceDefinition(),
processorDefinitionAttributeHandler(), (def, key) -> {
switch (key) {
case "failover": def.setLoadBalancerType(doParseFailoverLoadBalancerDefinition()); break;
case "random": def.setLoadBalancerType(doParseRandomLoadBalancerDefinition()); break;
case "customLoadBalancer": def.setLoadBalancerType(doParseCustomLoadBalancerDefinition()); break;
case "roundRobin": def.setLoadBalancerType(doParseRoundRobinLoadBalancerDefinition()); break;
case "sticky": def.setLoadBalancerType(doParseStickyLoadBalancerDefinition()); break;
case "topic": def.setLoadBalancerType(doParseTopicLoadBalancerDefinition()); break;
case "weighted": def.setLoadBalancerType(doParseWeightedLoadBalancerDefinition()); break;
default: return outputDefinitionElementHandler().accept(def, key);
}
return true;
}, noValueHandler());
}
protected LoadBalancerDefinition doParseLoadBalancerDefinition() throws IOException, XmlPullParserException {
return doParse(new LoadBalancerDefinition(),
identifiedTypeAttributeHandler(), noElementHandler(), noValueHandler());
}
protected LogDefinition doParseLogDefinition() throws IOException, XmlPullParserException {
return doParse(new LogDefinition(), (def, key, val) -> {
switch (key) {
case "logName": def.setLogName(val); break;
case "loggerRef": def.setLoggerRef(val); break;
case "loggingLevel": def.setLoggingLevel(val); break;
case "marker": def.setMarker(val); break;
case "message": def.setMessage(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected LoopDefinition doParseLoopDefinition() throws IOException, XmlPullParserException {
return doParse(new LoopDefinition(), (def, key, val) -> {
switch (key) {
case "breakOnShutdown": def.setBreakOnShutdown(val); break;
case "copy": def.setCopy(val); break;
case "doWhile": def.setDoWhile(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, outputExpressionNodeElementHandler(), noValueHandler());
}
protected MarshalDefinition doParseMarshalDefinition() throws IOException, XmlPullParserException {
return doParse(new MarshalDefinition(),
processorDefinitionAttributeHandler(), (def, key) -> {
DataFormatDefinition v = doParseDataFormatDefinitionRef(key);
if (v != null) {
def.setDataFormatType(v);
return true;
}
return optionalIdentifiedDefinitionElementHandler().accept(def, key);
}, noValueHandler());
}
protected MulticastDefinition doParseMulticastDefinition() throws IOException, XmlPullParserException {
return doParse(new MulticastDefinition(), (def, key, val) -> {
switch (key) {
case "executorServiceRef": def.setExecutorServiceRef(val); break;
case "onPrepareRef": def.setOnPrepareRef(val); break;
case "parallelAggregate": def.setParallelAggregate(val); break;
case "parallelProcessing": def.setParallelProcessing(val); break;
case "shareUnitOfWork": def.setShareUnitOfWork(val); break;
case "stopOnAggregateException": def.setStopOnAggregateException(val); break;
case "stopOnException": def.setStopOnException(val); break;
case "strategyMethodAllowNull": def.setStrategyMethodAllowNull(val); break;
case "strategyMethodName": def.setStrategyMethodName(val); break;
case "strategyRef": def.setStrategyRef(val); break;
case "streaming": def.setStreaming(val); break;
case "timeout": def.setTimeout(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, outputDefinitionElementHandler(), noValueHandler());
}
protected OnCompletionDefinition doParseOnCompletionDefinition() throws IOException, XmlPullParserException {
return doParse(new OnCompletionDefinition(), (def, key, val) -> {
switch (key) {
case "executorServiceRef": def.setExecutorServiceRef(val); break;
case "mode": def.setMode(val); break;
case "onCompleteOnly": def.setOnCompleteOnly(val); break;
case "onFailureOnly": def.setOnFailureOnly(val); break;
case "parallelProcessing": def.setParallelProcessing(val); break;
case "useOriginalMessage": def.setUseOriginalMessage(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, (def, key) -> {
if ("onWhen".equals(key)) {
def.setOnWhen(doParseWhenDefinition());
return true;
}
return outputDefinitionElementHandler().accept(def, key);
}, noValueHandler());
}
protected OnExceptionDefinition doParseOnExceptionDefinition() throws IOException, XmlPullParserException {
return doParse(new OnExceptionDefinition(), (def, key, val) -> {
switch (key) {
case "onExceptionOccurredRef": def.setOnExceptionOccurredRef(val); break;
case "onRedeliveryRef": def.setOnRedeliveryRef(val); break;
case "redeliveryPolicyRef": def.setRedeliveryPolicyRef(val); break;
case "useOriginalBody": def.setUseOriginalBody(val); break;
case "useOriginalMessage": def.setUseOriginalMessage(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, (def, key) -> {
switch (key) {
case "continued": def.setContinued(doParseExpressionSubElementDefinition()); break;
case "exception": doAdd(doParseText(), def.getExceptions(), def::setExceptions); break;
case "handled": def.setHandled(doParseExpressionSubElementDefinition()); break;
case "onWhen": def.setOnWhen(doParseWhenDefinition()); break;
case "redeliveryPolicy": def.setRedeliveryPolicyType(doParseRedeliveryPolicyDefinition()); break;
case "retryWhile": def.setRetryWhile(doParseExpressionSubElementDefinition()); break;
default: return outputDefinitionElementHandler().accept(def, key);
}
return true;
}, noValueHandler());
}
protected RedeliveryPolicyDefinition doParseRedeliveryPolicyDefinition() throws IOException, XmlPullParserException {
return doParse(new RedeliveryPolicyDefinition(), (def, key, val) -> {
switch (key) {
case "allowRedeliveryWhileStopping": def.setAllowRedeliveryWhileStopping(val); break;
case "asyncDelayedRedelivery": def.setAsyncDelayedRedelivery(val); break;
case "backOffMultiplier": def.setBackOffMultiplier(val); break;
case "collisionAvoidanceFactor": def.setCollisionAvoidanceFactor(val); break;
case "delayPattern": def.setDelayPattern(val); break;
case "disableRedelivery": def.setDisableRedelivery(val); break;
case "exchangeFormatterRef": def.setExchangeFormatterRef(val); break;
case "logContinued": def.setLogContinued(val); break;
case "logExhausted": def.setLogExhausted(val); break;
case "logExhaustedMessageBody": def.setLogExhaustedMessageBody(val); break;
case "logExhaustedMessageHistory": def.setLogExhaustedMessageHistory(val); break;
case "logHandled": def.setLogHandled(val); break;
case "logNewException": def.setLogNewException(val); break;
case "logRetryAttempted": def.setLogRetryAttempted(val); break;
case "logRetryStackTrace": def.setLogRetryStackTrace(val); break;
case "logStackTrace": def.setLogStackTrace(val); break;
case "maximumRedeliveries": def.setMaximumRedeliveries(val); break;
case "maximumRedeliveryDelay": def.setMaximumRedeliveryDelay(val); break;
case "redeliveryDelay": def.setRedeliveryDelay(val); break;
case "retriesExhaustedLogLevel": def.setRetriesExhaustedLogLevel(val); break;
case "retryAttemptedLogInterval": def.setRetryAttemptedLogInterval(val); break;
case "retryAttemptedLogLevel": def.setRetryAttemptedLogLevel(val); break;
case "useCollisionAvoidance": def.setUseCollisionAvoidance(val); break;
case "useExponentialBackOff": def.setUseExponentialBackOff(val); break;
default: return false;
}
return true;
}, noElementHandler(), noValueHandler());
}
protected OnFallbackDefinition doParseOnFallbackDefinition() throws IOException, XmlPullParserException {
return doParse(new OnFallbackDefinition(), (def, key, val) -> {
if ("fallbackViaNetwork".equals(key)) {
def.setFallbackViaNetwork(val);
return true;
}
return processorDefinitionAttributeHandler().accept(def, key, val);
}, outputDefinitionElementHandler(), noValueHandler());
}
protected OutputTypeDefinition doParseOutputTypeDefinition() throws IOException, XmlPullParserException {
return doParse(new OutputTypeDefinition(), (def, key, val) -> {
switch (key) {
case "urn": def.setUrn(val); break;
case "validate": def.setValidate(val); break;
default: return optionalIdentifiedDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected PackageScanDefinition doParsePackageScanDefinition() throws IOException, XmlPullParserException {
return doParse(new PackageScanDefinition(),
noAttributeHandler(), (def, key) -> {
switch (key) {
case "excludes": doAdd(doParseText(), def.getExcludes(), def::setExcludes); break;
case "includes": doAdd(doParseText(), def.getIncludes(), def::setIncludes); break;
case "package": doAdd(doParseText(), def.getPackages(), def::setPackages); break;
default: return false;
}
return true;
}, noValueHandler());
}
protected PipelineDefinition doParsePipelineDefinition() throws IOException, XmlPullParserException {
return doParse(new PipelineDefinition(),
processorDefinitionAttributeHandler(), outputDefinitionElementHandler(), noValueHandler());
}
protected PolicyDefinition doParsePolicyDefinition() throws IOException, XmlPullParserException {
return doParse(new PolicyDefinition(), (def, key, val) -> {
if ("ref".equals(key)) {
def.setRef(val);
return true;
}
return processorDefinitionAttributeHandler().accept(def, key, val);
}, outputDefinitionElementHandler(), noValueHandler());
}
protected PollEnrichDefinition doParsePollEnrichDefinition() throws IOException, XmlPullParserException {
return doParse(new PollEnrichDefinition(), (def, key, val) -> {
switch (key) {
case "aggregateOnException": def.setAggregateOnException(val); break;
case "cacheSize": def.setCacheSize(val); break;
case "ignoreInvalidEndpoint": def.setIgnoreInvalidEndpoint(val); break;
case "strategyMethodAllowNull": def.setAggregationStrategyMethodAllowNull(val); break;
case "strategyMethodName": def.setAggregationStrategyMethodName(val); break;
case "strategyRef": def.setAggregationStrategyRef(val); break;
case "timeout": def.setTimeout(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, expressionNodeElementHandler(), noValueHandler());
}
protected ProcessDefinition doParseProcessDefinition() throws IOException, XmlPullParserException {
return doParse(new ProcessDefinition(), (def, key, val) -> {
if ("ref".equals(key)) {
def.setRef(val);
return true;
}
return processorDefinitionAttributeHandler().accept(def, key, val);
}, optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected PropertyDefinition doParsePropertyDefinition() throws IOException, XmlPullParserException {
return doParse(new PropertyDefinition(), (def, key, val) -> {
switch (key) {
case "key": def.setKey(val); break;
case "value": def.setValue(val); break;
default: return false;
}
return true;
}, noElementHandler(), noValueHandler());
}
protected PropertyDefinitions doParsePropertyDefinitions() throws IOException, XmlPullParserException {
return doParse(new PropertyDefinitions(),
noAttributeHandler(), (def, key) -> {
if ("properties".equals(key)) {
doAdd(doParsePropertyDefinition(), def.getProperties(), def::setProperties);
return true;
}
return false;
}, noValueHandler());
}
protected PropertyExpressionDefinition doParsePropertyExpressionDefinition() throws IOException, XmlPullParserException {
return doParse(new PropertyExpressionDefinition(), (def, key, val) -> {
if ("key".equals(key)) {
def.setKey(val);
return true;
}
return false;
}, (def, key) -> {
ExpressionDefinition v = doParseExpressionDefinitionRef(key);
if (v != null) {
def.setExpression(v);
return true;
}
return false;
}, noValueHandler());
}
protected RecipientListDefinition doParseRecipientListDefinition() throws IOException, XmlPullParserException {
return doParse(new RecipientListDefinition(), (def, key, val) -> {
switch (key) {
case "cacheSize": def.setCacheSize(val); break;
case "delimiter": def.setDelimiter(val); break;
case "executorServiceRef": def.setExecutorServiceRef(val); break;
case "ignoreInvalidEndpoints": def.setIgnoreInvalidEndpoints(val); break;
case "onPrepareRef": def.setOnPrepareRef(val); break;
case "parallelAggregate": def.setParallelAggregate(val); break;
case "parallelProcessing": def.setParallelProcessing(val); break;
case "shareUnitOfWork": def.setShareUnitOfWork(val); break;
case "stopOnAggregateException": def.setStopOnAggregateException(val); break;
case "stopOnException": def.setStopOnException(val); break;
case "strategyMethodAllowNull": def.setStrategyMethodAllowNull(val); break;
case "strategyMethodName": def.setStrategyMethodName(val); break;
case "strategyRef": def.setStrategyRef(val); break;
case "streaming": def.setStreaming(val); break;
case "timeout": def.setTimeout(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, expressionNodeElementHandler(), noValueHandler());
}
protected RemoveHeaderDefinition doParseRemoveHeaderDefinition() throws IOException, XmlPullParserException {
return doParse(new RemoveHeaderDefinition(), (def, key, val) -> {
if ("name".equals(key)) {
def.setName(val);
return true;
}
return processorDefinitionAttributeHandler().accept(def, key, val);
}, optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected RemoveHeadersDefinition doParseRemoveHeadersDefinition() throws IOException, XmlPullParserException {
return doParse(new RemoveHeadersDefinition(), (def, key, val) -> {
switch (key) {
case "excludePattern": def.setExcludePattern(val); break;
case "pattern": def.setPattern(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected RemovePropertiesDefinition doParseRemovePropertiesDefinition() throws IOException, XmlPullParserException {
return doParse(new RemovePropertiesDefinition(), (def, key, val) -> {
switch (key) {
case "excludePattern": def.setExcludePattern(val); break;
case "pattern": def.setPattern(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected RemovePropertyDefinition doParseRemovePropertyDefinition() throws IOException, XmlPullParserException {
return doParse(new RemovePropertyDefinition(), (def, key, val) -> {
if ("name".equals(key)) {
def.setName(val);
return true;
}
return processorDefinitionAttributeHandler().accept(def, key, val);
}, optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected ResequenceDefinition doParseResequenceDefinition() throws IOException, XmlPullParserException {
return doParse(new ResequenceDefinition(),
processorDefinitionAttributeHandler(), (def, key) -> {
switch (key) {
case "batch-config": def.setResequencerConfig(doParseBatchResequencerConfig()); break;
case "stream-config": def.setResequencerConfig(doParseStreamResequencerConfig()); break;
default:
ExpressionDefinition v = doParseExpressionDefinitionRef(key);
if (v != null) {
def.setExpression(v);
return true;
}
return outputDefinitionElementHandler().accept(def, key);
}
return true;
}, noValueHandler());
}
protected <T extends Resilience4jConfigurationCommon> AttributeHandler<T> resilience4jConfigurationCommonAttributeHandler() {
return (def, key, val) -> {
switch (key) {
case "automaticTransitionFromOpenToHalfOpenEnabled": def.setAutomaticTransitionFromOpenToHalfOpenEnabled(val); break;
case "circuitBreakerRef": def.setCircuitBreakerRef(val); break;
case "configRef": def.setConfigRef(val); break;
case "failureRateThreshold": def.setFailureRateThreshold(val); break;
case "minimumNumberOfCalls": def.setMinimumNumberOfCalls(val); break;
case "permittedNumberOfCallsInHalfOpenState": def.setPermittedNumberOfCallsInHalfOpenState(val); break;
case "slidingWindowSize": def.setSlidingWindowSize(val); break;
case "slidingWindowType": def.setSlidingWindowType(val); break;
case "slowCallDurationThreshold": def.setSlowCallDurationThreshold(val); break;
case "slowCallRateThreshold": def.setSlowCallRateThreshold(val); break;
case "waitDurationInOpenState": def.setWaitDurationInOpenState(val); break;
case "writableStackTraceEnabled": def.setWritableStackTraceEnabled(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
};
}
protected <T extends Resilience4jConfigurationCommon> ElementHandler<T> resilience4jConfigurationCommonElementHandler() {
return (def, key) -> {
switch (key) {
case "bulkheadEnabled": def.setBulkheadEnabled(doParseText()); break;
case "bulkheadMaxConcurrentCalls": def.setBulkheadMaxConcurrentCalls(doParseText()); break;
case "bulkheadMaxWaitDuration": def.setBulkheadMaxWaitDuration(doParseText()); break;
case "timeoutCancelRunningFuture": def.setTimeoutCancelRunningFuture(doParseText()); break;
case "timeoutDuration": def.setTimeoutDuration(doParseText()); break;
case "timeoutEnabled": def.setTimeoutEnabled(doParseText()); break;
case "timeoutExecutorServiceRef": def.setTimeoutExecutorServiceRef(doParseText()); break;
default: return false;
}
return true;
};
}
protected Resilience4jConfigurationCommon doParseResilience4jConfigurationCommon() throws IOException, XmlPullParserException {
return doParse(new Resilience4jConfigurationCommon(), resilience4jConfigurationCommonAttributeHandler(), resilience4jConfigurationCommonElementHandler(), noValueHandler());
}
protected RestContextRefDefinition doParseRestContextRefDefinition() throws IOException, XmlPullParserException {
return doParse(new RestContextRefDefinition(), (def, key, val) -> {
if ("ref".equals(key)) {
def.setRef(val);
return true;
}
return false;
}, noElementHandler(), noValueHandler());
}
protected RollbackDefinition doParseRollbackDefinition() throws IOException, XmlPullParserException {
return doParse(new RollbackDefinition(), (def, key, val) -> {
switch (key) {
case "markRollbackOnly": def.setMarkRollbackOnly(val); break;
case "markRollbackOnlyLast": def.setMarkRollbackOnlyLast(val); break;
case "message": def.setMessage(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected RouteBuilderDefinition doParseRouteBuilderDefinition() throws IOException, XmlPullParserException {
return doParse(new RouteBuilderDefinition(), (def, key, val) -> {
if ("ref".equals(key)) {
def.setRef(val);
return true;
}
return identifiedTypeAttributeHandler().accept(def, key, val);
}, noElementHandler(), noValueHandler());
}
protected RouteConfigurationContextRefDefinition doParseRouteConfigurationContextRefDefinition() throws IOException, XmlPullParserException {
return doParse(new RouteConfigurationContextRefDefinition(), (def, key, val) -> {
if ("ref".equals(key)) {
def.setRef(val);
return true;
}
return false;
}, noElementHandler(), noValueHandler());
}
protected RouteConfigurationDefinition doParseRouteConfigurationDefinition() throws IOException, XmlPullParserException {
return doParse(new RouteConfigurationDefinition(),
optionalIdentifiedDefinitionAttributeHandler(), (def, key) -> {
switch (key) {
case "interceptFrom": doAdd(doParseInterceptFromDefinition(), def.getInterceptFroms(), def::setInterceptFroms); break;
case "interceptSendToEndpoint": doAdd(doParseInterceptSendToEndpointDefinition(), def.getInterceptSendTos(), def::setInterceptSendTos); break;
case "intercept": doAdd(doParseInterceptDefinition(), def.getIntercepts(), def::setIntercepts); break;
case "onCompletion": doAdd(doParseOnCompletionDefinition(), def.getOnCompletions(), def::setOnCompletions); break;
case "onException": doAdd(doParseOnExceptionDefinition(), def.getOnExceptions(), def::setOnExceptions); break;
default: return optionalIdentifiedDefinitionElementHandler().accept(def, key);
}
return true;
}, noValueHandler());
}
public Optional<RouteConfigurationsDefinition> parseRouteConfigurationsDefinition()
throws IOException, XmlPullParserException {
String tag = getNextTag("routeConfigurations", "routeConfiguration");
if (tag != null) {
switch (tag) {
case "routeConfigurations" : return Optional.of(doParseRouteConfigurationsDefinition());
case "routeConfiguration" : return parseSingleRouteConfigurationsDefinition();
}
}
return Optional.empty();
}
private Optional<RouteConfigurationsDefinition> parseSingleRouteConfigurationsDefinition()
throws IOException, XmlPullParserException {
Optional<RouteConfigurationDefinition> single = Optional.of(doParseRouteConfigurationDefinition());
if (single.isPresent()) {
List<RouteConfigurationDefinition> list = new ArrayList<>();
list.add(single.get());
RouteConfigurationsDefinition def = new RouteConfigurationsDefinition();
def.setRouteConfigurations(list);
return Optional.of(def);
}
return Optional.empty();
}
protected RouteConfigurationsDefinition doParseRouteConfigurationsDefinition() throws IOException, XmlPullParserException {
return doParse(new RouteConfigurationsDefinition(),
noAttributeHandler(), (def, key) -> {
if ("routeConfiguration".equals(key)) {
doAdd(doParseRouteConfigurationDefinition(), def.getRouteConfigurations(), def::setRouteConfigurations);
return true;
}
return false;
}, noValueHandler());
}
protected RouteContextRefDefinition doParseRouteContextRefDefinition() throws IOException, XmlPullParserException {
return doParse(new RouteContextRefDefinition(), (def, key, val) -> {
if ("ref".equals(key)) {
def.setRef(val);
return true;
}
return false;
}, noElementHandler(), noValueHandler());
}
protected RouteDefinition doParseRouteDefinition() throws IOException, XmlPullParserException {
return doParse(new RouteDefinition(), (def, key, val) -> {
switch (key) {
case "autoStartup": def.setAutoStartup(val); break;
case "delayer": def.setDelayer(val); break;
case "errorHandlerRef": def.setErrorHandlerRef(val); break;
case "group": def.setGroup(val); break;
case "logMask": def.setLogMask(val); break;
case "messageHistory": def.setMessageHistory(val); break;
case "routeConfigurationId": def.setRouteConfigurationId(val); break;
case "routePolicyRef": def.setRoutePolicyRef(val); break;
case "shutdownRoute": def.setShutdownRoute(val); break;
case "shutdownRunningTask": def.setShutdownRunningTask(val); break;
case "startupOrder": def.setStartupOrder(Integer.valueOf(val)); break;
case "streamCache": def.setStreamCache(val); break;
case "trace": def.setTrace(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, (def, key) -> {
switch (key) {
case "from": def.setInput(doParseFromDefinition()); break;
case "inputType": def.setInputType(doParseInputTypeDefinition()); break;
case "outputType": def.setOutputType(doParseOutputTypeDefinition()); break;
case "rest": def.setRest(Boolean.valueOf(doParseText())); break;
case "routeProperty": doAdd(doParsePropertyDefinition(), def.getRouteProperties(), def::setRouteProperties); break;
case "template": def.setTemplate(Boolean.valueOf(doParseText())); break;
default: return outputDefinitionElementHandler().accept(def, key);
}
return true;
}, noValueHandler());
}
protected RestDefinition doParseRestDefinition() throws IOException, XmlPullParserException {
return doParse(new RestDefinition(), (def, key, val) -> {
switch (key) {
case "apiDocs": def.setApiDocs(val); break;
case "bindingMode": def.setBindingMode(val); break;
case "clientRequestValidation": def.setClientRequestValidation(val); break;
case "consumes": def.setConsumes(val); break;
case "enableCORS": def.setEnableCORS(val); break;
case "path": def.setPath(val); break;
case "produces": def.setProduces(val); break;
case "skipBindingOnErrorCode": def.setSkipBindingOnErrorCode(val); break;
case "tag": def.setTag(val); break;
default: return optionalIdentifiedDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, (def, key) -> {
switch (key) {
case "delete": doAdd(doParseDeleteDefinition(), def.getVerbs(), def::setVerbs); break;
case "get": doAdd(doParseGetDefinition(), def.getVerbs(), def::setVerbs); break;
case "head": doAdd(doParseHeadDefinition(), def.getVerbs(), def::setVerbs); break;
case "patch": doAdd(doParsePatchDefinition(), def.getVerbs(), def::setVerbs); break;
case "post": doAdd(doParsePostDefinition(), def.getVerbs(), def::setVerbs); break;
case "put": doAdd(doParsePutDefinition(), def.getVerbs(), def::setVerbs); break;
case "securityDefinitions": def.setSecurityDefinitions(doParseRestSecuritiesDefinition()); break;
case "securityRequirements": def.setSecurityRequirements(doParseRestSecuritiesRequirement()); break;
default: return optionalIdentifiedDefinitionElementHandler().accept(def, key);
}
return true;
}, noValueHandler());
}
protected RestBindingDefinition doParseRestBindingDefinition() throws IOException, XmlPullParserException {
return doParse(new RestBindingDefinition(), (def, key, val) -> {
switch (key) {
case "bindingMode": def.setBindingMode(val); break;
case "clientRequestValidation": def.setClientRequestValidation(val); break;
case "component": def.setComponent(val); break;
case "consumes": def.setConsumes(val); break;
case "enableCORS": def.setEnableCORS(val); break;
case "outType": def.setOutType(val); break;
case "produces": def.setProduces(val); break;
case "skipBindingOnErrorCode": def.setSkipBindingOnErrorCode(val); break;
case "type": def.setType(val); break;
default: return optionalIdentifiedDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected RouteTemplateBeanDefinition doParseRouteTemplateBeanDefinition() throws IOException, XmlPullParserException {
return doParse(new RouteTemplateBeanDefinition(),
beanFactoryDefinitionAttributeHandler(), beanFactoryDefinitionElementHandler(), noValueHandler());
}
protected <T extends BeanFactoryDefinition> AttributeHandler<T> beanFactoryDefinitionAttributeHandler() {
return (def, key, val) -> {
switch (key) {
case "beanType": def.setBeanType(val); break;
case "name": def.setName(val); break;
case "type": def.setType(val); break;
default: return false;
}
return true;
};
}
protected <T extends BeanFactoryDefinition> ElementHandler<T> beanFactoryDefinitionElementHandler() {
return (def, key) -> {
switch (key) {
case "property": doAdd(doParsePropertyDefinition(), def.getProperties(), def::setProperties); break;
case "script": def.setScript(doParseText()); break;
default: return false;
}
return true;
};
}
protected RouteTemplateContextRefDefinition doParseRouteTemplateContextRefDefinition() throws IOException, XmlPullParserException {
return doParse(new RouteTemplateContextRefDefinition(), (def, key, val) -> {
if ("ref".equals(key)) {
def.setRef(val);
return true;
}
return false;
}, noElementHandler(), noValueHandler());
}
protected RouteTemplateDefinition doParseRouteTemplateDefinition() throws IOException, XmlPullParserException {
return doParse(new RouteTemplateDefinition(),
optionalIdentifiedDefinitionAttributeHandler(), (def, key) -> {
switch (key) {
case "route": def.setRoute(doParseRouteDefinition()); break;
case "templateBean": doAdd(doParseRouteTemplateBeanDefinition(), def.getTemplateBeans(), def::setTemplateBeans); break;
case "templateParameter": doAdd(doParseRouteTemplateParameterDefinition(), def.getTemplateParameters(), def::setTemplateParameters); break;
default: return optionalIdentifiedDefinitionElementHandler().accept(def, key);
}
return true;
}, noValueHandler());
}
protected RouteTemplateParameterDefinition doParseRouteTemplateParameterDefinition() throws IOException, XmlPullParserException {
return doParse(new RouteTemplateParameterDefinition(), (def, key, val) -> {
switch (key) {
case "defaultValue": def.setDefaultValue(val); break;
case "description": def.setDescription(val); break;
case "name": def.setName(val); break;
case "required": def.setRequired(Boolean.valueOf(val)); break;
default: return false;
}
return true;
}, noElementHandler(), noValueHandler());
}
public Optional<RouteTemplatesDefinition> parseRouteTemplatesDefinition()
throws IOException, XmlPullParserException {
String tag = getNextTag("routeTemplates", "routeTemplate");
if (tag != null) {
switch (tag) {
case "routeTemplates" : return Optional.of(doParseRouteTemplatesDefinition());
case "routeTemplate" : return parseSingleRouteTemplatesDefinition();
}
}
return Optional.empty();
}
private Optional<RouteTemplatesDefinition> parseSingleRouteTemplatesDefinition()
throws IOException, XmlPullParserException {
Optional<RouteTemplateDefinition> single = Optional.of(doParseRouteTemplateDefinition());
if (single.isPresent()) {
List<RouteTemplateDefinition> list = new ArrayList<>();
list.add(single.get());
RouteTemplatesDefinition def = new RouteTemplatesDefinition();
def.setRouteTemplates(list);
return Optional.of(def);
}
return Optional.empty();
}
protected RouteTemplatesDefinition doParseRouteTemplatesDefinition() throws IOException, XmlPullParserException {
return doParse(new RouteTemplatesDefinition(),
optionalIdentifiedDefinitionAttributeHandler(), (def, key) -> {
if ("routeTemplate".equals(key)) {
doAdd(doParseRouteTemplateDefinition(), def.getRouteTemplates(), def::setRouteTemplates);
return true;
}
return optionalIdentifiedDefinitionElementHandler().accept(def, key);
}, noValueHandler());
}
public Optional<RoutesDefinition> parseRoutesDefinition()
throws IOException, XmlPullParserException {
String tag = getNextTag("routes", "route");
if (tag != null) {
switch (tag) {
case "routes" : return Optional.of(doParseRoutesDefinition());
case "route" : return parseSingleRoutesDefinition();
}
}
return Optional.empty();
}
private Optional<RoutesDefinition> parseSingleRoutesDefinition()
throws IOException, XmlPullParserException {
Optional<RouteDefinition> single = Optional.of(doParseRouteDefinition());
if (single.isPresent()) {
List<RouteDefinition> list = new ArrayList<>();
list.add(single.get());
RoutesDefinition def = new RoutesDefinition();
def.setRoutes(list);
return Optional.of(def);
}
return Optional.empty();
}
protected RoutesDefinition doParseRoutesDefinition() throws IOException, XmlPullParserException {
return doParse(new RoutesDefinition(),
optionalIdentifiedDefinitionAttributeHandler(), (def, key) -> {
if ("route".equals(key)) {
doAdd(doParseRouteDefinition(), def.getRoutes(), def::setRoutes);
return true;
}
return optionalIdentifiedDefinitionElementHandler().accept(def, key);
}, noValueHandler());
}
protected RoutingSlipDefinition doParseRoutingSlipDefinition() throws IOException, XmlPullParserException {
return doParse(new RoutingSlipDefinition(), (def, key, val) -> {
switch (key) {
case "cacheSize": def.setCacheSize(val); break;
case "ignoreInvalidEndpoints": def.setIgnoreInvalidEndpoints(val); break;
case "uriDelimiter": def.setUriDelimiter(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, expressionNodeElementHandler(), noValueHandler());
}
protected SagaDefinition doParseSagaDefinition() throws IOException, XmlPullParserException {
return doParse(new SagaDefinition(), (def, key, val) -> {
switch (key) {
case "completionMode": def.setCompletionMode(val); break;
case "propagation": def.setPropagation(val); break;
case "sagaServiceRef": def.setSagaServiceRef(val); break;
case "timeout": def.setTimeout(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, (def, key) -> {
switch (key) {
case "compensation": def.setCompensation(doParseSagaActionUriDefinition()); break;
case "completion": def.setCompletion(doParseSagaActionUriDefinition()); break;
case "option": doAdd(doParsePropertyExpressionDefinition(), def.getOptions(), def::setOptions); break;
default: return outputDefinitionElementHandler().accept(def, key);
}
return true;
}, noValueHandler());
}
protected SagaActionUriDefinition doParseSagaActionUriDefinition() throws IOException, XmlPullParserException {
return doParse(new SagaActionUriDefinition(),
sendDefinitionAttributeHandler(), optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected SamplingDefinition doParseSamplingDefinition() throws IOException, XmlPullParserException {
return doParse(new SamplingDefinition(), (def, key, val) -> {
switch (key) {
case "messageFrequency": def.setMessageFrequency(val); break;
case "samplePeriod": def.setSamplePeriod(val); break;
case "units": def.setUnits(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected ScriptDefinition doParseScriptDefinition() throws IOException, XmlPullParserException {
return doParse(new ScriptDefinition(),
processorDefinitionAttributeHandler(), expressionNodeElementHandler(), noValueHandler());
}
protected SetBodyDefinition doParseSetBodyDefinition() throws IOException, XmlPullParserException {
return doParse(new SetBodyDefinition(),
processorDefinitionAttributeHandler(), expressionNodeElementHandler(), noValueHandler());
}
protected SetExchangePatternDefinition doParseSetExchangePatternDefinition() throws IOException, XmlPullParserException {
return doParse(new SetExchangePatternDefinition(), (def, key, val) -> {
if ("pattern".equals(key)) {
def.setPattern(val);
return true;
}
return processorDefinitionAttributeHandler().accept(def, key, val);
}, optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected SetHeaderDefinition doParseSetHeaderDefinition() throws IOException, XmlPullParserException {
return doParse(new SetHeaderDefinition(), (def, key, val) -> {
if ("name".equals(key)) {
def.setName(val);
return true;
}
return processorDefinitionAttributeHandler().accept(def, key, val);
}, expressionNodeElementHandler(), noValueHandler());
}
protected SetPropertyDefinition doParseSetPropertyDefinition() throws IOException, XmlPullParserException {
return doParse(new SetPropertyDefinition(), (def, key, val) -> {
if ("name".equals(key)) {
def.setName(val);
return true;
}
return processorDefinitionAttributeHandler().accept(def, key, val);
}, expressionNodeElementHandler(), noValueHandler());
}
protected SortDefinition doParseSortDefinition() throws IOException, XmlPullParserException {
return doParse(new SortDefinition(), (def, key, val) -> {
if ("comparatorRef".equals(key)) {
def.setComparatorRef(val);
return true;
}
return processorDefinitionAttributeHandler().accept(def, key, val);
}, expressionNodeElementHandler(), noValueHandler());
}
protected SplitDefinition doParseSplitDefinition() throws IOException, XmlPullParserException {
return doParse(new SplitDefinition(), (def, key, val) -> {
switch (key) {
case "delimiter": def.setDelimiter(val); break;
case "executorServiceRef": def.setExecutorServiceRef(val); break;
case "onPrepareRef": def.setOnPrepareRef(val); break;
case "parallelAggregate": def.setParallelAggregate(val); break;
case "parallelProcessing": def.setParallelProcessing(val); break;
case "shareUnitOfWork": def.setShareUnitOfWork(val); break;
case "stopOnAggregateException": def.setStopOnAggregateException(val); break;
case "stopOnException": def.setStopOnException(val); break;
case "strategyMethodAllowNull": def.setStrategyMethodAllowNull(val); break;
case "strategyMethodName": def.setStrategyMethodName(val); break;
case "strategyRef": def.setStrategyRef(val); break;
case "streaming": def.setStreaming(val); break;
case "timeout": def.setTimeout(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, outputExpressionNodeElementHandler(), noValueHandler());
}
protected StepDefinition doParseStepDefinition() throws IOException, XmlPullParserException {
return doParse(new StepDefinition(),
processorDefinitionAttributeHandler(), outputDefinitionElementHandler(), noValueHandler());
}
protected StopDefinition doParseStopDefinition() throws IOException, XmlPullParserException {
return doParse(new StopDefinition(),
processorDefinitionAttributeHandler(), optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected SwitchDefinition doParseSwitchDefinition() throws IOException, XmlPullParserException {
return doParse(new SwitchDefinition(),
processorDefinitionAttributeHandler(), choiceDefinitionElementHandler(), noValueHandler());
}
protected TemplatedRouteBeanDefinition doParseTemplatedRouteBeanDefinition() throws IOException, XmlPullParserException {
return doParse(new TemplatedRouteBeanDefinition(),
beanFactoryDefinitionAttributeHandler(), beanFactoryDefinitionElementHandler(), noValueHandler());
}
protected TemplatedRouteDefinition doParseTemplatedRouteDefinition() throws IOException, XmlPullParserException {
return doParse(new TemplatedRouteDefinition(), (def, key, val) -> {
switch (key) {
case "routeId": def.setRouteId(val); break;
case "routeTemplateRef": def.setRouteTemplateRef(val); break;
default: return false;
}
return true;
}, (def, key) -> {
switch (key) {
case "bean": doAdd(doParseTemplatedRouteBeanDefinition(), def.getBeans(), def::setBeans); break;
case "parameter": doAdd(doParseTemplatedRouteParameterDefinition(), def.getParameters(), def::setParameters); break;
default: return false;
}
return true;
}, noValueHandler());
}
protected TemplatedRouteParameterDefinition doParseTemplatedRouteParameterDefinition() throws IOException, XmlPullParserException {
return doParse(new TemplatedRouteParameterDefinition(), (def, key, val) -> {
switch (key) {
case "name": def.setName(val); break;
case "value": def.setValue(val); break;
default: return false;
}
return true;
}, noElementHandler(), noValueHandler());
}
public Optional<TemplatedRoutesDefinition> parseTemplatedRoutesDefinition()
throws IOException, XmlPullParserException {
String tag = getNextTag("templatedRoutes", "templatedRoute");
if (tag != null) {
switch (tag) {
case "templatedRoutes" : return Optional.of(doParseTemplatedRoutesDefinition());
case "templatedRoute" : return parseSingleTemplatedRoutesDefinition();
}
}
return Optional.empty();
}
private Optional<TemplatedRoutesDefinition> parseSingleTemplatedRoutesDefinition()
throws IOException, XmlPullParserException {
Optional<TemplatedRouteDefinition> single = Optional.of(doParseTemplatedRouteDefinition());
if (single.isPresent()) {
List<TemplatedRouteDefinition> list = new ArrayList<>();
list.add(single.get());
TemplatedRoutesDefinition def = new TemplatedRoutesDefinition();
def.setTemplatedRoutes(list);
return Optional.of(def);
}
return Optional.empty();
}
protected TemplatedRoutesDefinition doParseTemplatedRoutesDefinition() throws IOException, XmlPullParserException {
return doParse(new TemplatedRoutesDefinition(),
optionalIdentifiedDefinitionAttributeHandler(), (def, key) -> {
if ("templatedRoute".equals(key)) {
doAdd(doParseTemplatedRouteDefinition(), def.getTemplatedRoutes(), def::setTemplatedRoutes);
return true;
}
return optionalIdentifiedDefinitionElementHandler().accept(def, key);
}, noValueHandler());
}
protected ThreadPoolProfileDefinition doParseThreadPoolProfileDefinition() throws IOException, XmlPullParserException {
return doParse(new ThreadPoolProfileDefinition(), (def, key, val) -> {
switch (key) {
case "allowCoreThreadTimeOut": def.setAllowCoreThreadTimeOut(val); break;
case "defaultProfile": def.setDefaultProfile(val); break;
case "keepAliveTime": def.setKeepAliveTime(val); break;
case "maxPoolSize": def.setMaxPoolSize(val); break;
case "maxQueueSize": def.setMaxQueueSize(val); break;
case "poolSize": def.setPoolSize(val); break;
case "rejectedPolicy": def.setRejectedPolicy(val); break;
case "timeUnit": def.setTimeUnit(val); break;
default: return optionalIdentifiedDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected ThreadsDefinition doParseThreadsDefinition() throws IOException, XmlPullParserException {
return doParse(new ThreadsDefinition(), (def, key, val) -> {
switch (key) {
case "allowCoreThreadTimeOut": def.setAllowCoreThreadTimeOut(val); break;
case "callerRunsWhenRejected": def.setCallerRunsWhenRejected(val); break;
case "executorServiceRef": def.setExecutorServiceRef(val); break;
case "keepAliveTime": def.setKeepAliveTime(val); break;
case "maxPoolSize": def.setMaxPoolSize(val); break;
case "maxQueueSize": def.setMaxQueueSize(val); break;
case "poolSize": def.setPoolSize(val); break;
case "rejectedPolicy": def.setRejectedPolicy(val); break;
case "threadName": def.setThreadName(val); break;
case "timeUnit": def.setTimeUnit(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected ThrottleDefinition doParseThrottleDefinition() throws IOException, XmlPullParserException {
return doParse(new ThrottleDefinition(), (def, key, val) -> {
switch (key) {
case "asyncDelayed": def.setAsyncDelayed(val); break;
case "callerRunsWhenRejected": def.setCallerRunsWhenRejected(val); break;
case "executorServiceRef": def.setExecutorServiceRef(val); break;
case "rejectExecution": def.setRejectExecution(val); break;
case "timePeriodMillis": def.setTimePeriodMillis(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, (def, key) -> {
if ("correlationExpression".equals(key)) {
def.setCorrelationExpression(doParseExpressionSubElementDefinition());
return true;
}
return expressionNodeElementHandler().accept(def, key);
}, noValueHandler());
}
protected ThrowExceptionDefinition doParseThrowExceptionDefinition() throws IOException, XmlPullParserException {
return doParse(new ThrowExceptionDefinition(), (def, key, val) -> {
switch (key) {
case "exceptionType": def.setExceptionType(val); break;
case "message": def.setMessage(val); break;
case "ref": def.setRef(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected ToDefinition doParseToDefinition() throws IOException, XmlPullParserException {
return doParse(new ToDefinition(), (def, key, val) -> {
if ("pattern".equals(key)) {
def.setPattern(val);
return true;
}
return sendDefinitionAttributeHandler().accept(def, key, val);
}, optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected <T extends ToDynamicDefinition> AttributeHandler<T> toDynamicDefinitionAttributeHandler() {
return (def, key, val) -> {
switch (key) {
case "allowOptimisedComponents": def.setAllowOptimisedComponents(val); break;
case "autoStartComponents": def.setAutoStartComponents(val); break;
case "cacheSize": def.setCacheSize(val); break;
case "ignoreInvalidEndpoint": def.setIgnoreInvalidEndpoint(val); break;
case "pattern": def.setPattern(val); break;
case "uri": def.setUri(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
};
}
protected ToDynamicDefinition doParseToDynamicDefinition() throws IOException, XmlPullParserException {
return doParse(new ToDynamicDefinition(), toDynamicDefinitionAttributeHandler(), optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected TransactedDefinition doParseTransactedDefinition() throws IOException, XmlPullParserException {
return doParse(new TransactedDefinition(), (def, key, val) -> {
if ("ref".equals(key)) {
def.setRef(val);
return true;
}
return processorDefinitionAttributeHandler().accept(def, key, val);
}, outputDefinitionElementHandler(), noValueHandler());
}
protected TransformDefinition doParseTransformDefinition() throws IOException, XmlPullParserException {
return doParse(new TransformDefinition(),
processorDefinitionAttributeHandler(), expressionNodeElementHandler(), noValueHandler());
}
protected TryDefinition doParseTryDefinition() throws IOException, XmlPullParserException {
return doParse(new TryDefinition(),
processorDefinitionAttributeHandler(), outputDefinitionElementHandler(), noValueHandler());
}
protected UnmarshalDefinition doParseUnmarshalDefinition() throws IOException, XmlPullParserException {
return doParse(new UnmarshalDefinition(),
processorDefinitionAttributeHandler(), (def, key) -> {
DataFormatDefinition v = doParseDataFormatDefinitionRef(key);
if (v != null) {
def.setDataFormatType(v);
return true;
}
return optionalIdentifiedDefinitionElementHandler().accept(def, key);
}, noValueHandler());
}
protected ValidateDefinition doParseValidateDefinition() throws IOException, XmlPullParserException {
return doParse(new ValidateDefinition(), (def, key, val) -> {
if ("predicateExceptionFactory".equals(key)) {
def.setPredicateExceptionFactory(val);
return true;
}
return processorDefinitionAttributeHandler().accept(def, key, val);
}, expressionNodeElementHandler(), noValueHandler());
}
protected WireTapDefinition doParseWireTapDefinition() throws IOException, XmlPullParserException {
return doParse(new WireTapDefinition(), (def, key, val) -> {
switch (key) {
case "copy": def.setCopy(val); break;
case "dynamicUri": def.setDynamicUri(val); break;
case "executorServiceRef": def.setExecutorServiceRef(val); break;
case "onPrepareRef": def.setOnPrepareRef(val); break;
default: return toDynamicDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, optionalIdentifiedDefinitionElementHandler(), noValueHandler());
}
protected BlacklistServiceCallServiceFilterConfiguration doParseBlacklistServiceCallServiceFilterConfiguration() throws IOException, XmlPullParserException {
return doParse(new BlacklistServiceCallServiceFilterConfiguration(),
identifiedTypeAttributeHandler(), (def, key) -> {
if ("servers".equals(key)) {
doAdd(doParseText(), def.getServers(), def::setServers);
return true;
}
return serviceCallConfigurationElementHandler().accept(def, key);
}, noValueHandler());
}
protected ServiceCallServiceFilterConfiguration doParseServiceCallServiceFilterConfiguration() throws IOException, XmlPullParserException {
return doParse(new ServiceCallServiceFilterConfiguration(),
identifiedTypeAttributeHandler(), serviceCallConfigurationElementHandler(), noValueHandler());
}
protected <T extends ServiceCallConfiguration> ElementHandler<T> serviceCallConfigurationElementHandler() {
return (def, key) -> {
if ("properties".equals(key)) {
doAdd(doParsePropertyDefinition(), def.getProperties(), def::setProperties);
return true;
}
return false;
};
}
protected CachingServiceCallServiceDiscoveryConfiguration doParseCachingServiceCallServiceDiscoveryConfiguration() throws IOException, XmlPullParserException {
return doParse(new CachingServiceCallServiceDiscoveryConfiguration(), (def, key, val) -> {
switch (key) {
case "timeout": def.setTimeout(val); break;
case "units": def.setUnits(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, (def, key) -> {
switch (key) {
case "consulServiceDiscovery": def.setServiceDiscoveryConfiguration(doParseConsulServiceCallServiceDiscoveryConfiguration()); break;
case "dnsServiceDiscovery": def.setServiceDiscoveryConfiguration(doParseDnsServiceCallServiceDiscoveryConfiguration()); break;
case "etcdServiceDiscovery": def.setServiceDiscoveryConfiguration(doParseEtcdServiceCallServiceDiscoveryConfiguration()); break;
case "kubernetesServiceDiscovery": def.setServiceDiscoveryConfiguration(doParseKubernetesServiceCallServiceDiscoveryConfiguration()); break;
case "combinedServiceDiscovery": def.setServiceDiscoveryConfiguration(doParseCombinedServiceCallServiceDiscoveryConfiguration()); break;
case "staticServiceDiscovery": def.setServiceDiscoveryConfiguration(doParseStaticServiceCallServiceDiscoveryConfiguration()); break;
default: return serviceCallConfigurationElementHandler().accept(def, key);
}
return true;
}, noValueHandler());
}
protected ServiceCallServiceDiscoveryConfiguration doParseServiceCallServiceDiscoveryConfiguration() throws IOException, XmlPullParserException {
return doParse(new ServiceCallServiceDiscoveryConfiguration(),
identifiedTypeAttributeHandler(), serviceCallConfigurationElementHandler(), noValueHandler());
}
protected CombinedServiceCallServiceDiscoveryConfiguration doParseCombinedServiceCallServiceDiscoveryConfiguration() throws IOException, XmlPullParserException {
return doParse(new CombinedServiceCallServiceDiscoveryConfiguration(),
identifiedTypeAttributeHandler(), (def, key) -> {
switch (key) {
case "consulServiceDiscovery": doAdd(doParseConsulServiceCallServiceDiscoveryConfiguration(), def.getServiceDiscoveryConfigurations(), def::setServiceDiscoveryConfigurations); break;
case "dnsServiceDiscovery": doAdd(doParseDnsServiceCallServiceDiscoveryConfiguration(), def.getServiceDiscoveryConfigurations(), def::setServiceDiscoveryConfigurations); break;
case "etcdServiceDiscovery": doAdd(doParseEtcdServiceCallServiceDiscoveryConfiguration(), def.getServiceDiscoveryConfigurations(), def::setServiceDiscoveryConfigurations); break;
case "kubernetesServiceDiscovery": doAdd(doParseKubernetesServiceCallServiceDiscoveryConfiguration(), def.getServiceDiscoveryConfigurations(), def::setServiceDiscoveryConfigurations); break;
case "staticServiceDiscovery": doAdd(doParseStaticServiceCallServiceDiscoveryConfiguration(), def.getServiceDiscoveryConfigurations(), def::setServiceDiscoveryConfigurations); break;
case "cachingServiceDiscovery": doAdd(doParseCachingServiceCallServiceDiscoveryConfiguration(), def.getServiceDiscoveryConfigurations(), def::setServiceDiscoveryConfigurations); break;
default: return serviceCallConfigurationElementHandler().accept(def, key);
}
return true;
}, noValueHandler());
}
protected CombinedServiceCallServiceFilterConfiguration doParseCombinedServiceCallServiceFilterConfiguration() throws IOException, XmlPullParserException {
return doParse(new CombinedServiceCallServiceFilterConfiguration(),
identifiedTypeAttributeHandler(), (def, key) -> {
switch (key) {
case "blacklistServiceFilter": doAdd(doParseBlacklistServiceCallServiceFilterConfiguration(), def.getServiceFilterConfigurations(), def::setServiceFilterConfigurations); break;
case "customServiceFilter": doAdd(doParseCustomServiceCallServiceFilterConfiguration(), def.getServiceFilterConfigurations(), def::setServiceFilterConfigurations); break;
case "healthyServiceFilter": doAdd(doParseHealthyServiceCallServiceFilterConfiguration(), def.getServiceFilterConfigurations(), def::setServiceFilterConfigurations); break;
case "passThroughServiceFilter": doAdd(doParsePassThroughServiceCallServiceFilterConfiguration(), def.getServiceFilterConfigurations(), def::setServiceFilterConfigurations); break;
default: return serviceCallConfigurationElementHandler().accept(def, key);
}
return true;
}, noValueHandler());
}
protected ConsulServiceCallServiceDiscoveryConfiguration doParseConsulServiceCallServiceDiscoveryConfiguration() throws IOException, XmlPullParserException {
return doParse(new ConsulServiceCallServiceDiscoveryConfiguration(), (def, key, val) -> {
switch (key) {
case "aclToken": def.setAclToken(val); break;
case "blockSeconds": def.setBlockSeconds(val); break;
case "connectTimeoutMillis": def.setConnectTimeoutMillis(val); break;
case "datacenter": def.setDatacenter(val); break;
case "password": def.setPassword(val); break;
case "readTimeoutMillis": def.setReadTimeoutMillis(val); break;
case "url": def.setUrl(val); break;
case "userName": def.setUserName(val); break;
case "writeTimeoutMillis": def.setWriteTimeoutMillis(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, serviceCallConfigurationElementHandler(), noValueHandler());
}
protected CustomServiceCallServiceFilterConfiguration doParseCustomServiceCallServiceFilterConfiguration() throws IOException, XmlPullParserException {
return doParse(new CustomServiceCallServiceFilterConfiguration(), (def, key, val) -> {
if ("ref".equals(key)) {
def.setServiceFilterRef(val);
return true;
}
return identifiedTypeAttributeHandler().accept(def, key, val);
}, serviceCallConfigurationElementHandler(), noValueHandler());
}
protected DefaultServiceCallServiceLoadBalancerConfiguration doParseDefaultServiceCallServiceLoadBalancerConfiguration() throws IOException, XmlPullParserException {
return doParse(new DefaultServiceCallServiceLoadBalancerConfiguration(),
identifiedTypeAttributeHandler(), serviceCallConfigurationElementHandler(), noValueHandler());
}
protected ServiceCallServiceLoadBalancerConfiguration doParseServiceCallServiceLoadBalancerConfiguration() throws IOException, XmlPullParserException {
return doParse(new ServiceCallServiceLoadBalancerConfiguration(),
identifiedTypeAttributeHandler(), serviceCallConfigurationElementHandler(), noValueHandler());
}
protected DnsServiceCallServiceDiscoveryConfiguration doParseDnsServiceCallServiceDiscoveryConfiguration() throws IOException, XmlPullParserException {
return doParse(new DnsServiceCallServiceDiscoveryConfiguration(), (def, key, val) -> {
switch (key) {
case "domain": def.setDomain(val); break;
case "proto": def.setProto(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, serviceCallConfigurationElementHandler(), noValueHandler());
}
protected EtcdServiceCallServiceDiscoveryConfiguration doParseEtcdServiceCallServiceDiscoveryConfiguration() throws IOException, XmlPullParserException {
return doParse(new EtcdServiceCallServiceDiscoveryConfiguration(), (def, key, val) -> {
switch (key) {
case "password": def.setPassword(val); break;
case "servicePath": def.setServicePath(val); break;
case "timeout": def.setTimeout(val); break;
case "type": def.setType(val); break;
case "uris": def.setUris(val); break;
case "userName": def.setUserName(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, serviceCallConfigurationElementHandler(), noValueHandler());
}
protected HealthyServiceCallServiceFilterConfiguration doParseHealthyServiceCallServiceFilterConfiguration() throws IOException, XmlPullParserException {
return doParse(new HealthyServiceCallServiceFilterConfiguration(),
identifiedTypeAttributeHandler(), serviceCallConfigurationElementHandler(), noValueHandler());
}
protected KubernetesServiceCallServiceDiscoveryConfiguration doParseKubernetesServiceCallServiceDiscoveryConfiguration() throws IOException, XmlPullParserException {
return doParse(new KubernetesServiceCallServiceDiscoveryConfiguration(), (def, key, val) -> {
switch (key) {
case "apiVersion": def.setApiVersion(val); break;
case "caCertData": def.setCaCertData(val); break;
case "caCertFile": def.setCaCertFile(val); break;
case "clientCertData": def.setClientCertData(val); break;
case "clientCertFile": def.setClientCertFile(val); break;
case "clientKeyAlgo": def.setClientKeyAlgo(val); break;
case "clientKeyData": def.setClientKeyData(val); break;
case "clientKeyFile": def.setClientKeyFile(val); break;
case "clientKeyPassphrase": def.setClientKeyPassphrase(val); break;
case "dnsDomain": def.setDnsDomain(val); break;
case "lookup": def.setLookup(val); break;
case "masterUrl": def.setMasterUrl(val); break;
case "namespace": def.setNamespace(val); break;
case "oauthToken": def.setOauthToken(val); break;
case "password": def.setPassword(val); break;
case "portName": def.setPortName(val); break;
case "portProtocol": def.setPortProtocol(val); break;
case "trustCerts": def.setTrustCerts(val); break;
case "username": def.setUsername(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, serviceCallConfigurationElementHandler(), noValueHandler());
}
protected PassThroughServiceCallServiceFilterConfiguration doParsePassThroughServiceCallServiceFilterConfiguration() throws IOException, XmlPullParserException {
return doParse(new PassThroughServiceCallServiceFilterConfiguration(),
identifiedTypeAttributeHandler(), serviceCallConfigurationElementHandler(), noValueHandler());
}
protected RibbonServiceCallServiceLoadBalancerConfiguration doParseRibbonServiceCallServiceLoadBalancerConfiguration() throws IOException, XmlPullParserException {
return doParse(new RibbonServiceCallServiceLoadBalancerConfiguration(), (def, key, val) -> {
switch (key) {
case "clientName": def.setClientName(val); break;
case "namespace": def.setNamespace(val); break;
case "password": def.setPassword(val); break;
case "username": def.setUsername(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, serviceCallConfigurationElementHandler(), noValueHandler());
}
protected ServiceCallConfigurationDefinition doParseServiceCallConfigurationDefinition() throws IOException, XmlPullParserException {
return doParse(new ServiceCallConfigurationDefinition(), (def, key, val) -> {
switch (key) {
case "component": def.setComponent(val); break;
case "expressionRef": def.setExpressionRef(val); break;
case "loadBalancerRef": def.setLoadBalancerRef(val); break;
case "pattern": def.setPattern(val); break;
case "serviceChooserRef": def.setServiceChooserRef(val); break;
case "serviceDiscoveryRef": def.setServiceDiscoveryRef(val); break;
case "serviceFilterRef": def.setServiceFilterRef(val); break;
case "uri": def.setUri(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, (def, key) -> {
switch (key) {
case "ribbonLoadBalancer": def.setLoadBalancerConfiguration(doParseRibbonServiceCallServiceLoadBalancerConfiguration()); break;
case "defaultLoadBalancer": def.setLoadBalancerConfiguration(doParseDefaultServiceCallServiceLoadBalancerConfiguration()); break;
case "cachingServiceDiscovery": def.setServiceDiscoveryConfiguration(doParseCachingServiceCallServiceDiscoveryConfiguration()); break;
case "combinedServiceDiscovery": def.setServiceDiscoveryConfiguration(doParseCombinedServiceCallServiceDiscoveryConfiguration()); break;
case "consulServiceDiscovery": def.setServiceDiscoveryConfiguration(doParseConsulServiceCallServiceDiscoveryConfiguration()); break;
case "dnsServiceDiscovery": def.setServiceDiscoveryConfiguration(doParseDnsServiceCallServiceDiscoveryConfiguration()); break;
case "etcdServiceDiscovery": def.setServiceDiscoveryConfiguration(doParseEtcdServiceCallServiceDiscoveryConfiguration()); break;
case "kubernetesServiceDiscovery": def.setServiceDiscoveryConfiguration(doParseKubernetesServiceCallServiceDiscoveryConfiguration()); break;
case "staticServiceDiscovery": def.setServiceDiscoveryConfiguration(doParseStaticServiceCallServiceDiscoveryConfiguration()); break;
case "zookeeperServiceDiscovery": def.setServiceDiscoveryConfiguration(doParseZooKeeperServiceCallServiceDiscoveryConfiguration()); break;
case "blacklistServiceFilter": def.setServiceFilterConfiguration(doParseBlacklistServiceCallServiceFilterConfiguration()); break;
case "combinedServiceFilter": def.setServiceFilterConfiguration(doParseCombinedServiceCallServiceFilterConfiguration()); break;
case "customServiceFilter": def.setServiceFilterConfiguration(doParseCustomServiceCallServiceFilterConfiguration()); break;
case "healthyServiceFilter": def.setServiceFilterConfiguration(doParseHealthyServiceCallServiceFilterConfiguration()); break;
case "passThroughServiceFilter": def.setServiceFilterConfiguration(doParsePassThroughServiceCallServiceFilterConfiguration()); break;
case "expression": def.setExpressionConfiguration(doParseServiceCallExpressionConfiguration()); break;
default: return false;
}
return true;
}, noValueHandler());
}
protected ServiceCallExpressionConfiguration doParseServiceCallExpressionConfiguration() throws IOException, XmlPullParserException {
return doParse(new ServiceCallExpressionConfiguration(), (def, key, val) -> {
switch (key) {
case "hostHeader": def.setHostHeader(val); break;
case "portHeader": def.setPortHeader(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, (def, key) -> {
ExpressionDefinition v = doParseExpressionDefinitionRef(key);
if (v != null) {
def.setExpressionType(v);
return true;
}
return serviceCallConfigurationElementHandler().accept(def, key);
}, noValueHandler());
}
protected ServiceCallDefinition doParseServiceCallDefinition() throws IOException, XmlPullParserException {
return doParse(new ServiceCallDefinition(), (def, key, val) -> {
switch (key) {
case "component": def.setComponent(val); break;
case "configurationRef": def.setConfigurationRef(val); break;
case "expressionRef": def.setExpressionRef(val); break;
case "loadBalancerRef": def.setLoadBalancerRef(val); break;
case "name": def.setName(val); break;
case "pattern": def.setPattern(val); break;
case "serviceChooserRef": def.setServiceChooserRef(val); break;
case "serviceDiscoveryRef": def.setServiceDiscoveryRef(val); break;
case "serviceFilterRef": def.setServiceFilterRef(val); break;
case "uri": def.setUri(val); break;
default: return processorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, (def, key) -> {
switch (key) {
case "ribbonLoadBalancer": def.setLoadBalancerConfiguration(doParseRibbonServiceCallServiceLoadBalancerConfiguration()); break;
case "defaultLoadBalancer": def.setLoadBalancerConfiguration(doParseDefaultServiceCallServiceLoadBalancerConfiguration()); break;
case "cachingServiceDiscovery": def.setServiceDiscoveryConfiguration(doParseCachingServiceCallServiceDiscoveryConfiguration()); break;
case "combinedServiceDiscovery": def.setServiceDiscoveryConfiguration(doParseCombinedServiceCallServiceDiscoveryConfiguration()); break;
case "consulServiceDiscovery": def.setServiceDiscoveryConfiguration(doParseConsulServiceCallServiceDiscoveryConfiguration()); break;
case "dnsServiceDiscovery": def.setServiceDiscoveryConfiguration(doParseDnsServiceCallServiceDiscoveryConfiguration()); break;
case "etcdServiceDiscovery": def.setServiceDiscoveryConfiguration(doParseEtcdServiceCallServiceDiscoveryConfiguration()); break;
case "kubernetesServiceDiscovery": def.setServiceDiscoveryConfiguration(doParseKubernetesServiceCallServiceDiscoveryConfiguration()); break;
case "staticServiceDiscovery": def.setServiceDiscoveryConfiguration(doParseStaticServiceCallServiceDiscoveryConfiguration()); break;
case "zookeeperServiceDiscovery": def.setServiceDiscoveryConfiguration(doParseZooKeeperServiceCallServiceDiscoveryConfiguration()); break;
case "blacklistServiceFilter": def.setServiceFilterConfiguration(doParseBlacklistServiceCallServiceFilterConfiguration()); break;
case "combinedServiceFilter": def.setServiceFilterConfiguration(doParseCombinedServiceCallServiceFilterConfiguration()); break;
case "customServiceFilter": def.setServiceFilterConfiguration(doParseCustomServiceCallServiceFilterConfiguration()); break;
case "healthyServiceFilter": def.setServiceFilterConfiguration(doParseHealthyServiceCallServiceFilterConfiguration()); break;
case "passThroughServiceFilter": def.setServiceFilterConfiguration(doParsePassThroughServiceCallServiceFilterConfiguration()); break;
case "expression": def.setExpressionConfiguration(doParseServiceCallExpressionConfiguration()); break;
default: return optionalIdentifiedDefinitionElementHandler().accept(def, key);
}
return true;
}, noValueHandler());
}
protected ServiceCallServiceChooserConfiguration doParseServiceCallServiceChooserConfiguration() throws IOException, XmlPullParserException {
return doParse(new ServiceCallServiceChooserConfiguration(),
identifiedTypeAttributeHandler(), serviceCallConfigurationElementHandler(), noValueHandler());
}
protected StaticServiceCallServiceDiscoveryConfiguration doParseStaticServiceCallServiceDiscoveryConfiguration() throws IOException, XmlPullParserException {
return doParse(new StaticServiceCallServiceDiscoveryConfiguration(),
identifiedTypeAttributeHandler(), (def, key) -> {
if ("servers".equals(key)) {
doAdd(doParseText(), def.getServers(), def::setServers);
return true;
}
return serviceCallConfigurationElementHandler().accept(def, key);
}, noValueHandler());
}
protected ZooKeeperServiceCallServiceDiscoveryConfiguration doParseZooKeeperServiceCallServiceDiscoveryConfiguration() throws IOException, XmlPullParserException {
return doParse(new ZooKeeperServiceCallServiceDiscoveryConfiguration(), (def, key, val) -> {
switch (key) {
case "basePath": def.setBasePath(val); break;
case "connectionTimeout": def.setConnectionTimeout(val); break;
case "namespace": def.setNamespace(val); break;
case "nodes": def.setNodes(val); break;
case "reconnectBaseSleepTime": def.setReconnectBaseSleepTime(val); break;
case "reconnectMaxRetries": def.setReconnectMaxRetries(val); break;
case "reconnectMaxSleepTime": def.setReconnectMaxSleepTime(val); break;
case "sessionTimeout": def.setSessionTimeout(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, serviceCallConfigurationElementHandler(), noValueHandler());
}
protected BatchResequencerConfig doParseBatchResequencerConfig() throws IOException, XmlPullParserException {
return doParse(new BatchResequencerConfig(), (def, key, val) -> {
switch (key) {
case "allowDuplicates": def.setAllowDuplicates(val); break;
case "batchSize": def.setBatchSize(val); break;
case "batchTimeout": def.setBatchTimeout(val); break;
case "ignoreInvalidExchanges": def.setIgnoreInvalidExchanges(val); break;
case "reverse": def.setReverse(val); break;
default: return false;
}
return true;
}, noElementHandler(), noValueHandler());
}
protected StreamResequencerConfig doParseStreamResequencerConfig() throws IOException, XmlPullParserException {
return doParse(new StreamResequencerConfig(), (def, key, val) -> {
switch (key) {
case "capacity": def.setCapacity(val); break;
case "comparatorRef": def.setComparatorRef(val); break;
case "deliveryAttemptInterval": def.setDeliveryAttemptInterval(val); break;
case "ignoreInvalidExchanges": def.setIgnoreInvalidExchanges(val); break;
case "rejectOld": def.setRejectOld(val); break;
case "timeout": def.setTimeout(val); break;
default: return false;
}
return true;
}, noElementHandler(), noValueHandler());
}
protected ASN1DataFormat doParseASN1DataFormat() throws IOException, XmlPullParserException {
return doParse(new ASN1DataFormat(), (def, key, val) -> {
switch (key) {
case "unmarshalType": def.setUnmarshalTypeName(val); break;
case "usingIterator": def.setUsingIterator(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected Any23DataFormat doParseAny23DataFormat() throws IOException, XmlPullParserException {
return doParse(new Any23DataFormat(), (def, key, val) -> {
switch (key) {
case "baseUri": def.setBaseUri(val); break;
case "outputFormat": def.setOutputFormat(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, (def, key) -> {
switch (key) {
case "configuration": doAdd(doParsePropertyDefinition(), def.getConfiguration(), def::setConfiguration); break;
case "extractors": doAdd(doParseText(), def.getExtractors(), def::setExtractors); break;
default: return false;
}
return true;
}, noValueHandler());
}
protected AvroDataFormat doParseAvroDataFormat() throws IOException, XmlPullParserException {
return doParse(new AvroDataFormat(), (def, key, val) -> {
switch (key) {
case "allowJmsType": def.setAllowJmsType(val); break;
case "allowUnmarshallType": def.setAllowUnmarshallType(val); break;
case "autoDiscoverObjectMapper": def.setAutoDiscoverObjectMapper(val); break;
case "autoDiscoverSchemaResolver": def.setAutoDiscoverSchemaResolver(val); break;
case "collectionType": def.setCollectionTypeName(val); break;
case "contentTypeHeader": def.setContentTypeHeader(val); break;
case "disableFeatures": def.setDisableFeatures(val); break;
case "enableFeatures": def.setEnableFeatures(val); break;
case "include": def.setInclude(val); break;
case "instanceClassName": def.setInstanceClassName(val); break;
case "jsonView": def.setJsonViewTypeName(val); break;
case "library": def.setLibrary(AvroLibrary.valueOf(val)); break;
case "moduleClassNames": def.setModuleClassNames(val); break;
case "moduleRefs": def.setModuleRefs(val); break;
case "objectMapper": def.setObjectMapper(val); break;
case "schemaResolver": def.setSchemaResolver(val); break;
case "timezone": def.setTimezone(val); break;
case "unmarshalType": def.setUnmarshalTypeName(val); break;
case "useDefaultObjectMapper": def.setUseDefaultObjectMapper(val); break;
case "useList": def.setUseList(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected BarcodeDataFormat doParseBarcodeDataFormat() throws IOException, XmlPullParserException {
return doParse(new BarcodeDataFormat(), (def, key, val) -> {
switch (key) {
case "barcodeFormat": def.setBarcodeFormat(val); break;
case "height": def.setHeight(val); break;
case "imageType": def.setImageType(val); break;
case "width": def.setWidth(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected Base64DataFormat doParseBase64DataFormat() throws IOException, XmlPullParserException {
return doParse(new Base64DataFormat(), (def, key, val) -> {
switch (key) {
case "lineLength": def.setLineLength(val); break;
case "lineSeparator": def.setLineSeparator(val); break;
case "urlSafe": def.setUrlSafe(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected BeanioDataFormat doParseBeanioDataFormat() throws IOException, XmlPullParserException {
return doParse(new BeanioDataFormat(), (def, key, val) -> {
switch (key) {
case "beanReaderErrorHandlerType": def.setBeanReaderErrorHandlerType(val); break;
case "encoding": def.setEncoding(val); break;
case "ignoreInvalidRecords": def.setIgnoreInvalidRecords(val); break;
case "ignoreUnexpectedRecords": def.setIgnoreUnexpectedRecords(val); break;
case "ignoreUnidentifiedRecords": def.setIgnoreUnidentifiedRecords(val); break;
case "mapping": def.setMapping(val); break;
case "streamName": def.setStreamName(val); break;
case "unmarshalSingleObject": def.setUnmarshalSingleObject(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected BindyDataFormat doParseBindyDataFormat() throws IOException, XmlPullParserException {
return doParse(new BindyDataFormat(), (def, key, val) -> {
switch (key) {
case "allowEmptyStream": def.setAllowEmptyStream(val); break;
case "classType": def.setClassType(val); break;
case "locale": def.setLocale(val); break;
case "type": def.setType(val); break;
case "unwrapSingleInstance": def.setUnwrapSingleInstance(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected CBORDataFormat doParseCBORDataFormat() throws IOException, XmlPullParserException {
return doParse(new CBORDataFormat(), (def, key, val) -> {
switch (key) {
case "allowJmsType": def.setAllowJmsType(val); break;
case "allowUnmarshallType": def.setAllowUnmarshallType(val); break;
case "collectionType": def.setCollectionTypeName(val); break;
case "disableFeatures": def.setDisableFeatures(val); break;
case "enableFeatures": def.setEnableFeatures(val); break;
case "objectMapper": def.setObjectMapper(val); break;
case "prettyPrint": def.setPrettyPrint(val); break;
case "unmarshalType": def.setUnmarshalTypeName(val); break;
case "useDefaultObjectMapper": def.setUseDefaultObjectMapper(val); break;
case "useList": def.setUseList(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected CryptoDataFormat doParseCryptoDataFormat() throws IOException, XmlPullParserException {
return doParse(new CryptoDataFormat(), (def, key, val) -> {
switch (key) {
case "algorithm": def.setAlgorithm(val); break;
case "algorithmParameterRef": def.setAlgorithmParameterRef(val); break;
case "buffersize": def.setBuffersize(val); break;
case "cryptoProvider": def.setCryptoProvider(val); break;
case "initVectorRef": def.setInitVectorRef(val); break;
case "inline": def.setInline(val); break;
case "keyRef": def.setKeyRef(val); break;
case "macAlgorithm": def.setMacAlgorithm(val); break;
case "shouldAppendHMAC": def.setShouldAppendHMAC(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected CsvDataFormat doParseCsvDataFormat() throws IOException, XmlPullParserException {
return doParse(new CsvDataFormat(), (def, key, val) -> {
switch (key) {
case "allowMissingColumnNames": def.setAllowMissingColumnNames(val); break;
case "captureHeaderRecord": def.setCaptureHeaderRecord(val); break;
case "commentMarker": def.setCommentMarker(val); break;
case "commentMarkerDisabled": def.setCommentMarkerDisabled(val); break;
case "delimiter": def.setDelimiter(val); break;
case "escape": def.setEscape(val); break;
case "escapeDisabled": def.setEscapeDisabled(val); break;
case "formatName": def.setFormatName(val); break;
case "formatRef": def.setFormatRef(val); break;
case "headerDisabled": def.setHeaderDisabled(val); break;
case "ignoreEmptyLines": def.setIgnoreEmptyLines(val); break;
case "ignoreHeaderCase": def.setIgnoreHeaderCase(val); break;
case "ignoreSurroundingSpaces": def.setIgnoreSurroundingSpaces(val); break;
case "lazyLoad": def.setLazyLoad(val); break;
case "marshallerFactoryRef": def.setMarshallerFactoryRef(val); break;
case "nullString": def.setNullString(val); break;
case "nullStringDisabled": def.setNullStringDisabled(val); break;
case "quote": def.setQuote(val); break;
case "quoteDisabled": def.setQuoteDisabled(val); break;
case "quoteMode": def.setQuoteMode(val); break;
case "recordConverterRef": def.setRecordConverterRef(val); break;
case "recordSeparator": def.setRecordSeparator(val); break;
case "recordSeparatorDisabled": def.setRecordSeparatorDisabled(val); break;
case "skipHeaderRecord": def.setSkipHeaderRecord(val); break;
case "trailingDelimiter": def.setTrailingDelimiter(val); break;
case "trim": def.setTrim(val); break;
case "useMaps": def.setUseMaps(val); break;
case "useOrderedMaps": def.setUseOrderedMaps(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, (def, key) -> {
if ("header".equals(key)) {
doAdd(doParseText(), def.getHeader(), def::setHeader);
return true;
}
return false;
}, noValueHandler());
}
protected CustomDataFormat doParseCustomDataFormat() throws IOException, XmlPullParserException {
return doParse(new CustomDataFormat(), (def, key, val) -> {
if ("ref".equals(key)) {
def.setRef(val);
return true;
}
return identifiedTypeAttributeHandler().accept(def, key, val);
}, noElementHandler(), noValueHandler());
}
protected DataFormatsDefinition doParseDataFormatsDefinition() throws IOException, XmlPullParserException {
return doParse(new DataFormatsDefinition(),
noAttributeHandler(), (def, key) -> {
DataFormatDefinition v = doParseDataFormatDefinitionRef(key);
if (v != null) {
doAdd(v, def.getDataFormats(), def::setDataFormats);
return true;
}
return false;
}, noValueHandler());
}
protected FhirJsonDataFormat doParseFhirJsonDataFormat() throws IOException, XmlPullParserException {
return doParse(new FhirJsonDataFormat(),
fhirDataformatAttributeHandler(), noElementHandler(), noValueHandler());
}
protected <T extends FhirDataformat> AttributeHandler<T> fhirDataformatAttributeHandler() {
return (def, key, val) -> {
switch (key) {
case "contentTypeHeader": def.setContentTypeHeader(val); break;
case "dontEncodeElements": def.setDontEncodeElements(asStringSet(val)); break;
case "dontStripVersionsFromReferencesAtPaths": def.setDontStripVersionsFromReferencesAtPaths(asStringList(val)); break;
case "encodeElements": def.setEncodeElements(asStringSet(val)); break;
case "encodeElementsAppliesToChildResourcesOnly": def.setEncodeElementsAppliesToChildResourcesOnly(val); break;
case "fhirVersion": def.setFhirVersion(val); break;
case "omitResourceId": def.setOmitResourceId(val); break;
case "overrideResourceIdWithBundleEntryFullUrl": def.setOverrideResourceIdWithBundleEntryFullUrl(val); break;
case "prettyPrint": def.setPrettyPrint(val); break;
case "serverBaseUrl": def.setServerBaseUrl(val); break;
case "stripVersionsFromReferences": def.setStripVersionsFromReferences(val); break;
case "summaryMode": def.setSummaryMode(val); break;
case "suppressNarratives": def.setSuppressNarratives(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
};
}
protected FhirXmlDataFormat doParseFhirXmlDataFormat() throws IOException, XmlPullParserException {
return doParse(new FhirXmlDataFormat(),
fhirDataformatAttributeHandler(), noElementHandler(), noValueHandler());
}
protected FlatpackDataFormat doParseFlatpackDataFormat() throws IOException, XmlPullParserException {
return doParse(new FlatpackDataFormat(), (def, key, val) -> {
switch (key) {
case "allowShortLines": def.setAllowShortLines(val); break;
case "definition": def.setDefinition(val); break;
case "delimiter": def.setDelimiter(val); break;
case "fixed": def.setFixed(val); break;
case "ignoreExtraColumns": def.setIgnoreExtraColumns(val); break;
case "ignoreFirstRecord": def.setIgnoreFirstRecord(val); break;
case "parserFactoryRef": def.setParserFactoryRef(val); break;
case "textQualifier": def.setTextQualifier(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected GrokDataFormat doParseGrokDataFormat() throws IOException, XmlPullParserException {
return doParse(new GrokDataFormat(), (def, key, val) -> {
switch (key) {
case "allowMultipleMatchesPerLine": def.setAllowMultipleMatchesPerLine(val); break;
case "flattened": def.setFlattened(val); break;
case "namedOnly": def.setNamedOnly(val); break;
case "pattern": def.setPattern(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected GzipDeflaterDataFormat doParseGzipDeflaterDataFormat() throws IOException, XmlPullParserException {
return doParse(new GzipDeflaterDataFormat(),
identifiedTypeAttributeHandler(), noElementHandler(), noValueHandler());
}
protected HL7DataFormat doParseHL7DataFormat() throws IOException, XmlPullParserException {
return doParse(new HL7DataFormat(), (def, key, val) -> {
if ("validate".equals(key)) {
def.setValidate(val);
return true;
}
return identifiedTypeAttributeHandler().accept(def, key, val);
}, noElementHandler(), noValueHandler());
}
protected IcalDataFormat doParseIcalDataFormat() throws IOException, XmlPullParserException {
return doParse(new IcalDataFormat(), (def, key, val) -> {
if ("validating".equals(key)) {
def.setValidating(val);
return true;
}
return identifiedTypeAttributeHandler().accept(def, key, val);
}, noElementHandler(), noValueHandler());
}
protected JacksonXMLDataFormat doParseJacksonXMLDataFormat() throws IOException, XmlPullParserException {
return doParse(new JacksonXMLDataFormat(), (def, key, val) -> {
switch (key) {
case "allowJmsType": def.setAllowJmsType(val); break;
case "allowUnmarshallType": def.setAllowUnmarshallType(val); break;
case "collectionType": def.setCollectionTypeName(val); break;
case "contentTypeHeader": def.setContentTypeHeader(val); break;
case "disableFeatures": def.setDisableFeatures(val); break;
case "enableFeatures": def.setEnableFeatures(val); break;
case "enableJaxbAnnotationModule": def.setEnableJaxbAnnotationModule(val); break;
case "include": def.setInclude(val); break;
case "jsonView": def.setJsonViewTypeName(val); break;
case "moduleClassNames": def.setModuleClassNames(val); break;
case "moduleRefs": def.setModuleRefs(val); break;
case "prettyPrint": def.setPrettyPrint(val); break;
case "unmarshalType": def.setUnmarshalTypeName(val); break;
case "useList": def.setUseList(val); break;
case "xmlMapper": def.setXmlMapper(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected JaxbDataFormat doParseJaxbDataFormat() throws IOException, XmlPullParserException {
return doParse(new JaxbDataFormat(), (def, key, val) -> {
switch (key) {
case "contentTypeHeader": def.setContentTypeHeader(val); break;
case "contextPath": def.setContextPath(val); break;
case "contextPathIsClassName": def.setContextPathIsClassName(val); break;
case "encoding": def.setEncoding(val); break;
case "filterNonXmlChars": def.setFilterNonXmlChars(val); break;
case "fragment": def.setFragment(val); break;
case "ignoreJAXBElement": def.setIgnoreJAXBElement(val); break;
case "jaxbProviderProperties": def.setJaxbProviderProperties(val); break;
case "mustBeJAXBElement": def.setMustBeJAXBElement(val); break;
case "namespacePrefixRef": def.setNamespacePrefixRef(val); break;
case "noNamespaceSchemaLocation": def.setNoNamespaceSchemaLocation(val); break;
case "objectFactory": def.setObjectFactory(val); break;
case "partClass": def.setPartClass(val); break;
case "partNamespace": def.setPartNamespace(val); break;
case "prettyPrint": def.setPrettyPrint(val); break;
case "schema": def.setSchema(val); break;
case "schemaLocation": def.setSchemaLocation(val); break;
case "schemaSeverityLevel": def.setSchemaSeverityLevel(val); break;
case "xmlStreamWriterWrapper": def.setXmlStreamWriterWrapper(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected JsonApiDataFormat doParseJsonApiDataFormat() throws IOException, XmlPullParserException {
return doParse(new JsonApiDataFormat(), (def, key, val) -> {
switch (key) {
case "dataFormatTypes": def.setDataFormatTypes(asClassArray(val)); break;
case "mainFormatType": def.setMainFormatType(asClass(val)); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected JsonDataFormat doParseJsonDataFormat() throws IOException, XmlPullParserException {
return doParse(new JsonDataFormat(), (def, key, val) -> {
switch (key) {
case "allowJmsType": def.setAllowJmsType(val); break;
case "allowUnmarshallType": def.setAllowUnmarshallType(val); break;
case "autoDiscoverObjectMapper": def.setAutoDiscoverObjectMapper(val); break;
case "autoDiscoverSchemaResolver": def.setAutoDiscoverSchemaResolver(val); break;
case "collectionType": def.setCollectionTypeName(val); break;
case "contentTypeHeader": def.setContentTypeHeader(val); break;
case "disableFeatures": def.setDisableFeatures(val); break;
case "dropRootNode": def.setDropRootNode(val); break;
case "enableFeatures": def.setEnableFeatures(val); break;
case "include": def.setInclude(val); break;
case "jsonView": def.setJsonViewTypeName(val); break;
case "library": def.setLibrary(JsonLibrary.valueOf(val)); break;
case "moduleClassNames": def.setModuleClassNames(val); break;
case "moduleRefs": def.setModuleRefs(val); break;
case "namingStrategy": def.setNamingStrategy(val); break;
case "objectMapper": def.setObjectMapper(val); break;
case "permissions": def.setPermissions(val); break;
case "prettyPrint": def.setPrettyPrint(val); break;
case "schemaResolver": def.setSchemaResolver(val); break;
case "timezone": def.setTimezone(val); break;
case "unmarshalType": def.setUnmarshalTypeName(val); break;
case "useDefaultObjectMapper": def.setUseDefaultObjectMapper(val); break;
case "useList": def.setUseList(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected LZFDataFormat doParseLZFDataFormat() throws IOException, XmlPullParserException {
return doParse(new LZFDataFormat(), (def, key, val) -> {
if ("usingParallelCompression".equals(key)) {
def.setUsingParallelCompression(val);
return true;
}
return identifiedTypeAttributeHandler().accept(def, key, val);
}, noElementHandler(), noValueHandler());
}
protected MimeMultipartDataFormat doParseMimeMultipartDataFormat() throws IOException, XmlPullParserException {
return doParse(new MimeMultipartDataFormat(), (def, key, val) -> {
switch (key) {
case "binaryContent": def.setBinaryContent(val); break;
case "headersInline": def.setHeadersInline(val); break;
case "includeHeaders": def.setIncludeHeaders(val); break;
case "multipartSubType": def.setMultipartSubType(val); break;
case "multipartWithoutAttachment": def.setMultipartWithoutAttachment(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected PGPDataFormat doParsePGPDataFormat() throws IOException, XmlPullParserException {
return doParse(new PGPDataFormat(), (def, key, val) -> {
switch (key) {
case "algorithm": def.setAlgorithm(val); break;
case "armored": def.setArmored(val); break;
case "compressionAlgorithm": def.setCompressionAlgorithm(val); break;
case "hashAlgorithm": def.setHashAlgorithm(val); break;
case "integrity": def.setIntegrity(val); break;
case "keyFileName": def.setKeyFileName(val); break;
case "keyUserid": def.setKeyUserid(val); break;
case "password": def.setPassword(val); break;
case "provider": def.setProvider(val); break;
case "signatureKeyFileName": def.setSignatureKeyFileName(val); break;
case "signatureKeyRing": def.setSignatureKeyRing(val); break;
case "signatureKeyUserid": def.setSignatureKeyUserid(val); break;
case "signaturePassword": def.setSignaturePassword(val); break;
case "signatureVerificationOption": def.setSignatureVerificationOption(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected ProtobufDataFormat doParseProtobufDataFormat() throws IOException, XmlPullParserException {
return doParse(new ProtobufDataFormat(), (def, key, val) -> {
switch (key) {
case "allowJmsType": def.setAllowJmsType(val); break;
case "allowUnmarshallType": def.setAllowUnmarshallType(val); break;
case "autoDiscoverObjectMapper": def.setAutoDiscoverObjectMapper(val); break;
case "autoDiscoverSchemaResolver": def.setAutoDiscoverSchemaResolver(val); break;
case "collectionType": def.setCollectionTypeName(val); break;
case "contentTypeFormat": def.setContentTypeFormat(val); break;
case "contentTypeHeader": def.setContentTypeHeader(val); break;
case "disableFeatures": def.setDisableFeatures(val); break;
case "enableFeatures": def.setEnableFeatures(val); break;
case "include": def.setInclude(val); break;
case "instanceClass": def.setInstanceClass(val); break;
case "jsonView": def.setJsonViewTypeName(val); break;
case "library": def.setLibrary(ProtobufLibrary.valueOf(val)); break;
case "moduleClassNames": def.setModuleClassNames(val); break;
case "moduleRefs": def.setModuleRefs(val); break;
case "objectMapper": def.setObjectMapper(val); break;
case "schemaResolver": def.setSchemaResolver(val); break;
case "timezone": def.setTimezone(val); break;
case "unmarshalType": def.setUnmarshalTypeName(val); break;
case "useDefaultObjectMapper": def.setUseDefaultObjectMapper(val); break;
case "useList": def.setUseList(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected RssDataFormat doParseRssDataFormat() throws IOException, XmlPullParserException {
return doParse(new RssDataFormat(),
identifiedTypeAttributeHandler(), noElementHandler(), noValueHandler());
}
protected SoapDataFormat doParseSoapDataFormat() throws IOException, XmlPullParserException {
return doParse(new SoapDataFormat(), (def, key, val) -> {
switch (key) {
case "contextPath": def.setContextPath(val); break;
case "elementNameStrategyRef": def.setElementNameStrategyRef(val); break;
case "encoding": def.setEncoding(val); break;
case "namespacePrefixRef": def.setNamespacePrefixRef(val); break;
case "schema": def.setSchema(val); break;
case "version": def.setVersion(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected SyslogDataFormat doParseSyslogDataFormat() throws IOException, XmlPullParserException {
return doParse(new SyslogDataFormat(),
identifiedTypeAttributeHandler(), noElementHandler(), noValueHandler());
}
protected TarFileDataFormat doParseTarFileDataFormat() throws IOException, XmlPullParserException {
return doParse(new TarFileDataFormat(), (def, key, val) -> {
switch (key) {
case "allowEmptyDirectory": def.setAllowEmptyDirectory(val); break;
case "maxDecompressedSize": def.setMaxDecompressedSize(val); break;
case "preservePathElements": def.setPreservePathElements(val); break;
case "usingIterator": def.setUsingIterator(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected ThriftDataFormat doParseThriftDataFormat() throws IOException, XmlPullParserException {
return doParse(new ThriftDataFormat(), (def, key, val) -> {
switch (key) {
case "contentTypeFormat": def.setContentTypeFormat(val); break;
case "contentTypeHeader": def.setContentTypeHeader(val); break;
case "instanceClass": def.setInstanceClass(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected TidyMarkupDataFormat doParseTidyMarkupDataFormat() throws IOException, XmlPullParserException {
return doParse(new TidyMarkupDataFormat(), (def, key, val) -> {
switch (key) {
case "dataObjectType": def.setDataObjectTypeName(val); break;
case "omitXmlDeclaration": def.setOmitXmlDeclaration(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected UniVocityCsvDataFormat doParseUniVocityCsvDataFormat() throws IOException, XmlPullParserException {
return doParse(new UniVocityCsvDataFormat(), (def, key, val) -> {
switch (key) {
case "delimiter": def.setDelimiter(val); break;
case "quote": def.setQuote(val); break;
case "quoteAllFields": def.setQuoteAllFields(val); break;
case "quoteEscape": def.setQuoteEscape(val); break;
default: return uniVocityAbstractDataFormatAttributeHandler().accept(def, key, val);
}
return true;
}, uniVocityAbstractDataFormatElementHandler(), noValueHandler());
}
protected <T extends UniVocityAbstractDataFormat> AttributeHandler<T> uniVocityAbstractDataFormatAttributeHandler() {
return (def, key, val) -> {
switch (key) {
case "asMap": def.setAsMap(val); break;
case "comment": def.setComment(val); break;
case "emptyValue": def.setEmptyValue(val); break;
case "headerExtractionEnabled": def.setHeaderExtractionEnabled(val); break;
case "headersDisabled": def.setHeadersDisabled(val); break;
case "ignoreLeadingWhitespaces": def.setIgnoreLeadingWhitespaces(val); break;
case "ignoreTrailingWhitespaces": def.setIgnoreTrailingWhitespaces(val); break;
case "lazyLoad": def.setLazyLoad(val); break;
case "lineSeparator": def.setLineSeparator(val); break;
case "normalizedLineSeparator": def.setNormalizedLineSeparator(val); break;
case "nullValue": def.setNullValue(val); break;
case "numberOfRecordsToRead": def.setNumberOfRecordsToRead(val); break;
case "skipEmptyLines": def.setSkipEmptyLines(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
};
}
protected <T extends UniVocityAbstractDataFormat> ElementHandler<T> uniVocityAbstractDataFormatElementHandler() {
return (def, key) -> {
if ("univocityHeader".equals(key)) {
doAdd(doParseUniVocityHeader(), def.getHeaders(), def::setHeaders);
return true;
}
return false;
};
}
protected UniVocityHeader doParseUniVocityHeader() throws IOException, XmlPullParserException {
return doParse(new UniVocityHeader(), (def, key, val) -> {
if ("length".equals(key)) {
def.setLength(val);
return true;
}
return false;
}, noElementHandler(), (def, val) -> def.setName(val));
}
protected UniVocityFixedDataFormat doParseUniVocityFixedDataFormat() throws IOException, XmlPullParserException {
return doParse(new UniVocityFixedDataFormat(), (def, key, val) -> {
switch (key) {
case "padding": def.setPadding(val); break;
case "recordEndsOnNewline": def.setRecordEndsOnNewline(val); break;
case "skipTrailingCharsUntilNewline": def.setSkipTrailingCharsUntilNewline(val); break;
default: return uniVocityAbstractDataFormatAttributeHandler().accept(def, key, val);
}
return true;
}, uniVocityAbstractDataFormatElementHandler(), noValueHandler());
}
protected UniVocityTsvDataFormat doParseUniVocityTsvDataFormat() throws IOException, XmlPullParserException {
return doParse(new UniVocityTsvDataFormat(), (def, key, val) -> {
if ("escapeChar".equals(key)) {
def.setEscapeChar(val);
return true;
}
return uniVocityAbstractDataFormatAttributeHandler().accept(def, key, val);
}, uniVocityAbstractDataFormatElementHandler(), noValueHandler());
}
protected XMLSecurityDataFormat doParseXMLSecurityDataFormat() throws IOException, XmlPullParserException {
return doParse(new XMLSecurityDataFormat(), (def, key, val) -> {
switch (key) {
case "addKeyValueForEncryptedKey": def.setAddKeyValueForEncryptedKey(val); break;
case "digestAlgorithm": def.setDigestAlgorithm(val); break;
case "keyCipherAlgorithm": def.setKeyCipherAlgorithm(val); break;
case "keyOrTrustStoreParametersRef": def.setKeyOrTrustStoreParametersRef(val); break;
case "keyPassword": def.setKeyPassword(val); break;
case "mgfAlgorithm": def.setMgfAlgorithm(val); break;
case "passPhrase": def.setPassPhrase(val); break;
case "passPhraseByte": def.setPassPhraseByte(asByteArray(val)); break;
case "recipientKeyAlias": def.setRecipientKeyAlias(val); break;
case "secureTag": def.setSecureTag(val); break;
case "secureTagContents": def.setSecureTagContents(val); break;
case "xmlCipherAlgorithm": def.setXmlCipherAlgorithm(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected XStreamDataFormat doParseXStreamDataFormat() throws IOException, XmlPullParserException {
return doParse(new XStreamDataFormat(), (def, key, val) -> {
switch (key) {
case "contentTypeHeader": def.setContentTypeHeader(val); break;
case "driver": def.setDriver(val); break;
case "driverRef": def.setDriverRef(val); break;
case "encoding": def.setEncoding(val); break;
case "mode": def.setMode(val); break;
case "permissions": def.setPermissions(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, (def, key) -> {
switch (key) {
case "aliases": doAdd(doParsePropertyDefinition(), def.getAliases(), def::setAliases); break;
case "converters": doAdd(doParsePropertyDefinition(), def.getConverters(), def::setConverters); break;
case "implicitCollections": doAdd(doParsePropertyDefinition(), def.getImplicitCollections(), def::setImplicitCollections); break;
case "omitFields": doAdd(doParsePropertyDefinition(), def.getOmitFields(), def::setOmitFields); break;
default: return false;
}
return true;
}, noValueHandler());
}
protected YAMLDataFormat doParseYAMLDataFormat() throws IOException, XmlPullParserException {
return doParse(new YAMLDataFormat(), (def, key, val) -> {
switch (key) {
case "allowAnyType": def.setAllowAnyType(val); break;
case "allowRecursiveKeys": def.setAllowRecursiveKeys(val); break;
case "constructor": def.setConstructor(val); break;
case "dumperOptions": def.setDumperOptions(val); break;
case "library": def.setLibrary(YAMLLibrary.valueOf(val)); break;
case "maxAliasesForCollections": def.setMaxAliasesForCollections(val); break;
case "prettyFlow": def.setPrettyFlow(val); break;
case "representer": def.setRepresenter(val); break;
case "resolver": def.setResolver(val); break;
case "unmarshalType": def.setUnmarshalTypeName(val); break;
case "useApplicationContextClassLoader": def.setUseApplicationContextClassLoader(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, (def, key) -> {
if ("typeFilter".equals(key)) {
doAdd(doParseYAMLTypeFilterDefinition(), def.getTypeFilters(), def::setTypeFilters);
return true;
}
return false;
}, noValueHandler());
}
protected YAMLTypeFilterDefinition doParseYAMLTypeFilterDefinition() throws IOException, XmlPullParserException {
return doParse(new YAMLTypeFilterDefinition(), (def, key, val) -> {
switch (key) {
case "type": def.setType(val); break;
case "value": def.setValue(val); break;
default: return false;
}
return true;
}, noElementHandler(), noValueHandler());
}
protected ZipDeflaterDataFormat doParseZipDeflaterDataFormat() throws IOException, XmlPullParserException {
return doParse(new ZipDeflaterDataFormat(), (def, key, val) -> {
if ("compressionLevel".equals(key)) {
def.setCompressionLevel(val);
return true;
}
return identifiedTypeAttributeHandler().accept(def, key, val);
}, noElementHandler(), noValueHandler());
}
protected ZipFileDataFormat doParseZipFileDataFormat() throws IOException, XmlPullParserException {
return doParse(new ZipFileDataFormat(), (def, key, val) -> {
switch (key) {
case "allowEmptyDirectory": def.setAllowEmptyDirectory(val); break;
case "maxDecompressedSize": def.setMaxDecompressedSize(val); break;
case "preservePathElements": def.setPreservePathElements(val); break;
case "usingIterator": def.setUsingIterator(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected CSimpleExpression doParseCSimpleExpression() throws IOException, XmlPullParserException {
return doParse(new CSimpleExpression(), (def, key, val) -> {
if ("resultType".equals(key)) {
def.setResultTypeName(val);
return true;
}
return expressionDefinitionAttributeHandler().accept(def, key, val);
}, noElementHandler(), expressionDefinitionValueHandler());
}
protected ConstantExpression doParseConstantExpression() throws IOException, XmlPullParserException {
return doParse(new ConstantExpression(), (def, key, val) -> {
if ("resultType".equals(key)) {
def.setResultTypeName(val);
return true;
}
return expressionDefinitionAttributeHandler().accept(def, key, val);
}, noElementHandler(), expressionDefinitionValueHandler());
}
protected DatasonnetExpression doParseDatasonnetExpression() throws IOException, XmlPullParserException {
return doParse(new DatasonnetExpression(), (def, key, val) -> {
switch (key) {
case "bodyMediaType": def.setBodyMediaType(val); break;
case "outputMediaType": def.setOutputMediaType(val); break;
case "resultType": def.setResultTypeName(val); break;
default: return expressionDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), expressionDefinitionValueHandler());
}
protected ExchangePropertyExpression doParseExchangePropertyExpression() throws IOException, XmlPullParserException {
return doParse(new ExchangePropertyExpression(),
expressionDefinitionAttributeHandler(), noElementHandler(), expressionDefinitionValueHandler());
}
protected GroovyExpression doParseGroovyExpression() throws IOException, XmlPullParserException {
return doParse(new GroovyExpression(),
expressionDefinitionAttributeHandler(), noElementHandler(), expressionDefinitionValueHandler());
}
protected HeaderExpression doParseHeaderExpression() throws IOException, XmlPullParserException {
return doParse(new HeaderExpression(),
expressionDefinitionAttributeHandler(), noElementHandler(), expressionDefinitionValueHandler());
}
protected Hl7TerserExpression doParseHl7TerserExpression() throws IOException, XmlPullParserException {
return doParse(new Hl7TerserExpression(),
expressionDefinitionAttributeHandler(), noElementHandler(), expressionDefinitionValueHandler());
}
protected JoorExpression doParseJoorExpression() throws IOException, XmlPullParserException {
return doParse(new JoorExpression(), (def, key, val) -> {
switch (key) {
case "preCompile": def.setPreCompile(val); break;
case "resultType": def.setResultTypeName(val); break;
case "singleQuotes": def.setSingleQuotes(val); break;
default: return expressionDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), expressionDefinitionValueHandler());
}
protected JsonPathExpression doParseJsonPathExpression() throws IOException, XmlPullParserException {
return doParse(new JsonPathExpression(), (def, key, val) -> {
switch (key) {
case "allowEasyPredicate": def.setAllowEasyPredicate(val); break;
case "allowSimple": def.setAllowSimple(val); break;
case "headerName": def.setHeaderName(val); break;
case "option": def.setOption(val); break;
case "resultType": def.setResultTypeName(val); break;
case "suppressExceptions": def.setSuppressExceptions(val); break;
case "writeAsString": def.setWriteAsString(val); break;
default: return expressionDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), expressionDefinitionValueHandler());
}
protected LanguageExpression doParseLanguageExpression() throws IOException, XmlPullParserException {
return doParse(new LanguageExpression(), (def, key, val) -> {
if ("language".equals(key)) {
def.setLanguage(val);
return true;
}
return expressionDefinitionAttributeHandler().accept(def, key, val);
}, noElementHandler(), expressionDefinitionValueHandler());
}
protected MethodCallExpression doParseMethodCallExpression() throws IOException, XmlPullParserException {
return doParse(new MethodCallExpression(), (def, key, val) -> {
switch (key) {
case "beanType": def.setBeanTypeName(val); break;
case "method": def.setMethod(val); break;
case "ref": def.setRef(val); break;
case "scope": def.setScope(val); break;
default: return expressionDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), expressionDefinitionValueHandler());
}
protected MvelExpression doParseMvelExpression() throws IOException, XmlPullParserException {
return doParse(new MvelExpression(),
expressionDefinitionAttributeHandler(), noElementHandler(), expressionDefinitionValueHandler());
}
protected OgnlExpression doParseOgnlExpression() throws IOException, XmlPullParserException {
return doParse(new OgnlExpression(),
expressionDefinitionAttributeHandler(), noElementHandler(), expressionDefinitionValueHandler());
}
protected RefExpression doParseRefExpression() throws IOException, XmlPullParserException {
return doParse(new RefExpression(),
expressionDefinitionAttributeHandler(), noElementHandler(), expressionDefinitionValueHandler());
}
protected SimpleExpression doParseSimpleExpression() throws IOException, XmlPullParserException {
return doParse(new SimpleExpression(), (def, key, val) -> {
if ("resultType".equals(key)) {
def.setResultTypeName(val);
return true;
}
return expressionDefinitionAttributeHandler().accept(def, key, val);
}, noElementHandler(), expressionDefinitionValueHandler());
}
protected SpELExpression doParseSpELExpression() throws IOException, XmlPullParserException {
return doParse(new SpELExpression(),
expressionDefinitionAttributeHandler(), noElementHandler(), expressionDefinitionValueHandler());
}
protected TokenizerExpression doParseTokenizerExpression() throws IOException, XmlPullParserException {
return doParse(new TokenizerExpression(), (def, key, val) -> {
switch (key) {
case "endToken": def.setEndToken(val); break;
case "group": def.setGroup(val); break;
case "groupDelimiter": def.setGroupDelimiter(val); break;
case "headerName": def.setHeaderName(val); break;
case "includeTokens": def.setIncludeTokens(val); break;
case "inheritNamespaceTagName": def.setInheritNamespaceTagName(val); break;
case "regex": def.setRegex(val); break;
case "skipFirst": def.setSkipFirst(val); break;
case "token": def.setToken(val); break;
case "xml": def.setXml(val); break;
default: return expressionDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), expressionDefinitionValueHandler());
}
protected XMLTokenizerExpression doParseXMLTokenizerExpression() throws IOException, XmlPullParserException {
return doParse(new XMLTokenizerExpression(), (def, key, val) -> {
switch (key) {
case "group": def.setGroup(val); break;
case "headerName": def.setHeaderName(val); break;
case "mode": def.setMode(val); break;
default: return expressionDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), expressionDefinitionValueHandler());
}
protected XPathExpression doParseXPathExpression() throws IOException, XmlPullParserException {
return doParse(new XPathExpression(), (def, key, val) -> {
switch (key) {
case "documentType": def.setDocumentTypeName(val); break;
case "factoryRef": def.setFactoryRef(val); break;
case "headerName": def.setHeaderName(val); break;
case "logNamespaces": def.setLogNamespaces(val); break;
case "objectModel": def.setObjectModel(val); break;
case "preCompile": def.setPreCompile(val); break;
case "resultType": def.setResultTypeName(val); break;
case "saxon": def.setSaxon(val); break;
case "threadSafety": def.setThreadSafety(val); break;
default: return expressionDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), expressionDefinitionValueHandler());
}
protected XQueryExpression doParseXQueryExpression() throws IOException, XmlPullParserException {
return doParse(new XQueryExpression(), (def, key, val) -> {
switch (key) {
case "configurationRef": def.setConfigurationRef(val); break;
case "headerName": def.setHeaderName(val); break;
case "type": def.setType(val); break;
default: return expressionDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), expressionDefinitionValueHandler());
}
protected CustomLoadBalancerDefinition doParseCustomLoadBalancerDefinition() throws IOException, XmlPullParserException {
return doParse(new CustomLoadBalancerDefinition(), (def, key, val) -> {
if ("ref".equals(key)) {
def.setRef(val);
return true;
}
return identifiedTypeAttributeHandler().accept(def, key, val);
}, noElementHandler(), noValueHandler());
}
protected FailoverLoadBalancerDefinition doParseFailoverLoadBalancerDefinition() throws IOException, XmlPullParserException {
return doParse(new FailoverLoadBalancerDefinition(), (def, key, val) -> {
switch (key) {
case "maximumFailoverAttempts": def.setMaximumFailoverAttempts(val); break;
case "roundRobin": def.setRoundRobin(val); break;
case "sticky": def.setSticky(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, (def, key) -> {
if ("exception".equals(key)) {
doAdd(doParseText(), def.getExceptions(), def::setExceptions);
return true;
}
return false;
}, noValueHandler());
}
protected RandomLoadBalancerDefinition doParseRandomLoadBalancerDefinition() throws IOException, XmlPullParserException {
return doParse(new RandomLoadBalancerDefinition(),
identifiedTypeAttributeHandler(), noElementHandler(), noValueHandler());
}
protected RoundRobinLoadBalancerDefinition doParseRoundRobinLoadBalancerDefinition() throws IOException, XmlPullParserException {
return doParse(new RoundRobinLoadBalancerDefinition(),
identifiedTypeAttributeHandler(), noElementHandler(), noValueHandler());
}
protected StickyLoadBalancerDefinition doParseStickyLoadBalancerDefinition() throws IOException, XmlPullParserException {
return doParse(new StickyLoadBalancerDefinition(),
identifiedTypeAttributeHandler(), (def, key) -> {
if ("correlationExpression".equals(key)) {
def.setCorrelationExpression(doParseExpressionSubElementDefinition());
return true;
}
return false;
}, noValueHandler());
}
protected TopicLoadBalancerDefinition doParseTopicLoadBalancerDefinition() throws IOException, XmlPullParserException {
return doParse(new TopicLoadBalancerDefinition(),
identifiedTypeAttributeHandler(), noElementHandler(), noValueHandler());
}
protected WeightedLoadBalancerDefinition doParseWeightedLoadBalancerDefinition() throws IOException, XmlPullParserException {
return doParse(new WeightedLoadBalancerDefinition(), (def, key, val) -> {
switch (key) {
case "distributionRatio": def.setDistributionRatio(val); break;
case "distributionRatioDelimiter": def.setDistributionRatioDelimiter(val); break;
case "roundRobin": def.setRoundRobin(val); break;
default: return identifiedTypeAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected DeleteDefinition doParseDeleteDefinition() throws IOException, XmlPullParserException {
return doParse(new DeleteDefinition(),
verbDefinitionAttributeHandler(), verbDefinitionElementHandler(), noValueHandler());
}
protected <T extends VerbDefinition> AttributeHandler<T> verbDefinitionAttributeHandler() {
return (def, key, val) -> {
switch (key) {
case "apiDocs": def.setApiDocs(val); break;
case "bindingMode": def.setBindingMode(val); break;
case "clientRequestValidation": def.setClientRequestValidation(val); break;
case "consumes": def.setConsumes(val); break;
case "deprecated": def.setDeprecated(Boolean.valueOf(val)); break;
case "enableCORS": def.setEnableCORS(val); break;
case "outType": def.setOutType(val); break;
case "produces": def.setProduces(val); break;
case "routeId": def.setRouteId(val); break;
case "skipBindingOnErrorCode": def.setSkipBindingOnErrorCode(val); break;
case "type": def.setType(val); break;
case "uri": def.setUri(val); break;
default: return optionalIdentifiedDefinitionAttributeHandler().accept(def, key, val);
}
return true;
};
}
protected <T extends VerbDefinition> ElementHandler<T> verbDefinitionElementHandler() {
return (def, key) -> {
switch (key) {
case "param": doAdd(doParseRestOperationParamDefinition(), def.getParams(), def::setParams); break;
case "responseMessage": doAdd(doParseRestOperationResponseMsgDefinition(), def.getResponseMsgs(), def::setResponseMsgs); break;
case "security": doAdd(doParseSecurityDefinition(), def.getSecurity(), def::setSecurity); break;
case "to": def.setToOrRoute(doParseToDefinition()); break;
case "toD": def.setToOrRoute(doParseToDynamicDefinition()); break;
case "route": def.setToOrRoute(doParseRouteDefinition()); break;
default: return optionalIdentifiedDefinitionElementHandler().accept(def, key);
}
return true;
};
}
protected VerbDefinition doParseVerbDefinition() throws IOException, XmlPullParserException {
return doParse(new VerbDefinition(), verbDefinitionAttributeHandler(), verbDefinitionElementHandler(), noValueHandler());
}
protected RestOperationParamDefinition doParseRestOperationParamDefinition() throws IOException, XmlPullParserException {
return doParse(new RestOperationParamDefinition(), (def, key, val) -> {
switch (key) {
case "arrayType": def.setArrayType(val); break;
case "collectionFormat": def.setCollectionFormat(CollectionFormat.valueOf(val)); break;
case "dataFormat": def.setDataFormat(val); break;
case "dataType": def.setDataType(val); break;
case "defaultValue": def.setDefaultValue(val); break;
case "description": def.setDescription(val); break;
case "name": def.setName(val); break;
case "required": def.setRequired(Boolean.valueOf(val)); break;
case "type": def.setType(RestParamType.valueOf(val)); break;
default: return false;
}
return true;
}, (def, key) -> {
switch (key) {
case "value": doAdd(doParseText(), def.getAllowableValues(), def::setAllowableValues); break;
case "examples": doAdd(doParseRestPropertyDefinition(), def.getExamples(), def::setExamples); break;
default: return false;
}
return true;
}, noValueHandler());
}
protected RestOperationResponseMsgDefinition doParseRestOperationResponseMsgDefinition() throws IOException, XmlPullParserException {
return doParse(new RestOperationResponseMsgDefinition(), (def, key, val) -> {
switch (key) {
case "code": def.setCode(val); break;
case "message": def.setMessage(val); break;
case "responseModel": def.setResponseModel(val); break;
default: return false;
}
return true;
}, (def, key) -> {
switch (key) {
case "examples": doAdd(doParseRestPropertyDefinition(), def.getExamples(), def::setExamples); break;
case "header": doAdd(doParseRestOperationResponseHeaderDefinition(), def.getHeaders(), def::setHeaders); break;
default: return false;
}
return true;
}, noValueHandler());
}
protected SecurityDefinition doParseSecurityDefinition() throws IOException, XmlPullParserException {
return doParse(new SecurityDefinition(), (def, key, val) -> {
switch (key) {
case "key": def.setKey(val); break;
case "scopes": def.setScopes(val); break;
default: return false;
}
return true;
}, noElementHandler(), noValueHandler());
}
protected GetDefinition doParseGetDefinition() throws IOException, XmlPullParserException {
return doParse(new GetDefinition(),
verbDefinitionAttributeHandler(), verbDefinitionElementHandler(), noValueHandler());
}
protected HeadDefinition doParseHeadDefinition() throws IOException, XmlPullParserException {
return doParse(new HeadDefinition(),
verbDefinitionAttributeHandler(), verbDefinitionElementHandler(), noValueHandler());
}
protected PatchDefinition doParsePatchDefinition() throws IOException, XmlPullParserException {
return doParse(new PatchDefinition(),
verbDefinitionAttributeHandler(), verbDefinitionElementHandler(), noValueHandler());
}
protected PostDefinition doParsePostDefinition() throws IOException, XmlPullParserException {
return doParse(new PostDefinition(),
verbDefinitionAttributeHandler(), verbDefinitionElementHandler(), noValueHandler());
}
protected PutDefinition doParsePutDefinition() throws IOException, XmlPullParserException {
return doParse(new PutDefinition(),
verbDefinitionAttributeHandler(), verbDefinitionElementHandler(), noValueHandler());
}
protected RestConfigurationDefinition doParseRestConfigurationDefinition() throws IOException, XmlPullParserException {
return doParse(new RestConfigurationDefinition(), (def, key, val) -> {
switch (key) {
case "apiComponent": def.setApiComponent(val); break;
case "apiContextIdPattern": def.setApiContextIdPattern(val); break;
case "apiContextListing": def.setApiContextListing(Boolean.valueOf(val)); break;
case "apiContextPath": def.setApiContextPath(val); break;
case "apiContextRouteId": def.setApiContextRouteId(val); break;
case "apiHost": def.setApiHost(val); break;
case "apiVendorExtension": def.setApiVendorExtension(Boolean.valueOf(val)); break;
case "bindingMode": def.setBindingMode(RestBindingMode.valueOf(val)); break;
case "clientRequestValidation": def.setClientRequestValidation(Boolean.valueOf(val)); break;
case "component": def.setComponent(val); break;
case "contextPath": def.setContextPath(val); break;
case "enableCORS": def.setEnableCORS(Boolean.valueOf(val)); break;
case "host": def.setHost(val); break;
case "hostNameResolver": def.setHostNameResolver(RestHostNameResolver.valueOf(val)); break;
case "jsonDataFormat": def.setJsonDataFormat(val); break;
case "port": def.setPort(val); break;
case "producerApiDoc": def.setProducerApiDoc(val); break;
case "producerComponent": def.setProducerComponent(val); break;
case "scheme": def.setScheme(val); break;
case "skipBindingOnErrorCode": def.setSkipBindingOnErrorCode(Boolean.valueOf(val)); break;
case "useXForwardHeaders": def.setUseXForwardHeaders(Boolean.valueOf(val)); break;
case "xmlDataFormat": def.setXmlDataFormat(val); break;
default: return false;
}
return true;
}, (def, key) -> {
switch (key) {
case "apiProperty": doAdd(doParseRestPropertyDefinition(), def.getApiProperties(), def::setApiProperties); break;
case "componentProperty": doAdd(doParseRestPropertyDefinition(), def.getComponentProperties(), def::setComponentProperties); break;
case "consumerProperty": doAdd(doParseRestPropertyDefinition(), def.getConsumerProperties(), def::setConsumerProperties); break;
case "corsHeaders": doAdd(doParseRestPropertyDefinition(), def.getCorsHeaders(), def::setCorsHeaders); break;
case "dataFormatProperty": doAdd(doParseRestPropertyDefinition(), def.getDataFormatProperties(), def::setDataFormatProperties); break;
case "endpointProperty": doAdd(doParseRestPropertyDefinition(), def.getEndpointProperties(), def::setEndpointProperties); break;
default: return false;
}
return true;
}, noValueHandler());
}
protected RestPropertyDefinition doParseRestPropertyDefinition() throws IOException, XmlPullParserException {
return doParse(new RestPropertyDefinition(), (def, key, val) -> {
switch (key) {
case "key": def.setKey(val); break;
case "value": def.setValue(val); break;
default: return false;
}
return true;
}, noElementHandler(), noValueHandler());
}
protected RestSecuritiesDefinition doParseRestSecuritiesDefinition() throws IOException, XmlPullParserException {
return doParse(new RestSecuritiesDefinition(),
noAttributeHandler(), (def, key) -> {
switch (key) {
case "apiKey": doAdd(doParseRestSecurityApiKey(), def.getSecurityDefinitions(), def::setSecurityDefinitions); break;
case "basicAuth": doAdd(doParseRestSecurityBasicAuth(), def.getSecurityDefinitions(), def::setSecurityDefinitions); break;
case "bearer": doAdd(doParseRestSecurityBearerToken(), def.getSecurityDefinitions(), def::setSecurityDefinitions); break;
case "oauth2": doAdd(doParseRestSecurityOAuth2(), def.getSecurityDefinitions(), def::setSecurityDefinitions); break;
case "openIdConnect": doAdd(doParseRestSecurityOpenIdConnect(), def.getSecurityDefinitions(), def::setSecurityDefinitions); break;
case "mutualTLS": doAdd(doParseRestSecurityMutualTLS(), def.getSecurityDefinitions(), def::setSecurityDefinitions); break;
default: return false;
}
return true;
}, noValueHandler());
}
protected RestSecuritiesRequirement doParseRestSecuritiesRequirement() throws IOException, XmlPullParserException {
return doParse(new RestSecuritiesRequirement(),
noAttributeHandler(), (def, key) -> {
if ("securityRequirement".equals(key)) {
doAdd(doParseSecurityDefinition(), def.getSecurityRequirements(), def::setSecurityRequirements);
return true;
}
return false;
}, noValueHandler());
}
protected RestOperationResponseHeaderDefinition doParseRestOperationResponseHeaderDefinition() throws IOException, XmlPullParserException {
return doParse(new RestOperationResponseHeaderDefinition(), (def, key, val) -> {
switch (key) {
case "arrayType": def.setArrayType(val); break;
case "collectionFormat": def.setCollectionFormat(CollectionFormat.valueOf(val)); break;
case "dataFormat": def.setDataFormat(val); break;
case "dataType": def.setDataType(val); break;
case "description": def.setDescription(val); break;
case "example": def.setExample(val); break;
case "name": def.setName(val); break;
default: return false;
}
return true;
}, (def, key) -> {
if ("value".equals(key)) {
doAdd(doParseText(), def.getAllowableValues(), def::setAllowableValues);
return true;
}
return false;
}, noValueHandler());
}
protected <T extends RestSecurityDefinition> AttributeHandler<T> restSecurityDefinitionAttributeHandler() {
return (def, key, val) -> {
switch (key) {
case "description": def.setDescription(val); break;
case "key": def.setKey(val); break;
default: return false;
}
return true;
};
}
protected RestSecurityApiKey doParseRestSecurityApiKey() throws IOException, XmlPullParserException {
return doParse(new RestSecurityApiKey(), (def, key, val) -> {
switch (key) {
case "inCookie": def.setInCookie(val); break;
case "inHeader": def.setInHeader(val); break;
case "inQuery": def.setInQuery(val); break;
case "name": def.setName(val); break;
default: return restSecurityDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected RestSecurityBasicAuth doParseRestSecurityBasicAuth() throws IOException, XmlPullParserException {
return doParse(new RestSecurityBasicAuth(),
restSecurityDefinitionAttributeHandler(), noElementHandler(), noValueHandler());
}
protected RestSecurityBearerToken doParseRestSecurityBearerToken() throws IOException, XmlPullParserException {
return doParse(new RestSecurityBearerToken(), (def, key, val) -> {
if ("format".equals(key)) {
def.setFormat(val);
return true;
}
return restSecurityDefinitionAttributeHandler().accept(def, key, val);
}, noElementHandler(), noValueHandler());
}
protected RestSecurityMutualTLS doParseRestSecurityMutualTLS() throws IOException, XmlPullParserException {
return doParse(new RestSecurityMutualTLS(),
restSecurityDefinitionAttributeHandler(), noElementHandler(), noValueHandler());
}
protected RestSecurityOAuth2 doParseRestSecurityOAuth2() throws IOException, XmlPullParserException {
return doParse(new RestSecurityOAuth2(), (def, key, val) -> {
switch (key) {
case "authorizationUrl": def.setAuthorizationUrl(val); break;
case "flow": def.setFlow(val); break;
case "refreshUrl": def.setRefreshUrl(val); break;
case "tokenUrl": def.setTokenUrl(val); break;
default: return restSecurityDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, (def, key) -> {
if ("scopes".equals(key)) {
doAdd(doParseRestPropertyDefinition(), def.getScopes(), def::setScopes);
return true;
}
return false;
}, noValueHandler());
}
protected RestSecurityOpenIdConnect doParseRestSecurityOpenIdConnect() throws IOException, XmlPullParserException {
return doParse(new RestSecurityOpenIdConnect(), (def, key, val) -> {
if ("url".equals(key)) {
def.setUrl(val);
return true;
}
return restSecurityDefinitionAttributeHandler().accept(def, key, val);
}, noElementHandler(), noValueHandler());
}
public Optional<RestsDefinition> parseRestsDefinition()
throws IOException, XmlPullParserException {
String tag = getNextTag("rests", "rest");
if (tag != null) {
switch (tag) {
case "rests" : return Optional.of(doParseRestsDefinition());
case "rest" : return parseSingleRestsDefinition();
}
}
return Optional.empty();
}
private Optional<RestsDefinition> parseSingleRestsDefinition()
throws IOException, XmlPullParserException {
Optional<RestDefinition> single = Optional.of(doParseRestDefinition());
if (single.isPresent()) {
List<RestDefinition> list = new ArrayList<>();
list.add(single.get());
RestsDefinition def = new RestsDefinition();
def.setRests(list);
return Optional.of(def);
}
return Optional.empty();
}
protected RestsDefinition doParseRestsDefinition() throws IOException, XmlPullParserException {
return doParse(new RestsDefinition(),
optionalIdentifiedDefinitionAttributeHandler(), (def, key) -> {
if ("rest".equals(key)) {
doAdd(doParseRestDefinition(), def.getRests(), def::setRests);
return true;
}
return optionalIdentifiedDefinitionElementHandler().accept(def, key);
}, noValueHandler());
}
protected CustomTransformerDefinition doParseCustomTransformerDefinition() throws IOException, XmlPullParserException {
return doParse(new CustomTransformerDefinition(), (def, key, val) -> {
switch (key) {
case "className": def.setClassName(val); break;
case "ref": def.setRef(val); break;
default: return transformerDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected <T extends TransformerDefinition> AttributeHandler<T> transformerDefinitionAttributeHandler() {
return (def, key, val) -> {
switch (key) {
case "fromType": def.setFromType(val); break;
case "scheme": def.setScheme(val); break;
case "toType": def.setToType(val); break;
default: return false;
}
return true;
};
}
protected DataFormatTransformerDefinition doParseDataFormatTransformerDefinition() throws IOException, XmlPullParserException {
return doParse(new DataFormatTransformerDefinition(), (def, key, val) -> {
if ("ref".equals(key)) {
def.setRef(val);
return true;
}
return transformerDefinitionAttributeHandler().accept(def, key, val);
}, (def, key) -> {
DataFormatDefinition v = doParseDataFormatDefinitionRef(key);
if (v != null) {
def.setDataFormatType(v);
return true;
}
return false;
}, noValueHandler());
}
protected EndpointTransformerDefinition doParseEndpointTransformerDefinition() throws IOException, XmlPullParserException {
return doParse(new EndpointTransformerDefinition(), (def, key, val) -> {
switch (key) {
case "ref": def.setRef(val); break;
case "uri": def.setUri(val); break;
default: return transformerDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected TransformersDefinition doParseTransformersDefinition() throws IOException, XmlPullParserException {
return doParse(new TransformersDefinition(),
noAttributeHandler(), (def, key) -> {
switch (key) {
case "dataFormatTransformer": doAdd(doParseDataFormatTransformerDefinition(), def.getTransformers(), def::setTransformers); break;
case "endpointTransformer": doAdd(doParseEndpointTransformerDefinition(), def.getTransformers(), def::setTransformers); break;
case "customTransformer": doAdd(doParseCustomTransformerDefinition(), def.getTransformers(), def::setTransformers); break;
default: return false;
}
return true;
}, noValueHandler());
}
protected CustomValidatorDefinition doParseCustomValidatorDefinition() throws IOException, XmlPullParserException {
return doParse(new CustomValidatorDefinition(), (def, key, val) -> {
switch (key) {
case "className": def.setClassName(val); break;
case "ref": def.setRef(val); break;
default: return validatorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected <T extends ValidatorDefinition> AttributeHandler<T> validatorDefinitionAttributeHandler() {
return (def, key, val) -> {
if ("type".equals(key)) {
def.setType(val);
return true;
}
return false;
};
}
protected EndpointValidatorDefinition doParseEndpointValidatorDefinition() throws IOException, XmlPullParserException {
return doParse(new EndpointValidatorDefinition(), (def, key, val) -> {
switch (key) {
case "ref": def.setRef(val); break;
case "uri": def.setUri(val); break;
default: return validatorDefinitionAttributeHandler().accept(def, key, val);
}
return true;
}, noElementHandler(), noValueHandler());
}
protected PredicateValidatorDefinition doParsePredicateValidatorDefinition() throws IOException, XmlPullParserException {
return doParse(new PredicateValidatorDefinition(),
validatorDefinitionAttributeHandler(), (def, key) -> {
ExpressionDefinition v = doParseExpressionDefinitionRef(key);
if (v != null) {
def.setExpression(v);
return true;
}
return false;
}, noValueHandler());
}
protected ValidatorsDefinition doParseValidatorsDefinition() throws IOException, XmlPullParserException {
return doParse(new ValidatorsDefinition(),
noAttributeHandler(), (def, key) -> {
switch (key) {
case "endpointValidator": doAdd(doParseEndpointValidatorDefinition(), def.getValidators(), def::setValidators); break;
case "predicateValidator": doAdd(doParsePredicateValidatorDefinition(), def.getValidators(), def::setValidators); break;
case "customValidator": doAdd(doParseCustomValidatorDefinition(), def.getValidators(), def::setValidators); break;
default: return false;
}
return true;
}, noValueHandler());
}
protected ProcessorDefinition doParseProcessorDefinitionRef(String key) throws IOException, XmlPullParserException {
switch (key) {
case "aggregate": return doParseAggregateDefinition();
case "bean": return doParseBeanDefinition();
case "doCatch": return doParseCatchDefinition();
case "when": return doParseWhenDefinition();
case "choice": return doParseChoiceDefinition();
case "otherwise": return doParseOtherwiseDefinition();
case "circuitBreaker": return doParseCircuitBreakerDefinition();
case "claimCheck": return doParseClaimCheckDefinition();
case "convertBodyTo": return doParseConvertBodyDefinition();
case "delay": return doParseDelayDefinition();
case "dynamicRouter": return doParseDynamicRouterDefinition();
case "enrich": return doParseEnrichDefinition();
case "filter": return doParseFilterDefinition();
case "doFinally": return doParseFinallyDefinition();
case "idempotentConsumer": return doParseIdempotentConsumerDefinition();
case "inOnly": return doParseInOnlyDefinition();
case "inOut": return doParseInOutDefinition();
case "intercept": return doParseInterceptDefinition();
case "interceptFrom": return doParseInterceptFromDefinition();
case "interceptSendToEndpoint": return doParseInterceptSendToEndpointDefinition();
case "kamelet": return doParseKameletDefinition();
case "loadBalance": return doParseLoadBalanceDefinition();
case "log": return doParseLogDefinition();
case "loop": return doParseLoopDefinition();
case "marshal": return doParseMarshalDefinition();
case "multicast": return doParseMulticastDefinition();
case "onCompletion": return doParseOnCompletionDefinition();
case "onException": return doParseOnExceptionDefinition();
case "onFallback": return doParseOnFallbackDefinition();
case "pipeline": return doParsePipelineDefinition();
case "policy": return doParsePolicyDefinition();
case "pollEnrich": return doParsePollEnrichDefinition();
case "process": return doParseProcessDefinition();
case "recipientList": return doParseRecipientListDefinition();
case "removeHeader": return doParseRemoveHeaderDefinition();
case "removeHeaders": return doParseRemoveHeadersDefinition();
case "removeProperties": return doParseRemovePropertiesDefinition();
case "removeProperty": return doParseRemovePropertyDefinition();
case "resequence": return doParseResequenceDefinition();
case "rollback": return doParseRollbackDefinition();
case "route": return doParseRouteDefinition();
case "routingSlip": return doParseRoutingSlipDefinition();
case "saga": return doParseSagaDefinition();
case "sample": return doParseSamplingDefinition();
case "script": return doParseScriptDefinition();
case "setBody": return doParseSetBodyDefinition();
case "setExchangePattern": return doParseSetExchangePatternDefinition();
case "setHeader": return doParseSetHeaderDefinition();
case "setProperty": return doParseSetPropertyDefinition();
case "sort": return doParseSortDefinition();
case "split": return doParseSplitDefinition();
case "step": return doParseStepDefinition();
case "stop": return doParseStopDefinition();
case "doSwitch": return doParseSwitchDefinition();
case "threads": return doParseThreadsDefinition();
case "throttle": return doParseThrottleDefinition();
case "throwException": return doParseThrowExceptionDefinition();
case "to": return doParseToDefinition();
case "toD": return doParseToDynamicDefinition();
case "transacted": return doParseTransactedDefinition();
case "transform": return doParseTransformDefinition();
case "doTry": return doParseTryDefinition();
case "unmarshal": return doParseUnmarshalDefinition();
case "validate": return doParseValidateDefinition();
case "wireTap": return doParseWireTapDefinition();
case "serviceCall": return doParseServiceCallDefinition();
default: return null;
}
}
protected ExpressionDefinition doParseExpressionDefinitionRef(String key) throws IOException, XmlPullParserException {
switch (key) {
case "expressionDefinition": return doParseExpressionDefinition();
case "csimple": return doParseCSimpleExpression();
case "constant": return doParseConstantExpression();
case "datasonnet": return doParseDatasonnetExpression();
case "exchangeProperty": return doParseExchangePropertyExpression();
case "groovy": return doParseGroovyExpression();
case "header": return doParseHeaderExpression();
case "hl7terser": return doParseHl7TerserExpression();
case "joor": return doParseJoorExpression();
case "jsonpath": return doParseJsonPathExpression();
case "language": return doParseLanguageExpression();
case "method": return doParseMethodCallExpression();
case "mvel": return doParseMvelExpression();
case "ognl": return doParseOgnlExpression();
case "ref": return doParseRefExpression();
case "simple": return doParseSimpleExpression();
case "spel": return doParseSpELExpression();
case "tokenize": return doParseTokenizerExpression();
case "xtokenize": return doParseXMLTokenizerExpression();
case "xpath": return doParseXPathExpression();
case "xquery": return doParseXQueryExpression();
default: return null;
}
}
protected DataFormatDefinition doParseDataFormatDefinitionRef(String key) throws IOException, XmlPullParserException {
switch (key) {
case "asn1": return doParseASN1DataFormat();
case "any23": return doParseAny23DataFormat();
case "avro": return doParseAvroDataFormat();
case "barcode": return doParseBarcodeDataFormat();
case "base64": return doParseBase64DataFormat();
case "beanio": return doParseBeanioDataFormat();
case "bindy": return doParseBindyDataFormat();
case "cbor": return doParseCBORDataFormat();
case "crypto": return doParseCryptoDataFormat();
case "csv": return doParseCsvDataFormat();
case "custom": return doParseCustomDataFormat();
case "fhirJson": return doParseFhirJsonDataFormat();
case "fhirXml": return doParseFhirXmlDataFormat();
case "flatpack": return doParseFlatpackDataFormat();
case "grok": return doParseGrokDataFormat();
case "gzipDeflater": return doParseGzipDeflaterDataFormat();
case "hl7": return doParseHL7DataFormat();
case "ical": return doParseIcalDataFormat();
case "jacksonXml": return doParseJacksonXMLDataFormat();
case "jaxb": return doParseJaxbDataFormat();
case "jsonApi": return doParseJsonApiDataFormat();
case "json": return doParseJsonDataFormat();
case "lzf": return doParseLZFDataFormat();
case "mimeMultipart": return doParseMimeMultipartDataFormat();
case "pgp": return doParsePGPDataFormat();
case "protobuf": return doParseProtobufDataFormat();
case "rss": return doParseRssDataFormat();
case "soap": return doParseSoapDataFormat();
case "syslog": return doParseSyslogDataFormat();
case "tarFile": return doParseTarFileDataFormat();
case "thrift": return doParseThriftDataFormat();
case "tidyMarkup": return doParseTidyMarkupDataFormat();
case "univocityCsv": return doParseUniVocityCsvDataFormat();
case "univocityFixed": return doParseUniVocityFixedDataFormat();
case "univocityTsv": return doParseUniVocityTsvDataFormat();
case "xmlSecurity": return doParseXMLSecurityDataFormat();
case "xstream": return doParseXStreamDataFormat();
case "yaml": return doParseYAMLDataFormat();
case "zipDeflater": return doParseZipDeflaterDataFormat();
case "zipFile": return doParseZipFileDataFormat();
default: return null;
}
}
}
//CHECKSTYLE:ON
| CAMEL-17308: Remove verb as an allowed CAMEL REST YAML element.
| core/camel-xml-io/src/generated/java/org/apache/camel/xml/in/ModelParser.java | CAMEL-17308: Remove verb as an allowed CAMEL REST YAML element. | <ide><path>ore/camel-xml-io/src/generated/java/org/apache/camel/xml/in/ModelParser.java
<ide> }
<ide> return true;
<ide> };
<del> }
<del> protected VerbDefinition doParseVerbDefinition() throws IOException, XmlPullParserException {
<del> return doParse(new VerbDefinition(), verbDefinitionAttributeHandler(), verbDefinitionElementHandler(), noValueHandler());
<ide> }
<ide> protected RestOperationParamDefinition doParseRestOperationParamDefinition() throws IOException, XmlPullParserException {
<ide> return doParse(new RestOperationParamDefinition(), (def, key, val) -> { |
|
Java | apache-2.0 | 21420bcdd83b56efbbbce6491ea16b6bd9a63c9b | 0 | chibenwa/james,aduprat/james,chibenwa/james,rouazana/james,aduprat/james,aduprat/james,chibenwa/james,chibenwa/james,rouazana/james,aduprat/james,rouazana/james,rouazana/james | /* ====================================================================
* The Apache Software License, Version 1.1
*
* Copyright (c) 2000-2003 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Apache", "Jakarta", "JAMES" and "Apache Software Foundation"
* must not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* Portions of this software are based upon public domain software
* originally written at the National Center for Supercomputing Applications,
* University of Illinois, Urbana-Champaign.
*/
package org.apache.james.transport.mailets;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Locale;
import java.util.StringTokenizer;
import java.util.Vector;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.apache.james.util.RFC2822Headers;
import org.apache.james.util.RFC822DateFormat;
import org.apache.mailet.GenericMailet;
import org.apache.mailet.Mail;
import org.apache.mailet.MailAddress;
/**
*<P>A mailet providing configurable redirection services<BR>
*This mailet can produce listserver, forward and notify behaviour, with the original
*message intact, attached, appended or left out altogether.<BR>
*This built in functionality is controlled by the configuration as laid out below.</P>
*<P>However it is also designed to be easily subclassed to make authoring redirection
*mailets simple. <BR>
*By extending it and overriding one or more of these methods new behaviour can
*be quickly created without the author having to address any other issue than
*the relevant one:</P>
*<UL>
*<LI>attachError() , should error messages be appended to the message</LI>
*<LI>getAttachmentType(), what should be attached to the message</LI>
*<LI>getInLineType(), what should be included in the message</LI>
*<LI>getMessage(), The text of the message itself</LI>
*<LI>getRecipients(), the recipients the mail is sent to</LI>
*<LI>getReplyTo(), where replys to this message will be sent</LI>
*<LI>getSender(), who the mail is from</LI>
*<LI>getSubjectPrefix(), a prefix to be added to the message subject</LI>
*<LI>getTo(), a list of people to whom the mail is *apparently* sent</LI>
*<LI>getPassThrough(), should this mailet allow the original message to continue processing or GHOST it.</LI>
*<LI>isStatic(), should this mailet run the get methods for every mail, or just
*once. </LI>
*</UL>
*<P>The configuration parameters are:</P>
*<TABLE width="75%" border="0" cellspacing="2" cellpadding="2">
*<TR>
*<TD width="20%"><recipients></TD>
*<TD width="80%">A comma delimited list of email addresses for recipients of
*this message, it will use the "to" list if not specified. These
*addresses will only appear in the To: header if no "to" list is
*supplied.</TD>
*</TR>
*<TR>
*<TD width="20%"><to></TD>
*<TD width="80%">A comma delimited list of addresses to appear in the To: header,
*the email will only be delivered to these addresses if they are in the recipients
*list.<BR>
*The recipients list will be used if this is not supplied.</TD>
*</TR>
*<TR>
*<TD width="20%"><sender></TD>
*<TD width="80%">A single email address to appear in the From: header <BR>
*It can include constants "sender" and "postmaster"</TD>
*</TR>
*<TR>
*<TD width="20%"><message></TD>
*<TD width="80%">A text message to be the body of the email. Can be omitted.</TD>
*</TR>
*<TR>
*<TD width="20%"><inline></TD>
*<TD width="80%">
*<P>One of the following items:</P>
*<UL>
*<LI>unaltered The original message is the new
* message, for forwarding/aliasing</LI>
*<LI>heads The
* headers of the original message are appended to the message</LI>
*<LI>body The
* body of the original is appended to the new message</LI>
*<LI>all Both
* headers and body are appended</LI>
*<LI>none Neither
* body nor headers are appended</LI>
*</UL>
*</TD>
*</TR>
*<TR>
*<TD width="20%"><attachment></TD>
*<TD width="80%">
*<P>One of the following items:</P>
*<UL>
*<LI>heads The headers of the original
* are attached as text</LI>
*<LI>body The body of the original
* is attached as text</LI>
*<LI>all Both
* headers and body are attached as a single text file</LI>
*<LI>none Nothing is attached</LI>
*<LI>message The original message is attached as type message/rfc822,
* this means that it can, in many cases, be opened, resent, fw'd, replied
* to etc by email client software.</LI>
*</UL>
*</TD>
*</TR>
*<TR>
*<TD width="20%"><passThrough></TD>
*<TD width="80%">TRUE or FALSE, if true the original message continues in the
*mailet processor after this mailet is finished. False causes the original
*to be stopped.</TD>
*</TR>
*<TR>
*<TD width="20%"><attachError></TD>
*<TD width="80%">TRUE or FALSE, if true any error message available to the
*mailet is appended to the message body (except in the case of inline ==
*unaltered)</TD>
*</TR>
*<TR>
*<TD width="20%"><replyto></TD>
*<TD width="80%">A single email address to appear in the Rely-To: header, can
*also be "sender" or "postmaster", this header is not
*set if this is omited.</TD>
*</TR>
*<TR>
*<TD width="20%"><prefix></TD>
*<TD width="80%">An optional subject prefix prepended to the original message
*subject, for example:<BR>
*Undeliverable mail: </TD>
*</TR>
*<TR>
*<TD width="20%"><static></TD>
*<TD width="80%">
*<P>TRUE or FALSE. If this is TRUE it tells the mailet that it can
*reuse all the initial parameters (to, from, etc) without re-calculating
*their values. This will boost performance where a redirect task
*doesn't contain any dynamic values. If this is FALSE, it tells the
*mailet to recalculate the values for each e-mail processed.</P>
*<P>Note: If you use "magic words" such as "sender" in the <sender>
*tag, you must NOT use set static to TRUE.</P>
*<P>This defaults to false.<BR>
*</TD>
*</TR>
*</TABLE>
*
*<P>Example:</P>
*<P> <mailet match="RecipientIs=test@localhost" class="Redirect"><BR>
*<recipients>x@localhost, y@localhost, z@localhost</recipients><BR>
*<to>list@localhost</to><BR>
*<sender>owner@localhost</sender><BR>
*<message>sent on from James</message><BR>
*<inline>unaltered</inline><BR>
*<passThrough>FALSE</passThrough><BR>
*<replyto>postmaster</replyto><BR>
*<prefix xml:space="preserve">[test mailing] </prefix><BR>
*<!-- note the xml:space="preserve" to preserve whitespace --><BR>
*<static>TRUE</static><BR>
*</mailet><BR>
*</P>
*<P>and:</P>
*<P> <mailet match="All" class="Redirect"><BR>
*<recipients>x@localhost</recipients><BR>
*<sender>postmaster</sender><BR>
*<message xml:space="preserve">Message marked as spam:<BR>
*</message><BR>
*<inline>heads</inline><BR>
*<attachment>message</attachment><BR>
*<passThrough>FALSE</passThrough><BR>
*<attachError>TRUE</attachError><BR>
*<replyto>postmaster</replyto><BR>
*<prefix>[spam notification]</prefix><BR>
*<static>TRUE</static><BR>
*</mailet></P>
*
* @author Danny Angus <[email protected]>
*
*/
public class Redirect extends GenericMailet {
/**
* Controls certain log messages
*/
private boolean isDebug = false;
// The values that indicate how to attach the original mail
// to the redirected mail.
private static final int UNALTERED = 0;
private static final int HEADS = 1;
private static final int BODY = 2;
private static final int ALL = 3;
private static final int NONE = 4;
private static final int MESSAGE = 5;
private InternetAddress[] apparentlyTo;
private String messageText;
private Collection recipients;
private MailAddress replyTo;
private MailAddress sender;
private RFC822DateFormat rfc822DateFormat = new RFC822DateFormat();
/**
* returns one of these values to indicate how to attach the original message
*<ul>
* <li>BODY : original message body is attached as plain text to the new message</li>
* <li>HEADS : original message headers are attached as plain text to the new message</li>
* <li>ALL : original is attached as plain text with all headers</li>
* <li>MESSAGE : original message is attached as type message/rfc822, a complete mail message.</li>
* <li>NONE : original is not attached</li>
*</ul>
*
*/
public int getAttachmentType() {
if(getInitParameter("attachment") == null) {
return NONE;
} else {
return getTypeCode(getInitParameter("attachment"));
}
}
/**
* returns one of these values to indicate how to append the original message
*<ul>
* <li>UNALTERED : original message is the new message body</li>
* <li>BODY : original message body is appended to the new message</li>
* <li>HEADS : original message headers are appended to the new message</li>
* <li>ALL : original is appended with all headers</li>
* <li>NONE : original is not appended</li>
*</ul>
*/
public int getInLineType() {
if(getInitParameter("inline") == null) {
return BODY;
} else {
return getTypeCode(getInitParameter("inline"));
}
}
/**
* Return a string describing this mailet.
*
* @return a string describing this mailet
*/
public String getMailetInfo() {
return "Resend Mailet";
}
/**
* must return either an empty string, or a message to which the redirect can be attached/appended
*/
public String getMessage() {
if(getInitParameter("message") == null) {
return "";
} else {
return getInitParameter("message");
}
}
/**
* return true to allow thie original message to continue through the processor, false to GHOST it
*/
public boolean getPassThrough() {
if(getInitParameter("passThrough") == null) {
return false;
} else {
return new Boolean(getInitParameter("passThrough")).booleanValue();
}
}
/**
* must return a Collection of recipient MailAddresses
*/
public Collection getRecipients() {
Collection newRecipients = new HashSet();
String addressList = (getInitParameter("recipients") == null)
? getInitParameter("to")
: getInitParameter("recipients");
StringTokenizer st = new StringTokenizer(addressList, ",", false);
while(st.hasMoreTokens()) {
try {
newRecipients.add(new MailAddress(st.nextToken()));
} catch(Exception e) {
log("add recipient failed in getRecipients");
}
}
return newRecipients;
}
/**
* Returns the reply to address as a string.
*
* @return the replyto address for the mail as a string
*/
public MailAddress getReplyTo() {
String sr = getInitParameter("replyto");
if(sr != null) {
MailAddress rv;
if(sr.compareTo("postmaster") == 0) {
rv = getMailetContext().getPostmaster();
return rv;
}
if(sr.compareTo("sender") == 0) {
return null;
}
try {
rv = new MailAddress(sr);
return rv;
} catch(Exception e) {
log("Parse error in getReplyTo " + sr);
}
}
return null;
}
/**
* returns the senders address, as a MailAddress
*/
public MailAddress getSender() {
String sr = getInitParameter("sender");
if(sr != null) {
MailAddress rv;
if(sr.compareTo("postmaster") == 0) {
rv = getMailetContext().getPostmaster();
return rv;
}
if(sr.compareTo("sender") == 0) {
return null;
}
try {
rv = new MailAddress(sr);
return rv;
} catch(Exception e) {
log("Parse error in getSender " + sr);
}
}
return null;
}
/**
* return true to reduce calls to getTo, getSender, getRecipients, getReplyTo amd getMessage
* where these values don't change (eg hard coded, or got at startup from the mailet config)<br>
* return false where any of these methods generate their results dynamically eg in response to the message being processed,
* or by refrence to a repository of users
*/
public boolean isStatic() {
if(getInitParameter("static") == null) {
return false;
}
return new Boolean(getInitParameter("static")).booleanValue();
}
/**
* return a prefix for the message subject
*/
public String getSubjectPrefix() {
if(getInitParameter("prefix") == null) {
return "";
} else {
return getInitParameter("prefix");
}
}
/**
* returns an array of InternetAddress 'es for the To: header
*/
public InternetAddress[] getTo() {
String addressList = (getInitParameter("to") == null)
? getInitParameter("recipients") : getInitParameter("to");
StringTokenizer rec = new StringTokenizer(addressList, ",");
int tokensn = rec.countTokens();
InternetAddress[] iaarray = new InternetAddress[tokensn];
String tokenx = "";
for(int i = 0; i < tokensn; ++i) {
try {
tokenx = rec.nextToken();
iaarray[i] = new InternetAddress(tokenx);
} catch(Exception e) {
log("Internet address exception in getTo()");
}
}
return iaarray;
}
/**
* return true to append a description of any error to the main body part
* if getInlineType does not return "UNALTERED"
*/
public boolean attachError() {
if(getInitParameter("attachError") == null) {
return false;
} else {
return new Boolean(getInitParameter("attachError")).booleanValue();
}
}
/**
* init will setup static values for sender, recipients, message text, and reply to
* <br> if isStatic() returns true
* it calls getSender(), getReplyTo(), getMessage(), and getRecipients() and getTo()
*
*/
public void init() throws MessagingException {
if (isDebug) {
log("Redirect init");
}
isDebug = (getInitParameter("debug") == null) ? false : new Boolean(getInitParameter("debug")).booleanValue();
if(isStatic()) {
sender = getSender();
replyTo = getReplyTo();
messageText = getMessage();
recipients = getRecipients();
apparentlyTo = getTo();
if (isDebug) {
StringBuffer logBuffer =
new StringBuffer(1024)
.append("static, sender=")
.append(sender)
.append(", replyTo=")
.append(replyTo)
.append(", message=")
.append(messageText)
.append(" ");
log(logBuffer.toString());
}
}
}
/**
* Service does the hard work,and redirects the mail in the form specified
*
* @param mail the mail to process and redirect
* @throws MessagingException if a problem arising formulating the redirected mail
*/
public void service(Mail mail) throws MessagingException {
if(!isStatic()) {
sender = getSender();
replyTo = getReplyTo();
messageText = getMessage();
recipients = getRecipients();
apparentlyTo = getTo();
}
MimeMessage message = mail.getMessage();
MimeMessage reply = null;
//Create the message
if(getInLineType() != UNALTERED) {
if (isDebug) {
log("Alter message inline=:" + getInLineType());
}
reply = new MimeMessage(Session.getDefaultInstance(System.getProperties(),
null));
StringWriter sout = new StringWriter();
PrintWriter out = new PrintWriter(sout, true);
Enumeration heads = message.getAllHeaderLines();
String head = "";
StringBuffer headBuffer = new StringBuffer(1024);
while(heads.hasMoreElements()) {
headBuffer.append(heads.nextElement().toString()).append("\n");
}
head = headBuffer.toString();
boolean all = false;
if(messageText != null) {
out.println(messageText);
}
switch(getInLineType()) {
case ALL: //ALL:
all = true;
case HEADS: //HEADS:
out.println("Message Headers:");
out.println(head);
if(!all) {
break;
}
case BODY: //BODY:
out.println("Message:");
try {
out.println(message.getContent().toString());
} catch(Exception e) {
out.println("body unavailable");
}
break;
default:
case NONE: //NONE:
break;
}
MimeMultipart multipart = new MimeMultipart();
//Add message as the first mime body part
MimeBodyPart part = new MimeBodyPart();
part.setText(sout.toString());
part.setDisposition("inline");
multipart.addBodyPart(part);
if(getAttachmentType() != NONE) {
part = new MimeBodyPart();
switch(getAttachmentType()) {
case HEADS: //HEADS:
part.setText(head);
break;
case BODY: //BODY:
try {
part.setText(message.getContent().toString());
} catch(Exception e) {
part.setText("body unavailable");
}
break;
case ALL: //ALL:
StringBuffer textBuffer =
new StringBuffer(1024)
.append(head)
.append("\n\n")
.append(message.toString());
part.setText(textBuffer.toString());
break;
case MESSAGE: //MESSAGE:
part.setContent(message, "message/rfc822");
break;
}
part.setDisposition("Attachment");
multipart.addBodyPart(part);
}
reply.setContent(multipart);
reply.setHeader(RFC2822Headers.CONTENT_TYPE, multipart.getContentType());
reply.setRecipients(Message.RecipientType.TO, apparentlyTo);
} else {
// if we need the original, create a copy of this message to redirect
reply = getPassThrough() ? new MimeMessage(message) : message;
if (isDebug) {
log("Message resent unaltered.");
}
}
//Set additional headers
reply.setSubject(getSubjectPrefix() + message.getSubject());
if(reply.getHeader(RFC2822Headers.DATE) == null) {
reply.setHeader(RFC2822Headers.DATE, rfc822DateFormat.format(new Date()));
}
//
if(replyTo != null) {
InternetAddress[] iart = new InternetAddress[1];
iart[0] = replyTo.toInternetAddress();
reply.setReplyTo(iart);
}
if(sender == null) {
reply.setHeader(RFC2822Headers.FROM, message.getHeader(RFC2822Headers.FROM, ","));
sender = new MailAddress(((InternetAddress)message.getFrom()[0]).getAddress());
} else {
reply.setFrom(sender.toInternetAddress());
}
//Send it off...
getMailetContext().sendMail(sender, recipients, reply);
if(!getPassThrough()) {
mail.setState(Mail.GHOST);
}
}
/**
* A private method to convert types from string to int.
*
* @param param the string type
*
* @return the corresponding int enumeration
*/
private int getTypeCode(String param) {
int code;
param = param.toLowerCase(Locale.US);
if(param.compareTo("unaltered") == 0) {
return UNALTERED;
}
if(param.compareTo("heads") == 0) {
return HEADS;
}
if(param.compareTo("body") == 0) {
return BODY;
}
if(param.compareTo("all") == 0) {
return ALL;
}
if(param.compareTo("none") == 0) {
return NONE;
}
if(param.compareTo("message") == 0) {
return MESSAGE;
}
return NONE;
}
}
| src/java/org/apache/james/transport/mailets/Redirect.java | /* ====================================================================
* The Apache Software License, Version 1.1
*
* Copyright (c) 2000-2003 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Apache", "Jakarta", "JAMES" and "Apache Software Foundation"
* must not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* Portions of this software are based upon public domain software
* originally written at the National Center for Supercomputing Applications,
* University of Illinois, Urbana-Champaign.
*/
package org.apache.james.transport.mailets;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Locale;
import java.util.StringTokenizer;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.apache.mailet.GenericMailet;
import org.apache.mailet.Mail;
import org.apache.mailet.MailAddress;
import org.apache.mailet.RFC2822Headers;
import org.apache.mailet.dates.RFC822DateFormat;
/**
*<P>A mailet providing configurable redirection services<BR>
*This mailet can produce listserver, forward and notify behaviour, with the original
*message intact, attached, appended or left out altogether.<BR>
*This built in functionality is controlled by the configuration as laid out below.</P>
*<P>However it is also designed to be easily subclassed to make authoring redirection
*mailets simple. <BR>
*By extending it and overriding one or more of these methods new behaviour can
*be quickly created without the author having to address any other issue than
*the relevant one:</P>
*<UL>
*<LI>attachError() , should error messages be appended to the message</LI>
*<LI>getAttachmentType(), what should be attached to the message</LI>
*<LI>getInLineType(), what should be included in the message</LI>
*<LI>getMessage(), The text of the message itself</LI>
*<LI>getRecipients(), the recipients the mail is sent to</LI>
*<LI>getReplyTo(), where replys to this message will be sent</LI>
*<LI>getSender(), who the mail is from</LI>
*<LI>getSubjectPrefix(), a prefix to be added to the message subject</LI>
*<LI>getTo(), a list of people to whom the mail is *apparently* sent</LI>
*<LI>getPassThrough(), should this mailet allow the original message to continue processing or GHOST it.</LI>
*<LI>isStatic(), should this mailet run the get methods for every mail, or just
*once. </LI>
*</UL>
*<P>The configuration parameters are:</P>
*<TABLE width="75%" border="0" cellspacing="2" cellpadding="2">
*<TR>
*<TD width="20%"><recipients></TD>
*<TD width="80%">A comma delimited list of email addresses for recipients of
*this message, it will use the "to" list if not specified. These
*addresses will only appear in the To: header if no "to" list is
*supplied.</TD>
*</TR>
*<TR>
*<TD width="20%"><to></TD>
*<TD width="80%">A comma delimited list of addresses to appear in the To: header,
*the email will only be delivered to these addresses if they are in the recipients
*list.<BR>
*The recipients list will be used if this is not supplied.</TD>
*</TR>
*<TR>
*<TD width="20%"><sender></TD>
*<TD width="80%">A single email address to appear in the From: header <BR>
*It can include constants "sender" and "postmaster"</TD>
*</TR>
*<TR>
*<TD width="20%"><message></TD>
*<TD width="80%">A text message to be the body of the email. Can be omitted.</TD>
*</TR>
*<TR>
*<TD width="20%"><inline></TD>
*<TD width="80%">
*<P>One of the following items:</P>
*<UL>
*<LI>unaltered The original message is the new
* message, for forwarding/aliasing</LI>
*<LI>heads The
* headers of the original message are appended to the message</LI>
*<LI>body The
* body of the original is appended to the new message</LI>
*<LI>all Both
* headers and body are appended</LI>
*<LI>none Neither
* body nor headers are appended</LI>
*</UL>
*</TD>
*</TR>
*<TR>
*<TD width="20%"><attachment></TD>
*<TD width="80%">
*<P>One of the following items:</P>
*<UL>
*<LI>heads The headers of the original
* are attached as text</LI>
*<LI>body The body of the original
* is attached as text</LI>
*<LI>all Both
* headers and body are attached as a single text file</LI>
*<LI>none Nothing is attached</LI>
*<LI>message The original message is attached as type message/rfc822,
* this means that it can, in many cases, be opened, resent, fw'd, replied
* to etc by email client software.</LI>
*</UL>
*</TD>
*</TR>
*<TR>
*<TD width="20%"><passThrough></TD>
*<TD width="80%">TRUE or FALSE, if true the original message continues in the
*mailet processor after this mailet is finished. False causes the original
*to be stopped.</TD>
*</TR>
*<TR>
*<TD width="20%"><attachError></TD>
*<TD width="80%">TRUE or FALSE, if true any error message available to the
*mailet is appended to the message body (except in the case of inline ==
*unaltered)</TD>
*</TR>
*<TR>
*<TD width="20%"><replyto></TD>
*<TD width="80%">A single email address to appear in the Rely-To: header, can
*also be "sender" or "postmaster", this header is not
*set if this is omited.</TD>
*</TR>
*<TR>
*<TD width="20%"><prefix></TD>
*<TD width="80%">An optional subject prefix prepended to the original message
*subject, for example:<BR>
*Undeliverable mail: </TD>
*</TR>
*<TR>
*<TD width="20%"><static></TD>
*<TD width="80%">
*<P>TRUE or FALSE. If this is TRUE it tells the mailet that it can
*reuse all the initial parameters (to, from, etc) without re-calculating
*their values. This will boost performance where a redirect task
*doesn't contain any dynamic values. If this is FALSE, it tells the
*mailet to recalculate the values for each e-mail processed.</P>
*<P>Note: If you use "magic words" such as "sender" in the <sender>
*tag, you must NOT use set static to TRUE.</P>
*<P>This defaults to false.<BR>
*</TD>
*</TR>
*</TABLE>
*
*<P>Example:</P>
*<P> <mailet match="RecipientIs=test@localhost" class="Redirect"><BR>
*<recipients>x@localhost, y@localhost, z@localhost</recipients><BR>
*<to>list@localhost</to><BR>
*<sender>owner@localhost</sender><BR>
*<message>sent on from James</message><BR>
*<inline>unaltered</inline><BR>
*<passThrough>FALSE</passThrough><BR>
*<replyto>postmaster</replyto><BR>
*<prefix xml:space="preserve">[test mailing] </prefix><BR>
*<!-- note the xml:space="preserve" to preserve whitespace --><BR>
*<static>TRUE</static><BR>
*</mailet><BR>
*</P>
*<P>and:</P>
*<P> <mailet match="All" class="Redirect"><BR>
*<recipients>x@localhost</recipients><BR>
*<sender>postmaster</sender><BR>
*<message xml:space="preserve">Message marked as spam:<BR>
*</message><BR>
*<inline>heads</inline><BR>
*<attachment>message</attachment><BR>
*<passThrough>FALSE</passThrough><BR>
*<attachError>TRUE</attachError><BR>
*<replyto>postmaster</replyto><BR>
*<prefix>[spam notification]</prefix><BR>
*<static>TRUE</static><BR>
*</mailet></P>
*
*
*/
public class Redirect extends GenericMailet {
/**
* Controls certain log messages
*/
private boolean isDebug = false;
// The values that indicate how to attach the original mail
// to the redirected mail.
private static final int UNALTERED = 0;
private static final int HEADS = 1;
private static final int BODY = 2;
private static final int ALL = 3;
private static final int NONE = 4;
private static final int MESSAGE = 5;
private InternetAddress[] apparentlyTo;
private String messageText;
private Collection recipients;
private MailAddress replyTo;
private MailAddress sender;
private RFC822DateFormat rfc822DateFormat = new RFC822DateFormat();
/**
* returns one of these values to indicate how to attach the original message
*<ul>
* <li>BODY : original message body is attached as plain text to the new message</li>
* <li>HEADS : original message headers are attached as plain text to the new message</li>
* <li>ALL : original is attached as plain text with all headers</li>
* <li>MESSAGE : original message is attached as type message/rfc822, a complete mail message.</li>
* <li>NONE : original is not attached</li>
*</ul>
*
*/
public int getAttachmentType() {
if(getInitParameter("attachment") == null) {
return NONE;
} else {
return getTypeCode(getInitParameter("attachment"));
}
}
/**
* returns one of these values to indicate how to append the original message
*<ul>
* <li>UNALTERED : original message is the new message body</li>
* <li>BODY : original message body is appended to the new message</li>
* <li>HEADS : original message headers are appended to the new message</li>
* <li>ALL : original is appended with all headers</li>
* <li>NONE : original is not appended</li>
*</ul>
*/
public int getInLineType() {
if(getInitParameter("inline") == null) {
return BODY;
} else {
return getTypeCode(getInitParameter("inline"));
}
}
/**
* Return a string describing this mailet.
*
* @return a string describing this mailet
*/
public String getMailetInfo() {
return "Resend Mailet";
}
/**
* must return either an empty string, or a message to which the redirect can be attached/appended
*/
public String getMessage() {
if(getInitParameter("message") == null) {
return "";
} else {
return getInitParameter("message");
}
}
/**
* return true to allow thie original message to continue through the processor, false to GHOST it
*/
public boolean getPassThrough() {
if(getInitParameter("passThrough") == null) {
return false;
} else {
return new Boolean(getInitParameter("passThrough")).booleanValue();
}
}
/**
* must return a Collection of recipient MailAddresses
*/
public Collection getRecipients() {
Collection newRecipients = new HashSet();
String addressList = (getInitParameter("recipients") == null)
? getInitParameter("to")
: getInitParameter("recipients");
StringTokenizer st = new StringTokenizer(addressList, ",", false);
while(st.hasMoreTokens()) {
try {
newRecipients.add(new MailAddress(st.nextToken()));
} catch(Exception e) {
log("add recipient failed in getRecipients");
}
}
return newRecipients;
}
/**
* Returns the reply to address as a string.
*
* @return the replyto address for the mail as a string
*/
public MailAddress getReplyTo() {
String sr = getInitParameter("replyto");
if(sr != null) {
MailAddress rv;
if(sr.compareTo("postmaster") == 0) {
rv = getMailetContext().getPostmaster();
return rv;
}
if(sr.compareTo("sender") == 0) {
return null;
}
try {
rv = new MailAddress(sr);
return rv;
} catch(Exception e) {
log("Parse error in getReplyTo " + sr);
}
}
return null;
}
/**
* returns the senders address, as a MailAddress
*/
public MailAddress getSender() {
String sr = getInitParameter("sender");
if(sr != null) {
MailAddress rv;
if(sr.compareTo("postmaster") == 0) {
rv = getMailetContext().getPostmaster();
return rv;
}
if(sr.compareTo("sender") == 0) {
return null;
}
try {
rv = new MailAddress(sr);
return rv;
} catch(Exception e) {
log("Parse error in getSender " + sr);
}
}
return null;
}
/**
* return true to reduce calls to getTo, getSender, getRecipients, getReplyTo amd getMessage
* where these values don't change (eg hard coded, or got at startup from the mailet config)<br>
* return false where any of these methods generate their results dynamically eg in response to the message being processed,
* or by refrence to a repository of users
*/
public boolean isStatic() {
if(getInitParameter("static") == null) {
return false;
}
return new Boolean(getInitParameter("static")).booleanValue();
}
/**
* return a prefix for the message subject
*/
public String getSubjectPrefix() {
if(getInitParameter("prefix") == null) {
return "";
} else {
return getInitParameter("prefix");
}
}
/**
* returns an array of InternetAddress 'es for the To: header
*/
public InternetAddress[] getTo() {
String addressList = (getInitParameter("to") == null)
? getInitParameter("recipients") : getInitParameter("to");
StringTokenizer rec = new StringTokenizer(addressList, ",");
int tokensn = rec.countTokens();
InternetAddress[] iaarray = new InternetAddress[tokensn];
String tokenx = "";
for(int i = 0; i < tokensn; ++i) {
try {
tokenx = rec.nextToken();
iaarray[i] = new InternetAddress(tokenx);
} catch(Exception e) {
log("Internet address exception in getTo()");
}
}
return iaarray;
}
/**
* return true to append a description of any error to the main body part
* if getInlineType does not return "UNALTERED"
*/
public boolean attachError() {
if(getInitParameter("attachError") == null) {
return false;
} else {
return new Boolean(getInitParameter("attachError")).booleanValue();
}
}
/**
* init will setup static values for sender, recipients, message text, and reply to
* <br> if isStatic() returns true
* it calls getSender(), getReplyTo(), getMessage(), and getRecipients() and getTo()
*
*/
public void init() throws MessagingException {
if (isDebug) {
log("Redirect init");
}
isDebug = (getInitParameter("debug") == null) ? false : new Boolean(getInitParameter("debug")).booleanValue();
if(isStatic()) {
sender = getSender();
replyTo = getReplyTo();
messageText = getMessage();
recipients = getRecipients();
apparentlyTo = getTo();
if (isDebug) {
StringBuffer logBuffer =
new StringBuffer(1024)
.append("static, sender=")
.append(sender)
.append(", replyTo=")
.append(replyTo)
.append(", message=")
.append(messageText)
.append(" ");
log(logBuffer.toString());
}
}
}
/**
* Service does the hard work,and redirects the mail in the form specified
*
* @param mail the mail to process and redirect
* @throws MessagingException if a problem arising formulating the redirected mail
*/
public void service(Mail mail) throws MessagingException {
if(!isStatic()) {
sender = getSender();
replyTo = getReplyTo();
messageText = getMessage();
recipients = getRecipients();
apparentlyTo = getTo();
}
MimeMessage message = mail.getMessage();
MimeMessage reply = null;
//Create the message
if(getInLineType() != UNALTERED) {
if (isDebug) {
log("Alter message inline=:" + getInLineType());
}
reply = new MimeMessage(Session.getDefaultInstance(System.getProperties(),
null));
StringWriter sout = new StringWriter();
PrintWriter out = new PrintWriter(sout, true);
Enumeration heads = message.getAllHeaderLines();
String head = "";
StringBuffer headBuffer = new StringBuffer(1024);
while(heads.hasMoreElements()) {
headBuffer.append(heads.nextElement().toString()).append("\n");
}
head = headBuffer.toString();
boolean all = false;
if(messageText != null) {
out.println(messageText);
}
switch(getInLineType()) {
case ALL: //ALL:
all = true;
case HEADS: //HEADS:
out.println("Message Headers:");
out.println(head);
if(!all) {
break;
}
case BODY: //BODY:
out.println("Message:");
try {
out.println(message.getContent().toString());
} catch(Exception e) {
out.println("body unavailable");
}
break;
default:
case NONE: //NONE:
break;
}
MimeMultipart multipart = new MimeMultipart();
//Add message as the first mime body part
MimeBodyPart part = new MimeBodyPart();
part.setText(sout.toString());
part.setDisposition("inline");
multipart.addBodyPart(part);
if(getAttachmentType() != NONE) {
part = new MimeBodyPart();
switch(getAttachmentType()) {
case HEADS: //HEADS:
part.setText(head);
break;
case BODY: //BODY:
try {
part.setText(message.getContent().toString());
} catch(Exception e) {
part.setText("body unavailable");
}
break;
case ALL: //ALL:
StringBuffer textBuffer =
new StringBuffer(1024)
.append(head)
.append("\n\n")
.append(message.toString());
part.setText(textBuffer.toString());
break;
case MESSAGE: //MESSAGE:
part.setContent(message, "message/rfc822");
break;
}
part.setDisposition("Attachment");
multipart.addBodyPart(part);
}
reply.setContent(multipart);
reply.setHeader(RFC2822Headers.CONTENT_TYPE, multipart.getContentType());
reply.setRecipients(Message.RecipientType.TO, apparentlyTo);
} else {
// if we need the original, create a copy of this message to redirect
reply = getPassThrough() ? new MimeMessage(message) : message;
if (isDebug) {
log("Message resent unaltered.");
}
}
//Set additional headers
reply.setSubject(getSubjectPrefix() + message.getSubject());
if(reply.getHeader(RFC2822Headers.DATE) == null) {
reply.setHeader(RFC2822Headers.DATE, rfc822DateFormat.format(new Date()));
}
//
if(replyTo != null) {
InternetAddress[] iart = new InternetAddress[1];
iart[0] = replyTo.toInternetAddress();
reply.setReplyTo(iart);
}
if(sender == null) {
reply.setHeader(RFC2822Headers.FROM, message.getHeader(RFC2822Headers.FROM, ","));
sender = new MailAddress(((InternetAddress)message.getFrom()[0]).getAddress());
} else {
reply.setFrom(sender.toInternetAddress());
}
//Send it off...
getMailetContext().sendMail(sender, recipients, reply);
if(!getPassThrough()) {
mail.setState(Mail.GHOST);
}
}
/**
* A private method to convert types from string to int.
*
* @param param the string type
*
* @return the corresponding int enumeration
*/
private int getTypeCode(String param) {
int code;
param = param.toLowerCase(Locale.US);
if(param.compareTo("unaltered") == 0) {
return UNALTERED;
}
if(param.compareTo("heads") == 0) {
return HEADS;
}
if(param.compareTo("body") == 0) {
return BODY;
}
if(param.compareTo("all") == 0) {
return ALL;
}
if(param.compareTo("none") == 0) {
return NONE;
}
if(param.compareTo("message") == 0) {
return MESSAGE;
}
return NONE;
}
}
| Reverted Redirect to previous version. Accidentally committed new version that isn't quite finished yet.
git-svn-id: de9d04cf23151003780adc3e4ddb7078e3680318@108737 13f79535-47bb-0310-9956-ffa450edef68
| src/java/org/apache/james/transport/mailets/Redirect.java | Reverted Redirect to previous version. Accidentally committed new version that isn't quite finished yet. | <ide><path>rc/java/org/apache/james/transport/mailets/Redirect.java
<ide>
<ide> import java.io.PrintWriter;
<ide> import java.io.StringWriter;
<add>
<ide> import java.util.Collection;
<ide> import java.util.Date;
<ide> import java.util.Enumeration;
<ide> import java.util.HashSet;
<add>import java.util.Iterator;
<ide> import java.util.Locale;
<ide> import java.util.StringTokenizer;
<add>import java.util.Vector;
<add>
<ide>
<ide> import javax.mail.Message;
<ide> import javax.mail.MessagingException;
<ide> import javax.mail.internet.MimeMessage;
<ide> import javax.mail.internet.MimeMultipart;
<ide>
<add>import org.apache.james.util.RFC2822Headers;
<add>import org.apache.james.util.RFC822DateFormat;
<add>
<ide> import org.apache.mailet.GenericMailet;
<ide> import org.apache.mailet.Mail;
<ide> import org.apache.mailet.MailAddress;
<del>import org.apache.mailet.RFC2822Headers;
<del>import org.apache.mailet.dates.RFC822DateFormat;
<ide>
<ide>
<ide> /**
<ide> *<static>TRUE</static><BR>
<ide> *</mailet></P>
<ide> *
<add> * @author Danny Angus <[email protected]>
<ide> *
<ide> */
<ide> public class Redirect extends GenericMailet {
<ide> if(reply.getHeader(RFC2822Headers.DATE) == null) {
<ide> reply.setHeader(RFC2822Headers.DATE, rfc822DateFormat.format(new Date()));
<ide> }
<del>
<add>
<ide> //
<del>
<add>
<ide> if(replyTo != null) {
<ide> InternetAddress[] iart = new InternetAddress[1];
<ide> iart[0] = replyTo.toInternetAddress(); |
|
Java | apache-2.0 | 6dcae3f814f3ec29c138357dbc220f4ec31ece87 | 0 | t9nf/google-http-java-client,googleapis/google-http-java-client,nonexpectation/google-http-java-client,SunghanKim/google-http-java-client,googleapis/google-http-java-client,nonexpectation/google-http-java-client,suclike/google-http-java-client,bright60/google-http-java-client,ejona86/google-http-java-client,spotify/google-http-java-client,veraicon/google-http-java-client,googleapis/google-http-java-client,skinzer/google-http-java-client,spotify/google-http-java-client,jameswei/google-http-java-client,ejona86/google-http-java-client,b-cuts/google-http-java-client,SunghanKim/google-http-java-client,veraicon/google-http-java-client,bright60/google-http-java-client,veraicon/google-http-java-client,jameswei/google-http-java-client,suclike/google-http-java-client,suclike/google-http-java-client,bright60/google-http-java-client,spotify/google-http-java-client,skinzer/google-http-java-client,b-cuts/google-http-java-client,wgpshashank/google-http-java-client,googleapis/google-http-java-client,jameswei/google-http-java-client,b-cuts/google-http-java-client,ejona86/google-http-java-client,fengshao0907/google-http-java-client,t9nf/google-http-java-client,nonexpectation/google-http-java-client,fengshao0907/google-http-java-client,wgpshashank/google-http-java-client,wgpshashank/google-http-java-client,nonexpectation/google-http-java-client,veraicon/google-http-java-client,jameswei/google-http-java-client,b-cuts/google-http-java-client,t9nf/google-http-java-client,t9nf/google-http-java-client,SunghanKim/google-http-java-client,fengshao0907/google-http-java-client,skinzer/google-http-java-client,wgpshashank/google-http-java-client,bright60/google-http-java-client,SunghanKim/google-http-java-client | /*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.http;
import java.util.Arrays;
import java.util.logging.Logger;
/**
* Thread-safe abstract HTTP transport.
*
* <p>
* Implementation is thread-safe, and sub-classes must be thread-safe. For maximum efficiency,
* applications should use a single globally-shared instance of the HTTP transport.
* </p>
*
* <p>
* The recommended concrete implementation HTTP transport library to use depends on what environment
* you are running in:
* </p>
* <ul>
* <li>Google App Engine: use {@code com.google.api.client.appengine.UrlFetchTransport}.
* <ul>
* <li>{@code com.google.api.client.apache.ApacheHttpTransport} doesn't work on App Engine because
* the Apache HTTP Client opens its own sockets (though in theory there are ways to hack it to work
* on App Engine that might work).</li>
* <li>{@code com.google.api.client.javanet.NetHttpTransport} is discouraged due to a bug in the App
* Engine SDK itself in how it parses HTTP headers in the response.</li>
* </ul>
* </li>
* <li>Android:
* <ul>
* <li>Starting with SDK 2.3, strongly recommended to use
* {@code com.google.api.client.javanet.NetHttpTransport}. Their Apache HTTP Client implementation
* is not as well maintained.</li>
* <li>For SDK 2.2 and earlier, use {@code com.google.api.client.apache.ApacheHttpTransport}.
* {@code com.google.api.client.javanet.NetHttpTransport} is not recommended due to some bugs in the
* Android SDK implementation of HttpURLConnection.</li>
* </ul>
* </li>
* <li>Other Java environments
* <ul>
* <li>{@code com.google.api.client.javanet.NetHttpTransport} is based on the HttpURLConnection
* built into the Java SDK, so it is normally the preferred choice.</li>
* <li>{@code com.google.api.client.apache.ApacheHttpTransport} is a good choice for users of the
* Apache HTTP Client, especially if you need some of the configuration options available in that
* library.</li>
* </ul>
* </li>
* </ul>
*
* <p>
* Some HTTP transports do not support all HTTP methods. Use {@link #supportsMethod(String)} to
* check if a certain HTTP method is supported. Calling {@link #buildRequest()} on a method that is
* not supported will result in an {@link IllegalArgumentException}.
* </p>
*
* <p>
* Subclasses should override {@link #supportsMethod(String)} and
* {@link #buildRequest(String, String)} to build requests and specify which HTTP methods are
* supported.
* </p>
*
* @since 1.0
* @author Yaniv Inbar
*/
public abstract class HttpTransport {
static final Logger LOGGER = Logger.getLogger(HttpTransport.class.getName());
/**
* All valid request methods as specified in {@link #supportsMethod(String)}, sorted in ascending
* alphabetical order.
*/
private static final String[] SUPPORTED_METHODS =
{HttpMethods.DELETE, HttpMethods.GET, HttpMethods.POST, HttpMethods.PUT};
static {
Arrays.sort(SUPPORTED_METHODS);
}
/**
* Returns a new instance of an HTTP request factory based on this HTTP transport.
*
* @return new instance of an HTTP request factory
* @since 1.4
*/
public final HttpRequestFactory createRequestFactory() {
return createRequestFactory(null);
}
/**
* Returns a new instance of an HTTP request factory based on this HTTP transport with the given
* HTTP request initializer.
*
* @param initializer HTTP request initializer or {@code null} for none
* @return new instance of an HTTP request factory
* @since 1.4
*/
public final HttpRequestFactory createRequestFactory(HttpRequestInitializer initializer) {
return new HttpRequestFactory(this, initializer);
}
/**
* Builds a request without specifying the HTTP method.
*
* @return new HTTP request
*/
HttpRequest buildRequest() {
return new HttpRequest(this, null);
}
/**
* Returns whether this HTTP transport implementation supports the {@code HEAD} request method.
*
* <p>
* Default implementation calls {@link #supportsMethod}.
* </p>
*
* @since 1.3
* @deprecated (scheduled to be removed in 1.13) Use {@link #supportsMethod(String)} instead
*/
@Deprecated
public boolean supportsHead() {
return supportsMethod("HEAD");
}
/**
* Returns whether this HTTP transport implementation supports the {@code PATCH} request method.
*
* <p>
* Default implementation calls {@link #supportsMethod}.
* </p>
*
* @since 1.3
* @deprecated (scheduled to be removed in 1.13) Use {@link #supportsMethod(String)} instead
*/
@Deprecated
public boolean supportsPatch() {
return supportsMethod("PATCH");
}
/**
* Returns whether a specified HTTP method is supported by this transport.
*
* <p>
* Default implementation returns true if and only if the request method is {@code "DELETE"},
* {@code "GET"}, {@code "POST"}, or {@code "PUT"}. Subclasses should override.
* </p>
*
* @param method HTTP method
* @since 1.12
*/
public boolean supportsMethod(String method) {
return Arrays.binarySearch(SUPPORTED_METHODS, method) >= 0;
}
/**
* Builds a low level HTTP request for the given HTTP method.
*
* <p>
* Default implementation throws an {@link IllegalArgumentException}. Subclasses must override,
* though they should call the super implementation for an unsupported HTTP method.
* </p>
*
* @param method HTTP method
* @param url URL
* @return new low level HTTP request
* @throws IllegalArgumentException if HTTP method is not supported
* @since 1.12
*/
protected LowLevelHttpRequest buildRequest(String method, String url) throws Exception {
throw new IllegalArgumentException("HTTP transport doesn't support " + method);
}
/**
* Builds a {@code DELETE} request.
*
* <p>
* Default implementation calls {@link #buildRequest}.
* </p>
*
* <p>
* Upgrade warning: this method now throws an {@link Exception}. In prior version 1.11 it threw an
* {@link java.io.IOException}.
* </p>
*
* @param url URL
* @since 1.3
* @deprecated (scheduled to be removed in 1.13) Use {@link #buildRequest(String, String)} instead
*/
@Deprecated
protected LowLevelHttpRequest buildDeleteRequest(String url) throws Exception {
return buildRequest("DELETE", url);
}
/**
* Builds a {@code GET} request.
*
* <p>
* Default implementation calls {@link #buildRequest}.
* </p>
*
* <p>
* Upgrade warning: this method now throws an {@link Exception}. In prior version 1.11 it threw an
* {@link java.io.IOException}.
* </p>
*
* @param url URL
* @since 1.3
* @deprecated (scheduled to be removed in 1.13) Use {@link #buildRequest(String, String)} instead
*/
@Deprecated
protected LowLevelHttpRequest buildGetRequest(String url) throws Exception {
return buildRequest("GET", url);
}
/**
* Builds a {@code HEAD} request.
*
* <p>
* Won't be called if {@link #supportsHead()} returns {@code false}.
* </p>
*
* <p>
* Default implementation calls {@link #buildRequest}.
* </p>
*
* <p>
* Upgrade warning: in prior version it threw an {@link UnsupportedOperationException} by
* default}.
* </p>
*
* <p>
* Upgrade warning: this method now throws an {@link Exception}. In prior version 1.11 it threw an
* {@link java.io.IOException}.
* </p>
*
* @param url URL
* @since 1.3
* @deprecated (scheduled to be removed in 1.13) Use {@link #buildRequest(String, String)} instead
*/
@Deprecated
protected LowLevelHttpRequest buildHeadRequest(String url) throws Exception {
return buildRequest("HEAD", url);
}
/**
* Builds a {@code PATCH} request.
*
* <p>
* Won't be called if {@link #supportsPatch()} returns {@code false}.
* </p>
*
* <p>
* Default implementation calls {@link #buildRequest}.
* </p>
*
* <p>
* Upgrade warning: in prior version it threw an {@link UnsupportedOperationException} by
* default}.
* </p>
*
* <p>
* Upgrade warning: this method now throws an {@link Exception}. In prior version 1.11 it threw an
* {@link java.io.IOException}.
* </p>
*
* @param url URL
* @since 1.3
* @deprecated (scheduled to be removed in 1.13) Use {@link #buildRequest(String, String)} instead
*/
@Deprecated
protected LowLevelHttpRequest buildPatchRequest(String url) throws Exception {
return buildRequest("PATCH", url);
}
/**
* Builds a {@code POST} request.
*
* <p>
* Default implementation calls {@link #buildRequest}.
* </p>
*
* <p>
* Upgrade warning: this method now throws an {@link Exception}. In prior version 1.11 it threw an
* {@link java.io.IOException}.
* </p>
*
* @param url URL
* @since 1.3
* @deprecated (scheduled to be removed in 1.13) Use {@link #buildRequest(String, String)} instead
*/
@Deprecated
protected LowLevelHttpRequest buildPostRequest(String url) throws Exception {
return buildRequest("POST", url);
}
/**
* Builds a {@code PUT} request.
*
* <p>
* Default implementation calls {@link #buildRequest}.
* </p>
*
* <p>
* Upgrade warning: this method now throws an {@link Exception}. In prior version 1.11 it threw an
* {@link java.io.IOException}.
* </p>
*
* @param url URL
* @since 1.3
* @deprecated (scheduled to be removed in 1.13) Use {@link #buildRequest(String, String)} instead
*/
@Deprecated
protected LowLevelHttpRequest buildPutRequest(String url) throws Exception {
return buildRequest("PUT", url);
}
/**
* Default implementation does nothing, but subclasses may override to possibly release allocated
* system resources or close connections.
*
* <p>
* Upgrade warning: this method now throws an {@link Exception}. In prior version 1.11 it threw an
* {@link java.io.IOException}.
* </p>
*
* @since 1.4
*/
public void shutdown() throws Exception {
}
}
| google-http-client/src/main/java/com/google/api/client/http/HttpTransport.java | /*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.http;
import java.io.IOException;
import java.util.Arrays;
import java.util.logging.Logger;
/**
* Thread-safe abstract HTTP transport.
*
* <p>
* Implementation is thread-safe, and sub-classes must be thread-safe. For maximum efficiency,
* applications should use a single globally-shared instance of the HTTP transport.
* </p>
*
* <p>
* The recommended concrete implementation HTTP transport library to use depends on what environment
* you are running in:
* </p>
* <ul>
* <li>Google App Engine: use {@code com.google.api.client.appengine.UrlFetchTransport}.
* <ul>
* <li>{@code com.google.api.client.apache.ApacheHttpTransport} doesn't work on App Engine because
* the Apache HTTP Client opens its own sockets (though in theory there are ways to hack it to work
* on App Engine that might work).</li>
* <li>{@code com.google.api.client.javanet.NetHttpTransport} is discouraged due to a bug in the App
* Engine SDK itself in how it parses HTTP headers in the response.</li>
* </ul>
* </li>
* <li>Android:
* <ul>
* <li>Starting with SDK 2.3, strongly recommended to use
* {@code com.google.api.client.javanet.NetHttpTransport}. Their Apache HTTP Client implementation
* is not as well maintained.</li>
* <li>For SDK 2.2 and earlier, use {@code com.google.api.client.apache.ApacheHttpTransport}.
* {@code com.google.api.client.javanet.NetHttpTransport} is not recommended due to some bugs in the
* Android SDK implementation of HttpURLConnection.</li>
* </ul>
* </li>
* <li>Other Java environments
* <ul>
* <li>{@code com.google.api.client.javanet.NetHttpTransport} is based on the HttpURLConnection
* built into the Java SDK, so it is normally the preferred choice.</li>
* <li>{@code com.google.api.client.apache.ApacheHttpTransport} is a good choice for users of the
* Apache HTTP Client, especially if you need some of the configuration options available in that
* library.</li>
* </ul>
* </li>
* </ul>
*
* <p>
* Some HTTP transports do not support all HTTP methods. Use {@link #supportsMethod(String)} to
* check if a certain HTTP method is supported. Calling {@link #buildRequest()} on a method that is
* not supported will result in an {@link IllegalArgumentException}.
* </p>
*
* <p>
* Subclasses should override {@link #supportsMethod(String)} and
* {@link #buildRequest(String, String)} to build requests and specify which HTTP methods are
* supported.
* </p>
*
* @since 1.0
* @author Yaniv Inbar
*/
public abstract class HttpTransport {
static final Logger LOGGER = Logger.getLogger(HttpTransport.class.getName());
/**
* All valid request methods as specified in {@link #supportsMethod(String)}, sorted in ascending
* alphabetical order.
*/
private static final String[] SUPPORTED_METHODS =
{HttpMethods.DELETE, HttpMethods.GET, HttpMethods.POST, HttpMethods.PUT};
static {
Arrays.sort(SUPPORTED_METHODS);
}
/**
* Returns a new instance of an HTTP request factory based on this HTTP transport.
*
* @return new instance of an HTTP request factory
* @since 1.4
*/
public final HttpRequestFactory createRequestFactory() {
return createRequestFactory(null);
}
/**
* Returns a new instance of an HTTP request factory based on this HTTP transport with the given
* HTTP request initializer.
*
* @param initializer HTTP request initializer or {@code null} for none
* @return new instance of an HTTP request factory
* @since 1.4
*/
public final HttpRequestFactory createRequestFactory(HttpRequestInitializer initializer) {
return new HttpRequestFactory(this, initializer);
}
/**
* Builds a request without specifying the HTTP method.
*
* @return new HTTP request
*/
HttpRequest buildRequest() {
return new HttpRequest(this, null);
}
/**
* Returns whether this HTTP transport implementation supports the {@code HEAD} request method.
*
* <p>
* Default implementation calls {@link #supportsMethod}.
* </p>
*
* @since 1.3
* @deprecated (scheduled to be removed in 1.13) Use {@link #supportsMethod(String)} instead
*/
@Deprecated
public boolean supportsHead() {
return supportsMethod("HEAD");
}
/**
* Returns whether this HTTP transport implementation supports the {@code PATCH} request method.
*
* <p>
* Default implementation calls {@link #supportsMethod}.
* </p>
*
* @since 1.3
* @deprecated (scheduled to be removed in 1.13) Use {@link #supportsMethod(String)} instead
*/
@Deprecated
public boolean supportsPatch() {
return supportsMethod("PATCH");
}
/**
* Returns whether a specified HTTP method is supported by this transport.
*
* <p>
* Default implementation returns true if and only if the request method is {@code "DELETE"},
* {@code "GET"}, {@code "POST"}, or {@code "PUT"}. Subclasses should override.
* </p>
*
* @param method HTTP method
* @since 1.12
*/
public boolean supportsMethod(String method) {
return Arrays.binarySearch(SUPPORTED_METHODS, method) >= 0;
}
/**
* Builds a low level HTTP request for the given HTTP method.
*
* <p>
* Default implementation throws an {@link IllegalArgumentException}. Subclasses must override,
* though they should call the super implementation for an unsupported HTTP method.
* </p>
*
* @param method HTTP method
* @param url URL
* @return new low level HTTP request
* @throws IllegalArgumentException if HTTP method is not supported
* @since 1.12
*/
protected LowLevelHttpRequest buildRequest(String method, String url) throws Exception {
throw new IllegalArgumentException("HTTP transport doesn't support " + method);
}
/**
* Builds a {@code DELETE} request.
*
* <p>
* Default implementation calls {@link #buildRequest}.
* </p>
*
* <p>
* Upgrade warning: this method now throws an {@link Exception}. In prior version 1.11 it threw an
* {@link java.io.IOException}.
* </p>
*
* @param url URL
* @since 1.3
* @deprecated (scheduled to be removed in 1.13) Use {@link #buildRequest(String, String)} instead
*/
@Deprecated
protected LowLevelHttpRequest buildDeleteRequest(String url) throws Exception {
return buildRequest("DELETE", url);
}
/**
* Builds a {@code GET} request.
*
* <p>
* Default implementation calls {@link #buildRequest}.
* </p>
*
* <p>
* Upgrade warning: this method now throws an {@link Exception}. In prior version 1.11 it threw an
* {@link java.io.IOException}.
* </p>
*
* @param url URL
* @since 1.3
* @deprecated (scheduled to be removed in 1.13) Use {@link #buildRequest(String, String)} instead
*/
@Deprecated
protected LowLevelHttpRequest buildGetRequest(String url) throws Exception {
return buildRequest("GET", url);
}
/**
* Builds a {@code HEAD} request.
*
* <p>
* Won't be called if {@link #supportsHead()} returns {@code false}.
* </p>
*
* <p>
* Default implementation calls {@link #buildRequest}.
* </p>
*
* <p>
* Upgrade warning: in prior version it threw an {@link UnsupportedOperationException} by
* default}.
* </p>
*
* <p>
* Upgrade warning: this method now throws an {@link Exception}. In prior version 1.11 it threw an
* {@link java.io.IOException}.
* </p>
*
* @param url URL
* @since 1.3
* @deprecated (scheduled to be removed in 1.13) Use {@link #buildRequest(String, String)} instead
*/
@Deprecated
protected LowLevelHttpRequest buildHeadRequest(String url) throws Exception {
return buildRequest("HEAD", url);
}
/**
* Builds a {@code PATCH} request.
*
* <p>
* Won't be called if {@link #supportsPatch()} returns {@code false}.
* </p>
*
* <p>
* Default implementation calls {@link #buildRequest}.
* </p>
*
* <p>
* Upgrade warning: in prior version it threw an {@link UnsupportedOperationException} by
* default}.
* </p>
*
* <p>
* Upgrade warning: this method now throws an {@link Exception}. In prior version 1.11 it threw an
* {@link java.io.IOException}.
* </p>
*
* @param url URL
* @since 1.3
* @deprecated (scheduled to be removed in 1.13) Use {@link #buildRequest(String, String)} instead
*/
@Deprecated
protected LowLevelHttpRequest buildPatchRequest(String url) throws Exception {
return buildRequest("PATCH", url);
}
/**
* Builds a {@code POST} request.
*
* <p>
* Default implementation calls {@link #buildRequest}.
* </p>
*
* <p>
* Upgrade warning: this method now throws an {@link Exception}. In prior version 1.11 it threw an
* {@link java.io.IOException}.
* </p>
*
* @param url URL
* @since 1.3
* @deprecated (scheduled to be removed in 1.13) Use {@link #buildRequest(String, String)} instead
*/
@Deprecated
protected LowLevelHttpRequest buildPostRequest(String url) throws Exception {
return buildRequest("POST", url);
}
/**
* Builds a {@code PUT} request.
*
* <p>
* Default implementation calls {@link #buildRequest}.
* </p>
*
* <p>
* Upgrade warning: this method now throws an {@link Exception}. In prior version 1.11 it threw an
* {@link java.io.IOException}.
* </p>
*
* @param url URL
* @since 1.3
* @deprecated (scheduled to be removed in 1.13) Use {@link #buildRequest(String, String)} instead
*/
@Deprecated
protected LowLevelHttpRequest buildPutRequest(String url) throws Exception {
return buildRequest("PUT", url);
}
/**
* Default implementation does nothing, but subclasses may override to possibly release allocated
* system resources or close connections.
*
* @throws IOException I/O exception
* @since 1.4
*/
public void shutdown() throws IOException {
}
}
| [http] HttpTransport.shutdown() should throw Exception
https://codereview.appspot.com/6501126/
| google-http-client/src/main/java/com/google/api/client/http/HttpTransport.java | [http] HttpTransport.shutdown() should throw Exception | <ide><path>oogle-http-client/src/main/java/com/google/api/client/http/HttpTransport.java
<ide>
<ide> package com.google.api.client.http;
<ide>
<del>import java.io.IOException;
<ide> import java.util.Arrays;
<ide> import java.util.logging.Logger;
<ide>
<ide> * Default implementation does nothing, but subclasses may override to possibly release allocated
<ide> * system resources or close connections.
<ide> *
<del> * @throws IOException I/O exception
<add> * <p>
<add> * Upgrade warning: this method now throws an {@link Exception}. In prior version 1.11 it threw an
<add> * {@link java.io.IOException}.
<add> * </p>
<add> *
<ide> * @since 1.4
<ide> */
<del> public void shutdown() throws IOException {
<add> public void shutdown() throws Exception {
<ide> }
<ide> } |
|
Java | lgpl-2.1 | b0528ec66d558182b09cd01311977d3b2c80ddd2 | 0 | serrapos/opencms-core,serrapos/opencms-core,gallardo/opencms-core,victos/opencms-core,gallardo/opencms-core,gallardo/opencms-core,it-tavis/opencms-core,ggiudetti/opencms-core,sbonoc/opencms-core,mediaworx/opencms-core,sbonoc/opencms-core,MenZil/opencms-core,mediaworx/opencms-core,ggiudetti/opencms-core,MenZil/opencms-core,it-tavis/opencms-core,serrapos/opencms-core,serrapos/opencms-core,serrapos/opencms-core,it-tavis/opencms-core,serrapos/opencms-core,alkacon/opencms-core,serrapos/opencms-core,sbonoc/opencms-core,victos/opencms-core,ggiudetti/opencms-core,victos/opencms-core,ggiudetti/opencms-core,alkacon/opencms-core,alkacon/opencms-core,alkacon/opencms-core,gallardo/opencms-core,it-tavis/opencms-core,MenZil/opencms-core,mediaworx/opencms-core,victos/opencms-core,mediaworx/opencms-core,sbonoc/opencms-core,MenZil/opencms-core | /*
* File : $Source: /alkacon/cvs/opencms/src/org/opencms/workplace/tools/CmsHtmlIconButtonStyleEnum.java,v $
* Date : $Date: 2005/06/23 08:15:56 $
* Version: $Revision: 1.5 $
*
* This library is part of OpenCms -
* the Open Source Content Mananagement System
*
* Copyright (C) 2002 - 2005 Alkacon Software (http://www.alkacon.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* For further information about Alkacon Software, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.opencms.workplace.tools;
import org.opencms.main.CmsIllegalArgumentException;
import org.opencms.workplace.list.Messages;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
/**
* Wrapper class for
* the different style of icon buttons.<p>
*
* The possibles values are:<br>
* <ul>
* <li>BigIconText</li>
* <li>SmallIconText</li>
* <li>SmallIconOnly</li>
* </ul>
* <p>
*
* @author Michael Moossen
*
* @version $Revision: 1.5 $
*
* @since 6.0.0
*/
public final class CmsHtmlIconButtonStyleEnum {
/** Constant for ascending ordering. */
public static final CmsHtmlIconButtonStyleEnum BIG_ICON_TEXT = new CmsHtmlIconButtonStyleEnum("bigicontext");
/** Constant for none ordering. */
public static final CmsHtmlIconButtonStyleEnum SMALL_ICON_ONLY = new CmsHtmlIconButtonStyleEnum("smallicononly");
/** Constant for descending ordering. */
public static final CmsHtmlIconButtonStyleEnum SMALL_ICON_TEXT = new CmsHtmlIconButtonStyleEnum("smallicontext");
/** Array constant for column sorting. */
private static final CmsHtmlIconButtonStyleEnum[] C_VALUES = {BIG_ICON_TEXT, SMALL_ICON_TEXT, SMALL_ICON_ONLY};
/** List of ordering constants. */
public static final List VALUES = Collections.unmodifiableList(Arrays.asList(C_VALUES));
/** Internal representation. */
private final String m_style;
/**
* Private constructor.<p>
*
* @param style internal representation
*/
private CmsHtmlIconButtonStyleEnum(String style) {
m_style = style;
}
/**
* Parses an string into an element of this enumeration.<p>
*
* @param value the style to parse
*
* @return the enumeration element
*
* @throws CmsIllegalArgumentException if the given instance for the argument is not found
*/
public static CmsHtmlIconButtonStyleEnum valueOf(String value) throws CmsIllegalArgumentException {
Iterator iter = VALUES.iterator();
while (iter.hasNext()) {
CmsHtmlIconButtonStyleEnum target = (CmsHtmlIconButtonStyleEnum)iter.next();
if (value == target.getStyle()) {
return target;
}
}
throw new CmsIllegalArgumentException(Messages.get().container(
Messages.ERR_LIST_ENUM_PARSE_2,
new Integer(value),
CmsHtmlIconButtonStyleEnum.class.getName()));
}
/**
* Returns the style string.<p>
*
* @return the style string
*/
public String getStyle() {
return m_style;
}
/**
* @see java.lang.Object#toString()
*/
public String toString() {
return m_style;
}
} | src/org/opencms/workplace/tools/CmsHtmlIconButtonStyleEnum.java | /*
* File : $Source: /alkacon/cvs/opencms/src/org/opencms/workplace/tools/CmsHtmlIconButtonStyleEnum.java,v $
* Date : $Date: 2005/06/23 08:12:45 $
* Version: $Revision: 1.4 $
*
* This library is part of OpenCms -
* the Open Source Content Mananagement System
*
* Copyright (C) 2002 - 2005 Alkacon Software (http://www.alkacon.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* For further information about Alkacon Software, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.opencms.workplace.tools;
import org.opencms.main.CmsIllegalArgumentException;
import org.opencms.workplace.list.Messages;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
/**
* Wrapper class for
* the different style of icon buttons.<p>
*
* The possibles values are:<br>
* <ul>
* <li>BigIconText</li>
* <li>SmallIconText</li>
* <li>SmallIconOnly</li>
* </ul>
* <p>
*
* @author Michael Moossen
*
* @version $Revision: 1.4 $
*
* @since 6.0.0
*/
public final class CmsHtmlIconButtonStyleEnum {
/** Constant for ascending ordering. */
public static final CmsHtmlIconButtonStyleEnum BIG_ICON_TEXT = new CmsHtmlIconButtonStyleEnum("bigicontext");
/** Constant for none ordering. */
public static final CmsHtmlIconButtonStyleEnum SMALL_ICON_ONLY = new CmsHtmlIconButtonStyleEnum("smallicononly");
/** Constant for descending ordering. */
public static final CmsHtmlIconButtonStyleEnum SMALL_ICON_TEXT = new CmsHtmlIconButtonStyleEnum("smallicontext");
/** List of ordering constants. */
public static final List VALUES = Collections.unmodifiableList(Arrays.asList(C_VALUES));
/** Array constant for column sorting. */
private static final CmsHtmlIconButtonStyleEnum[] C_VALUES = {BIG_ICON_TEXT, SMALL_ICON_TEXT, SMALL_ICON_ONLY};
/** Internal representation. */
private final String m_style;
/**
* Private constructor.<p>
*
* @param style internal representation
*/
private CmsHtmlIconButtonStyleEnum(String style) {
m_style = style;
}
/**
* Parses an string into an element of this enumeration.<p>
*
* @param value the style to parse
*
* @return the enumeration element
*
* @throws CmsIllegalArgumentException if the given instance for the argument is not found
*/
public static CmsHtmlIconButtonStyleEnum valueOf(String value) throws CmsIllegalArgumentException {
Iterator iter = VALUES.iterator();
while (iter.hasNext()) {
CmsHtmlIconButtonStyleEnum target = (CmsHtmlIconButtonStyleEnum)iter.next();
if (value == target.getStyle()) {
return target;
}
}
throw new CmsIllegalArgumentException(Messages.get().container(
Messages.ERR_LIST_ENUM_PARSE_2,
new Integer(value),
CmsHtmlIconButtonStyleEnum.class.getName()));
}
/**
* Returns the style string.<p>
*
* @return the style string
*/
public String getStyle() {
return m_style;
}
/**
* @see java.lang.Object#toString()
*/
public String toString() {
return m_style;
}
} | wrong order of static members
| src/org/opencms/workplace/tools/CmsHtmlIconButtonStyleEnum.java | wrong order of static members | <ide><path>rc/org/opencms/workplace/tools/CmsHtmlIconButtonStyleEnum.java
<ide> /*
<ide> * File : $Source: /alkacon/cvs/opencms/src/org/opencms/workplace/tools/CmsHtmlIconButtonStyleEnum.java,v $
<del> * Date : $Date: 2005/06/23 08:12:45 $
<del> * Version: $Revision: 1.4 $
<add> * Date : $Date: 2005/06/23 08:15:56 $
<add> * Version: $Revision: 1.5 $
<ide> *
<ide> * This library is part of OpenCms -
<ide> * the Open Source Content Mananagement System
<ide> *
<ide> * @author Michael Moossen
<ide> *
<del> * @version $Revision: 1.4 $
<add> * @version $Revision: 1.5 $
<ide> *
<ide> * @since 6.0.0
<ide> */
<ide> /** Constant for descending ordering. */
<ide> public static final CmsHtmlIconButtonStyleEnum SMALL_ICON_TEXT = new CmsHtmlIconButtonStyleEnum("smallicontext");
<ide>
<add> /** Array constant for column sorting. */
<add> private static final CmsHtmlIconButtonStyleEnum[] C_VALUES = {BIG_ICON_TEXT, SMALL_ICON_TEXT, SMALL_ICON_ONLY};
<add>
<ide> /** List of ordering constants. */
<ide> public static final List VALUES = Collections.unmodifiableList(Arrays.asList(C_VALUES));
<del>
<del> /** Array constant for column sorting. */
<del> private static final CmsHtmlIconButtonStyleEnum[] C_VALUES = {BIG_ICON_TEXT, SMALL_ICON_TEXT, SMALL_ICON_ONLY};
<ide>
<ide> /** Internal representation. */
<ide> private final String m_style; |
|
JavaScript | mit | 76df42b3b8efea194f16544d09708b9f9b5919d6 | 0 | kbrsh/moon,KingPixil/moon,KingPixil/moon,kbrsh/moon,KingPixil/moon | "use strict";
(function(window) {
var config = {
silent: false
}
var directives = {};
var components = {};
/**
* Converts attributes into key-value pairs
* @param {Node} node
* @return {Object} Key-Value pairs of Attributes
*/
var extractAttrs = function(node) {
var attrs = {};
if(!node.attributes) return attrs;
var rawAttrs = node.attributes;
for(var i = 0; i < rawAttrs.length; i++) {
attrs[rawAttrs[i].name] = rawAttrs[i].value
}
return attrs;
}
/**
* Compiles a template with given data
* @param {String} template
* @param {Object} data
* @return {String} Template with data rendered
*/
var compileTemplate = function(template, data) {
var code = template,
re = /{{([A-Za-z0-9_.\[\]]+)}}/gi;
code.replace(re, function(match, p) {
code = code.replace(match, "` + data." + p + " + `");
});
var compile = new Function("data", "var out = `" + code + "`; return out");
var output = compile(data);
return output;
}
/**
* Gets Root Element
* @param {String} html
* @return {Node} Root Element
*/
var getRootElement = function(html) {
var dummy = document.createElement('div');
dummy.innerHTML = html;
return dummy.firstChild;
}
/**
* Merges two Objects
* @param {Object} obj
* @param {Object} obj2
* @return {Object} Merged Objects
*/
function merge(obj, obj2) {
for (var key in obj2) {
if (obj2.hasOwnProperty(key)) obj[key] = obj2[key];
}
return obj;
}
function Moon(opts) {
var _el = opts.el;
var _data = opts.data;
var _methods = opts.methods;
var _hooks = opts.hooks || {created: function() {}, mounted: function() {}, updated: function() {}, destroyed: function() {}};
var _destroyed = false;
var self = this;
this.$el = document.querySelector(_el);
this.$components = merge(opts.components || {}, components);
this.$dom = {type: this.$el.nodeName, children: [], node: this.$el};
// Change state when $data is changed
Object.defineProperty(this, '$data', {
get: function() {
return _data;
},
set: function(value) {
_data = value;
this.build(this.$dom.children);
},
configurable: true
});
/**
* Logs a Message
* @param {String} msg
*/
this.log = function(msg) {
if(!config.silent) console.log(msg);
}
/**
* Throws an Error
* @param {String} msg
*/
this.error = function(msg) {
console.log("Moon ERR: " + msg);
}
/**
* Creates an object to be used in a Virtual DOM
* @param {String} type
* @param {Array} children
* @param {String} val
* @param {Object} props
* @param {Node} node
* @return {Object} Object usable in Virtual DOM
*/
this.createElement = function(type, children, val, props, node) {
return {type: type, children: children, val: val, props: props, node: node};
}
/**
* Create Elements Recursively For all Children
* @param {Array} children
* @return {Array} Array of elements usable in Virtual DOM
*/
this.recursiveChildren = function(children) {
var recursiveChildrenArr = [];
for(var i = 0; i < children.length; i++) {
var child = children[i];
recursiveChildrenArr.push(this.createElement(child.nodeName, this.recursiveChildren(child.childNodes), child.textContent, extractAttrs(child), child));
}
return recursiveChildrenArr;
}
/**
* Creates Virtual DOM
* @param {Node} node
*/
this.createVirtualDOM = function(node) {
var vdom = this.createElement(node.nodeName, this.recursiveChildren(node.childNodes), node.textContent, extractAttrs(node), node);
this.$dom = vdom;
}
/**
* Turns Custom Components into their Corresponding Templates
*/
this.componentsToHTML = function() {
for(var component in this.$components) {
var componentsFound = document.getElementsByTagName(component);
componentsFound = Array.prototype.slice.call(componentsFound);
for(var i = 0; i < componentsFound.length; i++) {
var componentFound = componentsFound[i];
var componentProps = extractAttrs(componentFound);
var componentDummy = getRootElement(this.$components[component].template);
for(var attr in componentProps) {
componentDummy.setAttribute(attr, componentProps[attr]);
}
componentFound.outerHTML = componentDummy.outerHTML;
}
}
}
/**
* Sets Value in Data
* @param {String} key
* @param {String} val
*/
this.set = function(key, val) {
this.$data[key] = val;
if(!_destroyed) this.build(this.$dom.children);
if(_hooks.updated) {
_hooks.updated();
}
}
/**
* Gets Value in Data
* @param {String} key
* @return {String} Value of key in data
*/
this.get = function(key) {
return this.$data[key];
}
/**
* Calls a method
* @param {String} method
*/
this.method = function(method) {
_methods[method]();
}
this.destroy = function() {
Object.defineProperty(this, '$data', {
set: function(value) {
_data = value;
}
});
_destroyed = true;
if(_hooks.destroyed) _hooks.destroyed();
}
// Default Directives
directives["m-if"] = function(el, val, vdom) {
var evaluated = new Function("return " + val);
if(!evaluated()) {
el.textContent = "";
} else {
el.textContent = compileTemplate(vdom.val, self.$data);
}
}
directives["m-show"] = function(el, val, vdom) {
var evaluated = new Function("return " + val);
if(!evaluated()) {
el.style.display = 'none';
} else {
el.style.display = 'block';
}
}
directives["m-on"] = function(el, val, vdom) {
var splitVal = val.split(":");
var eventToCall = splitVal[0];
var methodToCall = splitVal[1];
el.addEventListener(eventToCall, function() {
self.method(methodToCall);
});
el.removeAttribute("m-on");
delete vdom.props["m-on"];
}
directives["m-model"] = function(el, val, vdom) {
el.value = self.get(val);
el.addEventListener("input", function() {
self.set(val, el.value);
});
el.removeAttribute("m-model");
delete vdom.props["m-model"];
}
directives["m-once"] = function(el, val, vdom) {
vdom.val = el.textContent;
for(var child in vdom.children) {
vdom.children[child].val = compileTemplate(vdom.children[child].val, self.$data);
}
}
directives["m-text"] = function(el, val, vdom) {
el.textContent = val;
}
directives["m-html"] = function(el, val, vdom) {
el.innerHTML = val;
}
directives["m-mask"] = function(el, val, vdom) {
}
// directives["m-for"] = function(el, val, vdom) {
// var splitVal = val.split(" in ");
// var alias = splitVal[0];
// var arr = self.get(splitVal[1]);
// var clone = el.cloneNode(true);
// var oldVal = vdom.val;
// var compilable = vdom.val.replace(new RegExp(alias, "gi"), splitVal[1] + '[0]');
// el.innerHTML = compileTemplate(compilable, self.$data);
// for(var i = 1; i < arr.length; i++) {
// var newClone = clone.cloneNode(true);
// var compilable = oldVal.replace(new RegExp(alias, "gi"), splitVal[1] + '[' + i + ']');
// newClone.innerHTML = compileTemplate(compilable, self.$data);
// var parent = el.parentNode;
// parent.appendChild(newClone);
// }
// vdom.val = el.textContent;
// delete vdom.props["m-for"];
// }
/**
* Builds the DOM With Data
* @param {Array} children
*/
this.build = function(children) {
for(var i = 0; i < children.length; i++) {
var el = children[i];
if(el.type === "#text") {
el.node.textContent = compileTemplate(el.val, this.$data);
} else if(el.props) {
for(var prop in el.props) {
var propVal = el.props[prop];
var compiledProperty = compileTemplate(propVal, this.$data);
var directive = directives[prop];
if(directive) {
el.node.removeAttribute(prop);
directive(el.node, compiledProperty, el);
}
if(!directive) el.node.setAttribute(prop, compiledProperty);
}
}
this.build(el.children);
}
}
/**
* Initializes Moon
*/
this.init = function() {
this.log("======= Moon =======");
if(_hooks.created) {
_hooks.created();
}
this.componentsToHTML();
this.createVirtualDOM(this.$el);
this.build(this.$dom.children);
if(_hooks.mounted) {
_hooks.mounted();
}
}
// Initialize ��
this.init();
}
/**
* Sets the Configuration of Moon
* @param {Object} opts
*/
Moon.config = function(opts) {
if(opts.silent) {
config.silent = opts.silent;
}
}
/**
* Runs an external Plugin
* @param {Object} plugin
*/
Moon.use = function(plugin) {
plugin.init(Moon);
}
/**
* Creates a Directive
* @param {String} name
* @param {Function} action
*/
Moon.directive = function(name, action) {
directives["m-" + name] = action;
}
/**
* Creates a Component
* @param {String} name
* @param {Function} action
*/
Moon.component = function(name, action) {
components[name] = action;
}
/**
* Makes an AJAX Request
* @param {String} method
* @param {String} url
* @param {Object} params
* @param {Function} cb
*/
Moon.ajax = function(method, url, params, cb) {
var xmlHttp = new XMLHttpRequest();
method = method.toUpperCase();
if(typeof params === "function") {
cb = params;
}
var urlParams = "?";
if(method === "POST") {
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
for(var param in params) {
urlParams += param + "=" + params[param] + "&";
}
}
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
cb(JSON.parse(xmlHttp.responseText));
}
xmlHttp.open(method, url, true);
xmlHttp.send(method === "POST" ? urlParams : null);
}
window.Moon = Moon;
window.$ = function(el) {
el = document.querySelectorAll(el);
return el.length === 1 ? el[0] : el;
}
})(window);
| src/core.js | "use strict";
(function(window) {
var config = {
silent: false
}
var directives = {};
var components = {};
/**
* Converts attributes into key-value pairs
* @param {Node} node
* @return {Object} Key-Value pairs of Attributes
*/
var extractAttrs = function(node) {
var attrs = {};
if(!node.attributes) return attrs;
var rawAttrs = node.attributes;
for(var i = 0; i < rawAttrs.length; i++) {
attrs[rawAttrs[i].name] = rawAttrs[i].value
}
return attrs;
}
/**
* Compiles a template with given data
* @param {String} template
* @param {Object} data
* @return {String} Template with data rendered
*/
var compileTemplate = function(template, data) {
var code = template,
re = /{{([A-Za-z0-9_.\[\]]+)}}/gi;
code.replace(re, function(match, p) {
code = code.replace(match, "` + data." + p + " + `");
});
var compile = new Function("data", "var out = `" + code + "`; return out");
var output = compile(data);
return output;
}
/**
* Gets Root Element
* @param {String} html
* @return {Node} Root Element
*/
var getRootElement = function(html) {
var dummy = document.createElement('div');
dummy.innerHTML = html;
return dummy.firstChild;
}
/**
* Merges two Objects
* @param {Object} obj
* @param {Object} obj2
* @return {Object} Merged Objects
*/
function merge(obj, obj2) {
for (var key in obj2) {
if (obj2.hasOwnProperty(key)) obj[key] = obj2[key];
}
return obj;
}
function Moon(opts) {
var _el = opts.el;
var _data = opts.data;
var _methods = opts.methods;
var _hooks = opts.hooks || {created: function() {}, mounted: function() {}, updated: function() {}, destroyed: function() {}};
var _destroyed = false;
var self = this;
this.$el = document.querySelector(_el);
this.$components = merge(opts.components || {}, components);
this.$dom = {type: this.$el.nodeName, children: [], node: this.$el};
// Change state when $data is changed
Object.defineProperty(this, '$data', {
get: function() {
return _data;
},
set: function(value) {
_data = value;
this.build(this.$dom.children);
},
configurable: true
});
/**
* Logs a Message
* @param {String} msg
*/
this.log = function(msg) {
if(!config.silent) console.log(msg);
}
/**
* Throws an Error
* @param {String} msg
*/
this.error = function(msg) {
console.log("Moon ERR: " + msg);
}
/**
* Creates an object to be used in a Virtual DOM
* @param {String} type
* @param {Array} children
* @param {String} val
* @param {Object} props
* @param {Node} node
* @return {Object} Object usable in Virtual DOM
*/
this.createElement = function(type, children, val, props, node) {
return {type: type, children: children, val: val, props: props, node: node};
}
/**
* Create Elements Recursively For all Children
* @param {Array} children
* @return {Array} Array of elements usable in Virtual DOM
*/
this.recursiveChildren = function(children) {
var recursiveChildrenArr = [];
for(var i = 0; i < children.length; i++) {
var child = children[i];
recursiveChildrenArr.push(this.createElement(child.nodeName, this.recursiveChildren(child.childNodes), child.textContent, extractAttrs(child), child));
}
return recursiveChildrenArr;
}
/**
* Creates Virtual DOM
* @param {Node} node
*/
this.createVirtualDOM = function(node) {
var vdom = this.createElement(node.nodeName, this.recursiveChildren(node.childNodes), node.textContent, extractAttrs(node), node);
this.$dom = vdom;
}
/**
* Turns Custom Components into their Corresponding Templates
*/
this.componentsToHTML = function() {
for(var component in this.$components) {
var componentsFound = document.getElementsByTagName(component);
componentsFound = Array.prototype.slice.call(componentsFound);
for(var i = 0; i < componentsFound.length; i++) {
var componentFound = componentsFound[i];
var componentProps = extractAttrs(componentFound);
var componentDummy = getRootElement(this.$components[component].template);
for(var attr in componentProps) {
componentDummy.setAttribute(attr, componentProps[attr]);
}
componentFound.outerHTML = componentDummy.outerHTML;
}
}
}
/**
* Sets Value in Data
* @param {String} key
* @param {String} val
*/
this.set = function(key, val) {
this.$data[key] = val;
if(!_destroyed) this.build(this.$dom.children);
if(_hooks.updated) {
_hooks.updated();
}
}
/**
* Gets Value in Data
* @param {String} key
* @return {String} Value of key in data
*/
this.get = function(key) {
return this.$data[key];
}
/**
* Calls a method
* @param {String} method
*/
this.method = function(method) {
_methods[method]();
}
this.destroy = function() {
Object.defineProperty(this, '$data', {
set: function(value) {
_data = value;
}
});
_destroyed = true;
if(_hooks.destroyed) _hooks.destroyed();
}
// Default Directives
directives["m-if"] = function(el, val, vdom) {
var evaluated = new Function("return " + val);
if(!evaluated()) {
el.textContent = "";
} else {
el.textContent = compileTemplate(vdom.val, self.$data);
}
}
directives["m-show"] = function(el, val, vdom) {
var evaluated = new Function("return " + val);
if(!evaluated()) {
el.style.display = '';
} else {
el.style.display = 'block';
}
}
directives["m-on"] = function(el, val, vdom) {
var splitVal = val.split(":");
var eventToCall = splitVal[0];
var methodToCall = splitVal[1];
el.addEventListener(eventToCall, function() {
self.method(methodToCall);
});
el.removeAttribute("m-on");
delete vdom.props["m-on"];
}
directives["m-model"] = function(el, val, vdom) {
el.value = self.get(val);
el.addEventListener("input", function() {
self.set(val, el.value);
});
el.removeAttribute("m-model");
delete vdom.props["m-model"];
}
directives["m-once"] = function(el, val, vdom) {
vdom.val = el.textContent;
for(var child in vdom.children) {
vdom.children[child].val = compileTemplate(vdom.children[child].val, self.$data);
}
}
directives["m-text"] = function(el, val, vdom) {
el.textContent = val;
}
directives["m-html"] = function(el, val, vdom) {
el.innerHTML = val;
}
directives["m-mask"] = function(el, val, vdom) {
}
// directives["m-for"] = function(el, val, vdom) {
// var splitVal = val.split(" in ");
// var alias = splitVal[0];
// var arr = self.get(splitVal[1]);
// var clone = el.cloneNode(true);
// var oldVal = vdom.val;
// var compilable = vdom.val.replace(new RegExp(alias, "gi"), splitVal[1] + '[0]');
// el.innerHTML = compileTemplate(compilable, self.$data);
// for(var i = 1; i < arr.length; i++) {
// var newClone = clone.cloneNode(true);
// var compilable = oldVal.replace(new RegExp(alias, "gi"), splitVal[1] + '[' + i + ']');
// newClone.innerHTML = compileTemplate(compilable, self.$data);
// var parent = el.parentNode;
// parent.appendChild(newClone);
// }
// vdom.val = el.textContent;
// delete vdom.props["m-for"];
// }
/**
* Builds the DOM With Data
* @param {Array} children
*/
this.build = function(children) {
for(var i = 0; i < children.length; i++) {
var el = children[i];
if(el.type === "#text") {
el.node.textContent = compileTemplate(el.val, this.$data);
} else if(el.props) {
for(var prop in el.props) {
var propVal = el.props[prop];
var compiledProperty = compileTemplate(propVal, this.$data);
var directive = directives[prop];
if(directive) {
el.node.removeAttribute(prop);
directive(el.node, compiledProperty, el);
}
if(!directive) el.node.setAttribute(prop, compiledProperty);
}
}
this.build(el.children);
}
}
/**
* Initializes Moon
*/
this.init = function() {
this.log("======= Moon =======");
if(_hooks.created) {
_hooks.created();
}
this.componentsToHTML();
this.createVirtualDOM(this.$el);
this.build(this.$dom.children);
if(_hooks.mounted) {
_hooks.mounted();
}
}
// Initialize ��
this.init();
}
/**
* Sets the Configuration of Moon
* @param {Object} opts
*/
Moon.config = function(opts) {
if(opts.silent) {
config.silent = opts.silent;
}
}
/**
* Runs an external Plugin
* @param {Object} plugin
*/
Moon.use = function(plugin) {
plugin.init(Moon);
}
/**
* Creates a Directive
* @param {String} name
* @param {Function} action
*/
Moon.directive = function(name, action) {
directives["m-" + name] = action;
}
/**
* Creates a Component
* @param {String} name
* @param {Function} action
*/
Moon.component = function(name, action) {
components[name] = action;
}
/**
* Makes an AJAX Request
* @param {String} method
* @param {String} url
* @param {Object} params
* @param {Function} cb
*/
Moon.ajax = function(method, url, params, cb) {
var xmlHttp = new XMLHttpRequest();
method = method.toUpperCase();
if(typeof params === "function") {
cb = params;
}
var urlParams = "?";
if(method === "POST") {
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
for(var param in params) {
urlParams += param + "=" + params[param] + "&";
}
}
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
cb(JSON.parse(xmlHttp.responseText));
}
xmlHttp.open(method, url, true);
xmlHttp.send(method === "POST" ? urlParams : null);
}
window.Moon = Moon;
window.$ = function(el) {
el = document.querySelectorAll(el);
return el.length === 1 ? el[0] : el;
}
})(window);
| set display to none
| src/core.js | set display to none | <ide><path>rc/core.js
<ide> directives["m-show"] = function(el, val, vdom) {
<ide> var evaluated = new Function("return " + val);
<ide> if(!evaluated()) {
<del> el.style.display = '';
<add> el.style.display = 'none';
<ide> } else {
<ide> el.style.display = 'block';
<ide> } |
|
Java | apache-2.0 | 9459cd8e0fc78103340b910ecabb9dd32a1887e6 | 0 | hackbuteer59/sakai,whumph/sakai,tl-its-umich-edu/sakai,Fudan-University/sakai,pushyamig/sakai,zqian/sakai,buckett/sakai-gitflow,tl-its-umich-edu/sakai,colczr/sakai,conder/sakai,introp-software/sakai,willkara/sakai,lorenamgUMU/sakai,udayg/sakai,noondaysun/sakai,rodriguezdevera/sakai,frasese/sakai,joserabal/sakai,OpenCollabZA/sakai,wfuedu/sakai,kingmook/sakai,frasese/sakai,OpenCollabZA/sakai,clhedrick/sakai,buckett/sakai-gitflow,colczr/sakai,conder/sakai,kwedoff1/sakai,liubo404/sakai,rodriguezdevera/sakai,whumph/sakai,bkirschn/sakai,OpenCollabZA/sakai,clhedrick/sakai,pushyamig/sakai,colczr/sakai,OpenCollabZA/sakai,frasese/sakai,udayg/sakai,introp-software/sakai,liubo404/sakai,kwedoff1/sakai,duke-compsci290-spring2016/sakai,duke-compsci290-spring2016/sakai,lorenamgUMU/sakai,ouit0408/sakai,willkara/sakai,noondaysun/sakai,ouit0408/sakai,ouit0408/sakai,buckett/sakai-gitflow,lorenamgUMU/sakai,introp-software/sakai,lorenamgUMU/sakai,wfuedu/sakai,bkirschn/sakai,udayg/sakai,colczr/sakai,zqian/sakai,surya-janani/sakai,willkara/sakai,surya-janani/sakai,rodriguezdevera/sakai,kwedoff1/sakai,zqian/sakai,liubo404/sakai,udayg/sakai,zqian/sakai,colczr/sakai,noondaysun/sakai,lorenamgUMU/sakai,zqian/sakai,joserabal/sakai,liubo404/sakai,kingmook/sakai,wfuedu/sakai,duke-compsci290-spring2016/sakai,clhedrick/sakai,liubo404/sakai,frasese/sakai,kwedoff1/sakai,bkirschn/sakai,introp-software/sakai,ktakacs/sakai,hackbuteer59/sakai,bzhouduke123/sakai,buckett/sakai-gitflow,joserabal/sakai,rodriguezdevera/sakai,wfuedu/sakai,ouit0408/sakai,ktakacs/sakai,wfuedu/sakai,conder/sakai,colczr/sakai,wfuedu/sakai,hackbuteer59/sakai,whumph/sakai,ktakacs/sakai,kingmook/sakai,ktakacs/sakai,willkara/sakai,tl-its-umich-edu/sakai,hackbuteer59/sakai,surya-janani/sakai,liubo404/sakai,ktakacs/sakai,joserabal/sakai,bkirschn/sakai,conder/sakai,udayg/sakai,conder/sakai,puramshetty/sakai,ktakacs/sakai,duke-compsci290-spring2016/sakai,introp-software/sakai,puramshetty/sakai,wfuedu/sakai,willkara/sakai,frasese/sakai,bzhouduke123/sakai,duke-compsci290-spring2016/sakai,noondaysun/sakai,lorenamgUMU/sakai,lorenamgUMU/sakai,hackbuteer59/sakai,ktakacs/sakai,colczr/sakai,Fudan-University/sakai,bkirschn/sakai,kwedoff1/sakai,clhedrick/sakai,kingmook/sakai,clhedrick/sakai,bkirschn/sakai,kingmook/sakai,kwedoff1/sakai,OpenCollabZA/sakai,whumph/sakai,Fudan-University/sakai,buckett/sakai-gitflow,hackbuteer59/sakai,bzhouduke123/sakai,bzhouduke123/sakai,bkirschn/sakai,surya-janani/sakai,pushyamig/sakai,joserabal/sakai,whumph/sakai,noondaysun/sakai,duke-compsci290-spring2016/sakai,OpenCollabZA/sakai,kingmook/sakai,kingmook/sakai,rodriguezdevera/sakai,joserabal/sakai,wfuedu/sakai,hackbuteer59/sakai,duke-compsci290-spring2016/sakai,liubo404/sakai,whumph/sakai,frasese/sakai,zqian/sakai,rodriguezdevera/sakai,joserabal/sakai,introp-software/sakai,OpenCollabZA/sakai,joserabal/sakai,whumph/sakai,OpenCollabZA/sakai,ouit0408/sakai,bzhouduke123/sakai,conder/sakai,clhedrick/sakai,rodriguezdevera/sakai,ouit0408/sakai,willkara/sakai,Fudan-University/sakai,Fudan-University/sakai,noondaysun/sakai,lorenamgUMU/sakai,puramshetty/sakai,surya-janani/sakai,buckett/sakai-gitflow,willkara/sakai,surya-janani/sakai,buckett/sakai-gitflow,duke-compsci290-spring2016/sakai,kwedoff1/sakai,introp-software/sakai,udayg/sakai,tl-its-umich-edu/sakai,puramshetty/sakai,bzhouduke123/sakai,clhedrick/sakai,bkirschn/sakai,surya-janani/sakai,pushyamig/sakai,tl-its-umich-edu/sakai,pushyamig/sakai,bzhouduke123/sakai,udayg/sakai,introp-software/sakai,pushyamig/sakai,rodriguezdevera/sakai,Fudan-University/sakai,whumph/sakai,pushyamig/sakai,buckett/sakai-gitflow,clhedrick/sakai,frasese/sakai,hackbuteer59/sakai,tl-its-umich-edu/sakai,pushyamig/sakai,conder/sakai,kingmook/sakai,noondaysun/sakai,puramshetty/sakai,zqian/sakai,zqian/sakai,willkara/sakai,tl-its-umich-edu/sakai,puramshetty/sakai,frasese/sakai,ouit0408/sakai,Fudan-University/sakai,conder/sakai,noondaysun/sakai,liubo404/sakai,puramshetty/sakai,colczr/sakai,ouit0408/sakai,tl-its-umich-edu/sakai,puramshetty/sakai,surya-janani/sakai,kwedoff1/sakai,ktakacs/sakai,udayg/sakai,Fudan-University/sakai,bzhouduke123/sakai | /**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2006, 2007, 2008, 2009 The Sakai Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ECL-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
package org.sakaiproject.connector.fck;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.codec.binary.Base64;
import org.sakaiproject.authz.api.SecurityAdvisor;
import org.sakaiproject.authz.api.SecurityService;
import org.sakaiproject.component.cover.ComponentManager;
import org.sakaiproject.component.api.ServerConfigurationService;
import org.sakaiproject.content.api.ContentCollection;
import org.sakaiproject.content.api.ContentCollectionEdit;
import org.sakaiproject.content.api.ContentHostingService;
import org.sakaiproject.content.api.ContentResource;
import org.sakaiproject.entity.api.Entity;
import org.sakaiproject.entity.api.ResourceProperties;
import org.sakaiproject.entity.api.ResourcePropertiesEdit;
import org.sakaiproject.entitybroker.EntityBroker;
import org.sakaiproject.entitybroker.entityprovider.extension.EntityData;
import org.sakaiproject.event.api.NotificationService;
import org.sakaiproject.exception.IdUsedException;
import org.sakaiproject.exception.PermissionException;
import org.sakaiproject.site.api.SiteService;
import org.sakaiproject.tool.api.SessionManager;
import org.sakaiproject.util.ResourceLoader;
import org.sakaiproject.util.StringUtil;
import org.sakaiproject.util.Validator;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.sakaiproject.api.app.messageforums.entity.DecoratedForumInfo;
import org.sakaiproject.api.app.messageforums.entity.DecoratedTopicInfo;
/**
* Conenctor Servlet to upload and browse files to a Sakai worksite for the FCK editor.<br>
*
* This servlet accepts 4 commands used to retrieve and create files and folders from a worksite resource.
* The allowed commands are:
* <ul>
* <li>GetFolders: Retrive the list of directory under the current folder
* <li>GetFoldersAndFiles: Retrive the list of files and directory under the current folder
* <li>CreateFolder: Create a new directory under the current folder
* <li>FileUpload: Send a new file to the server (must be sent with a POST)
* </ul>
*
* The current user must have a valid sakai session with permissions to access the realm associated
* with the resource.
*
* @author Joshua Ryan ([email protected]) merged servlets and Sakai-ified them
*
* This connector is loosely based on two servlets found on the FCK website http://www.fckeditor.net/
* written by Simone Chiaretta ([email protected])
*
*/
public class FCKConnectorServlet extends HttpServlet {
private static Log M_log = LogFactory.getLog(FCKConnectorServlet.class);
private static final long serialVersionUID = 1L;
private static final String MFORUM_FORUM_PREFIX = "/direct/forum/";
private static final String MFORUM_TOPIC_PREFIX = "/direct/forum_topic/";
private static final String MFORUM_MESSAGE_PREFIX = "/direct/forum_message/";
private static final String FCK_ADVISOR_BASE = "fck.security.advisor.";
private static final String CK_ADVISOR_BASE = "ck.security.advisor.";
private static final String FCK_EXTRA_COLLECTIONS_BASE = "fck.extra.collections.";
// private String[] hiddenProviders = {"forum_message", "forum_topic"};
//Default hidden providers
private List <String> hiddenProviders;
private String serverUrlPrefix = "";
private ContentHostingService contentHostingService = null;
private SecurityService securityService = null;
private SessionManager sessionManager = null;
private NotificationService notificationService = null;
private SiteService siteService = null;
private SecurityAdvisor contentNewAdvisor = null;
private EntityBroker entityBroker;
private ServerConfigurationService serverConfigurationService = null;
private ResourceLoader resourceLoader = null;
/**
* Injects dependencies using the ComponentManager cover.
*
* @param beanName The name of the bean to get.
* @return the bean
*/
private Object inject(String beanName) {
Object bean = null;
bean = ComponentManager.get(beanName);
if (bean == null) {
throw new IllegalStateException("FAILURE to inject dependency during initialization of the FCKConnectorServlet");
}
return bean;
}
/**
* Ensures all necessary dependencies are loaded.
*/
private void initialize() {
if (contentHostingService == null) {
contentHostingService = (ContentHostingService) inject("org.sakaiproject.content.api.ContentHostingService");
}
if (securityService == null) {
securityService = (SecurityService) inject("org.sakaiproject.authz.api.SecurityService");
}
if (sessionManager == null) {
sessionManager = (SessionManager) inject("org.sakaiproject.tool.api.SessionManager");
}
if (notificationService == null) {
notificationService = (NotificationService) inject("org.sakaiproject.event.api.NotificationService");
}
if (siteService == null) {
siteService = (SiteService) inject("org.sakaiproject.site.api.SiteService");
if (entityBroker == null) {
entityBroker = (EntityBroker) inject("org.sakaiproject.entitybroker.EntityBroker");
}
if (serverConfigurationService == null) {
serverConfigurationService = (ServerConfigurationService) inject("org.sakaiproject.component.api.ServerConfigurationService");
}
//Default providers to exclude, add addition with the property textarea.hiddenProviders if needed
// hiddenProviders = Arrays.asList("");
hiddenProviders = Arrays.asList("assignment","sam_pub","forum","forum_topic","topic");
}
if (resourceLoader == null) {
resourceLoader = new ResourceLoader("org.sakaiproject.connector.fck.Messages");
}
if (contentNewAdvisor == null) {
contentNewAdvisor = new SecurityAdvisor(){
public SecurityAdvice isAllowed(String userId, String function, String reference){
try {
securityService.popAdvisor();
return securityService.unlock(userId, "content.new".equals(function)?"content.read":function, reference)?
SecurityAdvice.ALLOWED:SecurityAdvice.NOT_ALLOWED;
} catch (Exception ex) {
return SecurityAdvice.NOT_ALLOWED;
} finally {
securityService.pushAdvisor(this);
}
}
};
}
}
public void init() throws ServletException {
super.init();
initialize();
}
/**
* pops a special private advisor when necessary
* @param thisDir Directory where this is referencing
* @param collectionBase base of the collection
*/
private void popPrivateAdvisor(String thisDir, String collectionBase) {
if (thisDir.startsWith("/private/")) {
SecurityAdvisor advisor = (SecurityAdvisor) sessionManager.getCurrentSession().getAttribute(FCK_ADVISOR_BASE + collectionBase);
if (advisor != null) {
securityService.popAdvisor(advisor);
}
advisor = (SecurityAdvisor) sessionManager.getCurrentSession().getAttribute(CK_ADVISOR_BASE + collectionBase);
if (advisor != null) {
securityService.popAdvisor(advisor);
}
}
}
/**
* pushes a special private advisor when necessary
* @param thisDir Directory where this is referencing
* @param collectionBase base of the collection
*/
private void pushPrivateAdvisor(String thisDir, String collectionBase) {
if (thisDir.startsWith("/private/")) {
SecurityAdvisor advisor = (SecurityAdvisor) sessionManager.getCurrentSession().getAttribute(FCK_ADVISOR_BASE + collectionBase);
if (advisor != null) {
securityService.pushAdvisor(advisor);
}
advisor = (SecurityAdvisor) sessionManager.getCurrentSession().getAttribute(CK_ADVISOR_BASE + collectionBase);
if (advisor != null) {
securityService.pushAdvisor(advisor);
}
}
}
/**
* Manage the Get requests (GetFolders, GetFoldersAndFiles, CreateFolder).<br>
*
* The servlet accepts commands sent in the following format:<br>
* connector?Command=CommandName&Type=ResourceType&CurrentFolder=FolderPath<br><br>
* It executes the command and then return the results to the client in XML format.
*
* Valid values for Type are: Image, File, Flash and Link
*
*/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
initialize();
response.setContentType("text/xml; charset=UTF-8");
response.setHeader("Cache-Control","no-cache");
PrintWriter out = null;
String commandStr = request.getParameter("Command");
String type = request.getParameter("Type");
String currentFolder = request.getParameter("CurrentFolder");
serverUrlPrefix = serverConfigurationService.getServerUrl();
String collectionBase = request.getPathInfo();
Document document = null;
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.newDocument();
}
catch (ParserConfigurationException pce) {
pce.printStackTrace();
}
Node root = createCommonXml(document, commandStr, type, currentFolder,
contentHostingService.getUrl(currentFolder));
//To support meletedocs, the call to getFolders has to be able to retrieve all folders that are part of melete private (which will be passed in) as
//well as ones that are not. This is why the advisor is being manipulated inside the getfolders method.
if ("GetFolders".equals(commandStr)) {
getFolders(currentFolder, root, document, collectionBase);
}
else if ("GetFoldersAndFiles".equals(commandStr)) {
getFolders(currentFolder, root, document, collectionBase);
//Might need this advisor for files
pushPrivateAdvisor(currentFolder,collectionBase);
getFiles(currentFolder, root, document, type);
popPrivateAdvisor(currentFolder,collectionBase);
}
else if ("GetFoldersFilesAssignsTestsTopics".equals(commandStr)) {
ConnectorHelper thisConnectorHelper = new ConnectorHelper();
thisConnectorHelper.init();
getFolders(currentFolder, root, document, collectionBase);
//Might need this advisor for files
pushPrivateAdvisor(currentFolder,collectionBase);
getFilesOnly(currentFolder, root, document, type);
popPrivateAdvisor(currentFolder,collectionBase);
getAssignmentsOnly(currentFolder, root, document, type, thisConnectorHelper);
getTestsOnly(currentFolder, root, document, type, thisConnectorHelper);
getOtherEntitiesOnly(currentFolder, root, document, type, thisConnectorHelper);
getForumsAndThreads(currentFolder, root, document, type, thisConnectorHelper);
}
else if ("GetResourcesAssignsTestsTopics".equals(commandStr)) {
ConnectorHelper thisConnectorHelper = new ConnectorHelper();
thisConnectorHelper.init();
pushPrivateAdvisor(currentFolder,collectionBase);
getResources(currentFolder, root, document, collectionBase, type);
popPrivateAdvisor(currentFolder,collectionBase);
getAssignmentsOnly(currentFolder, root, document, type, thisConnectorHelper);
getTestsOnly(currentFolder, root, document, type, thisConnectorHelper);
getOtherEntitiesOnly(currentFolder, root, document, type, thisConnectorHelper);
getForumsAndThreads(currentFolder, root, document, type, thisConnectorHelper);
}
else if ("GetResources".equals(commandStr)) {
pushPrivateAdvisor(currentFolder,collectionBase);
getResources(currentFolder, root, document, collectionBase, type);
popPrivateAdvisor(currentFolder,collectionBase);
}
else if ("CreateFolder".equals(commandStr)) {
String newFolderStr = request.getParameter("NewFolderName");
String status = "110";
pushPrivateAdvisor(currentFolder,collectionBase);
try {
ContentCollectionEdit edit = contentHostingService
.addCollection(currentFolder + Validator.escapeResourceName(newFolderStr) + Entity.SEPARATOR);
ResourcePropertiesEdit resourceProperties = edit.getPropertiesEdit();
resourceProperties.addProperty (ResourceProperties.PROP_DISPLAY_NAME, newFolderStr);
String altRoot = getAltReferenceRoot(currentFolder);
if (altRoot != null)
resourceProperties.addProperty (ContentHostingService.PROP_ALTERNATE_REFERENCE, altRoot);
contentHostingService.commitCollection(edit);
status="0";
}
catch (IdUsedException iue) {
status = "101";
}
catch(PermissionException pex) {
status = "103";
}
catch (Exception e) {
status = "102";
}
setCreateFolderResponse(status, root, document);
popPrivateAdvisor(currentFolder,collectionBase);
}
document.getDocumentElement().normalize();
try {
out = response.getWriter();
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(out);
transformer.transform(source, result);
}
catch (Exception ex) {
ex.printStackTrace();
}
finally {
if (out != null) {
out.close();
}
}
//Pop the advisor if we need to
popPrivateAdvisor(currentFolder,collectionBase);
}
/**
* Manage the Post requests (FileUpload).<br>
*
* The servlet accepts commands sent in the following format:<br>
* connector?Command=FileUpload&Type=ResourceType&CurrentFolder=FolderPath<br><br>
* It stores the file (renaming it in case a file with the same name exists) and then return an HTML file
* with a javascript command in it.
*
*/
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
initialize();
response.setContentType("text/html; charset=UTF-8");
response.setHeader("Cache-Control", "no-cache");
PrintWriter out = null;
String command = request.getParameter("Command");
String currentFolder = request.getParameter("CurrentFolder");
String collectionBase = request.getPathInfo();
pushPrivateAdvisor(currentFolder,collectionBase);
String fileName = "";
String errorMessage = "";
String status="0";
ContentResource attachment = null;
if (!"FileUpload".equals(command) && !"QuickUpload".equals(command) && !("QuickUploadEquation").equals(command) && !("QuickUploadAttachment").equals(command)) {
status = "203";
}
else {
DiskFileUpload upload = new DiskFileUpload();
String mime="";
InputStream requestStream = null;
byte [] bytes=null;
try {
//Special case for uploading fmath equations
if (("QuickUploadEquation").equals(command)) {
String image = request.getParameter("image");
String type = request.getParameter("type");
// size protection
if(image==null || image.length()>1000000) return;
bytes = Base64.decodeBase64(image);
fileName = "fmath-equation-"+request.getParameter("name");
if ("PNG".equals(type)) {
mime = "image/png";
if (fileName.indexOf(".") == -1) {
fileName+=".png";
}
}
else {
mime = "image/jpeg";
if (fileName.indexOf(".") == -1) {
fileName+=".jpg";
}
}
}
else {
//If this is a multipart request
if (ServletFileUpload.isMultipartContent(request)) {
List items = upload.parseRequest(request);
Map fields = new HashMap();
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
fields.put(item.getFieldName(), item.getString());
}
else {
fields.put(item.getFieldName(), item);
}
}
FileItem uplFile = (FileItem)fields.get("NewFile");
String filePath = uplFile.getName();
filePath = filePath.replace('\\','/');
String[] pathParts = filePath.split("/");
fileName = pathParts[pathParts.length-1];
mime = uplFile.getContentType();
requestStream = uplFile.getInputStream();
}
else {
requestStream = request.getInputStream();
mime = request.getHeader("Content-Type");
}
}
//If there's no filename, make a guid name with the mime extension?
if ("".equals (fileName)) {
fileName = UUID.randomUUID().toString();
}
String nameWithoutExt = fileName;
String ext = "";
if (fileName.lastIndexOf(".") > 0) {
nameWithoutExt = fileName.substring(0, fileName.lastIndexOf("."));
ext = fileName.substring(fileName.lastIndexOf("."));
}
int counter = 1;
boolean done = false;
while(!done) {
try {
ResourcePropertiesEdit resourceProperties = contentHostingService.newResourceProperties();
resourceProperties.addProperty (ResourceProperties.PROP_DISPLAY_NAME, fileName);
if ("QuickUploadEquation".equals(command) || "QuickUploadAttachment".equals(command)) {
attachment = bypassAddAttachment(request,fileName,mime,bytes,requestStream,resourceProperties);
} else {
String altRoot = getAltReferenceRoot(currentFolder);
if (altRoot != null)
resourceProperties.addProperty (ContentHostingService.PROP_ALTERNATE_REFERENCE, altRoot);
int noti = NotificationService.NOTI_NONE;
if (bytes != null) {
contentHostingService.addResource(currentFolder+fileName, mime, bytes, resourceProperties, noti);
}
else if (requestStream != null) {
contentHostingService.addResource(currentFolder+fileName, mime, requestStream, resourceProperties, noti);
}
else {
//Nothing to do
}
}
done = true;
}
catch (IdUsedException iue) {
//the name is already used, so we do a slight rename to prevent the colision
fileName = nameWithoutExt + "(" + counter + ")" + ext;
status = "201";
counter++;
}
catch (Exception ex) {
//this user can't write where they are trying to write.
done = true;
ex.printStackTrace();
status = "203";
}
}
}
catch (Exception ex) {
ex.printStackTrace();
status = "203";
}
}
try {
out = response.getWriter();
if ("QuickUploadEquation".equals(command) || "QuickUploadAttachment".equals(command)) {
out.println(attachment!=null?attachment.getUrl():"");
}
else {
out.println("<script type=\"text/javascript\">");
out.println("(function(){ var d = document.domain ; while ( true ) {");
out.println("try { var test = parent.document.domain ; break ; } catch( e ) {}");
out.println("d = d.replace( /.*?(?:\\.|$)/, '' ) ; if ( d.length == 0 ) break ;");
out.println("try { document.domain = d ; } catch (e) { break ; }}})() ;");
out.println("window.parent.OnUploadCompleted(" + status + ",'"
+ (attachment!=null?attachment.getUrl():"")
+ "','" + fileName + "','" + errorMessage + "');");
out.println("</script>");
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (out != null) {
out.close();
}
}
popPrivateAdvisor(currentFolder,collectionBase);
}
private void setCreateFolderResponse(String status, Node root, Document doc) {
Element element = doc.createElement("Error");
element.setAttribute("number", status);
root.appendChild(element);
}
private void getFolders(String dir, Node root, Document doc, String collectionBase) {
Element folders = doc.createElement("Folders");
root.appendChild(folders);
ContentCollection collection = null;
Map<String, String> map = null;
List <Iterator> foldersIterator = new ArrayList <Iterator> ();
try {
//hides the real root level stuff and just shows the users the
//the root folders of all the top collections they actually have access to.
int dirlength = dir.split("/").length;
if (dirlength == 2 || dir.startsWith("/private/")) {
List<String> collections = new ArrayList<String>();
map = contentHostingService.getCollectionMap();
for (String key : map.keySet()) {
if (!contentHostingService.isInDropbox((String)key)) {
collections.add(key);
}
}
List extras = (List) sessionManager.getCurrentSession()
.getAttribute(FCK_EXTRA_COLLECTIONS_BASE + collectionBase);
if (extras != null) {
collections.addAll(extras);
}
foldersIterator.add(collections.iterator());
}
if (dirlength > 2) {
pushPrivateAdvisor(dir,collectionBase);
collection = contentHostingService.getCollection(dir);
if (collection != null && collection.getMembers() != null) {
foldersIterator.add(collection.getMembers().iterator());
}
popPrivateAdvisor(dir,collectionBase);
}
}
catch (Exception e) {
e.printStackTrace();
//not a valid collection? file list will be empty and so will the doc
}
for (Iterator folderIterator : foldersIterator ) {
if (folderIterator != null) {
String current = null;
// create a SortedSet using the elements that are going to be added to the XML doc
SortedSet<Element> sortedFolders = new TreeSet<Element>(new SortElementsForDisplay());
while (folderIterator.hasNext()) {
try {
current = (String) folderIterator.next();
pushPrivateAdvisor(current,collectionBase);
ContentCollection myCollection = contentHostingService.getCollection(current);
Element element=doc.createElement("Folder");
element.setAttribute("url", current);
String collectionName = myCollection.getProperties().getProperty(myCollection.getProperties().getNamePropDisplayName());
if (current.contains("/meleteDocs/")) {
if (resourceLoader != null)
collectionName = resourceLoader.getString("melete_collectionname");
else
collectionName = "Melete Files";
}
element.setAttribute("name",collectionName);
// by adding the folders to this collection, they will be sorted for display
sortedFolders.add(element);
popPrivateAdvisor(current,collectionBase);
}
catch (Exception e) {
//do nothing, we either don't have access to the collction or it's a resource
M_log.debug("No access to display collection" + e.getMessage());
}
}
// now append the folderse to the parent document in sorted order
for (Element folder: sortedFolders) {
folders.appendChild(folder);
}
}
}
}
private void getResources(String dir, Node root, Document doc, String collectionBase, String type) {
Element folders = doc.createElement("Folders");
root.appendChild(folders);
ContentCollection collection = null;
Map<String, String> map = null;
Iterator foldersIterator = null;
try {
//hides the real root level stuff and just shows the users the
//the root folders of all the top collections they actually have access to.
if (dir.split("/").length == 2) {
List<String> collections = new ArrayList<String>();
map = contentHostingService.getCollectionMap();
if (map != null && map.keySet() != null) {
collections.addAll(map.keySet());
}
List extras = (List) sessionManager.getCurrentSession()
.getAttribute(FCK_EXTRA_COLLECTIONS_BASE + collectionBase);
if (extras != null) {
collections.addAll(extras);
}
foldersIterator = collections.iterator();
}
else if (dir.split("/").length > 2) {
collection = contentHostingService.getCollection(dir);
if (collection != null && collection.getMembers() != null) {
foldersIterator = collection.getMembers().iterator();
}
}
}
catch (Exception e) {
e.printStackTrace();
//not a valid collection? file list will be empty and so will the doc
}
if (foldersIterator != null) {
String current = null;
// create a SortedSet using the elements that are going to be added to the XML doc
SortedSet<Element> sortedFolders = new TreeSet<Element>(new SortElementsForDisplay());
while (foldersIterator.hasNext()) {
try {
current = (String) foldersIterator.next();
ContentCollection myCollection = contentHostingService.getCollection(current);
Element element=doc.createElement("Folder");
element.setAttribute("path", current);
element.setAttribute("url", contentHostingService.getUrl(current));
element.setAttribute("name", myCollection.getProperties().getProperty(
myCollection.getProperties().getNamePropDisplayName()));
// SAK-27756 Added children count to decide whether to show expand button as we removed nested iteration of files
element.setAttribute("childrenCount", myCollection.getMemberCount()+"");
// by adding the folders to this collection, they will be sorted for display
sortedFolders.add(element);
}
catch (Exception e) {
//do nothing, we either don't have access to the collction or it's a resource
}
}
// now append the folderse to the parent document in sorted order
for (Element folder: sortedFolders) {
Node addedFolder = folders.appendChild(folder);
}
getFilesOnly(dir, root, doc, type);
}
}
private void getFiles(String dir, Node root, Document doc, String type) {
Element files=doc.createElement("Files");
root.appendChild(files);
ContentCollection collection = null;
try {
collection = contentHostingService.getCollection(dir);
}
catch (Exception e) {
//do nothing, file will be empty and so will doc
}
if (collection != null) {
Iterator iterator = collection.getMemberResources().iterator();
// create a SortedSet using the elements that are going to be added to the XML doc
SortedSet<Element> sortedFiles = new TreeSet<Element>(new SortElementsForDisplay());
while (iterator.hasNext ()) {
try {
ContentResource current = (ContentResource)iterator.next();
String ext = current.getProperties().getProperty(
current.getProperties().getNamePropContentType());
if ( ("File".equals(type) && (ext != null) ) ||
("Flash".equals(type) && ext.equalsIgnoreCase("application/x-shockwave-flash") ) ||
("Image".equals(type) && ext.startsWith("image") ) ||
("Media".equals(type) && (ext.startsWith("video") || ext.startsWith("audio") || ext.equalsIgnoreCase("application/x-shockwave-flash")) ) ||
"Link".equals(type)) {
String id = current.getId();
Element element=doc.createElement("File");
// displaying the id instead of the display name because the url used
// for linking in the FCK editor uses what is returned...
element.setAttribute("name", current.getProperties().getProperty(
current.getProperties().getNamePropDisplayName()));
element.setAttribute("url", current.getUrl());
if (current.getProperties().getProperty(
current.getProperties().getNamePropContentLength()) != null) {
element.setAttribute("size", "" + current.getProperties()
.getPropertyFormatted(current.getProperties()
.getNamePropContentLength()));
}
else {
element.setAttribute("size", "0");
}
// by adding the files to this collection, they will be sorted for display
sortedFiles.add(element);
}
}
catch (ClassCastException e) {
//it's a colleciton not an item
}
catch (Exception e) {
//do nothing, we don't have access to the item
}
}
// now append the files to the parent document in sorted order
for (Element file: sortedFiles) {
files.appendChild(file);
}
}
}
private void getFilesOnly(String dir, Node root, Document doc, String type) {
Element files=doc.createElement("Files");
root.appendChild(files);
ContentCollection collection = null;
List myAssignments = null;
List myTests = null;
List myTopics = null;
String siteId = null;
String[] f = dir.split("/");
siteId = f[2];
try {
collection = contentHostingService.getCollection(dir);
}
catch (Exception e) {
//do nothing, file will be empty and so will doc
}
if (collection != null) {
Iterator iterator = collection.getMemberResources().iterator();
while (iterator.hasNext ()) {
try {
ContentResource current = (ContentResource)iterator.next();
String ext = current.getProperties().getProperty(
current.getProperties().getNamePropContentType());
if ( ("File".equals(type) && (ext != null) ) ||
("Flash".equals(type) && ext.equalsIgnoreCase("application/x-shockwave-flash") ) ||
("Image".equals(type) && ext.startsWith("image") ) ||
"Link".equals(type)) {
String id = current.getId();
Element element=doc.createElement("File");
// displaying the id instead of the display name because the url used
// for linking in the FCK editor uses what is returned...
element.setAttribute("name", current.getProperties().getProperty(
current.getProperties().getNamePropDisplayName()));
element.setAttribute("url", current.getUrl());
if (current.getProperties().getProperty(
current.getProperties().getNamePropContentLength()) != null) {
element.setAttribute("size", "" + current.getProperties()
.getPropertyFormatted(current.getProperties()
.getNamePropContentLength()));
}
else {
element.setAttribute("size", "0");
}
files.appendChild(element);
}
}
catch (ClassCastException e) {
//it's a colleciton not an item
}
catch (Exception e) {
//do nothing, we don't have access to the item
}
}
}
}
private void getAssignmentsOnly(String dir, Node root, Document doc, String type, ConnectorHelper ch) {
List myAssignments = null;
String siteId = null;
String[] f = dir.split("/");
siteId = f[2];
SortedSet<Element> sortedItems = new TreeSet<Element>(new SortElementsForDisplay());
Element assignments=doc.createElement("Assignments");
root.appendChild(assignments);
myAssignments = ch.getSiteAssignments(siteId);
Iterator assignmentsIterator = myAssignments.iterator();
while(assignmentsIterator.hasNext()){
String[] thisAssignmentReference = (String[]) assignmentsIterator.next();
Element element=doc.createElement("Assignment");
element.setAttribute("name",thisAssignmentReference[0]);
element.setAttribute("url",serverUrlPrefix + thisAssignmentReference[1]);
element.setAttribute("size", "0");
sortedItems.add(element);
}
for (Element item: sortedItems) {
assignments.appendChild(item);
}
}
private void getTestsOnly(String dir, Node root, Document doc, String type, ConnectorHelper ch) {
List myTests = null;
String siteId = null;
String[] f = dir.split("/");
siteId = f[2];
SortedSet<Element> sortedItems = new TreeSet<Element>(new SortElementsForDisplay());
Element assessments=doc.createElement("Assessments");
root.appendChild(assessments);
myTests = ch.getPublishedAssements(siteId);
Iterator assessmentIterator = myTests.iterator();
while(assessmentIterator.hasNext()){
String[] thisAssessmentReference = (String[]) assessmentIterator.next();
Element element=doc.createElement("Assessment");
element.setAttribute("name",thisAssessmentReference[0]);
element.setAttribute("url",serverUrlPrefix + thisAssessmentReference[1]);
element.setAttribute("size", "0");
sortedItems.add(element);
}
for (Element item: sortedItems) {
assessments.appendChild(item);
}
}
private void getOtherEntitiesOnly(String dir, Node root, Document doc, String type, ConnectorHelper ch) {
List myTests = null;
String siteId = null;
String user = sessionManager.getCurrentSessionUserId();
String[] f = dir.split("/");
siteId = f[2];
SortedSet<Element> sortedItems = new TreeSet<Element>(new SortElementsForDisplay());
Element otherEntities=doc.createElement("OtherEntities");
root.appendChild(otherEntities);
//Discover other entities available that this class doesn't already know about.
//Get registered provider prefixes
Set<String> providers = entityBroker.getRegisteredPrefixes();
//Read the additional hidden providers, provide backward compatibily with that old property
String[] txhiddenProviders = serverConfigurationService.getStrings("textarea.hiddenProviders");
String[] ebhiddenProviders = serverConfigurationService.getStrings("entity-browser.hiddenProviders");
//Combine txhiddenProviders, ebhiddenProviders and hiddenProviders
if (txhiddenProviders != null)
Collections.addAll(hiddenProviders,txhiddenProviders);
if (ebhiddenProviders != null)
Collections.addAll(hiddenProviders,ebhiddenProviders);
for (String provider : providers) {
// Check if this provider is hidden or not
boolean skip = false;
for (int i = 0; i < hiddenProviders.size(); i++) {
if (provider.equals(hiddenProviders.get(i)))
skip = true;
}
if (!skip) {
//Find entities in the provider
List<String> entities =
entityBroker.findEntityRefs(new String[] { provider },
new String[] { "context", "userId" }, new String[] { siteId, user }, true);
if (entities != null && entities.size() > 0) {
Element entityProvider=doc.createElement("EntityProvider");
//Get the title from the local properties file
String title = resourceLoader.getString("entitybrowser." + provider);
if (title == null) {
title = provider;
}
entityProvider.setAttribute("name", title);
entityProvider.setAttribute("provider", provider);
otherEntities.appendChild(entityProvider);
//Does this need the children recursion of the ListProducer?
for (String entity: entities) {
Element entityItem = appendEntity(entity,doc);
//This could go multiple levels but the original EBrowser only did 1 level
List<String> childEntities = findChildren(entity, user);
for (String childEntity: childEntities) {
Element entityChild = appendEntity(childEntity,doc);
entityItem.appendChild(entityChild);
}
entityProvider.appendChild(entityItem);
}
}
}
}
}
private Element appendEntity(String entity, Document doc) {
Element element=doc.createElement("EntityItem");
String title = entityBroker.getPropertyValue(entity, "title");
element.setAttribute("url", entityBroker.getEntityURL(entity));
element.setAttribute("name",title);
element.setAttribute("size","0");
return element;
}
/**
* Find the next level of decendent Entities for a given reference and user
*
* @param reference
* @param user
* @return List of Entity References
*/
private List<String> findChildren(String reference, String user) {
return entityBroker
.findEntityRefs(new String[] {entityBroker.getPropertyValue(reference, "child_provider")},
new String[] {"parentReference", "userId"},
new String[] {reference, user},
true);
}
private void getForumsAndThreads(String dir, Node root, Document doc, String type, ConnectorHelper ch) {
String siteId = null;
String[] f = dir.split("/");
siteId = f[2];
Element msgForums=doc.createElement("MsgForums");
root.appendChild(msgForums);
List theseMsgForums = ch.getForumTopicReferences(siteId);
if(theseMsgForums==null){
return;
}
SortedSet<Element> sortedForums = new TreeSet<Element>(new SortElementsForDisplay());
Iterator msgForumsIterator = theseMsgForums.iterator();
while(msgForumsIterator.hasNext()){
DecoratedForumInfo thisForumBean = (DecoratedForumInfo) ((EntityData) msgForumsIterator.next()).getData();
Element forumElement = doc.createElement("mForum");
forumElement.setAttribute("url", serverUrlPrefix + MFORUM_FORUM_PREFIX+String.valueOf(thisForumBean.getForumId()));
forumElement.setAttribute("name",thisForumBean.getForumTitle());
SortedSet<Element> sortedTopics = new TreeSet<Element>(new SortElementsForDisplay());
Iterator<DecoratedTopicInfo> topicIterator = thisForumBean.getTopics().iterator();
while(topicIterator.hasNext()){
DecoratedTopicInfo thisTopicBean = topicIterator.next();
Element topicElement = doc.createElement("mTopic");
topicElement.setAttribute("url", serverUrlPrefix + MFORUM_TOPIC_PREFIX+String.valueOf(thisTopicBean.getTopicId()));
topicElement.setAttribute("name", thisTopicBean.getTopicTitle());
// SortedSet<Element> sortedMessages = new TreeSet<Element>(new SortElementsForDisplay());
//
// Iterator thisMessageIterator = thisTopicBean.getMessages().iterator();
// while(thisMessageIterator.hasNext()){
// MessageBean thisMessageBean = (MessageBean) thisMessageIterator.next();
// Element messageElement = doc.createElement("mMessage");
// messageElement.setAttribute("url", serverUrlPrefix + MFORUM_MESSAGE_PREFIX+String.valueOf(thisMessageBean.getMessageId()));
// messageElement.setAttribute("name", thisMessageBean.getMessageLabel());
// sortedMessages.add(messageElement);
// }
//
// for (Element item: sortedMessages) {
// topicElement.appendChild(item);
// }
sortedTopics.add(topicElement);
}
for (Element item: sortedTopics) {
forumElement.appendChild(item);
}
sortedForums.add(forumElement);
}
for (Element item: sortedForums) {
msgForums.appendChild(item);
}
}
private Node createCommonXml(Document doc,String commandStr, String type, String currentPath, String currentUrl ) {
Element root = doc.createElement("Connector");
doc.appendChild(root);
root.setAttribute("command", commandStr);
root.setAttribute("resourceType", type);
Element element = doc.createElement("CurrentFolder");
element.setAttribute("path", currentPath);
element.setAttribute("url", currentUrl);
root.appendChild(element);
return root;
}
private String getAltReferenceRoot (String id) {
String altRoot = null;
try {
altRoot = StringUtil.trimToNull(contentHostingService.getProperties(id)
.getProperty(ContentHostingService.PROP_ALTERNATE_REFERENCE));
}
catch (Exception e) {
// do nothing, we either didn't have permission or the id is bogus
}
if (altRoot != null && !"/".equals(altRoot) && !"".equals(altRoot)) {
if (!altRoot.startsWith(Entity.SEPARATOR))
altRoot = Entity.SEPARATOR + altRoot;
if (altRoot.endsWith(Entity.SEPARATOR))
altRoot = altRoot.substring(0, altRoot.length() - Entity.SEPARATOR.length());
return altRoot;
}
else
return null;
}
private ContentResource bypassAddAttachment(HttpServletRequest request, String fileName, String mimeType, byte[] bytes, InputStream requestStream, ResourceProperties props) throws Exception {
try {
securityService.pushAdvisor(contentNewAdvisor);
String path = request.getPathInfo();
String resourceId = Validator.escapeResourceName(fileName);
String siteId = "";
if(path.contains("/user/")){
siteId = siteService.getSite("~" + path.replaceAll("\\/user\\/(.*)\\/", "$1")).getId();
} else {
siteId = siteService.getSite(path.replaceAll("\\/group\\/(.*)\\/", "$1")).getId();
}
String toolName = "fckeditor";
if (bytes != null) {
return contentHostingService.addAttachmentResource(resourceId, siteId, toolName, mimeType, new ByteArrayInputStream(bytes), props);
}
else if (requestStream != null) {
return contentHostingService.addAttachmentResource(resourceId, siteId, toolName, mimeType, requestStream, props);
}
} catch (Exception ex) {
throw ex;
} finally {
securityService.popAdvisor(contentNewAdvisor);
}
return null;
}
}
| textarea/FCKeditor/connector/src/java/org/sakaiproject/connector/fck/FCKConnectorServlet.java | /**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2006, 2007, 2008, 2009 The Sakai Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ECL-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
package org.sakaiproject.connector.fck;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.codec.binary.Base64;
import org.sakaiproject.authz.api.SecurityAdvisor;
import org.sakaiproject.authz.api.SecurityService;
import org.sakaiproject.component.cover.ComponentManager;
import org.sakaiproject.component.api.ServerConfigurationService;
import org.sakaiproject.content.api.ContentCollection;
import org.sakaiproject.content.api.ContentCollectionEdit;
import org.sakaiproject.content.api.ContentHostingService;
import org.sakaiproject.content.api.ContentResource;
import org.sakaiproject.entity.api.Entity;
import org.sakaiproject.entity.api.ResourceProperties;
import org.sakaiproject.entity.api.ResourcePropertiesEdit;
import org.sakaiproject.entitybroker.EntityBroker;
import org.sakaiproject.entitybroker.entityprovider.extension.EntityData;
import org.sakaiproject.event.api.NotificationService;
import org.sakaiproject.exception.IdUsedException;
import org.sakaiproject.exception.PermissionException;
import org.sakaiproject.site.api.SiteService;
import org.sakaiproject.tool.api.SessionManager;
import org.sakaiproject.util.ResourceLoader;
import org.sakaiproject.util.StringUtil;
import org.sakaiproject.util.Validator;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.sakaiproject.api.app.messageforums.entity.DecoratedForumInfo;
import org.sakaiproject.api.app.messageforums.entity.DecoratedTopicInfo;
/**
* Conenctor Servlet to upload and browse files to a Sakai worksite for the FCK editor.<br>
*
* This servlet accepts 4 commands used to retrieve and create files and folders from a worksite resource.
* The allowed commands are:
* <ul>
* <li>GetFolders: Retrive the list of directory under the current folder
* <li>GetFoldersAndFiles: Retrive the list of files and directory under the current folder
* <li>CreateFolder: Create a new directory under the current folder
* <li>FileUpload: Send a new file to the server (must be sent with a POST)
* </ul>
*
* The current user must have a valid sakai session with permissions to access the realm associated
* with the resource.
*
* @author Joshua Ryan ([email protected]) merged servlets and Sakai-ified them
*
* This connector is loosely based on two servlets found on the FCK website http://www.fckeditor.net/
* written by Simone Chiaretta ([email protected])
*
*/
public class FCKConnectorServlet extends HttpServlet {
private static Log M_log = LogFactory.getLog(FCKConnectorServlet.class);
private static final long serialVersionUID = 1L;
private static final String MFORUM_FORUM_PREFIX = "/direct/forum/";
private static final String MFORUM_TOPIC_PREFIX = "/direct/forum_topic/";
private static final String MFORUM_MESSAGE_PREFIX = "/direct/forum_message/";
private static final String FCK_ADVISOR_BASE = "fck.security.advisor.";
private static final String CK_ADVISOR_BASE = "ck.security.advisor.";
private static final String FCK_EXTRA_COLLECTIONS_BASE = "fck.extra.collections.";
// private String[] hiddenProviders = {"forum_message", "forum_topic"};
//Default hidden providers
private List <String> hiddenProviders;
private String serverUrlPrefix = "";
private ContentHostingService contentHostingService = null;
private SecurityService securityService = null;
private SessionManager sessionManager = null;
private NotificationService notificationService = null;
private SiteService siteService = null;
private SecurityAdvisor contentNewAdvisor = null;
private EntityBroker entityBroker;
private ServerConfigurationService serverConfigurationService = null;
private ResourceLoader resourceLoader = null;
/**
* Injects dependencies using the ComponentManager cover.
*
* @param beanName The name of the bean to get.
* @return the bean
*/
private Object inject(String beanName) {
Object bean = null;
bean = ComponentManager.get(beanName);
if (bean == null) {
throw new IllegalStateException("FAILURE to inject dependency during initialization of the FCKConnectorServlet");
}
return bean;
}
/**
* Ensures all necessary dependencies are loaded.
*/
private void initialize() {
if (contentHostingService == null) {
contentHostingService = (ContentHostingService) inject("org.sakaiproject.content.api.ContentHostingService");
}
if (securityService == null) {
securityService = (SecurityService) inject("org.sakaiproject.authz.api.SecurityService");
}
if (sessionManager == null) {
sessionManager = (SessionManager) inject("org.sakaiproject.tool.api.SessionManager");
}
if (notificationService == null) {
notificationService = (NotificationService) inject("org.sakaiproject.event.api.NotificationService");
}
if (siteService == null) {
siteService = (SiteService) inject("org.sakaiproject.site.api.SiteService");
if (entityBroker == null) {
entityBroker = (EntityBroker) inject("org.sakaiproject.entitybroker.EntityBroker");
}
if (serverConfigurationService == null) {
serverConfigurationService = (ServerConfigurationService) inject("org.sakaiproject.component.api.ServerConfigurationService");
}
//Default providers to exclude, add addition with the property textarea.hiddenProviders if needed
// hiddenProviders = Array.asList("");
hiddenProviders = Arrays.asList("assignment","sam_pub","forum","forum_topic","topic");
}
if (resourceLoader == null) {
resourceLoader = new ResourceLoader("org.sakaiproject.connector.fck.Messages");
}
if (contentNewAdvisor == null) {
contentNewAdvisor = new SecurityAdvisor(){
public SecurityAdvice isAllowed(String userId, String function, String reference){
try {
securityService.popAdvisor();
return securityService.unlock(userId, "content.new".equals(function)?"content.read":function, reference)?
SecurityAdvice.ALLOWED:SecurityAdvice.NOT_ALLOWED;
} catch (Exception ex) {
return SecurityAdvice.NOT_ALLOWED;
} finally {
securityService.pushAdvisor(this);
}
}
};
}
}
public void init() throws ServletException {
super.init();
initialize();
}
/**
* pops a special private advisor when necessary
* @param thisDir Directory where this is referencing
* @param collectionBase base of the collection
*/
private void popPrivateAdvisor(String thisDir, String collectionBase) {
if (thisDir.startsWith("/private/")) {
SecurityAdvisor advisor = (SecurityAdvisor) sessionManager.getCurrentSession().getAttribute(FCK_ADVISOR_BASE + collectionBase);
if (advisor != null) {
securityService.popAdvisor(advisor);
}
advisor = (SecurityAdvisor) sessionManager.getCurrentSession().getAttribute(CK_ADVISOR_BASE + collectionBase);
if (advisor != null) {
securityService.popAdvisor(advisor);
}
}
}
/**
* pushes a special private advisor when necessary
* @param thisDir Directory where this is referencing
* @param collectionBase base of the collection
*/
private void pushPrivateAdvisor(String thisDir, String collectionBase) {
if (thisDir.startsWith("/private/")) {
SecurityAdvisor advisor = (SecurityAdvisor) sessionManager.getCurrentSession().getAttribute(FCK_ADVISOR_BASE + collectionBase);
if (advisor != null) {
securityService.pushAdvisor(advisor);
}
advisor = (SecurityAdvisor) sessionManager.getCurrentSession().getAttribute(CK_ADVISOR_BASE + collectionBase);
if (advisor != null) {
securityService.pushAdvisor(advisor);
}
}
}
/**
* Manage the Get requests (GetFolders, GetFoldersAndFiles, CreateFolder).<br>
*
* The servlet accepts commands sent in the following format:<br>
* connector?Command=CommandName&Type=ResourceType&CurrentFolder=FolderPath<br><br>
* It executes the command and then return the results to the client in XML format.
*
* Valid values for Type are: Image, File, Flash and Link
*
*/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
initialize();
response.setContentType("text/xml; charset=UTF-8");
response.setHeader("Cache-Control","no-cache");
PrintWriter out = null;
String commandStr = request.getParameter("Command");
String type = request.getParameter("Type");
String currentFolder = request.getParameter("CurrentFolder");
serverUrlPrefix = serverConfigurationService.getServerUrl();
String collectionBase = request.getPathInfo();
Document document = null;
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.newDocument();
}
catch (ParserConfigurationException pce) {
pce.printStackTrace();
}
Node root = createCommonXml(document, commandStr, type, currentFolder,
contentHostingService.getUrl(currentFolder));
//To support meletedocs, the call to getFolders has to be able to retrieve all folders that are part of melete private (which will be passed in) as
//well as ones that are not. This is why the advisor is being manipulated inside the getfolders method.
if ("GetFolders".equals(commandStr)) {
getFolders(currentFolder, root, document, collectionBase);
}
else if ("GetFoldersAndFiles".equals(commandStr)) {
getFolders(currentFolder, root, document, collectionBase);
//Might need this advisor for files
pushPrivateAdvisor(currentFolder,collectionBase);
getFiles(currentFolder, root, document, type);
popPrivateAdvisor(currentFolder,collectionBase);
}
else if ("GetFoldersFilesAssignsTestsTopics".equals(commandStr)) {
ConnectorHelper thisConnectorHelper = new ConnectorHelper();
thisConnectorHelper.init();
getFolders(currentFolder, root, document, collectionBase);
//Might need this advisor for files
pushPrivateAdvisor(currentFolder,collectionBase);
getFilesOnly(currentFolder, root, document, type);
popPrivateAdvisor(currentFolder,collectionBase);
getAssignmentsOnly(currentFolder, root, document, type, thisConnectorHelper);
getTestsOnly(currentFolder, root, document, type, thisConnectorHelper);
getOtherEntitiesOnly(currentFolder, root, document, type, thisConnectorHelper);
getForumsAndThreads(currentFolder, root, document, type, thisConnectorHelper);
}
else if ("GetResourcesAssignsTestsTopics".equals(commandStr)) {
ConnectorHelper thisConnectorHelper = new ConnectorHelper();
thisConnectorHelper.init();
pushPrivateAdvisor(currentFolder,collectionBase);
getResources(currentFolder, root, document, collectionBase, type);
popPrivateAdvisor(currentFolder,collectionBase);
getAssignmentsOnly(currentFolder, root, document, type, thisConnectorHelper);
getTestsOnly(currentFolder, root, document, type, thisConnectorHelper);
getOtherEntitiesOnly(currentFolder, root, document, type, thisConnectorHelper);
getForumsAndThreads(currentFolder, root, document, type, thisConnectorHelper);
}
else if ("GetResources".equals(commandStr)) {
pushPrivateAdvisor(currentFolder,collectionBase);
getResources(currentFolder, root, document, collectionBase, type);
popPrivateAdvisor(currentFolder,collectionBase);
}
else if ("CreateFolder".equals(commandStr)) {
String newFolderStr = request.getParameter("NewFolderName");
String status = "110";
pushPrivateAdvisor(currentFolder,collectionBase);
try {
ContentCollectionEdit edit = contentHostingService
.addCollection(currentFolder + Validator.escapeResourceName(newFolderStr) + Entity.SEPARATOR);
ResourcePropertiesEdit resourceProperties = edit.getPropertiesEdit();
resourceProperties.addProperty (ResourceProperties.PROP_DISPLAY_NAME, newFolderStr);
String altRoot = getAltReferenceRoot(currentFolder);
if (altRoot != null)
resourceProperties.addProperty (ContentHostingService.PROP_ALTERNATE_REFERENCE, altRoot);
contentHostingService.commitCollection(edit);
status="0";
}
catch (IdUsedException iue) {
status = "101";
}
catch(PermissionException pex) {
status = "103";
}
catch (Exception e) {
status = "102";
}
setCreateFolderResponse(status, root, document);
popPrivateAdvisor(currentFolder,collectionBase);
}
document.getDocumentElement().normalize();
try {
out = response.getWriter();
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(out);
transformer.transform(source, result);
}
catch (Exception ex) {
ex.printStackTrace();
}
finally {
if (out != null) {
out.close();
}
}
//Pop the advisor if we need to
popPrivateAdvisor(currentFolder,collectionBase);
}
/**
* Manage the Post requests (FileUpload).<br>
*
* The servlet accepts commands sent in the following format:<br>
* connector?Command=FileUpload&Type=ResourceType&CurrentFolder=FolderPath<br><br>
* It stores the file (renaming it in case a file with the same name exists) and then return an HTML file
* with a javascript command in it.
*
*/
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
initialize();
response.setContentType("text/html; charset=UTF-8");
response.setHeader("Cache-Control", "no-cache");
PrintWriter out = null;
String command = request.getParameter("Command");
String currentFolder = request.getParameter("CurrentFolder");
String collectionBase = request.getPathInfo();
pushPrivateAdvisor(currentFolder,collectionBase);
String fileName = "";
String errorMessage = "";
String status="0";
ContentResource attachment = null;
if (!"FileUpload".equals(command) && !"QuickUpload".equals(command) && !("QuickUploadEquation").equals(command) && !("QuickUploadAttachment").equals(command)) {
status = "203";
}
else {
DiskFileUpload upload = new DiskFileUpload();
String mime="";
InputStream requestStream = null;
byte [] bytes=null;
try {
//Special case for uploading fmath equations
if (("QuickUploadEquation").equals(command)) {
String image = request.getParameter("image");
String type = request.getParameter("type");
// size protection
if(image==null || image.length()>1000000) return;
bytes = Base64.decodeBase64(image);
fileName = "fmath-equation-"+request.getParameter("name");
if ("PNG".equals(type)) {
mime = "image/png";
if (fileName.indexOf(".") == -1) {
fileName+=".png";
}
}
else {
mime = "image/jpeg";
if (fileName.indexOf(".") == -1) {
fileName+=".jpg";
}
}
}
else {
//If this is a multipart request
if (ServletFileUpload.isMultipartContent(request)) {
List items = upload.parseRequest(request);
Map fields = new HashMap();
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
fields.put(item.getFieldName(), item.getString());
}
else {
fields.put(item.getFieldName(), item);
}
}
FileItem uplFile = (FileItem)fields.get("NewFile");
String filePath = uplFile.getName();
filePath = filePath.replace('\\','/');
String[] pathParts = filePath.split("/");
fileName = pathParts[pathParts.length-1];
mime = uplFile.getContentType();
requestStream = uplFile.getInputStream();
}
else {
requestStream = request.getInputStream();
mime = request.getHeader("Content-Type");
}
}
//If there's no filename, make a guid name with the mime extension?
if ("".equals (fileName)) {
fileName = UUID.randomUUID().toString();
}
String nameWithoutExt = fileName;
String ext = "";
if (fileName.lastIndexOf(".") > 0) {
nameWithoutExt = fileName.substring(0, fileName.lastIndexOf("."));
ext = fileName.substring(fileName.lastIndexOf("."));
}
int counter = 1;
boolean done = false;
while(!done) {
try {
ResourcePropertiesEdit resourceProperties = contentHostingService.newResourceProperties();
resourceProperties.addProperty (ResourceProperties.PROP_DISPLAY_NAME, fileName);
if ("QuickUploadEquation".equals(command) || "QuickUploadAttachment".equals(command)) {
attachment = bypassAddAttachment(request,fileName,mime,bytes,requestStream,resourceProperties);
} else {
String altRoot = getAltReferenceRoot(currentFolder);
if (altRoot != null)
resourceProperties.addProperty (ContentHostingService.PROP_ALTERNATE_REFERENCE, altRoot);
int noti = NotificationService.NOTI_NONE;
if (bytes != null) {
contentHostingService.addResource(currentFolder+fileName, mime, bytes, resourceProperties, noti);
}
else if (requestStream != null) {
contentHostingService.addResource(currentFolder+fileName, mime, requestStream, resourceProperties, noti);
}
else {
//Nothing to do
}
}
done = true;
}
catch (IdUsedException iue) {
//the name is already used, so we do a slight rename to prevent the colision
fileName = nameWithoutExt + "(" + counter + ")" + ext;
status = "201";
counter++;
}
catch (Exception ex) {
//this user can't write where they are trying to write.
done = true;
ex.printStackTrace();
status = "203";
}
}
}
catch (Exception ex) {
ex.printStackTrace();
status = "203";
}
}
try {
out = response.getWriter();
if ("QuickUploadEquation".equals(command) || "QuickUploadAttachment".equals(command)) {
out.println(attachment!=null?attachment.getUrl():"");
}
else {
out.println("<script type=\"text/javascript\">");
out.println("(function(){ var d = document.domain ; while ( true ) {");
out.println("try { var test = parent.document.domain ; break ; } catch( e ) {}");
out.println("d = d.replace( /.*?(?:\\.|$)/, '' ) ; if ( d.length == 0 ) break ;");
out.println("try { document.domain = d ; } catch (e) { break ; }}})() ;");
out.println("window.parent.OnUploadCompleted(" + status + ",'"
+ (attachment!=null?attachment.getUrl():"")
+ "','" + fileName + "','" + errorMessage + "');");
out.println("</script>");
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (out != null) {
out.close();
}
}
popPrivateAdvisor(currentFolder,collectionBase);
}
private void setCreateFolderResponse(String status, Node root, Document doc) {
Element element = doc.createElement("Error");
element.setAttribute("number", status);
root.appendChild(element);
}
private void getFolders(String dir, Node root, Document doc, String collectionBase) {
Element folders = doc.createElement("Folders");
root.appendChild(folders);
ContentCollection collection = null;
Map<String, String> map = null;
List <Iterator> foldersIterator = new ArrayList <Iterator> ();
try {
//hides the real root level stuff and just shows the users the
//the root folders of all the top collections they actually have access to.
int dirlength = dir.split("/").length;
if (dirlength == 2 || dir.startsWith("/private/")) {
List<String> collections = new ArrayList<String>();
map = contentHostingService.getCollectionMap();
for (String key : map.keySet()) {
if (!contentHostingService.isInDropbox((String)key)) {
collections.add(key);
}
}
List extras = (List) sessionManager.getCurrentSession()
.getAttribute(FCK_EXTRA_COLLECTIONS_BASE + collectionBase);
if (extras != null) {
collections.addAll(extras);
}
foldersIterator.add(collections.iterator());
}
if (dirlength > 2) {
pushPrivateAdvisor(dir,collectionBase);
collection = contentHostingService.getCollection(dir);
if (collection != null && collection.getMembers() != null) {
foldersIterator.add(collection.getMembers().iterator());
}
popPrivateAdvisor(dir,collectionBase);
}
}
catch (Exception e) {
e.printStackTrace();
//not a valid collection? file list will be empty and so will the doc
}
for (Iterator folderIterator : foldersIterator ) {
if (folderIterator != null) {
String current = null;
// create a SortedSet using the elements that are going to be added to the XML doc
SortedSet<Element> sortedFolders = new TreeSet<Element>(new SortElementsForDisplay());
while (folderIterator.hasNext()) {
try {
current = (String) folderIterator.next();
pushPrivateAdvisor(current,collectionBase);
ContentCollection myCollection = contentHostingService.getCollection(current);
Element element=doc.createElement("Folder");
element.setAttribute("url", current);
String collectionName = myCollection.getProperties().getProperty(myCollection.getProperties().getNamePropDisplayName());
if (current.contains("/meleteDocs/")) {
if (resourceLoader != null)
collectionName = resourceLoader.getString("melete_collectionname");
else
collectionName = "Melete Files";
}
element.setAttribute("name",collectionName);
// by adding the folders to this collection, they will be sorted for display
sortedFolders.add(element);
popPrivateAdvisor(current,collectionBase);
}
catch (Exception e) {
//do nothing, we either don't have access to the collction or it's a resource
M_log.debug("No access to display collection" + e.getMessage());
}
}
// now append the folderse to the parent document in sorted order
for (Element folder: sortedFolders) {
folders.appendChild(folder);
}
}
}
}
private void getResources(String dir, Node root, Document doc, String collectionBase, String type) {
Element folders = doc.createElement("Folders");
root.appendChild(folders);
ContentCollection collection = null;
Map<String, String> map = null;
Iterator foldersIterator = null;
try {
//hides the real root level stuff and just shows the users the
//the root folders of all the top collections they actually have access to.
if (dir.split("/").length == 2) {
List<String> collections = new ArrayList<String>();
map = contentHostingService.getCollectionMap();
if (map != null && map.keySet() != null) {
collections.addAll(map.keySet());
}
List extras = (List) sessionManager.getCurrentSession()
.getAttribute(FCK_EXTRA_COLLECTIONS_BASE + collectionBase);
if (extras != null) {
collections.addAll(extras);
}
foldersIterator = collections.iterator();
}
else if (dir.split("/").length > 2) {
collection = contentHostingService.getCollection(dir);
if (collection != null && collection.getMembers() != null) {
foldersIterator = collection.getMembers().iterator();
}
}
}
catch (Exception e) {
e.printStackTrace();
//not a valid collection? file list will be empty and so will the doc
}
if (foldersIterator != null) {
String current = null;
// create a SortedSet using the elements that are going to be added to the XML doc
SortedSet<Element> sortedFolders = new TreeSet<Element>(new SortElementsForDisplay());
while (foldersIterator.hasNext()) {
try {
current = (String) foldersIterator.next();
ContentCollection myCollection = contentHostingService.getCollection(current);
Element element=doc.createElement("Folder");
element.setAttribute("path", current);
element.setAttribute("url", contentHostingService.getUrl(current));
element.setAttribute("name", myCollection.getProperties().getProperty(
myCollection.getProperties().getNamePropDisplayName()));
// SAK-27756 Added children count to decide whether to show expand button as we removed nested iteration of files
element.setAttribute("childrenCount", myCollection.getMemberCount()+"");
// by adding the folders to this collection, they will be sorted for display
sortedFolders.add(element);
}
catch (Exception e) {
//do nothing, we either don't have access to the collction or it's a resource
}
}
// now append the folderse to the parent document in sorted order
for (Element folder: sortedFolders) {
Node addedFolder = folders.appendChild(folder);
}
getFilesOnly(dir, root, doc, type);
}
}
private void getFiles(String dir, Node root, Document doc, String type) {
Element files=doc.createElement("Files");
root.appendChild(files);
ContentCollection collection = null;
try {
collection = contentHostingService.getCollection(dir);
}
catch (Exception e) {
//do nothing, file will be empty and so will doc
}
if (collection != null) {
Iterator iterator = collection.getMemberResources().iterator();
// create a SortedSet using the elements that are going to be added to the XML doc
SortedSet<Element> sortedFiles = new TreeSet<Element>(new SortElementsForDisplay());
while (iterator.hasNext ()) {
try {
ContentResource current = (ContentResource)iterator.next();
String ext = current.getProperties().getProperty(
current.getProperties().getNamePropContentType());
if ( ("File".equals(type) && (ext != null) ) ||
("Flash".equals(type) && ext.equalsIgnoreCase("application/x-shockwave-flash") ) ||
("Image".equals(type) && ext.startsWith("image") ) ||
("Media".equals(type) && (ext.startsWith("video") || ext.startsWith("audio") || ext.equalsIgnoreCase("application/x-shockwave-flash")) ) ||
"Link".equals(type)) {
String id = current.getId();
Element element=doc.createElement("File");
// displaying the id instead of the display name because the url used
// for linking in the FCK editor uses what is returned...
element.setAttribute("name", current.getProperties().getProperty(
current.getProperties().getNamePropDisplayName()));
element.setAttribute("url", current.getUrl());
if (current.getProperties().getProperty(
current.getProperties().getNamePropContentLength()) != null) {
element.setAttribute("size", "" + current.getProperties()
.getPropertyFormatted(current.getProperties()
.getNamePropContentLength()));
}
else {
element.setAttribute("size", "0");
}
// by adding the files to this collection, they will be sorted for display
sortedFiles.add(element);
}
}
catch (ClassCastException e) {
//it's a colleciton not an item
}
catch (Exception e) {
//do nothing, we don't have access to the item
}
}
// now append the files to the parent document in sorted order
for (Element file: sortedFiles) {
files.appendChild(file);
}
}
}
private void getFilesOnly(String dir, Node root, Document doc, String type) {
Element files=doc.createElement("Files");
root.appendChild(files);
ContentCollection collection = null;
List myAssignments = null;
List myTests = null;
List myTopics = null;
String siteId = null;
String[] f = dir.split("/");
siteId = f[2];
try {
collection = contentHostingService.getCollection(dir);
}
catch (Exception e) {
//do nothing, file will be empty and so will doc
}
if (collection != null) {
Iterator iterator = collection.getMemberResources().iterator();
while (iterator.hasNext ()) {
try {
ContentResource current = (ContentResource)iterator.next();
String ext = current.getProperties().getProperty(
current.getProperties().getNamePropContentType());
if ( ("File".equals(type) && (ext != null) ) ||
("Flash".equals(type) && ext.equalsIgnoreCase("application/x-shockwave-flash") ) ||
("Image".equals(type) && ext.startsWith("image") ) ||
"Link".equals(type)) {
String id = current.getId();
Element element=doc.createElement("File");
// displaying the id instead of the display name because the url used
// for linking in the FCK editor uses what is returned...
element.setAttribute("name", current.getProperties().getProperty(
current.getProperties().getNamePropDisplayName()));
element.setAttribute("url", current.getUrl());
if (current.getProperties().getProperty(
current.getProperties().getNamePropContentLength()) != null) {
element.setAttribute("size", "" + current.getProperties()
.getPropertyFormatted(current.getProperties()
.getNamePropContentLength()));
}
else {
element.setAttribute("size", "0");
}
files.appendChild(element);
}
}
catch (ClassCastException e) {
//it's a colleciton not an item
}
catch (Exception e) {
//do nothing, we don't have access to the item
}
}
}
}
private void getAssignmentsOnly(String dir, Node root, Document doc, String type, ConnectorHelper ch) {
List myAssignments = null;
String siteId = null;
String[] f = dir.split("/");
siteId = f[2];
SortedSet<Element> sortedItems = new TreeSet<Element>(new SortElementsForDisplay());
Element assignments=doc.createElement("Assignments");
root.appendChild(assignments);
myAssignments = ch.getSiteAssignments(siteId);
Iterator assignmentsIterator = myAssignments.iterator();
while(assignmentsIterator.hasNext()){
String[] thisAssignmentReference = (String[]) assignmentsIterator.next();
Element element=doc.createElement("Assignment");
element.setAttribute("name",thisAssignmentReference[0]);
element.setAttribute("url",serverUrlPrefix + thisAssignmentReference[1]);
element.setAttribute("size", "0");
sortedItems.add(element);
}
for (Element item: sortedItems) {
assignments.appendChild(item);
}
}
private void getTestsOnly(String dir, Node root, Document doc, String type, ConnectorHelper ch) {
List myTests = null;
String siteId = null;
String[] f = dir.split("/");
siteId = f[2];
SortedSet<Element> sortedItems = new TreeSet<Element>(new SortElementsForDisplay());
Element assessments=doc.createElement("Assessments");
root.appendChild(assessments);
myTests = ch.getPublishedAssements(siteId);
Iterator assessmentIterator = myTests.iterator();
while(assessmentIterator.hasNext()){
String[] thisAssessmentReference = (String[]) assessmentIterator.next();
Element element=doc.createElement("Assessment");
element.setAttribute("name",thisAssessmentReference[0]);
element.setAttribute("url",serverUrlPrefix + thisAssessmentReference[1]);
element.setAttribute("size", "0");
sortedItems.add(element);
}
for (Element item: sortedItems) {
assessments.appendChild(item);
}
}
private void getOtherEntitiesOnly(String dir, Node root, Document doc, String type, ConnectorHelper ch) {
List myTests = null;
String siteId = null;
String user = sessionManager.getCurrentSessionUserId();
String[] f = dir.split("/");
siteId = f[2];
SortedSet<Element> sortedItems = new TreeSet<Element>(new SortElementsForDisplay());
Element otherEntities=doc.createElement("OtherEntities");
root.appendChild(otherEntities);
//Discover other entities available that this class doesn't already know about.
//Get registered provider prefixes
Set<String> providers = entityBroker.getRegisteredPrefixes();
//Read the additional hidden providers, provide backward compatibily with that old property
String[] txhiddenProviders = serverConfigurationService.getStrings("textarea.hiddenProviders");
String[] ebhiddenProviders = serverConfigurationService.getStrings("entity-browser.hiddenProviders");
//Combine txhiddenProviders, ebhiddenProviders and hiddenProviders
if (txhiddenProviders != null)
Collections.addAll(hiddenProviders,txhiddenProviders);
if (ebhiddenProviders != null)
Collections.addAll(hiddenProviders,ebhiddenProviders);
for (String provider : providers) {
// Check if this provider is hidden or not
boolean skip = false;
for (int i = 0; i < hiddenProviders.size(); i++) {
if (provider.equals(hiddenProviders.get(i)))
skip = true;
}
if (!skip) {
//Find entities in the provider
List<String> entities =
entityBroker.findEntityRefs(new String[] { provider },
new String[] { "context", "userId" }, new String[] { siteId, user }, true);
if (entities != null && entities.size() > 0) {
Element entityProvider=doc.createElement("EntityProvider");
//Get the title from the local properties file
String title = resourceLoader.getString("entitybrowser." + provider);
if (title == null) {
title = provider;
}
entityProvider.setAttribute("name", title);
entityProvider.setAttribute("provider", provider);
otherEntities.appendChild(entityProvider);
//Does this need the children recursion of the ListProducer?
for (String entity: entities) {
M_log.info(provider);
title = entityBroker.getPropertyValue(entity, "title");
Element element=doc.createElement("EntityItem");
element.setAttribute("url", entityBroker.getEntityURL(entity));
element.setAttribute("name",title);
element.setAttribute("size","0");
entityProvider.appendChild(element);
}
}
}
}
/*
myTests = ch.getPublishedAssements(siteId);
Iterator assessmentIterator = myTests.iterator();
while(assessmentIterator.hasNext()){
String[] thisAssessmentReference = (String[]) assessmentIterator.next();
Element element=doc.createElement("Assessment");
element.setAttribute("name",thisAssessmentReference[0]);
element.setAttribute("url",serverUrlPrefix + thisAssessmentReference[1]);
element.setAttribute("size", "0");
sortedItems.add(element);
}
for (Element item: sortedItems) {
assessments.appendChild(item);
}
*/
}
/**
* Find the next level of decendent Entities for a given reference and user
*
* @param reference
* @param user
* @return List of Entity References
*/
private List<String> findChildren(String reference, String user) {
return entityBroker
.findEntityRefs(new String[] {entityBroker.getPropertyValue(reference, "child_provider")},
new String[] {"parentReference", "userId"},
new String[] {reference, user},
true);
}
private void getForumsAndThreads(String dir, Node root, Document doc, String type, ConnectorHelper ch) {
String siteId = null;
String[] f = dir.split("/");
siteId = f[2];
Element msgForums=doc.createElement("MsgForums");
root.appendChild(msgForums);
List theseMsgForums = ch.getForumTopicReferences(siteId);
if(theseMsgForums==null){
return;
}
SortedSet<Element> sortedForums = new TreeSet<Element>(new SortElementsForDisplay());
Iterator msgForumsIterator = theseMsgForums.iterator();
while(msgForumsIterator.hasNext()){
DecoratedForumInfo thisForumBean = (DecoratedForumInfo) ((EntityData) msgForumsIterator.next()).getData();
Element forumElement = doc.createElement("mForum");
forumElement.setAttribute("url", serverUrlPrefix + MFORUM_FORUM_PREFIX+String.valueOf(thisForumBean.getForumId()));
forumElement.setAttribute("name",thisForumBean.getForumTitle());
SortedSet<Element> sortedTopics = new TreeSet<Element>(new SortElementsForDisplay());
Iterator<DecoratedTopicInfo> topicIterator = thisForumBean.getTopics().iterator();
while(topicIterator.hasNext()){
DecoratedTopicInfo thisTopicBean = topicIterator.next();
Element topicElement = doc.createElement("mTopic");
topicElement.setAttribute("url", serverUrlPrefix + MFORUM_TOPIC_PREFIX+String.valueOf(thisTopicBean.getTopicId()));
topicElement.setAttribute("name", thisTopicBean.getTopicTitle());
// SortedSet<Element> sortedMessages = new TreeSet<Element>(new SortElementsForDisplay());
//
// Iterator thisMessageIterator = thisTopicBean.getMessages().iterator();
// while(thisMessageIterator.hasNext()){
// MessageBean thisMessageBean = (MessageBean) thisMessageIterator.next();
// Element messageElement = doc.createElement("mMessage");
// messageElement.setAttribute("url", serverUrlPrefix + MFORUM_MESSAGE_PREFIX+String.valueOf(thisMessageBean.getMessageId()));
// messageElement.setAttribute("name", thisMessageBean.getMessageLabel());
// sortedMessages.add(messageElement);
// }
//
// for (Element item: sortedMessages) {
// topicElement.appendChild(item);
// }
sortedTopics.add(topicElement);
}
for (Element item: sortedTopics) {
forumElement.appendChild(item);
}
sortedForums.add(forumElement);
}
for (Element item: sortedForums) {
msgForums.appendChild(item);
}
}
private Node createCommonXml(Document doc,String commandStr, String type, String currentPath, String currentUrl ) {
Element root = doc.createElement("Connector");
doc.appendChild(root);
root.setAttribute("command", commandStr);
root.setAttribute("resourceType", type);
Element element = doc.createElement("CurrentFolder");
element.setAttribute("path", currentPath);
element.setAttribute("url", currentUrl);
root.appendChild(element);
return root;
}
private String getAltReferenceRoot (String id) {
String altRoot = null;
try {
altRoot = StringUtil.trimToNull(contentHostingService.getProperties(id)
.getProperty(ContentHostingService.PROP_ALTERNATE_REFERENCE));
}
catch (Exception e) {
// do nothing, we either didn't have permission or the id is bogus
}
if (altRoot != null && !"/".equals(altRoot) && !"".equals(altRoot)) {
if (!altRoot.startsWith(Entity.SEPARATOR))
altRoot = Entity.SEPARATOR + altRoot;
if (altRoot.endsWith(Entity.SEPARATOR))
altRoot = altRoot.substring(0, altRoot.length() - Entity.SEPARATOR.length());
return altRoot;
}
else
return null;
}
private ContentResource bypassAddAttachment(HttpServletRequest request, String fileName, String mimeType, byte[] bytes, InputStream requestStream, ResourceProperties props) throws Exception {
try {
securityService.pushAdvisor(contentNewAdvisor);
String path = request.getPathInfo();
String resourceId = Validator.escapeResourceName(fileName);
String siteId = "";
if(path.contains("/user/")){
siteId = siteService.getSite("~" + path.replaceAll("\\/user\\/(.*)\\/", "$1")).getId();
} else {
siteId = siteService.getSite(path.replaceAll("\\/group\\/(.*)\\/", "$1")).getId();
}
String toolName = "fckeditor";
if (bytes != null) {
return contentHostingService.addAttachmentResource(resourceId, siteId, toolName, mimeType, new ByteArrayInputStream(bytes), props);
}
else if (requestStream != null) {
return contentHostingService.addAttachmentResource(resourceId, siteId, toolName, mimeType, requestStream, props);
}
} catch (Exception ex) {
throw ex;
} finally {
securityService.popAdvisor(contentNewAdvisor);
}
return null;
}
}
| SAK-23444 - iSyllabus discover should search for child entities
git-svn-id: 667c1c35c2fd077c53b6a62e18ca3c02239ace82@315072 66ffb92e-73f9-0310-93c1-f5514f145a0a
| textarea/FCKeditor/connector/src/java/org/sakaiproject/connector/fck/FCKConnectorServlet.java | SAK-23444 - iSyllabus discover should search for child entities | <ide><path>extarea/FCKeditor/connector/src/java/org/sakaiproject/connector/fck/FCKConnectorServlet.java
<ide> }
<ide>
<ide> //Default providers to exclude, add addition with the property textarea.hiddenProviders if needed
<del>// hiddenProviders = Array.asList("");
<add>// hiddenProviders = Arrays.asList("");
<ide> hiddenProviders = Arrays.asList("assignment","sam_pub","forum","forum_topic","topic");
<ide> }
<ide>
<ide> otherEntities.appendChild(entityProvider);
<ide> //Does this need the children recursion of the ListProducer?
<ide> for (String entity: entities) {
<del> M_log.info(provider);
<del> title = entityBroker.getPropertyValue(entity, "title");
<del> Element element=doc.createElement("EntityItem");
<del> element.setAttribute("url", entityBroker.getEntityURL(entity));
<del> element.setAttribute("name",title);
<del> element.setAttribute("size","0");
<del> entityProvider.appendChild(element);
<add> Element entityItem = appendEntity(entity,doc);
<add> //This could go multiple levels but the original EBrowser only did 1 level
<add> List<String> childEntities = findChildren(entity, user);
<add> for (String childEntity: childEntities) {
<add> Element entityChild = appendEntity(childEntity,doc);
<add> entityItem.appendChild(entityChild);
<add> }
<add> entityProvider.appendChild(entityItem);
<ide> }
<ide> }
<ide> }
<ide> }
<del>
<del> /*
<del> myTests = ch.getPublishedAssements(siteId);
<del> Iterator assessmentIterator = myTests.iterator();
<del> while(assessmentIterator.hasNext()){
<del> String[] thisAssessmentReference = (String[]) assessmentIterator.next();
<del> Element element=doc.createElement("Assessment");
<del> element.setAttribute("name",thisAssessmentReference[0]);
<del> element.setAttribute("url",serverUrlPrefix + thisAssessmentReference[1]);
<del> element.setAttribute("size", "0");
<del> sortedItems.add(element);
<del> }
<del>
<del> for (Element item: sortedItems) {
<del> assessments.appendChild(item);
<del> }
<del> */
<del>
<add> }
<add>
<add> private Element appendEntity(String entity, Document doc) {
<add> Element element=doc.createElement("EntityItem");
<add> String title = entityBroker.getPropertyValue(entity, "title");
<add> element.setAttribute("url", entityBroker.getEntityURL(entity));
<add> element.setAttribute("name",title);
<add> element.setAttribute("size","0");
<add> return element;
<ide> }
<ide>
<ide> /** |
|
Java | bsd-3-clause | b23289c5dacc51841524f0e759777e548b93ad97 | 0 | jvican/scala,scala/scala,slothspot/scala,jvican/scala,felixmulder/scala,slothspot/scala,shimib/scala,lrytz/scala,felixmulder/scala,felixmulder/scala,lrytz/scala,martijnhoekstra/scala,lrytz/scala,lrytz/scala,felixmulder/scala,slothspot/scala,scala/scala,scala/scala,jvican/scala,martijnhoekstra/scala,slothspot/scala,felixmulder/scala,martijnhoekstra/scala,slothspot/scala,slothspot/scala,scala/scala,shimib/scala,felixmulder/scala,shimib/scala,martijnhoekstra/scala,lrytz/scala,scala/scala,shimib/scala,slothspot/scala,felixmulder/scala,jvican/scala,jvican/scala,scala/scala,jvican/scala,shimib/scala,lrytz/scala,jvican/scala,shimib/scala,martijnhoekstra/scala,martijnhoekstra/scala | /* ____ ____ ____ ____ ______ *\
** / __// __ \/ __// __ \/ ____/ SOcos COmpiles Scala **
** __\_ \/ /_/ / /__/ /_/ /\_ \ (c) 2002, LAMP/EPFL **
** /_____/\____/\___/\____/____/ **
** **
** $Id$
\* */
package scalac.ast.parser;
import scalac.*;
import scalac.util.Name;
import scalac.util.Position;
/** A scanner for the programming language Scala.
*
* @author Matthias Zenger, Martin Odersky
* @version 1.0
*/
public class Scanner extends TokenData {
/** layout & character constants
*/
public int tabinc = 8;
public final static byte LF = 0xA;
protected final static byte FF = 0xC;
protected final static byte CR = 0xD;
protected final static byte SU = Sourcefile.SU;
/** the names of all tokens
*/
public Name[] tokenName = new Name[128];
public int numToken = 0;
/** keyword array; maps from name indices to tokens
*/
protected byte[] key;
protected int maxKey = 0;
/** we need one token lookahead
*/
protected TokenData next = new TokenData();
protected TokenData prev = new TokenData();
/** the first character position after the previous token
*/
public int lastpos = 0;
/** the last error position
*/
public int errpos = -1;
/** the input buffer:
*/
protected byte[] buf;
protected int bp;
/** the current character
*/
protected byte ch;
/** the line and column position of the current character
*/
public int cline;
public int ccol;
/** the current sourcefile
*/
public Sourcefile currentSource;
/** a buffer for character and string literals
*/
protected byte[] lit = new byte[64];
protected int litlen;
/** the compilation unit
*/
public Unit unit;
/** Construct a scanner from a file input stream.
*/
public Scanner(Unit unit) {
this.unit = unit;
buf = (currentSource = unit.source).getBuffer();
cline = 1;
bp = -1;
ccol = 0;
nextch();
token = EMPTY;
init();
nextToken();
}
/** only used to determine keywords. used in dtd2scala tool */
public Scanner() {
initKeywords();
}
private void nextch() {
ch = buf[++bp]; ccol++;
}
/** read next token and return last position
*/
public int skipToken() {
int p = pos;
nextToken();
return p;
}
public void nextToken() {
if (token == RBRACE) {
int prevpos = pos;
fetchToken();
switch (token) {
case ELSE: case EXTENDS: case WITH:
case YIELD: case DO:
case COMMA: case SEMI: case DOT:
case COLON: case EQUALS: case ARROW:
case LARROW: case SUBTYPE: case SUPERTYPE:
case HASH: case AS: case IS:
case RPAREN: case RBRACKET: case RBRACE:
break;
default:
if (token == EOF ||
((pos >>> Position.LINESHIFT) >
(prevpos >>> Position.LINESHIFT))) {
next.copyFrom(this);
this.token = SEMI;
this.pos = prevpos;
}
}
} else {
if (next.token == EMPTY) {
fetchToken();
} else {
copyFrom(next);
next.token = EMPTY;
}
if (token == CASE) {
prev.copyFrom(this);
fetchToken();
if (token == CLASS) {
token = CASECLASS;
} else if (token == OBJECT) {
token = CASEOBJECT;
} else {
next.copyFrom(this);
this.copyFrom(prev);
}
} else if (token == SEMI) {
prev.copyFrom(this);
fetchToken();
if (token != ELSE) {
next.copyFrom(this);
this.copyFrom(prev);
}
}
}
//System.out.println("<" + token2string(token) + ">");//DEBUG
}
/** read next token
*/
public void fetchToken() {
if (token == EOF) return;
lastpos = Position.encode(cline, ccol, currentSource.id);
int index = bp;
while(true) {
switch (ch) {
case ' ':
nextch();
break;
case '\t':
ccol = ((ccol - 1) / tabinc * tabinc) + tabinc;
nextch();
break;
case CR:
cline++;
ccol = 0;
nextch();
if (ch == LF) {
ccol = 0;
nextch();
}
break;
case LF:
case FF:
cline++;
ccol = 0;
nextch();
break;
default:
pos = Position.encode(cline, ccol, currentSource.id);
index = bp;
switch (ch) {
case 'A': case 'B': case 'C': case 'D': case 'E':
case 'F': case 'G': case 'H': case 'I': case 'J':
case 'K': case 'L': case 'M': case 'N': case 'O':
case 'P': case 'Q': case 'R': case 'S': case 'T':
case 'U': case 'V': case 'W': case 'X': case 'Y':
case 'Z': case '$':
case 'a': case 'b': case 'c': case 'd': case 'e':
case 'f': case 'g': case 'h': case 'i': case 'j':
case 'k': case 'l': case 'm': case 'n': case 'o':
case 'p': case 'q': case 'r': case 's': case 't':
case 'u': case 'v': case 'w': case 'x': case 'y':
case 'z':
nextch();
getIdentRest(index);
return;
case '~': case '!': case '@': case '#': case '%':
case '^': case '*': case '+': case '-': case '<':
case '>': case '?': case ':':
case '=': case '&': case '|':
nextch();
getOperatorRest(index);
return;
case '/':
nextch();
if (!skipComment()) {
getOperatorRest(index);
return;
}
break;
case '_':
nextch();
getIdentOrOperatorRest(index);
return;
case '0':
nextch();
if (ch == 'x' || ch == 'X') {
nextch();
getNumber(index + 2, 16);
} else
getNumber(index, 8);
return;
case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
getNumber(index, 10);
return;
case '\"':
nextch();
litlen = 0;
while (ch != '\"' && ch != CR && ch != LF && ch != SU)
getlitch();
if (ch == '\"') {
token = STRINGLIT;
name = Name.fromSource(lit, 0, litlen);
nextch();
}
else
syntaxError("unclosed character literal");
return;
case '\'':
nextch();
litlen = 0;
switch (ch) {
case 'A': case 'B': case 'C': case 'D': case 'E':
case 'F': case 'G': case 'H': case 'I': case 'J':
case 'K': case 'L': case 'M': case 'N': case 'O':
case 'P': case 'Q': case 'R': case 'S': case 'T':
case 'U': case 'V': case 'W': case 'X': case 'Y':
case 'Z': case '$':
case 'a': case 'b': case 'c': case 'd': case 'e':
case 'f': case 'g': case 'h': case 'i': case 'j':
case 'k': case 'l': case 'm': case 'n': case 'o':
case 'p': case 'q': case 'r': case 's': case 't':
case 'u': case 'v': case 'w': case 'x': case 'y':
case 'z':
index = bp;
putch(ch);
nextch();
if (ch != '\'') {
getIdentRest(index);
token = SYMBOLLIT;
return;
}
break;
default:
getlitch();
}
if (ch == '\'') {
nextch();
token = CHARLIT;
byte[] ascii = new byte[litlen * 2];
int alen = SourceRepresentation.source2ascii(lit, 0, litlen, ascii);
if (alen > 0)
intVal = SourceRepresentation.ascii2string(ascii, 0, alen).charAt(0);
else
intVal = 0;
} else
syntaxError("unclosed character literal");
return;
case '.':
nextch();
if (('0' <= ch) && (ch <= '9')) getFraction(index);
else token = DOT;
return;
case ';':
nextch(); token = SEMI;
return;
case ',':
nextch(); token = COMMA;
return;
case '(':
nextch(); token = LPAREN;
return;
case '{':
nextch(); token = LBRACE;
return;
case ')':
nextch(); token = RPAREN;
return;
case '}':
nextch(); token = RBRACE;
return;
case '[':
nextch(); token = LBRACKET;
return;
case ']':
nextch(); token = RBRACKET;
return;
case SU:
token = EOF;
currentSource.lines = cline;
return;
default:
nextch();
syntaxError("illegal character");
return;
}
}
}
}
private boolean skipComment() {
if (ch == '/') {
do {
nextch();
} while ((ch != CR) && (ch != LF) && (ch != SU));
return true;
} else if (ch == '*') {
int openComments = 1;
while (openComments > 0) {
do {
do {
if (ch == CR) {
cline++;
ccol = 0;
nextch();
if (ch == LF) {
ccol = 0;
nextch();
}
} else if (ch == LF) {
cline++;
ccol = 0;
nextch();
}
else if (ch == '\t') {
ccol = ((ccol - 1) / tabinc * tabinc) + tabinc;
nextch();
} else if (ch == '/') {
nextch();
if (ch == '*') {
nextch();
openComments++;
}
} else {
nextch();
}
} while ((ch != '*') && (ch != SU));
while (ch == '*') {
nextch();
}
} while (ch != '/' && ch != SU);
if (ch == '/') {
nextch();
openComments--;
} else {
syntaxError("unclosed comment");
return true;
}
}
return true;
} else {
return false;
}
}
private void getIdentRest(int index) {
while (true) {
switch (ch) {
case 'A': case 'B': case 'C': case 'D': case 'E':
case 'F': case 'G': case 'H': case 'I': case 'J':
case 'K': case 'L': case 'M': case 'N': case 'O':
case 'P': case 'Q': case 'R': case 'S': case 'T':
case 'U': case 'V': case 'W': case 'X': case 'Y':
case 'Z': case '$':
case 'a': case 'b': case 'c': case 'd': case 'e':
case 'f': case 'g': case 'h': case 'i': case 'j':
case 'k': case 'l': case 'm': case 'n': case 'o':
case 'p': case 'q': case 'r': case 's': case 't':
case 'u': case 'v': case 'w': case 'x': case 'y':
case 'z':
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
nextch();
break;
case '_':
nextch();
getIdentOrOperatorRest(index);
return;
default:
treatIdent(index, bp);
return;
}
}
}
private void getOperatorRest(int index) {
while (true) {
switch (ch) {
case '~': case '!': case '@': case '#': case '%':
case '^': case '*': case '+': case '-': case '<':
case '>': case '?': case ':':
case '=': case '&': case '|':
nextch();
break;
case '/':
int lastbp = bp;
nextch();
if (skipComment()) {
treatIdent(index, lastbp);
return;
} else {
break;
}
case '_':
nextch();
getIdentOrOperatorRest(index);
return;
default:
treatIdent(index, bp);
return;
}
}
}
private void getIdentOrOperatorRest(int index) {
switch (ch) {
case 'A': case 'B': case 'C': case 'D': case 'E':
case 'F': case 'G': case 'H': case 'I': case 'J':
case 'K': case 'L': case 'M': case 'N': case 'O':
case 'P': case 'Q': case 'R': case 'S': case 'T':
case 'U': case 'V': case 'W': case 'X': case 'Y':
case 'Z': case '$':
case 'a': case 'b': case 'c': case 'd': case 'e':
case 'f': case 'g': case 'h': case 'i': case 'j':
case 'k': case 'l': case 'm': case 'n': case 'o':
case 'p': case 'q': case 'r': case 's': case 't':
case 'u': case 'v': case 'w': case 'x': case 'y':
case 'z':
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
getIdentRest(index);
return;
case '~': case '!': case '@': case '#': case '%':
case '^': case '*': case '+': case '-': case '<':
case '>': case '?': case ':':
case '=': case '&': case '|':
case '/':
getOperatorRest(index);
return;
case '_':
nextch();
getIdentOrOperatorRest(index);
return;
default:
treatIdent(index, bp);
return;
}
}
/** returns true if argument corresponds to a keyword. used in dtd2scala tool */
public boolean isKeyword( String str ) {
Name name = Name.fromString( str );
return (name.index <= maxKey) ;
}
void treatIdent(int start, int end) {
name = Name.fromAscii(buf, start, end - start);
if (name.index <= maxKey) {
token = key[name.index];
if (token == OBJECT1) token = OBJECT; //todo: elim
}
else
token = IDENTIFIER;
}
/** generate an error at the given position
*/
void syntaxError(int pos, String msg) {
unit.error(pos, msg);
token = ERROR;
errpos = pos;
}
/** generate an error at the current token position
*/
void syntaxError(String msg) {
syntaxError(pos, msg);
}
/** append characteter to "lit" buffer
*/
protected void putch(byte c) {
if (litlen == lit.length) {
byte[] newlit = new byte[lit.length * 2];
System.arraycopy(lit, 0, newlit, 0, lit.length);
lit = newlit;
}
lit[litlen++] = c;
}
/** return true iff next 6 characters are a valid unicode sequence:
*/
protected boolean isUnicode() {
return
(bp + 6) < buf.length &&
(buf[bp] == '\\') &&
(buf[bp+1] == 'u') &&
(SourceRepresentation.digit2int(buf[bp+2], 16) >= 0) &&
(SourceRepresentation.digit2int(buf[bp+3], 16) >= 0) &&
(SourceRepresentation.digit2int(buf[bp+4], 16) >= 0) &&
(SourceRepresentation.digit2int(buf[bp+5], 16) >= 0);
}
/** read next character in character or string literal:
*/
protected void getlitch() {
if (ch == '\\') {
if (isUnicode()) {
putch(ch); nextch();
putch(ch); nextch();
putch(ch); nextch();
putch(ch); nextch();
putch(ch); nextch();
putch(ch); nextch();
} else {
nextch();
if ('0' <= ch && ch <= '7') {
byte leadch = ch;
int oct = SourceRepresentation.digit2int(ch, 8);
nextch();
if ('0' <= ch && ch <= '7') {
oct = oct * 8 + SourceRepresentation.digit2int(ch, 8);
nextch();
if (leadch <= '3' && '0' <= ch && ch <= '7') {
oct = oct * 8 + SourceRepresentation.digit2int(ch, 8);
nextch();
}
}
putch((byte)oct);
} else if (ch != SU) {
switch (ch) {
case 'b': case 't': case 'n':
case 'f': case 'r': case '\"':
case '\'': case '\\':
putch((byte)'\\');
putch(ch);
break;
default:
syntaxError(Position.encode(cline, ccol, currentSource.id) - 1, "invalid escape character");
putch(ch);
}
nextch();
}
}
} else if (ch != SU) {
putch(ch);
nextch();
}
}
/** read fractional part of floating point number;
* Then floatVal := buf[index..], converted to a floating point number.
*/
protected void getFraction(int index) {
while (SourceRepresentation.digit2int(ch, 10) >= 0) {
nextch();
}
token = DOUBLELIT;
if ((ch == 'e') || (ch == 'E')) {
nextch();
if ((ch == '+') || (ch == '-')) {
byte sign = ch;
nextch();
if (('0' > ch) || (ch > '9')) {
ch = sign;
bp--;
ccol--;
}
}
while (SourceRepresentation.digit2int(ch, 10) >= 0) {
nextch();
}
}
double limit = Double.MAX_VALUE;
if ((ch == 'd') || (ch == 'D')) {
nextch();
} else if ((ch == 'f') || (ch == 'F')) {
token = FLOATLIT;
limit = Float.MAX_VALUE;
nextch();
}
try {
floatVal = Double.valueOf(new String(buf, index, bp - index)).doubleValue();
if (floatVal > limit)
syntaxError("floating point number too large");
} catch (NumberFormatException e) {
syntaxError("malformed floating point number");
}
}
/** intVal := buf[index..index+len-1], converted to an integer number.
* base = the base of the number; one of 8, 10, 16.
* max = the maximal number before an overflow.
*/
protected void makeInt (int index, int len, int base, long max) {
intVal = 0;
int divider = (base == 10 ? 1 : 2);
for (int i = 0; i < len; i++) {
int d = SourceRepresentation.digit2int(buf[index + i], base);
if (d < 0) {
syntaxError("malformed integer number");
return;
}
if (intVal < 0 ||
max / (base / divider) < intVal ||
max - (d / divider) < (intVal * (base / divider) - 0)) {
syntaxError("integer number too large");
return;
}
intVal = intVal * base + d;
}
}
/** read a number,
* and convert buf[index..], setting either intVal or floatVal.
* base = the base of the number; one of 8, 10, 16.
*/
protected void getNumber(int index, int base) {
while (SourceRepresentation.digit2int(ch, base == 8 ? 10 : base) >= 0) {
nextch();
}
if (base <= 10 && ch == '.') {
nextch();
if ((ch >= '0') && (ch <= '9'))
getFraction(index);
else {
ch = buf[--bp]; ccol--;
makeInt(index, bp - index, base, Integer.MAX_VALUE);
intVal = (int)intVal;
token = INTLIT;
}
} else if (base <= 10 &&
(ch == 'e' || ch == 'E' ||
ch == 'f' || ch == 'F' ||
ch == 'd' || ch == 'D'))
getFraction(index);
else {
if (ch == 'l' || ch == 'L') {
makeInt(index, bp - index, base, Long.MAX_VALUE);
nextch();
token = LONGLIT;
} else {
makeInt(index, bp - index, base, Integer.MAX_VALUE);
intVal = (int)intVal;
token = INTLIT;
}
}
}
public int name2token(Name name) {
if (name.index <= maxKey)
return key[name.index];
else
return IDENTIFIER;
}
public String token2string(int token) {
switch (token) {
case IDENTIFIER:
return "identifier";
case CHARLIT:
return "character literal";
case INTLIT:
return "integer literal";
case LONGLIT:
return "long literal";
case FLOATLIT:
return "float literal";
case DOUBLELIT:
return "double literal";
case STRINGLIT:
return "string literal";
case SYMBOLLIT:
return "symbol literal";
case LPAREN:
return "'('";
case RPAREN:
return "')'";
case LBRACE:
return "'{'";
case RBRACE:
return "'}'";
case LBRACKET:
return "'['";
case RBRACKET:
return "']'";
case EOF:
return "eof";
case ERROR:
return "something";
case SEMI:
return "';'";
case COMMA:
return "','";
case CASECLASS:
return "case class";
case CASEOBJECT:
return "case object";
default:
try {
return "'" + tokenName[token].toString() + "'";
} catch (ArrayIndexOutOfBoundsException e) {
return "'<" + token + ">'";
} catch (NullPointerException e) {
return "'<(" + token + ")>'";
}
}
}
public String toString() {
switch (token) {
case IDENTIFIER:
return "id(" + name + ")";
case CHARLIT:
return "char(" + intVal + ")";
case INTLIT:
return "int(" + intVal + ")";
case LONGLIT:
return "long(" + intVal + ")";
case FLOATLIT:
return "float(" + floatVal + ")";
case DOUBLELIT:
return "double(" + floatVal + ")";
case STRINGLIT:
return "string(" + name + ")";
case SEMI:
return ";";
case COMMA:
return ",";
default:
return token2string(token);
}
}
protected void enterKeyword(String s, int tokenId) {
while (tokenId > tokenName.length) {
Name[] newTokName = new Name[tokenName.length * 2];
System.arraycopy(tokenName, 0, newTokName, 0, newTokName.length);
tokenName = newTokName;
}
Name n = Name.fromString(s);
tokenName[tokenId] = n;
if (n.index > maxKey)
maxKey = n.index;
if (tokenId >= numToken)
numToken = tokenId + 1;
}
protected void init() {
initKeywords();
key = new byte[maxKey+1];
for (int i = 0; i <= maxKey; i++)
key[i] = IDENTIFIER;
for (byte j = 0; j < numToken; j++)
if (tokenName[j] != null)
key[tokenName[j].index] = j;
}
protected void initKeywords() {
enterKeyword("if", IF);
enterKeyword("for", FOR);
enterKeyword("else", ELSE);
enterKeyword("this", THIS);
enterKeyword("null", NULL);
enterKeyword("new", NEW);
enterKeyword("with", WITH);
enterKeyword("super", SUPER);
enterKeyword("case", CASE);
enterKeyword("val", VAL);
enterKeyword("abstract", ABSTRACT);
enterKeyword("final", FINAL);
enterKeyword("private", PRIVATE);
enterKeyword("protected", PROTECTED);
enterKeyword("override", OVERRIDE);
enterKeyword("var", VAR);
enterKeyword("def", DEF);
enterKeyword("type", TYPE);
enterKeyword("extends", EXTENDS);
enterKeyword("object", OBJECT);
enterKeyword("module", OBJECT1);
enterKeyword("class",CLASS);
enterKeyword("constr",CONSTR);
enterKeyword("import", IMPORT);
enterKeyword("package", PACKAGE);
enterKeyword("true", TRUE);
enterKeyword("false", FALSE);
enterKeyword(".", DOT);
enterKeyword("_", USCORE);
enterKeyword(":", COLON);
enterKeyword("=", EQUALS);
enterKeyword("=>", ARROW);
enterKeyword("<-", LARROW);
enterKeyword("<:", SUBTYPE);
enterKeyword(">:", SUPERTYPE);
enterKeyword("yield", YIELD);
enterKeyword("do", DO);
enterKeyword("#", HASH);
enterKeyword("trait", TRAIT);
enterKeyword("as", AS);
enterKeyword("is", IS);
enterKeyword("@", AT);
}
}
| sources/scalac/ast/parser/Scanner.java | /* ____ ____ ____ ____ ______ *\
** / __// __ \/ __// __ \/ ____/ SOcos COmpiles Scala **
** __\_ \/ /_/ / /__/ /_/ /\_ \ (c) 2002, LAMP/EPFL **
** /_____/\____/\___/\____/____/ **
** **
** $Id$
\* */
package scalac.ast.parser;
import scalac.*;
import scalac.util.Name;
import scalac.util.Position;
/** A scanner for the programming language Scala.
*
* @author Matthias Zenger, Martin Odersky
* @version 1.0
*/
public class Scanner extends TokenData {
/** layout & character constants
*/
public int tabinc = 8;
public final static byte LF = 0xA;
protected final static byte FF = 0xC;
protected final static byte CR = 0xD;
protected final static byte SU = Sourcefile.SU;
/** the names of all tokens
*/
public Name[] tokenName = new Name[128];
public int numToken = 0;
/** keyword array; maps from name indices to tokens
*/
protected byte[] key;
protected int maxKey = 0;
/** we need one token lookahead
*/
protected TokenData next = new TokenData();
protected TokenData prev = new TokenData();
/** the first character position after the previous token
*/
public int lastpos = 0;
/** the last error position
*/
public int errpos = -1;
/** the input buffer:
*/
protected byte[] buf;
protected int bp;
/** the current character
*/
protected byte ch;
/** the line and column position of the current character
*/
public int cline;
public int ccol;
/** the current sourcefile
*/
public Sourcefile currentSource;
/** a buffer for character and string literals
*/
protected byte[] lit = new byte[64];
protected int litlen;
/** the compilation unit
*/
public Unit unit;
/** Construct a scanner from a file input stream.
*/
public Scanner(Unit unit) {
this.unit = unit;
buf = (currentSource = unit.source).getBuffer();
cline = 1;
bp = -1;
ccol = 0;
nextch();
token = EMPTY;
init();
nextToken();
}
private void nextch() {
ch = buf[++bp]; ccol++;
}
/** read next token and return last position
*/
public int skipToken() {
int p = pos;
nextToken();
return p;
}
public void nextToken() {
if (token == RBRACE) {
int prevpos = pos;
fetchToken();
switch (token) {
case ELSE: case EXTENDS: case WITH:
case YIELD: case DO:
case COMMA: case SEMI: case DOT:
case COLON: case EQUALS: case ARROW:
case LARROW: case SUBTYPE: case SUPERTYPE:
case HASH: case AS: case IS:
case RPAREN: case RBRACKET: case RBRACE:
break;
default:
if (token == EOF ||
((pos >>> Position.LINESHIFT) >
(prevpos >>> Position.LINESHIFT))) {
next.copyFrom(this);
this.token = SEMI;
this.pos = prevpos;
}
}
} else {
if (next.token == EMPTY) {
fetchToken();
} else {
copyFrom(next);
next.token = EMPTY;
}
if (token == CASE) {
prev.copyFrom(this);
fetchToken();
if (token == CLASS) {
token = CASECLASS;
} else if (token == OBJECT) {
token = CASEOBJECT;
} else {
next.copyFrom(this);
this.copyFrom(prev);
}
} else if (token == SEMI) {
prev.copyFrom(this);
fetchToken();
if (token != ELSE) {
next.copyFrom(this);
this.copyFrom(prev);
}
}
}
//System.out.println("<" + token2string(token) + ">");//DEBUG
}
/** read next token
*/
public void fetchToken() {
if (token == EOF) return;
lastpos = Position.encode(cline, ccol, currentSource.id);
int index = bp;
while(true) {
switch (ch) {
case ' ':
nextch();
break;
case '\t':
ccol = ((ccol - 1) / tabinc * tabinc) + tabinc;
nextch();
break;
case CR:
cline++;
ccol = 0;
nextch();
if (ch == LF) {
ccol = 0;
nextch();
}
break;
case LF:
case FF:
cline++;
ccol = 0;
nextch();
break;
default:
pos = Position.encode(cline, ccol, currentSource.id);
index = bp;
switch (ch) {
case 'A': case 'B': case 'C': case 'D': case 'E':
case 'F': case 'G': case 'H': case 'I': case 'J':
case 'K': case 'L': case 'M': case 'N': case 'O':
case 'P': case 'Q': case 'R': case 'S': case 'T':
case 'U': case 'V': case 'W': case 'X': case 'Y':
case 'Z': case '$':
case 'a': case 'b': case 'c': case 'd': case 'e':
case 'f': case 'g': case 'h': case 'i': case 'j':
case 'k': case 'l': case 'm': case 'n': case 'o':
case 'p': case 'q': case 'r': case 's': case 't':
case 'u': case 'v': case 'w': case 'x': case 'y':
case 'z':
nextch();
getIdentRest(index);
return;
case '~': case '!': case '@': case '#': case '%':
case '^': case '*': case '+': case '-': case '<':
case '>': case '?': case ':':
case '=': case '&': case '|':
nextch();
getOperatorRest(index);
return;
case '/':
nextch();
if (!skipComment()) {
getOperatorRest(index);
return;
}
break;
case '_':
nextch();
getIdentOrOperatorRest(index);
return;
case '0':
nextch();
if (ch == 'x' || ch == 'X') {
nextch();
getNumber(index + 2, 16);
} else
getNumber(index, 8);
return;
case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
getNumber(index, 10);
return;
case '\"':
nextch();
litlen = 0;
while (ch != '\"' && ch != CR && ch != LF && ch != SU)
getlitch();
if (ch == '\"') {
token = STRINGLIT;
name = Name.fromSource(lit, 0, litlen);
nextch();
}
else
syntaxError("unclosed character literal");
return;
case '\'':
nextch();
litlen = 0;
switch (ch) {
case 'A': case 'B': case 'C': case 'D': case 'E':
case 'F': case 'G': case 'H': case 'I': case 'J':
case 'K': case 'L': case 'M': case 'N': case 'O':
case 'P': case 'Q': case 'R': case 'S': case 'T':
case 'U': case 'V': case 'W': case 'X': case 'Y':
case 'Z': case '$':
case 'a': case 'b': case 'c': case 'd': case 'e':
case 'f': case 'g': case 'h': case 'i': case 'j':
case 'k': case 'l': case 'm': case 'n': case 'o':
case 'p': case 'q': case 'r': case 's': case 't':
case 'u': case 'v': case 'w': case 'x': case 'y':
case 'z':
index = bp;
putch(ch);
nextch();
if (ch != '\'') {
getIdentRest(index);
token = SYMBOLLIT;
return;
}
break;
default:
getlitch();
}
if (ch == '\'') {
nextch();
token = CHARLIT;
byte[] ascii = new byte[litlen * 2];
int alen = SourceRepresentation.source2ascii(lit, 0, litlen, ascii);
if (alen > 0)
intVal = SourceRepresentation.ascii2string(ascii, 0, alen).charAt(0);
else
intVal = 0;
} else
syntaxError("unclosed character literal");
return;
case '.':
nextch();
if (('0' <= ch) && (ch <= '9')) getFraction(index);
else token = DOT;
return;
case ';':
nextch(); token = SEMI;
return;
case ',':
nextch(); token = COMMA;
return;
case '(':
nextch(); token = LPAREN;
return;
case '{':
nextch(); token = LBRACE;
return;
case ')':
nextch(); token = RPAREN;
return;
case '}':
nextch(); token = RBRACE;
return;
case '[':
nextch(); token = LBRACKET;
return;
case ']':
nextch(); token = RBRACKET;
return;
case SU:
token = EOF;
currentSource.lines = cline;
return;
default:
nextch();
syntaxError("illegal character");
return;
}
}
}
}
private boolean skipComment() {
if (ch == '/') {
do {
nextch();
} while ((ch != CR) && (ch != LF) && (ch != SU));
return true;
} else if (ch == '*') {
int openComments = 1;
while (openComments > 0) {
do {
do {
if (ch == CR) {
cline++;
ccol = 0;
nextch();
if (ch == LF) {
ccol = 0;
nextch();
}
} else if (ch == LF) {
cline++;
ccol = 0;
nextch();
}
else if (ch == '\t') {
ccol = ((ccol - 1) / tabinc * tabinc) + tabinc;
nextch();
} else if (ch == '/') {
nextch();
if (ch == '*') {
nextch();
openComments++;
}
} else {
nextch();
}
} while ((ch != '*') && (ch != SU));
while (ch == '*') {
nextch();
}
} while (ch != '/' && ch != SU);
if (ch == '/') {
nextch();
openComments--;
} else {
syntaxError("unclosed comment");
return true;
}
}
return true;
} else {
return false;
}
}
private void getIdentRest(int index) {
while (true) {
switch (ch) {
case 'A': case 'B': case 'C': case 'D': case 'E':
case 'F': case 'G': case 'H': case 'I': case 'J':
case 'K': case 'L': case 'M': case 'N': case 'O':
case 'P': case 'Q': case 'R': case 'S': case 'T':
case 'U': case 'V': case 'W': case 'X': case 'Y':
case 'Z': case '$':
case 'a': case 'b': case 'c': case 'd': case 'e':
case 'f': case 'g': case 'h': case 'i': case 'j':
case 'k': case 'l': case 'm': case 'n': case 'o':
case 'p': case 'q': case 'r': case 's': case 't':
case 'u': case 'v': case 'w': case 'x': case 'y':
case 'z':
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
nextch();
break;
case '_':
nextch();
getIdentOrOperatorRest(index);
return;
default:
treatIdent(index, bp);
return;
}
}
}
private void getOperatorRest(int index) {
while (true) {
switch (ch) {
case '~': case '!': case '@': case '#': case '%':
case '^': case '*': case '+': case '-': case '<':
case '>': case '?': case ':':
case '=': case '&': case '|':
nextch();
break;
case '/':
int lastbp = bp;
nextch();
if (skipComment()) {
treatIdent(index, lastbp);
return;
} else {
break;
}
case '_':
nextch();
getIdentOrOperatorRest(index);
return;
default:
treatIdent(index, bp);
return;
}
}
}
private void getIdentOrOperatorRest(int index) {
switch (ch) {
case 'A': case 'B': case 'C': case 'D': case 'E':
case 'F': case 'G': case 'H': case 'I': case 'J':
case 'K': case 'L': case 'M': case 'N': case 'O':
case 'P': case 'Q': case 'R': case 'S': case 'T':
case 'U': case 'V': case 'W': case 'X': case 'Y':
case 'Z': case '$':
case 'a': case 'b': case 'c': case 'd': case 'e':
case 'f': case 'g': case 'h': case 'i': case 'j':
case 'k': case 'l': case 'm': case 'n': case 'o':
case 'p': case 'q': case 'r': case 's': case 't':
case 'u': case 'v': case 'w': case 'x': case 'y':
case 'z':
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
getIdentRest(index);
return;
case '~': case '!': case '@': case '#': case '%':
case '^': case '*': case '+': case '-': case '<':
case '>': case '?': case ':':
case '=': case '&': case '|':
case '/':
getOperatorRest(index);
return;
case '_':
nextch();
getIdentOrOperatorRest(index);
return;
default:
treatIdent(index, bp);
return;
}
}
void treatIdent(int start, int end) {
name = Name.fromAscii(buf, start, end - start);
if (name.index <= maxKey) {
token = key[name.index];
if (token == OBJECT1) token = OBJECT; //todo: elim
}
else
token = IDENTIFIER;
}
/** generate an error at the given position
*/
void syntaxError(int pos, String msg) {
unit.error(pos, msg);
token = ERROR;
errpos = pos;
}
/** generate an error at the current token position
*/
void syntaxError(String msg) {
syntaxError(pos, msg);
}
/** append characteter to "lit" buffer
*/
protected void putch(byte c) {
if (litlen == lit.length) {
byte[] newlit = new byte[lit.length * 2];
System.arraycopy(lit, 0, newlit, 0, lit.length);
lit = newlit;
}
lit[litlen++] = c;
}
/** return true iff next 6 characters are a valid unicode sequence:
*/
protected boolean isUnicode() {
return
(bp + 6) < buf.length &&
(buf[bp] == '\\') &&
(buf[bp+1] == 'u') &&
(SourceRepresentation.digit2int(buf[bp+2], 16) >= 0) &&
(SourceRepresentation.digit2int(buf[bp+3], 16) >= 0) &&
(SourceRepresentation.digit2int(buf[bp+4], 16) >= 0) &&
(SourceRepresentation.digit2int(buf[bp+5], 16) >= 0);
}
/** read next character in character or string literal:
*/
protected void getlitch() {
if (ch == '\\') {
if (isUnicode()) {
putch(ch); nextch();
putch(ch); nextch();
putch(ch); nextch();
putch(ch); nextch();
putch(ch); nextch();
putch(ch); nextch();
} else {
nextch();
if ('0' <= ch && ch <= '7') {
byte leadch = ch;
int oct = SourceRepresentation.digit2int(ch, 8);
nextch();
if ('0' <= ch && ch <= '7') {
oct = oct * 8 + SourceRepresentation.digit2int(ch, 8);
nextch();
if (leadch <= '3' && '0' <= ch && ch <= '7') {
oct = oct * 8 + SourceRepresentation.digit2int(ch, 8);
nextch();
}
}
putch((byte)oct);
} else if (ch != SU) {
switch (ch) {
case 'b': case 't': case 'n':
case 'f': case 'r': case '\"':
case '\'': case '\\':
putch((byte)'\\');
putch(ch);
break;
default:
syntaxError(Position.encode(cline, ccol, currentSource.id) - 1, "invalid escape character");
putch(ch);
}
nextch();
}
}
} else if (ch != SU) {
putch(ch);
nextch();
}
}
/** read fractional part of floating point number;
* Then floatVal := buf[index..], converted to a floating point number.
*/
protected void getFraction(int index) {
while (SourceRepresentation.digit2int(ch, 10) >= 0) {
nextch();
}
token = DOUBLELIT;
if ((ch == 'e') || (ch == 'E')) {
nextch();
if ((ch == '+') || (ch == '-')) {
byte sign = ch;
nextch();
if (('0' > ch) || (ch > '9')) {
ch = sign;
bp--;
ccol--;
}
}
while (SourceRepresentation.digit2int(ch, 10) >= 0) {
nextch();
}
}
double limit = Double.MAX_VALUE;
if ((ch == 'd') || (ch == 'D')) {
nextch();
} else if ((ch == 'f') || (ch == 'F')) {
token = FLOATLIT;
limit = Float.MAX_VALUE;
nextch();
}
try {
floatVal = Double.valueOf(new String(buf, index, bp - index)).doubleValue();
if (floatVal > limit)
syntaxError("floating point number too large");
} catch (NumberFormatException e) {
syntaxError("malformed floating point number");
}
}
/** intVal := buf[index..index+len-1], converted to an integer number.
* base = the base of the number; one of 8, 10, 16.
* max = the maximal number before an overflow.
*/
protected void makeInt (int index, int len, int base, long max) {
intVal = 0;
int divider = (base == 10 ? 1 : 2);
for (int i = 0; i < len; i++) {
int d = SourceRepresentation.digit2int(buf[index + i], base);
if (d < 0) {
syntaxError("malformed integer number");
return;
}
if (intVal < 0 ||
max / (base / divider) < intVal ||
max - (d / divider) < (intVal * (base / divider) - 0)) {
syntaxError("integer number too large");
return;
}
intVal = intVal * base + d;
}
}
/** read a number,
* and convert buf[index..], setting either intVal or floatVal.
* base = the base of the number; one of 8, 10, 16.
*/
protected void getNumber(int index, int base) {
while (SourceRepresentation.digit2int(ch, base == 8 ? 10 : base) >= 0) {
nextch();
}
if (base <= 10 && ch == '.') {
nextch();
if ((ch >= '0') && (ch <= '9'))
getFraction(index);
else {
ch = buf[--bp]; ccol--;
makeInt(index, bp - index, base, Integer.MAX_VALUE);
intVal = (int)intVal;
token = INTLIT;
}
} else if (base <= 10 &&
(ch == 'e' || ch == 'E' ||
ch == 'f' || ch == 'F' ||
ch == 'd' || ch == 'D'))
getFraction(index);
else {
if (ch == 'l' || ch == 'L') {
makeInt(index, bp - index, base, Long.MAX_VALUE);
nextch();
token = LONGLIT;
} else {
makeInt(index, bp - index, base, Integer.MAX_VALUE);
intVal = (int)intVal;
token = INTLIT;
}
}
}
public int name2token(Name name) {
if (name.index <= maxKey)
return key[name.index];
else
return IDENTIFIER;
}
public String token2string(int token) {
switch (token) {
case IDENTIFIER:
return "identifier";
case CHARLIT:
return "character literal";
case INTLIT:
return "integer literal";
case LONGLIT:
return "long literal";
case FLOATLIT:
return "float literal";
case DOUBLELIT:
return "double literal";
case STRINGLIT:
return "string literal";
case SYMBOLLIT:
return "symbol literal";
case LPAREN:
return "'('";
case RPAREN:
return "')'";
case LBRACE:
return "'{'";
case RBRACE:
return "'}'";
case LBRACKET:
return "'['";
case RBRACKET:
return "']'";
case EOF:
return "eof";
case ERROR:
return "something";
case SEMI:
return "';'";
case COMMA:
return "','";
case CASECLASS:
return "case class";
case CASEOBJECT:
return "case object";
default:
try {
return "'" + tokenName[token].toString() + "'";
} catch (ArrayIndexOutOfBoundsException e) {
return "'<" + token + ">'";
} catch (NullPointerException e) {
return "'<(" + token + ")>'";
}
}
}
public String toString() {
switch (token) {
case IDENTIFIER:
return "id(" + name + ")";
case CHARLIT:
return "char(" + intVal + ")";
case INTLIT:
return "int(" + intVal + ")";
case LONGLIT:
return "long(" + intVal + ")";
case FLOATLIT:
return "float(" + floatVal + ")";
case DOUBLELIT:
return "double(" + floatVal + ")";
case STRINGLIT:
return "string(" + name + ")";
case SEMI:
return ";";
case COMMA:
return ",";
default:
return token2string(token);
}
}
protected void enterKeyword(String s, int tokenId) {
while (tokenId > tokenName.length) {
Name[] newTokName = new Name[tokenName.length * 2];
System.arraycopy(tokenName, 0, newTokName, 0, newTokName.length);
tokenName = newTokName;
}
Name n = Name.fromString(s);
tokenName[tokenId] = n;
if (n.index > maxKey)
maxKey = n.index;
if (tokenId >= numToken)
numToken = tokenId + 1;
}
protected void init() {
initKeywords();
key = new byte[maxKey+1];
for (int i = 0; i <= maxKey; i++)
key[i] = IDENTIFIER;
for (byte j = 0; j < numToken; j++)
if (tokenName[j] != null)
key[tokenName[j].index] = j;
}
protected void initKeywords() {
enterKeyword("if", IF);
enterKeyword("for", FOR);
enterKeyword("else", ELSE);
enterKeyword("this", THIS);
enterKeyword("null", NULL);
enterKeyword("new", NEW);
enterKeyword("with", WITH);
enterKeyword("super", SUPER);
enterKeyword("case", CASE);
enterKeyword("val", VAL);
enterKeyword("abstract", ABSTRACT);
enterKeyword("final", FINAL);
enterKeyword("private", PRIVATE);
enterKeyword("protected", PROTECTED);
enterKeyword("override", OVERRIDE);
enterKeyword("var", VAR);
enterKeyword("def", DEF);
enterKeyword("type", TYPE);
enterKeyword("extends", EXTENDS);
enterKeyword("object", OBJECT);
enterKeyword("module", OBJECT1);
enterKeyword("class",CLASS);
enterKeyword("constr",CONSTR);
enterKeyword("import", IMPORT);
enterKeyword("package", PACKAGE);
enterKeyword("true", TRUE);
enterKeyword("false", FALSE);
enterKeyword(".", DOT);
enterKeyword("_", USCORE);
enterKeyword(":", COLON);
enterKeyword("=", EQUALS);
enterKeyword("=>", ARROW);
enterKeyword("<-", LARROW);
enterKeyword("<:", SUBTYPE);
enterKeyword(">:", SUPERTYPE);
enterKeyword("yield", YIELD);
enterKeyword("do", DO);
enterKeyword("#", HASH);
enterKeyword("trait", TRAIT);
enterKeyword("as", AS);
enterKeyword("is", IS);
enterKeyword("@", AT);
}
}
| modifications so keywords can be detected by XM...
modifications so keywords can be detected by XML tool dtd2scala
| sources/scalac/ast/parser/Scanner.java | modifications so keywords can be detected by XM... | <ide><path>ources/scalac/ast/parser/Scanner.java
<ide> token = EMPTY;
<ide> init();
<ide> nextToken();
<add> }
<add>
<add> /** only used to determine keywords. used in dtd2scala tool */
<add> public Scanner() {
<add> initKeywords();
<ide> }
<ide>
<ide> private void nextch() {
<ide> }
<ide> }
<ide>
<add> /** returns true if argument corresponds to a keyword. used in dtd2scala tool */
<add> public boolean isKeyword( String str ) {
<add> Name name = Name.fromString( str );
<add> return (name.index <= maxKey) ;
<add> }
<add>
<ide> void treatIdent(int start, int end) {
<ide> name = Name.fromAscii(buf, start, end - start);
<ide> if (name.index <= maxKey) { |
|
Java | mit | bcd9965da7fdb1f386d0ba81cc6212112c344ac2 | 0 | Team4761/Run-Queue | package org.robockets.runqueue.client.views;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionListener;
import javax.swing.*;
import org.robockets.runqueue.client.MainWindowListener;
import org.robockets.runqueue.client.models.QueueModel;
public class MainView {
private final int WIDTH = 500, HEIGHT = 280;
private final int ROWS = 2, COLUMNS = 1;
private final int BUTTON_WIDTH = 100;
private final int SECOND_LINE_OFFSET = 50;
private String[] priorities = {"Critical", "High", "Medium", "Low"};
private JFrame jFrame;
private Font font = new Font("Arial", Font.PLAIN, 30);
public JLabel usernameLabel, positionLabel;
private QueueModel queueModel;
public MainView (QueueModel queueModel) {
this.queueModel = queueModel;
this.jFrame = this.setupJFrame();
this.setupWindow();
}
private JFrame setupJFrame () {
try { // Nimbus theme
for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {}
JFrame jFrame = new JFrame("Robo Run-Queue Client");
jFrame.setSize(WIDTH, HEIGHT);
jFrame.setMaximumSize(new Dimension(WIDTH, HEIGHT));
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame.setLayout(new GridLayout(ROWS, COLUMNS));
return jFrame;
}
private void setupWindow () {
ActionListener actionListener = new MainWindowListener();
// Top half of the screen
JPanel topPanel = new JPanel();
topPanel.setMaximumSize(new Dimension(WIDTH, HEIGHT));
topPanel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
positionLabel = new JLabel("Position: 1/1");
font = font.deriveFont(30f);
positionLabel.setFont(font);
c.gridx = 0;
c.gridy = 0;
c.ipadx = 100;
c.anchor = GridBagConstraints.LINE_START;
topPanel.add(positionLabel, c);
usernameLabel = new JLabel("USERNAME");
font = font.deriveFont(40f);
usernameLabel.setFont(font);
c.gridx = 3;
c.gridy = 0;
c.ipadx = 0;
c.anchor = GridBagConstraints.LINE_END;
topPanel.add(usernameLabel, c);
JButton enableButton = new JButton("Enable");
enableButton.setActionCommand("ENABLE_BUTTON");
enableButton.addActionListener(actionListener);
c.gridx = 0;
c.gridy = 3;
c.ipadx = BUTTON_WIDTH / 3;
c.anchor = GridBagConstraints.LINE_START;
c.insets = new Insets(SECOND_LINE_OFFSET, 0, 0, 0);
topPanel.add(enableButton, c);
JButton disableButton = new JButton("Disable");
disableButton.setActionCommand("DISABLE_BUTTON");
disableButton.addActionListener(actionListener);
c.gridx = 0;
c.gridy = 3;
c.ipadx = BUTTON_WIDTH / 3;
c.insets = new Insets(SECOND_LINE_OFFSET, BUTTON_WIDTH, 0, 30);
c.anchor = GridBagConstraints.LINE_START;
topPanel.add(disableButton, c);
JLabel priorityLabel = new JLabel("Priority: ");
c.gridx = 3;
c.gridy = 3;
c.anchor = GridBagConstraints.LINE_START;
c.insets = new Insets(SECOND_LINE_OFFSET, 30, 0, 0);
topPanel.add(priorityLabel, c);
JComboBox<String> priorityDropdown = new JComboBox<String>(priorities);
priorityDropdown.setSelectedIndex(2);
priorityDropdown.setActionCommand("PRIORITY_DROPDOWN");
priorityDropdown.addActionListener(actionListener);
c.gridx = 3;
c.gridy = 3;
c.ipadx = 50;
c.insets = new Insets(SECOND_LINE_OFFSET, 50, 0, 2);
c.anchor = GridBagConstraints.LINE_END;
topPanel.add(priorityDropdown, c);
// Bottom half of the screen
JTable queueTable = new JTable(this.queueModel);
queueTable.setCellSelectionEnabled(false);
queueTable.getTableHeader().setReorderingAllowed(false);
queueTable.getTableHeader().setResizingAllowed(false);
JScrollPane queuePane = new JScrollPane(queueTable);
queuePane.setMaximumSize(new Dimension(WIDTH, HEIGHT));
jFrame.add(topPanel);
jFrame.add(queuePane);
jFrame.pack();
}
public void display () {
jFrame.setVisible(true);
}
} | src/org/robockets/runqueue/client/views/MainView.java | package org.robockets.runqueue.client.views;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionListener;
import javax.swing.*;
import org.robockets.runqueue.client.MainWindowListener;
import org.robockets.runqueue.client.models.QueueModel;
public class MainView {
private final int WIDTH = 500, HEIGHT = 280;
private final int ROWS = 2, COLUMNS = 1;
private final int BUTTON_WIDTH = 100, BUTTON_HEIGHT = 30;
private final int SECOND_LINE_OFFSET = 50;
private String[] priorities = {"Critical", "High", "Medium", "Low"};
private JFrame jFrame;
private Font font = new Font("Arial", Font.PLAIN, 30);
public JLabel usernameLabel, positionLabel;
private QueueModel queueModel;
public MainView (QueueModel queueModel) {
this.queueModel = queueModel;
this.jFrame = this.setupJFrame();
this.setupWindow();
}
private JFrame setupJFrame () {
try { // Nimbus theme
for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {}
JFrame jFrame = new JFrame("Robo Run-Queue Client");
jFrame.setSize(WIDTH, HEIGHT);
jFrame.setMaximumSize(new Dimension(WIDTH, HEIGHT));
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame.setLayout(new GridLayout(ROWS, COLUMNS));
return jFrame;
}
private void setupWindow () {
ActionListener actionListener = new MainWindowListener();
// Top half of the screen
JPanel topPanel = new JPanel();
topPanel.setMaximumSize(new Dimension(WIDTH, HEIGHT));
topPanel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
positionLabel = new JLabel("Position: 1/1");
font = font.deriveFont(30f);
positionLabel.setFont(font);
c.gridx = 0;
c.gridy = 0;
c.ipadx = 100;
c.anchor = GridBagConstraints.LINE_START;
topPanel.add(positionLabel, c);
usernameLabel = new JLabel("USERNAME");
font = font.deriveFont(40f);
usernameLabel.setFont(font);
c.gridx = 3;
c.gridy = 0;
c.ipadx = 0;
c.anchor = GridBagConstraints.LINE_END;
topPanel.add(usernameLabel, c);
JButton enableButton = new JButton("Enable");
enableButton.setActionCommand("ENABLE_BUTTON");
enableButton.addActionListener(actionListener);
c.gridx = 0;
c.gridy = 3;
c.ipadx = BUTTON_WIDTH / 3;
c.anchor = GridBagConstraints.LINE_START;
c.insets = new Insets(SECOND_LINE_OFFSET, 0, 0, 0);
topPanel.add(enableButton, c);
JButton disableButton = new JButton("Disable");
disableButton.setActionCommand("DISABLE_BUTTON");
disableButton.addActionListener(actionListener);
c.gridx = 0;
c.gridy = 3;
c.ipadx = BUTTON_WIDTH / 3;
c.insets = new Insets(SECOND_LINE_OFFSET, BUTTON_WIDTH, 0, 30);
c.anchor = GridBagConstraints.LINE_START;
topPanel.add(disableButton, c);
JLabel priorityLabel = new JLabel("Priority: ");
c.gridx = 3;
c.gridy = 3;
c.anchor = GridBagConstraints.LINE_START;
c.insets = new Insets(SECOND_LINE_OFFSET, 30, 0, 0);
topPanel.add(priorityLabel, c);
JComboBox<String> priorityDropdown = new JComboBox<String>(priorities);
priorityDropdown.setSelectedIndex(2);
priorityDropdown.setActionCommand("PRIORITY_DROPDOWN");
priorityDropdown.addActionListener(actionListener);
c.gridx = 3;
c.gridy = 3;
c.ipadx = 50;
c.insets = new Insets(SECOND_LINE_OFFSET, 50, 0, 2);
c.anchor = GridBagConstraints.LINE_END;
topPanel.add(priorityDropdown, c);
// Bottom half of the screen
JTable queueTable = new JTable(this.queueModel);
queueTable.setCellSelectionEnabled(false);
JScrollPane queuePane = new JScrollPane(queueTable);
queuePane.setMaximumSize(new Dimension(WIDTH, HEIGHT));
jFrame.add(topPanel);
jFrame.add(queuePane);
jFrame.pack();
}
public void display () {
jFrame.setVisible(true);
}
public void hide () {
jFrame.setVisible(false);
}
} | Turn off column resizing
| src/org/robockets/runqueue/client/views/MainView.java | Turn off column resizing | <ide><path>rc/org/robockets/runqueue/client/views/MainView.java
<ide> public class MainView {
<ide> private final int WIDTH = 500, HEIGHT = 280;
<ide> private final int ROWS = 2, COLUMNS = 1;
<del> private final int BUTTON_WIDTH = 100, BUTTON_HEIGHT = 30;
<add> private final int BUTTON_WIDTH = 100;
<ide> private final int SECOND_LINE_OFFSET = 50;
<ide>
<ide> private String[] priorities = {"Critical", "High", "Medium", "Low"};
<ide> // Bottom half of the screen
<ide> JTable queueTable = new JTable(this.queueModel);
<ide> queueTable.setCellSelectionEnabled(false);
<add> queueTable.getTableHeader().setReorderingAllowed(false);
<add> queueTable.getTableHeader().setResizingAllowed(false);
<ide>
<ide> JScrollPane queuePane = new JScrollPane(queueTable);
<ide> queuePane.setMaximumSize(new Dimension(WIDTH, HEIGHT));
<ide> public void display () {
<ide> jFrame.setVisible(true);
<ide> }
<del>
<del> public void hide () {
<del> jFrame.setVisible(false);
<del> }
<ide> } |
|
JavaScript | apache-2.0 | e15aef5ee281ad0a5052b385c3c8b965979ddf91 | 0 | binary-com/binary-static,negar-binary/binary-static,raunakkathuria/binary-static,kellybinary/binary-static,4p00rv/binary-static,binary-static-deployed/binary-static,binary-static-deployed/binary-static,negar-binary/binary-static,negar-binary/binary-static,binary-static-deployed/binary-static,4p00rv/binary-static,kellybinary/binary-static,4p00rv/binary-static,raunakkathuria/binary-static,ashkanx/binary-static,ashkanx/binary-static,binary-com/binary-static,raunakkathuria/binary-static,kellybinary/binary-static,ashkanx/binary-static,binary-com/binary-static | const MenuSelector = (() => {
let array_sections,
go_back,
go_next;
const init = (sections, show_div = true) => {
array_sections = sections;
go_back = document.getElementById('go_back');
go_next = document.getElementById('go_next');
const $sidebar_list_item = $('#sidebar-nav li');
$sidebar_list_item.click(function () {
$sidebar_list_item.removeClass('selected');
$(this).addClass('selected');
});
$(window).on('hashchange', showSelectedDiv);
if (show_div) {
showSelectedDiv();
}
};
const getHash = () => {
const hash = window.location.hash;
return hash && $.inArray(hash.substring(1), array_sections) !== -1 ? hash : `#${array_sections[0]}`;
};
const showSelectedDiv = () => {
const $sections_with_hash = $(`.sections[id="${getHash().substring(1)}"]`);
if ($sections_with_hash.is(':visible') && $('.sections:visible').length === 1) {
return;
}
$('.sections').setVisibility(0);
$sections_with_hash.setVisibility(1);
$(`#sidebar-nav a[href="${getHash()}"]`).parent().addClass('selected');
if (go_back && go_next) {
initBackNextButtons();
}
window.dispatchEvent(new Event('menu_selector_selected_shown'));
};
const selectedIsShown = () => {
return new Promise(resolve => {
if ($sections_with_hash.is(':visible')) {
resolve();
} else {
function handler() {
resolve();
window.removeEventListener('menu_selector_selected_shown', handler);
}
window.addEventListener('menu_selector_selected_shown', handler);
}
});
};
const initBackNextButtons = () => {
const current_section = getHash().slice(1);
const current_index = array_sections.indexOf(current_section);
if (current_index === 0) {
go_back.classList.add('button-disabled');
} else {
go_back.classList.remove('button-disabled');
go_back.setAttribute('href', `#${array_sections[current_index - 1]}`);
}
if (current_index === array_sections.length - 1) {
go_next.classList.add('button-disabled');
} else {
go_next.classList.remove('button-disabled');
go_next.setAttribute('href', `#${array_sections[current_index + 1]}`);
}
};
const clean = () => {
$(window).off('hashchange', showSelectedDiv);
};
return {
init,
clean,
selectedIsShown,
};
})();
module.exports = MenuSelector;
| src/javascript/_common/menu_selector.js | const MenuSelector = (() => {
let array_sections,
go_back,
go_next;
const init = (sections, show_div = true) => {
array_sections = sections;
go_back = document.getElementById('go_back');
go_next = document.getElementById('go_next');
const $sidebar_list_item = $('#sidebar-nav li');
$sidebar_list_item.click(function () {
$sidebar_list_item.removeClass('selected');
$(this).addClass('selected');
});
$(window).on('hashchange', showSelectedDiv);
if (show_div) {
showSelectedDiv();
}
};
const getHash = () => {
const hash = window.location.hash;
return hash && $.inArray(hash.substring(1), array_sections) !== -1 ? hash : `#${array_sections[0]}`;
};
const showSelectedDiv = () => {
const $sections_with_hash = $(`.sections[id="${getHash().substring(1)}"]`);
if ($sections_with_hash.is(':visible') && $('.sections:visible').length === 1) {
return;
}
$('.sections').setVisibility(0);
$sections_with_hash.setVisibility(1);
$(`#sidebar-nav a[href="${getHash()}"]`).parent().addClass('selected');
if (go_back && go_next) {
initBackNextButtons();
}
window.dispatchEvent(new Event('menu_selector_selected_shown'));
};
const initBackNextButtons = () => {
const current_section = getHash().slice(1);
const current_index = array_sections.indexOf(current_section);
if (current_index === 0) {
go_back.classList.add('button-disabled');
} else {
go_back.classList.remove('button-disabled');
go_back.setAttribute('href', `#${array_sections[current_index - 1]}`);
}
if (current_index === array_sections.length - 1) {
go_next.classList.add('button-disabled');
} else {
go_next.classList.remove('button-disabled');
go_next.setAttribute('href', `#${array_sections[current_index + 1]}`);
}
};
const clean = () => {
$(window).off('hashchange', showSelectedDiv);
};
return {
init,
clean,
};
})();
module.exports = MenuSelector;
| add promise returning method to menu selector
| src/javascript/_common/menu_selector.js | add promise returning method to menu selector | <ide><path>rc/javascript/_common/menu_selector.js
<ide> window.dispatchEvent(new Event('menu_selector_selected_shown'));
<ide> };
<ide>
<add> const selectedIsShown = () => {
<add> return new Promise(resolve => {
<add> if ($sections_with_hash.is(':visible')) {
<add> resolve();
<add> } else {
<add> function handler() {
<add> resolve();
<add> window.removeEventListener('menu_selector_selected_shown', handler);
<add> }
<add> window.addEventListener('menu_selector_selected_shown', handler);
<add> }
<add> });
<add> };
<add>
<ide> const initBackNextButtons = () => {
<ide> const current_section = getHash().slice(1);
<ide> const current_index = array_sections.indexOf(current_section);
<ide> return {
<ide> init,
<ide> clean,
<add> selectedIsShown,
<ide> };
<ide> })();
<ide> |
|
Java | mit | 8d4f01218190dfe09a2b0a7bc20167f8a0761c7e | 0 | aikar/TaskChain,aikar/TaskChain | /*
* Copyright (c) 2016 Daniel Ennis (Aikar) - MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package co.aikar.taskchain;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.event.game.state.GameStoppingEvent;
import org.spongepowered.api.plugin.PluginContainer;
import org.spongepowered.api.scheduler.Task;
import java.util.concurrent.TimeUnit;
@SuppressWarnings("WeakerAccess")
public class SpongeTaskChainFactory extends TaskChainFactory {
private SpongeTaskChainFactory(GameInterface impl) {
super(impl);
}
public static TaskChainFactory create(PluginContainer pluginContainer) {
return create(pluginContainer.getInstance().orElse(null));
}
public static TaskChainFactory create(Object plugin) {
return new SpongeTaskChainFactory(new SpongeGameInterface(plugin));
}
private static class SpongeGameInterface implements GameInterface {
private final AsyncQueue asyncQueue;
private final Object plugin;
private SpongeGameInterface(Object plugin) {
if (plugin == null || !Sponge.getPluginManager().fromInstance(plugin).isPresent()) {
throw new IllegalArgumentException("Not a valid Sponge Plugin");
}
this.plugin = plugin;
this.asyncQueue = new TaskChainAsyncQueue();
}
@Override
public boolean isMainThread() {
return false;
}
@Override
public AsyncQueue getAsyncQueue() {
return asyncQueue;
}
@Override
public void postToMain(Runnable run) {
Task.builder().execute(run).submit(plugin);
}
@Override
public void scheduleTask(int gameUnits, Runnable run) {
Task.builder().delayTicks(gameUnits).execute(run).submit(plugin);
}
@Override
public void registerShutdownHandler(TaskChainFactory factory) {
Sponge.getEventManager().registerListener(plugin, GameStoppingEvent.class, event -> {
factory.shutdown(60, TimeUnit.SECONDS);
});
}
}
}
| sponge/src/main/java/co/aikar/taskchain/SpongeTaskChainFactory.java | /*
* Copyright (c) 2016 Daniel Ennis (Aikar) - MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package co.aikar.taskchain;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.event.game.state.GameStoppingEvent;
import org.spongepowered.api.plugin.PluginContainer;
import org.spongepowered.api.scheduler.Task;
import java.util.concurrent.TimeUnit;
@SuppressWarnings("WeakerAccess")
public class SpongeTaskChainFactory extends TaskChainFactory {
private SpongeTaskChainFactory(GameInterface impl) {
super(impl);
}
public static TaskChainFactory create(PluginContainer plugin) {
return new SpongeTaskChainFactory(new SpongeGameInterface(plugin));
}
private static class SpongeGameInterface implements GameInterface {
private final AsyncQueue asyncQueue;
private final Object plugin;
private SpongeGameInterface(PluginContainer plugin) {
final Object pluginObject = plugin.getInstance().orElse(null);
if (pluginObject == null) {
throw new NullPointerException("Plugin can not be null");
}
this.plugin = pluginObject;
this.asyncQueue = new TaskChainAsyncQueue();
}
@Override
public boolean isMainThread() {
return false;
}
@Override
public AsyncQueue getAsyncQueue() {
return asyncQueue;
}
@Override
public void postToMain(Runnable run) {
Task.builder().execute(run).submit(plugin);
}
@Override
public void scheduleTask(int gameUnits, Runnable run) {
Task.builder().delayTicks(gameUnits).execute(run).submit(plugin);
}
@Override
public void registerShutdownHandler(TaskChainFactory factory) {
Sponge.getEventManager().registerListener(plugin, GameStoppingEvent.class, event -> {
factory.shutdown(60, TimeUnit.SECONDS);
});
}
}
}
| More Sponge work
| sponge/src/main/java/co/aikar/taskchain/SpongeTaskChainFactory.java | More Sponge work | <ide><path>ponge/src/main/java/co/aikar/taskchain/SpongeTaskChainFactory.java
<ide>
<ide> @SuppressWarnings("WeakerAccess")
<ide> public class SpongeTaskChainFactory extends TaskChainFactory {
<del>
<ide> private SpongeTaskChainFactory(GameInterface impl) {
<ide> super(impl);
<ide> }
<del> public static TaskChainFactory create(PluginContainer plugin) {
<add>
<add> public static TaskChainFactory create(PluginContainer pluginContainer) {
<add> return create(pluginContainer.getInstance().orElse(null));
<add> }
<add> public static TaskChainFactory create(Object plugin) {
<ide> return new SpongeTaskChainFactory(new SpongeGameInterface(plugin));
<ide> }
<ide>
<ide> private final AsyncQueue asyncQueue;
<ide> private final Object plugin;
<ide>
<del> private SpongeGameInterface(PluginContainer plugin) {
<del> final Object pluginObject = plugin.getInstance().orElse(null);
<del> if (pluginObject == null) {
<del> throw new NullPointerException("Plugin can not be null");
<add> private SpongeGameInterface(Object plugin) {
<add> if (plugin == null || !Sponge.getPluginManager().fromInstance(plugin).isPresent()) {
<add> throw new IllegalArgumentException("Not a valid Sponge Plugin");
<ide> }
<del> this.plugin = pluginObject;
<add> this.plugin = plugin;
<ide> this.asyncQueue = new TaskChainAsyncQueue();
<ide> }
<ide> |
|
Java | bsd-3-clause | d476b955046aee5d5f750111b567f5ed51bf85b8 | 0 | ShiftMediaProject/libilbc,ShiftMediaProject/libilbc,TimothyGu/libilbc,TimothyGu/libilbc,ShiftMediaProject/libilbc,TimothyGu/libilbc,ShiftMediaProject/libilbc,TimothyGu/libilbc,TimothyGu/libilbc,ShiftMediaProject/libilbc | /*
* libjingle
* Copyright 2015 Google Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.webrtc;
import android.opengl.EGL14;
import android.opengl.EGLConfig;
import android.opengl.EGLContext;
import android.opengl.EGLDisplay;
import android.opengl.EGLSurface;
import android.util.Log;
import android.view.Surface;
/**
* Holds EGL state and utility methods for handling an EGLContext, an EGLDisplay, and an EGLSurface.
*/
public final class EglBase {
private static final String TAG = "EglBase";
private static final int EGL14_SDK_VERSION = android.os.Build.VERSION_CODES.JELLY_BEAN_MR1;
private static final int CURRENT_SDK_VERSION = android.os.Build.VERSION.SDK_INT;
// Android-specific extension.
private static final int EGL_RECORDABLE_ANDROID = 0x3142;
private EGLContext eglContext;
private ConfigType configType;
private EGLConfig eglConfig;
private EGLDisplay eglDisplay;
private EGLSurface eglSurface = EGL14.EGL_NO_SURFACE;
public static boolean isEGL14Supported() {
Log.d(TAG, "SDK version: " + CURRENT_SDK_VERSION);
return (CURRENT_SDK_VERSION >= EGL14_SDK_VERSION);
}
// EGLConfig constructor type. Influences eglChooseConfig arguments.
public static enum ConfigType {
// No special parameters.
PLAIN,
// Configures with EGL_SURFACE_TYPE = EGL_PBUFFER_BIT.
PIXEL_BUFFER,
// Configures with EGL_RECORDABLE_ANDROID = 1.
// Discourages EGL from using pixel formats that cannot efficiently be
// converted to something usable by the video encoder.
RECORDABLE
}
// Create root context without any EGLSurface or parent EGLContext. This can be used for branching
// new contexts that share data.
public EglBase() {
this(EGL14.EGL_NO_CONTEXT, ConfigType.PLAIN);
}
// Create a new context with the specified config type, sharing data with sharedContext.
public EglBase(EGLContext sharedContext, ConfigType configType) {
this.configType = configType;
eglDisplay = getEglDisplay();
eglConfig = getEglConfig(eglDisplay, configType);
eglContext = createEglContext(sharedContext, eglDisplay, eglConfig);
}
// Create EGLSurface from the Android Surface.
public void createSurface(Surface surface) {
checkIsNotReleased();
if (configType == ConfigType.PIXEL_BUFFER) {
Log.w(TAG, "This EGL context is configured for PIXEL_BUFFER, but uses regular Surface");
}
if (eglSurface != EGL14.EGL_NO_SURFACE) {
throw new RuntimeException("Already has an EGLSurface");
}
int[] surfaceAttribs = {EGL14.EGL_NONE};
eglSurface = EGL14.eglCreateWindowSurface(eglDisplay, eglConfig, surface, surfaceAttribs, 0);
if (eglSurface == EGL14.EGL_NO_SURFACE) {
throw new RuntimeException("Failed to create window surface");
}
}
// Create dummy 1x1 pixel buffer surface so the context can be made current.
public void createDummyPbufferSurface() {
createPbufferSurface(1, 1);
}
public void createPbufferSurface(int width, int height) {
checkIsNotReleased();
if (configType != ConfigType.PIXEL_BUFFER) {
throw new RuntimeException(
"This EGL context is not configured to use a pixel buffer: " + configType);
}
if (eglSurface != EGL14.EGL_NO_SURFACE) {
throw new RuntimeException("Already has an EGLSurface");
}
int[] surfaceAttribs = {EGL14.EGL_WIDTH, width, EGL14.EGL_HEIGHT, height, EGL14.EGL_NONE};
eglSurface = EGL14.eglCreatePbufferSurface(eglDisplay, eglConfig, surfaceAttribs, 0);
if (eglSurface == EGL14.EGL_NO_SURFACE) {
throw new RuntimeException("Failed to create pixel buffer surface");
}
}
public EGLContext getContext() {
return eglContext;
}
public boolean hasSurface() {
return eglSurface != EGL14.EGL_NO_SURFACE;
}
public int surfaceWidth() {
final int widthArray[] = new int[1];
EGL14.eglQuerySurface(eglDisplay, eglSurface, EGL14.EGL_WIDTH, widthArray, 0);
return widthArray[0];
}
public int surfaceHeight() {
final int heightArray[] = new int[1];
EGL14.eglQuerySurface(eglDisplay, eglSurface, EGL14.EGL_HEIGHT, heightArray, 0);
return heightArray[0];
}
public void releaseSurface() {
if (eglSurface != EGL14.EGL_NO_SURFACE) {
EGL14.eglDestroySurface(eglDisplay, eglSurface);
eglSurface = EGL14.EGL_NO_SURFACE;
}
}
private void checkIsNotReleased() {
if (eglDisplay == EGL14.EGL_NO_DISPLAY || eglContext == EGL14.EGL_NO_CONTEXT
|| eglConfig == null) {
throw new RuntimeException("This object has been released");
}
}
public void release() {
checkIsNotReleased();
releaseSurface();
// Release our context.
EGL14.eglMakeCurrent(
eglDisplay, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_CONTEXT);
EGL14.eglDestroyContext(eglDisplay, eglContext);
EGL14.eglReleaseThread();
EGL14.eglTerminate(eglDisplay);
eglContext = EGL14.EGL_NO_CONTEXT;
eglDisplay = EGL14.EGL_NO_DISPLAY;
eglConfig = null;
}
public void makeCurrent() {
checkIsNotReleased();
if (eglSurface == EGL14.EGL_NO_SURFACE) {
throw new RuntimeException("No EGLSurface - can't make current");
}
if (!EGL14.eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext)) {
throw new RuntimeException("eglMakeCurrent failed");
}
}
public void swapBuffers() {
checkIsNotReleased();
if (eglSurface == EGL14.EGL_NO_SURFACE) {
throw new RuntimeException("No EGLSurface - can't swap buffers");
}
EGL14.eglSwapBuffers(eglDisplay, eglSurface);
}
// Return an EGLDisplay, or die trying.
private static EGLDisplay getEglDisplay() {
EGLDisplay eglDisplay = EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY);
if (eglDisplay == EGL14.EGL_NO_DISPLAY) {
throw new RuntimeException("Unable to get EGL14 display");
}
int[] version = new int[2];
if (!EGL14.eglInitialize(eglDisplay, version, 0, version, 1)) {
throw new RuntimeException("Unable to initialize EGL14");
}
return eglDisplay;
}
// Return an EGLConfig, or die trying.
private static EGLConfig getEglConfig(EGLDisplay eglDisplay, ConfigType configType) {
// Always RGB888, GLES2.
int[] configAttributes = {
EGL14.EGL_RED_SIZE, 8,
EGL14.EGL_GREEN_SIZE, 8,
EGL14.EGL_BLUE_SIZE, 8,
EGL14.EGL_RENDERABLE_TYPE, EGL14.EGL_OPENGL_ES2_BIT,
EGL14.EGL_NONE, 0, // Allocate dummy fields for specific options.
EGL14.EGL_NONE
};
// Fill in dummy fields based on configType.
switch (configType) {
case PLAIN:
break;
case PIXEL_BUFFER:
configAttributes[configAttributes.length - 3] = EGL14.EGL_SURFACE_TYPE;
configAttributes[configAttributes.length - 2] = EGL14.EGL_PBUFFER_BIT;
break;
case RECORDABLE:
configAttributes[configAttributes.length - 3] = EGL_RECORDABLE_ANDROID;
configAttributes[configAttributes.length - 2] = 1;
break;
default:
throw new IllegalArgumentException();
}
EGLConfig[] configs = new EGLConfig[1];
int[] numConfigs = new int[1];
if (!EGL14.eglChooseConfig(
eglDisplay, configAttributes, 0, configs, 0, configs.length, numConfigs, 0)) {
throw new RuntimeException("Unable to find RGB888 " + configType + " EGL config");
}
return configs[0];
}
// Return an EGLConfig, or die trying.
private static EGLContext createEglContext(
EGLContext sharedContext, EGLDisplay eglDisplay, EGLConfig eglConfig) {
int[] contextAttributes = {EGL14.EGL_CONTEXT_CLIENT_VERSION, 2, EGL14.EGL_NONE};
EGLContext eglContext =
EGL14.eglCreateContext(eglDisplay, eglConfig, sharedContext, contextAttributes, 0);
if (eglContext == EGL14.EGL_NO_CONTEXT) {
throw new RuntimeException("Failed to create EGL context");
}
return eglContext;
}
}
| talk/app/webrtc/java/android/org/webrtc/EglBase.java | /*
* libjingle
* Copyright 2015 Google Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.webrtc;
import android.opengl.EGL14;
import android.opengl.EGLConfig;
import android.opengl.EGLContext;
import android.opengl.EGLDisplay;
import android.opengl.EGLSurface;
import android.util.Log;
import android.view.Surface;
/**
* Holds EGL state and utility methods for handling an EGLContext, an EGLDisplay, and an EGLSurface.
*/
public final class EglBase {
private static final String TAG = "EglBase";
private static final int EGL14_SDK_VERSION = android.os.Build.VERSION_CODES.JELLY_BEAN_MR1;
private static final int CURRENT_SDK_VERSION = android.os.Build.VERSION.SDK_INT;
// Android-specific extension.
private static final int EGL_RECORDABLE_ANDROID = 0x3142;
private EGLContext eglContext;
private ConfigType configType;
private EGLConfig eglConfig;
private EGLDisplay eglDisplay;
private EGLSurface eglSurface = EGL14.EGL_NO_SURFACE;
public static boolean isEGL14Supported() {
Log.d(TAG, "SDK version: " + CURRENT_SDK_VERSION);
return (CURRENT_SDK_VERSION >= EGL14_SDK_VERSION);
}
// EGLConfig constructor type. Influences eglChooseConfig arguments.
public static enum ConfigType {
// No special parameters.
PLAIN,
// Configures with EGL_SURFACE_TYPE = EGL_PBUFFER_BIT.
PIXEL_BUFFER,
// Configures with EGL_RECORDABLE_ANDROID = 1.
// Discourages EGL from using pixel formats that cannot efficiently be
// converted to something usable by the video encoder.
RECORDABLE
}
// Create root context without any EGLSurface or parent EGLContext. This can be used for branching
// new contexts that share data.
public EglBase() {
this(EGL14.EGL_NO_CONTEXT, ConfigType.PLAIN);
}
// Create a new context with the specified config type, sharing data with sharedContext.
public EglBase(EGLContext sharedContext, ConfigType configType) {
this.configType = configType;
eglDisplay = getEglDisplay();
eglConfig = getEglConfig(eglDisplay, configType);
eglContext = createEglContext(sharedContext, eglDisplay, eglConfig);
}
// Create EGLSurface from the Android Surface.
public void createSurface(Surface surface) {
checkIsNotReleased();
if (configType == ConfigType.PIXEL_BUFFER) {
Log.w(TAG, "This EGL context is configured for PIXEL_BUFFER, but uses regular Surface");
}
if (eglSurface != EGL14.EGL_NO_SURFACE) {
throw new RuntimeException("Already has an EGLSurface");
}
int[] surfaceAttribs = {EGL14.EGL_NONE};
eglSurface = EGL14.eglCreateWindowSurface(eglDisplay, eglConfig, surface, surfaceAttribs, 0);
if (eglSurface == EGL14.EGL_NO_SURFACE) {
throw new RuntimeException("Failed to create window surface");
}
}
// Create dummy 1x1 pixel buffer surface so the context can be made current.
public void createDummyPbufferSurface() {
createPbufferSurface(1, 1);
}
public void createPbufferSurface(int width, int height) {
checkIsNotReleased();
if (configType != ConfigType.PIXEL_BUFFER) {
throw new RuntimeException(
"This EGL context is not configured to use a pixel buffer: " + configType);
}
if (eglSurface != EGL14.EGL_NO_SURFACE) {
throw new RuntimeException("Already has an EGLSurface");
}
int[] surfaceAttribs = {EGL14.EGL_WIDTH, width, EGL14.EGL_HEIGHT, height, EGL14.EGL_NONE};
eglSurface = EGL14.eglCreatePbufferSurface(eglDisplay, eglConfig, surfaceAttribs, 0);
if (eglSurface == EGL14.EGL_NO_SURFACE) {
throw new RuntimeException("Failed to create pixel buffer surface");
}
}
public EGLContext getContext() {
return eglContext;
}
public boolean hasSurface() {
return eglSurface != EGL14.EGL_NO_SURFACE;
}
public void releaseSurface() {
if (eglSurface != EGL14.EGL_NO_SURFACE) {
EGL14.eglDestroySurface(eglDisplay, eglSurface);
eglSurface = EGL14.EGL_NO_SURFACE;
}
}
private void checkIsNotReleased() {
if (eglDisplay == EGL14.EGL_NO_DISPLAY || eglContext == EGL14.EGL_NO_CONTEXT
|| eglConfig == null) {
throw new RuntimeException("This object has been released");
}
}
public void release() {
checkIsNotReleased();
releaseSurface();
// Release our context.
EGL14.eglMakeCurrent(
eglDisplay, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_CONTEXT);
EGL14.eglDestroyContext(eglDisplay, eglContext);
EGL14.eglReleaseThread();
EGL14.eglTerminate(eglDisplay);
eglContext = EGL14.EGL_NO_CONTEXT;
eglDisplay = EGL14.EGL_NO_DISPLAY;
eglConfig = null;
}
public void makeCurrent() {
checkIsNotReleased();
if (eglSurface == EGL14.EGL_NO_SURFACE) {
throw new RuntimeException("No EGLSurface - can't make current");
}
if (!EGL14.eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext)) {
throw new RuntimeException("eglMakeCurrent failed");
}
}
public void swapBuffers() {
checkIsNotReleased();
if (eglSurface == EGL14.EGL_NO_SURFACE) {
throw new RuntimeException("No EGLSurface - can't swap buffers");
}
EGL14.eglSwapBuffers(eglDisplay, eglSurface);
}
// Return an EGLDisplay, or die trying.
private static EGLDisplay getEglDisplay() {
EGLDisplay eglDisplay = EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY);
if (eglDisplay == EGL14.EGL_NO_DISPLAY) {
throw new RuntimeException("Unable to get EGL14 display");
}
int[] version = new int[2];
if (!EGL14.eglInitialize(eglDisplay, version, 0, version, 1)) {
throw new RuntimeException("Unable to initialize EGL14");
}
return eglDisplay;
}
// Return an EGLConfig, or die trying.
private static EGLConfig getEglConfig(EGLDisplay eglDisplay, ConfigType configType) {
// Always RGB888, GLES2.
int[] configAttributes = {
EGL14.EGL_RED_SIZE, 8,
EGL14.EGL_GREEN_SIZE, 8,
EGL14.EGL_BLUE_SIZE, 8,
EGL14.EGL_RENDERABLE_TYPE, EGL14.EGL_OPENGL_ES2_BIT,
EGL14.EGL_NONE, 0, // Allocate dummy fields for specific options.
EGL14.EGL_NONE
};
// Fill in dummy fields based on configType.
switch (configType) {
case PLAIN:
break;
case PIXEL_BUFFER:
configAttributes[configAttributes.length - 3] = EGL14.EGL_SURFACE_TYPE;
configAttributes[configAttributes.length - 2] = EGL14.EGL_PBUFFER_BIT;
break;
case RECORDABLE:
configAttributes[configAttributes.length - 3] = EGL_RECORDABLE_ANDROID;
configAttributes[configAttributes.length - 2] = 1;
break;
default:
throw new IllegalArgumentException();
}
EGLConfig[] configs = new EGLConfig[1];
int[] numConfigs = new int[1];
if (!EGL14.eglChooseConfig(
eglDisplay, configAttributes, 0, configs, 0, configs.length, numConfigs, 0)) {
throw new RuntimeException("Unable to find RGB888 " + configType + " EGL config");
}
return configs[0];
}
// Return an EGLConfig, or die trying.
private static EGLContext createEglContext(
EGLContext sharedContext, EGLDisplay eglDisplay, EGLConfig eglConfig) {
int[] contextAttributes = {EGL14.EGL_CONTEXT_CLIENT_VERSION, 2, EGL14.EGL_NONE};
EGLContext eglContext =
EGL14.eglCreateContext(eglDisplay, eglConfig, sharedContext, contextAttributes, 0);
if (eglContext == EGL14.EGL_NO_CONTEXT) {
throw new RuntimeException("Failed to create EGL context");
}
return eglContext;
}
}
| Android EglBase: Add helper functions to query the surface size
BUG=webrtc:4742
[email protected]
Review URL: https://codereview.webrtc.org/1299543004 .
Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#9739}
| talk/app/webrtc/java/android/org/webrtc/EglBase.java | Android EglBase: Add helper functions to query the surface size | <ide><path>alk/app/webrtc/java/android/org/webrtc/EglBase.java
<ide> return eglSurface != EGL14.EGL_NO_SURFACE;
<ide> }
<ide>
<add> public int surfaceWidth() {
<add> final int widthArray[] = new int[1];
<add> EGL14.eglQuerySurface(eglDisplay, eglSurface, EGL14.EGL_WIDTH, widthArray, 0);
<add> return widthArray[0];
<add> }
<add>
<add> public int surfaceHeight() {
<add> final int heightArray[] = new int[1];
<add> EGL14.eglQuerySurface(eglDisplay, eglSurface, EGL14.EGL_HEIGHT, heightArray, 0);
<add> return heightArray[0];
<add> }
<add>
<ide> public void releaseSurface() {
<ide> if (eglSurface != EGL14.EGL_NO_SURFACE) {
<ide> EGL14.eglDestroySurface(eglDisplay, eglSurface); |
|
JavaScript | mit | 6f7db4ecc368a6bcbb313a7e3ea025a4526e9505 | 0 | roychoo/upload-invoices,anthonyraymond/react-redux-starter-kit,febobo/react-redux-start,bingomanatee/ridecell,nkostelnik/blaiseclicks,z81/PolarOS_Next,flftfqwxf/react-redux-starter-kit,dmassaneiro/integracao-continua,cyrilf/ecokit,kevinchiu/react-redux-starter-kit,levkus/react-overcounters2,dapplab/babel-client,flftfqwxf/react-redux-starter-kit,JohanGustafsson91/React-JWT-Authentication-Redux-Router,hustlrb/yjbAdmin,SteveHoggNZ/Choice-As,samrocksc/lol-app,lencioni/gift-thing,SawyerHood/pomodoro-redux,j3dimaster/CircleCi-test,terakilobyte/react-redux-starter-kit,baopham/react-laravel-generator,oliveirafabio/wut-blog,gohup/react_testcase,somus/react-redux-starter-kit,SHBailey/echo-mvp,duongthien291291/react-redux-starter-kit-munchery-theme,TestKitt/TestKittUI,miyanokomiya/b-net,tonyxiao/segment-debugger,willthefirst/book-buddy,Anomen/universal-react-redux-starter-kit,fhassa/my-react-redux-start-ki,yangbin1994/react-redux-starter-kit,stefanwille/react-gameoflife,daimagine/gh-milestone,terakilobyte/terakilobyte.github.io,cuitianze/react-starter-kit,chozandrias76/responsive-sesame-test,okmttdhr/setsuna-firebase,terakilobyte/rumbl_front,raineroviir/SUWProject,NguyenManh94/circle-ci,baronkwan/ig_clone,josedab/react-redux-i18n-starter-kit,janoist1/route-share,hustlrb/yjbAdmin,huangc28/palestine,levsero/planning-app-ui,Stas-Buzunko/cyber-school,kevinchiu/react-redux-starter-kit,Dimitrievskislavcho/funfunfuncReduxCI,KirillSkomarovskiy/light-it,ptim/react-redux-starter-kit,MingYinLv/blog-admin,larsdolvik/portfolio,rbhat0987/funfunapp,flftfqwxf/react-redux-starter-kit,ptim/react-redux-starter-kit,stevecrozz/test-directory-client,Sixtease/MakonReact,roychoo/upload-invoices,gReis89/sam-ovens-website,k2data/react-redux-starter-kit,pawelniewie/czy-to-jest-paleo,vasekric/regrinder,codingarchitect/react-counter-pair,NguyenManh94/circle-ci,dfalling/todo,jhash/jhash,shyr1punk/schedule-ui,Gouthamve/BINS-FRONT,SHBailey/echo-mvp,rwenor/react-ci-app,jwoods1/xpress,learningnewthings/funfunapp,armaanshah96/lunchbox,hatton/BloomReact,cuitianze/react-starter-kit,pawelniewie/zen,lencioni/gift-thing,weixing2014/iTodo,youdeshi/single-page-app-best-practice-client,techcoop/techcoop.group,3a-classic/score,jarirepo/simple-ci-test-app,rwenor/react-ci-app,Vaishali512/mysampleapp,Stas-Buzunko/cyber-school,Edmondton/weather-forecasts,damirv/react-redux-starter-kit,KNMI/GeoWeb-FrontEnd,Ryann10/hci_term,techcoop/techcoop.group,chozandrias76/responsive-sesame-test,abachuk/fullbag-react-redux-dashboard,anara123/react-redux-starter,stefanwille/react-todo,julianvmodesto/tweetstat,wilwong89/didactic-web-game,guileen/react-forum,thanhiro/techmatrix,Dylan1312/pool-elo,gohup/react_testcase,davezuko/react-redux-starter-kit,shuliang/ReactConventionDemo,flftfqwxf/react-redux-starter-kit,bhoomit/formula-editor,wswoodruff/strangeluv-native,dmassaneiro/integracao-continua,shuliang/ReactConventionDemo,michaelgu95/ZltoReduxCore,k2data/react-redux-starter-kit,dapplab/babel-client,Gouthamve/BINS-FRONT,GreGGus/MIMApp,nivas8292/myapp,longseespace/quickflix,neverfox/react-redux-starter-kit,julianvmodesto/tweetstat,vasekric/regrinder,VladGne/Practice2017,cohenpts/CircleCITut,sljuka/buzzler-ui,JuntoLabs/Poetry,billdevcode/spaceship-emporium,flftfqwxf/react-redux-starter-kit,pawelniewie/presento,simors/yjbAdmin,kolyaka006/imaginarium,longseespace/quickflix,GreGGus/MIMApp,far-fetched/kiwi,gReis89/sam-ovens-website,Croissong/nussnougat,terakilobyte/rumbl_front,diMosellaAtWork/GeoWeb-FrontEnd,dictyBase/Dicty-Stock-Center,jwoods1/xpress,RequestTimeout408/alba-task,dingyoujian/webpack-react-demo,davezuko/wirk-starter,PassaP/passap-fronend,aibolik/my-todomvc,baronkwan/ig_clone,paulmorar/jxpectapp,haozeng/react-redux-filter,TestKitt/TestKittUI,lf2941270/react-zhihu-daily,PalmasLab/palmasplay,jeffaustin81/cropcompass-ui,Alexandre-Herve/react-redux-starter-kit,octavioturra/petpatinhas-react,gabrielmf/SIR-EDU-2.0,arseneyr/yt-party,findinstore/instore-webapp,michaelgu95/ZltoReduxCore,octavioturra/petpatinhas-react,pawelniewie/czy-to-jest-paleo,andreasnc/summer-project-tasks-2017,BigRoomStudios/strangeluv,eunvanz/flowerhada,atomdmac/roc-game-dev-gallery,tonyxiao/segment-debugger,seespace/dota2assistant,corbinpage/react-play,theosherry/react-hangman,kolyaka006/imaginarium,armaanshah96/lunchbox,kolpav/react-redux-starter-kit,stefanwille/react-gameoflife,jhash/jhash,maartenplieger/GeoWeb-FrontEnd,huangc28/palestine,rui19921122/StationTransformBrowserClient,VinodJayasinghe/CircleCI,roslaneshellanoo/react-redux-tutorial,danieljwest/ExamGenerator,flftfqwxf/react-redux-starter-kit,jenyckee/midi-redux,davezuko/react-redux-starter-kit,alukach/react-map-app,bhj/karaoke-forever,flftfqwxf/react-redux-starter-kit,dkushner/ArborJs-Playground,rbhat0987/funfunapp,dkushner/ArborJs-Playground,okmttdhr/hoppee-firebase,nkostelnik/blaiseclicks,Croissong/sntModelViewer,alukach/react-map-app,raineroviir/SUWProject,loliver/anz-code-test,flftfqwxf/react-redux-starter-kit,stranbury/react-miuus,daimagine/gh-milestone,Edmondton/weather-forecasts,z81/PolarOS_Next,oliveirafabio/wut-blog,terakilobyte/react-redux-starter-kit,corydolphin/kanban-github,commute-sh/commute-web,larsdolvik/portfolio,SawyerHood/pomodoro-redux,rui19921122/StationTransformBrowserClient,findinstore/instore-webapp,PalmasLab/palmasplay,stefanwille/react-todo,B1ll1/CircleCI,dingyoujian/webpack-react-demo,KirillSkomarovskiy/light-it,chozandrias76/responsive-sesame-test,madsid/spz,paulmorar/jxpectapp,houston88/housty-home-react,eordano/sherlock,tkshi/q,guileen/react-forum,lodelestra/SWClermont_2016,stevecrozz/test-directory-client,nivas8292/myapp,learningnewthings/funfunapp,sonofbjorn/circle-ci-test,flftfqwxf/react-redux-starter-kit,flftfqwxf/react-redux-starter-kit,haozeng/react-redux-filter,3a-classic/score,neverfox/react-redux-starter-kit,terakilobyte/terakilobyte.github.io,shtefanntz/cw,dictyBase/Dicty-Stock-Center,cyrilf/ecokit,baopham/react-laravel-generator,sonofbjorn/circle-ci-test,corbinpage/react-play,przeor/ReactC,theosherry/react-hangman,adrienhobbs/redux-glow,davezuko/wirk-starter,ethcards/react-redux-starter-kit,anthonyraymond/react-redux-starter-kit,tkshi/q,crssn/funfunapp,okmttdhr/hoppee-firebase,maartenlterpstra/GeoWeb-FrontEnd,codingarchitect/react-counter-pair,clayne11/react-popover-lifecycle-bug,Sixtease/MakonReact,flftfqwxf/react-redux-starter-kit,ayal/albi,dannyrdalton/example_signup_flow,shyr1punk/schedule-ui,jarirepo/simple-ci-test-app,seespace/dota2assistant,maartenlterpstra/GeoWeb-FrontEnd,andrewdever/boardlife,pachoulie/projects,rui19921122/StationTransformBrowserClient,theosherry/mx_pl,adrienhobbs/redux-glow,stranbury/react-miuus,chozandrias76/responsive-sesame-test,andrewdever/boardlife,flftfqwxf/react-redux-starter-kit,gribilly/react-redux-starter-kit,nodepie/react-redux-starter-kit,z0d14c/system-performance-viewer,madsid/spz,ethcards/react-redux-starter-kit,damirv/react-redux-starter-kit,Dimitrievskislavcho/funfunfuncReduxCI,j3dimaster/CircleCi-test,bhoomit/formula-editor,JuntoLabs/Poetry,atomdmac/roc-game-dev-gallery,Sixtease/MakonReact,juanda99/react-redux-material-ui,JohanGustafsson91/React-JWT-Authentication-Redux-Router,simors/yjbAdmin,pptang/ggm,warcraftlfg/warcrafthub-client,miyanokomiya/b-net,febobo/react-redux-start,weixing2014/iTodo,treeforever/voice-recognition-photo-gallary,danieljwest/ExamGenerator,jaronoff97/listmkr,octavioturra/pet-patinhas-react,janoist1/route-share,kolpav/react-redux-starter-kit,B1ll1/CircleCI,warcraftlfg/warcrafthub-client,andreasnc/summer-project-tasks-2017,dannyrdalton/example_signup_flow,fhassa/my-react-redux-start-ki,shtefanntz/cw,flftfqwxf/react-redux-starter-kit,janoist1/universal-react-redux-starter-kit,jakehm/mapgame2,juanda99/react-redux-material-ui,tylerbarabas/bbTools,roslaneshellanoo/react-redux-tutorial,pachoulie/projects,gabrielmf/SIR-EDU-2.0,przeor/ReactC,samrocksc/lol-app,abachuk/fullbag-react-redux-dashboard,eordano/sherlock,dfalling/todo,Dylan1312/pool-elo,rrlk/se2present,MingYinLv/blog-admin,duongthien291291/react-redux-starter-kit-munchery-theme,Vaishali512/mysampleapp,jaronoff97/listmkr,flftfqwxf/react-redux-starter-kit,kerwynrg/company-crud-app,clayne11/react-popover-lifecycle-bug,ahthamrin/kbri-admin2,pptang/ggm,eunvanz/handpokemon2,RequestTimeout408/alba-task,juanda99/arasaac,lf2941270/react-zhihu-daily,aibolik/my-todomvc,bingomanatee/ridecell,willthefirst/book-buddy,pawelniewie/zen,BigRoomStudios/strangeluv,jakehm/mapgame2,cohenpts/CircleCITut,arseneyr/yt-party,Alexandre-Herve/react-redux-starter-kit,flftfqwxf/react-redux-starter-kit,billdevcode/spaceship-emporium,z0d14c/system-performance-viewer,gribilly/react-redux-starter-kit,thanhiro/techmatrix,pawelniewie/czy-to-jest-paleo,wilwong89/didactic-web-game,commute-sh/commute-web,rickyduck/pp-frontend,Croissong/nussnougat,jhardin293/style-guide-manager,sljuka/buzzler-ui,crssn/funfunapp,jeffaustin81/cropcompass-ui,popaulina/grackle,rrlk/se2present,rickyduck/pp-frontend,longseespace/quickflix,Croissong/sntModelViewer,matteoantoci/expense-tracker,okmttdhr/setsuna-firebase,flftfqwxf/react-redux-starter-kit,pawelniewie/presento,filucian/funfunapp,dictyBase/Dicty-Stock-Center,ayal/albi,far-fetched/kiwi,levkus/react-overcounters2,KNMI/GeoWeb-FrontEnd,kerwynrg/company-crud-app,filucian/funfunapp,ahthamrin/kbri-admin2,maartenlterpstra/GeoWeb-FrontEnd,diMosellaAtWork/GeoWeb-FrontEnd,popaulina/grackle,octavioturra/pet-patinhas-react,OlivierWinsemius/circleci_test,jenyckee/midi-redux,jhardin293/style-guide-manager,KNMI/GeoWeb-FrontEnd,corydolphin/kanban-github,lodelestra/SWClermont_2016,juanda99/arasaac,josedab/react-redux-i18n-starter-kit,EngineerMostafa/CircleCI,PassaP/passap-fronend,parkgaram/solidware-mini-project,matteoantoci/expense-tracker,okmttdhr/aupa,eunvanz/flowerhada,SteveHoggNZ/Choice-As,somus/react-redux-starter-kit,anara123/react-redux-starter,flftfqwxf/react-redux-starter-kit,tylerbarabas/bbTools,eunvanz/handpokemon2,levsero/planning-app-ui,loliver/anz-code-test,okmttdhr/aupa,flftfqwxf/react-redux-starter-kit,VladGne/Practice2017,VinodJayasinghe/CircleCI,jaronoff97/listmkr,ahthamrin/kbri-admin2,EngineerMostafa/CircleCI,yangbin1994/react-redux-starter-kit,theosherry/mx_pl,bhj/karaoke-forever,eunvanz/flowerhada,OlivierWinsemius/circleci_test,hatton/BloomReact,flftfqwxf/react-redux-starter-kit,z0d14c/system-performance-viewer,youdeshi/single-page-app-best-practice-client,maartenplieger/GeoWeb-FrontEnd,Ryann10/hci_term,treeforever/voice-recognition-photo-gallary,houston88/housty-home-react,piu130/react-redux-gpa-app,nodepie/react-redux-starter-kit,parkgaram/solidware-mini-project | import React from 'react';
import ReactDOM from 'react-dom';
import Root from './containers/Root';
import configureStore from './stores';
const target = document.getElementById('root');
const store = configureStore(window.__INITIAL_STATE__, __DEBUG__);
const node = (
<Root store={store}
debug={__DEBUG__}
debugExternal={__DEBUG_NW__} />
);
ReactDOM.render(node, target);
| src/index.js | import React from 'react';
import ReactDOM from 'react-dom';
import Root from './containers/Root';
import configureStore from './stores';
const target = document.getElementById('root');
const store = configureStore(window.__INITIAL_STATE__, __DEBUG__);
const node = (
<Root store={store}
debug={__DEBUG__}
debugExternal={__DEBUG_NW__} />
);
ReactDOM.render(node, target);
| fix(app): cleanup import statements in app bootstrap
| src/index.js | fix(app): cleanup import statements in app bootstrap | <ide><path>rc/index.js
<del>import React from 'react';
<del>import ReactDOM from 'react-dom';
<del>import Root from './containers/Root';
<del>import configureStore from './stores';
<add>import React from 'react';
<add>import ReactDOM from 'react-dom';
<add>import Root from './containers/Root';
<add>import configureStore from './stores';
<ide>
<ide> const target = document.getElementById('root');
<ide> const store = configureStore(window.__INITIAL_STATE__, __DEBUG__); |
|
Java | apache-2.0 | d0d0cc90b857bc0f286f8046bdb7673771377dee | 0 | rapidoid/rapidoid,rapidoid/rapidoid,rapidoid/rapidoid,rapidoid/rapidoid | package org.rapidoid.model.impl;
/*
* #%L
* rapidoid-model
* %%
* Copyright (C) 2014 - 2015 Nikolche Mihajlovski and contributors
* %%
* 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%
*/
import org.rapidoid.annotation.Authors;
import org.rapidoid.annotation.Since;
import org.rapidoid.cls.Cls;
import org.rapidoid.model.Item;
import org.rapidoid.var.impl.AbstractVar;
@Authors("Nikolche Mihajlovski")
@Since("2.0.0")
public class ItemPropertyVar<T> extends AbstractVar<T> {
private static final long serialVersionUID = -1208784804459879580L;
private final Item item;
private final String property;
public ItemPropertyVar(String name, Item item, String property, T initValue) {
super(name);
this.item = item;
this.property = property;
if (initValue != null) {
set(initValue);
}
}
@Override
public T get() {
return item.get(property);
}
@Override
public void set(T value) {
T oldValue = get();
if (oldValue != null) {
item.set(property, Cls.convert(value, oldValue.getClass()));
} else {
item.set(property, value);
}
}
}
| rapidoid-model/src/main/java/org/rapidoid/model/impl/ItemPropertyVar.java | package org.rapidoid.model.impl;
/*
* #%L
* rapidoid-model
* %%
* Copyright (C) 2014 - 2015 Nikolche Mihajlovski and contributors
* %%
* 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%
*/
import org.rapidoid.annotation.Authors;
import org.rapidoid.annotation.Since;
import org.rapidoid.model.Item;
import org.rapidoid.var.impl.AbstractVar;
@Authors("Nikolche Mihajlovski")
@Since("2.0.0")
public class ItemPropertyVar<T> extends AbstractVar<T> {
private static final long serialVersionUID = -1208784804459879580L;
private final Item item;
private final String property;
public ItemPropertyVar(String name, Item item, String property, T initValue) {
super(name);
this.item = item;
this.property = property;
if (initValue != null) {
set(initValue);
}
}
@Override
public T get() {
return item.get(property);
}
@Override
public void set(T value) {
item.set(property, value);
}
}
| Preserving the value type on data binding.
| rapidoid-model/src/main/java/org/rapidoid/model/impl/ItemPropertyVar.java | Preserving the value type on data binding. | <ide><path>apidoid-model/src/main/java/org/rapidoid/model/impl/ItemPropertyVar.java
<ide>
<ide> import org.rapidoid.annotation.Authors;
<ide> import org.rapidoid.annotation.Since;
<add>import org.rapidoid.cls.Cls;
<ide> import org.rapidoid.model.Item;
<ide> import org.rapidoid.var.impl.AbstractVar;
<ide>
<ide>
<ide> @Override
<ide> public void set(T value) {
<del> item.set(property, value);
<add> T oldValue = get();
<add>
<add> if (oldValue != null) {
<add> item.set(property, Cls.convert(value, oldValue.getClass()));
<add> } else {
<add> item.set(property, value);
<add> }
<ide> }
<ide>
<ide> } |
|
JavaScript | mpl-2.0 | 4365ac483657081b18acc5624b550bfc0ba84d7e | 0 | AlexanderElias/oxe,AlexanderElias/jenie,AlexanderElias/jenie,AlexanderElias/oxe |
/*
TODO:
sort reverse
test array methods
figure out a way to not update removed items
*/
let Observer = {
splice () {
const self = this;
let startIndex = arguments[0];
let deleteCount = arguments[1];
let addCount = arguments.length > 2 ? arguments.length - 2 : 0;
if (typeof startIndex !== 'number' || typeof deleteCount !== 'number') {
return [];
}
// handle negative startIndex
if (startIndex < 0) {
startIndex = self.length + startIndex;
startIndex = startIndex > 0 ? startIndex : 0;
} else {
startIndex = startIndex < self.length ? startIndex : self.length;
}
// handle negative deleteCount
if (deleteCount < 0) {
deleteCount = 0;
} else if (deleteCount > (self.length - startIndex)) {
deleteCount = self.length - startIndex;
}
let totalCount = self.$meta.length;
let key, index, value, updateCount;
let argumentIndex = 2;
let argumentsCount = arguments.length - argumentIndex;
let result = self.slice(startIndex, deleteCount);
updateCount = (totalCount - 1) - startIndex;
let promises = [];
if (updateCount > 0) {
index = startIndex;
while (updateCount--) {
key = index++;
if (argumentsCount && argumentIndex < argumentsCount) {
value = arguments[argumentIndex++];
} else {
value = self.$meta[index];
}
self.$meta[key] = Observer.create(value, self.$meta.listener, self.$meta.path + key);
promises.push(self.$meta.listener.bind(null, self.$meta[key], self.$meta.path + key, key));
}
}
if (addCount > 0) {
promises.push(self.$meta.listener.bind(null, self.length + addCount, self.$meta.path.slice(0, -1), 'length'));
while (addCount--) {
key = self.length;
if (key in this === false) {
Object.defineProperty(this, key, Observer.descriptor(key));
}
self.$meta[key] = Observer.create(arguments[argumentIndex++], self.$meta.listener, self.$meta.path + key);
promises.push(self.$meta.listener.bind(null, self.$meta[key], self.$meta.path + key, key));
}
}
if (deleteCount > 0) {
promises.push(self.$meta.listener.bind(null, self.length - deleteCount, self.$meta.path.slice(0, -1), 'length'));
while (deleteCount--) {
self.$meta.length--;
self.length--;
key = self.length;
promises.push(self.$meta.listener.bind(null, undefined, self.$meta.path + key, key));
}
}
promises.reduce(function (promise, item) {
return promise.then(item);
}, Promise.resolve()).catch(console.error);
return result;
},
arrayProperties () {
const self = this;
return {
push: {
value: function () {
if (!arguments.length) return this.length;
for (let i = 0, l = arguments.length; i < l; i++) {
self.splice.call(this, this.length, 0, arguments[i]);
}
return this.length;
}
},
unshift: {
value: function () {
if (!arguments.length) return this.length;
for (let i = 0, l = arguments.length; i < l; i++) {
self.splice.call(this, 0, 0, arguments[i]);
}
return this.length;
}
},
pop: {
value: function () {
if (!this.length) return;
return self.splice.call(this, this.length-1, 1);
}
},
shift: {
value: function () {
if (!this.length) return;
return self.splice.call(this, 0, 1);
}
},
splice: {
value: self.splice
}
};
},
objectProperties () {
const self = this;
return {
$get: {
value: function (key) {
return this.$meta[key];
}
},
$set: {
value: function (key, value) {
if (value !== this.$meta[key]) {
if (key in this === false) {
Object.defineProperty(this, key, self.descriptor(key));
}
this.$meta[key] = self.create(value, this.$meta.listener, this.$meta.path + key);
this.$meta.listener(this.$meta[key], this.$meta.path + key, key, this);
}
}
},
$remove: {
value: function (key) {
if (key in this) {
if (this.constructor === Array) {
return self.splice.call(this, key, 1);
} else {
let result = this[key];
delete this.$meta[key];
delete this[key];
this.$meta.listener(undefined, this.$meta.path + key, key);
return result;
}
}
}
}
};
},
descriptor (key) {
const self = this;
return {
enumerable: true,
configurable: true,
get: function () {
return this.$meta[key];
},
set: function (value) {
if (value !== this.$meta[key]) {
// self.destroy(this[key], value);
this.$meta[key] = self.create(value, this.$meta.listener, this.$meta.path + key);
this.$meta.listener(this.$meta[key], this.$meta.path + key, key, this);
}
}
};
},
// destroy (target, source) {
//
// if (!target || target.constructor !== Object && target.constructor !== Array) {
// return;
// }
//
// const type = target.constructor;
//
// if (type === Array) {
// const data = source && source.constructor === Array ? source : [];
//
// while (target.length > data.length) {
// console.log(target.length - 1);
// // target.$remove(target.length - 1);
// target.pop();
// }
//
// } else if (type === Object) {
// const data = source && source.constructor === Object ? source : {};
//
// for (const key in target) {
// if (key in data === false) {
// target.$remove(key);
// }
// }
//
// }
//
// },
create (source, listener, path) {
const self = this;
if (!source || source.constructor !== Object && source.constructor !== Array) {
return source;
}
path = path ? path + '.' : '';
const type = source.constructor;
const target = source.constructor();
const descriptors = {};
descriptors.$meta = {
value: source.constructor()
};
descriptors.$meta.value.path = path;
descriptors.$meta.value.listener = listener;
if (type === Array) {
for (let key = 0, length = source.length; key < length; key++) {
descriptors.$meta.value[key] = this.create(source[key], listener, path + key);
descriptors[key] = this.descriptor(key);
}
}
if (type === Object) {
for (let key in source) {
descriptors.$meta.value[key] = this.create(source[key], listener, path + key);
descriptors[key] = this.descriptor(key);
}
}
Object.defineProperties(target, descriptors);
Object.defineProperties(target, this.objectProperties(source, listener, path));
if (type === Array) {
Object.defineProperties(target, this.arrayProperties(source, listener, path));
}
return target;
}
};
export default Observer;
| src/observer.js |
/*
TODO:
sort reverse
test array methods
figure out a way to not update removed items
*/
let Observer = {
splice () {
const self = this;
let startIndex = arguments[0];
let deleteCount = arguments[1];
let addCount = arguments.length > 2 ? arguments.length - 2 : 0;
if (typeof startIndex !== 'number' || typeof deleteCount !== 'number') {
return [];
}
// handle negative startIndex
if (startIndex < 0) {
startIndex = self.length + startIndex;
startIndex = startIndex > 0 ? startIndex : 0;
} else {
startIndex = startIndex < self.length ? startIndex : self.length;
}
// handle negative deleteCount
if (deleteCount < 0) {
deleteCount = 0;
} else if (deleteCount > (self.length - startIndex)) {
deleteCount = self.length - startIndex;
}
let totalCount = self.$meta.length;
let key, index, value, updateCount;
let argumentIndex = 2;
let argumentsCount = arguments.length - argumentIndex;
let result = self.slice(startIndex, deleteCount);
updateCount = (totalCount - 1) - startIndex;
let promises = [];
if (updateCount > 0) {
index = startIndex;
while (updateCount--) {
key = index++;
if (argumentsCount && argumentIndex < argumentsCount) {
value = arguments[argumentIndex++];
} else {
value = self.$meta[index];
}
self.$meta[key] = Observer.create(value, self.$meta.listener, self.$meta.path + key);
promises.push(self.$meta.listener.bind(null, self.$meta[key], self.$meta.path + key, key));
}
}
if (addCount > 0) {
promises.push(self.$meta.listener.bind(null, self.length + addCount, self.$meta.path.slice(0, -1), 'length'));
while (addCount--) {
key = self.length;
self.$meta[key] = Observer.create(arguments[argumentIndex++], self.$meta.listener, self.$meta.path + key);
Observer.defineProperty(self, key);
promises.push(self.$meta.listener.bind(null, self.$meta[key], self.$meta.path + key, key));
}
}
if (deleteCount > 0) {
promises.push(self.$meta.listener.bind(null, self.length - deleteCount, self.$meta.path.slice(0, -1), 'length'));
while (deleteCount--) {
self.$meta.length--;
self.length--;
key = self.length;
promises.push(self.$meta.listener.bind(null, undefined, self.$meta.path + key, key));
}
}
promises.reduce(function (promise, item) {
return promise.then(item);
}, Promise.resolve()).catch(console.error);
return result;
},
arrayProperties () {
const self = this;
return {
push: {
value: function () {
if (!arguments.length) return this.length;
for (let i = 0, l = arguments.length; i < l; i++) {
self.splice.call(this, this.length, 0, arguments[i]);
}
return this.length;
}
},
unshift: {
value: function () {
if (!arguments.length) return this.length;
for (let i = 0, l = arguments.length; i < l; i++) {
self.splice.call(this, 0, 0, arguments[i]);
}
return this.length;
}
},
pop: {
value: function () {
if (!this.length) return;
return self.splice.call(this, this.length-1, 1);
}
},
shift: {
value: function () {
if (!this.length) return;
return self.splice.call(this, 0, 1);
}
},
splice: {
value: self.splice
}
};
},
objectProperties () {
const self = this;
return {
$get: {
value: function (key) {
return this.$meta[key];
}
},
$set: {
value: function (key, value) {
if (value !== this.$meta[key]) {
self.defineProperty(this, key);
this.$meta[key] = self.create(value, this.$meta.listener, this.$meta.path + key);
this.$meta.listener(this[key], this.$meta.path + key, key, this);
}
}
},
$remove: {
value: function (key) {
if (key in this) {
if (this.constructor === Array) {
return self.splice.call(this, key, 1);
} else {
let result = this[key];
delete this.$meta[key];
delete this[key];
this.$meta.listener(undefined, this.$meta.path + key, key);
return result;
}
}
}
}
};
},
property (key) {
const self = this;
return {
enumerable: true,
configurable: true,
get: function () {
return this.$meta[key];
},
set: function (value) {
if (value !== this.$meta[key]) {
this.$meta[key] = self.create(value, this.$meta.listener, this.$meta.path + key);
this.$meta.listener(this[key], this.$meta.path + key, key, this);
}
}
};
},
defineProperty (data, key) {
return Object.defineProperty(data, key, this.property(key));
},
create (source, listener, path) {
const self = this;
if (!source || source.constructor !== Object && source.constructor !== Array) {
return source;
}
path = path ? path + '.' : '';
let key, length;
let type = source.constructor;
let target = source.constructor();
let properties = source.constructor();
properties.$meta = {
value: source.constructor()
};
properties.$meta.value.path = path;
properties.$meta.value.listener = listener;
if (type === Array) {
for (key = 0, length = source.length; key < length; key++) {
properties.$meta.value[key] = self.create(source[key], listener, path + key);
properties[key] = self.property(key);
}
let arrayProperties = self.arrayProperties();
for (key in arrayProperties) {
properties[key] = arrayProperties[key];
}
}
if (type === Object) {
for (key in source) {
properties.$meta.value[key] = self.create(source[key], listener, path + key);
properties[key] = self.property(key);
}
}
let objectProperties = self.objectProperties();
for (key in objectProperties) {
properties[key] = objectProperties[key];
}
return Object.defineProperties(target, properties);
}
};
export default Observer;
| bug fixes and improvments
| src/observer.js | bug fixes and improvments | <ide><path>rc/observer.js
<ide>
<ide> while (addCount--) {
<ide> key = self.length;
<add>
<add> if (key in this === false) {
<add> Object.defineProperty(this, key, Observer.descriptor(key));
<add> }
<add>
<ide> self.$meta[key] = Observer.create(arguments[argumentIndex++], self.$meta.listener, self.$meta.path + key);
<del> Observer.defineProperty(self, key);
<ide> promises.push(self.$meta.listener.bind(null, self.$meta[key], self.$meta.path + key, key));
<ide>
<ide> }
<ide> $set: {
<ide> value: function (key, value) {
<ide> if (value !== this.$meta[key]) {
<del> self.defineProperty(this, key);
<add>
<add> if (key in this === false) {
<add> Object.defineProperty(this, key, self.descriptor(key));
<add> }
<add>
<ide> this.$meta[key] = self.create(value, this.$meta.listener, this.$meta.path + key);
<del> this.$meta.listener(this[key], this.$meta.path + key, key, this);
<add> this.$meta.listener(this.$meta[key], this.$meta.path + key, key, this);
<ide> }
<ide> }
<ide> },
<ide> };
<ide> },
<ide>
<del> property (key) {
<add> descriptor (key) {
<ide> const self = this;
<ide>
<ide> return {
<ide> },
<ide> set: function (value) {
<ide> if (value !== this.$meta[key]) {
<add> // self.destroy(this[key], value);
<ide> this.$meta[key] = self.create(value, this.$meta.listener, this.$meta.path + key);
<del> this.$meta.listener(this[key], this.$meta.path + key, key, this);
<del> }
<del> }
<del> };
<del> },
<del>
<del> defineProperty (data, key) {
<del> return Object.defineProperty(data, key, this.property(key));
<del> },
<add> this.$meta.listener(this.$meta[key], this.$meta.path + key, key, this);
<add> }
<add> }
<add> };
<add> },
<add>
<add> // destroy (target, source) {
<add> //
<add> // if (!target || target.constructor !== Object && target.constructor !== Array) {
<add> // return;
<add> // }
<add> //
<add> // const type = target.constructor;
<add> //
<add> // if (type === Array) {
<add> // const data = source && source.constructor === Array ? source : [];
<add> //
<add> // while (target.length > data.length) {
<add> // console.log(target.length - 1);
<add> // // target.$remove(target.length - 1);
<add> // target.pop();
<add> // }
<add> //
<add> // } else if (type === Object) {
<add> // const data = source && source.constructor === Object ? source : {};
<add> //
<add> // for (const key in target) {
<add> // if (key in data === false) {
<add> // target.$remove(key);
<add> // }
<add> // }
<add> //
<add> // }
<add> //
<add> // },
<ide>
<ide> create (source, listener, path) {
<ide> const self = this;
<ide>
<ide> path = path ? path + '.' : '';
<ide>
<del> let key, length;
<del> let type = source.constructor;
<del> let target = source.constructor();
<del> let properties = source.constructor();
<del>
<del> properties.$meta = {
<add> const type = source.constructor;
<add> const target = source.constructor();
<add> const descriptors = {};
<add>
<add> descriptors.$meta = {
<ide> value: source.constructor()
<ide> };
<ide>
<del> properties.$meta.value.path = path;
<del> properties.$meta.value.listener = listener;
<add> descriptors.$meta.value.path = path;
<add> descriptors.$meta.value.listener = listener;
<ide>
<ide> if (type === Array) {
<del>
<del> for (key = 0, length = source.length; key < length; key++) {
<del> properties.$meta.value[key] = self.create(source[key], listener, path + key);
<del> properties[key] = self.property(key);
<del> }
<del>
<del> let arrayProperties = self.arrayProperties();
<del>
<del> for (key in arrayProperties) {
<del> properties[key] = arrayProperties[key];
<del> }
<del>
<add> for (let key = 0, length = source.length; key < length; key++) {
<add> descriptors.$meta.value[key] = this.create(source[key], listener, path + key);
<add> descriptors[key] = this.descriptor(key);
<add> }
<ide> }
<ide>
<ide> if (type === Object) {
<del>
<del> for (key in source) {
<del> properties.$meta.value[key] = self.create(source[key], listener, path + key);
<del> properties[key] = self.property(key);
<del> }
<del>
<del> }
<del>
<del> let objectProperties = self.objectProperties();
<del>
<del> for (key in objectProperties) {
<del> properties[key] = objectProperties[key];
<del> }
<del>
<del> return Object.defineProperties(target, properties);
<add> for (let key in source) {
<add> descriptors.$meta.value[key] = this.create(source[key], listener, path + key);
<add> descriptors[key] = this.descriptor(key);
<add> }
<add> }
<add>
<add> Object.defineProperties(target, descriptors);
<add> Object.defineProperties(target, this.objectProperties(source, listener, path));
<add>
<add> if (type === Array) {
<add> Object.defineProperties(target, this.arrayProperties(source, listener, path));
<add> }
<add>
<add> return target;
<ide> }
<ide>
<ide> }; |
|
Java | apache-2.0 | 72e12c45041655a8854c21caa721aa50c7568eba | 0 | kinbod/deeplearning4j,kinbod/deeplearning4j,kinbod/deeplearning4j,huitseeker/deeplearning4j,huitseeker/deeplearning4j,kinbod/deeplearning4j,huitseeker/deeplearning4j,huitseeker/deeplearning4j,huitseeker/deeplearning4j,huitseeker/deeplearning4j,kinbod/deeplearning4j,huitseeker/deeplearning4j,kinbod/deeplearning4j | /*-
*
* * Copyright 2015 Skymind,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 org.deeplearning4j.nn.conf;
import com.google.common.collect.Sets;
import lombok.*;
import org.apache.commons.lang3.ClassUtils;
import org.deeplearning4j.nn.api.OptimizationAlgorithm;
import org.deeplearning4j.nn.conf.distribution.Distribution;
import org.deeplearning4j.nn.conf.graph.GraphVertex;
import org.deeplearning4j.nn.conf.layers.ConvolutionLayer;
import org.deeplearning4j.nn.conf.layers.Layer;
import org.deeplearning4j.nn.conf.layers.LayerValidation;
import org.deeplearning4j.nn.conf.layers.SubsamplingLayer;
import org.deeplearning4j.nn.conf.layers.variational.ReconstructionDistribution;
import org.deeplearning4j.nn.conf.stepfunctions.StepFunction;
import org.deeplearning4j.util.reflections.DL4JSubTypesScanner;
import org.deeplearning4j.nn.weights.WeightInit;
import org.nd4j.linalg.activations.Activation;
import org.nd4j.linalg.activations.IActivation;
import org.nd4j.linalg.activations.impl.*;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.learning.*;
import org.nd4j.linalg.lossfunctions.ILossFunction;
import org.nd4j.shade.jackson.databind.DeserializationFeature;
import org.nd4j.shade.jackson.databind.MapperFeature;
import org.nd4j.shade.jackson.databind.ObjectMapper;
import org.nd4j.shade.jackson.databind.SerializationFeature;
import org.nd4j.shade.jackson.databind.introspect.AnnotatedClass;
import org.nd4j.shade.jackson.databind.jsontype.NamedType;
import org.nd4j.shade.jackson.dataformat.yaml.YAMLFactory;
import org.reflections.ReflectionUtils;
import org.reflections.Reflections;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;
import org.reflections.util.FilterBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.util.*;
/**
* A Serializable configuration
* for neural nets that covers per layer parameters
*
* @author Adam Gibson
*/
@Data
@NoArgsConstructor
public class NeuralNetConfiguration implements Serializable, Cloneable {
private static final Logger log = LoggerFactory.getLogger(NeuralNetConfiguration.class);
/**
* System property for custom layers, preprocessors, graph vertices etc. Enabled by default.
* Run JVM with "-Dorg.deeplearning4j.config.custom.enabled=false" to disable classpath scanning for
* Overriding the default (i.e., disabling) this is only useful if (a) no custom layers/preprocessors etc will be
* used, and (b) minimizing startup/initialization time for new JVMs is very important.
* Results are cached, so there is no cost to custom layers after the first network has been constructed.
*/
public static final String CUSTOM_FUNCTIONALITY = "org.deeplearning4j.config.custom.enabled";
protected Layer layer;
@Deprecated
protected double leakyreluAlpha;
//batch size: primarily used for conv nets. Will be reinforced if set.
protected boolean miniBatch = true;
protected int numIterations;
//number of line search iterations
protected int maxNumLineSearchIterations;
protected long seed;
protected OptimizationAlgorithm optimizationAlgo;
//gradient keys used for ensuring order when getting and setting the gradient
protected List<String> variables = new ArrayList<>();
//whether to constrain the gradient to unit norm or not
//adadelta - weight for how much to consider previous history
protected StepFunction stepFunction;
protected boolean useRegularization = false;
protected boolean useDropConnect = false;
//minimize or maximize objective
protected boolean minimize = true;
// Graves LSTM & RNN
protected Map<String, Double> learningRateByParam = new HashMap<>();
protected Map<String, Double> l1ByParam = new HashMap<>();
protected Map<String, Double> l2ByParam = new HashMap<>();
protected LearningRatePolicy learningRatePolicy = LearningRatePolicy.None;
protected double lrPolicyDecayRate;
protected double lrPolicySteps;
protected double lrPolicyPower;
protected boolean pretrain;
//Counter for the number of parameter updates so far for this layer.
//Note that this is only used for pretrain layers (RBM, VAE) - MultiLayerConfiguration and ComputationGraphConfiguration
//contain counters for standard backprop training.
// This is important for learning rate schedules, for example, and is stored here to ensure it is persisted
// for Spark and model serialization
protected int iterationCount = 0;
private static ObjectMapper mapper = initMapper();
private static final ObjectMapper mapperYaml = initMapperYaml();
private static Set<Class<?>> subtypesClassCache = null;
/**
* Creates and returns a deep copy of the configuration.
*/
@Override
public NeuralNetConfiguration clone() {
try {
NeuralNetConfiguration clone = (NeuralNetConfiguration) super.clone();
if (clone.layer != null)
clone.layer = clone.layer.clone();
if (clone.stepFunction != null)
clone.stepFunction = clone.stepFunction.clone();
if (clone.variables != null)
clone.variables = new ArrayList<>(clone.variables);
if (clone.learningRateByParam != null)
clone.learningRateByParam = new HashMap<>(clone.learningRateByParam);
if (clone.l1ByParam != null)
clone.l1ByParam = new HashMap<>(clone.l1ByParam);
if (clone.l2ByParam != null)
clone.l2ByParam = new HashMap<>(clone.l2ByParam);
return clone;
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
public List<String> variables() {
return new ArrayList<>(variables);
}
public List<String> variables(boolean copy) {
if (copy)
return variables();
return variables;
}
public void addVariable(String variable) {
if (!variables.contains(variable)) {
variables.add(variable);
setLayerParamLR(variable);
}
}
public void clearVariables() {
variables.clear();
}
public void setLayerParamLR(String variable) {
double lr = layer.getLearningRateByParam(variable);
double l1 = layer.getL1ByParam(variable);
if (Double.isNaN(l1))
l1 = 0.0; //Not set
double l2 = layer.getL2ByParam(variable);
if (Double.isNaN(l2))
l2 = 0.0; //Not set
learningRateByParam.put(variable, lr);
l1ByParam.put(variable, l1);
l2ByParam.put(variable, l2);
}
public double getLearningRateByParam(String variable) {
return learningRateByParam.get(variable);
}
public void setLearningRateByParam(String variable, double rate) {
learningRateByParam.put(variable, rate);
}
public double getL1ByParam(String variable) {
return l1ByParam.get(variable);
}
public double getL2ByParam(String variable) {
return l2ByParam.get(variable);
}
/**
* Fluent interface for building a list of configurations
*/
public static class ListBuilder extends MultiLayerConfiguration.Builder {
private Map<Integer, Builder> layerwise;
private Builder globalConfig;
// Constructor
public ListBuilder(Builder globalConfig, Map<Integer, Builder> layerMap) {
this.globalConfig = globalConfig;
this.layerwise = layerMap;
}
public ListBuilder(Builder globalConfig) {
this(globalConfig, new HashMap<Integer, Builder>());
}
public ListBuilder backprop(boolean backprop) {
this.backprop = backprop;
return this;
}
public ListBuilder pretrain(boolean pretrain) {
this.pretrain = pretrain;
return this;
}
public ListBuilder layer(int ind, Layer layer) {
if (layerwise.containsKey(ind)) {
layerwise.get(ind).layer(layer);
} else {
layerwise.put(ind, globalConfig.clone().layer(layer));
}
return this;
}
public Map<Integer, Builder> getLayerwise() {
return layerwise;
}
/**
* Build the multi layer network
* based on this neural network and
* overr ridden parameters
* @return the configuration to build
*/
public MultiLayerConfiguration build() {
List<NeuralNetConfiguration> list = new ArrayList<>();
if (layerwise.isEmpty())
throw new IllegalStateException("Invalid configuration: no layers defined");
for (int i = 0; i < layerwise.size(); i++) {
if (layerwise.get(i) == null) {
throw new IllegalStateException("Invalid configuration: layer number " + i
+ " not specified. Expect layer " + "numbers to be 0 to " + (layerwise.size() - 1)
+ " inclusive (number of layers defined: " + layerwise.size() + ")");
}
if (layerwise.get(i).getLayer() == null)
throw new IllegalStateException("Cannot construct network: Layer config for" + "layer with index "
+ i + " is not defined)");
//Layer names: set to default, if not set
if (layerwise.get(i).getLayer().getLayerName() == null) {
layerwise.get(i).getLayer().setLayerName("layer" + i);
}
list.add(layerwise.get(i).build());
}
return new MultiLayerConfiguration.Builder().backprop(backprop).inputPreProcessors(inputPreProcessors)
.pretrain(pretrain).backpropType(backpropType).tBPTTForwardLength(tbpttFwdLength)
.tBPTTBackwardLength(tbpttBackLength).cnnInputSize(this.cnnInputSize)
.setInputType(this.inputType).trainingWorkspaceMode(globalConfig.trainingWorkspaceMode).confs(list).build();
}
}
/**
* Return this configuration as json
* @return this configuration represented as json
*/
public String toYaml() {
ObjectMapper mapper = mapperYaml();
try {
String ret = mapper.writeValueAsString(this);
return ret;
} catch (org.nd4j.shade.jackson.core.JsonProcessingException e) {
throw new RuntimeException(e);
}
}
/**
* Create a neural net configuration from json
* @param json the neural net configuration from json
* @return
*/
public static NeuralNetConfiguration fromYaml(String json) {
ObjectMapper mapper = mapperYaml();
try {
NeuralNetConfiguration ret = mapper.readValue(json, NeuralNetConfiguration.class);
return ret;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Return this configuration as json
* @return this configuration represented as json
*/
public String toJson() {
ObjectMapper mapper = mapper();
try {
String ret = mapper.writeValueAsString(this);
return ret;
} catch (org.nd4j.shade.jackson.core.JsonProcessingException e) {
throw new RuntimeException(e);
}
}
/**
* Create a neural net configuration from json
* @param json the neural net configuration from json
* @return
*/
public static NeuralNetConfiguration fromJson(String json) {
ObjectMapper mapper = mapper();
try {
NeuralNetConfiguration ret = mapper.readValue(json, NeuralNetConfiguration.class);
return ret;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Object mapper for serialization of configurations
* @return
*/
public static ObjectMapper mapperYaml() {
return mapperYaml;
}
private static ObjectMapper initMapperYaml() {
ObjectMapper ret = new ObjectMapper(new YAMLFactory());
configureMapper(ret);
return ret;
}
/**
* Object mapper for serialization of configurations
* @return
*/
public static ObjectMapper mapper() {
return mapper;
}
/**Reinitialize and return the Jackson/json ObjectMapper with additional named types.
* This can be used to add additional subtypes at runtime (i.e., for JSON mapping with
* types defined outside of the main DL4J codebase)
*/
public static ObjectMapper reinitMapperWithSubtypes(Collection<NamedType> additionalTypes) {
mapper.registerSubtypes(additionalTypes.toArray(new NamedType[additionalTypes.size()]));
//Recreate the mapper (via copy), as mapper won't use registered subtypes after first use
mapper = mapper.copy();
return mapper;
}
private static ObjectMapper initMapper() {
ObjectMapper ret = new ObjectMapper();
configureMapper(ret);
return ret;
}
private static void configureMapper(ObjectMapper ret) {
ret.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
ret.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
ret.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);
ret.enable(SerializationFeature.INDENT_OUTPUT);
registerSubtypes(ret);
}
private static synchronized void registerSubtypes(ObjectMapper mapper) {
//Register concrete subtypes for JSON serialization
List<Class<?>> classes = Arrays.<Class<?>>asList(InputPreProcessor.class, ILossFunction.class,
IActivation.class, Layer.class, GraphVertex.class, ReconstructionDistribution.class);
List<String> classNames = new ArrayList<>(6);
for (Class<?> c : classes)
classNames.add(c.getName());
// First: scan the classpath and find all instances of the 'baseClasses' classes
if (subtypesClassCache == null) {
//Check system property:
String prop = System.getProperty(CUSTOM_FUNCTIONALITY);
if (prop != null && !Boolean.parseBoolean(prop)) {
subtypesClassCache = Collections.emptySet();
} else {
List<Class<?>> interfaces = Arrays.<Class<?>>asList(InputPreProcessor.class, ILossFunction.class,
IActivation.class, ReconstructionDistribution.class);
List<Class<?>> classesList = Arrays.<Class<?>>asList(Layer.class, GraphVertex.class);
Collection<URL> urls = ClasspathHelper.forClassLoader();
List<URL> scanUrls = new ArrayList<>();
for (URL u : urls) {
String path = u.getPath();
if (!path.matches(".*/jre/lib/.*jar")) { //Skip JRE/JDK JARs
scanUrls.add(u);
}
}
Reflections reflections = new Reflections(new ConfigurationBuilder().filterInputsBy(new FilterBuilder()
.exclude("^(?!.*\\.class$).*$") //Consider only .class files (to avoid debug messages etc. on .dlls, etc
//Exclude the following: the assumption here is that no custom functionality will ever be present
// under these package name prefixes. These are all common dependencies for DL4J
.exclude("^org.nd4j.*").exclude("^org.datavec.*").exclude("^org.bytedeco.*") //JavaCPP
.exclude("^com.fasterxml.*")//Jackson
.exclude("^org.apache.*") //Apache commons, Spark, log4j etc
.exclude("^org.projectlombok.*").exclude("^com.twelvemonkeys.*").exclude("^org.joda.*")
.exclude("^org.slf4j.*").exclude("^com.google.*").exclude("^org.reflections.*")
.exclude("^ch.qos.*") //Logback
).addUrls(scanUrls).setScanners(new DL4JSubTypesScanner(interfaces, classesList)));
org.reflections.Store store = reflections.getStore();
Iterable<String> subtypesByName = store.getAll(DL4JSubTypesScanner.class.getSimpleName(), classNames);
Set<? extends Class<?>> subtypeClasses = Sets.newHashSet(ReflectionUtils.forNames(subtypesByName));
subtypesClassCache = new HashSet<>();
for (Class<?> c : subtypeClasses) {
if (Modifier.isAbstract(c.getModifiers()) || Modifier.isInterface(c.getModifiers())) {
//log.info("Skipping abstract/interface: {}",c);
continue;
}
subtypesClassCache.add(c);
}
}
}
//Second: get all currently registered subtypes for this mapper
Set<Class<?>> registeredSubtypes = new HashSet<>();
for (Class<?> c : classes) {
AnnotatedClass ac = AnnotatedClass.construct(c, mapper.getSerializationConfig().getAnnotationIntrospector(),
null);
Collection<NamedType> types =
mapper.getSubtypeResolver().collectAndResolveSubtypes(ac, mapper.getSerializationConfig(),
mapper.getSerializationConfig().getAnnotationIntrospector());
for (NamedType nt : types) {
registeredSubtypes.add(nt.getType());
}
}
//Third: register all _concrete_ subtypes that are not already registered
List<NamedType> toRegister = new ArrayList<>();
for (Class<?> c : subtypesClassCache) {
//Check if it's concrete or abstract...
if (Modifier.isAbstract(c.getModifiers()) || Modifier.isInterface(c.getModifiers())) {
//log.info("Skipping abstract/interface: {}",c);
continue;
}
if (!registeredSubtypes.contains(c)) {
String name;
if (ClassUtils.isInnerClass(c)) {
Class<?> c2 = c.getDeclaringClass();
name = c2.getSimpleName() + "$" + c.getSimpleName();
} else {
name = c.getSimpleName();
}
toRegister.add(new NamedType(c, name));
if (log.isDebugEnabled()) {
for (Class<?> baseClass : classes) {
if (baseClass.isAssignableFrom(c)) {
log.debug("Registering class for JSON serialization: {} as subtype of {}", c.getName(),
baseClass.getName());
break;
}
}
}
}
}
mapper.registerSubtypes(toRegister.toArray(new NamedType[toRegister.size()]));
}
@Data
public static class Builder implements Cloneable {
protected IActivation activationFn = new ActivationSigmoid();
protected WeightInit weightInit = WeightInit.XAVIER;
protected double biasInit = 0.0;
protected Distribution dist = null;
protected double learningRate = 1e-1;
protected double biasLearningRate = Double.NaN;
protected Map<Integer, Double> learningRateSchedule = null;
protected double lrScoreBasedDecay;
protected double l1 = Double.NaN;
protected double l2 = Double.NaN;
protected double l1Bias = Double.NaN;
protected double l2Bias = Double.NaN;
protected double dropOut = 0;
protected Updater updater = Updater.SGD;
protected double momentum = Double.NaN;
protected Map<Integer, Double> momentumSchedule = null;
protected double epsilon = Double.NaN;
protected double rho = Double.NaN;
protected double rmsDecay = Double.NaN;
protected double adamMeanDecay = Double.NaN;
protected double adamVarDecay = Double.NaN;
protected Layer layer;
@Deprecated
protected double leakyreluAlpha = 0.01;
protected boolean miniBatch = true;
protected int numIterations = 1;
protected int maxNumLineSearchIterations = 5;
protected long seed = System.currentTimeMillis();
protected boolean useRegularization = false;
protected OptimizationAlgorithm optimizationAlgo = OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT;
protected StepFunction stepFunction = null;
protected boolean useDropConnect = false;
protected boolean minimize = true;
protected GradientNormalization gradientNormalization = GradientNormalization.None;
protected double gradientNormalizationThreshold = 1.0;
protected LearningRatePolicy learningRatePolicy = LearningRatePolicy.None;
protected double lrPolicyDecayRate = Double.NaN;
protected double lrPolicySteps = Double.NaN;
protected double lrPolicyPower = Double.NaN;
protected boolean pretrain = false;
protected WorkspaceMode trainingWorkspaceMode = WorkspaceMode.NONE;
protected WorkspaceMode inferenceWorkspaceMode = WorkspaceMode.SINGLE;
protected ConvolutionMode convolutionMode = ConvolutionMode.Truncate;
public Builder() {
//
}
public Builder(NeuralNetConfiguration newConf) {
if (newConf != null) {
minimize = newConf.minimize;
maxNumLineSearchIterations = newConf.maxNumLineSearchIterations;
layer = newConf.layer;
numIterations = newConf.numIterations;
useRegularization = newConf.useRegularization;
optimizationAlgo = newConf.optimizationAlgo;
seed = newConf.seed;
stepFunction = newConf.stepFunction;
useDropConnect = newConf.useDropConnect;
miniBatch = newConf.miniBatch;
learningRatePolicy = newConf.learningRatePolicy;
lrPolicyDecayRate = newConf.lrPolicyDecayRate;
lrPolicySteps = newConf.lrPolicySteps;
lrPolicyPower = newConf.lrPolicyPower;
pretrain = newConf.pretrain;
}
}
/** Process input as minibatch vs full dataset.
* Default set to true. */
public Builder miniBatch(boolean miniBatch) {
this.miniBatch = miniBatch;
return this;
}
/**
* This method defines Workspace mode being used during training:
* NONE: workspace won't be used
* SINGLE: one workspace will be used during whole iteration loop
* SEPARATE: separate workspaces will be used for feedforward and backprop iteration loops
*
* @param workspaceMode
* @return
*/
public Builder trainingWorkspaceMode(@NonNull WorkspaceMode workspaceMode) {
this.trainingWorkspaceMode = workspaceMode;
return this;
}
/**
* This method defines Workspace mode being used during inference:
* NONE: workspace won't be used
* SINGLE: one workspace will be used during whole iteration loop
* SEPARATE: separate workspaces will be used for feedforward and backprop iteration loops
*
* @param workspaceMode
* @return
*/
public Builder inferenceWorkspaceMode(@NonNull WorkspaceMode workspaceMode) {
this.inferenceWorkspaceMode = workspaceMode;
return this;
}
/**
* Use drop connect: multiply the weight by a binomial sampling wrt the dropout probability.
* Dropconnect probability is set using {@link #dropOut(double)}; this is the probability of retaining a weight
* @param useDropConnect whether to use drop connect or not
* @return the
*/
public Builder useDropConnect(boolean useDropConnect) {
this.useDropConnect = useDropConnect;
return this;
}
/** Objective function to minimize or maximize cost function
* Default set to minimize true. */
public Builder minimize(boolean minimize) {
this.minimize = minimize;
return this;
}
/** Maximum number of line search iterations.
* Only applies for line search optimizers: Line Search SGD, Conjugate Gradient, LBFGS
* is NOT applicable for standard SGD
* @param maxNumLineSearchIterations > 0
* @return
*/
public Builder maxNumLineSearchIterations(int maxNumLineSearchIterations) {
this.maxNumLineSearchIterations = maxNumLineSearchIterations;
return this;
}
/** Layer class. */
public Builder layer(Layer layer) {
this.layer = layer;
return this;
}
/** Step function to apply for back track line search.
* Only applies for line search optimizers: Line Search SGD, Conjugate Gradient, LBFGS
* Options: DefaultStepFunction (default), NegativeDefaultStepFunction
* GradientStepFunction (for SGD), NegativeGradientStepFunction */
public Builder stepFunction(StepFunction stepFunction) {
this.stepFunction = stepFunction;
return this;
}
/**Create a ListBuilder (for creating a MultiLayerConfiguration)<br>
* Usage:<br>
* <pre>
* {@code .list()
* .layer(0,new DenseLayer.Builder()...build())
* ...
* .layer(n,new OutputLayer.Builder()...build())
* }
* </pre>
* */
public ListBuilder list() {
return new ListBuilder(this);
}
/**Create a ListBuilder (for creating a MultiLayerConfiguration) with the specified layers<br>
* Usage:<br>
* <pre>
* {@code .list(
* new DenseLayer.Builder()...build(),
* ...,
* new OutputLayer.Builder()...build())
* }
* </pre>
* @param layers The layer configurations for the network
*/
public ListBuilder list(Layer... layers) {
if (layers == null || layers.length == 0)
throw new IllegalArgumentException("Cannot create network with no layers");
Map<Integer, Builder> layerMap = new HashMap<>();
for (int i = 0; i < layers.length; i++) {
Builder b = this.clone();
b.layer(layers[i]);
layerMap.put(i, b);
}
return new ListBuilder(this, layerMap);
}
/**
* Create a GraphBuilder (for creating a ComputationGraphConfiguration).
*/
public ComputationGraphConfiguration.GraphBuilder graphBuilder() {
return new ComputationGraphConfiguration.GraphBuilder(this);
}
/** Number of optimization iterations. */
public Builder iterations(int numIterations) {
this.numIterations = numIterations;
return this;
}
/** Random number generator seed. Used for reproducability between runs */
public Builder seed(int seed) {
this.seed = (long) seed;
Nd4j.getRandom().setSeed(seed);
return this;
}
/** Random number generator seed. Used for reproducability between runs */
public Builder seed(long seed) {
this.seed = seed;
Nd4j.getRandom().setSeed(seed);
return this;
}
/**
* Optimization algorithm to use. Most common: OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT
*
* @param optimizationAlgo Optimization algorithm to use when training
*/
public Builder optimizationAlgo(OptimizationAlgorithm optimizationAlgo) {
this.optimizationAlgo = optimizationAlgo;
return this;
}
/** Whether to use regularization (l1, l2, dropout, etc */
public Builder regularization(boolean useRegularization) {
this.useRegularization = useRegularization;
return this;
}
@Override
public Builder clone() {
try {
Builder clone = (Builder) super.clone();
if (clone.layer != null)
clone.layer = clone.layer.clone();
if (clone.stepFunction != null)
clone.stepFunction = clone.stepFunction.clone();
return clone;
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
/**Activation function / neuron non-linearity
* Typical values include:<br>
* "relu" (rectified linear), "tanh", "sigmoid", "softmax",
* "hardtanh", "leakyrelu", "maxout", "softsign", "softplus"
* @deprecated Use {@link #activation(Activation)} or
* {@link @activation(IActivation)}
*/
@Deprecated
public Builder activation(String activationFunction) {
return activation(Activation.fromString(activationFunction).getActivationFunction());
}
/**Activation function / neuron non-linearity
* @see #activation(Activation)
*/
public Builder activation(IActivation activationFunction) {
this.activationFn = activationFunction;
return this;
}
/**Activation function / neuron non-linearity
*/
public Builder activation(Activation activation) {
return activation(activation.getActivationFunction());
}
/**
* @deprecated Use {@link #activation(IActivation)} with leaky relu, setting alpha value directly in constructor.
*/
@Deprecated
public Builder leakyreluAlpha(double leakyreluAlpha) {
this.leakyreluAlpha = leakyreluAlpha;
return this;
}
/** Weight initialization scheme.
* @see org.deeplearning4j.nn.weights.WeightInit
*/
public Builder weightInit(WeightInit weightInit) {
this.weightInit = weightInit;
return this;
}
/**
* Constant for bias initialization. Default: 0.0
*
* @param biasInit Constant for bias initialization
*/
public Builder biasInit(double biasInit) {
this.biasInit = biasInit;
return this;
}
/** Distribution to sample initial weights from. Used in conjunction with
* .weightInit(WeightInit.DISTRIBUTION).
*/
public Builder dist(Distribution dist) {
this.dist = dist;
return this;
}
/** Learning rate. Defaults to 1e-1*/
public Builder learningRate(double learningRate) {
this.learningRate = learningRate;
return this;
}
/** Bias learning rate. Set this to apply a different learning rate to the bias*/
public Builder biasLearningRate(double biasLearningRate) {
this.biasLearningRate = biasLearningRate;
return this;
}
/** Learning rate schedule. Map of the iteration to the learning rate to apply at that iteration. */
public Builder learningRateSchedule(Map<Integer, Double> learningRateSchedule) {
this.learningRateSchedule = learningRateSchedule;
return this;
}
/** Rate to decrease learningRate by when the score stops improving.
* Learning rate is multiplied by this rate so ideally keep between 0 and 1. */
public Builder learningRateScoreBasedDecayRate(double lrScoreBasedDecay) {
this.lrScoreBasedDecay = lrScoreBasedDecay;
return this;
}
/** L1 regularization coefficient for the weights.
* Use with .regularization(true)
*/
public Builder l1(double l1) {
this.l1 = l1;
return this;
}
/** L2 regularization coefficient for the weights.
* Use with .regularization(true)
*/
public Builder l2(double l2) {
this.l2 = l2;
return this;
}
/** L1 regularization coefficient for the bias.
* Use with .regularization(true)
*/
public Builder l1Bias(double l1Bias) {
this.l1Bias = l1Bias;
return this;
}
/** L2 regularization coefficient for the bias.
* Use with .regularization(true)
*/
public Builder l2Bias(double l2Bias) {
this.l2Bias = l2Bias;
return this;
}
/**
* Dropout probability. This is the probability of <it>retaining</it> an activation. So dropOut(x) will keep an
* activation with probability x, and set to 0 with probability 1-x.<br>
* dropOut(0.0) is disabled (default).
* <p>
* Note: This sets the probability per-layer. Care should be taken when setting lower values for complex networks.
* </p>
*
* @param dropOut Dropout probability (probability of retaining an activation)
*/
public Builder dropOut(double dropOut) {
this.dropOut = dropOut;
return this;
}
/** Momentum rate
* Used only when Updater is set to {@link Updater#NESTEROVS}
*/
public Builder momentum(double momentum) {
this.momentum = momentum;
return this;
}
/** Momentum schedule. Map of the iteration to the momentum rate to apply at that iteration
* Used only when Updater is set to {@link Updater#NESTEROVS}
*/
public Builder momentumAfter(Map<Integer, Double> momentumAfter) {
this.momentumSchedule = momentumAfter;
return this;
}
/** Gradient updater. For example, Updater.SGD for standard stochastic gradient descent,
* Updater.NESTEROV for Nesterov momentum, Updater.RSMPROP for RMSProp, etc.
* @see Updater
*/
public Builder updater(Updater updater) {
this.updater = updater;
return this;
}
/**
* Ada delta coefficient
* @param rho
*/
public Builder rho(double rho) {
this.rho = rho;
return this;
}
/**
* Epsilon value for updaters: Adam, RMSProp, Adagrad, Adadelta
* Default values: {@link Adam#DEFAULT_ADAM_EPSILON}, {@link RmsProp#DEFAULT_RMSPROP_EPSILON}, {@link AdaGrad#DEFAULT_ADAGRAD_EPSILON},
* {@link AdaDelta#DEFAULT_ADADELTA_EPSILON}
*
* @param epsilon Epsilon value to use for adagrad or
*/
public Builder epsilon(double epsilon) {
this.epsilon = epsilon;
return this;
}
/** Decay rate for RMSProp. Only applies if using .updater(Updater.RMSPROP)
*/
public Builder rmsDecay(double rmsDecay) {
this.rmsDecay = rmsDecay;
return this;
}
/** Mean decay rate for Adam updater. Only applies if using .updater(Updater.ADAM) */
public Builder adamMeanDecay(double adamMeanDecay) {
this.adamMeanDecay = adamMeanDecay;
return this;
}
/** Variance decay rate for Adam updater. Only applies if using .updater(Updater.ADAM) */
public Builder adamVarDecay(double adamVarDecay) {
this.adamVarDecay = adamVarDecay;
return this;
}
/** Gradient normalization strategy. Used to specify gradient renormalization, gradient clipping etc.
* @param gradientNormalization Type of normalization to use. Defaults to None.
* @see GradientNormalization
*/
public Builder gradientNormalization(GradientNormalization gradientNormalization) {
this.gradientNormalization = gradientNormalization;
return this;
}
/** Threshold for gradient normalization, only used for GradientNormalization.ClipL2PerLayer,
* GradientNormalization.ClipL2PerParamType, and GradientNormalization.ClipElementWiseAbsoluteValue<br>
* Not used otherwise.<br>
* L2 threshold for first two types of clipping, or absolute value threshold for last type of clipping.
*/
public Builder gradientNormalizationThreshold(double threshold) {
this.gradientNormalizationThreshold = threshold;
return this;
}
/** Learning rate decay policy. Used to adapt learning rate based on policy.
* @param policy Type of policy to use. Defaults to None.
*/
public Builder learningRateDecayPolicy(LearningRatePolicy policy) {
this.learningRatePolicy = policy;
return this;
}
/** Set the decay rate for the learning rate decay policy.
* @param lrPolicyDecayRate rate.
*/
public Builder lrPolicyDecayRate(double lrPolicyDecayRate) {
this.lrPolicyDecayRate = lrPolicyDecayRate;
return this;
}
/** Set the number of steps used for learning decay rate steps policy.
* @param lrPolicySteps number of steps
*/
public Builder lrPolicySteps(double lrPolicySteps) {
this.lrPolicySteps = lrPolicySteps;
return this;
}
/** Set the power used for learning rate inverse policy.
* @param lrPolicyPower power
*/
public Builder lrPolicyPower(double lrPolicyPower) {
this.lrPolicyPower = lrPolicyPower;
return this;
}
public Builder convolutionMode(ConvolutionMode convolutionMode) {
this.convolutionMode = convolutionMode;
return this;
}
private void learningRateValidation(String layerName) {
if (learningRatePolicy != LearningRatePolicy.None && Double.isNaN(lrPolicyDecayRate)) {
//LR policy, if used, should have a decay rate. 2 exceptions: Map for schedule, and Poly + power param
if (!(learningRatePolicy == LearningRatePolicy.Schedule && learningRateSchedule != null)
&& !(learningRatePolicy == LearningRatePolicy.Poly && !Double.isNaN(lrPolicyPower)))
throw new IllegalStateException("Layer \"" + layerName
+ "\" learning rate policy decay rate (lrPolicyDecayRate) must be set to use learningRatePolicy.");
}
switch (learningRatePolicy) {
case Inverse:
case Poly:
if (Double.isNaN(lrPolicyPower))
throw new IllegalStateException("Layer \"" + layerName
+ "\" learning rate policy power (lrPolicyPower) must be set to use "
+ learningRatePolicy);
break;
case Step:
case Sigmoid:
if (Double.isNaN(lrPolicySteps))
throw new IllegalStateException("Layer \"" + layerName
+ "\" learning rate policy steps (lrPolicySteps) must be set to use "
+ learningRatePolicy);
break;
case Schedule:
if (learningRateSchedule == null)
throw new IllegalStateException("Layer \"" + layerName
+ "\" learning rate policy schedule (learningRateSchedule) must be set to use "
+ learningRatePolicy);
break;
}
if (!Double.isNaN(lrPolicyPower) && (learningRatePolicy != LearningRatePolicy.Inverse
&& learningRatePolicy != LearningRatePolicy.Poly))
throw new IllegalStateException("Layer \"" + layerName
+ "\" power has been set but will not be applied unless the learning rate policy is set to Inverse or Poly.");
if (!Double.isNaN(lrPolicySteps) && (learningRatePolicy != LearningRatePolicy.Step
&& learningRatePolicy != LearningRatePolicy.Sigmoid
&& learningRatePolicy != LearningRatePolicy.TorchStep))
throw new IllegalStateException("Layer \"" + layerName
+ "\" steps have been set but will not be applied unless the learning rate policy is set to Step or Sigmoid.");
if ((learningRateSchedule != null) && (learningRatePolicy != LearningRatePolicy.Schedule))
throw new IllegalStateException("Layer \"" + layerName
+ "\" learning rate schedule has been set but will not be applied unless the learning rate policy is set to Schedule.");
}
////////////////
/**
* Return a configuration based on this builder
*
* @return
*/
public NeuralNetConfiguration build() {
NeuralNetConfiguration conf = new NeuralNetConfiguration();
conf.minimize = minimize;
conf.maxNumLineSearchIterations = maxNumLineSearchIterations;
conf.layer = layer;
conf.numIterations = numIterations;
conf.useRegularization = useRegularization;
conf.optimizationAlgo = optimizationAlgo;
conf.seed = seed;
conf.stepFunction = stepFunction;
conf.useDropConnect = useDropConnect;
conf.miniBatch = miniBatch;
conf.learningRatePolicy = learningRatePolicy;
conf.lrPolicyDecayRate = lrPolicyDecayRate;
conf.lrPolicySteps = lrPolicySteps;
conf.lrPolicyPower = lrPolicyPower;
conf.pretrain = pretrain;
String layerName;
if (layer == null || layer.getLayerName() == null)
layerName = "Layer not named";
else
layerName = layer.getLayerName();
learningRateValidation(layerName);
if (layer != null) {
if (Double.isNaN(layer.getLearningRate()))
layer.setLearningRate(learningRate);
if (Double.isNaN(layer.getBiasLearningRate())) {
//Two possibilities when bias LR isn't set for layer:
// (a) If global bias LR *is* set -> set it to that
// (b) Otherwise, set to layer LR (and, by extension, the global LR)
if (!Double.isNaN(biasLearningRate)) {
//Global bias LR is set
layer.setBiasLearningRate(biasLearningRate);
} else {
layer.setBiasLearningRate(layer.getLearningRate());
}
}
if (layer.getLearningRateSchedule() == null)
layer.setLearningRateSchedule(learningRateSchedule);
if (Double.isNaN(layer.getL1()))
layer.setL1(l1);
if (Double.isNaN(layer.getL2()))
layer.setL2(l2);
if (layer.getActivationFn() == null)
layer.setActivationFn(activationFn);
if (layer.getWeightInit() == null)
layer.setWeightInit(weightInit);
if (Double.isNaN(layer.getBiasInit()))
layer.setBiasInit(biasInit);
if (Double.isNaN(layer.getDropOut()))
layer.setDropOut(dropOut);
if (layer.getUpdater() == null)
layer.setUpdater(updater);
// updaterValidation(layerName);
LayerValidation.updaterValidation(layerName, layer, momentum, momentumSchedule, adamMeanDecay,
adamVarDecay, rho, rmsDecay, epsilon);
if (layer.getGradientNormalization() == null)
layer.setGradientNormalization(gradientNormalization);
if (Double.isNaN(layer.getGradientNormalizationThreshold()))
layer.setGradientNormalizationThreshold(gradientNormalizationThreshold);
if (layer instanceof ConvolutionLayer) {
ConvolutionLayer cl = (ConvolutionLayer) layer;
if (cl.getConvolutionMode() == null) {
cl.setConvolutionMode(convolutionMode);
}
}
if (layer instanceof SubsamplingLayer) {
SubsamplingLayer sl = (SubsamplingLayer) layer;
if (sl.getConvolutionMode() == null) {
sl.setConvolutionMode(convolutionMode);
}
}
}
LayerValidation.generalValidation(layerName, layer, useRegularization, useDropConnect, dropOut, l2, l2Bias,
l1, l1Bias, dist);
return conf;
}
}
}
| deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/conf/NeuralNetConfiguration.java | /*-
*
* * Copyright 2015 Skymind,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 org.deeplearning4j.nn.conf;
import com.google.common.collect.Sets;
import lombok.*;
import org.apache.commons.lang3.ClassUtils;
import org.deeplearning4j.nn.api.OptimizationAlgorithm;
import org.deeplearning4j.nn.conf.distribution.Distribution;
import org.deeplearning4j.nn.conf.graph.GraphVertex;
import org.deeplearning4j.nn.conf.layers.ConvolutionLayer;
import org.deeplearning4j.nn.conf.layers.Layer;
import org.deeplearning4j.nn.conf.layers.LayerValidation;
import org.deeplearning4j.nn.conf.layers.SubsamplingLayer;
import org.deeplearning4j.nn.conf.layers.variational.ReconstructionDistribution;
import org.deeplearning4j.nn.conf.stepfunctions.StepFunction;
import org.deeplearning4j.util.reflections.DL4JSubTypesScanner;
import org.deeplearning4j.nn.weights.WeightInit;
import org.nd4j.linalg.activations.Activation;
import org.nd4j.linalg.activations.IActivation;
import org.nd4j.linalg.activations.impl.*;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.learning.*;
import org.nd4j.linalg.lossfunctions.ILossFunction;
import org.nd4j.shade.jackson.databind.DeserializationFeature;
import org.nd4j.shade.jackson.databind.MapperFeature;
import org.nd4j.shade.jackson.databind.ObjectMapper;
import org.nd4j.shade.jackson.databind.SerializationFeature;
import org.nd4j.shade.jackson.databind.introspect.AnnotatedClass;
import org.nd4j.shade.jackson.databind.jsontype.NamedType;
import org.nd4j.shade.jackson.dataformat.yaml.YAMLFactory;
import org.reflections.ReflectionUtils;
import org.reflections.Reflections;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;
import org.reflections.util.FilterBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.util.*;
/**
* A Serializable configuration
* for neural nets that covers per layer parameters
*
* @author Adam Gibson
*/
@Data
@NoArgsConstructor
public class NeuralNetConfiguration implements Serializable, Cloneable {
private static final Logger log = LoggerFactory.getLogger(NeuralNetConfiguration.class);
/**
* System property for custom layers, preprocessors, graph vertices etc. Enabled by default.
* Run JVM with "-Dorg.deeplearning4j.config.custom.enabled=false" to disable classpath scanning for
* Overriding the default (i.e., disabling) this is only useful if (a) no custom layers/preprocessors etc will be
* used, and (b) minimizing startup/initialization time for new JVMs is very important.
* Results are cached, so there is no cost to custom layers after the first network has been constructed.
*/
public static final String CUSTOM_FUNCTIONALITY = "org.deeplearning4j.config.custom.enabled";
protected Layer layer;
@Deprecated
protected double leakyreluAlpha;
//batch size: primarily used for conv nets. Will be reinforced if set.
protected boolean miniBatch = true;
protected int numIterations;
//number of line search iterations
protected int maxNumLineSearchIterations;
protected long seed;
protected OptimizationAlgorithm optimizationAlgo;
//gradient keys used for ensuring order when getting and setting the gradient
protected List<String> variables = new ArrayList<>();
//whether to constrain the gradient to unit norm or not
//adadelta - weight for how much to consider previous history
protected StepFunction stepFunction;
protected boolean useRegularization = false;
protected boolean useDropConnect = false;
//minimize or maximize objective
protected boolean minimize = true;
// Graves LSTM & RNN
protected Map<String, Double> learningRateByParam = new HashMap<>();
protected Map<String, Double> l1ByParam = new HashMap<>();
protected Map<String, Double> l2ByParam = new HashMap<>();
protected LearningRatePolicy learningRatePolicy = LearningRatePolicy.None;
protected double lrPolicyDecayRate;
protected double lrPolicySteps;
protected double lrPolicyPower;
protected boolean pretrain;
//Counter for the number of parameter updates so far for this layer.
//Note that this is only used for pretrain layers (RBM, VAE) - MultiLayerConfiguration and ComputationGraphConfiguration
//contain counters for standard backprop training.
// This is important for learning rate schedules, for example, and is stored here to ensure it is persisted
// for Spark and model serialization
protected int iterationCount = 0;
private static ObjectMapper mapper = initMapper();
private static final ObjectMapper mapperYaml = initMapperYaml();
private static Set<Class<?>> subtypesClassCache = null;
/**
* Creates and returns a deep copy of the configuration.
*/
@Override
public NeuralNetConfiguration clone() {
try {
NeuralNetConfiguration clone = (NeuralNetConfiguration) super.clone();
if (clone.layer != null)
clone.layer = clone.layer.clone();
if (clone.stepFunction != null)
clone.stepFunction = clone.stepFunction.clone();
if (clone.variables != null)
clone.variables = new ArrayList<>(clone.variables);
if (clone.learningRateByParam != null)
clone.learningRateByParam = new HashMap<>(clone.learningRateByParam);
if (clone.l1ByParam != null)
clone.l1ByParam = new HashMap<>(clone.l1ByParam);
if (clone.l2ByParam != null)
clone.l2ByParam = new HashMap<>(clone.l2ByParam);
return clone;
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
public List<String> variables() {
return new ArrayList<>(variables);
}
public List<String> variables(boolean copy) {
if (copy)
return variables();
return variables;
}
public void addVariable(String variable) {
if (!variables.contains(variable)) {
variables.add(variable);
setLayerParamLR(variable);
}
}
public void clearVariables() {
variables.clear();
}
public void setLayerParamLR(String variable) {
double lr = layer.getLearningRateByParam(variable);
double l1 = layer.getL1ByParam(variable);
if (Double.isNaN(l1))
l1 = 0.0; //Not set
double l2 = layer.getL2ByParam(variable);
if (Double.isNaN(l2))
l2 = 0.0; //Not set
learningRateByParam.put(variable, lr);
l1ByParam.put(variable, l1);
l2ByParam.put(variable, l2);
}
public double getLearningRateByParam(String variable) {
return learningRateByParam.get(variable);
}
public void setLearningRateByParam(String variable, double rate) {
learningRateByParam.put(variable, rate);
}
public double getL1ByParam(String variable) {
return l1ByParam.get(variable);
}
public double getL2ByParam(String variable) {
return l2ByParam.get(variable);
}
/**
* Fluent interface for building a list of configurations
*/
public static class ListBuilder extends MultiLayerConfiguration.Builder {
private Map<Integer, Builder> layerwise;
private Builder globalConfig;
// Constructor
public ListBuilder(Builder globalConfig, Map<Integer, Builder> layerMap) {
this.globalConfig = globalConfig;
this.layerwise = layerMap;
}
public ListBuilder(Builder globalConfig) {
this(globalConfig, new HashMap<Integer, Builder>());
}
public ListBuilder backprop(boolean backprop) {
this.backprop = backprop;
return this;
}
public ListBuilder pretrain(boolean pretrain) {
this.pretrain = pretrain;
return this;
}
public ListBuilder layer(int ind, Layer layer) {
if (layerwise.containsKey(ind)) {
layerwise.get(ind).layer(layer);
} else {
layerwise.put(ind, globalConfig.clone().layer(layer));
}
return this;
}
public Map<Integer, Builder> getLayerwise() {
return layerwise;
}
/**
* Build the multi layer network
* based on this neural network and
* overr ridden parameters
* @return the configuration to build
*/
public MultiLayerConfiguration build() {
List<NeuralNetConfiguration> list = new ArrayList<>();
if (layerwise.isEmpty())
throw new IllegalStateException("Invalid configuration: no layers defined");
for (int i = 0; i < layerwise.size(); i++) {
if (layerwise.get(i) == null) {
throw new IllegalStateException("Invalid configuration: layer number " + i
+ " not specified. Expect layer " + "numbers to be 0 to " + (layerwise.size() - 1)
+ " inclusive (number of layers defined: " + layerwise.size() + ")");
}
if (layerwise.get(i).getLayer() == null)
throw new IllegalStateException("Cannot construct network: Layer config for" + "layer with index "
+ i + " is not defined)");
//Layer names: set to default, if not set
if (layerwise.get(i).getLayer().getLayerName() == null) {
layerwise.get(i).getLayer().setLayerName("layer" + i);
}
list.add(layerwise.get(i).build());
}
return new MultiLayerConfiguration.Builder().backprop(backprop).inputPreProcessors(inputPreProcessors)
.pretrain(pretrain).backpropType(backpropType).tBPTTForwardLength(tbpttFwdLength)
.tBPTTBackwardLength(tbpttBackLength).cnnInputSize(this.cnnInputSize)
.setInputType(this.inputType).trainingWorkspaceMode(globalConfig.trainingWorkspaceMode).confs(list).build();
}
}
/**
* Return this configuration as json
* @return this configuration represented as json
*/
public String toYaml() {
ObjectMapper mapper = mapperYaml();
try {
String ret = mapper.writeValueAsString(this);
return ret;
} catch (org.nd4j.shade.jackson.core.JsonProcessingException e) {
throw new RuntimeException(e);
}
}
/**
* Create a neural net configuration from json
* @param json the neural net configuration from json
* @return
*/
public static NeuralNetConfiguration fromYaml(String json) {
ObjectMapper mapper = mapperYaml();
try {
NeuralNetConfiguration ret = mapper.readValue(json, NeuralNetConfiguration.class);
return ret;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Return this configuration as json
* @return this configuration represented as json
*/
public String toJson() {
ObjectMapper mapper = mapper();
try {
String ret = mapper.writeValueAsString(this);
return ret;
} catch (org.nd4j.shade.jackson.core.JsonProcessingException e) {
throw new RuntimeException(e);
}
}
/**
* Create a neural net configuration from json
* @param json the neural net configuration from json
* @return
*/
public static NeuralNetConfiguration fromJson(String json) {
ObjectMapper mapper = mapper();
try {
NeuralNetConfiguration ret = mapper.readValue(json, NeuralNetConfiguration.class);
return ret;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Object mapper for serialization of configurations
* @return
*/
public static ObjectMapper mapperYaml() {
return mapperYaml;
}
private static ObjectMapper initMapperYaml() {
ObjectMapper ret = new ObjectMapper(new YAMLFactory());
configureMapper(ret);
return ret;
}
/**
* Object mapper for serialization of configurations
* @return
*/
public static ObjectMapper mapper() {
return mapper;
}
/**Reinitialize and return the Jackson/json ObjectMapper with additional named types.
* This can be used to add additional subtypes at runtime (i.e., for JSON mapping with
* types defined outside of the main DL4J codebase)
*/
public static ObjectMapper reinitMapperWithSubtypes(Collection<NamedType> additionalTypes) {
mapper.registerSubtypes(additionalTypes.toArray(new NamedType[additionalTypes.size()]));
//Recreate the mapper (via copy), as mapper won't use registered subtypes after first use
mapper = mapper.copy();
return mapper;
}
private static ObjectMapper initMapper() {
ObjectMapper ret = new ObjectMapper();
configureMapper(ret);
return ret;
}
private static void configureMapper(ObjectMapper ret) {
ret.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
ret.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
ret.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);
ret.enable(SerializationFeature.INDENT_OUTPUT);
registerSubtypes(ret);
}
private static synchronized void registerSubtypes(ObjectMapper mapper) {
//Register concrete subtypes for JSON serialization
List<Class<?>> classes = Arrays.<Class<?>>asList(InputPreProcessor.class, ILossFunction.class,
IActivation.class, Layer.class, GraphVertex.class, ReconstructionDistribution.class);
List<String> classNames = new ArrayList<>(6);
for (Class<?> c : classes)
classNames.add(c.getName());
// First: scan the classpath and find all instances of the 'baseClasses' classes
if (subtypesClassCache == null) {
//Check system property:
String prop = System.getProperty(CUSTOM_FUNCTIONALITY);
if (prop != null && !Boolean.parseBoolean(prop)) {
subtypesClassCache = Collections.emptySet();
} else {
List<Class<?>> interfaces = Arrays.<Class<?>>asList(InputPreProcessor.class, ILossFunction.class,
IActivation.class, ReconstructionDistribution.class);
List<Class<?>> classesList = Arrays.<Class<?>>asList(Layer.class, GraphVertex.class);
Collection<URL> urls = ClasspathHelper.forClassLoader();
List<URL> scanUrls = new ArrayList<>();
for (URL u : urls) {
String path = u.getPath();
if (!path.matches(".*/jre/lib/.*jar")) { //Skip JRE/JDK JARs
scanUrls.add(u);
}
}
Reflections reflections = new Reflections(new ConfigurationBuilder().filterInputsBy(new FilterBuilder()
.exclude("^(?!.*\\.class$).*$") //Consider only .class files (to avoid debug messages etc. on .dlls, etc
//Exclude the following: the assumption here is that no custom functionality will ever be present
// under these package name prefixes. These are all common dependencies for DL4J
.exclude("^org.nd4j.*").exclude("^org.datavec.*").exclude("^org.bytedeco.*") //JavaCPP
.exclude("^com.fasterxml.*")//Jackson
.exclude("^org.apache.*") //Apache commons, Spark, log4j etc
.exclude("^org.projectlombok.*").exclude("^com.twelvemonkeys.*").exclude("^org.joda.*")
.exclude("^org.slf4j.*").exclude("^com.google.*").exclude("^org.reflections.*")
.exclude("^ch.qos.*") //Logback
).addUrls(scanUrls).setScanners(new DL4JSubTypesScanner(interfaces, classesList)));
org.reflections.Store store = reflections.getStore();
Iterable<String> subtypesByName = store.getAll(DL4JSubTypesScanner.class.getSimpleName(), classNames);
Set<? extends Class<?>> subtypeClasses = Sets.newHashSet(ReflectionUtils.forNames(subtypesByName));
subtypesClassCache = new HashSet<>();
for (Class<?> c : subtypeClasses) {
if (Modifier.isAbstract(c.getModifiers()) || Modifier.isInterface(c.getModifiers())) {
//log.info("Skipping abstract/interface: {}",c);
continue;
}
subtypesClassCache.add(c);
}
}
}
//Second: get all currently registered subtypes for this mapper
Set<Class<?>> registeredSubtypes = new HashSet<>();
for (Class<?> c : classes) {
AnnotatedClass ac = AnnotatedClass.construct(c, mapper.getSerializationConfig().getAnnotationIntrospector(),
null);
Collection<NamedType> types =
mapper.getSubtypeResolver().collectAndResolveSubtypes(ac, mapper.getSerializationConfig(),
mapper.getSerializationConfig().getAnnotationIntrospector());
for (NamedType nt : types) {
registeredSubtypes.add(nt.getType());
}
}
//Third: register all _concrete_ subtypes that are not already registered
List<NamedType> toRegister = new ArrayList<>();
for (Class<?> c : subtypesClassCache) {
//Check if it's concrete or abstract...
if (Modifier.isAbstract(c.getModifiers()) || Modifier.isInterface(c.getModifiers())) {
//log.info("Skipping abstract/interface: {}",c);
continue;
}
if (!registeredSubtypes.contains(c)) {
String name;
if (ClassUtils.isInnerClass(c)) {
Class<?> c2 = c.getDeclaringClass();
name = c2.getSimpleName() + "$" + c.getSimpleName();
} else {
name = c.getSimpleName();
}
toRegister.add(new NamedType(c, name));
if (log.isDebugEnabled()) {
for (Class<?> baseClass : classes) {
if (baseClass.isAssignableFrom(c)) {
log.debug("Registering class for JSON serialization: {} as subtype of {}", c.getName(),
baseClass.getName());
break;
}
}
}
}
}
mapper.registerSubtypes(toRegister.toArray(new NamedType[toRegister.size()]));
}
@Data
public static class Builder implements Cloneable {
protected IActivation activationFn = new ActivationSigmoid();
protected WeightInit weightInit = WeightInit.XAVIER;
protected double biasInit = 0.0;
protected Distribution dist = null;
protected double learningRate = 1e-1;
protected double biasLearningRate = Double.NaN;
protected Map<Integer, Double> learningRateSchedule = null;
protected double lrScoreBasedDecay;
protected double l1 = Double.NaN;
protected double l2 = Double.NaN;
protected double l1Bias = Double.NaN;
protected double l2Bias = Double.NaN;
protected double dropOut = 0;
protected Updater updater = Updater.SGD;
protected double momentum = Double.NaN;
protected Map<Integer, Double> momentumSchedule = null;
protected double epsilon = Double.NaN;
protected double rho = Double.NaN;
protected double rmsDecay = Double.NaN;
protected double adamMeanDecay = Double.NaN;
protected double adamVarDecay = Double.NaN;
protected Layer layer;
@Deprecated
protected double leakyreluAlpha = 0.01;
protected boolean miniBatch = true;
protected int numIterations = 1;
protected int maxNumLineSearchIterations = 5;
protected long seed = System.currentTimeMillis();
protected boolean useRegularization = false;
protected OptimizationAlgorithm optimizationAlgo = OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT;
protected StepFunction stepFunction = null;
protected boolean useDropConnect = false;
protected boolean minimize = true;
protected GradientNormalization gradientNormalization = GradientNormalization.None;
protected double gradientNormalizationThreshold = 1.0;
protected LearningRatePolicy learningRatePolicy = LearningRatePolicy.None;
protected double lrPolicyDecayRate = Double.NaN;
protected double lrPolicySteps = Double.NaN;
protected double lrPolicyPower = Double.NaN;
protected boolean pretrain = false;
protected WorkspaceMode trainingWorkspaceMode = WorkspaceMode.NONE;
protected WorkspaceMode inferenceWorkspaceMode = WorkspaceMode.SINGLE;
protected ConvolutionMode convolutionMode = ConvolutionMode.Truncate;
public Builder() {
//
}
public Builder(NeuralNetConfiguration newConf) {
if (newConf != null) {
minimize = newConf.minimize;
maxNumLineSearchIterations = newConf.maxNumLineSearchIterations;
layer = newConf.layer;
numIterations = newConf.numIterations;
useRegularization = newConf.useRegularization;
optimizationAlgo = newConf.optimizationAlgo;
seed = newConf.seed;
stepFunction = newConf.stepFunction;
useDropConnect = newConf.useDropConnect;
miniBatch = newConf.miniBatch;
learningRatePolicy = newConf.learningRatePolicy;
lrPolicyDecayRate = newConf.lrPolicyDecayRate;
lrPolicySteps = newConf.lrPolicySteps;
lrPolicyPower = newConf.lrPolicyPower;
pretrain = newConf.pretrain;
}
}
/** Process input as minibatch vs full dataset.
* Default set to true. */
public Builder miniBatch(boolean miniBatch) {
this.miniBatch = miniBatch;
return this;
}
/**
* This method defines Workspace mode being used during training:
* NONE: workspace won't be used
* SINGLE: one workspace will be used during whole iteration loop
* SEPARATE: separate workspaces will be used for feedforward and backprop iteration loops
*
* @param workspaceMode
* @return
*/
public Builder trainingWorkspaceMode(@NonNull WorkspaceMode workspaceMode) {
this.trainingWorkspaceMode = workspaceMode;
return this;
}
/**
* This method defines Workspace mode being used during inference:
* NONE: workspace won't be used
* SINGLE: one workspace will be used during whole iteration loop
* SEPARATE: separate workspaces will be used for feedforward and backprop iteration loops
*
* @param workspaceMode
* @return
*/
public Builder inferenceWorkspaceMode(@NonNull WorkspaceMode workspaceMode) {
this.inferenceWorkspaceMode = workspaceMode;
return this;
}
/**
* Use drop connect: multiply the weight by a binomial sampling wrt the dropout probability.
* Dropconnect probability is set using {@link #dropOut(double)}; this is the probability of retaining a weight
* @param useDropConnect whether to use drop connect or not
* @return the
*/
public Builder useDropConnect(boolean useDropConnect) {
this.useDropConnect = useDropConnect;
return this;
}
/** Objective function to minimize or maximize cost function
* Default set to minimize true. */
public Builder minimize(boolean minimize) {
this.minimize = minimize;
return this;
}
/** Maximum number of line search iterations.
* Only applies for line search optimizers: Line Search SGD, Conjugate Gradient, LBFGS
* is NOT applicable for standard SGD
* @param maxNumLineSearchIterations > 0
* @return
*/
public Builder maxNumLineSearchIterations(int maxNumLineSearchIterations) {
this.maxNumLineSearchIterations = maxNumLineSearchIterations;
return this;
}
/** Layer class. */
public Builder layer(Layer layer) {
this.layer = layer;
return this;
}
/** Step function to apply for back track line search.
* Only applies for line search optimizers: Line Search SGD, Conjugate Gradient, LBFGS
* Options: DefaultStepFunction (default), NegativeDefaultStepFunction
* GradientStepFunction (for SGD), NegativeGradientStepFunction */
public Builder stepFunction(StepFunction stepFunction) {
this.stepFunction = stepFunction;
return this;
}
/**Create a ListBuilder (for creating a MultiLayerConfiguration)<br>
* Usage:<br>
* <pre>
* {@code .list()
* .layer(0,new DenseLayer.Builder()...build())
* ...
* .layer(n,new OutputLayer.Builder()...build())
* }
* </pre>
* */
public ListBuilder list() {
return new ListBuilder(this);
}
/**Create a ListBuilder (for creating a MultiLayerConfiguration) with the specified layers<br>
* Usage:<br>
* <pre>
* {@code .list(
* new DenseLayer.Builder()...build(),
* ...,
* new OutputLayer.Builder()...build())
* }
* </pre>
* @param layers The layer configurations for the network
*/
public ListBuilder list(Layer... layers) {
if (layers == null || layers.length == 0)
throw new IllegalArgumentException("Cannot create network with no layers");
Map<Integer, Builder> layerMap = new HashMap<>();
for (int i = 0; i < layers.length; i++) {
Builder b = this.clone();
b.layer(layers[i]);
layerMap.put(i, b);
}
return new ListBuilder(this, layerMap);
}
/**
* Create a GraphBuilder (for creating a ComputationGraphConfiguration).
*/
public ComputationGraphConfiguration.GraphBuilder graphBuilder() {
return new ComputationGraphConfiguration.GraphBuilder(this);
}
/** Number of optimization iterations. */
public Builder iterations(int numIterations) {
this.numIterations = numIterations;
return this;
}
/** Random number generator seed. Used for reproducability between runs */
public Builder seed(int seed) {
this.seed = (long) seed;
Nd4j.getRandom().setSeed(seed);
return this;
}
/** Random number generator seed. Used for reproducability between runs */
public Builder seed(long seed) {
this.seed = seed;
Nd4j.getRandom().setSeed(seed);
return this;
}
/**
* Optimization algorithm to use. Most common: OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT
*
* @param optimizationAlgo Optimization algorithm to use when training
*/
public Builder optimizationAlgo(OptimizationAlgorithm optimizationAlgo) {
this.optimizationAlgo = optimizationAlgo;
return this;
}
/** Whether to use regularization (l1, l2, dropout, etc */
public Builder regularization(boolean useRegularization) {
this.useRegularization = useRegularization;
return this;
}
@Override
public Builder clone() {
try {
Builder clone = (Builder) super.clone();
if (clone.layer != null)
clone.layer = clone.layer.clone();
if (clone.stepFunction != null)
clone.stepFunction = clone.stepFunction.clone();
return clone;
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
/**Activation function / neuron non-linearity
* Typical values include:<br>
* "relu" (rectified linear), "tanh", "sigmoid", "softmax",
* "hardtanh", "leakyrelu", "maxout", "softsign", "softplus"
* @deprecated Use {@link #activation(Activation)} or
* {@link @activation(IActivation)}
*/
@Deprecated
public Builder activation(String activationFunction) {
return activation(Activation.fromString(activationFunction).getActivationFunction());
}
/**Activation function / neuron non-linearity
* @see #activation(Activation)
*/
public Builder activation(IActivation activationFunction) {
this.activationFn = activationFunction;
return this;
}
/**Activation function / neuron non-linearity
*/
public Builder activation(Activation activation) {
return activation(activation.getActivationFunction());
}
/**
* @deprecated Use {@link #activation(IActivation)} with leaky relu, setting alpha value directly in constructor.
*/
@Deprecated
public Builder leakyreluAlpha(double leakyreluAlpha) {
this.leakyreluAlpha = leakyreluAlpha;
return this;
}
/** Weight initialization scheme.
* @see org.deeplearning4j.nn.weights.WeightInit
*/
public Builder weightInit(WeightInit weightInit) {
this.weightInit = weightInit;
return this;
}
/**
* Constant for bias initialization. Default: 0.0
*
* @param biasInit Constant for bias initialization
*/
public Builder biasInit(double biasInit) {
this.biasInit = biasInit;
return this;
}
/** Distribution to sample initial weights from. Used in conjunction with
* .weightInit(WeightInit.DISTRIBUTION).
*/
public Builder dist(Distribution dist) {
this.dist = dist;
return this;
}
/** Learning rate. Defaults to 1e-1*/
public Builder learningRate(double learningRate) {
this.learningRate = learningRate;
return this;
}
/** Bias learning rate. Set this to apply a different learning rate to the bias*/
public Builder biasLearningRate(double biasLearningRate) {
this.biasLearningRate = biasLearningRate;
return this;
}
/** Learning rate schedule. Map of the iteration to the learning rate to apply at that iteration. */
public Builder learningRateSchedule(Map<Integer, Double> learningRateSchedule) {
this.learningRateSchedule = learningRateSchedule;
return this;
}
/** Rate to decrease learningRate by when the score stops improving.
* Learning rate is multiplied by this rate so ideally keep between 0 and 1. */
public Builder learningRateScoreBasedDecayRate(double lrScoreBasedDecay) {
this.lrScoreBasedDecay = lrScoreBasedDecay;
return this;
}
/** L1 regularization coefficient for the weights.
* Use with .regularization(true)
*/
public Builder l1(double l1) {
this.l1 = l1;
return this;
}
/** L2 regularization coefficient for the weights.
* Use with .regularization(true)
*/
public Builder l2(double l2) {
this.l2 = l2;
return this;
}
/** L1 regularization coefficient for the bias.
* Use with .regularization(true)
*/
public Builder l1Bias(double l1Bias) {
this.l1Bias = l1Bias;
return this;
}
/** L2 regularization coefficient for the bias.
* Use with .regularization(true)
*/
public Builder l2Bias(double l2Bias) {
this.l2Bias = l2Bias;
return this;
}
/**
* Dropout probability. This is the probability of <it>retaining</it> an activation. So dropOut(x) will keep an
* activation with probability x, and set to 0 with probability 1-x.<br>
* dropOut(0.0) is disabled (default).
*
* @param dropOut Dropout probability (probability of retaining an activation)
*/
public Builder dropOut(double dropOut) {
this.dropOut = dropOut;
return this;
}
/** Momentum rate
* Used only when Updater is set to {@link Updater#NESTEROVS}
*/
public Builder momentum(double momentum) {
this.momentum = momentum;
return this;
}
/** Momentum schedule. Map of the iteration to the momentum rate to apply at that iteration
* Used only when Updater is set to {@link Updater#NESTEROVS}
*/
public Builder momentumAfter(Map<Integer, Double> momentumAfter) {
this.momentumSchedule = momentumAfter;
return this;
}
/** Gradient updater. For example, Updater.SGD for standard stochastic gradient descent,
* Updater.NESTEROV for Nesterov momentum, Updater.RSMPROP for RMSProp, etc.
* @see Updater
*/
public Builder updater(Updater updater) {
this.updater = updater;
return this;
}
/**
* Ada delta coefficient
* @param rho
*/
public Builder rho(double rho) {
this.rho = rho;
return this;
}
/**
* Epsilon value for updaters: Adam, RMSProp, Adagrad, Adadelta
* Default values: {@link Adam#DEFAULT_ADAM_EPSILON}, {@link RmsProp#DEFAULT_RMSPROP_EPSILON}, {@link AdaGrad#DEFAULT_ADAGRAD_EPSILON},
* {@link AdaDelta#DEFAULT_ADADELTA_EPSILON}
*
* @param epsilon Epsilon value to use for adagrad or
*/
public Builder epsilon(double epsilon) {
this.epsilon = epsilon;
return this;
}
/** Decay rate for RMSProp. Only applies if using .updater(Updater.RMSPROP)
*/
public Builder rmsDecay(double rmsDecay) {
this.rmsDecay = rmsDecay;
return this;
}
/** Mean decay rate for Adam updater. Only applies if using .updater(Updater.ADAM) */
public Builder adamMeanDecay(double adamMeanDecay) {
this.adamMeanDecay = adamMeanDecay;
return this;
}
/** Variance decay rate for Adam updater. Only applies if using .updater(Updater.ADAM) */
public Builder adamVarDecay(double adamVarDecay) {
this.adamVarDecay = adamVarDecay;
return this;
}
/** Gradient normalization strategy. Used to specify gradient renormalization, gradient clipping etc.
* @param gradientNormalization Type of normalization to use. Defaults to None.
* @see GradientNormalization
*/
public Builder gradientNormalization(GradientNormalization gradientNormalization) {
this.gradientNormalization = gradientNormalization;
return this;
}
/** Threshold for gradient normalization, only used for GradientNormalization.ClipL2PerLayer,
* GradientNormalization.ClipL2PerParamType, and GradientNormalization.ClipElementWiseAbsoluteValue<br>
* Not used otherwise.<br>
* L2 threshold for first two types of clipping, or absolute value threshold for last type of clipping.
*/
public Builder gradientNormalizationThreshold(double threshold) {
this.gradientNormalizationThreshold = threshold;
return this;
}
/** Learning rate decay policy. Used to adapt learning rate based on policy.
* @param policy Type of policy to use. Defaults to None.
*/
public Builder learningRateDecayPolicy(LearningRatePolicy policy) {
this.learningRatePolicy = policy;
return this;
}
/** Set the decay rate for the learning rate decay policy.
* @param lrPolicyDecayRate rate.
*/
public Builder lrPolicyDecayRate(double lrPolicyDecayRate) {
this.lrPolicyDecayRate = lrPolicyDecayRate;
return this;
}
/** Set the number of steps used for learning decay rate steps policy.
* @param lrPolicySteps number of steps
*/
public Builder lrPolicySteps(double lrPolicySteps) {
this.lrPolicySteps = lrPolicySteps;
return this;
}
/** Set the power used for learning rate inverse policy.
* @param lrPolicyPower power
*/
public Builder lrPolicyPower(double lrPolicyPower) {
this.lrPolicyPower = lrPolicyPower;
return this;
}
public Builder convolutionMode(ConvolutionMode convolutionMode) {
this.convolutionMode = convolutionMode;
return this;
}
private void learningRateValidation(String layerName) {
if (learningRatePolicy != LearningRatePolicy.None && Double.isNaN(lrPolicyDecayRate)) {
//LR policy, if used, should have a decay rate. 2 exceptions: Map for schedule, and Poly + power param
if (!(learningRatePolicy == LearningRatePolicy.Schedule && learningRateSchedule != null)
&& !(learningRatePolicy == LearningRatePolicy.Poly && !Double.isNaN(lrPolicyPower)))
throw new IllegalStateException("Layer \"" + layerName
+ "\" learning rate policy decay rate (lrPolicyDecayRate) must be set to use learningRatePolicy.");
}
switch (learningRatePolicy) {
case Inverse:
case Poly:
if (Double.isNaN(lrPolicyPower))
throw new IllegalStateException("Layer \"" + layerName
+ "\" learning rate policy power (lrPolicyPower) must be set to use "
+ learningRatePolicy);
break;
case Step:
case Sigmoid:
if (Double.isNaN(lrPolicySteps))
throw new IllegalStateException("Layer \"" + layerName
+ "\" learning rate policy steps (lrPolicySteps) must be set to use "
+ learningRatePolicy);
break;
case Schedule:
if (learningRateSchedule == null)
throw new IllegalStateException("Layer \"" + layerName
+ "\" learning rate policy schedule (learningRateSchedule) must be set to use "
+ learningRatePolicy);
break;
}
if (!Double.isNaN(lrPolicyPower) && (learningRatePolicy != LearningRatePolicy.Inverse
&& learningRatePolicy != LearningRatePolicy.Poly))
throw new IllegalStateException("Layer \"" + layerName
+ "\" power has been set but will not be applied unless the learning rate policy is set to Inverse or Poly.");
if (!Double.isNaN(lrPolicySteps) && (learningRatePolicy != LearningRatePolicy.Step
&& learningRatePolicy != LearningRatePolicy.Sigmoid
&& learningRatePolicy != LearningRatePolicy.TorchStep))
throw new IllegalStateException("Layer \"" + layerName
+ "\" steps have been set but will not be applied unless the learning rate policy is set to Step or Sigmoid.");
if ((learningRateSchedule != null) && (learningRatePolicy != LearningRatePolicy.Schedule))
throw new IllegalStateException("Layer \"" + layerName
+ "\" learning rate schedule has been set but will not be applied unless the learning rate policy is set to Schedule.");
}
////////////////
/**
* Return a configuration based on this builder
*
* @return
*/
public NeuralNetConfiguration build() {
NeuralNetConfiguration conf = new NeuralNetConfiguration();
conf.minimize = minimize;
conf.maxNumLineSearchIterations = maxNumLineSearchIterations;
conf.layer = layer;
conf.numIterations = numIterations;
conf.useRegularization = useRegularization;
conf.optimizationAlgo = optimizationAlgo;
conf.seed = seed;
conf.stepFunction = stepFunction;
conf.useDropConnect = useDropConnect;
conf.miniBatch = miniBatch;
conf.learningRatePolicy = learningRatePolicy;
conf.lrPolicyDecayRate = lrPolicyDecayRate;
conf.lrPolicySteps = lrPolicySteps;
conf.lrPolicyPower = lrPolicyPower;
conf.pretrain = pretrain;
String layerName;
if (layer == null || layer.getLayerName() == null)
layerName = "Layer not named";
else
layerName = layer.getLayerName();
learningRateValidation(layerName);
if (layer != null) {
if (Double.isNaN(layer.getLearningRate()))
layer.setLearningRate(learningRate);
if (Double.isNaN(layer.getBiasLearningRate())) {
//Two possibilities when bias LR isn't set for layer:
// (a) If global bias LR *is* set -> set it to that
// (b) Otherwise, set to layer LR (and, by extension, the global LR)
if (!Double.isNaN(biasLearningRate)) {
//Global bias LR is set
layer.setBiasLearningRate(biasLearningRate);
} else {
layer.setBiasLearningRate(layer.getLearningRate());
}
}
if (layer.getLearningRateSchedule() == null)
layer.setLearningRateSchedule(learningRateSchedule);
if (Double.isNaN(layer.getL1()))
layer.setL1(l1);
if (Double.isNaN(layer.getL2()))
layer.setL2(l2);
if (layer.getActivationFn() == null)
layer.setActivationFn(activationFn);
if (layer.getWeightInit() == null)
layer.setWeightInit(weightInit);
if (Double.isNaN(layer.getBiasInit()))
layer.setBiasInit(biasInit);
if (Double.isNaN(layer.getDropOut()))
layer.setDropOut(dropOut);
if (layer.getUpdater() == null)
layer.setUpdater(updater);
// updaterValidation(layerName);
LayerValidation.updaterValidation(layerName, layer, momentum, momentumSchedule, adamMeanDecay,
adamVarDecay, rho, rmsDecay, epsilon);
if (layer.getGradientNormalization() == null)
layer.setGradientNormalization(gradientNormalization);
if (Double.isNaN(layer.getGradientNormalizationThreshold()))
layer.setGradientNormalizationThreshold(gradientNormalizationThreshold);
if (layer instanceof ConvolutionLayer) {
ConvolutionLayer cl = (ConvolutionLayer) layer;
if (cl.getConvolutionMode() == null) {
cl.setConvolutionMode(convolutionMode);
}
}
if (layer instanceof SubsamplingLayer) {
SubsamplingLayer sl = (SubsamplingLayer) layer;
if (sl.getConvolutionMode() == null) {
sl.setConvolutionMode(convolutionMode);
}
}
}
LayerValidation.generalValidation(layerName, layer, useRegularization, useDropConnect, dropOut, l2, l2Bias,
l1, l1Bias, dist);
return conf;
}
}
}
| Update dropout javadoc. | deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/conf/NeuralNetConfiguration.java | Update dropout javadoc. | <ide><path>eeplearning4j-nn/src/main/java/org/deeplearning4j/nn/conf/NeuralNetConfiguration.java
<ide> * Dropout probability. This is the probability of <it>retaining</it> an activation. So dropOut(x) will keep an
<ide> * activation with probability x, and set to 0 with probability 1-x.<br>
<ide> * dropOut(0.0) is disabled (default).
<add> * <p>
<add> * Note: This sets the probability per-layer. Care should be taken when setting lower values for complex networks.
<add> * </p>
<ide> *
<ide> * @param dropOut Dropout probability (probability of retaining an activation)
<ide> */ |
|
Java | mit | a638921178070be8918a3e71e73c597d9020c21a | 0 | funIntentions/chitchat | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.lamepancake.chitchat.DAO;
import com.lamepancake.chitchat.Chat;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author shane
*/
public class ChatDAOMySQLImpl extends MySQLDAOBase implements ChatDAO {
private static ChatDAOMySQLImpl inst;
private final PreparedStatement chatByIDStatement;
private final PreparedStatement chatByNameStatement;
private final PreparedStatement createChatStatement;
private final PreparedStatement updateChatStatement;
private final PreparedStatement deleteChatStatement;
public static void init(String username, String password) throws SQLException
{
final String initTable = "CREATE TABLE IF NOT EXISTS `chat` (" +
" `chatId` smallint(5) unsigned NOT NULL AUTO_INCREMENT," +
" `name` varchar(30) NOT NULL," +
" PRIMARY KEY (`chatId`)" +
") ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=latin1";
if(inst != null)
throw new UnsupportedOperationException("The ChatDAO has already been initialised.");
inst = new ChatDAOMySQLImpl(username, password, initTable);
}
public static ChatDAOMySQLImpl getInstance() throws SQLException
{
if(inst == null)
init(DEFAULT_UNAME, DEFAULT_PASS);
return inst;
}
private ChatDAOMySQLImpl(final String username, final String password, final String initTable) throws SQLException
{
super(username, password, initTable);
final String chatByID = "SELECT * FROM `chat` WHERE chatId= ?";
final String chatByName = "SELECT * FROM `chat` WHERE name= ?";
final String chatUsers = "SELECT * FROM `user` JOIN `chat_user` ON `user`.`userId`=`chat_user`.`userId` AND `chat_user`.`chatId` = ?";
final String createChat = "INSERT INTO `chat`(`name`) VALUES(?)";
final String updateChat = "UPDATE `chat` SET `name`= ? WHERE `chatId`= ?";
final String deleteChat = "DELETE FROM `chat` WHERE `chatId`= ?";
try {
chatByIDStatement = con.prepareStatement(chatByID);
chatByNameStatement = con.prepareStatement(chatByName);
createChatStatement = con.prepareStatement(createChat);
updateChatStatement = con.prepareStatement(updateChat);
deleteChatStatement = con.prepareStatement(deleteChat);
} catch(SQLException se) {
System.err.println("ChatDAOMySQLImpl constructor: could not prepare statements.");
throw(se);
}
}
@Override
public List<Chat> getAllChats() throws SQLException
{
List<Chat> chats;
int id;
String name;
String password;
queryResults = query.executeQuery("SELECT * FROM `chat`;");
chats = new ArrayList<>();
while(queryResults.next())
{
Chat nextChat;
id = queryResults.getInt("chatId");
name = queryResults.getString("name");
nextChat = new Chat(name, id);
chats.add(nextChat);
}
return chats;
}
@Override
public Chat getByID(int id) throws SQLException
{
Chat c;
final int chatID;
final String name;
chatByIDStatement.clearParameters();
chatByIDStatement.setInt(1, id);
queryResults = chatByIDStatement.executeQuery();
if(!queryResults.next())
return null;
chatID = queryResults.getInt("chatId");
name = queryResults.getString("name");;
c = new Chat(name, chatID);
return c;
}
@Override
public Chat getByName(String name) throws SQLException
{
Chat c;
final int chatID;
final String chatName;
chatByNameStatement.clearParameters();
chatByNameStatement.setString(1, name);
queryResults = chatByNameStatement.executeQuery();
if(!queryResults.next())
return null;
chatID = queryResults.getInt("chatId");
chatName = queryResults.getString("name");
c = new Chat(chatName, chatID);
return c;
}
@Override
public int create(Chat c) throws SQLException
{
int id = -1;
createChatStatement.clearParameters();
createChatStatement.setString(1, c.getName());
createChatStatement.executeUpdate();
queryResults = query.executeQuery("SELECT MAX(`chatId`) FROM `chat`");
if(queryResults.next())
id = queryResults.getInt(1);
return id;
}
@Override
public void update(Chat c) throws SQLException
{
updateChatStatement.clearParameters();
updateChatStatement.setString(1, c.getName());
updateChatStatement.setInt(2, c.getID());
updateChatStatement.executeUpdate();
}
@Override
public void delete(Chat c) throws SQLException
{
deleteChatStatement.clearParameters();
deleteChatStatement.setInt(1, c.getID());
deleteChatStatement.executeUpdate();
}
}
| src/com/lamepancake/chitchat/DAO/ChatDAOMySQLImpl.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.lamepancake.chitchat.DAO;
import com.lamepancake.chitchat.Chat;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author shane
*/
public class ChatDAOMySQLImpl extends MySQLDAOBase implements ChatDAO {
private static ChatDAOMySQLImpl inst;
private final PreparedStatement chatByIDStatement;
private final PreparedStatement chatByNameStatement;
private final PreparedStatement createChatStatement;
private final PreparedStatement updateChatStatement;
private final PreparedStatement deleteChatStatement;
public static void init(String username, String password) throws SQLException
{
final String initTable = "CREATE TABLE IF NOT EXISTS `chat` (" +
" `chatId` smallint(5) unsigned NOT NULL AUTO_INCREMENT," +
" `name` varchar(30) NOT NULL," +
" PRIMARY KEY (`chatId`)" +
") ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=latin1";
if(inst != null)
throw new UnsupportedOperationException("The ChatDAO has already been initialised.");
inst = new ChatDAOMySQLImpl(username, password, initTable);
}
public static ChatDAOMySQLImpl getInstance() throws SQLException
{
if(inst == null)
init(DEFAULT_UNAME, DEFAULT_PASS);
return inst;
}
private ChatDAOMySQLImpl(final String username, final String password, final String initTable) throws SQLException
{
super(username, password, initTable);
final String chatByID = "SELECT * FROM `chat` WHERE chatId= ?";
final String chatByName = "SELECT * FROM `chat` WHERE name= ?";
final String chatUsers = "SELECT * FROM `user` JOIN `chat_user` ON `user`.`userId`=`chat_user`.`userId` AND `chat_user`.`chatId` = ?";
final String createChat = "INSERT INTO `chat`(`name`) VALUES(?)";
final String updateChat = "UPDATE `chat` SET `name`= ? WHERE `chatId`= ?";
final String deleteChat = "DELETE FROM `chat` WHERE `chatId`= ?";
try {
chatByIDStatement = con.prepareStatement(chatByID);
chatByNameStatement = con.prepareStatement(chatByName);
createChatStatement = con.prepareStatement(createChat);
updateChatStatement = con.prepareStatement(updateChat);
deleteChatStatement = con.prepareStatement(deleteChat);
} catch(SQLException se) {
System.err.println("ChatDAOMySQLImpl constructor: could not prepare statements.");
throw(se);
}
}
@Override
public List<Chat> getAllChats() throws SQLException
{
List<Chat> chats;
int id;
String name;
String password;
queryResults = query.executeQuery("SELECT * FROM `chat`;");
chats = new ArrayList<>();
while(queryResults.next())
{
Chat nextChat;
id = queryResults.getInt("chatId");
name = queryResults.getString("name");
nextChat = new Chat(name, id);
chats.add(nextChat);
}
return chats;
}
@Override
public Chat getByID(int id) throws SQLException
{
Chat c;
final int chatID;
final String name;
chatByIDStatement.clearParameters();
chatByIDStatement.setInt(1, id);
queryResults = chatByIDStatement.executeQuery();
if(!queryResults.next())
return null;
chatID = queryResults.getInt("chatId");
name = queryResults.getString("name");;
c = new Chat(name, chatID);
return c;
}
@Override
public Chat getByName(String name) throws SQLException
{
Chat c;
final int chatID;
final String chatName;
chatByNameStatement.clearParameters();
chatByNameStatement.setString(1, name);
queryResults = chatByNameStatement.executeQuery();
if(!queryResults.next())
return null;
chatID = queryResults.getInt("chatId");
chatName = queryResults.getString("name");
c = new Chat(chatName, chatID);
return c;
}
@Override
public int create(Chat c) throws SQLException
{
createChatStatement.clearParameters();
createChatStatement.setString(1, c.getName());
createChatStatement.executeUpdate();
if(queryResults.next())
queryResults = query.executeQuery("SELECT MAX(`chatId`) FROM `chat`");
return queryResults.getInt(0);
}
@Override
public void update(Chat c) throws SQLException
{
updateChatStatement.clearParameters();
updateChatStatement.setString(1, c.getName());
updateChatStatement.setInt(2, c.getID());
updateChatStatement.executeUpdate();
}
@Override
public void delete(Chat c) throws SQLException
{
deleteChatStatement.clearParameters();
deleteChatStatement.setInt(1, c.getID());
deleteChatStatement.executeUpdate();
}
}
| Fix database bug; expose null pointer (can't find it)
| src/com/lamepancake/chitchat/DAO/ChatDAOMySQLImpl.java | Fix database bug; expose null pointer (can't find it) | <ide><path>rc/com/lamepancake/chitchat/DAO/ChatDAOMySQLImpl.java
<ide>
<ide> @Override
<ide> public int create(Chat c) throws SQLException
<del> {
<add> {
<add> int id = -1;
<ide> createChatStatement.clearParameters();
<ide> createChatStatement.setString(1, c.getName());
<ide> createChatStatement.executeUpdate();
<ide>
<add> queryResults = query.executeQuery("SELECT MAX(`chatId`) FROM `chat`");
<ide> if(queryResults.next())
<del> queryResults = query.executeQuery("SELECT MAX(`chatId`) FROM `chat`");
<del>
<del> return queryResults.getInt(0);
<add> id = queryResults.getInt(1);
<add>
<add> return id;
<ide> }
<ide>
<ide> @Override |
|
Java | apache-2.0 | d4513d62e69bd461b6a4dc987bff7730148ee8aa | 0 | sanderginn/isis,incodehq/isis,estatio/isis,incodehq/isis,sanderginn/isis,peridotperiod/isis,sanderginn/isis,peridotperiod/isis,howepeng/isis,estatio/isis,apache/isis,kidaa/isis,incodehq/isis,kidaa/isis,oscarbou/isis,howepeng/isis,apache/isis,niv0/isis,niv0/isis,niv0/isis,estatio/isis,peridotperiod/isis,oscarbou/isis,apache/isis,apache/isis,apache/isis,incodehq/isis,oscarbou/isis,sanderginn/isis,howepeng/isis,peridotperiod/isis,apache/isis,oscarbou/isis,kidaa/isis,kidaa/isis,estatio/isis,howepeng/isis,niv0/isis | /*
* 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 integration.tests;
import dom.todo.ToDoItem;
import dom.todo.ToDoItemSubscriptions;
import dom.todo.ToDoItems;
import fixture.todo.integtests.ToDoItemsIntegTestFixture;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.util.EventObject;
import java.util.List;
import javax.activation.MimeType;
import javax.inject.Inject;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.jmock.Expectations;
import org.jmock.Sequence;
import org.jmock.auto.Mock;
import org.joda.time.LocalDate;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.apache.isis.applib.NonRecoverableException;
import org.apache.isis.applib.RecoverableException;
import org.apache.isis.applib.clock.Clock;
import org.apache.isis.applib.fixturescripts.FixtureScripts;
import org.apache.isis.applib.services.clock.ClockService;
import org.apache.isis.applib.services.eventbus.AbstractInteractionEvent;
import org.apache.isis.applib.services.eventbus.ActionInteractionEvent;
import org.apache.isis.applib.services.eventbus.CollectionInteractionEvent;
import org.apache.isis.applib.services.eventbus.EventBusService;
import org.apache.isis.applib.services.eventbus.PropertyInteractionEvent;
import org.apache.isis.applib.value.Blob;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat;
public class ToDoItemIntegTest extends AbstractToDoIntegTest {
ToDoItemsIntegTestFixture fixture;
@Before
public void setUpData() throws Exception {
// executing the fixtures directly allows us to look up the results later.
fixtureScripts.runFixtureScript(fixture = new ToDoItemsIntegTestFixture(), null);
}
@Inject
FixtureScripts fixtureScripts;
@Inject
ToDoItems toDoItems;
@Inject
ToDoItemSubscriptions toDoItemSubscriptions;
ToDoItem toDoItem;
@Before
public void setUp() throws Exception {
final List<ToDoItem> all = toDoItems.notYetComplete();
toDoItem = wrap(all.get(0));
}
@After
public void tearDown() throws Exception {
toDoItemSubscriptions.reset();
}
public static class Title extends ToDoItemIntegTest {
private LocalDate dueBy;
@Before
public void setUp() throws Exception {
super.setUp();
final List<ToDoItem> all = wrap(toDoItems).notYetComplete();
toDoItem = wrap(all.get(0));
toDoItem = wrap(fixture.lookup("integ-test/to-do-items-recreate-and-complete-several/to-do-items-recreate/to-do-item-for-buy-bread/item-1", ToDoItem.class));
assertThat(toDoItem, is(not(nullValue())));
nextTransaction();
dueBy = toDoItem.getDueBy();
}
@Test
public void includesDescription() throws Exception {
// given
assertThat(container().titleOf(toDoItem), containsString("Buy bread due by"));
// when
unwrap(toDoItem).setDescription("Buy bread and butter");
// then
assertThat(container().titleOf(toDoItem), containsString("Buy bread and butter due by"));
}
@Test
public void includesDueDateIfAny() throws Exception {
// given
assertThat(container().titleOf(toDoItem), containsString("due by " + dueBy.toString("yyyy-MM-dd")));
// when
final LocalDate fiveDaysFromNow = Clock.getTimeAsLocalDate().plusDays(5);
unwrap(toDoItem).setDueBy(fiveDaysFromNow);
// then
assertThat(container().titleOf(toDoItem), containsString("due by " + fiveDaysFromNow.toString("yyyy-MM-dd")));
}
@Test
public void ignoresDueDateIfNone() throws Exception {
// when
// (since wrapped, will call clearDueBy)
toDoItem.setDueBy(null);
// then
assertThat(container().titleOf(toDoItem), not(containsString("due by")));
}
@Test
public void usesWhetherCompleted() throws Exception {
// given
assertThat(container().titleOf(toDoItem), not(containsString("Completed!")));
// when
toDoItem.completed();
// then
assertThat(container().titleOf(toDoItem), not(containsString("due by")));
assertThat(container().titleOf(toDoItem), containsString("Buy bread - Completed!"));
}
}
public static class Actions {
public static class Completed extends ToDoItemIntegTest {
@Test
public void happyCase() throws Exception {
// given
assertThat(toDoItem.isComplete(), is(false));
// when
toDoItem.completed();
// then
assertThat(toDoItem.isComplete(), is(true));
}
@Test
public void cannotCompleteIfAlreadyCompleted() throws Exception {
// given
unwrap(toDoItem).setComplete(true);
// when, then should fail
expectedExceptions.expectMessage("Already completed");
toDoItem.completed();
// and then
final EventObject ev = toDoItemSubscriptions.mostRecentlyReceivedEvent(EventObject.class);
assertThat(ev, is(nullValue()));
}
@Test
public void cannotSetPropertyDirectly() throws Exception {
// given
// when, then should fail
expectedExceptions.expectMessage("Always disabled");
toDoItem.setComplete(true);
// and then
final EventObject ev = toDoItemSubscriptions.mostRecentlyReceivedEvent(EventObject.class);
assertThat(ev, is(nullValue()));
}
@Test
public void subscriberReceivesEvents() throws Exception {
// given
toDoItemSubscriptions.reset();
assertThat(toDoItemSubscriptions.getSubscriberBehaviour(), is(ToDoItemSubscriptions.Behaviour.AnyExecuteAccept));
assertThat(unwrap(toDoItem).isComplete(), is(false));
// when
toDoItem.completed();
// then
assertThat(unwrap(toDoItem).isComplete(), is(true));
// and then
final List<ToDoItem.CompletedEvent> receivedEvents = toDoItemSubscriptions.receivedEvents(ToDoItem.CompletedEvent.class);
// hide, disable, validate, executing, executed
// sent to both the general on(ActionInteractionEvent ev)
// and also the specific on(final ToDoItem.CompletedEvent ev)
assertThat(receivedEvents.size(), is(5*2));
final ToDoItem.CompletedEvent ev = receivedEvents.get(0);
ToDoItem source = ev.getSource();
assertThat(source, is(equalTo(unwrap(toDoItem))));
assertThat(ev.getIdentifier().getMemberName(), is("completed"));
}
@Test
public void subscriberVetoesEventWithRecoverableException() throws Exception {
// given
toDoItemSubscriptions.subscriberBehaviour(ToDoItemSubscriptions.Behaviour.AnyExecuteVetoWithRecoverableException);
// then
expectedExceptions.expect(RecoverableException.class);
// when
toDoItem.completed();
}
@Test
public void subscriberVetoesEventWithNonRecoverableException() throws Exception {
// given
toDoItemSubscriptions.subscriberBehaviour(ToDoItemSubscriptions.Behaviour.AnyExecuteVetoWithNonRecoverableException);
// then
expectedExceptions.expect(NonRecoverableException.class);
// when
toDoItem.completed();
}
@Test
public void subscriberVetoesEventWithAnyOtherException() throws Exception {
// given
toDoItemSubscriptions.subscriberBehaviour(ToDoItemSubscriptions.Behaviour.AnyExecuteVetoWithOtherException);
// then
expectedExceptions.expect(RuntimeException.class);
// when
toDoItem.completed();
}
}
/**
* This test demonstrates how a single service can be replaced, eg to use a mock.
*/
public static class Completed_withMockService extends ToDoItemIntegTest {
private EventBusService originalEventBusService;
@Mock
private EventBusService mockEventBusService;
@Before
public void setUpMockEventBusService() throws Exception {
originalEventBusService = scenarioExecution().service(EventBusService.class);
context.checking(new Expectations() {{
ignoring(mockEventBusService).register(with(any(Object.class)));
ignoring(mockEventBusService).unregister(with(any(Object.class)));
}});
scenarioExecution().replaceService(originalEventBusService, mockEventBusService);
scenarioExecution().closeSession();
scenarioExecution().openSession();
final List<ToDoItem> all = toDoItems.notYetComplete();
toDoItem = wrap(all.get(0));
}
@After
public void reinstateOriginalEventBusService() throws Exception {
scenarioExecution().replaceService(mockEventBusService, originalEventBusService);
}
@Test
public void raisesEvent() throws Exception {
final Sequence busRulesThenExec = context.sequence("busRulesThenExec");
// then
context.checking(new Expectations() {{
oneOf(mockEventBusService).post(with(completedEvent(AbstractInteractionEvent.Phase.HIDE)));
inSequence(busRulesThenExec);
oneOf(mockEventBusService).post(with(completedEvent(AbstractInteractionEvent.Phase.DISABLE)));
inSequence(busRulesThenExec);
oneOf(mockEventBusService).post(with(completedEvent(AbstractInteractionEvent.Phase.VALIDATE)));
inSequence(busRulesThenExec);
oneOf(mockEventBusService).post(with(completedEvent(AbstractInteractionEvent.Phase.EXECUTING)));
inSequence(busRulesThenExec);
oneOf(mockEventBusService).post(with(completedEvent(AbstractInteractionEvent.Phase.EXECUTED)));
inSequence(busRulesThenExec);
}});
// when
toDoItem.completed();
}
private Matcher<Object> completedEvent(final AbstractInteractionEvent.Phase phase) {
return new TypeSafeMatcher<Object>() {
@Override
protected boolean matchesSafely(Object item) {
if (!(item instanceof ToDoItem.CompletedEvent)) {
return false;
}
final ToDoItem.CompletedEvent completedEvent = (ToDoItem.CompletedEvent) item;
return completedEvent.getPhase() == phase;
}
@Override
public void describeTo(Description description) {
description.appendText(" instance of a ToDoItem.CompletedEvent, " + phase);
}
};
}
}
public static class Duplicate extends ToDoItemIntegTest {
ToDoItem duplicateToDoItem;
@Inject
private ClockService clockService;
@Test
public void happyCase() throws Exception {
// given
final LocalDate todaysDate = clockService.now();
toDoItem.setDueBy(todaysDate);
toDoItem.updateCost(new BigDecimal("123.45"));
duplicateToDoItem = toDoItem.duplicate(
unwrap(toDoItem).default0Duplicate(),
unwrap(toDoItem).default1Duplicate(),
unwrap(toDoItem).default2Duplicate(),
unwrap(toDoItem).default3Duplicate(),
new BigDecimal("987.65"));
// then
assertThat(duplicateToDoItem.getDescription(), is(toDoItem.getDescription() + " - Copy"));
assertThat(duplicateToDoItem.getCategory(), is(toDoItem.getCategory()));
assertThat(duplicateToDoItem.getDueBy(), is(todaysDate));
assertThat(duplicateToDoItem.getCost(), is(new BigDecimal("987.65")));
}
}
public static class NotYetCompleted extends ToDoItemIntegTest {
@Test
public void happyCase() throws Exception {
// given
unwrap(toDoItem).setComplete(true);
// when
toDoItem.notYetCompleted();
// then
assertThat(toDoItem.isComplete(), is(false));
}
@Test
public void cannotUndoIfNotYetCompleted() throws Exception {
// given
assertThat(toDoItem.isComplete(), is(false));
// when, then should fail
expectedExceptions.expectMessage("Not yet completed");
toDoItem.notYetCompleted();
}
/**
* Even though {@link dom.todo.ToDoItem#notYetCompleted()} is not annotated with
* {@link org.apache.isis.applib.annotation.ActionInteraction}, an event is still raised.
*/
@Test
public void subscriberReceivesEvent() throws Exception {
// given
assertThat(toDoItemSubscriptions.getSubscriberBehaviour(), is(ToDoItemSubscriptions.Behaviour.AnyExecuteAccept));
unwrap(toDoItem).setComplete(true);
// when
toDoItem.notYetCompleted();
// then
assertThat(unwrap(toDoItem).isComplete(), is(false));
// and then
final ActionInteractionEvent<ToDoItem> ev = toDoItemSubscriptions.mostRecentlyReceivedEvent(ActionInteractionEvent.class);
assertThat(ev, is(not(nullValue())));
ToDoItem source = ev.getSource();
assertThat(source, is(equalTo(unwrap(toDoItem))));
assertThat(ev.getIdentifier().getMemberName(), is("notYetCompleted"));
}
}
}
public static class Collections {
public static class Dependencies {
public static class Add extends ToDoItemIntegTest {
private ToDoItem otherToDoItem;
@Before
public void setUp() throws Exception {
super.setUp();
final List<ToDoItem> items = wrap(toDoItems).notYetComplete();
otherToDoItem = wrap(items.get(1));
}
@After
public void tearDown() throws Exception {
unwrap(toDoItem).getDependencies().clear();
super.tearDown();
}
@Test
public void happyCase() throws Exception {
// given
assertThat(toDoItem.getDependencies().size(), is(0));
// when
toDoItem.add(otherToDoItem);
// then
assertThat(toDoItem.getDependencies().size(), is(1));
assertThat(toDoItem.getDependencies().first(), is(unwrap(otherToDoItem)));
}
@Test
public void cannotDependOnSelf() throws Exception {
// then
expectedExceptions.expectMessage("Can't set up a dependency to self");
// when
toDoItem.add(toDoItem);
}
@Test
public void cannotAddIfComplete() throws Exception {
// given
unwrap(toDoItem).setComplete(true);
// then
expectedExceptions.expectMessage("Cannot add dependencies for items that are complete");
// when
toDoItem.add(otherToDoItem);
}
@Test
public void subscriberReceivesEvent() throws Exception {
// given
toDoItemSubscriptions.reset();
// when
toDoItem.add(otherToDoItem);
// then received events
@SuppressWarnings("unchecked")
final List<EventObject> receivedEvents = toDoItemSubscriptions.receivedEvents();
assertThat(receivedEvents.size(), is(7));
assertThat(receivedEvents.get(0) instanceof ActionInteractionEvent, is(true)); // ToDoItem#add() executed
assertThat(receivedEvents.get(1) instanceof CollectionInteractionEvent, is(true)); // ToDoItem#dependencies add, executed
assertThat(receivedEvents.get(2) instanceof CollectionInteractionEvent, is(true)); // ToDoItem#dependencies add, executing
assertThat(receivedEvents.get(3) instanceof ActionInteractionEvent, is(true)); // ToDoItem#add executing
assertThat(receivedEvents.get(4) instanceof ActionInteractionEvent, is(true)); // ToDoItem#add validate
assertThat(receivedEvents.get(5) instanceof ActionInteractionEvent, is(true)); // ToDoItem#add disable
assertThat(receivedEvents.get(6) instanceof ActionInteractionEvent, is(true)); // ToDoItem#add hide
// inspect the collection interaction (posted programmatically in ToDoItem#add)
final CollectionInteractionEvent<ToDoItem,ToDoItem> ciEv = (CollectionInteractionEvent<ToDoItem, ToDoItem>) toDoItemSubscriptions.mostRecentlyReceivedEvent(CollectionInteractionEvent.class);
assertThat(ciEv, is(notNullValue()));
assertThat(ciEv.getSource(), is(equalTo(unwrap(toDoItem))));
assertThat(ciEv.getIdentifier().getMemberName(), is("dependencies"));
assertThat(ciEv.getOf(), is(CollectionInteractionEvent.Of.ADD_TO));
assertThat(ciEv.getValue(), is(unwrap(otherToDoItem)));
// inspect the action interaction (posted declaratively by framework)
final ActionInteractionEvent<ToDoItem> aiEv = (ActionInteractionEvent<ToDoItem>) toDoItemSubscriptions.mostRecentlyReceivedEvent(ActionInteractionEvent.class);
assertThat(aiEv, is(notNullValue()));
assertThat(aiEv.getSource(), is(equalTo(unwrap(toDoItem))));
assertThat(aiEv.getIdentifier().getMemberName(), is("add"));
assertThat(aiEv.getArguments().size(), is(1));
assertThat(aiEv.getArguments().get(0), is(unwrap((Object)otherToDoItem)));
assertThat(aiEv.getCommand(), is(notNullValue()));
}
@Test
public void subscriberVetoesEventWithRecoverableException() throws Exception {
// given
toDoItemSubscriptions.subscriberBehaviour(ToDoItemSubscriptions.Behaviour.AnyExecuteVetoWithRecoverableException);
// then
expectedExceptions.expect(RecoverableException.class);
// when
toDoItem.add(otherToDoItem);
}
@Test
public void subscriberVetoesEventWithNonRecoverableException() throws Exception {
// given
toDoItemSubscriptions.subscriberBehaviour(ToDoItemSubscriptions.Behaviour.AnyExecuteVetoWithNonRecoverableException);
// then
expectedExceptions.expect(NonRecoverableException.class);
// when
toDoItem.add(otherToDoItem);
}
@Test
public void subscriberVetoesEventWithAnyOtherException() throws Exception {
// given
toDoItemSubscriptions.subscriberBehaviour(ToDoItemSubscriptions.Behaviour.AnyExecuteVetoWithOtherException);
// then
expectedExceptions.expect(RuntimeException.class);
// when
toDoItem.add(otherToDoItem);
}
}
public static class Remove extends ToDoItemIntegTest {
private ToDoItem otherToDoItem;
private ToDoItem yetAnotherToDoItem;
@Before
public void setUp() throws Exception {
super.setUp();
final List<ToDoItem> items = wrap(toDoItems).notYetComplete();
otherToDoItem = wrap(items.get(1));
yetAnotherToDoItem = wrap(items.get(2));
toDoItem.add(otherToDoItem);
}
@After
public void tearDown() throws Exception {
unwrap(toDoItem).getDependencies().clear();
super.tearDown();
}
@Test
public void happyCase() throws Exception {
// given
assertThat(toDoItem.getDependencies().size(), is(1));
// when
toDoItem.remove(otherToDoItem);
// then
assertThat(toDoItem.getDependencies().size(), is(0));
}
@Test
public void cannotRemoveItemIfNotADependency() throws Exception {
// then
expectedExceptions.expectMessage("Not a dependency");
// when
toDoItem.remove(yetAnotherToDoItem);
}
@Test
public void cannotRemoveDependencyIfComplete() throws Exception {
// given
unwrap(toDoItem).setComplete(true);
// then
expectedExceptions.expectMessage("Cannot remove dependencies for items that are complete");
// when
toDoItem.remove(otherToDoItem);
}
@Test
public void subscriberVetoesEventWithRecoverableException() throws Exception {
// given
toDoItemSubscriptions.subscriberBehaviour(ToDoItemSubscriptions.Behaviour.AnyExecuteVetoWithRecoverableException);
// then
expectedExceptions.expect(RecoverableException.class);
// when
toDoItem.remove(otherToDoItem);
}
@Test
public void subscriberVetoesEventWithNonRecoverableException() throws Exception {
// given
toDoItemSubscriptions.subscriberBehaviour(ToDoItemSubscriptions.Behaviour.AnyExecuteVetoWithNonRecoverableException);
// then
expectedExceptions.expect(NonRecoverableException.class);
// when
toDoItem.remove(otherToDoItem);
}
@Test
public void subscriberVetoesEventWithAnyOtherException() throws Exception {
// given
toDoItemSubscriptions.subscriberBehaviour(ToDoItemSubscriptions.Behaviour.AnyExecuteVetoWithOtherException);
// then
expectedExceptions.expect(RuntimeException.class);
// when
toDoItem.remove(otherToDoItem);
}
}
}
}
public static class Properties {
public static class Attachment extends ToDoItemIntegTest {
@Test
public void happyCase() throws Exception {
byte[] bytes = "{\"foo\": \"bar\"}".getBytes(Charset.forName("UTF-8"));
final Blob newAttachment = new Blob("myfile.json", new MimeType("application/json"), bytes);
// when
toDoItem.setAttachment(newAttachment);
// then
assertThat(toDoItem.getAttachment(), is(newAttachment));
}
@Test
public void canBeNull() throws Exception {
// when
toDoItem.setAttachment((Blob)null);
// then
assertThat(toDoItem.getAttachment(), is((Blob)null));
}
}
public static class Category extends ToDoItemIntegTest {
@Test
public void cannotModify() throws Exception {
// when, then
expectedExceptions.expectMessage(containsString("Reason: Use action to update both category and subcategory."));
toDoItem.setCategory(ToDoItem.Category.Professional);
}
}
public static class Cost extends ToDoItemIntegTest {
private BigDecimal cost;
@Before
public void setUp() throws Exception {
super.setUp();
cost = toDoItem.getCost();
}
@Test
public void happyCaseUsingProperty() throws Exception {
final BigDecimal newCost = new BigDecimal("123.45");
// when
toDoItem.updateCost(newCost);
// then
assertThat(toDoItem.getCost(), is(newCost));
}
@Test
public void happyCaseUsingAction() throws Exception {
final BigDecimal newCost = new BigDecimal("123.45");
// when
toDoItem.updateCost(newCost);
// then
assertThat(toDoItem.getCost(), is(newCost));
}
@Test
public void canBeNull() throws Exception {
// when
toDoItem.updateCost((BigDecimal)null);
// then
assertThat(toDoItem.getCost(), is((BigDecimal)null));
}
@Test
public void defaultForAction() throws Exception {
// then
assertThat(unwrap(toDoItem).default0UpdateCost(), is(cost));
}
}
public static class Description extends ToDoItemIntegTest {
@Test
public void happyCase() throws Exception {
// given
assertThat(toDoItem.getDescription(), is("Buy bread"));
// when
toDoItem.setDescription("Buy bread and butter");
// then
assertThat(toDoItem.getDescription(), is("Buy bread and butter"));
}
@Test
public void failsRegex() throws Exception {
// when
expectedExceptions.expectMessage("Doesn't match pattern");
toDoItem.setDescription("exclamation marks are not allowed!!!");
}
@Test
public void cannotBeNull() throws Exception {
// when, then
expectedExceptions.expectMessage("Mandatory");
toDoItem.setDescription(null);
}
@Test
public void cannotUseModify() throws Exception {
expectedExceptions.expectMessage("Cannot invoke supporting method for 'Description'; use only property accessor/mutator");
// given
assertThat(toDoItem.getDescription(), is("Buy bread"));
// when
toDoItem.modifyDescription("Buy bread and butter");
// then
assertThat(toDoItem.getDescription(), is("Buy bread"));
}
@Test
public void cannotUseClear() throws Exception {
expectedExceptions.expectMessage("Cannot invoke supporting method for 'Description'; use only property accessor/mutator");
// given
assertThat(toDoItem.getDescription(), is("Buy bread"));
// when
toDoItem.clearDescription();
// then
assertThat(toDoItem.getDescription(), is("Buy bread"));
}
@Test
public void onlyJustShortEnough() throws Exception {
// when, then
toDoItem.setDescription(characters(100));
}
@Test
public void tooLong() throws Exception {
// then
expectedExceptions.expectMessage("The value proposed exceeds the maximum length of 100");
// when
toDoItem.setDescription(characters(101));
}
@Test
public void subscriberReceivesEvent() throws Exception {
// given
assertThat(toDoItemSubscriptions.getSubscriberBehaviour(), is(ToDoItemSubscriptions.Behaviour.AnyExecuteAccept));
assertThat(toDoItem.getDescription(), is("Buy bread"));
// when
toDoItem.setDescription("Buy bread and butter");
// then published and received
@SuppressWarnings("unchecked")
final PropertyInteractionEvent<ToDoItem,String> ev = toDoItemSubscriptions.mostRecentlyReceivedEvent(PropertyInteractionEvent.class);
assertThat(ev, is(not(nullValue())));
ToDoItem source = ev.getSource();
assertThat(source, is(equalTo(unwrap(toDoItem))));
assertThat(ev.getIdentifier().getMemberName(), is("description"));
assertThat(ev.getOldValue(), is("Buy bread"));
assertThat(ev.getNewValue(), is("Buy bread and butter"));
}
@Test
public void subscriberVetoesEventWithRecoverableException() throws Exception {
// given
toDoItemSubscriptions.subscriberBehaviour(ToDoItemSubscriptions.Behaviour.AnyExecuteVetoWithRecoverableException);
// then
expectedExceptions.expect(RecoverableException.class);
// when
toDoItem.setDescription("Buy bread and butter");
}
@Test
public void subscriberVetoesEventWithNonRecoverableException() throws Exception {
// given
toDoItemSubscriptions.subscriberBehaviour(ToDoItemSubscriptions.Behaviour.AnyExecuteVetoWithNonRecoverableException);
// then
expectedExceptions.expect(NonRecoverableException.class);
// when
toDoItem.setDescription("Buy bread and butter");
}
@Test
public void subscriberVetoesEventWithAnyOtherException() throws Exception {
// given
toDoItemSubscriptions.subscriberBehaviour(ToDoItemSubscriptions.Behaviour.AnyExecuteVetoWithOtherException);
// then
expectedExceptions.expect(RuntimeException.class);
// when
toDoItem.setDescription("Buy bread and butter");
}
private static String characters(final int n) {
StringBuffer buf = new StringBuffer();
for(int i=0; i<n; i++) {
buf.append("a");
}
return buf.toString();
}
}
public static class DueBy extends ToDoItemIntegTest {
@Inject
private ClockService clockService;
@Test
public void happyCase() throws Exception {
// when
final LocalDate fiveDaysFromNow = clockService.now().plusDays(5);
toDoItem.setDueBy(fiveDaysFromNow);
// then
assertThat(toDoItem.getDueBy(), is(fiveDaysFromNow));
}
@Test
public void canBeNull() throws Exception {
// when
toDoItem.setDueBy((LocalDate)null);
// then
assertThat(toDoItem.getDueBy(), is((LocalDate)null));
}
@Test
public void canBeUpToSixDaysInPast() throws Exception {
final LocalDate nowAsLocalDate = clockService.now();
final LocalDate sixDaysAgo = nowAsLocalDate.plusDays(-5);
// when
toDoItem.setDueBy(sixDaysAgo);
// then
assertThat(toDoItem.getDueBy(), is(sixDaysAgo));
}
@Test
public void cannotBeMoreThanSixDaysInPast() throws Exception {
final LocalDate sevenDaysAgo = Clock.getTimeAsLocalDate().plusDays(-7);
// when, then
expectedExceptions.expectMessage("Due by date cannot be more than one week old");
toDoItem.setDueBy(sevenDaysAgo);
}
}
public static class Notes extends ToDoItemIntegTest {
@Test
public void happyCase() throws Exception {
final String newNotes = "Lorem ipsum yada yada";
// when
toDoItem.setNotes(newNotes);
// then
assertThat(toDoItem.getNotes(), is(newNotes));
}
@Test
public void canBeNull() throws Exception {
// when
toDoItem.setNotes((String)null);
// then
assertThat(toDoItem.getNotes(), is((String)null));
}
@Test
public void suscriberReceivedDefaultEvent() throws Exception {
final String newNotes = "Lorem ipsum yada yada";
// when
toDoItem.setNotes(newNotes);
// then
assertThat(unwrap(toDoItem).getNotes(), is(newNotes));
// and then receive the default event.
@SuppressWarnings("unchecked")
final PropertyInteractionEvent.Default ev = toDoItemSubscriptions.mostRecentlyReceivedEvent(PropertyInteractionEvent.Default.class);
assertThat(ev, is(notNullValue()));
assertThat(ev.getSource(), is((Object)unwrap(toDoItem)));
assertThat(ev.getNewValue(), is((Object)newNotes));
}
}
public static class OwnedBy extends ToDoItemIntegTest {
@Test
public void cannotModify() throws Exception {
// when, then
expectedExceptions.expectMessage("Reason: Hidden on Everywhere. Identifier: dom.todo.ToDoItem#ownedBy()");
toDoItem.setOwnedBy("other");
}
}
public static class Subcategory extends ToDoItemIntegTest {
@Test
public void cannotModify() throws Exception {
// when, then
expectedExceptions.expectMessage(containsString("Reason: Use action to update both category and subcategory."));
toDoItem.setSubcategory(ToDoItem.Subcategory.Chores);
}
}
}
} | example/application/todoapp/integtests/src/test/java/integration/tests/ToDoItemIntegTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package integration.tests;
import dom.todo.ToDoItem;
import dom.todo.ToDoItemSubscriptions;
import dom.todo.ToDoItems;
import fixture.todo.integtests.ToDoItemsIntegTestFixture;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.util.EventObject;
import java.util.List;
import javax.activation.MimeType;
import javax.inject.Inject;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.jmock.Expectations;
import org.jmock.Sequence;
import org.jmock.auto.Mock;
import org.joda.time.LocalDate;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.apache.isis.applib.NonRecoverableException;
import org.apache.isis.applib.RecoverableException;
import org.apache.isis.applib.clock.Clock;
import org.apache.isis.applib.fixturescripts.FixtureScripts;
import org.apache.isis.applib.services.clock.ClockService;
import org.apache.isis.applib.services.eventbus.AbstractInteractionEvent;
import org.apache.isis.applib.services.eventbus.ActionInteractionEvent;
import org.apache.isis.applib.services.eventbus.CollectionInteractionEvent;
import org.apache.isis.applib.services.eventbus.EventBusService;
import org.apache.isis.applib.services.eventbus.PropertyInteractionEvent;
import org.apache.isis.applib.value.Blob;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat;
public class ToDoItemIntegTest extends AbstractToDoIntegTest {
ToDoItemsIntegTestFixture fixture;
@Before
public void setUpData() throws Exception {
// executing the fixtures directly allows us to look up the results later.
fixtureScripts.runFixtureScript(fixture = new ToDoItemsIntegTestFixture(), null);
}
@Inject
FixtureScripts fixtureScripts;
@Inject
ToDoItems toDoItems;
@Inject
ToDoItemSubscriptions toDoItemSubscriptions;
ToDoItem toDoItem;
@Before
public void setUp() throws Exception {
final List<ToDoItem> all = toDoItems.notYetComplete();
toDoItem = wrap(all.get(0));
}
@After
public void tearDown() throws Exception {
toDoItemSubscriptions.reset();
}
public static class Title extends ToDoItemIntegTest {
private LocalDate dueBy;
@Before
public void setUp() throws Exception {
super.setUp();
final List<ToDoItem> all = wrap(toDoItems).notYetComplete();
toDoItem = wrap(all.get(0));
toDoItem = wrap(fixture.lookup("integ-test/to-do-items-recreate-and-complete-several/to-do-items-recreate/to-do-item-for-buy-bread/item-1", ToDoItem.class));
assertThat(toDoItem, is(not(nullValue())));
nextTransaction();
dueBy = toDoItem.getDueBy();
}
@Test
public void includesDescription() throws Exception {
// given
assertThat(container().titleOf(toDoItem), containsString("Buy bread due by"));
// when
unwrap(toDoItem).setDescription("Buy bread and butter");
// then
assertThat(container().titleOf(toDoItem), containsString("Buy bread and butter due by"));
}
@Test
public void includesDueDateIfAny() throws Exception {
// given
assertThat(container().titleOf(toDoItem), containsString("due by " + dueBy.toString("yyyy-MM-dd")));
// when
final LocalDate fiveDaysFromNow = Clock.getTimeAsLocalDate().plusDays(5);
unwrap(toDoItem).setDueBy(fiveDaysFromNow);
// then
assertThat(container().titleOf(toDoItem), containsString("due by " + fiveDaysFromNow.toString("yyyy-MM-dd")));
}
@Test
public void ignoresDueDateIfNone() throws Exception {
// when
// (since wrapped, will call clearDueBy)
toDoItem.setDueBy(null);
// then
assertThat(container().titleOf(toDoItem), not(containsString("due by")));
}
@Test
public void usesWhetherCompleted() throws Exception {
// given
assertThat(container().titleOf(toDoItem), not(containsString("Completed!")));
// when
toDoItem.completed();
// then
assertThat(container().titleOf(toDoItem), not(containsString("due by")));
assertThat(container().titleOf(toDoItem), containsString("Buy bread - Completed!"));
}
}
public static class Actions {
public static class Completed extends ToDoItemIntegTest {
@Test
public void happyCase() throws Exception {
// given
assertThat(toDoItem.isComplete(), is(false));
// when
toDoItem.completed();
// then
assertThat(toDoItem.isComplete(), is(true));
}
@Test
public void cannotCompleteIfAlreadyCompleted() throws Exception {
// given
unwrap(toDoItem).setComplete(true);
// when, then should fail
expectedExceptions.expectMessage("Already completed");
toDoItem.completed();
// and then
final EventObject ev = toDoItemSubscriptions.mostRecentlyReceivedEvent(EventObject.class);
assertThat(ev, is(nullValue()));
}
@Test
public void cannotSetPropertyDirectly() throws Exception {
// given
// when, then should fail
expectedExceptions.expectMessage("Always disabled");
toDoItem.setComplete(true);
// and then
final EventObject ev = toDoItemSubscriptions.mostRecentlyReceivedEvent(EventObject.class);
assertThat(ev, is(nullValue()));
}
@Test
public void subscriberReceivesEvents() throws Exception {
// given
toDoItemSubscriptions.reset();
assertThat(toDoItemSubscriptions.getSubscriberBehaviour(), is(ToDoItemSubscriptions.Behaviour.AnyExecuteAccept));
assertThat(unwrap(toDoItem).isComplete(), is(false));
// when
toDoItem.completed();
// then
assertThat(unwrap(toDoItem).isComplete(), is(true));
// and then
final List<ToDoItem.CompletedEvent> receivedEvents = toDoItemSubscriptions.receivedEvents(ToDoItem.CompletedEvent.class);
// hide, disable, validate, executing, executed
// sent to both the general on(ActionInteractionEvent ev)
// and also the specific on(final ToDoItem.CompletedEvent ev)
assertThat(receivedEvents.size(), is(5*2));
final ToDoItem.CompletedEvent ev = receivedEvents.get(0);
ToDoItem source = ev.getSource();
assertThat(source, is(equalTo(unwrap(toDoItem))));
assertThat(ev.getIdentifier().getMemberName(), is("completed"));
}
@Test
public void subscriberVetoesEventWithRecoverableException() throws Exception {
// given
toDoItemSubscriptions.subscriberBehaviour(ToDoItemSubscriptions.Behaviour.AnyExecuteVetoWithRecoverableException);
// then
expectedExceptions.expect(RecoverableException.class);
// when
toDoItem.completed();
}
@Test
public void subscriberVetoesEventWithNonRecoverableException() throws Exception {
// given
toDoItemSubscriptions.subscriberBehaviour(ToDoItemSubscriptions.Behaviour.AnyExecuteVetoWithNonRecoverableException);
// then
expectedExceptions.expect(NonRecoverableException.class);
// when
toDoItem.completed();
}
@Test
public void subscriberVetoesEventWithAnyOtherException() throws Exception {
// given
toDoItemSubscriptions.subscriberBehaviour(ToDoItemSubscriptions.Behaviour.AnyExecuteVetoWithOtherException);
// then
expectedExceptions.expect(RuntimeException.class);
// when
toDoItem.completed();
}
}
/**
* This test demonstrates how a single service can be replaced, eg to use a mock.
*/
public static class Completed_withMockService extends ToDoItemIntegTest {
private EventBusService originalEventBusService;
@Mock
private EventBusService mockEventBusService;
@Before
public void setUpMockEventBusService() throws Exception {
originalEventBusService = scenarioExecution().service(EventBusService.class);
context.checking(new Expectations() {{
ignoring(mockEventBusService).register(with(any(Object.class)));
ignoring(mockEventBusService).unregister(with(any(Object.class)));
}});
scenarioExecution().replaceService(originalEventBusService, mockEventBusService);
scenarioExecution().closeSession();
scenarioExecution().openSession();
final List<ToDoItem> all = toDoItems.notYetComplete();
toDoItem = wrap(all.get(0));
}
@After
public void reinstateOriginalEventBusService() throws Exception {
scenarioExecution().replaceService(mockEventBusService, originalEventBusService);
}
@Test
public void raisesEvent() throws Exception {
final Sequence busRulesThenExec = context.sequence("busRulesThenExec");
// then
context.checking(new Expectations() {{
oneOf(mockEventBusService).post(with(completedEvent(AbstractInteractionEvent.Phase.HIDE)));
inSequence(busRulesThenExec);
oneOf(mockEventBusService).post(with(completedEvent(AbstractInteractionEvent.Phase.DISABLE)));
inSequence(busRulesThenExec);
oneOf(mockEventBusService).post(with(completedEvent(AbstractInteractionEvent.Phase.VALIDATE)));
inSequence(busRulesThenExec);
oneOf(mockEventBusService).post(with(completedEvent(AbstractInteractionEvent.Phase.EXECUTING)));
inSequence(busRulesThenExec);
oneOf(mockEventBusService).post(with(completedEvent(AbstractInteractionEvent.Phase.EXECUTED)));
inSequence(busRulesThenExec);
}});
// when
toDoItem.completed();
}
private Matcher<Object> completedEvent(final AbstractInteractionEvent.Phase phase) {
return new TypeSafeMatcher<Object>() {
@Override
protected boolean matchesSafely(Object item) {
if (!(item instanceof ToDoItem.CompletedEvent)) {
return false;
}
final ToDoItem.CompletedEvent completedEvent = (ToDoItem.CompletedEvent) item;
return completedEvent.getPhase() == phase;
}
@Override
public void describeTo(Description description) {
description.appendText(" instance of a ToDoItem.CompletedEvent, " + phase);
}
};
}
}
public static class Duplicate extends ToDoItemIntegTest {
ToDoItem duplicateToDoItem;
@Inject
private ClockService clockService;
@Test
public void happyCase() throws Exception {
// given
final LocalDate todaysDate = clockService.now();
toDoItem.setDueBy(todaysDate);
toDoItem.updateCost(new BigDecimal("123.45"));
duplicateToDoItem = toDoItem.duplicate(
unwrap(toDoItem).default0Duplicate(),
unwrap(toDoItem).default1Duplicate(),
unwrap(toDoItem).default2Duplicate(),
unwrap(toDoItem).default3Duplicate(),
new BigDecimal("987.65"));
// then
assertThat(duplicateToDoItem.getDescription(), is(toDoItem.getDescription() + " - Copy"));
assertThat(duplicateToDoItem.getCategory(), is(toDoItem.getCategory()));
assertThat(duplicateToDoItem.getDueBy(), is(todaysDate));
assertThat(duplicateToDoItem.getCost(), is(new BigDecimal("987.65")));
}
}
public static class NotYetCompleted extends ToDoItemIntegTest {
@Test
public void happyCase() throws Exception {
// given
unwrap(toDoItem).setComplete(true);
// when
toDoItem.notYetCompleted();
// then
assertThat(toDoItem.isComplete(), is(false));
}
@Test
public void cannotUndoIfNotYetCompleted() throws Exception {
// given
assertThat(toDoItem.isComplete(), is(false));
// when, then should fail
expectedExceptions.expectMessage("Not yet completed");
toDoItem.notYetCompleted();
}
/**
* Even though {@link dom.todo.ToDoItem#notYetCompleted()} is not annotated with
* {@link org.apache.isis.applib.annotation.ActionInteraction}, an event is still raised.
*/
@Test
public void subscriberReceivesEvent() throws Exception {
// given
assertThat(toDoItemSubscriptions.getSubscriberBehaviour(), is(ToDoItemSubscriptions.Behaviour.AnyExecuteAccept));
unwrap(toDoItem).setComplete(true);
// when
toDoItem.notYetCompleted();
// then
assertThat(unwrap(toDoItem).isComplete(), is(false));
// and then
final ActionInteractionEvent<ToDoItem> ev = toDoItemSubscriptions.mostRecentlyReceivedEvent(ActionInteractionEvent.class);
assertThat(ev, is(not(nullValue())));
ToDoItem source = ev.getSource();
assertThat(source, is(equalTo(unwrap(toDoItem))));
assertThat(ev.getIdentifier().getMemberName(), is("notYetCompleted"));
}
}
}
public static class Collections {
public static class Dependencies {
public static class Add extends ToDoItemIntegTest {
private ToDoItem otherToDoItem;
@Before
public void setUp() throws Exception {
super.setUp();
final List<ToDoItem> items = wrap(toDoItems).notYetComplete();
otherToDoItem = wrap(items.get(1));
}
@After
public void tearDown() throws Exception {
unwrap(toDoItem).getDependencies().clear();
super.tearDown();
}
@Test
public void happyCase() throws Exception {
// given
assertThat(toDoItem.getDependencies().size(), is(0));
// when
toDoItem.add(otherToDoItem);
// then
assertThat(toDoItem.getDependencies().size(), is(1));
assertThat(toDoItem.getDependencies().first(), is(unwrap(otherToDoItem)));
}
@Test
public void cannotDependOnSelf() throws Exception {
// then
expectedExceptions.expectMessage("Can't set up a dependency to self");
// when
toDoItem.add(toDoItem);
}
@Test
public void cannotAddIfComplete() throws Exception {
// given
unwrap(toDoItem).setComplete(true);
// then
expectedExceptions.expectMessage("Cannot add dependencies for items that are complete");
// when
toDoItem.add(otherToDoItem);
}
@Test
public void subscriberReceivesEvent() throws Exception {
// given
toDoItemSubscriptions.reset();
// when
toDoItem.add(otherToDoItem);
// then received events
@SuppressWarnings("unchecked")
final List<EventObject> receivedEvents = toDoItemSubscriptions.receivedEvents();
assertThat(receivedEvents.size(), is(7));
assertThat(receivedEvents.get(0) instanceof ActionInteractionEvent, is(true)); // ToDoItem#add() executed
assertThat(receivedEvents.get(1) instanceof CollectionInteractionEvent, is(true)); // ToDoItem#dependencies add, executed
assertThat(receivedEvents.get(2) instanceof CollectionInteractionEvent, is(true)); // ToDoItem#dependencies add, executing
assertThat(receivedEvents.get(3) instanceof ActionInteractionEvent, is(true)); // ToDoItem#add executing
assertThat(receivedEvents.get(4) instanceof ActionInteractionEvent, is(true)); // ToDoItem#add validate
assertThat(receivedEvents.get(5) instanceof ActionInteractionEvent, is(true)); // ToDoItem#add disable
assertThat(receivedEvents.get(6) instanceof ActionInteractionEvent, is(true)); // ToDoItem#add hide
// inspect the collection interaction (posted programmatically in ToDoItem#add)
final CollectionInteractionEvent<ToDoItem,ToDoItem> ciEv = (CollectionInteractionEvent<ToDoItem, ToDoItem>) toDoItemSubscriptions.mostRecentlyReceivedEvent(CollectionInteractionEvent.class);
assertThat(ciEv, is(notNullValue()));
assertThat(ciEv.getSource(), is(equalTo(unwrap(toDoItem))));
assertThat(ciEv.getIdentifier().getMemberName(), is("dependencies"));
assertThat(ciEv.getOf(), is(CollectionInteractionEvent.Of.ADD_TO));
assertThat(ciEv.getValue(), is(unwrap(otherToDoItem)));
// inspect the action interaction (posted declaratively by framework)
final ActionInteractionEvent<ToDoItem> aiEv = (ActionInteractionEvent<ToDoItem>) toDoItemSubscriptions.mostRecentlyReceivedEvent(ActionInteractionEvent.class);
assertThat(aiEv, is(notNullValue()));
assertThat(aiEv.getSource(), is(equalTo(unwrap(toDoItem))));
assertThat(aiEv.getIdentifier().getMemberName(), is("add"));
assertThat(aiEv.getArguments().size(), is(1));
assertThat(aiEv.getArguments().get(0), is(unwrap((Object)otherToDoItem)));
assertThat(aiEv.getCommand(), is(notNullValue()));
}
@Test
public void subscriberVetoesEventWithRecoverableException() throws Exception {
// given
toDoItemSubscriptions.subscriberBehaviour(ToDoItemSubscriptions.Behaviour.AnyExecuteVetoWithRecoverableException);
// then
expectedExceptions.expect(RecoverableException.class);
// when
toDoItem.add(otherToDoItem);
}
@Test
public void subscriberVetoesEventWithNonRecoverableException() throws Exception {
// given
toDoItemSubscriptions.subscriberBehaviour(ToDoItemSubscriptions.Behaviour.AnyExecuteVetoWithNonRecoverableException);
// then
expectedExceptions.expect(NonRecoverableException.class);
// when
toDoItem.add(otherToDoItem);
}
@Test
public void subscriberVetoesEventWithAnyOtherException() throws Exception {
// given
toDoItemSubscriptions.subscriberBehaviour(ToDoItemSubscriptions.Behaviour.AnyExecuteVetoWithOtherException);
// then
expectedExceptions.expect(RuntimeException.class);
// when
toDoItem.add(otherToDoItem);
}
}
public static class Remove extends ToDoItemIntegTest {
private ToDoItem otherToDoItem;
private ToDoItem yetAnotherToDoItem;
@Before
public void setUp() throws Exception {
super.setUp();
final List<ToDoItem> items = wrap(toDoItems).notYetComplete();
otherToDoItem = wrap(items.get(1));
yetAnotherToDoItem = wrap(items.get(2));
toDoItem.add(otherToDoItem);
}
@After
public void tearDown() throws Exception {
unwrap(toDoItem).getDependencies().clear();
super.tearDown();
}
@Test
public void happyCase() throws Exception {
// given
assertThat(toDoItem.getDependencies().size(), is(1));
// when
toDoItem.remove(otherToDoItem);
// then
assertThat(toDoItem.getDependencies().size(), is(0));
}
@Test
public void cannotRemoveItemIfNotADependency() throws Exception {
// then
expectedExceptions.expectMessage("Not a dependency");
// when
toDoItem.remove(yetAnotherToDoItem);
}
@Test
public void cannotRemoveDependencyIfComplete() throws Exception {
// given
unwrap(toDoItem).setComplete(true);
// then
expectedExceptions.expectMessage("Cannot remove dependencies for items that are complete");
// when
toDoItem.remove(otherToDoItem);
}
@Test
public void subscriberVetoesEventWithRecoverableException() throws Exception {
// given
toDoItemSubscriptions.subscriberBehaviour(ToDoItemSubscriptions.Behaviour.AnyExecuteVetoWithRecoverableException);
// then
expectedExceptions.expect(RecoverableException.class);
// when
toDoItem.remove(otherToDoItem);
}
@Test
public void subscriberVetoesEventWithNonRecoverableException() throws Exception {
// given
toDoItemSubscriptions.subscriberBehaviour(ToDoItemSubscriptions.Behaviour.AnyExecuteVetoWithNonRecoverableException);
// then
expectedExceptions.expect(NonRecoverableException.class);
// when
toDoItem.remove(otherToDoItem);
}
@Test
public void subscriberVetoesEventWithAnyOtherException() throws Exception {
// given
toDoItemSubscriptions.subscriberBehaviour(ToDoItemSubscriptions.Behaviour.AnyExecuteVetoWithOtherException);
// then
expectedExceptions.expect(RuntimeException.class);
// when
toDoItem.remove(otherToDoItem);
}
}
}
}
public static class Properties {
public static class Attachment extends ToDoItemIntegTest {
@Test
public void happyCase() throws Exception {
byte[] bytes = "{\"foo\": \"bar\"}".getBytes(Charset.forName("UTF-8"));
final Blob newAttachment = new Blob("myfile.json", new MimeType("application/json"), bytes);
// when
toDoItem.setAttachment(newAttachment);
// then
assertThat(toDoItem.getAttachment(), is(newAttachment));
}
@Test
public void canBeNull() throws Exception {
// when
toDoItem.setAttachment((Blob)null);
// then
assertThat(toDoItem.getAttachment(), is((Blob)null));
}
}
public static class Category extends ToDoItemIntegTest {
@Test
public void cannotModify() throws Exception {
// when, then
expectedExceptions.expectMessage(containsString("Reason: Use action to update both category and subcategory."));
toDoItem.setCategory(ToDoItem.Category.Professional);
}
}
public static class Cost extends ToDoItemIntegTest {
private BigDecimal cost;
@Before
public void setUp() throws Exception {
super.setUp();
cost = toDoItem.getCost();
}
@Test
public void happyCaseUsingProperty() throws Exception {
final BigDecimal newCost = new BigDecimal("123.45");
// when
toDoItem.updateCost(newCost);
// then
assertThat(toDoItem.getCost(), is(newCost));
}
@Test
public void happyCaseUsingAction() throws Exception {
final BigDecimal newCost = new BigDecimal("123.45");
// when
toDoItem.updateCost(newCost);
// then
assertThat(toDoItem.getCost(), is(newCost));
}
@Test
public void canBeNull() throws Exception {
// when
toDoItem.updateCost((BigDecimal)null);
// then
assertThat(toDoItem.getCost(), is((BigDecimal)null));
}
@Test
public void defaultForAction() throws Exception {
// then
assertThat(unwrap(toDoItem).default0UpdateCost(), is(cost));
}
}
public static class Description extends ToDoItemIntegTest {
@Test
public void happyCase() throws Exception {
// given
assertThat(toDoItem.getDescription(), is("Buy bread"));
// when
toDoItem.setDescription("Buy bread and butter");
// then
assertThat(toDoItem.getDescription(), is("Buy bread and butter"));
}
@Test
public void failsRegex() throws Exception {
// when
expectedExceptions.expectMessage("Doesn't match pattern");
toDoItem.setDescription("exclamation marks are not allowed!!!");
}
@Test
public void cannotBeNull() throws Exception {
// when, then
expectedExceptions.expectMessage("Mandatory");
toDoItem.setDescription(null);
}
@Test
public void cannotUseModify() throws Exception {
expectedExceptions.expectMessage("Cannot invoke supporting method for 'Description'; use only property accessor/mutator");
// given
assertThat(toDoItem.getDescription(), is("Buy bread"));
// when
toDoItem.modifyDescription("Buy bread and butter");
// then
assertThat(toDoItem.getDescription(), is("Buy bread"));
}
@Test
public void cannotUseClear() throws Exception {
expectedExceptions.expectMessage("Cannot invoke supporting method for 'Description'; use only property accessor/mutator");
// given
assertThat(toDoItem.getDescription(), is("Buy bread"));
// when
toDoItem.clearDescription();
// then
assertThat(toDoItem.getDescription(), is("Buy bread"));
}
@Test
public void onlyJustShortEnough() throws Exception {
// when, then
toDoItem.setDescription(characters(100));
}
@Test
public void tooLong() throws Exception {
// then
expectedExceptions.expectMessage("The value proposed exceeds the maximum length of 100");
// when
toDoItem.setDescription(characters(101));
}
@Test
public void subscriberReceivesEvent() throws Exception {
// given
assertThat(toDoItemSubscriptions.getSubscriberBehaviour(), is(ToDoItemSubscriptions.Behaviour.AnyExecuteAccept));
assertThat(toDoItem.getDescription(), is("Buy bread"));
// when
toDoItem.setDescription("Buy bread and butter");
// then published and received
@SuppressWarnings("unchecked")
final PropertyInteractionEvent<ToDoItem,String> ev = toDoItemSubscriptions.mostRecentlyReceivedEvent(PropertyInteractionEvent.class);
assertThat(ev, is(not(nullValue())));
ToDoItem source = ev.getSource();
assertThat(source, is(equalTo(unwrap(toDoItem))));
assertThat(ev.getIdentifier().getMemberName(), is("description"));
assertThat(ev.getOldValue(), is("Buy bread"));
assertThat(ev.getNewValue(), is("Buy bread and butter"));
}
@Test
public void subscriberVetoesEventWithRecoverableException() throws Exception {
// given
toDoItemSubscriptions.subscriberBehaviour(ToDoItemSubscriptions.Behaviour.AnyExecuteVetoWithRecoverableException);
// then
expectedExceptions.expect(RecoverableException.class);
// when
toDoItem.setDescription("Buy bread and butter");
}
@Test
public void subscriberVetoesEventWithNonRecoverableException() throws Exception {
// given
toDoItemSubscriptions.subscriberBehaviour(ToDoItemSubscriptions.Behaviour.AnyExecuteVetoWithNonRecoverableException);
// then
expectedExceptions.expect(NonRecoverableException.class);
// when
toDoItem.setDescription("Buy bread and butter");
}
@Test
public void subscriberVetoesEventWithAnyOtherException() throws Exception {
// given
toDoItemSubscriptions.subscriberBehaviour(ToDoItemSubscriptions.Behaviour.AnyExecuteVetoWithOtherException);
// then
expectedExceptions.expect(RuntimeException.class);
// when
toDoItem.setDescription("Buy bread and butter");
}
private static String characters(final int n) {
StringBuffer buf = new StringBuffer();
for(int i=0; i<n; i++) {
buf.append("a");
}
return buf.toString();
}
}
public static class DueBy extends ToDoItemIntegTest {
@Inject
private ClockService clockService;
@Test
public void happyCase() throws Exception {
// when
final LocalDate fiveDaysFromNow = clockService.now().plusDays(5);
toDoItem.setDueBy(fiveDaysFromNow);
// then
assertThat(toDoItem.getDueBy(), is(fiveDaysFromNow));
}
@Test
public void canBeNull() throws Exception {
// when
toDoItem.setDueBy((LocalDate)null);
// then
assertThat(toDoItem.getDueBy(), is((LocalDate)null));
}
@Test
public void canBeUpToSixDaysInPast() throws Exception {
final LocalDate nowAsLocalDate = clockService.now();
final LocalDate sixDaysAgo = nowAsLocalDate.plusDays(-5);
// when
toDoItem.setDueBy(sixDaysAgo);
// then
assertThat(toDoItem.getDueBy(), is(sixDaysAgo));
}
@Test
public void cannotBeMoreThanSixDaysInPast() throws Exception {
final LocalDate sevenDaysAgo = Clock.getTimeAsLocalDate().plusDays(-7);
// when, then
expectedExceptions.expectMessage("Due by date cannot be more than one week old");
toDoItem.setDueBy(sevenDaysAgo);
}
}
public static class Notes extends ToDoItemIntegTest {
@Test
public void happyCase() throws Exception {
final String newNotes = "Lorem ipsum yada yada";
// when
toDoItem.setNotes(newNotes);
// then
assertThat(toDoItem.getNotes(), is(newNotes));
}
@Test
public void canBeNull() throws Exception {
// when
toDoItem.setNotes((String)null);
// then
assertThat(toDoItem.getNotes(), is((String)null));
}
@Test
public void suscriberReceivedDefaultEvent() throws Exception {
final String newNotes = "Lorem ipsum yada yada";
// when
toDoItem.setNotes(newNotes);
// then
assertThat(unwrap(toDoItem).getNotes(), is(newNotes));
// and then receive the default event.
@SuppressWarnings("unchecked")
final PropertyInteractionEvent.Default ev = toDoItemSubscriptions.mostRecentlyReceivedEvent(PropertyInteractionEvent.Default.class);
assertThat(ev, is(notNullValue()));
assertThat(ev.getSource(), is((Object)unwrap(toDoItem)));
assertThat(ev.getNewValue(), is((Object)newNotes));
}
}
public static class OwnedBy extends ToDoItemIntegTest {
@Test
public void cannotModify() throws Exception {
// when, then
expectedExceptions.expectMessage("Always hidden");
toDoItem.setOwnedBy("other");
}
}
public static class Subcategory extends ToDoItemIntegTest {
@Test
public void cannotModify() throws Exception {
// when, then
expectedExceptions.expectMessage(containsString("Reason: Use action to update both category and subcategory."));
toDoItem.setSubcategory(ToDoItem.Subcategory.Chores);
}
}
}
} | ISIS-964: fix for todoapp integ test (already in the archetype)
| example/application/todoapp/integtests/src/test/java/integration/tests/ToDoItemIntegTest.java | ISIS-964: fix for todoapp integ test (already in the archetype) | <ide><path>xample/application/todoapp/integtests/src/test/java/integration/tests/ToDoItemIntegTest.java
<ide> public void cannotModify() throws Exception {
<ide>
<ide> // when, then
<del> expectedExceptions.expectMessage("Always hidden");
<add> expectedExceptions.expectMessage("Reason: Hidden on Everywhere. Identifier: dom.todo.ToDoItem#ownedBy()");
<ide> toDoItem.setOwnedBy("other");
<ide> }
<ide> |
|
Java | apache-2.0 | 5a84f682455839a0a357f7c14da1b722df580644 | 0 | cheng-li/pyramid,cheng-li/pyramid | package edu.neu.ccs.pyramid.experiment;
import edu.neu.ccs.pyramid.active_learning.BestVsSecond;
import edu.neu.ccs.pyramid.classification.boosting.lktb.LKTBConfig;
import edu.neu.ccs.pyramid.classification.boosting.lktb.LKTreeBoost;
import edu.neu.ccs.pyramid.configuration.Config;
import edu.neu.ccs.pyramid.dataset.*;
import edu.neu.ccs.pyramid.elasticsearch.SingleLabelIndex;
import edu.neu.ccs.pyramid.dataset.IdTranslator;
import edu.neu.ccs.pyramid.eval.Accuracy;
import edu.neu.ccs.pyramid.feature.*;
import edu.neu.ccs.pyramid.feature_extraction.*;
import edu.neu.ccs.pyramid.util.MathUtil;
import edu.neu.ccs.pyramid.util.Pair;
import edu.neu.ccs.pyramid.util.Sampling;
import org.apache.commons.lang3.time.StopWatch;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.search.SearchHit;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
/**
* feature extraction using elasticsearch,
* can start with initial features in ESindex
* can use default train/test split or random split
* follow golden_features, exp57
* Created by chengli on 9/7/14.
*/
public class Exp3 {
public static void main(String[] args) throws Exception{
if (args.length !=1){
throw new IllegalArgumentException("please specify the config file");
}
Config config = new Config(args[0]);
System.out.println(config);
SingleLabelIndex index = loadIndex(config);
if (config.getBoolean("train")){
train(config,index);
}
index.close();
}
static void train(Config config, SingleLabelIndex index) throws Exception{
int numDocsInIndex = index.getNumDocs();
String[] trainIndexIds = sampleTrain(config,index);
System.out.println("number of training documents = "+trainIndexIds.length);
IdTranslator trainIdTranslator = loadIdTranslator(trainIndexIds);
FeatureMappers featureMappers = new FeatureMappers();
LabelTranslator labelTranslator = loadLabelTranslator(config, index);
if (config.getBoolean("useInitialFeatures")){
addInitialFeatures(config,index,featureMappers,trainIndexIds);
}
ClfDataSet trainDataSet = loadTrainData(config,index,featureMappers, trainIdTranslator, labelTranslator);
System.out.println("in training set :");
showDistribution(config,trainDataSet,labelTranslator);
trainModel(config,trainDataSet,featureMappers,index, trainIdTranslator);
//only keep used columns
ClfDataSet trimmedTrainDataSet = DataSetUtil.trim(trainDataSet,featureMappers.getTotalDim());
DataSetUtil.setFeatureMappers(trimmedTrainDataSet,featureMappers);
saveDataSet(config, trimmedTrainDataSet, config.getString("archive.trainingSet"));
if (config.getBoolean("archive.dumpFields")){
dumpTrainFeatures(config,index,trainIdTranslator);
}
String[] testIndexIds = sampleTest(numDocsInIndex,trainIndexIds);
IdTranslator testIdTranslator = loadIdTranslator(testIndexIds);
ClfDataSet testDataSet = loadTestData(config,index,featureMappers,testIdTranslator,labelTranslator);
DataSetUtil.setFeatureMappers(testDataSet,featureMappers);
saveDataSet(config, testDataSet, config.getString("archive.testSet"));
if (config.getBoolean("archive.dumpFields")){
dumpTestFeatures(config,index,testIdTranslator);
}
}
static SingleLabelIndex loadIndex(Config config) throws Exception{
SingleLabelIndex.Builder builder = new SingleLabelIndex.Builder()
.setIndexName(config.getString("index.indexName"))
.setClusterName(config.getString("index.clusterName"))
.setClientType(config.getString("index.clientType"))
.setLabelField(config.getString("index.labelField"))
.setExtLabelField(config.getString("index.extLabelField"))
.setDocumentType(config.getString("index.documentType"));
if (config.getString("index.clientType").equals("transport")){
String[] hosts = config.getString("index.hosts").split(Pattern.quote(","));
String[] ports = config.getString("index.ports").split(Pattern.quote(","));
builder.addHostsAndPorts(hosts,ports);
}
SingleLabelIndex index = builder.build();
System.out.println("index loaded");
System.out.println("there are "+index.getNumDocs()+" documents in the index.");
// for (int i=0;i<index.getNumDocs();i++){
// System.out.println(i);
// System.out.println(index.getLabel(""+i));
// }
return index;
}
/**
*
* @param config
* @param index
* @param featureMappers
* @param idTranslator separate for training and test
* @param totalDim
* @return
* @throws Exception
*/
static ClfDataSet loadData(Config config, SingleLabelIndex index,
FeatureMappers featureMappers,
IdTranslator idTranslator, int totalDim,
LabelTranslator labelTranslator) throws Exception{
int numDataPoints = idTranslator.numData();
int numClasses = config.getInt("numClasses");
ClfDataSet dataSet;
if(config.getBoolean("featureMatrix.sparse")){
dataSet= new SparseClfDataSet(numDataPoints,totalDim,numClasses);
} else {
dataSet= new DenseClfDataSet(numDataPoints,totalDim,numClasses);
}
for(int i=0;i<numDataPoints;i++){
String dataIndexId = idTranslator.toExtId(i);
int label = index.getLabel(dataIndexId);
dataSet.setLabel(i,label);
}
String[] dataIndexIds = idTranslator.getAllExtIds();
featureMappers.getCategoricalFeatureMappers().stream().parallel().
forEach(categoricalFeatureMapper -> {
String featureName = categoricalFeatureMapper.getFeatureName();
String source = categoricalFeatureMapper.getSource();
if (source.equalsIgnoreCase("field")){
for (String id: dataIndexIds){
int algorithmId = idTranslator.toIntId(id);
String category = index.getStringField(id,featureName);
// might be a new category unseen in training
if (categoricalFeatureMapper.hasCategory(category)){
int featureIndex = categoricalFeatureMapper.getFeatureIndex(category);
dataSet.setFeatureValue(algorithmId,featureIndex,1);
}
}
}
});
featureMappers.getNumericalFeatureMappers().stream().parallel().
forEach(numericalFeatureMapper -> {
String featureName = numericalFeatureMapper.getFeatureName();
String source = numericalFeatureMapper.getSource();
int featureIndex = numericalFeatureMapper.getFeatureIndex();
if (source.equalsIgnoreCase("field")){
for (String id: dataIndexIds){
int algorithmId = idTranslator.toIntId(id);
float value = index.getFloatField(id,featureName);
dataSet.setFeatureValue(algorithmId,featureIndex,value);
}
}
if (source.equalsIgnoreCase("matching_score")){
SearchResponse response = null;
//todo assume unigram, so slop doesn't matter
response = index.matchPhrase(index.getBodyField(), featureName, dataIndexIds, 0);
SearchHit[] hits = response.getHits().getHits();
for (SearchHit hit: hits){
String indexId = hit.getId();
float score = hit.getScore();
int algorithmId = idTranslator.toIntId(indexId);
dataSet.setFeatureValue(algorithmId,featureIndex,score);
}
}
});
DataSetUtil.setIdTranslator(dataSet,idTranslator);
DataSetUtil.setLabelTranslator(dataSet, labelTranslator);
return dataSet;
}
static ClfDataSet loadTrainData(Config config, SingleLabelIndex index, FeatureMappers featureMappers,
IdTranslator idTranslator, LabelTranslator labelTranslator) throws Exception{
System.out.println("creating training set");
//todo fix
int totalDim = config.getInt("maxNumColumns");
System.out.println("allocating "+totalDim+" columns for training set");
ClfDataSet dataSet = loadData(config,index,featureMappers,idTranslator,totalDim,labelTranslator);
System.out.println("training set created");
return dataSet;
}
static ClfDataSet loadTestData(Config config, SingleLabelIndex index,
FeatureMappers featureMappers, IdTranslator idTranslator,
LabelTranslator labelTranslator) throws Exception{
System.out.println("creating test set");
int totalDim = featureMappers.getTotalDim();
ClfDataSet dataSet = loadData(config,index,featureMappers,idTranslator,totalDim,labelTranslator);
System.out.println("test set created");
return dataSet;
}
static void trainModel(Config config, ClfDataSet dataSet, FeatureMappers featureMappers,
SingleLabelIndex index, IdTranslator trainIdTranslator) throws Exception{
String archive = config.getString("archive.folder");
int numIterations = config.getInt("train.numIterations");
int numClasses = config.getInt("numClasses");
int numLeaves = config.getInt("train.numLeaves");
double learningRate = config.getDouble("train.learningRate");
int trainMinDataPerLeaf = config.getInt("train.minDataPerLeaf");
String modelName = config.getString("archive.model");
boolean overwriteModels = config.getBoolean("train.overwriteModels");
int numDocsToSelect = config.getInt("extraction.numDocsToSelect");
int numNgramsToExtract = config.getInt("extraction.numNgramsToExtract");
double extractionFrequency = config.getDouble("extraction.frequency");
if (extractionFrequency>1 || extractionFrequency<0){
throw new IllegalArgumentException("0<=extraction.frequency<=1");
}
LabelTranslator labelTranslator = dataSet.getSetting().getLabelTranslator();
StopWatch stopWatch = new StopWatch();
stopWatch.start();
System.out.println("training model ");
LKTBConfig trainConfig = new LKTBConfig.Builder(dataSet)
.learningRate(learningRate).minDataPerLeaf(trainMinDataPerLeaf)
.numLeaves(numLeaves)
.build();
LKTreeBoost lkTreeBoost = new LKTreeBoost(numClasses);
lkTreeBoost.setPriorProbs(dataSet);
lkTreeBoost.setTrainConfig(trainConfig);
TermSplitExtractor splitExtractor = new TermSplitExtractor(index, trainIdTranslator,
numNgramsToExtract)
.setMinDataPerLeaf(config.getInt("extraction.splitExtractor.minDataPerLeaf"));
TermTfidfExtractor tfidfExtractor = new TermTfidfExtractor(index,trainIdTranslator,
numNgramsToExtract).
setMinDf(config.getInt("extraction.tfidfExtractor.minDf"));
TermTfidfSplitExtractor tfidfSplitExtractor = new TermTfidfSplitExtractor(index,
trainIdTranslator,numNgramsToExtract).
setMinDf(config.getInt("extraction.tfidfSplitExtractor.minDf")).
setNumSurvivors(config.getInt("extraction.tfidfSplitExtractor.numSurvivors")).
setMinDataPerLeaf(config.getInt("extraction.tfidfSplitExtractor.minDataPerLeaf"));
PhraseSplitExtractor phraseSplitExtractor = new PhraseSplitExtractor(index,trainIdTranslator)
.setMinDataPerLeaf(config.getInt("extraction.phraseSplitExtractor.minDataPerLeaf"))
.setMinDf(config.getInt("extraction.phraseSplitExtractor.minDf"))
.setTopN(config.getInt("extraction.phraseSplitExtractor.topN"));
DFStats dfStats = loadDFStats(config,index,trainIdTranslator);
List<Set<String>> seedsForAllClasses = new ArrayList<>();
for (int i=0;i<numClasses;i++){
//todo parameters
Set<String> set = new HashSet<>();
set.addAll(dfStats.getSortedTerms(i,50,100));
seedsForAllClasses.add(set);
}
Set<String> blackList = new HashSet<>();
//start the matrix with the seeds
//may have duplicates, but should not be a big deal
for(Set<String> seeds: seedsForAllClasses){
for (String term: seeds){
int featureIndex = featureMappers.nextAvailable();
SearchResponse response = index.match(index.getBodyField(),
term,trainIdTranslator.getAllExtIds(), MatchQueryBuilder.Operator.AND);
for (SearchHit hit: response.getHits().getHits()){
String indexId = hit.getId();
int algorithmId = trainIdTranslator.toIntId(indexId);
float score = hit.getScore();
dataSet.setFeatureValue(algorithmId, featureIndex,score);
}
NumericalFeatureMapper mapper = NumericalFeatureMapper.getBuilder().
setFeatureIndex(featureIndex).setFeatureName(term).
setSource("matching_score").build();
featureMappers.addMapper(mapper);
blackList.add(term);
}
}
// //todo
// List<Integer> validationSet = new ArrayList<>();
// for (int i=0;i<trainIndex.getNumDocs();i++){
// validationSet.add(i);
// }
for (int iteration=0;iteration<numIterations;iteration++){
System.out.println("iteration "+iteration);
lkTreeBoost.calGradients();
boolean condition1 = (featureMappers.getTotalDim()
+numNgramsToExtract*numClasses*3
+config.getInt("extraction.phraseSplitExtractor.topN")*numClasses*3
<dataSet.getNumFeatures());
boolean condition2 = (Math.random()<extractionFrequency);
//should start with some feature
boolean condition3 = (iteration==0);
boolean shouldExtractFeatures = condition1&&condition2||condition3;
if (!shouldExtractFeatures){
if (!condition1){
System.out.println("we have reached the max number of columns " +
"and will not extract new features");
}
if (!condition2){
System.out.println("no feature extraction is scheduled for this round");
}
}
/**
* from easy set
*/
if (shouldExtractFeatures&&config.getBoolean("extraction.fromEasySet")){
//generate easy set
FocusSet focusSet = new FocusSet(numClasses);
for (int k=0;k<numClasses;k++){
double[] gradient = lkTreeBoost.getGradient(k);
Comparator<Pair<Integer,Double>> comparator = Comparator.comparing(Pair::getSecond);
List<Integer> easyExamples = IntStream.range(0,gradient.length)
.mapToObj(i -> new Pair<>(i,gradient[i]))
.filter(pair -> pair.getSecond()>0)
.sorted(comparator)
.limit(numDocsToSelect)
.map(Pair::getFirst)
.collect(Collectors.toList());
for(Integer doc: easyExamples){
focusSet.add(doc,k);
}
}
List<Integer> validationSet = focusSet.getAll();
for (int k=0;k<numClasses;k++){
double[] allGradients = lkTreeBoost.getGradient(k);
List<Double> gradientsForValidation = validationSet.stream()
.map(i -> allGradients[i]).collect(Collectors.toList());
List<String> goodTerms = null;
if(config.getString("extraction.Extractor").equalsIgnoreCase("splitExtractor")){
goodTerms = splitExtractor.getGoodTerms(focusSet,
validationSet,
blackList, k, gradientsForValidation);
} else if (config.getString("extraction.Extractor").equalsIgnoreCase("tfidfExtractor")){
goodTerms = tfidfExtractor.getGoodTerms(focusSet,blackList,k);
} else if (config.getString("extraction.Extractor").equalsIgnoreCase("tfidfSplitExtractor")){
goodTerms = tfidfSplitExtractor.getGoodTerms(focusSet,
validationSet,
blackList, k, gradientsForValidation);
} else {
throw new RuntimeException("ngram extractor is not specified correctly");
}
seedsForAllClasses.get(k).addAll(goodTerms);
List<String> focusSetIndexIds = focusSet.getDataClassK(k)
.parallelStream().map(trainIdTranslator::toExtId)
.collect(Collectors.toList());
System.out.println("easy set for class " +k+ "("+labelTranslator.toExtLabel(k)+ "):");
System.out.println(focusSetIndexIds.toString());
System.out.println("terms extracted from easy set for class " + k+" ("+labelTranslator.toExtLabel(k)+"):");
System.out.println(goodTerms);
//phrases
System.out.println("seeds for class " +k+ "("+labelTranslator.toExtLabel(k)+ "):");
System.out.println(seedsForAllClasses.get(k));
List<String> goodPhrases = phraseSplitExtractor.getGoodPhrases(focusSet,validationSet,blackList,k,
gradientsForValidation,seedsForAllClasses.get(k));
System.out.println("phrases extracted from easy set for class " + k+" ("+labelTranslator.toExtLabel(k)+"):");
System.out.println(goodPhrases);
blackList.addAll(goodPhrases);
for (String ngram:goodTerms){
int featureIndex = featureMappers.nextAvailable();
SearchResponse response = index.match(index.getBodyField(),
ngram,trainIdTranslator.getAllExtIds(), MatchQueryBuilder.Operator.AND);
for (SearchHit hit: response.getHits().getHits()){
String indexId = hit.getId();
int algorithmId = trainIdTranslator.toIntId(indexId);
float score = hit.getScore();
dataSet.setFeatureValue(algorithmId, featureIndex,score);
}
NumericalFeatureMapper mapper = NumericalFeatureMapper.getBuilder().
setFeatureIndex(featureIndex).setFeatureName(ngram).
setSource("matching_score").build();
featureMappers.addMapper(mapper);
blackList.add(ngram);
}
for (String phrase:goodPhrases){
int featureIndex = featureMappers.nextAvailable();
SearchResponse response = index.matchPhrase(index.getBodyField(),
phrase,trainIdTranslator.getAllExtIds(), 0);
for (SearchHit hit: response.getHits().getHits()){
String indexId = hit.getId();
int algorithmId = trainIdTranslator.toIntId(indexId);
float score = hit.getScore();
dataSet.setFeatureValue(algorithmId, featureIndex,score);
}
NumericalFeatureMapper mapper = NumericalFeatureMapper.getBuilder().
setFeatureIndex(featureIndex).setFeatureName(phrase).
setSource("matching_score").build();
featureMappers.addMapper(mapper);
}
}
}
/**
* hard set
*/
if (shouldExtractFeatures&&config.getBoolean("extraction.fromHardSet")){
//generate focus set
FocusSet focusSet = new FocusSet(numClasses);
for (int k=0;k<numClasses;k++){
double[] gradient = lkTreeBoost.getGradient(k);
Comparator<Pair<Integer,Double>> comparator = Comparator.comparing(Pair::getSecond);
List<Integer> hardExamples = IntStream.range(0,gradient.length)
.mapToObj(i -> new Pair<>(i,gradient[i]))
.filter(pair -> pair.getSecond()>0)
.sorted(comparator.reversed())
.limit(numDocsToSelect)
.map(Pair::getFirst)
.collect(Collectors.toList());
for(Integer doc: hardExamples){
focusSet.add(doc,k);
}
}
List<Integer> validationSet = focusSet.getAll();
for (int k=0;k<numClasses;k++){
double[] allGradients = lkTreeBoost.getGradient(k);
List<Double> gradientsForValidation = validationSet.stream()
.map(i -> allGradients[i]).collect(Collectors.toList());
List<String> goodTerms = null;
if(config.getString("extraction.Extractor").equalsIgnoreCase("splitExtractor")){
goodTerms = splitExtractor.getGoodTerms(focusSet,
validationSet,
blackList, k, gradientsForValidation);
} else if (config.getString("extraction.Extractor").equalsIgnoreCase("tfidfExtractor")){
goodTerms = tfidfExtractor.getGoodTerms(focusSet,blackList,k);
} else if (config.getString("extraction.Extractor").equalsIgnoreCase("tfidfSplitExtractor")){
goodTerms = tfidfSplitExtractor.getGoodTerms(focusSet,
validationSet,
blackList, k, gradientsForValidation);
} else {
throw new RuntimeException("ngram extractor is not specified correctly");
}
seedsForAllClasses.get(k).addAll(goodTerms);
List<String> focusSetIndexIds = focusSet.getDataClassK(k)
.parallelStream().map(trainIdTranslator::toExtId)
.collect(Collectors.toList());
System.out.println("hard set for class " +k+ "("+labelTranslator.toExtLabel(k)+ "):");
System.out.println(focusSetIndexIds.toString());
System.out.println("terms extracted from hard set for class " + k+" ("+labelTranslator.toExtLabel(k)+"):");
System.out.println(goodTerms);
//phrases
System.out.println("seeds for class " +k+ "("+labelTranslator.toExtLabel(k)+ "):");
System.out.println(seedsForAllClasses.get(k));
List<String> goodPhrases = phraseSplitExtractor.getGoodPhrases(focusSet,validationSet,blackList,k,
gradientsForValidation,seedsForAllClasses.get(k));
System.out.println("phrases extracted from hard set for class " + k+" ("+labelTranslator.toExtLabel(k)+"):");
System.out.println(goodPhrases);
blackList.addAll(goodPhrases);
for (String ngram:goodTerms){
int featureIndex = featureMappers.nextAvailable();
SearchResponse response = index.match(index.getBodyField(),
ngram,trainIdTranslator.getAllExtIds(), MatchQueryBuilder.Operator.AND);
for (SearchHit hit: response.getHits().getHits()){
String indexId = hit.getId();
int algorithmId = trainIdTranslator.toIntId(indexId);
float score = hit.getScore();
dataSet.setFeatureValue(algorithmId, featureIndex,score);
}
NumericalFeatureMapper mapper = NumericalFeatureMapper.getBuilder().
setFeatureIndex(featureIndex).setFeatureName(ngram).
setSource("matching_score").build();
featureMappers.addMapper(mapper);
blackList.add(ngram);
}
for (String phrase:goodPhrases){
int featureIndex = featureMappers.nextAvailable();
SearchResponse response = index.matchPhrase(index.getBodyField(),
phrase,trainIdTranslator.getAllExtIds(), 0);
for (SearchHit hit: response.getHits().getHits()){
String indexId = hit.getId();
int algorithmId = trainIdTranslator.toIntId(indexId);
float score = hit.getScore();
dataSet.setFeatureValue(algorithmId, featureIndex,score);
}
NumericalFeatureMapper mapper = NumericalFeatureMapper.getBuilder().
setFeatureIndex(featureIndex).setFeatureName(phrase).
setSource("matching_score").build();
featureMappers.addMapper(mapper);
}
}
}
/**
* uncertain set
*/
if (shouldExtractFeatures&&config.getBoolean("extraction.fromUncertainSet")){
//generate focus set
FocusSet focusSet = new FocusSet(numClasses);
Comparator<Pair<Integer,BestVsSecond>> comparator = Comparator.comparing(pair -> pair.getSecond().getDifference());
List<Integer> examples = IntStream.range(0,dataSet.getNumDataPoints())
.mapToObj(i -> new Pair<>(i,new BestVsSecond(lkTreeBoost.getClassProbs(i))))
.sorted(comparator).map(Pair::getFirst)
.limit(numClasses*numDocsToSelect).collect(Collectors.toList());
for (Integer dataPoint: examples){
int label = dataSet.getLabels()[dataPoint];
focusSet.add(dataPoint,label);
}
List<Integer> validationSet = focusSet.getAll();
for (int k=0;k<numClasses;k++){
double[] allGradients = lkTreeBoost.getGradient(k);
List<Double> gradientsForValidation = validationSet.stream()
.map(i -> allGradients[i]).collect(Collectors.toList());
List<String> goodTerms = null;
if(config.getString("extraction.Extractor").equalsIgnoreCase("splitExtractor")){
goodTerms = splitExtractor.getGoodTerms(focusSet,
validationSet,
blackList, k, gradientsForValidation);
} else if (config.getString("extraction.Extractor").equalsIgnoreCase("tfidfExtractor")){
goodTerms = tfidfExtractor.getGoodTerms(focusSet,blackList,k);
} else if (config.getString("extraction.Extractor").equalsIgnoreCase("tfidfSplitExtractor")){
goodTerms = tfidfSplitExtractor.getGoodTerms(focusSet,
validationSet,
blackList, k, gradientsForValidation);
} else {
throw new RuntimeException("ngram extractor is not specified correctly");
}
seedsForAllClasses.get(k).addAll(goodTerms);
List<String> focusSetIndexIds = focusSet.getDataClassK(k)
.parallelStream().map(trainIdTranslator::toExtId)
.collect(Collectors.toList());
System.out.println("uncertain set for class " +k+ "("+labelTranslator.toExtLabel(k)+ "):");
System.out.println(focusSetIndexIds.toString());
System.out.println("terms extracted from uncertain set for class " + k+" ("+labelTranslator.toExtLabel(k)+"):");
System.out.println(goodTerms);
//phrases
System.out.println("seeds for class " +k+ "("+labelTranslator.toExtLabel(k)+ "):");
System.out.println(seedsForAllClasses.get(k));
List<String> goodPhrases = phraseSplitExtractor.getGoodPhrases(focusSet,validationSet,blackList,k,
gradientsForValidation,seedsForAllClasses.get(k));
System.out.println("phrases extracted from uncertain set for class " + k+" ("+labelTranslator.toExtLabel(k)+"):");
System.out.println(goodPhrases);
blackList.addAll(goodPhrases);
for (String ngram:goodTerms){
int featureIndex = featureMappers.nextAvailable();
SearchResponse response = index.match(index.getBodyField(),
ngram,trainIdTranslator.getAllExtIds(), MatchQueryBuilder.Operator.AND);
for (SearchHit hit: response.getHits().getHits()){
String indexId = hit.getId();
int algorithmId = trainIdTranslator.toIntId(indexId);
float score = hit.getScore();
dataSet.setFeatureValue(algorithmId, featureIndex,score);
}
NumericalFeatureMapper mapper = NumericalFeatureMapper.getBuilder().
setFeatureIndex(featureIndex).setFeatureName(ngram).
setSource("matching_score").build();
featureMappers.addMapper(mapper);
blackList.add(ngram);
}
for (String phrase:goodPhrases){
int featureIndex = featureMappers.nextAvailable();
SearchResponse response = index.matchPhrase(index.getBodyField(),
phrase,trainIdTranslator.getAllExtIds(), 0);
for (SearchHit hit: response.getHits().getHits()){
String indexId = hit.getId();
int algorithmId = trainIdTranslator.toIntId(indexId);
float score = hit.getScore();
dataSet.setFeatureValue(algorithmId, featureIndex,score);
}
NumericalFeatureMapper mapper = NumericalFeatureMapper.getBuilder().
setFeatureIndex(featureIndex).setFeatureName(phrase).
setSource("matching_score").build();
featureMappers.addMapper(mapper);
}
}
}
int[] activeFeatures = IntStream.range(0, featureMappers.getTotalDim()).toArray();
lkTreeBoost.setActiveFeatures(activeFeatures);
lkTreeBoost.fitRegressors();
}
File serializedModel = new File(archive,modelName);
if (!overwriteModels && serializedModel.exists()){
throw new RuntimeException(serializedModel.getAbsolutePath()+"already exists");
}
lkTreeBoost.serialize(serializedModel);
System.out.println("model saved to "+serializedModel.getAbsolutePath());
System.out.println("accuracy on training set = "+ Accuracy.accuracy(lkTreeBoost,
dataSet));
System.out.println("time spent = "+stopWatch);
}
static String[] sampleTrain(Config config, SingleLabelIndex index){
int numDocsInIndex = index.getNumDocs();
String[] trainIds = null;
if (config.getString("split.fashion").equalsIgnoreCase("fixed")){
String splitField = config.getString("index.splitField");
trainIds = IntStream.range(0, numDocsInIndex).
filter(i -> index.getStringField("" + i, splitField).
equalsIgnoreCase("train")).
mapToObj(i -> "" + i).collect(Collectors.toList()).
toArray(new String[0]);
} else if (config.getString("split.fashion").equalsIgnoreCase("random")){
double trainPercentage = config.getDouble("split.random.trainPercentage");
int[] labels = new int[numDocsInIndex];
for (int i=0;i<labels.length;i++){
labels[i] = index.getLabel(""+i);
}
List<Integer> sample = Sampling.stratified(labels, trainPercentage);
trainIds = new String[sample.size()];
for (int i=0;i<trainIds.length;i++){
trainIds[i] = ""+sample.get(i);
}
} else {
throw new RuntimeException("illegal split fashion");
}
return trainIds;
}
static String[] sampleTest(int numDocsInIndex, String[] trainIndexIds){
Set<String> test = new HashSet<>(numDocsInIndex);
for (int i=0;i<numDocsInIndex;i++){
test.add(""+i);
}
List<String> _trainIndexIds = new ArrayList<>(trainIndexIds.length);
for (String id: trainIndexIds){
_trainIndexIds.add(id);
}
test.removeAll(_trainIndexIds);
return test.toArray(new String[0]);
}
static IdTranslator loadIdTranslator(String[] indexIds) throws Exception{
IdTranslator idTranslator = new IdTranslator();
for (int i=0;i<indexIds.length;i++){
idTranslator.addData(i,""+indexIds[i]);
}
return idTranslator;
}
static LabelTranslator loadLabelTranslator(Config config, SingleLabelIndex index) throws Exception{
int numClasses = config.getInt("numClasses");
int numDocs = index.getNumDocs();
Map<Integer, String> map = new HashMap<>(numClasses);
for (int i=0;i<numDocs;i++){
int intLabel = index.getLabel(""+i);
String extLabel = index.getExtLabel("" + i);
map.put(intLabel,extLabel);
}
return new LabelTranslator(map);
}
/**
*
* @param config
* @param index
* @param featureMappers to be updated
* @param ids pull features from train ids
* @throws Exception
*/
static void addInitialFeatures(Config config, SingleLabelIndex index,
FeatureMappers featureMappers,
String[] ids) throws Exception{
String featureFieldPrefix = config.getString("index.featureFieldPrefix");
Set<String> allFields = index.listAllFields();
List<String> featureFields = allFields.stream().
filter(field -> field.startsWith(featureFieldPrefix)).
collect(Collectors.toList());
System.out.println("all possible initial features:"+featureFields);
for (String field: featureFields){
String featureType = index.getFieldType(field);
if (featureType.equalsIgnoreCase("string")){
CategoricalFeatureMapperBuilder builder = new CategoricalFeatureMapperBuilder();
builder.setFeatureName(field);
builder.setStart(featureMappers.nextAvailable());
builder.setSource("field");
for (String id: ids){
String category = index.getStringField(id, field);
builder.addCategory(category);
}
boolean toAdd = true;
CategoricalFeatureMapper mapper = builder.build();
if (config.getBoolean("categFeature.filter")){
double threshold = config.getDouble("categFeature.percentThreshold");
int numCategories = mapper.getNumCategories();
if (numCategories> ids.length*threshold){
toAdd=false;
System.out.println("field "+field+" has too many categories "
+"("+numCategories+"), omitted.");
}
}
if(toAdd){
featureMappers.addMapper(mapper);
}
} else {
NumericalFeatureMapperBuilder builder = new NumericalFeatureMapperBuilder();
builder.setFeatureName(field);
builder.setFeatureIndex(featureMappers.nextAvailable());
builder.setSource("field");
NumericalFeatureMapper mapper = builder.build();
featureMappers.addMapper(mapper);
}
}
}
static void showDistribution(Config config, ClfDataSet dataSet, LabelTranslator labelTranslator){
int numClasses = config.getInt("numClasses");
int[] counts = new int[numClasses];
int[] labels = dataSet.getLabels();
for (int i=0;i<dataSet.getNumDataPoints();i++){
int label = labels[i];
counts[label] += 1;
}
System.out.println("label distribution:");
for (int i=0;i<numClasses;i++){
System.out.print(i+"("+labelTranslator.toExtLabel(i)+"):"+counts[i]+", ");
}
System.out.println("");
}
static void saveDataSet(Config config, ClfDataSet dataSet, String name) throws Exception{
String archive = config.getString("archive.folder");
File dataFile = new File(archive,name);
TRECFormat.save(dataSet, dataFile);
DataSetUtil.dumpDataSettings(dataSet,new File(dataFile,"data_settings.txt"));
DataSetUtil.dumpFeatureSettings(dataSet,new File(dataFile,"feature_settings.txt"));
System.out.println("data set saved to "+dataFile.getAbsolutePath());
}
static DFStats loadDFStats(Config config, SingleLabelIndex index, IdTranslator trainIdTranslator) throws IOException {
DFStats dfStats = new DFStats(config.getInt("numClasses"));
String[] trainIds = trainIdTranslator.getAllExtIds();
dfStats.update(index,trainIds);
dfStats.sort();
return dfStats;
}
static void dumpTrainFeatures(Config config, SingleLabelIndex index, IdTranslator idTranslator) throws Exception{
String archive = config.getString("archive.folder");
String trecFile = new File(archive,config.getString("archive.trainingSet")).getAbsolutePath();
String file = new File(trecFile,"dumped_fields.txt").getAbsolutePath();
dumpFeatures(config,index,idTranslator,file);
}
static void dumpTestFeatures(Config config, SingleLabelIndex index, IdTranslator idTranslator) throws Exception{
String archive = config.getString("archive.folder");
String trecFile = new File(archive,config.getString("archive.testSet")).getAbsolutePath();
String file = new File(trecFile,"dumped_fields.txt").getAbsolutePath();
dumpFeatures(config,index,idTranslator,file);
}
static void dumpFeatures(Config config, SingleLabelIndex index, IdTranslator idTranslator, String fileName) throws Exception{
String[] fields = config.getString("archive.dumpedFields").split(",");
int numDocs = idTranslator.numData();
try(BufferedWriter bw = new BufferedWriter(new FileWriter(fileName))
){
for (int intId=0;intId<numDocs;intId++){
bw.write("intId=");
bw.write(""+intId);
bw.write(",");
bw.write("extId=");
String extId = idTranslator.toExtId(intId);
bw.write(extId);
bw.write(",");
for (int i=0;i<fields.length;i++){
String field = fields[i];
bw.write(field+"=");
bw.write(index.getStringField(extId,field));
if (i!=fields.length-1){
bw.write(",");
}
}
bw.write("\n");
}
}
}
}
| src/main/java/edu/neu/ccs/pyramid/experiment/Exp3.java | package edu.neu.ccs.pyramid.experiment;
import edu.neu.ccs.pyramid.classification.boosting.lktb.LKTBConfig;
import edu.neu.ccs.pyramid.classification.boosting.lktb.LKTreeBoost;
import edu.neu.ccs.pyramid.configuration.Config;
import edu.neu.ccs.pyramid.dataset.*;
import edu.neu.ccs.pyramid.elasticsearch.SingleLabelIndex;
import edu.neu.ccs.pyramid.dataset.IdTranslator;
import edu.neu.ccs.pyramid.eval.Accuracy;
import edu.neu.ccs.pyramid.feature.*;
import edu.neu.ccs.pyramid.feature_extraction.*;
import edu.neu.ccs.pyramid.util.Pair;
import edu.neu.ccs.pyramid.util.Sampling;
import org.apache.commons.lang3.time.StopWatch;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.search.SearchHit;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
/**
* feature extraction using elasticsearch,
* can start with initial features in ESindex
* can use default train/test split or random split
* follow golden_features, exp57
* Created by chengli on 9/7/14.
*/
public class Exp3 {
public static void main(String[] args) throws Exception{
if (args.length !=1){
throw new IllegalArgumentException("please specify the config file");
}
Config config = new Config(args[0]);
System.out.println(config);
SingleLabelIndex index = loadIndex(config);
if (config.getBoolean("train")){
train(config,index);
}
index.close();
}
static void train(Config config, SingleLabelIndex index) throws Exception{
int numDocsInIndex = index.getNumDocs();
String[] trainIndexIds = sampleTrain(config,index);
System.out.println("number of training documents = "+trainIndexIds.length);
IdTranslator trainIdTranslator = loadIdTranslator(trainIndexIds);
FeatureMappers featureMappers = new FeatureMappers();
LabelTranslator labelTranslator = loadLabelTranslator(config, index);
if (config.getBoolean("useInitialFeatures")){
addInitialFeatures(config,index,featureMappers,trainIndexIds);
}
ClfDataSet trainDataSet = loadTrainData(config,index,featureMappers, trainIdTranslator, labelTranslator);
System.out.println("in training set :");
showDistribution(config,trainDataSet,labelTranslator);
trainModel(config,trainDataSet,featureMappers,index, trainIdTranslator);
//only keep used columns
ClfDataSet trimmedTrainDataSet = DataSetUtil.trim(trainDataSet,featureMappers.getTotalDim());
DataSetUtil.setFeatureMappers(trimmedTrainDataSet,featureMappers);
saveDataSet(config, trimmedTrainDataSet, config.getString("archive.trainingSet"));
if (config.getBoolean("archive.dumpFields")){
dumpTrainFeatures(config,index,trainIdTranslator);
}
String[] testIndexIds = sampleTest(numDocsInIndex,trainIndexIds);
IdTranslator testIdTranslator = loadIdTranslator(testIndexIds);
ClfDataSet testDataSet = loadTestData(config,index,featureMappers,testIdTranslator,labelTranslator);
DataSetUtil.setFeatureMappers(testDataSet,featureMappers);
saveDataSet(config, testDataSet, config.getString("archive.testSet"));
if (config.getBoolean("archive.dumpFields")){
dumpTestFeatures(config,index,testIdTranslator);
}
}
static SingleLabelIndex loadIndex(Config config) throws Exception{
SingleLabelIndex.Builder builder = new SingleLabelIndex.Builder()
.setIndexName(config.getString("index.indexName"))
.setClusterName(config.getString("index.clusterName"))
.setClientType(config.getString("index.clientType"))
.setLabelField(config.getString("index.labelField"))
.setExtLabelField(config.getString("index.extLabelField"))
.setDocumentType(config.getString("index.documentType"));
if (config.getString("index.clientType").equals("transport")){
String[] hosts = config.getString("index.hosts").split(Pattern.quote(","));
String[] ports = config.getString("index.ports").split(Pattern.quote(","));
builder.addHostsAndPorts(hosts,ports);
}
SingleLabelIndex index = builder.build();
System.out.println("index loaded");
System.out.println("there are "+index.getNumDocs()+" documents in the index.");
// for (int i=0;i<index.getNumDocs();i++){
// System.out.println(i);
// System.out.println(index.getLabel(""+i));
// }
return index;
}
/**
*
* @param config
* @param index
* @param featureMappers
* @param idTranslator separate for training and test
* @param totalDim
* @return
* @throws Exception
*/
static ClfDataSet loadData(Config config, SingleLabelIndex index,
FeatureMappers featureMappers,
IdTranslator idTranslator, int totalDim,
LabelTranslator labelTranslator) throws Exception{
int numDataPoints = idTranslator.numData();
int numClasses = config.getInt("numClasses");
ClfDataSet dataSet;
if(config.getBoolean("featureMatrix.sparse")){
dataSet= new SparseClfDataSet(numDataPoints,totalDim,numClasses);
} else {
dataSet= new DenseClfDataSet(numDataPoints,totalDim,numClasses);
}
for(int i=0;i<numDataPoints;i++){
String dataIndexId = idTranslator.toExtId(i);
int label = index.getLabel(dataIndexId);
dataSet.setLabel(i,label);
}
String[] dataIndexIds = idTranslator.getAllExtIds();
featureMappers.getCategoricalFeatureMappers().stream().parallel().
forEach(categoricalFeatureMapper -> {
String featureName = categoricalFeatureMapper.getFeatureName();
String source = categoricalFeatureMapper.getSource();
if (source.equalsIgnoreCase("field")){
for (String id: dataIndexIds){
int algorithmId = idTranslator.toIntId(id);
String category = index.getStringField(id,featureName);
// might be a new category unseen in training
if (categoricalFeatureMapper.hasCategory(category)){
int featureIndex = categoricalFeatureMapper.getFeatureIndex(category);
dataSet.setFeatureValue(algorithmId,featureIndex,1);
}
}
}
});
featureMappers.getNumericalFeatureMappers().stream().parallel().
forEach(numericalFeatureMapper -> {
String featureName = numericalFeatureMapper.getFeatureName();
String source = numericalFeatureMapper.getSource();
int featureIndex = numericalFeatureMapper.getFeatureIndex();
if (source.equalsIgnoreCase("field")){
for (String id: dataIndexIds){
int algorithmId = idTranslator.toIntId(id);
float value = index.getFloatField(id,featureName);
dataSet.setFeatureValue(algorithmId,featureIndex,value);
}
}
if (source.equalsIgnoreCase("matching_score")){
SearchResponse response = null;
//todo assume unigram, so slop doesn't matter
response = index.matchPhrase(index.getBodyField(), featureName, dataIndexIds, 0);
SearchHit[] hits = response.getHits().getHits();
for (SearchHit hit: hits){
String indexId = hit.getId();
float score = hit.getScore();
int algorithmId = idTranslator.toIntId(indexId);
dataSet.setFeatureValue(algorithmId,featureIndex,score);
}
}
});
DataSetUtil.setIdTranslator(dataSet,idTranslator);
DataSetUtil.setLabelTranslator(dataSet, labelTranslator);
return dataSet;
}
static ClfDataSet loadTrainData(Config config, SingleLabelIndex index, FeatureMappers featureMappers,
IdTranslator idTranslator, LabelTranslator labelTranslator) throws Exception{
System.out.println("creating training set");
//todo fix
int totalDim = config.getInt("maxNumColumns");
System.out.println("allocating "+totalDim+" columns for training set");
ClfDataSet dataSet = loadData(config,index,featureMappers,idTranslator,totalDim,labelTranslator);
System.out.println("training set created");
return dataSet;
}
static ClfDataSet loadTestData(Config config, SingleLabelIndex index,
FeatureMappers featureMappers, IdTranslator idTranslator,
LabelTranslator labelTranslator) throws Exception{
System.out.println("creating test set");
int totalDim = featureMappers.getTotalDim();
ClfDataSet dataSet = loadData(config,index,featureMappers,idTranslator,totalDim,labelTranslator);
System.out.println("test set created");
return dataSet;
}
static void trainModel(Config config, ClfDataSet dataSet, FeatureMappers featureMappers,
SingleLabelIndex index, IdTranslator trainIdTranslator) throws Exception{
String archive = config.getString("archive.folder");
int numIterations = config.getInt("train.numIterations");
int numClasses = config.getInt("numClasses");
int numLeaves = config.getInt("train.numLeaves");
double learningRate = config.getDouble("train.learningRate");
int trainMinDataPerLeaf = config.getInt("train.minDataPerLeaf");
String modelName = config.getString("archive.model");
boolean overwriteModels = config.getBoolean("train.overwriteModels");
int numDocsToSelect = config.getInt("extraction.numDocsToSelect");
int numNgramsToExtract = config.getInt("extraction.numNgramsToExtract");
double extractionFrequency = config.getDouble("extraction.frequency");
if (extractionFrequency>1 || extractionFrequency<0){
throw new IllegalArgumentException("0<=extraction.frequency<=1");
}
LabelTranslator labelTranslator = dataSet.getSetting().getLabelTranslator();
StopWatch stopWatch = new StopWatch();
stopWatch.start();
System.out.println("training model ");
LKTBConfig trainConfig = new LKTBConfig.Builder(dataSet)
.learningRate(learningRate).minDataPerLeaf(trainMinDataPerLeaf)
.numLeaves(numLeaves)
.build();
LKTreeBoost lkTreeBoost = new LKTreeBoost(numClasses);
lkTreeBoost.setPriorProbs(dataSet);
lkTreeBoost.setTrainConfig(trainConfig);
TermSplitExtractor splitExtractor = new TermSplitExtractor(index, trainIdTranslator,
numNgramsToExtract)
.setMinDataPerLeaf(config.getInt("extraction.splitExtractor.minDataPerLeaf"));
TermTfidfExtractor tfidfExtractor = new TermTfidfExtractor(index,trainIdTranslator,
numNgramsToExtract).
setMinDf(config.getInt("extraction.tfidfExtractor.minDf"));
TermTfidfSplitExtractor tfidfSplitExtractor = new TermTfidfSplitExtractor(index,
trainIdTranslator,numNgramsToExtract).
setMinDf(config.getInt("extraction.tfidfSplitExtractor.minDf")).
setNumSurvivors(config.getInt("extraction.tfidfSplitExtractor.numSurvivors")).
setMinDataPerLeaf(config.getInt("extraction.tfidfSplitExtractor.minDataPerLeaf"));
PhraseSplitExtractor phraseSplitExtractor = new PhraseSplitExtractor(index,trainIdTranslator)
.setMinDataPerLeaf(config.getInt("extraction.phraseSplitExtractor.minDataPerLeaf"))
.setMinDf(config.getInt("extraction.phraseSplitExtractor.minDf"))
.setTopN(config.getInt("extraction.phraseSplitExtractor.topN"));
DFStats dfStats = loadDFStats(config,index,trainIdTranslator);
List<Set<String>> seedsForAllClasses = new ArrayList<>();
for (int i=0;i<numClasses;i++){
//todo parameters
Set<String> set = new HashSet<>();
set.addAll(dfStats.getSortedTerms(i,50,100));
seedsForAllClasses.add(set);
}
Set<String> blackList = new HashSet<>();
//start the matrix with the seeds
//may have duplicates, but should not be a big deal
for(Set<String> seeds: seedsForAllClasses){
for (String term: seeds){
int featureIndex = featureMappers.nextAvailable();
SearchResponse response = index.match(index.getBodyField(),
term,trainIdTranslator.getAllExtIds(), MatchQueryBuilder.Operator.AND);
for (SearchHit hit: response.getHits().getHits()){
String indexId = hit.getId();
int algorithmId = trainIdTranslator.toIntId(indexId);
float score = hit.getScore();
dataSet.setFeatureValue(algorithmId, featureIndex,score);
}
NumericalFeatureMapper mapper = NumericalFeatureMapper.getBuilder().
setFeatureIndex(featureIndex).setFeatureName(term).
setSource("matching_score").build();
featureMappers.addMapper(mapper);
blackList.add(term);
}
}
// //todo
// List<Integer> validationSet = new ArrayList<>();
// for (int i=0;i<trainIndex.getNumDocs();i++){
// validationSet.add(i);
// }
for (int iteration=0;iteration<numIterations;iteration++){
System.out.println("iteration "+iteration);
lkTreeBoost.calGradients();
boolean condition1 = (featureMappers.getTotalDim()
+numNgramsToExtract*numClasses*2
+config.getInt("extraction.phraseSplitExtractor.topN")*numClasses*2
<dataSet.getNumFeatures());
boolean condition2 = (Math.random()<extractionFrequency);
//should start with some feature
boolean condition3 = (iteration==0);
boolean shouldExtractFeatures = condition1&&condition2||condition3;
if (!shouldExtractFeatures){
if (!condition1){
System.out.println("we have reached the max number of columns " +
"and will not extract new features");
}
if (!condition2){
System.out.println("no feature extraction is scheduled for this round");
}
}
/**
* from easy set
*/
if (shouldExtractFeatures&&config.getBoolean("extraction.fromEasySet")){
//generate easy set
FocusSet focusSet = new FocusSet(numClasses);
for (int k=0;k<numClasses;k++){
double[] gradient = lkTreeBoost.getGradient(k);
Comparator<Pair<Integer,Double>> comparator = Comparator.comparing(Pair::getSecond);
List<Integer> easyExamples = IntStream.range(0,gradient.length)
.mapToObj(i -> new Pair<>(i,gradient[i]))
.filter(pair -> pair.getSecond()>0)
.sorted(comparator)
.limit(numDocsToSelect)
.map(Pair::getFirst)
.collect(Collectors.toList());
for(Integer doc: easyExamples){
focusSet.add(doc,k);
}
}
List<Integer> validationSet = focusSet.getAll();
for (int k=0;k<numClasses;k++){
double[] allGradients = lkTreeBoost.getGradient(k);
List<Double> gradientsForValidation = validationSet.stream()
.map(i -> allGradients[i]).collect(Collectors.toList());
List<String> goodTerms = null;
if(config.getString("extraction.Extractor").equalsIgnoreCase("splitExtractor")){
goodTerms = splitExtractor.getGoodTerms(focusSet,
validationSet,
blackList, k, gradientsForValidation);
} else if (config.getString("extraction.Extractor").equalsIgnoreCase("tfidfExtractor")){
goodTerms = tfidfExtractor.getGoodTerms(focusSet,blackList,k);
} else if (config.getString("extraction.Extractor").equalsIgnoreCase("tfidfSplitExtractor")){
goodTerms = tfidfSplitExtractor.getGoodTerms(focusSet,
validationSet,
blackList, k, gradientsForValidation);
} else {
throw new RuntimeException("ngram extractor is not specified correctly");
}
seedsForAllClasses.get(k).addAll(goodTerms);
List<String> focusSetIndexIds = focusSet.getDataClassK(k)
.parallelStream().map(trainIdTranslator::toExtId)
.collect(Collectors.toList());
System.out.println("easy set for class " +k+ "("+labelTranslator.toExtLabel(k)+ "):");
System.out.println(focusSetIndexIds.toString());
System.out.println("terms extracted from easy set for class " + k+" ("+labelTranslator.toExtLabel(k)+"):");
System.out.println(goodTerms);
//phrases
System.out.println("seeds for class " +k+ "("+labelTranslator.toExtLabel(k)+ "):");
System.out.println(seedsForAllClasses.get(k));
List<String> goodPhrases = phraseSplitExtractor.getGoodPhrases(focusSet,validationSet,blackList,k,
gradientsForValidation,seedsForAllClasses.get(k));
System.out.println("phrases extracted from easy set for class " + k+" ("+labelTranslator.toExtLabel(k)+"):");
System.out.println(goodPhrases);
blackList.addAll(goodPhrases);
for (String ngram:goodTerms){
int featureIndex = featureMappers.nextAvailable();
SearchResponse response = index.match(index.getBodyField(),
ngram,trainIdTranslator.getAllExtIds(), MatchQueryBuilder.Operator.AND);
for (SearchHit hit: response.getHits().getHits()){
String indexId = hit.getId();
int algorithmId = trainIdTranslator.toIntId(indexId);
float score = hit.getScore();
dataSet.setFeatureValue(algorithmId, featureIndex,score);
}
NumericalFeatureMapper mapper = NumericalFeatureMapper.getBuilder().
setFeatureIndex(featureIndex).setFeatureName(ngram).
setSource("matching_score").build();
featureMappers.addMapper(mapper);
blackList.add(ngram);
}
for (String phrase:goodPhrases){
int featureIndex = featureMappers.nextAvailable();
SearchResponse response = index.matchPhrase(index.getBodyField(),
phrase,trainIdTranslator.getAllExtIds(), 0);
for (SearchHit hit: response.getHits().getHits()){
String indexId = hit.getId();
int algorithmId = trainIdTranslator.toIntId(indexId);
float score = hit.getScore();
dataSet.setFeatureValue(algorithmId, featureIndex,score);
}
NumericalFeatureMapper mapper = NumericalFeatureMapper.getBuilder().
setFeatureIndex(featureIndex).setFeatureName(phrase).
setSource("matching_score").build();
featureMappers.addMapper(mapper);
}
}
}
/**
* focus set
*/
if (shouldExtractFeatures&&config.getBoolean("extraction.fromHardSet")){
//generate focus set
FocusSet focusSet = new FocusSet(numClasses);
for (int k=0;k<numClasses;k++){
double[] gradient = lkTreeBoost.getGradient(k);
Comparator<Pair<Integer,Double>> comparator = Comparator.comparing(Pair::getSecond);
List<Integer> hardExamples = IntStream.range(0,gradient.length)
.mapToObj(i -> new Pair<>(i,gradient[i]))
.filter(pair -> pair.getSecond()>0)
.sorted(comparator.reversed())
.limit(numDocsToSelect)
.map(Pair::getFirst)
.collect(Collectors.toList());
for(Integer doc: hardExamples){
focusSet.add(doc,k);
}
}
List<Integer> validationSet = focusSet.getAll();
for (int k=0;k<numClasses;k++){
double[] allGradients = lkTreeBoost.getGradient(k);
List<Double> gradientsForValidation = validationSet.stream()
.map(i -> allGradients[i]).collect(Collectors.toList());
List<String> goodTerms = null;
if(config.getString("extraction.Extractor").equalsIgnoreCase("splitExtractor")){
goodTerms = splitExtractor.getGoodTerms(focusSet,
validationSet,
blackList, k, gradientsForValidation);
} else if (config.getString("extraction.Extractor").equalsIgnoreCase("tfidfExtractor")){
goodTerms = tfidfExtractor.getGoodTerms(focusSet,blackList,k);
} else if (config.getString("extraction.Extractor").equalsIgnoreCase("tfidfSplitExtractor")){
goodTerms = tfidfSplitExtractor.getGoodTerms(focusSet,
validationSet,
blackList, k, gradientsForValidation);
} else {
throw new RuntimeException("ngram extractor is not specified correctly");
}
seedsForAllClasses.get(k).addAll(goodTerms);
List<String> focusSetIndexIds = focusSet.getDataClassK(k)
.parallelStream().map(trainIdTranslator::toExtId)
.collect(Collectors.toList());
System.out.println("hard set for class " +k+ "("+labelTranslator.toExtLabel(k)+ "):");
System.out.println(focusSetIndexIds.toString());
System.out.println("terms extracted from hard set for class " + k+" ("+labelTranslator.toExtLabel(k)+"):");
System.out.println(goodTerms);
//phrases
System.out.println("seeds for class " +k+ "("+labelTranslator.toExtLabel(k)+ "):");
System.out.println(seedsForAllClasses.get(k));
List<String> goodPhrases = phraseSplitExtractor.getGoodPhrases(focusSet,validationSet,blackList,k,
gradientsForValidation,seedsForAllClasses.get(k));
System.out.println("phrases extracted from hard set for class " + k+" ("+labelTranslator.toExtLabel(k)+"):");
System.out.println(goodPhrases);
blackList.addAll(goodPhrases);
for (String ngram:goodTerms){
int featureIndex = featureMappers.nextAvailable();
SearchResponse response = index.match(index.getBodyField(),
ngram,trainIdTranslator.getAllExtIds(), MatchQueryBuilder.Operator.AND);
for (SearchHit hit: response.getHits().getHits()){
String indexId = hit.getId();
int algorithmId = trainIdTranslator.toIntId(indexId);
float score = hit.getScore();
dataSet.setFeatureValue(algorithmId, featureIndex,score);
}
NumericalFeatureMapper mapper = NumericalFeatureMapper.getBuilder().
setFeatureIndex(featureIndex).setFeatureName(ngram).
setSource("matching_score").build();
featureMappers.addMapper(mapper);
blackList.add(ngram);
}
for (String phrase:goodPhrases){
int featureIndex = featureMappers.nextAvailable();
SearchResponse response = index.matchPhrase(index.getBodyField(),
phrase,trainIdTranslator.getAllExtIds(), 0);
for (SearchHit hit: response.getHits().getHits()){
String indexId = hit.getId();
int algorithmId = trainIdTranslator.toIntId(indexId);
float score = hit.getScore();
dataSet.setFeatureValue(algorithmId, featureIndex,score);
}
NumericalFeatureMapper mapper = NumericalFeatureMapper.getBuilder().
setFeatureIndex(featureIndex).setFeatureName(phrase).
setSource("matching_score").build();
featureMappers.addMapper(mapper);
}
}
}
int[] activeFeatures = IntStream.range(0, featureMappers.getTotalDim()).toArray();
lkTreeBoost.setActiveFeatures(activeFeatures);
lkTreeBoost.fitRegressors();
}
File serializedModel = new File(archive,modelName);
if (!overwriteModels && serializedModel.exists()){
throw new RuntimeException(serializedModel.getAbsolutePath()+"already exists");
}
lkTreeBoost.serialize(serializedModel);
System.out.println("model saved to "+serializedModel.getAbsolutePath());
System.out.println("accuracy on training set = "+ Accuracy.accuracy(lkTreeBoost,
dataSet));
System.out.println("time spent = "+stopWatch);
}
static String[] sampleTrain(Config config, SingleLabelIndex index){
int numDocsInIndex = index.getNumDocs();
String[] trainIds = null;
if (config.getString("split.fashion").equalsIgnoreCase("fixed")){
String splitField = config.getString("index.splitField");
trainIds = IntStream.range(0, numDocsInIndex).
filter(i -> index.getStringField("" + i, splitField).
equalsIgnoreCase("train")).
mapToObj(i -> "" + i).collect(Collectors.toList()).
toArray(new String[0]);
} else if (config.getString("split.fashion").equalsIgnoreCase("random")){
double trainPercentage = config.getDouble("split.random.trainPercentage");
int[] labels = new int[numDocsInIndex];
for (int i=0;i<labels.length;i++){
labels[i] = index.getLabel(""+i);
}
List<Integer> sample = Sampling.stratified(labels, trainPercentage);
trainIds = new String[sample.size()];
for (int i=0;i<trainIds.length;i++){
trainIds[i] = ""+sample.get(i);
}
} else {
throw new RuntimeException("illegal split fashion");
}
return trainIds;
}
static String[] sampleTest(int numDocsInIndex, String[] trainIndexIds){
Set<String> test = new HashSet<>(numDocsInIndex);
for (int i=0;i<numDocsInIndex;i++){
test.add(""+i);
}
List<String> _trainIndexIds = new ArrayList<>(trainIndexIds.length);
for (String id: trainIndexIds){
_trainIndexIds.add(id);
}
test.removeAll(_trainIndexIds);
return test.toArray(new String[0]);
}
static IdTranslator loadIdTranslator(String[] indexIds) throws Exception{
IdTranslator idTranslator = new IdTranslator();
for (int i=0;i<indexIds.length;i++){
idTranslator.addData(i,""+indexIds[i]);
}
return idTranslator;
}
static LabelTranslator loadLabelTranslator(Config config, SingleLabelIndex index) throws Exception{
int numClasses = config.getInt("numClasses");
int numDocs = index.getNumDocs();
Map<Integer, String> map = new HashMap<>(numClasses);
for (int i=0;i<numDocs;i++){
int intLabel = index.getLabel(""+i);
String extLabel = index.getExtLabel("" + i);
map.put(intLabel,extLabel);
}
return new LabelTranslator(map);
}
/**
*
* @param config
* @param index
* @param featureMappers to be updated
* @param ids pull features from train ids
* @throws Exception
*/
static void addInitialFeatures(Config config, SingleLabelIndex index,
FeatureMappers featureMappers,
String[] ids) throws Exception{
String featureFieldPrefix = config.getString("index.featureFieldPrefix");
Set<String> allFields = index.listAllFields();
List<String> featureFields = allFields.stream().
filter(field -> field.startsWith(featureFieldPrefix)).
collect(Collectors.toList());
System.out.println("all possible initial features:"+featureFields);
for (String field: featureFields){
String featureType = index.getFieldType(field);
if (featureType.equalsIgnoreCase("string")){
CategoricalFeatureMapperBuilder builder = new CategoricalFeatureMapperBuilder();
builder.setFeatureName(field);
builder.setStart(featureMappers.nextAvailable());
builder.setSource("field");
for (String id: ids){
String category = index.getStringField(id, field);
builder.addCategory(category);
}
boolean toAdd = true;
CategoricalFeatureMapper mapper = builder.build();
if (config.getBoolean("categFeature.filter")){
double threshold = config.getDouble("categFeature.percentThreshold");
int numCategories = mapper.getNumCategories();
if (numCategories> ids.length*threshold){
toAdd=false;
System.out.println("field "+field+" has too many categories "
+"("+numCategories+"), omitted.");
}
}
if(toAdd){
featureMappers.addMapper(mapper);
}
} else {
NumericalFeatureMapperBuilder builder = new NumericalFeatureMapperBuilder();
builder.setFeatureName(field);
builder.setFeatureIndex(featureMappers.nextAvailable());
builder.setSource("field");
NumericalFeatureMapper mapper = builder.build();
featureMappers.addMapper(mapper);
}
}
}
static void showDistribution(Config config, ClfDataSet dataSet, LabelTranslator labelTranslator){
int numClasses = config.getInt("numClasses");
int[] counts = new int[numClasses];
int[] labels = dataSet.getLabels();
for (int i=0;i<dataSet.getNumDataPoints();i++){
int label = labels[i];
counts[label] += 1;
}
System.out.println("label distribution:");
for (int i=0;i<numClasses;i++){
System.out.print(i+"("+labelTranslator.toExtLabel(i)+"):"+counts[i]+", ");
}
System.out.println("");
}
static void saveDataSet(Config config, ClfDataSet dataSet, String name) throws Exception{
String archive = config.getString("archive.folder");
File dataFile = new File(archive,name);
TRECFormat.save(dataSet, dataFile);
DataSetUtil.dumpDataSettings(dataSet,new File(dataFile,"data_settings.txt"));
DataSetUtil.dumpFeatureSettings(dataSet,new File(dataFile,"feature_settings.txt"));
System.out.println("data set saved to "+dataFile.getAbsolutePath());
}
static DFStats loadDFStats(Config config, SingleLabelIndex index, IdTranslator trainIdTranslator) throws IOException {
DFStats dfStats = new DFStats(config.getInt("numClasses"));
String[] trainIds = trainIdTranslator.getAllExtIds();
dfStats.update(index,trainIds);
dfStats.sort();
return dfStats;
}
static void dumpTrainFeatures(Config config, SingleLabelIndex index, IdTranslator idTranslator) throws Exception{
String archive = config.getString("archive.folder");
String trecFile = new File(archive,config.getString("archive.trainingSet")).getAbsolutePath();
String file = new File(trecFile,"dumped_fields.txt").getAbsolutePath();
dumpFeatures(config,index,idTranslator,file);
}
static void dumpTestFeatures(Config config, SingleLabelIndex index, IdTranslator idTranslator) throws Exception{
String archive = config.getString("archive.folder");
String trecFile = new File(archive,config.getString("archive.testSet")).getAbsolutePath();
String file = new File(trecFile,"dumped_fields.txt").getAbsolutePath();
dumpFeatures(config,index,idTranslator,file);
}
static void dumpFeatures(Config config, SingleLabelIndex index, IdTranslator idTranslator, String fileName) throws Exception{
String[] fields = config.getString("archive.dumpedFields").split(",");
int numDocs = idTranslator.numData();
try(BufferedWriter bw = new BufferedWriter(new FileWriter(fileName))
){
for (int intId=0;intId<numDocs;intId++){
bw.write("intId=");
bw.write(""+intId);
bw.write(",");
bw.write("extId=");
String extId = idTranslator.toExtId(intId);
bw.write(extId);
bw.write(",");
for (int i=0;i<fields.length;i++){
String field = fields[i];
bw.write(field+"=");
bw.write(index.getStringField(extId,field));
if (i!=fields.length-1){
bw.write(",");
}
}
bw.write("\n");
}
}
}
}
| add uncertain set
| src/main/java/edu/neu/ccs/pyramid/experiment/Exp3.java | add uncertain set | <ide><path>rc/main/java/edu/neu/ccs/pyramid/experiment/Exp3.java
<ide> package edu.neu.ccs.pyramid.experiment;
<ide>
<add>import edu.neu.ccs.pyramid.active_learning.BestVsSecond;
<ide> import edu.neu.ccs.pyramid.classification.boosting.lktb.LKTBConfig;
<ide> import edu.neu.ccs.pyramid.classification.boosting.lktb.LKTreeBoost;
<ide> import edu.neu.ccs.pyramid.configuration.Config;
<ide> import edu.neu.ccs.pyramid.eval.Accuracy;
<ide> import edu.neu.ccs.pyramid.feature.*;
<ide> import edu.neu.ccs.pyramid.feature_extraction.*;
<add>import edu.neu.ccs.pyramid.util.MathUtil;
<ide> import edu.neu.ccs.pyramid.util.Pair;
<ide> import edu.neu.ccs.pyramid.util.Sampling;
<ide> import org.apache.commons.lang3.time.StopWatch;
<ide> lkTreeBoost.calGradients();
<ide>
<ide> boolean condition1 = (featureMappers.getTotalDim()
<del> +numNgramsToExtract*numClasses*2
<del> +config.getInt("extraction.phraseSplitExtractor.topN")*numClasses*2
<add> +numNgramsToExtract*numClasses*3
<add> +config.getInt("extraction.phraseSplitExtractor.topN")*numClasses*3
<ide> <dataSet.getNumFeatures());
<ide> boolean condition2 = (Math.random()<extractionFrequency);
<ide> //should start with some feature
<ide> }
<ide>
<ide> /**
<del> * focus set
<add> * hard set
<ide> */
<ide> if (shouldExtractFeatures&&config.getBoolean("extraction.fromHardSet")){
<ide> //generate focus set
<ide> List<String> goodPhrases = phraseSplitExtractor.getGoodPhrases(focusSet,validationSet,blackList,k,
<ide> gradientsForValidation,seedsForAllClasses.get(k));
<ide> System.out.println("phrases extracted from hard set for class " + k+" ("+labelTranslator.toExtLabel(k)+"):");
<add> System.out.println(goodPhrases);
<add> blackList.addAll(goodPhrases);
<add>
<add> for (String ngram:goodTerms){
<add> int featureIndex = featureMappers.nextAvailable();
<add> SearchResponse response = index.match(index.getBodyField(),
<add> ngram,trainIdTranslator.getAllExtIds(), MatchQueryBuilder.Operator.AND);
<add> for (SearchHit hit: response.getHits().getHits()){
<add> String indexId = hit.getId();
<add> int algorithmId = trainIdTranslator.toIntId(indexId);
<add> float score = hit.getScore();
<add> dataSet.setFeatureValue(algorithmId, featureIndex,score);
<add> }
<add>
<add> NumericalFeatureMapper mapper = NumericalFeatureMapper.getBuilder().
<add> setFeatureIndex(featureIndex).setFeatureName(ngram).
<add> setSource("matching_score").build();
<add> featureMappers.addMapper(mapper);
<add> blackList.add(ngram);
<add> }
<add>
<add> for (String phrase:goodPhrases){
<add> int featureIndex = featureMappers.nextAvailable();
<add> SearchResponse response = index.matchPhrase(index.getBodyField(),
<add> phrase,trainIdTranslator.getAllExtIds(), 0);
<add> for (SearchHit hit: response.getHits().getHits()){
<add> String indexId = hit.getId();
<add> int algorithmId = trainIdTranslator.toIntId(indexId);
<add> float score = hit.getScore();
<add> dataSet.setFeatureValue(algorithmId, featureIndex,score);
<add> }
<add>
<add> NumericalFeatureMapper mapper = NumericalFeatureMapper.getBuilder().
<add> setFeatureIndex(featureIndex).setFeatureName(phrase).
<add> setSource("matching_score").build();
<add> featureMappers.addMapper(mapper);
<add> }
<add> }
<add> }
<add>
<add> /**
<add> * uncertain set
<add> */
<add> if (shouldExtractFeatures&&config.getBoolean("extraction.fromUncertainSet")){
<add> //generate focus set
<add> FocusSet focusSet = new FocusSet(numClasses);
<add> Comparator<Pair<Integer,BestVsSecond>> comparator = Comparator.comparing(pair -> pair.getSecond().getDifference());
<add> List<Integer> examples = IntStream.range(0,dataSet.getNumDataPoints())
<add> .mapToObj(i -> new Pair<>(i,new BestVsSecond(lkTreeBoost.getClassProbs(i))))
<add> .sorted(comparator).map(Pair::getFirst)
<add> .limit(numClasses*numDocsToSelect).collect(Collectors.toList());
<add> for (Integer dataPoint: examples){
<add> int label = dataSet.getLabels()[dataPoint];
<add> focusSet.add(dataPoint,label);
<add> }
<add>
<add> List<Integer> validationSet = focusSet.getAll();
<add>
<add> for (int k=0;k<numClasses;k++){
<add>
<add> double[] allGradients = lkTreeBoost.getGradient(k);
<add> List<Double> gradientsForValidation = validationSet.stream()
<add> .map(i -> allGradients[i]).collect(Collectors.toList());
<add>
<add> List<String> goodTerms = null;
<add> if(config.getString("extraction.Extractor").equalsIgnoreCase("splitExtractor")){
<add> goodTerms = splitExtractor.getGoodTerms(focusSet,
<add> validationSet,
<add> blackList, k, gradientsForValidation);
<add> } else if (config.getString("extraction.Extractor").equalsIgnoreCase("tfidfExtractor")){
<add> goodTerms = tfidfExtractor.getGoodTerms(focusSet,blackList,k);
<add> } else if (config.getString("extraction.Extractor").equalsIgnoreCase("tfidfSplitExtractor")){
<add> goodTerms = tfidfSplitExtractor.getGoodTerms(focusSet,
<add> validationSet,
<add> blackList, k, gradientsForValidation);
<add> } else {
<add> throw new RuntimeException("ngram extractor is not specified correctly");
<add> }
<add> seedsForAllClasses.get(k).addAll(goodTerms);
<add>
<add> List<String> focusSetIndexIds = focusSet.getDataClassK(k)
<add> .parallelStream().map(trainIdTranslator::toExtId)
<add> .collect(Collectors.toList());
<add> System.out.println("uncertain set for class " +k+ "("+labelTranslator.toExtLabel(k)+ "):");
<add> System.out.println(focusSetIndexIds.toString());
<add> System.out.println("terms extracted from uncertain set for class " + k+" ("+labelTranslator.toExtLabel(k)+"):");
<add> System.out.println(goodTerms);
<add>
<add> //phrases
<add> System.out.println("seeds for class " +k+ "("+labelTranslator.toExtLabel(k)+ "):");
<add> System.out.println(seedsForAllClasses.get(k));
<add> List<String> goodPhrases = phraseSplitExtractor.getGoodPhrases(focusSet,validationSet,blackList,k,
<add> gradientsForValidation,seedsForAllClasses.get(k));
<add> System.out.println("phrases extracted from uncertain set for class " + k+" ("+labelTranslator.toExtLabel(k)+"):");
<ide> System.out.println(goodPhrases);
<ide> blackList.addAll(goodPhrases);
<ide> |
|
Java | apache-2.0 | 50970572c3af5216aecd86b4fd88908178005166 | 0 | nasa/MCT-Plugins | /*******************************************************************************
* Mission Control Technologies, Copyright (c) 2009-2012, United States Government
* as represented by the Administrator of the National Aeronautics and Space
* Administration. All rights reserved.
*
* The MCT platform is 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.
*
* MCT includes source code licensed under additional open source licenses. See
* the MCT Open Source Licenses file included with this distribution or the About
* MCT Licenses dialog available at runtime from the MCT Help menu for additional
* information.
*******************************************************************************/
package gov.nasa.arc.mct.scenario.component;
import gov.nasa.arc.mct.components.AbstractComponent;
import gov.nasa.arc.mct.platform.spi.PlatformAccess;
import java.awt.Component;
import java.awt.Dialog;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
/**
* Handles movement from one repository to another, popping up a blocking
* dialog which serves two purposes:
*
* - Blocks user interaction until the move is complete
* - Notifies the user that a move has occurred (this is atypical)
*
*/
public class RepositoryMoveHandler {
private static final ResourceBundle BUNDLE = ResourceBundle.getBundle("Bundle");
private RepositoryComponent repositoryComponent;
private Collection<AbstractComponent> addedComponents;
public RepositoryMoveHandler(RepositoryComponent repositoryComponent,
Collection<AbstractComponent> addedComponents) {
super();
this.repositoryComponent = repositoryComponent;
this.addedComponents = addedComponents;
}
/**
* Initiate the movement of objects out of previous repositories.
*/
public void handle() {
final SwingWorker<Map<String, Collection<String>>, ?> w = new RepositoryMoveWorker();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new RepositoryMoveDialog(w).setVisible(true);
}
});
w.execute();
}
// Dialog to display while moving. Handles display of both progress bar
// and user notification when operation is complete.
private class RepositoryMoveDialog extends JDialog {
private static final long serialVersionUID = 7688596759924866708L;
public RepositoryMoveDialog(final SwingWorker<Map<String, Collection<String>>,?> worker) {
super(null, Dialog.ModalityType.APPLICATION_MODAL);
final JPanel panel = new JPanel();
final JLabel label = new JLabel(String.format(BUNDLE.getString("repo_move_progress_message"), repositoryComponent.getDisplayName()));
final JLabel details = new JLabel("");
final JProgressBar progress = new JProgressBar(0, 100);
final JButton button = new JButton("OK");
button.setEnabled(false);
progress.setVisible(true);
details.setVisible(false);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
RepositoryMoveDialog.this.dispose();
}
});
worker.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent event) {
progress.setValue(worker.getProgress());
label.setVisible(!worker.isDone());
progress.setVisible(!worker.isDone());
details.setVisible(worker.isDone());
button.setEnabled(worker.isDone());
setDefaultCloseOperation(worker.isDone() ? DISPOSE_ON_CLOSE : DO_NOTHING_ON_CLOSE);
if (worker.isDone()) {
try {
worker.get();
dispose();
} catch (InterruptedException e) { // Fall back to default summary
details.setText(summarize(null));
} catch (ExecutionException e) { // Fall back to default summary
details.setText(summarize(null));
}
}
pack();
setLocationRelativeTo(null); // Re-center
}
});
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
panel.add(label);
panel.add(progress);
panel.add(details);
panel.add(Box.createVerticalStrut(17));
panel.add(button);
// Center all components
for (Component c : panel.getComponents()) {
if (c instanceof JComponent) {
((JComponent) c).setAlignmentX(JComponent.CENTER_ALIGNMENT);
}
}
// Add some padding with a border
panel.setBorder(BorderFactory.createEmptyBorder(12, 12, 12, 12));
add(panel);
pack();
// Disable resize, premature close
setResizable(false);
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
// Add title from bundle, and center dialog on screen
setTitle(BUNDLE.getString("repo_move_title"));
setLocationRelativeTo(null);
}
// Prepares a summary message describing the move that has taken place.
private String summarize(Map<String, Collection<String>> result) {
String summary = "";
if (result != null && result.size() > 0) {
for (Entry<String, Collection<String>> moved : result.entrySet()) {
String children = "";
for (String childName : moved.getValue()) {
children += String.format(
BUNDLE.getString("repo_move_summary_object"),
childName);
}
summary += String.format(
BUNDLE.getString("repo_move_summary_repo"),
moved.getKey(), // Name of previous repository parent
repositoryComponent.getDisplayName(),
children);
}
} else {
// This is fallback behavior in case of exception or empty result set
summary = String.format(
BUNDLE.getString("repo_move_summary_default"),
repositoryComponent.getDisplayName());
}
return String.format(
BUNDLE.getString("repo_move_summary"),
summary,
repositoryComponent.getDisplayName()
);
}
}
// Handles the actual process of removing components from old repositories.
// Implemented as a SwingWorker to make use of standard progress reporting approach.
private class RepositoryMoveWorker extends SwingWorker<Map<String, Collection<String>>, Void> {
@Override
protected Map<String, Collection<String>> doInBackground() throws Exception {
// Store lists of components to remove from parents,
// where parents are indicated by id (key to map)
Map<String, Set<AbstractComponent>> toRemove =
new HashMap<String, Set<AbstractComponent>>();
// getReferencingComponents may return different instances each time,
// so store the latest returned instance in relation to its id
Map<String, AbstractComponent> parentRepos =
new HashMap<String, AbstractComponent>();
// For progress reporting
int childIndex = 0;
int childCount = addedComponents.size();
// Build a list of things to remove
for (AbstractComponent child : addedComponents) {
Collection<AbstractComponent> parents = child.getReferencingComponents();
int parentIndex = 0;
int parentCount = parents.size();
for (AbstractComponent parent : parents) {
RepositoryCapability parentRepo = parent.getCapability(RepositoryCapability.class);
// Is another parent the same kind of repository?
if (parentRepo != null &&
parentRepo.getCapabilityClass().isAssignableFrom(repositoryComponent.getCapabilityClass())) {
String parentId = parent.getComponentId();
// Make sure we are not just looking at ourself
if (!(repositoryComponent.getComponentId().equals(parentId))) {
parentRepos.put(parentId, parent);
if (!toRemove.containsKey(parentId)) {
toRemove.put(parentId, new HashSet<AbstractComponent>());
}
toRemove.get(parentId).add(child);
}
}
parentIndex++;
setProgress((100 * childIndex + (parentIndex*childIndex/parentCount)) / childCount);
}
childIndex++;
setProgress(100 * childIndex / childCount);
}
// Now, remove them
for (String id : parentRepos.keySet()) {
parentRepos.get(id).removeDelegateComponents(toRemove.get(id));
}
// Finally, persist
PlatformAccess.getPlatform().getPersistenceProvider().persist(parentRepos.values());
// Then, prepare return values (display names)
Map<String, Collection<String>> result = new HashMap<String, Collection<String>>();
for (String id : parentRepos.keySet()) {
Collection<String> removed = new ArrayList<String>();
String name = parentRepos.get(id).getDisplayName();
for (AbstractComponent child : toRemove.get(id)) {
removed.add(child.getDisplayName());
}
result.put(name, removed);
}
return result;
}
}
}
| scenario/src/main/java/gov/nasa/arc/mct/scenario/component/RepositoryMoveHandler.java | /*******************************************************************************
* Mission Control Technologies, Copyright (c) 2009-2012, United States Government
* as represented by the Administrator of the National Aeronautics and Space
* Administration. All rights reserved.
*
* The MCT platform is 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.
*
* MCT includes source code licensed under additional open source licenses. See
* the MCT Open Source Licenses file included with this distribution or the About
* MCT Licenses dialog available at runtime from the MCT Help menu for additional
* information.
*******************************************************************************/
package gov.nasa.arc.mct.scenario.component;
import gov.nasa.arc.mct.components.AbstractComponent;
import gov.nasa.arc.mct.platform.spi.PlatformAccess;
import java.awt.Component;
import java.awt.Dialog;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
/**
* Handles movement from one repository to another, popping up a blocking
* dialog which serves two purposes:
*
* - Blocks user interaction until the move is complete
* - Notifies the user that a move has occurred (this is atypical)
*
*/
public class RepositoryMoveHandler {
private static final ResourceBundle BUNDLE = ResourceBundle.getBundle("Bundle");
private RepositoryComponent repositoryComponent;
private Collection<AbstractComponent> addedComponents;
public RepositoryMoveHandler(RepositoryComponent repositoryComponent,
Collection<AbstractComponent> addedComponents) {
super();
this.repositoryComponent = repositoryComponent;
this.addedComponents = addedComponents;
}
/**
* Initiate the movement of objects out of previous repositories.
*/
public void handle() {
final SwingWorker<Map<String, Collection<String>>, ?> w = new RepositoryMoveWorker();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new RepositoryMoveDialog(w).setVisible(true);
}
});
w.execute();
}
// Dialog to display while moving. Handles display of both progress bar
// and user notification when operation is complete.
private class RepositoryMoveDialog extends JDialog {
private static final long serialVersionUID = 7688596759924866708L;
public RepositoryMoveDialog(final SwingWorker<Map<String, Collection<String>>,?> worker) {
super(null, Dialog.ModalityType.APPLICATION_MODAL);
final JPanel panel = new JPanel();
final JLabel label = new JLabel(String.format(BUNDLE.getString("repo_move_progress_message"), repositoryComponent.getDisplayName()));
final JLabel details = new JLabel("");
final JProgressBar progress = new JProgressBar(0, 100);
final JButton button = new JButton("OK");
button.setEnabled(false);
progress.setVisible(true);
details.setVisible(false);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
RepositoryMoveDialog.this.dispose();
}
});
worker.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent event) {
progress.setValue(worker.getProgress());
label.setVisible(!worker.isDone());
progress.setVisible(!worker.isDone());
details.setVisible(worker.isDone());
button.setEnabled(worker.isDone());
setDefaultCloseOperation(worker.isDone() ? DISPOSE_ON_CLOSE : DO_NOTHING_ON_CLOSE);
if (worker.isDone()) {
try {
Map<String, Collection<String>> result = worker.get();
if (result.isEmpty()) {
dispose();
} else {
details.setText(summarize(result));
}
} catch (InterruptedException e) { // Fall back to default summary
details.setText(summarize(null));
} catch (ExecutionException e) { // Fall back to default summary
details.setText(summarize(null));
}
}
pack();
setLocationRelativeTo(null); // Re-center
}
});
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
panel.add(label);
panel.add(progress);
panel.add(details);
panel.add(Box.createVerticalStrut(17));
panel.add(button);
// Center all components
for (Component c : panel.getComponents()) {
if (c instanceof JComponent) {
((JComponent) c).setAlignmentX(JComponent.CENTER_ALIGNMENT);
}
}
// Add some padding with a border
panel.setBorder(BorderFactory.createEmptyBorder(12, 12, 12, 12));
add(panel);
pack();
// Disable resize, premature close
setResizable(false);
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
// Add title from bundle, and center dialog on screen
setTitle(BUNDLE.getString("repo_move_title"));
setLocationRelativeTo(null);
}
// Prepares a summary message describing the move that has taken place.
private String summarize(Map<String, Collection<String>> result) {
String summary = "";
if (result != null && result.size() > 0) {
for (Entry<String, Collection<String>> moved : result.entrySet()) {
String children = "";
for (String childName : moved.getValue()) {
children += String.format(
BUNDLE.getString("repo_move_summary_object"),
childName);
}
summary += String.format(
BUNDLE.getString("repo_move_summary_repo"),
moved.getKey(), // Name of previous repository parent
repositoryComponent.getDisplayName(),
children);
}
} else {
// This is fallback behavior in case of exception or empty result set
summary = String.format(
BUNDLE.getString("repo_move_summary_default"),
repositoryComponent.getDisplayName());
}
return String.format(
BUNDLE.getString("repo_move_summary"),
summary,
repositoryComponent.getDisplayName()
);
}
}
// Handles the actual process of removing components from old repositories.
// Implemented as a SwingWorker to make use of standard progress reporting approach.
private class RepositoryMoveWorker extends SwingWorker<Map<String, Collection<String>>, Void> {
@Override
protected Map<String, Collection<String>> doInBackground() throws Exception {
// Store lists of components to remove from parents,
// where parents are indicated by id (key to map)
Map<String, Set<AbstractComponent>> toRemove =
new HashMap<String, Set<AbstractComponent>>();
// getReferencingComponents may return different instances each time,
// so store the latest returned instance in relation to its id
Map<String, AbstractComponent> parentRepos =
new HashMap<String, AbstractComponent>();
// For progress reporting
int childIndex = 0;
int childCount = addedComponents.size();
// Build a list of things to remove
for (AbstractComponent child : addedComponents) {
Collection<AbstractComponent> parents = child.getReferencingComponents();
int parentIndex = 0;
int parentCount = parents.size();
for (AbstractComponent parent : parents) {
RepositoryCapability parentRepo = parent.getCapability(RepositoryCapability.class);
// Is another parent the same kind of repository?
if (parentRepo != null &&
parentRepo.getCapabilityClass().isAssignableFrom(repositoryComponent.getCapabilityClass())) {
String parentId = parent.getComponentId();
// Make sure we are not just looking at ourself
if (!(repositoryComponent.getComponentId().equals(parentId))) {
parentRepos.put(parentId, parent);
if (!toRemove.containsKey(parentId)) {
toRemove.put(parentId, new HashSet<AbstractComponent>());
}
toRemove.get(parentId).add(child);
}
}
parentIndex++;
setProgress((100 * childIndex + (parentIndex*childIndex/parentCount)) / childCount);
}
childIndex++;
setProgress(100 * childIndex / childCount);
}
// Now, remove them
for (String id : parentRepos.keySet()) {
parentRepos.get(id).removeDelegateComponents(toRemove.get(id));
}
// Finally, persist
PlatformAccess.getPlatform().getPersistenceProvider().persist(parentRepos.values());
// Then, prepare return values (display names)
Map<String, Collection<String>> result = new HashMap<String, Collection<String>>();
for (String id : parentRepos.keySet()) {
Collection<String> removed = new ArrayList<String>();
String name = parentRepos.get(id).getDisplayName();
for (AbstractComponent child : toRemove.get(id)) {
removed.add(child.getDisplayName());
}
result.put(name, removed);
}
return result;
}
}
}
| [Scenario] Remove unneeded dialog
Remove unneeded dialog which appears when
moving between repositories; this is now
clarified by the Move option that appears
when dragging between repositories.
| scenario/src/main/java/gov/nasa/arc/mct/scenario/component/RepositoryMoveHandler.java | [Scenario] Remove unneeded dialog | <ide><path>cenario/src/main/java/gov/nasa/arc/mct/scenario/component/RepositoryMoveHandler.java
<ide> setDefaultCloseOperation(worker.isDone() ? DISPOSE_ON_CLOSE : DO_NOTHING_ON_CLOSE);
<ide> if (worker.isDone()) {
<ide> try {
<del> Map<String, Collection<String>> result = worker.get();
<del> if (result.isEmpty()) {
<del> dispose();
<del> } else {
<del> details.setText(summarize(result));
<del> }
<add> worker.get();
<add> dispose();
<ide> } catch (InterruptedException e) { // Fall back to default summary
<ide> details.setText(summarize(null));
<ide> } catch (ExecutionException e) { // Fall back to default summary |
|
JavaScript | isc | 4fcda72566f09c1bde94d37100dd891437a8bc5e | 0 | derhuerst/vbb-station-photos | 'use strict'
module.exports = {
'900000100003': { // S+U Alexanderplatz
U2: {
label: ['flickr', 'ingolfbln', 6977132297],
platform: ['flickr', 'ingolfbln', 6831050998],
entrance: null
},
U5: {
label: ['flickr', 'ingolfbln', 6904300029],
platform: ['flickr', 'ingolfbln', 6904572417],
entrance: null
},
U8: {
label: ['commons', 'Berlin_-_Bahnhof_Alexanderplatz3.jpg'],
platform: ['flickr', 'ingolfbln', 7624771658],
entrance: null
}
},
'900000011102': { // U Afrikanische Straße
U6: {
label: ['flickr', 'ingolfbln', 24350635584],
platform: ['flickr', 'ingolfbln', 15241241614],
entrance: null
}
},
'900000023302': { // U Adenauerplatz
U7: {
label: ['flickr', 'ingolfbln', 6390440937],
platform: ['flickr', 'ingolfbln', 6390505317],
entrance: null
}
},
'900000070301': { // U Alt-Mariendorf
U6: {
// todo: better entrance photo
label: ['flickr', 'ingolfbln', 8442745166],
platform: ['flickr', 'ingolfbln', 8442753190],
entrance: ['flickr', 'ingolfbln', 8442828284]
}
},
'900000029301': { // U Altstadt Spandau
U7: {
label: ['flickr', 'ingolfbln', 8480776682],
platform: ['flickr', 'ingolfbln', 8479688177],
entrance: ['flickr', 'ingolfbln', 8479696353]
}
},
'900000089301': { // U Alt-Tegel
U9: {
label: ['flickr', 'ingolfbln', 7174331773],
platform: ['flickr', 'ingolfbln', 7359570360],
entrance: null
}
},
'900000009101': { // U Amrumer Str.
U9: {
label: ['flickr', 'ingolfbln', 6413966751],
platform: ['flickr', 'ingolfbln', 6413947281],
entrance: null
}
},
'900000055102': { // U Bayerischer Platz
U4: {
label: ['flickr', 'ingolfbln', 6444018965],
platform: ['flickr', 'ingolfbln', 6444065621],
entrance: null
},
U7: {
label: ['flickr', 'ingolfbln', 6443862789],
platform: ['flickr', 'ingolfbln', 6443871455],
entrance: null
}
},
'900000044201': { // U Berliner Str.
U7: {
label: ['flickr', '142745322@N06', 27760600346],
platform: ['commons', 'U-Bahn_Berlin_Berliner_Straße.jpg'],
entrance: null
},
U9: {
label: ['flickr', '142745322@N06', 27760595616],
platform: ['commons', 'Berlinerstr-u9-ubahn.jpg'],
entrance: null
}
},
'900000007110': { // U Bernauer Str.
U8: {
label: ['flickr', 'ingolfbln', 6335397247],
platform: ['flickr', 'ingolfbln', 6335405259],
entrance: null
}
},
'900000171005': {
U5: {
label: ['commons', 'Berlin U-Bahn station Biesdorf-Süd 01.jpg'],
platform: null},
entrance: null
},
'900000002201': { // U Birkenstr.
U9: {
label: ['flickr', 'ingolfbln', 6413815835],
platform: ['flickr', 'ingolfbln', 6413561591],
entrance: null
}
},
'900000024201': { // U Bismarckstr.
U2: {
label: ['flickr', 'ingolfbln', 6420827133],
platform: ['flickr', 'ingolfbln', 6420684483],
entrance: null
},
U7: {
label: ['flickr', 'ingolfbln', 6420923733],
platform: ['flickr', 'ingolfbln', 6421064143],
entrance: null
}
},
'900000080201': { // U Blaschkoallee
U7: {
label: ['flickr', 'ingolfbln', 7986890237],
platform: ['flickr', 'ingolfbln', 7986906582],
entrance: ['flickr', 'ingolfbln', 7986882684]
}
},
'900000041102': { // U Blissestr.
U7: {
label: ['flickr', 'ingolfbln', 6443698515],
platform: ['flickr', 'ingolfbln', 6443688697],
entrance: null
}
},
'900000079202': { // U Boddinstr.
U8: {
label: ['flickr', 'ingolfbln', 15018334836],
platform: ['flickr', 'ingolfbln', 15041298645],
entrance: null
}
},
'900000088202': { // U Borsigwerke
U6: {
label: ['flickr', 'ingolfbln', 7174241521],
platform: ['flickr', 'ingolfbln', 7174238429],
entrance: null
}
},
'900000100025': { // S+U Brandenburger Tor
U55: {
label: ['flickr', 'ingolfbln', 6247517033],
platform: ['flickr', 'ingolfbln', 8013530153],
entrance: null
}
},
'900000080402': { // U Britz-Süd
U7: {
label: ['flickr', 'ingolfbln', 15758843510],
platform: ['flickr', 'ingolfbln', 15758710458],
entrance: ['flickr', 'ingolfbln', 15758838800]
}
},
'900000056104': { // U Bülowstr.
U2: {
label: ['flickr', 'ingolfbln', 8991197746],
platform: ['flickr', 'ingolfbln', 9510232053],
entrance: ['flickr', 'ingolfbln', 9510210481]
}
},
'900000003254': { // U Bundestag
U55: {
label: ['flickr', 'ingolfbln', 22004585159],
platform: ['flickr', 'ingolfbln', 22003394950],
entrance: null
}
},
'900000044202': { // S+U Bundesplatz
U9: {
label: ['flickr', '142745322@N06', 27183844933],
platform: ['commons', 'Bundesplatz_west-ubahn.jpg'],
entrance: null
}
},
'900000175006': {
U5: {
label: ['commons', 'Berlin U-Bahn station Cottbusser Platz.jpg'],
platform: ['commons', 'U-Bahnhof_Cottbusser_Platz.jpg'],
entrance: null
}
},
'900000022201': { // U Deutsche Oper
U2: {
label: ['flickr', 'ingolfbln', 6420520007],
platform: ['flickr', 'ingolfbln', 6420536747],
entrance: null
}
},
'900000110006': { // U Eberswalder Str.
U2: {
label: ['flickr', 'ingolfbln', 9550979798],
platform: ['flickr', 'ingolfbln', 6261075205],
entrance: null
}
},
'900000054103': { // U Eisenacher Str.
U7: {
label: ['flickr', 'ingolfbln', 6385281907],
platform: ['flickr', 'ingolfbln', 6385333159],
entrance: null
}
},
'900000171006': { // U Elsterwerdaer Platz
U5: {
label: ['commons', 'Berlin U-Bahn station Elstawerdaer Platz.jpg'],
platform: ['commons', '2005-07-18_ubf_elsterwerdaer_platz_bahnsteig.jpg'],
entrance: null
}
},
'900000023101': { // U Ernst-Reuter-Platz
U2: {
label: ['flickr', 'ingolfbln', 7811608786],
platform: ['flickr', 'ingolfbln', 7811597724],
entrance: ['flickr', 'ingolfbln', 7811577562]
}
},
'900000041101': { // U Fehrbelliner Platz
U3: {
label: ['flickr', 'ingolfbln', 6384603637],
platform: ['flickr', 'ingolfbln', 6384672149],
entrance: null
},
U7: {
label: ['flickr', 'ingolfbln', 6384444067],
platform: ['flickr', 'ingolfbln', 6384476157],
entrance: null
}
},
'900000120001': { // S+U Frankfurter Allee
U5: {
label: ['flickr', 'ingolfbln', 13607255353],
platform: ['flickr', 'ingolfbln', 13607600174],
entrance: ['flickr', 'ingolfbln', 13607246325]
}
},
'900000120008': { // U Frankfurter Tor
U5: {
// todo: better entrance photo
label: ['flickr', 'ingolfbln', 13607728993],
platform: ['flickr', 'ingolfbln', 13607733313],
entrance: ['flickr', 'ingolfbln', 13608053194]
}
},
'900000100027': { // U Französische Str.
U6: {
label: ['flickr', 'ingolfbln', 7046228347],
platform: ['flickr', 'ingolfbln', 7046199547],
entrance: null
}
},
'900000161512': { // U Friedrichsfelde
U5: {
// todo: better entrance photo
label: ['flickr', 'ingolfbln', 8444925853],
platform: ['flickr', 'ingolfbln', 8444973707],
entrance: ['flickr', 'ingolfbln', 8444950453]
}
},
'900000100001': { // S+U Friedrichstr.
U6: {
label: ['flickr', 'ingolfbln', 6885603222],
platform: ['flickr', 'ingolfbln', 6885597904],
entrance: null
}
},
'900000061102': { // U Friedrich-Wilhelm-Platz
U9: {
label: ['flickr', 'ingolfbln', 8445906948],
platform: ['flickr', 'ingolfbln', 8445830122],
entrance: ['flickr', 'ingolfbln', 8444778417]
}
},
'900000007102': { // S+U Gesundbrunnen
U8: {
label: ['flickr', 'ingolfbln', 6521984893],
platform: ['flickr', 'ingolfbln', 6521972153],
entrance: null
}
},
'900000017103': { // U Gleisdreieck
U1: {
label: ['flickr', 'ingolfbln', 7931788740],
platform: ['flickr', 'ingolfbln', 7931841660],
entrance: null
},
U2: {
label: ['flickr', 'ingolfbln', 7184779634],
platform: ['flickr', 'ingolfbln', 7184839708],
entrance: null
}
},
'900000016101': { // U Gneisenaustr.
U7: {
label: ['flickr', 'ingolfbln', 6335901482],
platform: ['flickr', 'ingolfbln', 8292125259],
entrance: null
}
},
'900000014101': { // U Görlitzer Bahnhof
U1: {
label: ['flickr', 'ingolfbln', 6396112665],
platform: ['flickr', 'ingolfbln', 6800825848],
entrance: null
}
},
'900000080202': { // U Grenzallee
U7: {
label: ['flickr', 'ingolfbln', 8389921395],
platform: ['flickr', 'ingolfbln', 8389896257],
entrance: ['flickr', 'ingolfbln', 8389912401]
}
},
'900000043201': { // U Güntzelstr.
U9: {
label: ['flickr', '142745322@N06', 27183838403],
platform: ['flickr', 'ingolfbln', 7811698154],
entrance: null
}
},
'900000018102': { // U Halemweg
U7: {
// todo: better entrance photo
label: ['flickr', 'ingolfbln', 8447783145],
platform: ['flickr', 'ingolfbln', 8448906202],
entrance: ['flickr', 'ingolfbln', 8448883602]
}
},
'900000012103': { // U Hallesches Tor
U1: {
label: ['flickr', 'ingolfbln', 8194057063],
platform: ['flickr', 'ingolfbln', 8194069607],
entrance: ['flickr', 'ingolfbln', 8195191120]
},
U6: {
label: ['flickr', 'ingolfbln', 8194012643],
platform: ['flickr', 'ingolfbln', 8194021459],
entrance: ['flickr', 'ingolfbln', 8194036617]
}
},
'900000003101': { // U Hansaplatz
U9: {
label: ['flickr', 'ingolfbln', 6413038423],
platform: ['flickr', 'ingolfbln', 6413402697],
entrance: null
}
},
'900000034102': { // U Haselhorst
U7: {
// todo: better entrance photo
label: ['flickr', 'ingolfbln', 8480566324],
platform: ['flickr', 'ingolfbln', 8480519654],
entrance: ['flickr', 'ingolfbln', 8480535288]
}
},
'900000003201': { // S+U Hauptbahnhof
// todo: better platform photo
U55: {
label: ['flickr', '142745322@N06', 27516604790],
platform: ['flickr', 'ingolfbln', '8013595510'],
entrance: null
}
},
'900000100012': { // U Hausvogteiplatz
U2: {
label: ['flickr', 'ingolfbln', 8428213432],
platform: ['flickr', 'ingolfbln', 8427115893],
entrance: ['flickr', 'ingolfbln', 8428188718]
}
},
'900000045102': { // S+U Heidelberger Platz
U3: {
label: ['flickr', 'ingolfbln', 8294597799],
platform: ['flickr', 'ingolfbln', 8294606457],
entrance: null
}
},
'900000100008': { // U Heinrich-Heine-Str.
U8: {
label: ['flickr', 'ingolfbln', 7592578554],
platform: ['flickr', 'ingolfbln', 7592604840],
entrance: null
}
},
'900000078101': { // U Hermannplatz
U8: {
label: ['flickr', 'ingolfbln', 6335825554],
platform: ['flickr', 'ingolfbln', 8293152370],
entrance: null
},
U7: {
label: ['flickr', 'ingolfbln', 8480862534],
platform: ['flickr', 'ingolfbln', 8479757095],
entrance: null
}
},
'900000079221': { // S+U Hermannstr.
U8: {
label: ['flickr', 'ingolfbln', 6530852191],
platform: ['flickr', 'ingolfbln', 6530841673],
entrance: null
}
},
'900000175007': {
U5: {
label: ['commons', 'Berlin U-Bahn station Hellersdorf.jpg'],
platform: ['commons', 'Hellersdorf-ubahn.jpg'],
entrance: null
}
},
'900000043101': { // U Hohenzollernplatz
U3: {
label: ['flickr', 'ingolfbln', 8293135494],
platform: ['flickr', 'ingolfbln', 8292084211],
entrance: ['flickr', 'ingolfbln', 8292048983]
}
},
'900000175010': {
U5: {
label: ['commons', 'Berlin U-Bahn station Hönow.jpg'],
platform: ['commons', 'UBahnhf_Hoenow.JPG'],
entrance: null
}
},
'900000018101': { // U Jakob-Kaiser-Platz
U7: {
label: ['flickr', 'ingolfbln', 13547214604],
platform: ['flickr', 'ingolfbln', 13547008043],
entrance: ['flickr', 'ingolfbln', 13546801743]
}
},
'900000100004': { // S+U Jannowitzbrücke
U8: {
label: ['flickr', 'ingolfbln', 6323544365],
platform: ['flickr', 'ingolfbln', 6323560829],
entrance: null
}
},
'900000020201': { // S+U Jungfernheide
U7: {
label: ['flickr', 'ingolfbln', 6255097490],
platform: ['flickr', 'ingolfbln', 6255106242],
entrance: null
}
},
'900000068302': { // U Kaiserin-Augusta-Str.
// todo: still under construction?
U6: {
label: null,
platform: ['flickr', 'ingolfbln', 15817428556],
entrance: ['flickr', 'ingolfbln', 15655902810]
}
},
'900000096458': { // S+U Karl-Bonhoeffer-Nervenklinik
U8: {
label: ['flickr', 'ingolfbln', 7807059838],
platform: ['flickr', 'ingolfbln', 7807052574],
entrance: null
}
},
'900000078103': { // U Karl-Marx-Str.
U7: {
// todo: better entrance photo
label: ['flickr', 'ingolfbln', 8428333804],
platform: ['flickr', 'ingolfbln', 8427234401],
entrance: ['flickr', 'ingolfbln', 8428301850]
}
},
'900000175004': {
U5: {
label: ['commons', 'Berlin U-Bahn station Kaulsdorf Nord.jpg'],
platform: ['commons', 'Ubahnhf-Kaulsdorf-nord.JPG'],
entrance: null
}
},
'900000054102': { // U Kleistpark
U7: {
// todo: better entrance photo
label: ['flickr', 'ingolfbln', 8011466188],
platform: ['flickr', 'ingolfbln', 8011478612],
entrance: ['flickr', 'ingolfbln', 8011430580]
}
},
'900000100015': { // U Klosterstr.
U2: {
label: ['flickr', 'ingolfbln', 6336269032],
platform: ['flickr', 'ingolfbln', 6336236448],
entrance: null
}
},
'900000012102': { // U Kochstr./Checkpoint Charlie
U6: {
label: ['flickr', '142745322@N06', 27516587910],
platform: ['commons', 'Kochstr-ubahn.jpg'],
entrance: null
}
},
'900000041201': { // U Konstanzer Str.
U7: {
label: ['flickr', 'ingolfbln', 9096834614],
platform: ['flickr', 'ingolfbln', 9094593099],
entrance: ['flickr', 'ingolfbln', 9096772112]
}
},
'900000013102': { // U Kottbusser Tor
// todo: better entrance photos
U1: {
label: ['flickr', 'ingolfbln', 7932564208],
platform: ['flickr', 'ingolfbln', 7932567552],
entrance: ['flickr', 'ingolfbln', 7932443538]
},
U8: {
label: ['flickr', 'ingolfbln', 7932310940],
platform: ['flickr', 'ingolfbln', 7932259378],
entrance: ['flickr', 'ingolfbln', 7932443538]
}
},
'900000050201': { // U Krumme Lanke
U3: {
label: null,
platform: ['commons', 'Krummelanke-ubahn.jpg'],
entrance: null
}
},
'900000023203': { // U Kurfürstendamm
U1: {
label: ['flickr', 'ingolfbln', 8380738819],
platform: ['flickr', 'ingolfbln', 8380734785],
entrance: ['flickr', 'ingolfbln', 8380719173]
},
U9: {
label: ['flickr', 'ingolfbln', 8380633291],
platform: ['flickr', 'ingolfbln', 8381747376],
entrance: ['flickr', 'ingolfbln', 8380719173]
}
},
'900000086102': { // U Kurt-Schumacher-Platz
U6: {
label: ['flickr', 'ingolfbln', 24955027776],
platform: ['flickr', 'ingolfbln', 24863352592],
entrance: ['flickr', 'ingolfbln', 13546235063]
}
},
'900000079201': { // U Leinestr.
U8: {
label: ['flickr', 'ingolfbln', 6529442213],
platform: ['flickr', 'ingolfbln', 15041246505],
entrance: null
}
},
'900000086160': { // U Lindauer Allee
// todo: missing photo showing the name
U8: {
label: null,
platform: ['flickr', 'ingolfbln', 7806998528],
entrance: null
}
},
'900000009102': { // U Leopoldplatz
U6: {
label: ['flickr', 'ingolfbln', 7618720358],
platform: ['flickr', 'ingolfbln', 7618757186],
entrance: ['flickr', 'ingolfbln', 7618845284]
},
U9: {
label: ['flickr', 'ingolfbln', 7618811770],
platform: ['flickr', 'ingolfbln', 7618836372],
entrance: ['flickr', 'ingolfbln', 7618845284]
}
},
'900000082201': { // U Lipschitzallee
U7: {
label: ['flickr', 'ingolfbln', 15920214956],
platform: ['flickr', 'ingolfbln', 15760272957],
entrance: ['flickr', 'ingolfbln', 15758594928]
}
},
'900000175015': { // U Louis-Lewin-Straße
U5: {
label: ['commons', 'Berlin U-Bahn station Louis-Lewin-Straße.jpg'],
platform: ['commons', 'U-Bahn_Berlin_U5_Louis-Lewin-Strasse.JPG'],
entrance: null
}
},
'900000160004': { // S+U Lichtenberg
U5: {
label: ['flickr', 'ingolfbln', 6348818924],
platform: ['flickr', 'ingolfbln', 6348834488],
entrance: null
}
},
'900000160005': { // U Magdalenenstr.
U5: {
label: ['flickr', 'ingolfbln', 8445104431],
platform: ['flickr', 'ingolfbln', 8446262252],
entrance: ['flickr', 'ingolfbln', 8445154939]
}
},
'900000100014': { // U Märkisches Museum
U2: {
label: ['flickr', 'ingolfbln', 6286782697],
platform: ['flickr', 'ingolfbln', 6286717865],
entrance: null
}
},
'900000017101': { // U Mehringdamm
U6: {
label: ['flickr', 'ingolfbln', 6659117395],
platform: ['flickr', 'ingolfbln', 7882247220],
entrance: null
},
U7: {
label: ['flickr', 'ingolfbln', 6659117395],
platform: ['flickr', 'ingolfbln', 7882247220],
entrance: null
}
},
'900000005252': { // U Mendelssohn-Bartholdy-Park
U2: {
label: ['flickr', 'ingolfbln', 7184540992],
platform: ['flickr', 'ingolfbln', 7184408120],
entrance: null
}
},
'900000019204': { // U Mierendorffplatz
U7: {
label: ['flickr', 'ingolfbln', 6466605621],
platform: ['flickr', 'ingolfbln', 6466653109],
entrance: null
}
},
'900000017104': { // U Möckernbrücke
U1: {
label: ['flickr', 'ingolfbln', 7939725316],
platform: ['flickr', 'ingolfbln', 7939796296],
entrance: ['flickr', 'ingolfbln', 7939654880]
},
U7: {
label: ['flickr', 'ingolfbln', 7939573278],
platform: ['flickr', 'ingolfbln', 7939560024],
entrance: ['flickr', 'ingolfbln', 7939473964]
}
},
'900000100010': { // U Mohrenstr.
U2: {
label: ['flickr', 'ingolfbln', 7932699334],
platform: ['flickr', 'ingolfbln', 7932693798],
entrance: ['flickr', 'ingolfbln', 7932613738]
}
},
'900000013101': { // U Moritzplatz
U8: {
label: ['flickr', 'ingolfbln', 7798164546],
platform: ['flickr', 'ingolfbln', 7798170722],
entrance: ['flickr', 'ingolfbln', 7798301908]
}
},
'900000100009': { // U Naturkundemuseum
U6: {
label: ['flickr', 'ingolfbln', 6286546455],
platform: ['flickr', 'ingolfbln', 6286600655],
entrance: null
}
},
'900000009201': { // U Nauener Platz
U9: {
label: ['flickr', 'ingolfbln', 7811511250],
platform: ['flickr', 'ingolfbln', 7811496388],
entrance: ['flickr', 'ingolfbln', 7811405088]
}
},
'900000078201': { // S+U Neukölln
U7: {
label: ['flickr', 'ingolfbln', 8427326567],
platform: ['flickr', 'ingolfbln', 8428426774],
entrance: ['flickr', 'ingolfbln', 8427348789]
}
},
'900000026101': { // U Neu-Westend
U2: {
label: ['flickr', 'ingolfbln', 15021410257],
platform: ['flickr', 'ingolfbln', 15184959836],
entrance: ['flickr', 'ingolfbln', 15204938161]
}
},
'900000056102': { // U Nollendorfplatz
// https://www.flickr.com/photos/ingolfbln/11279253956/in/album-72157629097619388/
// todo: missing photo showing the name
U1: {
label: ['flickr', 'ingolfbln', 6933099425],
platform: ['flickr', 'ingolfbln', 6786986386],
entrance: null
},
U2: {
label: null,
platform: ['flickr', 'ingolfbln', 7184373680],
entrance: null
},
U3: {
label: ['flickr', 'ingolfbln', 6933099425],
platform: ['flickr', 'ingolfbln', 6786986386],
entrance: null
},
U4: {
label: ['flickr', 'ingolfbln', 6933099425],
platform: ['flickr', 'ingolfbln', 6786962078],
entrance: null
}
},
'900000025203': { // U Olympia-Stadion
U2: {
label: ['flickr', 'ingolfbln', 8021175922],
platform: ['flickr', 'ingolfbln', 8021163581],
entrance: null
}
},
'900000100019': { // U Oranienburger Tor
U6: {
label: ['flickr', '142745322@N06', 27516578870],
platform: ['commons', 'U-Bahn_Berlin_Oranienburger_Tor.jpg'],
entrance: null
}
},
'900000009202': { // U Osloer Str.
U8: {
label: ['flickr', 'ingolfbln', 7618273800],
platform: ['flickr', 'ingolfbln', 7618276924],
entrance: ['flickr', 'ingolfbln', 7618370998]
},
U9: {
label: ['flickr', 'ingolfbln', 7618273800],
platform: ['flickr', 'ingolfbln', 7618304156],
entrance: ['flickr', 'ingolfbln', 7618370998]
}
},
'900000130002': { // S+U Pankow
U2: {
label: ['flickr', 'ingolfbln', 6261170363],
platform: ['flickr', 'ingolfbln', 6261163011],
entrance: null
}
},
'900000009203': { // U Pankstr.
U8: {
label: ['flickr', 'ingolfbln', 7618016404],
platform: ['flickr', 'ingolfbln', 7618030952],
entrance: ['flickr', 'ingolfbln', 7618136362]
}
},
'900000085104': { // U Paracelsus-Bad
U8: {
label: ['flickr', 'ingolfbln', 6478942191],
platform: ['flickr', 'ingolfbln', 6478928281],
entrance: null
}
},
'900000068101': { // U Paradestr.
U6: {
label: ['flickr', 'ingolfbln', 8442059715],
platform: ['flickr', 'ingolfbln', 8443175236],
entrance: ['flickr', 'ingolfbln', 8443111484]
}
},
'900000080401': { // U Parchimer Allee
U7: {
// todo: better entrance photo
label: ['flickr', 'ingolfbln', 7986960720],
platform: ['flickr', 'ingolfbln', 7986959304],
entrance: ['flickr', 'ingolfbln', 7986920485]
}
},
'900000034101': { // U Paulsternstr.
U7: {
label: ['flickr', 'ingolfbln', 8480390556],
platform: ['flickr', 'ingolfbln', 8479277023],
entrance: ['flickr', 'ingolfbln', 8480373404]
}
},
'900000017102': { // U Platz der Luftbrücke
U6: {
label: ['flickr', 'ingolfbln', 6900004844],
platform: ['flickr', 'ingolfbln', 6900001996],
entrance: null
}
},
'900000100020': { // S+U Potsdamer Platz
U2: {
label: ['flickr', 'ingolfbln', 7185150538],
platform: ['flickr', 'ingolfbln', 7184978836],
entrance: null
}
},
'900000013103': { // U Prinzenstr.
U1: {
label: ['flickr', 'ingolfbln', 7545634198],
platform: ['flickr', 'ingolfbln', 7545616168],
entrance: null
}
},
'900000096410': { // U Rathaus Reinickendorf
U8: {
label: ['flickr', 'ingolfbln', 6477177115],
platform: ['flickr', 'ingolfbln', 6477334537],
entrance: null
}
},
'900000054101': { // U Rathaus Schöneberg
U4: {
label: ['flickr', 'ingolfbln', 7184233248],
platform: ['flickr', 'ingolfbln', 7184248666],
entrance: null
}
},
'900000029302': { // S+U Rathaus Spandau
U7: {
label: ['flickr', 'ingolfbln', 6473732171],
platform: ['flickr', 'ingolfbln', 6473287207],
entrance: null
}
},
'900000062202': { // S+U Rathaus Steglitz
U9: {
label: ['flickr', 'ingolfbln', 6657024963],
platform: ['flickr', 'ingolfbln', 6657102745],
entrance: null
}
},
'900000011101': { // U Rehberge
U6: {
label: ['flickr', 'ingolfbln', 15677835877],
platform: ['flickr', 'ingolfbln', 13547180563],
entrance: null
}
},
'900000008102': { // U Reinickendorfer Str.
U6: {
label: ['flickr', 'ingolfbln', 13366126825],
platform: ['flickr', 'ingolfbln', 13366625454],
entrance: ['flickr', 'ingolfbln', 13366380393]
}
},
'900000022202': { // U Richard-Wagner-Platz
U7: {
label: ['flickr', 'ingolfbln', 6421207533],
platform: ['flickr', 'ingolfbln', 6426655557],
entrance: null
}
},
'900000036101': { // U Rohrdamm
U7: {
// todo: better entrance photo
label: ['flickr', 'ingolfbln', 8448172473],
platform: ['flickr', 'ingolfbln', 8448175931],
entrance: ['flickr', 'ingolfbln', 8449229196]
}
},
'900000100016': { // U Rosa-Luxemburg-Platz
U2: {
label: ['flickr', 'ingolfbln', 7805059614],
platform: ['flickr', 'ingolfbln', 7805085780],
entrance: null
}
},
'900000100023': { // U Rosenthaler Platz
U8: {
label: ['flickr', 'ingolfbln', 6335985722],
platform: ['flickr', 'ingolfbln', 6335324081],
entrance: null
}
},
'900000045101': { // U Rüdesheimer Platz
U3: {
label: ['flickr', 'ingolfbln', 8990573305],
platform: ['flickr', 'ingolfbln', 8990554073],
entrance: ['flickr', 'ingolfbln', 8990634021]
}
},
'900000083201': { // U Rudow
U7: {
label: ['flickr', 'ingolfbln', 15759633679],
platform: ['flickr', 'ingolfbln', 15759612639],
entrance: ['flickr', 'ingolfbln', 15759622899]
}
},
'900000033101': { // U Zitadelle
U7: {
label: ['flickr', 'ingolfbln', 8480657860],
platform: ['flickr', 'ingolfbln', 8480660458],
entrance: ['flickr', 'ingolfbln', 8479550947]
},
},
'900000057103': { // S+U Yorckstraße
U7: {
label: ['flickr', 'ingolfbln', 6461502425],
platform: ['flickr', 'ingolfbln', 6461488195],
entrance: null
},
},
'900000083102': { // U Wutzkyallee
U7: {
label: ['flickr', 'ingolfbln', 15946240285],
platform: ['flickr', 'ingolfbln', 15326594443],
entrance: ['flickr', 'ingolfbln', 15946240285]
},
},
'900000175001': { // S+U Wuhletal
U5: {
label: ['commons', 'Berlin U-Bahn station Wuhletal.jpg'],
platform: ['flickr', 'ingolfbln', 9495178261],
entrance: ['flickr', 'ingolfbln', 9497859578]
},
},
'900000056101': { // U Wittenbergplatz
U1: {
label: ['flickr', 'ingolfbln', 7170316429],
platform: ['flickr', 'ingolfbln', 8291717701],
entrance: null
},
U2: {
label: ['flickr', 'ingolfbln', 7170316429],
platform: ['flickr', 'ingolfbln', 8291717701],
entrance: null
},
U3: {
label: ['flickr', 'ingolfbln', 7170316429],
platform: ['flickr', 'ingolfbln', 8291717701],
entrance: null
},
},
'900000070101': { // U Westphalweg
U6: {
label: ['flickr', 'ingolfbln', 8384130657],
platform: ['flickr', 'ingolfbln', 8385217432],
entrance: ['flickr', 'ingolfbln', 8384141965]
},
},
'900000001201': { // S+U Westhafen
U9: {
label: ['flickr', 'ingolfbln', 7606140134],
platform: ['flickr', 'ingolfbln', 7606128040],
entrance: null
},
},
'900000100051': { // U Weinmeisterstraße
U8: {
label: ['flickr', 'ingolfbln', 6942367173],
platform: ['flickr', 'ingolfbln', 6942388737],
entrance: null
},
},
'900000009104': { // S+U Wedding
U6: {
label: ['flickr', 'ingolfbln', 13366726265],
platform: ['flickr', 'ingolfbln', 13366747765],
entrance: ['flickr', 'ingolfbln', 13366849433]
},
},
'900000120025': { // U Weberwiese
U5: {
label: ['flickr', 'ingolfbln', 6261935322],
platform: ['flickr', 'ingolfbln', 6261917226],
entrance: null
},
},
'900000120004': { // S+U Warschauer Straße
U1: {
label: ['flickr', 'ingolfbln', 7658948668],
platform: ['flickr', 'ingolfbln', 7658942980],
entrance: null
},
},
'900000061101': { // U Walther-Schreiber-Platz
U9: {
label: ['flickr', 'ingolfbln', 8441812101],
platform: ['flickr', 'ingolfbln', 8442900284],
entrance: ['flickr', 'ingolfbln', 8442950484]
},
},
'900000007103': { // U Voltastraße
U8: {
label: ['flickr', 'ingolfbln', 7617740880],
platform: ['flickr', 'ingolfbln', 7617701868],
entrance: null
},
},
'900000130011': { // U Vinetastraße
U2: {
label: ['flickr', 'ingolfbln', 8431271806],
platform: ['flickr', 'ingolfbln', 8430182513],
entrance: ['flickr', 'ingolfbln', 8431209650]
},
},
'900000055101': { // U Viktoria-Luise-Platz
U4: {
label: ['flickr', 'ingolfbln', 7145955841],
platform: ['flickr', 'ingolfbln', 7145950145],
entrance: null
},
},
'900000069271': { // U Ullsteinstraße
U6: {
label: ['flickr', 'ingolfbln', 8430268841],
platform: ['flickr', 'ingolfbln', 8431336368],
entrance: ['flickr', 'ingolfbln', 8431314286]
},
},
'900000023301': { // U Uhlandstraße
U1: {
label: ['flickr', 'ingolfbln', 8389622307],
platform: ['flickr', 'ingolfbln', 8390712494],
entrance: ['flickr', 'ingolfbln', 8390720164]
},
},
'900000003104': { // U Turmstraße
U9: {
label: ['flickr', 'ingolfbln', 9487837043],
platform: ['flickr', 'ingolfbln', 9487950731],
entrance: ['flickr', 'ingolfbln', 9487875321]
},
},
'900000161002': { // U Tierpark
U5: {
label: ['flickr', 'ingolfbln', 6342263740],
platform: ['flickr', 'ingolfbln', 6341467799],
entrance: null
},
},
'900000026201': { // U Theodor-Heuss-Platz
U2: {
label: ['flickr', 'ingolfbln', 15021509277],
platform: ['flickr', 'ingolfbln', 15021516327],
entrance: ['flickr', 'ingolfbln', 15021291699]
},
},
'900000068201': { // S+U Tempelhof
U6: {
// todo: better entrance photo
label: ['flickr', 'ingolfbln', 6286996768],
platform: ['flickr', 'ingolfbln', 6286974820],
entrance: ['flickr', 'ingolfbln', 7965908534]
},
},
'900000016202': { // U Südstern
U7: {
label: ['flickr', 'ingolfbln', 6396587851],
platform: ['flickr', 'ingolfbln', 6396559009],
entrance: null
},
},
'900000120006': { // U Strausberger Platz
U5: {
label: ['flickr', 'ingolfbln', 6261512671],
platform: ['flickr', 'ingolfbln', 6262016490],
entrance: null
},
},
'900000100011': { // U Stadtmitte
U2: {
label: ['flickr', 'ingolfbln', 6478223615],
platform: ['flickr', 'ingolfbln', 6478372559],
entrance: null
},
U6: {
label: ['flickr', 'ingolfbln', 6478660389],
platform: ['flickr', 'ingolfbln', 6478706775],
entrance: null
},
},
'900000100013': { // U Spittelmarkt
U2: {
label: ['flickr', 'ingolfbln', 6315302831],
platform: ['flickr', 'ingolfbln', 7804943762],
entrance: null
},
},
'900000042101': { // U Spichernstraße
U3: {
label: ['commons', 'U-Bahnhof_Spichernstraße_(U3)_20130727_2.jpg'],
platform: ['flickr', 'ingolfbln', 7605884990],
entrance: null
},
U9: {
label: ['flickr', 'ingolfbln', 7606085308],
platform: ['flickr', 'ingolfbln', 7606062008],
entrance: null
},
},
'900000022101': { // U Sophie-Charlotte-Platz
U2: {
label: ['commons', 'Berlin_-_U-Bahnhof_Sophie-Charlotte-Platz_-_Linie_U2_(6945055571).jpg'],
platform: ['flickr', 'ingolfbln', 6945035051],
entrance: null
},
},
'900000035101': { // U Siemensdamm
// todo: missing photo showing name (close-up)
U7: {
label: ['flickr', 'ingolfbln', 8448112575],
platform: ['flickr', 'ingolfbln', 8449137556],
entrance: ['flickr', 'ingolfbln', 8448081863]
},
},
'900000110005': { // U Senefelderplatz
U2: {
label: ['commons', 'Senefelderplatz_plaque.jpg'],
platform: ['flickr', 'ingolfbln', 7804920404],
entrance: null
},
},
'900000100501': { // U Schwartzkopffstraße
// todo: missing photo showing name (close-up)
U6: {
label: ['flickr', 'ingolfbln', 13366448165],
platform: ['flickr', 'ingolfbln', 13366798574],
entrance: ['flickr', 'ingolfbln', 13366397835]
},
},
'900000120009': { // U Samariterstraße
U5: {
label: ['commons', 'Samariterstraße_(15186253620).jpg'],
platform: ['flickr', 'ingolfbln', 6261366635],
entrance: null
},
},
'900000100017': { // U Schillingstraße
U5: {
label: ['commons', 'Schillingstraße_subway_sign_01.JPG'],
platform: ['flickr', 'ingolfbln', 6261633179],
entrance: null
},
},
'900000014102': { // U Schlesisches Tor
U1: {
label: ['flickr', 'ingolfbln', 6319640129],
platform: ['flickr', 'ingolfbln', 6320226072],
entrance: null
},
},
'900000062203': { // U Schloßstraße
U9: {
label: ['flickr', 'ingolfbln', 6661967795],
platform: ['flickr', 'ingolfbln', 6659854511],
entrance: null
},
},
'900000110001': { // S+U Schönhauser Allee
U2: {
label: ['flickr', 'ingolfbln', 7592906382],
platform: ['flickr', 'ingolfbln', 7593090948],
entrance: null
},
},
'900000016201': { // U Schönleinstraße
U8: {
label: ['flickr', 'ingolfbln', 6528982091],
platform: ['flickr', 'ingolfbln', 6528938699],
entrance: null
},
},
'900000023201': { // S+U Zoologischer Garten
U2: {
label: ['flickr', 'pasa', 5864038454],
platform: ['flickr', 'galio', 4610552275],
entrance: null
},
// todo: glynlowe/23075396060 ?
U9: {
label: null,
platform: ['flickr', 'mbell1975', 3793762490],
entrance: null
}
},
'900000083101': { // U Zwickauer Damm
U7: {
label: ['flickr', 'ingolfbln', 15324013144],
platform: ['flickr', 'ingolfbln', 15758852748],
entrance: null
},
}
}
| photos.js | 'use strict'
module.exports = {
'900000100003': { // S+U Alexanderplatz
U2: {
label: ['flickr', 'ingolfbln', 6977132297],
platform: ['flickr', 'ingolfbln', 6831050998],
entrance: null
},
U5: {
label: ['flickr', 'ingolfbln', 6904300029],
platform: ['flickr', 'ingolfbln', 6904572417],
entrance: null
},
U8: {
label: ['commons', 'Berlin_-_Bahnhof_Alexanderplatz3.jpg'],
platform: ['flickr', 'ingolfbln', 7624771658],
entrance: null
}
},
'900000011102': { // U Afrikanische Straße
U6: {
label: ['flickr', 'ingolfbln', 24350635584],
platform: ['flickr', 'ingolfbln', 15241241614],
entrance: null
}
},
'900000023302': { // U Adenauerplatz
U7: {
label: ['flickr', 'ingolfbln', 6390440937],
platform: ['flickr', 'ingolfbln', 6390505317],
entrance: null
}
},
'900000070301': { // U Alt-Mariendorf
U6: {
// todo: better entrance photo
label: ['flickr', 'ingolfbln', 8442745166],
platform: ['flickr', 'ingolfbln', 8442753190],
entrance: ['flickr', 'ingolfbln', 8442828284]
}
},
'900000029301': { // U Altstadt Spandau
U7: {
label: ['flickr', 'ingolfbln', 8480776682],
platform: ['flickr', 'ingolfbln', 8479688177],
entrance: ['flickr', 'ingolfbln', 8479696353]
}
},
'900000089301': { // U Alt-Tegel
U9: {
label: ['flickr', 'ingolfbln', 7174331773],
platform: ['flickr', 'ingolfbln', 7359570360],
entrance: null
}
},
'900000009101': { // U Amrumer Str.
U9: {
label: ['flickr', 'ingolfbln', 6413966751],
platform: ['flickr', 'ingolfbln', 6413947281],
entrance: null
}
},
'900000055102': { // U Bayerischer Platz
U4: {
label: ['flickr', 'ingolfbln', 6444018965],
platform: ['flickr', 'ingolfbln', 6444065621],
entrance: null
},
U7: {
label: ['flickr', 'ingolfbln', 6443862789],
platform: ['flickr', 'ingolfbln', 6443871455],
entrance: null
}
},
'900000044201': { // U Berliner Str.
U7: {
label: ['flickr', '142745322@N06', 27760600346],
platform: ['commons', 'U-Bahn_Berlin_Berliner_Straße.jpg'],
entrance: null
},
U9: {
label: ['flickr', '142745322@N06', 27760595616],
platform: ['commons', 'Berlinerstr-u9-ubahn.jpg'],
entrance: null
}
},
'900000007110': { // U Bernauer Str.
U8: {
label: ['flickr', 'ingolfbln', 6335397247],
platform: ['flickr', 'ingolfbln', 6335405259],
entrance: null
}
},
'900000171005': {
U5: {
label: ['commons', 'Berlin U-Bahn station Biesdorf-Süd 01.jpg'],
platform: null},
entrance: null
},
'900000002201': { // U Birkenstr.
U9: {
label: ['flickr', 'ingolfbln', 6413815835],
platform: ['flickr', 'ingolfbln', 6413561591],
entrance: null
}
},
'900000024201': { // U Bismarckstr.
U2: {
label: ['flickr', 'ingolfbln', 6420827133],
platform: ['flickr', 'ingolfbln', 6420684483],
entrance: null
},
U7: {
label: ['flickr', 'ingolfbln', 6420923733],
platform: ['flickr', 'ingolfbln', 6421064143],
entrance: null
}
},
'900000080201': { // U Blaschkoallee
U7: {
label: ['flickr', 'ingolfbln', 7986890237],
platform: ['flickr', 'ingolfbln', 7986906582],
entrance: ['flickr', 'ingolfbln', 7986882684]
}
},
'900000041102': { // U Blissestr.
U7: {
label: ['flickr', 'ingolfbln', 6443698515],
platform: ['flickr', 'ingolfbln', 6443688697],
entrance: null
}
},
'900000079202': { // U Boddinstr.
U8: {
label: ['flickr', 'ingolfbln', 15018334836],
platform: ['flickr', 'ingolfbln', 15041298645],
entrance: null
}
},
'900000088202': { // U Borsigwerke
U6: {
label: ['flickr', 'ingolfbln', 7174241521],
platform: ['flickr', 'ingolfbln', 7174238429],
entrance: null
}
},
'900000100025': { // S+U Brandenburger Tor
U55: {
label: ['flickr', 'ingolfbln', 6247517033],
platform: ['flickr', 'ingolfbln', 8013530153],
entrance: null
}
},
'900000080402': { // U Britz-Süd
U7: {
label: ['flickr', 'ingolfbln', 15758843510],
platform: ['flickr', 'ingolfbln', 15758710458],
entrance: ['flickr', 'ingolfbln', 15758838800]
}
},
'900000056104': { // U Bülowstr.
U2: {
label: ['flickr', 'ingolfbln', 8991197746],
platform: ['flickr', 'ingolfbln', 9510232053],
entrance: ['flickr', 'ingolfbln', 9510210481]
}
},
'900000003254': { // U Bundestag
U55: {
label: ['flickr', 'ingolfbln', 22004585159],
platform: ['flickr', 'ingolfbln', 22003394950],
entrance: null
}
},
'900000044202': { // S+U Bundesplatz
U9: {
label: ['flickr', '142745322@N06', 27183844933],
platform: ['commons', 'Bundesplatz_west-ubahn.jpg'],
entrance: null
}
},
'900000175006': {
U5: {
label: ['commons', 'Berlin U-Bahn station Cottbusser Platz.jpg'],
platform: ['commons', 'U-Bahnhof_Cottbusser_Platz.jpg'],
entrance: null
}
},
'900000022201': { // U Deutsche Oper
U2: {
label: ['flickr', 'ingolfbln', 6420520007],
platform: ['flickr', 'ingolfbln', 6420536747],
entrance: null
}
},
'900000110006': { // U Eberswalder Str.
U2: {
label: ['flickr', 'ingolfbln', 9550979798],
platform: ['flickr', 'ingolfbln', 6261075205],
entrance: null
}
},
'900000054103': { // U Eisenacher Str.
U7: {
label: ['flickr', 'ingolfbln', 6385281907],
platform: ['flickr', 'ingolfbln', 6385333159],
entrance: null
}
},
'900000171006': { // U Elsterwerdaer Platz
U5: {
label: ['commons', 'Berlin U-Bahn station Elstawerdaer Platz.jpg'],
platform: ['commons', '2005-07-18_ubf_elsterwerdaer_platz_bahnsteig.jpg'],
entrance: null
}
},
'900000023101': { // U Ernst-Reuter-Platz
U2: {
label: ['flickr', 'ingolfbln', 7811608786],
platform: ['flickr', 'ingolfbln', 7811597724],
entrance: ['flickr', 'ingolfbln', 7811577562]
}
},
'900000041101': { // U Fehrbelliner Platz
U3: {
label: ['flickr', 'ingolfbln', 6384603637],
platform: ['flickr', 'ingolfbln', 6384672149],
entrance: null
},
U7: {
label: ['flickr', 'ingolfbln', 6384444067],
platform: ['flickr', 'ingolfbln', 6384476157],
entrance: null
}
},
'900000120001': { // S+U Frankfurter Allee
U5: {
label: ['flickr', 'ingolfbln', 13607255353],
platform: ['flickr', 'ingolfbln', 13607600174],
entrance: ['flickr', 'ingolfbln', 13607246325]
}
},
'900000120008': { // U Frankfurter Tor
U5: {
// todo: better entrance photo
label: ['flickr', 'ingolfbln', 13607728993],
platform: ['flickr', 'ingolfbln', 13607733313],
entrance: ['flickr', 'ingolfbln', 13608053194]
}
},
'900000100027': { // U Französische Str.
U6: {
label: ['flickr', 'ingolfbln', 7046228347],
platform: ['flickr', 'ingolfbln', 7046199547],
entrance: null
}
},
'900000161512': { // U Friedrichsfelde
U5: {
// todo: better entrance photo
label: ['flickr', 'ingolfbln', 8444925853],
platform: ['flickr', 'ingolfbln', 8444973707],
entrance: ['flickr', 'ingolfbln', 8444950453]
}
},
'900000100001': { // S+U Friedrichstr.
U6: {
label: ['flickr', 'ingolfbln', 6885603222],
platform: ['flickr', 'ingolfbln', 6885597904],
entrance: null
}
},
'900000061102': { // U Friedrich-Wilhelm-Platz
U9: {
label: ['flickr', 'ingolfbln', 8445906948],
platform: ['flickr', 'ingolfbln', 8445830122],
entrance: ['flickr', 'ingolfbln', 8444778417]
}
},
'900000007102': { // S+U Gesundbrunnen
U8: {
label: ['flickr', 'ingolfbln', 6521984893],
platform: ['flickr', 'ingolfbln', 6521972153],
entrance: null
}
},
'900000017103': { // U Gleisdreieck
U1: {
label: ['flickr', 'ingolfbln', 7931788740],
platform: ['flickr', 'ingolfbln', 7931841660],
entrance: null
},
U2: {
label: ['flickr', 'ingolfbln', 7184779634],
platform: ['flickr', 'ingolfbln', 7184839708],
entrance: null
}
},
'900000016101': { // U Gneisenaustr.
U7: {
label: ['flickr', 'ingolfbln', 6335901482],
platform: ['flickr', 'ingolfbln', 8292125259],
entrance: null
}
},
'900000014101': { // U Görlitzer Bahnhof
U1: {
label: ['flickr', 'ingolfbln', 6396112665],
platform: ['flickr', 'ingolfbln', 6800825848],
entrance: null
}
},
'900000080202': { // U Grenzallee
U7: {
label: ['flickr', 'ingolfbln', 8389921395],
platform: ['flickr', 'ingolfbln', 8389896257],
entrance: ['flickr', 'ingolfbln', 8389912401]
}
},
'900000043201': { // U Güntzelstr.
U9: {
label: ['flickr', '142745322@N06', 27183838403],
platform: ['flickr', 'ingolfbln', 7811698154],
entrance: null
}
},
'900000018102': { // U Halemweg
U7: {
// todo: better entrance photo
label: ['flickr', 'ingolfbln', 8447783145],
platform: ['flickr', 'ingolfbln', 8448906202],
entrance: ['flickr', 'ingolfbln', 8448883602]
}
},
'900000012103': { // U Hallesches Tor
U1: {
label: ['flickr', 'ingolfbln', 8194057063],
platform: ['flickr', 'ingolfbln', 8194069607],
entrance: ['flickr', 'ingolfbln', 8195191120]
},
U6: {
label: ['flickr', 'ingolfbln', 8194012643],
platform: ['flickr', 'ingolfbln', 8194021459],
entrance: ['flickr', 'ingolfbln', 8194036617]
}
},
'900000003101': { // U Hansaplatz
U9: {
label: ['flickr', 'ingolfbln', 6413038423],
platform: ['flickr', 'ingolfbln', 6413402697],
entrance: null
}
},
'900000034102': { // U Haselhorst
U7: {
// todo: better entrance photo
label: ['flickr', 'ingolfbln', 8480566324],
platform: ['flickr', 'ingolfbln', 8480519654],
entrance: ['flickr', 'ingolfbln', 8480535288]
}
},
'900000003201': { // S+U Hauptbahnhof
// todo: better platform photo
U55: {
label: ['flickr', '142745322@N06', 27516604790],
platform: ['flickr', 'ingolfbln', '8013595510'],
entrance: null
}
},
'900000100012': { // U Hausvogteiplatz
U2: {
label: ['flickr', 'ingolfbln', 8428213432],
platform: ['flickr', 'ingolfbln', 8427115893],
entrance: ['flickr', 'ingolfbln', 8428188718]
}
},
'900000045102': { // S+U Heidelberger Platz
U3: {
label: ['flickr', 'ingolfbln', 8294597799],
platform: ['flickr', 'ingolfbln', 8294606457],
entrance: null
}
},
'900000100008': { // U Heinrich-Heine-Str.
U8: {
label: ['flickr', 'ingolfbln', 7592578554],
platform: ['flickr', 'ingolfbln', 7592604840],
entrance: null
}
},
'900000078101': { // U Hermannplatz
U8: {
label: ['flickr', 'ingolfbln', 6335825554],
platform: ['flickr', 'ingolfbln', 8293152370],
entrance: null
},
U7: {
label: ['flickr', 'ingolfbln', 8480862534],
platform: ['flickr', 'ingolfbln', 8479757095],
entrance: null
}
},
'900000079221': { // S+U Hermannstr.
U8: {
label: ['flickr', 'ingolfbln', 6530852191],
platform: ['flickr', 'ingolfbln', 6530841673],
entrance: null
}
},
'900000175007': {
U5: {
label: ['commons', 'Berlin U-Bahn station Hellersdorf.jpg'],
platform: ['commons', 'Hellersdorf-ubahn.jpg'],
entrance: null
}
},
'900000043101': { // U Hohenzollernplatz
U3: {
label: ['flickr', 'ingolfbln', 8293135494],
platform: ['flickr', 'ingolfbln', 8292084211],
entrance: ['flickr', 'ingolfbln', 8292048983]
}
},
'900000175010': {
U5: {
label: ['commons', 'Berlin U-Bahn station Hönow.jpg'],
platform: ['commons', 'UBahnhf_Hoenow.JPG'],
entrance: null
}
},
'900000018101': { // U Jakob-Kaiser-Platz
U7: {
label: ['flickr', 'ingolfbln', 13547214604],
platform: ['flickr', 'ingolfbln', 13547008043],
entrance: ['flickr', 'ingolfbln', 13546801743]
}
},
'900000100004': { // S+U Jannowitzbrücke
U8: {
label: ['flickr', 'ingolfbln', 6323544365],
platform: ['flickr', 'ingolfbln', 6323560829],
entrance: null
}
},
'900000020201': { // S+U Jungfernheide
U7: {
label: ['flickr', 'ingolfbln', 6255097490],
platform: ['flickr', 'ingolfbln', 6255106242],
entrance: null
}
},
'900000068302': { // U Kaiserin-Augusta-Str.
// todo: still under construction?
U6: {
label: null,
platform: ['flickr', 'ingolfbln', 15817428556],
entrance: ['flickr', 'ingolfbln', 15655902810]
}
},
'900000096458': { // S+U Karl-Bonhoeffer-Nervenklinik
U8: {
label: ['flickr', 'ingolfbln', 7807059838],
platform: ['flickr', 'ingolfbln', 7807052574],
entrance: null
}
},
'900000078103': { // U Karl-Marx-Str.
U7: {
// todo: better entrance photo
label: ['flickr', 'ingolfbln', 8428333804],
platform: ['flickr', 'ingolfbln', 8427234401],
entrance: ['flickr', 'ingolfbln', 8428301850]
}
},
'900000175004': {
U5: {
label: ['commons', 'Berlin U-Bahn station Kaulsdorf Nord.jpg'],
platform: ['commons', 'Ubahnhf-Kaulsdorf-nord.JPG'],
entrance: null
}
},
'900000054102': { // U Kleistpark
U7: {
// todo: better entrance photo
label: ['flickr', 'ingolfbln', 8011466188],
platform: ['flickr', 'ingolfbln', 8011478612],
entrance: ['flickr', 'ingolfbln', 8011430580]
}
},
'900000100015': { // U Klosterstr.
U2: {
label: ['flickr', 'ingolfbln', 6336269032],
platform: ['flickr', 'ingolfbln', 6336236448],
entrance: null
}
},
'900000012102': { // U Kochstr./Checkpoint Charlie
U6: {
label: ['flickr', '142745322@N06', 27516587910],
platform: ['commons', 'Kochstr-ubahn.jpg'],
entrance: null
}
},
'900000041201': { // U Konstanzer Str.
U7: {
label: ['flickr', 'ingolfbln', 9096834614],
platform: ['flickr', 'ingolfbln', 9094593099],
entrance: ['flickr', 'ingolfbln', 9096772112]
}
},
'900000013102': { // U Kottbusser Tor
// todo: better entrance photos
U1: {
label: ['flickr', 'ingolfbln', 7932564208],
platform: ['flickr', 'ingolfbln', 7932567552],
entrance: ['flickr', 'ingolfbln', 7932443538]
},
U8: {
label: ['flickr', 'ingolfbln', 7932310940],
platform: ['flickr', 'ingolfbln', 7932259378],
entrance: ['flickr', 'ingolfbln', 7932443538]
}
},
'900000050201': { // U Krumme Lanke
U3: {
label: null,
platform: ['commons', 'Krummelanke-ubahn.jpg'],
entrance: null
}
},
'900000023203': { // U Kurfürstendamm
U1: {
label: ['flickr', 'ingolfbln', 8380738819],
platform: ['flickr', 'ingolfbln', 8380734785],
entrance: ['flickr', 'ingolfbln', 8380719173]
},
U9: {
label: ['flickr', 'ingolfbln', 8380633291],
platform: ['flickr', 'ingolfbln', 8381747376],
entrance: ['flickr', 'ingolfbln', 8380719173]
}
},
'900000086102': { // U Kurt-Schumacher-Platz
U6: {
label: ['flickr', 'ingolfbln', 24955027776],
platform: ['flickr', 'ingolfbln', 24863352592],
entrance: ['flickr', 'ingolfbln', 13546235063]
}
},
'900000079201': { // U Leinestr.
U8: {
label: ['flickr', 'ingolfbln', 6529442213],
platform: ['flickr', 'ingolfbln', 15041246505],
entrance: null
}
},
'900000086160': { // U Lindauer Allee
// todo: missing photo showing the name
U8: {
label: null,
platform: ['flickr', 'ingolfbln', 7806998528],
entrance: null
}
},
'900000009102': { // U Leopoldplatz
U6: {
label: ['flickr', 'ingolfbln', 7618720358],
platform: ['flickr', 'ingolfbln', 7618757186],
entrance: ['flickr', 'ingolfbln', 7618845284]
},
U9: {
label: ['flickr', 'ingolfbln', 7618811770],
platform: ['flickr', 'ingolfbln', 7618836372],
entrance: ['flickr', 'ingolfbln', 7618845284]
}
},
'900000082201': { // U Lipschitzallee
U7: {
label: ['flickr', 'ingolfbln', 15920214956],
platform: ['flickr', 'ingolfbln', 15760272957],
entrance: ['flickr', 'ingolfbln', 15758594928]
}
},
'900000175015': { // U Louis-Lewin-Straße
U5: {
label: ['commons', 'Berlin U-Bahn station Louis-Lewin-Straße.jpg'],
platform: ['commons', 'U-Bahn_Berlin_U5_Louis-Lewin-Strasse.JPG'],
entrance: null
}
},
'900000160004': { // S+U Lichtenberg
U5: {
label: ['flickr', 'ingolfbln', 6348818924],
platform: ['flickr', 'ingolfbln', 6348834488],
entrance: null
}
},
'900000160005': { // U Magdalenenstr.
U5: {
label: ['flickr', 'ingolfbln', 8445104431],
platform: ['flickr', 'ingolfbln', 8446262252],
entrance: ['flickr', 'ingolfbln', 8445154939]
}
},
'900000100014': { // U Märkisches Museum
U2: {
label: ['flickr', 'ingolfbln', 6286782697],
platform: ['flickr', 'ingolfbln', 6286717865],
entrance: null
}
},
'900000017101': { // U Mehringdamm
U6: {
label: ['flickr', 'ingolfbln', 6659117395],
platform: ['flickr', 'ingolfbln', 7882247220],
entrance: null
},
U7: {
label: ['flickr', 'ingolfbln', 6659117395],
platform: ['flickr', 'ingolfbln', 7882247220],
entrance: null
}
},
'900000005252': { // U Mendelssohn-Bartholdy-Park
U2: {
label: ['flickr', 'ingolfbln', 7184540992],
platform: ['flickr', 'ingolfbln', 7184408120],
entrance: null
}
},
'900000019204': { // U Mierendorffplatz
U7: {
label: ['flickr', 'ingolfbln', 6466605621],
platform: ['flickr', 'ingolfbln', 6466653109],
entrance: null
}
},
'900000017104': { // U Möckernbrücke
U1: {
label: ['flickr', 'ingolfbln', 7939725316],
platform: ['flickr', 'ingolfbln', 7939796296],
entrance: ['flickr', 'ingolfbln', 7939654880]
},
U7: {
label: ['flickr', 'ingolfbln', 7939573278],
platform: ['flickr', 'ingolfbln', 7939560024],
entrance: ['flickr', 'ingolfbln', 7939473964]
}
},
'900000100010': { // U Mohrenstr.
U2: {
label: ['flickr', 'ingolfbln', 7932699334],
platform: ['flickr', 'ingolfbln', 7932693798],
entrance: ['flickr', 'ingolfbln', 7932613738]
}
},
'900000013101': { // U Moritzplatz
U8: {
label: ['flickr', 'ingolfbln', 7798164546],
platform: ['flickr', 'ingolfbln', 7798170722],
entrance: ['flickr', 'ingolfbln', 7798301908]
}
},
'900000100009': { // U Naturkundemuseum
U6: {
label: ['flickr', 'ingolfbln', 6286546455],
platform: ['flickr', 'ingolfbln', 6286600655],
entrance: null
}
},
'900000009201': { // U Nauener Platz
U9: {
label: ['flickr', 'ingolfbln', 7811511250],
platform: ['flickr', 'ingolfbln', 7811496388],
entrance: ['flickr', 'ingolfbln', 7811405088]
}
},
'900000078201': { // S+U Neukölln
U7: {
label: ['flickr', 'ingolfbln', 8427326567],
platform: ['flickr', 'ingolfbln', 8428426774],
entrance: ['flickr', 'ingolfbln', 8427348789]
}
},
'900000026101': { // U Neu-Westend
U2: {
label: ['flickr', 'ingolfbln', 15021410257],
platform: ['flickr', 'ingolfbln', 15184959836],
entrance: ['flickr', 'ingolfbln', 15204938161]
}
},
'900000056102': { // U Nollendorfplatz
// https://www.flickr.com/photos/ingolfbln/11279253956/in/album-72157629097619388/
// todo: missing photo showing the name
U1: {
label: ['flickr', 'ingolfbln', 6933099425],
platform: ['flickr', 'ingolfbln', 6786986386],
entrance: null
},
U2: {
label: null,
platform: ['flickr', 'ingolfbln', 7184373680],
entrance: null
},
U3: {
label: ['flickr', 'ingolfbln', 6933099425],
platform: ['flickr', 'ingolfbln', 6786986386],
entrance: null
},
U4: {
label: ['flickr', 'ingolfbln', 6933099425],
platform: ['flickr', 'ingolfbln', 6786962078],
entrance: null
}
},
'900000025203': { // U Olympia-Stadion
U2: {
label: ['flickr', 'ingolfbln', 8021175922],
platform: ['flickr', 'ingolfbln', 8021163581],
entrance: null
}
},
'900000100019': { // U Oranienburger Tor
U6: {
label: ['flickr', '142745322@N06', 27516578870],
platform: ['commons', 'U-Bahn_Berlin_Oranienburger_Tor.jpg'],
entrance: null
}
},
'900000009202': { // U Osloer Str.
U8: {
label: ['flickr', 'ingolfbln', 7618273800],
platform: ['flickr', 'ingolfbln', 7618276924],
entrance: ['flickr', 'ingolfbln', 7618370998]
},
U9: {
label: ['flickr', 'ingolfbln', 7618273800],
platform: ['flickr', 'ingolfbln', 7618304156],
entrance: ['flickr', 'ingolfbln', 7618370998]
}
},
'900000130002': { // S+U Pankow
U2: {
label: ['flickr', 'ingolfbln', 6261170363],
platform: ['flickr', 'ingolfbln', 6261163011],
entrance: null
}
},
'900000009203': { // U Pankstr.
U8: {
label: ['flickr', 'ingolfbln', 7618016404],
platform: ['flickr', 'ingolfbln', 7618030952],
entrance: null
}
},
'900000085104': { // U Paracelsus-Bad
U8: {
label: ['flickr', 'ingolfbln', 6478942191],
platform: ['flickr', 'ingolfbln', 6478928281],
entrance: null
}
},
'900000068101': { // U Paradestr.
U6: {
label: ['flickr', 'ingolfbln', 8442059715],
platform: ['flickr', 'ingolfbln', 8443175236],
entrance: ['flickr', 'ingolfbln', 8443111484]
}
},
'900000080401': { // U Parchimer Allee
U7: {
// todo: better entrance photo
label: ['flickr', 'ingolfbln', 7986960720],
platform: ['flickr', 'ingolfbln', 7986959304],
entrance: ['flickr', 'ingolfbln', 7986920485]
}
},
'900000034101': { // U Paulsternstr.
U7: {
label: ['flickr', 'ingolfbln', 8480390556],
platform: ['flickr', 'ingolfbln', 8479277023],
entrance: ['flickr', 'ingolfbln', 8480373404]
}
},
'900000017102': { // U Platz der Luftbrücke
U6: {
label: ['flickr', 'ingolfbln', 6900004844],
platform: ['flickr', 'ingolfbln', 6900001996],
entrance: null
}
},
'900000100020': { // S+U Potsdamer Platz
U2: {
label: ['flickr', 'ingolfbln', 7185150538],
platform: ['flickr', 'ingolfbln', 7184978836],
entrance: null
}
},
'900000013103': { // U Prinzenstr.
U1: {
label: ['flickr', 'ingolfbln', 7545634198],
platform: ['flickr', 'ingolfbln', 7545616168],
entrance: null
}
},
'900000096410': { // U Rathaus Reinickendorf
U8: {
label: ['flickr', 'ingolfbln', 6477177115],
platform: ['flickr', 'ingolfbln', 6477334537],
entrance: null
}
},
'900000054101': { // U Rathaus Schöneberg
U4: {
label: ['flickr', 'ingolfbln', 7184233248],
platform: ['flickr', 'ingolfbln', 7184248666],
entrance: null
}
},
'900000029302': { // S+U Rathaus Spandau
U7: {
label: ['flickr', 'ingolfbln', 6473732171],
platform: ['flickr', 'ingolfbln', 6473287207],
entrance: null
}
},
'900000062202': { // S+U Rathaus Steglitz
U9: {
label: ['flickr', 'ingolfbln', 6657024963],
platform: ['flickr', 'ingolfbln', 6657102745],
entrance: null
}
},
'900000011101': { // U Rehberge
U6: {
label: ['flickr', 'ingolfbln', 15677835877],
platform: ['flickr', 'ingolfbln', 13547180563],
entrance: null
}
},
'900000008102': { // U Reinickendorfer Str.
U6: {
label: ['flickr', 'ingolfbln', 13366126825],
platform: ['flickr', 'ingolfbln', 13366625454],
entrance: ['flickr', 'ingolfbln', 13366380393]
}
},
'900000022202': { // U Richard-Wagner-Platz
U7: {
label: ['flickr', 'ingolfbln', 6421207533],
platform: ['flickr', 'ingolfbln', 6426655557],
entrance: null
}
},
'900000036101': { // U Rohrdamm
U7: {
// todo: better entrance photo
label: ['flickr', 'ingolfbln', 8448172473],
platform: ['flickr', 'ingolfbln', 8448175931],
entrance: ['flickr', 'ingolfbln', 8449229196]
}
},
'900000100016': { // U Rosa-Luxemburg-Platz
U2: {
label: ['flickr', 'ingolfbln', 7805059614],
platform: ['flickr', 'ingolfbln', 7805085780],
entrance: null
}
},
'900000100023': { // U Rosenthaler Platz
U8: {
label: ['flickr', 'ingolfbln', 6335985722],
platform: ['flickr', 'ingolfbln', 6335324081],
entrance: null
}
},
'900000045101': { // U Rüdesheimer Platz
U3: {
label: ['flickr', 'ingolfbln', 8990573305],
platform: ['flickr', 'ingolfbln', 8990554073],
entrance: ['flickr', 'ingolfbln', 8990634021]
}
},
'900000083201': { // U Rudow
U7: {
label: ['flickr', 'ingolfbln', 15759633679],
platform: ['flickr', 'ingolfbln', 15759612639],
entrance: ['flickr', 'ingolfbln', 15759622899]
}
},
'900000033101': { // U Zitadelle
U7: {
label: ['flickr', 'ingolfbln', 8480657860],
platform: ['flickr', 'ingolfbln', 8480660458],
entrance: ['flickr', 'ingolfbln', 8479550947]
},
},
'900000057103': { // S+U Yorckstraße
U7: {
label: ['flickr', 'ingolfbln', 6461502425],
platform: ['flickr', 'ingolfbln', 6461488195],
entrance: null
},
},
'900000083102': { // U Wutzkyallee
U7: {
label: ['flickr', 'ingolfbln', 15946240285],
platform: ['flickr', 'ingolfbln', 15326594443],
entrance: ['flickr', 'ingolfbln', 15946240285]
},
},
'900000175001': { // S+U Wuhletal
U5: {
label: ['commons', 'Berlin U-Bahn station Wuhletal.jpg'],
platform: ['flickr', 'ingolfbln', 9495178261],
entrance: ['flickr', 'ingolfbln', 9497859578]
},
},
'900000056101': { // U Wittenbergplatz
U1: {
label: ['flickr', 'ingolfbln', 7170316429],
platform: ['flickr', 'ingolfbln', 8291717701],
entrance: null
},
U2: {
label: ['flickr', 'ingolfbln', 7170316429],
platform: ['flickr', 'ingolfbln', 8291717701],
entrance: null
},
U3: {
label: ['flickr', 'ingolfbln', 7170316429],
platform: ['flickr', 'ingolfbln', 8291717701],
entrance: null
},
},
'900000070101': { // U Westphalweg
U6: {
label: ['flickr', 'ingolfbln', 8384130657],
platform: ['flickr', 'ingolfbln', 8385217432],
entrance: ['flickr', 'ingolfbln', 8384141965]
},
},
'900000001201': { // S+U Westhafen
U9: {
label: ['flickr', 'ingolfbln', 7606140134],
platform: ['flickr', 'ingolfbln', 7606128040],
entrance: null
},
},
'900000100051': { // U Weinmeisterstraße
U8: {
label: ['flickr', 'ingolfbln', 6942367173],
platform: ['flickr', 'ingolfbln', 6942388737],
entrance: null
},
},
'900000009104': { // S+U Wedding
U6: {
label: ['flickr', 'ingolfbln', 13366726265],
platform: ['flickr', 'ingolfbln', 13366747765],
entrance: ['flickr', 'ingolfbln', 13366849433]
},
},
'900000120025': { // U Weberwiese
U5: {
label: ['flickr', 'ingolfbln', 6261935322],
platform: ['flickr', 'ingolfbln', 6261917226],
entrance: null
},
},
'900000120004': { // S+U Warschauer Straße
U1: {
label: ['flickr', 'ingolfbln', 7658948668],
platform: ['flickr', 'ingolfbln', 7658942980],
entrance: null
},
},
'900000061101': { // U Walther-Schreiber-Platz
U9: {
label: ['flickr', 'ingolfbln', 8441812101],
platform: ['flickr', 'ingolfbln', 8442900284],
entrance: ['flickr', 'ingolfbln', 8442950484]
},
},
'900000007103': { // U Voltastraße
U8: {
label: ['flickr', 'ingolfbln', 7617740880],
platform: ['flickr', 'ingolfbln', 7617701868],
entrance: null
},
},
'900000130011': { // U Vinetastraße
U2: {
label: ['flickr', 'ingolfbln', 8431271806],
platform: ['flickr', 'ingolfbln', 8430182513],
entrance: ['flickr', 'ingolfbln', 8431209650]
},
},
'900000055101': { // U Viktoria-Luise-Platz
U4: {
label: ['flickr', 'ingolfbln', 7145955841],
platform: ['flickr', 'ingolfbln', 7145950145],
entrance: null
},
},
'900000069271': { // U Ullsteinstraße
U6: {
label: ['flickr', 'ingolfbln', 8430268841],
platform: ['flickr', 'ingolfbln', 8431336368],
entrance: ['flickr', 'ingolfbln', 8431314286]
},
},
'900000023301': { // U Uhlandstraße
U1: {
label: ['flickr', 'ingolfbln', 8389622307],
platform: ['flickr', 'ingolfbln', 8390712494],
entrance: ['flickr', 'ingolfbln', 8390720164]
},
},
'900000003104': { // U Turmstraße
U9: {
label: ['flickr', 'ingolfbln', 9487837043],
platform: ['flickr', 'ingolfbln', 9487950731],
entrance: ['flickr', 'ingolfbln', 9487875321]
},
},
'900000161002': { // U Tierpark
U5: {
label: ['flickr', 'ingolfbln', 6342263740],
platform: ['flickr', 'ingolfbln', 6341467799],
entrance: null
},
},
'900000026201': { // U Theodor-Heuss-Platz
U2: {
label: ['flickr', 'ingolfbln', 15021509277],
platform: ['flickr', 'ingolfbln', 15021516327],
entrance: ['flickr', 'ingolfbln', 15021291699]
},
},
'900000068201': { // S+U Tempelhof
U6: {
// todo: better entrance photo
label: ['flickr', 'ingolfbln', 6286996768],
platform: ['flickr', 'ingolfbln', 6286974820],
entrance: ['flickr', 'ingolfbln', 7965908534]
},
},
'900000016202': { // U Südstern
U7: {
label: ['flickr', 'ingolfbln', 6396587851],
platform: ['flickr', 'ingolfbln', 6396559009],
entrance: null
},
},
'900000120006': { // U Strausberger Platz
U5: {
label: ['flickr', 'ingolfbln', 6261512671],
platform: ['flickr', 'ingolfbln', 6262016490],
entrance: null
},
},
'900000100011': { // U Stadtmitte
U2: {
label: ['flickr', 'ingolfbln', 6478223615],
platform: ['flickr', 'ingolfbln', 6478372559],
entrance: null
},
U6: {
label: ['flickr', 'ingolfbln', 6478660389],
platform: ['flickr', 'ingolfbln', 6478706775],
entrance: null
},
},
'900000100013': { // U Spittelmarkt
U2: {
label: ['flickr', 'ingolfbln', 6315302831],
platform: ['flickr', 'ingolfbln', 7804943762],
entrance: null
},
},
'900000042101': { // U Spichernstraße
U3: {
label: ['commons', 'U-Bahnhof_Spichernstraße_(U3)_20130727_2.jpg'],
platform: ['flickr', 'ingolfbln', 7605884990],
entrance: null
},
U9: {
label: ['flickr', 'ingolfbln', 7606085308],
platform: ['flickr', 'ingolfbln', 7606062008],
entrance: null
},
},
'900000022101': { // U Sophie-Charlotte-Platz
U2: {
label: ['commons', 'Berlin_-_U-Bahnhof_Sophie-Charlotte-Platz_-_Linie_U2_(6945055571).jpg'],
platform: ['flickr', 'ingolfbln', 6945035051],
entrance: null
},
},
'900000035101': { // U Siemensdamm
// todo: missing photo showing name (close-up)
U7: {
label: ['flickr', 'ingolfbln', 8448112575],
platform: ['flickr', 'ingolfbln', 8449137556],
entrance: ['flickr', 'ingolfbln', 8448081863]
},
},
'900000110005': { // U Senefelderplatz
U2: {
label: ['commons', 'Senefelderplatz_plaque.jpg'],
platform: ['flickr', 'ingolfbln', 7804920404],
entrance: null
},
},
'900000100501': { // U Schwartzkopffstraße
// todo: missing photo showing name (close-up)
U6: {
label: ['flickr', 'ingolfbln', 13366448165],
platform: ['flickr', 'ingolfbln', 13366798574],
entrance: ['flickr', 'ingolfbln', 13366397835]
},
},
'900000120009': { // U Samariterstraße
U5: {
label: ['commons', 'Samariterstraße_(15186253620).jpg'],
platform: ['flickr', 'ingolfbln', 6261366635],
entrance: null
},
},
'900000100017': { // U Schillingstraße
U5: {
label: ['commons', 'Schillingstraße_subway_sign_01.JPG'],
platform: ['flickr', 'ingolfbln', 6261633179],
entrance: null
},
},
'900000014102': { // U Schlesisches Tor
U1: {
label: ['flickr', 'ingolfbln', 6319640129],
platform: ['flickr', 'ingolfbln', 6320226072],
entrance: null
},
},
'900000062203': { // U Schloßstraße
U9: {
label: ['flickr', 'ingolfbln', 6661967795],
platform: ['flickr', 'ingolfbln', 6659854511],
entrance: null
},
},
'900000110001': { // S+U Schönhauser Allee
U2: {
label: ['flickr', 'ingolfbln', 7592906382],
platform: ['flickr', 'ingolfbln', 7593090948],
entrance: null
},
},
'900000016201': { // U Schönleinstraße
U8: {
label: ['flickr', 'ingolfbln', 6528982091],
platform: ['flickr', 'ingolfbln', 6528938699],
entrance: null
},
},
'900000023201': { // S+U Zoologischer Garten
U2: {
label: ['flickr', 'pasa', 5864038454],
platform: ['flickr', 'galio', 4610552275],
entrance: null
},
// todo: glynlowe/23075396060 ?
U9: {
label: null,
platform: ['flickr', 'mbell1975', 3793762490],
entrance: null
}
},
'900000083101': { // U Zwickauer Damm
U7: {
label: ['flickr', 'ingolfbln', 15324013144],
platform: ['flickr', 'ingolfbln', 15758852748],
entrance: null
},
}
}
| add entrance for 'Pankstraße'
| photos.js | add entrance for 'Pankstraße' | <ide><path>hotos.js
<ide> U8: {
<ide> label: ['flickr', 'ingolfbln', 7618016404],
<ide> platform: ['flickr', 'ingolfbln', 7618030952],
<del> entrance: null
<add> entrance: ['flickr', 'ingolfbln', 7618136362]
<ide> }
<ide> },
<ide> '900000085104': { // U Paracelsus-Bad |
|
Java | apache-2.0 | c22b0939877fa364c51aae5750ca9e9a37ca613b | 0 | shekibobo/gh4a,edyesed/gh4a,Bloody-Badboy/gh4a,Bloody-Badboy/gh4a,DeLaSalleUniversity-Manila/octodroid-ToastyKrabstix,DeLaSalleUniversity-Manila/octodroid-ToastyKrabstix,slapperwan/gh4a,edyesed/gh4a,shineM/gh4a,shekibobo/gh4a,sauloaguiar/gh4a,AKiniyalocts/gh4a,shineM/gh4a,slapperwan/gh4a,AKiniyalocts/gh4a,sauloaguiar/gh4a | /*
* Copyright 2011 Azwan Adli Abdullah
*
* 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.gh4a.fragment;
import java.util.Arrays;
import java.util.List;
import org.eclipse.egit.github.core.Commit;
import org.eclipse.egit.github.core.Download;
import org.eclipse.egit.github.core.GollumPage;
import org.eclipse.egit.github.core.Issue;
import org.eclipse.egit.github.core.PullRequest;
import org.eclipse.egit.github.core.Release;
import org.eclipse.egit.github.core.Repository;
import org.eclipse.egit.github.core.client.PageIterator;
import org.eclipse.egit.github.core.event.CommitCommentPayload;
import org.eclipse.egit.github.core.event.DownloadPayload;
import org.eclipse.egit.github.core.event.Event;
import org.eclipse.egit.github.core.event.EventRepository;
import org.eclipse.egit.github.core.event.FollowPayload;
import org.eclipse.egit.github.core.event.ForkPayload;
import org.eclipse.egit.github.core.event.GistPayload;
import org.eclipse.egit.github.core.event.GollumPayload;
import org.eclipse.egit.github.core.event.IssueCommentPayload;
import org.eclipse.egit.github.core.event.IssuesPayload;
import org.eclipse.egit.github.core.event.PullRequestPayload;
import org.eclipse.egit.github.core.event.PullRequestReviewCommentPayload;
import org.eclipse.egit.github.core.event.PushPayload;
import org.eclipse.egit.github.core.event.ReleasePayload;
import org.eclipse.egit.github.core.service.EventService;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import com.gh4a.Constants;
import com.gh4a.Gh4Application;
import com.gh4a.R;
import com.gh4a.activities.CompareActivity;
import com.gh4a.activities.ReleaseInfoActivity;
import com.gh4a.activities.WikiListActivity;
import com.gh4a.adapter.FeedAdapter;
import com.gh4a.adapter.RootAdapter;
import com.gh4a.utils.IntentUtils;
import com.gh4a.utils.StringUtils;
import com.gh4a.utils.ToastUtils;
import com.gh4a.utils.UiUtils;
public abstract class EventListFragment extends PagedDataBaseFragment<Event> {
private static final int MENU_USER = 1;
private static final int MENU_REPO = 2;
private static final int MENU_OPEN_ISSUES = 4;
private static final int MENU_ISSUE = 5;
private static final int MENU_GIST = 6;
private static final int MENU_FORKED_REPO = 7;
private static final int MENU_WIKI_IN_BROWSER = 8;
private static final int MENU_PULL_REQ = 9;
private static final int MENU_COMPARE = 10;
private static final int MENU_COMMENT_COMMIT = 11;
private static final int MENU_DOWNLOAD_START = 100;
private static final int MENU_DOWNLOAD_END = 199;
private static final int MENU_PUSH_COMMIT_START = 200;
private String mLogin;
private boolean mIsPrivate;
private FeedAdapter mAdapter;
private static final String[] REPO_EVENTS = new String[] {
Event.TYPE_PUSH, Event.TYPE_ISSUES, Event.TYPE_WATCH, Event.TYPE_CREATE,
Event.TYPE_PULL_REQUEST, Event.TYPE_COMMIT_COMMENT, Event.TYPE_DELETE,
Event.TYPE_DOWNLOAD, Event.TYPE_FORK_APPLY, Event.TYPE_PUBLIC,
Event.TYPE_MEMBER, Event.TYPE_ISSUE_COMMENT
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLogin = getArguments().getString(Constants.User.LOGIN);
mIsPrivate = getArguments().getBoolean("private");
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
registerForContextMenu(getListView());
}
@Override
protected RootAdapter<Event> onCreateAdapter() {
mAdapter = new FeedAdapter(getActivity());
return mAdapter;
}
@Override
protected int getEmptyTextResId() {
return R.string.no_events_found;
}
@Override
protected PageIterator<Event> onCreateIterator() {
EventService eventService = (EventService)
Gh4Application.get(getActivity()).getService(Gh4Application.EVENT_SERVICE);
if (mIsPrivate) {
return eventService.pageUserReceivedEvents(mLogin, true);
}
return eventService.pageUserEvents(mLogin, false);
}
@Override
protected void onItemClick(Event event) {
Gh4Application context = Gh4Application.get(getActivity());
if (FeedAdapter.hasInvalidPayload(event)) {
return;
}
String eventType = event.getType();
EventRepository eventRepo = event.getRepo();
String repoOwner = "";
String repoName = "";
if (eventRepo != null) {
String[] repoNamePart = eventRepo.getName().split("/");
if (repoNamePart.length == 2) {
repoOwner = repoNamePart[0];
repoName = repoNamePart[1];
}
}
if (Arrays.binarySearch(REPO_EVENTS, eventType) >= 0 && eventRepo == null) {
ToastUtils.notFoundMessage(getActivity(), R.plurals.repository);
return;
}
if (Event.TYPE_COMMIT_COMMENT.equals(eventType)) {
CommitCommentPayload payload = (CommitCommentPayload) event.getPayload();
IntentUtils.openCommitInfoActivity(getActivity(), repoOwner, repoName,
payload.getComment().getCommitId(), 0);
} else if (Event.TYPE_CREATE.equals(eventType)) {
IntentUtils.openRepositoryInfoActivity(getActivity(), repoOwner, repoName, null, 0);
} else if (Event.TYPE_DELETE.equals(eventType)) {
IntentUtils.openRepositoryInfoActivity(getActivity(), repoOwner, repoName, null, 0);
} else if (Event.TYPE_DOWNLOAD.equals(eventType)) {
DownloadPayload payload = (DownloadPayload) event.getPayload();
Download download = payload.getDownload();
UiUtils.enqueueDownload(getActivity(), download.getHtmlUrl(), download.getContentType(),
download.getName(), download.getDescription(), null);
} else if (Event.TYPE_FOLLOW.equals(eventType)) {
FollowPayload payload = (FollowPayload) event.getPayload();
IntentUtils.openUserInfoActivity(getActivity(), payload.getTarget());
} else if (Event.TYPE_FORK.equals(eventType)) {
ForkPayload payload = (ForkPayload) event.getPayload();
Repository forkee = payload.getForkee();
if (forkee != null) {
IntentUtils.openRepositoryInfoActivity(getActivity(), forkee);
} else {
ToastUtils.notFoundMessage(getActivity(), R.plurals.repository);
}
} else if (Event.TYPE_FORK_APPLY.equals(eventType)) {
IntentUtils.openRepositoryInfoActivity(getActivity(), repoOwner, repoName, null, 0);
} else if (Event.TYPE_GIST.equals(eventType)) {
GistPayload payload = (GistPayload) event.getPayload();
String login = event.getActor().getLogin();
if (StringUtils.isBlank(login) && payload.getGist() != null
&& payload.getGist().getUser() != null) {
login = payload.getGist().getUser().getLogin();
}
if (!StringUtils.isBlank(login)) {
IntentUtils.openGistActivity(getActivity(), login, payload.getGist().getId(), 0);
}
} else if (Event.TYPE_GOLLUM.equals(eventType)) {
Intent intent = new Intent(getActivity(), WikiListActivity.class);
intent.putExtra(Constants.Repository.OWNER, repoOwner);
intent.putExtra(Constants.Repository.NAME, repoName);
GollumPayload payload = (GollumPayload) event.getPayload();
if (!payload.getPages().isEmpty()) {
intent.putExtra(Constants.Object.OBJECT_SHA, payload.getPages().get(0).getSha());
}
startActivity(intent);
} else if (Event.TYPE_ISSUE_COMMENT.equals(eventType)) {
IssueCommentPayload payload = (IssueCommentPayload) event.getPayload();
Issue issue = payload.getIssue();
PullRequest request = issue != null ? issue.getPullRequest() : null;
if (request != null && request.getHtmlUrl() != null) {
IntentUtils.openPullRequestActivity(getActivity(),
repoOwner, repoName, issue.getNumber());
} else if (issue != null) {
IntentUtils.openIssueActivity(getActivity(), repoOwner, repoName,
issue.getNumber(), issue.getState());
}
} else if (Event.TYPE_ISSUES.equals(eventType)) {
IssuesPayload payload = (IssuesPayload) event.getPayload();
IntentUtils.openIssueActivity(getActivity(), repoOwner, repoName, payload.getIssue().getNumber());
} else if (Event.TYPE_MEMBER.equals(eventType)) {
IntentUtils.openRepositoryInfoActivity(getActivity(), repoOwner, repoName, null, 0);
} else if (Event.TYPE_PUBLIC.equals(eventType)) {
IntentUtils.openRepositoryInfoActivity(getActivity(), repoOwner, repoName, null, 0);
} else if (Event.TYPE_PULL_REQUEST.equals(eventType)) {
PullRequestPayload payload = (PullRequestPayload) event.getPayload();
IntentUtils.openPullRequestActivity(getActivity(), repoOwner, repoName, payload.getNumber());
} else if (Event.TYPE_PULL_REQUEST_REVIEW_COMMENT.equals(eventType)) {
PullRequestReviewCommentPayload payload = (PullRequestReviewCommentPayload) event.getPayload();
IntentUtils.openCommitInfoActivity(getActivity(), repoOwner, repoName,
payload.getComment().getCommitId(), 0);
} else if (Event.TYPE_PUSH.equals(eventType)) {
PushPayload payload = (PushPayload) event.getPayload();
List<Commit> commits = payload.getCommits();
if (commits != null && !commits.isEmpty()) {
if (commits.size() > 1) {
// if commit > 1, then show compare activity
Intent intent = new Intent(context, CompareActivity.class);
intent.putExtra(Constants.Repository.OWNER, repoOwner);
intent.putExtra(Constants.Repository.NAME, repoName);
intent.putExtra(Constants.Repository.HEAD, payload.getHead());
intent.putExtra(Constants.Repository.BASE, payload.getBefore());
startActivity(intent);
} else {
// only 1 commit, then show the commit details
IntentUtils.openCommitInfoActivity(getActivity(), repoOwner, repoName,
payload.getCommits().get(0).getSha(), 0);
}
} else {
IntentUtils.openRepositoryInfoActivity(getActivity(), repoOwner, repoName, null, 0);
}
} else if (Event.TYPE_RELEASE.equals(eventType)) {
ReleasePayload payload = (ReleasePayload) event.getPayload();
Release release = payload.getRelease();
if (release != null) {
Intent intent = new Intent(getActivity(), ReleaseInfoActivity.class);
intent.putExtra(Constants.Release.RELEASE, release);
intent.putExtra(Constants.Release.RELEASER, event.getActor());
intent.putExtra(Constants.Repository.OWNER, repoOwner);
intent.putExtra(Constants.Repository.NAME, repoName);
startActivity(intent);
}
} else if (Event.TYPE_WATCH.equals(eventType)) {
IntentUtils.openRepositoryInfoActivity(getActivity(), repoOwner, repoName, null, 0);
}
}
public abstract int getMenuGroupId();
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
Event event = mAdapter.getItem(info.position);
int groupId = getMenuGroupId();
if (FeedAdapter.hasInvalidPayload(event)) {
return;
}
String eventType = event.getType();
EventRepository eventRepo = event.getRepo();
String[] repoNamePart = eventRepo.getName().split("/");
String repoOwner = repoNamePart.length == 2 ? repoNamePart[0] : null;
menu.setHeaderTitle(R.string.go_to);
/** Common menu */
menu.add(groupId, MENU_USER, Menu.NONE, getString(R.string.menu_user, event.getActor().getLogin()));
if (repoOwner != null) {
menu.add(groupId, MENU_REPO, Menu.NONE, getString(R.string.menu_repo, eventRepo.getName()));
}
if (Event.TYPE_COMMIT_COMMENT.equals(eventType) && repoOwner != null) {
CommitCommentPayload payload = (CommitCommentPayload) event.getPayload();
menu.add(groupId, MENU_COMMENT_COMMIT, Menu.NONE,
getString(R.string.menu_commit, payload.getComment().getCommitId().substring(0, 7)));
} else if (Event.TYPE_DOWNLOAD.equals(eventType)) {
DownloadPayload payload = (DownloadPayload) event.getPayload();
menu.add(groupId, MENU_DOWNLOAD_START, Menu.NONE,
getString(R.string.menu_file, payload.getDownload().getName()));
} else if (Event.TYPE_FOLLOW.equals(eventType)) {
FollowPayload payload = (FollowPayload) event.getPayload();
if (payload.getTarget() != null) {
menu.add(groupId, MENU_USER, Menu.NONE,
getString(R.string.menu_user, payload.getTarget().getLogin()));
}
} else if (Event.TYPE_FORK.equals(eventType)) {
ForkPayload payload = (ForkPayload) event.getPayload();
Repository forkee = payload.getForkee();
if (forkee != null) {
menu.add(groupId, MENU_FORKED_REPO, Menu.NONE,
getString(R.string.menu_fork, forkee.getOwner().getLogin() + "/" + forkee.getName()));
}
} else if (Event.TYPE_GIST.equals(eventType)) {
GistPayload payload = (GistPayload) event.getPayload();
menu.add(groupId, MENU_GIST, Menu.NONE,
getString(R.string.menu_gist, payload.getGist().getId()));
} else if (Event.TYPE_GOLLUM.equals(eventType)) {
menu.add(groupId, MENU_WIKI_IN_BROWSER, Menu.NONE, getString(R.string.menu_wiki));
} else if (Event.TYPE_ISSUE_COMMENT.equals(eventType)) {
menu.add(groupId, MENU_OPEN_ISSUES, Menu.NONE, getString(R.string.menu_issues));
} else if (Event.TYPE_ISSUES.equals(eventType)) {
IssuesPayload payload = (IssuesPayload) event.getPayload();
menu.add(groupId, MENU_ISSUE, Menu.NONE,
getString(R.string.menu_issue, payload.getIssue().getNumber()));
} else if (Event.TYPE_PULL_REQUEST.equals(eventType)) {
PullRequestPayload payload = (PullRequestPayload) event.getPayload();
menu.add(groupId, MENU_PULL_REQ, Menu.NONE, getString(R.string.menu_pull, payload.getNumber()));
} else if (Event.TYPE_PUSH.equals(eventType) && repoOwner != null) {
PushPayload payload = (PushPayload) event.getPayload();
menu.add(groupId, MENU_COMPARE, Menu.NONE,
getString(R.string.menu_compare, payload.getHead()));
List<Commit> commits = payload.getCommits();
for (int i = 0; i < commits.size(); i++) {
menu.add(groupId, MENU_PUSH_COMMIT_START + i, Menu.NONE,
getString(R.string.menu_commit, commits.get(i).getSha()));
}
} else if (Event.TYPE_RELEASE.equals(eventType)) {
ReleasePayload payload = (ReleasePayload) event.getPayload();
List<Download> downloads = payload.getRelease().getAssets();
int count = downloads != null ? downloads.size() : 0;
for (int i = 0; i < count; i++) {
menu.add(groupId, MENU_DOWNLOAD_START + i, Menu.NONE,
getString(R.string.menu_file, downloads.get(i).getName()));
}
}
}
public boolean open(MenuItem item) {
AdapterView.AdapterContextMenuInfo info =
(AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
Event event = mAdapter.getItem(info.position);
String[] repoNamePart = event.getRepo().getName().split("/");
String repoOwner = null;
String repoName = null;
if (repoNamePart.length == 2) {
repoOwner = repoNamePart[0];
repoName = repoNamePart[1];
}
int id = item.getItemId();
if (id == MENU_USER) {
IntentUtils.openUserInfoActivity(getActivity(), event.getActor().getLogin());
} else if (id == MENU_REPO) {
IntentUtils.openRepositoryInfoActivity(getActivity(), repoOwner, repoName, null, 0);
} else if (id >= MENU_PUSH_COMMIT_START || id == MENU_COMMENT_COMMIT) {
if (repoOwner != null) {
String sha = null;
if (Event.TYPE_PUSH.equals(event.getType())) {
int offset = id - MENU_PUSH_COMMIT_START;
sha = ((PushPayload) event.getPayload()).getCommits().get(offset).getSha();
} else if (Event.TYPE_COMMIT_COMMENT.equals(event.getType())) {
sha = ((CommitCommentPayload) event.getPayload()).getComment().getCommitId();
}
if (sha != null) {
IntentUtils.openCommitInfoActivity(getActivity(), repoOwner, repoName, sha, 0);
}
} else {
ToastUtils.notFoundMessage(getActivity(), R.plurals.repository);
}
} else if (id == MENU_OPEN_ISSUES) {
IntentUtils.openIssueListActivity(getActivity(), repoOwner, repoName,
Constants.Issue.STATE_OPEN);
} else if (id == MENU_ISSUE) {
IssuesPayload payload = (IssuesPayload) event.getPayload();
IntentUtils.openIssueActivity(getActivity(), repoOwner, repoName, payload.getIssue().getNumber());
} else if (id == MENU_GIST) {
GistPayload payload = (GistPayload) event.getPayload();
IntentUtils.openGistActivity(getActivity(), payload.getGist().getUser().getLogin(),
payload.getGist().getId(), 0);
} else if (id >= MENU_DOWNLOAD_START && id <= MENU_DOWNLOAD_END) {
Download download = null;
if (Event.TYPE_RELEASE.equals(event.getType())) {
ReleasePayload payload = (ReleasePayload) event.getPayload();
int offset = id - MENU_DOWNLOAD_START;
download = payload.getRelease().getAssets().get(offset);
} else if (Event.TYPE_DOWNLOAD.equals(event.getType())) {
DownloadPayload payload = (DownloadPayload) event.getPayload();
download = payload.getDownload();
}
if (download != null) {
UiUtils.enqueueDownload(getActivity(), download.getHtmlUrl(), download.getContentType(),
download.getName(), download.getDescription(), null);
}
} else if (id == MENU_FORKED_REPO) {
ForkPayload payload = (ForkPayload) event.getPayload();
Repository forkee = payload.getForkee();
if (forkee != null) {
IntentUtils.openRepositoryInfoActivity(getActivity(), forkee);
} else {
ToastUtils.notFoundMessage(getActivity(), R.plurals.repository);
}
} else if (id == MENU_WIKI_IN_BROWSER) {
GollumPayload payload = (GollumPayload) event.getPayload();
List<GollumPage> pages = payload.getPages();
if (pages != null && !pages.isEmpty()) { //TODO: now just open the first page
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(pages.get(0).getHtmlUrl()));
startActivity(intent);
}
} else if (id == MENU_PULL_REQ) {
PullRequestPayload payload = (PullRequestPayload) event.getPayload();
IntentUtils.openPullRequestActivity(getActivity(), repoOwner, repoName, payload.getNumber());
} else if (id == MENU_COMPARE) {
if (repoOwner != null) {
PushPayload payload = (PushPayload) event.getPayload();
Intent intent = new Intent(getActivity(), CompareActivity.class);
intent.putExtra(Constants.Repository.OWNER, repoOwner);
intent.putExtra(Constants.Repository.NAME, repoName);
intent.putExtra(Constants.Repository.HEAD, payload.getHead());
intent.putExtra(Constants.Repository.BASE, payload.getBefore());
startActivity(intent);
}
}
return true;
}
}
| src/com/gh4a/fragment/EventListFragment.java | /*
* Copyright 2011 Azwan Adli Abdullah
*
* 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.gh4a.fragment;
import java.util.Arrays;
import java.util.List;
import org.eclipse.egit.github.core.Commit;
import org.eclipse.egit.github.core.Download;
import org.eclipse.egit.github.core.GollumPage;
import org.eclipse.egit.github.core.Issue;
import org.eclipse.egit.github.core.PullRequest;
import org.eclipse.egit.github.core.Release;
import org.eclipse.egit.github.core.Repository;
import org.eclipse.egit.github.core.client.PageIterator;
import org.eclipse.egit.github.core.event.CommitCommentPayload;
import org.eclipse.egit.github.core.event.DownloadPayload;
import org.eclipse.egit.github.core.event.Event;
import org.eclipse.egit.github.core.event.EventRepository;
import org.eclipse.egit.github.core.event.FollowPayload;
import org.eclipse.egit.github.core.event.ForkPayload;
import org.eclipse.egit.github.core.event.GistPayload;
import org.eclipse.egit.github.core.event.GollumPayload;
import org.eclipse.egit.github.core.event.IssueCommentPayload;
import org.eclipse.egit.github.core.event.IssuesPayload;
import org.eclipse.egit.github.core.event.PullRequestPayload;
import org.eclipse.egit.github.core.event.PullRequestReviewCommentPayload;
import org.eclipse.egit.github.core.event.PushPayload;
import org.eclipse.egit.github.core.event.ReleasePayload;
import org.eclipse.egit.github.core.service.EventService;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import com.gh4a.Constants;
import com.gh4a.Gh4Application;
import com.gh4a.R;
import com.gh4a.activities.CompareActivity;
import com.gh4a.activities.ReleaseInfoActivity;
import com.gh4a.activities.WikiListActivity;
import com.gh4a.adapter.FeedAdapter;
import com.gh4a.adapter.RootAdapter;
import com.gh4a.utils.IntentUtils;
import com.gh4a.utils.StringUtils;
import com.gh4a.utils.ToastUtils;
import com.gh4a.utils.UiUtils;
public abstract class EventListFragment extends PagedDataBaseFragment<Event> {
private static final int MENU_USER = 1;
private static final int MENU_REPO = 2;
private static final int MENU_OPEN_ISSUES = 4;
private static final int MENU_ISSUE = 5;
private static final int MENU_GIST = 6;
private static final int MENU_FORKED_REPO = 7;
private static final int MENU_WIKI_IN_BROWSER = 8;
private static final int MENU_PULL_REQ = 9;
private static final int MENU_COMPARE = 10;
private static final int MENU_COMMENT_COMMIT = 11;
private static final int MENU_DOWNLOAD_START = 100;
private static final int MENU_DOWNLOAD_END = 199;
private static final int MENU_PUSH_COMMIT_START = 200;
private String mLogin;
private boolean mIsPrivate;
private FeedAdapter mAdapter;
private static final String[] REPO_EVENTS = new String[] {
Event.TYPE_PUSH, Event.TYPE_ISSUES, Event.TYPE_WATCH, Event.TYPE_CREATE,
Event.TYPE_PULL_REQUEST, Event.TYPE_COMMIT_COMMENT, Event.TYPE_DELETE,
Event.TYPE_DOWNLOAD, Event.TYPE_FORK_APPLY, Event.TYPE_PUBLIC,
Event.TYPE_MEMBER, Event.TYPE_ISSUE_COMMENT
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLogin = getArguments().getString(Constants.User.LOGIN);
mIsPrivate = getArguments().getBoolean("private");
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
registerForContextMenu(getListView());
}
@Override
protected RootAdapter<Event> onCreateAdapter() {
mAdapter = new FeedAdapter(getActivity());
return mAdapter;
}
@Override
protected int getEmptyTextResId() {
return R.string.no_events_found;
}
@Override
protected PageIterator<Event> onCreateIterator() {
EventService eventService = (EventService)
Gh4Application.get(getActivity()).getService(Gh4Application.EVENT_SERVICE);
if (mIsPrivate) {
return eventService.pageUserReceivedEvents(mLogin, true);
}
return eventService.pageUserEvents(mLogin, false);
}
@Override
protected void onItemClick(Event event) {
Gh4Application context = Gh4Application.get(getActivity());
if (!FeedAdapter.hasInvalidPayload(event)) {
return;
}
String eventType = event.getType();
EventRepository eventRepo = event.getRepo();
String repoOwner = "";
String repoName = "";
if (eventRepo != null) {
String[] repoNamePart = eventRepo.getName().split("/");
if (repoNamePart.length == 2) {
repoOwner = repoNamePart[0];
repoName = repoNamePart[1];
}
}
if (Arrays.binarySearch(REPO_EVENTS, eventType) >= 0 && eventRepo == null) {
ToastUtils.notFoundMessage(getActivity(), R.plurals.repository);
return;
}
if (Event.TYPE_COMMIT_COMMENT.equals(eventType)) {
CommitCommentPayload payload = (CommitCommentPayload) event.getPayload();
IntentUtils.openCommitInfoActivity(getActivity(), repoOwner, repoName,
payload.getComment().getCommitId(), 0);
} else if (Event.TYPE_CREATE.equals(eventType)) {
IntentUtils.openRepositoryInfoActivity(getActivity(), repoOwner, repoName, null, 0);
} else if (Event.TYPE_DELETE.equals(eventType)) {
IntentUtils.openRepositoryInfoActivity(getActivity(), repoOwner, repoName, null, 0);
} else if (Event.TYPE_DOWNLOAD.equals(eventType)) {
DownloadPayload payload = (DownloadPayload) event.getPayload();
Download download = payload.getDownload();
UiUtils.enqueueDownload(getActivity(), download.getHtmlUrl(), download.getContentType(),
download.getName(), download.getDescription(), null);
} else if (Event.TYPE_FOLLOW.equals(eventType)) {
FollowPayload payload = (FollowPayload) event.getPayload();
IntentUtils.openUserInfoActivity(getActivity(), payload.getTarget());
} else if (Event.TYPE_FORK.equals(eventType)) {
ForkPayload payload = (ForkPayload) event.getPayload();
Repository forkee = payload.getForkee();
if (forkee != null) {
IntentUtils.openRepositoryInfoActivity(getActivity(), forkee);
} else {
ToastUtils.notFoundMessage(getActivity(), R.plurals.repository);
}
} else if (Event.TYPE_FORK_APPLY.equals(eventType)) {
IntentUtils.openRepositoryInfoActivity(getActivity(), repoOwner, repoName, null, 0);
} else if (Event.TYPE_GIST.equals(eventType)) {
GistPayload payload = (GistPayload) event.getPayload();
String login = event.getActor().getLogin();
if (StringUtils.isBlank(login) && payload.getGist() != null
&& payload.getGist().getUser() != null) {
login = payload.getGist().getUser().getLogin();
}
if (!StringUtils.isBlank(login)) {
IntentUtils.openGistActivity(getActivity(), login, payload.getGist().getId(), 0);
}
} else if (Event.TYPE_GOLLUM.equals(eventType)) {
Intent intent = new Intent(getActivity(), WikiListActivity.class);
intent.putExtra(Constants.Repository.OWNER, repoOwner);
intent.putExtra(Constants.Repository.NAME, repoName);
GollumPayload payload = (GollumPayload) event.getPayload();
if (!payload.getPages().isEmpty()) {
intent.putExtra(Constants.Object.OBJECT_SHA, payload.getPages().get(0).getSha());
}
startActivity(intent);
} else if (Event.TYPE_ISSUE_COMMENT.equals(eventType)) {
IssueCommentPayload payload = (IssueCommentPayload) event.getPayload();
Issue issue = payload.getIssue();
PullRequest request = issue != null ? issue.getPullRequest() : null;
if (request != null && request.getHtmlUrl() != null) {
IntentUtils.openPullRequestActivity(getActivity(),
repoOwner, repoName, issue.getNumber());
} else if (issue != null) {
IntentUtils.openIssueActivity(getActivity(), repoOwner, repoName,
issue.getNumber(), issue.getState());
}
} else if (Event.TYPE_ISSUES.equals(eventType)) {
IssuesPayload payload = (IssuesPayload) event.getPayload();
IntentUtils.openIssueActivity(getActivity(), repoOwner, repoName, payload.getIssue().getNumber());
} else if (Event.TYPE_MEMBER.equals(eventType)) {
IntentUtils.openRepositoryInfoActivity(getActivity(), repoOwner, repoName, null, 0);
} else if (Event.TYPE_PUBLIC.equals(eventType)) {
IntentUtils.openRepositoryInfoActivity(getActivity(), repoOwner, repoName, null, 0);
} else if (Event.TYPE_PULL_REQUEST.equals(eventType)) {
PullRequestPayload payload = (PullRequestPayload) event.getPayload();
IntentUtils.openPullRequestActivity(getActivity(), repoOwner, repoName, payload.getNumber());
} else if (Event.TYPE_PULL_REQUEST_REVIEW_COMMENT.equals(eventType)) {
PullRequestReviewCommentPayload payload = (PullRequestReviewCommentPayload) event.getPayload();
IntentUtils.openCommitInfoActivity(getActivity(), repoOwner, repoName,
payload.getComment().getCommitId(), 0);
} else if (Event.TYPE_PUSH.equals(eventType)) {
PushPayload payload = (PushPayload) event.getPayload();
List<Commit> commits = payload.getCommits();
if (commits != null && !commits.isEmpty()) {
if (commits.size() > 1) {
// if commit > 1, then show compare activity
Intent intent = new Intent(context, CompareActivity.class);
intent.putExtra(Constants.Repository.OWNER, repoOwner);
intent.putExtra(Constants.Repository.NAME, repoName);
intent.putExtra(Constants.Repository.HEAD, payload.getHead());
intent.putExtra(Constants.Repository.BASE, payload.getBefore());
startActivity(intent);
} else {
// only 1 commit, then show the commit details
IntentUtils.openCommitInfoActivity(getActivity(), repoOwner, repoName,
payload.getCommits().get(0).getSha(), 0);
}
} else {
IntentUtils.openRepositoryInfoActivity(getActivity(), repoOwner, repoName, null, 0);
}
} else if (Event.TYPE_RELEASE.equals(eventType)) {
ReleasePayload payload = (ReleasePayload) event.getPayload();
Release release = payload.getRelease();
if (release != null) {
Intent intent = new Intent(getActivity(), ReleaseInfoActivity.class);
intent.putExtra(Constants.Release.RELEASE, release);
intent.putExtra(Constants.Release.RELEASER, event.getActor());
intent.putExtra(Constants.Repository.OWNER, repoOwner);
intent.putExtra(Constants.Repository.NAME, repoName);
startActivity(intent);
}
} else if (Event.TYPE_WATCH.equals(eventType)) {
IntentUtils.openRepositoryInfoActivity(getActivity(), repoOwner, repoName, null, 0);
}
}
public abstract int getMenuGroupId();
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
Event event = mAdapter.getItem(info.position);
int groupId = getMenuGroupId();
if (!FeedAdapter.hasInvalidPayload(event)) {
return;
}
String eventType = event.getType();
EventRepository eventRepo = event.getRepo();
String[] repoNamePart = eventRepo.getName().split("/");
String repoOwner = repoNamePart.length == 2 ? repoNamePart[0] : null;
menu.setHeaderTitle(R.string.go_to);
/** Common menu */
menu.add(groupId, MENU_USER, Menu.NONE, getString(R.string.menu_user, event.getActor().getLogin()));
if (repoOwner != null) {
menu.add(groupId, MENU_REPO, Menu.NONE, getString(R.string.menu_repo, eventRepo.getName()));
}
if (Event.TYPE_COMMIT_COMMENT.equals(eventType) && repoOwner != null) {
CommitCommentPayload payload = (CommitCommentPayload) event.getPayload();
menu.add(groupId, MENU_COMMENT_COMMIT, Menu.NONE,
getString(R.string.menu_commit, payload.getComment().getCommitId().substring(0, 7)));
} else if (Event.TYPE_DOWNLOAD.equals(eventType)) {
DownloadPayload payload = (DownloadPayload) event.getPayload();
menu.add(groupId, MENU_DOWNLOAD_START, Menu.NONE,
getString(R.string.menu_file, payload.getDownload().getName()));
} else if (Event.TYPE_FOLLOW.equals(eventType)) {
FollowPayload payload = (FollowPayload) event.getPayload();
if (payload.getTarget() != null) {
menu.add(groupId, MENU_USER, Menu.NONE,
getString(R.string.menu_user, payload.getTarget().getLogin()));
}
} else if (Event.TYPE_FORK.equals(eventType)) {
ForkPayload payload = (ForkPayload) event.getPayload();
Repository forkee = payload.getForkee();
if (forkee != null) {
menu.add(groupId, MENU_FORKED_REPO, Menu.NONE,
getString(R.string.menu_fork, forkee.getOwner().getLogin() + "/" + forkee.getName()));
}
} else if (Event.TYPE_GIST.equals(eventType)) {
GistPayload payload = (GistPayload) event.getPayload();
menu.add(groupId, MENU_GIST, Menu.NONE,
getString(R.string.menu_gist, payload.getGist().getId()));
} else if (Event.TYPE_GOLLUM.equals(eventType)) {
menu.add(groupId, MENU_WIKI_IN_BROWSER, Menu.NONE, getString(R.string.menu_wiki));
} else if (Event.TYPE_ISSUE_COMMENT.equals(eventType)) {
menu.add(groupId, MENU_OPEN_ISSUES, Menu.NONE, getString(R.string.menu_issues));
} else if (Event.TYPE_ISSUES.equals(eventType)) {
IssuesPayload payload = (IssuesPayload) event.getPayload();
menu.add(groupId, MENU_ISSUE, Menu.NONE,
getString(R.string.menu_issue, payload.getIssue().getNumber()));
} else if (Event.TYPE_PULL_REQUEST.equals(eventType)) {
PullRequestPayload payload = (PullRequestPayload) event.getPayload();
menu.add(groupId, MENU_PULL_REQ, Menu.NONE, getString(R.string.menu_pull, payload.getNumber()));
} else if (Event.TYPE_PUSH.equals(eventType) && repoOwner != null) {
PushPayload payload = (PushPayload) event.getPayload();
menu.add(groupId, MENU_COMPARE, Menu.NONE,
getString(R.string.menu_compare, payload.getHead()));
List<Commit> commits = payload.getCommits();
for (int i = 0; i < commits.size(); i++) {
menu.add(groupId, MENU_PUSH_COMMIT_START + i, Menu.NONE,
getString(R.string.menu_commit, commits.get(i).getSha()));
}
} else if (Event.TYPE_RELEASE.equals(eventType)) {
ReleasePayload payload = (ReleasePayload) event.getPayload();
List<Download> downloads = payload.getRelease().getAssets();
int count = downloads != null ? downloads.size() : 0;
for (int i = 0; i < count; i++) {
menu.add(groupId, MENU_DOWNLOAD_START + i, Menu.NONE,
getString(R.string.menu_file, downloads.get(i).getName()));
}
}
}
public boolean open(MenuItem item) {
AdapterView.AdapterContextMenuInfo info =
(AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
Event event = mAdapter.getItem(info.position);
String[] repoNamePart = event.getRepo().getName().split("/");
String repoOwner = null;
String repoName = null;
if (repoNamePart.length == 2) {
repoOwner = repoNamePart[0];
repoName = repoNamePart[1];
}
int id = item.getItemId();
if (id == MENU_USER) {
IntentUtils.openUserInfoActivity(getActivity(), event.getActor().getLogin());
} else if (id == MENU_REPO) {
IntentUtils.openRepositoryInfoActivity(getActivity(), repoOwner, repoName, null, 0);
} else if (id >= MENU_PUSH_COMMIT_START || id == MENU_COMMENT_COMMIT) {
if (repoOwner != null) {
String sha = null;
if (Event.TYPE_PUSH.equals(event.getType())) {
int offset = id - MENU_PUSH_COMMIT_START;
sha = ((PushPayload) event.getPayload()).getCommits().get(offset).getSha();
} else if (Event.TYPE_COMMIT_COMMENT.equals(event.getType())) {
sha = ((CommitCommentPayload) event.getPayload()).getComment().getCommitId();
}
if (sha != null) {
IntentUtils.openCommitInfoActivity(getActivity(), repoOwner, repoName, sha, 0);
}
} else {
ToastUtils.notFoundMessage(getActivity(), R.plurals.repository);
}
} else if (id == MENU_OPEN_ISSUES) {
IntentUtils.openIssueListActivity(getActivity(), repoOwner, repoName,
Constants.Issue.STATE_OPEN);
} else if (id == MENU_ISSUE) {
IssuesPayload payload = (IssuesPayload) event.getPayload();
IntentUtils.openIssueActivity(getActivity(), repoOwner, repoName, payload.getIssue().getNumber());
} else if (id == MENU_GIST) {
GistPayload payload = (GistPayload) event.getPayload();
IntentUtils.openGistActivity(getActivity(), payload.getGist().getUser().getLogin(),
payload.getGist().getId(), 0);
} else if (id >= MENU_DOWNLOAD_START && id <= MENU_DOWNLOAD_END) {
Download download = null;
if (Event.TYPE_RELEASE.equals(event.getType())) {
ReleasePayload payload = (ReleasePayload) event.getPayload();
int offset = id - MENU_DOWNLOAD_START;
download = payload.getRelease().getAssets().get(offset);
} else if (Event.TYPE_DOWNLOAD.equals(event.getType())) {
DownloadPayload payload = (DownloadPayload) event.getPayload();
download = payload.getDownload();
}
if (download != null) {
UiUtils.enqueueDownload(getActivity(), download.getHtmlUrl(), download.getContentType(),
download.getName(), download.getDescription(), null);
}
} else if (id == MENU_FORKED_REPO) {
ForkPayload payload = (ForkPayload) event.getPayload();
Repository forkee = payload.getForkee();
if (forkee != null) {
IntentUtils.openRepositoryInfoActivity(getActivity(), forkee);
} else {
ToastUtils.notFoundMessage(getActivity(), R.plurals.repository);
}
} else if (id == MENU_WIKI_IN_BROWSER) {
GollumPayload payload = (GollumPayload) event.getPayload();
List<GollumPage> pages = payload.getPages();
if (pages != null && !pages.isEmpty()) { //TODO: now just open the first page
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(pages.get(0).getHtmlUrl()));
startActivity(intent);
}
} else if (id == MENU_PULL_REQ) {
PullRequestPayload payload = (PullRequestPayload) event.getPayload();
IntentUtils.openPullRequestActivity(getActivity(), repoOwner, repoName, payload.getNumber());
} else if (id == MENU_COMPARE) {
if (repoOwner != null) {
PushPayload payload = (PushPayload) event.getPayload();
Intent intent = new Intent(getActivity(), CompareActivity.class);
intent.putExtra(Constants.Repository.OWNER, repoOwner);
intent.putExtra(Constants.Repository.NAME, repoName);
intent.putExtra(Constants.Repository.HEAD, payload.getHead());
intent.putExtra(Constants.Repository.BASE, payload.getBefore());
startActivity(intent);
}
}
return true;
}
}
| Fix valid payload checking
| src/com/gh4a/fragment/EventListFragment.java | Fix valid payload checking | <ide><path>rc/com/gh4a/fragment/EventListFragment.java
<ide> protected void onItemClick(Event event) {
<ide> Gh4Application context = Gh4Application.get(getActivity());
<ide>
<del> if (!FeedAdapter.hasInvalidPayload(event)) {
<add> if (FeedAdapter.hasInvalidPayload(event)) {
<ide> return;
<ide> }
<ide>
<ide> Event event = mAdapter.getItem(info.position);
<ide> int groupId = getMenuGroupId();
<ide>
<del> if (!FeedAdapter.hasInvalidPayload(event)) {
<add> if (FeedAdapter.hasInvalidPayload(event)) {
<ide> return;
<ide> }
<ide> |
|
Java | apache-2.0 | 82e55ebf1fc81e654ebcd3b2a99e24065784d032 | 0 | svn2github/commons-vfs2,svn2github/commons-vfs2,svn2github/commons-vfs2 | /*
* 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.vfs2.provider.ftp;
import java.net.Proxy;
import org.apache.commons.net.ftp.parser.FTPFileEntryParserFactory;
import org.apache.commons.vfs2.FileSystem;
import org.apache.commons.vfs2.FileSystemConfigBuilder;
import org.apache.commons.vfs2.FileSystemOptions;
/**
* The config builder for various ftp configuration options.
*/
public class FtpFileSystemConfigBuilder extends FileSystemConfigBuilder
{
private static final String _PREFIX = FtpFileSystemConfigBuilder.class.getName();
private static final FtpFileSystemConfigBuilder BUILDER = new FtpFileSystemConfigBuilder();
private static final String CONNECT_TIMEOUT = _PREFIX + ".CONNECT_TIMEOUT";
private static final String DATA_TIMEOUT = _PREFIX + ".DATA_TIMEOUT";
private static final String DEFAULT_DATE_FORMAT = _PREFIX + ".DEFAULT_DATE_FORMAT";
private static final String ENCODING = _PREFIX + ".ENCODING";
private static final String FACTORY_KEY = FTPFileEntryParserFactory.class.getName() + ".KEY";
private static final String FILE_TYPE = _PREFIX + ".FILE_TYPE";
private static final String PASSIVE_MODE = _PREFIX + ".PASSIVE";
private static final String PROXY = _PREFIX + ".PROXY";
private static final String RECENT_DATE_FORMAT = _PREFIX + ".RECENT_DATE_FORMAT";
private static final String SERVER_LANGUAGE_CODE = _PREFIX + ".SERVER_LANGUAGE_CODE";
private static final String SERVER_TIME_ZONE_ID = _PREFIX + ".SERVER_TIME_ZONE_ID";
private static final String SHORT_MONTH_NAMES = _PREFIX + ".SHORT_MONTH_NAMES";
private static final String SO_TIMEOUT = _PREFIX + ".SO_TIMEOUT";
private static final String USER_DIR_IS_ROOT = _PREFIX + ".USER_DIR_IS_ROOT";
/**
* Gets the singleton instance.
*
* @return the singleton instance.
*/
public static FtpFileSystemConfigBuilder getInstance()
{
return BUILDER;
}
private FtpFileSystemConfigBuilder()
{
super("ftp.");
}
/** @since 2.1 */
protected FtpFileSystemConfigBuilder(final String prefix) {
super(prefix);
}
@Override
protected Class<? extends FileSystem> getConfigClass()
{
return FtpFileSystem.class;
}
/**
* Gets the timeout in milliseconds to use for the socket connection.
*
* @param opts The FileSystemOptions.
* @return The timeout in milliseconds to use for the socket connection.
* @since 2.1
*/
public Integer getConnectTimeout(final FileSystemOptions opts)
{
return getInteger(opts, CONNECT_TIMEOUT);
}
/**
* @param opts The FileSystemOptions.
* @return The encoding.
* @since 2.0
* */
public String getControlEncoding(final FileSystemOptions opts)
{
return getString(opts, ENCODING);
}
/**
* @param opts The FileSystemOptions.
* @return The timeout for opening the data channel as an Integer.
* @see #setDataTimeout
*/
public Integer getDataTimeout(final FileSystemOptions opts)
{
return getInteger(opts, DATA_TIMEOUT);
}
/**
* Get the default date format used by the server. See {@link org.apache.commons.net.ftp.FTPClientConfig}
* for details and examples.
*
* @param opts The FileSystemOptions
* @return The default date format.
*/
public String getDefaultDateFormat(final FileSystemOptions opts)
{
return getString(opts, DEFAULT_DATE_FORMAT);
}
/**
* @param opts The FileSystemOptions.
* @see #setEntryParser
* @return the key to the EntryParser.
*/
public String getEntryParser(final FileSystemOptions opts)
{
return getString(opts, FACTORY_KEY);
}
/**
* @param opts The FlleSystemOptions.
* @see #setEntryParserFactory
* @return An FTPFileEntryParserFactory.
*/
public FTPFileEntryParserFactory getEntryParserFactory(final FileSystemOptions opts)
{
return (FTPFileEntryParserFactory) getParam(opts, FTPFileEntryParserFactory.class.getName());
}
/**
* Gets the file type parameter.
*
* @param opts The FileSystemOptions.
* @return A FtpFileType
* @since 2.1
*/
public FtpFileType getFileType(final FileSystemOptions opts)
{
return getEnum(FtpFileType.class, opts, FILE_TYPE);
}
/**
* @param opts The FileSystemOptions.
* @return true if passive mode is set.
* @see #setPassiveMode
*/
public Boolean getPassiveMode(final FileSystemOptions opts)
{
return getBoolean(opts, PASSIVE_MODE);
}
/**
* Gets the Proxy.
*
* @param opts The FileSystemOptions.
* @return the Proxy
* @since 2.1
*/
public Proxy getProxy(final FileSystemOptions opts)
{
return (Proxy) this.getParam(opts, PROXY);
}
/**
* See {@link org.apache.commons.net.ftp.FTPClientConfig} for details and examples.
*
* @param opts The FileSystemOptions.
* @return The recent date format.
*/
public String getRecentDateFormat(final FileSystemOptions opts)
{
return getString(opts, RECENT_DATE_FORMAT);
}
/**
* Get the language code used by the server. See {@link org.apache.commons.net.ftp.FTPClientConfig}
* for details and examples.
*
* @param opts The FilesystemOptions.
* @return The language code of the server.
*/
public String getServerLanguageCode(final FileSystemOptions opts)
{
return getString(opts, SERVER_LANGUAGE_CODE);
}
/**
* See {@link org.apache.commons.net.ftp.FTPClientConfig} for details and examples.
*
* @param opts The FileSystemOptions.
* @return The server timezone id.
*/
public String getServerTimeZoneId(final FileSystemOptions opts)
{
return getString(opts, SERVER_TIME_ZONE_ID);
}
/**
* See {@link org.apache.commons.net.ftp.FTPClientConfig} for details and examples.
*
* @param opts The FileSystemOptions.
* @return An array of short month names.
*/
public String[] getShortMonthNames(final FileSystemOptions opts)
{
return (String[]) getParam(opts, SHORT_MONTH_NAMES);
}
/**
* @param opts The FileSystem options.
* @return The timeout value.
* @see #getDataTimeout
* @since 2.0
*/
public Integer getSoTimeout(final FileSystemOptions opts)
{
return getInteger(opts, SO_TIMEOUT);
}
/**
* Returns {@link Boolean#TRUE} if VFS should treat the user directory as the root directory. Defaults to
* <code>Boolean.TRUE</code> if the method {@link #setUserDirIsRoot(FileSystemOptions, boolean)} has not been
* invoked.
*
* @param opts
* The FileSystemOptions.
* @return <code>Boolean.TRUE</code> if VFS treats the user directory as the root directory.
* @see #setUserDirIsRoot
*/
public Boolean getUserDirIsRoot(final FileSystemOptions opts)
{
return getBoolean(opts, USER_DIR_IS_ROOT, Boolean.TRUE);
}
/**
* Sets the timeout for the initial control connection.
* <p>
* If you set the connectTimeout to {@code null} no connectTimeout will be set.
*
* @param opts The FileSystemOptions.
* @param connectTimeout the timeout value in milliseconds
* @since 2.1
*/
public void setConnectTimeout(final FileSystemOptions opts, final Integer connectTimeout)
{
setParam(opts, CONNECT_TIMEOUT, connectTimeout);
}
/**
* See {@link org.apache.commons.net.ftp.FTP#setControlEncoding} for details and examples.
*
* @param opts The FileSystemOptions.
* @param encoding the encoding to use
* @since 2.0
*/
public void setControlEncoding(final FileSystemOptions opts, final String encoding)
{
setParam(opts, ENCODING, encoding);
}
/**
* Set the data timeout for the ftp client.
* <p>
* If you set the {@code dataTimeout} to null no dataTimeout will be set on the
* ftp client.
*
* @param opts The FileSystemOptions.
* @param dataTimeout The timeout value.
*/
public void setDataTimeout(final FileSystemOptions opts, final Integer dataTimeout)
{
setParam(opts, DATA_TIMEOUT, dataTimeout);
}
/**
* Set the default date format used by the server. See {@link org.apache.commons.net.ftp.FTPClientConfig}
* for details and examples.
*
* @param opts The FileSystemOptions.
* @param defaultDateFormat The default date format.
*/
public void setDefaultDateFormat(final FileSystemOptions opts, final String defaultDateFormat)
{
setParam(opts, DEFAULT_DATE_FORMAT, defaultDateFormat);
}
/**
* Set the FQCN of your FileEntryParser used to parse the directory listing from your server.
* <p>
* If you do not use the default commons-net FTPFileEntryParserFactory e.g. by using
* {@link #setEntryParserFactory} this is the "key" parameter passed as argument into your
* custom factory.
*
* @param opts The FileSystemOptions.
* @param key The key.
*/
public void setEntryParser(final FileSystemOptions opts, final String key)
{
setParam(opts, FACTORY_KEY, key);
}
/**
* FTPFileEntryParserFactory which will be used for ftp-entry parsing.
*
* @param opts The FileSystemOptions.
* @param factory instance of your factory
*/
public void setEntryParserFactory(final FileSystemOptions opts, final FTPFileEntryParserFactory factory)
{
setParam(opts, FTPFileEntryParserFactory.class.getName(), factory);
}
/**
* Sets the file type parameter.
*
* @param opts The FileSystemOptions.
* @param ftpFileType A FtpFileType
* @since 2.1
*/
public void setFileType(final FileSystemOptions opts, final FtpFileType ftpFileType)
{
setParam(opts, FILE_TYPE, ftpFileType);
}
/**
* Enter into passive mode.
*
* @param opts The FileSystemOptions.
* @param passiveMode true if passive mode should be used.
*/
public void setPassiveMode(final FileSystemOptions opts, final boolean passiveMode)
{
setParam(opts, PASSIVE_MODE, passiveMode ? Boolean.TRUE : Boolean.FALSE);
}
/**
* Sets the Proxy.
* <P>
* You might need to make sure that {@link #setPassiveMode(FileSystemOptions, boolean) passive mode}
* is activated.
*
* @param opts the FileSystem options.
* @param proxy the Proxy
* @since 2.1
*/
public void setProxy(final FileSystemOptions opts, Proxy proxy)
{
setParam(opts, PROXY, proxy);
}
/**
* See {@link org.apache.commons.net.ftp.FTPClientConfig} for details and examples.
*
* @param opts The FileSystemOptions.
* @param recentDateFormat The recent date format.
*/
public void setRecentDateFormat(final FileSystemOptions opts, final String recentDateFormat)
{
setParam(opts, RECENT_DATE_FORMAT, recentDateFormat);
}
/**
* Set the language code used by the server. See {@link org.apache.commons.net.ftp.FTPClientConfig}
* for details and examples.
*
* @param opts The FileSystemOptions.
* @param serverLanguageCode The servers language code.
*/
public void setServerLanguageCode(final FileSystemOptions opts, final String serverLanguageCode)
{
setParam(opts, SERVER_LANGUAGE_CODE, serverLanguageCode);
}
/**
* See {@link org.apache.commons.net.ftp.FTPClientConfig} for details and examples.
*
* @param opts The FileSystemOptions.
* @param serverTimeZoneId The server timezone id.
*/
public void setServerTimeZoneId(final FileSystemOptions opts, final String serverTimeZoneId)
{
setParam(opts, SERVER_TIME_ZONE_ID, serverTimeZoneId);
}
/**
* See {@link org.apache.commons.net.ftp.FTPClientConfig} for details and examples.
*
* @param opts The FileSystemOptions.
* @param shortMonthNames an array of short month name Strings.
*/
public void setShortMonthNames(final FileSystemOptions opts, final String[] shortMonthNames)
{
String[] clone = null;
if (shortMonthNames != null)
{
clone = new String[shortMonthNames.length];
System.arraycopy(shortMonthNames, 0, clone, 0, shortMonthNames.length);
}
setParam(opts, SHORT_MONTH_NAMES, clone);
}
/**
* Sets the socket timeout for the FTP client.
* <p>
* If you set the {@code soTimeout} to null no socket timeout will be set on the
* ftp client.
*
* @param opts The FileSystem options.
* @param soTimeout The timeout value.
* @since 2.0
*/
public void setSoTimeout(final FileSystemOptions opts, final Integer soTimeout)
{
setParam(opts, SO_TIMEOUT, soTimeout);
}
/**
* Use user directory as root (do not change to fs root).
*
* @param opts The FileSystemOptions.
* @param userDirIsRoot true if the user directory should be treated as the root.
*/
public void setUserDirIsRoot(final FileSystemOptions opts, final boolean userDirIsRoot)
{
setParam(opts, USER_DIR_IS_ROOT, userDirIsRoot ? Boolean.TRUE : Boolean.FALSE);
}
}
| core/src/main/java/org/apache/commons/vfs2/provider/ftp/FtpFileSystemConfigBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.ftp;
import java.net.Proxy;
import org.apache.commons.net.ftp.parser.FTPFileEntryParserFactory;
import org.apache.commons.vfs2.FileSystem;
import org.apache.commons.vfs2.FileSystemConfigBuilder;
import org.apache.commons.vfs2.FileSystemOptions;
/**
* The config builder for various ftp configuration options.
*/
public class FtpFileSystemConfigBuilder extends FileSystemConfigBuilder
{
private static final String _PREFIX = FtpFileSystemConfigBuilder.class.getName();
private static final FtpFileSystemConfigBuilder BUILDER = new FtpFileSystemConfigBuilder();
private static final String CONNECT_TIMEOUT = _PREFIX + ".CONNECT_TIMEOUT";
private static final String DATA_TIMEOUT = _PREFIX + ".DATA_TIMEOUT";
private static final String DEFAULT_DATE_FORMAT = _PREFIX + ".DEFAULT_DATE_FORMAT";
private static final String ENCODING = _PREFIX + ".ENCODING";
private static final String FACTORY_KEY = FTPFileEntryParserFactory.class.getName() + ".KEY";
private static final String FILE_TYPE = _PREFIX + ".FILE_TYPE";
private static final String PASSIVE_MODE = _PREFIX + ".PASSIVE";
private static final String PROXY = _PREFIX + ".PROXY";
private static final String RECENT_DATE_FORMAT = _PREFIX + ".RECENT_DATE_FORMAT";
private static final String SERVER_LANGUAGE_CODE = _PREFIX + ".SERVER_LANGUAGE_CODE";
private static final String SERVER_TIME_ZONE_ID = _PREFIX + ".SERVER_TIME_ZONE_ID";
private static final String SHORT_MONTH_NAMES = _PREFIX + ".SHORT_MONTH_NAMES";
private static final String SO_TIMEOUT = _PREFIX + ".SO_TIMEOUT";
private static final String USER_DIR_IS_ROOT = _PREFIX + ".USER_DIR_IS_ROOT";
/**
* Gets the singleton instance.
*
* @return the singleton instance.
*/
public static FtpFileSystemConfigBuilder getInstance()
{
return BUILDER;
}
private FtpFileSystemConfigBuilder()
{
super("ftp.");
}
/** @since 2.1 */
protected FtpFileSystemConfigBuilder(final String prefix) {
super(prefix);
}
@Override
protected Class<? extends FileSystem> getConfigClass()
{
return FtpFileSystem.class;
}
/**
* Gets the timeout in milliseconds to use for the socket connection.
*
* @param opts The FileSystemOptions.
* @return The timeout in milliseconds to use for the socket connection.
* @since 2.1
*/
public Integer getConnectTimeout(final FileSystemOptions opts)
{
return getInteger(opts, CONNECT_TIMEOUT);
}
/**
* @param opts The FileSystemOptions.
* @return The encoding.
* @since 2.0
* */
public String getControlEncoding(final FileSystemOptions opts)
{
return getString(opts, ENCODING);
}
/**
* @param opts The FileSystemOptions.
* @return The timeout for opening the data channel as an Integer.
* @see #setDataTimeout
*/
public Integer getDataTimeout(final FileSystemOptions opts)
{
return getInteger(opts, DATA_TIMEOUT);
}
/**
* Get the default date format used by the server. See {@link org.apache.commons.net.ftp.FTPClientConfig}
* for details and examples.
*
* @param opts The FileSystemOptions
* @return The default date format.
*/
public String getDefaultDateFormat(final FileSystemOptions opts)
{
return getString(opts, DEFAULT_DATE_FORMAT);
}
/**
* @param opts The FileSystemOptions.
* @see #setEntryParser
* @return the key to the EntryParser.
*/
public String getEntryParser(final FileSystemOptions opts)
{
return getString(opts, FACTORY_KEY);
}
/**
* @param opts The FlleSystemOptions.
* @see #setEntryParserFactory
* @return An FTPFileEntryParserFactory.
*/
public FTPFileEntryParserFactory getEntryParserFactory(final FileSystemOptions opts)
{
return (FTPFileEntryParserFactory) getParam(opts, FTPFileEntryParserFactory.class.getName());
}
/**
* Gets the file type parameter.
*
* @param opts The FileSystemOptions.
* @return A FtpFileType
* @since 2.1
*/
public FtpFileType getFileType(final FileSystemOptions opts)
{
return getEnum(FtpFileType.class, opts, FILE_TYPE);
}
/**
* @param opts The FileSystemOptions.
* @return true if passive mode is set.
* @see #setPassiveMode
*/
public Boolean getPassiveMode(final FileSystemOptions opts)
{
return getBoolean(opts, PASSIVE_MODE);
}
/**
* Gets the Proxy.
*
* @param opts The FileSystemOptions.
* @return the Proxy
* @since 2.1
*/
public Proxy getProxy(final FileSystemOptions opts)
{
return (Proxy) this.getParam(opts, PROXY);
}
/**
* See {@link org.apache.commons.net.ftp.FTPClientConfig} for details and examples.
*
* @param opts The FileSystemOptions.
* @return The recent date format.
*/
public String getRecentDateFormat(final FileSystemOptions opts)
{
return getString(opts, RECENT_DATE_FORMAT);
}
/**
* Get the language code used by the server. See {@link org.apache.commons.net.ftp.FTPClientConfig}
* for details and examples.
*
* @param opts The FilesystemOptions.
* @return The language code of the server.
*/
public String getServerLanguageCode(final FileSystemOptions opts)
{
return getString(opts, SERVER_LANGUAGE_CODE);
}
/**
* See {@link org.apache.commons.net.ftp.FTPClientConfig} for details and examples.
*
* @param opts The FileSystemOptions.
* @return The server timezone id.
*/
public String getServerTimeZoneId(final FileSystemOptions opts)
{
return getString(opts, SERVER_TIME_ZONE_ID);
}
/**
* See {@link org.apache.commons.net.ftp.FTPClientConfig} for details and examples.
*
* @param opts The FileSystemOptions.
* @return An array of short month names.
*/
public String[] getShortMonthNames(final FileSystemOptions opts)
{
return (String[]) getParam(opts, SHORT_MONTH_NAMES);
}
/**
* @param opts The FileSystem options.
* @return The timeout value.
* @see #getDataTimeout
* @since 2.0
*/
public Integer getSoTimeout(final FileSystemOptions opts)
{
return getInteger(opts, SO_TIMEOUT);
}
/**
* Returns {@link Boolean#TRUE} if VFS should treat the user directory as the root directory. Defaults to
* <code>Boolean.TRUE</code> if the method {@link #setUserDirIsRoot(FileSystemOptions, boolean)} has not been
* invoked.
*
* @param opts
* The FileSystemOptions.
* @return <code>Boolean.TRUE</code> if VFS treats the user directory as the root directory.
* @see #setUserDirIsRoot
*/
public Boolean getUserDirIsRoot(final FileSystemOptions opts)
{
return getBoolean(opts, USER_DIR_IS_ROOT, Boolean.TRUE);
}
/**
* Sets the timeout for the initial control connection.
* <p>
* If you set the connectTimeout to {@code null} no connectTimeout will be set.
*
* @param opts The FileSystemOptions.
* @param connectTimeout the timeout value in milliseconds
* @since 2.1
*/
public void setConnectTimeout(final FileSystemOptions opts, final Integer connectTimeout)
{
setParam(opts, CONNECT_TIMEOUT, connectTimeout);
}
/**
* See {@link org.apache.commons.net.ftp.FTP#setControlEncoding} for details and examples.
*
* @param opts The FileSystemOptions.
* @param encoding the encoding to use
* @since 2.0
*/
public void setControlEncoding(final FileSystemOptions opts, final String encoding)
{
setParam(opts, ENCODING, encoding);
}
/**
* Set the data timeout for the ftp client.
* <p>
* If you set the {@code dataTimeout} to null no dataTimeout will be set on the
* ftp client.
*
* @param opts The FileSystemOptions.
* @param dataTimeout The timeout value.
*/
public void setDataTimeout(final FileSystemOptions opts, final Integer dataTimeout)
{
setParam(opts, DATA_TIMEOUT, dataTimeout);
}
/**
* Set the default date format used by the server. See {@link org.apache.commons.net.ftp.FTPClientConfig}
* for details and examples.
*
* @param opts The FileSystemOptions.
* @param defaultDateFormat The default date format.
*/
public void setDefaultDateFormat(final FileSystemOptions opts, final String defaultDateFormat)
{
setParam(opts, DEFAULT_DATE_FORMAT, defaultDateFormat);
}
/**
* Set the FQCN of your FileEntryParser used to parse the directory listing from your server.
* <p>
* If you do not use the default commons-net FTPFileEntryParserFactory e.g. by using
* {@link #setEntryParserFactory} this is the "key" parameter passed as argument into your
* custom factory.
*
* @param opts The FileSystemOptions.
* @param key The key.
*/
public void setEntryParser(final FileSystemOptions opts, final String key)
{
setParam(opts, FACTORY_KEY, key);
}
/**
* FTPFileEntryParserFactory which will be used for ftp-entry parsing.
*
* @param opts The FileSystemOptions.
* @param factory instance of your factory
*/
public void setEntryParserFactory(final FileSystemOptions opts, final FTPFileEntryParserFactory factory)
{
setParam(opts, FTPFileEntryParserFactory.class.getName(), factory);
}
/**
* Sets the file type parameter.
*
* @param opts The FileSystemOptions.
* @param ftpFileType A FtpFileType
* @since 2.1
*/
public void setFileType(final FileSystemOptions opts, final FtpFileType ftpFileType)
{
setParam(opts, FILE_TYPE, ftpFileType);
}
/**
* Enter into passive mode.
*
* @param opts The FileSystemOptions.
* @param passiveMode true if passive mode should be used.
*/
public void setPassiveMode(final FileSystemOptions opts, final boolean passiveMode)
{
setParam(opts, PASSIVE_MODE, passiveMode ? Boolean.TRUE : Boolean.FALSE);
}
/**
* Sets the Proxy.
*
* @param opts the FileSystem options.
* @param proxy the Proxy
* @since 2.1
*/
public void setProxy(final FileSystemOptions opts, Proxy proxy)
{
setParam(opts, PROXY, proxy);
}
/**
* See {@link org.apache.commons.net.ftp.FTPClientConfig} for details and examples.
*
* @param opts The FileSystemOptions.
* @param recentDateFormat The recent date format.
*/
public void setRecentDateFormat(final FileSystemOptions opts, final String recentDateFormat)
{
setParam(opts, RECENT_DATE_FORMAT, recentDateFormat);
}
/**
* Set the language code used by the server. See {@link org.apache.commons.net.ftp.FTPClientConfig}
* for details and examples.
*
* @param opts The FileSystemOptions.
* @param serverLanguageCode The servers language code.
*/
public void setServerLanguageCode(final FileSystemOptions opts, final String serverLanguageCode)
{
setParam(opts, SERVER_LANGUAGE_CODE, serverLanguageCode);
}
/**
* See {@link org.apache.commons.net.ftp.FTPClientConfig} for details and examples.
*
* @param opts The FileSystemOptions.
* @param serverTimeZoneId The server timezone id.
*/
public void setServerTimeZoneId(final FileSystemOptions opts, final String serverTimeZoneId)
{
setParam(opts, SERVER_TIME_ZONE_ID, serverTimeZoneId);
}
/**
* See {@link org.apache.commons.net.ftp.FTPClientConfig} for details and examples.
*
* @param opts The FileSystemOptions.
* @param shortMonthNames an array of short month name Strings.
*/
public void setShortMonthNames(final FileSystemOptions opts, final String[] shortMonthNames)
{
String[] clone = null;
if (shortMonthNames != null)
{
clone = new String[shortMonthNames.length];
System.arraycopy(shortMonthNames, 0, clone, 0, shortMonthNames.length);
}
setParam(opts, SHORT_MONTH_NAMES, clone);
}
/**
* Sets the socket timeout for the FTP client.
* <p>
* If you set the {@code soTimeout} to null no socket timeout will be set on the
* ftp client.
*
* @param opts The FileSystem options.
* @param soTimeout The timeout value.
* @since 2.0
*/
public void setSoTimeout(final FileSystemOptions opts, final Integer soTimeout)
{
setParam(opts, SO_TIMEOUT, soTimeout);
}
/**
* Use user directory as root (do not change to fs root).
*
* @param opts The FileSystemOptions.
* @param userDirIsRoot true if the user directory should be treated as the root.
*/
public void setUserDirIsRoot(final FileSystemOptions opts, final boolean userDirIsRoot)
{
setParam(opts, USER_DIR_IS_ROOT, userDirIsRoot ? Boolean.TRUE : Boolean.FALSE);
}
}
| [VFS-167][FTP] Add comment, you need to set passive mode for most proxies.
git-svn-id: c455d203a03ec41bf444183aad31e7cce55db786@1591795 13f79535-47bb-0310-9956-ffa450edef68
| core/src/main/java/org/apache/commons/vfs2/provider/ftp/FtpFileSystemConfigBuilder.java | [VFS-167][FTP] Add comment, you need to set passive mode for most proxies. | <ide><path>ore/src/main/java/org/apache/commons/vfs2/provider/ftp/FtpFileSystemConfigBuilder.java
<ide>
<ide> /**
<ide> * Sets the Proxy.
<add> * <P>
<add> * You might need to make sure that {@link #setPassiveMode(FileSystemOptions, boolean) passive mode}
<add> * is activated.
<ide> *
<ide> * @param opts the FileSystem options.
<ide> * @param proxy the Proxy |
|
Java | mit | 1895842155ba51c01ab53c06350b785fcd1e4ef1 | 0 | braintree/braintree_android,braintree/braintree_android,braintree/braintree_android,braintree/braintree_android | package com.braintreepayments.api;
import android.content.Context;
import android.content.Intent;
import android.os.Parcel;
import android.os.Parcelable;
import com.google.android.gms.wallet.Cart;
import java.util.List;
/**
* Used to start {@link BraintreePaymentActivity} and {@link PaymentButton} with specified options.
*/
public class PaymentRequest implements Parcelable {
private String mAuthorization;
private String mAmount;
private String mCurrencyCode;
private Cart mAndroidPayCart;
private boolean mAndroidPayShippingAddressRequired;
private boolean mAndroidPayPhoneNumberRequired;
private int mAndroidPayRequestCode;
private List<String> mPayPalAdditionalScopes;
private String mActionBarTitle;
private int mActionBarLogo;
private String mPrimaryDescription;
private String mSecondaryDescription;
private String mSubmitButtonText;
public PaymentRequest() {}
/**
* Provide authorization allowing this client to communicate with Braintree. Either
* {@link #clientToken(String)} or {@link #tokenizationKey(String)} must be set or an
* {@link com.braintreepayments.api.exceptions.AuthenticationException} will occur.
*
* @param clientToken The client token to use for the request.
*/
public PaymentRequest clientToken(String clientToken) {
mAuthorization = clientToken;
return this;
}
/**
* Provide authorization allowing this client to communicate with Braintree. Either
* {@link #clientToken(String)} or {@link #tokenizationKey(String)} must be set or an
* {@link com.braintreepayments.api.exceptions.AuthenticationException} will occur.
*
* @param tokenizationKey The tokenization key to use for the request.
*/
public PaymentRequest tokenizationKey(String tokenizationKey) {
mAuthorization = tokenizationKey;
return this;
}
/**
* This method is optional.
*
* @param amount Amount of the transaction.
*/
public PaymentRequest amount(String amount) {
mAmount = amount;
return this;
}
/**
* This method is optional.
*
* @param currencyCode Currency code of the transaction.
*/
public PaymentRequest currencyCode(String currencyCode) {
mCurrencyCode = currencyCode;
return this;
}
/**
* This method is optional.
*
* @param cart The Android Pay {@link Cart} for the transaction.
*/
public PaymentRequest androidPayCart(Cart cart) {
mAndroidPayCart = cart;
return this;
}
/**
* This method is optional.
*
* @param shippingAddressRequired {@code true} if Android Pay requests should request a
* shipping address from the user.
*/
public PaymentRequest androidPayShippingAddressRequired(boolean shippingAddressRequired) {
mAndroidPayShippingAddressRequired = shippingAddressRequired;
return this;
}
/**
* This method is optional.
*
* @param phoneNumberRequired {@code true} if Android Pay requests should request a phone
* number from the user.
*/
public PaymentRequest androidPayPhoneNumberRequired(boolean phoneNumberRequired) {
mAndroidPayPhoneNumberRequired = phoneNumberRequired;
return this;
}
/**
* This method is optional.
*
* @param requestCode The requestCode to use when making an Android Pay
* {@link com.google.android.gms.wallet.MaskedWalletRequest} with
* {@link android.app.Activity#startActivityForResult(Intent, int)}}.
*/
public PaymentRequest androidPayRequestCode(int requestCode) {
mAndroidPayRequestCode = requestCode;
return this;
}
/**
* Set additional scopes to request when a user is authorizing PayPal.
*
* This method is optional.
*
* @param additionalScopes A {@link java.util.List} of additional scopes.
* Ex: PayPal.SCOPE_ADDRESS.
* Acceptable scopes are defined in {@link PayPal}.
*/
public PaymentRequest paypalAdditionalScopes(List<String> additionalScopes) {
mPayPalAdditionalScopes = additionalScopes;
return this;
}
/**
* This method is optional.
*
* @param title The title to display in the action bar when present.
*/
public PaymentRequest actionBarTitle(String title) {
mActionBarTitle = title;
return this;
}
/**
* This method is optional.
*
* @param drawable The icon to display in the action bar when present.
*/
public PaymentRequest actionBarLogo(int drawable) {
mActionBarLogo = drawable;
return this;
}
/**
* This method is optional.
*
* @param primaryDescription Main header for description bar. Displayed in bold.
*/
public PaymentRequest primaryDescription(String primaryDescription) {
mPrimaryDescription = primaryDescription;
return this;
}
/**
* This method is optional.
*
* @param secondaryDescription Subheader for description bar. Displayed in normal weight text.
*/
public PaymentRequest secondaryDescription(String secondaryDescription) {
mSecondaryDescription = secondaryDescription;
return this;
}
/**
* This method is optional.
*
* @param submitButtonText Text for submit button. Displayed in uppercase.
* Will be combined with amount if set via {@link #amount(String)}.
*/
public PaymentRequest submitButtonText(String submitButtonText) {
mSubmitButtonText = submitButtonText;
return this;
}
/**
* Get an {@link Intent} that can be used in {@link android.app.Activity#startActivityForResult(Intent, int)}
* to launch {@link BraintreePaymentActivity} and the Drop-in UI.
*
* @param context
* @return {@link Intent} containing all of the options set in {@link PaymentRequest}.
*/
public Intent getIntent(Context context) {
return new Intent(context, BraintreePaymentActivity.class)
.putExtra(BraintreePaymentActivity.EXTRA_CHECKOUT_REQUEST, this);
}
String getAuthorization() {
return mAuthorization;
}
String getAmount() {
return mAmount;
}
String getCurrencyCode() {
return mCurrencyCode;
}
Cart getAndroidPayCart() throws NoClassDefFoundError {
return mAndroidPayCart;
}
boolean isAndroidPayShippingAddressRequired() {
return mAndroidPayShippingAddressRequired;
}
boolean isAndroidPayPhoneNumberRequired() {
return mAndroidPayPhoneNumberRequired;
}
int getAndroidPayRequestCode() {
return mAndroidPayRequestCode;
}
List<String> getPayPalAdditionalScopes() {
return mPayPalAdditionalScopes;
}
String getActionBarTitle() {
return mActionBarTitle;
}
int getActionBarLogo() {
return mActionBarLogo;
}
String getPrimaryDescription() {
return mPrimaryDescription;
}
String getSecondaryDescription() {
return mSecondaryDescription;
}
String getSubmitButtonText() {
return mSubmitButtonText;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(mAuthorization);
dest.writeString(mAmount);
dest.writeString(mCurrencyCode);
try {
Cart.class.getClassLoader();
dest.writeParcelable(mAndroidPayCart, 0);
dest.writeByte(mAndroidPayShippingAddressRequired ? (byte) 1 : (byte) 0);
dest.writeByte(mAndroidPayPhoneNumberRequired ? (byte) 1 : (byte) 0);
dest.writeInt(mAndroidPayRequestCode);
} catch (NoClassDefFoundError ignored) {}
dest.writeStringList(mPayPalAdditionalScopes);
dest.writeString(mActionBarTitle);
dest.writeInt(mActionBarLogo);
dest.writeString(mPrimaryDescription);
dest.writeString(mSecondaryDescription);
dest.writeString(mSubmitButtonText);
}
protected PaymentRequest(Parcel in) {
mAuthorization = in.readString();
mAmount = in.readString();
mCurrencyCode = in.readString();
try {
mAndroidPayCart = in.readParcelable(Cart.class.getClassLoader());
mAndroidPayShippingAddressRequired = in.readByte() != 0;
mAndroidPayPhoneNumberRequired = in.readByte() != 0;
mAndroidPayRequestCode = in.readInt();
} catch (NoClassDefFoundError ignored) {}
mPayPalAdditionalScopes = in.createStringArrayList();
mActionBarTitle = in.readString();
mActionBarLogo = in.readInt();
mPrimaryDescription = in.readString();
mSecondaryDescription = in.readString();
mSubmitButtonText = in.readString();
}
public static final Creator<PaymentRequest> CREATOR = new Creator<PaymentRequest>() {
public PaymentRequest createFromParcel(Parcel source) {
return new PaymentRequest(source);
}
public PaymentRequest[] newArray(int size) {
return new PaymentRequest[size];
}
};
}
| Drop-In/src/main/java/com/braintreepayments/api/PaymentRequest.java | package com.braintreepayments.api;
import android.content.Context;
import android.content.Intent;
import android.os.Parcel;
import android.os.Parcelable;
import com.google.android.gms.wallet.Cart;
import java.util.List;
/**
* Used to start {@link BraintreePaymentActivity} and {@link PaymentButton} with specified options.
*/
public class PaymentRequest implements Parcelable {
private String mAuthorization;
private String mAmount;
private String mCurrencyCode;
private Cart mAndroidPayCart;
private boolean mAndroidPayShippingAddressRequired;
private boolean mAndroidPayPhoneNumberRequired;
private int mAndroidPayRequestCode;
private List<String> mPayPalAdditionalScopes;
private String mActionBarTitle;
private int mActionBarLogo;
private String mPrimaryDescription;
private String mSecondaryDescription;
private String mSubmitButtonText;
public PaymentRequest() {}
/**
* Provide authorization allowing this client to communicate with Braintree. Either
* {@link #clientToken(String)} or {@link #tokenizationKey(String)} must be set or an
* {@link com.braintreepayments.api.exceptions.AuthenticationException} will occur.
*
* @param clientToken The client token to use for the request.
*/
public PaymentRequest clientToken(String clientToken) {
mAuthorization = clientToken;
return this;
}
/**
* Provide authorization allowing this client to communicate with Braintree. Either
* {@link #clientToken(String)} or {@link #tokenizationKey(String)} must be set or an
* {@link com.braintreepayments.api.exceptions.AuthenticationException} will occur.
*
* @param tokenizationKey The tokenization key to use for the request.
*/
public PaymentRequest tokenizationKey(String tokenizationKey) {
mAuthorization = tokenizationKey;
return this;
}
/**
* This method is optional.
*
* @param amount Amount of the transaction.
*/
public PaymentRequest amount(String amount) {
mAmount = amount;
return this;
}
/**
* This method is optional.
*
* @param currencyCode Currency code of the transaction.
*/
public PaymentRequest currencyCode(String currencyCode) {
mCurrencyCode = currencyCode;
return this;
}
/**
* This method is optional.
*
* @param cart The Android Pay {@link Cart} for the transaction.
*/
public PaymentRequest androidPayCart(Cart cart) {
mAndroidPayCart = cart;
return this;
}
/**
* This method is optional.
*
* @param shippingAddressRequired {@code true} if Android Pay requests should request a
* shipping address from the user.
*/
public PaymentRequest androidPayShippingAddressRequired(boolean shippingAddressRequired) {
mAndroidPayShippingAddressRequired = shippingAddressRequired;
return this;
}
/**
* This method is optional.
*
* @param phoneNumberRequired {@code true} if Android Pay requests should request a phone
* number from the user.
*/
public PaymentRequest androidPayPhoneNumberRequired(boolean phoneNumberRequired) {
mAndroidPayPhoneNumberRequired = phoneNumberRequired;
return this;
}
/**
* This method is optional.
*
* @param requestCode The requestCode to use when making an Android Pay
* {@link com.google.android.gms.wallet.MaskedWalletRequest} with
* {@link android.app.Activity#startActivityForResult(Intent, int)}}.
*/
public PaymentRequest androidPayRequestCode(int requestCode) {
mAndroidPayRequestCode = requestCode;
return this;
}
/**
* Set additional scopes to request when a user is authorizing PayPal.
*
* This method is optional.
*
* @param additionalScopes A {@link java.util.List} of additional scopes.
* Ex: PayPal.SCOPE_ADDRESS.
* Acceptable scopes are defined in {@link PayPal}.
*/
public PaymentRequest paypalAdditionalScopes(List<String> additionalScopes) {
mPayPalAdditionalScopes = additionalScopes;
return this;
}
/**
* This method is optional.
*
* @param title The title to display in the action bar when present.
*/
public PaymentRequest actionBarTitle(String title) {
mActionBarTitle = title;
return this;
}
/**
* This method is optional.
*
* @param drawable The icon to display in the action bar when present.
*/
public PaymentRequest actionBarLogo(int drawable) {
mActionBarLogo = drawable;
return this;
}
/**
* This method is optional.
*
* @param primaryDescription Main header for description bar. Displayed in bold.
*/
public PaymentRequest primaryDescription(String primaryDescription) {
mPrimaryDescription = primaryDescription;
return this;
}
/**
* This method is optional.
*
* @param secondaryDescription Subheader for description bar. Displayed in normal weight text.
*/
public PaymentRequest secondaryDescription(String secondaryDescription) {
mSecondaryDescription = secondaryDescription;
return this;
}
/**
* This method is optional.
*
* @param submitButtonText Text for submit button. Displayed in uppercase.
* Will be combined with amount if set via {@link #amount(String)}.
*/
public PaymentRequest submitButtonText(String submitButtonText) {
mSubmitButtonText = submitButtonText;
return this;
}
/**
* Get an {@link Intent} that can be used in {@link android.app.Activity#startActivityForResult(Intent, int)}
* to launch {@link BraintreePaymentActivity} and the Drop-in UI.
*
* @param context
* @return {@link Intent} containing all of the options set in {@link PaymentRequest}.
*/
public Intent getIntent(Context context) {
return new Intent(context, BraintreePaymentActivity.class)
.putExtra(BraintreePaymentActivity.EXTRA_CHECKOUT_REQUEST, this);
}
String getAuthorization() {
return mAuthorization;
}
String getAmount() {
return mAmount;
}
String getCurrencyCode() {
return mCurrencyCode;
}
Cart getAndroidPayCart() throws NoClassDefFoundError {
return mAndroidPayCart;
}
boolean isAndroidPayShippingAddressRequired() {
return mAndroidPayShippingAddressRequired;
}
boolean isAndroidPayPhoneNumberRequired() {
return mAndroidPayPhoneNumberRequired;
}
int getAndroidPayRequestCode() {
return mAndroidPayRequestCode;
}
List<String> getPayPalAdditionalScopes() {
return mPayPalAdditionalScopes;
}
String getActionBarTitle() {
return mActionBarTitle;
}
int getActionBarLogo() {
return mActionBarLogo;
}
String getPrimaryDescription() {
return mPrimaryDescription;
}
String getSecondaryDescription() {
return mSecondaryDescription;
}
String getSubmitButtonText() {
return mSubmitButtonText;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(mAuthorization);
dest.writeString(mAmount);
dest.writeString(mCurrencyCode);
dest.writeParcelable(mAndroidPayCart, 0);
dest.writeByte(mAndroidPayShippingAddressRequired ? (byte) 1 : (byte) 0);
dest.writeByte(mAndroidPayPhoneNumberRequired ? (byte) 1 : (byte) 0);
dest.writeInt(mAndroidPayRequestCode);
dest.writeStringList(mPayPalAdditionalScopes);
dest.writeString(mActionBarTitle);
dest.writeInt(mActionBarLogo);
dest.writeString(mPrimaryDescription);
dest.writeString(mSecondaryDescription);
dest.writeString(mSubmitButtonText);
}
protected PaymentRequest(Parcel in) {
mAuthorization = in.readString();
mAmount = in.readString();
mCurrencyCode = in.readString();
mAndroidPayCart = in.readParcelable(Cart.class.getClassLoader());
mAndroidPayShippingAddressRequired = in.readByte() != 0;
mAndroidPayPhoneNumberRequired = in.readByte() != 0;
mAndroidPayRequestCode = in.readInt();
mPayPalAdditionalScopes = in.createStringArrayList();
mActionBarTitle = in.readString();
mActionBarLogo = in.readInt();
mPrimaryDescription = in.readString();
mSecondaryDescription = in.readString();
mSubmitButtonText = in.readString();
}
public static final Creator<PaymentRequest> CREATOR = new Creator<PaymentRequest>() {
public PaymentRequest createFromParcel(Parcel source) {
return new PaymentRequest(source);
}
public PaymentRequest[] newArray(int size) {
return new PaymentRequest[size];
}
};
}
| Fix PaymentRequest crash when Google Play Services is not present
| Drop-In/src/main/java/com/braintreepayments/api/PaymentRequest.java | Fix PaymentRequest crash when Google Play Services is not present | <ide><path>rop-In/src/main/java/com/braintreepayments/api/PaymentRequest.java
<ide> dest.writeString(mAuthorization);
<ide> dest.writeString(mAmount);
<ide> dest.writeString(mCurrencyCode);
<del> dest.writeParcelable(mAndroidPayCart, 0);
<del> dest.writeByte(mAndroidPayShippingAddressRequired ? (byte) 1 : (byte) 0);
<del> dest.writeByte(mAndroidPayPhoneNumberRequired ? (byte) 1 : (byte) 0);
<del> dest.writeInt(mAndroidPayRequestCode);
<add>
<add> try {
<add> Cart.class.getClassLoader();
<add> dest.writeParcelable(mAndroidPayCart, 0);
<add> dest.writeByte(mAndroidPayShippingAddressRequired ? (byte) 1 : (byte) 0);
<add> dest.writeByte(mAndroidPayPhoneNumberRequired ? (byte) 1 : (byte) 0);
<add> dest.writeInt(mAndroidPayRequestCode);
<add> } catch (NoClassDefFoundError ignored) {}
<add>
<ide> dest.writeStringList(mPayPalAdditionalScopes);
<ide> dest.writeString(mActionBarTitle);
<ide> dest.writeInt(mActionBarLogo);
<ide> mAuthorization = in.readString();
<ide> mAmount = in.readString();
<ide> mCurrencyCode = in.readString();
<del> mAndroidPayCart = in.readParcelable(Cart.class.getClassLoader());
<del> mAndroidPayShippingAddressRequired = in.readByte() != 0;
<del> mAndroidPayPhoneNumberRequired = in.readByte() != 0;
<del> mAndroidPayRequestCode = in.readInt();
<add>
<add> try {
<add> mAndroidPayCart = in.readParcelable(Cart.class.getClassLoader());
<add> mAndroidPayShippingAddressRequired = in.readByte() != 0;
<add> mAndroidPayPhoneNumberRequired = in.readByte() != 0;
<add> mAndroidPayRequestCode = in.readInt();
<add> } catch (NoClassDefFoundError ignored) {}
<add>
<ide> mPayPalAdditionalScopes = in.createStringArrayList();
<ide> mActionBarTitle = in.readString();
<ide> mActionBarLogo = in.readInt(); |
|
Java | apache-2.0 | f8664ee75c17c9ff5a7692b5bd86d607dccf2d50 | 0 | MatthewTamlin/Spyglass | package com.matthewtamlin.spyglass.consumer;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Looper;
import android.util.AttributeSet;
import android.view.View;
import com.matthewtamlin.java_utilities.testing.Tested;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import static com.matthewtamlin.java_utilities.checkers.NullChecker.checkNotNull;
/**
* Translates view attributes into method calls via annotations. This class interacts with the UI, so all method
* calls must be made on the main thread. This class uses the builder pattern for instantiation
* (see {@link #builder()}).
*/
@Tested(testMethod = "automated")
public class Spyglass {
/**
* The target to pass data to via reflective method calls.
*/
private final View target;
/**
* A context which provides access to system resources.
*/
private final Context context;
/**
* Supplies the data to pass to the target.
*/
private final TypedArray attrSource;
/**
* Class containing the logic for invoking methods in the target class.
*/
private Class<?> companionClass;
/**
* Constructs a new Spyglass from a builder.
*
* @param builder
* the builder to use as the base for the spyglass
*/
private Spyglass(final Builder builder) {
this.target = builder.target;
this.context = builder.context;
this.attrSource = context.obtainStyledAttributes(
builder.attributeSet,
builder.styleableRes,
builder.defStyleAttr,
builder.defStyleRes);
final String targetClassName = builder.targetClass.getCanonicalName();
try {
companionClass = Class.forName(targetClassName + "_SpyglassCompanion");
} catch (final ClassNotFoundException e) {
final String unformattedExceptionMessage =
"No companion class was found for class \'%1$s\'.\n" +
"Check the following:\n" +
"- Does the class have any Spyglass handler annotations?\n" +
"- Was the Spyglass annotation processor enabled at compile time?\n" +
"- Were the generated files deleted manually or by a trimming tool?";
throw new MissingCompanionClassException(String.format(unformattedExceptionMessage, targetClassName));
}
}
/**
* Passes data to the target view using its method annotations. Methods are validated prior to use, to ensure
* that annotations have been applied correctly. This method will fail if called on a non-UI thread.
*
* @throws IllegalThreadException
* if this method is called on a non-UI thread
* @throws SpyglassInvocationException
* if a target method throws an exception when invoked, with the cause set to the thrown exception
*/
public void passDataToMethods() {
if (Looper.myLooper() != Looper.getMainLooper()) {
throw new IllegalThreadException("Spyglass methods must be called on the UI thread.");
}
try {
final Method activateCallers = companionClass.getMethod(
"activateCallers",
target.getClass(),
Context.class,
TypedArray.class);
activateCallers.invoke(null, target, context, attrSource);
} catch (final NoSuchMethodException e) {
throw new InvalidSpyglassCompanionException(
"Spyglass found an invalid companion class. Were the generated files modified?", e);
} catch (final InvocationTargetException e) {
throw new SpyglassInvocationException(
"Spyglass encountered an exception when invoking a method in a target class.", e);
} catch (final IllegalAccessException e) {
throw new RuntimeException("Spyglass cannot access a method in the target class.", e);
}
}
/**
* @return a new spyglass builder
*/
public static Builder builder() {
return new Builder();
}
/**
* Builds new instances of the {@link Spyglass} tool. Attempting to call {@link #build()} without first setting
* the target, context and styleable-resource properties will result in an exception being thrown.
*/
public static class Builder {
/**
* The target to pass data to. This property is mandatory and must be non-null prior to calling
* {@link #build()}.
*/
private View target;
/**
* The class to look for annotations in. This property is mandatory and must be non-null prior to calling
* {@link #build()}. The target must be an instance of this class.
*/
private Class<? extends View> annotationSource;
/**
* The context to use when accessing system resources. This property is mandatory and must be non-null prior
* to calling {@link #build()}.
*/
private Context context;
/**
* The styleable resource to use when interpreting data. This property is mandatory and must be non-null
* prior to calling {@link #build()}.
*/
private int styleableRes[];
/**
* The attribute set to source data from. This property is optional and does not need to be changed prior to
* calling {@link #build()}.
*/
private AttributeSet attributeSet;
/**
* An attribute in the current theme which references the style to source defaults from. This property is
* optional and does not need to be changed prior to calling {@link #build()}.
*/
private int defStyleAttr;
/**
* The resource ID of the style to source defaults from. This property is optional and does not need to be
* changed prior to calling {@link #build()}.
*/
private int defStyleRes;
/**
* Constructs a new builder without setting any values. The new builder cannot be used to create a spyglass
* without setting the mandatory properties first.
*/
private Builder() {}
/**
* Sets the target to pass data to. If this method is called more than once, only the most recent values are
* used. This method must be called with non-null values prior to calling {@link #build()}.
*
* @param view
* the target to pass data to
*
* @return this builder
*/
public <T extends View> Builder withTarget(final T view) {
this.target = view;
return this;
}
/**
* Sets the class to use as the annotation source. Do not pass the runtime class of the target to this method,
* instead pass a static class reference. This is important because the Spyglass framework uses this class to
* lookup compiled data at runtime. If this method is called more than once, only the most recent value is
* used. This method must be called with a non-null value prior to calling {@link #build()}, and the target
* supplied to {@link #withTarget(View)} must be an instance of the annotation source class.
*
* @param annotationSource
* the class containing the annotations to use
*
* @return this builder
*/
public Builder withAnnotationSource(final Class<? extends View> annotationSource) {
this.annotationSource = annotationSource;
return this;
}
/**
* Sets the context to use when accessing system resources. If this method is called more than once, only the
* most recent value is used. This method must be called with a non-null value prior to calling {@link
* #build()}.
*
* @param context
* the context to use when accessing system resources
*
* @return this builder
*/
public Builder withContext(final Context context) {
this.context = context;
return this;
}
/**
* Sets the styleable resource to use when interpreting attribute data. The behaviour of the spyglass is
* undefined if the styleable resource is not applicable to the target view. If this method is called more than
* once, only the most recent value is used. This method must be called with a non-null value prior to calling
* {@link #build()}.
*
* @param styleableRes
* the styleable resource to use when interpreting attribute data
*
* @return this builder
*/
public Builder withStyleableResource(final int[] styleableRes) {
this.styleableRes = styleableRes;
return this;
}
/**
* Sets the attribute set to source data from. If this method is called more than once, only the most recent
* value is used. An attribute set is not mandatory, and {@link #build()} can safely be called without ever
* calling this method.
*
* @param attributeSet
* the attribute set to source data from, may be null
*
* @return this builder
*/
public Builder withAttributeSet(final AttributeSet attributeSet) {
this.attributeSet = attributeSet;
return this;
}
/**
* Sets the style to source defaults from if the attribute set is missing data. The data in the attribute set
* takes precedence, so the data in the default style is only used if the attribute set is missing data for a
* particular attribute. If this method is called more than once, only the most recent value is used. This value
* is not mandatory, and {@link #build()} can safely be called without ever calling this method.
*
* @param defStyleAttr
* an attribute in the current theme which references the default style, 0 to use no default style
*
* @return this builder
*/
public Builder withDefStyleAttr(final int defStyleAttr) {
this.defStyleAttr = defStyleAttr;
return this;
}
/**
* Sets the style to source defaults from if the attribute set is missing data. The data in the attribute set
* takes precedence, so the data in the default style is only used if the attribute set is missing data for a
* particular attribute. If this method is called more than once, only the most recent value is used. This
* value is not mandatory, and {@link #build()} can safely be called without ever calling this method.
*
* @param defStyleRes
* the resource ID of the default style, 0 to use no default style
*
* @return this builder
*/
public Builder withDefStyleRes(final int defStyleRes) {
this.defStyleRes = defStyleRes;
return this;
}
/**
* Constructs a new spyglass using this builder. Attempting to call this method without first setting the
* target, the context and the styleable resource will result in an exception being thrown.
*
* @return the new spyglass
*
* @throws InvalidBuilderStateException
* if no target has been set
* @throws InvalidBuilderStateException
* if no context has been set
* @throws InvalidBuilderStateException
* if no styleable resource has been set
*/
public Spyglass build() {
checkNotNull(target, new InvalidBuilderStateException("Unable to build a Spyglass without a target. Call " +
"method withTarget(View) before calling build()."));
checkNotNull(annotationSource, new InvalidBuilderStateException("Unable to build a Spyglass without an " +
"annotation source. Use method withAnnotationSource(Class) before calling build()."));
checkNotNull(context, new InvalidBuilderStateException("Unable to build a Spyglass without a context. " +
"Call method withContext(Context) before calling build()."));
checkNotNull(styleableRes, new InvalidBuilderStateException("Unable to build a Spyglass without a " +
"styleable resource. Call method withStyleableRes(int[]) before calling build()."));
return new Spyglass(this);
}
}
} | consumer/src/main/java/com/matthewtamlin/spyglass/consumer/Spyglass.java | package com.matthewtamlin.spyglass.consumer;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Looper;
import android.util.AttributeSet;
import android.view.View;
import com.matthewtamlin.java_utilities.testing.Tested;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import static com.matthewtamlin.java_utilities.checkers.NullChecker.checkNotNull;
/**
* Translates view attributes into method calls via annotations. This class interacts with the UI, so all method
* calls must be made on the main thread. This class uses the builder pattern for instantiation
* (see {@link #builder()}).
*/
@Tested(testMethod = "automated")
public class Spyglass {
/**
* The target to pass data to via reflective method calls.
*/
private final View target;
/**
* A context which provides access to system resources.
*/
private final Context context;
/**
* Supplies the data to pass to the target.
*/
private final TypedArray attrSource;
/**
* Class containing the logic for invoking methods in the target class.
*/
private Class<?> companionClass;
/**
* Constructs a new Spyglass from a builder.
*
* @param builder
* the builder to use as the base for the spyglass
*/
private Spyglass(final Builder builder) {
this.target = builder.target;
this.context = builder.context;
this.attrSource = context.obtainStyledAttributes(
builder.attributeSet,
builder.styleableRes,
builder.defStyleAttr,
builder.defStyleRes);
final String targetClassName = builder.targetClass.getCanonicalName();
try {
companionClass = Class.forName(targetClassName + "_SpyglassCompanion");
} catch (final ClassNotFoundException e) {
final String unformattedExceptionMessage =
"No companion class was found for class \'%1$s\'.\n" +
"Check the following:\n" +
"- Does the class have any Spyglass handler annotations?\n" +
"- Was the Spyglass annotation processor enabled at compile time?\n" +
"- Were the generated files deleted manually or by a trimming tool?";
throw new MissingCompanionClassException(String.format(unformattedExceptionMessage, targetClassName));
}
}
/**
* Passes data to the target view using its method annotations. Methods are validated prior to use, to ensure
* that annotations have been applied correctly. This method will fail if called on a non-UI thread.
*
* @throws IllegalThreadException
* if this method is called on a non-UI thread
* @throws SpyglassInvocationException
* if a target method throws an exception when invoked, with the cause set to the thrown exception
*/
public void passDataToMethods() {
if (Looper.myLooper() != Looper.getMainLooper()) {
throw new IllegalThreadException("Spyglass methods must be called on the UI thread.");
}
try {
final Method activateCallers = companionClass.getMethod(
"activateCallers",
target.getClass(),
Context.class,
TypedArray.class);
activateCallers.invoke(null, target, context, attrSource);
} catch (final NoSuchMethodException e) {
throw new InvalidSpyglassCompanionException(
"Spyglass found an invalid companion class. Were the generated files modified?", e);
} catch (final InvocationTargetException e) {
throw new SpyglassInvocationException(
"Spyglass encountered an exception when invoking a method in a target class.", e);
} catch (final IllegalAccessException e) {
throw new RuntimeException("Spyglass cannot access a method in the target class.", e);
}
}
/**
* @return a new spyglass builder
*/
public static Builder builder() {
return new Builder();
}
/**
* Builds new instances of the {@link Spyglass} tool. Attempting to call {@link #build()} without first setting
* the target, context and styleable-resource properties will result in an exception being thrown.
*/
public static class Builder {
/**
* The target to pass data to. This property is mandatory and must be non-null prior to calling
* {@link #build()}.
*/
private View target;
/**
* The context to use when accessing system resources. This property is mandatory and must be non-null prior
* to calling {@link #build()}.
*/
private Context context;
/**
* The styleable resource to use when interpreting data. This property is mandatory and must be non-null
* prior to calling {@link #build()}.
*/
private int styleableRes[];
/**
* The attribute set to source data from. This property is optional and does not need to be changed prior to
* calling {@link #build()}.
*/
private AttributeSet attributeSet;
/**
* An attribute in the current theme which references the style to source defaults from. This property is
* optional and does not need to be changed prior to calling {@link #build()}.
*/
private int defStyleAttr;
/**
* The resource ID of the style to source defaults from. This property is optional and does not need to be
* changed prior to calling {@link #build()}.
*/
private int defStyleRes;
/**
* Constructs a new builder without setting any values. The new builder cannot be used to create a spyglass
* without setting the mandatory properties first.
*/
private Builder() {}
/**
* Sets the target to pass data to. If this method is called more than once, only the most recent values are
* used. This method must be called with non-null values prior to calling {@link #build()}.
*
* @param view
* the target to pass data to
*
* @return this builder
*/
public <T extends View> Builder withTarget(final T view) {
this.target = view;
return this;
}
/**
* Sets the context to use when accessing system resources. If this method is called more than once, only the
* most recent value is used. This method must be called with a non-null value prior to calling {@link
* #build()}.
*
* @param context
* the context to use when accessing system resources
*
* @return this builder
*/
public Builder withContext(final Context context) {
this.context = context;
return this;
}
/**
* Sets the styleable resource to use when interpreting attribute data. The behaviour of the spyglass is
* undefined if the styleable resource is not applicable to the target view. If this method is called more than
* once, only the most recent value is used. This method must be called with a non-null value prior to calling
* {@link #build()}.
*
* @param styleableRes
* the styleable resource to use when interpreting attribute data
*
* @return this builder
*/
public Builder withStyleableResource(final int[] styleableRes) {
this.styleableRes = styleableRes;
return this;
}
/**
* Sets the attribute set to source data from. If this method is called more than once, only the most recent
* value is used. An attribute set is not mandatory, and {@link #build()} can safely be called without ever
* calling this method.
*
* @param attributeSet
* the attribute set to source data from, may be null
*
* @return this builder
*/
public Builder withAttributeSet(final AttributeSet attributeSet) {
this.attributeSet = attributeSet;
return this;
}
/**
* Sets the style to source defaults from if the attribute set is missing data. The data in the attribute set
* takes precedence, so the data in the default style is only used if the attribute set is missing data for a
* particular attribute. If this method is called more than once, only the most recent value is used. This value
* is not mandatory, and {@link #build()} can safely be called without ever calling this method.
*
* @param defStyleAttr
* an attribute in the current theme which references the default style, 0 to use no default style
*
* @return this builder
*/
public Builder withDefStyleAttr(final int defStyleAttr) {
this.defStyleAttr = defStyleAttr;
return this;
}
/**
* Sets the style to source defaults from if the attribute set is missing data. The data in the attribute set
* takes precedence, so the data in the default style is only used if the attribute set is missing data for a
* particular attribute. If this method is called more than once, only the most recent value is used. This
* value is not mandatory, and {@link #build()} can safely be called without ever calling this method.
*
* @param defStyleRes
* the resource ID of the default style, 0 to use no default style
*
* @return this builder
*/
public Builder withDefStyleRes(final int defStyleRes) {
this.defStyleRes = defStyleRes;
return this;
}
/**
* Constructs a new spyglass using this builder. Attempting to call this method without first setting the
* target, the context and the styleable resource will result in an exception being thrown.
*
* @return the new spyglass
*
* @throws InvalidBuilderStateException
* if no target has been set
* @throws InvalidBuilderStateException
* if no context has been set
* @throws InvalidBuilderStateException
* if no styleable resource has been set
*/
public Spyglass build() {
checkNotNull(target, new InvalidBuilderStateException("Unable to build a Spyglass without a target. Call " +
"method withTarget(View) before calling build()."));
checkNotNull(targetClass, new InvalidBuilderStateException("Unable to build a Spyglass without a target " +
"class. Use method withTarget(View, Class) before calling build()."));
checkNotNull(context, new InvalidBuilderStateException("Unable to build a Spyglass without a context. " +
"Call method withContext(Context) before calling build()."));
checkNotNull(styleableRes, new InvalidBuilderStateException("Unable to build a Spyglass without a " +
"styleable resource. Call method withStyleableRes(int[]) before calling build()."));
return new Spyglass(this);
}
}
} | Added annotation source to builder
| consumer/src/main/java/com/matthewtamlin/spyglass/consumer/Spyglass.java | Added annotation source to builder | <ide><path>onsumer/src/main/java/com/matthewtamlin/spyglass/consumer/Spyglass.java
<ide> private View target;
<ide>
<ide> /**
<add> * The class to look for annotations in. This property is mandatory and must be non-null prior to calling
<add> * {@link #build()}. The target must be an instance of this class.
<add> */
<add> private Class<? extends View> annotationSource;
<add>
<add> /**
<ide> * The context to use when accessing system resources. This property is mandatory and must be non-null prior
<ide> * to calling {@link #build()}.
<ide> */
<ide> public <T extends View> Builder withTarget(final T view) {
<ide> this.target = view;
<ide>
<add> return this;
<add> }
<add>
<add> /**
<add> * Sets the class to use as the annotation source. Do not pass the runtime class of the target to this method,
<add> * instead pass a static class reference. This is important because the Spyglass framework uses this class to
<add> * lookup compiled data at runtime. If this method is called more than once, only the most recent value is
<add> * used. This method must be called with a non-null value prior to calling {@link #build()}, and the target
<add> * supplied to {@link #withTarget(View)} must be an instance of the annotation source class.
<add> *
<add> * @param annotationSource
<add> * the class containing the annotations to use
<add> *
<add> * @return this builder
<add> */
<add> public Builder withAnnotationSource(final Class<? extends View> annotationSource) {
<add> this.annotationSource = annotationSource;
<ide> return this;
<ide> }
<ide>
<ide> checkNotNull(target, new InvalidBuilderStateException("Unable to build a Spyglass without a target. Call " +
<ide> "method withTarget(View) before calling build()."));
<ide>
<del> checkNotNull(targetClass, new InvalidBuilderStateException("Unable to build a Spyglass without a target " +
<del> "class. Use method withTarget(View, Class) before calling build()."));
<add> checkNotNull(annotationSource, new InvalidBuilderStateException("Unable to build a Spyglass without an " +
<add> "annotation source. Use method withAnnotationSource(Class) before calling build()."));
<ide>
<ide> checkNotNull(context, new InvalidBuilderStateException("Unable to build a Spyglass without a context. " +
<ide> "Call method withContext(Context) before calling build().")); |
|
Java | apache-2.0 | 05a432e7fd6593fa5ec0599b26cda40513463db8 | 0 | apache/commons-dbutils,mohanaraosv/commons-dbutils,apache/commons-dbutils,mohanaraosv/commons-dbutils,kettas/commons-dbutils | /*
* 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.dbutils;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;
/**
* <p>
* Wraps a <code>ResultSet</code> in an <code>Iterator<Object[]></code>. This is useful
* when you want to present a non-database application layer with domain
* neutral data.
* </p>
*
* <p>
* This implementation requires the <code>ResultSet.isLast()</code> method
* to be implemented.
* </p>
*/
public class ResultSetIterator implements Iterator<Object[]> {
/**
* The wrapped <code>ResultSet</code>.
*/
private final ResultSet rs;
/**
* The processor to use when converting a row into an Object[].
*/
private final RowProcessor convert;
/**
* Constructor for ResultSetIterator.
* @param rs Wrap this <code>ResultSet</code> in an <code>Iterator</code>.
*/
public ResultSetIterator(ResultSet rs) {
this(rs, new BasicRowProcessor());
}
/**
* Constructor for ResultSetIterator.
* @param rs Wrap this <code>ResultSet</code> in an <code>Iterator</code>.
* @param convert The processor to use when converting a row into an
* <code>Object[]</code>. Defaults to a
* <code>BasicRowProcessor</code>.
*/
public ResultSetIterator(ResultSet rs, RowProcessor convert) {
this.rs = rs;
this.convert = convert;
}
/**
* Returns true if there are more rows in the ResultSet.
* @return boolean <code>true</code> if there are more rows
* @throws RuntimeException if an SQLException occurs.
*/
public boolean hasNext() {
try {
return !rs.isLast();
} catch (SQLException e) {
rethrow(e);
return false;
}
}
/**
* Returns the next row as an <code>Object[]</code>.
* @return An <code>Object[]</code> with the same number of elements as
* columns in the <code>ResultSet</code>.
* @see java.util.Iterator#next()
* @throws RuntimeException if an SQLException occurs.
*/
public Object[] next() {
try {
rs.next();
return this.convert.toArray(rs);
} catch (SQLException e) {
rethrow(e);
return null;
}
}
/**
* Deletes the current row from the <code>ResultSet</code>.
* @see java.util.Iterator#remove()
* @throws RuntimeException if an SQLException occurs.
*/
public void remove() {
try {
this.rs.deleteRow();
} catch (SQLException e) {
rethrow(e);
}
}
/**
* Rethrow the SQLException as a RuntimeException. This implementation
* creates a new RuntimeException with the SQLException's error message.
* @param e SQLException to rethrow
* @since DbUtils 1.1
*/
protected void rethrow(SQLException e) {
throw new RuntimeException(e.getMessage());
}
/**
* Generates an <code>Iterable</code>, suitable for use in for-each loops.
*
* @param rs Wrap this <code>ResultSet</code> in an <code>Iterator</code>.
* @return an <code>Iterable</code>, suitable for use in for-each loops.
*/
public static Iterable<Object[]> iterable(final ResultSet rs) {
return new Iterable<Object[]>() {
public Iterator<Object[]> iterator() {
return new ResultSetIterator(rs);
}
};
}
}
| src/java/org/apache/commons/dbutils/ResultSetIterator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.dbutils;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;
/**
* <p>
* Wraps a <code>ResultSet</code> in an <code>Iterator<Object[]></code>. This is useful
* when you want to present a non-database application layer with domain
* neutral data.
* </p>
*
* <p>
* This implementation requires the <code>ResultSet.isLast()</code> method
* to be implemented.
* </p>
*/
public class ResultSetIterator implements Iterator<Object[]> {
/**
* The wrapped <code>ResultSet</code>.
*/
private final ResultSet rs;
/**
* The processor to use when converting a row into an Object[].
*/
private final RowProcessor convert;
/**
* Constructor for ResultSetIterator.
* @param rs Wrap this <code>ResultSet</code> in an <code>Iterator</code>.
*/
public ResultSetIterator(ResultSet rs) {
this(rs, new BasicRowProcessor());
}
/**
* Constructor for ResultSetIterator.
* @param rs Wrap this <code>ResultSet</code> in an <code>Iterator</code>.
* @param convert The processor to use when converting a row into an
* <code>Object[]</code>. Defaults to a
* <code>BasicRowProcessor</code>.
*/
public ResultSetIterator(ResultSet rs, RowProcessor convert) {
this.rs = rs;
this.convert = convert;
}
/**
* Returns true if there are more rows in the ResultSet.
* @return boolean <code>true</code> if there are more rows
* @throws RuntimeException if an SQLException occurs.
*/
public boolean hasNext() {
try {
return !rs.isLast();
} catch (SQLException e) {
rethrow(e);
return false;
}
}
/**
* Returns the next row as an <code>Object[]</code>.
* @return An <code>Object[]</code> with the same number of elements as
* columns in the <code>ResultSet</code>.
* @see java.util.Iterator#next()
* @throws RuntimeException if an SQLException occurs.
*/
public Object[] next() {
try {
rs.next();
return this.convert.toArray(rs);
} catch (SQLException e) {
rethrow(e);
return null;
}
}
/**
* Deletes the current row from the <code>ResultSet</code>.
* @see java.util.Iterator#remove()
* @throws RuntimeException if an SQLException occurs.
*/
public void remove() {
try {
this.rs.deleteRow();
} catch (SQLException e) {
rethrow(e);
}
}
/**
* Rethrow the SQLException as a RuntimeException. This implementation
* creates a new RuntimeException with the SQLException's error message.
* @param e SQLException to rethrow
* @since DbUtils 1.1
*/
protected void rethrow(SQLException e) {
throw new RuntimeException(e.getMessage());
}
/** Generates an <code>Iterable</code>, suitable for use in for-each loops.
*
* @param rs Wrap this <code>ResultSet</code> in an <code>Iterator</code>.
* @return an <code>Iterable</code>, suitable for use in for-each loops.
*/
public static Iterable<Object[]> iterable(final ResultSet rs) {
return new Iterable<Object[]>() {
public Iterator<Object[]> iterator() {
return new ResultSetIterator(rs);
}
};
}
}
| removed trailing spaces
git-svn-id: a0b68194c4535a6dc73c52d151f88c541cb4b11d@1171752 13f79535-47bb-0310-9956-ffa450edef68
| src/java/org/apache/commons/dbutils/ResultSetIterator.java | removed trailing spaces | <ide><path>rc/java/org/apache/commons/dbutils/ResultSetIterator.java
<ide> * when you want to present a non-database application layer with domain
<ide> * neutral data.
<ide> * </p>
<del> *
<add> *
<ide> * <p>
<ide> * This implementation requires the <code>ResultSet.isLast()</code> method
<ide> * to be implemented.
<ide> * The wrapped <code>ResultSet</code>.
<ide> */
<ide> private final ResultSet rs;
<del>
<add>
<ide> /**
<ide> * The processor to use when converting a row into an Object[].
<ide> */
<ide> public ResultSetIterator(ResultSet rs) {
<ide> this(rs, new BasicRowProcessor());
<ide> }
<del>
<add>
<ide> /**
<ide> * Constructor for ResultSetIterator.
<ide> * @param rs Wrap this <code>ResultSet</code> in an <code>Iterator</code>.
<del> * @param convert The processor to use when converting a row into an
<add> * @param convert The processor to use when converting a row into an
<ide> * <code>Object[]</code>. Defaults to a
<ide> * <code>BasicRowProcessor</code>.
<ide> */
<ide> /**
<ide> * Returns the next row as an <code>Object[]</code>.
<ide> * @return An <code>Object[]</code> with the same number of elements as
<del> * columns in the <code>ResultSet</code>.
<add> * columns in the <code>ResultSet</code>.
<ide> * @see java.util.Iterator#next()
<ide> * @throws RuntimeException if an SQLException occurs.
<ide> */
<ide> throw new RuntimeException(e.getMessage());
<ide> }
<ide>
<del> /** Generates an <code>Iterable</code>, suitable for use in for-each loops.
<del> *
<add> /**
<add> * Generates an <code>Iterable</code>, suitable for use in for-each loops.
<add> *
<ide> * @param rs Wrap this <code>ResultSet</code> in an <code>Iterator</code>.
<ide> * @return an <code>Iterable</code>, suitable for use in for-each loops.
<ide> */
<ide> public Iterator<Object[]> iterator() {
<ide> return new ResultSetIterator(rs);
<ide> }
<del>
<add>
<ide> };
<ide> }
<del>
<add>
<ide> } |
|
Java | mit | 988b327efe5a3c0c1b8323425f982a8cea9bd25b | 0 | wskplho/AntennaPod,ChaoticMind/AntennaPod,domingos86/AntennaPod,queenp/AntennaPod,the100rabh/AntennaPod,wooi/AntennaPod,keunes/AntennaPod,hgl888/AntennaPod,hgl888/AntennaPod,wooi/AntennaPod,johnjohndoe/AntennaPod,corecode/AntennaPod,ChaoticMind/AntennaPod,volhol/AntennaPod,SpicyCurry/AntennaPod,LTUvac/AntennaPod,jimulabs/AntennaPod-mirror,wooi/AntennaPod,volhol/AntennaPod,domingos86/AntennaPod,gaohongyuan/AntennaPod,gk23/AntennaPod,twiceyuan/AntennaPod,twiceyuan/AntennaPod,udif/AntennaPod,corecode/AntennaPod,mfietz/AntennaPod,udif/AntennaPod,orelogo/AntennaPod,TomHennen/AntennaPod,gk23/AntennaPod,wangjun/AntennaPod,keunes/AntennaPod,waylife/AntennaPod,cdysthe/AntennaPod,TimB0/AntennaPod,gk23/AntennaPod,SpicyCurry/AntennaPod,SpicyCurry/AntennaPod,mxttie/AntennaPod,queenp/AntennaPod,wangjun/AntennaPod,orelogo/AntennaPod,waylife/AntennaPod,twiceyuan/AntennaPod,jimulabs/AntennaPod-mirror,richq/AntennaPod,TimB0/AntennaPod,LTUvac/AntennaPod,udif/AntennaPod,cdysthe/AntennaPod,waylife/AntennaPod,wooi/AntennaPod,TimB0/AntennaPod,johnjohndoe/AntennaPod,johnjohndoe/AntennaPod,LTUvac/AntennaPod,richq/AntennaPod,TimB0/AntennaPod,TomHennen/AntennaPod,mxttie/AntennaPod,gaohongyuan/AntennaPod,volhol/AntennaPod,the100rabh/AntennaPod,corecode/AntennaPod,corecode/AntennaPod,orelogo/AntennaPod,udif/AntennaPod,drabux/AntennaPod,gk23/AntennaPod,domingos86/AntennaPod,wangjun/AntennaPod,hgl888/AntennaPod,mxttie/AntennaPod,wangjun/AntennaPod,mxttie/AntennaPod,the100rabh/AntennaPod,wskplho/AntennaPod,richq/AntennaPod,keunes/AntennaPod,twiceyuan/AntennaPod,drabux/AntennaPod,samarone/AntennaPod,ChaoticMind/AntennaPod,samarone/AntennaPod,gaohongyuan/AntennaPod,jimulabs/AntennaPod-mirror,gaohongyuan/AntennaPod,TomHennen/AntennaPod,richq/AntennaPod,samarone/AntennaPod,mfietz/AntennaPod,domingos86/AntennaPod,drabux/AntennaPod,mfietz/AntennaPod,drabux/AntennaPod,TomHennen/AntennaPod,orelogo/AntennaPod,keunes/AntennaPod,the100rabh/AntennaPod,SpicyCurry/AntennaPod,wskplho/AntennaPod,mfietz/AntennaPod,cdysthe/AntennaPod,LTUvac/AntennaPod,johnjohndoe/AntennaPod,queenp/AntennaPod | package de.danoeh.antennapod.asynctask;
import android.content.Context;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.util.Log;
import android.webkit.MimeTypeMap;
import com.squareup.picasso.Cache;
import com.squareup.picasso.Downloader;
import com.squareup.picasso.LruCache;
import com.squareup.picasso.OkHttpDownloader;
import com.squareup.picasso.Picasso;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Provides access to Picasso instances.
*/
public class PicassoProvider {
private static final String TAG = "PicassoProvider";
private static final boolean DEBUG = false;
private static ExecutorService executorService;
private static Cache memoryCache;
private static Picasso defaultPicassoInstance;
private static Picasso mediaMetadataPicassoInstance;
private static synchronized ExecutorService getExecutorService() {
if (executorService == null) {
executorService = Executors.newFixedThreadPool(3);
}
return executorService;
}
private static synchronized Cache getMemoryCache(Context context) {
if (memoryCache == null) {
memoryCache = new LruCache(context);
}
return memoryCache;
}
/**
* Returns a Picasso instance that uses an OkHttpDownloader. This instance can only load images
* from image files.
* <p/>
* This instance should be used as long as no images from media files are loaded.
*/
public static synchronized Picasso getDefaultPicassoInstance(Context context) {
Validate.notNull(context);
if (defaultPicassoInstance == null) {
defaultPicassoInstance = new Picasso.Builder(context)
.indicatorsEnabled(DEBUG)
.loggingEnabled(DEBUG)
.downloader(new OkHttpDownloader(context))
.executor(getExecutorService())
.memoryCache(getMemoryCache(context))
.listener(new Picasso.Listener() {
@Override
public void onImageLoadFailed(Picasso picasso, Uri uri, Exception e) {
Log.e(TAG, "Failed to load Uri:" + uri.toString());
e.printStackTrace();
}
})
.build();
}
return defaultPicassoInstance;
}
/**
* Returns a Picasso instance that uses a MediaMetadataRetriever if the given Uri is a media file
* and a default OkHttpDownloader otherwise.
*/
public static synchronized Picasso getMediaMetadataPicassoInstance(Context context) {
Validate.notNull(context);
if (mediaMetadataPicassoInstance == null) {
mediaMetadataPicassoInstance = new Picasso.Builder(context)
.indicatorsEnabled(DEBUG)
.loggingEnabled(DEBUG)
.downloader(new MediaMetadataDownloader(context))
.executor(getExecutorService())
.memoryCache(getMemoryCache(context))
.listener(new Picasso.Listener() {
@Override
public void onImageLoadFailed(Picasso picasso, Uri uri, Exception e) {
Log.e(TAG, "Failed to load Uri:" + uri.toString());
e.printStackTrace();
}
})
.build();
}
return mediaMetadataPicassoInstance;
}
private static class MediaMetadataDownloader implements Downloader {
private static final String TAG = "MediaMetadataDownloader";
private final OkHttpDownloader okHttpDownloader;
public MediaMetadataDownloader(Context context) {
Validate.notNull(context);
okHttpDownloader = new OkHttpDownloader(context);
}
@Override
public Response load(Uri uri, boolean b) throws IOException {
if (StringUtils.equals(uri.getScheme(), PicassoImageResource.SCHEME_MEDIA)) {
String type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(FilenameUtils.getExtension(uri.getLastPathSegment()));
if (StringUtils.startsWith(type, "image")) {
File imageFile = new File(uri.toString());
return new Response(new BufferedInputStream(new FileInputStream(imageFile)), true, imageFile.length());
} else {
MediaMetadataRetriever mmr = new MediaMetadataRetriever();
mmr.setDataSource(uri.getPath());
byte[] data = mmr.getEmbeddedPicture();
mmr.release();
if (data != null) {
return new Response(new ByteArrayInputStream(data), true, data.length);
} else {
return null;
}
}
}
return okHttpDownloader.load(uri, b);
}
}
}
| src/de/danoeh/antennapod/asynctask/PicassoProvider.java | package de.danoeh.antennapod.asynctask;
import android.content.Context;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.util.Log;
import android.webkit.MimeTypeMap;
import com.squareup.picasso.Cache;
import com.squareup.picasso.Downloader;
import com.squareup.picasso.LruCache;
import com.squareup.picasso.OkHttpDownloader;
import com.squareup.picasso.Picasso;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Provides access to Picasso instances.
*/
public class PicassoProvider {
private static final String TAG = "PicassoProvider";
private static final boolean DEBUG = false;
private static ExecutorService executorService;
private static Cache memoryCache;
private static Picasso defaultPicassoInstance;
private static Picasso mediaMetadataPicassoInstance;
private static synchronized ExecutorService getExecutorService() {
if (executorService == null) {
executorService = Executors.newFixedThreadPool(3);
}
return executorService;
}
private static synchronized Cache getMemoryCache(Context context) {
if (memoryCache == null) {
memoryCache = new LruCache(context);
}
return memoryCache;
}
/**
* Returns a Picasso instance that uses an OkHttpDownloader. This instance can only load images
* from image files.
* <p/>
* This instance should be used as long as no images from media files are loaded.
*/
public static synchronized Picasso getDefaultPicassoInstance(Context context) {
Validate.notNull(context);
if (defaultPicassoInstance == null) {
defaultPicassoInstance = new Picasso.Builder(context)
.indicatorsEnabled(DEBUG)
.loggingEnabled(DEBUG)
.downloader(new OkHttpDownloader(context))
.executor(getExecutorService())
.memoryCache(getMemoryCache(context))
.listener(new Picasso.Listener() {
@Override
public void onImageLoadFailed(Picasso picasso, Uri uri, Exception e) {
Log.e(TAG, "Failed to load Uri:" + uri.toString());
e.printStackTrace();
}
})
.build();
}
return defaultPicassoInstance;
}
/**
* Returns a Picasso instance that uses a MediaMetadataRetriever if the given Uri is a media file
* and a default OkHttpDownloader otherwise.
*/
public static synchronized Picasso getMediaMetadataPicassoInstance(Context context) {
Validate.notNull(context);
if (mediaMetadataPicassoInstance == null) {
mediaMetadataPicassoInstance = new Picasso.Builder(context)
.indicatorsEnabled(DEBUG)
.loggingEnabled(DEBUG)
.downloader(new MediaMetadataDownloader(context))
.executor(getExecutorService())
.memoryCache(getMemoryCache(context))
.listener(new Picasso.Listener() {
@Override
public void onImageLoadFailed(Picasso picasso, Uri uri, Exception e) {
Log.e(TAG, "Failed to load Uri:" + uri.toString());
e.printStackTrace();
}
})
.build();
}
return mediaMetadataPicassoInstance;
}
private static class MediaMetadataDownloader implements Downloader {
private static final String TAG = "MediaMetadataDownloader";
private final OkHttpDownloader okHttpDownloader;
public MediaMetadataDownloader(Context context) {
Validate.notNull(context);
okHttpDownloader = new OkHttpDownloader(context);
}
@Override
public Response load(Uri uri, boolean b) throws IOException {
if (StringUtils.equals(uri.getScheme(), PicassoImageResource.SCHEME_MEDIA)) {
String type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(FilenameUtils.getExtension(uri.getLastPathSegment()));
if (StringUtils.startsWith(type, "image")) {
File imageFile = new File(uri.toString());
return new Response(new BufferedInputStream(new FileInputStream(imageFile)), true, imageFile.length());
} else {
MediaMetadataRetriever mmr = new MediaMetadataRetriever();
mmr.setDataSource(uri.getPath());
byte[] data = mmr.getEmbeddedPicture();
mmr.release();
return new Response(new ByteArrayInputStream(data), true, data.length);
}
}
return okHttpDownloader.load(uri, b);
}
}
}
| Fixed NullPointerException in PicassoProvider
| src/de/danoeh/antennapod/asynctask/PicassoProvider.java | Fixed NullPointerException in PicassoProvider | <ide><path>rc/de/danoeh/antennapod/asynctask/PicassoProvider.java
<ide> mmr.setDataSource(uri.getPath());
<ide> byte[] data = mmr.getEmbeddedPicture();
<ide> mmr.release();
<del> return new Response(new ByteArrayInputStream(data), true, data.length);
<add> if (data != null) {
<add> return new Response(new ByteArrayInputStream(data), true, data.length);
<add> } else {
<add> return null;
<add> }
<ide> }
<ide> }
<ide> |
|
Java | apache-2.0 | 7ca8e6b8407ef8b8608832f7962e9724b26b02a8 | 0 | mdunker/usergrid,mdunker/usergrid,mdunker/usergrid,mdunker/usergrid,mdunker/usergrid,mdunker/usergrid,mdunker/usergrid,mdunker/usergrid | package org.apache.usergrid.persistence.collection.cassandra;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import org.jukito.JukitoRunner;
import org.jukito.UseModules;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.usergrid.persistence.collection.guice.PropertyUtils;
import com.netflix.config.ConcurrentCompositeConfiguration;
import com.netflix.config.ConfigurationManager;
import com.netflix.config.DynamicConfiguration;
import com.netflix.config.FixedDelayPollingScheduler;
import com.netflix.config.sources.URLConfigurationSource;
import static org.apache.usergrid.persistence.collection.cassandra.ICassandraConfig.CASSANDRA_CLUSTER_NAME;
import static org.apache.usergrid.persistence.collection.cassandra.ICassandraConfig.CASSANDRA_CONNECTIONS;
import static org.apache.usergrid.persistence.collection.cassandra.ICassandraConfig.CASSANDRA_HOSTS;
import static org.apache.usergrid.persistence.collection.cassandra.ICassandraConfig.CASSANDRA_PORT;
import static org.apache.usergrid.persistence.collection.cassandra.ICassandraConfig.CASSANDRA_TIMEOUT;
import static org.apache.usergrid.persistence.collection.cassandra.ICassandraConfig.CASSANDRA_VERSION;
import static org.apache.usergrid.persistence.collection.cassandra.ICassandraConfig.COLLECTIONS_KEYSPACE_NAME;
import static junit.framework.Assert.assertEquals;
import static junit.framework.TestCase.assertNotNull;
import static junit.framework.Assert.assertTrue;
/**
* Tests the proper operation of the DynamicCassandraConfig.
*/
@RunWith( JukitoRunner.class )
public class DynamicCassandraConfigTest {
private static final String APP_CONFIG = "dynamic-test.properties";
private static final Logger LOG = LoggerFactory.getLogger( DynamicCassandraConfigTest.class );
private static final Properties original = PropertyUtils.loadFromClassPath( APP_CONFIG );
private static FixedDelayPollingScheduler scheduler;
private static DynamicConfiguration dynamicConfig;
private static ConcurrentCompositeConfiguration finalConfig;
@BeforeClass
public static void setup() {
scheduler = new FixedDelayPollingScheduler( 100, 100, false );
URLConfigurationSource source = new URLConfigurationSource( ClassLoader.getSystemResource( APP_CONFIG ) );
dynamicConfig = new DynamicConfiguration( source, scheduler );
finalConfig = new ConcurrentCompositeConfiguration();
finalConfig.addConfiguration( dynamicConfig );
ConfigurationManager.install( finalConfig );
}
@AfterClass
public static void restore() throws Exception {
write( original );
finalConfig.removeConfiguration( dynamicConfig );
scheduler.stop();
}
@Test
@UseModules( CassandraConfigModule.class )
public void testSingleEvent( IDynamicCassandraConfig config ) throws Exception {
final Set<ConfigChangeType> changes = new HashSet<ConfigChangeType>();
final List<CassandraConfigEvent> events = new ArrayList<CassandraConfigEvent>();
Properties properties = PropertyUtils.loadFromClassPath( APP_CONFIG );
String oldPort = properties.getProperty( CASSANDRA_PORT );
LOG.debug( "old port = {}", oldPort );
assertNotNull( config );
config.register( new CassandraConfigListener() {
@Override
public void reconfigurationEvent( final CassandraConfigEvent event ) {
LOG.debug( "got reconfiguration even: {}" + event );
changes.addAll( event.getChanges() );
events.add( event );
}
} );
// change the property
String newPort = getRandomNumber( oldPort );
LOG.debug( "new port = {}", oldPort );
properties.setProperty( CASSANDRA_PORT, newPort );
long startTime = System.currentTimeMillis();
write( properties );
while ( changes.isEmpty() ) {
Thread.sleep( 100L );
LOG.debug( "waking up" );
}
long propagationTime = System.currentTimeMillis() - startTime;
assertTrue( "the default notification delay is not working: propagation time = " + propagationTime,
propagationTime >= DynamicCassandraConfig.DEFAULT_NOTIFICATION_DELAY );
assertEquals( "there should only be one changed property", 1, changes.size() );
assertEquals( "there should only be one event", 1, events.size() );
assertEquals( "only the port should change", ConfigChangeType.PORT, changes.iterator().next() );
assertEquals( "the old port does not match", Integer.parseInt( oldPort ), events.get( 0 ).getOld().getPort() );
assertEquals( "the new port does not match", Integer.parseInt( newPort ), events.get( 0 ).getCurrent().getPort() );
assertEquals( "only one event change should be present", 1, events.get( 0 ).getChanges().size() );
assertTrue( "the port change should exist", events.get( 0 ).hasChange( ConfigChangeType.PORT ) );
}
@Test
@UseModules( CassandraConfigModule.class )
public void testAllEvents( IDynamicCassandraConfig config ) throws Exception {
final Set<ConfigChangeType> changes = new HashSet<ConfigChangeType>();
final List<CassandraConfigEvent> events = new ArrayList<CassandraConfigEvent>();
Properties properties = PropertyUtils.loadFromClassPath( APP_CONFIG );
String oldPort = properties.getProperty( CASSANDRA_PORT );
String oldConnections = properties.getProperty( CASSANDRA_CONNECTIONS );
String oldCluster = properties.getProperty( CASSANDRA_CLUSTER_NAME );
String oldHosts = properties.getProperty( CASSANDRA_HOSTS );
String oldTimeout = properties.getProperty( CASSANDRA_TIMEOUT );
String oldVersion = properties.getProperty( CASSANDRA_VERSION );
String oldKeyspace = properties.getProperty( COLLECTIONS_KEYSPACE_NAME );
LOG.debug( "old port = {}", oldPort );
LOG.debug( "old connections = {}", oldConnections );
LOG.debug( "old cluster = {}", oldCluster );
LOG.debug( "old hosts = {}", oldHosts );
LOG.debug( "old timeout = {}", oldTimeout );
LOG.debug( "old version = {}", oldVersion );
LOG.debug( "old keyspace = {}", oldKeyspace );
assertNotNull( config );
CassandraConfigListener listener = new CassandraConfigListener() {
@Override
public void reconfigurationEvent( final CassandraConfigEvent event ) {
LOG.debug( "got reconfiguration even: {}" + event );
changes.addAll( event.getChanges() );
events.add( event );
}
};
config.register( listener );
// change the property
String newPort = getRandomNumber( oldPort );
String newConnections = getRandomNumber( oldConnections );
String newCluster = getRandomString( oldCluster );
String newHosts = getRandomString( oldHosts );
String newTimeout = getRandomNumber( oldTimeout );
String newVersion = getRandomString( oldVersion );
String newKeyspace = getRandomString( oldKeyspace );
LOG.debug( "new port = {}", newPort );
LOG.debug( "new connections = {}", newConnections );
LOG.debug( "new cluster = {}", newCluster );
LOG.debug( "new hosts = {}", newHosts );
LOG.debug( "new timeout = {}", newTimeout );
LOG.debug( "new version = {}", newVersion );
LOG.debug( "new keyspace = {}", newKeyspace );
properties.setProperty( CASSANDRA_PORT, newPort );
properties.setProperty( CASSANDRA_CONNECTIONS, newConnections );
properties.setProperty( CASSANDRA_CLUSTER_NAME, newCluster );
properties.setProperty( CASSANDRA_HOSTS, newHosts );
properties.setProperty( CASSANDRA_TIMEOUT, newTimeout );
properties.setProperty( CASSANDRA_VERSION, newVersion );
properties.setProperty( COLLECTIONS_KEYSPACE_NAME, newKeyspace );
long startTime = System.currentTimeMillis();
write( properties );
while ( changes.size() < 7 ) {
Thread.sleep( 100L );
LOG.debug( "waking up" );
}
long propagationTime = System.currentTimeMillis() - startTime;
assertTrue( "the default notification delay is not working: propagation time = " + propagationTime,
propagationTime >= DynamicCassandraConfig.DEFAULT_NOTIFICATION_DELAY );
assertEquals( "there should be 7 changed properties", 7, changes.size() );
assertEquals( "there should only be one event", 1, events.size() );
assertEquals( "the old port does not match", Integer.parseInt( oldPort ), events.get( 0 ).getOld().getPort() );
assertEquals( "the new port does not match", Integer.parseInt( newPort ), events.get( 0 ).getCurrent().getPort() );
assertTrue( "the port change should exist", events.get( 0 ).hasChange( ConfigChangeType.PORT ) );
assertEquals( "the old connections does not match", Integer.parseInt( oldConnections ), events.get( 0 ).getOld().getConnections() );
assertEquals( "the new connections does not match", Integer.parseInt( newConnections ), events.get( 0 ).getCurrent().getConnections() );
assertTrue( "the connections change should exist", events.get( 0 ).hasChange( ConfigChangeType.CONNECTIONS ) );
assertEquals( "the old cluster does not match", oldCluster, events.get( 0 ).getOld().getClusterName() );
assertEquals( "the new cluster does not match", newCluster, events.get( 0 ).getCurrent().getClusterName() );
assertTrue( "the cluster change should exist", events.get( 0 ).hasChange( ConfigChangeType.CLUSTER_NAME ) );
assertEquals( "the old hosts does not match", oldHosts, events.get( 0 ).getOld().getHosts() );
assertEquals( "the new hosts does not match", newHosts, events.get( 0 ).getCurrent().getHosts() );
assertTrue( "the hosts change should exist", events.get( 0 ).hasChange( ConfigChangeType.HOSTS ) );
assertEquals( "the old timeout does not match", Integer.parseInt( oldTimeout ), events.get( 0 ).getOld().getTimeout() );
assertEquals( "the new timeout does not match", Integer.parseInt( newTimeout ), events.get( 0 ).getCurrent().getTimeout() );
assertTrue( "the timeout change should exist", events.get( 0 ).hasChange( ConfigChangeType.TIMEOUT ) );
assertEquals( "the old version does not match", oldVersion, events.get( 0 ).getOld().getVersion() );
assertEquals( "the new version does not match", newVersion, events.get( 0 ).getCurrent().getVersion() );
assertTrue( "the version change should exist", events.get( 0 ).hasChange( ConfigChangeType.VERSION ) );
assertEquals( "the old keyspace does not match", oldKeyspace, events.get( 0 ).getOld().getKeyspaceName() );
assertEquals( "the new keyspace does not match", newKeyspace, events.get( 0 ).getCurrent().getKeyspaceName() );
assertTrue( "the keyspace change should exist", events.get( 0 ).hasChange( ConfigChangeType.KEYSPACE_NAME ) );
assertEquals( "7 event change should be present", 7, events.get( 0 ).getChanges().size() );
// now we test that unregister actually works
changes.clear();
events.clear();
config.unregister( listener );
write( original );
Thread.sleep( DynamicCassandraConfig.DEFAULT_NOTIFICATION_DELAY );
assertTrue( "events should be empty with listener removed", events.isEmpty() );
assertTrue( "changes should be empty with listener removed", changes.isEmpty() );
}
private static void write( Properties properties ) throws IOException {
URL path = ClassLoader.getSystemClassLoader().getResource( APP_CONFIG );
assert path != null;
File file = new File( path.getFile() );
FileOutputStream out = new FileOutputStream( file );
properties.store( out, null );
out.flush();
out.close();
}
private static String getRandomString( String oldValue ) {
if ( oldValue == null ) {
return RandomStringUtils.randomAlphabetic( 7 );
}
// make sure we do not generate random port same as old - no change event that way
String newValue = RandomStringUtils.randomAlphabetic( oldValue.length() );
while ( newValue.equals( oldValue ) ) {
newValue = RandomStringUtils.randomAlphabetic( oldValue.length() );
}
return newValue;
}
private static String getRandomNumber( String oldNumber ) {
if ( oldNumber == null ) {
return RandomStringUtils.randomNumeric( 4 );
}
// make sure we do not generate random number same as old - no change event that way
String newValue = RandomStringUtils.randomNumeric( oldNumber.length() );
while ( newValue.equals( oldNumber) ) {
newValue = RandomStringUtils.randomNumeric( oldNumber.length() );
}
return newValue;
}
}
| stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/cassandra/DynamicCassandraConfigTest.java | package org.apache.usergrid.persistence.collection.cassandra;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import org.jukito.JukitoRunner;
import org.jukito.UseModules;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.usergrid.persistence.collection.guice.PropertyUtils;
import com.netflix.config.ConcurrentCompositeConfiguration;
import com.netflix.config.ConfigurationManager;
import com.netflix.config.DynamicConfiguration;
import com.netflix.config.FixedDelayPollingScheduler;
import com.netflix.config.sources.URLConfigurationSource;
import static org.apache.usergrid.persistence.collection.cassandra.ICassandraConfig.CASSANDRA_CLUSTER_NAME;
import static org.apache.usergrid.persistence.collection.cassandra.ICassandraConfig.CASSANDRA_CONNECTIONS;
import static org.apache.usergrid.persistence.collection.cassandra.ICassandraConfig.CASSANDRA_HOSTS;
import static org.apache.usergrid.persistence.collection.cassandra.ICassandraConfig.CASSANDRA_PORT;
import static org.apache.usergrid.persistence.collection.cassandra.ICassandraConfig.CASSANDRA_TIMEOUT;
import static org.apache.usergrid.persistence.collection.cassandra.ICassandraConfig.CASSANDRA_VERSION;
import static org.apache.usergrid.persistence.collection.cassandra.ICassandraConfig.COLLECTIONS_KEYSPACE_NAME;
import static junit.framework.Assert.assertEquals;
import static junit.framework.TestCase.assertNotNull;
import static junit.framework.Assert.assertTrue;
/**
* Tests the proper operation of the DynamicCassandraConfig.
*/
@RunWith( JukitoRunner.class )
public class DynamicCassandraConfigTest {
private static final String APP_CONFIG = "dynamic-test.properties";
private static final Logger LOG = LoggerFactory.getLogger( DynamicCassandraConfigTest.class );
private static final Properties original = PropertyUtils.loadFromClassPath( APP_CONFIG );
private static FixedDelayPollingScheduler scheduler;
private static DynamicConfiguration dynamicConfig;
private static ConcurrentCompositeConfiguration finalConfig;
@BeforeClass
public static void setup() {
scheduler = new FixedDelayPollingScheduler( 100, 100, false );
URLConfigurationSource source = new URLConfigurationSource( ClassLoader.getSystemResource( APP_CONFIG ) );
dynamicConfig = new DynamicConfiguration( source, scheduler );
finalConfig = new ConcurrentCompositeConfiguration();
finalConfig.addConfiguration( dynamicConfig );
ConfigurationManager.install( finalConfig );
}
@AfterClass
public static void restore() throws Exception {
write( original );
finalConfig.removeConfiguration( finalConfig );
scheduler.stop();
}
@Test
@UseModules( CassandraConfigModule.class )
public void testSingleEvent( IDynamicCassandraConfig config ) throws Exception {
final Set<ConfigChangeType> changes = new HashSet<ConfigChangeType>();
final List<CassandraConfigEvent> events = new ArrayList<CassandraConfigEvent>();
Properties properties = PropertyUtils.loadFromClassPath( APP_CONFIG );
String oldPort = properties.getProperty( CASSANDRA_PORT );
LOG.debug( "old port = {}", oldPort );
assertNotNull( config );
config.register( new CassandraConfigListener() {
@Override
public void reconfigurationEvent( final CassandraConfigEvent event ) {
LOG.debug( "got reconfiguration even: {}" + event );
changes.addAll( event.getChanges() );
events.add( event );
}
} );
// change the property
String newPort = getRandomNumber( oldPort );
LOG.debug( "new port = {}", oldPort );
properties.setProperty( CASSANDRA_PORT, newPort );
long startTime = System.currentTimeMillis();
write( properties );
while ( changes.isEmpty() ) {
Thread.sleep( 100L );
LOG.debug( "waking up" );
}
long propagationTime = System.currentTimeMillis() - startTime;
assertTrue( "the default notification delay is not working: propagation time = " + propagationTime,
propagationTime >= DynamicCassandraConfig.DEFAULT_NOTIFICATION_DELAY );
assertEquals( "there should only be one changed property", 1, changes.size() );
assertEquals( "there should only be one event", 1, events.size() );
assertEquals( "only the port should change", ConfigChangeType.PORT, changes.iterator().next() );
assertEquals( "the old port does not match", Integer.parseInt( oldPort ), events.get( 0 ).getOld().getPort() );
assertEquals( "the new port does not match", Integer.parseInt( newPort ), events.get( 0 ).getCurrent().getPort() );
assertEquals( "only one event change should be present", 1, events.get( 0 ).getChanges().size() );
assertTrue( "the port change should exist", events.get( 0 ).hasChange( ConfigChangeType.PORT ) );
}
@Test
@UseModules( CassandraConfigModule.class )
public void testAllEvents( IDynamicCassandraConfig config ) throws Exception {
final Set<ConfigChangeType> changes = new HashSet<ConfigChangeType>();
final List<CassandraConfigEvent> events = new ArrayList<CassandraConfigEvent>();
Properties properties = PropertyUtils.loadFromClassPath( APP_CONFIG );
String oldPort = properties.getProperty( CASSANDRA_PORT );
String oldConnections = properties.getProperty( CASSANDRA_CONNECTIONS );
String oldCluster = properties.getProperty( CASSANDRA_CLUSTER_NAME );
String oldHosts = properties.getProperty( CASSANDRA_HOSTS );
String oldTimeout = properties.getProperty( CASSANDRA_TIMEOUT );
String oldVersion = properties.getProperty( CASSANDRA_VERSION );
String oldKeyspace = properties.getProperty( COLLECTIONS_KEYSPACE_NAME );
LOG.debug( "old port = {}", oldPort );
LOG.debug( "old connections = {}", oldConnections );
LOG.debug( "old cluster = {}", oldCluster );
LOG.debug( "old hosts = {}", oldHosts );
LOG.debug( "old timeout = {}", oldTimeout );
LOG.debug( "old version = {}", oldVersion );
LOG.debug( "old keyspace = {}", oldKeyspace );
assertNotNull( config );
CassandraConfigListener listener = new CassandraConfigListener() {
@Override
public void reconfigurationEvent( final CassandraConfigEvent event ) {
LOG.debug( "got reconfiguration even: {}" + event );
changes.addAll( event.getChanges() );
events.add( event );
}
};
config.register( listener );
// change the property
String newPort = getRandomNumber( oldPort );
String newConnections = getRandomNumber( oldConnections );
String newCluster = getRandomString( oldCluster );
String newHosts = getRandomString( oldHosts );
String newTimeout = getRandomNumber( oldTimeout );
String newVersion = getRandomString( oldVersion );
String newKeyspace = getRandomString( oldKeyspace );
LOG.debug( "new port = {}", newPort );
LOG.debug( "new connections = {}", newConnections );
LOG.debug( "new cluster = {}", newCluster );
LOG.debug( "new hosts = {}", newHosts );
LOG.debug( "new timeout = {}", newTimeout );
LOG.debug( "new version = {}", newVersion );
LOG.debug( "new keyspace = {}", newKeyspace );
properties.setProperty( CASSANDRA_PORT, newPort );
properties.setProperty( CASSANDRA_CONNECTIONS, newConnections );
properties.setProperty( CASSANDRA_CLUSTER_NAME, newCluster );
properties.setProperty( CASSANDRA_HOSTS, newHosts );
properties.setProperty( CASSANDRA_TIMEOUT, newTimeout );
properties.setProperty( CASSANDRA_VERSION, newVersion );
properties.setProperty( COLLECTIONS_KEYSPACE_NAME, newKeyspace );
long startTime = System.currentTimeMillis();
write( properties );
while ( changes.size() < 7 ) {
Thread.sleep( 100L );
LOG.debug( "waking up" );
}
long propagationTime = System.currentTimeMillis() - startTime;
assertTrue( "the default notification delay is not working: propagation time = " + propagationTime,
propagationTime >= DynamicCassandraConfig.DEFAULT_NOTIFICATION_DELAY );
assertEquals( "there should be 7 changed properties", 7, changes.size() );
assertEquals( "there should only be one event", 1, events.size() );
assertEquals( "the old port does not match", Integer.parseInt( oldPort ), events.get( 0 ).getOld().getPort() );
assertEquals( "the new port does not match", Integer.parseInt( newPort ), events.get( 0 ).getCurrent().getPort() );
assertTrue( "the port change should exist", events.get( 0 ).hasChange( ConfigChangeType.PORT ) );
assertEquals( "the old connections does not match", Integer.parseInt( oldConnections ), events.get( 0 ).getOld().getConnections() );
assertEquals( "the new connections does not match", Integer.parseInt( newConnections ), events.get( 0 ).getCurrent().getConnections() );
assertTrue( "the connections change should exist", events.get( 0 ).hasChange( ConfigChangeType.CONNECTIONS ) );
assertEquals( "the old cluster does not match", oldCluster, events.get( 0 ).getOld().getClusterName() );
assertEquals( "the new cluster does not match", newCluster, events.get( 0 ).getCurrent().getClusterName() );
assertTrue( "the cluster change should exist", events.get( 0 ).hasChange( ConfigChangeType.CLUSTER_NAME ) );
assertEquals( "the old hosts does not match", oldHosts, events.get( 0 ).getOld().getHosts() );
assertEquals( "the new hosts does not match", newHosts, events.get( 0 ).getCurrent().getHosts() );
assertTrue( "the hosts change should exist", events.get( 0 ).hasChange( ConfigChangeType.HOSTS ) );
assertEquals( "the old timeout does not match", Integer.parseInt( oldTimeout ), events.get( 0 ).getOld().getTimeout() );
assertEquals( "the new timeout does not match", Integer.parseInt( newTimeout ), events.get( 0 ).getCurrent().getTimeout() );
assertTrue( "the timeout change should exist", events.get( 0 ).hasChange( ConfigChangeType.TIMEOUT ) );
assertEquals( "the old version does not match", oldVersion, events.get( 0 ).getOld().getVersion() );
assertEquals( "the new version does not match", newVersion, events.get( 0 ).getCurrent().getVersion() );
assertTrue( "the version change should exist", events.get( 0 ).hasChange( ConfigChangeType.VERSION ) );
assertEquals( "the old keyspace does not match", oldKeyspace, events.get( 0 ).getOld().getKeyspaceName() );
assertEquals( "the new keyspace does not match", newKeyspace, events.get( 0 ).getCurrent().getKeyspaceName() );
assertTrue( "the keyspace change should exist", events.get( 0 ).hasChange( ConfigChangeType.KEYSPACE_NAME ) );
assertEquals( "7 event change should be present", 7, events.get( 0 ).getChanges().size() );
// now we test that unregister actually works
changes.clear();
events.clear();
config.unregister( listener );
write( original );
Thread.sleep( DynamicCassandraConfig.DEFAULT_NOTIFICATION_DELAY );
assertTrue( "events should be empty with listener removed", events.isEmpty() );
assertTrue( "changes should be empty with listener removed", changes.isEmpty() );
}
private static void write( Properties properties ) throws IOException {
URL path = ClassLoader.getSystemClassLoader().getResource( APP_CONFIG );
assert path != null;
File file = new File( path.getFile() );
FileOutputStream out = new FileOutputStream( file );
properties.store( out, null );
out.flush();
out.close();
}
private static String getRandomString( String oldValue ) {
if ( oldValue == null ) {
return RandomStringUtils.randomAlphabetic( 7 );
}
// make sure we do not generate random port same as old - no change event that way
String newValue = RandomStringUtils.randomAlphabetic( oldValue.length() );
while ( newValue.equals( oldValue ) ) {
newValue = RandomStringUtils.randomAlphabetic( oldValue.length() );
}
return newValue;
}
private static String getRandomNumber( String oldNumber ) {
if ( oldNumber == null ) {
return RandomStringUtils.randomNumeric( 4 );
}
// make sure we do not generate random number same as old - no change event that way
String newValue = RandomStringUtils.randomNumeric( oldNumber.length() );
while ( newValue.equals( oldNumber) ) {
newValue = RandomStringUtils.randomNumeric( oldNumber.length() );
}
return newValue;
}
}
| found small bug in test where config was not removed from archaius: little impact
| stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/cassandra/DynamicCassandraConfigTest.java | found small bug in test where config was not removed from archaius: little impact | <ide><path>tack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/cassandra/DynamicCassandraConfigTest.java
<ide> @AfterClass
<ide> public static void restore() throws Exception {
<ide> write( original );
<del> finalConfig.removeConfiguration( finalConfig );
<add> finalConfig.removeConfiguration( dynamicConfig );
<ide> scheduler.stop();
<ide> }
<ide> |
|
Java | apache-2.0 | fdf97f23bb80d5f80942895856266c11feee8feb | 0 | anchela/jackrabbit-oak,apache/jackrabbit-oak,apache/jackrabbit-oak,mreutegg/jackrabbit-oak,mreutegg/jackrabbit-oak,amit-jain/jackrabbit-oak,trekawek/jackrabbit-oak,trekawek/jackrabbit-oak,trekawek/jackrabbit-oak,anchela/jackrabbit-oak,amit-jain/jackrabbit-oak,amit-jain/jackrabbit-oak,amit-jain/jackrabbit-oak,anchela/jackrabbit-oak,mreutegg/jackrabbit-oak,amit-jain/jackrabbit-oak,apache/jackrabbit-oak,anchela/jackrabbit-oak,anchela/jackrabbit-oak,apache/jackrabbit-oak,mreutegg/jackrabbit-oak,trekawek/jackrabbit-oak,trekawek/jackrabbit-oak,apache/jackrabbit-oak,mreutegg/jackrabbit-oak | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.jackrabbit.oak.plugins.index.lucene;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.annotation.CheckForNull;
import com.google.common.collect.Iterables;
import org.apache.jackrabbit.JcrConstants;
import org.apache.jackrabbit.oak.commons.PathUtils;
import org.apache.jackrabbit.oak.plugins.index.lucene.IndexDefinition.IndexingRule;
import org.apache.jackrabbit.oak.query.fulltext.FullTextExpression;
import org.apache.jackrabbit.oak.query.fulltext.FullTextTerm;
import org.apache.jackrabbit.oak.query.fulltext.FullTextVisitor;
import org.apache.jackrabbit.oak.spi.query.Filter;
import org.apache.lucene.index.IndexReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Lists.newArrayListWithCapacity;
import static com.google.common.collect.Maps.newHashMap;
import static org.apache.jackrabbit.oak.commons.PathUtils.getAncestorPath;
import static org.apache.jackrabbit.oak.commons.PathUtils.getDepth;
import static org.apache.jackrabbit.oak.commons.PathUtils.getParentPath;
import static org.apache.jackrabbit.oak.spi.query.Filter.PropertyRestriction;
import static org.apache.jackrabbit.oak.spi.query.QueryIndex.IndexPlan;
import static org.apache.jackrabbit.oak.spi.query.QueryIndex.OrderEntry;
class IndexPlanner {
private static final Logger log = LoggerFactory.getLogger(IndexPlanner.class);
private final IndexDefinition defn;
private final Filter filter;
private final String indexPath;
private final List<OrderEntry> sortOrder;
private IndexNode indexNode;
private PlanResult result;
public IndexPlanner(IndexNode indexNode,
String indexPath,
Filter filter, List<OrderEntry> sortOrder) {
this.indexNode = indexNode;
this.indexPath = indexPath;
this.defn = indexNode.getDefinition();
this.filter = filter;
this.sortOrder = sortOrder;
}
IndexPlan getPlan() {
IndexPlan.Builder builder = getPlanBuilder();
if (defn.isTestMode()){
if ( builder == null) {
if (notSupportedFeature()) {
return null;
}
String msg = String.format("No plan found for filter [%s] " +
"while using definition [%s] and testMode is found to be enabled", filter, defn);
throw new IllegalStateException(msg);
} else {
builder.setEstimatedEntryCount(1)
.setCostPerExecution(1e-3)
.setCostPerEntry(1e-3);
}
}
return builder != null ? builder.build() : null;
}
@Override
public String toString() {
return "IndexPlanner{" +
"indexPath='" + indexPath + '\'' +
", filter=" + filter +
", sortOrder=" + sortOrder +
'}';
}
private IndexPlan.Builder getPlanBuilder() {
log.trace("Evaluating plan with index definition {}", defn);
FullTextExpression ft = filter.getFullTextConstraint();
if (!defn.getVersion().isAtLeast(IndexFormatVersion.V2)){
log.trace("Index is old format. Not supported");
return null;
}
//Query Fulltext and Index does not support fulltext
if (ft != null && !defn.isFullTextEnabled()) {
return null;
}
IndexingRule indexingRule = getApplicableRule();
if (indexingRule == null){
return null;
}
//Query Fulltext and indexing rule does not support fulltext
if (ft != null && !indexingRule.isFulltextEnabled()){
return null;
}
result = new PlanResult(indexPath, defn, indexingRule);
if (defn.hasFunctionDefined()
&& filter.getPropertyRestriction(defn.getFunctionName()) != null) {
//If native function is handled by this index then ensure
// that lowest cost if returned
return defaultPlan().setEstimatedEntryCount(1);
}
List<String> indexedProps = newArrayListWithCapacity(filter.getPropertyRestrictions().size());
//Optimization - Go further only if any of the property is configured
//for property index
if (indexingRule.propertyIndexEnabled) {
for (PropertyRestriction pr : filter.getPropertyRestrictions()) {
PropertyDefinition pd = indexingRule.getConfig(pr.propertyName);
if (pd != null && pd.propertyIndexEnabled()) {
indexedProps.add(pr.propertyName);
result.propDefns.put(pr.propertyName, pd);
}
}
}
boolean evalPathRestrictions = canEvalPathRestrictions();
boolean canEvalAlFullText = canEvalAllFullText(indexingRule, ft);
if (ft != null && !canEvalAlFullText){
return null;
}
//Fulltext expression can also be like jcr:contains(jcr:content/metadata/@format, 'image')
List<OrderEntry> sortOrder = createSortOrder(indexingRule);
if (!indexedProps.isEmpty() || !sortOrder.isEmpty() || ft != null || evalPathRestrictions) {
//TODO Need a way to have better cost estimate to indicate that
//this index can evaluate more propertyRestrictions natively (if more props are indexed)
//For now we reduce cost per entry
int costPerEntryFactor = indexedProps.size();
costPerEntryFactor += sortOrder.size();
//this index can evaluate more propertyRestrictions natively (if more props are indexed)
//For now we reduce cost per entry
IndexPlan.Builder plan = defaultPlan();
if (!sortOrder.isEmpty()) {
plan.setSortOrder(sortOrder);
}
if (costPerEntryFactor == 0){
costPerEntryFactor = 1;
}
if (ft == null){
result.enableNonFullTextConstraints();
}
return plan.setCostPerEntry(defn.getCostPerEntry() / costPerEntryFactor);
}
//TODO Support for property existence queries
//TODO support for nodeName queries
//Above logic would not return any plan for pure nodeType based query like
//select * from nt:unstructured. We can do that but this is better handled
//by NodeType index
return null;
}
private boolean canEvalAllFullText(final IndexingRule indexingRule, FullTextExpression ft) {
if (ft == null){
return false;
}
final HashSet<String> relPaths = new HashSet<String>();
final HashSet<String> nonIndexedPaths = new HashSet<String>();
final AtomicBoolean relativeParentsFound = new AtomicBoolean();
ft.accept(new FullTextVisitor.FullTextVisitorBase() {
@Override
public boolean visit(FullTextTerm term) {
String p = term.getPropertyName();
String propertyPath = null;
String nodePath = null;
if (p == null) {
relPaths.add("");
} else if (p.startsWith("../") || p.startsWith("./")) {
relPaths.add(p);
relativeParentsFound.set(true);
} else if (getDepth(p) > 1) {
String parent = getParentPath(p);
if (LucenePropertyIndex.isNodePath(p)){
nodePath = parent;
} else {
propertyPath = p;
}
relPaths.add(parent);
} else {
propertyPath = p;
relPaths.add("");
}
if (nodePath != null
&& !indexingRule.isAggregated(nodePath)){
nonIndexedPaths.add(p);
} else if (propertyPath != null
&& !indexingRule.isIndexed(propertyPath)){
nonIndexedPaths.add(p);
}
return true;
}
});
if (relativeParentsFound.get()){
log.debug("Relative parents found {} which are not supported", relPaths);
return false;
}
if (!nonIndexedPaths.isEmpty()){
if (relPaths.size() > 1){
log.debug("Following relative property paths are not index", relPaths);
return false;
}
result.setParentPath(Iterables.getOnlyElement(relPaths, ""));
//Such path translation would only work if index contains
//all the nodes
return defn.indexesAllTypes();
} else {
result.setParentPath("");
}
return true;
}
private boolean canEvalPathRestrictions() {
if (filter.getPathRestriction() == Filter.PathRestriction.NO_RESTRICTION){
return false;
}
//TODO If no other restrictions is provided and query is pure
//path restriction based then need to be sure that index definition at least
//allows indexing all the path for given nodeType
return defn.evaluatePathRestrictions();
}
private IndexPlan.Builder defaultPlan() {
return new IndexPlan.Builder()
.setCostPerExecution(defn.getCostPerExecution())
.setCostPerEntry(defn.getCostPerEntry())
.setFulltextIndex(defn.isFullTextEnabled())
.setIncludesNodeData(false) // we should not include node data
.setFilter(filter)
.setPathPrefix(getPathPrefix())
.setDelayed(true) //Lucene is always async
.setAttribute(LucenePropertyIndex.ATTR_PLAN_RESULT, result)
.setEstimatedEntryCount(estimatedEntryCount());
}
private long estimatedEntryCount() {
//Other index only compete in case of property indexes. For fulltext
//index return true count so as to allow multiple property indexes
//to be compared fairly
FullTextExpression ft = filter.getFullTextConstraint();
if (ft != null && defn.isFullTextEnabled()){
return defn.getFulltextEntryCount(getReader().numDocs());
}
return Math.min(defn.getEntryCount(), getReader().numDocs());
}
private String getPathPrefix() {
// 2 = /oak:index/<index name>
String parentPath = PathUtils.getAncestorPath(indexPath, 2);
return PathUtils.denotesRoot(parentPath) ? "" : parentPath;
}
private IndexReader getReader() {
return indexNode.getSearcher().getIndexReader();
}
private List<OrderEntry> createSortOrder(IndexingRule rule) {
if (sortOrder == null) {
return Collections.emptyList();
}
List<OrderEntry> orderEntries = newArrayListWithCapacity(sortOrder.size());
for (OrderEntry o : sortOrder) {
PropertyDefinition pd = rule.getConfig(o.getPropertyName());
if (pd != null
&& pd.ordered
&& o.getPropertyType() != null
&& !o.getPropertyType().isArray()) {
orderEntries.add(o); //Lucene can manage any order desc/asc
result.sortedProperties.add(pd);
}
}
//TODO Should we return order entries only when all order clauses are satisfied
return orderEntries;
}
@CheckForNull
private IndexingRule getApplicableRule() {
if (filter.matchesAllTypes()){
return defn.getApplicableIndexingRule(JcrConstants.NT_BASE);
} else {
//TODO May be better if filter.getSuperTypes returned a list which maintains
//inheritance order and then we iterate over that
for (IndexingRule rule : defn.getDefinedRules()){
if (filter.getSupertypes().contains(rule.getNodeTypeName())){
//Theoretically there may be multiple rules for same nodeType with
//some condition defined. So again find a rule which applies
IndexingRule matchingRule = defn.getApplicableIndexingRule(rule.getNodeTypeName());
if (matchingRule != null){
log.debug("Applicable IndexingRule found {}", matchingRule);
return rule;
}
}
//nt:base is applicable for all. This specific condition is
//required to support mixin case as filter.getSupertypes() for mixin based
//query only includes the mixin type and not nt:base
if (rule.getNodeTypeName().equals(JcrConstants.NT_BASE)){
return rule;
}
}
log.trace("No applicable IndexingRule found for any of the superTypes {}",
filter.getSupertypes());
}
return null;
}
private boolean notSupportedFeature() {
if(filter.getPathRestriction() == Filter.PathRestriction.NO_RESTRICTION
&& filter.matchesAllTypes()
&& filter.getPropertyRestrictions().isEmpty()){
//This mode includes name(), localname() queries
//OrImpl [a/name] = 'Hello' or [b/name] = 'World'
//Relative parent properties where [../foo1] is not null
return true;
}
return false;
}
//~--------------------------------------------------------< PlanResult >
public static class PlanResult {
final String indexPath;
final IndexDefinition indexDefinition;
final IndexingRule indexingRule;
private List<PropertyDefinition> sortedProperties = newArrayList();
private Map<String, PropertyDefinition> propDefns = newHashMap();
private boolean nonFullTextConstraints;
private int parentDepth;
private String parentPathSegment;
private boolean relativize;
public PlanResult(String indexPath, IndexDefinition defn, IndexingRule indexingRule) {
this.indexPath = indexPath;
this.indexDefinition = defn;
this.indexingRule = indexingRule;
}
public PropertyDefinition getPropDefn(PropertyRestriction pr){
return propDefns.get(pr.propertyName);
}
public PropertyDefinition getOrderedProperty(int index){
return sortedProperties.get(index);
}
public boolean isPathTransformed(){
return relativize;
}
/**
* Transforms the given path if the query involved relative properties and index
* is not making use of aggregated properties. If the path
*
* @param path path to transform
* @return transformed path. Returns null if the path does not confirm to relative
* path requirements
*/
@CheckForNull
public String transformPath(String path){
if (isPathTransformed()){
// get the base path
// ensure the path ends with the given
// relative path
if (!path.endsWith(parentPathSegment)) {
return null;
}
return getAncestorPath(path, parentDepth);
}
return path;
}
public boolean evaluateNonFullTextConstraints(){
return nonFullTextConstraints;
}
private void setParentPath(String relativePath){
parentPathSegment = "/" + relativePath;
if (relativePath.isEmpty()){
// we only restrict non-full-text conditions if there is
// no relative property in the full-text constraint
enableNonFullTextConstraints();
} else {
relativize = true;
parentDepth = getDepth(relativePath);
}
}
private void enableNonFullTextConstraints(){
nonFullTextConstraints = true;
}
}
}
| oak-lucene/src/main/java/org/apache/jackrabbit/oak/plugins/index/lucene/IndexPlanner.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.jackrabbit.oak.plugins.index.lucene;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.annotation.CheckForNull;
import com.google.common.collect.Iterables;
import org.apache.jackrabbit.JcrConstants;
import org.apache.jackrabbit.oak.commons.PathUtils;
import org.apache.jackrabbit.oak.plugins.index.lucene.IndexDefinition.IndexingRule;
import org.apache.jackrabbit.oak.query.fulltext.FullTextExpression;
import org.apache.jackrabbit.oak.query.fulltext.FullTextTerm;
import org.apache.jackrabbit.oak.query.fulltext.FullTextVisitor;
import org.apache.jackrabbit.oak.spi.query.Filter;
import org.apache.lucene.index.IndexReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Lists.newArrayListWithCapacity;
import static com.google.common.collect.Maps.newHashMap;
import static org.apache.jackrabbit.oak.commons.PathUtils.getAncestorPath;
import static org.apache.jackrabbit.oak.commons.PathUtils.getDepth;
import static org.apache.jackrabbit.oak.commons.PathUtils.getParentPath;
import static org.apache.jackrabbit.oak.spi.query.Filter.PropertyRestriction;
import static org.apache.jackrabbit.oak.spi.query.QueryIndex.IndexPlan;
import static org.apache.jackrabbit.oak.spi.query.QueryIndex.OrderEntry;
class IndexPlanner {
private static final Logger log = LoggerFactory.getLogger(IndexPlanner.class);
private final IndexDefinition defn;
private final Filter filter;
private final String indexPath;
private final List<OrderEntry> sortOrder;
private IndexNode indexNode;
private PlanResult result;
public IndexPlanner(IndexNode indexNode,
String indexPath,
Filter filter, List<OrderEntry> sortOrder) {
this.indexNode = indexNode;
this.indexPath = indexPath;
this.defn = indexNode.getDefinition();
this.filter = filter;
this.sortOrder = sortOrder;
}
IndexPlan getPlan() {
IndexPlan.Builder builder = getPlanBuilder();
if (defn.isTestMode()){
if ( builder == null) {
if (notSupportedFeature()) {
return null;
}
String msg = String.format("No plan found for filter [%s] " +
"while using definition [%s] and testMode is found to be enabled", filter, defn);
throw new IllegalStateException(msg);
} else {
builder.setEstimatedEntryCount(1)
.setCostPerExecution(1e-3)
.setCostPerEntry(1e-3);
}
}
return builder != null ? builder.build() : null;
}
@Override
public String toString() {
return "IndexPlanner{" +
"indexPath='" + indexPath + '\'' +
", filter=" + filter +
", sortOrder=" + sortOrder +
'}';
}
private IndexPlan.Builder getPlanBuilder() {
log.trace("Evaluating plan with index definition {}", defn);
FullTextExpression ft = filter.getFullTextConstraint();
if (!defn.getVersion().isAtLeast(IndexFormatVersion.V2)){
log.trace("Index is old format. Not supported");
return null;
}
//Query Fulltext and Index does not support fulltext
if (ft != null && !defn.isFullTextEnabled()) {
return null;
}
IndexingRule indexingRule = getApplicableRule();
if (indexingRule == null){
return null;
}
//Query Fulltext and indexing rule does not support fulltext
if (ft != null && !indexingRule.isFulltextEnabled()){
return null;
}
result = new PlanResult(indexPath, defn, indexingRule);
if (defn.hasFunctionDefined()
&& filter.getPropertyRestriction(defn.getFunctionName()) != null) {
//If native function is handled by this index then ensure
// that lowest cost if returned
return defaultPlan().setEstimatedEntryCount(1);
}
List<String> indexedProps = newArrayListWithCapacity(filter.getPropertyRestrictions().size());
//Optimization - Go further only if any of the property is configured
//for property index
if (indexingRule.propertyIndexEnabled) {
for (PropertyRestriction pr : filter.getPropertyRestrictions()) {
PropertyDefinition pd = indexingRule.getConfig(pr.propertyName);
if (pd != null && pd.propertyIndexEnabled()) {
indexedProps.add(pr.propertyName);
result.propDefns.put(pr.propertyName, pd);
}
}
}
boolean evalPathRestrictions = canEvalPathRestrictions();
boolean canEvalAlFullText = canEvalAllFullText(indexingRule, ft);
if (ft != null && !canEvalAlFullText){
return null;
}
//Fulltext expression can also be like jcr:contains(jcr:content/metadata/@format, 'image')
List<OrderEntry> sortOrder = createSortOrder(indexingRule);
if (!indexedProps.isEmpty() || !sortOrder.isEmpty() || ft != null || evalPathRestrictions) {
//TODO Need a way to have better cost estimate to indicate that
//this index can evaluate more propertyRestrictions natively (if more props are indexed)
//For now we reduce cost per entry
int costPerEntryFactor = indexedProps.size();
costPerEntryFactor += sortOrder.size();
//this index can evaluate more propertyRestrictions natively (if more props are indexed)
//For now we reduce cost per entry
IndexPlan.Builder plan = defaultPlan();
if (!sortOrder.isEmpty()) {
plan.setSortOrder(sortOrder);
}
if (costPerEntryFactor == 0){
costPerEntryFactor = 1;
}
if (ft == null){
result.enableNonFullTextConstraints();
}
return plan.setCostPerEntry(defn.getCostPerEntry() / costPerEntryFactor);
}
//TODO Support for property existence queries
//TODO support for nodeName queries
//Above logic would not return any plan for pure nodeType based query like
//select * from nt:unstructured. We can do that but this is better handled
//by NodeType index
return null;
}
private boolean canEvalAllFullText(final IndexingRule indexingRule, FullTextExpression ft) {
if (ft == null){
return false;
}
final HashSet<String> relPaths = new HashSet<String>();
final HashSet<String> nonIndexedPaths = new HashSet<String>();
final AtomicBoolean relativeParentsFound = new AtomicBoolean();
ft.accept(new FullTextVisitor.FullTextVisitorBase() {
@Override
public boolean visit(FullTextTerm term) {
String p = term.getPropertyName();
String propertyPath = null;
String nodePath = null;
if (p == null) {
relPaths.add("");
} else if (p.startsWith("../") || p.startsWith("./")) {
relPaths.add(p);
relativeParentsFound.set(true);
} else if (getDepth(p) > 1) {
String parent = getParentPath(p);
if (LucenePropertyIndex.isNodePath(p)){
nodePath = parent;
} else {
propertyPath = p;
}
relPaths.add(parent);
} else {
propertyPath = p;
relPaths.add("");
}
if (nodePath != null
&& !indexingRule.isAggregated(nodePath)){
nonIndexedPaths.add(p);
} else if (propertyPath != null
&& !indexingRule.isIndexed(propertyPath)){
nonIndexedPaths.add(p);
}
return true;
}
});
if (relativeParentsFound.get()){
log.debug("Relative parents found {} which are not supported", relPaths);
return false;
}
if (!nonIndexedPaths.isEmpty()){
if (relPaths.size() > 1){
log.debug("Following relative property paths are not index", relPaths);
return false;
}
result.setParentPath(Iterables.getOnlyElement(relPaths, ""));
//Such path translation would only work if index contains
//all the nodes
return defn.indexesAllTypes();
} else {
result.setParentPath("");
}
return true;
}
private boolean canEvalPathRestrictions() {
if (filter.getPathRestriction() == Filter.PathRestriction.NO_RESTRICTION){
return false;
}
//TODO If no other restrictions is provided and query is pure
//path restriction based then need to be sure that index definition at least
//allows indexing all the path for given nodeType
return defn.evaluatePathRestrictions();
}
private IndexPlan.Builder defaultPlan() {
return new IndexPlan.Builder()
.setCostPerExecution(defn.getCostPerExecution())
.setCostPerEntry(defn.getCostPerEntry())
.setFulltextIndex(defn.isFullTextEnabled())
.setIncludesNodeData(false) // we should not include node data
.setFilter(filter)
.setPathPrefix(getPathPrefix())
.setDelayed(true) //Lucene is always async
.setAttribute(LucenePropertyIndex.ATTR_PLAN_RESULT, result)
.setEstimatedEntryCount(estimatedEntryCount());
}
private long estimatedEntryCount() {
//Other index only compete in case of property indexes. For fulltext
//index return true count so as to allow multiple property indexes
//to be compared fairly
FullTextExpression ft = filter.getFullTextConstraint();
if (ft != null && defn.isFullTextEnabled()){
return defn.getFulltextEntryCount(getReader().numDocs());
}
return Math.min(defn.getEntryCount(), getReader().numDocs());
}
private String getPathPrefix() {
// 2 = /oak:index/<index name>
String parentPath = PathUtils.getAncestorPath(indexPath, 2);
return PathUtils.denotesRoot(parentPath) ? "" : parentPath;
}
private IndexReader getReader() {
return indexNode.getSearcher().getIndexReader();
}
private List<OrderEntry> createSortOrder(IndexingRule rule) {
if (sortOrder == null) {
return Collections.emptyList();
}
List<OrderEntry> orderEntries = newArrayListWithCapacity(sortOrder.size());
for (OrderEntry o : sortOrder) {
PropertyDefinition pd = rule.getConfig(o.getPropertyName());
if (pd != null
&& pd.ordered
&& o.getPropertyType() != null
&& !o.getPropertyType().isArray()) {
orderEntries.add(o); //Lucene can manage any order desc/asc
result.sortedProperties.add(pd);
}
}
//TODO Should we return order entries only when all order clauses are satisfied
return orderEntries;
}
@CheckForNull
private IndexingRule getApplicableRule() {
if (filter.matchesAllTypes()){
return defn.getApplicableIndexingRule(JcrConstants.NT_BASE);
} else {
//TODO May be better if filter.getSuperTypes returned a list which maintains
//inheritance order and then we iterate over that
for (IndexingRule rule : defn.getDefinedRules()){
if (filter.getSupertypes().contains(rule.getNodeTypeName())){
//Theoretically there may be multiple rules for same nodeType with
//some condition defined. So again find a rule which applies
IndexingRule matchingRule = defn.getApplicableIndexingRule(rule.getNodeTypeName());
if (matchingRule != null){
log.debug("Applicable IndexingRule found {}", matchingRule);
return rule;
}
}
}
log.trace("No applicable IndexingRule found for any of the superTypes {}",
filter.getSupertypes());
}
return null;
}
private boolean notSupportedFeature() {
if(filter.getPathRestriction() == Filter.PathRestriction.NO_RESTRICTION
&& filter.matchesAllTypes()
&& filter.getPropertyRestrictions().isEmpty()){
//This mode includes name(), localname() queries
//OrImpl [a/name] = 'Hello' or [b/name] = 'World'
//Relative parent properties where [../foo1] is not null
return true;
}
return false;
}
//~--------------------------------------------------------< PlanResult >
public static class PlanResult {
final String indexPath;
final IndexDefinition indexDefinition;
final IndexingRule indexingRule;
private List<PropertyDefinition> sortedProperties = newArrayList();
private Map<String, PropertyDefinition> propDefns = newHashMap();
private boolean nonFullTextConstraints;
private int parentDepth;
private String parentPathSegment;
private boolean relativize;
public PlanResult(String indexPath, IndexDefinition defn, IndexingRule indexingRule) {
this.indexPath = indexPath;
this.indexDefinition = defn;
this.indexingRule = indexingRule;
}
public PropertyDefinition getPropDefn(PropertyRestriction pr){
return propDefns.get(pr.propertyName);
}
public PropertyDefinition getOrderedProperty(int index){
return sortedProperties.get(index);
}
public boolean isPathTransformed(){
return relativize;
}
/**
* Transforms the given path if the query involved relative properties and index
* is not making use of aggregated properties. If the path
*
* @param path path to transform
* @return transformed path. Returns null if the path does not confirm to relative
* path requirements
*/
@CheckForNull
public String transformPath(String path){
if (isPathTransformed()){
// get the base path
// ensure the path ends with the given
// relative path
if (!path.endsWith(parentPathSegment)) {
return null;
}
return getAncestorPath(path, parentDepth);
}
return path;
}
public boolean evaluateNonFullTextConstraints(){
return nonFullTextConstraints;
}
private void setParentPath(String relativePath){
parentPathSegment = "/" + relativePath;
if (relativePath.isEmpty()){
// we only restrict non-full-text conditions if there is
// no relative property in the full-text constraint
enableNonFullTextConstraints();
} else {
relativize = true;
parentDepth = getDepth(relativePath);
}
}
private void enableNonFullTextConstraints(){
nonFullTextConstraints = true;
}
}
}
| OAK-2335 - IndexPlanner does not return plan for mixin based queries
A nt:based based rule should be applicable for all cases
git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1644383 13f79535-47bb-0310-9956-ffa450edef68
| oak-lucene/src/main/java/org/apache/jackrabbit/oak/plugins/index/lucene/IndexPlanner.java | OAK-2335 - IndexPlanner does not return plan for mixin based queries | <ide><path>ak-lucene/src/main/java/org/apache/jackrabbit/oak/plugins/index/lucene/IndexPlanner.java
<ide> return rule;
<ide> }
<ide> }
<add> //nt:base is applicable for all. This specific condition is
<add> //required to support mixin case as filter.getSupertypes() for mixin based
<add> //query only includes the mixin type and not nt:base
<add> if (rule.getNodeTypeName().equals(JcrConstants.NT_BASE)){
<add> return rule;
<add> }
<ide> }
<ide> log.trace("No applicable IndexingRule found for any of the superTypes {}",
<ide> filter.getSupertypes()); |
|
Java | apache-2.0 | 0c1de967bd971cc003e41ad5b86c0c9936badc16 | 0 | SnowVolf/FF-Translator,SnowVolf/FF-Translator,SnowVolf/FF-Translator | package ru.SnowVolf.translate.util;
import android.util.Base64;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.util.HashMap;
import java.util.zip.CRC32;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
/**
* Created by Snow Volf on 15.07.2017, 14:48
*/
public class KeystoreUtil {
private static final int MAGIC = -1395514454;
private static final String FILE_NAME = "FileName";
private static final String KEYSTORE_PASSWORD = "KeystorePassword";
private static final String ALIAS_NAME = "AliasName";
private static final String ALIAS_PASSWORD = "AliasPassword";
private static final String KEY_PASSWORD = "KeyPassword";
public static void main(final String[] args) {
try {
final File dir = new File(System.getProperty("java.class.path")).getParentFile();
final File ini = new File(dir, "key.ini");
final HashMap<String, String> map = new HashMap<>();
readIni(map, ini);
if (!map.containsKey(FILE_NAME)) {
throw new NullPointerException("FileName not found");
}
if (!map.containsKey(KEYSTORE_PASSWORD)) {
throw new NullPointerException("KeystorePassword not found");
}
if (!map.containsKey(ALIAS_NAME)) {
throw new NullPointerException("AliasName not found");
}
if (!map.containsKey(ALIAS_PASSWORD)) {
throw new NullPointerException("AliasPassword not found");
}
final String name = map.get(FILE_NAME);
final String password = map.get(KEYSTORE_PASSWORD);
final String alias = map.get(ALIAS_NAME);
final String aliasPass = map.get(ALIAS_PASSWORD);
final File file = new File(dir, name);
final File outDir = new File(dir, "keys");
outDir.mkdirs();
final KeyStore keyStore = loadKeyStore(file, password);
System.err.println("Output:");
if (map.containsKey(KEY_PASSWORD) && map.get(KEY_PASSWORD).length() > 0) {
final String keyPass = map.get(KEY_PASSWORD);
final File out = new File(outDir, getName(file.getName()) + ".aes");
encryptSplit(keyStore, out, keyPass, alias, aliasPass);
}
else {
split(keyStore, getName(file.getName()), outDir, alias, aliasPass);
}
System.err.println();
System.out.println("succeed.");
}
catch (Exception e) {
System.err.println();
e.printStackTrace();
}
try {
System.in.read();
}
catch (IOException ex) {}
}
private static String getName(final String string) {
final int i = string.lastIndexOf(46);
if (i == -1) {
return string;
}
return string.substring(0, i);
}
private static void readIni(final HashMap<String, String> map, final File ini) throws IOException {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(ini));
String line;
while ((line = br.readLine()) != null) {
line = line.replaceAll("^#.*$", "").replaceAll("^//.*$", "").replaceAll("[ \\t]+$", "");
final int separator = line.indexOf(61);
if (separator != -1) {
final String head = line.substring(0, separator).trim();
final String body = line.substring(separator + 1).trim();
map.put(head, body);
}
}
}
finally {
if (br != null) {
try {
br.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static KeyStore loadKeyStore(final File file, final String passWord) throws Exception {
final KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(new FileInputStream(file), passWord.toCharArray());
return keyStore;
}
private static void split(final KeyStore keyStore, final String name, final File dir, final String alias, final String passWord) throws Exception {
final Certificate pubkey = keyStore.getCertificate(alias);
final Key key = keyStore.getKey(alias, passWord.toCharArray());
final KeyPair kp = new KeyPair(pubkey.getPublicKey(), (PrivateKey)key);
final FileOutputStream m_fos_x509 = new FileOutputStream(new File(dir, name + ".x509.pem"));
m_fos_x509.write("-----BEGIN CERTIFICATE-----\n".getBytes());
m_fos_x509.write(Base64.encode(pubkey.getEncoded(), Base64.NO_WRAP));
m_fos_x509.write("\n-----END CERTIFICATE-----".getBytes());
m_fos_x509.close();
System.out.println("-> keys/" + name + ".x509.pem");
final FileOutputStream m_fos_pk8 = new FileOutputStream(new File(dir, name + ".pk8"));
m_fos_pk8.write(kp.getPrivate().getEncoded());
m_fos_pk8.close();
System.out.println("-> keys/" + name + ".pk8");
}
private static void encryptSplit(final KeyStore keyStore, final File outFile, final String filePassWord, final String alias, final String passWord) throws Exception {
final Certificate pubkey = keyStore.getCertificate(alias);
final Key key = keyStore.getKey(alias, passWord.toCharArray());
final KeyPair kp = new KeyPair(pubkey.getPublicKey(), (PrivateKey)key);
DataOutputStream dos = null;
FileOutputStream fos = null;
final CRC32 crc32 = new CRC32();
try {
fos = new FileOutputStream(outFile);
dos = new DataOutputStream(fos);
dos.writeInt(-1395514454);
byte[] data = ("-----BEGIN CERTIFICATE-----\n" + Base64.encodeToString(pubkey.getEncoded(), Base64.NO_WRAP) + "\n-----END CERTIFICATE-----").getBytes();
crc32.update(data);
data = encrypt(data, filePassWord);
dos.writeInt(data.length);
dos.write(data);
data = kp.getPrivate().getEncoded();
crc32.update(data);
data = encrypt(data, filePassWord);
dos.writeInt(data.length);
dos.write(data);
dos.writeLong(crc32.getValue());
dos.flush();
System.out.println("-> keys/" + outFile.getName());
}
finally {
try {
if (dos != null) {
dos.close();
}
}
catch (IOException ex) {}
try {
if (fos != null) {
fos.close();
}
}
catch (IOException ex2) {}
}
}
private static byte[] encrypt(final byte[] data, final String password) throws Exception {
final MessageDigest mdInst = MessageDigest.getInstance("MD5");
final byte[] pass = new byte[16];
byte[] md5 = mdInst.digest(password.getBytes());
System.arraycopy(md5, 0, pass, 0, 16);
final SecretKeySpec key = new SecretKeySpec(pass, "AES");
final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
md5 = mdInst.digest(md5);
System.arraycopy(md5, 0, pass, 0, 16);
cipher.init(1, key, new IvParameterSpec(pass));
return cipher.doFinal(data);
}
}
| app/src/main/java/ru/SnowVolf/translate/util/KeystoreUtil.java | package ru.SnowVolf.translate.util;
import android.util.Base64;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.util.HashMap;
import java.util.zip.CRC32;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
/**
* Created by Snow Volf on 15.07.2017, 14:48
*/
public class KeystoreUtil
{
private static final int MAGIC = -1395514454;
private static final String FILE_NAME = "FileName";
private static final String KEYSTORE_PASSWORD = "KeystorePassword";
private static final String ALIAS_NAME = "AliasName";
private static final String ALIAS_PASSWORD = "AliasPassword";
private static final String KEY_PASSWORD = "KeyPassword";
public static void main(final String[] args) {
try {
final File dir = new File(System.getProperty("java.class.path")).getParentFile();
final File ini = new File(dir, "key.ini");
final HashMap<String, String> map = new HashMap<>();
readIni(map, ini);
if (!map.containsKey("FileName")) {
throw new NullPointerException("FileName not found");
}
if (!map.containsKey("KeystorePassword")) {
throw new NullPointerException("KeystorePassword not found");
}
if (!map.containsKey("AliasName")) {
throw new NullPointerException("AliasName not found");
}
if (!map.containsKey("AliasPassword")) {
throw new NullPointerException("AliasPassword not found");
}
final String name = map.get("FileName");
final String password = map.get("KeystorePassword");
final String alias = map.get("AliasName");
final String aliasPass = map.get("AliasPassword");
final File file = new File(dir, name);
final File outDir = new File(dir, "keys");
outDir.mkdirs();
final KeyStore keyStore = loadKeyStore(file, password);
System.err.println("Output:");
if (map.containsKey("KeyPassword") && map.get("KeyPassword").length() > 0) {
final String keyPass = map.get("KeyPassword");
final File out = new File(outDir, getName(file.getName()) + ".aes");
encryptSplit(keyStore, out, keyPass, alias, aliasPass);
}
else {
split(keyStore, getName(file.getName()), outDir, alias, aliasPass);
}
System.err.println();
System.out.println("succeed.");
}
catch (Exception e) {
System.err.println();
e.printStackTrace();
}
try {
System.in.read();
}
catch (IOException ex) {}
}
private static String getName(final String string) {
final int i = string.lastIndexOf(46);
if (i == -1) {
return string;
}
return string.substring(0, i);
}
private static void readIni(final HashMap<String, String> map, final File ini) throws IOException {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(ini));
String line;
while ((line = br.readLine()) != null) {
line = line.replaceAll("^#.*$", "").replaceAll("^//.*$", "").replaceAll("[ \\t]+$", "");
final int separator = line.indexOf(61);
if (separator != -1) {
final String head = line.substring(0, separator).trim();
final String body = line.substring(separator + 1).trim();
map.put(head, body);
}
}
}
finally {
if (br != null) {
try {
br.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static KeyStore loadKeyStore(final File file, final String passWord) throws Exception {
final KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(new FileInputStream(file), passWord.toCharArray());
return keyStore;
}
private static void split(final KeyStore keyStore, final String name, final File dir, final String alias, final String passWord) throws Exception {
final Certificate pubkey = keyStore.getCertificate(alias);
final Key key = keyStore.getKey(alias, passWord.toCharArray());
final KeyPair kp = new KeyPair(pubkey.getPublicKey(), (PrivateKey)key);
final FileOutputStream m_fos_x509 = new FileOutputStream(new File(dir, name + ".x509.pem"));
m_fos_x509.write("-----BEGIN CERTIFICATE-----\n".getBytes());
m_fos_x509.write(Base64.encode(pubkey.getEncoded(), Base64.NO_WRAP));
m_fos_x509.write("\n-----END CERTIFICATE-----".getBytes());
m_fos_x509.close();
System.out.println("-> keys/" + name + ".x509.pem");
final FileOutputStream m_fos_pk8 = new FileOutputStream(new File(dir, name + ".pk8"));
m_fos_pk8.write(kp.getPrivate().getEncoded());
m_fos_pk8.close();
System.out.println("-> keys/" + name + ".pk8");
}
private static void encryptSplit(final KeyStore keyStore, final File outFile, final String filePassWord, final String alias, final String passWord) throws Exception {
final Certificate pubkey = keyStore.getCertificate(alias);
final Key key = keyStore.getKey(alias, passWord.toCharArray());
final KeyPair kp = new KeyPair(pubkey.getPublicKey(), (PrivateKey)key);
DataOutputStream dos = null;
FileOutputStream fos = null;
final CRC32 crc32 = new CRC32();
try {
fos = new FileOutputStream(outFile);
dos = new DataOutputStream(fos);
dos.writeInt(-1395514454);
byte[] data = ("-----BEGIN CERTIFICATE-----\n" + Base64.encodeToString(pubkey.getEncoded(), Base64.NO_WRAP) + "\n-----END CERTIFICATE-----").getBytes();
crc32.update(data);
data = encrypt(data, filePassWord);
dos.writeInt(data.length);
dos.write(data);
data = kp.getPrivate().getEncoded();
crc32.update(data);
data = encrypt(data, filePassWord);
dos.writeInt(data.length);
dos.write(data);
dos.writeLong(crc32.getValue());
dos.flush();
System.out.println("-> keys/" + outFile.getName());
}
finally {
try {
if (dos != null) {
dos.close();
}
}
catch (IOException ex) {}
try {
if (fos != null) {
fos.close();
}
}
catch (IOException ex2) {}
}
}
private static byte[] encrypt(final byte[] data, final String password) throws Exception {
final MessageDigest mdInst = MessageDigest.getInstance("MD5");
final byte[] pass = new byte[16];
byte[] md5 = mdInst.digest(password.getBytes());
System.arraycopy(md5, 0, pass, 0, 16);
final SecretKeySpec key = new SecretKeySpec(pass, "AES");
final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
md5 = mdInst.digest(md5);
System.arraycopy(md5, 0, pass, 0, 16);
cipher.init(1, key, new IvParameterSpec(pass));
return cipher.doFinal(data);
}
}
| fixes
| app/src/main/java/ru/SnowVolf/translate/util/KeystoreUtil.java | fixes | <ide><path>pp/src/main/java/ru/SnowVolf/translate/util/KeystoreUtil.java
<ide> * Created by Snow Volf on 15.07.2017, 14:48
<ide> */
<ide>
<del>public class KeystoreUtil
<del>{
<add>public class KeystoreUtil {
<ide> private static final int MAGIC = -1395514454;
<ide> private static final String FILE_NAME = "FileName";
<ide> private static final String KEYSTORE_PASSWORD = "KeystorePassword";
<ide> final File ini = new File(dir, "key.ini");
<ide> final HashMap<String, String> map = new HashMap<>();
<ide> readIni(map, ini);
<del> if (!map.containsKey("FileName")) {
<add> if (!map.containsKey(FILE_NAME)) {
<ide> throw new NullPointerException("FileName not found");
<ide> }
<del> if (!map.containsKey("KeystorePassword")) {
<add> if (!map.containsKey(KEYSTORE_PASSWORD)) {
<ide> throw new NullPointerException("KeystorePassword not found");
<ide> }
<del> if (!map.containsKey("AliasName")) {
<add> if (!map.containsKey(ALIAS_NAME)) {
<ide> throw new NullPointerException("AliasName not found");
<ide> }
<del> if (!map.containsKey("AliasPassword")) {
<add> if (!map.containsKey(ALIAS_PASSWORD)) {
<ide> throw new NullPointerException("AliasPassword not found");
<ide> }
<del> final String name = map.get("FileName");
<del> final String password = map.get("KeystorePassword");
<del> final String alias = map.get("AliasName");
<del> final String aliasPass = map.get("AliasPassword");
<add> final String name = map.get(FILE_NAME);
<add> final String password = map.get(KEYSTORE_PASSWORD);
<add> final String alias = map.get(ALIAS_NAME);
<add> final String aliasPass = map.get(ALIAS_PASSWORD);
<ide> final File file = new File(dir, name);
<ide> final File outDir = new File(dir, "keys");
<ide> outDir.mkdirs();
<ide> final KeyStore keyStore = loadKeyStore(file, password);
<ide> System.err.println("Output:");
<del> if (map.containsKey("KeyPassword") && map.get("KeyPassword").length() > 0) {
<del> final String keyPass = map.get("KeyPassword");
<add> if (map.containsKey(KEY_PASSWORD) && map.get(KEY_PASSWORD).length() > 0) {
<add> final String keyPass = map.get(KEY_PASSWORD);
<ide> final File out = new File(outDir, getName(file.getName()) + ".aes");
<ide> encryptSplit(keyStore, out, keyPass, alias, aliasPass);
<ide> } |
|
JavaScript | mit | 2bbd591936eeb9cca0a287a862b4cd3bd1e46560 | 0 | MarkEWaite/jenkins,v1v/jenkins,daniel-beck/jenkins,ikedam/jenkins,viqueen/jenkins,DanielWeber/jenkins,rsandell/jenkins,viqueen/jenkins,MarkEWaite/jenkins,patbos/jenkins,MarkEWaite/jenkins,patbos/jenkins,damianszczepanik/jenkins,patbos/jenkins,pjanouse/jenkins,daniel-beck/jenkins,daniel-beck/jenkins,MarkEWaite/jenkins,jenkinsci/jenkins,jenkinsci/jenkins,pjanouse/jenkins,DanielWeber/jenkins,daniel-beck/jenkins,damianszczepanik/jenkins,DanielWeber/jenkins,v1v/jenkins,patbos/jenkins,damianszczepanik/jenkins,ikedam/jenkins,daniel-beck/jenkins,jenkinsci/jenkins,damianszczepanik/jenkins,daniel-beck/jenkins,v1v/jenkins,viqueen/jenkins,MarkEWaite/jenkins,daniel-beck/jenkins,oleg-nenashev/jenkins,patbos/jenkins,oleg-nenashev/jenkins,damianszczepanik/jenkins,pjanouse/jenkins,v1v/jenkins,ikedam/jenkins,v1v/jenkins,rsandell/jenkins,oleg-nenashev/jenkins,ikedam/jenkins,rsandell/jenkins,viqueen/jenkins,DanielWeber/jenkins,v1v/jenkins,oleg-nenashev/jenkins,viqueen/jenkins,rsandell/jenkins,oleg-nenashev/jenkins,DanielWeber/jenkins,rsandell/jenkins,ikedam/jenkins,damianszczepanik/jenkins,patbos/jenkins,jenkinsci/jenkins,v1v/jenkins,damianszczepanik/jenkins,DanielWeber/jenkins,daniel-beck/jenkins,rsandell/jenkins,MarkEWaite/jenkins,viqueen/jenkins,jenkinsci/jenkins,pjanouse/jenkins,rsandell/jenkins,jenkinsci/jenkins,pjanouse/jenkins,ikedam/jenkins,DanielWeber/jenkins,oleg-nenashev/jenkins,MarkEWaite/jenkins,patbos/jenkins,ikedam/jenkins,MarkEWaite/jenkins,oleg-nenashev/jenkins,ikedam/jenkins,pjanouse/jenkins,jenkinsci/jenkins,rsandell/jenkins,pjanouse/jenkins,viqueen/jenkins,jenkinsci/jenkins,damianszczepanik/jenkins | import $ from 'jquery';
import { getWindow } from 'window-handle';
import page from '../../util/page';
import tableMetadata from './model/ConfigTableMetaData';
import behaviorShim from '../../util/behavior-shim';
import jenkinsLocalStorage from '../../util/jenkinsLocalStorage';
/**
* Extracting this call from outside of the addPageTabs due to a regression
* in 2.216/2.217 (see JENKINS-61429)
*
* The proxied call to Behaviour.specify needs to be called from outside of the
* addPageTabs function. Otherwise, it will not apply to existing draggable
* elements on the form. It would only only apply to new elements.
*
* Extracting this Behaviour.specify call to the module level causes it to be executed
* on script load, and this seems to set up the event listeners properly.
*/
behaviorShim.specify(".dd-handle", 'config-drag-start', 1000, function(el) {
page.fixDragEvent(el);
});
export var tabBarShowPreferenceKey = 'config:usetabs';
export var addPageTabs = function(configSelector, onEachConfigTable, options) {
$(function() {
// We need to wait until after radioBlock.js Behaviour.js rules
// have been applied, otherwise row-set rows become visible across sections.
page.onload('.block-control', function() {
// Only do job configs for now.
var configTables = $(configSelector);
if (configTables.size() > 0) {
var tabBarShowPreference = jenkinsLocalStorage.getGlobalItem(tabBarShowPreferenceKey, "yes");
page.fixDragEvent(configTables);
if (tabBarShowPreference === "yes") {
configTables.each(function() {
var configTable = $(this);
var tabBar = addTabs(configTable, options);
onEachConfigTable.call(configTable, tabBar);
tabBar.deactivator.click(function() {
jenkinsLocalStorage.setGlobalItem(tabBarShowPreferenceKey, "no");
getWindow().location.reload();
});
});
} else {
configTables.each(function() {
var configTable = $(this);
var activator = addTabsActivator(configTable);
tableMetadata.markConfigTableParentForm(configTable);
activator.click(function() {
jenkinsLocalStorage.setGlobalItem(tabBarShowPreferenceKey, "yes");
getWindow().location.reload();
});
});
}
}
}, configSelector);
});
};
export var addTabsOnFirst = function() {
return addTabs(tableMetadata.findConfigTables().first());
};
export var addTabs = function(configTable, options) {
var configTableMetadata;
var tabOptions = (options || {});
var trackSectionVisibility = (tabOptions.trackSectionVisibility || false);
if ($.isArray(configTable)) {
// It's a config <table> metadata block
configTableMetadata = configTable;
} else if (typeof configTable === 'string') {
// It's a config <table> selector
var configTableEl = $(configTable);
if (configTableEl.size() === 0) {
throw "No config table found using selector '" + configTable + "'";
} else {
configTableMetadata = tableMetadata.fromConfigTable(configTableEl);
}
} else {
// It's a config <table> element
configTableMetadata = tableMetadata.fromConfigTable(configTable);
}
var tabBar = $('<div class="tabBar config-section-activators"></div>');
configTableMetadata.activatorContainer = tabBar;
function newTab(section) {
var tab = $('<div class="tab config-section-activator"></div>');
tab.text(section.title);
tab.addClass(section.id);
return tab;
}
var section;
for (var i = 0; i < configTableMetadata.sections.length; i++) {
section = configTableMetadata.sections[i];
var tab = newTab(section);
tabBar.append(tab);
section.setActivator(tab);
}
var tabs = $('<div class="form-config tabBarFrame"></div>');
var noTabs = $('<div class="noTabs" title="Remove configuration tabs and revert to the "classic" configuration view">Remove tabs</div>');
configTableMetadata.configWidgets.append(tabs);
configTableMetadata.configWidgets.prepend(noTabs);
tabs.append(tabBar);
tabs.mouseenter(function() {
tabs.addClass('mouse-over');
});
tabs.mouseleave(function() {
tabs.removeClass('mouse-over');
});
configTableMetadata.deactivator = noTabs;
// Always activate the first section by default.
configTableMetadata.activateFirstSection();
if (trackSectionVisibility === true) {
configTableMetadata.trackSectionVisibility();
}
return configTableMetadata;
};
export var addTabsActivator = function(configTable) {
var configWidgets = $('<div class="jenkins-config-widgets"><div class="showTabs" title="Add configuration section tabs">Add tabs</div></div>');
configWidgets.insertBefore(configTable.parent());
return configWidgets;
};
export var addFinderToggle = function(configTableMetadata) {
var findToggle = $('<div class="find-toggle" title="Find"></div>');
var finderShowPreferenceKey = 'config:showfinder';
findToggle.click(function() {
var findContainer = $('.find-container', configTableMetadata.configWidgets);
if (findContainer.hasClass('visible')) {
findContainer.removeClass('visible');
jenkinsLocalStorage.setGlobalItem(finderShowPreferenceKey, "no");
} else {
findContainer.addClass('visible');
$('input', findContainer).focus();
jenkinsLocalStorage.setGlobalItem(finderShowPreferenceKey, "yes");
}
});
if (jenkinsLocalStorage.getGlobalItem(finderShowPreferenceKey, "yes") === 'yes') {
findToggle.click();
}
};
| war/src/main/js/widgets/config/tabbar.js | import $ from 'jquery';
import { getWindow } from 'window-handle';
import page from '../../util/page';
import tableMetadata from './model/ConfigTableMetaData';
import behaviorShim from '../../util/behavior-shim';
import jenkinsLocalStorage from '../../util/jenkinsLocalStorage';
/**
* Extracting this call from outside of the addPageTabs due to a regression
* in 2.216/2.217
*
* The proxied call to Behaviour.specify needs to be called from outside of the
* addPageTabs function. Otherwise, it will not apply to existing draggable
* elements on the form. It would only only apply to new elements.
*
* Extracting this Behaviour.specify call to the module level causes it to be executed
* on script load, and this seems to set up the event listeners properly.
*/
behaviorShim.specify(".dd-handle", 'config-drag-start', 1000, function(el) {
page.fixDragEvent(el);
});
export var tabBarShowPreferenceKey = 'config:usetabs';
export var addPageTabs = function(configSelector, onEachConfigTable, options) {
$(function() {
// We need to wait until after radioBlock.js Behaviour.js rules
// have been applied, otherwise row-set rows become visible across sections.
page.onload('.block-control', function() {
// Only do job configs for now.
var configTables = $(configSelector);
if (configTables.size() > 0) {
var tabBarShowPreference = jenkinsLocalStorage.getGlobalItem(tabBarShowPreferenceKey, "yes");
page.fixDragEvent(configTables);
if (tabBarShowPreference === "yes") {
configTables.each(function() {
var configTable = $(this);
var tabBar = addTabs(configTable, options);
onEachConfigTable.call(configTable, tabBar);
tabBar.deactivator.click(function() {
jenkinsLocalStorage.setGlobalItem(tabBarShowPreferenceKey, "no");
getWindow().location.reload();
});
});
} else {
configTables.each(function() {
var configTable = $(this);
var activator = addTabsActivator(configTable);
tableMetadata.markConfigTableParentForm(configTable);
activator.click(function() {
jenkinsLocalStorage.setGlobalItem(tabBarShowPreferenceKey, "yes");
getWindow().location.reload();
});
});
}
}
}, configSelector);
});
};
export var addTabsOnFirst = function() {
return addTabs(tableMetadata.findConfigTables().first());
};
export var addTabs = function(configTable, options) {
var configTableMetadata;
var tabOptions = (options || {});
var trackSectionVisibility = (tabOptions.trackSectionVisibility || false);
if ($.isArray(configTable)) {
// It's a config <table> metadata block
configTableMetadata = configTable;
} else if (typeof configTable === 'string') {
// It's a config <table> selector
var configTableEl = $(configTable);
if (configTableEl.size() === 0) {
throw "No config table found using selector '" + configTable + "'";
} else {
configTableMetadata = tableMetadata.fromConfigTable(configTableEl);
}
} else {
// It's a config <table> element
configTableMetadata = tableMetadata.fromConfigTable(configTable);
}
var tabBar = $('<div class="tabBar config-section-activators"></div>');
configTableMetadata.activatorContainer = tabBar;
function newTab(section) {
var tab = $('<div class="tab config-section-activator"></div>');
tab.text(section.title);
tab.addClass(section.id);
return tab;
}
var section;
for (var i = 0; i < configTableMetadata.sections.length; i++) {
section = configTableMetadata.sections[i];
var tab = newTab(section);
tabBar.append(tab);
section.setActivator(tab);
}
var tabs = $('<div class="form-config tabBarFrame"></div>');
var noTabs = $('<div class="noTabs" title="Remove configuration tabs and revert to the "classic" configuration view">Remove tabs</div>');
configTableMetadata.configWidgets.append(tabs);
configTableMetadata.configWidgets.prepend(noTabs);
tabs.append(tabBar);
tabs.mouseenter(function() {
tabs.addClass('mouse-over');
});
tabs.mouseleave(function() {
tabs.removeClass('mouse-over');
});
configTableMetadata.deactivator = noTabs;
// Always activate the first section by default.
configTableMetadata.activateFirstSection();
if (trackSectionVisibility === true) {
configTableMetadata.trackSectionVisibility();
}
return configTableMetadata;
};
export var addTabsActivator = function(configTable) {
var configWidgets = $('<div class="jenkins-config-widgets"><div class="showTabs" title="Add configuration section tabs">Add tabs</div></div>');
configWidgets.insertBefore(configTable.parent());
return configWidgets;
};
export var addFinderToggle = function(configTableMetadata) {
var findToggle = $('<div class="find-toggle" title="Find"></div>');
var finderShowPreferenceKey = 'config:showfinder';
findToggle.click(function() {
var findContainer = $('.find-container', configTableMetadata.configWidgets);
if (findContainer.hasClass('visible')) {
findContainer.removeClass('visible');
jenkinsLocalStorage.setGlobalItem(finderShowPreferenceKey, "no");
} else {
findContainer.addClass('visible');
$('input', findContainer).focus();
jenkinsLocalStorage.setGlobalItem(finderShowPreferenceKey, "yes");
}
});
if (jenkinsLocalStorage.getGlobalItem(finderShowPreferenceKey, "yes") === 'yes') {
findToggle.click();
}
}; | Update war/src/main/js/widgets/config/tabbar.js
Co-Authored-By: Oleg Nenashev <[email protected]>
(cherry picked from commit 7f19c4de5bfa9df58c54a4c04081800f516a8482)
| war/src/main/js/widgets/config/tabbar.js | Update war/src/main/js/widgets/config/tabbar.js | <ide><path>ar/src/main/js/widgets/config/tabbar.js
<ide>
<ide> /**
<ide> * Extracting this call from outside of the addPageTabs due to a regression
<del> * in 2.216/2.217
<add> * in 2.216/2.217 (see JENKINS-61429)
<ide> *
<ide> * The proxied call to Behaviour.specify needs to be called from outside of the
<ide> * addPageTabs function. Otherwise, it will not apply to existing draggable |
|
Java | apache-2.0 | 34e481af2b84ccd50c125aa12bc7f2882454de72 | 0 | comcp/android-StupidMethod | package com.stupid.method.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Map;
import java.util.WeakHashMap;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.util.Base64;
import android.util.Log;
/**
*
* SharedPreferences 工具类
*
* @author wangx 2016-04-27 重构
*
* **/
public class SharedPreferencesHelper {
private static final String empty = "";
private static final WeakHashMap<Context, Map<String, SharedPreferencesHelper>> mCache = new WeakHashMap<Context, Map<String, SharedPreferencesHelper>>(
3);
private static final String tag = "SharePreferenceHelper";
/***
* 线程安全
* **/
public static SharedPreferencesHelper getCache(Context context, String name) {
Map<String, SharedPreferencesHelper> hashmap = null;
hashmap = mCache.get(context);// 根据主键 取出 主键缓存,
if (hashmap == null) {// 如果二级缓存是否为空,
synchronized (mCache) {// 给一级缓存加线程锁
hashmap = mCache.get(context);// 再取出二级缓存
if (hashmap == null) {// 判断二级缓存是否为空,在极端条件下,这个地方很有可能会被其他线程初始化
hashmap = new WeakHashMap<String, SharedPreferencesHelper>(
2);
mCache.put(context, hashmap);
}
}
}
SharedPreferencesHelper result = null;
result = hashmap.get(name);
if (result == null) {
synchronized (hashmap) {
result = hashmap.get(name);
if (result == null) {
result = new SharedPreferencesHelper(context, name);
hashmap.put(name, result);
}
}
}
return result;
}
private static String getKey(Object key) {
if (key == null) {
return empty;
} else if (key instanceof CharSequence) {
return key.toString();
} else if (key instanceof Class<?>) {
return ((Class<?>) key).getName();
} else {
return key.getClass().getName();
}
}
public synchronized static void onLowMemory() {
mCache.clear();
}
final private SharedPreferences sp;// SP 杂化轨道,呵呵
public SharedPreferencesHelper(Context context, String name) {
sp = context.getSharedPreferences(name, Context.MODE_PRIVATE);
}
public SharedPreferencesHelper(SharedPreferences sp) {
this.sp = sp;
}
public SharedPreferencesHelper clear() {
Editor editor = edit();
editor.clear();
editor.commit();
return this;
}
private Editor edit() {
return getSharedPreferences().edit();
}
public Map<String, ?> getAll() {
return getSharedPreferences().getAll();
}
public boolean getBoolean(String key, boolean defValue) {
return getSharedPreferences().getBoolean(key, defValue);
}
public float getFloat(String key, float defValue) {
return getSharedPreferences().getFloat(key, defValue);
}
public int getInt(String key, int defValue) {
return getSharedPreferences().getInt(key, defValue);
}
public <T> T getJSON(Class<?> key, Class<T> clazz) {
return getJSON(key.getName(), clazz);
}
public <T> T getJSON(Class<T> clazz) {
return getJSON(clazz, clazz);
}
public <T> T getJSON(String key, Class<T> clazz) {
try {
return JsonUtils.parseObject(getString((key)), clazz);
} catch (Exception e) {
Log.w(tag, "getJSON", e);
return null;
}
}
/**
* 测试中的方法,从xml里取出序列化的对象
*
* @param key
* @author wangx
* @throws ClassNotFoundException
* **/
@SuppressLint("NewApi")
public Object getObject(String key) throws ClassNotFoundException {
String base64 = getString(key);
ByteArrayInputStream is = new ByteArrayInputStream(Base64.decode(
base64, Base64.DEFAULT));
try {
ObjectInputStream ois = new ObjectInputStream(is);
return ois.readObject();
} catch (IOException e) {
return null;
}
}
private SharedPreferences getSharedPreferences() {
return sp;
}
public String getString(String key) {
return this.getString(key, empty);
}
public String getString(String key, String defValue) {
return getSharedPreferences().getString(key, defValue);
}
public SharedPreferencesHelper putBoolean(String key, boolean value) {
Editor editor = edit();
editor.putBoolean(key, value);
editor.commit();
return this;
}
public SharedPreferencesHelper putInt(String key, int value) {
Editor editor = edit();
editor.putInt(key, value);
editor.commit();
return this;
}
public SharedPreferencesHelper putJSON(Class<?> key, Object value) {
putJSON(key.getName(), value);
return this;
}
public SharedPreferencesHelper putJSON(Object value) {
putJSON(value.getClass().getName(), value);
return this;
}
public SharedPreferencesHelper putJSON(String key, Object value) {
Editor editor = edit();
editor.putString(
getKey(key),
value instanceof CharSequence ? value.toString() : JsonUtils
.toJSONString(value));
editor.commit();
return this;
}
public SharedPreferencesHelper putLon(String key, long value) {
Editor editor = edit();
editor.putLong(key, value);
editor.commit();
return this;
}
/**
* 测试中的方法,保存序列化的对象到xml里
*
* @param key
* @author wangx
* **/
@SuppressLint("NewApi")
public void putObject(String key, Serializable serializable)
throws IOException {
ByteArrayOutputStream bots = new ByteArrayOutputStream();
ObjectOutputStream opt = new ObjectOutputStream(bots);
opt.writeObject(serializable);
opt.flush();
opt.close();
opt.reset();
String base64 = Base64.encodeToString(bots.toByteArray(),
Base64.DEFAULT);
putString(key, base64);
bots = null;
opt = null;
base64 = null;
}
public SharedPreferencesHelper putString(String key, String value) {
Editor editor = edit();
editor.putString(key, value);
editor.commit();
return this;
}
public SharedPreferencesHelper registerOnSharedPreferenceChangeListener(
OnSharedPreferenceChangeListener listener) {
getSharedPreferences().registerOnSharedPreferenceChangeListener(
listener);
return this;
}
public SharedPreferencesHelper remove(String key) {
Editor editor = edit();
editor.remove(key);
editor.commit();
return this;
}
public SharedPreferencesHelper unregisterOnSharedPreferenceChangeListener(
OnSharedPreferenceChangeListener listener) {
getSharedPreferences().unregisterOnSharedPreferenceChangeListener(
listener);
return this;
}
}
| StupidMethod/src/com/stupid/method/util/SharedPreferencesHelper.java | package com.stupid.method.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Map;
import java.util.WeakHashMap;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.util.Base64;
import android.util.Log;
/**
*
* SharedPreferences 工具类
*
* @author wangx 2016-04-27 重构
*
* **/
public class SharedPreferencesHelper {
private static final String empty = "";
private static final WeakHashMap<Context, Map<String, SharedPreferencesHelper>> mCache = new WeakHashMap<Context, Map<String, SharedPreferencesHelper>>(
3);
private static final String tag = "SharePreferenceHelper";
/***
* 线程安全
* **/
public static SharedPreferencesHelper getCache(Context context, String name) {
Map<String, SharedPreferencesHelper> hashmap = null;
hashmap = mCache.get(context);// 根据主键 取出 主键缓存,
if (hashmap == null) {// 如果二级缓存是否为空,
synchronized (mCache) {// 给一级缓存加线程锁
hashmap = mCache.get(context);// 再取出二级缓存
if (hashmap == null) {// 判断二级缓存是否为空,在极端条件下,这个地方很有可能会被其他线程初始化
hashmap = new WeakHashMap<String, SharedPreferencesHelper>(
2);
mCache.put(context, hashmap);
}
}
}
SharedPreferencesHelper result = null;
result = hashmap.get(name);
if (result == null) {
synchronized (hashmap) {
result = hashmap.get(name);
if (result == null) {
result = new SharedPreferencesHelper(context, name);
hashmap.put(name, result);
}
}
}
return result;
}
private static String getKey(Object key) {
if (key == null) {
return empty;
} else if (key instanceof CharSequence) {
return key.toString();
} else if (key instanceof Class<?>) {
return ((Class<?>) key).getName();
} else {
return key.getClass().getName();
}
}
public synchronized static void onLowMemory() {
mCache.clear();
}
final private boolean autoCommit;
final private SharedPreferences sp;// SP 杂化轨道,呵呵
public SharedPreferencesHelper(Context context, String name) {
this(context, name, true);
}
public SharedPreferencesHelper(Context context, String name,
boolean autoCommit) {
sp = context.getSharedPreferences(name, Context.MODE_PRIVATE);
this.autoCommit = autoCommit;
}
public SharedPreferencesHelper(SharedPreferences sp) {
this(sp, true);
}
public SharedPreferencesHelper(SharedPreferences sp, boolean autoCommit) {
this.sp = sp;
this.autoCommit = autoCommit;
}
public SharedPreferencesHelper clear() {
edit().clear();
if (autoCommit)
edit().commit();
return this;
}
public SharedPreferencesHelper commit() {
edit().commit();
return this;
}
private Editor edit() {
return getSharedPreferences().edit();
}
public Map<String, ?> getAll() {
return getSharedPreferences().getAll();
}
public boolean getBoolean(String key, boolean defValue) {
return getSharedPreferences().getBoolean(key, defValue);
}
public float getFloat(String key, float defValue) {
return getSharedPreferences().getFloat(key, defValue);
}
public int getInt(String key, int defValue) {
return getSharedPreferences().getInt(key, defValue);
}
public <T> T getJSON(Class<?> key, Class<T> clazz) {
return getJSON(key.getName(), clazz);
}
public <T> T getJSON(Class<T> clazz) {
return getJSON(clazz, clazz);
}
public <T> T getJSON(String key, Class<T> clazz) {
try {
return JsonUtils.parseObject(
getSharedPreferences().getString((key), empty), clazz);
} catch (Exception e) {
Log.w(tag, "getJSON", e);
return null;
}
}
private SharedPreferences getSharedPreferences() {
return sp;
}
public String getString(String key) {
return this.getString(key, empty);
}
public String getString(String key, String defValue) {
return getSharedPreferences().getString(key, defValue);
}
public SharedPreferencesHelper registerOnSharedPreferenceChangeListener(
OnSharedPreferenceChangeListener listener) {
getSharedPreferences().registerOnSharedPreferenceChangeListener(
listener);
return this;
}
public SharedPreferencesHelper remove(String key) {
edit().remove(key);
if (autoCommit)
edit().commit();
return this;
}
public SharedPreferencesHelper putBoolean(String key, boolean value) {
edit().putBoolean(key, value);
if (autoCommit)
edit().commit();
return this;
}
public SharedPreferencesHelper putInt(String key, int value) {
edit().putInt(key, value);
if (autoCommit)
edit().commit();
return this;
}
public SharedPreferencesHelper putJSON(Class<?> key, Object value) {
putJSON(key.getName(), value);
return this;
}
public SharedPreferencesHelper putJSON(Object value) {
putJSON(value.getClass().getName(), value);
return this;
}
public SharedPreferencesHelper putJSON(String key, Object value) {
edit().putString(
getKey(key),
value instanceof CharSequence ? value.toString() : JsonUtils
.toJSONString(value));
if (autoCommit)
edit().commit();
return this;
}
public SharedPreferencesHelper putLon(String key, long value) {
edit().putLong(key, value);
if (autoCommit)
edit().commit();
return this;
}
public SharedPreferencesHelper putString(String key, String value) {
edit().putString(key, value);
if (autoCommit)
edit().commit();
return this;
}
public SharedPreferencesHelper unregisterOnSharedPreferenceChangeListener(
OnSharedPreferenceChangeListener listener) {
getSharedPreferences().unregisterOnSharedPreferenceChangeListener(
listener);
return this;
}
/**
* 测试中的方法,保存序列化的对象到xml里
*
* @param key
* @author wangx
* **/
@SuppressLint("NewApi")
public void putObject(String key, Serializable serializable)
throws IOException {
ByteArrayOutputStream bots = new ByteArrayOutputStream();
ObjectOutputStream opt = new ObjectOutputStream(bots);
opt.writeObject(serializable);
opt.flush();
opt.close();
opt.reset();
String base64 = Base64.encodeToString(bots.toByteArray(),
Base64.DEFAULT);
putString(key, base64);
bots = null;
opt = null;
base64 = null;
}
/**
* 测试中的方法,从xml里取出序列化的对象
*
* @param key
* @author wangx
* @throws ClassNotFoundException
* **/
@SuppressLint("NewApi")
public Object getObject(String key) throws ClassNotFoundException {
String base64 = getString(key);
ByteArrayInputStream is = new ByteArrayInputStream(Base64.decode(
base64, Base64.DEFAULT));
try {
ObjectInputStream ois = new ObjectInputStream(is);
return ois.readObject();
} catch (IOException e) {
return null;
}
}
}
| SharedPreferencesHelper | StupidMethod/src/com/stupid/method/util/SharedPreferencesHelper.java | SharedPreferencesHelper | <ide><path>tupidMethod/src/com/stupid/method/util/SharedPreferencesHelper.java
<ide> package com.stupid.method.util;
<del>
<ide>
<ide> import java.io.ByteArrayInputStream;
<ide> import java.io.ByteArrayOutputStream;
<ide> * **/
<ide> public class SharedPreferencesHelper {
<ide>
<del> private static final String empty = "";
<del>
<del> private static final WeakHashMap<Context, Map<String, SharedPreferencesHelper>> mCache = new WeakHashMap<Context, Map<String, SharedPreferencesHelper>>(
<del> 3);
<del>
<del> private static final String tag = "SharePreferenceHelper";
<del>
<del> /***
<del> * 线程安全
<del> * **/
<del> public static SharedPreferencesHelper getCache(Context context, String name) {
<del> Map<String, SharedPreferencesHelper> hashmap = null;
<del> hashmap = mCache.get(context);// 根据主键 取出 主键缓存,
<del>
<del> if (hashmap == null) {// 如果二级缓存是否为空,
<del> synchronized (mCache) {// 给一级缓存加线程锁
<del> hashmap = mCache.get(context);// 再取出二级缓存
<del> if (hashmap == null) {// 判断二级缓存是否为空,在极端条件下,这个地方很有可能会被其他线程初始化
<del> hashmap = new WeakHashMap<String, SharedPreferencesHelper>(
<del> 2);
<del> mCache.put(context, hashmap);
<del> }
<del>
<del> }
<del>
<del> }
<del> SharedPreferencesHelper result = null;
<del> result = hashmap.get(name);
<del> if (result == null) {
<del> synchronized (hashmap) {
<del> result = hashmap.get(name);
<del> if (result == null) {
<del> result = new SharedPreferencesHelper(context, name);
<del> hashmap.put(name, result);
<del> }
<del> }
<del> }
<del>
<del> return result;
<del> }
<del>
<del> private static String getKey(Object key) {
<del>
<del> if (key == null) {
<del> return empty;
<del> } else if (key instanceof CharSequence) {
<del>
<del> return key.toString();
<del>
<del> } else if (key instanceof Class<?>) {
<del>
<del> return ((Class<?>) key).getName();
<del> } else {
<del>
<del> return key.getClass().getName();
<del> }
<del> }
<del>
<del> public synchronized static void onLowMemory() {
<del>
<del> mCache.clear();
<del> }
<del>
<del> final private boolean autoCommit;
<del>
<del> final private SharedPreferences sp;// SP 杂化轨道,呵呵
<del>
<del> public SharedPreferencesHelper(Context context, String name) {
<del> this(context, name, true);
<del> }
<del>
<del> public SharedPreferencesHelper(Context context, String name,
<del> boolean autoCommit) {
<del> sp = context.getSharedPreferences(name, Context.MODE_PRIVATE);
<del> this.autoCommit = autoCommit;
<del> }
<del>
<del> public SharedPreferencesHelper(SharedPreferences sp) {
<del> this(sp, true);
<del> }
<del>
<del> public SharedPreferencesHelper(SharedPreferences sp, boolean autoCommit) {
<del> this.sp = sp;
<del> this.autoCommit = autoCommit;
<del> }
<del>
<del> public SharedPreferencesHelper clear() {
<del> edit().clear();
<del> if (autoCommit)
<del> edit().commit();
<del> return this;
<del> }
<del>
<del> public SharedPreferencesHelper commit() {
<del> edit().commit();
<del> return this;
<del> }
<del>
<del> private Editor edit() {
<del> return getSharedPreferences().edit();
<del> }
<del>
<del> public Map<String, ?> getAll() {
<del> return getSharedPreferences().getAll();
<del> }
<del>
<del> public boolean getBoolean(String key, boolean defValue) {
<del> return getSharedPreferences().getBoolean(key, defValue);
<del> }
<del>
<del> public float getFloat(String key, float defValue) {
<del> return getSharedPreferences().getFloat(key, defValue);
<del> }
<del>
<del> public int getInt(String key, int defValue) {
<del> return getSharedPreferences().getInt(key, defValue);
<del> }
<del>
<del> public <T> T getJSON(Class<?> key, Class<T> clazz) {
<del> return getJSON(key.getName(), clazz);
<del>
<del> }
<del>
<del> public <T> T getJSON(Class<T> clazz) {
<del> return getJSON(clazz, clazz);
<del>
<del> }
<del>
<del> public <T> T getJSON(String key, Class<T> clazz) {
<del> try {
<del> return JsonUtils.parseObject(
<del> getSharedPreferences().getString((key), empty), clazz);
<del> } catch (Exception e) {
<del>
<del> Log.w(tag, "getJSON", e);
<del>
<del> return null;
<del> }
<del>
<del> }
<del>
<del> private SharedPreferences getSharedPreferences() {
<del>
<del> return sp;
<del> }
<del>
<del> public String getString(String key) {
<del>
<del> return this.getString(key, empty);
<del> }
<del>
<del> public String getString(String key, String defValue) {
<del>
<del> return getSharedPreferences().getString(key, defValue);
<del> }
<del>
<del> public SharedPreferencesHelper registerOnSharedPreferenceChangeListener(
<del> OnSharedPreferenceChangeListener listener) {
<del> getSharedPreferences().registerOnSharedPreferenceChangeListener(
<del> listener);
<del> return this;
<del> }
<del>
<del> public SharedPreferencesHelper remove(String key) {
<del> edit().remove(key);
<del> if (autoCommit)
<del> edit().commit();
<del> return this;
<del>
<del> }
<del>
<del> public SharedPreferencesHelper putBoolean(String key, boolean value) {
<del> edit().putBoolean(key, value);
<del> if (autoCommit)
<del> edit().commit();
<del>
<del> return this;
<del> }
<del>
<del> public SharedPreferencesHelper putInt(String key, int value) {
<del>
<del> edit().putInt(key, value);
<del> if (autoCommit)
<del> edit().commit();
<del> return this;
<del>
<del> }
<del>
<del> public SharedPreferencesHelper putJSON(Class<?> key, Object value) {
<del>
<del> putJSON(key.getName(), value);
<del> return this;
<del> }
<del>
<del> public SharedPreferencesHelper putJSON(Object value) {
<del>
<del> putJSON(value.getClass().getName(), value);
<del> return this;
<del> }
<del>
<del> public SharedPreferencesHelper putJSON(String key, Object value) {
<del>
<del> edit().putString(
<del> getKey(key),
<del> value instanceof CharSequence ? value.toString() : JsonUtils
<del> .toJSONString(value));
<del> if (autoCommit)
<del> edit().commit();
<del> return this;
<del> }
<del>
<del> public SharedPreferencesHelper putLon(String key, long value) {
<del> edit().putLong(key, value);
<del> if (autoCommit)
<del> edit().commit();
<del> return this;
<del> }
<del>
<del> public SharedPreferencesHelper putString(String key, String value) {
<del>
<del> edit().putString(key, value);
<del> if (autoCommit)
<del> edit().commit();
<del> return this;
<del> }
<del>
<del> public SharedPreferencesHelper unregisterOnSharedPreferenceChangeListener(
<del> OnSharedPreferenceChangeListener listener) {
<del> getSharedPreferences().unregisterOnSharedPreferenceChangeListener(
<del> listener);
<del> return this;
<del> }
<del>
<del> /**
<del> * 测试中的方法,保存序列化的对象到xml里
<del> *
<del> * @param key
<del> * @author wangx
<del> * **/
<del> @SuppressLint("NewApi")
<del> public void putObject(String key, Serializable serializable)
<del> throws IOException {
<del>
<del> ByteArrayOutputStream bots = new ByteArrayOutputStream();
<del> ObjectOutputStream opt = new ObjectOutputStream(bots);
<del> opt.writeObject(serializable);
<del> opt.flush();
<del> opt.close();
<del> opt.reset();
<del>
<del> String base64 = Base64.encodeToString(bots.toByteArray(),
<del> Base64.DEFAULT);
<del> putString(key, base64);
<del> bots = null;
<del>
<del> opt = null;
<del> base64 = null;
<del>
<del> }
<del>
<del> /**
<del> * 测试中的方法,从xml里取出序列化的对象
<del> *
<del> * @param key
<del> * @author wangx
<del> * @throws ClassNotFoundException
<del> * **/
<del> @SuppressLint("NewApi")
<del> public Object getObject(String key) throws ClassNotFoundException {
<del>
<del> String base64 = getString(key);
<del> ByteArrayInputStream is = new ByteArrayInputStream(Base64.decode(
<del> base64, Base64.DEFAULT));
<del> try {
<del> ObjectInputStream ois = new ObjectInputStream(is);
<del>
<del> return ois.readObject();
<del>
<del> } catch (IOException e) {
<del> return null;
<del> }
<del>
<del> }
<add> private static final String empty = "";
<add>
<add> private static final WeakHashMap<Context, Map<String, SharedPreferencesHelper>> mCache = new WeakHashMap<Context, Map<String, SharedPreferencesHelper>>(
<add> 3);
<add>
<add> private static final String tag = "SharePreferenceHelper";
<add>
<add> /***
<add> * 线程安全
<add> * **/
<add> public static SharedPreferencesHelper getCache(Context context, String name) {
<add> Map<String, SharedPreferencesHelper> hashmap = null;
<add> hashmap = mCache.get(context);// 根据主键 取出 主键缓存,
<add>
<add> if (hashmap == null) {// 如果二级缓存是否为空,
<add> synchronized (mCache) {// 给一级缓存加线程锁
<add> hashmap = mCache.get(context);// 再取出二级缓存
<add> if (hashmap == null) {// 判断二级缓存是否为空,在极端条件下,这个地方很有可能会被其他线程初始化
<add> hashmap = new WeakHashMap<String, SharedPreferencesHelper>(
<add> 2);
<add> mCache.put(context, hashmap);
<add> }
<add>
<add> }
<add>
<add> }
<add> SharedPreferencesHelper result = null;
<add> result = hashmap.get(name);
<add> if (result == null) {
<add> synchronized (hashmap) {
<add> result = hashmap.get(name);
<add> if (result == null) {
<add> result = new SharedPreferencesHelper(context, name);
<add> hashmap.put(name, result);
<add> }
<add> }
<add> }
<add>
<add> return result;
<add> }
<add>
<add> private static String getKey(Object key) {
<add>
<add> if (key == null) {
<add> return empty;
<add> } else if (key instanceof CharSequence) {
<add>
<add> return key.toString();
<add>
<add> } else if (key instanceof Class<?>) {
<add>
<add> return ((Class<?>) key).getName();
<add> } else {
<add>
<add> return key.getClass().getName();
<add> }
<add> }
<add>
<add> public synchronized static void onLowMemory() {
<add>
<add> mCache.clear();
<add> }
<add>
<add> final private SharedPreferences sp;// SP 杂化轨道,呵呵
<add>
<add> public SharedPreferencesHelper(Context context, String name) {
<add> sp = context.getSharedPreferences(name, Context.MODE_PRIVATE);
<add> }
<add>
<add> public SharedPreferencesHelper(SharedPreferences sp) {
<add> this.sp = sp;
<add> }
<add>
<add> public SharedPreferencesHelper clear() {
<add> Editor editor = edit();
<add> editor.clear();
<add> editor.commit();
<add> return this;
<add> }
<add>
<add> private Editor edit() {
<add> return getSharedPreferences().edit();
<add> }
<add>
<add> public Map<String, ?> getAll() {
<add> return getSharedPreferences().getAll();
<add> }
<add>
<add> public boolean getBoolean(String key, boolean defValue) {
<add> return getSharedPreferences().getBoolean(key, defValue);
<add> }
<add>
<add> public float getFloat(String key, float defValue) {
<add> return getSharedPreferences().getFloat(key, defValue);
<add> }
<add>
<add> public int getInt(String key, int defValue) {
<add> return getSharedPreferences().getInt(key, defValue);
<add> }
<add>
<add> public <T> T getJSON(Class<?> key, Class<T> clazz) {
<add> return getJSON(key.getName(), clazz);
<add>
<add> }
<add>
<add> public <T> T getJSON(Class<T> clazz) {
<add> return getJSON(clazz, clazz);
<add>
<add> }
<add>
<add> public <T> T getJSON(String key, Class<T> clazz) {
<add> try {
<add> return JsonUtils.parseObject(getString((key)), clazz);
<add> } catch (Exception e) {
<add> Log.w(tag, "getJSON", e);
<add> return null;
<add> }
<add>
<add> }
<add>
<add> /**
<add> * 测试中的方法,从xml里取出序列化的对象
<add> *
<add> * @param key
<add> * @author wangx
<add> * @throws ClassNotFoundException
<add> * **/
<add> @SuppressLint("NewApi")
<add> public Object getObject(String key) throws ClassNotFoundException {
<add>
<add> String base64 = getString(key);
<add> ByteArrayInputStream is = new ByteArrayInputStream(Base64.decode(
<add> base64, Base64.DEFAULT));
<add> try {
<add> ObjectInputStream ois = new ObjectInputStream(is);
<add>
<add> return ois.readObject();
<add>
<add> } catch (IOException e) {
<add> return null;
<add> }
<add>
<add> }
<add>
<add> private SharedPreferences getSharedPreferences() {
<add>
<add> return sp;
<add> }
<add>
<add> public String getString(String key) {
<add>
<add> return this.getString(key, empty);
<add> }
<add>
<add> public String getString(String key, String defValue) {
<add>
<add> return getSharedPreferences().getString(key, defValue);
<add> }
<add>
<add> public SharedPreferencesHelper putBoolean(String key, boolean value) {
<add> Editor editor = edit();
<add> editor.putBoolean(key, value);
<add>
<add> editor.commit();
<add>
<add> return this;
<add> }
<add>
<add> public SharedPreferencesHelper putInt(String key, int value) {
<add>
<add> Editor editor = edit();
<add> editor.putInt(key, value);
<add>
<add> editor.commit();
<add> return this;
<add>
<add> }
<add>
<add> public SharedPreferencesHelper putJSON(Class<?> key, Object value) {
<add>
<add> putJSON(key.getName(), value);
<add> return this;
<add> }
<add>
<add> public SharedPreferencesHelper putJSON(Object value) {
<add>
<add> putJSON(value.getClass().getName(), value);
<add> return this;
<add> }
<add>
<add> public SharedPreferencesHelper putJSON(String key, Object value) {
<add> Editor editor = edit();
<add> editor.putString(
<add> getKey(key),
<add> value instanceof CharSequence ? value.toString() : JsonUtils
<add> .toJSONString(value));
<add>
<add> editor.commit();
<add> return this;
<add> }
<add>
<add> public SharedPreferencesHelper putLon(String key, long value) {
<add> Editor editor = edit();
<add> editor.putLong(key, value);
<add>
<add> editor.commit();
<add> return this;
<add> }
<add>
<add> /**
<add> * 测试中的方法,保存序列化的对象到xml里
<add> *
<add> * @param key
<add> * @author wangx
<add> * **/
<add> @SuppressLint("NewApi")
<add> public void putObject(String key, Serializable serializable)
<add> throws IOException {
<add>
<add> ByteArrayOutputStream bots = new ByteArrayOutputStream();
<add> ObjectOutputStream opt = new ObjectOutputStream(bots);
<add> opt.writeObject(serializable);
<add> opt.flush();
<add> opt.close();
<add> opt.reset();
<add>
<add> String base64 = Base64.encodeToString(bots.toByteArray(),
<add> Base64.DEFAULT);
<add> putString(key, base64);
<add> bots = null;
<add>
<add> opt = null;
<add> base64 = null;
<add>
<add> }
<add>
<add> public SharedPreferencesHelper putString(String key, String value) {
<add>
<add> Editor editor = edit();
<add> editor.putString(key, value);
<add>
<add> editor.commit();
<add> return this;
<add> }
<add>
<add> public SharedPreferencesHelper registerOnSharedPreferenceChangeListener(
<add> OnSharedPreferenceChangeListener listener) {
<add> getSharedPreferences().registerOnSharedPreferenceChangeListener(
<add> listener);
<add> return this;
<add> }
<add>
<add> public SharedPreferencesHelper remove(String key) {
<add> Editor editor = edit();
<add> editor.remove(key);
<add>
<add> editor.commit();
<add> return this;
<add>
<add> }
<add>
<add> public SharedPreferencesHelper unregisterOnSharedPreferenceChangeListener(
<add> OnSharedPreferenceChangeListener listener) {
<add> getSharedPreferences().unregisterOnSharedPreferenceChangeListener(
<add> listener);
<add> return this;
<add> }
<ide> } |
|
Java | epl-1.0 | 871e142e85d6fd94530caa09c1a5eebc56bf3978 | 0 | vadimnehta/mdht,sarpkayanehta/mdht,sarpkayanehta/mdht,drbgfc/mdht,vadimnehta/mdht,sarpkayanehta/mdht,drbgfc/mdht,mdht/mdht,vadimnehta/mdht,drbgfc/mdht,drbgfc/mdht,vadimnehta/mdht,mdht/mdht,vadimnehta/mdht,mdht/mdht,drbgfc/mdht,drbgfc/mdht,mdht/mdht,sarpkayanehta/mdht,sarpkayanehta/mdht,vadimnehta/mdht,sarpkayanehta/mdht,mdht/mdht | /*******************************************************************************
* Copyright (c) 2009, 2012 David A Carlson and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* David A Carlson (XMLmodeling.com) - initial API and implementation
* John T.E. Timm (IBM Corporation) - added template parameter
* Christian W. Damus - generate multiple OCL constraints from one property (artf3121)
* - discriminate multiple property constraints (artf3185)
* - implement terminology constraint dependencies (artf3030)
* - support nested datatype subclasses (artf3350)
* Rama Ramakrishnan - Generated OCL for subclassed datatypes does not check nullFlavor(artf3450)
*
* $Id$
*******************************************************************************/
package org.openhealthtools.mdht.uml.transform.ecore;
import java.util.List;
import org.eclipse.uml2.uml.Class;
import org.eclipse.uml2.uml.Classifier;
import org.eclipse.uml2.uml.Constraint;
import org.eclipse.uml2.uml.Element;
import org.eclipse.uml2.uml.OpaqueExpression;
import org.eclipse.uml2.uml.Property;
import org.eclipse.uml2.uml.UMLPackage;
import org.openhealthtools.mdht.uml.common.util.UMLUtil;
import org.openhealthtools.mdht.uml.transform.AbstractTransform;
import org.openhealthtools.mdht.uml.transform.IBaseModelReflection;
import org.openhealthtools.mdht.uml.transform.PluginPropertiesUtil;
import org.openhealthtools.mdht.uml.transform.TransformerOptions;
import org.openhealthtools.mdht.uml.transform.ecore.IEcoreProfileReflection.ValidationSeverityKind;
import org.openhealthtools.mdht.uml.transform.ecore.IEcoreProfileReflection.ValidationStereotypeKind;
import org.openhealthtools.mdht.uml.transform.internal.Logger;
/**
* Abstract base class for UML-to-Ecore model transformations.
*/
public abstract class TransformAbstract extends AbstractTransform {
public static final String LF = System.getProperty("line.separator");
public static final String VALIDATION_ERROR = "constraints.validation.error";
public static final String VALIDATION_WARNING = "constraints.validation.warning";
public static final String VALIDATION_INFO = "constraints.validation.info";
private static final String VALIDATION_QUERY = "constraints.validation.query";
public static final String PARENT_CLASS_NULLFLAVOR_CHECK_STRING_PREPEND = " ( self.isNullFlavorUndefined() implies (";
public static final String PARENT_CLASS_NULLFLAVOR_CHECK_STRING_APPEND = " ))";
private final IEcoreProfileReflection ecoreProfile;
public TransformAbstract(TransformerOptions options, IBaseModelReflection baseModelReflection) {
super(options, baseModelReflection);
ecoreProfile = baseModelReflection.getAdapter(IEcoreProfileReflection.class);
if (ecoreProfile == null) {
throw new IllegalArgumentException(
"baseModelReflection does not provide IEcoreProfileReflection adapter required for UML-to-Ecore transformation");
}
}
protected final IEcoreProfileReflection getEcoreProfile() {
return ecoreProfile;
}
public boolean hasValidationSupport(Element element) {
return getEcoreProfile().getAppliedValidationStereotype(element) != null;
}
public void addValidationSupport(Property property, ValidationStereotypeKind kind, String constraintName) {
ValidationSeverityKind severity = getEcoreProfile().getValidationSeverity(property, kind);
String message = getEcoreProfile().getValidationMessage(property, kind);
Class constrainedClass = property.getClass_();
switch (severity) {
case INFO:
addValidationInfo(constrainedClass, constraintName, message);
break;
case WARNING:
addValidationWarning(constrainedClass, constraintName, message);
break;
default:
addValidationError(constrainedClass, constraintName, message);
break;
}
}
public void addValidationError(Class constrainedClass, String constraintName, String message) {
AnnotationsUtil annotationsUtil = getEcoreProfile().annotate(constrainedClass);
annotationsUtil.addAnnotation(VALIDATION_ERROR, constraintName);
annotationsUtil.saveAnnotations();
addValidationMessage(constrainedClass, constraintName, message);
}
public void addValidationWarning(Class constrainedClass, String constraintName, String message) {
AnnotationsUtil annotationsUtil = getEcoreProfile().annotate(constrainedClass);
annotationsUtil.addAnnotation(VALIDATION_WARNING, constraintName);
annotationsUtil.saveAnnotations();
addValidationMessage(constrainedClass, constraintName, message);
}
public void addValidationInfo(Class constrainedClass, String constraintName, String message) {
AnnotationsUtil annotationsUtil = getEcoreProfile().annotate(constrainedClass);
annotationsUtil.addAnnotation(VALIDATION_INFO, constraintName);
annotationsUtil.saveAnnotations();
addValidationMessage(constrainedClass, constraintName, message);
}
public void addValidationMessage(Class constrainedClass, String constraintName, String message) {
if (message == null) {
message = constraintName + " error message";
}
PluginPropertiesUtil properties = transformerOptions.getPluginPropertiesUtil();
if (properties != null) {
properties.addProperty(generateQualifiedConstraintName(constrainedClass, constraintName), message);
}
}
/*
* TODO - Revisit approach to naming constraints -
* Current approach uses nearest package to differentiate from inherited class methods for
* hierarchies with the same class name
*/
protected String generateQualifiedConstraintName(Class constrainedClass, String constraintName) {
String prefix = constrainedClass.getQualifiedName().replace("::", "").replace(
constrainedClass.getNearestPackage().getName(), "");
for (Classifier g : UMLUtil.getAllGeneralizations(constrainedClass)) {
if (g.getName().equals(constrainedClass.getName()) &&
(!g.getQualifiedName().equals(constrainedClass.getQualifiedName()))) {
prefix = constrainedClass.getNearestPackage().getName().toUpperCase() + prefix;
break;
}
}
if (constraintName != null && constraintName.startsWith(prefix)) {
return constraintName;
} else {
return prefix + (constraintName != null
? constraintName
: "");
}
}
protected void addOCLConstraint(Property property, ValidationStereotypeKind stereotype, StringBuffer body) {
addOCLConstraint(property, stereotype, body, null);
}
protected Constraint addOCLConstraint(Property property, ValidationStereotypeKind stereotype, StringBuffer body,
String constraintName) {
if (constraintName == null) {
constraintName = createConstraintName(property);
}
if (property.getClass_().getOwnedRule(constraintName) != null) {
String message = "Constraint name already defined: '" + constraintName + "' in " +
property.getClass_().getQualifiedName();
Logger.log(Logger.WARNING, message);
// add validation message, if included in the model
addValidationSupport(property, stereotype, constraintName);
return null;
}
Property baseProperty = getBaseProperty(property);
String selfName = "self." + baseProperty.getName();
String nullFlavorBody = body.toString();
boolean hasNullFlavor = false;
if (baseProperty.getType() instanceof Class) {
hasNullFlavor = isSubTypeOfANY((Class) baseProperty.getType());
}
if (hasNullFlavor && !getEcoreProfile().isMandatory(property)) {
if (baseProperty.upperBound() == 1) {
nullFlavorBody = "(" + selfName + ".oclIsUndefined() or " + selfName +
".isNullFlavorUndefined()) implies (" + body + ")";
} else {
// must have size()==1 to have nullFlavor
nullFlavorBody = "(" + selfName + "->isEmpty() or " + selfName +
"->exists(element | element.isNullFlavorUndefined()))" + " implies (" + body + ")";
}
}
// Add nullFlavor checks for the enclosing parent (if necessary)
// This check will be relaxed further if the parent attribute is Mandatory, in which case the check is not required.
if (property.eContainer() instanceof Class) {
if (isSubTypeOfANY((Class) property.eContainer())) {
nullFlavorBody = PARENT_CLASS_NULLFLAVOR_CHECK_STRING_PREPEND + nullFlavorBody +
PARENT_CLASS_NULLFLAVOR_CHECK_STRING_APPEND;
}
}
Constraint result = property.getClass_().createOwnedRule(constraintName, UMLPackage.eINSTANCE.getConstraint());
result.getConstrainedElements().add(property.getClass_());
OpaqueExpression expression = (OpaqueExpression) result.createSpecification(
null, null, UMLPackage.eINSTANCE.getOpaqueExpression());
expression.getLanguages().add("OCL");
expression.getBodies().add(nullFlavorBody);
addValidationSupport(property, stereotype, constraintName);
return result;
}
protected String createInheritedConstraintName(Property property, ValidationStereotypeKind stereotype) {
String constraintName = null;
if (getEcoreProfile().getValidationSeverity(property, stereotype) == ValidationSeverityKind.ERROR) {
Property inheritedProperty = org.openhealthtools.mdht.uml.common.util.UMLUtil.getInheritedProperty(property);
if (getEcoreProfile().inheritsConstraintName(property, inheritedProperty, stereotype)) {
constraintName = createInheritedConstraintName(inheritedProperty, stereotype);
}
}
if (constraintName == null) {
constraintName = createConstraintName(property);
}
return constraintName;
}
protected String createConstraintName(Property property) {
return createConstraintName(property.getClass_(), property.getName().substring(0, 1).toUpperCase() +
property.getName().substring(1));
}
protected String createConstraintName(Class umlClass, String suffix) {
return generateQualifiedConstraintName(umlClass, suffix);
}
protected String getConstraintDependency(AnnotationsUtil annotations, String constraintName) {
return annotations.getAnnotation("constraints.validation.dependOn." + constraintName);
}
protected void setConstraintDependency(AnnotationsUtil annotations, String constraintName, String dependencyName) {
// for now, we only support a single dependency (terminology on property)
annotations.setAnnotation("constraints.validation.dependOn." + constraintName, dependencyName);
}
protected void annotateQueryConstraint(Constraint constraint, Class context) {
AnnotationsUtil annotationsUtil = getEcoreProfile().annotate(context);
annotationsUtil.addAnnotation(VALIDATION_QUERY, constraint.getName());
annotationsUtil.saveAnnotations();
}
public static String normalizeConstraintName(String constraintName) {
String result = "";
String[] parts = constraintName.split("_");
for (String part : parts) {
result += part.substring(0, 1).toUpperCase() + part.substring(1);
}
return result;
}
/**
* Checks if the Class is a subtype of datatpes::ANY
*
* @return
*/
public boolean isSubTypeOfANY(Classifier clazz) {
boolean retVal = false;
// Check if the property is of type Class
if (clazz instanceof Class) {
List<String> parentNames = org.openhealthtools.mdht.uml.common.util.UMLUtil.getAllParentNames(clazz);
retVal = parentNames.contains("ANY");
}
return retVal;
}
}
| core/plugins/org.openhealthtools.mdht.uml.transform/src/org/openhealthtools/mdht/uml/transform/ecore/TransformAbstract.java | /*******************************************************************************
* Copyright (c) 2009, 2012 David A Carlson and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* David A Carlson (XMLmodeling.com) - initial API and implementation
* John T.E. Timm (IBM Corporation) - added template parameter
* Christian W. Damus - generate multiple OCL constraints from one property (artf3121)
* - discriminate multiple property constraints (artf3185)
* - implement terminology constraint dependencies (artf3030)
* - support nested datatype subclasses (artf3350)
* Rama Ramakrishnan - Generated OCL for subclassed datatypes does not check nullFlavor(artf3450)
*
* $Id$
*******************************************************************************/
package org.openhealthtools.mdht.uml.transform.ecore;
import java.util.List;
import org.eclipse.uml2.uml.Class;
import org.eclipse.uml2.uml.Classifier;
import org.eclipse.uml2.uml.Constraint;
import org.eclipse.uml2.uml.Element;
import org.eclipse.uml2.uml.OpaqueExpression;
import org.eclipse.uml2.uml.Property;
import org.eclipse.uml2.uml.UMLPackage;
import org.openhealthtools.mdht.uml.transform.AbstractTransform;
import org.openhealthtools.mdht.uml.transform.IBaseModelReflection;
import org.openhealthtools.mdht.uml.transform.PluginPropertiesUtil;
import org.openhealthtools.mdht.uml.transform.TransformerOptions;
import org.openhealthtools.mdht.uml.transform.ecore.IEcoreProfileReflection.ValidationSeverityKind;
import org.openhealthtools.mdht.uml.transform.ecore.IEcoreProfileReflection.ValidationStereotypeKind;
import org.openhealthtools.mdht.uml.transform.internal.Logger;
/**
* Abstract base class for UML-to-Ecore model transformations.
*/
public abstract class TransformAbstract extends AbstractTransform {
public static final String LF = System.getProperty("line.separator");
public static final String VALIDATION_ERROR = "constraints.validation.error";
public static final String VALIDATION_WARNING = "constraints.validation.warning";
public static final String VALIDATION_INFO = "constraints.validation.info";
private static final String VALIDATION_QUERY = "constraints.validation.query";
public static final String PARENT_CLASS_NULLFLAVOR_CHECK_STRING_PREPEND = " ( self.isNullFlavorUndefined() implies (";
public static final String PARENT_CLASS_NULLFLAVOR_CHECK_STRING_APPEND = " ))";
private final IEcoreProfileReflection ecoreProfile;
public TransformAbstract(TransformerOptions options, IBaseModelReflection baseModelReflection) {
super(options, baseModelReflection);
ecoreProfile = baseModelReflection.getAdapter(IEcoreProfileReflection.class);
if (ecoreProfile == null) {
throw new IllegalArgumentException(
"baseModelReflection does not provide IEcoreProfileReflection adapter required for UML-to-Ecore transformation");
}
}
protected final IEcoreProfileReflection getEcoreProfile() {
return ecoreProfile;
}
public boolean hasValidationSupport(Element element) {
return getEcoreProfile().getAppliedValidationStereotype(element) != null;
}
public void addValidationSupport(Property property, ValidationStereotypeKind kind, String constraintName) {
ValidationSeverityKind severity = getEcoreProfile().getValidationSeverity(property, kind);
String message = getEcoreProfile().getValidationMessage(property, kind);
Class constrainedClass = property.getClass_();
switch (severity) {
case INFO:
addValidationInfo(constrainedClass, constraintName, message);
break;
case WARNING:
addValidationWarning(constrainedClass, constraintName, message);
break;
default:
addValidationError(constrainedClass, constraintName, message);
break;
}
}
public void addValidationError(Class constrainedClass, String constraintName, String message) {
AnnotationsUtil annotationsUtil = getEcoreProfile().annotate(constrainedClass);
annotationsUtil.addAnnotation(VALIDATION_ERROR, constraintName);
annotationsUtil.saveAnnotations();
addValidationMessage(constrainedClass, constraintName, message);
}
public void addValidationWarning(Class constrainedClass, String constraintName, String message) {
AnnotationsUtil annotationsUtil = getEcoreProfile().annotate(constrainedClass);
annotationsUtil.addAnnotation(VALIDATION_WARNING, constraintName);
annotationsUtil.saveAnnotations();
addValidationMessage(constrainedClass, constraintName, message);
}
public void addValidationInfo(Class constrainedClass, String constraintName, String message) {
AnnotationsUtil annotationsUtil = getEcoreProfile().annotate(constrainedClass);
annotationsUtil.addAnnotation(VALIDATION_INFO, constraintName);
annotationsUtil.saveAnnotations();
addValidationMessage(constrainedClass, constraintName, message);
}
public void addValidationMessage(Class constrainedClass, String constraintName, String message) {
if (message == null) {
message = constraintName + " error message";
}
PluginPropertiesUtil properties = transformerOptions.getPluginPropertiesUtil();
if (properties != null) {
properties.addProperty(generateQualifiedConstraintName(constrainedClass, constraintName), message);
}
}
protected String generateQualifiedConstraintName(Class constrainedClass, String constraintName) {
String prefix = constrainedClass.getQualifiedName().replace("::", "");
if (constraintName != null && constraintName.startsWith(prefix)) {
return constraintName;
} else {
return prefix + (constraintName != null
? constraintName
: "");
}
}
protected void addOCLConstraint(Property property, ValidationStereotypeKind stereotype, StringBuffer body) {
addOCLConstraint(property, stereotype, body, null);
}
protected Constraint addOCLConstraint(Property property, ValidationStereotypeKind stereotype, StringBuffer body,
String constraintName) {
if (constraintName == null) {
constraintName = createConstraintName(property);
}
if (property.getClass_().getOwnedRule(constraintName) != null) {
String message = "Constraint name already defined: '" + constraintName + "' in " +
property.getClass_().getQualifiedName();
Logger.log(Logger.WARNING, message);
// add validation message, if included in the model
addValidationSupport(property, stereotype, constraintName);
return null;
}
Property baseProperty = getBaseProperty(property);
String selfName = "self." + baseProperty.getName();
String nullFlavorBody = body.toString();
boolean hasNullFlavor = false;
if (baseProperty.getType() instanceof Class) {
hasNullFlavor = isSubTypeOfANY((Class) baseProperty.getType());
}
if (hasNullFlavor && !getEcoreProfile().isMandatory(property)) {
if (baseProperty.upperBound() == 1) {
nullFlavorBody = "(" + selfName + ".oclIsUndefined() or " + selfName +
".isNullFlavorUndefined()) implies (" + body + ")";
} else {
// must have size()==1 to have nullFlavor
nullFlavorBody = "(" + selfName + "->isEmpty() or " + selfName +
"->exists(element | element.isNullFlavorUndefined()))" + " implies (" + body + ")";
}
}
// Add nullFlavor checks for the enclosing parent (if necessary)
// This check will be relaxed further if the parent attribute is Mandatory, in which case the check is not required.
if (property.eContainer() instanceof Class) {
if (isSubTypeOfANY((Class) property.eContainer())) {
nullFlavorBody = PARENT_CLASS_NULLFLAVOR_CHECK_STRING_PREPEND + nullFlavorBody +
PARENT_CLASS_NULLFLAVOR_CHECK_STRING_APPEND;
}
}
Constraint result = property.getClass_().createOwnedRule(constraintName, UMLPackage.eINSTANCE.getConstraint());
result.getConstrainedElements().add(property.getClass_());
OpaqueExpression expression = (OpaqueExpression) result.createSpecification(
null, null, UMLPackage.eINSTANCE.getOpaqueExpression());
expression.getLanguages().add("OCL");
expression.getBodies().add(nullFlavorBody);
addValidationSupport(property, stereotype, constraintName);
return result;
}
protected String createInheritedConstraintName(Property property, ValidationStereotypeKind stereotype) {
String constraintName = null;
if (getEcoreProfile().getValidationSeverity(property, stereotype) == ValidationSeverityKind.ERROR) {
Property inheritedProperty = org.openhealthtools.mdht.uml.common.util.UMLUtil.getInheritedProperty(property);
if (getEcoreProfile().inheritsConstraintName(property, inheritedProperty, stereotype)) {
constraintName = createInheritedConstraintName(inheritedProperty, stereotype);
}
}
if (constraintName == null) {
constraintName = createConstraintName(property);
}
return constraintName;
}
protected String createConstraintName(Property property) {
return createConstraintName(property.getClass_(), property.getName().substring(0, 1).toUpperCase() +
property.getName().substring(1));
}
protected String createConstraintName(Class umlClass, String suffix) {
return generateQualifiedConstraintName(umlClass, suffix);
}
protected String getConstraintDependency(AnnotationsUtil annotations, String constraintName) {
return annotations.getAnnotation("constraints.validation.dependOn." + constraintName);
}
protected void setConstraintDependency(AnnotationsUtil annotations, String constraintName, String dependencyName) {
// for now, we only support a single dependency (terminology on property)
annotations.setAnnotation("constraints.validation.dependOn." + constraintName, dependencyName);
}
protected void annotateQueryConstraint(Constraint constraint, Class context) {
AnnotationsUtil annotationsUtil = getEcoreProfile().annotate(context);
annotationsUtil.addAnnotation(VALIDATION_QUERY, constraint.getName());
annotationsUtil.saveAnnotations();
}
public static String normalizeConstraintName(String constraintName) {
String result = "";
String[] parts = constraintName.split("_");
for (String part : parts) {
result += part.substring(0, 1).toUpperCase() + part.substring(1);
}
return result;
}
/**
* Checks if the Class is a subtype of datatpes::ANY
*
* @return
*/
public boolean isSubTypeOfANY(Classifier clazz) {
boolean retVal = false;
// Check if the property is of type Class
if (clazz instanceof Class) {
List<String> parentNames = org.openhealthtools.mdht.uml.common.util.UMLUtil.getAllParentNames(clazz);
retVal = parentNames.contains("ANY");
}
return retVal;
}
}
| Fix issue with overriding constrains with same name from base class | core/plugins/org.openhealthtools.mdht.uml.transform/src/org/openhealthtools/mdht/uml/transform/ecore/TransformAbstract.java | Fix issue with overriding constrains with same name from base class | <ide><path>ore/plugins/org.openhealthtools.mdht.uml.transform/src/org/openhealthtools/mdht/uml/transform/ecore/TransformAbstract.java
<ide> import org.eclipse.uml2.uml.OpaqueExpression;
<ide> import org.eclipse.uml2.uml.Property;
<ide> import org.eclipse.uml2.uml.UMLPackage;
<add>import org.openhealthtools.mdht.uml.common.util.UMLUtil;
<ide> import org.openhealthtools.mdht.uml.transform.AbstractTransform;
<ide> import org.openhealthtools.mdht.uml.transform.IBaseModelReflection;
<ide> import org.openhealthtools.mdht.uml.transform.PluginPropertiesUtil;
<ide> }
<ide> }
<ide>
<add> /*
<add> * TODO - Revisit approach to naming constraints -
<add> * Current approach uses nearest package to differentiate from inherited class methods for
<add> * hierarchies with the same class name
<add> */
<ide> protected String generateQualifiedConstraintName(Class constrainedClass, String constraintName) {
<del> String prefix = constrainedClass.getQualifiedName().replace("::", "");
<add> String prefix = constrainedClass.getQualifiedName().replace("::", "").replace(
<add> constrainedClass.getNearestPackage().getName(), "");
<add>
<add> for (Classifier g : UMLUtil.getAllGeneralizations(constrainedClass)) {
<add>
<add> if (g.getName().equals(constrainedClass.getName()) &&
<add> (!g.getQualifiedName().equals(constrainedClass.getQualifiedName()))) {
<add>
<add> prefix = constrainedClass.getNearestPackage().getName().toUpperCase() + prefix;
<add> break;
<add> }
<add>
<add> }
<add>
<ide> if (constraintName != null && constraintName.startsWith(prefix)) {
<ide> return constraintName;
<ide> } else { |
|
Java | mpl-2.0 | bd5ca24d8c3b4b12c410aaae00a581c0f5cc89d4 | 0 | msteinhoff/hello-world | 4c85b673-cb8e-11e5-bb93-00264a111016 | src/main/java/HelloWorld.java | 4c76fba8-cb8e-11e5-9458-00264a111016 | I finished programming, there is nothing left to program | src/main/java/HelloWorld.java | I finished programming, there is nothing left to program | <ide><path>rc/main/java/HelloWorld.java
<del>4c76fba8-cb8e-11e5-9458-00264a111016
<add>4c85b673-cb8e-11e5-bb93-00264a111016 |
|
JavaScript | mit | 903552b0c3fae7380677a927a7121e876c576138 | 0 | indexzero/errs,brianloveswords/errs | /*
* errs.js: Simple error creation and passing utilities.
*
* (C) 2012, Nodejitsu Inc.
* MIT LICENSE
*
*/
var events = require('events'),
util = require('util');
//
// Container for registered error types.
//
exports.registered = {};
//
// ### function create (type, opts)
// #### @type {string} **Optional** Registered error type to create
// #### @opts {string|object|Array|function} Options for creating the error:
// * `string`: Message for the error
// * `object`: Properties to include on the error
// * `array`: Message for the error (' ' joined).
// * `function`: Function to return error options.
//
// Creates a new error instance for with the specified `type`
// and `options`. If the `type` is not registered then a new
// `Error` instance will be created.
//
exports.create = function createErr(type, opts) {
if (!arguments[1] && !exports.registered[type]) {
opts = type;
type = null;
}
//
// If the `opts` has a `stack` property assume
// that it is already an error instance.
//
if (opts && opts.stack) {
return opts;
}
var message,
ErrorProto,
error;
//
// Parse arguments liberally for the message
//
if (typeof opts === 'function') {
opts = opts();
}
if (Array.isArray(opts)) {
message = opts.join(' ');
opts = null;
}
else if (opts) {
switch (typeof opts) {
case 'string':
message = opts || 'Unspecified error';
opts = null;
break;
case 'object':
message = (opts && opts.message) || 'Unspecified error';
break;
default:
message = 'Unspecified error';
break;
}
}
//
// Instantiate a new Error instance or a new
// registered error type (if it exists).
//
ErrorProto = type && exports.registered[type] || Error;
error = new (ErrorProto)(message);
if (!error.name || error.name === 'Error') {
error.name = ErrorProto.name || 'Error';
}
//
// Capture a stack trace if it does not already exist and
// remote the part of the stack trace referencing `errs.js`.
//
if (!error.stack) {
Error.call(error);
Error.captureStackTrace(error, createErr);
}
else {
error.stack = error.stack.split('\n');
error.stack.splice(1, 1);
error.stack = error.stack.join('\n');
}
//
// Copy all options to the new error instance.
//
if (opts) {
Object.keys(opts).forEach(function (key) {
error[key] = opts[key];
});
}
return error;
};
//
// ### function merge (err, type, opts)
// #### @err {error} The error to merge
// #### @type {string} **Optional** Registered error type to create
// #### @opts {string|object|Array|function} Options for creating the error:
// * `string`: Message for the error
// * `object`: Properties to include on the error
// * `array`: Message for the error (' ' joined).
// * `function`: Function to return error options.
//
// Merges an existing error with a new error instance for with
// the specified `type` and `options`.
//
exports.merge = function (err, type, opts) {
var merged = exports.create(type, opts);
// optional stuff that might be created by module
Object.keys(err).forEach(function (key) {
// in node v0.4 v8 errors where treated differently
// we need to make sure we aren't merging these properties
// http://code.google.com/p/v8/issues/detail?id=1215
if(['stack', 'type', 'arguments', 'message'].indexOf(key)===-1) {
merged[key] = err[key];
}
});
// merging
merged.name = merged.name || err.name;
merged.message = merged.message || err.message;
// override stack
merged.stack = err.stack;
// add human-readable errors
merged.description = err.message;
merged.stacktrace = err.stack.split("\n");
return merged;
};
//
// ### function handle (error, callback)
// #### @error {string|function|Array|object} Error to handle
// #### @callback {function|EventEmitter} **Optional** Continuation or stream to pass the error to.
// #### @stream {EventEmitter} **Optional** Explicit EventEmitter to use.
//
// Attempts to instantiate the given `error`. If the `error` is already a properly
// formed `error` object (with a `stack` property) it will not be modified.
//
// * If `callback` is a function, it is invoked with the `error`.
// * If `callback` is an `EventEmitter`, it emits the `error` event on
// that emitter and returns it.
// * If no `callback`, return a new `EventEmitter` which emits `error`
// on `process.nextTick()`.
//
exports.handle = function (error, callback, stream) {
error = exports.create(error);
if (typeof callback === 'function') {
callback(error);
}
if (typeof callback !== 'function' || stream) {
var emitter = stream || callback || new events.EventEmitter();
process.nextTick(function () { emitter.emit('error', error); });
return emitter;
}
};
//
// ### function register (type, proto)
// #### @type {string} **Optional** Type of the error to register.
// #### @proto {function} Constructor function of the error to register.
//
// Registers the specified `proto` to `type` for future calls to
// `errors.create(type, opts)`.
//
exports.register = function (type, proto) {
if (arguments.length === 1) {
proto = type;
type = proto.name.toLowerCase();
}
exports.registered[type] = proto;
};
//
// ### function unregister (type)
// #### @type {string} Type of the error to unregister.
//
// Unregisters the specified `type` for future calls to
// `errors.create(type, opts)`.
//
exports.unregister = function (type) {
delete exports.registered[type];
};
| lib/errs.js | /*
* errs.js: Simple error creation and passing utilities.
*
* (C) 2012, Nodejitsu Inc.
* MIT LICENSE
*
*/
var events = require('events'),
util = require('util');
//
// Container for registered error types.
//
exports.registered = {};
//
// ### function create (type, opts)
// #### @type {string} **Optional** Registered error type to create
// #### @opts {string|object|Array|function} Options for creating the error:
// * `string`: Message for the error
// * `object`: Properties to include on the error
// * `array`: Message for the error (' ' joined).
// * `function`: Function to return error options.
//
// Creates a new error instance for with the specified `type`
// and `options`. If the `type` is not registered then a new
// `Error` instance will be created.
//
exports.create = function createErr(type, opts) {
if (!arguments[1] && !exports.registered[type]) {
opts = type;
type = null;
}
//
// If the `opts` has a `stack` property assume
// that it is already an error instance.
//
if (opts && opts.stack) {
return opts;
}
var message,
ErrorProto,
error;
//
// Parse arguments liberally for the message
//
if (typeof opts === 'function') {
opts = opts();
}
if (Array.isArray(opts)) {
message = opts.join(' ');
opts = null;
}
else if (opts) {
switch (typeof opts) {
case 'string':
message = opts || 'Unspecified error';
opts = null;
break;
case 'object':
message = (opts && opts.message) || 'Unspecified error';
break;
default:
message = 'Unspecified error';
break;
}
}
//
// Instantiate a new Error instance or a new
// registered error type (if it exists).
//
ErrorProto = type && exports.registered[type] || Error;
error = new (ErrorProto)(message);
if (!error.name || error.name === 'Error') {
error.name = ErrorProto.name || 'Error';
}
//
// Capture a stack trace if it does not already exist and
// remote the part of the stack trace referencing `errs.js`.
//
if (!error.stack) {
Error.call(error);
Error.captureStackTrace(error, createErr);
}
else {
error.stack = error.stack.split('\n');
error.stack.splice(1, 1);
error.stack = error.stack.join('\n');
}
//
// Copy all options to the new error instance.
//
if (opts) {
Object.keys(opts).forEach(function (key) {
error[key] = opts[key];
});
}
return error;
};
//
// ### function merge (err, type, opts)
// #### @err {error} The error to merge
// #### @type {string} **Optional** Registered error type to create
// #### @opts {string|object|Array|function} Options for creating the error:
// * `string`: Message for the error
// * `object`: Properties to include on the error
// * `array`: Message for the error (' ' joined).
// * `function`: Function to return error options.
//
// Merges an existing error with a new error instance for with
// the specified `type` and `options`.
//
exports.merge = function (err, type, opts) {
var merged = exports.create(type, opts);
// optional stuff that might be created by module
Object.keys(err).forEach(function (key) {
// in node v0.4 v8 errors where treated differently
// we need to make sure we aren't merging these properties
if(['stack', 'type', 'arguments', 'message'].indexOf(key)===-1) {
merged[key] = err[key];
}
});
// merging
merged.name = merged.name || err.name;
merged.message = merged.message || err.message;
// override stack
merged.stack = err.stack;
// add human-readable errors
merged.description = err.message;
merged.stacktrace = err.stack.split("\n");
return merged;
};
//
// ### function handle (error, callback)
// #### @error {string|function|Array|object} Error to handle
// #### @callback {function|EventEmitter} **Optional** Continuation or stream to pass the error to.
// #### @stream {EventEmitter} **Optional** Explicit EventEmitter to use.
//
// Attempts to instantiate the given `error`. If the `error` is already a properly
// formed `error` object (with a `stack` property) it will not be modified.
//
// * If `callback` is a function, it is invoked with the `error`.
// * If `callback` is an `EventEmitter`, it emits the `error` event on
// that emitter and returns it.
// * If no `callback`, return a new `EventEmitter` which emits `error`
// on `process.nextTick()`.
//
exports.handle = function (error, callback, stream) {
error = exports.create(error);
if (typeof callback === 'function') {
callback(error);
}
if (typeof callback !== 'function' || stream) {
var emitter = stream || callback || new events.EventEmitter();
process.nextTick(function () { emitter.emit('error', error); });
return emitter;
}
};
//
// ### function register (type, proto)
// #### @type {string} **Optional** Type of the error to register.
// #### @proto {function} Constructor function of the error to register.
//
// Registers the specified `proto` to `type` for future calls to
// `errors.create(type, opts)`.
//
exports.register = function (type, proto) {
if (arguments.length === 1) {
proto = type;
type = proto.name.toLowerCase();
}
exports.registered[type] = proto;
};
//
// ### function unregister (type)
// #### @type {string} Type of the error to unregister.
//
// Unregisters the specified `type` for future calls to
// `errors.create(type, opts)`.
//
exports.unregister = function (type) {
delete exports.registered[type];
};
| [minor] added reference to the spec
| lib/errs.js | [minor] added reference to the spec | <ide><path>ib/errs.js
<ide> Object.keys(err).forEach(function (key) {
<ide> // in node v0.4 v8 errors where treated differently
<ide> // we need to make sure we aren't merging these properties
<add> // http://code.google.com/p/v8/issues/detail?id=1215
<ide> if(['stack', 'type', 'arguments', 'message'].indexOf(key)===-1) {
<ide> merged[key] = err[key];
<ide> } |
|
JavaScript | mit | 65a9ad3be00548482762d717e90b29556fec386a | 0 | dmoll1974/lt-dash,dmoll1974/lt-dash,dmoll1974/lt-dash,dmoll1974/lt-dash | 'use strict';
module.exports = function(app) {
var users = require('../../app/controllers/users.server.controller');
var dashboards = require('../../app/controllers/dashboards.server.controller');
// Dashboards Routes
app.route('/dashboards')
.get(dashboards.list)
.post(users.requiresLogin, dashboards.create);
app.route('dashboards/:productName/:dashboardName')
.get(dashboards.read)
.put(users.requiresLogin, dashboards.hasAuthorization, dashboards.update)
.delete(users.requiresLogin, dashboards.hasAuthorization, dashboards.delete);
// Finish by binding the Dashboard middleware
app.param('dashboardId', dashboards.dashboardByID);
// app.param('dashboardName', dashboards.dashboardByName);
app.param('productName', dashboards.dashboardByProductName);
};
| app/routes/dashboards.server.routes.js | 'use strict';
module.exports = function(app) {
var users = require('../../app/controllers/users.server.controller');
var dashboards = require('../../app/controllers/dashboards.server.controller');
// Dashboards Routes
app.route('/dashboards')
.get(dashboards.list)
.post(users.requiresLogin, dashboards.create);
app.route('/dashboards/:dashboardId')
.get(dashboards.read)
.put(users.requiresLogin, dashboards.hasAuthorization, dashboards.update)
.delete(users.requiresLogin, dashboards.hasAuthorization, dashboards.delete);
// Finish by binding the Dashboard middleware
app.param('dashboardId', dashboards.dashboardByID);
app.param('productId', dashboards.dashboardByProductId);
};
| addede middleware
| app/routes/dashboards.server.routes.js | addede middleware | <ide><path>pp/routes/dashboards.server.routes.js
<ide> .get(dashboards.list)
<ide> .post(users.requiresLogin, dashboards.create);
<ide>
<del> app.route('/dashboards/:dashboardId')
<add> app.route('dashboards/:productName/:dashboardName')
<ide> .get(dashboards.read)
<ide> .put(users.requiresLogin, dashboards.hasAuthorization, dashboards.update)
<ide> .delete(users.requiresLogin, dashboards.hasAuthorization, dashboards.delete);
<ide>
<ide> // Finish by binding the Dashboard middleware
<ide> app.param('dashboardId', dashboards.dashboardByID);
<del> app.param('productId', dashboards.dashboardByProductId);
<add>// app.param('dashboardName', dashboards.dashboardByName);
<add> app.param('productName', dashboards.dashboardByProductName);
<ide> }; |
|
JavaScript | apache-2.0 | 58fcb02ea99d2b6c0f65101d0a373689662c20a5 | 0 | IoSL-INav/backend | /**
* IoSL-INav routes/hotspots
* SNET TU Berlin
* using PIazza code base
*
* Hotspots specific endpoints
*/
/* Variables and configurations. */
var express = require('express');
var Hotspot = require('./../models/hotspot');
var config = require('./../config');
var controller = require('./../controllers/hotspots');
var router = express();
/* Param middleware. */
/* If given, add hotspot ID to request. */
router.param('hid', function(req, res, next, hid) {
req.hotspotID = hid;
next();
});
/* If given, add beacon ID to request. */
router.param('bid', function(req, res, next, bid) {
req.beaconID = bid;
next();
});
/* Routes concerning hotspots. */
router.route('/')
.get(config.authenticate, controller.getAllHotspots);
router.route('/active_friends')
.get(config.authenticate, controller.getActiveFriends);
router.route('/:hid')
.get(config.authenticate, controller.getHotspot);
router.route('/:hid/beacons')
.get(config.authenticate, controller.getAllBeacons);
router.route('/:hid/beacons/:bid')
.get(config.authenticate, controller.getBeacon);
/* Export router with described routes. */
module.exports = router; | routes/hotspots.js | /**
* IoSL-INav routes/hotspots
* SNET TU Berlin
* using PIazza code base
*
* Hotspots specific endpoints
*/
/* Variables and configurations. */
var express = require('express');
var Hotspot = require('./../models/hotspot');
var config = require('./../config');
var controller = require('./../controllers/hotspots');
var router = express();
/* Param middleware. */
/* If given, add hotspot ID to request. */
router.param('hid', function(req, res, next, hid) {
req.hotspotID = hid;
next();
});
/* If given, add beacon ID to request. */
router.param('bid', function(req, res, next, bid) {
req.beaconID = bid;
next();
});
/* Routes concerning hotspots. */
router.route('/')
.get(config.authenticate, controller.getAllHotspots);
router.route('/:hid')
.get(config.authenticate, controller.getHotspot);
router.route('/active_friends')
.get(config.authenticate, controller.getActiveFriends);
router.route('/:hid/beacons')
.get(config.authenticate, controller.getAllBeacons);
router.route('/:hid/beacons/:bid')
.get(config.authenticate, controller.getBeacon);
/* Export router with described routes. */
module.exports = router; | Change of routes.
| routes/hotspots.js | Change of routes. | <ide><path>outes/hotspots.js
<ide> router.route('/')
<ide> .get(config.authenticate, controller.getAllHotspots);
<ide>
<add>router.route('/active_friends')
<add> .get(config.authenticate, controller.getActiveFriends);
<add>
<ide> router.route('/:hid')
<ide> .get(config.authenticate, controller.getHotspot);
<del>
<del>router.route('/active_friends')
<del> .get(config.authenticate, controller.getActiveFriends);
<ide>
<ide> router.route('/:hid/beacons')
<ide> .get(config.authenticate, controller.getAllBeacons); |
|
JavaScript | mit | cb3e6f3cf60df232250a494dd9a778053835e65f | 0 | NekR/webpack,SimenB/webpack,NekR/webpack,webpack/webpack,SimenB/webpack,EliteScientist/webpack,EliteScientist/webpack,SimenB/webpack,webpack/webpack,webpack/webpack,SimenB/webpack,webpack/webpack | /*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const RequestShortener = require("./RequestShortener");
const SizeFormatHelpers = require("./SizeFormatHelpers");
const formatLocation = require("./formatLocation");
const identifierUtils = require("./util/identifier");
const compareLocations = require("./compareLocations");
const optionsOrFallback = (...args) => {
let optionValues = [];
optionValues.push(...args);
return optionValues.find(optionValue => optionValue !== undefined);
};
const compareId = (a, b) => {
if (typeof a !== typeof b) {
return typeof a < typeof b ? -1 : 1;
}
if (a < b) return -1;
if (a > b) return 1;
return 0;
};
class Stats {
constructor(compilation) {
this.compilation = compilation;
this.hash = compilation.hash;
this.startTime = undefined;
this.endTime = undefined;
}
static filterWarnings(warnings, warningsFilter) {
// we dont have anything to filter so all warnings can be shown
if (!warningsFilter) {
return warnings;
}
// create a chain of filters
// if they return "true" a warning should be suppressed
const normalizedWarningsFilters = [].concat(warningsFilter).map(filter => {
if (typeof filter === "string") {
return warning => warning.includes(filter);
}
if (filter instanceof RegExp) {
return warning => filter.test(warning);
}
if (typeof filter === "function") {
return filter;
}
throw new Error(
`Can only filter warnings with Strings or RegExps. (Given: ${filter})`
);
});
return warnings.filter(warning => {
return !normalizedWarningsFilters.some(check => check(warning));
});
}
formatFilePath(filePath) {
const OPTIONS_REGEXP = /^(\s|\S)*!/;
return filePath.includes("!")
? `${filePath.replace(OPTIONS_REGEXP, "")} (${filePath})`
: `${filePath}`;
}
hasWarnings() {
return (
this.compilation.warnings.length > 0 ||
this.compilation.children.some(child => child.getStats().hasWarnings())
);
}
hasErrors() {
return (
this.compilation.errors.length > 0 ||
this.compilation.children.some(child => child.getStats().hasErrors())
);
}
// remove a prefixed "!" that can be specified to reverse sort order
normalizeFieldKey(field) {
if (field[0] === "!") {
return field.substr(1);
}
return field;
}
// if a field is prefixed by a "!" reverse sort order
sortOrderRegular(field) {
if (field[0] === "!") {
return false;
}
return true;
}
toJson(options, forToString) {
if (typeof options === "boolean" || typeof options === "string") {
options = Stats.presetToOptions(options);
} else if (!options) {
options = {};
}
const optionOrLocalFallback = (v, def) =>
v !== undefined ? v : options.all !== undefined ? options.all : def;
const testAgainstGivenOption = item => {
if (typeof item === "string") {
const regExp = new RegExp(
`[\\\\/]${item.replace(
// eslint-disable-next-line no-useless-escape
/[-[\]{}()*+?.\\^$|]/g,
"\\$&"
)}([\\\\/]|$|!|\\?)`
);
return ident => regExp.test(ident);
}
if (item && typeof item === "object" && typeof item.test === "function") {
return ident => item.test(ident);
}
if (typeof item === "function") {
return item;
}
if (typeof item === "boolean") {
return () => item;
}
};
const compilation = this.compilation;
const context = optionsOrFallback(
options.context,
compilation.compiler.context
);
const requestShortener =
compilation.compiler.context === context
? compilation.requestShortener
: new RequestShortener(context);
const showPerformance = optionOrLocalFallback(options.performance, true);
const showHash = optionOrLocalFallback(options.hash, true);
const showEnv = optionOrLocalFallback(options.env, false);
const showVersion = optionOrLocalFallback(options.version, true);
const showTimings = optionOrLocalFallback(options.timings, true);
const showBuiltAt = optionOrLocalFallback(options.builtAt, true);
const showAssets = optionOrLocalFallback(options.assets, true);
const showEntrypoints = optionOrLocalFallback(options.entrypoints, true);
const showChunkGroups = optionOrLocalFallback(
options.chunkGroups,
!forToString
);
const showChunks = optionOrLocalFallback(options.chunks, !forToString);
const showChunkModules = optionOrLocalFallback(options.chunkModules, true);
const showChunkOrigins = optionOrLocalFallback(
options.chunkOrigins,
!forToString
);
const showModules = optionOrLocalFallback(options.modules, true);
const showNestedModules = optionOrLocalFallback(
options.nestedModules,
true
);
const showModuleAssets = optionOrLocalFallback(
options.moduleAssets,
!forToString
);
const showDepth = optionOrLocalFallback(options.depth, !forToString);
const showCachedModules = optionOrLocalFallback(options.cached, true);
const showCachedAssets = optionOrLocalFallback(options.cachedAssets, true);
const showReasons = optionOrLocalFallback(options.reasons, !forToString);
const showUsedExports = optionOrLocalFallback(
options.usedExports,
!forToString
);
const showProvidedExports = optionOrLocalFallback(
options.providedExports,
!forToString
);
const showOptimizationBailout = optionOrLocalFallback(
options.optimizationBailout,
!forToString
);
const showChildren = optionOrLocalFallback(options.children, true);
const showSource = optionOrLocalFallback(options.source, !forToString);
const showModuleTrace = optionOrLocalFallback(options.moduleTrace, true);
const showErrors = optionOrLocalFallback(options.errors, true);
const showErrorDetails = optionOrLocalFallback(
options.errorDetails,
!forToString
);
const showWarnings = optionOrLocalFallback(options.warnings, true);
const warningsFilter = optionsOrFallback(options.warningsFilter, null);
const showPublicPath = optionOrLocalFallback(
options.publicPath,
!forToString
);
const excludeModules = []
.concat(optionsOrFallback(options.excludeModules, options.exclude, []))
.map(testAgainstGivenOption);
const excludeAssets = []
.concat(optionsOrFallback(options.excludeAssets, []))
.map(testAgainstGivenOption);
const maxModules = optionsOrFallback(
options.maxModules,
forToString ? 15 : Infinity
);
const sortModules = optionsOrFallback(options.modulesSort, "id");
const sortChunks = optionsOrFallback(options.chunksSort, "id");
const sortAssets = optionsOrFallback(options.assetsSort, "");
const showOutputPath = optionOrLocalFallback(
options.outputPath,
!forToString
);
if (!showCachedModules) {
excludeModules.push((ident, module) => !module.built);
}
const createModuleFilter = () => {
let i = 0;
return module => {
if (excludeModules.length > 0) {
const ident = requestShortener.shorten(module.resource);
const excluded = excludeModules.some(fn => fn(ident, module));
if (excluded) return false;
}
const result = i < maxModules;
i++;
return result;
};
};
const createAssetFilter = () => {
return asset => {
if (excludeAssets.length > 0) {
const ident = asset.name;
const excluded = excludeAssets.some(fn => fn(ident, asset));
if (excluded) return false;
}
return showCachedAssets || asset.emitted;
};
};
const sortByFieldAndOrder = (fieldKey, a, b) => {
if (a[fieldKey] === null && b[fieldKey] === null) return 0;
if (a[fieldKey] === null) return 1;
if (b[fieldKey] === null) return -1;
if (a[fieldKey] === b[fieldKey]) return 0;
if (typeof a[fieldKey] !== typeof b[fieldKey])
return typeof a[fieldKey] < typeof b[fieldKey] ? -1 : 1;
return a[fieldKey] < b[fieldKey] ? -1 : 1;
};
const sortByField = (field, originalArray) => {
const originalMap = originalArray.reduce((map, v, i) => {
map.set(v, i);
return map;
}, new Map());
return (a, b) => {
if (field) {
const fieldKey = this.normalizeFieldKey(field);
// if a field is prefixed with a "!" the sort is reversed!
const sortIsRegular = this.sortOrderRegular(field);
const cmp = sortByFieldAndOrder(
fieldKey,
sortIsRegular ? a : b,
sortIsRegular ? b : a
);
if (cmp) return cmp;
}
return originalMap.get(a) - originalMap.get(b);
};
};
const formatError = e => {
let text = "";
if (typeof e === "string") {
e = { message: e };
}
if (e.chunk) {
text += `chunk ${e.chunk.name || e.chunk.id}${
e.chunk.hasRuntime()
? " [entry]"
: e.chunk.canBeInitial()
? " [initial]"
: ""
}\n`;
}
if (e.file) {
text += `${e.file}\n`;
}
if (
e.module &&
e.module.readableIdentifier &&
typeof e.module.readableIdentifier === "function"
) {
text += this.formatFilePath(
e.module.readableIdentifier(requestShortener)
);
if (typeof e.loc === "object") {
const locInfo = formatLocation(e.loc);
if (locInfo) text += ` ${locInfo}`;
}
text += "\n";
}
text += e.message;
if (showErrorDetails && e.details) {
text += `\n${e.details}`;
}
if (showErrorDetails && e.missing) {
text += e.missing.map(item => `\n[${item}]`).join("");
}
if (showModuleTrace && e.origin) {
text += `\n @ ${this.formatFilePath(
e.origin.readableIdentifier(requestShortener)
)}`;
if (typeof e.originLoc === "object") {
const locInfo = formatLocation(e.originLoc);
if (locInfo) text += ` ${locInfo}`;
}
if (e.dependencies) {
for (const dep of e.dependencies) {
if (!dep.loc) continue;
if (typeof dep.loc === "string") continue;
const locInfo = formatLocation(dep.loc);
if (!locInfo) continue;
text += ` ${locInfo}`;
}
}
let current = e.origin;
while (current.issuer) {
current = current.issuer;
text += `\n @ ${current.readableIdentifier(requestShortener)}`;
}
}
return text;
};
const obj = {
errors: compilation.errors.map(formatError),
warnings: Stats.filterWarnings(
compilation.warnings.map(formatError),
warningsFilter
)
};
//We just hint other renderers since actually omitting
//errors/warnings from the JSON would be kind of weird.
Object.defineProperty(obj, "_showWarnings", {
value: showWarnings,
enumerable: false
});
Object.defineProperty(obj, "_showErrors", {
value: showErrors,
enumerable: false
});
if (showVersion) {
obj.version = require("../package.json").version;
}
if (showHash) obj.hash = this.hash;
if (showTimings && this.startTime && this.endTime) {
obj.time = this.endTime - this.startTime;
}
if (showBuiltAt && this.endTime) {
obj.builtAt = this.endTime;
}
if (showEnv && options._env) {
obj.env = options._env;
}
if (compilation.needAdditionalPass) {
obj.needAdditionalPass = true;
}
if (showPublicPath) {
obj.publicPath = this.compilation.mainTemplate.getPublicPath({
hash: this.compilation.hash
});
}
if (showOutputPath) {
obj.outputPath = this.compilation.mainTemplate.outputOptions.path;
}
if (showAssets) {
const assetsByFile = {};
const compilationAssets = Object.keys(compilation.assets).sort();
obj.assetsByChunkName = {};
obj.assets = compilationAssets
.map(asset => {
const obj = {
name: asset,
size: compilation.assets[asset].size(),
chunks: [],
chunkNames: [],
// TODO webpack 5: remove .emitted
emitted:
compilation.assets[asset].emitted ||
compilation.emittedAssets.has(asset)
};
if (showPerformance) {
obj.isOverSizeLimit = compilation.assets[asset].isOverSizeLimit;
}
assetsByFile[asset] = obj;
return obj;
})
.filter(createAssetFilter());
obj.filteredAssets = compilationAssets.length - obj.assets.length;
for (const chunk of compilation.chunks) {
for (const asset of chunk.files) {
if (assetsByFile[asset]) {
for (const id of chunk.ids) {
assetsByFile[asset].chunks.push(id);
}
if (chunk.name) {
assetsByFile[asset].chunkNames.push(chunk.name);
if (obj.assetsByChunkName[chunk.name]) {
obj.assetsByChunkName[chunk.name] = []
.concat(obj.assetsByChunkName[chunk.name])
.concat([asset]);
} else {
obj.assetsByChunkName[chunk.name] = asset;
}
}
}
}
}
obj.assets.sort(sortByField(sortAssets, obj.assets));
}
const fnChunkGroup = groupMap => {
const obj = {};
for (const keyValuePair of groupMap) {
const name = keyValuePair[0];
const cg = keyValuePair[1];
const children = cg.getChildrenByOrders();
obj[name] = {
chunks: cg.chunks.map(c => c.id),
assets: cg.chunks.reduce(
(array, c) => array.concat(c.files || []),
[]
),
children: Object.keys(children).reduce((obj, key) => {
const groups = children[key];
obj[key] = groups.map(group => ({
name: group.name,
chunks: group.chunks.map(c => c.id),
assets: group.chunks.reduce(
(array, c) => array.concat(c.files || []),
[]
)
}));
return obj;
}, Object.create(null)),
childAssets: Object.keys(children).reduce((obj, key) => {
const groups = children[key];
obj[key] = Array.from(
groups.reduce((set, group) => {
for (const chunk of group.chunks) {
for (const asset of chunk.files) {
set.add(asset);
}
}
return set;
}, new Set())
);
return obj;
}, Object.create(null))
};
if (showPerformance) {
obj[name].isOverSizeLimit = cg.isOverSizeLimit;
}
}
return obj;
};
if (showEntrypoints) {
obj.entrypoints = fnChunkGroup(compilation.entrypoints);
}
if (showChunkGroups) {
obj.namedChunkGroups = fnChunkGroup(compilation.namedChunkGroups);
}
const fnModule = module => {
const path = [];
let current = module;
while (current.issuer) {
path.push((current = current.issuer));
}
path.reverse();
const obj = {
id: module.id,
identifier: module.identifier(),
name: module.readableIdentifier(requestShortener),
index: module.index,
index2: module.index2,
size: module.size(),
cacheable: module.buildInfo.cacheable,
built: !!module.built,
optional: module.optional,
prefetched: module.prefetched,
chunks: Array.from(module.chunksIterable, chunk => chunk.id),
issuer: module.issuer && module.issuer.identifier(),
issuerId: module.issuer && module.issuer.id,
issuerName:
module.issuer && module.issuer.readableIdentifier(requestShortener),
issuerPath:
module.issuer &&
path.map(module => ({
id: module.id,
identifier: module.identifier(),
name: module.readableIdentifier(requestShortener),
profile: module.profile
})),
profile: module.profile,
failed: !!module.error,
errors: module.errors ? module.errors.length : 0,
warnings: module.warnings ? module.warnings.length : 0
};
if (showModuleAssets) {
obj.assets = Object.keys(module.buildInfo.assets || {});
}
if (showReasons) {
obj.reasons = module.reasons
.sort((a, b) => {
if (a.module && !b.module) return -1;
if (!a.module && b.module) return 1;
if (a.module && b.module) {
const cmp = compareId(a.module.id, b.module.id);
if (cmp) return cmp;
}
if (a.dependency && !b.dependency) return -1;
if (!a.dependency && b.dependency) return 1;
if (a.dependency && b.dependency) {
const cmp = compareLocations(a.dependency.loc, b.dependency.loc);
if (cmp) return cmp;
if (a.dependency.type < b.dependency.type) return -1;
if (a.dependency.type > b.dependency.type) return 1;
}
return 0;
})
.map(reason => {
const obj = {
moduleId: reason.module ? reason.module.id : null,
moduleIdentifier: reason.module
? reason.module.identifier()
: null,
module: reason.module
? reason.module.readableIdentifier(requestShortener)
: null,
moduleName: reason.module
? reason.module.readableIdentifier(requestShortener)
: null,
type: reason.dependency ? reason.dependency.type : null,
explanation: reason.explanation,
userRequest: reason.dependency
? reason.dependency.userRequest
: null
};
if (reason.dependency) {
const locInfo = formatLocation(reason.dependency.loc);
if (locInfo) {
obj.loc = locInfo;
}
}
return obj;
});
}
if (showUsedExports) {
if (module.used === true) {
obj.usedExports = module.usedExports;
} else if (module.used === false) {
obj.usedExports = false;
}
}
if (showProvidedExports) {
obj.providedExports = Array.isArray(module.buildMeta.providedExports)
? module.buildMeta.providedExports
: null;
}
if (showOptimizationBailout) {
obj.optimizationBailout = module.optimizationBailout.map(item => {
if (typeof item === "function") return item(requestShortener);
return item;
});
}
if (showDepth) {
obj.depth = module.depth;
}
if (showNestedModules) {
if (module.modules) {
const modules = module.modules;
obj.modules = modules
.sort(sortByField("depth", modules))
.filter(createModuleFilter())
.map(fnModule);
obj.filteredModules = modules.length - obj.modules.length;
obj.modules.sort(sortByField(sortModules, obj.modules));
}
}
if (showSource && module._source) {
obj.source = module._source.source();
}
return obj;
};
if (showChunks) {
obj.chunks = compilation.chunks.map(chunk => {
const parents = new Set();
const children = new Set();
const siblings = new Set();
const childIdByOrder = chunk.getChildIdsByOrders();
for (const chunkGroup of chunk.groupsIterable) {
for (const parentGroup of chunkGroup.parentsIterable) {
for (const chunk of parentGroup.chunks) {
parents.add(chunk.id);
}
}
for (const childGroup of chunkGroup.childrenIterable) {
for (const chunk of childGroup.chunks) {
children.add(chunk.id);
}
}
for (const sibling of chunkGroup.chunks) {
if (sibling !== chunk) siblings.add(sibling.id);
}
}
const obj = {
id: chunk.id,
rendered: chunk.rendered,
initial: chunk.canBeInitial(),
entry: chunk.hasRuntime(),
recorded: chunk.recorded,
reason: chunk.chunkReason,
size: chunk.modulesSize(),
names: chunk.name ? [chunk.name] : [],
files: chunk.files.slice(),
hash: chunk.renderedHash,
siblings: Array.from(siblings).sort(compareId),
parents: Array.from(parents).sort(compareId),
children: Array.from(children).sort(compareId),
childrenByOrder: childIdByOrder
};
if (showChunkModules) {
const modules = chunk.getModules();
obj.modules = modules
.slice()
.sort(sortByField("depth", modules))
.filter(createModuleFilter())
.map(fnModule);
obj.filteredModules = chunk.getNumberOfModules() - obj.modules.length;
obj.modules.sort(sortByField(sortModules, obj.modules));
}
if (showChunkOrigins) {
obj.origins = Array.from(chunk.groupsIterable, g => g.origins)
.reduce((a, b) => a.concat(b), [])
.map(origin => ({
moduleId: origin.module ? origin.module.id : undefined,
module: origin.module ? origin.module.identifier() : "",
moduleIdentifier: origin.module ? origin.module.identifier() : "",
moduleName: origin.module
? origin.module.readableIdentifier(requestShortener)
: "",
loc: formatLocation(origin.loc),
request: origin.request,
reasons: origin.reasons || []
}))
.sort((a, b) => {
const cmp1 = compareId(a.moduleId, b.moduleId);
if (cmp1) return cmp1;
const cmp2 = compareId(a.loc, b.loc);
if (cmp2) return cmp2;
const cmp3 = compareId(a.request, b.request);
if (cmp3) return cmp3;
return 0;
});
}
return obj;
});
obj.chunks.sort(sortByField(sortChunks, obj.chunks));
}
if (showModules) {
obj.modules = compilation.modules
.slice()
.sort(sortByField("depth", compilation.modules))
.filter(createModuleFilter())
.map(fnModule);
obj.filteredModules = compilation.modules.length - obj.modules.length;
obj.modules.sort(sortByField(sortModules, obj.modules));
}
if (showChildren) {
obj.children = compilation.children.map((child, idx) => {
const childOptions = Stats.getChildOptions(options, idx);
const obj = new Stats(child).toJson(childOptions, forToString);
delete obj.hash;
delete obj.version;
if (child.name) {
obj.name = identifierUtils.makePathsRelative(
context,
child.name,
compilation.cache
);
}
return obj;
});
}
return obj;
}
toString(options) {
if (typeof options === "boolean" || typeof options === "string") {
options = Stats.presetToOptions(options);
} else if (!options) {
options = {};
}
const useColors = optionsOrFallback(options.colors, false);
const obj = this.toJson(options, true);
return Stats.jsonToString(obj, useColors);
}
static jsonToString(obj, useColors) {
const buf = [];
const defaultColors = {
bold: "\u001b[1m",
yellow: "\u001b[1m\u001b[33m",
red: "\u001b[1m\u001b[31m",
green: "\u001b[1m\u001b[32m",
cyan: "\u001b[1m\u001b[36m",
magenta: "\u001b[1m\u001b[35m"
};
const colors = Object.keys(defaultColors).reduce(
(obj, color) => {
obj[color] = str => {
if (useColors) {
buf.push(
useColors === true || useColors[color] === undefined
? defaultColors[color]
: useColors[color]
);
}
buf.push(str);
if (useColors) {
buf.push("\u001b[39m\u001b[22m");
}
};
return obj;
},
{
normal: str => buf.push(str)
}
);
const coloredTime = time => {
let times = [800, 400, 200, 100];
if (obj.time) {
times = [obj.time / 2, obj.time / 4, obj.time / 8, obj.time / 16];
}
if (time < times[3]) colors.normal(`${time}ms`);
else if (time < times[2]) colors.bold(`${time}ms`);
else if (time < times[1]) colors.green(`${time}ms`);
else if (time < times[0]) colors.yellow(`${time}ms`);
else colors.red(`${time}ms`);
};
const newline = () => buf.push("\n");
const getText = (arr, row, col) => {
return arr[row][col].value;
};
const table = (array, align, splitter) => {
const rows = array.length;
const cols = array[0].length;
const colSizes = new Array(cols);
for (let col = 0; col < cols; col++) {
colSizes[col] = 0;
}
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) {
const value = `${getText(array, row, col)}`;
if (value.length > colSizes[col]) {
colSizes[col] = value.length;
}
}
}
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) {
const format = array[row][col].color;
const value = `${getText(array, row, col)}`;
let l = value.length;
if (align[col] === "l") {
format(value);
}
for (; l < colSizes[col] && col !== cols - 1; l++) {
colors.normal(" ");
}
if (align[col] === "r") {
format(value);
}
if (col + 1 < cols && colSizes[col] !== 0) {
colors.normal(splitter || " ");
}
}
newline();
}
};
const getAssetColor = (asset, defaultColor) => {
if (asset.isOverSizeLimit) {
return colors.yellow;
}
return defaultColor;
};
if (obj.hash) {
colors.normal("Hash: ");
colors.bold(obj.hash);
newline();
}
if (obj.version) {
colors.normal("Version: webpack ");
colors.bold(obj.version);
newline();
}
if (typeof obj.time === "number") {
colors.normal("Time: ");
colors.bold(obj.time);
colors.normal("ms");
newline();
}
if (typeof obj.builtAt === "number") {
const builtAtDate = new Date(obj.builtAt);
colors.normal("Built at: ");
colors.normal(
builtAtDate.toLocaleDateString(undefined, {
day: "2-digit",
month: "2-digit",
year: "numeric"
})
);
colors.normal(" ");
colors.bold(builtAtDate.toLocaleTimeString());
newline();
}
if (obj.env) {
colors.normal("Environment (--env): ");
colors.bold(JSON.stringify(obj.env, null, 2));
newline();
}
if (obj.publicPath) {
colors.normal("PublicPath: ");
colors.bold(obj.publicPath);
newline();
}
if (obj.assets && obj.assets.length > 0) {
const t = [
[
{
value: "Asset",
color: colors.bold
},
{
value: "Size",
color: colors.bold
},
{
value: "Chunks",
color: colors.bold
},
{
value: "",
color: colors.bold
},
{
value: "",
color: colors.bold
},
{
value: "Chunk Names",
color: colors.bold
}
]
];
for (const asset of obj.assets) {
t.push([
{
value: asset.name,
color: getAssetColor(asset, colors.green)
},
{
value: SizeFormatHelpers.formatSize(asset.size),
color: getAssetColor(asset, colors.normal)
},
{
value: asset.chunks.join(", "),
color: colors.bold
},
{
value: asset.emitted ? "[emitted]" : "",
color: colors.green
},
{
value: asset.isOverSizeLimit ? "[big]" : "",
color: getAssetColor(asset, colors.normal)
},
{
value: asset.chunkNames.join(", "),
color: colors.normal
}
]);
}
table(t, "rrrlll");
}
if (obj.filteredAssets > 0) {
colors.normal(" ");
if (obj.assets.length > 0) colors.normal("+ ");
colors.normal(obj.filteredAssets);
if (obj.assets.length > 0) colors.normal(" hidden");
colors.normal(obj.filteredAssets !== 1 ? " assets" : " asset");
newline();
}
const processChunkGroups = (namedGroups, prefix) => {
for (const name of Object.keys(namedGroups)) {
const cg = namedGroups[name];
colors.normal(`${prefix} `);
colors.bold(name);
if (cg.isOverSizeLimit) {
colors.normal(" ");
colors.yellow("[big]");
}
colors.normal(" =");
for (const asset of cg.assets) {
colors.normal(" ");
colors.green(asset);
}
for (const name of Object.keys(cg.childAssets)) {
const assets = cg.childAssets[name];
if (assets && assets.length > 0) {
colors.normal(" ");
colors.magenta(`(${name}:`);
for (const asset of assets) {
colors.normal(" ");
colors.green(asset);
}
colors.magenta(")");
}
}
newline();
}
};
if (obj.entrypoints) {
processChunkGroups(obj.entrypoints, "Entrypoint");
}
if (obj.namedChunkGroups) {
let outputChunkGroups = obj.namedChunkGroups;
if (obj.entrypoints) {
outputChunkGroups = Object.keys(outputChunkGroups)
.filter(name => !obj.entrypoints[name])
.reduce((result, name) => {
result[name] = obj.namedChunkGroups[name];
return result;
}, {});
}
processChunkGroups(outputChunkGroups, "Chunk Group");
}
const modulesByIdentifier = {};
if (obj.modules) {
for (const module of obj.modules) {
modulesByIdentifier[`$${module.identifier}`] = module;
}
} else if (obj.chunks) {
for (const chunk of obj.chunks) {
if (chunk.modules) {
for (const module of chunk.modules) {
modulesByIdentifier[`$${module.identifier}`] = module;
}
}
}
}
const processModuleAttributes = module => {
colors.normal(" ");
colors.normal(SizeFormatHelpers.formatSize(module.size));
if (module.chunks) {
for (const chunk of module.chunks) {
colors.normal(" {");
colors.yellow(chunk);
colors.normal("}");
}
}
if (typeof module.depth === "number") {
colors.normal(` [depth ${module.depth}]`);
}
if (module.cacheable === false) {
colors.red(" [not cacheable]");
}
if (module.optional) {
colors.yellow(" [optional]");
}
if (module.built) {
colors.green(" [built]");
}
if (module.assets && module.assets.length) {
colors.magenta(
` [${module.assets.length} asset${
module.assets.length === 1 ? "" : "s"
}]`
);
}
if (module.prefetched) {
colors.magenta(" [prefetched]");
}
if (module.failed) colors.red(" [failed]");
if (module.warnings) {
colors.yellow(
` [${module.warnings} warning${module.warnings === 1 ? "" : "s"}]`
);
}
if (module.errors) {
colors.red(
` [${module.errors} error${module.errors === 1 ? "" : "s"}]`
);
}
};
const processModuleContent = (module, prefix) => {
if (Array.isArray(module.providedExports)) {
colors.normal(prefix);
if (module.providedExports.length === 0) {
colors.cyan("[no exports]");
} else {
colors.cyan(`[exports: ${module.providedExports.join(", ")}]`);
}
newline();
}
if (module.usedExports !== undefined) {
if (module.usedExports !== true) {
colors.normal(prefix);
if (module.usedExports === null) {
colors.cyan("[used exports unknown]");
} else if (module.usedExports === false) {
colors.cyan("[no exports used]");
} else if (
Array.isArray(module.usedExports) &&
module.usedExports.length === 0
) {
colors.cyan("[no exports used]");
} else if (Array.isArray(module.usedExports)) {
const providedExportsCount = Array.isArray(module.providedExports)
? module.providedExports.length
: null;
if (
providedExportsCount !== null &&
providedExportsCount === module.usedExports.length
) {
colors.cyan("[all exports used]");
} else {
colors.cyan(
`[only some exports used: ${module.usedExports.join(", ")}]`
);
}
}
newline();
}
}
if (Array.isArray(module.optimizationBailout)) {
for (const item of module.optimizationBailout) {
colors.normal(prefix);
colors.yellow(item);
newline();
}
}
if (module.reasons) {
for (const reason of module.reasons) {
colors.normal(prefix);
if (reason.type) {
colors.normal(reason.type);
colors.normal(" ");
}
if (reason.userRequest) {
colors.cyan(reason.userRequest);
colors.normal(" ");
}
if (reason.moduleId !== null) {
colors.normal("[");
colors.normal(reason.moduleId);
colors.normal("]");
}
if (reason.module && reason.module !== reason.moduleId) {
colors.normal(" ");
colors.magenta(reason.module);
}
if (reason.loc) {
colors.normal(" ");
colors.normal(reason.loc);
}
if (reason.explanation) {
colors.normal(" ");
colors.cyan(reason.explanation);
}
newline();
}
}
if (module.profile) {
colors.normal(prefix);
let sum = 0;
if (module.issuerPath) {
for (const m of module.issuerPath) {
colors.normal("[");
colors.normal(m.id);
colors.normal("] ");
if (m.profile) {
const time = (m.profile.factory || 0) + (m.profile.building || 0);
coloredTime(time);
sum += time;
colors.normal(" ");
}
colors.normal("-> ");
}
}
for (const key of Object.keys(module.profile)) {
colors.normal(`${key}:`);
const time = module.profile[key];
coloredTime(time);
colors.normal(" ");
sum += time;
}
colors.normal("= ");
coloredTime(sum);
newline();
}
if (module.modules) {
processModulesList(module, prefix + "| ");
}
};
const processModulesList = (obj, prefix) => {
if (obj.modules) {
let maxModuleId = 0;
for (const module of obj.modules) {
if (typeof module.id === "number") {
if (maxModuleId < module.id) maxModuleId = module.id;
}
}
let contentPrefix = prefix + " ";
if (maxModuleId >= 10) contentPrefix += " ";
if (maxModuleId >= 100) contentPrefix += " ";
if (maxModuleId >= 1000) contentPrefix += " ";
for (const module of obj.modules) {
colors.normal(prefix);
const name = module.name || module.identifier;
if (typeof module.id === "string" || typeof module.id === "number") {
if (typeof module.id === "number") {
if (module.id < 1000 && maxModuleId >= 1000) colors.normal(" ");
if (module.id < 100 && maxModuleId >= 100) colors.normal(" ");
if (module.id < 10 && maxModuleId >= 10) colors.normal(" ");
} else {
if (maxModuleId >= 1000) colors.normal(" ");
if (maxModuleId >= 100) colors.normal(" ");
if (maxModuleId >= 10) colors.normal(" ");
}
if (name !== module.id) {
colors.normal("[");
colors.normal(module.id);
colors.normal("]");
colors.normal(" ");
} else {
colors.normal("[");
colors.bold(module.id);
colors.normal("]");
}
}
if (name !== module.id) {
colors.bold(name);
}
processModuleAttributes(module);
newline();
processModuleContent(module, contentPrefix);
}
if (obj.filteredModules > 0) {
colors.normal(prefix);
colors.normal(" ");
if (obj.modules.length > 0) colors.normal(" + ");
colors.normal(obj.filteredModules);
if (obj.modules.length > 0) colors.normal(" hidden");
colors.normal(obj.filteredModules !== 1 ? " modules" : " module");
newline();
}
}
};
if (obj.chunks) {
for (const chunk of obj.chunks) {
colors.normal("chunk ");
if (chunk.id < 1000) colors.normal(" ");
if (chunk.id < 100) colors.normal(" ");
if (chunk.id < 10) colors.normal(" ");
colors.normal("{");
colors.yellow(chunk.id);
colors.normal("} ");
colors.green(chunk.files.join(", "));
if (chunk.names && chunk.names.length > 0) {
colors.normal(" (");
colors.normal(chunk.names.join(", "));
colors.normal(")");
}
colors.normal(" ");
colors.normal(SizeFormatHelpers.formatSize(chunk.size));
for (const id of chunk.parents) {
colors.normal(" <{");
colors.yellow(id);
colors.normal("}>");
}
for (const id of chunk.siblings) {
colors.normal(" ={");
colors.yellow(id);
colors.normal("}=");
}
for (const id of chunk.children) {
colors.normal(" >{");
colors.yellow(id);
colors.normal("}<");
}
if (chunk.childrenByOrder) {
for (const name of Object.keys(chunk.childrenByOrder)) {
const children = chunk.childrenByOrder[name];
colors.normal(" ");
colors.magenta(`(${name}:`);
for (const id of children) {
colors.normal(" {");
colors.yellow(id);
colors.normal("}");
}
colors.magenta(")");
}
}
if (chunk.entry) {
colors.yellow(" [entry]");
} else if (chunk.initial) {
colors.yellow(" [initial]");
}
if (chunk.rendered) {
colors.green(" [rendered]");
}
if (chunk.recorded) {
colors.green(" [recorded]");
}
if (chunk.reason) {
colors.yellow(` ${chunk.reason}`);
}
newline();
if (chunk.origins) {
for (const origin of chunk.origins) {
colors.normal(" > ");
if (origin.reasons && origin.reasons.length) {
colors.yellow(origin.reasons.join(" "));
colors.normal(" ");
}
if (origin.request) {
colors.normal(origin.request);
colors.normal(" ");
}
if (origin.module) {
colors.normal("[");
colors.normal(origin.moduleId);
colors.normal("] ");
const module = modulesByIdentifier[`$${origin.module}`];
if (module) {
colors.bold(module.name);
colors.normal(" ");
}
}
if (origin.loc) {
colors.normal(origin.loc);
}
newline();
}
}
processModulesList(chunk, " ");
}
}
processModulesList(obj, "");
if (obj._showWarnings && obj.warnings) {
for (const warning of obj.warnings) {
newline();
colors.yellow(`WARNING in ${warning}`);
newline();
}
}
if (obj._showErrors && obj.errors) {
for (const error of obj.errors) {
newline();
colors.red(`ERROR in ${error}`);
newline();
}
}
if (obj.children) {
for (const child of obj.children) {
const childString = Stats.jsonToString(child, useColors);
if (childString) {
if (child.name) {
colors.normal("Child ");
colors.bold(child.name);
colors.normal(":");
} else {
colors.normal("Child");
}
newline();
buf.push(" ");
buf.push(childString.replace(/\n/g, "\n "));
newline();
}
}
}
if (obj.needAdditionalPass) {
colors.yellow(
"Compilation needs an additional pass and will compile again."
);
}
while (buf[buf.length - 1] === "\n") {
buf.pop();
}
return buf.join("");
}
static presetToOptions(name) {
// Accepted values: none, errors-only, minimal, normal, detailed, verbose
// Any other falsy value will behave as 'none', truthy values as 'normal'
const pn =
(typeof name === "string" && name.toLowerCase()) || name || "none";
switch (pn) {
case "none":
return {
all: false
};
case "verbose":
return {
entrypoints: true,
chunkGroups: true,
modules: false,
chunks: true,
chunkModules: true,
chunkOrigins: true,
depth: true,
env: true,
reasons: true,
usedExports: true,
providedExports: true,
optimizationBailout: true,
errorDetails: true,
publicPath: true,
exclude: false,
maxModules: Infinity
};
case "detailed":
return {
entrypoints: true,
chunkGroups: true,
chunks: true,
chunkModules: false,
chunkOrigins: true,
depth: true,
usedExports: true,
providedExports: true,
optimizationBailout: true,
errorDetails: true,
publicPath: true,
exclude: false,
maxModules: Infinity
};
case "minimal":
return {
all: false,
modules: true,
maxModules: 0,
errors: true,
warnings: true
};
case "errors-only":
return {
all: false,
errors: true,
moduleTrace: true
};
case "errors-warnings":
return {
all: false,
errors: true,
warnings: true
};
default:
return {};
}
}
static getChildOptions(options, idx) {
let innerOptions;
if (Array.isArray(options.children)) {
if (idx < options.children.length) {
innerOptions = options.children[idx];
}
} else if (typeof options.children === "object" && options.children) {
innerOptions = options.children;
}
if (typeof innerOptions === "boolean" || typeof innerOptions === "string") {
innerOptions = Stats.presetToOptions(innerOptions);
}
if (!innerOptions) {
return options;
}
const childOptions = Object.assign({}, options);
delete childOptions.children; // do not inherit children
return Object.assign(childOptions, innerOptions);
}
}
module.exports = Stats;
| lib/Stats.js | /*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const RequestShortener = require("./RequestShortener");
const SizeFormatHelpers = require("./SizeFormatHelpers");
const formatLocation = require("./formatLocation");
const identifierUtils = require("./util/identifier");
const compareLocations = require("./compareLocations");
const optionsOrFallback = (...args) => {
let optionValues = [];
optionValues.push(...args);
return optionValues.find(optionValue => optionValue !== undefined);
};
const compareId = (a, b) => {
if (typeof a !== typeof b) {
return typeof a < typeof b ? -1 : 1;
}
if (a < b) return -1;
if (a > b) return 1;
return 0;
};
class Stats {
constructor(compilation) {
this.compilation = compilation;
this.hash = compilation.hash;
this.startTime = undefined;
this.endTime = undefined;
}
static filterWarnings(warnings, warningsFilter) {
// we dont have anything to filter so all warnings can be shown
if (!warningsFilter) {
return warnings;
}
// create a chain of filters
// if they return "true" a warning should be suppressed
const normalizedWarningsFilters = [].concat(warningsFilter).map(filter => {
if (typeof filter === "string") {
return warning => warning.includes(filter);
}
if (filter instanceof RegExp) {
return warning => filter.test(warning);
}
if (typeof filter === "function") {
return filter;
}
throw new Error(
`Can only filter warnings with Strings or RegExps. (Given: ${filter})`
);
});
return warnings.filter(warning => {
return !normalizedWarningsFilters.some(check => check(warning));
});
}
formatFilePath(filePath) {
const OPTIONS_REGEXP = /^(\s|\S)*!/;
return filePath.includes("!")
? `${filePath.replace(OPTIONS_REGEXP, "")} (${filePath})`
: `${filePath}`;
}
hasWarnings() {
return (
this.compilation.warnings.length > 0 ||
this.compilation.children.some(child => child.getStats().hasWarnings())
);
}
hasErrors() {
return (
this.compilation.errors.length > 0 ||
this.compilation.children.some(child => child.getStats().hasErrors())
);
}
// remove a prefixed "!" that can be specified to reverse sort order
normalizeFieldKey(field) {
if (field[0] === "!") {
return field.substr(1);
}
return field;
}
// if a field is prefixed by a "!" reverse sort order
sortOrderRegular(field) {
if (field[0] === "!") {
return false;
}
return true;
}
toJson(options, forToString) {
if (typeof options === "boolean" || typeof options === "string") {
options = Stats.presetToOptions(options);
} else if (!options) {
options = {};
}
const optionOrLocalFallback = (v, def) =>
v !== undefined ? v : options.all !== undefined ? options.all : def;
const testAgainstGivenOption = item => {
if (typeof item === "string") {
const regExp = new RegExp(
`[\\\\/]${item.replace(
// eslint-disable-next-line no-useless-escape
/[-[\]{}()*+?.\\^$|]/g,
"\\$&"
)}([\\\\/]|$|!|\\?)`
);
return ident => regExp.test(ident);
}
if (item && typeof item === "object" && typeof item.test === "function") {
return ident => item.test(ident);
}
if (typeof item === "function") {
return item;
}
if (typeof item === "boolean") {
return () => item;
}
};
const compilation = this.compilation;
const context = optionsOrFallback(
options.context,
compilation.compiler.context
);
const requestShortener =
compilation.compiler.context === context
? compilation.requestShortener
: new RequestShortener(context);
const showPerformance = optionOrLocalFallback(options.performance, true);
const showHash = optionOrLocalFallback(options.hash, true);
const showEnv = optionOrLocalFallback(options.env, false);
const showVersion = optionOrLocalFallback(options.version, true);
const showTimings = optionOrLocalFallback(options.timings, true);
const showBuiltAt = optionOrLocalFallback(options.builtAt, true);
const showAssets = optionOrLocalFallback(options.assets, true);
const showEntrypoints = optionOrLocalFallback(options.entrypoints, true);
const showChunkGroups = optionOrLocalFallback(
options.chunkGroups,
!forToString
);
const showChunks = optionOrLocalFallback(options.chunks, !forToString);
const showChunkModules = optionOrLocalFallback(options.chunkModules, true);
const showChunkOrigins = optionOrLocalFallback(
options.chunkOrigins,
!forToString
);
const showModules = optionOrLocalFallback(options.modules, true);
const showNestedModules = optionOrLocalFallback(
options.nestedModules,
true
);
const showModuleAssets = optionOrLocalFallback(
options.moduleAssets,
!forToString
);
const showDepth = optionOrLocalFallback(options.depth, !forToString);
const showCachedModules = optionOrLocalFallback(options.cached, true);
const showCachedAssets = optionOrLocalFallback(options.cachedAssets, true);
const showReasons = optionOrLocalFallback(options.reasons, !forToString);
const showUsedExports = optionOrLocalFallback(
options.usedExports,
!forToString
);
const showProvidedExports = optionOrLocalFallback(
options.providedExports,
!forToString
);
const showOptimizationBailout = optionOrLocalFallback(
options.optimizationBailout,
!forToString
);
const showChildren = optionOrLocalFallback(options.children, true);
const showSource = optionOrLocalFallback(options.source, !forToString);
const showModuleTrace = optionOrLocalFallback(options.moduleTrace, true);
const showErrors = optionOrLocalFallback(options.errors, true);
const showErrorDetails = optionOrLocalFallback(
options.errorDetails,
!forToString
);
const showWarnings = optionOrLocalFallback(options.warnings, true);
const warningsFilter = optionsOrFallback(options.warningsFilter, null);
const showPublicPath = optionOrLocalFallback(
options.publicPath,
!forToString
);
const excludeModules = []
.concat(optionsOrFallback(options.excludeModules, options.exclude, []))
.map(testAgainstGivenOption);
const excludeAssets = []
.concat(optionsOrFallback(options.excludeAssets, []))
.map(testAgainstGivenOption);
const maxModules = optionsOrFallback(
options.maxModules,
forToString ? 15 : Infinity
);
const sortModules = optionsOrFallback(options.modulesSort, "id");
const sortChunks = optionsOrFallback(options.chunksSort, "id");
const sortAssets = optionsOrFallback(options.assetsSort, "");
const showOutputPath = optionOrLocalFallback(
options.outputPath,
!forToString
);
if (!showCachedModules) {
excludeModules.push((ident, module) => !module.built);
}
const createModuleFilter = () => {
let i = 0;
return module => {
if (excludeModules.length > 0) {
const ident = requestShortener.shorten(module.resource);
const excluded = excludeModules.some(fn => fn(ident, module));
if (excluded) return false;
}
const result = i < maxModules;
i++;
return result;
};
};
const createAssetFilter = () => {
return asset => {
if (excludeAssets.length > 0) {
const ident = asset.name;
const excluded = excludeAssets.some(fn => fn(ident, asset));
if (excluded) return false;
}
return showCachedAssets || asset.emitted;
};
};
const sortByFieldAndOrder = (fieldKey, a, b) => {
if (a[fieldKey] === null && b[fieldKey] === null) return 0;
if (a[fieldKey] === null) return 1;
if (b[fieldKey] === null) return -1;
if (a[fieldKey] === b[fieldKey]) return 0;
if (typeof a[fieldKey] !== typeof b[fieldKey])
return typeof a[fieldKey] < typeof b[fieldKey] ? -1 : 1;
return a[fieldKey] < b[fieldKey] ? -1 : 1;
};
const sortByField = (field, originalArray) => {
const originalMap = originalArray.reduce((map, v, i) => {
map.set(v, i);
return map;
}, new Map());
return (a, b) => {
if (field) {
const fieldKey = this.normalizeFieldKey(field);
// if a field is prefixed with a "!" the sort is reversed!
const sortIsRegular = this.sortOrderRegular(field);
const cmp = sortByFieldAndOrder(
fieldKey,
sortIsRegular ? a : b,
sortIsRegular ? b : a
);
if (cmp) return cmp;
}
return originalMap.get(a) - originalMap.get(b);
};
};
const formatError = e => {
let text = "";
if (typeof e === "string") {
e = { message: e };
}
if (e.chunk) {
text += `chunk ${e.chunk.name || e.chunk.id}${
e.chunk.hasRuntime()
? " [entry]"
: e.chunk.canBeInitial()
? " [initial]"
: ""
}\n`;
}
if (e.file) {
text += `${e.file}\n`;
}
if (
e.module &&
e.module.readableIdentifier &&
typeof e.module.readableIdentifier === "function"
) {
text += this.formatFilePath(
e.module.readableIdentifier(requestShortener)
);
if (typeof e.loc === "object") {
const locInfo = formatLocation(e.loc);
if (locInfo) text += ` ${locInfo}`;
}
text += "\n";
}
text += e.message;
if (showErrorDetails && e.details) {
text += `\n${e.details}`;
}
if (showErrorDetails && e.missing) {
text += e.missing.map(item => `\n[${item}]`).join("");
}
if (showModuleTrace && e.origin) {
text += `\n @ ${this.formatFilePath(
e.origin.readableIdentifier(requestShortener)
)}`;
if (typeof e.originLoc === "object") {
const locInfo = formatLocation(e.originLoc);
if (locInfo) text += ` ${locInfo}`;
}
if (e.dependencies) {
for (const dep of e.dependencies) {
if (!dep.loc) continue;
if (typeof dep.loc === "string") continue;
const locInfo = formatLocation(dep.loc);
if (!locInfo) continue;
text += ` ${locInfo}`;
}
}
let current = e.origin;
while (current.issuer) {
current = current.issuer;
text += `\n @ ${current.readableIdentifier(requestShortener)}`;
}
}
return text;
};
const obj = {
errors: compilation.errors.map(formatError),
warnings: Stats.filterWarnings(
compilation.warnings.map(formatError),
warningsFilter
)
};
//We just hint other renderers since actually omitting
//errors/warnings from the JSON would be kind of weird.
Object.defineProperty(obj, "_showWarnings", {
value: showWarnings,
enumerable: false
});
Object.defineProperty(obj, "_showErrors", {
value: showErrors,
enumerable: false
});
if (showVersion) {
obj.version = require("../package.json").version;
}
if (showHash) obj.hash = this.hash;
if (showTimings && this.startTime && this.endTime) {
obj.time = this.endTime - this.startTime;
}
if (showBuiltAt && this.endTime) {
obj.builtAt = this.endTime;
}
if (showEnv && options._env) {
obj.env = options._env;
}
if (compilation.needAdditionalPass) {
obj.needAdditionalPass = true;
}
if (showPublicPath) {
obj.publicPath = this.compilation.mainTemplate.getPublicPath({
hash: this.compilation.hash
});
}
if (showOutputPath) {
obj.outputPath = this.compilation.mainTemplate.outputOptions.path;
}
if (showAssets) {
const assetsByFile = {};
const compilationAssets = Object.keys(compilation.assets).sort();
obj.assetsByChunkName = {};
obj.assets = compilationAssets
.map(asset => {
const obj = {
name: asset,
size: compilation.assets[asset].size(),
chunks: [],
chunkNames: [],
// TODO webpack 5: remove .emitted
emitted:
compilation.assets[asset].emitted ||
compilation.emittedAssets.has(asset)
};
if (showPerformance) {
obj.isOverSizeLimit = compilation.assets[asset].isOverSizeLimit;
}
assetsByFile[asset] = obj;
return obj;
})
.filter(createAssetFilter());
obj.filteredAssets = compilationAssets.length - obj.assets.length;
for (const chunk of compilation.chunks) {
for (const asset of chunk.files) {
if (assetsByFile[asset]) {
for (const id of chunk.ids) {
assetsByFile[asset].chunks.push(id);
}
if (chunk.name) {
assetsByFile[asset].chunkNames.push(chunk.name);
if (obj.assetsByChunkName[chunk.name]) {
obj.assetsByChunkName[chunk.name] = []
.concat(obj.assetsByChunkName[chunk.name])
.concat([asset]);
} else {
obj.assetsByChunkName[chunk.name] = asset;
}
}
}
}
}
obj.assets.sort(sortByField(sortAssets, obj.assets));
}
const fnChunkGroup = groupMap => {
const obj = {};
for (const keyValuePair of groupMap) {
const name = keyValuePair[0];
const cg = keyValuePair[1];
const children = cg.getChildrenByOrders();
obj[name] = {
chunks: cg.chunks.map(c => c.id),
assets: cg.chunks.reduce(
(array, c) => array.concat(c.files || []),
[]
),
children: Object.keys(children).reduce((obj, key) => {
const groups = children[key];
obj[key] = groups.map(group => ({
name: group.name,
chunks: group.chunks.map(c => c.id),
assets: group.chunks.reduce(
(array, c) => array.concat(c.files || []),
[]
)
}));
return obj;
}, Object.create(null)),
childAssets: Object.keys(children).reduce((obj, key) => {
const groups = children[key];
obj[key] = Array.from(
groups.reduce((set, group) => {
for (const chunk of group.chunks) {
for (const asset of chunk.files) {
set.add(asset);
}
}
return set;
}, new Set())
);
return obj;
}, Object.create(null))
};
if (showPerformance) {
obj[name].isOverSizeLimit = cg.isOverSizeLimit;
}
}
return obj;
};
if (showEntrypoints) {
obj.entrypoints = fnChunkGroup(compilation.entrypoints);
}
if (showChunkGroups) {
obj.namedChunkGroups = fnChunkGroup(compilation.namedChunkGroups);
}
const fnModule = module => {
const path = [];
let current = module;
while (current.issuer) {
path.push((current = current.issuer));
}
path.reverse();
const obj = {
id: module.id,
identifier: module.identifier(),
name: module.readableIdentifier(requestShortener),
index: module.index,
index2: module.index2,
size: module.size(),
cacheable: module.buildInfo.cacheable,
built: !!module.built,
optional: module.optional,
prefetched: module.prefetched,
chunks: Array.from(module.chunksIterable, chunk => chunk.id),
issuer: module.issuer && module.issuer.identifier(),
issuerId: module.issuer && module.issuer.id,
issuerName:
module.issuer && module.issuer.readableIdentifier(requestShortener),
issuerPath:
module.issuer &&
path.map(module => ({
id: module.id,
identifier: module.identifier(),
name: module.readableIdentifier(requestShortener),
profile: module.profile
})),
profile: module.profile,
failed: !!module.error,
errors: module.errors ? module.errors.length : 0,
warnings: module.warnings ? module.warnings.length : 0
};
if (showModuleAssets) {
obj.assets = Object.keys(module.buildInfo.assets || {});
}
if (showReasons) {
obj.reasons = module.reasons
.sort((a, b) => {
if (a.module && !b.module) return -1;
if (!a.module && b.module) return 1;
if (a.module && b.module) {
const cmp = compareId(a.module.id, b.module.id);
if (cmp) return cmp;
}
if (a.dependency && !b.dependency) return -1;
if (!a.dependency && b.dependency) return 1;
if (a.dependency && b.dependency) {
const cmp = compareLocations(a.dependency.loc, b.dependency.loc);
if (cmp) return cmp;
if (a.dependency.type < b.dependency.type) return -1;
if (a.dependency.type > b.dependency.type) return 1;
}
return 0;
})
.map(reason => {
const obj = {
moduleId: reason.module ? reason.module.id : null,
moduleIdentifier: reason.module
? reason.module.identifier()
: null,
module: reason.module
? reason.module.readableIdentifier(requestShortener)
: null,
moduleName: reason.module
? reason.module.readableIdentifier(requestShortener)
: null,
type: reason.dependency ? reason.dependency.type : null,
explanation: reason.explanation,
userRequest: reason.dependency
? reason.dependency.userRequest
: null
};
if (reason.dependency) {
const locInfo = formatLocation(reason.dependency.loc);
if (locInfo) {
obj.loc = locInfo;
}
}
return obj;
});
}
if (showUsedExports) {
if (module.used === true) {
obj.usedExports = module.usedExports;
} else if (module.used === false) {
obj.usedExports = false;
}
}
if (showProvidedExports) {
obj.providedExports = Array.isArray(module.buildMeta.providedExports)
? module.buildMeta.providedExports
: null;
}
if (showOptimizationBailout) {
obj.optimizationBailout = module.optimizationBailout.map(item => {
if (typeof item === "function") return item(requestShortener);
return item;
});
}
if (showDepth) {
obj.depth = module.depth;
}
if (showNestedModules) {
if (module.modules) {
const modules = module.modules;
obj.modules = modules
.sort(sortByField("depth", modules))
.filter(createModuleFilter())
.map(fnModule);
obj.filteredModules = modules.length - obj.modules.length;
obj.modules.sort(sortByField(sortModules, obj.modules));
}
}
if (showSource && module._source) {
obj.source = module._source.source();
}
return obj;
};
if (showChunks) {
obj.chunks = compilation.chunks.map(chunk => {
const parents = new Set();
const children = new Set();
const siblings = new Set();
const childIdByOrder = chunk.getChildIdsByOrders();
for (const chunkGroup of chunk.groupsIterable) {
for (const parentGroup of chunkGroup.parentsIterable) {
for (const chunk of parentGroup.chunks) {
parents.add(chunk.id);
}
}
for (const childGroup of chunkGroup.childrenIterable) {
for (const chunk of childGroup.chunks) {
children.add(chunk.id);
}
}
for (const sibling of chunkGroup.chunks) {
if (sibling !== chunk) siblings.add(sibling.id);
}
}
const obj = {
id: chunk.id,
rendered: chunk.rendered,
initial: chunk.canBeInitial(),
entry: chunk.hasRuntime(),
recorded: chunk.recorded,
reason: chunk.chunkReason,
size: chunk.modulesSize(),
names: chunk.name ? [chunk.name] : [],
files: chunk.files.slice(),
hash: chunk.renderedHash,
siblings: Array.from(siblings).sort(compareId),
parents: Array.from(parents).sort(compareId),
children: Array.from(children).sort(compareId),
childrenByOrder: childIdByOrder
};
if (showChunkModules) {
const modules = chunk.getModules();
obj.modules = modules
.slice()
.sort(sortByField("depth", modules))
.filter(createModuleFilter())
.map(fnModule);
obj.filteredModules = chunk.getNumberOfModules() - obj.modules.length;
obj.modules.sort(sortByField(sortModules, obj.modules));
}
if (showChunkOrigins) {
obj.origins = Array.from(chunk.groupsIterable, g => g.origins)
.reduce((a, b) => a.concat(b), [])
.map(origin => ({
moduleId: origin.module ? origin.module.id : undefined,
module: origin.module ? origin.module.identifier() : "",
moduleIdentifier: origin.module ? origin.module.identifier() : "",
moduleName: origin.module
? origin.module.readableIdentifier(requestShortener)
: "",
loc: formatLocation(origin.loc),
request: origin.request,
reasons: origin.reasons || []
}))
.sort((a, b) => {
const cmp1 = compareId(a.moduleId, b.moduleId);
if (cmp1) return cmp1;
const cmp2 = compareId(a.loc, b.loc);
if (cmp2) return cmp2;
const cmp3 = compareId(a.request, b.request);
if (cmp3) return cmp3;
return 0;
});
}
return obj;
});
obj.chunks.sort(sortByField(sortChunks, obj.chunks));
}
if (showModules) {
obj.modules = compilation.modules
.slice()
.sort(sortByField("depth", compilation.modules))
.filter(createModuleFilter())
.map(fnModule);
obj.filteredModules = compilation.modules.length - obj.modules.length;
obj.modules.sort(sortByField(sortModules, obj.modules));
}
if (showChildren) {
obj.children = compilation.children.map((child, idx) => {
const childOptions = Stats.getChildOptions(options, idx);
const obj = new Stats(child).toJson(childOptions, forToString);
delete obj.hash;
delete obj.version;
if (child.name) {
obj.name = identifierUtils.makePathsRelative(
context,
child.name,
compilation.cache
);
}
return obj;
});
}
return obj;
}
toString(options) {
if (typeof options === "boolean" || typeof options === "string") {
options = Stats.presetToOptions(options);
} else if (!options) {
options = {};
}
const useColors = optionsOrFallback(options.colors, false);
const obj = this.toJson(options, true);
return Stats.jsonToString(obj, useColors);
}
static jsonToString(obj, useColors) {
const buf = [];
const defaultColors = {
bold: "\u001b[1m",
yellow: "\u001b[1m\u001b[33m",
red: "\u001b[1m\u001b[31m",
green: "\u001b[1m\u001b[32m",
cyan: "\u001b[1m\u001b[36m",
magenta: "\u001b[1m\u001b[35m"
};
const colors = Object.keys(defaultColors).reduce(
(obj, color) => {
obj[color] = str => {
if (useColors) {
buf.push(
useColors === true || useColors[color] === undefined
? defaultColors[color]
: useColors[color]
);
}
buf.push(str);
if (useColors) {
buf.push("\u001b[39m\u001b[22m");
}
};
return obj;
},
{
normal: str => buf.push(str)
}
);
const coloredTime = time => {
let times = [800, 400, 200, 100];
if (obj.time) {
times = [obj.time / 2, obj.time / 4, obj.time / 8, obj.time / 16];
}
if (time < times[3]) colors.normal(`${time}ms`);
else if (time < times[2]) colors.bold(`${time}ms`);
else if (time < times[1]) colors.green(`${time}ms`);
else if (time < times[0]) colors.yellow(`${time}ms`);
else colors.red(`${time}ms`);
};
const newline = () => buf.push("\n");
const getText = (arr, row, col) => {
return arr[row][col].value;
};
const table = (array, align, splitter) => {
const rows = array.length;
const cols = array[0].length;
const colSizes = new Array(cols);
for (let col = 0; col < cols; col++) {
colSizes[col] = 0;
}
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) {
const value = `${getText(array, row, col)}`;
if (value.length > colSizes[col]) {
colSizes[col] = value.length;
}
}
}
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) {
const format = array[row][col].color;
const value = `${getText(array, row, col)}`;
let l = value.length;
if (align[col] === "l") {
format(value);
}
for (; l < colSizes[col] && col !== cols - 1; l++) {
colors.normal(" ");
}
if (align[col] === "r") {
format(value);
}
if (col + 1 < cols && colSizes[col] !== 0) {
colors.normal(splitter || " ");
}
}
newline();
}
};
const getAssetColor = (asset, defaultColor) => {
if (asset.isOverSizeLimit) {
return colors.yellow;
}
return defaultColor;
};
if (obj.hash) {
colors.normal("Hash: ");
colors.bold(obj.hash);
newline();
}
if (obj.version) {
colors.normal("Version: webpack ");
colors.bold(obj.version);
newline();
}
if (typeof obj.time === "number") {
colors.normal("Time: ");
colors.bold(obj.time);
colors.normal("ms");
newline();
}
if (typeof obj.builtAt === "number") {
const builtAtDate = new Date(obj.builtAt);
colors.normal("Built at: ");
colors.normal(
builtAtDate.toLocaleDateString(undefined, {
day: "2-digit",
month: "2-digit",
year: "numeric"
})
);
colors.normal(" ");
colors.bold(builtAtDate.toLocaleTimeString());
newline();
}
if (obj.env) {
colors.normal("Environment (--env): ");
colors.bold(JSON.stringify(obj.env, null, 2));
newline();
}
if (obj.publicPath) {
colors.normal("PublicPath: ");
colors.bold(obj.publicPath);
newline();
}
if (obj.assets && obj.assets.length > 0) {
const t = [
[
{
value: "Asset",
color: colors.bold
},
{
value: "Size",
color: colors.bold
},
{
value: "Chunks",
color: colors.bold
},
{
value: "",
color: colors.bold
},
{
value: "",
color: colors.bold
},
{
value: "Chunk Names",
color: colors.bold
}
]
];
for (const asset of obj.assets) {
t.push([
{
value: asset.name,
color: getAssetColor(asset, colors.green)
},
{
value: SizeFormatHelpers.formatSize(asset.size),
color: getAssetColor(asset, colors.normal)
},
{
value: asset.chunks.join(", "),
color: colors.bold
},
{
value: asset.emitted ? "[emitted]" : "",
color: colors.green
},
{
value: asset.isOverSizeLimit ? "[big]" : "",
color: getAssetColor(asset, colors.normal)
},
{
value: asset.chunkNames.join(", "),
color: colors.normal
}
]);
}
table(t, "rrrlll");
}
if (obj.filteredAssets > 0) {
colors.normal(" ");
if (obj.assets.length > 0) colors.normal("+ ");
colors.normal(obj.filteredAssets);
if (obj.assets.length > 0) colors.normal(" hidden");
colors.normal(obj.filteredAssets !== 1 ? " assets" : " asset");
newline();
}
const processChunkGroups = (namedGroups, prefix) => {
for (const name of Object.keys(namedGroups)) {
const cg = namedGroups[name];
colors.normal(`${prefix} `);
colors.bold(name);
if (cg.isOverSizeLimit) {
colors.normal(" ");
colors.yellow("[big]");
}
colors.normal(" =");
for (const asset of cg.assets) {
colors.normal(" ");
colors.green(asset);
}
for (const name of Object.keys(cg.childAssets)) {
const assets = cg.childAssets[name];
if (assets && assets.length > 0) {
colors.normal(" ");
colors.magenta(`(${name}:`);
for (const asset of assets) {
colors.normal(" ");
colors.green(asset);
}
colors.magenta(")");
}
}
newline();
}
};
if (obj.entrypoints) {
processChunkGroups(obj.entrypoints, "Entrypoint");
}
if (obj.namedChunkGroups) {
let outputChunkGroups = obj.namedChunkGroups;
if (obj.entrypoints) {
outputChunkGroups = Object.keys(outputChunkGroups)
.filter(name => !obj.entrypoints[name])
.reduce((result, name) => {
result[name] = obj.namedChunkGroups[name];
return result;
}, {});
}
processChunkGroups(outputChunkGroups, "Chunk Group");
}
const modulesByIdentifier = {};
if (obj.modules) {
for (const module of obj.modules) {
modulesByIdentifier[`$${module.identifier}`] = module;
}
} else if (obj.chunks) {
for (const chunk of obj.chunks) {
if (chunk.modules) {
for (const module of chunk.modules) {
modulesByIdentifier[`$${module.identifier}`] = module;
}
}
}
}
const processModuleAttributes = module => {
colors.normal(" ");
colors.normal(SizeFormatHelpers.formatSize(module.size));
if (module.chunks) {
for (const chunk of module.chunks) {
colors.normal(" {");
colors.yellow(chunk);
colors.normal("}");
}
}
if (typeof module.depth === "number") {
colors.normal(` [depth ${module.depth}]`);
}
if (module.cacheable === false) {
colors.red(" [not cacheable]");
}
if (module.optional) {
colors.yellow(" [optional]");
}
if (module.built) {
colors.green(" [built]");
}
if (module.assets && module.assets.length) {
colors.magenta(
` [${module.assets.length} asset${
module.assets.length === 1 ? "" : "s"
}]`
);
}
if (module.prefetched) {
colors.magenta(" [prefetched]");
}
if (module.failed) colors.red(" [failed]");
if (module.warnings) {
colors.yellow(
` [${module.warnings} warning${module.warnings === 1 ? "" : "s"}]`
);
}
if (module.errors) {
colors.red(
` [${module.errors} error${module.errors === 1 ? "" : "s"}]`
);
}
};
const processModuleContent = (module, prefix) => {
if (Array.isArray(module.providedExports)) {
colors.normal(prefix);
if (module.providedExports.length === 0) {
colors.cyan("[no exports]");
} else {
colors.cyan(`[exports: ${module.providedExports.join(", ")}]`);
}
newline();
}
if (module.usedExports !== undefined) {
if (module.usedExports !== true) {
colors.normal(prefix);
if (module.usedExports === null) {
colors.cyan("[used exports unknown]");
} else if (module.usedExports === false) {
colors.cyan("[no exports used]");
} else if (
Array.isArray(module.usedExports) &&
module.usedExports.length === 0
) {
colors.cyan("[no exports used]");
} else if (Array.isArray(module.usedExports)) {
const providedExportsCount = Array.isArray(module.providedExports)
? module.providedExports.length
: null;
if (
providedExportsCount !== null &&
providedExportsCount === module.usedExports.length
) {
colors.cyan("[all exports used]");
} else {
colors.cyan(
`[only some exports used: ${module.usedExports.join(", ")}]`
);
}
}
newline();
}
}
if (Array.isArray(module.optimizationBailout)) {
for (const item of module.optimizationBailout) {
colors.normal(prefix);
colors.yellow(item);
newline();
}
}
if (module.reasons) {
for (const reason of module.reasons) {
colors.normal(prefix);
if (reason.type) {
colors.normal(reason.type);
colors.normal(" ");
}
if (reason.userRequest) {
colors.cyan(reason.userRequest);
colors.normal(" ");
}
if (reason.moduleId !== null) {
colors.normal("[");
colors.normal(reason.moduleId);
colors.normal("]");
}
if (reason.module && reason.module !== reason.moduleId) {
colors.normal(" ");
colors.magenta(reason.module);
}
if (reason.loc) {
colors.normal(" ");
colors.normal(reason.loc);
}
if (reason.explanation) {
colors.normal(" ");
colors.cyan(reason.explanation);
}
newline();
}
}
if (module.profile) {
colors.normal(prefix);
let sum = 0;
if (module.issuerPath) {
for (const m of module.issuerPath) {
colors.normal("[");
colors.normal(m.id);
colors.normal("] ");
if (m.profile) {
const time = (m.profile.factory || 0) + (m.profile.building || 0);
coloredTime(time);
sum += time;
colors.normal(" ");
}
colors.normal("-> ");
}
}
for (const key of Object.keys(module.profile)) {
colors.normal(`${key}:`);
const time = module.profile[key];
coloredTime(time);
colors.normal(" ");
sum += time;
}
colors.normal("= ");
coloredTime(sum);
newline();
}
if (module.modules) {
processModulesList(module, prefix + "| ");
}
};
const processModulesList = (obj, prefix) => {
if (obj.modules) {
let maxModuleId = 0;
for (const module of obj.modules) {
if (typeof module.id === "number") {
if (maxModuleId < module.id) maxModuleId = module.id;
}
}
let contentPrefix = prefix + " ";
if (maxModuleId >= 10) contentPrefix += " ";
if (maxModuleId >= 100) contentPrefix += " ";
if (maxModuleId >= 1000) contentPrefix += " ";
for (const module of obj.modules) {
colors.normal(prefix);
const name = module.name || module.identifier;
if (typeof module.id === "string" || typeof module.id === "number") {
if (typeof module.id === "number") {
if (module.id < 1000 && maxModuleId >= 1000) colors.normal(" ");
if (module.id < 100 && maxModuleId >= 100) colors.normal(" ");
if (module.id < 10 && maxModuleId >= 10) colors.normal(" ");
} else {
if (maxModuleId >= 1000) colors.normal(" ");
if (maxModuleId >= 100) colors.normal(" ");
if (maxModuleId >= 10) colors.normal(" ");
}
if (name !== module.id) {
colors.normal("[");
colors.normal(module.id);
colors.normal("]");
colors.normal(" ");
} else {
colors.normal("[");
colors.bold(module.id);
colors.normal("]");
}
}
if (name !== module.id) {
colors.bold(name);
}
processModuleAttributes(module);
newline();
processModuleContent(module, contentPrefix);
}
if (obj.filteredModules > 0) {
colors.normal(prefix);
colors.normal(" ");
if (obj.modules.length > 0) colors.normal(" + ");
colors.normal(obj.filteredModules);
if (obj.modules.length > 0) colors.normal(" hidden");
colors.normal(obj.filteredModules !== 1 ? " modules" : " module");
newline();
}
}
};
if (obj.chunks) {
for (const chunk of obj.chunks) {
colors.normal("chunk ");
if (chunk.id < 1000) colors.normal(" ");
if (chunk.id < 100) colors.normal(" ");
if (chunk.id < 10) colors.normal(" ");
colors.normal("{");
colors.yellow(chunk.id);
colors.normal("} ");
colors.green(chunk.files.join(", "));
if (chunk.names && chunk.names.length > 0) {
colors.normal(" (");
colors.normal(chunk.names.join(", "));
colors.normal(")");
}
colors.normal(" ");
colors.normal(SizeFormatHelpers.formatSize(chunk.size));
for (const id of chunk.parents) {
colors.normal(" <{");
colors.yellow(id);
colors.normal("}>");
}
for (const id of chunk.siblings) {
colors.normal(" ={");
colors.yellow(id);
colors.normal("}=");
}
for (const id of chunk.children) {
colors.normal(" >{");
colors.yellow(id);
colors.normal("}<");
}
if (chunk.childrenByOrder) {
for (const name of Object.keys(chunk.childrenByOrder)) {
const children = chunk.childrenByOrder[name];
colors.normal(" ");
colors.magenta(`(${name}:`);
for (const id of children) {
colors.normal(" {");
colors.yellow(id);
colors.normal("}");
}
colors.magenta(")");
}
}
if (chunk.entry) {
colors.yellow(" [entry]");
} else if (chunk.initial) {
colors.yellow(" [initial]");
}
if (chunk.rendered) {
colors.green(" [rendered]");
}
if (chunk.recorded) {
colors.green(" [recorded]");
}
if (chunk.reason) {
colors.yellow(` ${chunk.reason}`);
}
newline();
if (chunk.origins) {
for (const origin of chunk.origins) {
colors.normal(" > ");
if (origin.reasons && origin.reasons.length) {
colors.yellow(origin.reasons.join(" "));
colors.normal(" ");
}
if (origin.request) {
colors.normal(origin.request);
colors.normal(" ");
}
if (origin.module) {
colors.normal("[");
colors.normal(origin.moduleId);
colors.normal("] ");
const module = modulesByIdentifier[`$${origin.module}`];
if (module) {
colors.bold(module.name);
colors.normal(" ");
}
}
if (origin.loc) {
colors.normal(origin.loc);
}
newline();
}
}
processModulesList(chunk, " ");
}
}
processModulesList(obj, "");
if (obj._showWarnings && obj.warnings) {
for (const warning of obj.warnings) {
newline();
colors.yellow(`WARNING in ${warning}`);
newline();
}
}
if (obj._showErrors && obj.errors) {
for (const error of obj.errors) {
newline();
colors.red(`ERROR in ${error}`);
newline();
}
}
if (obj.children) {
for (const child of obj.children) {
const childString = Stats.jsonToString(child, useColors);
if (childString) {
if (child.name) {
colors.normal("Child ");
colors.bold(child.name);
colors.normal(":");
} else {
colors.normal("Child");
}
newline();
buf.push(" ");
buf.push(childString.replace(/\n/g, "\n "));
newline();
}
}
}
if (obj.needAdditionalPass) {
colors.yellow(
"Compilation needs an additional pass and will compile again."
);
}
while (buf[buf.length - 1] === "\n") {
buf.pop();
}
return buf.join("");
}
static presetToOptions(name) {
// Accepted values: none, errors-only, minimal, normal, detailed, verbose
// Any other falsy value will behave as 'none', truthy values as 'normal'
const pn =
(typeof name === "string" && name.toLowerCase()) || name || "none";
switch (pn) {
case "none":
return {
all: false
};
case "verbose":
return {
entrypoints: true,
chunkGroups: true,
modules: false,
chunks: true,
chunkModules: true,
chunkOrigins: true,
depth: true,
env: true,
reasons: true,
usedExports: true,
providedExports: true,
optimizationBailout: true,
errorDetails: true,
publicPath: true,
exclude: false,
maxModules: Infinity
};
case "detailed":
return {
entrypoints: true,
chunkGroups: true,
chunks: true,
chunkModules: false,
chunkOrigins: true,
depth: true,
usedExports: true,
providedExports: true,
optimizationBailout: true,
errorDetails: true,
publicPath: true,
exclude: false,
maxModules: Infinity
};
case "minimal":
return {
all: false,
modules: true,
maxModules: 0,
errors: true,
warnings: true
};
case "errors-only":
return {
all: false,
errors: true,
moduleTrace: true
};
default:
return {};
}
}
static getChildOptions(options, idx) {
let innerOptions;
if (Array.isArray(options.children)) {
if (idx < options.children.length) {
innerOptions = options.children[idx];
}
} else if (typeof options.children === "object" && options.children) {
innerOptions = options.children;
}
if (typeof innerOptions === "boolean" || typeof innerOptions === "string") {
innerOptions = Stats.presetToOptions(innerOptions);
}
if (!innerOptions) {
return options;
}
const childOptions = Object.assign({}, options);
delete childOptions.children; // do not inherit children
return Object.assign(childOptions, innerOptions);
}
}
module.exports = Stats;
| Preset option for errors & warnings only | lib/Stats.js | Preset option for errors & warnings only | <ide><path>ib/Stats.js
<ide> errors: true,
<ide> moduleTrace: true
<ide> };
<add> case "errors-warnings":
<add> return {
<add> all: false,
<add> errors: true,
<add> warnings: true
<add> };
<ide> default:
<ide> return {};
<ide> } |
|
JavaScript | isc | b8fcd1fbf2decccac229d2d15ff749f5eb688dfb | 0 | macmillanpublishers/bookmaker,macmillanpublishers/bookmaker,macmillanpublishers/bookmaker,macmillanpublishers/bookmaker | var fs = require('fs');
var cheerio = require('cheerio');
var file = process.argv[2];
var srcEl = process.argv[3];
var srcType = process.argv[4];
var srcClass = process.argv[5];
if (process.argv[6] > 0) {
var num = process.argv[6] - 1;
var ss = "[" + num.toString() + "]";
} else {
var ss = "";
}
var destEl = process.argv[7];
var destType = process.argv[8];
var destClass = process.argv[9];
if (process.argv[10] > 0) {
var num2 = process.argv[10] - 1;
var ds = "[" + num2.toString() + "]";
} else {
var ds = "";
}
fs.readFile(file, function moveSection (err, contents) {
$ = cheerio.load(contents, {
xmlMode: true
});
if (srcType && srcClass) {
var source = $(srcEl + '[class="' + srcClass + '"][data-type="' + srcType + '"]') + ss;
} else if (srcType && !srcClass) {
var source = $(srcEl + '[data-type="' + srcType + '"]') + ss;
} else if (!srcType && srcClass) {
var source = $(srcEl + '[class="' + srcClass + '"]') + ss;
} else {
var source = $(srcEl) + ss;
};
if (destType && destClass) {
var destination = $(destEl + '[class="' + destClass + '"][data-type="' + destType + '"]') + ds;
} else if (destType && !destClass) {
var destination = $(destEl + '[data-type="' + destType + '"]') + ds;
} else if (!destType && destClass) {
var destination = $(destEl + '[class="' + destClass + '"]') + ds;
} else {
var destination = $(destEl) + ds;
};
if (destEl == "body") {
$('body').append(source);
} else {
$(source).insertBefore(destination);
};
var output = $.html();
fs.writeFile(file, output, function(err) {
if(err) {
return console.log(err);
}
console.log("Section has been moved!");
});
}); | core/utilities/movesection.js | var fs = require('fs');
var cheerio = require('cheerio');
var file = process.argv[2];
var srcEl = process.argv[3];
var srcType = process.argv[4];
var srcClass = process.argv[5];
var ss = process.argv[6] - 1;
var destEl = process.argv[7];
var destType = process.argv[8];
var destClass = process.argv[9];
var ds = process.argv[10] - 1;
fs.readFile(file, function moveSection (err, contents) {
$ = cheerio.load(contents, {
xmlMode: true
});
if (srcType && srcClass) {
var source = $(srcEl + '[class="' + srcClass + '"][data-type="' + srcType + '"]')[ss];
} else if (srcType && !srcClass) {
var source = $(srcEl + '[data-type="' + srcType + '"]')[ss];
} else if (!srcType && srcClass) {
var source = $(srcEl + '[class="' + srcClass + '"]')[ss];
} else {
var source = $(srcEl)[ss];
};
if (destType && destClass) {
var destination = $(destEl + '[class="' + destClass + '"][data-type="' + destType + '"]')[ds];
} else if (destType && !destClass) {
var destination = $(destEl + '[data-type="' + destType + '"]')[ds];
} else if (!destType && destClass) {
var destination = $(destEl + '[class="' + destClass + '"]')[ds];
} else {
var destination = $(destEl)[ds];
};
if (destEl == "body") {
$('body').append(source);
} else {
$(source).insertBefore(destination);
};
var output = $.html();
fs.writeFile(file, output, function(err) {
if(err) {
return console.log(err);
}
console.log("Section has been moved!");
});
}); | revising section sequence logic
| core/utilities/movesection.js | revising section sequence logic | <ide><path>ore/utilities/movesection.js
<ide> var srcEl = process.argv[3];
<ide> var srcType = process.argv[4];
<ide> var srcClass = process.argv[5];
<del>var ss = process.argv[6] - 1;
<add>if (process.argv[6] > 0) {
<add> var num = process.argv[6] - 1;
<add> var ss = "[" + num.toString() + "]";
<add>} else {
<add> var ss = "";
<add>}
<ide> var destEl = process.argv[7];
<ide> var destType = process.argv[8];
<ide> var destClass = process.argv[9];
<del>var ds = process.argv[10] - 1;
<add>if (process.argv[10] > 0) {
<add> var num2 = process.argv[10] - 1;
<add> var ds = "[" + num2.toString() + "]";
<add>} else {
<add> var ds = "";
<add>}
<ide>
<ide> fs.readFile(file, function moveSection (err, contents) {
<ide> $ = cheerio.load(contents, {
<ide> });
<ide>
<ide> if (srcType && srcClass) {
<del> var source = $(srcEl + '[class="' + srcClass + '"][data-type="' + srcType + '"]')[ss];
<add> var source = $(srcEl + '[class="' + srcClass + '"][data-type="' + srcType + '"]') + ss;
<ide> } else if (srcType && !srcClass) {
<del> var source = $(srcEl + '[data-type="' + srcType + '"]')[ss];
<add> var source = $(srcEl + '[data-type="' + srcType + '"]') + ss;
<ide> } else if (!srcType && srcClass) {
<del> var source = $(srcEl + '[class="' + srcClass + '"]')[ss];
<add> var source = $(srcEl + '[class="' + srcClass + '"]') + ss;
<ide> } else {
<del> var source = $(srcEl)[ss];
<add> var source = $(srcEl) + ss;
<ide> };
<ide>
<ide> if (destType && destClass) {
<del> var destination = $(destEl + '[class="' + destClass + '"][data-type="' + destType + '"]')[ds];
<add> var destination = $(destEl + '[class="' + destClass + '"][data-type="' + destType + '"]') + ds;
<ide> } else if (destType && !destClass) {
<del> var destination = $(destEl + '[data-type="' + destType + '"]')[ds];
<add> var destination = $(destEl + '[data-type="' + destType + '"]') + ds;
<ide> } else if (!destType && destClass) {
<del> var destination = $(destEl + '[class="' + destClass + '"]')[ds];
<add> var destination = $(destEl + '[class="' + destClass + '"]') + ds;
<ide> } else {
<del> var destination = $(destEl)[ds];
<add> var destination = $(destEl) + ds;
<ide> };
<ide>
<ide> if (destEl == "body") { |
|
Java | apache-2.0 | error: pathspec 'server/src/main/java/de/oliver_heger/mediastore/client/pages/overview/OverviewCallbackFactory.java' did not match any file(s) known to git
| c021e884ad385515e8d32cd0f987421219b23a5e | 1 | oheger/LineDJ | package de.oliver_heger.mediastore.client.pages.overview;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.view.client.HasData;
import de.oliver_heger.mediastore.shared.search.MediaSearchServiceAsync;
import de.oliver_heger.mediastore.shared.search.SearchResult;
/**
* <p>
* Definition of a factory interface for the creation of callback objects.
* </p>
* <p>
* This interface is used for server calls which require an
* {@code AsyncCallback} object.
* </p>
*
* @author Oliver Heger
* @version $Id: $
* @param <T> the type of data objects this factory has to deal with
*/
public interface OverviewCallbackFactory<T>
{
/**
* Creates a callback object for a simple search operation. A "simple"
* search can be performed in a single step, i.e. when the server call
* returns and the callback is invoked all data can be written into the
* widget.
*
* @param queryHandler the {@code OverviewQueryHandler}
* @param widget the cell widget to be populated with data
* @return the callback object
*/
AsyncCallback<SearchResult<T>> createSimpleSearchCallback(
OverviewQueryHandler<T> queryHandler, HasData<T> widget);
/**
* Creates a callback object for a search operation with parameters. Such a
* search can require multiple iterations and further server calls until all
* results have been retrieved.
*
* @param searchService the media search service
* @param queryHandler the {@code OverviewQueryHandler}
* @param widget the cell widget to be populated with data
* @return the callback object
*/
AsyncCallback<SearchResult<T>> createParameterSearchCallback(
MediaSearchServiceAsync searchService,
OverviewQueryHandler<T> queryHandler, HasData<T> widget);
}
| server/src/main/java/de/oliver_heger/mediastore/client/pages/overview/OverviewCallbackFactory.java | Added OverviewCallbackFactory interface. | server/src/main/java/de/oliver_heger/mediastore/client/pages/overview/OverviewCallbackFactory.java | Added OverviewCallbackFactory interface. | <ide><path>erver/src/main/java/de/oliver_heger/mediastore/client/pages/overview/OverviewCallbackFactory.java
<add>package de.oliver_heger.mediastore.client.pages.overview;
<add>
<add>import com.google.gwt.user.client.rpc.AsyncCallback;
<add>import com.google.gwt.view.client.HasData;
<add>
<add>import de.oliver_heger.mediastore.shared.search.MediaSearchServiceAsync;
<add>import de.oliver_heger.mediastore.shared.search.SearchResult;
<add>
<add>/**
<add> * <p>
<add> * Definition of a factory interface for the creation of callback objects.
<add> * </p>
<add> * <p>
<add> * This interface is used for server calls which require an
<add> * {@code AsyncCallback} object.
<add> * </p>
<add> *
<add> * @author Oliver Heger
<add> * @version $Id: $
<add> * @param <T> the type of data objects this factory has to deal with
<add> */
<add>public interface OverviewCallbackFactory<T>
<add>{
<add> /**
<add> * Creates a callback object for a simple search operation. A "simple"
<add> * search can be performed in a single step, i.e. when the server call
<add> * returns and the callback is invoked all data can be written into the
<add> * widget.
<add> *
<add> * @param queryHandler the {@code OverviewQueryHandler}
<add> * @param widget the cell widget to be populated with data
<add> * @return the callback object
<add> */
<add> AsyncCallback<SearchResult<T>> createSimpleSearchCallback(
<add> OverviewQueryHandler<T> queryHandler, HasData<T> widget);
<add>
<add> /**
<add> * Creates a callback object for a search operation with parameters. Such a
<add> * search can require multiple iterations and further server calls until all
<add> * results have been retrieved.
<add> *
<add> * @param searchService the media search service
<add> * @param queryHandler the {@code OverviewQueryHandler}
<add> * @param widget the cell widget to be populated with data
<add> * @return the callback object
<add> */
<add> AsyncCallback<SearchResult<T>> createParameterSearchCallback(
<add> MediaSearchServiceAsync searchService,
<add> OverviewQueryHandler<T> queryHandler, HasData<T> widget);
<add>} |
|
Java | apache-2.0 | f769991e62dfdf4e401e772aa904dd707945c439 | 0 | dachuanz/rabbitmq-rpc |
package org.apache.qpid.contrib.json.utils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream;
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream;
/**
* bzip 压缩比更高
* @author zdc
* @since 2015年5月28日
*/
public class BZip2Utils {
public static final int BUFFER = 1024;
public static final CharSequence EXT = ".bz2";
/**
* 数据压缩
*
* @param data
* @return
* @throws Exception
*/
public static byte[] compress(byte[] data) throws Exception {
ByteArrayInputStream bais = new ByteArrayInputStream(data);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// 压缩
compress(bais, baos);
byte[] output = baos.toByteArray();
baos.flush();
baos.close();
bais.close();
return output;
}
/**
* 文件压缩
*
* @param file
* @throws Exception
*/
public static void compress(File file) throws Exception {
compress(file, true);
}
/**
* 文件压缩
*
* @param file
* @param delete
* 是否删除原始文件
* @throws Exception
*/
public static void compress(File file, boolean delete) throws Exception {
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(file.getPath() + EXT);
compress(fis, fos);
fis.close();
fos.flush();
fos.close();
if (delete) {
file.delete();
}
}
/**
* 数据压缩
*
* @param is
* @param os
* @throws Exception
*/
public static void compress(InputStream is, OutputStream os) throws Exception {
BZip2CompressorOutputStream gos = new BZip2CompressorOutputStream(os);
int count;
byte data[] = new byte[BUFFER];
while ((count = is.read(data, 0, BUFFER)) != -1) {
gos.write(data, 0, count);
}
gos.finish();
gos.flush();
gos.close();
}
/**
* 文件压缩
*
* @param path
* @throws Exception
*/
public static void compress(String path) throws Exception {
compress(path, true);
}
/**
* 文件压缩
*
* @param path
* @param delete
* 是否删除原始文件
* @throws Exception
*/
public static void compress(String path, boolean delete) throws Exception {
File file = new File(path);
compress(file, delete);
}
/**
* 数据解压缩
*
* @param data
* @return
* @throws Exception
*/
public static byte[] decompress(byte[] data) throws Exception {
ByteArrayInputStream bais = new ByteArrayInputStream(data);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// 解压缩
decompress(bais, baos);
data = baos.toByteArray();
baos.flush();
baos.close();
bais.close();
return data;
}
/**
* 文件解压缩
*
* @param file
* @throws Exception
*/
public static void decompress(File file) throws Exception {
decompress(file, true);
}
/**
* 文件解压缩
*
* @param file
* @param delete
* 是否删除原始文件
* @throws Exception
*/
public static void decompress(File file, boolean delete) throws Exception {
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(file.getPath().replace(EXT, ""));
decompress(fis, fos);
fis.close();
fos.flush();
fos.close();
if (delete) {
file.delete();
}
}
/**
* 数据解压缩
*
* @param is
* @param os
* @throws Exception
*/
public static void decompress(InputStream is, OutputStream os) throws Exception {
BZip2CompressorInputStream gis = new BZip2CompressorInputStream(is);
int count;
byte data[] = new byte[BUFFER];
while ((count = gis.read(data, 0, BUFFER)) != -1) {
os.write(data, 0, count);
}
gis.close();
}
/**
* 文件解压缩
*
* @param path
* @throws Exception
*/
public static void decompress(String path) throws Exception {
decompress(path, true);
}
/**
* 文件解压缩
*
* @param path
* @param delete
* 是否删除原始文件
* @throws Exception
*/
public static void decompress(String path, boolean delete) throws Exception {
File file = new File(path);
decompress(file, delete);
}
}
| src/org/apache/qpid/contrib/json/utils/BZip2Utils.java |
package org.apache.qpid.contrib.json.utils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream;
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream;
/**
* @author zdc
* @since 2015年5月28日
*/
public class BZip2Utils {
public static final int BUFFER = 1024;
public static final CharSequence EXT = ".bz2";
/**
* 数据压缩
*
* @param data
* @return
* @throws Exception
*/
public static byte[] compress(byte[] data) throws Exception {
ByteArrayInputStream bais = new ByteArrayInputStream(data);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// 压缩
compress(bais, baos);
byte[] output = baos.toByteArray();
baos.flush();
baos.close();
bais.close();
return output;
}
/**
* 文件压缩
*
* @param file
* @throws Exception
*/
public static void compress(File file) throws Exception {
compress(file, true);
}
/**
* 文件压缩
*
* @param file
* @param delete
* 是否删除原始文件
* @throws Exception
*/
public static void compress(File file, boolean delete) throws Exception {
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(file.getPath() + EXT);
compress(fis, fos);
fis.close();
fos.flush();
fos.close();
if (delete) {
file.delete();
}
}
/**
* 数据压缩
*
* @param is
* @param os
* @throws Exception
*/
public static void compress(InputStream is, OutputStream os) throws Exception {
BZip2CompressorOutputStream gos = new BZip2CompressorOutputStream(os);
int count;
byte data[] = new byte[BUFFER];
while ((count = is.read(data, 0, BUFFER)) != -1) {
gos.write(data, 0, count);
}
gos.finish();
gos.flush();
gos.close();
}
/**
* 文件压缩
*
* @param path
* @throws Exception
*/
public static void compress(String path) throws Exception {
compress(path, true);
}
/**
* 文件压缩
*
* @param path
* @param delete
* 是否删除原始文件
* @throws Exception
*/
public static void compress(String path, boolean delete) throws Exception {
File file = new File(path);
compress(file, delete);
}
/**
* 数据解压缩
*
* @param data
* @return
* @throws Exception
*/
public static byte[] decompress(byte[] data) throws Exception {
ByteArrayInputStream bais = new ByteArrayInputStream(data);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// 解压缩
decompress(bais, baos);
data = baos.toByteArray();
baos.flush();
baos.close();
bais.close();
return data;
}
/**
* 文件解压缩
*
* @param file
* @throws Exception
*/
public static void decompress(File file) throws Exception {
decompress(file, true);
}
/**
* 文件解压缩
*
* @param file
* @param delete
* 是否删除原始文件
* @throws Exception
*/
public static void decompress(File file, boolean delete) throws Exception {
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(file.getPath().replace(EXT, ""));
decompress(fis, fos);
fis.close();
fos.flush();
fos.close();
if (delete) {
file.delete();
}
}
/**
* 数据解压缩
*
* @param is
* @param os
* @throws Exception
*/
public static void decompress(InputStream is, OutputStream os) throws Exception {
BZip2CompressorInputStream gis = new BZip2CompressorInputStream(is);
int count;
byte data[] = new byte[BUFFER];
while ((count = gis.read(data, 0, BUFFER)) != -1) {
os.write(data, 0, count);
}
gis.close();
}
/**
* 文件解压缩
*
* @param path
* @throws Exception
*/
public static void decompress(String path) throws Exception {
decompress(path, true);
}
/**
* 文件解压缩
*
* @param path
* @param delete
* 是否删除原始文件
* @throws Exception
*/
public static void decompress(String path, boolean delete) throws Exception {
File file = new File(path);
decompress(file, delete);
}
}
| Update BZip2Utils.java | src/org/apache/qpid/contrib/json/utils/BZip2Utils.java | Update BZip2Utils.java | <ide><path>rc/org/apache/qpid/contrib/json/utils/BZip2Utils.java
<ide> import org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream;
<ide>
<ide> /**
<add> * bzip 压缩比更高
<ide> * @author zdc
<ide> * @since 2015年5月28日
<ide> */ |
|
Java | apache-2.0 | 71fb611bf61fd20b87b84d5b842c210865ffceff | 0 | greese/dasein-cloud-aws,OSS-TheWeatherCompany/dasein-cloud-aws,daniellemayne/dasein-cloud-aws_old,jeffrey-yan/dasein-cloud-aws,maksimov/dasein-cloud-aws,maksimov/dasein-cloud-aws-old,TheWeatherCompany/dasein-cloud-aws,drewlyall/dasein-cloud-aws,dasein-cloud/dasein-cloud-aws,daniellemayne/dasein-cloud-aws | /**
* Copyright (C) 2009-2014 Dell, Inc.
* See annotations for authorship information
*
* ====================================================================
* 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.dasein.cloud.aws.compute;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import org.dasein.cloud.*;
import org.dasein.cloud.aws.AWSCloud;
import org.dasein.cloud.aws.AWSResourceNotFoundException;
import org.dasein.cloud.compute.*;
import org.dasein.cloud.identity.ServiceAction;
import org.dasein.cloud.network.*;
import org.dasein.cloud.util.APITrace;
import org.dasein.cloud.util.Cache;
import org.dasein.cloud.util.CacheLevel;
import org.dasein.util.CalendarWrapper;
import org.dasein.util.uom.storage.Gigabyte;
import org.dasein.util.uom.storage.Megabyte;
import org.dasein.util.uom.storage.Storage;
import org.dasein.util.uom.time.Day;
import org.dasein.util.uom.time.TimePeriod;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.*;
public class EC2Instance extends AbstractVMSupport<AWSCloud> {
static private final Logger logger = Logger.getLogger(EC2Instance.class);
static private final Calendar UTC_CALENDAR = Calendar.getInstance(new SimpleTimeZone(0, "GMT"));
private transient volatile EC2InstanceCapabilities capabilities;
EC2Instance(AWSCloud provider) {
super(provider);
}
@Override
public VirtualMachine alterVirtualMachine(@Nonnull String vmId, @Nonnull VMScalingOptions options) throws InternalException, CloudException {
APITrace.begin(getProvider(), "alterVirtualMachine");
try {
Map<String, String> parameters = getProvider().getStandardParameters(getProvider().getContext(), EC2Method.MODIFY_INSTANCE_ATTRIBUTE);
EC2Method method;
parameters.put("InstanceId", vmId);
parameters.put("InstanceType.Value", options.getProviderProductId());
method = new EC2Method(getProvider(), getProvider().getEc2Url(), parameters);
try {
method.invoke();
} catch( EC2Exception e ) {
logger.error(e.getSummary());
throw new CloudException(e);
} catch( Throwable ex ) {
throw new CloudException(ex);
}
return getVirtualMachine(vmId);
} finally {
APITrace.end();
}
}
@Override
public VirtualMachine modifyInstance(@Nonnull String vmId, @Nonnull String[] firewalls) throws InternalException, CloudException {
APITrace.begin(getProvider(), "alterVirtualMachine");
try {
Map<String, String> parameters = getProvider().getStandardParameters(getProvider().getContext(), EC2Method.MODIFY_INSTANCE_ATTRIBUTE);
EC2Method method;
parameters.put("InstanceId", vmId);
for( int i = 0; i < firewalls.length; i++ ) {
parameters.put("GroupId." + i, firewalls[i]);
}
method = new EC2Method(getProvider(), getProvider().getEc2Url(), parameters);
try {
method.invoke();
} catch( EC2Exception e ) {
logger.error(e.getSummary());
throw new CloudException(e);
} catch( Throwable ex ) {
throw new CloudException(ex);
}
return getVirtualMachine(vmId);
} finally {
APITrace.end();
}
}
@Override
public void start(@Nonnull String instanceId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "startVM");
try {
VirtualMachine vm = getVirtualMachine(instanceId);
if( vm == null ) {
throw new CloudException("No such instance: " + instanceId);
}
if( !vm.isPersistent() ) {
throw new OperationNotSupportedException("Instances backed by ephemeral drives are not start/stop capable");
}
Map<String, String> parameters = getProvider().getStandardParameters(getProvider().getContext(), EC2Method.START_INSTANCES);
EC2Method method;
parameters.put("InstanceId.1", instanceId);
method = new EC2Method(getProvider(), getProvider().getEc2Url(), parameters);
try {
method.invoke();
} catch( EC2Exception e ) {
logger.error(e.getSummary());
throw new CloudException(e);
}
} finally {
APITrace.end();
}
}
static private class Metric implements Comparable<Metric> {
int samples = 0;
long timestamp = -1L;
double minimum = -1.0;
double maximum = 0.0;
double average = 0.0;
public int compareTo(Metric other) {
if( other == this ) {
return 0;
}
return ( new Long(timestamp) ).compareTo(other.timestamp);
}
}
private Set<Metric> calculate(String metric, String unit, String id, boolean idIsVolumeId, long startTimestamp, long endTimestamp) throws CloudException, InternalException {
APITrace.begin(getProvider(), "calculateVMAnalytics");
try {
if( !getProvider().getEC2Provider().isAWS() ) {
return new TreeSet<Metric>();
}
Map<String, String> parameters = getProvider().getStandardCloudWatchParameters(getContext(), EC2Method.GET_METRIC_STATISTICS);
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
fmt.setCalendar(UTC_CALENDAR);
EC2Method method;
NodeList blocks;
Document doc;
parameters.put("EndTime", fmt.format(new Date(endTimestamp)));
parameters.put("StartTime", fmt.format(new Date(startTimestamp)));
parameters.put("MetricName", metric);
parameters.put("Namespace", idIsVolumeId ? "AWS/EBS" : "AWS/EC2");
parameters.put("Unit", unit);
parameters.put("Dimensions.member.Name.1", idIsVolumeId ? "VolumeId" : "InstanceId");
parameters.put("Dimensions.member.Value.1", id);
parameters.put("Statistics.member.1", "Average");
parameters.put("Statistics.member.2", "Minimum");
parameters.put("Statistics.member.3", "Maximum");
parameters.put("Period", "60");
method = new EC2Method(getProvider(), getCloudWatchUrl(getContext()), parameters);
try {
doc = method.invoke();
} catch( EC2Exception e ) {
logger.error(e.getSummary());
throw new CloudException(e);
}
TreeSet<Metric> metrics = new TreeSet<Metric>();
fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
fmt.setCalendar(UTC_CALENDAR);
blocks = doc.getElementsByTagName("member");
for( int i = 0; i < blocks.getLength(); i++ ) {
NodeList items = blocks.item(i).getChildNodes();
Metric m = new Metric();
for( int j = 0; j < items.getLength(); j++ ) {
Node item = items.item(j);
if( item.getNodeName().equals("Timestamp") ) {
String dateString = item.getFirstChild().getNodeValue();
try {
m.timestamp = fmt.parse(dateString).getTime();
} catch( ParseException e ) {
logger.error(e);
throw new InternalException(e);
}
} else if( item.getNodeName().equals("Average") ) {
m.average = Double.parseDouble(item.getFirstChild().getNodeValue());
} else if( item.getNodeName().equals("Minimum") ) {
m.minimum = Double.parseDouble(item.getFirstChild().getNodeValue());
} else if( item.getNodeName().equals("Maximum") ) {
m.maximum = Double.parseDouble(item.getFirstChild().getNodeValue());
} else if( item.getNodeName().equals("Samples") ) {
m.samples = (int) Double.parseDouble(item.getFirstChild().getNodeValue());
}
}
metrics.add(m);
}
return metrics;
} finally {
APITrace.end();
}
}
private interface ApplyCalcs {
public void apply(VmStatistics stats, long start, long end, int samples, double average, double minimum, double maximum);
}
private void calculate(VmStatistics stats, String metricName, String unit, String id, boolean idIsVolumeId, long startTimestamp, long endTimestamp, ApplyCalcs apply) throws CloudException, InternalException {
Set<Metric> metrics = calculate(metricName, unit, id, idIsVolumeId, startTimestamp, endTimestamp);
double minimum = -1.0, maximum = 0.0, sum = 0.0;
long start = -1L, end = 0L;
int samples = 0;
for( Metric metric : metrics ) {
if( start < 0L ) {
start = metric.timestamp;
}
if( metric.timestamp > end ) {
end = metric.timestamp;
}
samples++;
if( metric.minimum < minimum || minimum < 0.0 ) {
minimum = metric.minimum;
}
if( metric.maximum > maximum ) {
maximum = metric.maximum;
}
sum += metric.average;
}
if( start < 0L ) {
start = startTimestamp;
}
if( end < 0L ) {
end = endTimestamp;
if( end < 1L ) {
end = System.currentTimeMillis();
}
}
if( minimum < 0.0 ) {
minimum = 0.0;
}
apply.apply(stats, start, end, samples, samples == 0 ? 0.0 : sum / samples, minimum, maximum);
}
private void calculateCpuUtilization(VmStatistics statistics, String instanceId, long startTimestamp, long endTimestamp) throws CloudException, InternalException {
ApplyCalcs apply = new ApplyCalcs() {
public void apply(VmStatistics stats, long start, long end, int samples, double average, double minimum, double maximum) {
stats.setSamples(samples);
stats.setStartTimestamp(start);
stats.setMinimumCpuUtilization(minimum);
stats.setAverageCpuUtilization(average);
stats.setMaximumCpuUtilization(maximum);
stats.setEndTimestamp(end);
}
};
calculate(statistics, "CPUUtilization", "Percent", instanceId, false, startTimestamp, endTimestamp, apply);
}
private void calculateDiskReadBytes(VmStatistics statistics, String id, boolean idIsVolumeId, long startTimestamp, long endTimestamp) throws CloudException, InternalException {
ApplyCalcs apply = new ApplyCalcs() {
public void apply(VmStatistics stats, long start, long end, int samples, double average, double minimum, double maximum) {
stats.setMinimumDiskReadBytes(minimum);
stats.setAverageDiskReadBytes(average);
stats.setMaximumDiskReadBytes(maximum);
}
};
calculate(statistics, idIsVolumeId ? "VolumeReadBytes" : "DiskReadBytes", "Bytes", id, idIsVolumeId, startTimestamp, endTimestamp, apply);
}
private void calculateDiskReadOps(VmStatistics statistics, String id, boolean idIsVolumeId, long startTimestamp, long endTimestamp) throws CloudException, InternalException {
ApplyCalcs apply = new ApplyCalcs() {
public void apply(VmStatistics stats, long start, long end, int samples, double average, double minimum, double maximum) {
stats.setMinimumDiskReadOperations(minimum);
stats.setAverageDiskReadOperations(average);
stats.setMaximumDiskReadOperations(maximum);
}
};
calculate(statistics, idIsVolumeId ? "VolumeReadOps" : "DiskReadOps", "Count", id, idIsVolumeId, startTimestamp, endTimestamp, apply);
}
private void calculateDiskWriteBytes(VmStatistics statistics, String id, boolean idIsVolumeId, long startTimestamp, long endTimestamp) throws CloudException, InternalException {
ApplyCalcs apply = new ApplyCalcs() {
public void apply(VmStatistics stats, long start, long end, int samples, double average, double minimum, double maximum) {
stats.setMinimumDiskWriteBytes(minimum);
stats.setAverageDiskWriteBytes(average);
stats.setMaximumDiskWriteBytes(maximum);
}
};
calculate(statistics, idIsVolumeId ? "VolumeWriteBytes" : "DiskWriteBytes", "Bytes", id, idIsVolumeId, startTimestamp, endTimestamp, apply);
}
private void calculateDiskWriteOps(VmStatistics statistics, String id, boolean idIsVolumeId, long startTimestamp, long endTimestamp) throws CloudException, InternalException {
ApplyCalcs apply = new ApplyCalcs() {
public void apply(VmStatistics stats, long start, long end, int samples, double average, double minimum, double maximum) {
stats.setMinimumDiskWriteOperations(minimum);
stats.setAverageDiskWriteOperations(average);
stats.setMaximumDiskWriteOperations(maximum);
}
};
calculate(statistics, idIsVolumeId ? "VolumeWriteOps" : "DiskWriteOps", "Count", id, idIsVolumeId, startTimestamp, endTimestamp, apply);
}
private void calculateNetworkIn(VmStatistics statistics, String instanceId, long startTimestamp, long endTimestamp) throws CloudException, InternalException {
ApplyCalcs apply = new ApplyCalcs() {
public void apply(VmStatistics stats, long start, long end, int samples, double average, double minimum, double maximum) {
stats.setMinimumNetworkIn(minimum);
stats.setAverageNetworkIn(average);
stats.setMaximumNetworkIn(maximum);
}
};
calculate(statistics, "NetworkIn", "Bytes", instanceId, false, startTimestamp, endTimestamp, apply);
}
private void calculateNetworkOut(VmStatistics statistics, String instanceId, long startTimestamp, long endTimestamp) throws CloudException, InternalException {
ApplyCalcs apply = new ApplyCalcs() {
public void apply(VmStatistics stats, long start, long end, int samples, double average, double minimum, double maximum) {
stats.setMinimumNetworkOut(minimum);
stats.setAverageNetworkOut(average);
stats.setMaximumNetworkOut(maximum);
}
};
calculate(statistics, "NetworkOut", "Bytes", instanceId, false, startTimestamp, endTimestamp, apply);
}
@Override
public @Nonnull VirtualMachine clone(@Nonnull String vmId, @Nonnull String intoDcId, @Nonnull String name, @Nonnull String description, boolean powerOn, @Nullable String... firewallIds) throws InternalException, CloudException {
throw new OperationNotSupportedException("AWS instances cannot be cloned.");
}
@Override
public void enableAnalytics(@Nonnull String instanceId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "enableVMAnalytics");
try {
if( getProvider().getEC2Provider().isAWS() || getProvider().getEC2Provider().isEnStratus() ) {
Map<String, String> parameters = getProvider().getStandardParameters(getProvider().getContext(), EC2Method.MONITOR_INSTANCES);
EC2Method method;
parameters.put("InstanceId.1", instanceId);
method = new EC2Method(getProvider(), getProvider().getEc2Url(), parameters);
try {
method.invoke();
} catch( EC2Exception e ) {
logger.error(e.getSummary());
throw new CloudException(e);
}
}
} finally {
APITrace.end();
}
}
private Architecture getArchitecture(String size) {
if( size.equals("m1.small") || size.equals("c1.medium") ) {
return Architecture.I32;
} else {
return Architecture.I64;
}
}
public @Nonnull EC2InstanceCapabilities getCapabilities() {
if( capabilities == null ) {
capabilities = new EC2InstanceCapabilities(getProvider());
}
return capabilities;
}
private @Nonnull String getCloudWatchUrl(@Nonnull ProviderContext ctx) {
return ( "https://monitoring." + ctx.getRegionId() + ".amazonaws.com" );
}
@Override
public @Nullable String getPassword(@Nonnull String instanceId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "getPassword");
try {
Callable<String> callable = new GetPassCallable(
instanceId,
getProvider().getStandardParameters(getProvider().getContext(), EC2Method.GET_PASSWORD_DATA),
getProvider(),
getProvider().getEc2Url()
);
return callable.call();
} catch( EC2Exception e ) {
logger.error(e.getSummary());
throw new CloudException(e);
} catch( CloudException ce ) {
throw ce;
} catch( Exception e ) {
throw new InternalException(e);
} finally {
APITrace.end();
}
}
public static class GetPassCallable implements Callable {
private String instanceId;
private Map<String, String> params;
private AWSCloud awsProvider;
private String ec2url;
public GetPassCallable(String iId, Map<String, String> p, AWSCloud ap, String eUrl) {
instanceId = iId;
params = p;
awsProvider = ap;
ec2url = eUrl;
}
public String call() throws CloudException {
EC2Method method;
NodeList blocks;
Document doc;
params.put("InstanceId", instanceId);
try {
method = new EC2Method(awsProvider, ec2url, params);
} catch( InternalException e ) {
logger.error(e.getMessage());
throw new CloudException(e);
}
try {
doc = method.invoke();
} catch( EC2Exception e ) {
logger.error(e.getSummary());
throw new CloudException(e);
} catch( InternalException e ) {
logger.error(e.getMessage());
throw new CloudException(e);
}
blocks = doc.getElementsByTagName("passwordData");
if( blocks.getLength() > 0 ) {
Node pw = blocks.item(0);
if( pw.hasChildNodes() ) {
return pw.getFirstChild().getNodeValue();
}
return null;
}
return null;
}
}
@Override
public @Nullable String getUserData(@Nonnull String instanceId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "getUserData");
try {
Callable<String> callable = new GetUserDataCallable(
instanceId,
getProvider().getStandardParameters(getProvider().getContext(), EC2Method.DESCRIBE_INSTANCE_ATTRIBUTE),
getProvider(),
getProvider().getEc2Url()
);
String encodedUserDataValue = callable.call();
return new String(Base64.decodeBase64(encodedUserDataValue));
} catch( EC2Exception e ) {
logger.error(e.getSummary());
throw new CloudException(e);
} catch( CloudException ce ) {
throw ce;
} catch( Exception e ) {
throw new InternalException(e);
} finally {
APITrace.end();
}
}
public static class GetUserDataCallable implements Callable {
private String instanceId;
private Map<String, String> params;
private AWSCloud awsProvider;
private String ec2url;
public GetUserDataCallable(String iId, Map<String, String> p, AWSCloud ap, String eUrl) {
instanceId = iId;
params = p;
awsProvider = ap;
ec2url = eUrl;
}
public String call() throws CloudException {
EC2Method method;
NodeList blocks;
Document doc;
params.put("InstanceId", instanceId);
params.put("Attribute", "userData");
try {
method = new EC2Method(awsProvider, ec2url, params);
} catch( InternalException e ) {
logger.error(e.getMessage());
throw new CloudException(e);
}
try {
doc = method.invoke();
} catch( EC2Exception e ) {
logger.error(e.getSummary());
throw new CloudException(e);
} catch( InternalException e ) {
logger.error(e.getMessage());
throw new CloudException(e);
}
blocks = doc.getElementsByTagName("value");
if( blocks.getLength() > 0 ) {
Node pw = blocks.item(0);
if( pw.hasChildNodes() ) {
return pw.getFirstChild().getNodeValue();
}
return null;
}
return null;
}
}
@Override
public @Nonnull String getConsoleOutput(@Nonnull String instanceId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "getConsoleOutput");
try {
Map<String, String> parameters = getProvider().getStandardParameters(getProvider().getContext(), EC2Method.GET_CONSOLE_OUTPUT);
String output = null;
EC2Method method;
NodeList blocks;
Document doc;
parameters.put("InstanceId", instanceId);
method = new EC2Method(getProvider(), getProvider().getEc2Url(), parameters);
try {
doc = method.invoke();
} catch( EC2Exception e ) {
String code = e.getCode();
if( code != null && code.startsWith("InvalidInstanceID") ) {
return "";
}
logger.error(e.getSummary());
throw new CloudException(e);
}
blocks = doc.getElementsByTagName("timestamp");
for( int i = 0; i < blocks.getLength(); i++ ) {
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
fmt.setCalendar(UTC_CALENDAR);
String ts = blocks.item(i).getFirstChild().getNodeValue();
long timestamp;
try {
timestamp = fmt.parse(ts).getTime();
} catch( ParseException e ) {
logger.error(e);
throw new CloudException(e);
}
if( timestamp > -1L ) {
break;
}
}
blocks = doc.getElementsByTagName("output");
for( int i = 0; i < blocks.getLength(); i++ ) {
Node item = blocks.item(i);
if( item.hasChildNodes() ) {
output = item.getFirstChild().getNodeValue().trim();
if( output != null ) {
break;
}
}
}
if( output != null ) {
try {
return new String(Base64.decodeBase64(output.getBytes("utf-8")), "utf-8");
} catch( UnsupportedEncodingException e ) {
logger.error(e);
throw new InternalException(e);
}
}
return "";
} finally {
APITrace.end();
}
}
@Override
public int getCostFactor(@Nonnull VmState vmState) throws InternalException, CloudException {
return ( vmState.equals(VmState.STOPPED) ? 0 : 100 );
}
@Override
public int getMaximumVirtualMachineCount() throws CloudException, InternalException {
return -2;
}
@Override
public @Nonnull Iterable<String> listFirewalls(@Nonnull String instanceId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "listFirewallsForVM");
try {
Map<String, String> parameters = getProvider().getStandardParameters(getProvider().getContext(), EC2Method.DESCRIBE_INSTANCES);
ArrayList<String> firewalls = new ArrayList<String>();
EC2Method method;
NodeList blocks;
Document doc;
parameters.put("InstanceId.1", instanceId);
method = new EC2Method(getProvider(), getProvider().getEc2Url(), parameters);
try {
doc = method.invoke();
} catch( EC2Exception e ) {
String code = e.getCode();
if( code != null && code.startsWith("InvalidInstanceID") ) {
return firewalls;
}
logger.error(e.getSummary());
throw new CloudException(e);
}
blocks = doc.getElementsByTagName("groupSet");
for( int i = 0; i < blocks.getLength(); i++ ) {
NodeList items = blocks.item(i).getChildNodes();
for( int j = 0; j < items.getLength(); j++ ) {
Node item = items.item(j);
if( item.getNodeName().equals("item") ) {
NodeList sub = item.getChildNodes();
for( int k = 0; k < sub.getLength(); k++ ) {
Node id = sub.item(k);
if( id.getNodeName().equalsIgnoreCase("groupId") && id.hasChildNodes() ) {
firewalls.add(id.getFirstChild().getNodeValue().trim());
break;
}
}
}
}
}
return firewalls;
} finally {
APITrace.end();
}
}
@Override
public @Nullable VirtualMachine getVirtualMachine(@Nonnull String instanceId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "getVirtualMachine");
try {
ProviderContext ctx = getProvider().getContext();
if( ctx == null ) {
throw new CloudException("No context was established for this request");
}
Future<Iterable<IpAddress>> ipPoolFuture = null;
Iterable<IpAddress> addresses;
if( getProvider().hasNetworkServices() ) {
NetworkServices services = getProvider().getNetworkServices();
if( services != null ) {
if( services.hasIpAddressSupport() ) {
IpAddressSupport support = services.getIpAddressSupport();
if( support != null ) {
ipPoolFuture = support.listIpPoolConcurrently(IPVersion.IPV4, false);
}
}
}
}
Map<String, String> parameters = getProvider().getStandardParameters(getProvider().getContext(), EC2Method.DESCRIBE_INSTANCES);
EC2Method method;
NodeList blocks;
Document doc;
parameters.put("InstanceId.1", instanceId);
method = new EC2Method(getProvider(), getProvider().getEc2Url(), parameters);
try {
doc = method.invoke();
} catch( EC2Exception e ) {
String code = e.getCode();
if( code != null && code.startsWith("InvalidInstanceID") ) {
return null;
}
logger.error(e.getSummary());
throw new CloudException(e);
}
blocks = doc.getElementsByTagName("instancesSet");
for( int i = 0; i < blocks.getLength(); i++ ) {
NodeList instances = blocks.item(i).getChildNodes();
for( int j = 0; j < instances.getLength(); j++ ) {
Node instance = instances.item(j);
if( instance.getNodeName().equals("item") ) {
try {
if( ipPoolFuture != null ) {
addresses = ipPoolFuture.get(30, TimeUnit.SECONDS);
}
else {
addresses = Collections.emptyList();
}
} catch( InterruptedException e ) {
logger.error(e.getMessage());
addresses = Collections.emptyList();
} catch( ExecutionException e ) {
logger.error(e.getMessage());
addresses = Collections.emptyList();
} catch( TimeoutException e ) {
logger.error(e.getMessage());
addresses = Collections.emptyList();
}
VirtualMachine server = toVirtualMachine( ctx, instance, addresses );
if ( server != null && server.getProviderVirtualMachineId().equals( instanceId ) ) {
return server;
}
}
}
}
return null;
} catch( Exception e ) {
e.printStackTrace();
if( e instanceof CloudException ) {
throw ( CloudException ) e;
}
throw new InternalException(e);
} finally {
APITrace.end();
}
}
@Override
public @Nullable VirtualMachineProduct getProduct(@Nonnull String sizeId) throws CloudException, InternalException {
for( Architecture a : getCapabilities().listSupportedArchitectures() ) {
for( VirtualMachineProduct prd : listProducts(a) ) {
if( prd.getProviderProductId().equals(sizeId) ) {
return prd;
}
}
}
return null;
}
private VmState getServerState(String state) {
if( state.equals("pending") ) {
return VmState.PENDING;
} else if( state.equals("running") ) {
return VmState.RUNNING;
} else if( state.equals("terminating") || state.equals("stopping") ) {
return VmState.STOPPING;
} else if( state.equals("stopped") ) {
return VmState.STOPPED;
} else if( state.equals("shutting-down") ) {
return VmState.STOPPING;
} else if( state.equals("terminated") ) {
return VmState.TERMINATED;
} else if( state.equals("rebooting") ) {
return VmState.REBOOTING;
}
logger.warn("Unknown server state: " + state);
return VmState.PENDING;
}
@Override
public @Nonnull VmStatistics getVMStatistics(@Nonnull String instanceId, @Nonnegative long startTimestamp, @Nonnegative long endTimestamp) throws InternalException, CloudException {
APITrace.begin(getProvider(), "getVMStatistics");
try {
VmStatistics statistics = new VmStatistics();
if( endTimestamp < 1L ) {
endTimestamp = System.currentTimeMillis() + 1000L;
}
if( startTimestamp < ( System.currentTimeMillis() - ( 2L * CalendarWrapper.DAY ) ) ) {
startTimestamp = System.currentTimeMillis() - ( 2L * CalendarWrapper.DAY );
if( startTimestamp > ( endTimestamp - ( 2L * CalendarWrapper.MINUTE ) ) ) {
endTimestamp = startTimestamp + ( 2L * CalendarWrapper.MINUTE );
}
} else if( startTimestamp > ( endTimestamp - ( 2L * CalendarWrapper.MINUTE ) ) ) {
startTimestamp = endTimestamp - ( 2L * CalendarWrapper.MINUTE );
}
String id = instanceId;
boolean idIsVolumeId = false;
VirtualMachine vm = getVirtualMachine(instanceId);
if( vm != null ) {
if( vm.isPersistent() ) {
if( vm.getProviderVolumeIds(getProvider()).length > 0 ) {
id = vm.getProviderVolumeIds(getProvider())[0];
idIsVolumeId = true;
}
}
calculateCpuUtilization(statistics, instanceId, startTimestamp, endTimestamp);
calculateDiskReadBytes(statistics, id, idIsVolumeId, startTimestamp, endTimestamp);
calculateDiskReadOps(statistics, id, idIsVolumeId, startTimestamp, endTimestamp);
calculateDiskWriteBytes(statistics, id, idIsVolumeId, startTimestamp, endTimestamp);
calculateDiskWriteOps(statistics, id, idIsVolumeId, startTimestamp, endTimestamp);
calculateNetworkIn(statistics, instanceId, startTimestamp, endTimestamp);
calculateNetworkOut(statistics, instanceId, startTimestamp, endTimestamp);
}
return statistics;
} finally {
APITrace.end();
}
}
@Override
public @Nonnull Iterable<VmStatistics> getVMStatisticsForPeriod(@Nonnull String instanceId, long startTimestamp, long endTimestamp) throws InternalException, CloudException {
APITrace.begin(getProvider(), "getVMStatisticsForPeriod");
try {
if( endTimestamp < 1L ) {
endTimestamp = System.currentTimeMillis() + 1000L;
}
if( startTimestamp < ( System.currentTimeMillis() - CalendarWrapper.DAY ) ) {
startTimestamp = System.currentTimeMillis() - CalendarWrapper.DAY;
if( startTimestamp > ( endTimestamp - ( 2L * CalendarWrapper.MINUTE ) ) ) {
endTimestamp = startTimestamp + ( 2L * CalendarWrapper.MINUTE );
}
} else if( startTimestamp > ( endTimestamp - ( 2L * CalendarWrapper.MINUTE ) ) ) {
startTimestamp = endTimestamp - ( 2L * CalendarWrapper.MINUTE );
}
TreeMap<Integer, VmStatistics> statMap = new TreeMap<Integer, VmStatistics>();
int minutes = (int) ( ( endTimestamp - startTimestamp ) / CalendarWrapper.MINUTE );
for( int i = 1; i <= minutes; i++ ) {
statMap.put(i, new VmStatistics());
}
Set<Metric> metrics = calculate("CPUUtilization", "Percent", instanceId, false, startTimestamp, endTimestamp);
for( Metric m : metrics ) {
int minute = 1 + (int) ( ( m.timestamp - startTimestamp ) / CalendarWrapper.MINUTE );
VmStatistics stats = statMap.get(minute);
if( stats == null ) {
stats = new VmStatistics();
statMap.put(minute, stats);
}
stats.setAverageCpuUtilization(m.average);
stats.setMaximumCpuUtilization(m.maximum);
stats.setMinimumCpuUtilization(m.minimum);
stats.setStartTimestamp(m.timestamp);
stats.setEndTimestamp(m.timestamp);
stats.setSamples(m.samples);
}
String id = instanceId;
boolean idIsVolumeId = false;
VirtualMachine vm = getVirtualMachine(instanceId);
if( vm != null && vm.isPersistent() ) {
if( vm.getProviderVolumeIds(getProvider()).length > 0 ) {
id = vm.getProviderVolumeIds(getProvider())[0];
idIsVolumeId = true;
}
}
metrics = calculate(idIsVolumeId ? "VolumeReadBytes" : "DiskReadBytes", "Bytes", id, idIsVolumeId, startTimestamp, endTimestamp);
for( Metric m : metrics ) {
int minute = 1 + (int) ( ( m.timestamp - startTimestamp ) / CalendarWrapper.MINUTE );
VmStatistics stats = statMap.get(minute);
if( stats == null ) {
stats = new VmStatistics();
statMap.put(minute, stats);
}
stats.setAverageDiskReadBytes(m.average);
stats.setMinimumDiskReadBytes(m.minimum);
stats.setMaximumDiskReadBytes(m.maximum);
if( stats.getSamples() < 1 ) {
stats.setSamples(m.samples);
}
}
metrics = calculate(idIsVolumeId ? "VolumeReadOps" : "DiskReadOps", "Count", id, idIsVolumeId, startTimestamp, endTimestamp);
for( Metric m : metrics ) {
int minute = 1 + (int) ( ( m.timestamp - startTimestamp ) / CalendarWrapper.MINUTE );
VmStatistics stats = statMap.get(minute);
if( stats == null ) {
stats = new VmStatistics();
statMap.put(minute, stats);
}
stats.setAverageDiskReadOperations(m.average);
stats.setMinimumDiskReadOperations(m.minimum);
stats.setMaximumDiskReadOperations(m.maximum);
if( stats.getSamples() < 1 ) {
stats.setSamples(m.samples);
}
}
metrics = calculate(idIsVolumeId ? "VolumeWriteBytes" : "DiskWriteBytes", "Bytes", id, idIsVolumeId, startTimestamp, endTimestamp);
for( Metric m : metrics ) {
int minute = 1 + (int) ( ( m.timestamp - startTimestamp ) / CalendarWrapper.MINUTE );
VmStatistics stats = statMap.get(minute);
if( stats == null ) {
stats = new VmStatistics();
statMap.put(minute, stats);
}
stats.setAverageDiskWriteBytes(m.average);
stats.setMinimumDiskWriteBytes(m.minimum);
stats.setMaximumDiskWriteBytes(m.maximum);
if( stats.getSamples() < 1 ) {
stats.setSamples(m.samples);
}
}
metrics = calculate(idIsVolumeId ? "VolumeWriteOps" : "DiskWriteOps", "Count", id, idIsVolumeId, startTimestamp, endTimestamp);
for( Metric m : metrics ) {
int minute = 1 + (int) ( ( m.timestamp - startTimestamp ) / CalendarWrapper.MINUTE );
VmStatistics stats = statMap.get(minute);
if( stats == null ) {
stats = new VmStatistics();
statMap.put(minute, stats);
}
stats.setAverageDiskWriteOperations(m.average);
stats.setMinimumDiskWriteOperations(m.minimum);
stats.setMaximumDiskWriteOperations(m.maximum);
if( stats.getSamples() < 1 ) {
stats.setSamples(m.samples);
}
}
metrics = calculate("NetworkIn", "Bytes", instanceId, false, startTimestamp, endTimestamp);
for( Metric m : metrics ) {
int minute = 1 + (int) ( ( m.timestamp - startTimestamp ) / CalendarWrapper.MINUTE );
VmStatistics stats = statMap.get(minute);
if( stats == null ) {
stats = new VmStatistics();
statMap.put(minute, stats);
}
stats.setAverageNetworkIn(m.average);
stats.setMinimumNetworkIn(m.minimum);
stats.setMaximumNetworkIn(m.maximum);
if( stats.getSamples() < 1 ) {
stats.setSamples(m.samples);
}
}
metrics = calculate("NetworkOut", "Bytes", instanceId, false, startTimestamp, endTimestamp);
for( Metric m : metrics ) {
int minute = 1 + (int) ( ( m.timestamp - startTimestamp ) / CalendarWrapper.MINUTE );
VmStatistics stats = statMap.get(minute);
if( stats == null ) {
stats = new VmStatistics();
statMap.put(minute, stats);
}
stats.setAverageNetworkOut(m.average);
stats.setMinimumNetworkOut(m.minimum);
stats.setMaximumNetworkOut(m.maximum);
if( stats.getSamples() < 1 ) {
stats.setSamples(m.samples);
}
}
ArrayList<VmStatistics> list = new ArrayList<VmStatistics>();
for( Map.Entry<Integer, VmStatistics> entry : statMap.entrySet() ) {
VmStatistics stats = entry.getValue();
if( stats != null && stats.getSamples() > 0 ) {
list.add(stats);
}
}
return list;
} finally {
APITrace.end();
}
}
@Override
public Iterable<VirtualMachineStatus> getVMStatus(@Nullable String... vmIds) throws InternalException, CloudException {
VmStatusFilterOptions filterOptions = vmIds != null ? VmStatusFilterOptions.getInstance().withVmIds(vmIds) : VmStatusFilterOptions.getInstance();
return getVMStatus(filterOptions);
}
@Override
public @Nullable Iterable<VirtualMachineStatus> getVMStatus( @Nullable VmStatusFilterOptions filterOptions) throws InternalException, CloudException {
APITrace.begin(getProvider(), "getVMStatus");
try {
ProviderContext ctx = getProvider().getContext();
if( ctx == null ) {
throw new CloudException("No context was established for this request");
}
Map<String, String> params = getProvider().getStandardParameters(getProvider().getContext(), EC2Method.DESCRIBE_INSTANCE_STATUS);
EC2Method method;
NodeList blocks;
Document doc;
Map<String, String> filterParameters = createFilterParametersFrom(filterOptions);
getProvider().putExtraParameters(params, filterParameters);
try {
method = new EC2Method(getProvider(), getProvider().getEc2Url(), params);
} catch( InternalException e ) {
logger.error(e.getMessage());
throw new CloudException(e);
}
try {
doc = method.invoke();
} catch( EC2Exception e ) {
String code = e.getCode();
if( code != null && code.startsWith("InvalidInstanceID") ) {
return null;
}
logger.error(e.getSummary());
throw new CloudException(e);
} catch( InternalException e ) {
logger.error(e.getMessage());
throw new CloudException(e);
}
ArrayList<VirtualMachineStatus> list = new ArrayList<VirtualMachineStatus>();
blocks = doc.getElementsByTagName("instanceStatusSet");
for( int i = 0; i < blocks.getLength(); i++ ) {
NodeList instances = blocks.item(i).getChildNodes();
for( int j = 0; j < instances.getLength(); j++ ) {
Node instance = instances.item(j);
if( instance.getNodeName().equals("item") ) {
NodeList attrs = instance.getChildNodes();
VirtualMachineStatus vm = new VirtualMachineStatus();
for( int k = 0; k < attrs.getLength(); k++ ) {
Node attr = attrs.item(k);
String name;
name = attr.getNodeName();
if( name.equals("instanceId") ) {
String value = attr.getFirstChild().getNodeValue().trim();
vm.setProviderVirtualMachineId(value);
}
else if( name.equals("systemStatus") ) {
NodeList details = attr.getChildNodes();
for( int l = 0; l < details.getLength(); l++ ) {
Node detail = details.item(l);
name = detail.getNodeName();
if( name.equals("status") ) {
String value = detail.getFirstChild().getNodeValue().trim();
vm.setProviderHostStatus(toVmStatus(value));
}
}
}
else if( name.equals("instanceStatus") ) {
NodeList details = attr.getChildNodes();
for( int l = 0; l < details.getLength(); l++ ) {
Node detail = details.item(l);
name = detail.getNodeName();
if( name.equals("status") ) {
String value = detail.getFirstChild().getNodeValue().trim();
vm.setProviderVmStatus(toVmStatus(value));
}
}
}
}
list.add(vm);
}
}
}
return list;
} catch( CloudException ce ) {
ce.printStackTrace();
throw ce;
} catch( Exception e ) {
e.printStackTrace();
throw new InternalException(e);
} finally {
APITrace.end();
}
}
private Map<String, String> createFilterParametersFrom(@Nullable VmStatusFilterOptions options ) {
if( options == null || options.isMatchesAny() ) {
return Collections.emptyMap();
}
// tag advantage of EC2-based filtering if we can...
Map<String, String> extraParameters = new HashMap<String, String>();
int filterIndex = 0;
if( options.getVmStatuses() != null ) {
getProvider().addFilterParameter(extraParameters, filterIndex++, "system-status.status", options.getVmStatuses());
getProvider().addFilterParameter(extraParameters, filterIndex++, "instance-status.status", options.getVmStatuses());
}
String[] vmIds = options.getVmIds();
if( vmIds != null ) {
for( int y = 0; y < vmIds.length; y++ ) {
extraParameters.put("InstanceId." + String.valueOf(y + 1), vmIds[y]);
}
}
return extraParameters;
}
@Override
public boolean isSubscribed() throws InternalException, CloudException {
APITrace.begin(getProvider(), "isSubscribedVirtualMachine");
try {
Map<String, String> parameters = getProvider().getStandardParameters(getProvider().getContext(), EC2Method.DESCRIBE_INSTANCES);
EC2Method method = new EC2Method(getProvider(), getProvider().getEc2Url(), parameters);
try {
method.invoke();
return true;
} catch( EC2Exception e ) {
if( e.getStatus() == HttpServletResponse.SC_UNAUTHORIZED || e.getStatus() == HttpServletResponse.SC_FORBIDDEN ) {
return false;
}
String code = e.getCode();
if( code != null && code.equals("SignatureDoesNotMatch") ) {
return false;
}
logger.warn(e.getSummary());
throw new CloudException(e);
}
} finally {
APITrace.end();
}
}
@Override
public @Nonnull Iterable<VirtualMachineProduct> listProducts(Architecture architecture) throws InternalException, CloudException {
ProviderContext ctx = getProvider().getContext();
if( ctx == null ) {
throw new CloudException("No context was set for this request");
}
Cache<VirtualMachineProduct> cache = Cache.getInstance(getProvider(), "products" + architecture.name(), VirtualMachineProduct.class, CacheLevel.REGION, new TimePeriod<Day>(1, TimePeriod.DAY));
Iterable<VirtualMachineProduct> products = cache.get(ctx);
if( products == null ) {
ArrayList<VirtualMachineProduct> list = new ArrayList<VirtualMachineProduct>();
try {
InputStream input = EC2Instance.class.getResourceAsStream("/org/dasein/cloud/aws/vmproducts.json");
if( input != null ) {
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder json = new StringBuilder();
String line;
while( ( line = reader.readLine() ) != null ) {
json.append(line);
json.append("\n");
}
JSONArray arr = new JSONArray(json.toString());
JSONObject toCache = null;
for( int i = 0; i < arr.length(); i++ ) {
JSONObject productSet = arr.getJSONObject(i);
String cloud, providerName;
if( productSet.has("cloud") ) {
cloud = productSet.getString("cloud");
} else {
continue;
}
if( productSet.has("provider") ) {
providerName = productSet.getString("provider");
} else {
continue;
}
if( !productSet.has("products") ) {
continue;
}
if( toCache == null || ( providerName.equals("AWS") && cloud.equals("AWS") ) ) {
toCache = productSet;
}
if( providerName.equalsIgnoreCase(getProvider().getProviderName()) && cloud.equalsIgnoreCase(getProvider().getCloudName()) ) {
toCache = productSet;
break;
}
}
if( toCache == null ) {
logger.warn("No products were defined");
return Collections.emptyList();
}
JSONArray plist = toCache.getJSONArray("products");
for( int i = 0; i < plist.length(); i++ ) {
JSONObject product = plist.getJSONObject(i);
boolean supported = false;
if( product.has("architectures") ) {
JSONArray architectures = product.getJSONArray("architectures");
for( int j = 0; j < architectures.length(); j++ ) {
String a = architectures.getString(j);
if( architecture.name().equals(a) ) {
supported = true;
break;
}
}
}
if( !supported ) {
continue;
}
if( product.has("excludesRegions") ) {
JSONArray regions = product.getJSONArray("excludesRegions");
for( int j = 0; j < regions.length(); j++ ) {
String r = regions.getString(j);
if( r.equals(ctx.getRegionId()) ) {
supported = false;
break;
}
}
}
if( !supported ) {
continue;
}
VirtualMachineProduct prd = toProduct(product);
if( prd != null ) {
list.add(prd);
}
}
} else {
logger.warn("No standard products resource exists for /org/dasein/cloud/aws/vmproducts.json");
}
input = EC2Instance.class.getResourceAsStream("/org/dasein/cloud/aws/vmproducts-custom.json");
if( input != null ) {
ArrayList<VirtualMachineProduct> customList = new ArrayList<VirtualMachineProduct>();
TreeSet<String> discard = new TreeSet<String>();
boolean discardAll = false;
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder json = new StringBuilder();
String line;
while( ( line = reader.readLine() ) != null ) {
json.append(line);
json.append("\n");
}
JSONArray arr = new JSONArray(json.toString());
JSONObject toCache = null;
for( int i = 0; i < arr.length(); i++ ) {
JSONObject listing = arr.getJSONObject(i);
String cloud, providerName, endpoint = null;
if( listing.has("cloud") ) {
cloud = listing.getString("cloud");
} else {
continue;
}
if( listing.has("provider") ) {
providerName = listing.getString("provider");
} else {
continue;
}
if( listing.has("endpoint") ) {
endpoint = listing.getString("endpoint");
}
if( !cloud.equals(getProvider().getCloudName()) || !providerName.equals(getProvider().getProviderName()) ) {
continue;
}
if( endpoint != null && endpoint.equals(ctx.getEndpoint()) ) {
toCache = listing;
break;
}
if( endpoint == null && toCache == null ) {
toCache = listing;
}
}
if( toCache != null ) {
if( toCache.has("discardDefaults") ) {
discardAll = toCache.getBoolean("discardDefaults");
}
if( toCache.has("discard") ) {
JSONArray dlist = toCache.getJSONArray("discard");
for( int i = 0; i < dlist.length(); i++ ) {
discard.add(dlist.getString(i));
}
}
if( toCache.has("products") ) {
JSONArray plist = toCache.getJSONArray("products");
for( int i = 0; i < plist.length(); i++ ) {
JSONObject product = plist.getJSONObject(i);
boolean supported = false;
if( product.has("architectures") ) {
JSONArray architectures = product.getJSONArray("architectures");
for( int j = 0; j < architectures.length(); j++ ) {
String a = architectures.getString(j);
if( architecture.name().equals(a) ) {
supported = true;
break;
}
}
}
if( !supported ) {
continue;
}
if( product.has("excludesRegions") ) {
JSONArray regions = product.getJSONArray("excludesRegions");
for( int j = 0; j < regions.length(); j++ ) {
String r = regions.getString(j);
if( r.equals(ctx.getRegionId()) ) {
supported = false;
break;
}
}
}
if( !supported ) {
continue;
}
VirtualMachineProduct prd = toProduct(product);
if( prd != null ) {
customList.add(prd);
}
}
}
if( !discardAll ) {
for( VirtualMachineProduct product : list ) {
if( !discard.contains(product.getProviderProductId()) ) {
customList.add(product);
}
}
}
list = customList;
}
}
products = list;
cache.put(ctx, products);
} catch( IOException e ) {
throw new InternalException(e);
} catch( JSONException e ) {
throw new InternalException(e);
}
}
return products;
}
private String guess(String privateDnsAddress) {
String dnsAddress = privateDnsAddress;
String[] parts = dnsAddress.split("\\.");
if( parts != null && parts.length > 1 ) {
dnsAddress = parts[0];
}
if( dnsAddress.startsWith("ip-") ) {
dnsAddress = dnsAddress.replace('-', '.');
return dnsAddress.substring(3);
}
return null;
}
@Override
public @Nonnull VirtualMachine launch(@Nonnull VMLaunchOptions cfg) throws CloudException, InternalException {
APITrace.begin(getProvider(), "launchVM");
try {
ProviderContext ctx = getProvider().getContext();
if( ctx == null ) {
throw new CloudException("No context was established for this request");
}
MachineImage img = getProvider().getComputeServices().getImageSupport().getMachineImage(cfg.getMachineImageId());
if( img == null ) {
throw new AWSResourceNotFoundException("No such machine image: " + cfg.getMachineImageId());
}
Map<String, String> parameters = getProvider().getStandardParameters(getProvider().getContext(), EC2Method.RUN_INSTANCES);
String ramdiskImage = (String) cfg.getMetaData().get("ramdiskImageId"), kernelImage = (String) cfg.getMetaData().get("kernelImageId");
EC2Method method;
NodeList blocks;
Document doc;
parameters.put("ImageId", cfg.getMachineImageId());
parameters.put("MinCount", "1");
parameters.put("MaxCount", "1");
parameters.put("InstanceType", cfg.getStandardProductId());
if( ramdiskImage != null ) {
parameters.put("ramdiskId", ramdiskImage);
}
if( kernelImage != null ) {
parameters.put("kernelId", kernelImage);
}
if( cfg.getRoleId() != null ) {
parameters.put("IamInstanceProfile.Arn", cfg.getRoleId());
}
if( cfg.getUserData() != null ) {
try {
parameters.put("UserData", Base64.encodeBase64String(cfg.getUserData().getBytes("utf-8")));
} catch( UnsupportedEncodingException e ) {
throw new InternalException(e);
}
}
if( cfg.isPreventApiTermination() ) {
parameters.put("DisableApiTermination", "true");
}
if( cfg.getDataCenterId() != null ) {
parameters.put("Placement.AvailabilityZone", cfg.getDataCenterId());
} else if( cfg.getVolumes().length > 0 ) {
String dc = null;
for( VolumeAttachment a : cfg.getVolumes() ) {
if( a.volumeToCreate != null ) {
dc = a.volumeToCreate.getDataCenterId();
if( dc != null ) {
break;
}
}
}
if( dc != null ) {
cfg.inDataCenter(dc);
}
}
if( cfg.getBootstrapKey() != null ) {
parameters.put("KeyName", cfg.getBootstrapKey());
}
if( getProvider().getEC2Provider().isAWS() ) {
parameters.put("Monitoring.Enabled", String.valueOf(cfg.isExtendedAnalytics()));
}
final ArrayList<VolumeAttachment> existingVolumes = new ArrayList<VolumeAttachment>();
TreeSet<String> deviceIds = new TreeSet<String>();
if( cfg.isIoOptimized() ) {
parameters.put("EbsOptimized", "true");
}
if( cfg.getVolumes().length > 0 ) {
Iterable<String> possibles = getProvider().getComputeServices().getVolumeSupport().listPossibleDeviceIds(img.getPlatform());
int i = 1;
for( VolumeAttachment a : cfg.getVolumes() ) {
if( a.deviceId != null ) {
deviceIds.add(a.deviceId);
} else if( a.volumeToCreate != null && a.volumeToCreate.getDeviceId() != null ) {
deviceIds.add(a.volumeToCreate.getDeviceId());
a.deviceId = a.volumeToCreate.getDeviceId();
}
}
for( VolumeAttachment a : cfg.getVolumes() ) {
if( a.deviceId == null ) {
for( String id : possibles ) {
if( !deviceIds.contains(id) ) {
a.deviceId = id;
deviceIds.add(id);
}
}
if( a.deviceId == null ) {
throw new InternalException("Unable to identify a device ID for volume");
}
}
if( a.existingVolumeId == null ) {
parameters.put("BlockDeviceMapping." + i + ".DeviceName", a.deviceId);
VolumeProduct prd = getProvider().getComputeServices().getVolumeSupport().getVolumeProduct(a.volumeToCreate.getVolumeProductId());
parameters.put("BlockDeviceMapping." + i + ".Ebs.VolumeType", prd.getProviderProductId());
if( a.volumeToCreate.getIops() > 0 ) {
parameters.put("BlockDeviceMapping." + i + ".Ebs.Iops", String.valueOf(a.volumeToCreate.getIops()));
}
if( a.volumeToCreate.getSnapshotId() != null ) {
parameters.put("BlockDeviceMapping." + i + ".Ebs.SnapshotId", a.volumeToCreate.getSnapshotId());
} else {
parameters.put("BlockDeviceMapping." + i + ".Ebs.VolumeSize", String.valueOf(a.volumeToCreate.getVolumeSize().getQuantity().intValue()));
}
i++;
} else {
existingVolumes.add(a);
}
}
}
if( cfg.getSubnetId() == null ) {
String[] ids = cfg.getFirewallIds();
if( ids.length > 0 ) {
int i = 1;
for( String id : ids ) {
parameters.put("SecurityGroupId." + ( i++ ), id);
}
}
}
else if( cfg.getNetworkInterfaces() != null && cfg.getNetworkInterfaces().length > 0 ) {
VMLaunchOptions.NICConfig[] nics = cfg.getNetworkInterfaces();
int i = 1;
for( VMLaunchOptions.NICConfig c : nics ) {
parameters.put("NetworkInterface." + i + ".DeviceIndex", String.valueOf(i));
// this only applies for the first NIC
if( i == 1 ) {
parameters.put("NetworkInterface.1.AssociatePublicIpAddress", String.valueOf(cfg.isAssociatePublicIpAddress()));
}
if( c.nicId == null ) {
parameters.put("NetworkInterface." + i + ".SubnetId", c.nicToCreate.getSubnetId());
parameters.put("NetworkInterface." + i + ".Description", c.nicToCreate.getDescription());
if( c.nicToCreate.getIpAddress() != null ) {
parameters.put("NetworkInterface." + i + ".PrivateIpAddress", c.nicToCreate.getIpAddress());
}
if( c.nicToCreate.getFirewallIds().length > 0 ) {
int j = 1;
for( String id : c.nicToCreate.getFirewallIds() ) {
parameters.put("NetworkInterface." + i + ".SecurityGroupId." + j, id);
j++;
}
}
} else {
parameters.put("NetworkInterface." + i + ".NetworkInterfaceId", c.nicId);
}
i++;
}
} else {
parameters.put("NetworkInterface.1.DeviceIndex", "0");
parameters.put("NetworkInterface.1.SubnetId", cfg.getSubnetId());
parameters.put("NetworkInterface.1.AssociatePublicIpAddress", String.valueOf(cfg.isAssociatePublicIpAddress()));
if( cfg.getPrivateIp() != null ) {
parameters.put("NetworkInterface.1.PrivateIpAddress", cfg.getPrivateIp());
}
int securityGroupIndex = 1;
for( String id : cfg.getFirewallIds() ) {
parameters.put("NetworkInterface.1.SecurityGroupId." + securityGroupIndex, id);
securityGroupIndex++;
}
}
method = new EC2Method(getProvider(), getProvider().getEc2Url(), parameters);
try {
doc = method.invoke();
} catch( EC2Exception e ) {
String code = e.getCode();
if( code != null && code.equals("InsufficientInstanceCapacity") ) {
return null;
}
logger.error(e.getSummary());
throw new CloudException(e);
}
blocks = doc.getElementsByTagName("instancesSet");
VirtualMachine server = null;
for( int i = 0; i < blocks.getLength(); i++ ) {
NodeList instances = blocks.item(i).getChildNodes();
for( int j = 0; j < instances.getLength(); j++ ) {
Node instance = instances.item(j);
if( instance.getNodeName().equals("item") ) {
server = toVirtualMachine(ctx, instance, new ArrayList<IpAddress>() /* can't be an elastic IP */);
if( server != null ) {
break;
}
}
}
}
if( server != null ) {
// wait for EC2 to figure out the server exists
VirtualMachine copy = getVirtualMachine(server.getProviderVirtualMachineId());
if( copy == null ) {
long timeout = System.currentTimeMillis() + CalendarWrapper.MINUTE;
while( timeout > System.currentTimeMillis() ) {
try {
Thread.sleep(5000L);
} catch( InterruptedException ignore ) {
}
try {
copy = getVirtualMachine(server.getProviderVirtualMachineId());
} catch( Throwable ignore ) {
}
if( copy != null ) {
break;
}
}
}
}
if( cfg.isIpForwardingAllowed() ) {
enableIpForwarding(server.getProviderVirtualMachineId());
}
if( cfg.isIpForwardingAllowed() ) {
enableIpForwarding(server.getProviderVirtualMachineId());
}
if( server != null && cfg.getBootstrapKey() != null ) {
try {
final String sid = server.getProviderVirtualMachineId();
try {
Callable<String> callable = new GetPassCallable(
sid,
getProvider().getStandardParameters(getProvider().getContext(), EC2Method.GET_PASSWORD_DATA),
getProvider(),
getProvider().getEc2Url()
);
String password = callable.call();
if( password == null ) {
server.setRootPassword(null);
server.setPasswordCallback(callable);
} else {
server.setRootPassword(password);
}
server.setPlatform(Platform.WINDOWS);
} catch( CloudException e ) {
logger.warn(e.getMessage());
}
} catch( Throwable t ) {
logger.warn("Unable to retrieve password for " + server.getProviderVirtualMachineId() + ", Let's hope it's Unix: " + t.getMessage());
}
}
Map<String, Object> meta = cfg.getMetaData();
Tag[] toCreate;
int i = 0;
if( meta.isEmpty() ) {
toCreate = new Tag[2];
} else {
int count = 0;
for( Map.Entry<String, Object> entry : meta.entrySet() ) {
if( entry.getKey().equalsIgnoreCase("name") || entry.getKey().equalsIgnoreCase("description") ) {
continue;
}
count++;
}
toCreate = new Tag[count + 2];
for( Map.Entry<String, Object> entry : meta.entrySet() ) {
if( entry.getKey().equalsIgnoreCase("name") || entry.getKey().equalsIgnoreCase("description") ) {
continue;
}
toCreate[i++] = new Tag(entry.getKey(), entry.getValue().toString());
}
}
Tag t = new Tag();
t.setKey("Name");
t.setValue(cfg.getFriendlyName());
toCreate[i++] = t;
t = new Tag();
t.setKey("Description");
t.setValue(cfg.getDescription());
toCreate[i] = t;
getProvider().createTags(server.getProviderVirtualMachineId(), toCreate);
if( !existingVolumes.isEmpty() ) {
final VirtualMachine vm = server;
getProvider().hold();
Thread thread = new Thread() {
public void run() {
try {
for( VolumeAttachment a : existingVolumes ) {
try {
getProvider().getComputeServices().getVolumeSupport().attach(a.existingVolumeId, vm.getProviderMachineImageId(), a.deviceId);
} catch( Throwable t ) {
}
}
} finally {
getProvider().release();
}
}
};
thread.setName("Volume Mounter for " + server);
thread.start();
}
return server;
} finally {
APITrace.end();
}
}
private void enableIpForwarding(final String instanceId) throws CloudException {
Thread t = new Thread() {
public void run() {
APITrace.begin(getProvider(), "enableIpForwarding");
long timeout = System.currentTimeMillis() + CalendarWrapper.MINUTE;
while( timeout > System.currentTimeMillis() ) {
try {
Map<String, String> params = getProvider().getStandardParameters(getProvider().getContext(), EC2Method.MODIFY_INSTANCE_ATTRIBUTE);
EC2Method m;
params.put("InstanceId", instanceId);
params.put("SourceDestCheck.Value", "false");
m = new EC2Method(getProvider(), getProvider().getEc2Url(), params);
m.invoke();
return;
} catch( EC2Exception ex ) {
if( ex.getStatus() != 404 ) {
logger.error("Unable to modify instance attributes on " + instanceId + ".", ex);
return;
}
} catch( Throwable ex ) {
logger.error("Unable to modify instance attributes on " + instanceId + ".", ex);
return;
} finally {
APITrace.end();
}
try {
Thread.sleep(5000L);
} catch( InterruptedException ignore ) {
}
}
}
};
t.setName(EC2Method.MODIFY_INSTANCE_ATTRIBUTE + " thread");
t.setDaemon(true);
t.start();
}
@Override
public @Nonnull Iterable<ResourceStatus> listVirtualMachineStatus() throws InternalException, CloudException {
APITrace.begin(getProvider(), "listVirtualMachineStatus");
try {
ProviderContext ctx = getProvider().getContext();
if( ctx == null ) {
throw new CloudException("No context was established for this request");
}
Map<String, String> parameters = getProvider().getStandardParameters(getProvider().getContext(), EC2Method.DESCRIBE_INSTANCES);
EC2Method method = new EC2Method(getProvider(), getProvider().getEc2Url(), parameters);
ArrayList<ResourceStatus> list = new ArrayList<ResourceStatus>();
NodeList blocks;
Document doc;
try {
doc = method.invoke();
} catch( EC2Exception e ) {
logger.error(e.getSummary());
throw new CloudException(e);
}
blocks = doc.getElementsByTagName("instancesSet");
for( int i = 0; i < blocks.getLength(); i++ ) {
NodeList instances = blocks.item(i).getChildNodes();
for( int j = 0; j < instances.getLength(); j++ ) {
Node instance = instances.item(j);
if( instance.getNodeName().equals("item") ) {
ResourceStatus status = toStatus(instance);
if( status != null ) {
list.add(status);
}
}
}
}
return list;
} finally {
APITrace.end();
}
}
@Override
public @Nonnull Iterable<VirtualMachine> listVirtualMachines() throws InternalException, CloudException {
return listVirtualMachinesWithParams(null, null);
}
@Override
public @Nonnull Iterable<VirtualMachine> listVirtualMachines(@Nullable VMFilterOptions options) throws InternalException, CloudException {
Map<String, String> filterParameters = createFilterParametersFrom(options);
if( options.getRegex() != null ) {
// still have to match on regex
options = VMFilterOptions.getInstance(false, options.getRegex());
}
else {
// nothing else to match on
options = null;
}
return listVirtualMachinesWithParams(filterParameters, options);
}
private Map<String, String> createFilterParametersFrom(@Nullable VMFilterOptions options) {
if( options == null || options.isMatchesAny() ) {
return Collections.emptyMap();
}
// tag advantage of EC2-based filtering if we can...
Map<String, String> extraParameters = new HashMap<String, String>();
int filterIndex = 0;
if( options.getTags() != null && !options.getTags().isEmpty() ) {
getProvider().putExtraParameters(extraParameters, getProvider().getTagFilterParams(options.getTags(), filterIndex));
}
if( options.getVmStates() != null ) {
getProvider().addFilterParameter(extraParameters, filterIndex++, "instance-state-name", options.getVmStates());
}
return extraParameters;
}
private @Nonnull Iterable<VirtualMachine> listVirtualMachinesWithParams(Map<String, String> extraParameters, @Nullable VMFilterOptions options) throws InternalException, CloudException {
APITrace.begin(getProvider(), "listVirtualMachines");
try {
ProviderContext ctx = getProvider().getContext();
if( ctx == null ) {
throw new CloudException("No context was established for this request");
}
Future<Iterable<IpAddress>> ipPoolFuture = null;
Iterable<IpAddress> addresses;
if( getProvider().hasNetworkServices() ) {
NetworkServices services = getProvider().getNetworkServices();
if( services != null ) {
if( services.hasIpAddressSupport() ) {
IpAddressSupport support = services.getIpAddressSupport();
if( support != null ) {
ipPoolFuture = support.listIpPoolConcurrently(IPVersion.IPV4, false);
}
}
}
}
Map<String, String> parameters = getProvider().getStandardParameters(getProvider().getContext(), EC2Method.DESCRIBE_INSTANCES);
getProvider().putExtraParameters(parameters, extraParameters);
EC2Method method = new EC2Method(getProvider(), getProvider().getEc2Url(), parameters);
ArrayList<VirtualMachine> list = new ArrayList<VirtualMachine>();
NodeList blocks;
Document doc;
try {
doc = method.invoke();
} catch( EC2Exception e ) {
logger.error(e.getSummary());
throw new CloudException(e);
}
blocks = doc.getElementsByTagName("instancesSet");
for( int i = 0; i < blocks.getLength(); i++ ) {
NodeList instances = blocks.item(i).getChildNodes();
for( int j = 0; j < instances.getLength(); j++ ) {
Node instance = instances.item(j);
if( instance.getNodeName().equals("item") ) {
try {
if( ipPoolFuture != null ) {
addresses = ipPoolFuture.get(30, TimeUnit.SECONDS);
}
else {
addresses = Collections.emptyList();
}
} catch( InterruptedException e ) {
logger.error(e.getMessage());
addresses = Collections.emptyList();
} catch( ExecutionException e ) {
logger.error(e.getMessage());
addresses = Collections.emptyList();
} catch( TimeoutException e ) {
logger.error(e.getMessage());
addresses = Collections.emptyList();
}
VirtualMachine vm = toVirtualMachine(ctx, instance, addresses);
if( options == null || options.matches(vm) ) {
list.add(vm);
}
}
}
}
return list;
} finally {
APITrace.end();
}
}
@Override
public void pause(@Nonnull String vmId) throws InternalException, CloudException {
throw new OperationNotSupportedException("Pause/unpause not supported by the EC2 API");
}
@Override
public @Nonnull String[] mapServiceAction(@Nonnull ServiceAction action) {
if( action.equals(VirtualMachineSupport.ANY) ) {
return new String[]{EC2Method.EC2_PREFIX + "*"};
} else if( action.equals(VirtualMachineSupport.BOOT) ) {
return new String[]{EC2Method.EC2_PREFIX + EC2Method.START_INSTANCES};
} else if( action.equals(VirtualMachineSupport.CLONE) ) {
return new String[0];
} else if( action.equals(VirtualMachineSupport.CREATE_VM) ) {
return new String[]{EC2Method.EC2_PREFIX + EC2Method.RUN_INSTANCES};
} else if( action.equals(VirtualMachineSupport.GET_VM) || action.equals(VirtualMachineSupport.LIST_VM) ) {
return new String[]{EC2Method.EC2_PREFIX + EC2Method.DESCRIBE_INSTANCES};
} else if( action.equals(VirtualMachineSupport.PAUSE) ) {
return new String[]{EC2Method.EC2_PREFIX + EC2Method.STOP_INSTANCES};
} else if( action.equals(VirtualMachineSupport.REBOOT) ) {
return new String[]{EC2Method.EC2_PREFIX + EC2Method.REBOOT_INSTANCES};
} else if( action.equals(VirtualMachineSupport.REMOVE_VM) ) {
return new String[]{EC2Method.EC2_PREFIX + EC2Method.TERMINATE_INSTANCES};
} else if( action.equals(VirtualMachineSupport.TOGGLE_ANALYTICS) ) {
return new String[]{EC2Method.EC2_PREFIX + EC2Method.MONITOR_INSTANCES};
} else if( action.equals(VirtualMachineSupport.VIEW_ANALYTICS) ) {
return new String[]{EC2Method.EC2_PREFIX + EC2Method.GET_METRIC_STATISTICS};
} else if( action.equals(VirtualMachineSupport.VIEW_CONSOLE) ) {
return new String[]{EC2Method.EC2_PREFIX + EC2Method.GET_CONSOLE_OUTPUT};
}
return new String[0];
}
@Override
public void stop(@Nonnull String instanceId, boolean force) throws InternalException, CloudException {
APITrace.begin(getProvider(), "stopVM");
try {
VirtualMachine vm = getVirtualMachine(instanceId);
if( vm == null ) {
throw new CloudException("No such instance: " + instanceId);
}
if( !vm.isPersistent() ) {
throw new OperationNotSupportedException("Instances backed by ephemeral drives are not start/stop capable");
}
Map<String, String> parameters = getProvider().getStandardParameters(getProvider().getContext(), EC2Method.STOP_INSTANCES);
EC2Method method;
parameters.put("InstanceId.1", instanceId);
if( force ) {
parameters.put("Force", "true");
}
method = new EC2Method(getProvider(), getProvider().getEc2Url(), parameters);
try {
method.invoke();
} catch( EC2Exception e ) {
logger.error(e.getSummary());
throw new CloudException(e);
}
} finally {
APITrace.end();
}
}
@Override
public void reboot(@Nonnull String instanceId) throws CloudException, InternalException {
APITrace.begin(getProvider(), "rebootVM");
try {
Map<String, String> parameters = getProvider().getStandardParameters(getProvider().getContext(), EC2Method.REBOOT_INSTANCES);
EC2Method method;
parameters.put("InstanceId.1", instanceId);
method = new EC2Method(getProvider(), getProvider().getEc2Url(), parameters);
try {
method.invoke();
} catch( EC2Exception e ) {
logger.error(e.getSummary());
throw new CloudException(e);
}
} finally {
APITrace.end();
}
}
@Override
public void resume(@Nonnull String vmId) throws CloudException, InternalException {
throw new OperationNotSupportedException("Suspend/resume not supported by the EC2 API");
}
@Override
public void suspend(@Nonnull String vmId) throws CloudException, InternalException {
throw new OperationNotSupportedException("Suspend/resume not supported by the EC2 API");
}
@Override
public void terminate(@Nonnull String instanceId, @Nullable String explanation) throws InternalException, CloudException {
APITrace.begin(getProvider(), "terminateVM");
try {
Map<String, String> parameters = getProvider().getStandardParameters(getProvider().getContext(), EC2Method.TERMINATE_INSTANCES);
EC2Method method;
parameters.put("InstanceId.1", instanceId);
method = new EC2Method(getProvider(), getProvider().getEc2Url(), parameters);
try {
method.invoke();
} catch( EC2Exception e ) {
logger.error(e.getSummary());
throw new CloudException(e);
}
} finally {
APITrace.end();
}
}
@Override
public void unpause(@Nonnull String vmId) throws CloudException, InternalException {
throw new OperationNotSupportedException("Pause/unpause not supported by the EC2 API");
}
private @Nullable ResourceStatus toStatus(@Nullable Node instance) throws CloudException {
if( instance == null ) {
return null;
}
NodeList attrs = instance.getChildNodes();
VmState state = VmState.PENDING;
String vmId = null;
for( int i = 0; i < attrs.getLength(); i++ ) {
Node attr = attrs.item(i);
String name;
name = attr.getNodeName();
if( name.equals("instanceId") ) {
vmId = attr.getFirstChild().getNodeValue().trim();
} else if( name.equals("instanceState") ) {
NodeList details = attr.getChildNodes();
for( int j = 0; j < details.getLength(); j++ ) {
Node detail = details.item(j);
name = detail.getNodeName();
if( name.equals("name") ) {
String value = detail.getFirstChild().getNodeValue().trim();
state = getServerState(value);
}
}
}
}
if( vmId == null ) {
return null;
}
return new ResourceStatus(vmId, state);
}
private @Nullable VmStatus toVmStatus(@Nonnull String status ) {
// ok | impaired | insufficient-data | not-applicable
if( status.equalsIgnoreCase("ok") ) return VmStatus.OK;
else if( status.equalsIgnoreCase("impaired") ) {
return VmStatus.IMPAIRED;
}
else if( status.equalsIgnoreCase("insufficient-data") ) {
return VmStatus.INSUFFICIENT_DATA;
}
else if( status.equalsIgnoreCase("not-applicable") ) {
return VmStatus.NOT_APPLICABLE;
}
else {
return VmStatus.INSUFFICIENT_DATA;
}
}
private @Nullable VirtualMachine toVirtualMachine(@Nonnull ProviderContext ctx, @Nullable Node instance, @Nonnull Iterable<IpAddress> addresses) throws CloudException {
if( instance == null ) {
return null;
}
String rootDeviceName = null;
NodeList attrs = instance.getChildNodes();
VirtualMachine server = new VirtualMachine();
server.setPersistent(false);
server.setProviderOwnerId(ctx.getAccountNumber());
server.setCurrentState(VmState.PENDING);
server.setName(null);
server.setDescription(null);
for( int i = 0; i < attrs.getLength(); i++ ) {
Node attr = attrs.item(i);
String name;
name = attr.getNodeName();
if( name.equals("instanceId") ) {
String value = attr.getFirstChild().getNodeValue().trim();
server.setProviderVirtualMachineId(value);
} else if( name.equals("architecture") ) {
String value = attr.getFirstChild().getNodeValue().trim();
Architecture architecture;
if( value.equalsIgnoreCase("i386") ) {
architecture = Architecture.I32;
} else {
architecture = Architecture.I64;
}
server.setArchitecture(architecture);
} else if( name.equals("imageId") ) {
String value = attr.getFirstChild().getNodeValue().trim();
server.setProviderMachineImageId(value);
} else if( name.equals("kernelId") ) {
String value = attr.getFirstChild().getNodeValue().trim();
server.setTag("kernelImageId", value);
server.setProviderKernelImageId(value);
} else if( name.equals("ramdiskId") ) {
String value = attr.getFirstChild().getNodeValue().trim();
server.setTag("ramdiskImageId", value);
server.setProviderRamdiskImageId(value);
} else if( name.equalsIgnoreCase("subnetId") ) {
server.setProviderSubnetId(attr.getFirstChild().getNodeValue().trim());
} else if( name.equalsIgnoreCase("vpcId") ) {
server.setProviderVlanId(attr.getFirstChild().getNodeValue().trim());
} else if( name.equals("instanceState") ) {
NodeList details = attr.getChildNodes();
for( int j = 0; j < details.getLength(); j++ ) {
Node detail = details.item(j);
name = detail.getNodeName();
if( name.equals("name") ) {
String value = detail.getFirstChild().getNodeValue().trim();
server.setCurrentState(getServerState(value));
}
}
} else if( name.equals("privateDnsName") ) {
if( attr.hasChildNodes() ) {
String value = attr.getFirstChild().getNodeValue();
RawAddress[] addrs = server.getPrivateAddresses();
server.setPrivateDnsAddress(value);
if( addrs == null || addrs.length < 1 ) {
value = guess(value);
if( value != null ) {
server.setPrivateAddresses(new RawAddress(value));
}
}
}
} else if( name.equals("dnsName") ) {
if( attr.hasChildNodes() ) {
String value = attr.getFirstChild().getNodeValue();
RawAddress[] addrs = server.getPublicAddresses();
server.setPublicDnsAddress(value);
}
} else if( name.equals("privateIpAddress") ) {
if( attr.hasChildNodes() ) {
String value = attr.getFirstChild().getNodeValue();
server.setPrivateAddresses(new RawAddress(value));
}
} else if( name.equals("ipAddress") ) {
if( attr.hasChildNodes() ) {
String value = attr.getFirstChild().getNodeValue();
server.setPublicAddresses(new RawAddress(value));
for( IpAddress addr : addresses ) {
if( value.equals(addr.getRawAddress().getIpAddress()) ) {
server.setProviderAssignedIpAddressId(addr.getProviderIpAddressId());
break;
}
}
}
} else if( name.equals("rootDeviceType") ) {
if( attr.hasChildNodes() ) {
server.setPersistent(attr.getFirstChild().getNodeValue().equalsIgnoreCase("ebs"));
}
} else if( name.equals("tagSet") ) {
Map<String, String> tags = getProvider().getTagsFromTagSet(attr);
if( tags != null && tags.size() > 0 ) {
server.setTags(tags);
for( Map.Entry<String, String> entry : tags.entrySet() ) {
if( entry.getKey().equalsIgnoreCase("name") ) {
server.setName(entry.getValue());
} else if( entry.getKey().equalsIgnoreCase("description") ) {
server.setDescription(entry.getValue());
}
}
}
} else if( name.equals("instanceType") ) {
String value = attr.getFirstChild().getNodeValue().trim();
server.setProductId(value);
} else if( name.equals("launchTime") ) {
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
fmt.setCalendar(UTC_CALENDAR);
String value = attr.getFirstChild().getNodeValue().trim();
try {
server.setLastBootTimestamp(fmt.parse(value).getTime());
server.setCreationTimestamp(server.getLastBootTimestamp());
} catch( ParseException e ) {
logger.error(e);
throw new CloudException(e);
}
} else if( name.equals("platform") ) {
if( attr.hasChildNodes() ) {
Platform platform = Platform.guess(attr.getFirstChild().getNodeValue());
if( platform.equals(Platform.UNKNOWN) ) {
platform = Platform.UNIX;
}
server.setPlatform(platform);
}
} else if( name.equals("placement") ) {
NodeList details = attr.getChildNodes();
for( int j = 0; j < details.getLength(); j++ ) {
Node detail = details.item(j);
name = detail.getNodeName();
if( name.equals("availabilityZone") ) {
if( detail.hasChildNodes() ) {
String value = detail.getFirstChild().getNodeValue().trim();
server.setProviderDataCenterId(value);
}
}
}
} else if( name.equals("networkInterfaceSet") ) {
ArrayList<String> networkInterfaceIds = new ArrayList<String>();
if( attr.hasChildNodes() ) {
NodeList items = attr.getChildNodes();
for( int j = 0; j < items.getLength(); j++ ) {
Node item = items.item(j);
if( item.getNodeName().equals("item") && item.hasChildNodes() ) {
NodeList parts = item.getChildNodes();
String networkInterfaceId = null;
for( int k = 0; k < parts.getLength(); k++ ) {
Node part = parts.item(k);
if( part.getNodeName().equalsIgnoreCase("networkInterfaceId") ) {
if( part.hasChildNodes() ) {
networkInterfaceId = part.getFirstChild().getNodeValue().trim();
}
}
}
if( networkInterfaceId != null ) {
networkInterfaceIds.add(networkInterfaceId);
}
}
}
}
if( networkInterfaceIds.size() > 0 ) {
server.setProviderNetworkInterfaceIds(networkInterfaceIds.toArray(new String[networkInterfaceIds.size()]));
}
/*
[FIXME?] TODO: Really networkInterfaceSet needs to be own type/resource
Example:
<networkInterfaceSet>
<item>
<networkInterfaceId>eni-1a2b3c4d</networkInterfaceId>
<subnetId>subnet-1a2b3c4d</subnetId>
<vpcId>vpc-1a2b3c4d</vpcId>
<description>Primary network interface</description>
<ownerId>111122223333</ownerId>
<status>in-use</status>
<macAddress>1b:2b:3c:4d:5e:6f</macAddress>
<privateIpAddress>10.0.0.12</privateIpAddress>
<sourceDestCheck>true</sourceDestCheck>
<groupSet>
<item>
<groupId>sg-1a2b3c4d</groupId>
<groupName>my-security-group</groupName>
</item>
</groupSet>
<attachment>
<attachmentId>eni-attach-1a2b3c4d</attachmentId>
<deviceIndex>0</deviceIndex>
<status>attached</status>
<attachTime>YYYY-MM-DDTHH:MM:SS+0000</attachTime>
<deleteOnTermination>true</deleteOnTermination>
</attachment>
<association>
<publicIp>198.51.100.63</publicIp>
<ipOwnerId>111122223333</ipOwnerId>
</association>
<privateIpAddressesSet>
<item>
<privateIpAddress>10.0.0.12</privateIpAddress>
<primary>true</primary>
<association>
<publicIp>198.51.100.63</publicIp>
<ipOwnerId>111122223333</ipOwnerId>
</association>
</item>
<item>
<privateIpAddress>10.0.0.14</privateIpAddress>
<primary>false</primary>
<association>
<publicIp>198.51.100.177</publicIp>
<ipOwnerId>111122223333</ipOwnerId>
</association>
</item>
</privateIpAddressesSet>
</item>
</networkInterfaceSet>
*/
} else if( name.equals("keyName") ) {
String value = attr.getFirstChild().getNodeValue().trim();
server.setProviderKeypairId(value);
} else if( name.equals("groupSet") ) {
ArrayList<String> firewalls = new ArrayList<String>();
if( attr.hasChildNodes() ) {
NodeList tags = attr.getChildNodes();
for( int j = 0; j < tags.getLength(); j++ ) {
Node tag = tags.item(j);
if( tag.getNodeName().equals("item") && tag.hasChildNodes() ) {
NodeList parts = tag.getChildNodes();
String groupId = null;
for( int k = 0; k < parts.getLength(); k++ ) {
Node part = parts.item(k);
if( part.getNodeName().equalsIgnoreCase("groupId") ) {
if( part.hasChildNodes() ) {
groupId = part.getFirstChild().getNodeValue().trim();
}
}
}
if( groupId != null ) {
firewalls.add(groupId);
}
}
}
}
if( firewalls.size() > 0 ) {
server.setProviderFirewallIds(firewalls.toArray(new String[firewalls.size()]));
}
} else if( "blockDeviceMapping".equals(name) && attr.hasChildNodes() ) {
List<Volume> volumes = new ArrayList<Volume>();
if( attr.hasChildNodes() ) {
NodeList blockDeviceMapping = attr.getChildNodes();
for( int j = 0; j < blockDeviceMapping.getLength(); j++ ) {
Node bdmItems = blockDeviceMapping.item(j);
if( bdmItems.getNodeName().equals("item") && bdmItems.hasChildNodes() ) {
NodeList items = bdmItems.getChildNodes();
Volume volume = new Volume();
for( int k = 0; k < items.getLength(); k++ ) {
Node item = items.item(k);
String itemNodeName = item.getNodeName();
if( "deviceName".equals(itemNodeName) ) {
volume.setDeviceId(AWSCloud.getTextValue(item));
} else if( "ebs".equals(itemNodeName) ) {
NodeList ebsNodeList = item.getChildNodes();
for( int l = 0; l < ebsNodeList.getLength(); l++ ) {
Node ebsNode = ebsNodeList.item(l);
String ebsNodeName = ebsNode.getNodeName();
if( "volumeId".equals(ebsNodeName) ) {
volume.setProviderVolumeId(AWSCloud.getTextValue(ebsNode));
} else if( "status".equals(ebsNodeName) ) {
volume.setCurrentState(EBSVolume.toVolumeState(ebsNode));
} else if( "deleteOnTermination".equals(ebsNodeName) ) {
volume.setDeleteOnVirtualMachineTermination(AWSCloud.getBooleanValue(ebsNode));
}
}
}
}
if( volume.getDeviceId() != null ) {
volumes.add(volume);
}
}
}
}
if( volumes.size() > 0 ) {
server.setVolumes(volumes.toArray(new Volume[volumes.size()]));
}
} else if( "rootDeviceName".equals(name) && attr.hasChildNodes() ) {
rootDeviceName = AWSCloud.getTextValue(attr);
} else if( "ebsOptimized".equals(name) && attr.hasChildNodes() ) {
server.setIoOptimized(Boolean.valueOf(attr.getFirstChild().getNodeValue()));
} else if( "sourceDestCheck".equals(name) && attr.hasChildNodes() ) {
/**
* note: a value of <sourceDestCheck>true</sourceDestCheck> means this instance cannot
* function as a NAT instance, so we negate the value to indicate if it is allowed
*/
server.setIpForwardingAllowed(!Boolean.valueOf(attr.getFirstChild().getNodeValue()));
} else if( "stateReasonMessage".equals(name) ) {
server.setStateReasonMessage(attr.getFirstChild().getNodeValue().trim());
} else if( "iamInstanceProfile".equals(name) && attr.hasChildNodes() ) {
NodeList details = attr.getChildNodes();
for( int j = 0; j < details.getLength(); j++ ) {
Node detail = details.item(j);
name = detail.getNodeName();
if( name.equals("arn") ) {
if( detail.hasChildNodes() ) {
String value = detail.getFirstChild().getNodeValue().trim();
server.setProviderRoleId(value);
}
}
}
}
}
if( server.getPlatform() == null ) {
server.setPlatform(Platform.UNKNOWN);
}
server.setProviderRegionId(ctx.getRegionId());
if( server.getName() == null ) {
server.setName(server.getProviderVirtualMachineId());
}
if( server.getDescription() == null ) {
server.setDescription(server.getName() + " (" + server.getProductId() + ")");
}
if( server.getArchitecture() == null && server.getProductId() != null ) {
server.setArchitecture(getArchitecture(server.getProductId()));
} else if( server.getArchitecture() == null ) {
server.setArchitecture(Architecture.I64);
}
// find the root device in the volumes list and set boolean value
if( rootDeviceName != null && server.getVolumes() != null ) {
for( Volume volume : server.getVolumes() ) {
if( rootDeviceName.equals(volume.getDeviceId()) ) {
volume.setRootVolume(true);
break;
}
}
}
return server;
}
@Override
public void disableAnalytics(@Nonnull String instanceId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "disableVMAnalytics");
try {
if( getProvider().getEC2Provider().isAWS() || getProvider().getEC2Provider().isEnStratus() ) {
Map<String, String> parameters = getProvider().getStandardParameters(getProvider().getContext(), EC2Method.UNMONITOR_INSTANCES);
EC2Method method;
parameters.put("InstanceId.1", instanceId);
method = new EC2Method(getProvider(), getProvider().getEc2Url(), parameters);
try {
method.invoke();
} catch( EC2Exception e ) {
logger.error(e.getSummary());
throw new CloudException(e);
}
}
} finally {
APITrace.end();
}
}
private @Nullable VirtualMachineProduct toProduct(@Nonnull JSONObject json) throws InternalException {
/*
{
"architectures":["I32"],
"id":"m1.small",
"name":"Small Instance (m1.small)",
"description":"Small Instance (m1.small)",
"cpuCount":1,
"rootVolumeSizeInGb":160,
"ramSizeInMb": 1700
},
*/
VirtualMachineProduct prd = new VirtualMachineProduct();
try {
if( json.has("id") ) {
prd.setProviderProductId(json.getString("id"));
} else {
return null;
}
if( json.has("name") ) {
prd.setName(json.getString("name"));
} else {
prd.setName(prd.getProviderProductId());
}
if( json.has("description") ) {
prd.setDescription(json.getString("description"));
} else {
prd.setDescription(prd.getName());
}
if( json.has("cpuCount") ) {
prd.setCpuCount(json.getInt("cpuCount"));
} else {
prd.setCpuCount(1);
}
if( json.has("rootVolumeSizeInGb") ) {
prd.setRootVolumeSize(new Storage<Gigabyte>(json.getInt("rootVolumeSizeInGb"), Storage.GIGABYTE));
} else {
prd.setRootVolumeSize(new Storage<Gigabyte>(1, Storage.GIGABYTE));
}
if( json.has("ramSizeInMb") ) {
prd.setRamSize(new Storage<Megabyte>(json.getInt("ramSizeInMb"), Storage.MEGABYTE));
} else {
prd.setRamSize(new Storage<Megabyte>(512, Storage.MEGABYTE));
}
if( json.has("standardHourlyRates") ) {
JSONArray rates = json.getJSONArray("standardHourlyRates");
for( int i = 0; i < rates.length(); i++ ) {
JSONObject rate = rates.getJSONObject(i);
if( rate.has("rate") ) {
prd.setStandardHourlyRate((float) rate.getDouble("rate"));
}
}
}
} catch( JSONException e ) {
throw new InternalException(e);
}
return prd;
}
@Override
public void updateTags(@Nonnull String vmId, @Nonnull Tag... tags) throws CloudException, InternalException {
getProvider().createTags(vmId, tags);
}
@Override
public void updateTags(@Nonnull String[] vmIds, @Nonnull Tag... tags) throws CloudException, InternalException {
getProvider().createTags(vmIds, tags);
}
@Override
public void removeTags(@Nonnull String vmId, @Nonnull Tag... tags) throws CloudException, InternalException {
getProvider().removeTags(vmId, tags);
}
@Override
public void removeTags(@Nonnull String[] vmIds, @Nonnull Tag... tags) throws CloudException, InternalException {
getProvider().removeTags(vmIds, tags);
}
}
| src/main/java/org/dasein/cloud/aws/compute/EC2Instance.java | /**
* Copyright (C) 2009-2014 Dell, Inc.
* See annotations for authorship information
*
* ====================================================================
* 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.dasein.cloud.aws.compute;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import org.dasein.cloud.*;
import org.dasein.cloud.aws.AWSCloud;
import org.dasein.cloud.aws.AWSResourceNotFoundException;
import org.dasein.cloud.compute.*;
import org.dasein.cloud.identity.ServiceAction;
import org.dasein.cloud.network.*;
import org.dasein.cloud.util.APITrace;
import org.dasein.cloud.util.Cache;
import org.dasein.cloud.util.CacheLevel;
import org.dasein.util.CalendarWrapper;
import org.dasein.util.uom.storage.Gigabyte;
import org.dasein.util.uom.storage.Megabyte;
import org.dasein.util.uom.storage.Storage;
import org.dasein.util.uom.time.Day;
import org.dasein.util.uom.time.TimePeriod;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.*;
public class EC2Instance extends AbstractVMSupport<AWSCloud> {
static private final Logger logger = Logger.getLogger(EC2Instance.class);
static private final Calendar UTC_CALENDAR = Calendar.getInstance(new SimpleTimeZone(0, "GMT"));
private transient volatile EC2InstanceCapabilities capabilities;
EC2Instance(AWSCloud provider) {
super(provider);
}
@Override
public VirtualMachine alterVirtualMachine(@Nonnull String vmId, @Nonnull VMScalingOptions options) throws InternalException, CloudException {
APITrace.begin(getProvider(), "alterVirtualMachine");
try {
Map<String, String> parameters = getProvider().getStandardParameters(getProvider().getContext(), EC2Method.MODIFY_INSTANCE_ATTRIBUTE);
EC2Method method;
parameters.put("InstanceId", vmId);
parameters.put("InstanceType.Value", options.getProviderProductId());
method = new EC2Method(getProvider(), getProvider().getEc2Url(), parameters);
try {
method.invoke();
} catch( EC2Exception e ) {
logger.error(e.getSummary());
throw new CloudException(e);
} catch( Throwable ex ) {
throw new CloudException(ex);
}
return getVirtualMachine(vmId);
} finally {
APITrace.end();
}
}
@Override
public VirtualMachine modifyInstance(@Nonnull String vmId, @Nonnull String[] firewalls) throws InternalException, CloudException {
APITrace.begin(getProvider(), "alterVirtualMachine");
try {
Map<String, String> parameters = getProvider().getStandardParameters(getProvider().getContext(), EC2Method.MODIFY_INSTANCE_ATTRIBUTE);
EC2Method method;
parameters.put("InstanceId", vmId);
for( int i = 0; i < firewalls.length; i++ ) {
parameters.put("GroupId." + i, firewalls[i]);
}
method = new EC2Method(getProvider(), getProvider().getEc2Url(), parameters);
try {
method.invoke();
} catch( EC2Exception e ) {
logger.error(e.getSummary());
throw new CloudException(e);
} catch( Throwable ex ) {
throw new CloudException(ex);
}
return getVirtualMachine(vmId);
} finally {
APITrace.end();
}
}
@Override
public void start(@Nonnull String instanceId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "startVM");
try {
VirtualMachine vm = getVirtualMachine(instanceId);
if( vm == null ) {
throw new CloudException("No such instance: " + instanceId);
}
if( !vm.isPersistent() ) {
throw new OperationNotSupportedException("Instances backed by ephemeral drives are not start/stop capable");
}
Map<String, String> parameters = getProvider().getStandardParameters(getProvider().getContext(), EC2Method.START_INSTANCES);
EC2Method method;
parameters.put("InstanceId.1", instanceId);
method = new EC2Method(getProvider(), getProvider().getEc2Url(), parameters);
try {
method.invoke();
} catch( EC2Exception e ) {
logger.error(e.getSummary());
throw new CloudException(e);
}
} finally {
APITrace.end();
}
}
static private class Metric implements Comparable<Metric> {
int samples = 0;
long timestamp = -1L;
double minimum = -1.0;
double maximum = 0.0;
double average = 0.0;
public int compareTo(Metric other) {
if( other == this ) {
return 0;
}
return ( new Long(timestamp) ).compareTo(other.timestamp);
}
}
private Set<Metric> calculate(String metric, String unit, String id, boolean idIsVolumeId, long startTimestamp, long endTimestamp) throws CloudException, InternalException {
APITrace.begin(getProvider(), "calculateVMAnalytics");
try {
if( !getProvider().getEC2Provider().isAWS() ) {
return new TreeSet<Metric>();
}
Map<String, String> parameters = getProvider().getStandardCloudWatchParameters(getContext(), EC2Method.GET_METRIC_STATISTICS);
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
fmt.setCalendar(UTC_CALENDAR);
EC2Method method;
NodeList blocks;
Document doc;
parameters.put("EndTime", fmt.format(new Date(endTimestamp)));
parameters.put("StartTime", fmt.format(new Date(startTimestamp)));
parameters.put("MetricName", metric);
parameters.put("Namespace", idIsVolumeId ? "AWS/EBS" : "AWS/EC2");
parameters.put("Unit", unit);
parameters.put("Dimensions.member.Name.1", idIsVolumeId ? "VolumeId" : "InstanceId");
parameters.put("Dimensions.member.Value.1", id);
parameters.put("Statistics.member.1", "Average");
parameters.put("Statistics.member.2", "Minimum");
parameters.put("Statistics.member.3", "Maximum");
parameters.put("Period", "60");
method = new EC2Method(getProvider(), getCloudWatchUrl(getContext()), parameters);
try {
doc = method.invoke();
} catch( EC2Exception e ) {
logger.error(e.getSummary());
throw new CloudException(e);
}
TreeSet<Metric> metrics = new TreeSet<Metric>();
fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
fmt.setCalendar(UTC_CALENDAR);
blocks = doc.getElementsByTagName("member");
for( int i = 0; i < blocks.getLength(); i++ ) {
NodeList items = blocks.item(i).getChildNodes();
Metric m = new Metric();
for( int j = 0; j < items.getLength(); j++ ) {
Node item = items.item(j);
if( item.getNodeName().equals("Timestamp") ) {
String dateString = item.getFirstChild().getNodeValue();
try {
m.timestamp = fmt.parse(dateString).getTime();
} catch( ParseException e ) {
logger.error(e);
throw new InternalException(e);
}
} else if( item.getNodeName().equals("Average") ) {
m.average = Double.parseDouble(item.getFirstChild().getNodeValue());
} else if( item.getNodeName().equals("Minimum") ) {
m.minimum = Double.parseDouble(item.getFirstChild().getNodeValue());
} else if( item.getNodeName().equals("Maximum") ) {
m.maximum = Double.parseDouble(item.getFirstChild().getNodeValue());
} else if( item.getNodeName().equals("Samples") ) {
m.samples = (int) Double.parseDouble(item.getFirstChild().getNodeValue());
}
}
metrics.add(m);
}
return metrics;
} finally {
APITrace.end();
}
}
private interface ApplyCalcs {
public void apply(VmStatistics stats, long start, long end, int samples, double average, double minimum, double maximum);
}
private void calculate(VmStatistics stats, String metricName, String unit, String id, boolean idIsVolumeId, long startTimestamp, long endTimestamp, ApplyCalcs apply) throws CloudException, InternalException {
Set<Metric> metrics = calculate(metricName, unit, id, idIsVolumeId, startTimestamp, endTimestamp);
double minimum = -1.0, maximum = 0.0, sum = 0.0;
long start = -1L, end = 0L;
int samples = 0;
for( Metric metric : metrics ) {
if( start < 0L ) {
start = metric.timestamp;
}
if( metric.timestamp > end ) {
end = metric.timestamp;
}
samples++;
if( metric.minimum < minimum || minimum < 0.0 ) {
minimum = metric.minimum;
}
if( metric.maximum > maximum ) {
maximum = metric.maximum;
}
sum += metric.average;
}
if( start < 0L ) {
start = startTimestamp;
}
if( end < 0L ) {
end = endTimestamp;
if( end < 1L ) {
end = System.currentTimeMillis();
}
}
if( minimum < 0.0 ) {
minimum = 0.0;
}
apply.apply(stats, start, end, samples, samples == 0 ? 0.0 : sum / samples, minimum, maximum);
}
private void calculateCpuUtilization(VmStatistics statistics, String instanceId, long startTimestamp, long endTimestamp) throws CloudException, InternalException {
ApplyCalcs apply = new ApplyCalcs() {
public void apply(VmStatistics stats, long start, long end, int samples, double average, double minimum, double maximum) {
stats.setSamples(samples);
stats.setStartTimestamp(start);
stats.setMinimumCpuUtilization(minimum);
stats.setAverageCpuUtilization(average);
stats.setMaximumCpuUtilization(maximum);
stats.setEndTimestamp(end);
}
};
calculate(statistics, "CPUUtilization", "Percent", instanceId, false, startTimestamp, endTimestamp, apply);
}
private void calculateDiskReadBytes(VmStatistics statistics, String id, boolean idIsVolumeId, long startTimestamp, long endTimestamp) throws CloudException, InternalException {
ApplyCalcs apply = new ApplyCalcs() {
public void apply(VmStatistics stats, long start, long end, int samples, double average, double minimum, double maximum) {
stats.setMinimumDiskReadBytes(minimum);
stats.setAverageDiskReadBytes(average);
stats.setMaximumDiskReadBytes(maximum);
}
};
calculate(statistics, idIsVolumeId ? "VolumeReadBytes" : "DiskReadBytes", "Bytes", id, idIsVolumeId, startTimestamp, endTimestamp, apply);
}
private void calculateDiskReadOps(VmStatistics statistics, String id, boolean idIsVolumeId, long startTimestamp, long endTimestamp) throws CloudException, InternalException {
ApplyCalcs apply = new ApplyCalcs() {
public void apply(VmStatistics stats, long start, long end, int samples, double average, double minimum, double maximum) {
stats.setMinimumDiskReadOperations(minimum);
stats.setAverageDiskReadOperations(average);
stats.setMaximumDiskReadOperations(maximum);
}
};
calculate(statistics, idIsVolumeId ? "VolumeReadOps" : "DiskReadOps", "Count", id, idIsVolumeId, startTimestamp, endTimestamp, apply);
}
private void calculateDiskWriteBytes(VmStatistics statistics, String id, boolean idIsVolumeId, long startTimestamp, long endTimestamp) throws CloudException, InternalException {
ApplyCalcs apply = new ApplyCalcs() {
public void apply(VmStatistics stats, long start, long end, int samples, double average, double minimum, double maximum) {
stats.setMinimumDiskWriteBytes(minimum);
stats.setAverageDiskWriteBytes(average);
stats.setMaximumDiskWriteBytes(maximum);
}
};
calculate(statistics, idIsVolumeId ? "VolumeWriteBytes" : "DiskWriteBytes", "Bytes", id, idIsVolumeId, startTimestamp, endTimestamp, apply);
}
private void calculateDiskWriteOps(VmStatistics statistics, String id, boolean idIsVolumeId, long startTimestamp, long endTimestamp) throws CloudException, InternalException {
ApplyCalcs apply = new ApplyCalcs() {
public void apply(VmStatistics stats, long start, long end, int samples, double average, double minimum, double maximum) {
stats.setMinimumDiskWriteOperations(minimum);
stats.setAverageDiskWriteOperations(average);
stats.setMaximumDiskWriteOperations(maximum);
}
};
calculate(statistics, idIsVolumeId ? "VolumeWriteOps" : "DiskWriteOps", "Count", id, idIsVolumeId, startTimestamp, endTimestamp, apply);
}
private void calculateNetworkIn(VmStatistics statistics, String instanceId, long startTimestamp, long endTimestamp) throws CloudException, InternalException {
ApplyCalcs apply = new ApplyCalcs() {
public void apply(VmStatistics stats, long start, long end, int samples, double average, double minimum, double maximum) {
stats.setMinimumNetworkIn(minimum);
stats.setAverageNetworkIn(average);
stats.setMaximumNetworkIn(maximum);
}
};
calculate(statistics, "NetworkIn", "Bytes", instanceId, false, startTimestamp, endTimestamp, apply);
}
private void calculateNetworkOut(VmStatistics statistics, String instanceId, long startTimestamp, long endTimestamp) throws CloudException, InternalException {
ApplyCalcs apply = new ApplyCalcs() {
public void apply(VmStatistics stats, long start, long end, int samples, double average, double minimum, double maximum) {
stats.setMinimumNetworkOut(minimum);
stats.setAverageNetworkOut(average);
stats.setMaximumNetworkOut(maximum);
}
};
calculate(statistics, "NetworkOut", "Bytes", instanceId, false, startTimestamp, endTimestamp, apply);
}
@Override
public @Nonnull VirtualMachine clone(@Nonnull String vmId, @Nonnull String intoDcId, @Nonnull String name, @Nonnull String description, boolean powerOn, @Nullable String... firewallIds) throws InternalException, CloudException {
throw new OperationNotSupportedException("AWS instances cannot be cloned.");
}
@Override
public void enableAnalytics(@Nonnull String instanceId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "enableVMAnalytics");
try {
if( getProvider().getEC2Provider().isAWS() || getProvider().getEC2Provider().isEnStratus() ) {
Map<String, String> parameters = getProvider().getStandardParameters(getProvider().getContext(), EC2Method.MONITOR_INSTANCES);
EC2Method method;
parameters.put("InstanceId.1", instanceId);
method = new EC2Method(getProvider(), getProvider().getEc2Url(), parameters);
try {
method.invoke();
} catch( EC2Exception e ) {
logger.error(e.getSummary());
throw new CloudException(e);
}
}
} finally {
APITrace.end();
}
}
private Architecture getArchitecture(String size) {
if( size.equals("m1.small") || size.equals("c1.medium") ) {
return Architecture.I32;
} else {
return Architecture.I64;
}
}
public @Nonnull EC2InstanceCapabilities getCapabilities() {
if( capabilities == null ) {
capabilities = new EC2InstanceCapabilities(getProvider());
}
return capabilities;
}
private @Nonnull String getCloudWatchUrl(@Nonnull ProviderContext ctx) {
return ( "https://monitoring." + ctx.getRegionId() + ".amazonaws.com" );
}
@Override
public @Nullable String getPassword(@Nonnull String instanceId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "getPassword");
try {
Callable<String> callable = new GetPassCallable(
instanceId,
getProvider().getStandardParameters(getProvider().getContext(), EC2Method.GET_PASSWORD_DATA),
getProvider(),
getProvider().getEc2Url()
);
return callable.call();
} catch( EC2Exception e ) {
logger.error(e.getSummary());
throw new CloudException(e);
} catch( CloudException ce ) {
throw ce;
} catch( Exception e ) {
throw new InternalException(e);
} finally {
APITrace.end();
}
}
public static class GetPassCallable implements Callable {
private String instanceId;
private Map<String, String> params;
private AWSCloud awsProvider;
private String ec2url;
public GetPassCallable(String iId, Map<String, String> p, AWSCloud ap, String eUrl) {
instanceId = iId;
params = p;
awsProvider = ap;
ec2url = eUrl;
}
public String call() throws CloudException {
EC2Method method;
NodeList blocks;
Document doc;
params.put("InstanceId", instanceId);
try {
method = new EC2Method(awsProvider, ec2url, params);
} catch( InternalException e ) {
logger.error(e.getMessage());
throw new CloudException(e);
}
try {
doc = method.invoke();
} catch( EC2Exception e ) {
logger.error(e.getSummary());
throw new CloudException(e);
} catch( InternalException e ) {
logger.error(e.getMessage());
throw new CloudException(e);
}
blocks = doc.getElementsByTagName("passwordData");
if( blocks.getLength() > 0 ) {
Node pw = blocks.item(0);
if( pw.hasChildNodes() ) {
return pw.getFirstChild().getNodeValue();
}
return null;
}
return null;
}
}
@Override
public @Nullable String getUserData(@Nonnull String instanceId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "getUserData");
try {
Callable<String> callable = new GetUserDataCallable(
instanceId,
getProvider().getStandardParameters(getProvider().getContext(), EC2Method.DESCRIBE_INSTANCE_ATTRIBUTE),
getProvider(),
getProvider().getEc2Url()
);
return callable.call();
} catch( EC2Exception e ) {
logger.error(e.getSummary());
throw new CloudException(e);
} catch( CloudException ce ) {
throw ce;
} catch( Exception e ) {
throw new InternalException(e);
} finally {
APITrace.end();
}
}
public static class GetUserDataCallable implements Callable {
private String instanceId;
private Map<String, String> params;
private AWSCloud awsProvider;
private String ec2url;
public GetUserDataCallable(String iId, Map<String, String> p, AWSCloud ap, String eUrl) {
instanceId = iId;
params = p;
awsProvider = ap;
ec2url = eUrl;
}
public String call() throws CloudException {
EC2Method method;
NodeList blocks;
Document doc;
params.put("InstanceId", instanceId);
params.put("Attribute", "userData");
try {
method = new EC2Method(awsProvider, ec2url, params);
} catch( InternalException e ) {
logger.error(e.getMessage());
throw new CloudException(e);
}
try {
doc = method.invoke();
} catch( EC2Exception e ) {
logger.error(e.getSummary());
throw new CloudException(e);
} catch( InternalException e ) {
logger.error(e.getMessage());
throw new CloudException(e);
}
blocks = doc.getElementsByTagName("value");
if( blocks.getLength() > 0 ) {
Node pw = blocks.item(0);
if( pw.hasChildNodes() ) {
return pw.getFirstChild().getNodeValue();
}
return null;
}
return null;
}
}
@Override
public @Nonnull String getConsoleOutput(@Nonnull String instanceId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "getConsoleOutput");
try {
Map<String, String> parameters = getProvider().getStandardParameters(getProvider().getContext(), EC2Method.GET_CONSOLE_OUTPUT);
String output = null;
EC2Method method;
NodeList blocks;
Document doc;
parameters.put("InstanceId", instanceId);
method = new EC2Method(getProvider(), getProvider().getEc2Url(), parameters);
try {
doc = method.invoke();
} catch( EC2Exception e ) {
String code = e.getCode();
if( code != null && code.startsWith("InvalidInstanceID") ) {
return "";
}
logger.error(e.getSummary());
throw new CloudException(e);
}
blocks = doc.getElementsByTagName("timestamp");
for( int i = 0; i < blocks.getLength(); i++ ) {
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
fmt.setCalendar(UTC_CALENDAR);
String ts = blocks.item(i).getFirstChild().getNodeValue();
long timestamp;
try {
timestamp = fmt.parse(ts).getTime();
} catch( ParseException e ) {
logger.error(e);
throw new CloudException(e);
}
if( timestamp > -1L ) {
break;
}
}
blocks = doc.getElementsByTagName("output");
for( int i = 0; i < blocks.getLength(); i++ ) {
Node item = blocks.item(i);
if( item.hasChildNodes() ) {
output = item.getFirstChild().getNodeValue().trim();
if( output != null ) {
break;
}
}
}
if( output != null ) {
try {
return new String(Base64.decodeBase64(output.getBytes("utf-8")), "utf-8");
} catch( UnsupportedEncodingException e ) {
logger.error(e);
throw new InternalException(e);
}
}
return "";
} finally {
APITrace.end();
}
}
@Override
public int getCostFactor(@Nonnull VmState vmState) throws InternalException, CloudException {
return ( vmState.equals(VmState.STOPPED) ? 0 : 100 );
}
@Override
public int getMaximumVirtualMachineCount() throws CloudException, InternalException {
return -2;
}
@Override
public @Nonnull Iterable<String> listFirewalls(@Nonnull String instanceId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "listFirewallsForVM");
try {
Map<String, String> parameters = getProvider().getStandardParameters(getProvider().getContext(), EC2Method.DESCRIBE_INSTANCES);
ArrayList<String> firewalls = new ArrayList<String>();
EC2Method method;
NodeList blocks;
Document doc;
parameters.put("InstanceId.1", instanceId);
method = new EC2Method(getProvider(), getProvider().getEc2Url(), parameters);
try {
doc = method.invoke();
} catch( EC2Exception e ) {
String code = e.getCode();
if( code != null && code.startsWith("InvalidInstanceID") ) {
return firewalls;
}
logger.error(e.getSummary());
throw new CloudException(e);
}
blocks = doc.getElementsByTagName("groupSet");
for( int i = 0; i < blocks.getLength(); i++ ) {
NodeList items = blocks.item(i).getChildNodes();
for( int j = 0; j < items.getLength(); j++ ) {
Node item = items.item(j);
if( item.getNodeName().equals("item") ) {
NodeList sub = item.getChildNodes();
for( int k = 0; k < sub.getLength(); k++ ) {
Node id = sub.item(k);
if( id.getNodeName().equalsIgnoreCase("groupId") && id.hasChildNodes() ) {
firewalls.add(id.getFirstChild().getNodeValue().trim());
break;
}
}
}
}
}
return firewalls;
} finally {
APITrace.end();
}
}
@Override
public @Nullable VirtualMachine getVirtualMachine(@Nonnull String instanceId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "getVirtualMachine");
try {
ProviderContext ctx = getProvider().getContext();
if( ctx == null ) {
throw new CloudException("No context was established for this request");
}
Future<Iterable<IpAddress>> ipPoolFuture = null;
Iterable<IpAddress> addresses;
if( getProvider().hasNetworkServices() ) {
NetworkServices services = getProvider().getNetworkServices();
if( services != null ) {
if( services.hasIpAddressSupport() ) {
IpAddressSupport support = services.getIpAddressSupport();
if( support != null ) {
ipPoolFuture = support.listIpPoolConcurrently(IPVersion.IPV4, false);
}
}
}
}
Map<String, String> parameters = getProvider().getStandardParameters(getProvider().getContext(), EC2Method.DESCRIBE_INSTANCES);
EC2Method method;
NodeList blocks;
Document doc;
parameters.put("InstanceId.1", instanceId);
method = new EC2Method(getProvider(), getProvider().getEc2Url(), parameters);
try {
doc = method.invoke();
} catch( EC2Exception e ) {
String code = e.getCode();
if( code != null && code.startsWith("InvalidInstanceID") ) {
return null;
}
logger.error(e.getSummary());
throw new CloudException(e);
}
blocks = doc.getElementsByTagName("instancesSet");
for( int i = 0; i < blocks.getLength(); i++ ) {
NodeList instances = blocks.item(i).getChildNodes();
for( int j = 0; j < instances.getLength(); j++ ) {
Node instance = instances.item(j);
if( instance.getNodeName().equals("item") ) {
try {
if( ipPoolFuture != null ) {
addresses = ipPoolFuture.get(30, TimeUnit.SECONDS);
}
else {
addresses = Collections.emptyList();
}
} catch( InterruptedException e ) {
logger.error(e.getMessage());
addresses = Collections.emptyList();
} catch( ExecutionException e ) {
logger.error(e.getMessage());
addresses = Collections.emptyList();
} catch( TimeoutException e ) {
logger.error(e.getMessage());
addresses = Collections.emptyList();
}
VirtualMachine server = toVirtualMachine( ctx, instance, addresses );
if ( server != null && server.getProviderVirtualMachineId().equals( instanceId ) ) {
return server;
}
}
}
}
return null;
} catch( Exception e ) {
e.printStackTrace();
if( e instanceof CloudException ) {
throw ( CloudException ) e;
}
throw new InternalException(e);
} finally {
APITrace.end();
}
}
@Override
public @Nullable VirtualMachineProduct getProduct(@Nonnull String sizeId) throws CloudException, InternalException {
for( Architecture a : getCapabilities().listSupportedArchitectures() ) {
for( VirtualMachineProduct prd : listProducts(a) ) {
if( prd.getProviderProductId().equals(sizeId) ) {
return prd;
}
}
}
return null;
}
private VmState getServerState(String state) {
if( state.equals("pending") ) {
return VmState.PENDING;
} else if( state.equals("running") ) {
return VmState.RUNNING;
} else if( state.equals("terminating") || state.equals("stopping") ) {
return VmState.STOPPING;
} else if( state.equals("stopped") ) {
return VmState.STOPPED;
} else if( state.equals("shutting-down") ) {
return VmState.STOPPING;
} else if( state.equals("terminated") ) {
return VmState.TERMINATED;
} else if( state.equals("rebooting") ) {
return VmState.REBOOTING;
}
logger.warn("Unknown server state: " + state);
return VmState.PENDING;
}
@Override
public @Nonnull VmStatistics getVMStatistics(@Nonnull String instanceId, @Nonnegative long startTimestamp, @Nonnegative long endTimestamp) throws InternalException, CloudException {
APITrace.begin(getProvider(), "getVMStatistics");
try {
VmStatistics statistics = new VmStatistics();
if( endTimestamp < 1L ) {
endTimestamp = System.currentTimeMillis() + 1000L;
}
if( startTimestamp < ( System.currentTimeMillis() - ( 2L * CalendarWrapper.DAY ) ) ) {
startTimestamp = System.currentTimeMillis() - ( 2L * CalendarWrapper.DAY );
if( startTimestamp > ( endTimestamp - ( 2L * CalendarWrapper.MINUTE ) ) ) {
endTimestamp = startTimestamp + ( 2L * CalendarWrapper.MINUTE );
}
} else if( startTimestamp > ( endTimestamp - ( 2L * CalendarWrapper.MINUTE ) ) ) {
startTimestamp = endTimestamp - ( 2L * CalendarWrapper.MINUTE );
}
String id = instanceId;
boolean idIsVolumeId = false;
VirtualMachine vm = getVirtualMachine(instanceId);
if( vm != null ) {
if( vm.isPersistent() ) {
if( vm.getProviderVolumeIds(getProvider()).length > 0 ) {
id = vm.getProviderVolumeIds(getProvider())[0];
idIsVolumeId = true;
}
}
calculateCpuUtilization(statistics, instanceId, startTimestamp, endTimestamp);
calculateDiskReadBytes(statistics, id, idIsVolumeId, startTimestamp, endTimestamp);
calculateDiskReadOps(statistics, id, idIsVolumeId, startTimestamp, endTimestamp);
calculateDiskWriteBytes(statistics, id, idIsVolumeId, startTimestamp, endTimestamp);
calculateDiskWriteOps(statistics, id, idIsVolumeId, startTimestamp, endTimestamp);
calculateNetworkIn(statistics, instanceId, startTimestamp, endTimestamp);
calculateNetworkOut(statistics, instanceId, startTimestamp, endTimestamp);
}
return statistics;
} finally {
APITrace.end();
}
}
@Override
public @Nonnull Iterable<VmStatistics> getVMStatisticsForPeriod(@Nonnull String instanceId, long startTimestamp, long endTimestamp) throws InternalException, CloudException {
APITrace.begin(getProvider(), "getVMStatisticsForPeriod");
try {
if( endTimestamp < 1L ) {
endTimestamp = System.currentTimeMillis() + 1000L;
}
if( startTimestamp < ( System.currentTimeMillis() - CalendarWrapper.DAY ) ) {
startTimestamp = System.currentTimeMillis() - CalendarWrapper.DAY;
if( startTimestamp > ( endTimestamp - ( 2L * CalendarWrapper.MINUTE ) ) ) {
endTimestamp = startTimestamp + ( 2L * CalendarWrapper.MINUTE );
}
} else if( startTimestamp > ( endTimestamp - ( 2L * CalendarWrapper.MINUTE ) ) ) {
startTimestamp = endTimestamp - ( 2L * CalendarWrapper.MINUTE );
}
TreeMap<Integer, VmStatistics> statMap = new TreeMap<Integer, VmStatistics>();
int minutes = (int) ( ( endTimestamp - startTimestamp ) / CalendarWrapper.MINUTE );
for( int i = 1; i <= minutes; i++ ) {
statMap.put(i, new VmStatistics());
}
Set<Metric> metrics = calculate("CPUUtilization", "Percent", instanceId, false, startTimestamp, endTimestamp);
for( Metric m : metrics ) {
int minute = 1 + (int) ( ( m.timestamp - startTimestamp ) / CalendarWrapper.MINUTE );
VmStatistics stats = statMap.get(minute);
if( stats == null ) {
stats = new VmStatistics();
statMap.put(minute, stats);
}
stats.setAverageCpuUtilization(m.average);
stats.setMaximumCpuUtilization(m.maximum);
stats.setMinimumCpuUtilization(m.minimum);
stats.setStartTimestamp(m.timestamp);
stats.setEndTimestamp(m.timestamp);
stats.setSamples(m.samples);
}
String id = instanceId;
boolean idIsVolumeId = false;
VirtualMachine vm = getVirtualMachine(instanceId);
if( vm != null && vm.isPersistent() ) {
if( vm.getProviderVolumeIds(getProvider()).length > 0 ) {
id = vm.getProviderVolumeIds(getProvider())[0];
idIsVolumeId = true;
}
}
metrics = calculate(idIsVolumeId ? "VolumeReadBytes" : "DiskReadBytes", "Bytes", id, idIsVolumeId, startTimestamp, endTimestamp);
for( Metric m : metrics ) {
int minute = 1 + (int) ( ( m.timestamp - startTimestamp ) / CalendarWrapper.MINUTE );
VmStatistics stats = statMap.get(minute);
if( stats == null ) {
stats = new VmStatistics();
statMap.put(minute, stats);
}
stats.setAverageDiskReadBytes(m.average);
stats.setMinimumDiskReadBytes(m.minimum);
stats.setMaximumDiskReadBytes(m.maximum);
if( stats.getSamples() < 1 ) {
stats.setSamples(m.samples);
}
}
metrics = calculate(idIsVolumeId ? "VolumeReadOps" : "DiskReadOps", "Count", id, idIsVolumeId, startTimestamp, endTimestamp);
for( Metric m : metrics ) {
int minute = 1 + (int) ( ( m.timestamp - startTimestamp ) / CalendarWrapper.MINUTE );
VmStatistics stats = statMap.get(minute);
if( stats == null ) {
stats = new VmStatistics();
statMap.put(minute, stats);
}
stats.setAverageDiskReadOperations(m.average);
stats.setMinimumDiskReadOperations(m.minimum);
stats.setMaximumDiskReadOperations(m.maximum);
if( stats.getSamples() < 1 ) {
stats.setSamples(m.samples);
}
}
metrics = calculate(idIsVolumeId ? "VolumeWriteBytes" : "DiskWriteBytes", "Bytes", id, idIsVolumeId, startTimestamp, endTimestamp);
for( Metric m : metrics ) {
int minute = 1 + (int) ( ( m.timestamp - startTimestamp ) / CalendarWrapper.MINUTE );
VmStatistics stats = statMap.get(minute);
if( stats == null ) {
stats = new VmStatistics();
statMap.put(minute, stats);
}
stats.setAverageDiskWriteBytes(m.average);
stats.setMinimumDiskWriteBytes(m.minimum);
stats.setMaximumDiskWriteBytes(m.maximum);
if( stats.getSamples() < 1 ) {
stats.setSamples(m.samples);
}
}
metrics = calculate(idIsVolumeId ? "VolumeWriteOps" : "DiskWriteOps", "Count", id, idIsVolumeId, startTimestamp, endTimestamp);
for( Metric m : metrics ) {
int minute = 1 + (int) ( ( m.timestamp - startTimestamp ) / CalendarWrapper.MINUTE );
VmStatistics stats = statMap.get(minute);
if( stats == null ) {
stats = new VmStatistics();
statMap.put(minute, stats);
}
stats.setAverageDiskWriteOperations(m.average);
stats.setMinimumDiskWriteOperations(m.minimum);
stats.setMaximumDiskWriteOperations(m.maximum);
if( stats.getSamples() < 1 ) {
stats.setSamples(m.samples);
}
}
metrics = calculate("NetworkIn", "Bytes", instanceId, false, startTimestamp, endTimestamp);
for( Metric m : metrics ) {
int minute = 1 + (int) ( ( m.timestamp - startTimestamp ) / CalendarWrapper.MINUTE );
VmStatistics stats = statMap.get(minute);
if( stats == null ) {
stats = new VmStatistics();
statMap.put(minute, stats);
}
stats.setAverageNetworkIn(m.average);
stats.setMinimumNetworkIn(m.minimum);
stats.setMaximumNetworkIn(m.maximum);
if( stats.getSamples() < 1 ) {
stats.setSamples(m.samples);
}
}
metrics = calculate("NetworkOut", "Bytes", instanceId, false, startTimestamp, endTimestamp);
for( Metric m : metrics ) {
int minute = 1 + (int) ( ( m.timestamp - startTimestamp ) / CalendarWrapper.MINUTE );
VmStatistics stats = statMap.get(minute);
if( stats == null ) {
stats = new VmStatistics();
statMap.put(minute, stats);
}
stats.setAverageNetworkOut(m.average);
stats.setMinimumNetworkOut(m.minimum);
stats.setMaximumNetworkOut(m.maximum);
if( stats.getSamples() < 1 ) {
stats.setSamples(m.samples);
}
}
ArrayList<VmStatistics> list = new ArrayList<VmStatistics>();
for( Map.Entry<Integer, VmStatistics> entry : statMap.entrySet() ) {
VmStatistics stats = entry.getValue();
if( stats != null && stats.getSamples() > 0 ) {
list.add(stats);
}
}
return list;
} finally {
APITrace.end();
}
}
@Override
public Iterable<VirtualMachineStatus> getVMStatus(@Nullable String... vmIds) throws InternalException, CloudException {
VmStatusFilterOptions filterOptions = vmIds != null ? VmStatusFilterOptions.getInstance().withVmIds(vmIds) : VmStatusFilterOptions.getInstance();
return getVMStatus(filterOptions);
}
@Override
public @Nullable Iterable<VirtualMachineStatus> getVMStatus( @Nullable VmStatusFilterOptions filterOptions) throws InternalException, CloudException {
APITrace.begin(getProvider(), "getVMStatus");
try {
ProviderContext ctx = getProvider().getContext();
if( ctx == null ) {
throw new CloudException("No context was established for this request");
}
Map<String, String> params = getProvider().getStandardParameters(getProvider().getContext(), EC2Method.DESCRIBE_INSTANCE_STATUS);
EC2Method method;
NodeList blocks;
Document doc;
Map<String, String> filterParameters = createFilterParametersFrom(filterOptions);
getProvider().putExtraParameters(params, filterParameters);
try {
method = new EC2Method(getProvider(), getProvider().getEc2Url(), params);
} catch( InternalException e ) {
logger.error(e.getMessage());
throw new CloudException(e);
}
try {
doc = method.invoke();
} catch( EC2Exception e ) {
String code = e.getCode();
if( code != null && code.startsWith("InvalidInstanceID") ) {
return null;
}
logger.error(e.getSummary());
throw new CloudException(e);
} catch( InternalException e ) {
logger.error(e.getMessage());
throw new CloudException(e);
}
ArrayList<VirtualMachineStatus> list = new ArrayList<VirtualMachineStatus>();
blocks = doc.getElementsByTagName("instanceStatusSet");
for( int i = 0; i < blocks.getLength(); i++ ) {
NodeList instances = blocks.item(i).getChildNodes();
for( int j = 0; j < instances.getLength(); j++ ) {
Node instance = instances.item(j);
if( instance.getNodeName().equals("item") ) {
NodeList attrs = instance.getChildNodes();
VirtualMachineStatus vm = new VirtualMachineStatus();
for( int k = 0; k < attrs.getLength(); k++ ) {
Node attr = attrs.item(k);
String name;
name = attr.getNodeName();
if( name.equals("instanceId") ) {
String value = attr.getFirstChild().getNodeValue().trim();
vm.setProviderVirtualMachineId(value);
}
else if( name.equals("systemStatus") ) {
NodeList details = attr.getChildNodes();
for( int l = 0; l < details.getLength(); l++ ) {
Node detail = details.item(l);
name = detail.getNodeName();
if( name.equals("status") ) {
String value = detail.getFirstChild().getNodeValue().trim();
vm.setProviderHostStatus(toVmStatus(value));
}
}
}
else if( name.equals("instanceStatus") ) {
NodeList details = attr.getChildNodes();
for( int l = 0; l < details.getLength(); l++ ) {
Node detail = details.item(l);
name = detail.getNodeName();
if( name.equals("status") ) {
String value = detail.getFirstChild().getNodeValue().trim();
vm.setProviderVmStatus(toVmStatus(value));
}
}
}
}
list.add(vm);
}
}
}
return list;
} catch( CloudException ce ) {
ce.printStackTrace();
throw ce;
} catch( Exception e ) {
e.printStackTrace();
throw new InternalException(e);
} finally {
APITrace.end();
}
}
private Map<String, String> createFilterParametersFrom(@Nullable VmStatusFilterOptions options ) {
if( options == null || options.isMatchesAny() ) {
return Collections.emptyMap();
}
// tag advantage of EC2-based filtering if we can...
Map<String, String> extraParameters = new HashMap<String, String>();
int filterIndex = 0;
if( options.getVmStatuses() != null ) {
getProvider().addFilterParameter(extraParameters, filterIndex++, "system-status.status", options.getVmStatuses());
getProvider().addFilterParameter(extraParameters, filterIndex++, "instance-status.status", options.getVmStatuses());
}
String[] vmIds = options.getVmIds();
if( vmIds != null ) {
for( int y = 0; y < vmIds.length; y++ ) {
extraParameters.put("InstanceId." + String.valueOf(y + 1), vmIds[y]);
}
}
return extraParameters;
}
@Override
public boolean isSubscribed() throws InternalException, CloudException {
APITrace.begin(getProvider(), "isSubscribedVirtualMachine");
try {
Map<String, String> parameters = getProvider().getStandardParameters(getProvider().getContext(), EC2Method.DESCRIBE_INSTANCES);
EC2Method method = new EC2Method(getProvider(), getProvider().getEc2Url(), parameters);
try {
method.invoke();
return true;
} catch( EC2Exception e ) {
if( e.getStatus() == HttpServletResponse.SC_UNAUTHORIZED || e.getStatus() == HttpServletResponse.SC_FORBIDDEN ) {
return false;
}
String code = e.getCode();
if( code != null && code.equals("SignatureDoesNotMatch") ) {
return false;
}
logger.warn(e.getSummary());
throw new CloudException(e);
}
} finally {
APITrace.end();
}
}
@Override
public @Nonnull Iterable<VirtualMachineProduct> listProducts(Architecture architecture) throws InternalException, CloudException {
ProviderContext ctx = getProvider().getContext();
if( ctx == null ) {
throw new CloudException("No context was set for this request");
}
Cache<VirtualMachineProduct> cache = Cache.getInstance(getProvider(), "products" + architecture.name(), VirtualMachineProduct.class, CacheLevel.REGION, new TimePeriod<Day>(1, TimePeriod.DAY));
Iterable<VirtualMachineProduct> products = cache.get(ctx);
if( products == null ) {
ArrayList<VirtualMachineProduct> list = new ArrayList<VirtualMachineProduct>();
try {
InputStream input = EC2Instance.class.getResourceAsStream("/org/dasein/cloud/aws/vmproducts.json");
if( input != null ) {
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder json = new StringBuilder();
String line;
while( ( line = reader.readLine() ) != null ) {
json.append(line);
json.append("\n");
}
JSONArray arr = new JSONArray(json.toString());
JSONObject toCache = null;
for( int i = 0; i < arr.length(); i++ ) {
JSONObject productSet = arr.getJSONObject(i);
String cloud, providerName;
if( productSet.has("cloud") ) {
cloud = productSet.getString("cloud");
} else {
continue;
}
if( productSet.has("provider") ) {
providerName = productSet.getString("provider");
} else {
continue;
}
if( !productSet.has("products") ) {
continue;
}
if( toCache == null || ( providerName.equals("AWS") && cloud.equals("AWS") ) ) {
toCache = productSet;
}
if( providerName.equalsIgnoreCase(getProvider().getProviderName()) && cloud.equalsIgnoreCase(getProvider().getCloudName()) ) {
toCache = productSet;
break;
}
}
if( toCache == null ) {
logger.warn("No products were defined");
return Collections.emptyList();
}
JSONArray plist = toCache.getJSONArray("products");
for( int i = 0; i < plist.length(); i++ ) {
JSONObject product = plist.getJSONObject(i);
boolean supported = false;
if( product.has("architectures") ) {
JSONArray architectures = product.getJSONArray("architectures");
for( int j = 0; j < architectures.length(); j++ ) {
String a = architectures.getString(j);
if( architecture.name().equals(a) ) {
supported = true;
break;
}
}
}
if( !supported ) {
continue;
}
if( product.has("excludesRegions") ) {
JSONArray regions = product.getJSONArray("excludesRegions");
for( int j = 0; j < regions.length(); j++ ) {
String r = regions.getString(j);
if( r.equals(ctx.getRegionId()) ) {
supported = false;
break;
}
}
}
if( !supported ) {
continue;
}
VirtualMachineProduct prd = toProduct(product);
if( prd != null ) {
list.add(prd);
}
}
} else {
logger.warn("No standard products resource exists for /org/dasein/cloud/aws/vmproducts.json");
}
input = EC2Instance.class.getResourceAsStream("/org/dasein/cloud/aws/vmproducts-custom.json");
if( input != null ) {
ArrayList<VirtualMachineProduct> customList = new ArrayList<VirtualMachineProduct>();
TreeSet<String> discard = new TreeSet<String>();
boolean discardAll = false;
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder json = new StringBuilder();
String line;
while( ( line = reader.readLine() ) != null ) {
json.append(line);
json.append("\n");
}
JSONArray arr = new JSONArray(json.toString());
JSONObject toCache = null;
for( int i = 0; i < arr.length(); i++ ) {
JSONObject listing = arr.getJSONObject(i);
String cloud, providerName, endpoint = null;
if( listing.has("cloud") ) {
cloud = listing.getString("cloud");
} else {
continue;
}
if( listing.has("provider") ) {
providerName = listing.getString("provider");
} else {
continue;
}
if( listing.has("endpoint") ) {
endpoint = listing.getString("endpoint");
}
if( !cloud.equals(getProvider().getCloudName()) || !providerName.equals(getProvider().getProviderName()) ) {
continue;
}
if( endpoint != null && endpoint.equals(ctx.getEndpoint()) ) {
toCache = listing;
break;
}
if( endpoint == null && toCache == null ) {
toCache = listing;
}
}
if( toCache != null ) {
if( toCache.has("discardDefaults") ) {
discardAll = toCache.getBoolean("discardDefaults");
}
if( toCache.has("discard") ) {
JSONArray dlist = toCache.getJSONArray("discard");
for( int i = 0; i < dlist.length(); i++ ) {
discard.add(dlist.getString(i));
}
}
if( toCache.has("products") ) {
JSONArray plist = toCache.getJSONArray("products");
for( int i = 0; i < plist.length(); i++ ) {
JSONObject product = plist.getJSONObject(i);
boolean supported = false;
if( product.has("architectures") ) {
JSONArray architectures = product.getJSONArray("architectures");
for( int j = 0; j < architectures.length(); j++ ) {
String a = architectures.getString(j);
if( architecture.name().equals(a) ) {
supported = true;
break;
}
}
}
if( !supported ) {
continue;
}
if( product.has("excludesRegions") ) {
JSONArray regions = product.getJSONArray("excludesRegions");
for( int j = 0; j < regions.length(); j++ ) {
String r = regions.getString(j);
if( r.equals(ctx.getRegionId()) ) {
supported = false;
break;
}
}
}
if( !supported ) {
continue;
}
VirtualMachineProduct prd = toProduct(product);
if( prd != null ) {
customList.add(prd);
}
}
}
if( !discardAll ) {
for( VirtualMachineProduct product : list ) {
if( !discard.contains(product.getProviderProductId()) ) {
customList.add(product);
}
}
}
list = customList;
}
}
products = list;
cache.put(ctx, products);
} catch( IOException e ) {
throw new InternalException(e);
} catch( JSONException e ) {
throw new InternalException(e);
}
}
return products;
}
private String guess(String privateDnsAddress) {
String dnsAddress = privateDnsAddress;
String[] parts = dnsAddress.split("\\.");
if( parts != null && parts.length > 1 ) {
dnsAddress = parts[0];
}
if( dnsAddress.startsWith("ip-") ) {
dnsAddress = dnsAddress.replace('-', '.');
return dnsAddress.substring(3);
}
return null;
}
@Override
public @Nonnull VirtualMachine launch(@Nonnull VMLaunchOptions cfg) throws CloudException, InternalException {
APITrace.begin(getProvider(), "launchVM");
try {
ProviderContext ctx = getProvider().getContext();
if( ctx == null ) {
throw new CloudException("No context was established for this request");
}
MachineImage img = getProvider().getComputeServices().getImageSupport().getMachineImage(cfg.getMachineImageId());
if( img == null ) {
throw new AWSResourceNotFoundException("No such machine image: " + cfg.getMachineImageId());
}
Map<String, String> parameters = getProvider().getStandardParameters(getProvider().getContext(), EC2Method.RUN_INSTANCES);
String ramdiskImage = (String) cfg.getMetaData().get("ramdiskImageId"), kernelImage = (String) cfg.getMetaData().get("kernelImageId");
EC2Method method;
NodeList blocks;
Document doc;
parameters.put("ImageId", cfg.getMachineImageId());
parameters.put("MinCount", "1");
parameters.put("MaxCount", "1");
parameters.put("InstanceType", cfg.getStandardProductId());
if( ramdiskImage != null ) {
parameters.put("ramdiskId", ramdiskImage);
}
if( kernelImage != null ) {
parameters.put("kernelId", kernelImage);
}
if( cfg.getRoleId() != null ) {
parameters.put("IamInstanceProfile.Arn", cfg.getRoleId());
}
if( cfg.getUserData() != null ) {
try {
parameters.put("UserData", Base64.encodeBase64String(cfg.getUserData().getBytes("utf-8")));
} catch( UnsupportedEncodingException e ) {
throw new InternalException(e);
}
}
if( cfg.isPreventApiTermination() ) {
parameters.put("DisableApiTermination", "true");
}
if( cfg.getDataCenterId() != null ) {
parameters.put("Placement.AvailabilityZone", cfg.getDataCenterId());
} else if( cfg.getVolumes().length > 0 ) {
String dc = null;
for( VolumeAttachment a : cfg.getVolumes() ) {
if( a.volumeToCreate != null ) {
dc = a.volumeToCreate.getDataCenterId();
if( dc != null ) {
break;
}
}
}
if( dc != null ) {
cfg.inDataCenter(dc);
}
}
if( cfg.getBootstrapKey() != null ) {
parameters.put("KeyName", cfg.getBootstrapKey());
}
if( getProvider().getEC2Provider().isAWS() ) {
parameters.put("Monitoring.Enabled", String.valueOf(cfg.isExtendedAnalytics()));
}
final ArrayList<VolumeAttachment> existingVolumes = new ArrayList<VolumeAttachment>();
TreeSet<String> deviceIds = new TreeSet<String>();
if( cfg.isIoOptimized() ) {
parameters.put("EbsOptimized", "true");
}
if( cfg.getVolumes().length > 0 ) {
Iterable<String> possibles = getProvider().getComputeServices().getVolumeSupport().listPossibleDeviceIds(img.getPlatform());
int i = 1;
for( VolumeAttachment a : cfg.getVolumes() ) {
if( a.deviceId != null ) {
deviceIds.add(a.deviceId);
} else if( a.volumeToCreate != null && a.volumeToCreate.getDeviceId() != null ) {
deviceIds.add(a.volumeToCreate.getDeviceId());
a.deviceId = a.volumeToCreate.getDeviceId();
}
}
for( VolumeAttachment a : cfg.getVolumes() ) {
if( a.deviceId == null ) {
for( String id : possibles ) {
if( !deviceIds.contains(id) ) {
a.deviceId = id;
deviceIds.add(id);
}
}
if( a.deviceId == null ) {
throw new InternalException("Unable to identify a device ID for volume");
}
}
if( a.existingVolumeId == null ) {
parameters.put("BlockDeviceMapping." + i + ".DeviceName", a.deviceId);
VolumeProduct prd = getProvider().getComputeServices().getVolumeSupport().getVolumeProduct(a.volumeToCreate.getVolumeProductId());
parameters.put("BlockDeviceMapping." + i + ".Ebs.VolumeType", prd.getProviderProductId());
if( a.volumeToCreate.getIops() > 0 ) {
parameters.put("BlockDeviceMapping." + i + ".Ebs.Iops", String.valueOf(a.volumeToCreate.getIops()));
}
if( a.volumeToCreate.getSnapshotId() != null ) {
parameters.put("BlockDeviceMapping." + i + ".Ebs.SnapshotId", a.volumeToCreate.getSnapshotId());
} else {
parameters.put("BlockDeviceMapping." + i + ".Ebs.VolumeSize", String.valueOf(a.volumeToCreate.getVolumeSize().getQuantity().intValue()));
}
i++;
} else {
existingVolumes.add(a);
}
}
}
if( cfg.getSubnetId() == null ) {
String[] ids = cfg.getFirewallIds();
if( ids.length > 0 ) {
int i = 1;
for( String id : ids ) {
parameters.put("SecurityGroupId." + ( i++ ), id);
}
}
}
else if( cfg.getNetworkInterfaces() != null && cfg.getNetworkInterfaces().length > 0 ) {
VMLaunchOptions.NICConfig[] nics = cfg.getNetworkInterfaces();
int i = 1;
for( VMLaunchOptions.NICConfig c : nics ) {
parameters.put("NetworkInterface." + i + ".DeviceIndex", String.valueOf(i));
// this only applies for the first NIC
if( i == 1 ) {
parameters.put("NetworkInterface.1.AssociatePublicIpAddress", String.valueOf(cfg.isAssociatePublicIpAddress()));
}
if( c.nicId == null ) {
parameters.put("NetworkInterface." + i + ".SubnetId", c.nicToCreate.getSubnetId());
parameters.put("NetworkInterface." + i + ".Description", c.nicToCreate.getDescription());
if( c.nicToCreate.getIpAddress() != null ) {
parameters.put("NetworkInterface." + i + ".PrivateIpAddress", c.nicToCreate.getIpAddress());
}
if( c.nicToCreate.getFirewallIds().length > 0 ) {
int j = 1;
for( String id : c.nicToCreate.getFirewallIds() ) {
parameters.put("NetworkInterface." + i + ".SecurityGroupId." + j, id);
j++;
}
}
} else {
parameters.put("NetworkInterface." + i + ".NetworkInterfaceId", c.nicId);
}
i++;
}
} else {
parameters.put("NetworkInterface.1.DeviceIndex", "0");
parameters.put("NetworkInterface.1.SubnetId", cfg.getSubnetId());
parameters.put("NetworkInterface.1.AssociatePublicIpAddress", String.valueOf(cfg.isAssociatePublicIpAddress()));
if( cfg.getPrivateIp() != null ) {
parameters.put("NetworkInterface.1.PrivateIpAddress", cfg.getPrivateIp());
}
int securityGroupIndex = 1;
for( String id : cfg.getFirewallIds() ) {
parameters.put("NetworkInterface.1.SecurityGroupId." + securityGroupIndex, id);
securityGroupIndex++;
}
}
method = new EC2Method(getProvider(), getProvider().getEc2Url(), parameters);
try {
doc = method.invoke();
} catch( EC2Exception e ) {
String code = e.getCode();
if( code != null && code.equals("InsufficientInstanceCapacity") ) {
return null;
}
logger.error(e.getSummary());
throw new CloudException(e);
}
blocks = doc.getElementsByTagName("instancesSet");
VirtualMachine server = null;
for( int i = 0; i < blocks.getLength(); i++ ) {
NodeList instances = blocks.item(i).getChildNodes();
for( int j = 0; j < instances.getLength(); j++ ) {
Node instance = instances.item(j);
if( instance.getNodeName().equals("item") ) {
server = toVirtualMachine(ctx, instance, new ArrayList<IpAddress>() /* can't be an elastic IP */);
if( server != null ) {
break;
}
}
}
}
if( server != null ) {
// wait for EC2 to figure out the server exists
VirtualMachine copy = getVirtualMachine(server.getProviderVirtualMachineId());
if( copy == null ) {
long timeout = System.currentTimeMillis() + CalendarWrapper.MINUTE;
while( timeout > System.currentTimeMillis() ) {
try {
Thread.sleep(5000L);
} catch( InterruptedException ignore ) {
}
try {
copy = getVirtualMachine(server.getProviderVirtualMachineId());
} catch( Throwable ignore ) {
}
if( copy != null ) {
break;
}
}
}
}
if( cfg.isIpForwardingAllowed() ) {
enableIpForwarding(server.getProviderVirtualMachineId());
}
if( cfg.isIpForwardingAllowed() ) {
enableIpForwarding(server.getProviderVirtualMachineId());
}
if( server != null && cfg.getBootstrapKey() != null ) {
try {
final String sid = server.getProviderVirtualMachineId();
try {
Callable<String> callable = new GetPassCallable(
sid,
getProvider().getStandardParameters(getProvider().getContext(), EC2Method.GET_PASSWORD_DATA),
getProvider(),
getProvider().getEc2Url()
);
String password = callable.call();
if( password == null ) {
server.setRootPassword(null);
server.setPasswordCallback(callable);
} else {
server.setRootPassword(password);
}
server.setPlatform(Platform.WINDOWS);
} catch( CloudException e ) {
logger.warn(e.getMessage());
}
} catch( Throwable t ) {
logger.warn("Unable to retrieve password for " + server.getProviderVirtualMachineId() + ", Let's hope it's Unix: " + t.getMessage());
}
}
Map<String, Object> meta = cfg.getMetaData();
Tag[] toCreate;
int i = 0;
if( meta.isEmpty() ) {
toCreate = new Tag[2];
} else {
int count = 0;
for( Map.Entry<String, Object> entry : meta.entrySet() ) {
if( entry.getKey().equalsIgnoreCase("name") || entry.getKey().equalsIgnoreCase("description") ) {
continue;
}
count++;
}
toCreate = new Tag[count + 2];
for( Map.Entry<String, Object> entry : meta.entrySet() ) {
if( entry.getKey().equalsIgnoreCase("name") || entry.getKey().equalsIgnoreCase("description") ) {
continue;
}
toCreate[i++] = new Tag(entry.getKey(), entry.getValue().toString());
}
}
Tag t = new Tag();
t.setKey("Name");
t.setValue(cfg.getFriendlyName());
toCreate[i++] = t;
t = new Tag();
t.setKey("Description");
t.setValue(cfg.getDescription());
toCreate[i] = t;
getProvider().createTags(server.getProviderVirtualMachineId(), toCreate);
if( !existingVolumes.isEmpty() ) {
final VirtualMachine vm = server;
getProvider().hold();
Thread thread = new Thread() {
public void run() {
try {
for( VolumeAttachment a : existingVolumes ) {
try {
getProvider().getComputeServices().getVolumeSupport().attach(a.existingVolumeId, vm.getProviderMachineImageId(), a.deviceId);
} catch( Throwable t ) {
}
}
} finally {
getProvider().release();
}
}
};
thread.setName("Volume Mounter for " + server);
thread.start();
}
return server;
} finally {
APITrace.end();
}
}
private void enableIpForwarding(final String instanceId) throws CloudException {
Thread t = new Thread() {
public void run() {
APITrace.begin(getProvider(), "enableIpForwarding");
long timeout = System.currentTimeMillis() + CalendarWrapper.MINUTE;
while( timeout > System.currentTimeMillis() ) {
try {
Map<String, String> params = getProvider().getStandardParameters(getProvider().getContext(), EC2Method.MODIFY_INSTANCE_ATTRIBUTE);
EC2Method m;
params.put("InstanceId", instanceId);
params.put("SourceDestCheck.Value", "false");
m = new EC2Method(getProvider(), getProvider().getEc2Url(), params);
m.invoke();
return;
} catch( EC2Exception ex ) {
if( ex.getStatus() != 404 ) {
logger.error("Unable to modify instance attributes on " + instanceId + ".", ex);
return;
}
} catch( Throwable ex ) {
logger.error("Unable to modify instance attributes on " + instanceId + ".", ex);
return;
} finally {
APITrace.end();
}
try {
Thread.sleep(5000L);
} catch( InterruptedException ignore ) {
}
}
}
};
t.setName(EC2Method.MODIFY_INSTANCE_ATTRIBUTE + " thread");
t.setDaemon(true);
t.start();
}
@Override
public @Nonnull Iterable<ResourceStatus> listVirtualMachineStatus() throws InternalException, CloudException {
APITrace.begin(getProvider(), "listVirtualMachineStatus");
try {
ProviderContext ctx = getProvider().getContext();
if( ctx == null ) {
throw new CloudException("No context was established for this request");
}
Map<String, String> parameters = getProvider().getStandardParameters(getProvider().getContext(), EC2Method.DESCRIBE_INSTANCES);
EC2Method method = new EC2Method(getProvider(), getProvider().getEc2Url(), parameters);
ArrayList<ResourceStatus> list = new ArrayList<ResourceStatus>();
NodeList blocks;
Document doc;
try {
doc = method.invoke();
} catch( EC2Exception e ) {
logger.error(e.getSummary());
throw new CloudException(e);
}
blocks = doc.getElementsByTagName("instancesSet");
for( int i = 0; i < blocks.getLength(); i++ ) {
NodeList instances = blocks.item(i).getChildNodes();
for( int j = 0; j < instances.getLength(); j++ ) {
Node instance = instances.item(j);
if( instance.getNodeName().equals("item") ) {
ResourceStatus status = toStatus(instance);
if( status != null ) {
list.add(status);
}
}
}
}
return list;
} finally {
APITrace.end();
}
}
@Override
public @Nonnull Iterable<VirtualMachine> listVirtualMachines() throws InternalException, CloudException {
return listVirtualMachinesWithParams(null, null);
}
@Override
public @Nonnull Iterable<VirtualMachine> listVirtualMachines(@Nullable VMFilterOptions options) throws InternalException, CloudException {
Map<String, String> filterParameters = createFilterParametersFrom(options);
if( options.getRegex() != null ) {
// still have to match on regex
options = VMFilterOptions.getInstance(false, options.getRegex());
}
else {
// nothing else to match on
options = null;
}
return listVirtualMachinesWithParams(filterParameters, options);
}
private Map<String, String> createFilterParametersFrom(@Nullable VMFilterOptions options) {
if( options == null || options.isMatchesAny() ) {
return Collections.emptyMap();
}
// tag advantage of EC2-based filtering if we can...
Map<String, String> extraParameters = new HashMap<String, String>();
int filterIndex = 0;
if( options.getTags() != null && !options.getTags().isEmpty() ) {
getProvider().putExtraParameters(extraParameters, getProvider().getTagFilterParams(options.getTags(), filterIndex));
}
if( options.getVmStates() != null ) {
getProvider().addFilterParameter(extraParameters, filterIndex++, "instance-state-name", options.getVmStates());
}
return extraParameters;
}
private @Nonnull Iterable<VirtualMachine> listVirtualMachinesWithParams(Map<String, String> extraParameters, @Nullable VMFilterOptions options) throws InternalException, CloudException {
APITrace.begin(getProvider(), "listVirtualMachines");
try {
ProviderContext ctx = getProvider().getContext();
if( ctx == null ) {
throw new CloudException("No context was established for this request");
}
Future<Iterable<IpAddress>> ipPoolFuture = null;
Iterable<IpAddress> addresses;
if( getProvider().hasNetworkServices() ) {
NetworkServices services = getProvider().getNetworkServices();
if( services != null ) {
if( services.hasIpAddressSupport() ) {
IpAddressSupport support = services.getIpAddressSupport();
if( support != null ) {
ipPoolFuture = support.listIpPoolConcurrently(IPVersion.IPV4, false);
}
}
}
}
Map<String, String> parameters = getProvider().getStandardParameters(getProvider().getContext(), EC2Method.DESCRIBE_INSTANCES);
getProvider().putExtraParameters(parameters, extraParameters);
EC2Method method = new EC2Method(getProvider(), getProvider().getEc2Url(), parameters);
ArrayList<VirtualMachine> list = new ArrayList<VirtualMachine>();
NodeList blocks;
Document doc;
try {
doc = method.invoke();
} catch( EC2Exception e ) {
logger.error(e.getSummary());
throw new CloudException(e);
}
blocks = doc.getElementsByTagName("instancesSet");
for( int i = 0; i < blocks.getLength(); i++ ) {
NodeList instances = blocks.item(i).getChildNodes();
for( int j = 0; j < instances.getLength(); j++ ) {
Node instance = instances.item(j);
if( instance.getNodeName().equals("item") ) {
try {
if( ipPoolFuture != null ) {
addresses = ipPoolFuture.get(30, TimeUnit.SECONDS);
}
else {
addresses = Collections.emptyList();
}
} catch( InterruptedException e ) {
logger.error(e.getMessage());
addresses = Collections.emptyList();
} catch( ExecutionException e ) {
logger.error(e.getMessage());
addresses = Collections.emptyList();
} catch( TimeoutException e ) {
logger.error(e.getMessage());
addresses = Collections.emptyList();
}
VirtualMachine vm = toVirtualMachine(ctx, instance, addresses);
if( options == null || options.matches(vm) ) {
list.add(vm);
}
}
}
}
return list;
} finally {
APITrace.end();
}
}
@Override
public void pause(@Nonnull String vmId) throws InternalException, CloudException {
throw new OperationNotSupportedException("Pause/unpause not supported by the EC2 API");
}
@Override
public @Nonnull String[] mapServiceAction(@Nonnull ServiceAction action) {
if( action.equals(VirtualMachineSupport.ANY) ) {
return new String[]{EC2Method.EC2_PREFIX + "*"};
} else if( action.equals(VirtualMachineSupport.BOOT) ) {
return new String[]{EC2Method.EC2_PREFIX + EC2Method.START_INSTANCES};
} else if( action.equals(VirtualMachineSupport.CLONE) ) {
return new String[0];
} else if( action.equals(VirtualMachineSupport.CREATE_VM) ) {
return new String[]{EC2Method.EC2_PREFIX + EC2Method.RUN_INSTANCES};
} else if( action.equals(VirtualMachineSupport.GET_VM) || action.equals(VirtualMachineSupport.LIST_VM) ) {
return new String[]{EC2Method.EC2_PREFIX + EC2Method.DESCRIBE_INSTANCES};
} else if( action.equals(VirtualMachineSupport.PAUSE) ) {
return new String[]{EC2Method.EC2_PREFIX + EC2Method.STOP_INSTANCES};
} else if( action.equals(VirtualMachineSupport.REBOOT) ) {
return new String[]{EC2Method.EC2_PREFIX + EC2Method.REBOOT_INSTANCES};
} else if( action.equals(VirtualMachineSupport.REMOVE_VM) ) {
return new String[]{EC2Method.EC2_PREFIX + EC2Method.TERMINATE_INSTANCES};
} else if( action.equals(VirtualMachineSupport.TOGGLE_ANALYTICS) ) {
return new String[]{EC2Method.EC2_PREFIX + EC2Method.MONITOR_INSTANCES};
} else if( action.equals(VirtualMachineSupport.VIEW_ANALYTICS) ) {
return new String[]{EC2Method.EC2_PREFIX + EC2Method.GET_METRIC_STATISTICS};
} else if( action.equals(VirtualMachineSupport.VIEW_CONSOLE) ) {
return new String[]{EC2Method.EC2_PREFIX + EC2Method.GET_CONSOLE_OUTPUT};
}
return new String[0];
}
@Override
public void stop(@Nonnull String instanceId, boolean force) throws InternalException, CloudException {
APITrace.begin(getProvider(), "stopVM");
try {
VirtualMachine vm = getVirtualMachine(instanceId);
if( vm == null ) {
throw new CloudException("No such instance: " + instanceId);
}
if( !vm.isPersistent() ) {
throw new OperationNotSupportedException("Instances backed by ephemeral drives are not start/stop capable");
}
Map<String, String> parameters = getProvider().getStandardParameters(getProvider().getContext(), EC2Method.STOP_INSTANCES);
EC2Method method;
parameters.put("InstanceId.1", instanceId);
if( force ) {
parameters.put("Force", "true");
}
method = new EC2Method(getProvider(), getProvider().getEc2Url(), parameters);
try {
method.invoke();
} catch( EC2Exception e ) {
logger.error(e.getSummary());
throw new CloudException(e);
}
} finally {
APITrace.end();
}
}
@Override
public void reboot(@Nonnull String instanceId) throws CloudException, InternalException {
APITrace.begin(getProvider(), "rebootVM");
try {
Map<String, String> parameters = getProvider().getStandardParameters(getProvider().getContext(), EC2Method.REBOOT_INSTANCES);
EC2Method method;
parameters.put("InstanceId.1", instanceId);
method = new EC2Method(getProvider(), getProvider().getEc2Url(), parameters);
try {
method.invoke();
} catch( EC2Exception e ) {
logger.error(e.getSummary());
throw new CloudException(e);
}
} finally {
APITrace.end();
}
}
@Override
public void resume(@Nonnull String vmId) throws CloudException, InternalException {
throw new OperationNotSupportedException("Suspend/resume not supported by the EC2 API");
}
@Override
public void suspend(@Nonnull String vmId) throws CloudException, InternalException {
throw new OperationNotSupportedException("Suspend/resume not supported by the EC2 API");
}
@Override
public void terminate(@Nonnull String instanceId, @Nullable String explanation) throws InternalException, CloudException {
APITrace.begin(getProvider(), "terminateVM");
try {
Map<String, String> parameters = getProvider().getStandardParameters(getProvider().getContext(), EC2Method.TERMINATE_INSTANCES);
EC2Method method;
parameters.put("InstanceId.1", instanceId);
method = new EC2Method(getProvider(), getProvider().getEc2Url(), parameters);
try {
method.invoke();
} catch( EC2Exception e ) {
logger.error(e.getSummary());
throw new CloudException(e);
}
} finally {
APITrace.end();
}
}
@Override
public void unpause(@Nonnull String vmId) throws CloudException, InternalException {
throw new OperationNotSupportedException("Pause/unpause not supported by the EC2 API");
}
private @Nullable ResourceStatus toStatus(@Nullable Node instance) throws CloudException {
if( instance == null ) {
return null;
}
NodeList attrs = instance.getChildNodes();
VmState state = VmState.PENDING;
String vmId = null;
for( int i = 0; i < attrs.getLength(); i++ ) {
Node attr = attrs.item(i);
String name;
name = attr.getNodeName();
if( name.equals("instanceId") ) {
vmId = attr.getFirstChild().getNodeValue().trim();
} else if( name.equals("instanceState") ) {
NodeList details = attr.getChildNodes();
for( int j = 0; j < details.getLength(); j++ ) {
Node detail = details.item(j);
name = detail.getNodeName();
if( name.equals("name") ) {
String value = detail.getFirstChild().getNodeValue().trim();
state = getServerState(value);
}
}
}
}
if( vmId == null ) {
return null;
}
return new ResourceStatus(vmId, state);
}
private @Nullable VmStatus toVmStatus(@Nonnull String status ) {
// ok | impaired | insufficient-data | not-applicable
if( status.equalsIgnoreCase("ok") ) return VmStatus.OK;
else if( status.equalsIgnoreCase("impaired") ) {
return VmStatus.IMPAIRED;
}
else if( status.equalsIgnoreCase("insufficient-data") ) {
return VmStatus.INSUFFICIENT_DATA;
}
else if( status.equalsIgnoreCase("not-applicable") ) {
return VmStatus.NOT_APPLICABLE;
}
else {
return VmStatus.INSUFFICIENT_DATA;
}
}
private @Nullable VirtualMachine toVirtualMachine(@Nonnull ProviderContext ctx, @Nullable Node instance, @Nonnull Iterable<IpAddress> addresses) throws CloudException {
if( instance == null ) {
return null;
}
String rootDeviceName = null;
NodeList attrs = instance.getChildNodes();
VirtualMachine server = new VirtualMachine();
server.setPersistent(false);
server.setProviderOwnerId(ctx.getAccountNumber());
server.setCurrentState(VmState.PENDING);
server.setName(null);
server.setDescription(null);
for( int i = 0; i < attrs.getLength(); i++ ) {
Node attr = attrs.item(i);
String name;
name = attr.getNodeName();
if( name.equals("instanceId") ) {
String value = attr.getFirstChild().getNodeValue().trim();
server.setProviderVirtualMachineId(value);
} else if( name.equals("architecture") ) {
String value = attr.getFirstChild().getNodeValue().trim();
Architecture architecture;
if( value.equalsIgnoreCase("i386") ) {
architecture = Architecture.I32;
} else {
architecture = Architecture.I64;
}
server.setArchitecture(architecture);
} else if( name.equals("imageId") ) {
String value = attr.getFirstChild().getNodeValue().trim();
server.setProviderMachineImageId(value);
} else if( name.equals("kernelId") ) {
String value = attr.getFirstChild().getNodeValue().trim();
server.setTag("kernelImageId", value);
server.setProviderKernelImageId(value);
} else if( name.equals("ramdiskId") ) {
String value = attr.getFirstChild().getNodeValue().trim();
server.setTag("ramdiskImageId", value);
server.setProviderRamdiskImageId(value);
} else if( name.equalsIgnoreCase("subnetId") ) {
server.setProviderSubnetId(attr.getFirstChild().getNodeValue().trim());
} else if( name.equalsIgnoreCase("vpcId") ) {
server.setProviderVlanId(attr.getFirstChild().getNodeValue().trim());
} else if( name.equals("instanceState") ) {
NodeList details = attr.getChildNodes();
for( int j = 0; j < details.getLength(); j++ ) {
Node detail = details.item(j);
name = detail.getNodeName();
if( name.equals("name") ) {
String value = detail.getFirstChild().getNodeValue().trim();
server.setCurrentState(getServerState(value));
}
}
} else if( name.equals("privateDnsName") ) {
if( attr.hasChildNodes() ) {
String value = attr.getFirstChild().getNodeValue();
RawAddress[] addrs = server.getPrivateAddresses();
server.setPrivateDnsAddress(value);
if( addrs == null || addrs.length < 1 ) {
value = guess(value);
if( value != null ) {
server.setPrivateAddresses(new RawAddress(value));
}
}
}
} else if( name.equals("dnsName") ) {
if( attr.hasChildNodes() ) {
String value = attr.getFirstChild().getNodeValue();
RawAddress[] addrs = server.getPublicAddresses();
server.setPublicDnsAddress(value);
}
} else if( name.equals("privateIpAddress") ) {
if( attr.hasChildNodes() ) {
String value = attr.getFirstChild().getNodeValue();
server.setPrivateAddresses(new RawAddress(value));
}
} else if( name.equals("ipAddress") ) {
if( attr.hasChildNodes() ) {
String value = attr.getFirstChild().getNodeValue();
server.setPublicAddresses(new RawAddress(value));
for( IpAddress addr : addresses ) {
if( value.equals(addr.getRawAddress().getIpAddress()) ) {
server.setProviderAssignedIpAddressId(addr.getProviderIpAddressId());
break;
}
}
}
} else if( name.equals("rootDeviceType") ) {
if( attr.hasChildNodes() ) {
server.setPersistent(attr.getFirstChild().getNodeValue().equalsIgnoreCase("ebs"));
}
} else if( name.equals("tagSet") ) {
Map<String, String> tags = getProvider().getTagsFromTagSet(attr);
if( tags != null && tags.size() > 0 ) {
server.setTags(tags);
for( Map.Entry<String, String> entry : tags.entrySet() ) {
if( entry.getKey().equalsIgnoreCase("name") ) {
server.setName(entry.getValue());
} else if( entry.getKey().equalsIgnoreCase("description") ) {
server.setDescription(entry.getValue());
}
}
}
} else if( name.equals("instanceType") ) {
String value = attr.getFirstChild().getNodeValue().trim();
server.setProductId(value);
} else if( name.equals("launchTime") ) {
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
fmt.setCalendar(UTC_CALENDAR);
String value = attr.getFirstChild().getNodeValue().trim();
try {
server.setLastBootTimestamp(fmt.parse(value).getTime());
server.setCreationTimestamp(server.getLastBootTimestamp());
} catch( ParseException e ) {
logger.error(e);
throw new CloudException(e);
}
} else if( name.equals("platform") ) {
if( attr.hasChildNodes() ) {
Platform platform = Platform.guess(attr.getFirstChild().getNodeValue());
if( platform.equals(Platform.UNKNOWN) ) {
platform = Platform.UNIX;
}
server.setPlatform(platform);
}
} else if( name.equals("placement") ) {
NodeList details = attr.getChildNodes();
for( int j = 0; j < details.getLength(); j++ ) {
Node detail = details.item(j);
name = detail.getNodeName();
if( name.equals("availabilityZone") ) {
if( detail.hasChildNodes() ) {
String value = detail.getFirstChild().getNodeValue().trim();
server.setProviderDataCenterId(value);
}
}
}
} else if( name.equals("networkInterfaceSet") ) {
ArrayList<String> networkInterfaceIds = new ArrayList<String>();
if( attr.hasChildNodes() ) {
NodeList items = attr.getChildNodes();
for( int j = 0; j < items.getLength(); j++ ) {
Node item = items.item(j);
if( item.getNodeName().equals("item") && item.hasChildNodes() ) {
NodeList parts = item.getChildNodes();
String networkInterfaceId = null;
for( int k = 0; k < parts.getLength(); k++ ) {
Node part = parts.item(k);
if( part.getNodeName().equalsIgnoreCase("networkInterfaceId") ) {
if( part.hasChildNodes() ) {
networkInterfaceId = part.getFirstChild().getNodeValue().trim();
}
}
}
if( networkInterfaceId != null ) {
networkInterfaceIds.add(networkInterfaceId);
}
}
}
}
if( networkInterfaceIds.size() > 0 ) {
server.setProviderNetworkInterfaceIds(networkInterfaceIds.toArray(new String[networkInterfaceIds.size()]));
}
/*
[FIXME?] TODO: Really networkInterfaceSet needs to be own type/resource
Example:
<networkInterfaceSet>
<item>
<networkInterfaceId>eni-1a2b3c4d</networkInterfaceId>
<subnetId>subnet-1a2b3c4d</subnetId>
<vpcId>vpc-1a2b3c4d</vpcId>
<description>Primary network interface</description>
<ownerId>111122223333</ownerId>
<status>in-use</status>
<macAddress>1b:2b:3c:4d:5e:6f</macAddress>
<privateIpAddress>10.0.0.12</privateIpAddress>
<sourceDestCheck>true</sourceDestCheck>
<groupSet>
<item>
<groupId>sg-1a2b3c4d</groupId>
<groupName>my-security-group</groupName>
</item>
</groupSet>
<attachment>
<attachmentId>eni-attach-1a2b3c4d</attachmentId>
<deviceIndex>0</deviceIndex>
<status>attached</status>
<attachTime>YYYY-MM-DDTHH:MM:SS+0000</attachTime>
<deleteOnTermination>true</deleteOnTermination>
</attachment>
<association>
<publicIp>198.51.100.63</publicIp>
<ipOwnerId>111122223333</ipOwnerId>
</association>
<privateIpAddressesSet>
<item>
<privateIpAddress>10.0.0.12</privateIpAddress>
<primary>true</primary>
<association>
<publicIp>198.51.100.63</publicIp>
<ipOwnerId>111122223333</ipOwnerId>
</association>
</item>
<item>
<privateIpAddress>10.0.0.14</privateIpAddress>
<primary>false</primary>
<association>
<publicIp>198.51.100.177</publicIp>
<ipOwnerId>111122223333</ipOwnerId>
</association>
</item>
</privateIpAddressesSet>
</item>
</networkInterfaceSet>
*/
} else if( name.equals("keyName") ) {
String value = attr.getFirstChild().getNodeValue().trim();
server.setProviderKeypairId(value);
} else if( name.equals("groupSet") ) {
ArrayList<String> firewalls = new ArrayList<String>();
if( attr.hasChildNodes() ) {
NodeList tags = attr.getChildNodes();
for( int j = 0; j < tags.getLength(); j++ ) {
Node tag = tags.item(j);
if( tag.getNodeName().equals("item") && tag.hasChildNodes() ) {
NodeList parts = tag.getChildNodes();
String groupId = null;
for( int k = 0; k < parts.getLength(); k++ ) {
Node part = parts.item(k);
if( part.getNodeName().equalsIgnoreCase("groupId") ) {
if( part.hasChildNodes() ) {
groupId = part.getFirstChild().getNodeValue().trim();
}
}
}
if( groupId != null ) {
firewalls.add(groupId);
}
}
}
}
if( firewalls.size() > 0 ) {
server.setProviderFirewallIds(firewalls.toArray(new String[firewalls.size()]));
}
} else if( "blockDeviceMapping".equals(name) && attr.hasChildNodes() ) {
List<Volume> volumes = new ArrayList<Volume>();
if( attr.hasChildNodes() ) {
NodeList blockDeviceMapping = attr.getChildNodes();
for( int j = 0; j < blockDeviceMapping.getLength(); j++ ) {
Node bdmItems = blockDeviceMapping.item(j);
if( bdmItems.getNodeName().equals("item") && bdmItems.hasChildNodes() ) {
NodeList items = bdmItems.getChildNodes();
Volume volume = new Volume();
for( int k = 0; k < items.getLength(); k++ ) {
Node item = items.item(k);
String itemNodeName = item.getNodeName();
if( "deviceName".equals(itemNodeName) ) {
volume.setDeviceId(AWSCloud.getTextValue(item));
} else if( "ebs".equals(itemNodeName) ) {
NodeList ebsNodeList = item.getChildNodes();
for( int l = 0; l < ebsNodeList.getLength(); l++ ) {
Node ebsNode = ebsNodeList.item(l);
String ebsNodeName = ebsNode.getNodeName();
if( "volumeId".equals(ebsNodeName) ) {
volume.setProviderVolumeId(AWSCloud.getTextValue(ebsNode));
} else if( "status".equals(ebsNodeName) ) {
volume.setCurrentState(EBSVolume.toVolumeState(ebsNode));
} else if( "deleteOnTermination".equals(ebsNodeName) ) {
volume.setDeleteOnVirtualMachineTermination(AWSCloud.getBooleanValue(ebsNode));
}
}
}
}
if( volume.getDeviceId() != null ) {
volumes.add(volume);
}
}
}
}
if( volumes.size() > 0 ) {
server.setVolumes(volumes.toArray(new Volume[volumes.size()]));
}
} else if( "rootDeviceName".equals(name) && attr.hasChildNodes() ) {
rootDeviceName = AWSCloud.getTextValue(attr);
} else if( "ebsOptimized".equals(name) && attr.hasChildNodes() ) {
server.setIoOptimized(Boolean.valueOf(attr.getFirstChild().getNodeValue()));
} else if( "sourceDestCheck".equals(name) && attr.hasChildNodes() ) {
/**
* note: a value of <sourceDestCheck>true</sourceDestCheck> means this instance cannot
* function as a NAT instance, so we negate the value to indicate if it is allowed
*/
server.setIpForwardingAllowed(!Boolean.valueOf(attr.getFirstChild().getNodeValue()));
} else if( "stateReasonMessage".equals(name) ) {
server.setStateReasonMessage(attr.getFirstChild().getNodeValue().trim());
} else if( "iamInstanceProfile".equals(name) && attr.hasChildNodes() ) {
NodeList details = attr.getChildNodes();
for( int j = 0; j < details.getLength(); j++ ) {
Node detail = details.item(j);
name = detail.getNodeName();
if( name.equals("arn") ) {
if( detail.hasChildNodes() ) {
String value = detail.getFirstChild().getNodeValue().trim();
server.setProviderRoleId(value);
}
}
}
}
}
if( server.getPlatform() == null ) {
server.setPlatform(Platform.UNKNOWN);
}
server.setProviderRegionId(ctx.getRegionId());
if( server.getName() == null ) {
server.setName(server.getProviderVirtualMachineId());
}
if( server.getDescription() == null ) {
server.setDescription(server.getName() + " (" + server.getProductId() + ")");
}
if( server.getArchitecture() == null && server.getProductId() != null ) {
server.setArchitecture(getArchitecture(server.getProductId()));
} else if( server.getArchitecture() == null ) {
server.setArchitecture(Architecture.I64);
}
// find the root device in the volumes list and set boolean value
if( rootDeviceName != null && server.getVolumes() != null ) {
for( Volume volume : server.getVolumes() ) {
if( rootDeviceName.equals(volume.getDeviceId()) ) {
volume.setRootVolume(true);
break;
}
}
}
return server;
}
@Override
public void disableAnalytics(@Nonnull String instanceId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "disableVMAnalytics");
try {
if( getProvider().getEC2Provider().isAWS() || getProvider().getEC2Provider().isEnStratus() ) {
Map<String, String> parameters = getProvider().getStandardParameters(getProvider().getContext(), EC2Method.UNMONITOR_INSTANCES);
EC2Method method;
parameters.put("InstanceId.1", instanceId);
method = new EC2Method(getProvider(), getProvider().getEc2Url(), parameters);
try {
method.invoke();
} catch( EC2Exception e ) {
logger.error(e.getSummary());
throw new CloudException(e);
}
}
} finally {
APITrace.end();
}
}
private @Nullable VirtualMachineProduct toProduct(@Nonnull JSONObject json) throws InternalException {
/*
{
"architectures":["I32"],
"id":"m1.small",
"name":"Small Instance (m1.small)",
"description":"Small Instance (m1.small)",
"cpuCount":1,
"rootVolumeSizeInGb":160,
"ramSizeInMb": 1700
},
*/
VirtualMachineProduct prd = new VirtualMachineProduct();
try {
if( json.has("id") ) {
prd.setProviderProductId(json.getString("id"));
} else {
return null;
}
if( json.has("name") ) {
prd.setName(json.getString("name"));
} else {
prd.setName(prd.getProviderProductId());
}
if( json.has("description") ) {
prd.setDescription(json.getString("description"));
} else {
prd.setDescription(prd.getName());
}
if( json.has("cpuCount") ) {
prd.setCpuCount(json.getInt("cpuCount"));
} else {
prd.setCpuCount(1);
}
if( json.has("rootVolumeSizeInGb") ) {
prd.setRootVolumeSize(new Storage<Gigabyte>(json.getInt("rootVolumeSizeInGb"), Storage.GIGABYTE));
} else {
prd.setRootVolumeSize(new Storage<Gigabyte>(1, Storage.GIGABYTE));
}
if( json.has("ramSizeInMb") ) {
prd.setRamSize(new Storage<Megabyte>(json.getInt("ramSizeInMb"), Storage.MEGABYTE));
} else {
prd.setRamSize(new Storage<Megabyte>(512, Storage.MEGABYTE));
}
if( json.has("standardHourlyRates") ) {
JSONArray rates = json.getJSONArray("standardHourlyRates");
for( int i = 0; i < rates.length(); i++ ) {
JSONObject rate = rates.getJSONObject(i);
if( rate.has("rate") ) {
prd.setStandardHourlyRate((float) rate.getDouble("rate"));
}
}
}
} catch( JSONException e ) {
throw new InternalException(e);
}
return prd;
}
@Override
public void updateTags(@Nonnull String vmId, @Nonnull Tag... tags) throws CloudException, InternalException {
getProvider().createTags(vmId, tags);
}
@Override
public void updateTags(@Nonnull String[] vmIds, @Nonnull Tag... tags) throws CloudException, InternalException {
getProvider().createTags(vmIds, tags);
}
@Override
public void removeTags(@Nonnull String vmId, @Nonnull Tag... tags) throws CloudException, InternalException {
getProvider().removeTags(vmId, tags);
}
@Override
public void removeTags(@Nonnull String[] vmIds, @Nonnull Tag... tags) throws CloudException, InternalException {
getProvider().removeTags(vmIds, tags);
}
}
| TheWeatherCompany/grid-api/issues/#722
Return userData value for instances in plaintext
| src/main/java/org/dasein/cloud/aws/compute/EC2Instance.java | TheWeatherCompany/grid-api/issues/#722 | <ide><path>rc/main/java/org/dasein/cloud/aws/compute/EC2Instance.java
<ide> getProvider(),
<ide> getProvider().getEc2Url()
<ide> );
<del> return callable.call();
<add> String encodedUserDataValue = callable.call();
<add> return new String(Base64.decodeBase64(encodedUserDataValue));
<ide> } catch( EC2Exception e ) {
<ide> logger.error(e.getSummary());
<ide> throw new CloudException(e); |
|
Java | apache-2.0 | ab3c0ef88a77b6a7572375188c5346c8f55d3ee7 | 0 | leerduo/DanmakuFlameMaster,Jaeandroid/DanmakuFlameMaster,PC-ai/DanmakuFlameMaster,xiaomeixw/DanmakuFlameMaster,whstudy/DanmakuFlameMaster,jwzhangjie/DanmakuFlameMaster,jackeychens/DanmakuFlameMaster,yoyojacky/DanmakuFlameMaster,AbooJan/DanmakuFlameMaster,happycodinggirl/DanmakuFlameMaster,cgpllx/DanmakuFlameMaster,chuangWu/DanmakuFlameMaster,wen14148/DanmakuFlameMaster,guoxiaojun001/DanmakuFlameMaster,zzuli4519/DanmakuFlameMaster,wangkang0627/DanmakuFlameMaster,Bilibili/DanmakuFlameMaster,kmfish/DanmakuFlameMaster,liuyingwen/DanmakuFlameMaster,hgl888/DanmakuFlameMaster,zzhopen/DanmakuFlameMaster,xyczero/DanmakuFlameMaster,GeekHades/DanmakuFlameMaster,lcj1005/DanmakuFlameMaster,leglars/DanmakuFlameMaster,PenguinK/DanmakuFlameMaster,vfs1234/DanmakuFlameMaster,10045125/DanmakuFlameMaster,tsdl2013/DanmakuFlameMaster,yangpeiyong/DanmakuFlameMaster,bajian/DanmakuFlameMaster,dersoncheng/DanmakuFlameMaster,winiceo/DanmakuFlameMaster,ctiao/DanmakuFlameMaster,chenquanjun/DanmakuFlameMaster,xabad/DanmakuFlameMaster,msdgwzhy6/DanmakuFlameMaster,mowangdk/DanmakuFlameMaster,java02014/DanmakuFlameMaster,Suninus/DanmakuFlameMaster |
package master.flame.danmaku.danmaku.model;
public class SpecialDanmaku extends BaseDanmaku {
public float beginX, beginY;
public float endX, endY;
public float deltaX, deltaY;
public long translationDuration;
public long translationStartDelay;
public int beginAlpha;
public int endAlpha;
public int deltaAlpha;
public long alphaDuration;
public float rotateX, rotateZ;
public float pivotX, pivotY;
private float[] currStateValues = new float[4];
@Override
public void layout(IDisplayer displayer, float x, float y) {
getRectAtTime(displayer, mTimer.currMillisecond);
}
@Override
public float[] getRectAtTime(IDisplayer displayer, long currTime) {
if (!isMeasured())
return null;
long deltaTime = currTime - time;
// caculate alpha
if (alphaDuration > 0 && deltaAlpha != 0) {
if(deltaTime >= alphaDuration){
alpha = endAlpha;
}else{
float alphaProgress = deltaTime / (float) alphaDuration;
int vectorAlpha = (int) (deltaAlpha * alphaProgress);
alpha = beginAlpha + vectorAlpha;
}
}
// caculate x y
float currX = beginX;
float currY = beginY;
long dtime = deltaTime - translationStartDelay;
if (translationDuration > 0 && dtime >= 0 && dtime <= translationDuration) {
float tranalationProgress = dtime / (float) translationDuration;
if (deltaX != 0) {
float vectorX = deltaX * tranalationProgress;
currX = beginX + vectorX;
}
if (deltaY != 0) {
float vectorY = deltaY * tranalationProgress;
currY = beginY + vectorY;
}
} else if(dtime > translationDuration){
currX = endX;
currY = endY;
}
currStateValues[0] = currX;
currStateValues[1] = currY;
currStateValues[2] = currX + paintWidth;
currStateValues[3] = currY + paintHeight;
this.setVisibility(!isOutside());
return currStateValues;
}
@Override
public float getLeft() {
return currStateValues[0];
}
@Override
public float getTop() {
return currStateValues[1];
}
@Override
public float getRight() {
return currStateValues[2];
}
@Override
public float getBottom() {
return currStateValues[3];
}
@Override
public int getType() {
return TYPE_SPECIAL;
}
public void setTranslationData(float beginX, float beginY, float endX, float endY,
long translationDuration, long translationStartDelay) {
this.beginX = beginX;
this.beginY = beginY;
this.endX = endX;
this.endY = endY;
this.deltaX = endX - beginX;
this.deltaY = endY - beginY;
this.translationDuration = translationDuration;
this.translationStartDelay = translationStartDelay;
}
public void setAlphaData(int beginAlpha, int endAlpha, long alphaDuration) {
this.beginAlpha = beginAlpha;
this.endAlpha = endAlpha;
this.deltaAlpha = endAlpha - beginAlpha;
this.alphaDuration = alphaDuration;
if(deltaAlpha != 0 && beginAlpha != AlphaValue.MAX){
alpha = beginAlpha;
}
}
}
| DanmakuFlameMaster/src/main/java/master/flame/danmaku/danmaku/model/SpecialDanmaku.java |
package master.flame.danmaku.danmaku.model;
public class SpecialDanmaku extends BaseDanmaku {
public float beginX, beginY;
public float endX, endY;
public float deltaX, deltaY;
public long translationDuration;
public long translationStartDelay;
public int beginAlpha;
public int endAlpha;
public int deltaAlpha;
public long alphaDuration;
public float rotateX, rotateZ;
public float pivotX, pivotY;
private float[] currStateValues = new float[4];
@Override
public void layout(IDisplayer displayer, float x, float y) {
getRectAtTime(displayer, mTimer.currMillisecond);
}
@Override
public float[] getRectAtTime(IDisplayer displayer, long currTime) {
if (!isMeasured())
return null;
long deltaTime = currTime - time;
// caculate alpha
if (alphaDuration > 0 && deltaAlpha != 0) {
if(deltaTime >= alphaDuration){
alpha = endAlpha;
}else{
float alphaProgress = deltaTime / (float) alphaDuration;
int vectorAlpha = (int) (deltaAlpha * alphaProgress);
alpha = beginAlpha + vectorAlpha;
}
}
// caculate x y
float currX = beginX;
float currY = beginY;
long dtime = deltaTime - translationStartDelay;
if (translationDuration > 0 && dtime >= 0 && dtime <= translationDuration) {
float tranalationProgress = dtime / (float) translationDuration;
if (deltaX != 0) {
float vectorX = deltaX * tranalationProgress;
currX = beginX + vectorX;
}
if (deltaY != 0) {
float vectorY = deltaY * tranalationProgress;
currY = beginY + vectorY;
}
} else if(dtime > translationDuration){
currX = endX;
currY = endY;
}
currStateValues[0] = currX;
currStateValues[1] = currY;
currStateValues[2] = currX + paintWidth;
currStateValues[3] = currY + paintHeight;
this.visibility = isOutside() ? INVISIBLE : VISIBLE;
return currStateValues;
}
@Override
public float getLeft() {
return currStateValues[0];
}
@Override
public float getTop() {
return currStateValues[1];
}
@Override
public float getRight() {
return currStateValues[2];
}
@Override
public float getBottom() {
return currStateValues[3];
}
@Override
public int getType() {
return TYPE_SPECIAL;
}
public void setTranslationData(float beginX, float beginY, float endX, float endY,
long translationDuration, long translationStartDelay) {
this.beginX = beginX;
this.beginY = beginY;
this.endX = endX;
this.endY = endY;
this.deltaX = endX - beginX;
this.deltaY = endY - beginY;
this.translationDuration = translationDuration;
this.translationStartDelay = translationStartDelay;
}
public void setAlphaData(int beginAlpha, int endAlpha, long alphaDuration) {
this.beginAlpha = beginAlpha;
this.endAlpha = endAlpha;
this.deltaAlpha = endAlpha - beginAlpha;
this.alphaDuration = alphaDuration;
if(deltaAlpha != 0 && beginAlpha != AlphaValue.MAX){
alpha = beginAlpha;
}
}
}
| SpecialDanmaku:Apply VISIBLE_RESET_FLAG
| DanmakuFlameMaster/src/main/java/master/flame/danmaku/danmaku/model/SpecialDanmaku.java | SpecialDanmaku:Apply VISIBLE_RESET_FLAG | <ide><path>anmakuFlameMaster/src/main/java/master/flame/danmaku/danmaku/model/SpecialDanmaku.java
<ide> currStateValues[2] = currX + paintWidth;
<ide> currStateValues[3] = currY + paintHeight;
<ide>
<del> this.visibility = isOutside() ? INVISIBLE : VISIBLE;
<add> this.setVisibility(!isOutside());
<ide>
<ide> return currStateValues;
<ide> } |
|
Java | mpl-2.0 | 4733384b8499bece99038f54c41fc3af7b057d47 | 0 | deanhiller/databus,deanhiller/databus,deanhiller/databus,deanhiller/databus,deanhiller/databus,deanhiller/databus,deanhiller/databus | package controllers.gui;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import models.message.ChartVarMeta;
import models.message.StreamEditor;
import models.message.StreamModule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import play.mvc.Controller;
import play.mvc.With;
import controllers.gui.auth.GuiSecure;
import controllers.gui.util.ChartUtil;
import controllers.modules2.framework.ModuleController;
import controllers.modules2.framework.RawProcessorFactory;
import controllers.modules2.framework.procs.PullProcessor;
@With(GuiSecure.class)
public class MyDataStreams extends Controller {
private static final Logger log = LoggerFactory.getLogger(MyDataStreams.class);
public static void editAggregation(String encoded) {
if("start".equals(encoded)) {
render(null, null, encoded);
}
StreamEditor editor = DataStreamUtil.decode(encoded);
StreamTuple tuple = findCurrentStream(editor);
StreamModule stream = tuple.getStream();
String path = tuple.getPath();
render(stream, path, encoded);
}
public static void postAggregation(String encoded, String name) {
StreamModule stream = new StreamModule();
stream.setName(name);
StreamEditor editor;
if("start".equals(encoded)) {
editor = new StreamEditor();
editor.setStream(stream);
} else {
editor = DataStreamUtil.decode(encoded);
StreamTuple tuple = findCurrentStream(editor);
tuple.getStream().getStreams().add(stream);
editor.getLocation().add(tuple.getStream().getStreams().size()-1);
}
encoded = DataStreamUtil.encode(editor);
viewAggregation(encoded);
}
public static void viewAggregation(String encoded) {
StreamEditor editor = DataStreamUtil.decode(encoded);
StreamTuple tuple = findCurrentStream(editor);
StreamModule stream = tuple.getStream();
String path = tuple.getPath();
render(stream, path, encoded);
}
public static void aggregationComplete(String encoded) {
StreamEditor editor = DataStreamUtil.decode(encoded);
List<Integer> locs = editor.getLocation();
locs.remove(locs.size()-1);
encoded = DataStreamUtil.encode(editor);
viewAggregation(encoded);
}
private static StreamTuple findCurrentStream(StreamEditor editor) {
StreamModule currentStr = editor.getStream();
if(editor.getLocation().size() == 0)
return new StreamTuple(currentStr, currentStr.getName());;
String path = currentStr.getName();
//first, find current location of what user was just looking at...
for(Integer loc : editor.getLocation()) {
currentStr = currentStr.getStreams().get(loc);
path += " -> "+currentStr.getName();
}
return new StreamTuple(currentStr, path);
}
public static void editStream(String encoded, int index) {
StreamEditor editor = DataStreamUtil.decode(encoded);
StreamTuple tuple = findCurrentStream(editor);
StreamModule stream = tuple.getStream();
if(index < 0) {
//add
StreamModule child = new StreamModule();
child.setModule("stream");
stream.getStreams().add(child);
editor.getLocation().add(stream.getStreams().size()-1);
stream = child;
} else {
//edit
stream = stream.getStreams().get(index-1);
editor.getLocation().add(index-1);
}
encoded = DataStreamUtil.encode(editor);
render(stream, encoded);
}
public static void postStream(String encoded, String name) {
StreamEditor editor = DataStreamUtil.decode(encoded);
StreamTuple tuple = findCurrentStream(editor);
StreamModule stream = tuple.getStream();
stream.setName(name);
encoded = DataStreamUtil.encode(editor);
viewStream(encoded);
}
public static void viewStream(String encoded) {
StreamEditor editor = DataStreamUtil.decode(encoded);
StreamTuple tuple = findCurrentStream(editor);
StreamModule stream = tuple.getStream();
String path = tuple.getPath();
render(encoded, stream, path);
}
public static void editModule(String encoded, int index) {
RawProcessorFactory factory = ModuleController.fetchFactory();
List<String> modules = factory.fetchProcessorNames();
StreamEditor editor = DataStreamUtil.decode(encoded);
StreamTuple tuple = findCurrentStream(editor);
StreamModule parent = tuple.getStream();
StreamModule module = null;
if(index >= 0) {
module = parent.getStreams().get(index-1);
}
encoded = DataStreamUtil.encode(editor);
render(modules, module, encoded, index);
}
public static void postModule(String encoded, String moduleName, int index) {
StreamEditor editor = DataStreamUtil.decode(encoded);
StreamTuple tuple = findCurrentStream(editor);
StreamModule parent = tuple.getStream();
if(index >= 0) {
StreamModule module = parent.getStreams().get(index-1);
module.setModule(moduleName);
} else {
StreamModule module = new StreamModule();
module.setModule(moduleName);
parent.getStreams().add(module);
index = parent.getStreams().size(); //the one we just added
}
encoded = DataStreamUtil.encode(editor);
editModuleParams(encoded, index);
}
public static void editModuleParams(String encoded, int index) {
StreamEditor editor = DataStreamUtil.decode(encoded);
StreamTuple tuple = findCurrentStream(editor);
String path = tuple.getPath();
StreamModule parent = tuple.getStream();
StreamModule module = parent.getStreams().get(index-1);
RawProcessorFactory factory = ModuleController.fetchFactory();
Map<String, PullProcessor> nameToProc = factory.fetchPullProcessors();
PullProcessor proc = nameToProc.get(module.getModule());
Map<String, ChartVarMeta> paramMeta = proc.getParameterMeta();
Map<String, String> params2 = module.getParams();
List<VarWrapper> paramList = new ArrayList<VarWrapper>();
//here we add variables. to distinguish it from any other parameters that may be coming in like "encoded" above or "index", etc....
for(Entry<String, ChartVarMeta> entry : paramMeta.entrySet()) {
VarWrapper var = new VarWrapper(entry.getValue());
String value = params2.get(entry.getKey());
if(value == null)
value = entry.getValue().getDefaultValue();
var.setValue(value);
paramList.add(var);
}
//We need to lookup the parameters here and form a dynamic form just like we do in the charting wizard
render(encoded, index, module, path, paramList);
}
public static void postModuleParams(String encoded, int index) {
StreamEditor editor = DataStreamUtil.decode(encoded);
StreamTuple tuple = findCurrentStream(editor);
StreamModule parent = tuple.getStream();
StreamModule module = parent.getStreams().get(index-1);
//apply parameters here...decode and re-encode StreamEditor
Map<String, String[]> paramMap = params.all();
Map<String, String> params = module.getParams();
params.clear(); //clear whatever the previous module was before
for(String key : paramMap.keySet()) {
if(key.startsWith("variables.")) {
String[] values = paramMap.get(key);
String value = values[0];
String javascriptKey = key.substring("variables.".length());
params.put(javascriptKey, value);
}
}
encoded = DataStreamUtil.encode(editor);
viewStream(encoded);
}
public static void streamComplete(String encoded) {
StreamEditor editor = DataStreamUtil.decode(encoded);
List<Integer> locs = editor.getLocation();
locs.remove(locs.size()-1);
encoded = DataStreamUtil.encode(editor);
viewAggregation(encoded);
}
}
| webapp/app/controllers/gui/MyDataStreams.java | package controllers.gui;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import models.message.ChartVarMeta;
import models.message.StreamEditor;
import models.message.StreamModule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import play.mvc.Controller;
import play.mvc.With;
import controllers.gui.auth.GuiSecure;
import controllers.gui.util.ChartUtil;
import controllers.modules2.framework.ModuleController;
import controllers.modules2.framework.RawProcessorFactory;
import controllers.modules2.framework.procs.PullProcessor;
@With(GuiSecure.class)
public class MyDataStreams extends Controller {
private static final Logger log = LoggerFactory.getLogger(MyDataStreams.class);
public static void editAggregation(String encoded) {
if("start".equals(encoded)) {
render(null, null, encoded);
}
StreamEditor editor = DataStreamUtil.decode(encoded);
StreamTuple tuple = findCurrentStream(editor);
StreamModule stream = tuple.getStream();
String path = tuple.getPath();
render(stream, path, encoded);
}
public static void postAggregation(String encoded, String name) {
StreamModule stream = new StreamModule();
stream.setName(name);
StreamEditor editor;
if("start".equals(encoded)) {
editor = new StreamEditor();
editor.setStream(stream);
} else {
editor = DataStreamUtil.decode(encoded);
StreamTuple tuple = findCurrentStream(editor);
tuple.getStream().getStreams().add(stream);
editor.getLocation().add(tuple.getStream().getStreams().size()-1);
}
encoded = DataStreamUtil.encode(editor);
viewAggregation(encoded);
}
public static void viewAggregation(String encoded) {
StreamEditor editor = DataStreamUtil.decode(encoded);
StreamTuple tuple = findCurrentStream(editor);
StreamModule stream = tuple.getStream();
String path = tuple.getPath();
render(stream, path, encoded);
}
public static void aggregationComplete(String encoded) {
StreamEditor editor = DataStreamUtil.decode(encoded);
List<Integer> locs = editor.getLocation();
locs.remove(locs.size()-1);
encoded = DataStreamUtil.encode(editor);
viewAggregation(encoded);
}
private static StreamTuple findCurrentStream(StreamEditor editor) {
StreamModule currentStr = editor.getStream();
if(editor.getLocation().size() == 0)
return new StreamTuple(currentStr, currentStr.getName());;
String path = currentStr.getName();
//first, find current location of what user was just looking at...
for(Integer loc : editor.getLocation()) {
currentStr = currentStr.getStreams().get(loc);
path += " -> "+currentStr.getName();
}
return new StreamTuple(currentStr, path);
}
public static void editStream(String encoded, int index) {
StreamEditor editor = DataStreamUtil.decode(encoded);
StreamTuple tuple = findCurrentStream(editor);
StreamModule stream = tuple.getStream();
if(index < 0) {
//add
StreamModule child = new StreamModule();
child.setModule("stream");
stream.getStreams().add(child);
editor.getLocation().add(stream.getStreams().size()-1);
stream = child;
} else {
//edit
stream = stream.getStreams().get(index-1);
editor.getLocation().add(index-1);
}
encoded = DataStreamUtil.encode(editor);
render(stream, encoded);
}
public static void postStream(String encoded, String name) {
StreamEditor editor = DataStreamUtil.decode(encoded);
StreamTuple tuple = findCurrentStream(editor);
StreamModule stream = tuple.getStream();
stream.setName(name);
encoded = DataStreamUtil.encode(editor);
viewStream(encoded);
}
public static void viewStream(String encoded) {
StreamEditor editor = DataStreamUtil.decode(encoded);
StreamTuple tuple = findCurrentStream(editor);
StreamModule stream = tuple.getStream();
String path = tuple.getPath();
render(encoded, stream, path);
}
public static void editModule(String encoded, int index) {
RawProcessorFactory factory = ModuleController.fetchFactory();
List<String> modules = factory.fetchProcessorNames();
StreamEditor editor = DataStreamUtil.decode(encoded);
StreamTuple tuple = findCurrentStream(editor);
StreamModule parent = tuple.getStream();
StreamModule module = null;
if(index >= 0) {
module = parent.getStreams().get(index-1);
}
encoded = DataStreamUtil.encode(editor);
render(modules, module, encoded, index);
}
public static void postModule(String encoded, String moduleName, int index) {
StreamEditor editor = DataStreamUtil.decode(encoded);
StreamTuple tuple = findCurrentStream(editor);
StreamModule parent = tuple.getStream();
if(index >= 0) {
StreamModule module = parent.getStreams().get(index-1);
module.setModule(moduleName);
} else {
StreamModule module = new StreamModule();
module.setModule(moduleName);
parent.getStreams().add(module);
index = parent.getStreams().size(); //the one we just added
}
encoded = DataStreamUtil.encode(editor);
editModuleParams(encoded, index);
}
public static void editModuleParams(String encoded, int index) {
StreamEditor editor = DataStreamUtil.decode(encoded);
StreamTuple tuple = findCurrentStream(editor);
String path = tuple.getPath();
StreamModule parent = tuple.getStream();
StreamModule module = parent.getStreams().get(index-1);
RawProcessorFactory factory = ModuleController.fetchFactory();
Map<String, PullProcessor> nameToProc = factory.fetchPullProcessors();
PullProcessor proc = nameToProc.get(module.getModule());
Map<String, ChartVarMeta> paramMeta = proc.getParameterMeta();
Map<String, String> params2 = module.getParams();
List<VarWrapper> paramList = new ArrayList<VarWrapper>();
//here we add variables. to distinguish it from any other parameters that may be coming in like "encoded" above or "index", etc....
for(Entry<String, ChartVarMeta> entry : paramMeta.entrySet()) {
VarWrapper var = new VarWrapper(entry.getValue());
String value = params2.get(entry.getKey());
if(value == null)
value = entry.getValue().getDefaultValue();
var.setValue(value);
paramList.add(var);
}
//We need to lookup the parameters here and form a dynamic form just like we do in the charting wizard
render(encoded, index, module, path, paramList);
}
public static void postModuleParams(String encoded, int index) {
StreamEditor editor = DataStreamUtil.decode(encoded);
StreamTuple tuple = findCurrentStream(editor);
StreamModule parent = tuple.getStream();
StreamModule module = parent.getStreams().get(index-1);
//apply parameters here...decode and re-encode StreamEditor
Map<String, String[]> paramMap = params.all();
for(String key : paramMap.keySet()) {
if(key.startsWith("variables.")) {
String[] values = paramMap.get(key);
String value = values[0];
String javascriptKey = key.substring("variables.".length());
module.getParams().put(javascriptKey, value);
}
}
encoded = DataStreamUtil.encode(editor);
viewStream(encoded);
}
public static void streamComplete(String encoded) {
StreamEditor editor = DataStreamUtil.decode(encoded);
List<Integer> locs = editor.getLocation();
locs.remove(locs.size()-1);
encoded = DataStreamUtil.encode(editor);
viewAggregation(encoded);
}
}
| fix the edit when changing modules so params get cleared out
| webapp/app/controllers/gui/MyDataStreams.java | fix the edit when changing modules so params get cleared out | <ide><path>ebapp/app/controllers/gui/MyDataStreams.java
<ide>
<ide> //apply parameters here...decode and re-encode StreamEditor
<ide> Map<String, String[]> paramMap = params.all();
<del>
<add> Map<String, String> params = module.getParams();
<add> params.clear(); //clear whatever the previous module was before
<ide> for(String key : paramMap.keySet()) {
<ide> if(key.startsWith("variables.")) {
<ide> String[] values = paramMap.get(key);
<ide> String value = values[0];
<ide> String javascriptKey = key.substring("variables.".length());
<del> module.getParams().put(javascriptKey, value);
<add> params.put(javascriptKey, value);
<ide> }
<ide> }
<ide> |
|
Java | apache-2.0 | a916944524dbc4bc04ceef6ebabde3f1e01f4449 | 0 | okankurtulus/droidparts,vovan888/droidparts,droidparts/droidparts,b-cuts/droidparts,yanchenko/droidparts | /**
* Copyright 2013 Alex Yanchenko
*
* 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.droidparts.widget;
import static org.droidparts.util.Strings.isNotEmpty;
import org.droidparts.adapter.widget.TextWatcherAdapter;
import org.droidparts.adapter.widget.TextWatcherAdapter.TextWatcherListener;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.widget.EditText;
/**
* To change clear icon, set
*
* <pre>
* android:drawableRight="@drawable/custom_icon"
* </pre>
*/
public class ClearableEditText extends EditText implements OnTouchListener,
OnFocusChangeListener, TextWatcherListener {
public interface Listener {
void didClearText();
}
public void setListener(Listener listener) {
this.listener = listener;
}
private Drawable xD;
private Listener listener;
public ClearableEditText(Context context) {
super(context);
init();
}
public ClearableEditText(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public ClearableEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
@Override
public void setOnTouchListener(OnTouchListener l) {
this.l = l;
}
@Override
public void setOnFocusChangeListener(OnFocusChangeListener f) {
this.f = f;
}
private OnTouchListener l;
private OnFocusChangeListener f;
@Override
public boolean onTouch(View v, MotionEvent event) {
if (getCompoundDrawables()[2] != null) {
boolean tappedX = event.getX() > (getWidth() - getPaddingRight() - xD
.getIntrinsicWidth());
if (tappedX) {
if (event.getAction() == MotionEvent.ACTION_UP) {
setText("");
if (listener != null) {
listener.didClearText();
}
}
return true;
}
}
if (l != null) {
return l.onTouch(v, event);
}
return false;
}
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
setClearIconVisible(isNotEmpty(getText()));
} else {
setClearIconVisible(false);
}
if (f != null) {
f.onFocusChange(v, hasFocus);
}
}
@Override
public void onTextChanged(EditText view, String text) {
if (isFocused()) {
setClearIconVisible(isNotEmpty(text));
}
}
private void init() {
xD = getCompoundDrawables()[2];
if (xD == null) {
xD = getResources()
.getDrawable(android.R.drawable.presence_offline);
}
xD.setBounds(0, 0, xD.getIntrinsicWidth(), xD.getIntrinsicHeight());
setClearIconVisible(false);
super.setOnTouchListener(this);
super.setOnFocusChangeListener(this);
addTextChangedListener(new TextWatcherAdapter(this, this));
}
protected void setClearIconVisible(boolean visible) {
Drawable x = visible ? xD : null;
setCompoundDrawables(getCompoundDrawables()[0],
getCompoundDrawables()[1], x, getCompoundDrawables()[3]);
}
}
| droidparts/src/org/droidparts/widget/ClearableEditText.java | /**
* Copyright 2013 Alex Yanchenko
*
* 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.droidparts.widget;
import static org.droidparts.util.Strings.isNotEmpty;
import org.droidparts.adapter.widget.TextWatcherAdapter;
import org.droidparts.adapter.widget.TextWatcherAdapter.TextWatcherListener;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.widget.EditText;
/**
* To change clear icon, set
*
* <pre>
* android:drawableRight="@drawable/custom_icon"
* </pre>
*/
public class ClearableEditText extends EditText implements OnTouchListener,
OnFocusChangeListener, TextWatcherListener {
public interface Listener {
void didClearText();
}
public void setListener(Listener listener) {
this.listener = listener;
}
private Drawable xD;
private Listener listener;
public ClearableEditText(Context context) {
super(context);
init();
}
public ClearableEditText(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public ClearableEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
@Override
public void setOnTouchListener(OnTouchListener l) {
this.l = l;
}
@Override
public void setOnFocusChangeListener(OnFocusChangeListener f) {
this.f = f;
}
private OnTouchListener l;
private OnFocusChangeListener f;
@Override
public boolean onTouch(View v, MotionEvent event) {
if (getCompoundDrawables()[2] != null) {
boolean tappedX = event.getX() > (getWidth() - getPaddingRight() - xD
.getIntrinsicWidth());
if (tappedX) {
if (event.getAction() == MotionEvent.ACTION_UP) {
setText("");
if (listener != null) {
listener.didClearText();
}
}
return true;
}
}
if (l != null) {
return l.onTouch(v, event);
}
return false;
}
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
setClearIconVisible(isNotEmpty(getText()));
} else {
setClearIconVisible(false);
}
if (f != null) {
f.onFocusChange(v, hasFocus);
}
}
@Override
public void onTextChanged(EditText view, String text) {
if (isFocused()) {
setClearIconVisible(isNotEmpty(text));
}
}
private void init() {
xD = getCompoundDrawables()[2];
if (xD == null) {
xD = getResources().getDrawable(getDefaultClearIconId());
}
xD.setBounds(0, 0, xD.getIntrinsicWidth(), xD.getIntrinsicHeight());
setClearIconVisible(false);
super.setOnTouchListener(this);
super.setOnFocusChangeListener(this);
addTextChangedListener(new TextWatcherAdapter(this, this));
}
private int getDefaultClearIconId() {
int id = getResources()
.getIdentifier("ic_clear", "drawable", "android");
if (id == 0) {
id = android.R.drawable.presence_offline;
}
return id;
}
protected void setClearIconVisible(boolean visible) {
Drawable x = visible ? xD : null;
setCompoundDrawables(getCompoundDrawables()[0],
getCompoundDrawables()[1], x, getCompoundDrawables()[3]);
}
}
| ClearableEditText: reverted to old icon. | droidparts/src/org/droidparts/widget/ClearableEditText.java | ClearableEditText: reverted to old icon. | <ide><path>roidparts/src/org/droidparts/widget/ClearableEditText.java
<ide> private void init() {
<ide> xD = getCompoundDrawables()[2];
<ide> if (xD == null) {
<del> xD = getResources().getDrawable(getDefaultClearIconId());
<add> xD = getResources()
<add> .getDrawable(android.R.drawable.presence_offline);
<ide> }
<ide> xD.setBounds(0, 0, xD.getIntrinsicWidth(), xD.getIntrinsicHeight());
<ide> setClearIconVisible(false);
<ide> addTextChangedListener(new TextWatcherAdapter(this, this));
<ide> }
<ide>
<del> private int getDefaultClearIconId() {
<del> int id = getResources()
<del> .getIdentifier("ic_clear", "drawable", "android");
<del> if (id == 0) {
<del> id = android.R.drawable.presence_offline;
<del> }
<del> return id;
<del> }
<del>
<ide> protected void setClearIconVisible(boolean visible) {
<ide> Drawable x = visible ? xD : null;
<ide> setCompoundDrawables(getCompoundDrawables()[0], |
|
Java | bsd-2-clause | 0cc92339cacc525cd4d3ef422efe2bfba03e826b | 0 | JFormDesigner/RichTextFX,JFormDesigner/RichTextFX,JordanMartinez/RichTextFX,JordanMartinez/RichTextFX,cemartins/RichTextFX,TomasMikula/RichTextFX,FXMisc/RichTextFX,afester/RichTextFX,afester/RichTextFX,FXMisc/RichTextFX,TomasMikula/RichTextFX,MewesK/RichTextFX | package codearea.control;
import inhibeans.property.ReadOnlyIntegerWrapper;
import java.util.ArrayList;
import java.util.List;
import javafx.beans.binding.StringBinding;
import javafx.beans.value.ObservableIntegerValue;
import javafx.beans.value.ObservableStringValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.IndexRange;
import codearea.rx.PushSource;
import codearea.rx.Source;
/**
* Content model for {@link StyledTextArea}. Implements edit operations
* on styled text, but not worrying about additional aspects such as
* caret or selection.
*/
final class StyledTextDocument<S> implements TwoDimensional {
/***************************************************************************
* *
* Observables *
* *
* Observables are "dynamic" (i.e. changing) characteristics of an object. *
* They are not directly settable by the client code, but change in *
* response to user input and/or API actions. *
* *
**************************************************************************/
/**
* Content of this {@code StyledTextDocument}.
*/
private final StringBinding text = BindingFactories.createStringBinding(() -> getContent());
public String getText() { return text.get(); }
public ObservableStringValue textProperty() { return text; }
/**
* Length of this {@code StyledTextDocument}.
*/
private final ReadOnlyIntegerWrapper length = new ReadOnlyIntegerWrapper();
public int getLength() { return length.get(); }
public ObservableIntegerValue lengthProperty() { return length.getReadOnlyProperty(); }
/**
* Unmodifiable observable list of styled paragraphs of this document.
*/
public ObservableList<Paragraph<S>> getParagraphs() {
return FXCollections.unmodifiableObservableList(paragraphs);
}
/***************************************************************************
* *
* Event streams *
* *
**************************************************************************/
private final PushSource<TextChange> textChanges = new PushSource<>();
public Source<TextChange> textChanges() { return textChanges; }
/***************************************************************************
* *
* Private fields *
* *
***************************************************************************/
private final ObservableList<Paragraph<S>> paragraphs =
FXCollections.observableArrayList();
private final TwoLevelNavigator navigator = new TwoLevelNavigator(
() -> paragraphs.size(),
i -> {
int len = paragraphs.get(i).length();
// add 1 for newline to every paragraph except last
return i == paragraphs.size()-1 ? len : len + 1;
});
/***************************************************************************
* *
* Constructors *
* *
***************************************************************************/
StyledTextDocument(S initialStyle) {
paragraphs.add(new Paragraph<S>("", initialStyle));
length.set(0);
}
/***************************************************************************
* *
* Queries *
* *
* Queries are parameterized observables. *
* *
***************************************************************************/
public String getText(IndexRange range) {
return getText(range.getStart(), range.getEnd());
}
public String getText(int start, int end) {
int length = end - start;
StringBuilder sb = new StringBuilder(length);
Position start2D = navigator.offsetToPosition(start);
Position end2D = start2D.offsetBy(length);
int p1 = start2D.getMajor();
int col1 = start2D.getMinor();
int p2 = end2D.getMajor();
int col2 = end2D.getMinor();
if(p1 == p2) {
sb.append(paragraphs.get(p1).substring(col1, col2));
} else {
sb.append(paragraphs.get(p1).substring(col1));
sb.append('\n');
for(int i = p1 + 1; i < p2; ++i) {
sb.append(paragraphs.get(i).toString());
sb.append('\n');
}
sb.append(paragraphs.get(p2).substring(0, col2));
}
// If we were instructed to go beyond the end in a non-last paragraph,
// we omitted a newline. Add it back.
if(col2 > paragraphs.get(p2).length() && p2 < paragraphs.size() - 1) {
sb.append('\n');
}
return sb.toString();
}
public S getStyleAt(int pos) {
Position pos2D = navigator.offsetToPosition(pos);
int line = pos2D.getMajor();
int col = pos2D.getMinor();
return paragraphs.get(line).getStyleAt(col);
}
public S getStyleAt(int paragraph, int column) {
return paragraphs.get(paragraph).getStyleAt(column);
}
@Override
public Position offsetToPosition(int offset) {
return navigator.offsetToPosition(offset);
}
@Override
public Position position(int row, int col) {
return navigator.position(row, col);
}
/***************************************************************************
* *
* Actions *
* *
* Actions change the state of the object. They typically cause a change *
* of one or more observables and/or produce an event. *
* *
**************************************************************************/
public void replaceText(int start, int end, String replacement) {
if (replacement == null)
throw new NullPointerException("replacement text is null");
Position start2D = navigator.offsetToPosition(start);
Position end2D = start2D.offsetBy(end - start);
int leadingLineIndex = start2D.getMajor();
int leadingLineFrom = start2D.getMinor();
int trailingLineIndex = end2D.getMajor();
int trailingLineTo = end2D.getMinor();
replacement = filterInput(replacement);
String replacedText = getText(start, end);
// Get the leftovers after cutting out the deletion
Paragraph<S> leadingLine = paragraphs.get(leadingLineIndex);
Paragraph<S> trailingLine = paragraphs.get(trailingLineIndex);
Paragraph<S> left = leadingLine.split(leadingLineFrom)[0];
Paragraph<S> right = trailingLine.split(trailingLineTo)[1];
String[] replacementLines = replacement.split("\n", -1);
int n = replacementLines.length;
S replacementStyle = leadingLine.getStyleAt(leadingLineFrom-1);
if(n == 1) {
// replacement is just a single line,
// use it to join the two leftover lines
left.append(replacementLines[0]);
left.appendFrom(right);
// replace the affected liens with the merger of leftovers and the replacement line
// TODO: use setAll(from, to, col) when implemented (see https://javafx-jira.kenai.com/browse/RT-32655)
paragraphs.set(leadingLineIndex, left); // use set() instead of remove and add to make sure the number of lines is never 0
paragraphs.remove(leadingLineIndex+1, trailingLineIndex+1);
}
else {
// append the first replacement line to the left leftover
// and prepend the last replacement line to the right leftover
left.append(replacementLines[0]);
right.insert(0, replacementLines[n-1]);
// create list of new lines to replace the affected lines
List<Paragraph<S>> newLines = new ArrayList<>(n-1);
for(int i = 1; i < n - 1; ++i)
newLines.add(new Paragraph<S>(replacementLines[i], replacementStyle));
newLines.add(right);
// replace the affected lines with the new lines
// TODO: use setAll(from, to, col) when implemented (see https://javafx-jira.kenai.com/browse/RT-32655)
paragraphs.set(leadingLineIndex, left); // use set() instead of remove and add to make sure the number of lines is never 0
paragraphs.remove(leadingLineIndex+1, trailingLineIndex+1);
paragraphs.addAll(leadingLineIndex+1, newLines);
}
// update length, invalidate text
int newLength = length.get() - (end - start) + replacement.length();
length.blockWhile(() -> { // don't publish length change until text is invalidated
length.set(newLength);
text.invalidate();
});
// emit change event
fireTextChange(start, replacedText, replacement);
}
public void setStyle(int from, int to, S style) {
Position start = navigator.offsetToPosition(from);
Position end = start.offsetBy(to - from);
int firstLineIndex = start.getMajor();
int firstLineFrom = start.getMinor();
int lastLineIndex = end.getMajor();
int lastLineTo = end.getMinor();
if(from == to)
return;
if(firstLineIndex == lastLineIndex) {
setStyle(firstLineIndex, firstLineFrom, lastLineTo, style);
}
else {
int firstLineLen = paragraphs.get(firstLineIndex).length();
setStyle(firstLineIndex, firstLineFrom, firstLineLen, style);
for(int i=firstLineIndex+1; i<lastLineIndex; ++i) {
setStyle(i, style);
}
setStyle(lastLineIndex, 0, lastLineTo, style);
}
}
public void setStyle(int paragraph, S style) {
Paragraph<S> p = paragraphs.get(paragraph);
p.setStyle(style);
paragraphs.set(paragraph, p); // to generate change event
}
public void setStyle(int paragraph, int fromCol, int toCol, S style) {
Paragraph<S> p = paragraphs.get(paragraph);
p.setStyle(fromCol, toCol, style);
paragraphs.set(paragraph, p); // to generate change event
}
/***************************************************************************
* *
* Private methods *
* *
**************************************************************************/
private String getContent() {
return getText(0, getLength());
}
private void fireTextChange(int pos, String removedText, String addedText) {
textChanges.push(new TextChange(pos, removedText, addedText));
}
/**
* Filters out illegal characters.
*/
private static String filterInput(String txt) {
if(txt.chars().allMatch(c -> isLegal((char) c))) {
return txt;
} else {
StringBuilder sb = new StringBuilder(txt.length());
txt.chars().filter(c -> isLegal((char) c)).forEach(c -> sb.append((char) c));
return sb.toString();
}
}
private static boolean isLegal(char c) {
return !Character.isISOControl(c) || c == '\n' || c == '\t';
}
} | codearea/src/main/java/codearea/control/StyledTextDocument.java | package codearea.control;
import java.util.ArrayList;
import java.util.List;
import javafx.beans.binding.StringBinding;
import javafx.beans.property.ReadOnlyIntegerWrapper;
import javafx.beans.value.ObservableIntegerValue;
import javafx.beans.value.ObservableStringValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.IndexRange;
import codearea.rx.PushSource;
import codearea.rx.Source;
/**
* Content model for {@link StyledTextArea}. Implements edit operations
* on styled text, but not worrying about additional aspects such as
* caret or selection.
*/
final class StyledTextDocument<S> implements TwoDimensional {
/***************************************************************************
* *
* Observables *
* *
* Observables are "dynamic" (i.e. changing) characteristics of an object. *
* They are not directly settable by the client code, but change in *
* response to user input and/or API actions. *
* *
**************************************************************************/
/**
* Content of this {@code StyledTextDocument}.
*/
private final StringBinding text = BindingFactories.createStringBinding(() -> getContent());
public String getText() { return text.get(); }
public ObservableStringValue textProperty() { return text; }
/**
* Length of this {@code StyledTextDocument}.
*/
private final ReadOnlyIntegerWrapper length = new ReadOnlyIntegerWrapper();
public int getLength() { return length.get(); }
public ObservableIntegerValue lengthProperty() { return length.getReadOnlyProperty(); }
/**
* Unmodifiable observable list of styled paragraphs of this document.
*/
public ObservableList<Paragraph<S>> getParagraphs() {
return FXCollections.unmodifiableObservableList(paragraphs);
}
/***************************************************************************
* *
* Event streams *
* *
**************************************************************************/
private final PushSource<TextChange> textChanges = new PushSource<>();
public Source<TextChange> textChanges() { return textChanges; }
/***************************************************************************
* *
* Private fields *
* *
***************************************************************************/
private final ObservableList<Paragraph<S>> paragraphs =
FXCollections.observableArrayList();
private final TwoLevelNavigator navigator = new TwoLevelNavigator(
() -> paragraphs.size(),
i -> {
int len = paragraphs.get(i).length();
// add 1 for newline to every paragraph except last
return i == paragraphs.size()-1 ? len : len + 1;
});
/***************************************************************************
* *
* Constructors *
* *
***************************************************************************/
StyledTextDocument(S initialStyle) {
paragraphs.add(new Paragraph<S>("", initialStyle));
length.set(0);
}
/***************************************************************************
* *
* Queries *
* *
* Queries are parameterized observables. *
* *
***************************************************************************/
public String getText(IndexRange range) {
return getText(range.getStart(), range.getEnd());
}
public String getText(int start, int end) {
int length = end - start;
StringBuilder sb = new StringBuilder(length);
Position start2D = navigator.offsetToPosition(start);
Position end2D = start2D.offsetBy(length);
int p1 = start2D.getMajor();
int col1 = start2D.getMinor();
int p2 = end2D.getMajor();
int col2 = end2D.getMinor();
if(p1 == p2) {
sb.append(paragraphs.get(p1).substring(col1, col2));
} else {
sb.append(paragraphs.get(p1).substring(col1));
sb.append('\n');
for(int i = p1 + 1; i < p2; ++i) {
sb.append(paragraphs.get(i).toString());
sb.append('\n');
}
sb.append(paragraphs.get(p2).substring(0, col2));
}
// If we were instructed to go beyond the end in a non-last paragraph,
// we omitted a newline. Add it back.
if(col2 > paragraphs.get(p2).length() && p2 < paragraphs.size() - 1) {
sb.append('\n');
}
return sb.toString();
}
public S getStyleAt(int pos) {
Position pos2D = navigator.offsetToPosition(pos);
int line = pos2D.getMajor();
int col = pos2D.getMinor();
return paragraphs.get(line).getStyleAt(col);
}
public S getStyleAt(int paragraph, int column) {
return paragraphs.get(paragraph).getStyleAt(column);
}
@Override
public Position offsetToPosition(int offset) {
return navigator.offsetToPosition(offset);
}
@Override
public Position position(int row, int col) {
return navigator.position(row, col);
}
/***************************************************************************
* *
* Actions *
* *
* Actions change the state of the object. They typically cause a change *
* of one or more observables and/or produce an event. *
* *
**************************************************************************/
public void replaceText(int start, int end, String replacement) {
if (replacement == null)
throw new NullPointerException("replacement text is null");
Position start2D = navigator.offsetToPosition(start);
Position end2D = start2D.offsetBy(end - start);
int leadingLineIndex = start2D.getMajor();
int leadingLineFrom = start2D.getMinor();
int trailingLineIndex = end2D.getMajor();
int trailingLineTo = end2D.getMinor();
replacement = filterInput(replacement);
String replacedText = getText(start, end);
// Get the leftovers after cutting out the deletion
Paragraph<S> leadingLine = paragraphs.get(leadingLineIndex);
Paragraph<S> trailingLine = paragraphs.get(trailingLineIndex);
Paragraph<S> left = leadingLine.split(leadingLineFrom)[0];
Paragraph<S> right = trailingLine.split(trailingLineTo)[1];
String[] replacementLines = replacement.split("\n", -1);
int n = replacementLines.length;
S replacementStyle = leadingLine.getStyleAt(leadingLineFrom-1);
if(n == 1) {
// replacement is just a single line,
// use it to join the two leftover lines
left.append(replacementLines[0]);
left.appendFrom(right);
// replace the affected liens with the merger of leftovers and the replacement line
// TODO: use setAll(from, to, col) when implemented (see https://javafx-jira.kenai.com/browse/RT-32655)
paragraphs.set(leadingLineIndex, left); // use set() instead of remove and add to make sure the number of lines is never 0
paragraphs.remove(leadingLineIndex+1, trailingLineIndex+1);
}
else {
// append the first replacement line to the left leftover
// and prepend the last replacement line to the right leftover
left.append(replacementLines[0]);
right.insert(0, replacementLines[n-1]);
// create list of new lines to replace the affected lines
List<Paragraph<S>> newLines = new ArrayList<>(n-1);
for(int i = 1; i < n - 1; ++i)
newLines.add(new Paragraph<S>(replacementLines[i], replacementStyle));
newLines.add(right);
// replace the affected lines with the new lines
// TODO: use setAll(from, to, col) when implemented (see https://javafx-jira.kenai.com/browse/RT-32655)
paragraphs.set(leadingLineIndex, left); // use set() instead of remove and add to make sure the number of lines is never 0
paragraphs.remove(leadingLineIndex+1, trailingLineIndex+1);
paragraphs.addAll(leadingLineIndex+1, newLines);
}
// update length, invalidate text, emit change event
length.set(length.get() - (end - start) + replacement.length());
text.invalidate(); // TODO invalidate length and text "atomically"
fireTextChange(start, replacedText, replacement);
}
public void setStyle(int from, int to, S style) {
Position start = navigator.offsetToPosition(from);
Position end = start.offsetBy(to - from);
int firstLineIndex = start.getMajor();
int firstLineFrom = start.getMinor();
int lastLineIndex = end.getMajor();
int lastLineTo = end.getMinor();
if(from == to)
return;
if(firstLineIndex == lastLineIndex) {
setStyle(firstLineIndex, firstLineFrom, lastLineTo, style);
}
else {
int firstLineLen = paragraphs.get(firstLineIndex).length();
setStyle(firstLineIndex, firstLineFrom, firstLineLen, style);
for(int i=firstLineIndex+1; i<lastLineIndex; ++i) {
setStyle(i, style);
}
setStyle(lastLineIndex, 0, lastLineTo, style);
}
}
public void setStyle(int paragraph, S style) {
Paragraph<S> p = paragraphs.get(paragraph);
p.setStyle(style);
paragraphs.set(paragraph, p); // to generate change event
}
public void setStyle(int paragraph, int fromCol, int toCol, S style) {
Paragraph<S> p = paragraphs.get(paragraph);
p.setStyle(fromCol, toCol, style);
paragraphs.set(paragraph, p); // to generate change event
}
/***************************************************************************
* *
* Private methods *
* *
**************************************************************************/
private String getContent() {
return getText(0, getLength());
}
private void fireTextChange(int pos, String removedText, String addedText) {
textChanges.push(new TextChange(pos, removedText, addedText));
}
/**
* Filters out illegal characters.
*/
private static String filterInput(String txt) {
if(txt.chars().allMatch(c -> isLegal((char) c))) {
return txt;
} else {
StringBuilder sb = new StringBuilder(txt.length());
txt.chars().filter(c -> isLegal((char) c)).forEach(c -> sb.append((char) c));
return sb.toString();
}
}
private static boolean isLegal(char c) {
return !Character.isISOControl(c) || c == '\n' || c == '\t';
}
} | Use InhiBeans to ensure consistency of text and length properties of StyledTextDocument.
| codearea/src/main/java/codearea/control/StyledTextDocument.java | Use InhiBeans to ensure consistency of text and length properties of StyledTextDocument. | <ide><path>odearea/src/main/java/codearea/control/StyledTextDocument.java
<ide> package codearea.control;
<add>
<add>import inhibeans.property.ReadOnlyIntegerWrapper;
<ide>
<ide> import java.util.ArrayList;
<ide> import java.util.List;
<ide>
<ide> import javafx.beans.binding.StringBinding;
<del>import javafx.beans.property.ReadOnlyIntegerWrapper;
<ide> import javafx.beans.value.ObservableIntegerValue;
<ide> import javafx.beans.value.ObservableStringValue;
<ide> import javafx.collections.FXCollections;
<ide> paragraphs.addAll(leadingLineIndex+1, newLines);
<ide> }
<ide>
<del> // update length, invalidate text, emit change event
<del> length.set(length.get() - (end - start) + replacement.length());
<del> text.invalidate(); // TODO invalidate length and text "atomically"
<add> // update length, invalidate text
<add> int newLength = length.get() - (end - start) + replacement.length();
<add> length.blockWhile(() -> { // don't publish length change until text is invalidated
<add> length.set(newLength);
<add> text.invalidate();
<add> });
<add>
<add> // emit change event
<ide> fireTextChange(start, replacedText, replacement);
<ide> }
<ide> |
|
Java | apache-2.0 | 88e63beda9816b4ac9f8869114102e1d6a9871ed | 0 | lucafavatella/intellij-community,allotria/intellij-community,jagguli/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,fengbaicanhe/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,fnouama/intellij-community,petteyg/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,petteyg/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,izonder/intellij-community,fitermay/intellij-community,caot/intellij-community,diorcety/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,amith01994/intellij-community,slisson/intellij-community,signed/intellij-community,akosyakov/intellij-community,akosyakov/intellij-community,kool79/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,samthor/intellij-community,adedayo/intellij-community,asedunov/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,retomerz/intellij-community,jagguli/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,da1z/intellij-community,allotria/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,semonte/intellij-community,samthor/intellij-community,FHannes/intellij-community,slisson/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,samthor/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,akosyakov/intellij-community,supersven/intellij-community,robovm/robovm-studio,supersven/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,akosyakov/intellij-community,allotria/intellij-community,signed/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,Distrotech/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,hurricup/intellij-community,clumsy/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,ibinti/intellij-community,dslomov/intellij-community,adedayo/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,jagguli/intellij-community,Lekanich/intellij-community,holmes/intellij-community,ryano144/intellij-community,apixandru/intellij-community,vladmm/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,petteyg/intellij-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,dslomov/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,signed/intellij-community,TangHao1987/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,diorcety/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,da1z/intellij-community,ryano144/intellij-community,petteyg/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,petteyg/intellij-community,retomerz/intellij-community,semonte/intellij-community,izonder/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,retomerz/intellij-community,samthor/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,robovm/robovm-studio,michaelgallacher/intellij-community,signed/intellij-community,FHannes/intellij-community,kdwink/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,kool79/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,FHannes/intellij-community,clumsy/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,caot/intellij-community,diorcety/intellij-community,holmes/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,supersven/intellij-community,muntasirsyed/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,fnouama/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,apixandru/intellij-community,holmes/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,salguarnieri/intellij-community,signed/intellij-community,kdwink/intellij-community,signed/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,jagguli/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,caot/intellij-community,mglukhikh/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,robovm/robovm-studio,samthor/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,adedayo/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,vladmm/intellij-community,fitermay/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,supersven/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,vladmm/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,fitermay/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,dslomov/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,izonder/intellij-community,gnuhub/intellij-community,ahb0327/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,semonte/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,Lekanich/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,hurricup/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,izonder/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,kool79/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,caot/intellij-community,allotria/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,signed/intellij-community,slisson/intellij-community,robovm/robovm-studio,clumsy/intellij-community,allotria/intellij-community,gnuhub/intellij-community,izonder/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,slisson/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,dslomov/intellij-community,holmes/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,hurricup/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,FHannes/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,ryano144/intellij-community,semonte/intellij-community,Lekanich/intellij-community,hurricup/intellij-community,holmes/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,orekyuu/intellij-community,izonder/intellij-community,dslomov/intellij-community,asedunov/intellij-community,wreckJ/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,caot/intellij-community,ftomassetti/intellij-community,signed/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,clumsy/intellij-community,caot/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,ryano144/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,ryano144/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,petteyg/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,fnouama/intellij-community,fnouama/intellij-community,slisson/intellij-community,FHannes/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,allotria/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,izonder/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,robovm/robovm-studio,ftomassetti/intellij-community,caot/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,retomerz/intellij-community,fitermay/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,signed/intellij-community,amith01994/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,kool79/intellij-community,allotria/intellij-community,akosyakov/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,slisson/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,apixandru/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,caot/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,supersven/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,signed/intellij-community,dslomov/intellij-community,kool79/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,hurricup/intellij-community,supersven/intellij-community,hurricup/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,izonder/intellij-community,ryano144/intellij-community,da1z/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,supersven/intellij-community,semonte/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,da1z/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,amith01994/intellij-community,robovm/robovm-studio,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,caot/intellij-community,kool79/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,slisson/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,signed/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,robovm/robovm-studio,semonte/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,xfournet/intellij-community,fnouama/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,ryano144/intellij-community,holmes/intellij-community,izonder/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,ryano144/intellij-community,adedayo/intellij-community,diorcety/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,amith01994/intellij-community,holmes/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,allotria/intellij-community,slisson/intellij-community,retomerz/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,diorcety/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,ftomassetti/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,allotria/intellij-community,caot/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,hurricup/intellij-community,da1z/intellij-community,petteyg/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,samthor/intellij-community | /*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.externalSystem.settings;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Disposer;
import com.intellij.util.containers.ContainerUtilRt;
import com.intellij.util.messages.Topic;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
/**
* Common base class for external system settings. Defines a minimal api which is necessary for the common external system
* support codebase.
* <p/>
* <b>Note:</b> non-abstract sub-classes of this class are expected to be marked by {@link State} annotation configured as necessary.
*
* @author Denis Zhdanov
* @since 4/3/13 4:04 PM
*/
public abstract class AbstractExternalSystemSettings<
SS extends AbstractExternalSystemSettings<SS, PS, L>,
PS extends ExternalProjectSettings,
L extends ExternalSystemSettingsListener<PS>>
implements Disposable
{
@NotNull private final Topic<L> myChangesTopic;
private Project myProject;
@NotNull private final Map<String/* project path */, PS> myLinkedProjectsSettings = ContainerUtilRt.newHashMap();
@NotNull private final Map<String/* project path */, PS> myLinkedProjectsSettingsView
= Collections.unmodifiableMap(myLinkedProjectsSettings);
protected AbstractExternalSystemSettings(@NotNull Topic<L> topic, @NotNull Project project) {
myChangesTopic = topic;
myProject = project;
Disposer.register(project, this);
}
@Override
public void dispose() {
myProject = null;
}
@NotNull
public Project getProject() {
return myProject;
}
/**
* Every time particular external system setting is changed corresponding message is sent via ide
* <a href="http://confluence.jetbrains.com/display/IDEADEV/IntelliJ+IDEA+Messaging+infrastructure">messaging sub-system</a>.
* The problem is that every external system implementation defines it's own topic/listener pair. Listener interface is derived
* from the common {@link ExternalSystemSettingsListener} interface and is specific to external sub-system implementation.
* However, it's possible that a client wants to perform particular actions based only on {@link ExternalSystemSettingsListener}
* facilities. There is no way for such external system-agnostic client to create external system-specific listener
* implementation then.
* <p/>
* That's why this method allows to wrap given 'generic listener' into external system-specific one.
*
* @param listener target generic listener to wrap to external system-specific implementation
*/
public abstract void subscribe(@NotNull ExternalSystemSettingsListener<PS> listener);
public void copyFrom(@NotNull SS settings) {
for (PS projectSettings : settings.getLinkedProjectsSettings()) {
myLinkedProjectsSettings.put(projectSettings.getExternalProjectPath(), projectSettings);
}
copyExtraSettingsFrom(settings);
}
protected abstract void copyExtraSettingsFrom(@NotNull SS settings);
@SuppressWarnings("unchecked")
@NotNull
public Collection<PS> getLinkedProjectsSettings() {
return myLinkedProjectsSettingsView.values();
}
@Nullable
public PS getLinkedProjectSettings(@NotNull String linkedProjectPath) {
PS ps = myLinkedProjectsSettings.get(linkedProjectPath);
if(ps == null) {
for (PS ps1 : myLinkedProjectsSettings.values()) {
for (String modulePath : ps1.getModules()) {
if(linkedProjectPath.equals(modulePath)) return ps1;
}
}
}
return ps;
}
public void linkProject(@NotNull PS settings) throws IllegalArgumentException {
PS existing = getLinkedProjectSettings(settings.getExternalProjectPath());
if (existing != null) {
throw new IllegalArgumentException(String.format(
"Can't link external project '%s'. Reason: it's already registered at the current ide project",
settings.getExternalProjectPath()
));
}
myLinkedProjectsSettings.put(settings.getExternalProjectPath(), settings);
getPublisher().onProjectsLinked(Collections.singleton(settings));
}
/**
* Un-links given external project from the current ide project.
*
* @param linkedProjectPath path of external project to be unlinked
* @return <code>true</code> if there was an external project with the given config path linked to the current
* ide project;
* <code>false</code> otherwise
*/
public boolean unlinkExternalProject(@NotNull String linkedProjectPath) {
PS removed = myLinkedProjectsSettings.remove(linkedProjectPath);
if (removed == null) {
return false;
}
getPublisher().onProjectsUnlinked(Collections.singleton(linkedProjectPath));
return true;
}
public void setLinkedProjectsSettings(@NotNull Collection<PS> settings) {
List<PS> added = ContainerUtilRt.newArrayList();
Map<String, PS> removed = ContainerUtilRt.newHashMap(myLinkedProjectsSettings);
myLinkedProjectsSettings.clear();
for (PS current : settings) {
myLinkedProjectsSettings.put(current.getExternalProjectPath(), current);
}
for (PS current : settings) {
PS old = removed.remove(current.getExternalProjectPath());
if (old == null) {
added.add(current);
}
else {
if (current.isUseAutoImport() != old.isUseAutoImport()) {
getPublisher().onUseAutoImportChange(current.isUseAutoImport(), current.getExternalProjectPath());
}
checkSettings(old, current);
}
}
if (!added.isEmpty()) {
getPublisher().onProjectsLinked(added);
}
if (!removed.isEmpty()) {
getPublisher().onProjectsUnlinked(removed.keySet());
}
}
/**
* Is assumed to check if given old settings external system-specific state differs from the given new one
* and {@link #getPublisher() notify} listeners in case of the positive answer.
*
* @param old old settings state
* @param current current settings state
*/
protected abstract void checkSettings(@NotNull PS old, @NotNull PS current);
@NotNull
public Topic<L> getChangesTopic() {
return myChangesTopic;
}
@NotNull
public L getPublisher() {
return myProject.getMessageBus().syncPublisher(myChangesTopic);
}
protected void fillState(@NotNull State<PS> state) {
state.setLinkedExternalProjectsSettings(ContainerUtilRt.newTreeSet(myLinkedProjectsSettings.values()));
}
@SuppressWarnings("unchecked")
protected void loadState(@NotNull State<PS> state) {
Set<PS> settings = state.getLinkedExternalProjectsSettings();
if (settings != null) {
myLinkedProjectsSettings.clear();
for (PS projectSettings : settings) {
myLinkedProjectsSettings.put(projectSettings.getExternalProjectPath(), projectSettings);
}
}
}
public interface State<S> {
Set<S> getLinkedExternalProjectsSettings();
void setLinkedExternalProjectsSettings(Set<S> settings);
}
}
| platform/external-system-api/src/com/intellij/openapi/externalSystem/settings/AbstractExternalSystemSettings.java | /*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.externalSystem.settings;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Disposer;
import com.intellij.util.containers.ContainerUtilRt;
import com.intellij.util.messages.Topic;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
/**
* Common base class for external system settings. Defines a minimal api which is necessary for the common external system
* support codebase.
* <p/>
* <b>Note:</b> non-abstract sub-classes of this class are expected to be marked by {@link State} annotation configured as necessary.
*
* @author Denis Zhdanov
* @since 4/3/13 4:04 PM
*/
public abstract class AbstractExternalSystemSettings<
SS extends AbstractExternalSystemSettings<SS, PS, L>,
PS extends ExternalProjectSettings,
L extends ExternalSystemSettingsListener<PS>>
implements Disposable
{
@NotNull private final Topic<L> myChangesTopic;
private Project myProject;
@NotNull private final Map<String/* project path */, PS> myLinkedProjectsSettings = ContainerUtilRt.newHashMap();
@NotNull private final Map<String/* project path */, PS> myLinkedProjectsSettingsView
= Collections.unmodifiableMap(myLinkedProjectsSettings);
protected AbstractExternalSystemSettings(@NotNull Topic<L> topic, @NotNull Project project) {
myChangesTopic = topic;
myProject = project;
Disposer.register(project, this);
}
@Override
public void dispose() {
myProject = null;
}
@NotNull
public Project getProject() {
return myProject;
}
/**
* Every time particular external system setting is changed corresponding message is sent via ide
* <a href="http://confluence.jetbrains.com/display/IDEADEV/IntelliJ+IDEA+Messaging+infrastructure">messaging sub-system</a>.
* The problem is that every external system implementation defines it's own topic/listener pair. Listener interface is derived
* from the common {@link ExternalSystemSettingsListener} interface and is specific to external sub-system implementation.
* However, it's possible that a client wants to perform particular actions based only on {@link ExternalSystemSettingsListener}
* facilities. There is no way for such external system-agnostic client to create external system-specific listener
* implementation then.
* <p/>
* That's why this method allows to wrap given 'generic listener' into external system-specific one.
*
* @param listener target generic listener to wrap to external system-specific implementation
*/
public abstract void subscribe(@NotNull ExternalSystemSettingsListener<PS> listener);
public void copyFrom(@NotNull SS settings) {
myLinkedProjectsSettings.clear();
for (PS projectSettings : settings.getLinkedProjectsSettings()) {
myLinkedProjectsSettings.put(projectSettings.getExternalProjectPath(), projectSettings);
}
copyExtraSettingsFrom(settings);
}
protected abstract void copyExtraSettingsFrom(@NotNull SS settings);
@SuppressWarnings("unchecked")
@NotNull
public Collection<PS> getLinkedProjectsSettings() {
return myLinkedProjectsSettingsView.values();
}
@Nullable
public PS getLinkedProjectSettings(@NotNull String linkedProjectPath) {
PS ps = myLinkedProjectsSettings.get(linkedProjectPath);
if(ps == null) {
for (PS ps1 : myLinkedProjectsSettings.values()) {
for (String modulePath : ps1.getModules()) {
if(linkedProjectPath.equals(modulePath)) return ps1;
}
}
}
return ps;
}
public void linkProject(@NotNull PS settings) throws IllegalArgumentException {
PS existing = getLinkedProjectSettings(settings.getExternalProjectPath());
if (existing != null) {
throw new IllegalArgumentException(String.format(
"Can't link external project '%s'. Reason: it's already registered at the current ide project",
settings.getExternalProjectPath()
));
}
myLinkedProjectsSettings.put(settings.getExternalProjectPath(), settings);
getPublisher().onProjectsLinked(Collections.singleton(settings));
}
/**
* Un-links given external project from the current ide project.
*
* @param linkedProjectPath path of external project to be unlinked
* @return <code>true</code> if there was an external project with the given config path linked to the current
* ide project;
* <code>false</code> otherwise
*/
public boolean unlinkExternalProject(@NotNull String linkedProjectPath) {
PS removed = myLinkedProjectsSettings.remove(linkedProjectPath);
if (removed == null) {
return false;
}
getPublisher().onProjectsUnlinked(Collections.singleton(linkedProjectPath));
return true;
}
public void setLinkedProjectsSettings(@NotNull Collection<PS> settings) {
List<PS> added = ContainerUtilRt.newArrayList();
Map<String, PS> removed = ContainerUtilRt.newHashMap(myLinkedProjectsSettings);
myLinkedProjectsSettings.clear();
for (PS current : settings) {
myLinkedProjectsSettings.put(current.getExternalProjectPath(), current);
}
for (PS current : settings) {
PS old = removed.remove(current.getExternalProjectPath());
if (old == null) {
added.add(current);
}
else {
if (current.isUseAutoImport() != old.isUseAutoImport()) {
getPublisher().onUseAutoImportChange(current.isUseAutoImport(), current.getExternalProjectPath());
}
checkSettings(old, current);
}
}
if (!added.isEmpty()) {
getPublisher().onProjectsLinked(added);
}
if (!removed.isEmpty()) {
getPublisher().onProjectsUnlinked(removed.keySet());
}
}
/**
* Is assumed to check if given old settings external system-specific state differs from the given new one
* and {@link #getPublisher() notify} listeners in case of the positive answer.
*
* @param old old settings state
* @param current current settings state
*/
protected abstract void checkSettings(@NotNull PS old, @NotNull PS current);
@NotNull
public Topic<L> getChangesTopic() {
return myChangesTopic;
}
@NotNull
public L getPublisher() {
return myProject.getMessageBus().syncPublisher(myChangesTopic);
}
protected void fillState(@NotNull State<PS> state) {
state.setLinkedExternalProjectsSettings(ContainerUtilRt.newTreeSet(myLinkedProjectsSettings.values()));
}
@SuppressWarnings("unchecked")
protected void loadState(@NotNull State<PS> state) {
Set<PS> settings = state.getLinkedExternalProjectsSettings();
if (settings != null) {
myLinkedProjectsSettings.clear();
for (PS projectSettings : settings) {
myLinkedProjectsSettings.put(projectSettings.getExternalProjectPath(), projectSettings);
}
}
}
public interface State<S> {
Set<S> getLinkedExternalProjectsSettings();
void setLinkedExternalProjectsSettings(Set<S> settings);
}
}
| external sytem: do not run import after new project attachment for other linked projects
| platform/external-system-api/src/com/intellij/openapi/externalSystem/settings/AbstractExternalSystemSettings.java | external sytem: do not run import after new project attachment for other linked projects | <ide><path>latform/external-system-api/src/com/intellij/openapi/externalSystem/settings/AbstractExternalSystemSettings.java
<ide> public abstract void subscribe(@NotNull ExternalSystemSettingsListener<PS> listener);
<ide>
<ide> public void copyFrom(@NotNull SS settings) {
<del> myLinkedProjectsSettings.clear();
<ide> for (PS projectSettings : settings.getLinkedProjectsSettings()) {
<ide> myLinkedProjectsSettings.put(projectSettings.getExternalProjectPath(), projectSettings);
<ide> } |
|
JavaScript | mit | c2a5f5256295df09080d67b15010d4cc46a42f48 | 0 | staticland/staticland-api,staticland/staticland-api,staticland/staticland-api | var assert = require('assert')
var path = require('path')
var createCertbot = require('certbot-wrapper')
module.exports = function createCert (config) {
assert.equal(typeof config, 'object', 'cert: options object is required')
assert.equal(typeof config.letsEncryptDir, 'string', 'cert: options.letsEncryptDir string is required')
assert.equal(typeof config.letsEncryptChallengeDir, 'string', 'cert: options.letsEncryptChallengeDir string is required')
config.cmd = config.cmd || 'certbot-auto'
var cert = {}
var certbot = createCertbot(config)
cert.create = function createCert (options, callback) {
assert.equal(typeof options, 'object', 'cert.create: options object is required')
if (config.requestCerts === false) return callback()
var opts = {
args: {
text: true,
quiet: true,
noSelfUpgrade: true,
agreeTos: true,
webroot: true,
w: config.letsEncryptChallengeDir,
domains: options.domain,
email: options.email || '[email protected]',
configDir: path.join(config.letsEncryptDir, 'config'),
logsDir: path.join(config.letsEncryptDir, 'logs'),
workDir: path.join(config.letsEncryptDir, 'work')
}
}
if (config.debug) opts.args.staging = true
certbot.certonly(opts, callback)
}
// cert.renew = function renew (options, callback) {
// var domain = options.domain
// var email = options.email || '[email protected]'
//
// letsencrypt.getCert({
// url: url,
// email: email,
// domains: [options.domain],
// challenge: function challenge (domain, challengepath, data, done) {
// var challengeDir = path.join(config.dirs.sitesDir, 'html', domain, '.well-known', 'acme-challenge')
// var filename = challengepath.split('/acme-challenge/')[1]
//
// mkdirp(challengeDir, function () {
// fs.writeFile(path.join(challengeDir, filename), data, function (err) {
// if (err) return done(err)
// done()
// })
// })
// },
// certFile: path.join(certDir, '/fullchain.pem'),
// caFile: path.join(certDir, '/ca.pem'),
// privateKey: path.join(certDir, '/privkey.pem'),
// accountKey: path.join(certDir, '/account.pem'),
// agreeTerms: true
// }, function (err, cert, key, ca, account) {
// if (err) return callback(err)
// fs.writeFileSync(path.join(certDir, '/account.pem'), account)
// fs.writeFileSync(path.join(certDir, '/privkey.pem'), key)
// fs.writeFileSync(path.join(certDir, '/fullchain.pem'), cert)
// fs.writeFileSync(path.join(certDir, '/ca.pem'), ca)
// callback(null)
// })
// }
return cert
}
| lib/cert.js | var assert = require('assert')
var path = require('path')
var createCertbot = require('certbot-wrapper')
module.exports = function createCert (config) {
assert.equal(typeof config, 'object', 'cert: options object is required')
assert.equal(typeof config.letsEncryptDir, 'string', 'cert: options.letsEncryptDir string is required')
assert.equal(typeof config.letsEncryptChallengeDir, 'string', 'cert: options.letsEncryptChallengeDir string is required')
config.cmd = config.cmd || 'certbot-auto'
var cert = {}
var certbot = createCertbot(config)
cert.create = function createCert (options, callback) {
assert.equal(typeof options, 'object', 'cert.create: options object is required')
if (config.requestCerts === false) return callback()
var opts = {
args: {
text: true,
quiet: true,
noSelfUpgrade: true,
agreeTos: true,
webroot: true,
w: config.letsEncryptChallengeDir,
domains: options.domain,
email: options.email || '[email protected]',
configDir: path.join(config.letsEncryptDir, 'config'),
logsDir: path.join(config.letsEncryptDir, 'logs'),
workDir: path.join(config.letsEncryptDi, 'work')
}
}
if (config.debug) opts.args.staging = true
certbot.certonly(opts, callback)
}
// cert.renew = function renew (options, callback) {
// var domain = options.domain
// var email = options.email || '[email protected]'
//
// letsencrypt.getCert({
// url: url,
// email: email,
// domains: [options.domain],
// challenge: function challenge (domain, challengepath, data, done) {
// var challengeDir = path.join(config.dirs.sitesDir, 'html', domain, '.well-known', 'acme-challenge')
// var filename = challengepath.split('/acme-challenge/')[1]
//
// mkdirp(challengeDir, function () {
// fs.writeFile(path.join(challengeDir, filename), data, function (err) {
// if (err) return done(err)
// done()
// })
// })
// },
// certFile: path.join(certDir, '/fullchain.pem'),
// caFile: path.join(certDir, '/ca.pem'),
// privateKey: path.join(certDir, '/privkey.pem'),
// accountKey: path.join(certDir, '/account.pem'),
// agreeTerms: true
// }, function (err, cert, key, ca, account) {
// if (err) return callback(err)
// fs.writeFileSync(path.join(certDir, '/account.pem'), account)
// fs.writeFileSync(path.join(certDir, '/privkey.pem'), key)
// fs.writeFileSync(path.join(certDir, '/fullchain.pem'), cert)
// fs.writeFileSync(path.join(certDir, '/ca.pem'), ca)
// callback(null)
// })
// }
return cert
}
| fix typo
| lib/cert.js | fix typo | <ide><path>ib/cert.js
<ide> email: options.email || '[email protected]',
<ide> configDir: path.join(config.letsEncryptDir, 'config'),
<ide> logsDir: path.join(config.letsEncryptDir, 'logs'),
<del> workDir: path.join(config.letsEncryptDi, 'work')
<add> workDir: path.join(config.letsEncryptDir, 'work')
<ide> }
<ide> }
<ide> |
|
Java | lgpl-2.1 | 715750c05513d5b51d23b1c1d75f5513b2d0d7e6 | 0 | samskivert/samskivert,samskivert/samskivert | //
// $Id: SwingUtil.java,v 1.29 2004/01/12 08:39:49 ray Exp $
//
// samskivert library - useful routines for java programs
// Copyright (C) 2001 Michael Bayne
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.samskivert.swing.util;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Graphics;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.Point;
import java.awt.Polygon;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.Toolkit;
import java.awt.Transparency;
import java.awt.Window;
import java.awt.geom.Area;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Random;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.DocumentFilter;
import javax.swing.text.JTextComponent;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import com.samskivert.util.SortableArrayList;
/**
* Miscellaneous useful Swing-related utility functions.
*/
public class SwingUtil
{
/**
* Center the given window within the screen boundaries.
*
* @param window the window to be centered.
*/
public static void centerWindow (Window window)
{
Toolkit tk = window.getToolkit();
Dimension ss = tk.getScreenSize();
int width = window.getWidth(), height = window.getHeight();
window.setBounds((ss.width-width)/2, (ss.height-height)/2,
width, height);
}
/**
* Centers component <code>b</code> within component <code>a</code>.
*/
public static void centerComponent (Component a, Component b)
{
Dimension asize = a.getSize(), bsize = b.getSize();
b.setLocation((asize.width - bsize.width) / 2,
(asize.height - bsize.height) / 2);
}
/**
* Draw a string centered within a rectangle. The string is drawn
* using the graphics context's current font and color.
*
* @param g the graphics context.
* @param str the string.
* @param x the bounding x position.
* @param y the bounding y position.
* @param width the bounding width.
* @param height the bounding height.
*/
public static void drawStringCentered (
Graphics g, String str, int x, int y, int width, int height)
{
FontMetrics fm = g.getFontMetrics(g.getFont());
int xpos = x + ((width - fm.stringWidth(str)) / 2);
int ypos = y + ((height + fm.getAscent()) / 2);
g.drawString(str, xpos, ypos);
}
/**
* Returns the most reasonable position for the specified rectangle to
* be placed at so as to maximize its containment by the specified
* bounding rectangle while still placing it as near its original
* coordinates as possible.
*
* @param rect the rectangle to be positioned.
* @param bounds the containing rectangle.
*/
public static Point fitRectInRect (
Rectangle rect, Rectangle bounds)
{
// Guarantee that the right and bottom edges will be contained
// and do our best for the top and left edges.
return new Point(
Math.min(bounds.x + bounds.width - rect.width,
Math.max(rect.x, bounds.x)),
Math.min(bounds.y + bounds.height - rect.height,
Math.max(rect.y, bounds.y)));
}
/**
* Position the specified rectangle as closely as possible to
* its current position, but make sure it is within the specified
* bounds and that it does not overlap any of the Shapes contained
* in the avoid list.
*
* @param r the rectangle to attempt to position.
* @param bounds the bounding box within which the rectangle must be
* positioned.
* @param avoidShapes a collection of Shapes that must not be overlapped.
* The collection will be destructively modified.
*
* @return true if the rectangle was successfully placed, given the
* constraints, or false if the positioning failed (the rectangle will
* be left at it's original location.
*/
public static boolean positionRect (
Rectangle r, Rectangle bounds, Collection avoidShapes)
{
Point origPos = r.getLocation();
Comparator comp = createPointComparator(origPos);
SortableArrayList possibles = new SortableArrayList();
// we start things off with the passed-in point (adjusted to
// be inside the bounds, if needed)
possibles.add(fitRectInRect(r, bounds));
// keep track of area that doesn't generate new possibles
Area dead = new Area();
CHECKPOSSIBLES:
while (!possibles.isEmpty()) {
r.setLocation((Point) possibles.remove(0));
// make sure the rectangle is in the view and not over a dead area
if ((!bounds.contains(r)) || dead.intersects(r)) {
continue;
}
// see if it hits any shapes we're trying to avoid
for (Iterator iter=avoidShapes.iterator(); iter.hasNext(); ) {
Shape shape = (Shape) iter.next();
if (shape.intersects(r)) {
// remove that shape from our avoid list
iter.remove();
// but add it to our dead area
dead.add(new Area(shape));
// add 4 new possible points, each pushed in one direction
Rectangle pusher = shape.getBounds();
possibles.add(new Point(pusher.x - r.width, r.y));
possibles.add(new Point(r.x, pusher.y - r.height));
possibles.add(new Point(pusher.x + pusher.width, r.y));
possibles.add(new Point(r.x, pusher.y + pusher.height));
// re-sort the list
possibles.sort(comp);
continue CHECKPOSSIBLES;
}
}
// hey! if we got here, then it worked!
return true;
}
// we never found a match, move the rectangle back
r.setLocation(origPos);
return false;
}
/**
* Create a comparator that compares against the distance from
* the specified point.
*
* Used by positionRect().
*/
public static Comparator createPointComparator (Point origin)
{
final int xo = origin.x;
final int yo = origin.y;
return new Comparator() {
public int compare (Object o1, Object o2)
{
Point p1 = (Point) o1;
Point p2 = (Point) o2;
int x1 = xo - p1.x;
int y1 = yo - p1.y;
int x2 = xo - p2.x;
int y2 = yo - p2.y;
// since we are dealing with positive integers, we can
// omit the Math.sqrt() step for optimization
int dist1 = (x1 * x1) + (y1 * y1);
int dist2 = (x2 * x2) + (y2 * y2);
return dist1 - dist2;
}
};
}
/**
* Enables (or disables) the specified component, <em>and all of its
* children.</cite> A simple call to {@link Container#setEnabled}
* does not propagate the enabled state to the children of a
* component, which is senseless in our opinion, but was surely done
* for some arguably good reason.
*/
public static void setEnabled (Container comp, final boolean enabled)
{
applyToHierarchy(comp, new ComponentOp() {
public void apply (Component comp) {
comp.setEnabled(enabled);
}
});
}
/**
* Set the opacity on the specified component, <em>and all of its
* children.</cite>
*/
public static void setOpaque (JComponent comp, final boolean opaque)
{
applyToHierarchy(comp, new ComponentOp() {
public void apply (Component comp) {
if (comp instanceof JComponent) {
((JComponent) comp).setOpaque(opaque);
}
}
});
}
/**
* Apply the specified ComponentOp to the supplied component
* and then all its descendants.
*/
public static void applyToHierarchy (Component comp, ComponentOp op)
{
if (comp == null) {
return;
}
op.apply(comp);
if (comp instanceof Container) {
Container c = (Container) comp;
int ccount = c.getComponentCount();
for (int ii = 0; ii < ccount; ii++) {
applyToHierarchy(c.getComponent(ii), op);
}
}
}
/**
* An operation that may be applied to a component.
*/
public static interface ComponentOp
{
/**
* Apply an operation to the given component.
*/
public void apply (Component comp);
}
/**
* An interface for validating the text contained within a document.
*/
public static interface DocumentValidator
{
/**
* Should return false if the text is not valid for any reason.
*/
public boolean isValid (String text);
}
/**
* An interface for transforming the text contained within a document.
*/
public static interface DocumentTransformer
{
/**
* Should transform the specified text in some way, or simply
* return the text untransformed.
*/
public String transform (String text);
}
/**
* Set active Document helpers on the specified text component.
* Changes will not and cannot be made (either via user inputs or
* direct method manipulation) unless the validator says that the
* changes are ok.
*
* @param validator if non-null, all changes are sent to this for approval.
* @param transformer if non-null, is queried to change the text
* after all changes are made.
*/
public static void setDocumentHelpers (
JTextComponent comp, DocumentValidator validator,
DocumentTransformer transformer)
{
setDocumentHelpers(comp.getDocument(), validator, transformer);
}
/**
* Set active Document helpers on the specified Document.
* Changes will not and cannot be made (either via user inputs or
* direct method manipulation) unless the validator says that the
* changes are ok.
*
* @param validator if non-null, all changes are sent to this for approval.
* @param transformer if non-null, is queried to change the text
* after all changes are made.
*/
public static void setDocumentHelpers (
final Document doc, final DocumentValidator validator,
final DocumentTransformer transformer)
{
if (!(doc instanceof AbstractDocument)) {
throw new IllegalArgumentException(
"Specified document cannot be filtered!");
}
// set up the filter.
((AbstractDocument) doc).setDocumentFilter(new DocumentFilter()
{
// documentation inherited
public void remove (FilterBypass fb, int offset, int length)
throws BadLocationException
{
if (replaceOk(offset, length, "")) {
fb.remove(offset, length);
transform(fb);
}
}
// documentation inherited
public void insertString (
FilterBypass fb, int offset, String string, AttributeSet attr)
throws BadLocationException
{
if (replaceOk(offset, 0, string)) {
fb.insertString(offset, string, attr);
transform(fb);
}
}
// documentation inherited
public void replace (
FilterBypass fb, int offset, int length, String text,
AttributeSet attrs)
throws BadLocationException
{
if (replaceOk(offset, length, text)) {
fb.replace(offset, length, text, attrs);
transform(fb);
}
}
/**
* Convenience for remove/insert/replace to see if the
* proposed change is valid.
*/
protected boolean replaceOk (int offset, int length, String text)
throws BadLocationException
{
if (validator == null) {
return true; // everything's ok
}
try {
String current = doc.getText(0, doc.getLength());
String potential = current.substring(0, offset) +
text + current.substring(offset + length);
// validate the potential text.
return validator.isValid(potential);
} catch (IndexOutOfBoundsException ioobe) {
throw new BadLocationException(
"Bad Location", offset + length);
}
}
/**
* After a remove/insert/replace has taken place, we may
* want to transform the text in some way.
*/
protected void transform (FilterBypass fb)
{
if (transformer == null) {
return;
}
try {
String text = doc.getText(0, doc.getLength());
String xform = transformer.transform(text);
if (!text.equals(xform)) {
fb.replace(0, text.length(), xform, null);
}
} catch (BadLocationException ble) {
// oh well.
}
}
});
}
/**
* Activates anti-aliasing in the supplied graphics context.
*
* @return an object that should be passed to {@link
* #restoreAntiAliasing} to restore the graphics context to its
* original settings.
*/
public static Object activateAntiAliasing (Graphics2D gfx)
{
Object oalias = gfx.getRenderingHint(
RenderingHints.KEY_ANTIALIASING);
gfx.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
return oalias;
}
/**
* Restores anti-aliasing in the supplied graphics context to its
* original setting.
*
* @param rock the results of a previous call to {@link
* #activateAntiAliasing}.
*/
public static void restoreAntiAliasing (Graphics2D gfx, Object rock)
{
gfx.setRenderingHint(RenderingHints.KEY_ANTIALIASING, rock);
}
/**
* Adjusts the widths and heights of the cells of the supplied table
* to fit their contents.
*/
public static void sizeToContents (JTable table)
{
TableModel model = table.getModel();
TableColumn column = null;
Component comp = null;
int headerWidth = 0, cellWidth = 0, cellHeight = 0;
int ccount = table.getColumnModel().getColumnCount(),
rcount = model.getRowCount();
for (int cc = 0; cc < ccount; cc++) {
column = table.getColumnModel().getColumn(cc);
try {
comp = column.getHeaderRenderer().
getTableCellRendererComponent(null, column.getHeaderValue(),
false, false, 0, 0);
headerWidth = comp.getPreferredSize().width;
} catch (NullPointerException e) {
// getHeaderRenderer() this doesn't work in 1.3
}
for (int rr = 0; rr < rcount; rr++) {
Object cellValue = model.getValueAt(rr, cc);
comp = table.getDefaultRenderer(model.getColumnClass(cc)).
getTableCellRendererComponent(table, cellValue,
false, false, 0, cc);
Dimension psize = comp.getPreferredSize();
cellWidth = Math.max(psize.width, cellWidth);
cellHeight = Math.max(psize.height, cellHeight);
}
column.setPreferredWidth(Math.max(headerWidth, cellWidth));
}
if (cellHeight > 0) {
table.setRowHeight(cellHeight);
}
}
/**
* Refreshes the supplied {@link JComponent} to effect a call to
* {@link JComponent#revalidate} and {@link JComponent#repaint}, which
* is frequently necessary in cases such as adding components to or
* removing components from a {@link JPanel} since Swing doesn't
* automatically invalidate things for proper re-rendering.
*/
public static void refresh (JComponent c)
{
c.revalidate();
c.repaint();
}
/**
* Create a custom cursor out of the specified image, putting the hotspot
* in the exact center of the created cursor.
*/
public static Cursor createImageCursor (Image img)
{
return createImageCursor(img, null);
}
/**
* Create a custom cursor out of the specified image, with the specified
* hotspot.
*/
public static Cursor createImageCursor (Image img, Point hotspot)
{
Toolkit tk = Toolkit.getDefaultToolkit();
// for now, just report the cursor restrictions, then blindly create
int w = img.getWidth(null);
int h = img.getHeight(null);
Dimension d = tk.getBestCursorSize(w, h);
int colors = tk.getMaximumCursorColors();
// Log.debug("Creating custom cursor [desiredSize=" + w + "x" + h +
// ", bestSize=" + d.width + "x" + d.height +
// ", maxcolors=" + colors + "].");
// if the passed-in image is smaller, pad it with transparent pixels
// and use it anyway.
if (((w < d.width) && (h <= d.height)) ||
((w <= d.width) && (h < d.height))) {
Image padder = GraphicsEnvironment.getLocalGraphicsEnvironment().
getDefaultScreenDevice().getDefaultConfiguration().
createCompatibleImage(d.width, d.height, Transparency.BITMASK);
Graphics g = padder.getGraphics();
g.drawImage(img, 0, 0, null);
g.dispose();
// and reassign the image to the padded image
img = padder;
// and adjust the 'best' to cheat the hotspot checking code
d.width = w;
d.height = h;
}
// make sure the hotspot is valid
if (hotspot == null) {
hotspot = new Point(d.width / 2, d.height / 2);
} else {
hotspot.x = Math.min(d.width - 1, Math.max(0, hotspot.x));
hotspot.y = Math.min(d.height - 1, Math.max(0, hotspot.y));
}
// and create the cursor
return tk.createCustomCursor(img, hotspot, "samskivertDnDCursor");
}
/**
* Adds a one pixel border of random color to this and all panels
* contained in this panel's child hierarchy.
*/
public static void addDebugBorders (JPanel panel)
{
Color bcolor = new Color(Math.abs(_rando.nextInt()) % 256,
Math.abs(_rando.nextInt()) % 256,
Math.abs(_rando.nextInt()) % 256);
panel.setBorder(BorderFactory.createLineBorder(bcolor));
for (int ii = 0; ii < panel.getComponentCount(); ii++) {
Object child = panel.getComponent(ii);
if (child instanceof JPanel) {
addDebugBorders((JPanel)child);
}
}
}
/** Used by {@link #addDebugBorders}. */
protected static Random _rando = new Random();
}
| projects/samskivert/src/java/com/samskivert/swing/util/SwingUtil.java | //
// $Id: SwingUtil.java,v 1.28 2003/12/19 04:07:33 mdb Exp $
//
// samskivert library - useful routines for java programs
// Copyright (C) 2001 Michael Bayne
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.samskivert.swing.util;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Graphics;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.Point;
import java.awt.Polygon;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.Toolkit;
import java.awt.Transparency;
import java.awt.Window;
import java.awt.geom.Area;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Random;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.DocumentFilter;
import javax.swing.text.JTextComponent;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import com.samskivert.util.SortableArrayList;
/**
* Miscellaneous useful Swing-related utility functions.
*/
public class SwingUtil
{
/**
* Center the given window within the screen boundaries.
*
* @param window the window to be centered.
*/
public static void centerWindow (Window window)
{
Toolkit tk = window.getToolkit();
Dimension ss = tk.getScreenSize();
int width = window.getWidth(), height = window.getHeight();
window.setBounds((ss.width-width)/2, (ss.height-height)/2,
width, height);
}
/**
* Centers component <code>b</code> within component <code>a</code>.
*/
public static void centerComponent (Component a, Component b)
{
Dimension asize = a.getSize(), bsize = b.getSize();
b.setLocation((asize.width - bsize.width) / 2,
(asize.height - bsize.height) / 2);
}
/**
* Draw a string centered within a rectangle. The string is drawn
* using the graphics context's current font and color.
*
* @param g the graphics context.
* @param str the string.
* @param x the bounding x position.
* @param y the bounding y position.
* @param width the bounding width.
* @param height the bounding height.
*/
public static void drawStringCentered (
Graphics g, String str, int x, int y, int width, int height)
{
FontMetrics fm = g.getFontMetrics(g.getFont());
int xpos = x + ((width - fm.stringWidth(str)) / 2);
int ypos = y + ((height + fm.getAscent()) / 2);
g.drawString(str, xpos, ypos);
}
/**
* Returns the most reasonable position for the specified rectangle to
* be placed at so as to maximize its containment by the specified
* bounding rectangle while still placing it as near its original
* coordinates as possible.
*
* @param rect the rectangle to be positioned.
* @param bounds the containing rectangle.
*/
public static Point fitRectInRect (
Rectangle rect, Rectangle bounds)
{
// Guarantee that the right and bottom edges will be contained
// and do our best for the top and left edges.
return new Point(
Math.min(bounds.x + bounds.width - rect.width,
Math.max(rect.x, bounds.x)),
Math.min(bounds.y + bounds.height - rect.height,
Math.max(rect.y, bounds.y)));
}
/**
* Position the specified rectangle as closely as possible to
* its current position, but make sure it is within the specified
* bounds and that it does not overlap any of the Shapes contained
* in the avoid list.
*
* @param r the rectangle to attempt to position.
* @param bounds the bounding box within which the rectangle must be
* positioned.
* @param avoidShapes a collection of Shapes that must not be overlapped.
* The collection will be destructively modified.
*
* @return true if the rectangle was successfully placed, given the
* constraints, or false if the positioning failed (the rectangle will
* be left at it's original location.
*/
public static boolean positionRect (
Rectangle r, Rectangle bounds, Collection avoidShapes)
{
Point origPos = r.getLocation();
Comparator comp = createPointComparator(origPos);
SortableArrayList possibles = new SortableArrayList();
// we start things off with the passed-in point (adjusted to
// be inside the bounds, if needed)
possibles.add(fitRectInRect(r, bounds));
// keep track of area that doesn't generate new possibles
Area dead = new Area();
CHECKPOSSIBLES:
while (!possibles.isEmpty()) {
r.setLocation((Point) possibles.remove(0));
// make sure the rectangle is in the view and not over a dead area
if ((!bounds.contains(r)) || dead.intersects(r)) {
continue;
}
// see if it hits any shapes we're trying to avoid
for (Iterator iter=avoidShapes.iterator(); iter.hasNext(); ) {
Shape shape = (Shape) iter.next();
if (shape.intersects(r)) {
// remove that shape from our avoid list
iter.remove();
// but add it to our dead area
dead.add(new Area(shape));
// add 4 new possible points, each pushed in one direction
Rectangle pusher = shape.getBounds();
possibles.add(new Point(pusher.x - r.width, r.y));
possibles.add(new Point(r.x, pusher.y - r.height));
possibles.add(new Point(pusher.x + pusher.width, r.y));
possibles.add(new Point(r.x, pusher.y + pusher.height));
// re-sort the list
possibles.sort(comp);
continue CHECKPOSSIBLES;
}
}
// hey! if we got here, then it worked!
return true;
}
// we never found a match, move the rectangle back
r.setLocation(origPos);
return false;
}
/**
* Create a comparator that compares against the distance from
* the specified point.
*
* Used by positionRect().
*/
public static Comparator createPointComparator (Point origin)
{
final int xo = origin.x;
final int yo = origin.y;
return new Comparator() {
public int compare (Object o1, Object o2)
{
Point p1 = (Point) o1;
Point p2 = (Point) o2;
int x1 = xo - p1.x;
int y1 = yo - p1.y;
int x2 = xo - p2.x;
int y2 = yo - p2.y;
// since we are dealing with positive integers, we can
// omit the Math.sqrt() step for optimization
int dist1 = (x1 * x1) + (y1 * y1);
int dist2 = (x2 * x2) + (y2 * y2);
return dist1 - dist2;
}
};
}
/**
* Enables (or disables) the specified component, <em>and all of its
* children.</cite> A simple call to {@link Container#setEnabled}
* does not propagate the enabled state to the children of a
* component, which is senseless in our opinion, but was surely done
* for some arguably good reason.
*/
public static void setEnabled (Container comp, final boolean enabled)
{
applyToHierarchy(comp, new ComponentOp() {
public void apply (Component comp)
{
comp.setEnabled(enabled);
}
});
}
/**
* Apply the specified ComponentOp to the supplied component
* and then all its descendants.
*/
public static void applyToHierarchy (Component comp, ComponentOp op)
{
if (comp == null) {
return;
}
op.apply(comp);
if (comp instanceof Container) {
Container c = (Container) comp;
int ccount = c.getComponentCount();
for (int ii = 0; ii < ccount; ii++) {
applyToHierarchy(c.getComponent(ii), op);
}
}
}
/**
* An operation that may be applied to a component.
*/
public static interface ComponentOp
{
/**
* Apply an operation to the given component.
*/
public void apply (Component comp);
}
/**
* An interface for validating the text contained within a document.
*/
public static interface DocumentValidator
{
/**
* Should return false if the text is not valid for any reason.
*/
public boolean isValid (String text);
}
/**
* An interface for transforming the text contained within a document.
*/
public static interface DocumentTransformer
{
/**
* Should transform the specified text in some way, or simply
* return the text untransformed.
*/
public String transform (String text);
}
/**
* Set active Document helpers on the specified text component.
* Changes will not and cannot be made (either via user inputs or
* direct method manipulation) unless the validator says that the
* changes are ok.
*
* @param validator if non-null, all changes are sent to this for approval.
* @param transformer if non-null, is queried to change the text
* after all changes are made.
*/
public static void setDocumentHelpers (
JTextComponent comp, DocumentValidator validator,
DocumentTransformer transformer)
{
setDocumentHelpers(comp.getDocument(), validator, transformer);
}
/**
* Set active Document helpers on the specified Document.
* Changes will not and cannot be made (either via user inputs or
* direct method manipulation) unless the validator says that the
* changes are ok.
*
* @param validator if non-null, all changes are sent to this for approval.
* @param transformer if non-null, is queried to change the text
* after all changes are made.
*/
public static void setDocumentHelpers (
final Document doc, final DocumentValidator validator,
final DocumentTransformer transformer)
{
if (!(doc instanceof AbstractDocument)) {
throw new IllegalArgumentException(
"Specified document cannot be filtered!");
}
// set up the filter.
((AbstractDocument) doc).setDocumentFilter(new DocumentFilter()
{
// documentation inherited
public void remove (FilterBypass fb, int offset, int length)
throws BadLocationException
{
if (replaceOk(offset, length, "")) {
fb.remove(offset, length);
transform(fb);
}
}
// documentation inherited
public void insertString (
FilterBypass fb, int offset, String string, AttributeSet attr)
throws BadLocationException
{
if (replaceOk(offset, 0, string)) {
fb.insertString(offset, string, attr);
transform(fb);
}
}
// documentation inherited
public void replace (
FilterBypass fb, int offset, int length, String text,
AttributeSet attrs)
throws BadLocationException
{
if (replaceOk(offset, length, text)) {
fb.replace(offset, length, text, attrs);
transform(fb);
}
}
/**
* Convenience for remove/insert/replace to see if the
* proposed change is valid.
*/
protected boolean replaceOk (int offset, int length, String text)
throws BadLocationException
{
if (validator == null) {
return true; // everything's ok
}
try {
String current = doc.getText(0, doc.getLength());
String potential = current.substring(0, offset) +
text + current.substring(offset + length);
// validate the potential text.
return validator.isValid(potential);
} catch (IndexOutOfBoundsException ioobe) {
throw new BadLocationException(
"Bad Location", offset + length);
}
}
/**
* After a remove/insert/replace has taken place, we may
* want to transform the text in some way.
*/
protected void transform (FilterBypass fb)
{
if (transformer == null) {
return;
}
try {
String text = doc.getText(0, doc.getLength());
String xform = transformer.transform(text);
if (!text.equals(xform)) {
fb.replace(0, text.length(), xform, null);
}
} catch (BadLocationException ble) {
// oh well.
}
}
});
}
/**
* Activates anti-aliasing in the supplied graphics context.
*
* @return an object that should be passed to {@link
* #restoreAntiAliasing} to restore the graphics context to its
* original settings.
*/
public static Object activateAntiAliasing (Graphics2D gfx)
{
Object oalias = gfx.getRenderingHint(
RenderingHints.KEY_ANTIALIASING);
gfx.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
return oalias;
}
/**
* Restores anti-aliasing in the supplied graphics context to its
* original setting.
*
* @param rock the results of a previous call to {@link
* #activateAntiAliasing}.
*/
public static void restoreAntiAliasing (Graphics2D gfx, Object rock)
{
gfx.setRenderingHint(RenderingHints.KEY_ANTIALIASING, rock);
}
/**
* Adjusts the widths and heights of the cells of the supplied table
* to fit their contents.
*/
public static void sizeToContents (JTable table)
{
TableModel model = table.getModel();
TableColumn column = null;
Component comp = null;
int headerWidth = 0, cellWidth = 0, cellHeight = 0;
int ccount = table.getColumnModel().getColumnCount(),
rcount = model.getRowCount();
for (int cc = 0; cc < ccount; cc++) {
column = table.getColumnModel().getColumn(cc);
try {
comp = column.getHeaderRenderer().
getTableCellRendererComponent(null, column.getHeaderValue(),
false, false, 0, 0);
headerWidth = comp.getPreferredSize().width;
} catch (NullPointerException e) {
// getHeaderRenderer() this doesn't work in 1.3
}
for (int rr = 0; rr < rcount; rr++) {
Object cellValue = model.getValueAt(rr, cc);
comp = table.getDefaultRenderer(model.getColumnClass(cc)).
getTableCellRendererComponent(table, cellValue,
false, false, 0, cc);
Dimension psize = comp.getPreferredSize();
cellWidth = Math.max(psize.width, cellWidth);
cellHeight = Math.max(psize.height, cellHeight);
}
column.setPreferredWidth(Math.max(headerWidth, cellWidth));
}
if (cellHeight > 0) {
table.setRowHeight(cellHeight);
}
}
/**
* Refreshes the supplied {@link JComponent} to effect a call to
* {@link JComponent#revalidate} and {@link JComponent#repaint}, which
* is frequently necessary in cases such as adding components to or
* removing components from a {@link JPanel} since Swing doesn't
* automatically invalidate things for proper re-rendering.
*/
public static void refresh (JComponent c)
{
c.revalidate();
c.repaint();
}
/**
* Create a custom cursor out of the specified image, putting the hotspot
* in the exact center of the created cursor.
*/
public static Cursor createImageCursor (Image img)
{
return createImageCursor(img, null);
}
/**
* Create a custom cursor out of the specified image, with the specified
* hotspot.
*/
public static Cursor createImageCursor (Image img, Point hotspot)
{
Toolkit tk = Toolkit.getDefaultToolkit();
// for now, just report the cursor restrictions, then blindly create
int w = img.getWidth(null);
int h = img.getHeight(null);
Dimension d = tk.getBestCursorSize(w, h);
int colors = tk.getMaximumCursorColors();
// Log.debug("Creating custom cursor [desiredSize=" + w + "x" + h +
// ", bestSize=" + d.width + "x" + d.height +
// ", maxcolors=" + colors + "].");
// if the passed-in image is smaller, pad it with transparent pixels
// and use it anyway.
if (((w < d.width) && (h <= d.height)) ||
((w <= d.width) && (h < d.height))) {
Image padder = GraphicsEnvironment.getLocalGraphicsEnvironment().
getDefaultScreenDevice().getDefaultConfiguration().
createCompatibleImage(d.width, d.height, Transparency.BITMASK);
Graphics g = padder.getGraphics();
g.drawImage(img, 0, 0, null);
g.dispose();
// and reassign the image to the padded image
img = padder;
// and adjust the 'best' to cheat the hotspot checking code
d.width = w;
d.height = h;
}
// make sure the hotspot is valid
if (hotspot == null) {
hotspot = new Point(d.width / 2, d.height / 2);
} else {
hotspot.x = Math.min(d.width - 1, Math.max(0, hotspot.x));
hotspot.y = Math.min(d.height - 1, Math.max(0, hotspot.y));
}
// and create the cursor
return tk.createCustomCursor(img, hotspot, "samskivertDnDCursor");
}
/**
* Adds a one pixel border of random color to this and all panels
* contained in this panel's child hierarchy.
*/
public static void addDebugBorders (JPanel panel)
{
Color bcolor = new Color(Math.abs(_rando.nextInt()) % 256,
Math.abs(_rando.nextInt()) % 256,
Math.abs(_rando.nextInt()) % 256);
panel.setBorder(BorderFactory.createLineBorder(bcolor));
for (int ii = 0; ii < panel.getComponentCount(); ii++) {
Object child = panel.getComponent(ii);
if (child instanceof JPanel) {
addDebugBorders((JPanel)child);
}
}
}
/** Used by {@link #addDebugBorders}. */
protected static Random _rando = new Random();
}
| added setOpaque().
git-svn-id: 64ebf368729f38804935acb7146e017e0f909c6b@1367 6335cc39-0255-0410-8fd6-9bcaacd3b74c
| projects/samskivert/src/java/com/samskivert/swing/util/SwingUtil.java | added setOpaque(). | <ide><path>rojects/samskivert/src/java/com/samskivert/swing/util/SwingUtil.java
<ide> //
<del>// $Id: SwingUtil.java,v 1.28 2003/12/19 04:07:33 mdb Exp $
<add>// $Id: SwingUtil.java,v 1.29 2004/01/12 08:39:49 ray Exp $
<ide> //
<ide> // samskivert library - useful routines for java programs
<ide> // Copyright (C) 2001 Michael Bayne
<ide> public static void setEnabled (Container comp, final boolean enabled)
<ide> {
<ide> applyToHierarchy(comp, new ComponentOp() {
<del> public void apply (Component comp)
<del> {
<add> public void apply (Component comp) {
<ide> comp.setEnabled(enabled);
<add> }
<add> });
<add> }
<add>
<add> /**
<add> * Set the opacity on the specified component, <em>and all of its
<add> * children.</cite>
<add> */
<add> public static void setOpaque (JComponent comp, final boolean opaque)
<add> {
<add> applyToHierarchy(comp, new ComponentOp() {
<add> public void apply (Component comp) {
<add> if (comp instanceof JComponent) {
<add> ((JComponent) comp).setOpaque(opaque);
<add> }
<ide> }
<ide> });
<ide> } |
|
Java | apache-2.0 | 0cda7ee0a696443927b6a521557c0a6456d47bb4 | 0 | vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa | // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.container.http;
import com.yahoo.component.ComponentId;
import com.yahoo.jdisc.http.ConnectorConfig;
import com.yahoo.osgi.provider.model.ComponentModel;
import com.yahoo.vespa.model.container.component.SimpleComponent;
import com.yahoo.vespa.model.container.http.ssl.DefaultSslProvider;
import com.yahoo.vespa.model.container.http.ssl.SslProvider;
import java.util.Optional;
/**
* @author Einar M R Rosenvinge
* @author bjorncs
* @author mortent
*/
public class ConnectorFactory extends SimpleComponent implements ConnectorConfig.Producer {
private final String name;
private final int listenPort;
private final SslProvider sslProviderComponent;
private volatile ComponentId defaultRequestFilterChain;
private volatile ComponentId defaultResponseFilterChain;
protected ConnectorFactory(Builder builder) {
super(new ComponentModel(builder.name,
com.yahoo.jdisc.http.server.jetty.ConnectorFactory.class.getName(),
null));
this.name = builder.name;
this.listenPort = builder.listenPort;
this.sslProviderComponent = builder.sslProvider != null ? builder.sslProvider : new DefaultSslProvider(name);
this.defaultRequestFilterChain = builder.defaultRequestFilterChain;
this.defaultResponseFilterChain = builder.defaultResponseFilterChain;
addChild(sslProviderComponent);
inject(sslProviderComponent);
}
@Override
public void getConfig(ConnectorConfig.Builder connectorBuilder) {
connectorBuilder.listenPort(listenPort);
connectorBuilder.name(name);
sslProviderComponent.amendConnectorConfig(connectorBuilder);
}
public String getName() {
return name;
}
public int getListenPort() {
return listenPort;
}
public Optional<ComponentId> getDefaultRequestFilterChain() { return Optional.ofNullable(defaultRequestFilterChain); }
public Optional<ComponentId> getDefaultResponseFilterChain() { return Optional.ofNullable(defaultResponseFilterChain); }
public void setDefaultRequestFilterChain(ComponentId filterChain) { this.defaultRequestFilterChain = filterChain; }
public void setDefaultResponseFilterChain(ComponentId filterChain) { this.defaultResponseFilterChain = filterChain; }
public static class Builder {
private final String name;
private final int listenPort;
private SslProvider sslProvider;
private ComponentId defaultRequestFilterChain;
private ComponentId defaultResponseFilterChain;
public Builder(String name, int listenPort) {
this.name = name;
this.listenPort = listenPort;
}
public Builder sslProvider(SslProvider sslProvider) {
this.sslProvider = sslProvider; return this;
}
public Builder defaultRequestFilterChain(ComponentId filterChain) {
this.defaultRequestFilterChain = filterChain; return this;
}
public Builder defaultResponseFilterChain(ComponentId filterChain) {
this.defaultResponseFilterChain = filterChain; return this;
}
public ConnectorFactory build() {
return new ConnectorFactory(this);
}
}
}
| config-model/src/main/java/com/yahoo/vespa/model/container/http/ConnectorFactory.java | // Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.container.http;
import com.yahoo.component.ComponentId;
import com.yahoo.jdisc.http.ConnectorConfig;
import com.yahoo.osgi.provider.model.ComponentModel;
import com.yahoo.vespa.model.container.component.SimpleComponent;
import com.yahoo.vespa.model.container.http.ssl.DefaultSslProvider;
import com.yahoo.vespa.model.container.http.ssl.SslProvider;
import java.util.Optional;
/**
* @author Einar M R Rosenvinge
* @author bjorncs
* @author mortent
*/
public class ConnectorFactory extends SimpleComponent implements ConnectorConfig.Producer {
private final String name;
private final int listenPort;
private final SslProvider sslProviderComponent;
private final boolean enableHttp2;
private volatile ComponentId defaultRequestFilterChain;
private volatile ComponentId defaultResponseFilterChain;
protected ConnectorFactory(Builder builder) {
super(new ComponentModel(builder.name,
com.yahoo.jdisc.http.server.jetty.ConnectorFactory.class.getName(),
null));
this.name = builder.name;
this.listenPort = builder.listenPort;
this.sslProviderComponent = builder.sslProvider != null ? builder.sslProvider : new DefaultSslProvider(name);
this.defaultRequestFilterChain = builder.defaultRequestFilterChain;
this.defaultResponseFilterChain = builder.defaultResponseFilterChain;
this.enableHttp2 = builder.enableHttp2 != null ? builder.enableHttp2 : false;
addChild(sslProviderComponent);
inject(sslProviderComponent);
}
@Override
public void getConfig(ConnectorConfig.Builder connectorBuilder) {
connectorBuilder.listenPort(listenPort);
connectorBuilder.name(name);
connectorBuilder.http2Enabled(enableHttp2);
sslProviderComponent.amendConnectorConfig(connectorBuilder);
}
public String getName() {
return name;
}
public int getListenPort() {
return listenPort;
}
public Optional<ComponentId> getDefaultRequestFilterChain() { return Optional.ofNullable(defaultRequestFilterChain); }
public Optional<ComponentId> getDefaultResponseFilterChain() { return Optional.ofNullable(defaultResponseFilterChain); }
public void setDefaultRequestFilterChain(ComponentId filterChain) { this.defaultRequestFilterChain = filterChain; }
public void setDefaultResponseFilterChain(ComponentId filterChain) { this.defaultResponseFilterChain = filterChain; }
public static class Builder {
private final String name;
private final int listenPort;
private SslProvider sslProvider;
private ComponentId defaultRequestFilterChain;
private ComponentId defaultResponseFilterChain;
private Boolean enableHttp2;
public Builder(String name, int listenPort) {
this.name = name;
this.listenPort = listenPort;
}
public Builder sslProvider(SslProvider sslProvider) {
this.sslProvider = sslProvider; return this;
}
public Builder defaultRequestFilterChain(ComponentId filterChain) {
this.defaultRequestFilterChain = filterChain; return this;
}
public Builder defaultResponseFilterChain(ComponentId filterChain) {
this.defaultResponseFilterChain = filterChain; return this;
}
public Builder enableHttp2(boolean enabled) { this.enableHttp2 = enabled; return this; }
public ConnectorFactory build() {
return new ConnectorFactory(this);
}
}
}
| Remove leftovers from HTTP2 feature flag
This will effectively re-enable HTTP/2 (since initial PR for removing feature flag)
| config-model/src/main/java/com/yahoo/vespa/model/container/http/ConnectorFactory.java | Remove leftovers from HTTP2 feature flag | <ide><path>onfig-model/src/main/java/com/yahoo/vespa/model/container/http/ConnectorFactory.java
<ide> private final String name;
<ide> private final int listenPort;
<ide> private final SslProvider sslProviderComponent;
<del> private final boolean enableHttp2;
<ide> private volatile ComponentId defaultRequestFilterChain;
<ide> private volatile ComponentId defaultResponseFilterChain;
<ide>
<ide> this.sslProviderComponent = builder.sslProvider != null ? builder.sslProvider : new DefaultSslProvider(name);
<ide> this.defaultRequestFilterChain = builder.defaultRequestFilterChain;
<ide> this.defaultResponseFilterChain = builder.defaultResponseFilterChain;
<del> this.enableHttp2 = builder.enableHttp2 != null ? builder.enableHttp2 : false;
<ide> addChild(sslProviderComponent);
<ide> inject(sslProviderComponent);
<ide> }
<ide> public void getConfig(ConnectorConfig.Builder connectorBuilder) {
<ide> connectorBuilder.listenPort(listenPort);
<ide> connectorBuilder.name(name);
<del> connectorBuilder.http2Enabled(enableHttp2);
<ide> sslProviderComponent.amendConnectorConfig(connectorBuilder);
<ide> }
<ide>
<ide> private SslProvider sslProvider;
<ide> private ComponentId defaultRequestFilterChain;
<ide> private ComponentId defaultResponseFilterChain;
<del> private Boolean enableHttp2;
<ide>
<ide> public Builder(String name, int listenPort) {
<ide> this.name = name;
<ide> this.defaultResponseFilterChain = filterChain; return this;
<ide> }
<ide>
<del> public Builder enableHttp2(boolean enabled) { this.enableHttp2 = enabled; return this; }
<del>
<ide> public ConnectorFactory build() {
<ide> return new ConnectorFactory(this);
<ide> } |
|
Java | epl-1.0 | b090c699b2a1906c0b55b2b9b3b2af17ecd70324 | 0 | sguan-actuate/birt,sguan-actuate/birt,rrimmana/birt-1,rrimmana/birt-1,rrimmana/birt-1,rrimmana/birt-1,Charling-Huang/birt,rrimmana/birt-1,Charling-Huang/birt,Charling-Huang/birt,Charling-Huang/birt,sguan-actuate/birt,Charling-Huang/birt,sguan-actuate/birt,sguan-actuate/birt | /*******************************************************************************
* Copyright (c) 2004 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.report.designer.ui.lib.explorer;
import org.eclipse.birt.report.designer.internal.ui.editors.parts.AbstractMultiPageLayoutEditor;
import org.eclipse.birt.report.designer.internal.ui.util.UIUtil;
import org.eclipse.birt.report.designer.internal.ui.views.ILibraryProvider;
import org.eclipse.birt.report.designer.nls.Messages;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.part.IContributedContentsView;
import org.eclipse.ui.part.IPage;
import org.eclipse.ui.part.MessagePage;
import org.eclipse.ui.part.PageBook;
import org.eclipse.ui.part.PageBookView;
/**
* Attribute view shows the attributes of the selected control. If no control is
* selected, it will show no attributes and a sentence describing there is
* nothing to show for the selected object.
* </p>
* Multi-selection of control of the same type will normally show the same UI as
* if only one control was selected. Some of the values may be gray or blank if
* the selected controls have different attributes. If the controls have
* different type, nothing will be shown in the attributes view.
* </P>
*
*
*/
public class LibraryExplorerView extends PageBookView
{
/**
* the ID
*/
public static final String ID = "org.eclipse.birt.report.designer.ui.lib.explorer.view"; //$NON-NLS-1$
private String defaultText = Messages.getString( "LibraryExplorerView.defaultText.notAvailable" ); //$NON-NLS-1$
/**
* default constructor
*/
public LibraryExplorerView( )
{
super( );
}
/**
* Creates and returns the default page for this view.
*
* @param book
* the pagebook control
* @return the default page
*/
protected IPage createDefaultPage( PageBook book )
{
MessagePage page = new MessagePage( );
initPage( page );
page.createControl( book );
page.setMessage( defaultText );
return page;
}
/**
* Creates a new page in the pagebook for a particular part. This page will
* be made visible whenever the part is active, and will be destroyed with a
* call to <code>doDestroyPage</code>.
*
* @param part
* the input part
* @return the record describing a new page for this view
* @see #doDestroyPage
*/
protected PageRec doCreatePage( IWorkbenchPart part )
{
if ( part instanceof AbstractMultiPageLayoutEditor )
{
LibraryExplorerTreeViewPage page = new LibraryExplorerTreeViewPage( );
IEditorPart editor = UIUtil.getActiveEditor( true );
if(editor !=null)
{
ILibraryProvider provider = (ILibraryProvider) editor.getAdapter( ILibraryProvider.class );
if( provider != null )
{
page.setLibraryProvider( provider );
initPage( page );
page.createControl( getPageBook( ) );
return new PageRec( part, page );
}
}
}
return null;
}
/**
* Destroys a page in the pagebook for a particular part. This page was
* returned as a result from <code>doCreatePage</code>.
*
* @param part
* the input part
* @param pageRecord
* a page record for the part
* @see #doCreatePage
*/
protected void doDestroyPage( IWorkbenchPart part, PageRec pageRecord )
{
IPage page = pageRecord.page;
page.dispose( );
pageRecord.dispose( );
}
/**
* Returns the active, important workbench part for this view.
* <p>
* When the page book view is created it has no idea which part within the
* workbook should be used to generate the first page. Therefore, it
* delegates the choice to subclasses of <code>PageBookView</code>.
* </p>
* <p>
* Implementors of this method should return an active, important part in
* the workbench or <code>null</code> if none found.
* </p>
*
* @return the active important part, or <code>null</code> if none
*/
protected IWorkbenchPart getBootstrapPart( )
{
IWorkbenchPage page = getSite( ).getPage( );
if ( page != null )
{
return page.getActiveEditor( );
}
return null;
}
/**
* Returns whether the given part should be added to this view.
*
* @param part
* the input part
* @return <code>true</code> if the part is relevant, and
* <code>false</code> otherwise
*/
protected boolean isImportant( IWorkbenchPart part )
{
return ( part instanceof IEditorPart );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class)
*/
public Object getAdapter( Class key )
{
if ( key == IContributedContentsView.class )
return new IContributedContentsView( ) {
public IWorkbenchPart getContributingPart( )
{
return getCurrentContributingPart( );
}
};
return super.getAdapter( key );
}
} | UI/org.eclipse.birt.report.designer.ui.lib.explorer/src/org/eclipse/birt/report/designer/ui/lib/explorer/LibraryExplorerView.java | /*******************************************************************************
* Copyright (c) 2004 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.report.designer.ui.lib.explorer;
import org.eclipse.birt.report.designer.internal.ui.editors.parts.AbstractMultiPageLayoutEditor;
import org.eclipse.birt.report.designer.internal.ui.util.UIUtil;
import org.eclipse.birt.report.designer.internal.ui.views.ILibraryProvider;
import org.eclipse.birt.report.designer.nls.Messages;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.part.IContributedContentsView;
import org.eclipse.ui.part.IPage;
import org.eclipse.ui.part.MessagePage;
import org.eclipse.ui.part.PageBook;
import org.eclipse.ui.part.PageBookView;
/**
* Attribute view shows the attributes of the selected control. If no control is
* selected, it will show no attributes and a sentence describing there is
* nothing to show for the selected object.
* </p>
* Multi-selection of control of the same type will normally show the same UI as
* if only one control was selected. Some of the values may be gray or blank if
* the selected controls have different attributes. If the controls have
* different type, nothing will be shown in the attributes view.
* </P>
*
*
*/
public class LibraryExplorerView extends PageBookView
{
/**
* the ID
*/
public static final String ID = "org.eclipse.birt.report.designer.ui.lib.explorer.view"; //$NON-NLS-1$
private String defaultText = Messages.getString( "LibraryExplorerView.defaultText.notAvailable" ); //$NON-NLS-1$
/**
* default constructor
*/
public LibraryExplorerView( )
{
super( );
}
/**
* Creates and returns the default page for this view.
*
* @param book
* the pagebook control
* @return the default page
*/
protected IPage createDefaultPage( PageBook book )
{
MessagePage page = new MessagePage( );
initPage( page );
page.createControl( book );
page.setMessage( defaultText );
return page;
}
/**
* Creates a new page in the pagebook for a particular part. This page will
* be made visible whenever the part is active, and will be destroyed with a
* call to <code>doDestroyPage</code>.
*
* @param part
* the input part
* @return the record describing a new page for this view
* @see #doDestroyPage
*/
protected PageRec doCreatePage( IWorkbenchPart part )
{
if ( part instanceof AbstractMultiPageLayoutEditor )
{
LibraryExplorerTreeViewPage page = new LibraryExplorerTreeViewPage( );
IEditorPart editor = UIUtil.getActiveEditor( true );
ILibraryProvider provider = (ILibraryProvider) editor.getAdapter( ILibraryProvider.class );
if( provider != null )
{
page.setLibraryProvider( provider );
initPage( page );
page.createControl( getPageBook( ) );
return new PageRec( part, page );
}
}
return null;
}
/**
* Destroys a page in the pagebook for a particular part. This page was
* returned as a result from <code>doCreatePage</code>.
*
* @param part
* the input part
* @param pageRecord
* a page record for the part
* @see #doCreatePage
*/
protected void doDestroyPage( IWorkbenchPart part, PageRec pageRecord )
{
IPage page = pageRecord.page;
page.dispose( );
pageRecord.dispose( );
}
/**
* Returns the active, important workbench part for this view.
* <p>
* When the page book view is created it has no idea which part within the
* workbook should be used to generate the first page. Therefore, it
* delegates the choice to subclasses of <code>PageBookView</code>.
* </p>
* <p>
* Implementors of this method should return an active, important part in
* the workbench or <code>null</code> if none found.
* </p>
*
* @return the active important part, or <code>null</code> if none
*/
protected IWorkbenchPart getBootstrapPart( )
{
IWorkbenchPage page = getSite( ).getPage( );
if ( page != null )
{
return page.getActiveEditor( );
}
return null;
}
/**
* Returns whether the given part should be added to this view.
*
* @param part
* the input part
* @return <code>true</code> if the part is relevant, and
* <code>false</code> otherwise
*/
protected boolean isImportant( IWorkbenchPart part )
{
return ( part instanceof IEditorPart );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class)
*/
public Object getAdapter( Class key )
{
if ( key == IContributedContentsView.class )
return new IContributedContentsView( ) {
public IWorkbenchPart getContributingPart( )
{
return getCurrentContributingPart( );
}
};
return super.getAdapter( key );
}
} | - Summary: Prevent NPE problem when init the library explorer at init stage.
- Bugzilla Bug (s) Resolved:
- Description: If user close the workspace with library explorer opening, at NPE can be thrown when user reopen the eclipse and the eclipse try to restore the layout. That's a issue of eclipse that when the editor is opened, the getActiveEditor() can return null in some cases.
A opening problem is the library explorer can be empty even a designer is opening in this case. User need to reselect the editor or refresh the library explorer explicit.
- Tests Description: manual
- Files Edited:
- Files Added:
- Notes to Build Team:
- Notes to Developers:
- Notes to QA:
- Notes to Documentation:
| UI/org.eclipse.birt.report.designer.ui.lib.explorer/src/org/eclipse/birt/report/designer/ui/lib/explorer/LibraryExplorerView.java | - Summary: Prevent NPE problem when init the library explorer at init stage. | <ide><path>I/org.eclipse.birt.report.designer.ui.lib.explorer/src/org/eclipse/birt/report/designer/ui/lib/explorer/LibraryExplorerView.java
<ide> {
<ide> LibraryExplorerTreeViewPage page = new LibraryExplorerTreeViewPage( );
<ide> IEditorPart editor = UIUtil.getActiveEditor( true );
<del> ILibraryProvider provider = (ILibraryProvider) editor.getAdapter( ILibraryProvider.class );
<del> if( provider != null )
<add> if(editor !=null)
<ide> {
<del> page.setLibraryProvider( provider );
<del> initPage( page );
<del> page.createControl( getPageBook( ) );
<del> return new PageRec( part, page );
<add> ILibraryProvider provider = (ILibraryProvider) editor.getAdapter( ILibraryProvider.class );
<add> if( provider != null )
<add> {
<add> page.setLibraryProvider( provider );
<add> initPage( page );
<add> page.createControl( getPageBook( ) );
<add> return new PageRec( part, page );
<add> }
<ide> }
<ide> }
<ide> return null; |
|
Java | apache-2.0 | 2c2dbdf078a36f93a2409b9b0a5bf1ff6ecead3b | 0 | jeorme/OG-Platform,ChinaQuants/OG-Platform,codeaudit/OG-Platform,ChinaQuants/OG-Platform,jerome79/OG-Platform,codeaudit/OG-Platform,DevStreet/FinanceAnalytics,ChinaQuants/OG-Platform,jeorme/OG-Platform,jeorme/OG-Platform,jerome79/OG-Platform,McLeodMoores/starling,codeaudit/OG-Platform,nssales/OG-Platform,nssales/OG-Platform,DevStreet/FinanceAnalytics,jerome79/OG-Platform,codeaudit/OG-Platform,nssales/OG-Platform,McLeodMoores/starling,jerome79/OG-Platform,jeorme/OG-Platform,nssales/OG-Platform,McLeodMoores/starling,ChinaQuants/OG-Platform,DevStreet/FinanceAnalytics,McLeodMoores/starling,DevStreet/FinanceAnalytics | /**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.master.timeseries.impl;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import javax.time.calendar.LocalDate;
import javax.time.calendar.format.CalendricalParseException;
import org.apache.commons.lang.StringUtils;
import com.google.common.base.Supplier;
import com.opengamma.DataNotFoundException;
import com.opengamma.id.Identifier;
import com.opengamma.id.IdentifierBundle;
import com.opengamma.id.IdentifierBundleWithDates;
import com.opengamma.id.IdentifierWithDates;
import com.opengamma.id.UniqueIdentifier;
import com.opengamma.id.UniqueIdentifierSupplier;
import com.opengamma.master.timeseries.DataPointDocument;
import com.opengamma.master.timeseries.TimeSeriesDocument;
import com.opengamma.master.timeseries.TimeSeriesMaster;
import com.opengamma.master.timeseries.TimeSeriesSearchHistoricRequest;
import com.opengamma.master.timeseries.TimeSeriesSearchHistoricResult;
import com.opengamma.master.timeseries.TimeSeriesSearchRequest;
import com.opengamma.master.timeseries.TimeSeriesSearchResult;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.db.Paging;
import com.opengamma.util.time.DateUtil;
import com.opengamma.util.timeseries.DoubleTimeSeries;
import com.opengamma.util.timeseries.localdate.MapLocalDateDoubleTimeSeries;
import com.opengamma.util.tuple.Pair;
/**
* An in-memory implementation of a time-series master.
*/
public class InMemoryLocalDateTimeSeriesMaster implements TimeSeriesMaster<LocalDate> {
/**
* A cache of LocalDate time-series by identifier.
*/
private final ConcurrentHashMap<UniqueIdentifier, TimeSeriesDocument<LocalDate>> _timeseriesDb = new ConcurrentHashMap<UniqueIdentifier, TimeSeriesDocument<LocalDate>>();
/**
* The default scheme used for each {@link UniqueIdentifier}.
*/
public static final String DEFAULT_UID_SCHEME = "TssMemory";
/**
* The supplied of identifiers.
*/
private final Supplier<UniqueIdentifier> _uniqueIdSupplier;
/**
* Creates an empty time-series master using the default scheme for any {@link UniqueIdentifier}s created.
*/
public InMemoryLocalDateTimeSeriesMaster() {
this(new UniqueIdentifierSupplier(DEFAULT_UID_SCHEME));
}
/**
* Creates an instance specifying the supplier of unique identifiers.
*
* @param uniqueIdSupplier the supplier of unique identifiers, not null
*/
private InMemoryLocalDateTimeSeriesMaster(final Supplier<UniqueIdentifier> uniqueIdSupplier) {
ArgumentChecker.notNull(uniqueIdSupplier, "uniqueIdSupplier");
_uniqueIdSupplier = uniqueIdSupplier;
}
//-------------------------------------------------------------------------
@Override
public List<IdentifierBundleWithDates> getAllIdentifiers() {
List<IdentifierBundleWithDates> result = new ArrayList<IdentifierBundleWithDates>();
Collection<TimeSeriesDocument<LocalDate>> docs = _timeseriesDb.values();
for (TimeSeriesDocument<LocalDate> tsDoc : docs) {
result.add(tsDoc.getIdentifiers());
}
return result;
}
@Override
public TimeSeriesSearchResult<LocalDate> search(final TimeSeriesSearchRequest<LocalDate> request) {
ArgumentChecker.notNull(request, "request");
List<TimeSeriesDocument<LocalDate>> list = new ArrayList<TimeSeriesDocument<LocalDate>>();
for (TimeSeriesDocument<LocalDate> doc : _timeseriesDb.values()) {
if (request.matches(doc)) {
list.add(doc);
}
}
if (request.isLoadDates()) {
for (TimeSeriesDocument<LocalDate> tsDocument : list) {
assert tsDocument.getTimeSeries() != null;
tsDocument.setLatest(tsDocument.getTimeSeries().getLatestTime());
tsDocument.setEarliest(tsDocument.getTimeSeries().getEarliestTime());
}
}
if (!request.isLoadTimeSeries()) {
List<TimeSeriesDocument<LocalDate>> noSeries = new ArrayList<TimeSeriesDocument<LocalDate>>();
for (TimeSeriesDocument<LocalDate> tsDocument : list) {
TimeSeriesDocument<LocalDate> doc = new TimeSeriesDocument<LocalDate>();
doc.setDataField(tsDocument.getDataField());
doc.setDataProvider(tsDocument.getDataProvider());
doc.setDataSource(tsDocument.getDataSource());
doc.setEarliest(tsDocument.getEarliest());
doc.setIdentifiers(tsDocument.getIdentifiers());
doc.setLatest(tsDocument.getLatest());
doc.setObservationTime(tsDocument.getObservationTime());
doc.setUniqueId(tsDocument.getUniqueId());
noSeries.add(doc);
}
list = noSeries;
}
if (request.getStart() != null && request.getEnd() != null) {
List<TimeSeriesDocument<LocalDate>> subseriesList = new ArrayList<TimeSeriesDocument<LocalDate>>();
for (TimeSeriesDocument<LocalDate> tsDocument : list) {
TimeSeriesDocument<LocalDate> doc = new TimeSeriesDocument<LocalDate>();
doc.setDataField(tsDocument.getDataField());
doc.setDataProvider(tsDocument.getDataProvider());
doc.setDataSource(tsDocument.getDataSource());
doc.setEarliest(tsDocument.getEarliest());
doc.setIdentifiers(tsDocument.getIdentifiers());
doc.setLatest(tsDocument.getLatest());
doc.setObservationTime(tsDocument.getObservationTime());
doc.setUniqueId(tsDocument.getUniqueId());
DoubleTimeSeries<LocalDate> subseries = tsDocument.getTimeSeries().subSeries(request.getStart(), true, request.getEnd(), false);
doc.setTimeSeries(subseries);
subseriesList.add(doc);
}
list = subseriesList;
}
final TimeSeriesSearchResult<LocalDate> result = new TimeSeriesSearchResult<LocalDate>();
result.setPaging(Paging.of(request.getPagingRequest(), list));
result.getDocuments().addAll(request.getPagingRequest().select(list));
return result;
}
//-------------------------------------------------------------------------
@Override
public TimeSeriesDocument<LocalDate> get(UniqueIdentifier uniqueId) {
validateUid(uniqueId);
final TimeSeriesDocument<LocalDate> document = _timeseriesDb.get(uniqueId);
if (document == null) {
throw new DataNotFoundException("Time-series not found: " + uniqueId);
}
return document;
}
private void validateUid(UniqueIdentifier uniqueId) {
ArgumentChecker.notNull(uniqueId, "TimeSeries UID");
ArgumentChecker.isTrue(uniqueId.getScheme().equals(DEFAULT_UID_SCHEME), "UID not " + DEFAULT_UID_SCHEME);
ArgumentChecker.isTrue(uniqueId.getValue() != null, "Uid value cannot be null");
try {
Long.parseLong(uniqueId.getValue());
} catch (NumberFormatException ex) {
throw new IllegalArgumentException("Invalid UID " + uniqueId);
}
}
@Override
public TimeSeriesDocument<LocalDate> add(TimeSeriesDocument<LocalDate> document) {
validateTimeSeriesDocument(document);
if (!contains(document)) {
final UniqueIdentifier uniqueId = _uniqueIdSupplier.get();
final TimeSeriesDocument<LocalDate> doc = new TimeSeriesDocument<LocalDate>();
doc.setUniqueId(uniqueId);
doc.setDataField(document.getDataField());
doc.setDataProvider(document.getDataProvider());
doc.setDataSource(document.getDataSource());
doc.setIdentifiers(document.getIdentifiers());
doc.setObservationTime(document.getObservationTime());
doc.setTimeSeries(document.getTimeSeries());
_timeseriesDb.put(uniqueId, doc); // unique identifier should be unique
document.setUniqueId(uniqueId);
return document;
} else {
throw new IllegalArgumentException("cannot add duplicate TimeSeries for identifiers " + document.getIdentifiers());
}
}
private boolean contains(TimeSeriesDocument<LocalDate> document) {
for (IdentifierWithDates identifierWithDates : document.getIdentifiers()) {
Identifier identifier = identifierWithDates.asIdentifier();
UniqueIdentifier uniqueId = resolveIdentifier(
IdentifierBundle.of(identifier),
identifierWithDates.getValidFrom(),
document.getDataSource(),
document.getDataProvider(),
document.getDataField());
if (uniqueId != null) {
return true;
}
}
return false;
}
@Override
public TimeSeriesDocument<LocalDate> update(TimeSeriesDocument<LocalDate> document) {
ArgumentChecker.notNull(document.getUniqueId(), "document.uniqueId");
validateTimeSeriesDocument(document);
final UniqueIdentifier uniqueId = document.getUniqueId();
final TimeSeriesDocument<LocalDate> storedDocument = _timeseriesDb.get(uniqueId);
if (storedDocument == null) {
throw new DataNotFoundException("Time-series not found: " + uniqueId);
}
if (_timeseriesDb.replace(uniqueId, storedDocument, document) == false) {
throw new IllegalArgumentException("Concurrent modification");
}
return document;
}
@Override
public void remove(UniqueIdentifier uniqueId) {
ArgumentChecker.notNull(uniqueId, "uniqueId");
if (_timeseriesDb.remove(uniqueId) == null) {
throw new DataNotFoundException("Time-series not found: " + uniqueId);
}
}
@Override
public TimeSeriesSearchHistoricResult<LocalDate> searchHistoric(final TimeSeriesSearchHistoricRequest request) {
ArgumentChecker.notNull(request, "request");
ArgumentChecker.notNull(request.getTimeSeriesId(), "request.timeSeriesId");
final TimeSeriesSearchHistoricResult<LocalDate> result = new TimeSeriesSearchHistoricResult<LocalDate>();
TimeSeriesDocument<LocalDate> doc = get(request.getTimeSeriesId());
if (doc != null) {
result.getDocuments().add(doc);
}
result.setPaging(Paging.of(result.getDocuments()));
return result;
}
@Override
public DataPointDocument<LocalDate> updateDataPoint(DataPointDocument<LocalDate> document) {
ArgumentChecker.notNull(document, "dataPoint document");
ArgumentChecker.notNull(document.getDate(), "data point date");
ArgumentChecker.notNull(document.getValue(), "data point value");
UniqueIdentifier timeSeriesId = document.getTimeSeriesId();
validateUid(timeSeriesId);
TimeSeriesDocument<LocalDate> storeDoc = _timeseriesDb.get(timeSeriesId);
DoubleTimeSeries<LocalDate> timeSeries = storeDoc.getTimeSeries();
MapLocalDateDoubleTimeSeries mutableTS = new MapLocalDateDoubleTimeSeries(timeSeries);
mutableTS.putDataPoint(document.getDate(), document.getValue());
storeDoc.setTimeSeries(mutableTS);
return document;
}
@Override
public DataPointDocument<LocalDate> addDataPoint(DataPointDocument<LocalDate> document) {
ArgumentChecker.notNull(document, "dataPoint document");
ArgumentChecker.notNull(document.getDate(), "data point date");
ArgumentChecker.notNull(document.getValue(), "data point value");
UniqueIdentifier timeSeriesId = document.getTimeSeriesId();
validateUid(timeSeriesId);
TimeSeriesDocument<LocalDate> storedDoc = _timeseriesDb.get(timeSeriesId);
MapLocalDateDoubleTimeSeries mutableTS = new MapLocalDateDoubleTimeSeries();
mutableTS.putDataPoint(document.getDate(), document.getValue());
DoubleTimeSeries<LocalDate> mergedTS = storedDoc.getTimeSeries().noIntersectionOperation(mutableTS);
storedDoc.setTimeSeries(mergedTS);
String uniqueId = new StringBuilder(timeSeriesId.getValue()).append("/").append(DateUtil.printYYYYMMDD(document.getDate())).toString();
document.setDataPointId(UniqueIdentifier.of(DEFAULT_UID_SCHEME, uniqueId));
return document;
}
@Override
public DataPointDocument<LocalDate> getDataPoint(UniqueIdentifier uniqueId) {
Pair<Long, LocalDate> uniqueIdPair = validateAndGetDataPointId(uniqueId);
Long tsId = uniqueIdPair.getFirst();
LocalDate date = uniqueIdPair.getSecond();
final DataPointDocument<LocalDate> result = new DataPointDocument<LocalDate>();
result.setDate(uniqueIdPair.getSecond());
result.setTimeSeriesId(UniqueIdentifier.of(DEFAULT_UID_SCHEME, String.valueOf(tsId)));
result.setDataPointId(uniqueId);
TimeSeriesDocument<LocalDate> storedDoc = _timeseriesDb.get(UniqueIdentifier.of(DEFAULT_UID_SCHEME, String.valueOf(tsId)));
Double value = storedDoc.getTimeSeries().getValue(date);
result.setValue(value);
return result;
}
private Pair<Long, LocalDate> validateAndGetDataPointId(UniqueIdentifier uniqueId) {
ArgumentChecker.notNull(uniqueId, "DataPoint UID");
ArgumentChecker.isTrue(uniqueId.getScheme().equals(DEFAULT_UID_SCHEME), "UID not TssMemory");
ArgumentChecker.isTrue(uniqueId.getValue() != null, "Uid value cannot be null");
String[] tokens = StringUtils.split(uniqueId.getValue(), '/');
if (tokens.length != 2) {
throw new IllegalArgumentException("UID not expected format<12345/date> " + uniqueId);
}
String id = tokens[0];
String dateStr = tokens[1];
LocalDate date = null;
Long tsId = Long.MIN_VALUE;
if (id != null && dateStr != null) {
try {
date = DateUtil.toLocalDate(dateStr);
} catch (CalendricalParseException ex) {
throw new IllegalArgumentException("UID not expected format<12345/date> " + uniqueId, ex);
}
try {
tsId = Long.parseLong(id);
} catch (NumberFormatException ex) {
throw new IllegalArgumentException("UID not expected format<12345/date> " + uniqueId, ex);
}
} else {
throw new IllegalArgumentException("UID not expected format<12345/date> " + uniqueId);
}
return Pair.of(tsId, date);
}
@Override
public void removeDataPoint(UniqueIdentifier uniqueId) {
Pair<Long, LocalDate> uniqueIdPair = validateAndGetDataPointId(uniqueId);
Long tsId = uniqueIdPair.getFirst();
TimeSeriesDocument<LocalDate> storedDoc = _timeseriesDb.get(UniqueIdentifier.of(DEFAULT_UID_SCHEME, String.valueOf(tsId)));
MapLocalDateDoubleTimeSeries mutableTS = new MapLocalDateDoubleTimeSeries(storedDoc.getTimeSeries());
mutableTS.removeDataPoint(uniqueIdPair.getSecond());
storedDoc.setTimeSeries(mutableTS);
}
@Override
public void appendTimeSeries(TimeSeriesDocument<LocalDate> document) {
validateTimeSeriesDocument(document);
validateUid(document.getUniqueId());
UniqueIdentifier uniqueId = document.getUniqueId();
TimeSeriesDocument<LocalDate> storedDoc = _timeseriesDb.get(uniqueId);
DoubleTimeSeries<LocalDate> mergedTS = storedDoc.getTimeSeries().noIntersectionOperation(document.getTimeSeries());
storedDoc.setTimeSeries(mergedTS);
}
@Override
public UniqueIdentifier resolveIdentifier(IdentifierBundle securityBundle, String dataSource, String dataProvider, String dataField) {
return resolveIdentifier(securityBundle, (LocalDate) null, dataSource, dataProvider, dataField);
}
@Override
public UniqueIdentifier resolveIdentifier(IdentifierBundle securityKey, LocalDate currentDate, String dataSource, String dataProvider, String dataField) {
ArgumentChecker.notNull(securityKey, "securityBundle");
ArgumentChecker.notNull(dataSource, "dataSource");
ArgumentChecker.notNull(dataProvider, "dataProvider");
ArgumentChecker.notNull(dataField, "dataField");
for (Entry<UniqueIdentifier, TimeSeriesDocument<LocalDate>> entry : _timeseriesDb.entrySet()) {
UniqueIdentifier uniqueId = entry.getKey();
TimeSeriesDocument<LocalDate> tsDoc = entry.getValue();
if (tsDoc.getDataSource().equals(dataSource) && tsDoc.getDataProvider().equals(dataProvider) && tsDoc.getDataField().equals(dataField)) {
for (IdentifierWithDates idWithDates : tsDoc.getIdentifiers()) {
if (securityKey.contains(idWithDates.asIdentifier())) {
LocalDate validFrom = idWithDates.getValidFrom();
LocalDate validTo = idWithDates.getValidTo();
if (currentDate != null) {
if (currentDate.equals(validFrom) || (currentDate.isAfter(validFrom) && currentDate.isBefore(validTo)) || currentDate.equals(validTo)) {
return uniqueId;
}
} else {
return uniqueId;
}
}
}
}
}
return null;
}
@Override
public void removeDataPoints(UniqueIdentifier timeSeriesUid, LocalDate firstDateToRetain) {
validateUid(timeSeriesUid);
TimeSeriesDocument<LocalDate> storedDoc = _timeseriesDb.get(timeSeriesUid);
DoubleTimeSeries<LocalDate> timeSeries = storedDoc.getTimeSeries();
DoubleTimeSeries<LocalDate> subSeries = timeSeries.subSeries(firstDateToRetain, true, timeSeries.getLatestTime(), false);
storedDoc.setTimeSeries(subSeries);
}
//-------------------------------------------------------------------------
private void validateTimeSeriesDocument(TimeSeriesDocument<LocalDate> document) {
ArgumentChecker.notNull(document, "document");
ArgumentChecker.notNull(document.getTimeSeries(), "document.timeSeries");
ArgumentChecker.notNull(document.getIdentifiers(), "document.identifiers");
ArgumentChecker.isTrue(document.getIdentifiers().asIdentifierBundle().getIdentifiers().size() > 0, "document.identifiers must not be empty");
ArgumentChecker.isTrue(StringUtils.isNotBlank(document.getDataSource()), "document.dataSource must not be blank");
ArgumentChecker.isTrue(StringUtils.isNotBlank(document.getDataProvider()), "document.dataProvider must not be blank");
ArgumentChecker.isTrue(StringUtils.isNotBlank(document.getDataField()), "document.dataField must not be blank");
ArgumentChecker.isTrue(StringUtils.isNotBlank(document.getObservationTime()), "document.observationTime must not be blank");
}
}
| projects/OG-Master/src/com/opengamma/master/timeseries/impl/InMemoryLocalDateTimeSeriesMaster.java | /**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.master.timeseries.impl;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import javax.time.calendar.LocalDate;
import javax.time.calendar.format.CalendricalParseException;
import org.apache.commons.lang.StringUtils;
import com.google.common.base.Supplier;
import com.opengamma.DataNotFoundException;
import com.opengamma.id.Identifier;
import com.opengamma.id.IdentifierBundle;
import com.opengamma.id.IdentifierBundleWithDates;
import com.opengamma.id.IdentifierWithDates;
import com.opengamma.id.UniqueIdentifier;
import com.opengamma.id.UniqueIdentifierSupplier;
import com.opengamma.master.timeseries.DataPointDocument;
import com.opengamma.master.timeseries.TimeSeriesDocument;
import com.opengamma.master.timeseries.TimeSeriesMaster;
import com.opengamma.master.timeseries.TimeSeriesSearchHistoricRequest;
import com.opengamma.master.timeseries.TimeSeriesSearchHistoricResult;
import com.opengamma.master.timeseries.TimeSeriesSearchRequest;
import com.opengamma.master.timeseries.TimeSeriesSearchResult;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.db.Paging;
import com.opengamma.util.time.DateUtil;
import com.opengamma.util.timeseries.DoubleTimeSeries;
import com.opengamma.util.timeseries.localdate.MapLocalDateDoubleTimeSeries;
import com.opengamma.util.tuple.Pair;
/**
* An in-memory implementation of a time-series master.
*/
public class InMemoryLocalDateTimeSeriesMaster implements TimeSeriesMaster<LocalDate> {
/**
* A cache of LocalDate time-series by identifier.
*/
private final ConcurrentHashMap<UniqueIdentifier, TimeSeriesDocument<LocalDate>> _timeseriesDb = new ConcurrentHashMap<UniqueIdentifier, TimeSeriesDocument<LocalDate>>();
/**
* The default scheme used for each {@link UniqueIdentifier}.
*/
public static final String DEFAULT_UID_SCHEME = "TssMemory";
/**
* The supplied of identifiers.
*/
private final Supplier<UniqueIdentifier> _uniqueIdSupplier;
/**
* Creates an empty time-series master using the default scheme for any {@link UniqueIdentifier}s created.
*/
public InMemoryLocalDateTimeSeriesMaster() {
this(new UniqueIdentifierSupplier(DEFAULT_UID_SCHEME));
}
/**
* Creates an instance specifying the supplier of unique identifiers.
*
* @param uniqueIdSupplier the supplier of unique identifiers, not null
*/
private InMemoryLocalDateTimeSeriesMaster(final Supplier<UniqueIdentifier> uniqueIdSupplier) {
ArgumentChecker.notNull(uniqueIdSupplier, "uniqueIdSupplier");
_uniqueIdSupplier = uniqueIdSupplier;
}
//-------------------------------------------------------------------------
@Override
public List<IdentifierBundleWithDates> getAllIdentifiers() {
List<IdentifierBundleWithDates> result = new ArrayList<IdentifierBundleWithDates>();
Collection<TimeSeriesDocument<LocalDate>> docs = _timeseriesDb.values();
for (TimeSeriesDocument<LocalDate> tsDoc : docs) {
result.add(tsDoc.getIdentifiers());
}
return result;
}
@Override
public TimeSeriesSearchResult<LocalDate> search(final TimeSeriesSearchRequest<LocalDate> request) {
ArgumentChecker.notNull(request, "request");
List<TimeSeriesDocument<LocalDate>> list = new ArrayList<TimeSeriesDocument<LocalDate>>();
for (TimeSeriesDocument<LocalDate> doc : _timeseriesDb.values()) {
if (request.matches(doc)) {
list.add(doc);
}
}
if (request.isLoadDates()) {
for (TimeSeriesDocument<LocalDate> tsDocument : list) {
assert tsDocument.getTimeSeries() != null;
tsDocument.setLatest(tsDocument.getTimeSeries().getLatestTime());
tsDocument.setEarliest(tsDocument.getTimeSeries().getEarliestTime());
}
}
if (!request.isLoadTimeSeries()) {
List<TimeSeriesDocument<LocalDate>> noSeries = new ArrayList<TimeSeriesDocument<LocalDate>>();
for (TimeSeriesDocument<LocalDate> tsDocument : list) {
TimeSeriesDocument<LocalDate> doc = new TimeSeriesDocument<LocalDate>();
doc.setDataField(tsDocument.getDataField());
doc.setDataProvider(tsDocument.getDataProvider());
doc.setDataSource(tsDocument.getDataSource());
doc.setEarliest(tsDocument.getEarliest());
doc.setIdentifiers(tsDocument.getIdentifiers());
doc.setLatest(tsDocument.getLatest());
doc.setObservationTime(tsDocument.getObservationTime());
doc.setUniqueId(tsDocument.getUniqueId());
noSeries.add(doc);
}
list = noSeries;
}
if (request.getStart() != null && request.getEnd() != null) {
List<TimeSeriesDocument<LocalDate>> subseriesList = new ArrayList<TimeSeriesDocument<LocalDate>>();
for (TimeSeriesDocument<LocalDate> tsDocument : list) {
TimeSeriesDocument<LocalDate> doc = new TimeSeriesDocument<LocalDate>();
doc.setDataField(tsDocument.getDataField());
doc.setDataProvider(tsDocument.getDataProvider());
doc.setDataSource(tsDocument.getDataSource());
doc.setEarliest(tsDocument.getEarliest());
doc.setIdentifiers(tsDocument.getIdentifiers());
doc.setLatest(tsDocument.getLatest());
doc.setObservationTime(tsDocument.getObservationTime());
doc.setUniqueId(tsDocument.getUniqueId());
DoubleTimeSeries<LocalDate> subseries = tsDocument.getTimeSeries().subSeries(request.getStart(), true, request.getEnd(), false);
doc.setTimeSeries(subseries);
subseriesList.add(doc);
}
list = subseriesList;
}
final TimeSeriesSearchResult<LocalDate> result = new TimeSeriesSearchResult<LocalDate>();
result.setPaging(Paging.of(request.getPagingRequest(), list));
result.getDocuments().addAll(request.getPagingRequest().select(list));
return result;
}
//-------------------------------------------------------------------------
@Override
public TimeSeriesDocument<LocalDate> get(UniqueIdentifier uniqueId) {
validateUId(uniqueId);
final TimeSeriesDocument<LocalDate> document = _timeseriesDb.get(uniqueId);
if (document == null) {
throw new DataNotFoundException("Timeseries not found: " + uniqueId);
}
return document;
}
private void validateUId(UniqueIdentifier uniqueId) {
ArgumentChecker.notNull(uniqueId, "TimeSeries UID");
ArgumentChecker.isTrue(uniqueId.getScheme().equals(DEFAULT_UID_SCHEME), "UID not " + DEFAULT_UID_SCHEME);
ArgumentChecker.isTrue(uniqueId.getValue() != null, "Uid value cannot be null");
try {
Long.parseLong(uniqueId.getValue());
} catch (NumberFormatException ex) {
throw new IllegalArgumentException("Invalid UID " + uniqueId);
}
}
@Override
public TimeSeriesDocument<LocalDate> add(TimeSeriesDocument<LocalDate> document) {
validateTimeSeriesDocument(document);
if (!contains(document)) {
final UniqueIdentifier uniqueId = _uniqueIdSupplier.get();
final TimeSeriesDocument<LocalDate> doc = new TimeSeriesDocument<LocalDate>();
doc.setUniqueId(uniqueId);
doc.setDataField(document.getDataField());
doc.setDataProvider(document.getDataProvider());
doc.setDataSource(document.getDataSource());
doc.setIdentifiers(document.getIdentifiers());
doc.setObservationTime(document.getObservationTime());
doc.setTimeSeries(document.getTimeSeries());
_timeseriesDb.put(uniqueId, doc); // unique identifier should be unique
document.setUniqueId(uniqueId);
return document;
} else {
throw new IllegalArgumentException("cannot add duplicate TimeSeries for identifiers " + document.getIdentifiers());
}
}
private void validateTimeSeriesDocument(TimeSeriesDocument<LocalDate> document) {
ArgumentChecker.notNull(document, "timeseries document");
ArgumentChecker.notNull(document.getTimeSeries(), "Timeseries");
ArgumentChecker.notNull(document.getIdentifiers(), "identifiers");
ArgumentChecker.isTrue(!document.getIdentifiers().asIdentifierBundle().getIdentifiers().isEmpty(), "cannot add timeseries with empty identifiers");
ArgumentChecker.isTrue(!StringUtils.isBlank(document.getDataSource()), "cannot add timeseries with blank dataSource");
ArgumentChecker.isTrue(!StringUtils.isBlank(document.getDataProvider()), "cannot add timeseries with blank dataProvider");
ArgumentChecker.isTrue(!StringUtils.isBlank(document.getDataProvider()), "cannot add timeseries with blank dataProvider");
ArgumentChecker.isTrue(!StringUtils.isBlank(document.getDataField()), "cannot add timeseries with blank field");
ArgumentChecker.isTrue(!StringUtils.isBlank(document.getObservationTime()), "cannot add timeseries with blank observationTime");
ArgumentChecker.isTrue(!StringUtils.isBlank(document.getDataProvider()), "cannot add timeseries with blank dataProvider");
}
private boolean contains(TimeSeriesDocument<LocalDate> document) {
for (IdentifierWithDates identifierWithDates : document.getIdentifiers()) {
Identifier identifier = identifierWithDates.asIdentifier();
UniqueIdentifier uniqueId = resolveIdentifier(
IdentifierBundle.of(identifier),
identifierWithDates.getValidFrom(),
document.getDataSource(),
document.getDataProvider(),
document.getDataField());
if (uniqueId != null) {
return true;
}
}
return false;
}
@Override
public TimeSeriesDocument<LocalDate> update(TimeSeriesDocument<LocalDate> document) {
ArgumentChecker.notNull(document, "document");
ArgumentChecker.notNull(document.getTimeSeries(), "document.timeseries");
ArgumentChecker.notNull(document.getDataField(), "document.dataField");
ArgumentChecker.notNull(document.getDataProvider(), "document.dataProvider");
ArgumentChecker.notNull(document.getDataSource(), "document.dataSource");
ArgumentChecker.notNull(document.getObservationTime(), "document.observationTime");
ArgumentChecker.notNull(document.getUniqueId(), "document.uniqueId");
final UniqueIdentifier uniqueId = document.getUniqueId();
final TimeSeriesDocument<LocalDate> storedDocument = _timeseriesDb.get(uniqueId);
if (storedDocument == null) {
throw new DataNotFoundException("Timeseries not found: " + uniqueId);
}
if (_timeseriesDb.replace(uniqueId, storedDocument, document) == false) {
throw new IllegalArgumentException("Concurrent modification");
}
return document;
}
@Override
public void remove(UniqueIdentifier uniqueId) {
ArgumentChecker.notNull(uniqueId, "uniqueId");
if (_timeseriesDb.remove(uniqueId) == null) {
throw new DataNotFoundException("Timeseries not found: " + uniqueId);
}
}
@Override
public TimeSeriesSearchHistoricResult<LocalDate> searchHistoric(final TimeSeriesSearchHistoricRequest request) {
ArgumentChecker.notNull(request, "request");
ArgumentChecker.notNull(request.getTimeSeriesId(), "request.timeseriesId");
final TimeSeriesSearchHistoricResult<LocalDate> result = new TimeSeriesSearchHistoricResult<LocalDate>();
TimeSeriesDocument<LocalDate> doc = get(request.getTimeSeriesId());
if (doc != null) {
result.getDocuments().add(doc);
}
result.setPaging(Paging.of(result.getDocuments()));
return result;
}
@Override
public DataPointDocument<LocalDate> updateDataPoint(DataPointDocument<LocalDate> document) {
ArgumentChecker.notNull(document, "dataPoint document");
ArgumentChecker.notNull(document.getDate(), "data point date");
ArgumentChecker.notNull(document.getValue(), "data point value");
UniqueIdentifier timeSeriesId = document.getTimeSeriesId();
validateUId(timeSeriesId);
TimeSeriesDocument<LocalDate> storeDoc = _timeseriesDb.get(timeSeriesId);
DoubleTimeSeries<LocalDate> timeSeries = storeDoc.getTimeSeries();
MapLocalDateDoubleTimeSeries mutableTS = new MapLocalDateDoubleTimeSeries(timeSeries);
mutableTS.putDataPoint(document.getDate(), document.getValue());
storeDoc.setTimeSeries(mutableTS);
return document;
}
@Override
public DataPointDocument<LocalDate> addDataPoint(DataPointDocument<LocalDate> document) {
ArgumentChecker.notNull(document, "dataPoint document");
ArgumentChecker.notNull(document.getDate(), "data point date");
ArgumentChecker.notNull(document.getValue(), "data point value");
UniqueIdentifier timeSeriesId = document.getTimeSeriesId();
validateUId(timeSeriesId);
TimeSeriesDocument<LocalDate> storedDoc = _timeseriesDb.get(timeSeriesId);
MapLocalDateDoubleTimeSeries mutableTS = new MapLocalDateDoubleTimeSeries();
mutableTS.putDataPoint(document.getDate(), document.getValue());
DoubleTimeSeries<LocalDate> mergedTS = storedDoc.getTimeSeries().noIntersectionOperation(mutableTS);
storedDoc.setTimeSeries(mergedTS);
String uniqueId = new StringBuilder(timeSeriesId.getValue()).append("/").append(DateUtil.printYYYYMMDD(document.getDate())).toString();
document.setDataPointId(UniqueIdentifier.of(DEFAULT_UID_SCHEME, uniqueId));
return document;
}
@Override
public DataPointDocument<LocalDate> getDataPoint(UniqueIdentifier uniqueId) {
Pair<Long, LocalDate> uniqueIdPair = validateAndGetDataPointId(uniqueId);
Long tsId = uniqueIdPair.getFirst();
LocalDate date = uniqueIdPair.getSecond();
final DataPointDocument<LocalDate> result = new DataPointDocument<LocalDate>();
result.setDate(uniqueIdPair.getSecond());
result.setTimeSeriesId(UniqueIdentifier.of(DEFAULT_UID_SCHEME, String.valueOf(tsId)));
result.setDataPointId(uniqueId);
TimeSeriesDocument<LocalDate> storedDoc = _timeseriesDb.get(UniqueIdentifier.of(DEFAULT_UID_SCHEME, String.valueOf(tsId)));
Double value = storedDoc.getTimeSeries().getValue(date);
result.setValue(value);
return result;
}
private Pair<Long, LocalDate> validateAndGetDataPointId(UniqueIdentifier uniqueId) {
ArgumentChecker.notNull(uniqueId, "DataPoint UID");
ArgumentChecker.isTrue(uniqueId.getScheme().equals(DEFAULT_UID_SCHEME), "UID not TssMemory");
ArgumentChecker.isTrue(uniqueId.getValue() != null, "Uid value cannot be null");
String[] tokens = StringUtils.split(uniqueId.getValue(), '/');
if (tokens.length != 2) {
throw new IllegalArgumentException("UID not expected format<12345/date> " + uniqueId);
}
String id = tokens[0];
String dateStr = tokens[1];
LocalDate date = null;
Long tsId = Long.MIN_VALUE;
if (id != null && dateStr != null) {
try {
date = DateUtil.toLocalDate(dateStr);
} catch (CalendricalParseException ex) {
throw new IllegalArgumentException("UID not expected format<12345/date> " + uniqueId, ex);
}
try {
tsId = Long.parseLong(id);
} catch (NumberFormatException ex) {
throw new IllegalArgumentException("UID not expected format<12345/date> " + uniqueId, ex);
}
} else {
throw new IllegalArgumentException("UID not expected format<12345/date> " + uniqueId);
}
return Pair.of(tsId, date);
}
@Override
public void removeDataPoint(UniqueIdentifier uniqueId) {
Pair<Long, LocalDate> uniqueIdPair = validateAndGetDataPointId(uniqueId);
Long tsId = uniqueIdPair.getFirst();
TimeSeriesDocument<LocalDate> storedDoc = _timeseriesDb.get(UniqueIdentifier.of(DEFAULT_UID_SCHEME, String.valueOf(tsId)));
MapLocalDateDoubleTimeSeries mutableTS = new MapLocalDateDoubleTimeSeries(storedDoc.getTimeSeries());
mutableTS.removeDataPoint(uniqueIdPair.getSecond());
storedDoc.setTimeSeries(mutableTS);
}
@Override
public void appendTimeSeries(TimeSeriesDocument<LocalDate> document) {
ArgumentChecker.notNull(document, "document");
ArgumentChecker.notNull(document.getIdentifiers(), "identifiers");
ArgumentChecker.notNull(document.getDataSource(), "dataSource");
ArgumentChecker.notNull(document.getDataProvider(), "dataProvider");
ArgumentChecker.notNull(document.getDataField(), "dataField");
validateUId(document.getUniqueId());
UniqueIdentifier uniqueId = document.getUniqueId();
TimeSeriesDocument<LocalDate> storedDoc = _timeseriesDb.get(uniqueId);
DoubleTimeSeries<LocalDate> mergedTS = storedDoc.getTimeSeries().noIntersectionOperation(document.getTimeSeries());
storedDoc.setTimeSeries(mergedTS);
}
@Override
public UniqueIdentifier resolveIdentifier(IdentifierBundle securityBundle, String dataSource, String dataProvider, String dataField) {
return resolveIdentifier(securityBundle, (LocalDate) null, dataSource, dataProvider, dataField);
}
@Override
public UniqueIdentifier resolveIdentifier(IdentifierBundle securityBundle, LocalDate currentDate, String dataSource, String dataProvider, String dataField) {
ArgumentChecker.notNull(securityBundle, "securityBundle");
ArgumentChecker.notNull(dataSource, "dataSource");
ArgumentChecker.notNull(dataProvider, "dataProvider");
ArgumentChecker.notNull(dataField, "dataField");
for (Entry<UniqueIdentifier, TimeSeriesDocument<LocalDate>> entry : _timeseriesDb.entrySet()) {
UniqueIdentifier uniqueId = entry.getKey();
TimeSeriesDocument<LocalDate> tsDoc = entry.getValue();
if (tsDoc.getDataSource().equals(dataSource) && tsDoc.getDataProvider().equals(dataProvider) && tsDoc.getDataField().equals(dataField)) {
for (IdentifierWithDates idWithDates : tsDoc.getIdentifiers()) {
if (securityBundle.contains(idWithDates.asIdentifier())) {
LocalDate validFrom = idWithDates.getValidFrom();
LocalDate validTo = idWithDates.getValidTo();
if (currentDate != null) {
if (currentDate.equals(validFrom) || (currentDate.isAfter(validFrom) && currentDate.isBefore(validTo)) || currentDate.equals(validTo)) {
return uniqueId;
}
} else {
return uniqueId;
}
}
}
}
}
return null;
}
@Override
public void removeDataPoints(UniqueIdentifier timeSeriesUid, LocalDate firstDateToRetain) {
validateUId(timeSeriesUid);
TimeSeriesDocument<LocalDate> storedDoc = _timeseriesDb.get(timeSeriesUid);
DoubleTimeSeries<LocalDate> timeSeries = storedDoc.getTimeSeries();
DoubleTimeSeries<LocalDate> subSeries = timeSeries.subSeries(firstDateToRetain, true, timeSeries.getLatestTime(), false);
storedDoc.setTimeSeries(subSeries);
}
}
| [PLAT-1296] Refactor time-series master; Better validation
Enhance validation within in-memory master
| projects/OG-Master/src/com/opengamma/master/timeseries/impl/InMemoryLocalDateTimeSeriesMaster.java | [PLAT-1296] Refactor time-series master; Better validation | <ide><path>rojects/OG-Master/src/com/opengamma/master/timeseries/impl/InMemoryLocalDateTimeSeriesMaster.java
<ide> //-------------------------------------------------------------------------
<ide> @Override
<ide> public TimeSeriesDocument<LocalDate> get(UniqueIdentifier uniqueId) {
<del> validateUId(uniqueId);
<add> validateUid(uniqueId);
<ide> final TimeSeriesDocument<LocalDate> document = _timeseriesDb.get(uniqueId);
<ide> if (document == null) {
<del> throw new DataNotFoundException("Timeseries not found: " + uniqueId);
<add> throw new DataNotFoundException("Time-series not found: " + uniqueId);
<ide> }
<ide> return document;
<ide> }
<ide>
<del> private void validateUId(UniqueIdentifier uniqueId) {
<add> private void validateUid(UniqueIdentifier uniqueId) {
<ide> ArgumentChecker.notNull(uniqueId, "TimeSeries UID");
<ide> ArgumentChecker.isTrue(uniqueId.getScheme().equals(DEFAULT_UID_SCHEME), "UID not " + DEFAULT_UID_SCHEME);
<ide> ArgumentChecker.isTrue(uniqueId.getValue() != null, "Uid value cannot be null");
<ide> throw new IllegalArgumentException("cannot add duplicate TimeSeries for identifiers " + document.getIdentifiers());
<ide> }
<ide> }
<del>
<del> private void validateTimeSeriesDocument(TimeSeriesDocument<LocalDate> document) {
<del> ArgumentChecker.notNull(document, "timeseries document");
<del> ArgumentChecker.notNull(document.getTimeSeries(), "Timeseries");
<del> ArgumentChecker.notNull(document.getIdentifiers(), "identifiers");
<del> ArgumentChecker.isTrue(!document.getIdentifiers().asIdentifierBundle().getIdentifiers().isEmpty(), "cannot add timeseries with empty identifiers");
<del> ArgumentChecker.isTrue(!StringUtils.isBlank(document.getDataSource()), "cannot add timeseries with blank dataSource");
<del> ArgumentChecker.isTrue(!StringUtils.isBlank(document.getDataProvider()), "cannot add timeseries with blank dataProvider");
<del> ArgumentChecker.isTrue(!StringUtils.isBlank(document.getDataProvider()), "cannot add timeseries with blank dataProvider");
<del> ArgumentChecker.isTrue(!StringUtils.isBlank(document.getDataField()), "cannot add timeseries with blank field");
<del> ArgumentChecker.isTrue(!StringUtils.isBlank(document.getObservationTime()), "cannot add timeseries with blank observationTime");
<del> ArgumentChecker.isTrue(!StringUtils.isBlank(document.getDataProvider()), "cannot add timeseries with blank dataProvider");
<del> }
<del>
<add>
<ide> private boolean contains(TimeSeriesDocument<LocalDate> document) {
<ide> for (IdentifierWithDates identifierWithDates : document.getIdentifiers()) {
<ide> Identifier identifier = identifierWithDates.asIdentifier();
<ide>
<ide> @Override
<ide> public TimeSeriesDocument<LocalDate> update(TimeSeriesDocument<LocalDate> document) {
<del> ArgumentChecker.notNull(document, "document");
<del> ArgumentChecker.notNull(document.getTimeSeries(), "document.timeseries");
<del> ArgumentChecker.notNull(document.getDataField(), "document.dataField");
<del> ArgumentChecker.notNull(document.getDataProvider(), "document.dataProvider");
<del> ArgumentChecker.notNull(document.getDataSource(), "document.dataSource");
<del> ArgumentChecker.notNull(document.getObservationTime(), "document.observationTime");
<ide> ArgumentChecker.notNull(document.getUniqueId(), "document.uniqueId");
<add> validateTimeSeriesDocument(document);
<ide>
<ide> final UniqueIdentifier uniqueId = document.getUniqueId();
<ide> final TimeSeriesDocument<LocalDate> storedDocument = _timeseriesDb.get(uniqueId);
<ide> if (storedDocument == null) {
<del> throw new DataNotFoundException("Timeseries not found: " + uniqueId);
<add> throw new DataNotFoundException("Time-series not found: " + uniqueId);
<ide> }
<ide> if (_timeseriesDb.replace(uniqueId, storedDocument, document) == false) {
<ide> throw new IllegalArgumentException("Concurrent modification");
<ide> public void remove(UniqueIdentifier uniqueId) {
<ide> ArgumentChecker.notNull(uniqueId, "uniqueId");
<ide> if (_timeseriesDb.remove(uniqueId) == null) {
<del> throw new DataNotFoundException("Timeseries not found: " + uniqueId);
<add> throw new DataNotFoundException("Time-series not found: " + uniqueId);
<ide> }
<ide> }
<ide>
<ide> @Override
<ide> public TimeSeriesSearchHistoricResult<LocalDate> searchHistoric(final TimeSeriesSearchHistoricRequest request) {
<ide> ArgumentChecker.notNull(request, "request");
<del> ArgumentChecker.notNull(request.getTimeSeriesId(), "request.timeseriesId");
<add> ArgumentChecker.notNull(request.getTimeSeriesId(), "request.timeSeriesId");
<ide>
<ide> final TimeSeriesSearchHistoricResult<LocalDate> result = new TimeSeriesSearchHistoricResult<LocalDate>();
<ide> TimeSeriesDocument<LocalDate> doc = get(request.getTimeSeriesId());
<ide> ArgumentChecker.notNull(document.getValue(), "data point value");
<ide>
<ide> UniqueIdentifier timeSeriesId = document.getTimeSeriesId();
<del> validateUId(timeSeriesId);
<add> validateUid(timeSeriesId);
<ide>
<ide> TimeSeriesDocument<LocalDate> storeDoc = _timeseriesDb.get(timeSeriesId);
<ide> DoubleTimeSeries<LocalDate> timeSeries = storeDoc.getTimeSeries();
<ide> ArgumentChecker.notNull(document.getDate(), "data point date");
<ide> ArgumentChecker.notNull(document.getValue(), "data point value");
<ide> UniqueIdentifier timeSeriesId = document.getTimeSeriesId();
<del> validateUId(timeSeriesId);
<add> validateUid(timeSeriesId);
<ide>
<ide> TimeSeriesDocument<LocalDate> storedDoc = _timeseriesDb.get(timeSeriesId);
<ide> MapLocalDateDoubleTimeSeries mutableTS = new MapLocalDateDoubleTimeSeries();
<ide>
<ide> @Override
<ide> public void appendTimeSeries(TimeSeriesDocument<LocalDate> document) {
<del> ArgumentChecker.notNull(document, "document");
<del> ArgumentChecker.notNull(document.getIdentifiers(), "identifiers");
<del> ArgumentChecker.notNull(document.getDataSource(), "dataSource");
<del> ArgumentChecker.notNull(document.getDataProvider(), "dataProvider");
<del> ArgumentChecker.notNull(document.getDataField(), "dataField");
<del>
<del> validateUId(document.getUniqueId());
<add> validateTimeSeriesDocument(document);
<add>
<add> validateUid(document.getUniqueId());
<ide> UniqueIdentifier uniqueId = document.getUniqueId();
<ide> TimeSeriesDocument<LocalDate> storedDoc = _timeseriesDb.get(uniqueId);
<ide> DoubleTimeSeries<LocalDate> mergedTS = storedDoc.getTimeSeries().noIntersectionOperation(document.getTimeSeries());
<ide> }
<ide>
<ide> @Override
<del> public UniqueIdentifier resolveIdentifier(IdentifierBundle securityBundle, LocalDate currentDate, String dataSource, String dataProvider, String dataField) {
<del> ArgumentChecker.notNull(securityBundle, "securityBundle");
<add> public UniqueIdentifier resolveIdentifier(IdentifierBundle securityKey, LocalDate currentDate, String dataSource, String dataProvider, String dataField) {
<add> ArgumentChecker.notNull(securityKey, "securityBundle");
<ide> ArgumentChecker.notNull(dataSource, "dataSource");
<ide> ArgumentChecker.notNull(dataProvider, "dataProvider");
<ide> ArgumentChecker.notNull(dataField, "dataField");
<ide> TimeSeriesDocument<LocalDate> tsDoc = entry.getValue();
<ide> if (tsDoc.getDataSource().equals(dataSource) && tsDoc.getDataProvider().equals(dataProvider) && tsDoc.getDataField().equals(dataField)) {
<ide> for (IdentifierWithDates idWithDates : tsDoc.getIdentifiers()) {
<del> if (securityBundle.contains(idWithDates.asIdentifier())) {
<add> if (securityKey.contains(idWithDates.asIdentifier())) {
<ide> LocalDate validFrom = idWithDates.getValidFrom();
<ide> LocalDate validTo = idWithDates.getValidTo();
<ide> if (currentDate != null) {
<ide>
<ide> @Override
<ide> public void removeDataPoints(UniqueIdentifier timeSeriesUid, LocalDate firstDateToRetain) {
<del> validateUId(timeSeriesUid);
<add> validateUid(timeSeriesUid);
<ide> TimeSeriesDocument<LocalDate> storedDoc = _timeseriesDb.get(timeSeriesUid);
<ide> DoubleTimeSeries<LocalDate> timeSeries = storedDoc.getTimeSeries();
<ide> DoubleTimeSeries<LocalDate> subSeries = timeSeries.subSeries(firstDateToRetain, true, timeSeries.getLatestTime(), false);
<ide> storedDoc.setTimeSeries(subSeries);
<ide> }
<ide>
<add> //-------------------------------------------------------------------------
<add> private void validateTimeSeriesDocument(TimeSeriesDocument<LocalDate> document) {
<add> ArgumentChecker.notNull(document, "document");
<add> ArgumentChecker.notNull(document.getTimeSeries(), "document.timeSeries");
<add> ArgumentChecker.notNull(document.getIdentifiers(), "document.identifiers");
<add> ArgumentChecker.isTrue(document.getIdentifiers().asIdentifierBundle().getIdentifiers().size() > 0, "document.identifiers must not be empty");
<add> ArgumentChecker.isTrue(StringUtils.isNotBlank(document.getDataSource()), "document.dataSource must not be blank");
<add> ArgumentChecker.isTrue(StringUtils.isNotBlank(document.getDataProvider()), "document.dataProvider must not be blank");
<add> ArgumentChecker.isTrue(StringUtils.isNotBlank(document.getDataField()), "document.dataField must not be blank");
<add> ArgumentChecker.isTrue(StringUtils.isNotBlank(document.getObservationTime()), "document.observationTime must not be blank");
<add> }
<add>
<ide> } |
|
Java | apache-2.0 | b277ec96fa3cf1b70a582f6baac295933bfd204d | 0 | kryptnostic/kodex | package com.kryptnostic.v2.storage.api;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import com.kryptnostic.kodex.v1.crypto.ciphers.BlockCiphertext;
import com.kryptnostic.v2.constants.Names;
import com.kryptnostic.v2.storage.models.CreateMetadataObjectRequest;
import com.kryptnostic.v2.storage.models.CreateObjectRequest;
import com.kryptnostic.v2.storage.models.ObjectMetadata;
import com.kryptnostic.v2.storage.models.ObjectMetadataEncryptedNode;
import com.kryptnostic.v2.storage.models.ObjectTreeLoadRequest;
import com.kryptnostic.v2.storage.models.PaddedMetadataObjectIds;
import com.kryptnostic.v2.storage.models.VersionedObjectKey;
import retrofit.client.Response;
import retrofit.http.Body;
import retrofit.http.DELETE;
import retrofit.http.GET;
import retrofit.http.POST;
import retrofit.http.PUT;
import retrofit.http.Path;
/**
* @author Matthew Tamayo-Rios <[email protected]>
*
*/
public interface ObjectStorageApi {
String CONTROLLER = "/object";
// Parameter names
String ID = Names.ID_FIELD;
String VERSION = "version";
String CONTENT = "content";
String BLOCK = "block";
String USER = "user";
// Paths
String OBJECT_ID_PATH = "/id/{" + ID + "}";
String VERSION_PATH = "/{" + VERSION + "}";
String BLOCK_PATH = "/{" + BLOCK + "}";
String USER_ID_PATH = "/{" + ID + "}";
String CONTENTS_PATH = "/" + Names.CONTENTS;
String IV_PATH = "/iv";
String SALT_PATH = "/salt";
String TAG_PATH = "/tag";
String LEVELS_PATH = "/levels";
String OBJECT_APPEND_PATH = "/append";
String OBJECT_METADATA_PATH = "/metadata";
String BULK_PATH = "/bulk";
/**
* Request a new object be created in a pending state
*
* @return The ID of the newly created object
*/
@POST( CONTROLLER )
VersionedObjectKey createObject( @Body CreateObjectRequest request );
@GET( CONTROLLER + OBJECT_ID_PATH )
VersionedObjectKey getVersionedObjectKey( @Path( ID ) UUID id );
/**
* Lazy Person API for writing base64 encoded block ciphertexts in bulk.
*
* @param objectIds
* @return
*/
@POST( CONTROLLER + BULK_PATH )
Map<UUID, BlockCiphertext> getObjects( @Body Set<UUID> objectIds );
/**
* Lazy Person API for writing base64 encoded block ciphertexts. Objects written via this API will be available
* through the more efficient byte level APIs.
*
* @param objectId
* @param ciphertext
* @return
*/
@PUT( CONTROLLER + OBJECT_ID_PATH + VERSION_PATH )
Response setObjectFromBlockCiphertext(
@Path( ID ) UUID objectId,
@Path( VERSION ) long version,
@Body BlockCiphertext ciphertext );
/**
* Cached Lazy Person API for reading base64 encoded block ciphertexts. Objects readable by this API will be
* available through the more efficient byte level APIs.
*
* @param objectId
* @param block
* @return
*/
@GET( CONTROLLER + OBJECT_ID_PATH + VERSION_PATH )
BlockCiphertext getObjectAsBlockCiphertext( @Path( ID ) UUID objectId, @Path( VERSION ) long version );
/**
* Sets the IV for an object block
*
* @param objectId
* @param block
* @param iv
* @return
*/
@PUT( CONTROLLER + OBJECT_ID_PATH + VERSION_PATH + IV_PATH )
Response setObjectIv( @Path( ID ) UUID objectId, @Path( VERSION ) long version, @Body byte[] iv );
@PUT( CONTROLLER + OBJECT_ID_PATH + VERSION_PATH + CONTENTS_PATH )
Response setObjectContent( @Path( ID ) UUID objectId, @Path( VERSION ) long version, @Body byte[] content);
@PUT( CONTROLLER + OBJECT_ID_PATH + VERSION_PATH + SALT_PATH )
Response setObjectSalt( @Path( ID ) UUID objectId, @Path( VERSION ) long version, @Body byte[] salt );
@PUT( CONTROLLER + OBJECT_ID_PATH + VERSION_PATH + TAG_PATH )
Response setObjectTag( @Path( ID ) UUID objectId, @Path( VERSION ) long version, @Body byte[] tag );
@GET( CONTROLLER + OBJECT_ID_PATH + VERSION_PATH + CONTENTS_PATH )
byte[] getObjectContent( @Path( ID ) UUID objectId, @Path( VERSION ) long version );
@GET( CONTROLLER + OBJECT_ID_PATH + VERSION_PATH + IV_PATH )
byte[] getObjectIV( @Path( ID ) UUID objectId, @Path( VERSION ) long version );
@GET( CONTROLLER + OBJECT_ID_PATH + VERSION_PATH + SALT_PATH )
byte[] getObjectSalt( @Path( ID ) UUID objectId, @Path( VERSION ) long version );
@GET( CONTROLLER + OBJECT_ID_PATH + VERSION_PATH + TAG_PATH )
byte[] getObjectTag( @Path( ID ) UUID objectId, @Path( VERSION ) long version );
@GET( CONTROLLER + OBJECT_ID_PATH + OBJECT_METADATA_PATH )
ObjectMetadata getObjectMetadata( @Path( ID ) UUID id );
@DELETE( CONTROLLER + OBJECT_ID_PATH + VERSION_PATH )
Response delete( @Path( ID ) UUID id, @Path( VERSION ) long version );
@DELETE( CONTROLLER + OBJECT_ID_PATH )
Response delete( @Path( ID ) UUID id );
@DELETE( CONTROLLER )
Set<UUID> deleteObjectTrees( @Body Set<UUID> objectTrees );
@POST( CONTROLLER + LEVELS_PATH )
Map<UUID, ObjectMetadataEncryptedNode> getObjectsByTypeAndLoadLevel( @Body ObjectTreeLoadRequest request );
// METADATA APIs
/**
* Request a new object be created in a pending state
*
* @return The ID of the newly created object
*/
@POST( CONTROLLER + OBJECT_METADATA_PATH )
VersionedObjectKey createMetadataObject( @Body CreateMetadataObjectRequest request );
@POST( CONTROLLER + OBJECT_METADATA_PATH + OBJECT_ID_PATH )
Response createMetadataEntry(
@Path( ID ) UUID objectId,
@Body Set<PaddedMetadataObjectIds> paddedMetadataObjectIds );
@DELETE( CONTROLLER + OBJECT_METADATA_PATH + OBJECT_ID_PATH )
Response createMetadataEntry( @Path( ID ) UUID objectId );
}
| src/main/java/com/kryptnostic/v2/storage/api/ObjectStorageApi.java | package com.kryptnostic.v2.storage.api;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import com.kryptnostic.kodex.v1.crypto.ciphers.BlockCiphertext;
import com.kryptnostic.v2.constants.Names;
import com.kryptnostic.v2.storage.models.CreateMetadataObjectRequest;
import com.kryptnostic.v2.storage.models.CreateObjectRequest;
import com.kryptnostic.v2.storage.models.ObjectMetadata;
import com.kryptnostic.v2.storage.models.ObjectMetadataEncryptedNode;
import com.kryptnostic.v2.storage.models.ObjectTreeLoadRequest;
import com.kryptnostic.v2.storage.models.PaddedMetadataObjectIds;
import com.kryptnostic.v2.storage.models.VersionedObjectKey;
import retrofit.client.Response;
import retrofit.http.Body;
import retrofit.http.DELETE;
import retrofit.http.GET;
import retrofit.http.POST;
import retrofit.http.PUT;
import retrofit.http.Path;
/**
* @author Matthew Tamayo-Rios <[email protected]>
*
*/
public interface ObjectStorageApi {
String CONTROLLER = "/object";
// Parameter names
String ID = Names.ID_FIELD;
String VERSION = "version";
String CONTENT = "content";
String BLOCK = "block";
String USER = "user";
// Paths
String OBJECT_ID_PATH = "/id/{" + ID + "}";
String VERSION_PATH = "/{" + VERSION + "}";
String BLOCK_PATH = "/{" + BLOCK + "}";
String USER_ID_PATH = "/{" + ID + "}";
String CONTENTS_PATH = "/" + Names.CONTENTS;
String IV_PATH = "/iv";
String SALT_PATH = "/salt";
String TAG_PATH = "/tag";
String LEVELS_PATH = "/levels";
String TYPE = "type";
String TYPE_PATH = "/type/{" + TYPE + "}";
String OBJECT_APPEND_PATH = "/append";
String OBJECT_METADATA_PATH = "/metadata";
String BULK_PATH = "/bulk";
/**
* Request a new object be created in a pending state
*
* @return The ID of the newly created object
*/
@POST( CONTROLLER )
VersionedObjectKey createObject( @Body CreateObjectRequest request );
@GET( CONTROLLER + OBJECT_ID_PATH )
VersionedObjectKey getVersionedObjectKey( @Path( ID ) UUID id );
/**
* Lazy Person API for writing base64 encoded block ciphertexts in bulk.
*
* @param objectIds
* @return
*/
@POST( CONTROLLER + BULK_PATH )
Map<UUID, BlockCiphertext> getObjects( @Body Set<UUID> objectIds );
/**
* Lazy Person API for writing base64 encoded block ciphertexts. Objects written via this API will be available
* through the more efficient byte level APIs.
*
* @param objectId
* @param ciphertext
* @return
*/
@PUT( CONTROLLER + OBJECT_ID_PATH + VERSION_PATH )
Response setObjectFromBlockCiphertext(
@Path( ID ) UUID objectId,
@Path( VERSION ) long version,
@Body BlockCiphertext ciphertext );
/**
* Cached Lazy Person API for reading base64 encoded block ciphertexts. Objects readable by this API will be
* available through the more efficient byte level APIs.
*
* @param objectId
* @param block
* @return
*/
@GET( CONTROLLER + OBJECT_ID_PATH + VERSION_PATH )
BlockCiphertext getObjectAsBlockCiphertext( @Path( ID ) UUID objectId, @Path( VERSION ) long version );
/**
* Sets the IV for an object block
*
* @param objectId
* @param block
* @param iv
* @return
*/
@PUT( CONTROLLER + OBJECT_ID_PATH + VERSION_PATH + IV_PATH )
Response setObjectIv( @Path( ID ) UUID objectId, @Path( VERSION ) long version, @Body byte[] iv );
@PUT( CONTROLLER + OBJECT_ID_PATH + VERSION_PATH + CONTENTS_PATH )
Response setObjectContent( @Path( ID ) UUID objectId, @Path( VERSION ) long version, @Body byte[] content);
@PUT( CONTROLLER + OBJECT_ID_PATH + VERSION_PATH + SALT_PATH )
Response setObjectSalt( @Path( ID ) UUID objectId, @Path( VERSION ) long version, @Body byte[] salt );
@PUT( CONTROLLER + OBJECT_ID_PATH + VERSION_PATH + TAG_PATH )
Response setObjectTag( @Path( ID ) UUID objectId, @Path( VERSION ) long version, @Body byte[] tag );
@GET( CONTROLLER + OBJECT_ID_PATH + VERSION_PATH + CONTENTS_PATH )
byte[] getObjectContent( @Path( ID ) UUID objectId, @Path( VERSION ) long version );
@GET( CONTROLLER + OBJECT_ID_PATH + VERSION_PATH + IV_PATH )
byte[] getObjectIV( @Path( ID ) UUID objectId, @Path( VERSION ) long version );
@GET( CONTROLLER + OBJECT_ID_PATH + VERSION_PATH + SALT_PATH )
byte[] getObjectSalt( @Path( ID ) UUID objectId, @Path( VERSION ) long version );
@GET( CONTROLLER + OBJECT_ID_PATH + VERSION_PATH + TAG_PATH )
byte[] getObjectTag( @Path( ID ) UUID objectId, @Path( VERSION ) long version );
@GET( CONTROLLER + OBJECT_ID_PATH + OBJECT_METADATA_PATH )
ObjectMetadata getObjectMetadata( @Path( ID ) UUID id );
@DELETE( CONTROLLER + OBJECT_ID_PATH + VERSION_PATH )
Response delete( @Path( ID ) UUID id, @Path( VERSION ) long version );
@DELETE( CONTROLLER + OBJECT_ID_PATH )
Response delete( @Path( ID ) UUID id );
@DELETE( CONTROLLER )
Set<UUID> deleteObjectTrees( @Body Set<UUID> objectTrees );
@POST( CONTROLLER + LEVELS_PATH )
Map<UUID, ObjectMetadataEncryptedNode> getObjectsByTypeAndLoadLevel( @Body ObjectTreeLoadRequest request );
// METADATA APIs
/**
* Request a new object be created in a pending state
*
* @return The ID of the newly created object
*/
@POST( CONTROLLER + OBJECT_METADATA_PATH )
VersionedObjectKey createMetadataObject( @Body CreateMetadataObjectRequest request );
@POST( CONTROLLER + OBJECT_METADATA_PATH + OBJECT_ID_PATH )
Response createMetadataEntry(
@Path( ID ) UUID objectId,
@Body Set<PaddedMetadataObjectIds> paddedMetadataObjectIds );
@DELETE( CONTROLLER + OBJECT_METADATA_PATH + OBJECT_ID_PATH )
Response createMetadataEntry( @Path( ID ) UUID objectId );
}
| TYPE and TYPE_PATH were moved to ObjectListingApi
| src/main/java/com/kryptnostic/v2/storage/api/ObjectStorageApi.java | TYPE and TYPE_PATH were moved to ObjectListingApi | <ide><path>rc/main/java/com/kryptnostic/v2/storage/api/ObjectStorageApi.java
<ide> String SALT_PATH = "/salt";
<ide> String TAG_PATH = "/tag";
<ide> String LEVELS_PATH = "/levels";
<del> String TYPE = "type";
<del> String TYPE_PATH = "/type/{" + TYPE + "}";
<ide> String OBJECT_APPEND_PATH = "/append";
<ide> String OBJECT_METADATA_PATH = "/metadata";
<ide> String BULK_PATH = "/bulk"; |
|
Java | apache-2.0 | d6b4c14369ade1b35a3ff74e40ab0cf6c02a5e6a | 0 | 0359xiaodong/dmix,jcnoir/dmix,0359xiaodong/dmix,joansmith/dmix,jcnoir/dmix,hurzl/dmix,joansmith/dmix,philchand/mpdroid-2014,philchand/mpdroid-2014,philchand/mpdroid-2014,abarisain/dmix,abarisain/dmix,philchand/mpdroid-2014,hurzl/dmix | package org.a0z.mpd;
import android.content.Context;
import android.util.Log;
import org.a0z.mpd.exception.MPDClientException;
import org.a0z.mpd.exception.MPDConnectionException;
import org.a0z.mpd.exception.MPDServerException;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.*;
/**
* MPD Server controller.
*
* @version $Id: MPD.java 2716 2004-11-20 17:37:20Z galmeida $
*/
public class MPD {
private MPDConnection mpdConnection;
private MPDConnection mpdIdleConnection;
private MPDStatus mpdStatus;
private MPDPlaylist playlist;
private Directory rootDirectory;
static private boolean useAlbumArtist = false;
static private boolean sortByTrackNumber = true;
static private boolean sortAlbumsByYear = false;
static private boolean showArtistAlbumCount = false;
static private boolean showAlbumTrackCount = true;
static private Context applicationContext = null;
static public Context getApplicationContext() {
return applicationContext;
}
static public void setApplicationContext(Context context) {
applicationContext = context;
}
static public boolean useAlbumArtist() {
return useAlbumArtist;
}
static public boolean sortAlbumsByYear() {
return sortAlbumsByYear;
}
static public boolean sortByTrackNumber() {
return sortByTrackNumber;
}
static public boolean showArtistAlbumCount() {
return showArtistAlbumCount;
}
static public boolean showAlbumTrackCount() {
return showAlbumTrackCount;
}
static public void setUseAlbumArtist(boolean v) {
useAlbumArtist=v;
}
static public void setSortByTrackNumber(boolean v) {
sortByTrackNumber=v;
}
static public void setSortAlbumsByYear(boolean v) {
sortAlbumsByYear=v;
}
static public void setShowArtistAlbumCount(boolean v) {
showArtistAlbumCount=v;
}
static public void setShowAlbumTrackCount(boolean v) {
showAlbumTrackCount=v;
}
/**
* Constructs a new MPD server controller without connection.
*/
public MPD() {
this.playlist = new MPDPlaylist(this);
this.mpdStatus = new MPDStatus();
this.rootDirectory = Directory.makeRootDirectory(this);
}
/**
* Constructs a new MPD server controller.
*
* @param server
* server address or host name
* @param port
* server port
* @throws MPDServerException
* if an error occur while contacting server
* @throws UnknownHostException
*/
public MPD(String server, int port) throws MPDServerException, UnknownHostException {
this();
connect(server, port);
}
/**
* Constructs a new MPD server controller.
*
* @param server
* server address or host name
* @param port
* server port
* @throws MPDServerException
* if an error occur while contacting server
*/
public MPD(InetAddress server, int port) throws MPDServerException {
this();
connect(server, port);
}
/**
* Retrieves <code>MPDConnection</code>.
*
* @return <code>MPDConnection</code>.
*/
public MPDConnection getMpdConnection() {
return this.mpdConnection;
}
MPDConnection getMpdIdleConnection() {
return this.mpdIdleConnection;
}
/**
* Wait for server changes using "idle" command on the dedicated connection.
*
* @return Data readed from the server.
* @throws MPDServerException if an error occur while contacting server
*/
public List<String> waitForChanges() throws MPDServerException {
while (mpdIdleConnection != null && mpdIdleConnection.isConnected()) {
List<String> data = mpdIdleConnection
.sendAsyncCommand(MPDCommand.MPD_CMD_IDLE);
if (data.isEmpty()) {
continue;
}
return data;
}
throw new MPDConnectionException("IDLE connection lost");
}
public boolean isMpdConnectionNull() {
return (this.mpdConnection == null);
}
/**
* Increases or decreases volume by <code>modifier</code> amount.
*
* @param modifier
* volume adjustment
* @throws MPDServerException
* if an error occur while contacting server
*/
public void adjustVolume(int modifier) throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
// calculate final volume (clip value with [0, 100])
int vol = getVolume() + modifier;
vol = Math.max(MPDCommand.MIN_VOLUME, Math.min(MPDCommand.MAX_VOLUME, vol));
mpdConnection.sendCommand(MPDCommand.MPD_CMD_SET_VOLUME, Integer.toString(vol));
}
/**
* Clears error message.
*
* @throws MPDServerException
* if an error occur while contacting server.
*/
public void clearError() throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
mpdConnection.sendCommand(MPDCommand.MPD_CMD_CLEARERROR);
}
/**
* Connects to a MPD server.
*
* @param server
* server address or host name
* @param port
* server port
* @throws MPDServerException
* if an error occur while contacting server
* @throws UnknownHostException
*/
public final void connect(String server, int port) throws MPDServerException, UnknownHostException {
InetAddress adress = InetAddress.getByName(server);
connect(adress, port);
}
/**
* Connects to a MPD server.
*
* @param server
* server address or host name
* @param port
* server port
*/
public final void connect(InetAddress server, int port) throws MPDServerException {
this.mpdConnection = new MPDConnection(server, port);
this.mpdIdleConnection = new MPDConnection(server, port, 1000);
}
/**
* Connects to a MPD server.
*
* @param server
* server address or host name and port (server:port)
* @throws MPDServerException
* if an error occur while contacting server
* @throws UnknownHostException
*/
public final void connect(String server) throws MPDServerException, UnknownHostException {
int port = MPDCommand.DEFAULT_MPD_PORT;
String host = null;
if (server.indexOf(':') != -1) {
host = server.substring(0, server.lastIndexOf(':'));
port = Integer.parseInt(server.substring(server.lastIndexOf(':') + 1));
} else {
host = server;
}
connect(host, port);
}
/**
* Disconnects from server.
*
* @throws MPDServerException
* if an error occur while closing connection
*/
public void disconnect() throws MPDServerException {
MPDServerException ex = null;
if (mpdConnection != null && mpdConnection.isConnected()) {
try {
mpdConnection.sendCommand(MPDCommand.MPD_CMD_CLOSE);
} catch (MPDServerException e) {
ex = e;
}
}
if (mpdConnection != null && mpdConnection.isConnected()) {
try {
mpdConnection.disconnect();
} catch (MPDServerException e) {
ex = (ex != null) ? ex : e;// Always keep first non null
// exception
}
}
if (mpdIdleConnection != null && mpdIdleConnection.isConnected()) {
try {
mpdIdleConnection.disconnect();
} catch (MPDServerException e) {
ex = (ex != null) ? ex : e;// Always keep non null first
// exception
}
}
if (ex != null) {
throw ex;
}
}
/**
* Similar to <code>search</code>,<code>find</code> looks for exact matches in the MPD database.
*
* @param type
* type of search. Should be one of the following constants: MPD_FIND_ARTIST, MPD_FIND_ALBUM
* @param string
* case-insensitive locator string. Anything that exactly matches <code>string</code> will be returned in the results.
* @return a Collection of <code>Music</code>
* @throws MPDServerException
* if an error occur while contacting server
* @see org.a0z.mpd.Music
*/
public List<Music> find(String type, String string) throws MPDServerException {
return genericSearch(MPDCommand.MPD_CMD_FIND, type, string);
}
public List<Music> find(String[] args) throws MPDServerException {
return genericSearch(MPDCommand.MPD_CMD_FIND, args, true);
}
// Returns a pattern where all punctuation characters are escaped.
private List<Music> genericSearch(String searchCommand, String type, String strToFind) throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
List<String> response = mpdConnection.sendCommand(searchCommand, type, strToFind);
return Music.getMusicFromList(response, true);
}
private List<Music> genericSearch(String searchCommand, String args[], boolean sort) throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
return Music.getMusicFromList(mpdConnection.sendCommand(searchCommand, args), sort);
}
/**
* Retrieves a database directory listing of the base of the database directory path.
*
* @return a <code>Collection</code> of <code>Music</code> and <code>Directory</code> representing directory entries.
* @throws MPDServerException
* if an error occur while contacting server.
* @see Music
* @see Directory
*/
public List<FilesystemTreeEntry> getDir() throws MPDServerException {
return getDir(null);
}
/**
* Retrieves a database directory listing of <code>path</code> directory.
*
* @param path Directory to be listed.
* @return a <code>Collection</code> of <code>Music</code> and <code>Directory</code> representing directory entries.
* @throws MPDServerException
* if an error occur while contacting server.
* @see Music
* @see Directory
*/
public List<FilesystemTreeEntry> getDir(String path) throws MPDServerException {
if(!isConnected())
throw new MPDServerException("MPD Connection is not established");
List<String> resonse = mpdConnection.sendCommand(MPDCommand.MPD_CMD_LSDIR, path);
LinkedList<String> lineCache = new LinkedList<String>();
LinkedList<FilesystemTreeEntry> result = new LinkedList<FilesystemTreeEntry>();
for (String line : resonse) {
// file-elements are the only ones using fileCache,
// therefore if something new begins and the cache
// contains data, its music
if ((line.startsWith("file: ") || line.startsWith("directory: ") || line.startsWith("playlist: ")) && lineCache.size() > 0) {
result.add(new Music(lineCache));
lineCache.clear();
}
if (line.startsWith("playlist: ")) {
line = line.substring("playlist: ".length());
result.add(new PlaylistFile(line));
} else if (line.startsWith("directory: ")) {
line = line.substring("directory: ".length());
result.add(rootDirectory.makeDirectory(line));
} else if (line.startsWith("file: ")) {
lineCache.add(line);
}
}
if (lineCache.size() > 0) {
result.add(new Music(lineCache));
}
return result;
}
/**
* Returns MPD server version.
*
* @return MPD Server version.
*/
public String getMpdVersion() throws MPDServerException {
if(!isConnected())
throw new MPDServerException("MPD Connection is not established");
int[] version = mpdConnection.getMpdVersion();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < version.length; i++) {
sb.append(version[i]);
if (i < (version.length - 1))
sb.append(".");
}
return sb.toString();
}
/**
* Retrieves <code>playlist</code>.
*
* @return playlist.
*/
public MPDPlaylist getPlaylist() {
return this.playlist;
}
/**
* Retrieves statistics for the connected server.
*
* @return statistics for the connected server.
* @throws MPDServerException
* if an error occur while contacting server.
*/
public MPDStatistics getStatistics() throws MPDServerException {
List<String> response = mpdConnection.sendCommand(MPDCommand.MPD_CMD_STATISTICS);
return new MPDStatistics(response);
}
/**
* Retrieves status of the connected server.
*
* @return status of the connected server.
* @throws MPDServerException
* if an error occur while contacting server.
*/
public MPDStatus getStatus() throws MPDServerException {
if(!isConnected())
throw new MPDServerException("MPD Connection is not established");
List<String> response = mpdConnection.sendCommand(MPDCommand.MPD_CMD_STATUS);
mpdStatus.updateStatus(response);
return mpdStatus;
}
/**
* Retrieves current volume.
*
* @return current volume.
* @throws MPDServerException
* if an error occur while contacting server.
*/
public int getVolume() throws MPDServerException {
return this.getStatus().getVolume();
}
/**
* Returns true when connected and false when not connected.
*
* @return true when connected and false when not connected
*/
public boolean isConnected() {
if (mpdConnection == null)
return false;
return mpdConnection.isConnected() ;
}
/**
* List all albums from database.
*
* @return <code>Collection</code> with all album names from database.
* @throws MPDServerException
* if an error occur while contacting server.
*/
public List<String> listAlbums() throws MPDServerException {
return listAlbums(null, false, false);
}
/**
* List all albums from database.
*
* @param useAlbumArtist
* use AlbumArtist instead of Artist
* @return <code>Collection</code> with all album names from database.
* @throws MPDServerException
* if an error occur while contacting server.
*/
public List<String> listAlbums(boolean useAlbumArtist) throws MPDServerException {
return listAlbums(null, useAlbumArtist, false);
}
/**
* List all albums from a given artist, including an entry for songs with no album tag.
*
* @param artist
* artist to list albums
* @param useAlbumArtist
* use AlbumArtist instead of Artist
* @return <code>Collection</code> with all album names from database.
* @throws MPDServerException
* if an error occur while contacting server.
*/
public List<String> listAlbums(String artist, boolean useAlbumArtist) throws MPDServerException {
return listAlbums(artist, useAlbumArtist, true);
}
/*
* get raw command String for listAlbums
*/
public MPDCommand listAlbumsCommand(String artist, boolean useAlbumArtist) {
if (useAlbumArtist) {
return new MPDCommand(MPDCommand.MPD_CMD_LIST_TAG, MPDCommand.MPD_TAG_ALBUM, MPDCommand.MPD_TAG_ALBUM_ARTIST, artist);
} else {
return new MPDCommand(MPDCommand.MPD_CMD_LIST_TAG, MPDCommand.MPD_TAG_ALBUM, artist);
}
}
/**
* List all albums from a given artist.
*
* @param artist
* artist to list albums
* @param useAlbumArtist
* use AlbumArtist instead of Artist
* @param includeUnknownAlbum
* include an entry for songs with no album tag
* @return <code>Collection</code> with all album names from the given artist present in database.
* @throws MPDServerException
* if an error occur while contacting server.
*/
public List<String> listAlbums(String artist, boolean useAlbumArtist, boolean includeUnknownAlbum) throws MPDServerException {
if(!isConnected())
throw new MPDServerException("MPD Connection is not established");
boolean foundSongWithoutAlbum = false;
List<String> response =
mpdConnection.sendCommand
(listAlbumsCommand(artist, useAlbumArtist));
ArrayList<String> result = new ArrayList<String>();
for (String line : response) {
String name = line.substring("Album: ".length());
if (name.length() > 0) {
result.add(name);
}else{
foundSongWithoutAlbum = true;
}
}
Collections.sort(result);
// add a single blank entry to host all songs without an album set
if((includeUnknownAlbum == true) && (foundSongWithoutAlbum == true)) {
result.add("");
}
return result;
}
private Long[] getAlbumDetails(String artist, String album, boolean useAlbumArtistTag) throws MPDServerException {
if (!isConnected()) {
throw new MPDServerException("MPD Connection is not established");
}
Long[] result = new Long[3];
result[0] = 0l;
result[1] = 0l;
result[2] = 0l;
if (MPD.showAlbumTrackCount()) {
String[] args = new String[4];
args[0] = useAlbumArtistTag ? MPDCommand.MPD_TAG_ALBUM_ARTIST : MPDCommand.MPD_TAG_ARTIST;
args[1] = artist;
args[2] = MPDCommand.MPD_TAG_ALBUM;
args[3] = album;
List<String> list = mpdConnection.sendCommand("count", args);
for (String line : list) {
if (line.startsWith("songs: ")) {
result[0] = Long.parseLong(line.substring("songs: ".length()));
} else if (line.startsWith("playtime: ")) {
result[1] = Long.parseLong(line.substring("playtime: ".length()));
}
}
}
if (MPD.sortAlbumsByYear()) {
String[] args = new String[6];
args[0] = useAlbumArtistTag ? MPDCommand.MPD_TAG_ALBUM_ARTIST : MPDCommand.MPD_TAG_ARTIST;
args[1] = artist;
args[2] = MPDCommand.MPD_TAG_ALBUM;
args[3] = album;
args[4] = "track";
args[5] = "1";
List<Music> songs = find(args);
if (null==songs || songs.isEmpty()) {
args[5] = "01";
songs = find(args);
}
if (null==songs || songs.isEmpty()) {
args[5] = "1";
songs = search(args);
}
if (null!=songs && !songs.isEmpty()) {
result[2]=songs.get(0).getDate();
}
}
return result;
}
public int getAlbumCount(Artist artist, boolean useAlbumArtistTag) throws MPDServerException {
return listAlbums(artist.getName(), useAlbumArtistTag).size();
}
public int getAlbumCount(String artist, boolean useAlbumArtistTag) throws MPDServerException {
if (mpdConnection == null) {
throw new MPDServerException("MPD Connection is not established");
}
return listAlbums(artist, useAlbumArtistTag).size();
}
/**
* Recursively retrieves all songs and directories.
*
* @param dir
* directory to list.
* @throws MPDServerException
* if an error occur while contacting server.
* @return <code>FileStorage</code> with all songs and directories.
*/
/*
public Directory listAllFiles(String dir) throws MPDServerException {
if(!isConnected())
throw new MPDServerException("MPD Connection is not established");
List<String> list = mpdConnection.sendCommand(MPD_CMD_LISTALL, dir);
for (String line : list) {
if (line.startsWith("directory: ")) {
rootDirectory.makeDirectory(line.substring("directory: ".length()));
} else if (line.startsWith("file: ")) {
rootDirectory.addFile(new Music(line.substring("file: ".length())));
}
}
return rootDirectory;
}
*/
/**
* List all genre names from database.
*
* @return artist names from database.
*
* @throws MPDServerException if an error occur while contacting server.
*/
public List<String> listGenres() throws MPDServerException {
return listGenres(true);
}
/**
* List all genre names from database.
*
* @param sortInsensitive
* boolean for insensitive sort when true
* @return artist names from database.
* @throws MPDServerException
* if an error occur while contacting server.
*/
public List<String> listGenres(boolean sortInsensitive) throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
List<String> response = mpdConnection.sendCommand(MPDCommand.MPD_CMD_LIST_TAG, MPDCommand.MPD_TAG_GENRE);
ArrayList<String> result = new ArrayList<String>();
for (String s : response) {
String name = s.substring("Genre: ".length());
if (name.length() > 0)
result.add(name);
}
if (sortInsensitive)
Collections.sort(result, String.CASE_INSENSITIVE_ORDER);
else
Collections.sort(result);
return result;
}
/*
* List all albumartist or artist names of all given albums from database.
*
* @return list of array of artist names for each album.
* @throws MPDServerException
* if an error occurs while contacting server.
*/
public List<String[]> listArtists(List<Album> albums, boolean albumArtist) throws MPDServerException {
if(!isConnected())
throw new MPDServerException("MPD Connection is not established");
for (Album a : albums) {
mpdConnection.queueCommand
(new MPDCommand(MPDCommand.MPD_CMD_LIST_TAG,
(albumArtist ? MPDCommand.MPD_TAG_ALBUM_ARTIST :
MPDCommand.MPD_TAG_ARTIST),
MPDCommand.MPD_TAG_ALBUM,
a.getName()));
}
List<String[]> responses = mpdConnection.sendCommandQueueSeparated();
ArrayList<String []> result = new ArrayList<String[]>();
for (String[] r : responses){
ArrayList<String> albumresult = new ArrayList<String>();
for (String s : r) {
String name = s.substring((albumArtist?"AlbumArtist: ":"Artist: ").length());
if (name.length() > 0)
albumresult.add(name);
}
result.add((String[])albumresult.toArray(new String[0]));
}
return result;
}
/**
* List all artist names from database.
*
* @return artist names from database.
* @throws MPDServerException
* if an error occur while contacting server.
*/
public List<String> listArtists() throws MPDServerException {
return listArtists(true);
}
/**
* List all artist names from database.
*
* @param sortInsensitive
* boolean for insensitive sort when true
* @return artist names from database.
* @throws MPDServerException
* if an error occur while contacting server.
*/
public List<String> listArtists(boolean sortInsensitive) throws MPDServerException {
if(!isConnected())
throw new MPDServerException("MPD Connection is not established");
List<String> response = mpdConnection.sendCommand(MPDCommand.MPD_CMD_LIST_TAG, MPDCommand.MPD_TAG_ARTIST);
ArrayList<String> result = new ArrayList<String>();
for (String s : response) {
String name = s.substring("Artist: ".length());
if (name.length() > 0)
result.add(name);
}
if (sortInsensitive)
Collections.sort(result, String.CASE_INSENSITIVE_ORDER);
else
Collections.sort(result);
return result;
}
/**
* List all artist names from database.
*
* @return artist names from database.
* @throws MPDServerException
* if an error occur while contacting server.
*/
public List<String> listArtists(String genre) throws MPDServerException {
return listArtists(genre, true);
}
/**
* List all artist names from database.
*
* @param sortInsensitive
* boolean for insensitive sort when true
* @return artist names from database.
* @throws MPDServerException
* if an error occur while contacting server.
*/
public List<String> listArtists(String genre, boolean sortInsensitive) throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
List<String> response = mpdConnection.sendCommand(MPDCommand.MPD_CMD_LIST_TAG, MPDCommand.MPD_TAG_ARTIST, MPDCommand.MPD_TAG_GENRE, genre);
ArrayList<String> result = new ArrayList<String>();
for (String s : response) {
String name = s.substring("Artist: ".length());
if (name.length() > 0)
result.add(name);
}
if (sortInsensitive)
Collections.sort(result, String.CASE_INSENSITIVE_ORDER);
else
Collections.sort(result);
return result;
}
/**
* List all album artist names from database.
*
* @return album artist names from database.
* @throws MPDServerException
* if an error occur while contacting server.
*/
public List<String> listAlbumArtists() throws MPDServerException {
if(!isConnected())
throw new MPDServerException("MPD Connection is not established");
List<String> response = mpdConnection.sendCommand(MPDCommand.MPD_CMD_LIST_TAG, MPDCommand.MPD_TAG_ALBUM_ARTIST);
ArrayList<String> result = new ArrayList<String>();
for (String s : response) {
String name = s.substring("albumartist: ".length());
if (name.length() > 0)
result.add(name);
}
Collections.sort(result);
return result;
}
/**
* List all album artist names from database.
*
* @return album artist names from database.
* @throws MPDServerException
* if an error occur while contacting server.
*/
public List<String> listAlbumArtists(Genre genre) throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
List<String> response = mpdConnection.sendCommand(MPDCommand.MPD_CMD_LIST_TAG, MPDCommand.MPD_TAG_ALBUM_ARTIST, MPDCommand.MPD_TAG_GENRE,
genre.getName());
ArrayList<String> result = new ArrayList<String>();
for (String s : response) {
String name = s.substring("albumartist: ".length());
if (name.length() > 0)
result.add(name);
}
Collections.sort(result);
return result;
}
/**
* Jumps to next playlist track.
*
* @throws MPDServerException
* if an error occur while contacting server.
*/
public void next() throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
mpdConnection.sendCommand(MPDCommand.MPD_CMD_NEXT);
}
/**
* Authenticate using password.
*
* @param password
* password.
* @throws MPDServerException
* if an error occur while contacting server.
*/
public void password(String password) throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
mpdConnection.sendCommand(MPDCommand.MPD_CMD_PASSWORD, password);
mpdIdleConnection.sendCommand(MPDCommand.MPD_CMD_PASSWORD, password);
}
/**
* Pauses/Resumes music playing.
*
* @throws MPDServerException
* if an error occur while contacting server.
*/
public void pause() throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
mpdConnection.sendCommand(MPDCommand.MPD_CMD_PAUSE);
}
/**
* Starts playing music.
*
* @throws MPDServerException
* if an error occur while contacting server.
*/
public void play() throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
mpdConnection.sendCommand(MPDCommand.MPD_CMD_PLAY);
}
/**
* Plays previous playlist music.
*
* @throws MPDServerException
* if an error occur while contacting server..
*/
public void previous() throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
mpdConnection.sendCommand(MPDCommand.MPD_CMD_PREV);
}
/**
* Tells server to refresh database.
*
* @throws MPDServerException
* if an error occur while contacting server.
*/
public void refreshDatabase() throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
mpdConnection.sendCommand(MPDCommand.MPD_CMD_REFRESH);
}
/**
* Similar to <code>find</code>,<code>search</code> looks for partial matches in the MPD database.
*
* @param type
* type of search. Should be one of the following constants: MPD_SEARCH_ARTIST, MPD_SEARCH_TITLE, MPD_SEARCH_ALBUM,
* MPD_SEARCG_FILENAME
* @param string
* case-insensitive locator string. Anything that contains <code>string</code> will be returned in the results.
* @return a Collection of <code>Music</code>.
* @throws MPDServerException
* if an error occur while contacting server.
* @see org.a0z.mpd.Music
*/
public Collection<Music> search(String type, String string) throws MPDServerException {
return genericSearch(MPDCommand.MPD_CMD_SEARCH, type, string);
}
public List<Music> search(String[] args) throws MPDServerException {
return genericSearch(MPDCommand.MPD_CMD_SEARCH, args, true);
}
/**
* Seeks music to the position.
*
* @param songId
* music id in playlist.
* @param position
* song position in seconds.
* @throws MPDServerException
* if an error occur while contacting server.
*/
public void seekById(int songId, long position) throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
mpdConnection.sendCommand(MPDCommand.MPD_CMD_SEEK_ID, Integer.toString(songId), Long.toString(position));
}
/**
* Seeks music to the position.
*
* @param index
* music position in playlist.
* @param position
* song position in seconds.
* @throws MPDServerException
* if an error occur while contacting server.
*/
public void seekByIndex(int index, long position) throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
mpdConnection.sendCommand(MPDCommand.MPD_CMD_SEEK, Integer.toString(index), Long.toString(position));
}
/**
* Seeks current music to the position.
*
* @param position
* song position in seconds
* @throws MPDServerException
* if an error occur while contacting server.
*/
public void seek(long position) throws MPDServerException {
seekById(this.getStatus().getSongId(), position);
}
/**
* Enabled or disable random.
*
* @param random
* if true random will be enabled, if false random will be disabled.
* @throws MPDServerException
* if an error occur while contacting server.
*/
public void setRandom(boolean random) throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
mpdConnection.sendCommand(MPDCommand.MPD_CMD_RANDOM, random ? "1" : "0");
}
/**
* Enabled or disable repeating.
*
* @param repeat
* if true repeating will be enabled, if false repeating will be disabled.
* @throws MPDServerException
* if an error occur while contacting server.
*/
public void setRepeat(boolean repeat) throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
mpdConnection.sendCommand(MPDCommand.MPD_CMD_REPEAT, repeat ? "1" : "0");
}
/**
* Enabled or disable single mode.
*
* @param single
* if true single mode will be enabled, if false single mode will be disabled.
* @throws MPDServerException
* if an error occur while contacting server.
*/
public void setSingle(boolean single) throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
mpdConnection.sendCommand(MPDCommand.MPD_CMD_SINGLE, single ? "1" : "0");
}
/**
* Enabled or disable consuming.
*
* @param consume
* if true song consuming will be enabled, if false song consuming will be disabled.
* @throws MPDServerException
* if an error occur while contacting server.
*/
public void setConsume(boolean consume) throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
mpdConnection.sendCommand(MPDCommand.MPD_CMD_CONSUME, consume ? "1" : "0");
}
/**
* Sets volume to <code>volume</code>.
*
* @param volume
* new volume value, must be in 0-100 range.
* @throws MPDServerException
* if an error occur while contacting server.
*/
public void setVolume(int volume) throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
int vol = Math.max(MPDCommand.MIN_VOLUME, Math.min(MPDCommand.MAX_VOLUME, volume));
mpdConnection.sendCommand(MPDCommand.MPD_CMD_SET_VOLUME, Integer.toString(vol));
}
/**
* Kills server.
*
* @throws MPDServerException
* if an error occur while contacting server.
*/
public void shutdown() throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
mpdConnection.sendCommand(MPDCommand.MPD_CMD_KILL);
}
/**
* Jumps to track <code>position</code> from playlist.
*
* @param position
* track number.
* @throws MPDServerException
* if an error occur while contacting server.
* @see #skipToId(int)
*/
public void skipToPositon(int position) throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
mpdConnection.sendCommand(MPDCommand.MPD_CMD_PLAY, Integer.toString(position));
}
/**
* Skip to song with specified <code>id</code>.
*
* @param id
* song id.
* @throws MPDServerException
* if an error occur while contacting server.
*/
public void skipToId(int id) throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
mpdConnection.sendCommand(MPDCommand.MPD_CMD_PLAY_ID, Integer.toString(id));
}
/**
* Stops music playing.
*
* @throws MPDServerException
* if an error occur while contacting server.
*/
public void stop() throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
mpdConnection.sendCommand(MPDCommand.MPD_CMD_STOP);
}
/**
* Retrieves root directory.
*
* @return root directory.
*/
public Directory getRootDirectory() {
return rootDirectory;
}
/**
* Sets cross-fade.
*
* @param time
* cross-fade time in seconds. 0 to disable cross-fade.
* @throws MPDServerException
* if an error occur while contacting server.
*/
public void setCrossfade(int time) throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
mpdConnection.sendCommand(MPDCommand.MPD_CMD_CROSSFADE, Integer.toString(Math.max(0, time)));
}
/**
* Returns the available outputs
*
* @return List of available outputs
*/
public List<MPDOutput> getOutputs() throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
List<MPDOutput> result = new LinkedList<MPDOutput>();
List<String> response = mpdConnection.sendCommand(MPDCommand.MPD_CMD_OUTPUTS);
LinkedList<String> lineCache = new LinkedList<String>();
for (String line : response) {
if (line.startsWith("outputid: ")) {
if (lineCache.size() != 0) {
result.add(new MPDOutput(lineCache));
lineCache.clear();
}
}
lineCache.add(line);
}
if (lineCache.size() != 0) {
result.add(new MPDOutput(lineCache));
}
return result;
}
/**
* Returns a list of all available playlists
*/
public List<Item> getPlaylists() throws MPDServerException {
return getPlaylists(false);
}
/**
* Returns a list of all available playlists
*
* @param sort whether the return list should be sorted
*/
public List<Item> getPlaylists(boolean sort) throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
List<Item> result = new ArrayList<Item>();
List<String> response = mpdConnection.sendCommand(MPDCommand.MPD_CMD_LISTPLAYLISTS);
for(String line : response) {
if(line.startsWith("playlist"))
result.add(new Playlist(line.substring("playlist: ".length())));
}
if (sort)
Collections.sort(result);
return result;
}
public void enableOutput(int id) throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
mpdConnection.sendCommand(MPDCommand.MPD_CMD_OUTPUTENABLE, Integer.toString(id));
}
public void disableOutput(int id) throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
mpdConnection.sendCommand(MPDCommand.MPD_CMD_OUTPUTDISABLE, Integer.toString(id));
}
public List<Music> getSongs(Artist artist, Album album) throws MPDServerException {
List<Music> aasongs = getSongs(artist, album, true); // album artist
if (aasongs == null || aasongs.size() == 0)
return getSongs(artist, album, false); // artist
else
return aasongs;
}
public List<Music> getSongs(Artist artist, Album album, boolean useAlbumArtist) throws MPDServerException {
boolean haveArtist = (null != artist);
boolean haveAlbum = (null != album) && !(album instanceof UnknownAlbum);
String[] search = null;
int pos=0;
if (haveAlbum || haveArtist) {
search=new String[haveAlbum && haveArtist ? 4 : 2];
if (haveArtist) {
search[pos++] = useAlbumArtist ? MPDCommand.MPD_TAG_ALBUM_ARTIST : MPDCommand.MPD_FIND_ARTIST;
search[pos++]=artist.getName();
}
if (haveAlbum) {
search[pos++]=MPDCommand.MPD_FIND_ALBUM;
search[pos++]=album.getName();
}
}
List<Music> songs=find(search);
if(album instanceof UnknownAlbum) {
// filter out any songs with which have the album tag set
Iterator<Music> iter = songs.iterator();
while (iter.hasNext()) {
if (iter.next().getAlbum() != null) iter.remove();
}
}
if (null!=songs) {
Collections.sort(songs);
}
return songs;
}
public List<Album> getAlbums(Artist artist) throws MPDServerException {
return getAlbums(artist, true);
}
public List<Album> getAlbums(Artist artist, boolean trackCountNeeded) throws MPDServerException {
return getAlbums(artist, trackCountNeeded, useAlbumArtist);
}
public List<Album> getAlbums(Artist artist, boolean trackCountNeeded,
boolean _useAlbumArtist) throws MPDServerException {
List<String> albumNames = null;
List<Album> albums = null;
final Artist unknownArtist = UnknownArtist.instance;
if(artist != null) {
albumNames = listAlbums(artist.getName(), _useAlbumArtist);
}else{
albumNames = listAlbums(false);
artist = unknownArtist;
}
if (null!=albumNames && !albumNames.isEmpty()) {
albums=new ArrayList<Album>();
for (String album : albumNames) {
if(album == "") {
// add a blank entry to host all songs without an album set
albums.add(UnknownAlbum.instance);
}else{
long songCount = 0;
long duration = 0;
long year = 0;
if (unknownArtist != artist && ((MPD.showAlbumTrackCount() && trackCountNeeded) || MPD.sortAlbumsByYear())) {
try {
Long[] albumDetails = getAlbumDetails(artist.getName(), album, _useAlbumArtist);
if (null!=albumDetails && 3==albumDetails.length) {
songCount=albumDetails[0];
duration=albumDetails[1];
year=albumDetails[2];
}
} catch (MPDServerException e) {
}
}
albums.add(new Album(album, songCount, duration, year, artist));
}
}
if (!_useAlbumArtist && artist != unknownArtist) {
fixAlbumArtists(albums);
}
}
if (null!=albums) {
Collections.sort(albums);
}
return albums;
}
void fixAlbumArtists(List<Album> albums) {
List<String[]> albumartists = null;
try {
albumartists = listArtists(albums,true);
} catch (MPDServerException e) {
return;
}
if (albumartists == null || albumartists.size() != albums.size()) {
// Log.d("ALBUMARTISTS", "ERROR " + albumartists.size() + " != " +albums.size());
return;
}
int i = 0;
List<Album> splitalbums = new ArrayList<Album>();
for (Album a : albums) {
String[] aartists = (String[])albumartists.get(i);
if (aartists.length > 0) {
a.setArtist(new Artist(aartists[0])); // fix this album
if (aartists.length > 1) { // it's more than one album, insert
for (int n = 1; n < aartists.length; n++){
Album newalbum = new Album(a.getName(),
new Artist(aartists[n]));
splitalbums.add(newalbum);
}
}
}
i++;
}
albums.addAll(splitalbums);
Collections.sort(albums);
}
public List<Genre> getGenres() throws MPDServerException {
List<String> genreNames = listGenres();
List<Genre> genres = null;
if (null != genreNames && !genreNames.isEmpty()) {
genres = new ArrayList<Genre>();
for (String genre : genreNames) {
genres.add(new Genre(genre));
}
}
if (null != genres) {
Collections.sort(genres);
}
return genres;
}
public List<Artist> getArtists() throws MPDServerException {
List<String> artistNames=MPD.useAlbumArtist() ? listAlbumArtists() : listArtists(true);
List<Artist> artists = null;
if (null!=artistNames && !artistNames.isEmpty()) {
artists=new ArrayList<Artist>();
for (String artist : artistNames) {
artists.add(new Artist(artist, MPD.showArtistAlbumCount() ? getAlbumCount(artist, useAlbumArtist) : 0));
}
}
if (null!=artists) {
Collections.sort(artists);
}
return artists;
}
public List<Artist> getArtists(Genre genre) throws MPDServerException {
List<String> artistNames = MPD.useAlbumArtist() ? listAlbumArtists(genre) : listArtists(genre.getName(), true);
List<Artist> artists = null;
if (null != artistNames && !artistNames.isEmpty()) {
artists = new ArrayList<Artist>();
for (String artist : artistNames) {
artists.add(new Artist(artist, MPD.showArtistAlbumCount() ? getAlbumCount(artist, useAlbumArtist) : 0));
}
}
if (null != artists) {
Collections.sort(artists);
}
return artists;
}
public List<Music> getPlaylistSongs(String playlistName) throws MPDServerException {
String args[]=new String[1];
args[0]=playlistName;
List<Music> music=genericSearch(MPDCommand.MPD_CMD_PLAYLIST_INFO, args, false);
for (int i=0; i<music.size(); ++i) {
music.get(i).setSongId(i);
}
return music;
}
public void movePlaylistSong(String playlistName, int from, int to) throws MPDServerException {
getMpdConnection().sendCommand(MPDCommand.MPD_CMD_PLAYLIST_MOVE, playlistName, Integer.toString(from), Integer.toString(to));
}
public void removeFromPlaylist(String playlistName, Integer pos) throws MPDServerException {
getMpdConnection().sendCommand(MPDCommand.MPD_CMD_PLAYLIST_DEL, playlistName, Integer.toString(pos));
}
public void addToPlaylist(String playlistName, Collection<Music> c) throws MPDServerException {
if (null==c || c.size()<1) {
return;
}
for (Music m : c) {
getMpdConnection().queueCommand(MPDCommand.MPD_CMD_PLAYLIST_ADD, playlistName, m.getFullpath());
}
getMpdConnection().sendCommandQueue();
}
public void addToPlaylist(String playlistName, FilesystemTreeEntry entry) throws MPDServerException {
getMpdConnection().sendCommand(MPDCommand.MPD_CMD_PLAYLIST_ADD, playlistName, entry.getFullpath());
}
public void add(Artist artist) throws MPDServerException {
add(artist, false, false);
}
public void add(Artist artist, Album album) throws MPDServerException {
add(artist, album, false, false);
}
public void add(Music music) throws MPDServerException {
add(music, false, false);
}
public void add(String playlist) throws MPDServerException {
add(playlist, false, false);
}
public void add(Artist artist, boolean replace, boolean play) throws MPDServerException {
add(artist, null, replace, play);
}
public void add(final FilesystemTreeEntry music, boolean replace, boolean play) throws MPDServerException {
final Runnable r = new Runnable() {
@Override
public void run() {
try {
if (music instanceof Music) {
getPlaylist().add(music);
} else if (music instanceof PlaylistFile) {
getPlaylist().load(music.getFullpath());
}
} catch (MPDServerException e) {
e.printStackTrace();
}
}
};
add(r, replace, play);
}
public void add(final Artist artist, final Album album, boolean replace, boolean play) throws MPDServerException {
final Runnable r = new Runnable() {
@Override
public void run() {
try {
final ArrayList<Music> songs = new ArrayList<Music>(getSongs(artist, album));
getPlaylist().addAll(songs);
} catch (MPDServerException e) {
e.printStackTrace();
}
}
};
add(r, replace, play);
}
public void add(final String playlist, boolean replace, boolean play) throws MPDServerException {
final Runnable r = new Runnable() {
@Override
public void run() {
try {
getPlaylist().load(playlist);
} catch (MPDServerException e) {
e.printStackTrace();
}
}
};
add(r, replace, play);
}
public void add(final URL stream, boolean replace, boolean play) throws MPDServerException {
final Runnable r = new Runnable() {
@Override
public void run() {
try {
getPlaylist().add(stream);
} catch (MPDServerException e) {
e.printStackTrace();
} catch (MPDClientException e) {
e.printStackTrace();
}
}
};
add(r, replace, play);
}
public void add(final Directory directory, boolean replace, boolean play) throws MPDServerException {
final Runnable r = new Runnable() {
@Override
public void run() {
try {
getPlaylist().add(directory);
} catch (MPDServerException e) {
e.printStackTrace();
}
}
};
add(r, replace, play);
}
/**
* Adds songs to the queue. It is possible to request a clear of the current one, and to start the playback once done.
*
* @param runnable
* The runnable that will be responsible of inserting the songs into the queue
* @param replace
* If true, clears the queue before inserting
* @param play
* If true, starts playing once added
* @throws MPDServerException
*/
public void add(Runnable runnable, boolean replace, boolean play) throws MPDServerException {
int oldSize = 0;
String status = null;
if (replace) {
status = getStatus().getState();
stop();
getPlaylist().clear();
} else if (play) {
oldSize = getPlaylist().size();
}
runnable.run();
if (replace) {
if (play || MPDStatus.MPD_STATE_PLAYING.equals(status)) {
play();
}
} else if (play) {
try {
int id = getPlaylist().getByIndex(oldSize).getSongId();
skipToId(id);
play();
} catch (NullPointerException e) {
// If song adding fails, don't crash !
}
}
}
public void addToPlaylist(String playlistName, Artist artist) throws MPDServerException {
addToPlaylist(playlistName, artist, null);
}
public void addToPlaylist(String playlistName, Album album) throws MPDServerException {
addToPlaylist(playlistName, null, album);
}
public void addToPlaylist(String playlistName, Artist artist, Album album) throws MPDServerException {
addToPlaylist(playlistName, new ArrayList<Music>(getSongs(artist, album)));
}
public void addToPlaylist(String playlistName, Music music) throws MPDServerException {
final ArrayList<Music> songs = new ArrayList<Music>();
songs.add(music);
addToPlaylist(playlistName, songs);
}
}
| JMPDComm/src/org/a0z/mpd/MPD.java | package org.a0z.mpd;
import android.content.Context;
import android.util.Log;
import org.a0z.mpd.exception.MPDClientException;
import org.a0z.mpd.exception.MPDConnectionException;
import org.a0z.mpd.exception.MPDServerException;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.*;
/**
* MPD Server controller.
*
* @version $Id: MPD.java 2716 2004-11-20 17:37:20Z galmeida $
*/
public class MPD {
private MPDConnection mpdConnection;
private MPDConnection mpdIdleConnection;
private MPDStatus mpdStatus;
private MPDPlaylist playlist;
private Directory rootDirectory;
static private boolean useAlbumArtist = false;
static private boolean sortByTrackNumber = true;
static private boolean sortAlbumsByYear = false;
static private boolean showArtistAlbumCount = false;
static private boolean showAlbumTrackCount = true;
static private Context applicationContext = null;
static public Context getApplicationContext() {
return applicationContext;
}
static public void setApplicationContext(Context context) {
applicationContext = context;
}
static public boolean useAlbumArtist() {
return useAlbumArtist;
}
static public boolean sortAlbumsByYear() {
return sortAlbumsByYear;
}
static public boolean sortByTrackNumber() {
return sortByTrackNumber;
}
static public boolean showArtistAlbumCount() {
return showArtistAlbumCount;
}
static public boolean showAlbumTrackCount() {
return showAlbumTrackCount;
}
static public void setUseAlbumArtist(boolean v) {
useAlbumArtist=v;
}
static public void setSortByTrackNumber(boolean v) {
sortByTrackNumber=v;
}
static public void setSortAlbumsByYear(boolean v) {
sortAlbumsByYear=v;
}
static public void setShowArtistAlbumCount(boolean v) {
showArtistAlbumCount=v;
}
static public void setShowAlbumTrackCount(boolean v) {
showAlbumTrackCount=v;
}
/**
* Constructs a new MPD server controller without connection.
*/
public MPD() {
this.playlist = new MPDPlaylist(this);
this.mpdStatus = new MPDStatus();
this.rootDirectory = Directory.makeRootDirectory(this);
}
/**
* Constructs a new MPD server controller.
*
* @param server
* server address or host name
* @param port
* server port
* @throws MPDServerException
* if an error occur while contacting server
* @throws UnknownHostException
*/
public MPD(String server, int port) throws MPDServerException, UnknownHostException {
this();
connect(server, port);
}
/**
* Constructs a new MPD server controller.
*
* @param server
* server address or host name
* @param port
* server port
* @throws MPDServerException
* if an error occur while contacting server
*/
public MPD(InetAddress server, int port) throws MPDServerException {
this();
connect(server, port);
}
/**
* Retrieves <code>MPDConnection</code>.
*
* @return <code>MPDConnection</code>.
*/
public MPDConnection getMpdConnection() {
return this.mpdConnection;
}
MPDConnection getMpdIdleConnection() {
return this.mpdIdleConnection;
}
/**
* Wait for server changes using "idle" command on the dedicated connection.
*
* @return Data readed from the server.
* @throws MPDServerException if an error occur while contacting server
*/
public List<String> waitForChanges() throws MPDServerException {
while (mpdIdleConnection != null && mpdIdleConnection.isConnected()) {
List<String> data = mpdIdleConnection
.sendAsyncCommand(MPDCommand.MPD_CMD_IDLE);
if (data.isEmpty()) {
continue;
}
return data;
}
throw new MPDConnectionException("IDLE connection lost");
}
public boolean isMpdConnectionNull() {
return (this.mpdConnection == null);
}
/**
* Increases or decreases volume by <code>modifier</code> amount.
*
* @param modifier
* volume adjustment
* @throws MPDServerException
* if an error occur while contacting server
*/
public void adjustVolume(int modifier) throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
// calculate final volume (clip value with [0, 100])
int vol = getVolume() + modifier;
vol = Math.max(MPDCommand.MIN_VOLUME, Math.min(MPDCommand.MAX_VOLUME, vol));
mpdConnection.sendCommand(MPDCommand.MPD_CMD_SET_VOLUME, Integer.toString(vol));
}
/**
* Clears error message.
*
* @throws MPDServerException
* if an error occur while contacting server.
*/
public void clearError() throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
mpdConnection.sendCommand(MPDCommand.MPD_CMD_CLEARERROR);
}
/**
* Connects to a MPD server.
*
* @param server
* server address or host name
* @param port
* server port
* @throws MPDServerException
* if an error occur while contacting server
* @throws UnknownHostException
*/
public final void connect(String server, int port) throws MPDServerException, UnknownHostException {
InetAddress adress = InetAddress.getByName(server);
connect(adress, port);
}
/**
* Connects to a MPD server.
*
* @param server
* server address or host name
* @param port
* server port
*/
public final void connect(InetAddress server, int port) throws MPDServerException {
this.mpdConnection = new MPDConnection(server, port);
this.mpdIdleConnection = new MPDConnection(server, port, 1000);
}
/**
* Connects to a MPD server.
*
* @param server
* server address or host name and port (server:port)
* @throws MPDServerException
* if an error occur while contacting server
* @throws UnknownHostException
*/
public final void connect(String server) throws MPDServerException, UnknownHostException {
int port = MPDCommand.DEFAULT_MPD_PORT;
String host = null;
if (server.indexOf(':') != -1) {
host = server.substring(0, server.lastIndexOf(':'));
port = Integer.parseInt(server.substring(server.lastIndexOf(':') + 1));
} else {
host = server;
}
connect(host, port);
}
/**
* Disconnects from server.
*
* @throws MPDServerException
* if an error occur while closing connection
*/
public void disconnect() throws MPDServerException {
MPDServerException ex = null;
if (mpdConnection != null && mpdConnection.isConnected()) {
try {
mpdConnection.sendCommand(MPDCommand.MPD_CMD_CLOSE);
} catch (MPDServerException e) {
ex = e;
}
}
if (mpdConnection != null && mpdConnection.isConnected()) {
try {
mpdConnection.disconnect();
} catch (MPDServerException e) {
ex = (ex != null) ? ex : e;// Always keep first non null
// exception
}
}
if (mpdIdleConnection != null && mpdIdleConnection.isConnected()) {
try {
mpdIdleConnection.disconnect();
} catch (MPDServerException e) {
ex = (ex != null) ? ex : e;// Always keep non null first
// exception
}
}
if (ex != null) {
throw ex;
}
}
/**
* Similar to <code>search</code>,<code>find</code> looks for exact matches in the MPD database.
*
* @param type
* type of search. Should be one of the following constants: MPD_FIND_ARTIST, MPD_FIND_ALBUM
* @param string
* case-insensitive locator string. Anything that exactly matches <code>string</code> will be returned in the results.
* @return a Collection of <code>Music</code>
* @throws MPDServerException
* if an error occur while contacting server
* @see org.a0z.mpd.Music
*/
public List<Music> find(String type, String string) throws MPDServerException {
return genericSearch(MPDCommand.MPD_CMD_FIND, type, string);
}
public List<Music> find(String[] args) throws MPDServerException {
return genericSearch(MPDCommand.MPD_CMD_FIND, args, true);
}
// Returns a pattern where all punctuation characters are escaped.
private List<Music> genericSearch(String searchCommand, String type, String strToFind) throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
List<String> response = mpdConnection.sendCommand(searchCommand, type, strToFind);
return Music.getMusicFromList(response, true);
}
private List<Music> genericSearch(String searchCommand, String args[], boolean sort) throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
return Music.getMusicFromList(mpdConnection.sendCommand(searchCommand, args), sort);
}
/**
* Retrieves a database directory listing of the base of the database directory path.
*
* @return a <code>Collection</code> of <code>Music</code> and <code>Directory</code> representing directory entries.
* @throws MPDServerException
* if an error occur while contacting server.
* @see Music
* @see Directory
*/
public List<FilesystemTreeEntry> getDir() throws MPDServerException {
return getDir(null);
}
/**
* Retrieves a database directory listing of <code>path</code> directory.
*
* @param path Directory to be listed.
* @return a <code>Collection</code> of <code>Music</code> and <code>Directory</code> representing directory entries.
* @throws MPDServerException
* if an error occur while contacting server.
* @see Music
* @see Directory
*/
public List<FilesystemTreeEntry> getDir(String path) throws MPDServerException {
if(!isConnected())
throw new MPDServerException("MPD Connection is not established");
List<String> resonse = mpdConnection.sendCommand(MPDCommand.MPD_CMD_LSDIR, path);
LinkedList<String> lineCache = new LinkedList<String>();
LinkedList<FilesystemTreeEntry> result = new LinkedList<FilesystemTreeEntry>();
for (String line : resonse) {
// file-elements are the only ones using fileCache,
// therefore if something new begins and the cache
// contains data, its music
if ((line.startsWith("file: ") || line.startsWith("directory: ") || line.startsWith("playlist: ")) && lineCache.size() > 0) {
result.add(new Music(lineCache));
lineCache.clear();
}
if (line.startsWith("playlist: ")) {
line = line.substring("playlist: ".length());
result.add(new PlaylistFile(line));
} else if (line.startsWith("directory: ")) {
line = line.substring("directory: ".length());
result.add(rootDirectory.makeDirectory(line));
} else if (line.startsWith("file: ")) {
lineCache.add(line);
}
}
if (lineCache.size() > 0) {
result.add(new Music(lineCache));
}
return result;
}
/**
* Returns MPD server version.
*
* @return MPD Server version.
*/
public String getMpdVersion() throws MPDServerException {
if(!isConnected())
throw new MPDServerException("MPD Connection is not established");
int[] version = mpdConnection.getMpdVersion();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < version.length; i++) {
sb.append(version[i]);
if (i < (version.length - 1))
sb.append(".");
}
return sb.toString();
}
/**
* Retrieves <code>playlist</code>.
*
* @return playlist.
*/
public MPDPlaylist getPlaylist() {
return this.playlist;
}
/**
* Retrieves statistics for the connected server.
*
* @return statistics for the connected server.
* @throws MPDServerException
* if an error occur while contacting server.
*/
public MPDStatistics getStatistics() throws MPDServerException {
List<String> response = mpdConnection.sendCommand(MPDCommand.MPD_CMD_STATISTICS);
return new MPDStatistics(response);
}
/**
* Retrieves status of the connected server.
*
* @return status of the connected server.
* @throws MPDServerException
* if an error occur while contacting server.
*/
public MPDStatus getStatus() throws MPDServerException {
if(!isConnected())
throw new MPDServerException("MPD Connection is not established");
List<String> response = mpdConnection.sendCommand(MPDCommand.MPD_CMD_STATUS);
mpdStatus.updateStatus(response);
return mpdStatus;
}
/**
* Retrieves current volume.
*
* @return current volume.
* @throws MPDServerException
* if an error occur while contacting server.
*/
public int getVolume() throws MPDServerException {
return this.getStatus().getVolume();
}
/**
* Returns true when connected and false when not connected.
*
* @return true when connected and false when not connected
*/
public boolean isConnected() {
if (mpdConnection == null)
return false;
return mpdConnection.isConnected() ;
}
/**
* List all albums from database.
*
* @return <code>Collection</code> with all album names from database.
* @throws MPDServerException
* if an error occur while contacting server.
*/
public List<String> listAlbums() throws MPDServerException {
return listAlbums(null, false, false);
}
/**
* List all albums from database.
*
* @param useAlbumArtist
* use AlbumArtist instead of Artist
* @return <code>Collection</code> with all album names from database.
* @throws MPDServerException
* if an error occur while contacting server.
*/
public List<String> listAlbums(boolean useAlbumArtist) throws MPDServerException {
return listAlbums(null, useAlbumArtist, false);
}
/**
* List all albums from a given artist, including an entry for songs with no album tag.
*
* @param artist
* artist to list albums
* @param useAlbumArtist
* use AlbumArtist instead of Artist
* @return <code>Collection</code> with all album names from database.
* @throws MPDServerException
* if an error occur while contacting server.
*/
public List<String> listAlbums(String artist, boolean useAlbumArtist) throws MPDServerException {
return listAlbums(artist, useAlbumArtist, true);
}
/*
* get raw command String for listAlbums
*/
public MPDCommand listAlbumsCommand(String artist, boolean useAlbumArtist) {
if (useAlbumArtist) {
return new MPDCommand(MPDCommand.MPD_CMD_LIST_TAG, MPDCommand.MPD_TAG_ALBUM, MPDCommand.MPD_TAG_ALBUM_ARTIST, artist);
} else {
return new MPDCommand(MPDCommand.MPD_CMD_LIST_TAG, MPDCommand.MPD_TAG_ALBUM, artist);
}
}
/**
* List all albums from a given artist.
*
* @param artist
* artist to list albums
* @param useAlbumArtist
* use AlbumArtist instead of Artist
* @param includeUnknownAlbum
* include an entry for songs with no album tag
* @return <code>Collection</code> with all album names from the given artist present in database.
* @throws MPDServerException
* if an error occur while contacting server.
*/
public List<String> listAlbums(String artist, boolean useAlbumArtist, boolean includeUnknownAlbum) throws MPDServerException {
if(!isConnected())
throw new MPDServerException("MPD Connection is not established");
boolean foundSongWithoutAlbum = false;
List<String> response =
mpdConnection.sendCommand
(listAlbumsCommand(artist, useAlbumArtist));
ArrayList<String> result = new ArrayList<String>();
for (String line : response) {
String name = line.substring("Album: ".length());
if (name.length() > 0) {
result.add(name);
}else{
foundSongWithoutAlbum = true;
}
}
Collections.sort(result);
// add a single blank entry to host all songs without an album set
if((includeUnknownAlbum == true) && (foundSongWithoutAlbum == true)) {
result.add("");
}
return result;
}
private Long[] getAlbumDetails(String artist, String album, boolean useAlbumArtistTag) throws MPDServerException {
if (!isConnected()) {
throw new MPDServerException("MPD Connection is not established");
}
Long[] result = new Long[3];
result[0] = 0l;
result[1] = 0l;
result[2] = 0l;
if (MPD.showAlbumTrackCount()) {
String[] args = new String[4];
args[0] = useAlbumArtistTag ? MPDCommand.MPD_TAG_ALBUM_ARTIST : MPDCommand.MPD_TAG_ARTIST;
args[1] = artist;
args[2] = MPDCommand.MPD_TAG_ALBUM;
args[3] = album;
List<String> list = mpdConnection.sendCommand("count", args);
for (String line : list) {
if (line.startsWith("songs: ")) {
result[0] = Long.parseLong(line.substring("songs: ".length()));
} else if (line.startsWith("playtime: ")) {
result[1] = Long.parseLong(line.substring("playtime: ".length()));
}
}
}
if (MPD.sortAlbumsByYear()) {
String[] args = new String[6];
args[0] = useAlbumArtistTag ? MPDCommand.MPD_TAG_ALBUM_ARTIST : MPDCommand.MPD_TAG_ARTIST;
args[1] = artist;
args[2] = MPDCommand.MPD_TAG_ALBUM;
args[3] = album;
args[4] = "track";
args[5] = "1";
List<Music> songs = find(args);
if (null==songs || songs.isEmpty()) {
args[5] = "01";
songs = find(args);
}
if (null==songs || songs.isEmpty()) {
args[5] = "1";
songs = search(args);
}
if (null!=songs && !songs.isEmpty()) {
result[2]=songs.get(0).getDate();
}
}
return result;
}
public int getAlbumCount(Artist artist, boolean useAlbumArtistTag) throws MPDServerException {
return listAlbums(artist.getName(), useAlbumArtistTag).size();
}
public int getAlbumCount(String artist, boolean useAlbumArtistTag) throws MPDServerException {
if (mpdConnection == null) {
throw new MPDServerException("MPD Connection is not established");
}
return listAlbums(artist, useAlbumArtistTag).size();
}
/**
* Recursively retrieves all songs and directories.
*
* @param dir
* directory to list.
* @throws MPDServerException
* if an error occur while contacting server.
* @return <code>FileStorage</code> with all songs and directories.
*/
/*
public Directory listAllFiles(String dir) throws MPDServerException {
if(!isConnected())
throw new MPDServerException("MPD Connection is not established");
List<String> list = mpdConnection.sendCommand(MPD_CMD_LISTALL, dir);
for (String line : list) {
if (line.startsWith("directory: ")) {
rootDirectory.makeDirectory(line.substring("directory: ".length()));
} else if (line.startsWith("file: ")) {
rootDirectory.addFile(new Music(line.substring("file: ".length())));
}
}
return rootDirectory;
}
*/
/**
* List all genre names from database.
*
* @return artist names from database.
*
* @throws MPDServerException if an error occur while contacting server.
*/
public List<String> listGenres() throws MPDServerException {
return listGenres(true);
}
/**
* List all genre names from database.
*
* @param sortInsensitive
* boolean for insensitive sort when true
* @return artist names from database.
* @throws MPDServerException
* if an error occur while contacting server.
*/
public List<String> listGenres(boolean sortInsensitive) throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
List<String> response = mpdConnection.sendCommand(MPDCommand.MPD_CMD_LIST_TAG, MPDCommand.MPD_TAG_GENRE);
ArrayList<String> result = new ArrayList<String>();
for (String s : response) {
String name = s.substring("Genre: ".length());
if (name.length() > 0)
result.add(name);
}
if (sortInsensitive)
Collections.sort(result, String.CASE_INSENSITIVE_ORDER);
else
Collections.sort(result);
return result;
}
/**
* List all artist names from database.
*
* @return artist names from database.
* @throws MPDServerException
* if an error occur while contacting server.
*/
public List<String> listArtists() throws MPDServerException {
return listArtists(true);
}
/**
* List all artist names from database.
*
* @param sortInsensitive
* boolean for insensitive sort when true
* @return artist names from database.
* @throws MPDServerException
* if an error occur while contacting server.
*/
public List<String> listArtists(boolean sortInsensitive) throws MPDServerException {
if(!isConnected())
throw new MPDServerException("MPD Connection is not established");
List<String> response = mpdConnection.sendCommand(MPDCommand.MPD_CMD_LIST_TAG, MPDCommand.MPD_TAG_ARTIST);
ArrayList<String> result = new ArrayList<String>();
for (String s : response) {
String name = s.substring("Artist: ".length());
if (name.length() > 0)
result.add(name);
}
if (sortInsensitive)
Collections.sort(result, String.CASE_INSENSITIVE_ORDER);
else
Collections.sort(result);
return result;
}
/**
* List all artist names from database.
*
* @return artist names from database.
* @throws MPDServerException
* if an error occur while contacting server.
*/
public List<String> listArtists(String genre) throws MPDServerException {
return listArtists(genre, true);
}
/**
* List all artist names from database.
*
* @param sortInsensitive
* boolean for insensitive sort when true
* @return artist names from database.
* @throws MPDServerException
* if an error occur while contacting server.
*/
public List<String> listArtists(String genre, boolean sortInsensitive) throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
List<String> response = mpdConnection.sendCommand(MPDCommand.MPD_CMD_LIST_TAG, MPDCommand.MPD_TAG_ARTIST, MPDCommand.MPD_TAG_GENRE, genre);
ArrayList<String> result = new ArrayList<String>();
for (String s : response) {
String name = s.substring("Artist: ".length());
if (name.length() > 0)
result.add(name);
}
if (sortInsensitive)
Collections.sort(result, String.CASE_INSENSITIVE_ORDER);
else
Collections.sort(result);
return result;
}
/**
* List all album artist names from database.
*
* @return album artist names from database.
* @throws MPDServerException
* if an error occur while contacting server.
*/
public List<String> listAlbumArtists() throws MPDServerException {
if(!isConnected())
throw new MPDServerException("MPD Connection is not established");
List<String> response = mpdConnection.sendCommand(MPDCommand.MPD_CMD_LIST_TAG, MPDCommand.MPD_TAG_ALBUM_ARTIST);
ArrayList<String> result = new ArrayList<String>();
for (String s : response) {
String name = s.substring("albumartist: ".length());
if (name.length() > 0)
result.add(name);
}
Collections.sort(result);
return result;
}
/**
* List all album artist names from database.
*
* @return album artist names from database.
* @throws MPDServerException
* if an error occur while contacting server.
*/
public List<String> listAlbumArtists(Genre genre) throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
List<String> response = mpdConnection.sendCommand(MPDCommand.MPD_CMD_LIST_TAG, MPDCommand.MPD_TAG_ALBUM_ARTIST, MPDCommand.MPD_TAG_GENRE,
genre.getName());
ArrayList<String> result = new ArrayList<String>();
for (String s : response) {
String name = s.substring("albumartist: ".length());
if (name.length() > 0)
result.add(name);
}
Collections.sort(result);
return result;
}
/**
* Jumps to next playlist track.
*
* @throws MPDServerException
* if an error occur while contacting server.
*/
public void next() throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
mpdConnection.sendCommand(MPDCommand.MPD_CMD_NEXT);
}
/**
* Authenticate using password.
*
* @param password
* password.
* @throws MPDServerException
* if an error occur while contacting server.
*/
public void password(String password) throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
mpdConnection.sendCommand(MPDCommand.MPD_CMD_PASSWORD, password);
mpdIdleConnection.sendCommand(MPDCommand.MPD_CMD_PASSWORD, password);
}
/**
* Pauses/Resumes music playing.
*
* @throws MPDServerException
* if an error occur while contacting server.
*/
public void pause() throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
mpdConnection.sendCommand(MPDCommand.MPD_CMD_PAUSE);
}
/**
* Starts playing music.
*
* @throws MPDServerException
* if an error occur while contacting server.
*/
public void play() throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
mpdConnection.sendCommand(MPDCommand.MPD_CMD_PLAY);
}
/**
* Plays previous playlist music.
*
* @throws MPDServerException
* if an error occur while contacting server..
*/
public void previous() throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
mpdConnection.sendCommand(MPDCommand.MPD_CMD_PREV);
}
/**
* Tells server to refresh database.
*
* @throws MPDServerException
* if an error occur while contacting server.
*/
public void refreshDatabase() throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
mpdConnection.sendCommand(MPDCommand.MPD_CMD_REFRESH);
}
/**
* Similar to <code>find</code>,<code>search</code> looks for partial matches in the MPD database.
*
* @param type
* type of search. Should be one of the following constants: MPD_SEARCH_ARTIST, MPD_SEARCH_TITLE, MPD_SEARCH_ALBUM,
* MPD_SEARCG_FILENAME
* @param string
* case-insensitive locator string. Anything that contains <code>string</code> will be returned in the results.
* @return a Collection of <code>Music</code>.
* @throws MPDServerException
* if an error occur while contacting server.
* @see org.a0z.mpd.Music
*/
public Collection<Music> search(String type, String string) throws MPDServerException {
return genericSearch(MPDCommand.MPD_CMD_SEARCH, type, string);
}
public List<Music> search(String[] args) throws MPDServerException {
return genericSearch(MPDCommand.MPD_CMD_SEARCH, args, true);
}
/**
* Seeks music to the position.
*
* @param songId
* music id in playlist.
* @param position
* song position in seconds.
* @throws MPDServerException
* if an error occur while contacting server.
*/
public void seekById(int songId, long position) throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
mpdConnection.sendCommand(MPDCommand.MPD_CMD_SEEK_ID, Integer.toString(songId), Long.toString(position));
}
/**
* Seeks music to the position.
*
* @param index
* music position in playlist.
* @param position
* song position in seconds.
* @throws MPDServerException
* if an error occur while contacting server.
*/
public void seekByIndex(int index, long position) throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
mpdConnection.sendCommand(MPDCommand.MPD_CMD_SEEK, Integer.toString(index), Long.toString(position));
}
/**
* Seeks current music to the position.
*
* @param position
* song position in seconds
* @throws MPDServerException
* if an error occur while contacting server.
*/
public void seek(long position) throws MPDServerException {
seekById(this.getStatus().getSongId(), position);
}
/**
* Enabled or disable random.
*
* @param random
* if true random will be enabled, if false random will be disabled.
* @throws MPDServerException
* if an error occur while contacting server.
*/
public void setRandom(boolean random) throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
mpdConnection.sendCommand(MPDCommand.MPD_CMD_RANDOM, random ? "1" : "0");
}
/**
* Enabled or disable repeating.
*
* @param repeat
* if true repeating will be enabled, if false repeating will be disabled.
* @throws MPDServerException
* if an error occur while contacting server.
*/
public void setRepeat(boolean repeat) throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
mpdConnection.sendCommand(MPDCommand.MPD_CMD_REPEAT, repeat ? "1" : "0");
}
/**
* Enabled or disable single mode.
*
* @param single
* if true single mode will be enabled, if false single mode will be disabled.
* @throws MPDServerException
* if an error occur while contacting server.
*/
public void setSingle(boolean single) throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
mpdConnection.sendCommand(MPDCommand.MPD_CMD_SINGLE, single ? "1" : "0");
}
/**
* Enabled or disable consuming.
*
* @param consume
* if true song consuming will be enabled, if false song consuming will be disabled.
* @throws MPDServerException
* if an error occur while contacting server.
*/
public void setConsume(boolean consume) throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
mpdConnection.sendCommand(MPDCommand.MPD_CMD_CONSUME, consume ? "1" : "0");
}
/**
* Sets volume to <code>volume</code>.
*
* @param volume
* new volume value, must be in 0-100 range.
* @throws MPDServerException
* if an error occur while contacting server.
*/
public void setVolume(int volume) throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
int vol = Math.max(MPDCommand.MIN_VOLUME, Math.min(MPDCommand.MAX_VOLUME, volume));
mpdConnection.sendCommand(MPDCommand.MPD_CMD_SET_VOLUME, Integer.toString(vol));
}
/**
* Kills server.
*
* @throws MPDServerException
* if an error occur while contacting server.
*/
public void shutdown() throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
mpdConnection.sendCommand(MPDCommand.MPD_CMD_KILL);
}
/**
* Jumps to track <code>position</code> from playlist.
*
* @param position
* track number.
* @throws MPDServerException
* if an error occur while contacting server.
* @see #skipToId(int)
*/
public void skipToPositon(int position) throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
mpdConnection.sendCommand(MPDCommand.MPD_CMD_PLAY, Integer.toString(position));
}
/**
* Skip to song with specified <code>id</code>.
*
* @param id
* song id.
* @throws MPDServerException
* if an error occur while contacting server.
*/
public void skipToId(int id) throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
mpdConnection.sendCommand(MPDCommand.MPD_CMD_PLAY_ID, Integer.toString(id));
}
/**
* Stops music playing.
*
* @throws MPDServerException
* if an error occur while contacting server.
*/
public void stop() throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
mpdConnection.sendCommand(MPDCommand.MPD_CMD_STOP);
}
/**
* Retrieves root directory.
*
* @return root directory.
*/
public Directory getRootDirectory() {
return rootDirectory;
}
/**
* Sets cross-fade.
*
* @param time
* cross-fade time in seconds. 0 to disable cross-fade.
* @throws MPDServerException
* if an error occur while contacting server.
*/
public void setCrossfade(int time) throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
mpdConnection.sendCommand(MPDCommand.MPD_CMD_CROSSFADE, Integer.toString(Math.max(0, time)));
}
/**
* Returns the available outputs
*
* @return List of available outputs
*/
public List<MPDOutput> getOutputs() throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
List<MPDOutput> result = new LinkedList<MPDOutput>();
List<String> response = mpdConnection.sendCommand(MPDCommand.MPD_CMD_OUTPUTS);
LinkedList<String> lineCache = new LinkedList<String>();
for (String line : response) {
if (line.startsWith("outputid: ")) {
if (lineCache.size() != 0) {
result.add(new MPDOutput(lineCache));
lineCache.clear();
}
}
lineCache.add(line);
}
if (lineCache.size() != 0) {
result.add(new MPDOutput(lineCache));
}
return result;
}
/**
* Returns a list of all available playlists
*/
public List<Item> getPlaylists() throws MPDServerException {
return getPlaylists(false);
}
/**
* Returns a list of all available playlists
*
* @param sort whether the return list should be sorted
*/
public List<Item> getPlaylists(boolean sort) throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
List<Item> result = new ArrayList<Item>();
List<String> response = mpdConnection.sendCommand(MPDCommand.MPD_CMD_LISTPLAYLISTS);
for(String line : response) {
if(line.startsWith("playlist"))
result.add(new Playlist(line.substring("playlist: ".length())));
}
if (sort)
Collections.sort(result);
return result;
}
public void enableOutput(int id) throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
mpdConnection.sendCommand(MPDCommand.MPD_CMD_OUTPUTENABLE, Integer.toString(id));
}
public void disableOutput(int id) throws MPDServerException {
if (!isConnected())
throw new MPDServerException("MPD Connection is not established");
mpdConnection.sendCommand(MPDCommand.MPD_CMD_OUTPUTDISABLE, Integer.toString(id));
}
public List<Music> getSongs(Artist artist, Album album) throws MPDServerException {
List<Music> aasongs = getSongs(artist, album, true); // album artist
if (aasongs == null || aasongs.size() == 0)
return getSongs(artist, album, false); // artist
else
return aasongs;
}
public List<Music> getSongs(Artist artist, Album album, boolean useAlbumArtist) throws MPDServerException {
boolean haveArtist = (null != artist);
boolean haveAlbum = (null != album) && !(album instanceof UnknownAlbum);
String[] search = null;
int pos=0;
if (haveAlbum || haveArtist) {
search=new String[haveAlbum && haveArtist ? 4 : 2];
if (haveArtist) {
search[pos++] = useAlbumArtist ? MPDCommand.MPD_TAG_ALBUM_ARTIST : MPDCommand.MPD_FIND_ARTIST;
search[pos++]=artist.getName();
}
if (haveAlbum) {
search[pos++]=MPDCommand.MPD_FIND_ALBUM;
search[pos++]=album.getName();
}
}
List<Music> songs=find(search);
if(album instanceof UnknownAlbum) {
// filter out any songs with which have the album tag set
Iterator<Music> iter = songs.iterator();
while (iter.hasNext()) {
if (iter.next().getAlbum() != null) iter.remove();
}
}
if (null!=songs) {
Collections.sort(songs);
}
return songs;
}
public List<Album> getAlbums(Artist artist) throws MPDServerException {
return getAlbums(artist, true);
}
public List<Album> getAlbums(Artist artist, boolean trackCountNeeded) throws MPDServerException {
return getAlbums(artist, trackCountNeeded, useAlbumArtist);
}
public List<Album> getAlbums(Artist artist, boolean trackCountNeeded,
boolean _useAlbumArtist) throws MPDServerException {
List<String> albumNames = null;
List<Album> albums = null;
final Artist unknownArtist = UnknownArtist.instance;
if(artist != null) {
albumNames = listAlbums(artist.getName(), _useAlbumArtist);
}else{
albumNames = listAlbums(false);
artist = unknownArtist;
}
if (null!=albumNames && !albumNames.isEmpty()) {
albums=new ArrayList<Album>();
for (String album : albumNames) {
if(album == "") {
// add a blank entry to host all songs without an album set
albums.add(UnknownAlbum.instance);
}else{
long songCount = 0;
long duration = 0;
long year = 0;
if (unknownArtist != artist && ((MPD.showAlbumTrackCount() && trackCountNeeded) || MPD.sortAlbumsByYear())) {
try {
Long[] albumDetails = getAlbumDetails(artist.getName(), album, _useAlbumArtist);
if (null!=albumDetails && 3==albumDetails.length) {
songCount=albumDetails[0];
duration=albumDetails[1];
year=albumDetails[2];
}
} catch (MPDServerException e) {
}
}
albums.add(new Album(album, songCount, duration, year, artist));
}
}
}
if (null!=albums) {
Collections.sort(albums);
}
return albums;
}
public List<Genre> getGenres() throws MPDServerException {
List<String> genreNames = listGenres();
List<Genre> genres = null;
if (null != genreNames && !genreNames.isEmpty()) {
genres = new ArrayList<Genre>();
for (String genre : genreNames) {
genres.add(new Genre(genre));
}
}
if (null != genres) {
Collections.sort(genres);
}
return genres;
}
public List<Artist> getArtists() throws MPDServerException {
List<String> artistNames=MPD.useAlbumArtist() ? listAlbumArtists() : listArtists(true);
List<Artist> artists = null;
if (null!=artistNames && !artistNames.isEmpty()) {
artists=new ArrayList<Artist>();
for (String artist : artistNames) {
artists.add(new Artist(artist, MPD.showArtistAlbumCount() ? getAlbumCount(artist, useAlbumArtist) : 0));
}
}
if (null!=artists) {
Collections.sort(artists);
}
return artists;
}
public List<Artist> getArtists(Genre genre) throws MPDServerException {
List<String> artistNames = MPD.useAlbumArtist() ? listAlbumArtists(genre) : listArtists(genre.getName(), true);
List<Artist> artists = null;
if (null != artistNames && !artistNames.isEmpty()) {
artists = new ArrayList<Artist>();
for (String artist : artistNames) {
artists.add(new Artist(artist, MPD.showArtistAlbumCount() ? getAlbumCount(artist, useAlbumArtist) : 0));
}
}
if (null != artists) {
Collections.sort(artists);
}
return artists;
}
public List<Music> getPlaylistSongs(String playlistName) throws MPDServerException {
String args[]=new String[1];
args[0]=playlistName;
List<Music> music=genericSearch(MPDCommand.MPD_CMD_PLAYLIST_INFO, args, false);
for (int i=0; i<music.size(); ++i) {
music.get(i).setSongId(i);
}
return music;
}
public void movePlaylistSong(String playlistName, int from, int to) throws MPDServerException {
getMpdConnection().sendCommand(MPDCommand.MPD_CMD_PLAYLIST_MOVE, playlistName, Integer.toString(from), Integer.toString(to));
}
public void removeFromPlaylist(String playlistName, Integer pos) throws MPDServerException {
getMpdConnection().sendCommand(MPDCommand.MPD_CMD_PLAYLIST_DEL, playlistName, Integer.toString(pos));
}
public void addToPlaylist(String playlistName, Collection<Music> c) throws MPDServerException {
if (null==c || c.size()<1) {
return;
}
for (Music m : c) {
getMpdConnection().queueCommand(MPDCommand.MPD_CMD_PLAYLIST_ADD, playlistName, m.getFullpath());
}
getMpdConnection().sendCommandQueue();
}
public void addToPlaylist(String playlistName, FilesystemTreeEntry entry) throws MPDServerException {
getMpdConnection().sendCommand(MPDCommand.MPD_CMD_PLAYLIST_ADD, playlistName, entry.getFullpath());
}
public void add(Artist artist) throws MPDServerException {
add(artist, false, false);
}
public void add(Artist artist, Album album) throws MPDServerException {
add(artist, album, false, false);
}
public void add(Music music) throws MPDServerException {
add(music, false, false);
}
public void add(String playlist) throws MPDServerException {
add(playlist, false, false);
}
public void add(Artist artist, boolean replace, boolean play) throws MPDServerException {
add(artist, null, replace, play);
}
public void add(final FilesystemTreeEntry music, boolean replace, boolean play) throws MPDServerException {
final Runnable r = new Runnable() {
@Override
public void run() {
try {
if (music instanceof Music) {
getPlaylist().add(music);
} else if (music instanceof PlaylistFile) {
getPlaylist().load(music.getFullpath());
}
} catch (MPDServerException e) {
e.printStackTrace();
}
}
};
add(r, replace, play);
}
public void add(final Artist artist, final Album album, boolean replace, boolean play) throws MPDServerException {
final Runnable r = new Runnable() {
@Override
public void run() {
try {
final ArrayList<Music> songs = new ArrayList<Music>(getSongs(artist, album));
getPlaylist().addAll(songs);
} catch (MPDServerException e) {
e.printStackTrace();
}
}
};
add(r, replace, play);
}
public void add(final String playlist, boolean replace, boolean play) throws MPDServerException {
final Runnable r = new Runnable() {
@Override
public void run() {
try {
getPlaylist().load(playlist);
} catch (MPDServerException e) {
e.printStackTrace();
}
}
};
add(r, replace, play);
}
public void add(final URL stream, boolean replace, boolean play) throws MPDServerException {
final Runnable r = new Runnable() {
@Override
public void run() {
try {
getPlaylist().add(stream);
} catch (MPDServerException e) {
e.printStackTrace();
} catch (MPDClientException e) {
e.printStackTrace();
}
}
};
add(r, replace, play);
}
public void add(final Directory directory, boolean replace, boolean play) throws MPDServerException {
final Runnable r = new Runnable() {
@Override
public void run() {
try {
getPlaylist().add(directory);
} catch (MPDServerException e) {
e.printStackTrace();
}
}
};
add(r, replace, play);
}
/**
* Adds songs to the queue. It is possible to request a clear of the current one, and to start the playback once done.
*
* @param runnable
* The runnable that will be responsible of inserting the songs into the queue
* @param replace
* If true, clears the queue before inserting
* @param play
* If true, starts playing once added
* @throws MPDServerException
*/
public void add(Runnable runnable, boolean replace, boolean play) throws MPDServerException {
int oldSize = 0;
String status = null;
if (replace) {
status = getStatus().getState();
stop();
getPlaylist().clear();
} else if (play) {
oldSize = getPlaylist().size();
}
runnable.run();
if (replace) {
if (play || MPDStatus.MPD_STATE_PLAYING.equals(status)) {
play();
}
} else if (play) {
try {
int id = getPlaylist().getByIndex(oldSize).getSongId();
skipToId(id);
play();
} catch (NullPointerException e) {
// If song adding fails, don't crash !
}
}
}
public void addToPlaylist(String playlistName, Artist artist) throws MPDServerException {
addToPlaylist(playlistName, artist, null);
}
public void addToPlaylist(String playlistName, Album album) throws MPDServerException {
addToPlaylist(playlistName, null, album);
}
public void addToPlaylist(String playlistName, Artist artist, Album album) throws MPDServerException {
addToPlaylist(playlistName, new ArrayList<Music>(getSongs(artist, album)));
}
public void addToPlaylist(String playlistName, Music music) throws MPDServerException {
final ArrayList<Music> songs = new ArrayList<Music>();
songs.add(music);
addToPlaylist(playlistName, songs);
}
}
| fix albums list covers by calling MPD for albumartists of albums
not used on the full album list
it will not fix that the found albums only show the artist's tracks
| JMPDComm/src/org/a0z/mpd/MPD.java | fix albums list covers by calling MPD for albumartists of albums | <ide><path>MPDComm/src/org/a0z/mpd/MPD.java
<ide> return result;
<ide> }
<ide>
<add> /*
<add> * List all albumartist or artist names of all given albums from database.
<add> *
<add> * @return list of array of artist names for each album.
<add> * @throws MPDServerException
<add> * if an error occurs while contacting server.
<add> */
<add> public List<String[]> listArtists(List<Album> albums, boolean albumArtist) throws MPDServerException {
<add> if(!isConnected())
<add> throw new MPDServerException("MPD Connection is not established");
<add>
<add> for (Album a : albums) {
<add> mpdConnection.queueCommand
<add> (new MPDCommand(MPDCommand.MPD_CMD_LIST_TAG,
<add> (albumArtist ? MPDCommand.MPD_TAG_ALBUM_ARTIST :
<add> MPDCommand.MPD_TAG_ARTIST),
<add> MPDCommand.MPD_TAG_ALBUM,
<add> a.getName()));
<add> }
<add> List<String[]> responses = mpdConnection.sendCommandQueueSeparated();
<add>
<add> ArrayList<String []> result = new ArrayList<String[]>();
<add> for (String[] r : responses){
<add> ArrayList<String> albumresult = new ArrayList<String>();
<add> for (String s : r) {
<add> String name = s.substring((albumArtist?"AlbumArtist: ":"Artist: ").length());
<add> if (name.length() > 0)
<add> albumresult.add(name);
<add> }
<add> result.add((String[])albumresult.toArray(new String[0]));
<add> }
<add> return result;
<add> }
<add>
<ide> /**
<ide> * List all artist names from database.
<ide> *
<ide> public List<String> listArtists() throws MPDServerException {
<ide> return listArtists(true);
<ide> }
<add>
<ide> /**
<ide> * List all artist names from database.
<ide> *
<ide> albums.add(new Album(album, songCount, duration, year, artist));
<ide> }
<ide> }
<add> if (!_useAlbumArtist && artist != unknownArtist) {
<add> fixAlbumArtists(albums);
<add> }
<ide> }
<ide> if (null!=albums) {
<ide> Collections.sort(albums);
<ide> }
<ide> return albums;
<add> }
<add>
<add> void fixAlbumArtists(List<Album> albums) {
<add> List<String[]> albumartists = null;
<add> try {
<add> albumartists = listArtists(albums,true);
<add> } catch (MPDServerException e) {
<add> return;
<add> }
<add> if (albumartists == null || albumartists.size() != albums.size()) {
<add> // Log.d("ALBUMARTISTS", "ERROR " + albumartists.size() + " != " +albums.size());
<add> return;
<add> }
<add> int i = 0;
<add> List<Album> splitalbums = new ArrayList<Album>();
<add> for (Album a : albums) {
<add> String[] aartists = (String[])albumartists.get(i);
<add> if (aartists.length > 0) {
<add> a.setArtist(new Artist(aartists[0])); // fix this album
<add> if (aartists.length > 1) { // it's more than one album, insert
<add> for (int n = 1; n < aartists.length; n++){
<add> Album newalbum = new Album(a.getName(),
<add> new Artist(aartists[n]));
<add> splitalbums.add(newalbum);
<add> }
<add> }
<add> }
<add> i++;
<add> }
<add> albums.addAll(splitalbums);
<add> Collections.sort(albums);
<ide> }
<ide>
<ide> public List<Genre> getGenres() throws MPDServerException { |
|
Java | apache-2.0 | error: pathspec 'platform/platform-tests/testSrc/com/intellij/ui/FinderRecursivePanelTest.java' did not match any file(s) known to git
| 3afb3f366c2fad41cbd4aafcd32eb8133aaf88b1 | 1 | salguarnieri/intellij-community,fnouama/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,holmes/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,Distrotech/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,ol-loginov/intellij-community,vladmm/intellij-community,supersven/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,adedayo/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,hurricup/intellij-community,amith01994/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,samthor/intellij-community,caot/intellij-community,blademainer/intellij-community,ibinti/intellij-community,kool79/intellij-community,fitermay/intellij-community,xfournet/intellij-community,blademainer/intellij-community,dslomov/intellij-community,slisson/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,fitermay/intellij-community,fengbaicanhe/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,kdwink/intellij-community,samthor/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,diorcety/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,supersven/intellij-community,tmpgit/intellij-community,allotria/intellij-community,signed/intellij-community,fitermay/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,wreckJ/intellij-community,semonte/intellij-community,petteyg/intellij-community,izonder/intellij-community,fnouama/intellij-community,signed/intellij-community,Lekanich/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,apixandru/intellij-community,jagguli/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,kool79/intellij-community,semonte/intellij-community,robovm/robovm-studio,semonte/intellij-community,SerCeMan/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,jagguli/intellij-community,semonte/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,fitermay/intellij-community,ftomassetti/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,kool79/intellij-community,signed/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,clumsy/intellij-community,fnouama/intellij-community,ryano144/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,ryano144/intellij-community,petteyg/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,izonder/intellij-community,caot/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,holmes/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,pwoodworth/intellij-community,signed/intellij-community,tmpgit/intellij-community,adedayo/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,kool79/intellij-community,kool79/intellij-community,petteyg/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,caot/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,signed/intellij-community,ryano144/intellij-community,ryano144/intellij-community,supersven/intellij-community,petteyg/intellij-community,pwoodworth/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,allotria/intellij-community,robovm/robovm-studio,lucafavatella/intellij-community,idea4bsd/idea4bsd,amith01994/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,slisson/intellij-community,fnouama/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,supersven/intellij-community,vladmm/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,holmes/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,holmes/intellij-community,amith01994/intellij-community,izonder/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,caot/intellij-community,da1z/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,holmes/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,signed/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,jagguli/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,signed/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,semonte/intellij-community,robovm/robovm-studio,blademainer/intellij-community,jagguli/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,semonte/intellij-community,FHannes/intellij-community,samthor/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,fitermay/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,robovm/robovm-studio,asedunov/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,slisson/intellij-community,petteyg/intellij-community,xfournet/intellij-community,asedunov/intellij-community,hurricup/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,adedayo/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,da1z/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,allotria/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,slisson/intellij-community,slisson/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,FHannes/intellij-community,ibinti/intellij-community,signed/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,diorcety/intellij-community,gnuhub/intellij-community,ahb0327/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,samthor/intellij-community,blademainer/intellij-community,da1z/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,salguarnieri/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,allotria/intellij-community,ryano144/intellij-community,supersven/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,izonder/intellij-community,retomerz/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,semonte/intellij-community,slisson/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,ahb0327/intellij-community,izonder/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,caot/intellij-community,adedayo/intellij-community,asedunov/intellij-community,supersven/intellij-community,nicolargo/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,signed/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,da1z/intellij-community,adedayo/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,signed/intellij-community,TangHao1987/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,petteyg/intellij-community,jagguli/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,diorcety/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,caot/intellij-community,lucafavatella/intellij-community,caot/intellij-community,FHannes/intellij-community,FHannes/intellij-community,retomerz/intellij-community,da1z/intellij-community,tmpgit/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,allotria/intellij-community,allotria/intellij-community,kool79/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,tmpgit/intellij-community,robovm/robovm-studio,holmes/intellij-community,Distrotech/intellij-community,nicolargo/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,allotria/intellij-community,petteyg/intellij-community,FHannes/intellij-community,petteyg/intellij-community,allotria/intellij-community,orekyuu/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,robovm/robovm-studio,xfournet/intellij-community,MER-GROUP/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,fitermay/intellij-community,diorcety/intellij-community,hurricup/intellij-community,asedunov/intellij-community,fnouama/intellij-community,semonte/intellij-community,clumsy/intellij-community,kool79/intellij-community,diorcety/intellij-community,kool79/intellij-community,amith01994/intellij-community,kdwink/intellij-community,allotria/intellij-community,caot/intellij-community,xfournet/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,asedunov/intellij-community,samthor/intellij-community,kdwink/intellij-community,apixandru/intellij-community,hurricup/intellij-community,asedunov/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,slisson/intellij-community,caot/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,izonder/intellij-community,muntasirsyed/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,ibinti/intellij-community,ryano144/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,amith01994/intellij-community,ibinti/intellij-community,hurricup/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,kdwink/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,signed/intellij-community,izonder/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,petteyg/intellij-community,apixandru/intellij-community,da1z/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,SerCeMan/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,dslomov/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,clumsy/intellij-community,kool79/intellij-community,suncycheng/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,izonder/intellij-community,diorcety/intellij-community,adedayo/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,vladmm/intellij-community,dslomov/intellij-community,kdwink/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,jagguli/intellij-community,fitermay/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,asedunov/intellij-community,izonder/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,supersven/intellij-community,supersven/intellij-community,amith01994/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,caot/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,caot/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,samthor/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,fnouama/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,ftomassetti/intellij-community,caot/intellij-community,asedunov/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,akosyakov/intellij-community | /*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ui;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Disposer;
import com.intellij.testFramework.LightPlatformTestCase;
import com.intellij.ui.components.JBList;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.util.Arrays;
import java.util.List;
public class FinderRecursivePanelTest extends LightPlatformTestCase {
public void testListModelMerge1() {
assertMerge(new String[]{"a", "b", "c", "d"}, 0, 0, "a");
}
public void testListModelMerge2() {
assertMerge(new String[0], "a", "b", "c", "d");
}
public void testListModelMerge3() {
assertMerge(new String[]{"a", "b", "c", "d"}, 0, -1, new String[0]);
}
public void testListModelMerge4() {
assertMerge(new String[]{"a", "b", "c", "d"}, 2, 2, new String[]{"a", "b", "c", "d"});
}
public void _testListModelMerge5() {
assertMerge(new String[]{"a", "b", "c", "d"}, new String[]{"d", "c", "b", "a"});
}
public void testListModelMerge6() {
assertMerge(new String[]{"a", "b", "c", "d"}, 2, 1, "b", "c");
}
public void testListModelMerge7() {
assertMerge(new String[]{"a", "b", "c", "d"}, 1, 0, "b", "c", "d", "e");
}
public void _testListModelMerge8() {
assertMerge(new String[]{"a", "a", "b", "b"}, "b", "a", "b", "a");
}
public void testListModelMerge9() {
assertMerge(new String[]{"a", "b"}, 1, 3, "e", "d", "a", "b");
}
public void testListModelMerge10() {
assertMerge(new String[]{"a", "b"}, 0, -1, "c", "d");
}
private static void assertMerge(String[] items, int startSelection, int expectedSelection, String... newItems) {
CollectionListModel<String> model = new CollectionListModel<String>();
model.add(Arrays.asList(items));
JBList list = new JBList(model);
list.setSelectedIndex(startSelection);
FinderRecursivePanel.mergeListItems(model, Arrays.asList(newItems));
assertEquals(model.getSize(), newItems.length);
for (int i = 0; i < newItems.length; i++) {
assertEquals(newItems[i], model.getElementAt(i));
}
assertEquals(list.getSelectedIndex(), expectedSelection);
}
private static void assertMerge(String[] items, String... newItems) {
assertMerge(items, -1, -1, newItems);
}
public void testUpdate() {
StringFinderRecursivePanel panel_0 = new StringFinderRecursivePanel(getProject()) {
@NotNull
@Override
protected JComponent createRightComponent(String s) {
return new StringFinderRecursivePanel(this) {
@Override
@NotNull
protected JComponent createRightComponent(String s) {
return new StringFinderRecursivePanel(this) {
@Override
@NotNull
protected JComponent createRightComponent(String s) {
return new StringFinderRecursivePanel(this);
}
};
}
};
}
};
Disposer.register(myTestRootDisposable, panel_0);
panel_0.getList().setSelectedIndex(0);
//panel_0.updateRightComponent(true);
StringFinderRecursivePanel panel_1 = (StringFinderRecursivePanel)panel_0.getChildPanel();
panel_1.getList().setSelectedIndex(1);
StringFinderRecursivePanel panel_2 = (StringFinderRecursivePanel)panel_1.getChildPanel();
panel_2.getList().setSelectedIndex(2);
StringFinderRecursivePanel panel_3 = (StringFinderRecursivePanel)panel_2.getChildPanel();
panel_3.getList().setSelectedIndex(3);
panel_0.updatePanel();
assertEquals(panel_0.getSelectedValue(), "a");
assertEquals(panel_1.getSelectedValue(), "b");
assertEquals(panel_2.getSelectedValue(), "c");
assertEquals(panel_3.getSelectedValue(), "d");
}
private class StringFinderRecursivePanel extends FinderRecursivePanel<String> {
private StringFinderRecursivePanel(Project project) {
super(project, "fooPanel");
init();
}
public StringFinderRecursivePanel(StringFinderRecursivePanel panel) {
super(panel);
init();
}
@NotNull
@Override
protected List<String> getListItems() {
return Arrays.asList("a", "b", "c", "d");
}
@Override
protected JBList createList() {
JBList list = super.createList();
((CollectionListModel)list.getModel()).replaceAll(getListItems());
return list;
}
}
}
| platform/platform-tests/testSrc/com/intellij/ui/FinderRecursivePanelTest.java | FinderRecursivePanelTest: move to platform-tests
| platform/platform-tests/testSrc/com/intellij/ui/FinderRecursivePanelTest.java | FinderRecursivePanelTest: move to platform-tests | <ide><path>latform/platform-tests/testSrc/com/intellij/ui/FinderRecursivePanelTest.java
<add>/*
<add> * Copyright 2000-2013 JetBrains s.r.o.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>package com.intellij.ui;
<add>
<add>import com.intellij.openapi.project.Project;
<add>import com.intellij.openapi.util.Disposer;
<add>import com.intellij.testFramework.LightPlatformTestCase;
<add>import com.intellij.ui.components.JBList;
<add>import org.jetbrains.annotations.NotNull;
<add>
<add>import javax.swing.*;
<add>import java.util.Arrays;
<add>import java.util.List;
<add>
<add>public class FinderRecursivePanelTest extends LightPlatformTestCase {
<add>
<add> public void testListModelMerge1() {
<add> assertMerge(new String[]{"a", "b", "c", "d"}, 0, 0, "a");
<add> }
<add>
<add> public void testListModelMerge2() {
<add> assertMerge(new String[0], "a", "b", "c", "d");
<add> }
<add>
<add> public void testListModelMerge3() {
<add> assertMerge(new String[]{"a", "b", "c", "d"}, 0, -1, new String[0]);
<add> }
<add>
<add> public void testListModelMerge4() {
<add> assertMerge(new String[]{"a", "b", "c", "d"}, 2, 2, new String[]{"a", "b", "c", "d"});
<add> }
<add>
<add> public void _testListModelMerge5() {
<add> assertMerge(new String[]{"a", "b", "c", "d"}, new String[]{"d", "c", "b", "a"});
<add> }
<add>
<add> public void testListModelMerge6() {
<add> assertMerge(new String[]{"a", "b", "c", "d"}, 2, 1, "b", "c");
<add> }
<add>
<add> public void testListModelMerge7() {
<add> assertMerge(new String[]{"a", "b", "c", "d"}, 1, 0, "b", "c", "d", "e");
<add> }
<add>
<add> public void _testListModelMerge8() {
<add> assertMerge(new String[]{"a", "a", "b", "b"}, "b", "a", "b", "a");
<add> }
<add>
<add> public void testListModelMerge9() {
<add> assertMerge(new String[]{"a", "b"}, 1, 3, "e", "d", "a", "b");
<add> }
<add>
<add> public void testListModelMerge10() {
<add> assertMerge(new String[]{"a", "b"}, 0, -1, "c", "d");
<add> }
<add>
<add> private static void assertMerge(String[] items, int startSelection, int expectedSelection, String... newItems) {
<add>
<add> CollectionListModel<String> model = new CollectionListModel<String>();
<add> model.add(Arrays.asList(items));
<add> JBList list = new JBList(model);
<add> list.setSelectedIndex(startSelection);
<add>
<add> FinderRecursivePanel.mergeListItems(model, Arrays.asList(newItems));
<add> assertEquals(model.getSize(), newItems.length);
<add> for (int i = 0; i < newItems.length; i++) {
<add> assertEquals(newItems[i], model.getElementAt(i));
<add> }
<add> assertEquals(list.getSelectedIndex(), expectedSelection);
<add> }
<add>
<add> private static void assertMerge(String[] items, String... newItems) {
<add> assertMerge(items, -1, -1, newItems);
<add> }
<add>
<add> public void testUpdate() {
<add> StringFinderRecursivePanel panel_0 = new StringFinderRecursivePanel(getProject()) {
<add> @NotNull
<add> @Override
<add> protected JComponent createRightComponent(String s) {
<add> return new StringFinderRecursivePanel(this) {
<add> @Override
<add> @NotNull
<add> protected JComponent createRightComponent(String s) {
<add> return new StringFinderRecursivePanel(this) {
<add> @Override
<add> @NotNull
<add> protected JComponent createRightComponent(String s) {
<add> return new StringFinderRecursivePanel(this);
<add> }
<add> };
<add> }
<add> };
<add> }
<add> };
<add> Disposer.register(myTestRootDisposable, panel_0);
<add> panel_0.getList().setSelectedIndex(0);
<add> //panel_0.updateRightComponent(true);
<add>
<add> StringFinderRecursivePanel panel_1 = (StringFinderRecursivePanel)panel_0.getChildPanel();
<add> panel_1.getList().setSelectedIndex(1);
<add>
<add> StringFinderRecursivePanel panel_2 = (StringFinderRecursivePanel)panel_1.getChildPanel();
<add> panel_2.getList().setSelectedIndex(2);
<add>
<add> StringFinderRecursivePanel panel_3 = (StringFinderRecursivePanel)panel_2.getChildPanel();
<add> panel_3.getList().setSelectedIndex(3);
<add>
<add> panel_0.updatePanel();
<add>
<add> assertEquals(panel_0.getSelectedValue(), "a");
<add> assertEquals(panel_1.getSelectedValue(), "b");
<add> assertEquals(panel_2.getSelectedValue(), "c");
<add> assertEquals(panel_3.getSelectedValue(), "d");
<add> }
<add>
<add>
<add> private class StringFinderRecursivePanel extends FinderRecursivePanel<String> {
<add>
<add> private StringFinderRecursivePanel(Project project) {
<add> super(project, "fooPanel");
<add> init();
<add> }
<add>
<add> public StringFinderRecursivePanel(StringFinderRecursivePanel panel) {
<add> super(panel);
<add> init();
<add> }
<add>
<add> @NotNull
<add> @Override
<add> protected List<String> getListItems() {
<add> return Arrays.asList("a", "b", "c", "d");
<add> }
<add>
<add> @Override
<add> protected JBList createList() {
<add> JBList list = super.createList();
<add> ((CollectionListModel)list.getModel()).replaceAll(getListItems());
<add> return list;
<add> }
<add> }
<add>} |
|
Java | apache-2.0 | error: pathspec 'support/src/test/java/org/springframework/richclient/command/CommandGroupFactoryBeanTests.java' did not match any file(s) known to git
| 3b21dfa9ec72a0913cd480d37057f9484f6aac5c | 1 | springrichclient/springrcp,springrichclient/springrcp,springrichclient/springrcp | /*
* Copyright 2002-2004 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.richclient.command;
import junit.framework.Assert;
import junit.framework.TestCase;
import org.easymock.EasyMock;
import org.springframework.richclient.application.PropertyNotSetException;
import org.springframework.richclient.command.config.CommandConfigurer;
/**
* Provides a suite of unit tests for the {@link CommandGroupFactoryBean} class.
*
* @author Kevin Stembridge
* @since 0.3
*
*/
public class CommandGroupFactoryBeanTests extends TestCase {
private AbstractCommand noOpCommand = new AbstractCommand() {
public void execute() {
//do nothing
}
/**
* {@inheritDoc}
*/
public String getId() {
return "noOpCommand";
}
};
private ToggleCommand toggleCommand = new ToggleCommand() {
/**
* {@inheritDoc}
*/
public String getId() {
return "toggleCommand";
}
};
/**
* Creates a new uninitialized {@code CommandGroupFactoryBeanTests}.
*/
public CommandGroupFactoryBeanTests() {
super();
}
/**
* Confirms that an exception is thrown from the afterPropertiesSet method if the
* encodedMembers property has not been set.
*/
public void testForEncodedMembersNotSet() {
CommandGroupFactoryBean factoryBean = new CommandGroupFactoryBean();
try {
factoryBean.afterPropertiesSet();
Assert.fail("Should have thrown a PropertyNotSetException");
}
catch (PropertyNotSetException e) {
Assert.assertEquals("members", e.getPropertyName());
}
}
/**
* Tests the constructor that takes the group id and members array.
* @throws Exception
*/
public final void testConstructorTakingGroupIdAndMembersArray() throws Exception {
String groupId = "groupId";
Object[] members = null;
try {
new CommandGroupFactoryBean(groupId, members);
Assert.fail("Should have thrown an IllegalArgumentException");
}
catch(IllegalArgumentException e) {
//do nothing, test passes
}
members = new Object[] {noOpCommand};
CommandGroupFactoryBean factoryBean = new CommandGroupFactoryBean(groupId, members);
CommandGroup commandGroup = (CommandGroup) factoryBean.getObject();
Assert.assertEquals(groupId, commandGroup.getId());
Assert.assertEquals(1, commandGroup.size());
}
/**
* Test method for {@link CommandGroupFactoryBean#setMembers(java.lang.Object[])}.
*/
public final void testSetMembers() {
CommandGroupFactoryBean factoryBean = new CommandGroupFactoryBean();
try {
factoryBean.setMembers(null);
Assert.fail("Should have thrown an IllegalArgumentException");
}
catch (IllegalArgumentException e) {
//test passes
}
factoryBean.setMembers(new Object[] {});
}
/**
* Test method for {@link org.springframework.richclient.command.CommandGroupFactoryBean#setBeanName(java.lang.String)}.
* @throws Exception
*/
public final void testSetBeanName() throws Exception {
String groupId = "bogusGroupId";
String beanName = "bogusBeanName";
Object[] members = new Object[] {noOpCommand};
CommandGroupFactoryBean factoryBean = new CommandGroupFactoryBean(groupId, members);
CommandGroup commandGroup = (CommandGroup) factoryBean.getObject();
Assert.assertEquals(groupId, commandGroup.getId());
//confirm that setting the beanName will override the groupId
factoryBean = new CommandGroupFactoryBean(groupId, members);
factoryBean.setBeanName(beanName);
commandGroup = (CommandGroup) factoryBean.getObject();
Assert.assertEquals(beanName, commandGroup.getId());
}
/**
* Confirms that an exception is thrown if the 'group:' prefix appears in the members list
* with no following command name.
*/
public void testInvalidGroupPrefix() {
Object[] members = new Object[] {CommandGroupFactoryBean.GROUP_MEMBER_PREFIX};
CommandGroupFactoryBean factoryBean = new CommandGroupFactoryBean();
factoryBean.setMembers(members);
try {
factoryBean.getCommandGroup();
Assert.fail("Should have thrown an InvalidGroupMemberEncodingException");
}
catch (InvalidGroupMemberEncodingException e) {
Assert.assertEquals(CommandGroupFactoryBean.GROUP_MEMBER_PREFIX, e.getEncodedString());
}
}
/**
* Confirms that an exception is thrown if the 'command:' prefix appears in the members list
* with no following command name.
*/
public void testInvalidCommandPrefix() {
Object[] members = new Object[] {CommandGroupFactoryBean.COMMAND_MEMBER_PREFIX};
CommandGroupFactoryBean factoryBean = new CommandGroupFactoryBean();
factoryBean.setMembers(members);
try {
factoryBean.getCommandGroup();
Assert.fail("Should have thrown an InvalidGroupMemberEncodingException");
}
catch (InvalidGroupMemberEncodingException e) {
Assert.assertEquals(CommandGroupFactoryBean.COMMAND_MEMBER_PREFIX, e.getEncodedString());
}
}
/**
* Test method for {@link CommandGroupFactoryBean#createCommandGroup()}.
* @throws Exception
*/
public final void testCreateCommandGroup() throws Exception {
String groupId = "bogusGroupId";
String securityId = "bogusSecurityId";
Object[] members = new Object[] {toggleCommand};
CommandGroupFactoryBean factoryBean = new CommandGroupFactoryBean(groupId, members);
factoryBean.setSecurityControllerId(securityId);
CommandGroup commandGroup = (CommandGroup) factoryBean.getObject();
Assert.assertEquals(securityId , commandGroup.getSecurityControllerId());
Assert.assertFalse("Assert command group not exclusive", commandGroup instanceof ExclusiveCommandGroup);
Assert.assertEquals(1, commandGroup.size());
factoryBean = new CommandGroupFactoryBean(groupId, members);
factoryBean.setExclusive(true);
factoryBean.setAllowsEmptySelection(true);
commandGroup = (CommandGroup) factoryBean.getObject();
Assert.assertTrue("Assert command group is exclusive", commandGroup instanceof ExclusiveCommandGroup);
Assert.assertTrue("Assert allows empty selection is true",
((ExclusiveCommandGroup) commandGroup).getAllowsEmptySelection());
}
/**
* Test method for {@link CommandGroupFactoryBean#configureIfNecessary(AbstractCommand)}.
*/
public final void testConfigureIfNecessary() {
CommandGroupFactoryBean factoryBean = new CommandGroupFactoryBean();
try {
factoryBean.configureIfNecessary(null);
Assert.fail("Should have thrown an IllegalArgumentException");
}
catch (IllegalArgumentException e) {
//test passes
}
AbstractCommand command = new AbstractCommand() {
public void execute() {
//do nothing
}
};
//no configurer has been set, confirming that this doesn't throw an exception
factoryBean.configureIfNecessary(command);
CommandConfigurer configurer = (CommandConfigurer) EasyMock.createMock(CommandConfigurer.class);
EasyMock.expect(configurer.configure(command)).andReturn(command);
EasyMock.replay(configurer);
factoryBean.setCommandConfigurer(configurer);
factoryBean.configureIfNecessary(command);
EasyMock.verify(configurer);
}
/**
* Test method for {@link CommandGroupFactoryBean#getObjectType()}.
*/
public final void testGetObjectType() {
Assert.assertEquals(CommandGroup.class, new CommandGroupFactoryBean().getObjectType());
}
/**
* Confirms that the command group is assigned the security controller id of the factory bean.
* @throws Exception
*/
public final void testSecurityControllerIdIsApplied() throws Exception {
String groupId = "bogusGroupId";
String securityId = "bogusSecurityId";
Object[] members = new Object[] {noOpCommand};
CommandGroupFactoryBean factoryBean = new CommandGroupFactoryBean(groupId, members);
factoryBean.setSecurityControllerId(securityId);
CommandGroup commandGroup = (CommandGroup) factoryBean.getObject();
Assert.assertEquals(securityId , commandGroup.getSecurityControllerId());
}
}
| support/src/test/java/org/springframework/richclient/command/CommandGroupFactoryBeanTests.java | Initial import
| support/src/test/java/org/springframework/richclient/command/CommandGroupFactoryBeanTests.java | Initial import | <ide><path>upport/src/test/java/org/springframework/richclient/command/CommandGroupFactoryBeanTests.java
<add>/*
<add> * Copyright 2002-2004 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not
<add> * use this file except in compliance with the License. You may obtain a copy of
<add> * the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
<add> * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
<add> * License for the specific language governing permissions and limitations under
<add> * the License.
<add> */
<add>package org.springframework.richclient.command;
<add>
<add>import junit.framework.Assert;
<add>import junit.framework.TestCase;
<add>
<add>import org.easymock.EasyMock;
<add>import org.springframework.richclient.application.PropertyNotSetException;
<add>import org.springframework.richclient.command.config.CommandConfigurer;
<add>
<add>
<add>/**
<add> * Provides a suite of unit tests for the {@link CommandGroupFactoryBean} class.
<add> *
<add> * @author Kevin Stembridge
<add> * @since 0.3
<add> *
<add> */
<add>public class CommandGroupFactoryBeanTests extends TestCase {
<add>
<add> private AbstractCommand noOpCommand = new AbstractCommand() {
<add> public void execute() {
<add> //do nothing
<add> }
<add>
<add> /**
<add> * {@inheritDoc}
<add> */
<add> public String getId() {
<add> return "noOpCommand";
<add> }
<add>
<add> };
<add>
<add> private ToggleCommand toggleCommand = new ToggleCommand() {
<add>
<add> /**
<add> * {@inheritDoc}
<add> */
<add> public String getId() {
<add> return "toggleCommand";
<add> }
<add>
<add> };
<add>
<add> /**
<add> * Creates a new uninitialized {@code CommandGroupFactoryBeanTests}.
<add> */
<add> public CommandGroupFactoryBeanTests() {
<add> super();
<add> }
<add>
<add> /**
<add> * Confirms that an exception is thrown from the afterPropertiesSet method if the
<add> * encodedMembers property has not been set.
<add> */
<add> public void testForEncodedMembersNotSet() {
<add>
<add> CommandGroupFactoryBean factoryBean = new CommandGroupFactoryBean();
<add>
<add> try {
<add> factoryBean.afterPropertiesSet();
<add> Assert.fail("Should have thrown a PropertyNotSetException");
<add> }
<add> catch (PropertyNotSetException e) {
<add> Assert.assertEquals("members", e.getPropertyName());
<add> }
<add>
<add> }
<add>
<add> /**
<add> * Tests the constructor that takes the group id and members array.
<add> * @throws Exception
<add> */
<add> public final void testConstructorTakingGroupIdAndMembersArray() throws Exception {
<add>
<add> String groupId = "groupId";
<add> Object[] members = null;
<add>
<add> try {
<add> new CommandGroupFactoryBean(groupId, members);
<add> Assert.fail("Should have thrown an IllegalArgumentException");
<add> }
<add> catch(IllegalArgumentException e) {
<add> //do nothing, test passes
<add> }
<add>
<add> members = new Object[] {noOpCommand};
<add>
<add> CommandGroupFactoryBean factoryBean = new CommandGroupFactoryBean(groupId, members);
<add> CommandGroup commandGroup = (CommandGroup) factoryBean.getObject();
<add> Assert.assertEquals(groupId, commandGroup.getId());
<add> Assert.assertEquals(1, commandGroup.size());
<add>
<add> }
<add>
<add> /**
<add> * Test method for {@link CommandGroupFactoryBean#setMembers(java.lang.Object[])}.
<add> */
<add> public final void testSetMembers() {
<add>
<add> CommandGroupFactoryBean factoryBean = new CommandGroupFactoryBean();
<add>
<add> try {
<add> factoryBean.setMembers(null);
<add> Assert.fail("Should have thrown an IllegalArgumentException");
<add> }
<add> catch (IllegalArgumentException e) {
<add> //test passes
<add> }
<add>
<add> factoryBean.setMembers(new Object[] {});
<add>
<add> }
<add>
<add> /**
<add> * Test method for {@link org.springframework.richclient.command.CommandGroupFactoryBean#setBeanName(java.lang.String)}.
<add> * @throws Exception
<add> */
<add> public final void testSetBeanName() throws Exception {
<add>
<add> String groupId = "bogusGroupId";
<add> String beanName = "bogusBeanName";
<add> Object[] members = new Object[] {noOpCommand};
<add>
<add> CommandGroupFactoryBean factoryBean = new CommandGroupFactoryBean(groupId, members);
<add> CommandGroup commandGroup = (CommandGroup) factoryBean.getObject();
<add> Assert.assertEquals(groupId, commandGroup.getId());
<add>
<add> //confirm that setting the beanName will override the groupId
<add> factoryBean = new CommandGroupFactoryBean(groupId, members);
<add> factoryBean.setBeanName(beanName);
<add> commandGroup = (CommandGroup) factoryBean.getObject();
<add> Assert.assertEquals(beanName, commandGroup.getId());
<add>
<add> }
<add>
<add> /**
<add> * Confirms that an exception is thrown if the 'group:' prefix appears in the members list
<add> * with no following command name.
<add> */
<add> public void testInvalidGroupPrefix() {
<add>
<add> Object[] members = new Object[] {CommandGroupFactoryBean.GROUP_MEMBER_PREFIX};
<add>
<add> CommandGroupFactoryBean factoryBean = new CommandGroupFactoryBean();
<add> factoryBean.setMembers(members);
<add>
<add> try {
<add> factoryBean.getCommandGroup();
<add> Assert.fail("Should have thrown an InvalidGroupMemberEncodingException");
<add> }
<add> catch (InvalidGroupMemberEncodingException e) {
<add> Assert.assertEquals(CommandGroupFactoryBean.GROUP_MEMBER_PREFIX, e.getEncodedString());
<add> }
<add>
<add> }
<add>
<add> /**
<add> * Confirms that an exception is thrown if the 'command:' prefix appears in the members list
<add> * with no following command name.
<add> */
<add> public void testInvalidCommandPrefix() {
<add>
<add> Object[] members = new Object[] {CommandGroupFactoryBean.COMMAND_MEMBER_PREFIX};
<add>
<add> CommandGroupFactoryBean factoryBean = new CommandGroupFactoryBean();
<add> factoryBean.setMembers(members);
<add>
<add> try {
<add> factoryBean.getCommandGroup();
<add> Assert.fail("Should have thrown an InvalidGroupMemberEncodingException");
<add> }
<add> catch (InvalidGroupMemberEncodingException e) {
<add> Assert.assertEquals(CommandGroupFactoryBean.COMMAND_MEMBER_PREFIX, e.getEncodedString());
<add> }
<add>
<add> }
<add>
<add> /**
<add> * Test method for {@link CommandGroupFactoryBean#createCommandGroup()}.
<add> * @throws Exception
<add> */
<add> public final void testCreateCommandGroup() throws Exception {
<add>
<add> String groupId = "bogusGroupId";
<add> String securityId = "bogusSecurityId";
<add> Object[] members = new Object[] {toggleCommand};
<add>
<add> CommandGroupFactoryBean factoryBean = new CommandGroupFactoryBean(groupId, members);
<add> factoryBean.setSecurityControllerId(securityId);
<add> CommandGroup commandGroup = (CommandGroup) factoryBean.getObject();
<add> Assert.assertEquals(securityId , commandGroup.getSecurityControllerId());
<add> Assert.assertFalse("Assert command group not exclusive", commandGroup instanceof ExclusiveCommandGroup);
<add> Assert.assertEquals(1, commandGroup.size());
<add>
<add> factoryBean = new CommandGroupFactoryBean(groupId, members);
<add> factoryBean.setExclusive(true);
<add> factoryBean.setAllowsEmptySelection(true);
<add> commandGroup = (CommandGroup) factoryBean.getObject();
<add> Assert.assertTrue("Assert command group is exclusive", commandGroup instanceof ExclusiveCommandGroup);
<add> Assert.assertTrue("Assert allows empty selection is true",
<add> ((ExclusiveCommandGroup) commandGroup).getAllowsEmptySelection());
<add>
<add>
<add> }
<add>
<add> /**
<add> * Test method for {@link CommandGroupFactoryBean#configureIfNecessary(AbstractCommand)}.
<add> */
<add> public final void testConfigureIfNecessary() {
<add>
<add> CommandGroupFactoryBean factoryBean = new CommandGroupFactoryBean();
<add>
<add> try {
<add> factoryBean.configureIfNecessary(null);
<add> Assert.fail("Should have thrown an IllegalArgumentException");
<add> }
<add> catch (IllegalArgumentException e) {
<add> //test passes
<add> }
<add>
<add> AbstractCommand command = new AbstractCommand() {
<add> public void execute() {
<add> //do nothing
<add> }
<add> };
<add>
<add> //no configurer has been set, confirming that this doesn't throw an exception
<add> factoryBean.configureIfNecessary(command);
<add>
<add> CommandConfigurer configurer = (CommandConfigurer) EasyMock.createMock(CommandConfigurer.class);
<add> EasyMock.expect(configurer.configure(command)).andReturn(command);
<add>
<add> EasyMock.replay(configurer);
<add>
<add> factoryBean.setCommandConfigurer(configurer);
<add> factoryBean.configureIfNecessary(command);
<add>
<add> EasyMock.verify(configurer);
<add>
<add> }
<add>
<add> /**
<add> * Test method for {@link CommandGroupFactoryBean#getObjectType()}.
<add> */
<add> public final void testGetObjectType() {
<add> Assert.assertEquals(CommandGroup.class, new CommandGroupFactoryBean().getObjectType());
<add> }
<add>
<add> /**
<add> * Confirms that the command group is assigned the security controller id of the factory bean.
<add> * @throws Exception
<add> */
<add> public final void testSecurityControllerIdIsApplied() throws Exception {
<add>
<add> String groupId = "bogusGroupId";
<add> String securityId = "bogusSecurityId";
<add> Object[] members = new Object[] {noOpCommand};
<add>
<add> CommandGroupFactoryBean factoryBean = new CommandGroupFactoryBean(groupId, members);
<add> factoryBean.setSecurityControllerId(securityId);
<add> CommandGroup commandGroup = (CommandGroup) factoryBean.getObject();
<add> Assert.assertEquals(securityId , commandGroup.getSecurityControllerId());
<add>
<add> }
<add>
<add>} |
|
Java | apache-2.0 | 4b705f50496ea85a78640b782d3684af48154529 | 0 | TatsianaKasiankova/pentaho-kettle,sajeetharan/pentaho-kettle,cjsonger/pentaho-kettle,roboguy/pentaho-kettle,akhayrutdinov/pentaho-kettle,HiromuHota/pentaho-kettle,drndos/pentaho-kettle,matrix-stone/pentaho-kettle,rfellows/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,ViswesvarSekar/pentaho-kettle,mkambol/pentaho-kettle,stevewillcock/pentaho-kettle,HiromuHota/pentaho-kettle,tkafalas/pentaho-kettle,pymjer/pentaho-kettle,graimundo/pentaho-kettle,flbrino/pentaho-kettle,yshakhau/pentaho-kettle,brosander/pentaho-kettle,dkincade/pentaho-kettle,pentaho/pentaho-kettle,kurtwalker/pentaho-kettle,alina-ipatina/pentaho-kettle,ddiroma/pentaho-kettle,mdamour1976/pentaho-kettle,pedrofvteixeira/pentaho-kettle,GauravAshara/pentaho-kettle,SergeyTravin/pentaho-kettle,nantunes/pentaho-kettle,emartin-pentaho/pentaho-kettle,tkafalas/pentaho-kettle,Advent51/pentaho-kettle,birdtsai/pentaho-kettle,pavel-sakun/pentaho-kettle,pedrofvteixeira/pentaho-kettle,GauravAshara/pentaho-kettle,rmansoor/pentaho-kettle,ivanpogodin/pentaho-kettle,dkincade/pentaho-kettle,ccaspanello/pentaho-kettle,tmcsantos/pentaho-kettle,e-cuellar/pentaho-kettle,GauravAshara/pentaho-kettle,ddiroma/pentaho-kettle,nicoben/pentaho-kettle,brosander/pentaho-kettle,yshakhau/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,ccaspanello/pentaho-kettle,YuryBY/pentaho-kettle,DFieldFL/pentaho-kettle,denisprotopopov/pentaho-kettle,mattyb149/pentaho-kettle,jbrant/pentaho-kettle,EcoleKeine/pentaho-kettle,cjsonger/pentaho-kettle,nicoben/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,pentaho/pentaho-kettle,pentaho/pentaho-kettle,ma459006574/pentaho-kettle,DFieldFL/pentaho-kettle,nanata1115/pentaho-kettle,airy-ict/pentaho-kettle,wseyler/pentaho-kettle,nicoben/pentaho-kettle,andrei-viaryshka/pentaho-kettle,Advent51/pentaho-kettle,stepanovdg/pentaho-kettle,marcoslarsen/pentaho-kettle,mbatchelor/pentaho-kettle,hudak/pentaho-kettle,cjsonger/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,mkambol/pentaho-kettle,ivanpogodin/pentaho-kettle,YuryBY/pentaho-kettle,CapeSepias/pentaho-kettle,SergeyTravin/pentaho-kettle,CapeSepias/pentaho-kettle,brosander/pentaho-kettle,mdamour1976/pentaho-kettle,kurtwalker/pentaho-kettle,MikhailHubanau/pentaho-kettle,kurtwalker/pentaho-kettle,rmansoor/pentaho-kettle,DFieldFL/pentaho-kettle,mbatchelor/pentaho-kettle,nicoben/pentaho-kettle,aminmkhan/pentaho-kettle,pavel-sakun/pentaho-kettle,pminutillo/pentaho-kettle,aminmkhan/pentaho-kettle,nantunes/pentaho-kettle,ccaspanello/pentaho-kettle,pymjer/pentaho-kettle,ViswesvarSekar/pentaho-kettle,mdamour1976/pentaho-kettle,wseyler/pentaho-kettle,tmcsantos/pentaho-kettle,emartin-pentaho/pentaho-kettle,pymjer/pentaho-kettle,matthewtckr/pentaho-kettle,wseyler/pentaho-kettle,pedrofvteixeira/pentaho-kettle,denisprotopopov/pentaho-kettle,hudak/pentaho-kettle,ViswesvarSekar/pentaho-kettle,gretchiemoran/pentaho-kettle,alina-ipatina/pentaho-kettle,marcoslarsen/pentaho-kettle,ccaspanello/pentaho-kettle,HiromuHota/pentaho-kettle,sajeetharan/pentaho-kettle,sajeetharan/pentaho-kettle,nantunes/pentaho-kettle,rmansoor/pentaho-kettle,rmansoor/pentaho-kettle,sajeetharan/pentaho-kettle,zlcnju/kettle,matrix-stone/pentaho-kettle,skofra0/pentaho-kettle,akhayrutdinov/pentaho-kettle,tmcsantos/pentaho-kettle,ma459006574/pentaho-kettle,airy-ict/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,pymjer/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,lgrill-pentaho/pentaho-kettle,flbrino/pentaho-kettle,ma459006574/pentaho-kettle,Advent51/pentaho-kettle,stepanovdg/pentaho-kettle,ivanpogodin/pentaho-kettle,matthewtckr/pentaho-kettle,graimundo/pentaho-kettle,YuryBY/pentaho-kettle,MikhailHubanau/pentaho-kettle,e-cuellar/pentaho-kettle,wseyler/pentaho-kettle,codek/pentaho-kettle,matrix-stone/pentaho-kettle,tkafalas/pentaho-kettle,mattyb149/pentaho-kettle,hudak/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,tmcsantos/pentaho-kettle,jbrant/pentaho-kettle,AlexanderBuloichik/pentaho-kettle,cjsonger/pentaho-kettle,nanata1115/pentaho-kettle,mbatchelor/pentaho-kettle,kurtwalker/pentaho-kettle,ma459006574/pentaho-kettle,rfellows/pentaho-kettle,gretchiemoran/pentaho-kettle,skofra0/pentaho-kettle,HiromuHota/pentaho-kettle,denisprotopopov/pentaho-kettle,drndos/pentaho-kettle,nanata1115/pentaho-kettle,denisprotopopov/pentaho-kettle,matthewtckr/pentaho-kettle,nanata1115/pentaho-kettle,lgrill-pentaho/pentaho-kettle,birdtsai/pentaho-kettle,mkambol/pentaho-kettle,mkambol/pentaho-kettle,gretchiemoran/pentaho-kettle,emartin-pentaho/pentaho-kettle,birdtsai/pentaho-kettle,dkincade/pentaho-kettle,alina-ipatina/pentaho-kettle,EcoleKeine/pentaho-kettle,mattyb149/pentaho-kettle,stevewillcock/pentaho-kettle,eayoungs/pentaho-kettle,jbrant/pentaho-kettle,birdtsai/pentaho-kettle,DFieldFL/pentaho-kettle,zlcnju/kettle,stevewillcock/pentaho-kettle,stepanovdg/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,EcoleKeine/pentaho-kettle,pavel-sakun/pentaho-kettle,alina-ipatina/pentaho-kettle,EcoleKeine/pentaho-kettle,roboguy/pentaho-kettle,flbrino/pentaho-kettle,pentaho/pentaho-kettle,bmorrise/pentaho-kettle,pminutillo/pentaho-kettle,tkafalas/pentaho-kettle,ivanpogodin/pentaho-kettle,ViswesvarSekar/pentaho-kettle,CapeSepias/pentaho-kettle,bmorrise/pentaho-kettle,codek/pentaho-kettle,flbrino/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,aminmkhan/pentaho-kettle,SergeyTravin/pentaho-kettle,drndos/pentaho-kettle,mdamour1976/pentaho-kettle,eayoungs/pentaho-kettle,matthewtckr/pentaho-kettle,gretchiemoran/pentaho-kettle,pavel-sakun/pentaho-kettle,airy-ict/pentaho-kettle,roboguy/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,bmorrise/pentaho-kettle,yshakhau/pentaho-kettle,hudak/pentaho-kettle,mattyb149/pentaho-kettle,jbrant/pentaho-kettle,pminutillo/pentaho-kettle,eayoungs/pentaho-kettle,matrix-stone/pentaho-kettle,zlcnju/kettle,ddiroma/pentaho-kettle,MikhailHubanau/pentaho-kettle,stepanovdg/pentaho-kettle,emartin-pentaho/pentaho-kettle,YuryBY/pentaho-kettle,nantunes/pentaho-kettle,lgrill-pentaho/pentaho-kettle,akhayrutdinov/pentaho-kettle,eayoungs/pentaho-kettle,pedrofvteixeira/pentaho-kettle,andrei-viaryshka/pentaho-kettle,pminutillo/pentaho-kettle,codek/pentaho-kettle,brosander/pentaho-kettle,airy-ict/pentaho-kettle,lgrill-pentaho/pentaho-kettle,Advent51/pentaho-kettle,andrei-viaryshka/pentaho-kettle,skofra0/pentaho-kettle,stevewillcock/pentaho-kettle,graimundo/pentaho-kettle,skofra0/pentaho-kettle,mbatchelor/pentaho-kettle,drndos/pentaho-kettle,zlcnju/kettle,SergeyTravin/pentaho-kettle,codek/pentaho-kettle,TatsianaKasiankova/pentaho-kettle,e-cuellar/pentaho-kettle,roboguy/pentaho-kettle,GauravAshara/pentaho-kettle,e-cuellar/pentaho-kettle,rfellows/pentaho-kettle,yshakhau/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,marcoslarsen/pentaho-kettle,IvanNikolaychuk/pentaho-kettle,ddiroma/pentaho-kettle,akhayrutdinov/pentaho-kettle,dkincade/pentaho-kettle,AliaksandrShuhayeu/pentaho-kettle,CapeSepias/pentaho-kettle,bmorrise/pentaho-kettle,graimundo/pentaho-kettle,marcoslarsen/pentaho-kettle,aminmkhan/pentaho-kettle | /**********************************************************************
** **
** This code belongs to the KETTLE project. **
** **
** Kettle, from version 2.2 on, is released into the public domain **
** under the Lesser GNU Public License (LGPL). **
** **
** For more details, please read the document LICENSE.txt, included **
** in this project **
** **
** http://www.kettle.be **
** [email protected] **
** **
**********************************************************************/
package be.ibridge.kettle.trans.step.textfileoutput;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import be.ibridge.kettle.core.Const;
import be.ibridge.kettle.core.ResultFile;
import be.ibridge.kettle.core.Row;
import be.ibridge.kettle.core.exception.KettleException;
import be.ibridge.kettle.core.value.Value;
import be.ibridge.kettle.trans.Trans;
import be.ibridge.kettle.trans.TransMeta;
import be.ibridge.kettle.trans.step.BaseStep;
import be.ibridge.kettle.trans.step.StepDataInterface;
import be.ibridge.kettle.trans.step.StepInterface;
import be.ibridge.kettle.trans.step.StepMeta;
import be.ibridge.kettle.trans.step.StepMetaInterface;
/**
* Converts input rows to text and then writes this text to one or more files.
*
* @author Matt
* @since 4-apr-2003
*/
public class TextFileOutput extends BaseStep implements StepInterface
{
private TextFileOutputMeta meta;
private TextFileOutputData data;
public TextFileOutput(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans)
{
super(stepMeta, stepDataInterface, copyNr, transMeta, trans);
}
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException
{
meta=(TextFileOutputMeta)smi;
data=(TextFileOutputData)sdi;
Row r;
boolean result=true;
boolean bEndedLineWrote=false;
r=getRow(); // This also waits for a row to be finished.
if ( ( r==null && data.headerrow!=null && meta.isFooterEnabled() ) ||
( r!=null && linesOutput>0 && meta.getSplitEvery()>0 && (linesOutput%meta.getSplitEvery())==0)
)
{
if (writeHeader()) linesOutput++;
if (r==null)
{
//add tag to last line if needed
writeEndedLine();
bEndedLineWrote=true;
}
// Done with this part or with everything.
closeFile();
// Not finished: open another file...
if (r!=null)
{
if (!openNewFile())
{
logError("Unable to open new file (split #"+data.splitnr+"...");
setErrors(1);
return false;
}
if (meta.isHeaderEnabled() && data.headerrow!=null) if (writeHeader()) linesOutput++;
}
}
if (r==null) // no more input to be expected...
{
if (false==bEndedLineWrote)
{
//add tag to last line if needed
writeEndedLine();
bEndedLineWrote=true;
}
setOutputDone();
return false;
}
result=writeRowToFile(r);
if (!result)
{
setErrors(1);
stopAll();
return false;
}
putRow(r); // in case we want it to go further...
if ((linesOutput>0) && (linesOutput%Const.ROWS_UPDATE)==0)logBasic("linenr "+linesOutput);
return result;
}
private boolean writeRowToFile(Row r)
{
Value v;
try
{
if (first)
{
first=false;
if (!meta.isFileAppended() && ( meta.isHeaderEnabled() || meta.isFooterEnabled())) // See if we have to write a header-line)
{
data.headerrow=new Row(r); // copy the row for the footer!
if (meta.isHeaderEnabled())
{
if (writeHeader()) return false;
}
}
data.fieldnrs=new int[meta.getOutputFields().length];
for (int i=0;i<meta.getOutputFields().length;i++)
{
data.fieldnrs[i]=r.searchValueIndex(meta.getOutputFields()[i].getName());
if (data.fieldnrs[i]<0)
{
logError("Field ["+meta.getOutputFields()[i].getName()+"] couldn't be found in the input stream!");
setErrors(1);
stopAll();
return false;
}
}
}
if (meta.getOutputFields()==null || meta.getOutputFields().length==0)
{
/*
* Write all values in stream to text file.
*/
for (int i=0;i<r.size();i++)
{
if (i>0) data.writer.write(meta.getSeparator().toCharArray());
v=r.getValue(i);
if(!writeField(v, -1)) return false;
}
data.writer.write(meta.getNewline().toCharArray());
}
else
{
/*
* Only write the fields specified!
*/
for (int i=0;i<meta.getOutputFields().length;i++)
{
if (i>0) data.writer.write(meta.getSeparator().toCharArray());
v=r.getValue(data.fieldnrs[i]);
v.setLength(meta.getOutputFields()[i].getLength(), meta.getOutputFields()[i].getPrecision());
if(!writeField(v, i)) return false;
}
data.writer.write(meta.getNewline().toCharArray());
}
}
catch(Exception e)
{
logError("Error writing line :"+e.toString());
return false;
}
linesOutput++;
return true;
}
private String formatField(Value v, int idx)
{
String retval="";
TextFileField field = null;
if (idx>=0) field = meta.getOutputFields()[idx];
if (v.isString())
{
if (v.isNull() || v.getString()==null)
{
if (idx>=0 && field!=null && field.getNullString()!=null)
{
if (meta.isEnclosureForced() && meta.getEnclosure()!=null)
{
retval=meta.getEnclosure()+field.getNullString()+meta.getEnclosure();
}
else
{
retval=field.getNullString();
}
}
}
else
{
// Any separators in string?
// example: 123.4;"a;b;c";Some name
//
if (meta.isEnclosureForced() && meta.getEnclosure()!=null) // Force enclosure?
{
retval=meta.getEnclosure()+v.toString()+meta.getEnclosure();
}
else // See if there is a separator in the String...
{
int seppos = v.toString().indexOf(meta.getSeparator());
if (seppos<0) retval=v.toString();
else retval=meta.getEnclosure()+v.toString()+meta.getEnclosure();
}
}
}
else if (v.isBigNumber())
{
if (idx>=0 && field!=null && field.getFormat()!=null)
{
if (v.isNull())
{
if (field.getNullString()!=null) retval=field.getNullString();
else retval = "";
}
else
{
data.df.applyPattern(field.getFormat());
if (field.getDecimalSymbol()!=null && field.getDecimalSymbol().length()>0) data.dfs.setDecimalSeparator( field.getDecimalSymbol().charAt(0) );
if (field.getGroupingSymbol()!=null && field.getGroupingSymbol().length()>0) data.dfs.setGroupingSeparator( field.getGroupingSymbol().charAt(0) );
if (field.getCurrencySymbol()!=null) data.dfs.setCurrencySymbol( field.getCurrencySymbol() );
data.df.setDecimalFormatSymbols(data.dfs);
retval=data.df.format(v.getBigNumber());
}
}
else
{
if (v.isNull())
{
if (idx>=0 && field!=null && field.getNullString()!=null) retval=field.getNullString();
else retval = "";
}
else
{
retval=v.toString();
}
}
}
else if (v.isNumeric())
{
if (idx>=0 && field!=null && field.getFormat()!=null)
{
if (v.isNull())
{
if (field.getNullString()!=null) retval=field.getNullString();
else retval = "";
}
else
{
data.df.applyPattern(field.getFormat());
if (field.getDecimalSymbol()!=null && field.getDecimalSymbol().length()>0) data.dfs.setDecimalSeparator( field.getDecimalSymbol().charAt(0) );
if (field.getGroupingSymbol()!=null && field.getGroupingSymbol().length()>0) data.dfs.setGroupingSeparator( field.getGroupingSymbol().charAt(0) );
if (field.getCurrencySymbol()!=null) data.dfs.setCurrencySymbol( field.getCurrencySymbol() );
data.df.setDecimalFormatSymbols(data.dfs);
if ( v.isInteger() )
{
retval=data.df.format(v.getInteger());
}
else if ( v.isNumber() )
{
retval=data.df.format(v.getNumber());
}
}
}
else
{
if (v.isNull())
{
if (idx>=0 && field!=null && field.getNullString()!=null) retval=field.getNullString();
}
else
{
retval=v.toString();
}
}
}
else if (v.isDate())
{
if (idx>=0 && field!=null && field.getFormat()!=null && v.getDate()!=null)
{
data.daf.applyPattern( field.getFormat() );
data.daf.setDateFormatSymbols(data.dafs);
retval= data.daf.format(v.getDate());
}
else
{
if (v.isNull() || v.getDate()==null)
{
if (idx>=0 && field!=null && field.getNullString()!=null) retval=field.getNullString();
}
else
{
retval=v.toString();
}
}
}
else if (v.isBinary())
{
if (v.isNull())
{
if (field.getNullString()!=null) retval=field.getNullString();
else retval=Const.NULL_BINARY;
}
else
{
try {
retval=new String(v.getBytes(), "US-ASCII");
} catch (UnsupportedEncodingException e) {
// changes are small we'll get here. US_ASCII is
// mandatory.
retval=Const.NULL_BINARY;
}
}
}
else // Boolean
{
if (v.isNull())
{
if (idx>=0 && field!=null && field.getNullString()!=null) retval=field.getNullString();
}
else
{
retval=v.toString();
}
}
if (meta.isPadded()) // maybe we need to rightpad to field length?
{
// What's the field length?
int length, precision;
if (idx<0 || field==null) // Nothing specified: get it from the values themselves.
{
length =v.getLength()<0?0:v.getLength();
precision=v.getPrecision()<0?0:v.getPrecision();
}
else // Get the info from the specified lengths & precision...
{
length =field.getLength() <0?0:field.getLength();
precision=field.getPrecision()<0?0:field.getPrecision();
}
if (v.isNumber())
{
length++; // for the sign...
if (precision>0) length++; // for the decimal point...
}
if (v.isDate()) { length=23; precision=0; }
if (v.isBoolean()) { length=5; precision=0; }
retval=Const.rightPad(new StringBuffer(retval), length+precision);
}
return retval;
}
private boolean writeField(Value v, int idx)
{
try
{
String str = formatField(v, idx);
if (str!=null) data.writer.write(str.toCharArray());
}
catch(Exception e)
{
logError("Error writing line :"+e.toString());
return false;
}
return true;
}
private boolean writeEndedLine()
{
boolean retval=false;
try
{
String sLine = meta.getEndedLine();
if (sLine!=null)
{
if (sLine.trim().length()>0)
data.writer.write(sLine.toCharArray());
}
}
catch(Exception e)
{
logError("Error writing ended tag line: "+e.toString());
e.printStackTrace();
retval=true;
}
linesOutput++;
return retval;
}
private boolean writeHeader()
{
boolean retval=false;
Row r=data.headerrow;
try
{
// If we have fields specified: list them in this order!
if (meta.getOutputFields()!=null && meta.getOutputFields().length>0)
{
String header = "";
for (int i=0;i<meta.getOutputFields().length;i++)
{
String fieldName = meta.getOutputFields()[i].getName();
Value v = r.searchValue(fieldName);
if (i>0 && meta.getSeparator()!=null && meta.getSeparator().length()>0)
{
header+=meta.getSeparator();
}
if (meta.isEnclosureForced() && meta.getEnclosure()!=null && v!=null && v.isString())
{
header+=meta.getEnclosure();
}
header+=fieldName;
if (meta.isEnclosureForced() && meta.getEnclosure()!=null && v!=null && v.isString())
{
header+=meta.getEnclosure();
}
}
header+=meta.getNewline();
data.writer.write(header.toCharArray());
}
else
if (r!=null) // Just put all field names in the header/footer
{
for (int i=0;i<r.size();i++)
{
if (i>0) data.writer.write(meta.getSeparator().toCharArray());
Value v = r.getValue(i);
// Header-value contains the name of the value
Value header_value = new Value(v.getName(), Value.VALUE_TYPE_STRING);
header_value.setValue(v.getName());
if (meta.isEnclosureForced() && meta.getEnclosure()!=null && v.isString())
{
data.writer.write(meta.getEnclosure().toCharArray());
}
data.writer.write(header_value.toString().toCharArray());
if (meta.isEnclosureForced() && meta.getEnclosure()!=null && v.isString())
{
data.writer.write(meta.getEnclosure().toCharArray());
}
}
data.writer.write(meta.getNewline().toCharArray());
}
else
{
data.writer.write(("no rows selected"+Const.CR).toCharArray());
}
}
catch(Exception e)
{
logError("Error writing header line: "+e.toString());
e.printStackTrace();
retval=true;
}
linesOutput++;
return retval;
}
public String buildFilename(boolean ziparchive)
{
return meta.buildFilename(getCopy(), data.splitnr, ziparchive);
}
public boolean openNewFile()
{
boolean retval=false;
data.writer=null;
try
{
File file = new File(buildFilename(true));
// Add this to the result file names...
ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL, file, getTransMeta().getName(), getStepname());
resultFile.setComment("This file was created with a text file output step");
addResultFile(resultFile);
OutputStream outputStream;
if (meta.isZipped())
{
FileOutputStream fos = new FileOutputStream(file, meta.isFileAppended());
data.zip = new ZipOutputStream(fos);
File entry = new File(buildFilename(false));
ZipEntry zipentry = new ZipEntry(entry.getName());
zipentry.setComment("Compressed by Kettle");
data.zip.putNextEntry(zipentry);
outputStream=data.zip;
}
else
{
FileOutputStream fos=new FileOutputStream(file, meta.isFileAppended());
outputStream=fos;
}
if (meta.getEncoding()!=null && meta.getEncoding().length()>0)
{
log.logBasic(toString(), "Opening output stream in encoding: "+meta.getEncoding());
data.writer = new OutputStreamWriter(outputStream, meta.getEncoding());
}
else
{
log.logBasic(toString(), "Opening output stream in default encoding");
data.writer = new OutputStreamWriter(outputStream);
}
retval=true;
}
catch(Exception e)
{
logError("Error opening new file : "+e.toString());
}
// System.out.println("end of newFile(), splitnr="+splitnr);
data.splitnr++;
return retval;
}
private boolean closeFile()
{
boolean retval=false;
try
{
data.writer.close();
if (meta.isZipped())
{
//System.out.println("close zip entry ");
data.zip.closeEntry();
//System.out.println("finish file...");
data.zip.finish();
data.zip.close();
}
//System.out.println("Closed file...");
retval=true;
}
catch(Exception e)
{
}
return retval;
}
public boolean init(StepMetaInterface smi, StepDataInterface sdi)
{
meta=(TextFileOutputMeta)smi;
data=(TextFileOutputData)sdi;
if (super.init(smi, sdi))
{
data.splitnr=0;
if (openNewFile())
{
return true;
}
else
{
logError("Couldn't open file "+meta.getFileName());
setErrors(1L);
stopAll();
}
}
return false;
}
public void dispose(StepMetaInterface smi, StepDataInterface sdi)
{
meta=(TextFileOutputMeta)smi;
data=(TextFileOutputData)sdi;
super.dispose(smi, sdi);
closeFile();
}
//
// Run is were the action happens!
public void run()
{
try
{
logBasic("Starting to run...");
while (processRow(meta, data) && !isStopped());
}
catch(Exception e)
{
logError("Unexpected error : "+e.toString());
logError(Const.getStackTracker(e));
setErrors(1);
stopAll();
}
finally
{
dispose(meta, data);
logSummary();
markStop();
}
}
}
| src/be/ibridge/kettle/trans/step/textfileoutput/TextFileOutput.java | /**********************************************************************
** **
** This code belongs to the KETTLE project. **
** **
** Kettle, from version 2.2 on, is released into the public domain **
** under the Lesser GNU Public License (LGPL). **
** **
** For more details, please read the document LICENSE.txt, included **
** in this project **
** **
** http://www.kettle.be **
** [email protected] **
** **
**********************************************************************/
package be.ibridge.kettle.trans.step.textfileoutput;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import be.ibridge.kettle.core.Const;
import be.ibridge.kettle.core.ResultFile;
import be.ibridge.kettle.core.Row;
import be.ibridge.kettle.core.exception.KettleException;
import be.ibridge.kettle.core.value.Value;
import be.ibridge.kettle.trans.Trans;
import be.ibridge.kettle.trans.TransMeta;
import be.ibridge.kettle.trans.step.BaseStep;
import be.ibridge.kettle.trans.step.StepDataInterface;
import be.ibridge.kettle.trans.step.StepInterface;
import be.ibridge.kettle.trans.step.StepMeta;
import be.ibridge.kettle.trans.step.StepMetaInterface;
/**
* Converts input rows to text and then writes this text to one or more files.
*
* @author Matt
* @since 4-apr-2003
*/
public class TextFileOutput extends BaseStep implements StepInterface
{
private TextFileOutputMeta meta;
private TextFileOutputData data;
public TextFileOutput(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans)
{
super(stepMeta, stepDataInterface, copyNr, transMeta, trans);
}
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException
{
meta=(TextFileOutputMeta)smi;
data=(TextFileOutputData)sdi;
Row r;
boolean result=true;
boolean bEndedLineWrote=false;
r=getRow(); // This also waits for a row to be finished.
if ( ( r==null && data.headerrow!=null && meta.isFooterEnabled() ) ||
( r!=null && linesOutput>0 && meta.getSplitEvery()>0 && (linesOutput%meta.getSplitEvery())==0)
)
{
if (writeHeader()) linesOutput++;
if (r==null)
{
//add tag to last line if needed
writeEndedLine();
bEndedLineWrote=true;
}
// Done with this part or with everything.
closeFile();
// Not finished: open another file...
if (r!=null)
{
if (!openNewFile())
{
logError("Unable to open new file (split #"+data.splitnr+"...");
setErrors(1);
return false;
}
if (meta.isHeaderEnabled() && data.headerrow!=null) if (writeHeader()) linesOutput++;
}
}
if (r==null) // no more input to be expected...
{
if (false==bEndedLineWrote)
{
//add tag to last line if needed
writeEndedLine();
bEndedLineWrote=true;
}
setOutputDone();
return false;
}
result=writeRowToFile(r);
if (!result)
{
setErrors(1);
stopAll();
return false;
}
putRow(r); // in case we want it to go further...
if ((linesOutput>0) && (linesOutput%Const.ROWS_UPDATE)==0)logBasic("linenr "+linesOutput);
return result;
}
private boolean writeRowToFile(Row r)
{
Value v;
try
{
if (first)
{
first=false;
if (!meta.isFileAppended() && ( meta.isHeaderEnabled() || meta.isFooterEnabled())) // See if we have to write a header-line)
{
data.headerrow=new Row(r); // copy the row for the footer!
if (meta.isHeaderEnabled())
{
if (writeHeader()) return false;
}
}
data.fieldnrs=new int[meta.getOutputFields().length];
for (int i=0;i<meta.getOutputFields().length;i++)
{
data.fieldnrs[i]=r.searchValueIndex(meta.getOutputFields()[i].getName());
if (data.fieldnrs[i]<0)
{
logError("Field ["+meta.getOutputFields()[i].getName()+"] couldn't be found in the input stream!");
setErrors(1);
stopAll();
return false;
}
}
}
if (meta.getOutputFields()==null || meta.getOutputFields().length==0)
{
/*
* Write all values in stream to text file.
*/
for (int i=0;i<r.size();i++)
{
if (i>0) data.writer.write(meta.getSeparator().toCharArray());
v=r.getValue(i);
if(!writeField(v, -1)) return false;
}
data.writer.write(meta.getNewline().toCharArray());
}
else
{
/*
* Only write the fields specified!
*/
for (int i=0;i<meta.getOutputFields().length;i++)
{
if (i>0) data.writer.write(meta.getSeparator().toCharArray());
v=r.getValue(data.fieldnrs[i]);
v.setLength(meta.getOutputFields()[i].getLength(), meta.getOutputFields()[i].getPrecision());
if(!writeField(v, i)) return false;
}
data.writer.write(meta.getNewline().toCharArray());
}
}
catch(Exception e)
{
logError("Error writing line :"+e.toString());
return false;
}
linesOutput++;
return true;
}
private String formatField(Value v, int idx)
{
String retval="";
TextFileField field = null;
if (idx>=0) field = meta.getOutputFields()[idx];
if (v.isString())
{
if (v.isNull() || v.getString()==null)
{
if (idx>=0 && field!=null && field.getNullString()!=null)
{
if (meta.isEnclosureForced() && meta.getEnclosure()!=null)
{
retval=meta.getEnclosure()+field.getNullString()+meta.getEnclosure();
}
else
{
retval=field.getNullString();
}
}
}
else
{
// Any separators in string?
// example: 123.4;"a;b;c";Some name
//
if (meta.isEnclosureForced() && meta.getEnclosure()!=null) // Force enclosure?
{
retval=meta.getEnclosure()+v.toString()+meta.getEnclosure();
}
else // See if there is a separator in the String...
{
int seppos = v.toString().indexOf(meta.getSeparator());
if (seppos<0) retval=v.toString();
else retval=meta.getEnclosure()+v.toString()+meta.getEnclosure();
}
}
}
else if (v.isBigNumber())
{
if (idx>=0 && field!=null && field.getFormat()!=null)
{
if (v.isNull())
{
if (field.getNullString()!=null) retval=field.getNullString();
else retval = "";
}
else
{
data.df.applyPattern(field.getFormat());
if (field.getDecimalSymbol()!=null && field.getDecimalSymbol().length()>0) data.dfs.setDecimalSeparator( field.getDecimalSymbol().charAt(0) );
if (field.getGroupingSymbol()!=null && field.getGroupingSymbol().length()>0) data.dfs.setGroupingSeparator( field.getGroupingSymbol().charAt(0) );
if (field.getCurrencySymbol()!=null) data.dfs.setCurrencySymbol( field.getCurrencySymbol() );
data.df.setDecimalFormatSymbols(data.dfs);
retval=data.df.format(v.getBigNumber());
}
}
else
{
if (v.isNull())
{
if (idx>=0 && field!=null && field.getNullString()!=null) retval=field.getNullString();
else retval = "";
}
else
{
retval=v.toString();
}
}
}
else if (v.isNumeric())
{
if (idx>=0 && field!=null && field.getFormat()!=null)
{
if (v.isNull())
{
if (field.getNullString()!=null) retval=field.getNullString();
else retval = "";
}
else
{
data.df.applyPattern(field.getFormat());
if (field.getDecimalSymbol()!=null && field.getDecimalSymbol().length()>0) data.dfs.setDecimalSeparator( field.getDecimalSymbol().charAt(0) );
if (field.getGroupingSymbol()!=null && field.getGroupingSymbol().length()>0) data.dfs.setGroupingSeparator( field.getGroupingSymbol().charAt(0) );
if (field.getCurrencySymbol()!=null) data.dfs.setCurrencySymbol( field.getCurrencySymbol() );
data.df.setDecimalFormatSymbols(data.dfs);
if ( v.isInteger() )
{
retval=data.df.format(v.getInteger());
}
else if ( v.isNumber() )
{
retval=data.df.format(v.getNumber());
}
}
}
else
{
if (v.isNull())
{
if (idx>=0 && field!=null && field.getNullString()!=null) retval=field.getNullString();
}
else
{
retval=v.toString();
}
}
}
else if (v.isDate())
{
if (idx>=0 && field!=null && field.getFormat()!=null && v.getDate()!=null)
{
data.daf.applyPattern( field.getFormat() );
data.daf.setDateFormatSymbols(data.dafs);
retval= data.daf.format(v.getDate());
}
else
{
if (v.isNull() || v.getDate()==null)
{
if (idx>=0 && field!=null && field.getNullString()!=null) retval=field.getNullString();
}
else
{
retval=v.toString();
}
}
}
else if (v.isBinary())
{
if (v.isNull())
{
if (field.getNullString()!=null) retval=field.getNullString();
else retval=Const.NULL_BINARY;
}
else
{
try {
retval=new String(v.getBytes(), "US-ASCII");
} catch (UnsupportedEncodingException e) {
// changes are small we'll get here. US_ASCII is
// mandatory.
retval=Const.NULL_BINARY;
}
}
}
else // Boolean
{
if (v.isNull())
{
if (idx>=0 && field!=null && field.getNullString()!=null) retval=field.getNullString();
}
else
{
retval=v.toString();
}
}
if (meta.isPadded()) // maybe we need to rightpad to field length?
{
// What's the field length?
int length, precision;
if (idx<0 || field==null) // Nothing specified: get it from the values themselves.
{
length =v.getLength()<0?0:v.getLength();
precision=v.getPrecision()<0?0:v.getPrecision();
}
else // Get the info from the specified lengths & precision...
{
length =field.getLength() <0?0:field.getLength();
precision=field.getPrecision()<0?0:field.getPrecision();
}
if (v.isNumber())
{
length++; // for the sign...
if (precision>0) length++; // for the decimal point...
}
if (v.isDate()) { length=23; precision=0; }
if (v.isBoolean()) { length=5; precision=0; }
retval=Const.rightPad(new StringBuffer(retval), length+precision);
}
return retval;
}
private boolean writeField(Value v, int idx)
{
try
{
String str = formatField(v, idx);
if (str!=null) data.writer.write(str.toCharArray());
}
catch(Exception e)
{
logError("Error writing line :"+e.toString());
return false;
}
return true;
}
private boolean writeEndedLine()
{
boolean retval=false;
try
{
String sLine = meta.getEndedLine();
if (sLine!=null)
{
if (sLine.trim().length()>0)
data.writer.write(sLine.toCharArray());
}
}
catch(Exception e)
{
logError("Error writing ended tag line: "+e.toString());
e.printStackTrace();
retval=true;
}
linesOutput++;
return retval;
}
private boolean writeHeader()
{
boolean retval=false;
Row r=data.headerrow;
try
{
// If we have fields specified: list them in this order!
if (meta.getOutputFields()!=null && meta.getOutputFields().length>0)
{
String header = "";
for (int i=0;i<meta.getOutputFields().length;i++)
{
String fieldName = meta.getOutputFields()[i].getName();
Value v = r.searchValue(fieldName);
if (i>0 && meta.getSeparator()!=null && meta.getSeparator().length()>0)
{
header+=meta.getSeparator();
}
if (meta.isEnclosureForced() && meta.getEnclosure()!=null && v!=null && v.isString())
{
header+=meta.getEnclosure();
}
header+=fieldName;
if (meta.isEnclosureForced() && meta.getEnclosure()!=null && v!=null && v.isString())
{
header+=meta.getEnclosure();
}
}
header+=meta.getNewline();
data.writer.write(header.toCharArray());
}
else
if (r!=null) // Just put all field names in the header/footer
{
for (int i=0;i<r.size();i++)
{
if (i>0) data.writer.write(meta.getSeparator().toCharArray());
Value v = r.getValue(i);
// Header-value contains the name of the value
Value header_value = new Value(v.getName(), Value.VALUE_TYPE_STRING);
header_value.setValue(v.getName());
if (meta.isEnclosureForced() && meta.getEnclosure()!=null && v.isString())
{
data.writer.write(meta.getEnclosure().toCharArray());
}
data.writer.write(header_value.toString().toCharArray());
if (meta.isEnclosureForced() && meta.getEnclosure()!=null && v.isString())
{
data.writer.write(meta.getEnclosure().toCharArray());
}
}
data.writer.write(meta.getNewline().toCharArray());
}
else
{
data.writer.write(("no rows selected"+Const.CR).toCharArray());
}
}
catch(Exception e)
{
logError("Error writing header line: "+e.toString());
e.printStackTrace();
retval=true;
}
linesOutput++;
return retval;
}
public String buildFilename(boolean ziparchive)
{
return meta.buildFilename(getCopy(), data.splitnr, ziparchive);
}
public boolean openNewFile()
{
boolean retval=false;
data.writer=null;
try
{
File file = new File(buildFilename(true));
// Add this to the result file names...
ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL, file, getTransMeta().getName(), getStepname());
resultFile.setComment("This file was created with a text file output step");
addResultFile(resultFile);
OutputStream outputStream;
if (meta.isZipped())
{
FileOutputStream fos = new FileOutputStream(file, meta.isFileAppended());
data.zip = new ZipOutputStream(fos);
File entry = new File(buildFilename(false));
ZipEntry zipentry = new ZipEntry(entry.getName());
zipentry.setComment("Compressed by Kettle");
data.zip.putNextEntry(zipentry);
outputStream=data.zip;
}
else
{
FileOutputStream fos=new FileOutputStream(file, meta.isFileAppended());
outputStream=fos;
}
if (meta.getEncoding()!=null && meta.getEncoding().length()>0)
{
log.logBasic(toString(), "Opening output stream in encoding: "+meta.getEncoding());
data.writer = new OutputStreamWriter(outputStream, meta.getEncoding());
}
else
{
log.logBasic(toString(), "Opening output stream in default encoding");
data.writer = new OutputStreamWriter(outputStream);
}
retval=true;
}
catch(Exception e)
{
logError("Error opening new file : "+e.toString());
}
// System.out.println("end of newFile(), splitnr="+splitnr);
data.splitnr++;
return retval;
}
private boolean closeFile()
{
boolean retval=false;
try
{
if (meta.isZipped())
{
//System.out.println("close zip entry ");
data.zip.closeEntry();
//System.out.println("finish file...");
data.zip.finish();
data.zip.close();
}
else
{
data.writer.close();
}
//System.out.println("Closed file...");
retval=true;
}
catch(Exception e)
{
}
return retval;
}
public boolean init(StepMetaInterface smi, StepDataInterface sdi)
{
meta=(TextFileOutputMeta)smi;
data=(TextFileOutputData)sdi;
if (super.init(smi, sdi))
{
data.splitnr=0;
if (openNewFile())
{
return true;
}
else
{
logError("Couldn't open file "+meta.getFileName());
setErrors(1L);
stopAll();
}
}
return false;
}
public void dispose(StepMetaInterface smi, StepDataInterface sdi)
{
meta=(TextFileOutputMeta)smi;
data=(TextFileOutputData)sdi;
super.dispose(smi, sdi);
closeFile();
}
//
// Run is were the action happens!
public void run()
{
try
{
logBasic("Starting to run...");
while (processRow(meta, data) && !isStopped());
}
catch(Exception e)
{
logError("Unexpected error : "+e.toString());
logError(Const.getStackTracker(e));
setErrors(1);
stopAll();
}
finally
{
dispose(meta, data);
logSummary();
markStop();
}
}
}
| Fix up for CR #3273 : zip file is now closed properly and not cut down halfway.
git-svn-id: 9499f031eb5c9fb9d11553a06c92651e5446d292@1621 5fb7f6ec-07c1-534a-b4ca-9155e429e800
| src/be/ibridge/kettle/trans/step/textfileoutput/TextFileOutput.java | Fix up for CR #3273 : zip file is now closed properly and not cut down halfway. | <ide><path>rc/be/ibridge/kettle/trans/step/textfileoutput/TextFileOutput.java
<ide>
<ide> try
<ide> {
<add> data.writer.close();
<ide> if (meta.isZipped())
<ide> {
<ide> //System.out.println("close zip entry ");
<ide> data.zip.finish();
<ide> data.zip.close();
<ide> }
<del> else
<del> {
<del> data.writer.close();
<del> }
<del>
<ide> //System.out.println("Closed file...");
<del>
<add>
<ide> retval=true;
<ide> }
<ide> catch(Exception e)
<ide> {
<ide> }
<del>
<add>
<ide> return retval;
<ide> }
<ide> |
|
Java | bsd-2-clause | eb2acf8c46608259604bbe85517fae900b2ba4b6 | 0 | RealTimeGenomics/rtg-tools,RealTimeGenomics/rtg-tools,RealTimeGenomics/rtg-tools,RealTimeGenomics/rtg-tools | /*
* Copyright (c) 2017. Real Time Genomics Limited.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.rtg.visualization;
import com.rtg.launcher.globals.GlobalFlags;
import com.rtg.launcher.globals.ToolsGlobalFlags;
import com.rtg.util.StringUtils;
/**
* Assists with display of potentially colored text.
* This base class displays without any markup, and subclasses add markup capability.
*/
public class DisplayHelper {
/** Possible markup implementations */
public enum MarkupType {
/** Perform no markup */
NONE,
/** Markup with <code>ANSI</code> escape sequences */
ANSI,
/** Markup with <code>HTML</code> sequences */
HTML,
}
/** A default instance that can be used for text display */
public static final DisplayHelper DEFAULT = getDefault();
static DisplayHelper getDefault() {
switch ((MarkupType) GlobalFlags.getFlag(ToolsGlobalFlags.DEFAULT_MARKUP).getValue()) {
case ANSI:
return new AnsiDisplayHelper();
case HTML:
return new HtmlDisplayHelper();
case NONE:
default:
return new DisplayHelper();
}
}
static final int LABEL_LENGTH = 6;
static final char SPACE_CHAR = ' ';
static final char INSERT_CHAR = '_';
//Define color identifiers.
/** Color code for black */
public static final int BLACK = 0;
/** Color code for red */
public static final int RED = 1;
/** Color code for green */
public static final int GREEN = 2;
/** Color code for yellow */
public static final int YELLOW = 3;
/** Color code for blue */
public static final int BLUE = 4;
/** Color code for magenta */
public static final int MAGENTA = 5;
/** Color code for cyan */
public static final int CYAN = 6;
/** Color code for white */
public static final int WHITE = 7;
/** Color code for off-white */
public static final int WHITE_PLUS = 8;
String getSpaces(final int diff) {
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < diff; ++i) {
sb.append(SPACE_CHAR);
}
return sb.toString();
}
String getInserts(final int diff) {
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < diff; ++i) {
sb.append(INSERT_CHAR);
}
return sb.toString();
}
int getBaseColor(char readChar) {
switch (readChar) {
case 'a':
case 'A':
return DisplayHelper.GREEN;
case 't':
case 'T':
return DisplayHelper.RED;
case 'c':
case 'C':
return DisplayHelper.BLUE;
case 'g':
case 'G':
return DisplayHelper.MAGENTA;
default:
return -1;
}
}
protected String escape(String text) {
return text;
}
protected String header() {
return null;
}
protected String footer() {
return null;
}
/**
* @return true if display properties can nest
*/
public boolean supportsNesting() {
return false;
}
/**
* Mark up the text with underlining
* @param text the text
* @return the marked up text
*/
public String decorateUnderline(String text) {
return text;
}
/**
* Mark up the text with boldness
* @param text the text
* @return the marked up text
*/
public String decorateBold(String text) {
return text;
}
/**
* Mark up the text with a foreground color
* @param text the text
* @param color the foreground color
* @return the marked up text
*/
public String decorateForeground(String text, int color) {
return text;
}
/**
* Mark up the text with a background color
* @param text the text
* @param color the background color
* @return the marked up text
*/
public String decorateBackground(String text, int color) {
return text;
}
/**
* Mark up the text with foreground and background colors
* @param text the text
* @param fgcolor the foreground color
* @param bgcolor the background color
* @return the marked up text
*/
public String decorate(final String text, int fgcolor, int bgcolor) {
return decorateForeground(decorateBackground(text, bgcolor), fgcolor);
}
protected String decorateLabel(final String label) {
String shortLabel = (label.length() >= LABEL_LENGTH ? label.substring(label.length() - LABEL_LENGTH) : label) + ":";
if (shortLabel.length() < LABEL_LENGTH) {
shortLabel = getSpaces(LABEL_LENGTH - shortLabel.length()) + shortLabel;
}
return decorateForeground(shortLabel, DisplayHelper.CYAN) + " ";
}
protected boolean isMarkupStart(char c) {
return false;
}
protected boolean isMarkupEnd(char c) {
return false;
}
/**
* Mark up a section of text that contains DNA bases, coloring each base accordingly
* @param text the text
* @return the marked up text
*/
public String decorateBases(final String text) {
return decorateWithHighlight(text, null, BLACK, true);
}
// Decorates a section of DNA with highlight colors, not marking up space characters at the ends
protected String decorateWithHighlight(final String str, boolean[] highlightMask, int bgcolor, boolean colorBases) {
final StringBuilder output = new StringBuilder();
int coord = 0; // coordinate ignoring markup
final StringBuilder toHighlight = new StringBuilder();
boolean highlight = false;
boolean inMarkup = false;
for (int i = 0; i < str.length(); ++i) {
final char c = str.charAt(i);
if (inMarkup) {
if (isMarkupEnd(c)) {
inMarkup = false;
}
output.append(c);
} else {
if (isMarkupStart(c)) {
inMarkup = true;
output.append(c);
} else {
final boolean hl = highlightMask != null && coord < highlightMask.length && highlightMask[coord];
if (hl != highlight) {
if (highlight) {
output.append(trimHighlighting(toHighlight.toString(), bgcolor));
toHighlight.setLength(0);
}
highlight = highlightMask[coord];
}
final StringBuilder dest = highlight ? toHighlight : output;
final int col = getBaseColor(c);
if (colorBases && col >= 0) {
dest.append(decorateForeground(String.valueOf(c), col));
} else {
dest.append(c);
}
++coord;
}
}
}
if (highlight) {
output.append(trimHighlighting(toHighlight.toString(), bgcolor));
}
return output.toString();
}
private String trimHighlighting(final String dna, int bgcolor) {
final String trimmed = StringUtils.trimSpaces(dna);
if (trimmed.length() == 0) { // All whitespace, no markup needed
return dna;
}
if (trimmed.length() == dna.length()) { // No trimming needed
return decorateBackground(dna, bgcolor);
} else {
if (dna.charAt(0) == ' ') { // Some amount of non-marked up prefix needed
int prefixEnd = 0;
while (dna.charAt(prefixEnd) == ' ') {
++prefixEnd;
}
return dna.substring(0, prefixEnd) + decorateBackground(trimmed, bgcolor) + dna.substring(prefixEnd + trimmed.length());
} else { // Trimming was only at the end
return decorateBackground(trimmed, bgcolor) + dna.substring(trimmed.length());
}
}
}
/**
* Trims a sequence for display.
* @param sequence the string to clip. May contain markup
* @param clipStart first position in non-markup coordinates to output
* @param clipEnd end position (exclusive) in non-markup coordinates
* @return the clipped sequence.
*/
protected String clipSequence(String sequence, final int clipStart, final int clipEnd) {
final StringBuilder sb = new StringBuilder();
int coord = 0; // coordinate ignoring markup
boolean inMarkup = false;
for (int currpos = 0; currpos < sequence.length(); ++currpos) {
final char c = sequence.charAt(currpos);
if (inMarkup) {
if (isMarkupEnd(c)) {
inMarkup = false;
}
sb.append(c);
} else {
if (isMarkupStart(c)) {
inMarkup = true;
sb.append(c);
} else {
if ((coord >= clipStart) && (coord < clipEnd)) {
sb.append(c);
}
++coord;
}
}
}
return sb.toString();
}
}
| src/com/rtg/visualization/DisplayHelper.java | /*
* Copyright (c) 2017. Real Time Genomics Limited.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.rtg.visualization;
import com.rtg.launcher.globals.GlobalFlags;
import com.rtg.launcher.globals.ToolsGlobalFlags;
import com.rtg.util.StringUtils;
/**
* Assists with display of potentially colored text.
* This base class displays without any markup, and subclasses add markup capability.
*/
public class DisplayHelper {
/** Possible markup implementations */
public enum MarkupType {
/** Perform no markup */
NONE,
/** Markup with <code>ANSI</code> escape sequences */
ANSI,
/** Markup with <code>HTML</code> sequences */
HTML,
}
/** A default instance that can be used for text display */
public static final DisplayHelper DEFAULT = getDefault();
static DisplayHelper getDefault() {
switch ((MarkupType) GlobalFlags.getFlag(ToolsGlobalFlags.DEFAULT_MARKUP).getValue()) {
case ANSI:
return new AnsiDisplayHelper();
case HTML:
return new HtmlDisplayHelper();
case NONE:
default:
return new DisplayHelper();
}
}
static final int LABEL_LENGTH = 6;
static final char SPACE_CHAR = ' ';
static final char INSERT_CHAR = '_';
//Define color identifiers.
/** Color code for black */
public static final int BLACK = 0;
/** Color code for red */
public static final int RED = 1;
/** Color code for green */
public static final int GREEN = 2;
/** Color code for yellow */
public static final int YELLOW = 3;
/** Color code for blue */
public static final int BLUE = 4;
/** Color code for magenta */
public static final int MAGENTA = 5;
/** Color code for cyan */
public static final int CYAN = 6;
/** Color code for white */
public static final int WHITE = 7;
/** Color code for off-white */
public static final int WHITE_PLUS = 8;
String getSpaces(final int diff) {
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < diff; ++i) {
sb.append(SPACE_CHAR);
}
return sb.toString();
}
String getInserts(final int diff) {
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < diff; ++i) {
sb.append(INSERT_CHAR);
}
return sb.toString();
}
int getBaseColor(char readChar) {
switch (readChar) {
case 'a':
case 'A':
return DisplayHelper.GREEN;
case 't':
case 'T':
return DisplayHelper.RED;
case 'c':
case 'C':
return DisplayHelper.BLUE;
case 'g':
case 'G':
return DisplayHelper.MAGENTA;
default:
return -1;
}
}
protected String escape(String text) {
return text;
}
protected String header() {
return null;
}
protected String footer() {
return null;
}
/**
* @return true if display properties can nest
*/
public boolean supportsNesting() {
return false;
}
/**
* Mark up the text with underlining
* @param text the text
* @return the marked up text
*/
public String decorateUnderline(String text) {
return text;
}
/**
* Mark up the text with boldness
* @param text the text
* @return the marked up text
*/
public String decorateBold(String text) {
return text;
}
/**
* Mark up the text with a foreground color
* @param text the text
* @param color the foreground color
* @return the marked up text
*/
public String decorateForeground(String text, int color) {
return text;
}
/**
* Mark up the text with a background color
* @param text the text
* @param color the background color
* @return the marked up text
*/
public String decorateBackground(String text, int color) {
return text;
}
/**
* Mark up the text with foreground and background colors
* @param text the text
* @param fgcolor the foreground color
* @param bgcolor the background color
* @return the marked up text
*/
public String decorate(final String text, int fgcolor, int bgcolor) {
return decorateForeground(decorateBackground(text, bgcolor), fgcolor);
}
protected String decorateLabel(final String label) {
String shortLabel = (label.length() >= LABEL_LENGTH ? label.substring(label.length() - LABEL_LENGTH) : label) + ":";
if (shortLabel.length() < LABEL_LENGTH) {
shortLabel = getSpaces(LABEL_LENGTH - shortLabel.length()) + shortLabel;
}
return decorateForeground(shortLabel, DisplayHelper.CYAN) + " ";
}
protected boolean isMarkupStart(char c) {
return false;
}
protected boolean isMarkupEnd(char c) {
return false;
}
/**
* Mark up a section of text that contains DNA bases, coloring each base accordingly
* @param text the text
* @return the marked up text
*/
public String decorateBases(final String text) {
return decorateWithHighlight(text, null, BLACK, true);
}
// Decorates a section of DNA with highlight colors, not marking up space characters at the ends
protected String decorateWithHighlight(final String str, boolean[] highlightMask, int bgcolor, boolean colorBases) {
final StringBuilder output = new StringBuilder();
int coord = 0; // coordinate ignoring markup
final StringBuilder toHighlight = new StringBuilder();
boolean highlight = false;
boolean inMarkup = false;
for (int i = 0; i < str.length(); ++i) {
final char c = str.charAt(i);
if (inMarkup) {
if (isMarkupEnd(c)) {
inMarkup = false;
}
output.append(c);
} else {
if (isMarkupStart(c)) {
inMarkup = true;
output.append(c);
} else {
if (highlightMask != null && highlightMask[coord] != highlight) {
if (highlight) {
output.append(trimHighlighting(toHighlight.toString(), bgcolor));
toHighlight.setLength(0);
}
highlight = highlightMask[coord];
}
final StringBuilder dest = highlight ? toHighlight : output;
final int col = getBaseColor(c);
if (colorBases && col >= 0) {
dest.append(decorateForeground(String.valueOf(c), col));
} else {
dest.append(c);
}
++coord;
}
}
}
if (highlight) {
output.append(trimHighlighting(toHighlight.toString(), bgcolor));
}
return output.toString();
}
private String trimHighlighting(final String dna, int bgcolor) {
final String trimmed = StringUtils.trimSpaces(dna);
if (trimmed.length() == 0) { // All whitespace, no markup needed
return dna;
}
if (trimmed.length() == dna.length()) { // No trimming needed
return decorateBackground(dna, bgcolor);
} else {
if (dna.charAt(0) == ' ') { // Some amount of non-marked up prefix needed
int prefixEnd = 0;
while (dna.charAt(prefixEnd) == ' ') {
++prefixEnd;
}
return dna.substring(0, prefixEnd) + decorateBackground(trimmed, bgcolor) + dna.substring(prefixEnd + trimmed.length());
} else { // Trimming was only at the end
return decorateBackground(trimmed, bgcolor) + dna.substring(trimmed.length());
}
}
}
/**
* Trims a sequence for display.
* @param sequence the string to clip. May contain markup
* @param clipStart first position in non-markup coordinates to output
* @param clipEnd end position (exclusive) in non-markup coordinates
* @return the clipped sequence.
*/
protected String clipSequence(String sequence, final int clipStart, final int clipEnd) {
final StringBuilder sb = new StringBuilder();
int coord = 0; // coordinate ignoring markup
boolean inMarkup = false;
for (int currpos = 0; currpos < sequence.length(); ++currpos) {
final char c = sequence.charAt(currpos);
if (inMarkup) {
if (isMarkupEnd(c)) {
inMarkup = false;
}
sb.append(c);
} else {
if (isMarkupStart(c)) {
inMarkup = true;
sb.append(c);
} else {
if ((coord >= clipStart) && (coord < clipEnd)) {
sb.append(c);
}
++coord;
}
}
}
return sb.toString();
}
}
| aview: add --print-sample and --sort-sample options
| src/com/rtg/visualization/DisplayHelper.java | aview: add --print-sample and --sort-sample options | <ide><path>rc/com/rtg/visualization/DisplayHelper.java
<ide> inMarkup = true;
<ide> output.append(c);
<ide> } else {
<del> if (highlightMask != null && highlightMask[coord] != highlight) {
<add> final boolean hl = highlightMask != null && coord < highlightMask.length && highlightMask[coord];
<add> if (hl != highlight) {
<ide> if (highlight) {
<ide> output.append(trimHighlighting(toHighlight.toString(), bgcolor));
<ide> toHighlight.setLength(0); |
|
JavaScript | isc | b74c25768036dee87333740e294060f7a818819c | 0 | TechnologyAdvice/Squiss | /*
* Copyright (c) 2015-2016 TechnologyAdvice
*/
'use strict'
const AWS = require('aws-sdk')
const Squiss = require('src/index')
const SQSStub = require('test/stubs/SQSStub')
const delay = require('delay')
let inst = null
const origSQS = AWS.SQS
const wait = (ms) => delay(ms === undefined ? 20 : ms)
describe('index', () => {
afterEach(() => {
if (inst) inst.stop()
inst = null
AWS.SQS = origSQS
})
describe('constructor', () => {
it('creates a new Squiss instance', () => {
inst = new Squiss({
queueUrl: 'foo',
unwrapSns: true,
visibilityTimeoutSecs: 10
})
should.exist(inst)
})
it('fails if queue is not specified', () => {
let errored = false
try {
new Squiss()
} catch (e) {
should.exist(e)
e.should.be.instanceOf(Error)
errored = true
}
errored.should.be.true
})
it('provides a configured sqs client instance', () => {
inst = new Squiss({
queueUrl: 'foo',
awsConfig: {
region: 'us-east-1'
}
})
inst.should.have.property('sqs')
inst.sqs.should.be.an.Object
inst.sqs.config.region.should.equal('us-east-1')
})
})
describe('Receiving', () => {
it('reports the appropriate "running" status', () => {
inst = new Squiss({ queueUrl: 'foo' })
inst._getBatch = () => {}
inst.running.should.be.false
inst.start()
inst.running.should.be.true
})
it('treats start() as idempotent', () => {
inst = new Squiss({ queueUrl: 'foo' })
inst._getBatch = () => {}
inst.running.should.be.false
inst.start()
inst.start()
inst.running.should.be.true
})
it('receives a batch of messages under the max', () => {
const spy = sinon.spy()
inst = new Squiss({ queueUrl: 'foo' })
inst.sqs = new SQSStub(5)
inst.on('gotMessages', spy)
inst.start()
return wait().then(() => {
spy.should.be.calledOnce
spy.should.be.calledWith(5)
})
})
it('receives batches of messages', () => {
const batches = []
const spy = sinon.spy()
inst = new Squiss({ queueUrl: 'foo' })
inst.sqs = new SQSStub(15, 0)
inst.on('gotMessages', (count) => batches.push({total: count, num: 0}))
inst.on('message', () => batches[batches.length - 1].num++)
inst.once('queueEmpty', spy)
inst.start()
return wait().then(() => {
spy.should.be.calledOnce
batches.should.deep.equal([
{total: 10, num: 10},
{total: 5, num: 5}
])
})
})
it('receives batches of messages when maxInflight = receiveBatchSize', () => {
const batches = []
const spy = sinon.spy()
inst = new Squiss({ queueUrl: 'foo', maxInFlight: 10, receiveBatchSize: 10 })
inst.sqs = new SQSStub(15, 0)
inst.on('gotMessages', (count) => batches.push({total: count, num: 0}))
inst.on('message', (m) => {
batches[batches.length - 1].num++
m.del()
})
inst.once('queueEmpty', spy)
inst.start()
return wait().then(() => {
spy.should.be.calledOnce
batches.should.deep.equal([
{total: 10, num: 10},
{total: 5, num: 5}
])
})
})
it('emits queueEmpty event with no messages', () => {
const msgSpy = sinon.spy()
const qeSpy = sinon.spy()
inst = new Squiss({ queueUrl: 'foo' })
inst.sqs = new SQSStub(0, 0)
inst.on('message', msgSpy)
inst.once('queueEmpty', qeSpy)
inst.start()
return wait().then(() => {
msgSpy.should.not.be.called
qeSpy.should.be.calledOnce
})
})
it('emits aborted when stopped with an active message req', () => {
const spy = sinon.spy()
inst = new Squiss({ queueUrl: 'foo' })
inst.sqs = new SQSStub(0, 1000)
inst.on('aborted', spy)
inst.start()
return wait().then(() => {
spy.should.not.be.called
inst.stop()
return wait()
}).then(() => {
spy.should.be.calledOnce
})
})
it('observes the maxInFlight cap', () => {
const msgSpy = sinon.spy()
const maxSpy = sinon.spy()
inst = new Squiss({ queueUrl: 'foo', maxInFlight: 10 })
inst.sqs = new SQSStub(15)
inst.on('message', msgSpy)
inst.on('maxInFlight', maxSpy)
inst.start()
return wait().then(() => {
msgSpy.should.have.callCount(10)
maxSpy.should.have.callCount(1)
})
})
it('respects maxInFlight as 0 (no cap)', () => {
const msgSpy = sinon.spy()
const qeSpy = sinon.spy()
const gmSpy = sinon.spy()
inst = new Squiss({ queueUrl: 'foo', maxInFlight: 0 })
inst.sqs = new SQSStub(35, 0)
inst.on('message', msgSpy)
inst.on('gotMessages', gmSpy)
inst.once('queueEmpty', qeSpy)
inst.start()
return wait(50).then(() => {
msgSpy.should.have.callCount(35)
gmSpy.should.have.callCount(4)
qeSpy.should.have.callCount(1)
})
})
it('reports the correct number of inFlight messages', () => {
const msgs = []
inst = new Squiss({ queueUrl: 'foo', deleteWaitMs: 1 })
inst.sqs = new SQSStub(5)
inst.on('message', (msg) => msgs.push(msg))
inst.start()
return wait().then(() => {
inst.inFlight.should.equal(5)
inst.deleteMessage(msgs.pop())
inst.handledMessage()
return wait(1)
}).then(() => {
inst.inFlight.should.equal(3)
})
})
it('pauses polling when maxInFlight is reached; resumes after', () => {
const msgSpy = sinon.spy()
const maxSpy = sinon.spy()
inst = new Squiss({ queueUrl: 'foo', maxInFlight: 10 })
inst.sqs = new SQSStub(11, 1000)
inst.on('message', msgSpy)
inst.on('maxInFlight', maxSpy)
inst.start()
return wait().then(() => {
msgSpy.should.have.callCount(10)
maxSpy.should.be.calledOnce
for (let i = 0; i < 10; i++) {
inst.handledMessage()
}
return wait()
}).then(() => {
msgSpy.should.have.callCount(11)
})
})
it('observes the visibilityTimeout setting', () => {
inst = new Squiss({ queueUrl: 'foo', visibilityTimeoutSecs: 10 })
inst.sqs = new SQSStub()
const spy = sinon.spy(inst.sqs, 'receiveMessage')
inst.start()
return wait().then(() => {
spy.should.be.calledWith({
QueueUrl: 'foo',
MaxNumberOfMessages: 10,
WaitTimeSeconds: 20,
VisibilityTimeout: 10
})
})
})
it('observes activePollIntervalMs', () => {
const abortSpy = sinon.spy()
const gmSpy = sinon.spy()
inst = new Squiss({ queueUrl: 'foo', activePollIntervalMs: 1000 })
inst.sqs = new SQSStub(1, 0)
inst.on('aborted', abortSpy)
inst.on('gotMessages', gmSpy)
inst.start()
return wait().then(() => {
gmSpy.should.be.calledOnce
abortSpy.should.not.be.called
})
})
it('observes idlePollIntervalMs', () => {
const abortSpy = sinon.spy()
const qeSpy = sinon.spy()
inst = new Squiss({ queueUrl: 'foo', idlePollIntervalMs: 1000 })
inst.sqs = new SQSStub(1, 0)
inst.on('aborted', abortSpy)
inst.on('queueEmpty', qeSpy)
inst.start()
return wait().then(() => {
qeSpy.should.be.calledOnce
abortSpy.should.not.be.called
})
})
})
describe('Deleting', () => {
it('deletes messages using internal API', () => {
const msgs = []
inst = new Squiss({ queueUrl: 'foo', deleteWaitMs: 1 })
inst.sqs = new SQSStub(5)
const spy = sinon.spy(inst.sqs, 'deleteMessageBatch')
inst.on('message', (msg) => msgs.push(msg))
inst.start()
return wait().then(() => {
msgs.should.have.length(5)
inst.deleteMessage(msgs.pop())
return wait(10)
}).then(() => {
spy.should.be.calledOnce
})
})
it('deletes messages using Message API', () => {
const msgs = []
inst = new Squiss({ queueUrl: 'foo', deleteWaitMs: 1 })
inst.sqs = new SQSStub(5)
const spy = sinon.spy(inst.sqs, 'deleteMessageBatch')
inst.on('message', (msg) => msgs.push(msg))
inst.start()
return wait().then(() => {
msgs.should.have.length(5)
msgs.pop().del()
return wait(10)
}).then(() => {
spy.should.be.calledOnce
})
})
it('deletes messages in batches', () => {
inst = new Squiss({ queueUrl: 'foo', deleteWaitMs: 10 })
inst.sqs = new SQSStub(15)
const spy = sinon.spy(inst.sqs, 'deleteMessageBatch')
inst.on('message', (msg) => msg.del())
inst.start()
return wait().then(() => {
spy.should.be.calledTwice
})
})
it('deletes immediately with batch size=1', () => {
inst = new Squiss({ queueUrl: 'foo', deleteBatchSize: 1 })
inst.sqs = new SQSStub(5)
const spy = sinon.spy(inst.sqs, 'deleteMessageBatch')
inst.on('message', (msg) => msg.del())
inst.start()
return wait().then(() => {
spy.should.have.callCount(5)
})
})
it('delWaitTime timeout should be cleared after timeout runs', () => {
const msgs = []
inst = new Squiss({ queueUrl: 'foo', deleteBatchSize: 10, deleteWaitMs: 10})
inst.sqs = new SQSStub(2)
const spy = sinon.spy(inst, '_deleteMessages')
inst.on('message', (msg) => msgs.push(msg))
inst.start()
return wait().then(() => {
inst.stop()
msgs[0].del()
return wait(15)
}).then(() => {
spy.should.be.calledOnce
msgs[1].del()
return wait(15)
}).then(() => {
spy.should.be.calledTwice
})
})
})
describe('Failures', () => {
it('emits delError when a message fails to delete', () => {
const spy = sinon.spy()
inst = new Squiss({ queueUrl: 'foo', deleteBatchSize: 1 })
inst.sqs = new SQSStub(1)
inst.on('delError', spy)
inst.deleteMessage({
raw: {
MessageId: 'foo',
ReceiptHandle: 'bar'
}
})
return wait().then(() => {
spy.should.be.calledOnce
spy.should.be.calledWith({ Code: '404', Id: 'foo', Message: 'Does not exist', SenderFault: true })
})
})
it('emits error when delete call fails', () => {
const spy = sinon.spy()
inst = new Squiss({ queueUrl: 'foo', deleteBatchSize: 1 })
inst.sqs = new SQSStub(1)
inst.sqs.deleteMessageBatch = () => {
return {
promise: () => Promise.reject(new Error('test'))
}
}
inst.on('error', spy)
inst.deleteMessage({
raw: {
MessageId: 'foo',
ReceiptHandle: 'bar'
}
})
return wait().then(() => {
spy.should.be.calledOnce
spy.should.be.calledWith(sinon.match.instanceOf(Error))
})
})
it('emits error when receive call fails', () => {
const spy = sinon.spy()
inst = new Squiss({ queueUrl: 'foo' })
inst.sqs = new SQSStub(1)
inst.sqs.receiveMessage = () => {
return {
promise: () => Promise.reject(new Error('test')),
abort: () => {}
}
}
inst.on('error', spy)
inst.start()
return wait().then(() => {
spy.should.be.calledOnce
spy.should.be.calledWith(sinon.match.instanceOf(Error))
})
})
it('attempts to restart polling after a receive call fails', () => {
const msgSpy = sinon.spy()
const errSpy = sinon.spy()
inst = new Squiss({ queueUrl: 'foo', receiveBatchSize: 1, pollRetryMs: 5})
inst.sqs = new SQSStub(2)
sinon.stub(inst.sqs, 'receiveMessage', () => {
inst.sqs.receiveMessage.restore()
return {
promise: () => Promise.reject(new Error('test')),
abort: () => {}
}
})
inst.on('message', msgSpy)
inst.on('error', errSpy)
inst.start()
return wait().then(() => {
errSpy.should.be.calledOnce
msgSpy.should.be.calledTwice
})
})
it('emits error when GetQueueURL call fails', () => {
const spy = sinon.spy()
inst = new Squiss({ queueName: 'foo' })
inst.sqs.getQueueUrl = () => {
return {
promise: () => Promise.reject(new Error('test'))
}
}
inst.on('error', spy)
inst.start()
return wait().then(() => {
spy.should.be.calledOnce
spy.should.be.calledWith(sinon.match.instanceOf(Error))
})
})
})
describe('Testing', () => {
it('allows queue URLs to be corrected to the endpoint hostname', () => {
inst = new Squiss({ queueName: 'foo', correctQueueUrl: true })
inst.sqs = new SQSStub(1)
return inst.getQueueUrl().then((url) => {
url.should.equal('http://foo.bar/queues/foo')
})
})
})
describe('createQueue', () => {
it('rejects if Squiss was instantiated without queueName', () => {
inst = new Squiss({ queueUrl: 'foo' })
inst.sqs = new SQSStub(1)
return inst.createQueue().should.be.rejected
})
it('calls SQS SDK createQueue method with default attributes', () => {
inst = new Squiss({ queueName: 'foo' })
inst.sqs = new SQSStub(1)
const spy = sinon.spy(inst.sqs, 'createQueue')
return inst.createQueue().then((queueUrl) => {
queueUrl.should.be.a.string
spy.should.be.calledOnce
spy.should.be.calledWith({
QueueName: 'foo',
Attributes: {
ReceiveMessageWaitTimeSeconds: '20',
DelaySeconds: '0',
MaximumMessageSize: '262144',
MessageRetentionPeriod: '345600'
}
})
})
})
it('configures VisibilityTimeout if specified', () => {
inst = new Squiss({ queueName: 'foo', visibilityTimeoutSecs: 15 })
inst.sqs = new SQSStub(1)
const spy = sinon.spy(inst.sqs, 'createQueue')
return inst.createQueue().then((queueUrl) => {
queueUrl.should.be.a.string
spy.should.be.calledOnce
spy.should.be.calledWith({
QueueName: 'foo',
Attributes: {
ReceiveMessageWaitTimeSeconds: '20',
DelaySeconds: '0',
MaximumMessageSize: '262144',
MessageRetentionPeriod: '345600',
VisibilityTimeout: '15'
}
})
})
})
it('calls SQS SDK createQueue method with custom attributes', () => {
inst = new Squiss({
queueName: 'foo',
receiveWaitTimeSecs: 10,
delaySecs: 300,
maxMessageBytes: 100,
messageRetentionSecs: 60,
visibilityTimeoutSecs: 10,
queuePolicy: {foo: 'bar'}
})
inst.sqs = new SQSStub(1)
const spy = sinon.spy(inst.sqs, 'createQueue')
return inst.createQueue().then((queueUrl) => {
queueUrl.should.be.a.string
spy.should.be.calledOnce
spy.should.be.calledWith({
QueueName: 'foo',
Attributes: {
ReceiveMessageWaitTimeSeconds: '10',
DelaySeconds: '300',
MaximumMessageSize: '100',
MessageRetentionPeriod: '60',
VisibilityTimeout: '10',
Policy: {foo: 'bar'}
}
})
})
})
})
describe('deleteQueue', () => {
it('calls SQS SDK deleteQueue method with queue URL', () => {
inst = new Squiss({ queueUrl: 'foo' })
inst.sqs = new SQSStub(1)
const spy = sinon.spy(inst.sqs, 'deleteQueue')
return inst.deleteQueue().then((res) => {
res.should.be.an.object
spy.should.be.calledOnce
spy.should.be.calledWith({ QueueUrl: 'foo' })
})
})
})
describe('getQueueUrl', () => {
it('resolves with the provided queueUrl without hitting SQS', () => {
inst = new Squiss({ queueUrl: 'foo' })
inst.sqs = new SQSStub(1)
const spy = sinon.spy(inst.sqs, 'getQueueUrl')
return inst.getQueueUrl((queueUrl) => {
queueUrl.should.equal('foo')
spy.should.not.be.called
})
})
it('asks SQS for the URL if queueUrl was not provided', () => {
inst = new Squiss({ queueName: 'foo' })
inst.sqs = new SQSStub(1)
const spy = sinon.spy(inst.sqs, 'getQueueUrl')
return inst.getQueueUrl((queueUrl) => {
queueUrl.indexOf('http').should.equal(0)
spy.should.be.calledOnce
spy.should.be.calledWith({ QueueName: 'foo' })
})
})
it('caches the queueUrl after the first call to SQS', () => {
inst = new Squiss({ queueName: 'foo' })
inst.sqs = new SQSStub(1)
const spy = sinon.spy(inst.sqs, 'getQueueUrl')
return inst.getQueueUrl(() => {
spy.should.be.calledOnce
return inst.getQueueUrl()
}).then(() => {
spy.should.be.calledOnce
})
})
it('includes the account number if provided', () => {
inst = new Squiss({ queueName: 'foo', accountNumber: 1234 })
inst.sqs = new SQSStub(1)
const spy = sinon.spy(inst.sqs, 'getQueueUrl')
return inst.getQueueUrl((queueUrl) => {
queueUrl.indexOf('http').should.equal(0)
spy.should.be.calledOnce
spy.should.be.calledWith({
QueueName: 'foo',
QueueOwnerAWSAccountId: '1234'
})
})
})
})
describe('sendMessage', () => {
it('sends a string message with no extra arguments', () => {
inst = new Squiss({ queueUrl: 'foo' })
inst.sqs = new SQSStub()
const spy = sinon.spy(inst.sqs, 'sendMessage')
return inst.sendMessage('bar').then(() => {
spy.should.be.calledOnce
spy.should.be.calledWith({ QueueUrl: 'foo', MessageBody: 'bar' })
})
})
it('sends a JSON message with no extra arguments', () => {
inst = new Squiss({ queueUrl: 'foo' })
inst.sqs = new SQSStub()
const spy = sinon.spy(inst.sqs, 'sendMessage')
return inst.sendMessage({ bar: 'baz' }).then(() => {
spy.should.be.calledOnce
spy.should.be.calledWith({ QueueUrl: 'foo', MessageBody: '{"bar":"baz"}' })
})
})
it('sends a message with a delay and attributes', () => {
inst = new Squiss({ queueUrl: 'foo' })
inst.sqs = new SQSStub()
const spy = sinon.spy(inst.sqs, 'sendMessage')
return inst.sendMessage('bar', 10, { baz: 'fizz' }).then(() => {
spy.should.be.calledWith({
QueueUrl: 'foo',
MessageBody: 'bar',
DelaySeconds: 10,
MessageAttributes: { baz: 'fizz' }
})
})
})
})
describe('sendMessages', () => {
it('sends a single string message with no extra arguments', () => {
inst = new Squiss({ queueUrl: 'foo' })
inst.sqs = new SQSStub()
const spy = sinon.spy(inst.sqs, 'sendMessageBatch')
return inst.sendMessages('bar').then((res) => {
spy.should.be.calledOnce
spy.should.be.calledWith({
QueueUrl: 'foo',
Entries: [
{ Id: '0', MessageBody: 'bar' }
]
})
res.should.have.property('Successful').with.length(1)
res.Successful[0].should.have.property('Id').equal('0')
})
})
it('sends a single JSON message with no extra arguments', () => {
inst = new Squiss({ queueUrl: 'foo' })
inst.sqs = new SQSStub()
const spy = sinon.spy(inst.sqs, 'sendMessageBatch')
return inst.sendMessages({bar: 'baz'}).then(() => {
spy.should.be.calledOnce
spy.should.be.calledWith({
QueueUrl: 'foo',
Entries: [
{ Id: '0', MessageBody: '{"bar":"baz"}' }
]
})
})
})
it('sends a single message with delay and attributes', () => {
inst = new Squiss({ queueUrl: 'foo' })
inst.sqs = new SQSStub()
const spy = sinon.spy(inst.sqs, 'sendMessageBatch')
return inst.sendMessages('bar', 10, { baz: 'fizz' }).then(() => {
spy.should.be.calledOnce
spy.should.be.calledWith({
QueueUrl: 'foo',
Entries: [{
Id: '0',
MessageBody: 'bar',
DelaySeconds: 10,
MessageAttributes: { baz: 'fizz' }
}]
})
})
})
it('sends multiple batches of messages and merges successes', () => {
inst = new Squiss({ queueUrl: 'foo' })
inst.sqs = new SQSStub()
const spy = sinon.spy(inst.sqs, 'sendMessageBatch')
const msgs = 'a.b.c.d.e.f.g.h.i.j.k.l.m.n.o'.split('.')
return inst.sendMessages(msgs).then((res) => {
spy.should.be.calledTwice
inst.sqs.msgs.length.should.equal(15)
res.should.have.property('Successful').with.length(15)
res.should.have.property('Failed').with.length(0)
})
})
it('sends multiple batches of messages and merges failures', () => {
inst = new Squiss({ queueUrl: 'foo' })
inst.sqs = new SQSStub()
const spy = sinon.spy(inst.sqs, 'sendMessageBatch')
const msgs = 'a.FAIL.c.d.e.f.g.h.i.j.k.l.m.n.FAIL'.split('.')
return inst.sendMessages(msgs).then((res) => {
spy.should.be.calledTwice
inst.sqs.msgs.length.should.equal(13)
res.should.have.property('Successful').with.length(13)
res.should.have.property('Failed').with.length(2)
})
})
})
describe('Deprecations', () => {
it('writes to stderr when visibilityTimeout is used', () => {
const stub = sinon.stub(process.stderr, 'write', () => {})
inst = new Squiss({ queueUrl: 'foo', visibilityTimeout: 30})
stub.should.be.calledOnce
stub.restore()
inst._opts.should.have.property('visibilityTimeoutSecs').equal(30)
})
})
})
| test/src/index.spec.js | /*
* Copyright (c) 2015-2016 TechnologyAdvice
*/
'use strict'
const AWS = require('aws-sdk')
const Squiss = require('src/index')
const SQSStub = require('test/stubs/SQSStub')
const delay = require('delay')
let inst = null
const origSQS = AWS.SQS
const wait = (ms) => delay(ms === undefined ? 20 : ms)
describe('index', () => {
afterEach(() => {
if (inst) inst.stop()
inst = null
AWS.SQS = origSQS
})
describe('constructor', () => {
it('creates a new Squiss instance', () => {
inst = new Squiss({
queueUrl: 'foo',
unwrapSns: true,
visibilityTimeout: 10
})
should.exist(inst)
})
it('fails if queue is not specified', () => {
let errored = false
try {
new Squiss()
} catch (e) {
should.exist(e)
e.should.be.instanceOf(Error)
errored = true
}
errored.should.be.true
})
it('provides a configured sqs client instance', () => {
inst = new Squiss({
queueUrl: 'foo',
awsConfig: {
region: 'us-east-1'
}
})
inst.should.have.property('sqs')
inst.sqs.should.be.an.Object
inst.sqs.config.region.should.equal('us-east-1')
})
})
describe('Receiving', () => {
it('reports the appropriate "running" status', () => {
inst = new Squiss({ queueUrl: 'foo' })
inst._getBatch = () => {}
inst.running.should.be.false
inst.start()
inst.running.should.be.true
})
it('treats start() as idempotent', () => {
inst = new Squiss({ queueUrl: 'foo' })
inst._getBatch = () => {}
inst.running.should.be.false
inst.start()
inst.start()
inst.running.should.be.true
})
it('receives a batch of messages under the max', () => {
const spy = sinon.spy()
inst = new Squiss({ queueUrl: 'foo' })
inst.sqs = new SQSStub(5)
inst.on('gotMessages', spy)
inst.start()
return wait().then(() => {
spy.should.be.calledOnce
spy.should.be.calledWith(5)
})
})
it('receives batches of messages', () => {
const batches = []
const spy = sinon.spy()
inst = new Squiss({ queueUrl: 'foo' })
inst.sqs = new SQSStub(15, 0)
inst.on('gotMessages', (count) => batches.push({total: count, num: 0}))
inst.on('message', () => batches[batches.length - 1].num++)
inst.once('queueEmpty', spy)
inst.start()
return wait().then(() => {
spy.should.be.calledOnce
batches.should.deep.equal([
{total: 10, num: 10},
{total: 5, num: 5}
])
})
})
it('receives batches of messages when maxInflight = receiveBatchSize', () => {
const batches = []
const spy = sinon.spy()
inst = new Squiss({ queueUrl: 'foo', maxInFlight: 10, receiveBatchSize: 10 })
inst.sqs = new SQSStub(15, 0)
inst.on('gotMessages', (count) => batches.push({total: count, num: 0}))
inst.on('message', (m) => {
batches[batches.length - 1].num++
m.del()
})
inst.once('queueEmpty', spy)
inst.start()
return wait().then(() => {
spy.should.be.calledOnce
batches.should.deep.equal([
{total: 10, num: 10},
{total: 5, num: 5}
])
})
})
it('emits queueEmpty event with no messages', () => {
const msgSpy = sinon.spy()
const qeSpy = sinon.spy()
inst = new Squiss({ queueUrl: 'foo' })
inst.sqs = new SQSStub(0, 0)
inst.on('message', msgSpy)
inst.once('queueEmpty', qeSpy)
inst.start()
return wait().then(() => {
msgSpy.should.not.be.called
qeSpy.should.be.calledOnce
})
})
it('emits aborted when stopped with an active message req', () => {
const spy = sinon.spy()
inst = new Squiss({ queueUrl: 'foo' })
inst.sqs = new SQSStub(0, 1000)
inst.on('aborted', spy)
inst.start()
return wait().then(() => {
spy.should.not.be.called
inst.stop()
return wait()
}).then(() => {
spy.should.be.calledOnce
})
})
it('observes the maxInFlight cap', () => {
const msgSpy = sinon.spy()
const maxSpy = sinon.spy()
inst = new Squiss({ queueUrl: 'foo', maxInFlight: 10 })
inst.sqs = new SQSStub(15)
inst.on('message', msgSpy)
inst.on('maxInFlight', maxSpy)
inst.start()
return wait().then(() => {
msgSpy.should.have.callCount(10)
maxSpy.should.have.callCount(1)
})
})
it('respects maxInFlight as 0 (no cap)', () => {
const msgSpy = sinon.spy()
const qeSpy = sinon.spy()
const gmSpy = sinon.spy()
inst = new Squiss({ queueUrl: 'foo', maxInFlight: 0 })
inst.sqs = new SQSStub(35, 0)
inst.on('message', msgSpy)
inst.on('gotMessages', gmSpy)
inst.once('queueEmpty', qeSpy)
inst.start()
return wait(50).then(() => {
msgSpy.should.have.callCount(35)
gmSpy.should.have.callCount(4)
qeSpy.should.have.callCount(1)
})
})
it('reports the correct number of inFlight messages', () => {
const msgs = []
inst = new Squiss({ queueUrl: 'foo', deleteWaitMs: 1 })
inst.sqs = new SQSStub(5)
inst.on('message', (msg) => msgs.push(msg))
inst.start()
return wait().then(() => {
inst.inFlight.should.equal(5)
inst.deleteMessage(msgs.pop())
inst.handledMessage()
return wait(1)
}).then(() => {
inst.inFlight.should.equal(3)
})
})
it('pauses polling when maxInFlight is reached; resumes after', () => {
const msgSpy = sinon.spy()
const maxSpy = sinon.spy()
inst = new Squiss({ queueUrl: 'foo', maxInFlight: 10 })
inst.sqs = new SQSStub(11, 1000)
inst.on('message', msgSpy)
inst.on('maxInFlight', maxSpy)
inst.start()
return wait().then(() => {
msgSpy.should.have.callCount(10)
maxSpy.should.be.calledOnce
for (let i = 0; i < 10; i++) {
inst.handledMessage()
}
return wait()
}).then(() => {
msgSpy.should.have.callCount(11)
})
})
it('observes the visibilityTimeout setting', () => {
inst = new Squiss({ queueUrl: 'foo', visibilityTimeoutSecs: 10 })
inst.sqs = new SQSStub()
const spy = sinon.spy(inst.sqs, 'receiveMessage')
inst.start()
return wait().then(() => {
spy.should.be.calledWith({
QueueUrl: 'foo',
MaxNumberOfMessages: 10,
WaitTimeSeconds: 20,
VisibilityTimeout: 10
})
})
})
it('observes activePollIntervalMs', () => {
const abortSpy = sinon.spy()
const gmSpy = sinon.spy()
inst = new Squiss({ queueUrl: 'foo', activePollIntervalMs: 1000 })
inst.sqs = new SQSStub(1, 0)
inst.on('aborted', abortSpy)
inst.on('gotMessages', gmSpy)
inst.start()
return wait().then(() => {
gmSpy.should.be.calledOnce
abortSpy.should.not.be.called
})
})
it('observes idlePollIntervalMs', () => {
const abortSpy = sinon.spy()
const qeSpy = sinon.spy()
inst = new Squiss({ queueUrl: 'foo', idlePollIntervalMs: 1000 })
inst.sqs = new SQSStub(1, 0)
inst.on('aborted', abortSpy)
inst.on('queueEmpty', qeSpy)
inst.start()
return wait().then(() => {
qeSpy.should.be.calledOnce
abortSpy.should.not.be.called
})
})
})
describe('Deleting', () => {
it('deletes messages using internal API', () => {
const msgs = []
inst = new Squiss({ queueUrl: 'foo', deleteWaitMs: 1 })
inst.sqs = new SQSStub(5)
const spy = sinon.spy(inst.sqs, 'deleteMessageBatch')
inst.on('message', (msg) => msgs.push(msg))
inst.start()
return wait().then(() => {
msgs.should.have.length(5)
inst.deleteMessage(msgs.pop())
return wait(10)
}).then(() => {
spy.should.be.calledOnce
})
})
it('deletes messages using Message API', () => {
const msgs = []
inst = new Squiss({ queueUrl: 'foo', deleteWaitMs: 1 })
inst.sqs = new SQSStub(5)
const spy = sinon.spy(inst.sqs, 'deleteMessageBatch')
inst.on('message', (msg) => msgs.push(msg))
inst.start()
return wait().then(() => {
msgs.should.have.length(5)
msgs.pop().del()
return wait(10)
}).then(() => {
spy.should.be.calledOnce
})
})
it('deletes messages in batches', () => {
inst = new Squiss({ queueUrl: 'foo', deleteWaitMs: 10 })
inst.sqs = new SQSStub(15)
const spy = sinon.spy(inst.sqs, 'deleteMessageBatch')
inst.on('message', (msg) => msg.del())
inst.start()
return wait().then(() => {
spy.should.be.calledTwice
})
})
it('deletes immediately with batch size=1', () => {
inst = new Squiss({ queueUrl: 'foo', deleteBatchSize: 1 })
inst.sqs = new SQSStub(5)
const spy = sinon.spy(inst.sqs, 'deleteMessageBatch')
inst.on('message', (msg) => msg.del())
inst.start()
return wait().then(() => {
spy.should.have.callCount(5)
})
})
it('delWaitTime timeout should be cleared after timeout runs', () => {
const msgs = []
inst = new Squiss({ queueUrl: 'foo', deleteBatchSize: 10, deleteWaitMs: 10})
inst.sqs = new SQSStub(2)
const spy = sinon.spy(inst, '_deleteMessages')
inst.on('message', (msg) => msgs.push(msg))
inst.start()
return wait().then(() => {
inst.stop()
msgs[0].del()
return wait(15)
}).then(() => {
spy.should.be.calledOnce
msgs[1].del()
return wait(15)
}).then(() => {
spy.should.be.calledTwice
})
})
})
describe('Failures', () => {
it('emits delError when a message fails to delete', () => {
const spy = sinon.spy()
inst = new Squiss({ queueUrl: 'foo', deleteBatchSize: 1 })
inst.sqs = new SQSStub(1)
inst.on('delError', spy)
inst.deleteMessage({
raw: {
MessageId: 'foo',
ReceiptHandle: 'bar'
}
})
return wait().then(() => {
spy.should.be.calledOnce
spy.should.be.calledWith({ Code: '404', Id: 'foo', Message: 'Does not exist', SenderFault: true })
})
})
it('emits error when delete call fails', () => {
const spy = sinon.spy()
inst = new Squiss({ queueUrl: 'foo', deleteBatchSize: 1 })
inst.sqs = new SQSStub(1)
inst.sqs.deleteMessageBatch = () => {
return {
promise: () => Promise.reject(new Error('test'))
}
}
inst.on('error', spy)
inst.deleteMessage({
raw: {
MessageId: 'foo',
ReceiptHandle: 'bar'
}
})
return wait().then(() => {
spy.should.be.calledOnce
spy.should.be.calledWith(sinon.match.instanceOf(Error))
})
})
it('emits error when receive call fails', () => {
const spy = sinon.spy()
inst = new Squiss({ queueUrl: 'foo' })
inst.sqs = new SQSStub(1)
inst.sqs.receiveMessage = () => {
return {
promise: () => Promise.reject(new Error('test')),
abort: () => {}
}
}
inst.on('error', spy)
inst.start()
return wait().then(() => {
spy.should.be.calledOnce
spy.should.be.calledWith(sinon.match.instanceOf(Error))
})
})
it('attempts to restart polling after a receive call fails', () => {
const msgSpy = sinon.spy()
const errSpy = sinon.spy()
inst = new Squiss({ queueUrl: 'foo', receiveBatchSize: 1, pollRetryMs: 5})
inst.sqs = new SQSStub(2)
sinon.stub(inst.sqs, 'receiveMessage', () => {
inst.sqs.receiveMessage.restore()
return {
promise: () => Promise.reject(new Error('test')),
abort: () => {}
}
})
inst.on('message', msgSpy)
inst.on('error', errSpy)
inst.start()
return wait().then(() => {
errSpy.should.be.calledOnce
msgSpy.should.be.calledTwice
})
})
it('emits error when GetQueueURL call fails', () => {
const spy = sinon.spy()
inst = new Squiss({ queueName: 'foo' })
inst.sqs.getQueueUrl = () => {
return {
promise: () => Promise.reject(new Error('test'))
}
}
inst.on('error', spy)
inst.start()
return wait().then(() => {
spy.should.be.calledOnce
spy.should.be.calledWith(sinon.match.instanceOf(Error))
})
})
})
describe('Testing', () => {
it('allows queue URLs to be corrected to the endpoint hostname', () => {
inst = new Squiss({ queueName: 'foo', correctQueueUrl: true })
inst.sqs = new SQSStub(1)
return inst.getQueueUrl().then((url) => {
url.should.equal('http://foo.bar/queues/foo')
})
})
})
describe('createQueue', () => {
it('rejects if Squiss was instantiated without queueName', () => {
inst = new Squiss({ queueUrl: 'foo' })
inst.sqs = new SQSStub(1)
return inst.createQueue().should.be.rejected
})
it('calls SQS SDK createQueue method with default attributes', () => {
inst = new Squiss({ queueName: 'foo' })
inst.sqs = new SQSStub(1)
const spy = sinon.spy(inst.sqs, 'createQueue')
return inst.createQueue().then((queueUrl) => {
queueUrl.should.be.a.string
spy.should.be.calledOnce
spy.should.be.calledWith({
QueueName: 'foo',
Attributes: {
ReceiveMessageWaitTimeSeconds: '20',
DelaySeconds: '0',
MaximumMessageSize: '262144',
MessageRetentionPeriod: '345600'
}
})
})
})
it('configures VisibilityTimeout if specified', () => {
inst = new Squiss({ queueName: 'foo', visibilityTimeoutSecs: 15 })
inst.sqs = new SQSStub(1)
const spy = sinon.spy(inst.sqs, 'createQueue')
return inst.createQueue().then((queueUrl) => {
queueUrl.should.be.a.string
spy.should.be.calledOnce
spy.should.be.calledWith({
QueueName: 'foo',
Attributes: {
ReceiveMessageWaitTimeSeconds: '20',
DelaySeconds: '0',
MaximumMessageSize: '262144',
MessageRetentionPeriod: '345600',
VisibilityTimeout: '15'
}
})
})
})
it('calls SQS SDK createQueue method with custom attributes', () => {
inst = new Squiss({
queueName: 'foo',
receiveWaitTimeSecs: 10,
delaySecs: 300,
maxMessageBytes: 100,
messageRetentionSecs: 60,
visibilityTimeoutSecs: 10,
queuePolicy: {foo: 'bar'}
})
inst.sqs = new SQSStub(1)
const spy = sinon.spy(inst.sqs, 'createQueue')
return inst.createQueue().then((queueUrl) => {
queueUrl.should.be.a.string
spy.should.be.calledOnce
spy.should.be.calledWith({
QueueName: 'foo',
Attributes: {
ReceiveMessageWaitTimeSeconds: '10',
DelaySeconds: '300',
MaximumMessageSize: '100',
MessageRetentionPeriod: '60',
VisibilityTimeout: '10',
Policy: {foo: 'bar'}
}
})
})
})
})
describe('deleteQueue', () => {
it('calls SQS SDK deleteQueue method with queue URL', () => {
inst = new Squiss({ queueUrl: 'foo' })
inst.sqs = new SQSStub(1)
const spy = sinon.spy(inst.sqs, 'deleteQueue')
return inst.deleteQueue().then((res) => {
res.should.be.an.object
spy.should.be.calledOnce
spy.should.be.calledWith({ QueueUrl: 'foo' })
})
})
})
describe('getQueueUrl', () => {
it('resolves with the provided queueUrl without hitting SQS', () => {
inst = new Squiss({ queueUrl: 'foo' })
inst.sqs = new SQSStub(1)
const spy = sinon.spy(inst.sqs, 'getQueueUrl')
return inst.getQueueUrl((queueUrl) => {
queueUrl.should.equal('foo')
spy.should.not.be.called
})
})
it('asks SQS for the URL if queueUrl was not provided', () => {
inst = new Squiss({ queueName: 'foo' })
inst.sqs = new SQSStub(1)
const spy = sinon.spy(inst.sqs, 'getQueueUrl')
return inst.getQueueUrl((queueUrl) => {
queueUrl.indexOf('http').should.equal(0)
spy.should.be.calledOnce
spy.should.be.calledWith({ QueueName: 'foo' })
})
})
it('caches the queueUrl after the first call to SQS', () => {
inst = new Squiss({ queueName: 'foo' })
inst.sqs = new SQSStub(1)
const spy = sinon.spy(inst.sqs, 'getQueueUrl')
return inst.getQueueUrl(() => {
spy.should.be.calledOnce
return inst.getQueueUrl()
}).then(() => {
spy.should.be.calledOnce
})
})
it('includes the account number if provided', () => {
inst = new Squiss({ queueName: 'foo', accountNumber: 1234 })
inst.sqs = new SQSStub(1)
const spy = sinon.spy(inst.sqs, 'getQueueUrl')
return inst.getQueueUrl((queueUrl) => {
queueUrl.indexOf('http').should.equal(0)
spy.should.be.calledOnce
spy.should.be.calledWith({
QueueName: 'foo',
QueueOwnerAWSAccountId: '1234'
})
})
})
})
describe('sendMessage', () => {
it('sends a string message with no extra arguments', () => {
inst = new Squiss({ queueUrl: 'foo' })
inst.sqs = new SQSStub()
const spy = sinon.spy(inst.sqs, 'sendMessage')
return inst.sendMessage('bar').then(() => {
spy.should.be.calledOnce
spy.should.be.calledWith({ QueueUrl: 'foo', MessageBody: 'bar' })
})
})
it('sends a JSON message with no extra arguments', () => {
inst = new Squiss({ queueUrl: 'foo' })
inst.sqs = new SQSStub()
const spy = sinon.spy(inst.sqs, 'sendMessage')
return inst.sendMessage({ bar: 'baz' }).then(() => {
spy.should.be.calledOnce
spy.should.be.calledWith({ QueueUrl: 'foo', MessageBody: '{"bar":"baz"}' })
})
})
it('sends a message with a delay and attributes', () => {
inst = new Squiss({ queueUrl: 'foo' })
inst.sqs = new SQSStub()
const spy = sinon.spy(inst.sqs, 'sendMessage')
return inst.sendMessage('bar', 10, { baz: 'fizz' }).then(() => {
spy.should.be.calledWith({
QueueUrl: 'foo',
MessageBody: 'bar',
DelaySeconds: 10,
MessageAttributes: { baz: 'fizz' }
})
})
})
})
describe('sendMessages', () => {
it('sends a single string message with no extra arguments', () => {
inst = new Squiss({ queueUrl: 'foo' })
inst.sqs = new SQSStub()
const spy = sinon.spy(inst.sqs, 'sendMessageBatch')
return inst.sendMessages('bar').then((res) => {
spy.should.be.calledOnce
spy.should.be.calledWith({
QueueUrl: 'foo',
Entries: [
{ Id: '0', MessageBody: 'bar' }
]
})
res.should.have.property('Successful').with.length(1)
res.Successful[0].should.have.property('Id').equal('0')
})
})
it('sends a single JSON message with no extra arguments', () => {
inst = new Squiss({ queueUrl: 'foo' })
inst.sqs = new SQSStub()
const spy = sinon.spy(inst.sqs, 'sendMessageBatch')
return inst.sendMessages({bar: 'baz'}).then(() => {
spy.should.be.calledOnce
spy.should.be.calledWith({
QueueUrl: 'foo',
Entries: [
{ Id: '0', MessageBody: '{"bar":"baz"}' }
]
})
})
})
it('sends a single message with delay and attributes', () => {
inst = new Squiss({ queueUrl: 'foo' })
inst.sqs = new SQSStub()
const spy = sinon.spy(inst.sqs, 'sendMessageBatch')
return inst.sendMessages('bar', 10, { baz: 'fizz' }).then(() => {
spy.should.be.calledOnce
spy.should.be.calledWith({
QueueUrl: 'foo',
Entries: [{
Id: '0',
MessageBody: 'bar',
DelaySeconds: 10,
MessageAttributes: { baz: 'fizz' }
}]
})
})
})
it('sends multiple batches of messages and merges successes', () => {
inst = new Squiss({ queueUrl: 'foo' })
inst.sqs = new SQSStub()
const spy = sinon.spy(inst.sqs, 'sendMessageBatch')
const msgs = 'a.b.c.d.e.f.g.h.i.j.k.l.m.n.o'.split('.')
return inst.sendMessages(msgs).then((res) => {
spy.should.be.calledTwice
inst.sqs.msgs.length.should.equal(15)
res.should.have.property('Successful').with.length(15)
res.should.have.property('Failed').with.length(0)
})
})
it('sends multiple batches of messages and merges failures', () => {
inst = new Squiss({ queueUrl: 'foo' })
inst.sqs = new SQSStub()
const spy = sinon.spy(inst.sqs, 'sendMessageBatch')
const msgs = 'a.FAIL.c.d.e.f.g.h.i.j.k.l.m.n.FAIL'.split('.')
return inst.sendMessages(msgs).then((res) => {
spy.should.be.calledTwice
inst.sqs.msgs.length.should.equal(13)
res.should.have.property('Successful').with.length(13)
res.should.have.property('Failed').with.length(2)
})
})
})
describe('Deprecations', () => {
it('writes to stderr when visibilityTimeout is used', () => {
const stub = sinon.stub(process.stderr, 'write', () => {})
inst = new Squiss({ queueUrl: 'foo', visibilityTimeout: 30})
stub.should.be.calledOnce
stub.restore()
inst._opts.should.have.property('visibilityTimeoutSecs').equal(30)
})
})
})
| Test: Don't use deprecated props
| test/src/index.spec.js | Test: Don't use deprecated props | <ide><path>est/src/index.spec.js
<ide> inst = new Squiss({
<ide> queueUrl: 'foo',
<ide> unwrapSns: true,
<del> visibilityTimeout: 10
<add> visibilityTimeoutSecs: 10
<ide> })
<ide> should.exist(inst)
<ide> }) |
|
Java | agpl-3.0 | e924f1696720ca05a777275b3a8f059a731f28eb | 0 | lp0/cursus-core,lp0/cursus-ui | /*
cursus - Race series management program
Copyright 2011 Simon Arlott
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package eu.lp0.cursus.scoring;
import java.util.HashSet;
import java.util.Map.Entry;
import java.util.Set;
import com.google.common.base.Predicates;
import com.google.common.collect.Sets;
import eu.lp0.cursus.db.data.Pilot;
import eu.lp0.cursus.db.data.Race;
public class GenericOverallPointsData<T extends ScoredData & RacePointsData & RaceDiscardsData & OverallPenaltiesData> extends AbstractOverallPointsData<T> {
public GenericOverallPointsData(T scores) {
super(scores);
}
@Override
protected int calculateOverallPoints(Pilot pilot) {
int points = 0;
Set<Race> discardedRaces = scores.getDiscardedRaces(pilot);
// Add race points but not discards
for (Entry<Race, Integer> racePoints : scores.getRacePoints(pilot).entrySet()) {
if (!discardedRaces.contains(racePoints.getKey())) {
points += racePoints.getValue();
}
}
// Add all penalties (this includes race penalties)
points += scores.getOverallPenalties(pilot);
if (points < 0) {
points = 0;
}
return points;
}
@Override
protected int calculateOverallFleetSize() {
Set<Pilot> pilots = new HashSet<Pilot>(scores.getPilots().size() * 2);
for (Race race : scores.getRaces()) {
pilots.addAll(Sets.filter(race.getAttendees().keySet(), Predicates.in(scores.getPilots())));
}
return pilots.size();
}
} | src/main/java/eu/lp0/cursus/scoring/GenericOverallPointsData.java | /*
cursus - Race series management program
Copyright 2011 Simon Arlott
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package eu.lp0.cursus.scoring;
import java.util.HashSet;
import java.util.Map.Entry;
import java.util.Set;
import com.google.common.base.Predicates;
import com.google.common.collect.Sets;
import eu.lp0.cursus.db.data.Pilot;
import eu.lp0.cursus.db.data.Race;
public class GenericOverallPointsData<T extends ScoredData & RacePointsData & RaceDiscardsData & OverallPenaltiesData> extends AbstractOverallPointsData<T> {
public enum OverallFleetMethod {
FILTERED, UNFILTERED;
}
public GenericOverallPointsData(T scores) {
super(scores);
}
@Override
protected int calculateOverallPoints(Pilot pilot) {
int points = 0;
Set<Race> discardedRaces = scores.getDiscardedRaces(pilot);
// Add race points but not discards
for (Entry<Race, Integer> racePoints : scores.getRacePoints(pilot).entrySet()) {
if (!discardedRaces.contains(racePoints.getKey())) {
points += racePoints.getValue();
}
}
// Add all penalties (this includes race penalties)
points += scores.getOverallPenalties(pilot);
if (points < 0) {
points = 0;
}
return points;
}
@Override
protected int calculateOverallFleetSize() {
Set<Pilot> pilots = new HashSet<Pilot>(scores.getPilots().size() * 2);
for (Race race : scores.getRaces()) {
pilots.addAll(Sets.filter(race.getAttendees().keySet(), Predicates.in(scores.getPilots())));
}
return pilots.size();
}
} | remove unused enum | src/main/java/eu/lp0/cursus/scoring/GenericOverallPointsData.java | remove unused enum | <ide><path>rc/main/java/eu/lp0/cursus/scoring/GenericOverallPointsData.java
<ide> import eu.lp0.cursus.db.data.Race;
<ide>
<ide> public class GenericOverallPointsData<T extends ScoredData & RacePointsData & RaceDiscardsData & OverallPenaltiesData> extends AbstractOverallPointsData<T> {
<del> public enum OverallFleetMethod {
<del> FILTERED, UNFILTERED;
<del> }
<del>
<ide> public GenericOverallPointsData(T scores) {
<ide> super(scores);
<ide> } |
|
Java | apache-2.0 | ab4e07cc15ffb2e70316718b9f03fcab4dcc0263 | 0 | Overseas-Student-Living/jackrabbit,kigsmtua/jackrabbit,Kast0rTr0y/jackrabbit,SylvesterAbreu/jackrabbit,afilimonov/jackrabbit,tripodsan/jackrabbit,Overseas-Student-Living/jackrabbit,sdmcraft/jackrabbit,tripodsan/jackrabbit,sdmcraft/jackrabbit,bartosz-grabski/jackrabbit,afilimonov/jackrabbit,SylvesterAbreu/jackrabbit,SylvesterAbreu/jackrabbit,kigsmtua/jackrabbit,afilimonov/jackrabbit,tripodsan/jackrabbit,Kast0rTr0y/jackrabbit,kigsmtua/jackrabbit,bartosz-grabski/jackrabbit,Kast0rTr0y/jackrabbit,Overseas-Student-Living/jackrabbit,sdmcraft/jackrabbit,bartosz-grabski/jackrabbit | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.core.persistence.bundle;
import static org.apache.jackrabbit.spi.commons.name.NameConstants.JCR_MIXINTYPES;
import static org.apache.jackrabbit.spi.commons.name.NameConstants.JCR_PRIMARYTYPE;
import static org.apache.jackrabbit.spi.commons.name.NameConstants.JCR_UUID;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import javax.jcr.PropertyType;
import org.apache.jackrabbit.api.stats.RepositoryStatistics;
import org.apache.jackrabbit.core.cache.Cache;
import org.apache.jackrabbit.core.cache.CacheAccessListener;
import org.apache.jackrabbit.core.cache.ConcurrentCache;
import org.apache.jackrabbit.core.fs.FileSystem;
import org.apache.jackrabbit.core.fs.FileSystemResource;
import org.apache.jackrabbit.core.id.ItemId;
import org.apache.jackrabbit.core.id.NodeId;
import org.apache.jackrabbit.core.id.PropertyId;
import org.apache.jackrabbit.core.persistence.CachingPersistenceManager;
import org.apache.jackrabbit.core.persistence.IterablePersistenceManager;
import org.apache.jackrabbit.core.persistence.PMContext;
import org.apache.jackrabbit.core.persistence.PersistenceManager;
import org.apache.jackrabbit.core.persistence.util.BLOBStore;
import org.apache.jackrabbit.core.persistence.util.FileBasedIndex;
import org.apache.jackrabbit.core.persistence.util.NodePropBundle;
import org.apache.jackrabbit.core.persistence.util.NodePropBundle.PropertyEntry;
import org.apache.jackrabbit.core.state.ChangeLog;
import org.apache.jackrabbit.core.state.ItemState;
import org.apache.jackrabbit.core.state.ItemStateException;
import org.apache.jackrabbit.core.state.NoSuchItemStateException;
import org.apache.jackrabbit.core.state.NodeReferences;
import org.apache.jackrabbit.core.state.NodeState;
import org.apache.jackrabbit.core.state.PropertyState;
import org.apache.jackrabbit.core.stats.RepositoryStatisticsImpl;
import org.apache.jackrabbit.core.util.StringIndex;
import org.apache.jackrabbit.core.value.InternalValue;
import org.apache.jackrabbit.spi.Name;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The <code>AbstractBundlePersistenceManager</code> acts as base for all
* persistence managers that store the state in a {@link NodePropBundle}.
* <p/>
* The state and all property states of one node are stored together in one
* record. Property values of a certain size can be store outside of the bundle.
* This currently only works for binary properties. NodeReferences are not
* included in the bundle since they are addressed by the target id.
* <p/>
* Some strings like namespaces and local names are additionally managed by
* separate indexes. only the index number is serialized to the records which
* reduces the amount of memory used.
* <p/>
* Special treatment is performed for the properties "jcr:uuid", "jcr:primaryType"
* and "jcr:mixinTypes". As they are also stored in the node state they are not
* included in the bundle but generated when required.
* <p/>
* In order to increase performance, there are 2 caches maintained. One is the
* bundle cache that caches already loaded bundles. The other is the
* {@link LRUNodeIdCache} that caches non-existent bundles. This is useful
* because a lot of {@link #exists(NodeId)} calls are issued that would result
* in a useless SQL execution if the desired bundle does not exist.
* <p/>
* Configuration:<br>
* <ul>
* <li><param name="{@link #setBundleCacheSize(String) bundleCacheSize}" value="8"/>
* </ul>
*/
public abstract class AbstractBundlePersistenceManager implements
PersistenceManager, CachingPersistenceManager, IterablePersistenceManager, CacheAccessListener {
/** the default logger */
private static Logger log = LoggerFactory.getLogger(AbstractBundlePersistenceManager.class);
/** the prefix of a node file */
protected static final String NODEFILENAME = "n";
/** the prefix of a node references file */
protected static final String NODEREFSFILENAME = "r";
/** the name of the names-index resource */
protected static final String RES_NAME_INDEX = "/names.properties";
/** the name of the namespace-index resource */
protected static final String RES_NS_INDEX = "/namespaces.properties";
/** Sentinel instance used to mark a non-existent bundle in the cache */
private static final NodePropBundle MISSING =
new NodePropBundle(NodeId.randomId());
/** the index for namespaces */
private StringIndex nsIndex;
/** the index for local names */
private StringIndex nameIndex;
/** the cache of loaded bundles */
private ConcurrentCache<NodeId, NodePropBundle> bundles;
/** The default minimum stats logging interval (in ms). */
private static final int DEFAULT_LOG_STATS_INTERVAL = 60 * 1000;
/** The minimum interval time between stats are logged */
private long minLogStatsInterval = Long.getLong(
"org.apache.jackrabbit.cacheLogStatsInterval",
DEFAULT_LOG_STATS_INTERVAL);
/** The last time the cache stats were logged. */
private volatile long nextLogStats =
System.currentTimeMillis() + DEFAULT_LOG_STATS_INTERVAL;
/** the persistence manager context */
protected PMContext context;
/** default size of the bundle cache */
private long bundleCacheSize = 8 * 1024 * 1024;
/** Counter of read operations. */
private AtomicLong readCounter;
/** Counter of write operations. */
private AtomicLong writeCounter;
/** Duration of read operations. */
private AtomicLong readDuration;
/** Duration of write operations. */
private AtomicLong writeDuration;
/** Counter of bundle cache accesses. */
private AtomicLong cacheCounter;
/**
* Returns the size of the bundle cache in megabytes.
* @return the size of the bundle cache in megabytes.
*/
public String getBundleCacheSize() {
return String.valueOf(bundleCacheSize / (1024 * 1024));
}
/**
* Sets the size of the bundle cache in megabytes.
* the default is 8.
*
* @param bundleCacheSize the bundle cache size in megabytes.
*/
public void setBundleCacheSize(String bundleCacheSize) {
this.bundleCacheSize = Long.parseLong(bundleCacheSize) * 1024 * 1024;
}
/**
* Creates the folder path for the given node id that is suitable for
* storing states in a filesystem.
*
* @param buf buffer to append to or <code>null</code>
* @param id the id of the node
* @return the buffer with the appended data.
*/
protected StringBuffer buildNodeFolderPath(StringBuffer buf, NodeId id) {
if (buf == null) {
buf = new StringBuffer();
}
char[] chars = id.toString().toCharArray();
int cnt = 0;
for (int i = 0; i < chars.length; i++) {
if (chars[i] == '-') {
continue;
}
//if (cnt > 0 && cnt % 4 == 0) {
if (cnt == 2 || cnt == 4) {
buf.append(FileSystem.SEPARATOR_CHAR);
}
buf.append(chars[i]);
cnt++;
}
return buf;
}
/**
* Creates the folder path for the given property id that is suitable for
* storing states in a filesystem.
*
* @param buf buffer to append to or <code>null</code>
* @param id the id of the property
* @return the buffer with the appended data.
*/
protected StringBuffer buildPropFilePath(StringBuffer buf, PropertyId id) {
if (buf == null) {
buf = new StringBuffer();
}
buildNodeFolderPath(buf, id.getParentId());
buf.append(FileSystem.SEPARATOR);
buf.append(getNsIndex().stringToIndex(id.getName().getNamespaceURI()));
buf.append('.');
buf.append(getNameIndex().stringToIndex(id.getName().getLocalName()));
return buf;
}
/**
* Creates the file path for the given property id and value index that is
* suitable for storing property values in a filesystem.
*
* @param buf buffer to append to or <code>null</code>
* @param id the id of the property
* @param i the index of the property value
* @return the buffer with the appended data.
*/
protected StringBuffer buildBlobFilePath(StringBuffer buf, PropertyId id,
int i) {
if (buf == null) {
buf = new StringBuffer();
}
buildPropFilePath(buf, id);
buf.append('.');
buf.append(i);
return buf;
}
/**
* Creates the file path for the given node id that is
* suitable for storing node states in a filesystem.
*
* @param buf buffer to append to or <code>null</code>
* @param id the id of the node
* @return the buffer with the appended data.
*/
protected StringBuffer buildNodeFilePath(StringBuffer buf, NodeId id) {
if (buf == null) {
buf = new StringBuffer();
}
buildNodeFolderPath(buf, id);
buf.append(FileSystem.SEPARATOR);
buf.append(NODEFILENAME);
return buf;
}
/**
* Creates the file path for the given references id that is
* suitable for storing reference states in a filesystem.
*
* @param buf buffer to append to or <code>null</code>
* @param id the id of the node
* @return the buffer with the appended data.
*/
protected StringBuffer buildNodeReferencesFilePath(
StringBuffer buf, NodeId id) {
if (buf == null) {
buf = new StringBuffer();
}
buildNodeFolderPath(buf, id);
buf.append(FileSystem.SEPARATOR);
buf.append(NODEREFSFILENAME);
return buf;
}
/**
* Returns the namespace index
* @return the namespace index
* @throws IllegalStateException if an error occurs.
*/
public StringIndex getNsIndex() {
try {
if (nsIndex == null) {
// load name and ns index
FileSystemResource nsFile = new FileSystemResource(context.getFileSystem(), RES_NS_INDEX);
if (nsFile.exists()) {
nsIndex = new FileBasedIndex(nsFile);
} else {
nsIndex = (StringIndex) context.getNamespaceRegistry();
}
}
return nsIndex;
} catch (Exception e) {
IllegalStateException e2 = new IllegalStateException("Unable to create nsIndex.");
e2.initCause(e);
throw e2;
}
}
/**
* Returns the local name index
* @return the local name index
* @throws IllegalStateException if an error occurs.
*/
public StringIndex getNameIndex() {
try {
if (nameIndex == null) {
nameIndex = new FileBasedIndex(new FileSystemResource(
context.getFileSystem(), RES_NAME_INDEX));
}
return nameIndex;
} catch (Exception e) {
IllegalStateException e2 = new IllegalStateException("Unable to create nameIndex.");
e2.initCause(e);
throw e2;
}
}
//-----------------------------------------< CacheablePersistenceManager >--
/**
* {@inheritDoc}
*/
public synchronized void onExternalUpdate(ChangeLog changes) {
for (ItemState state : changes.modifiedStates()) {
bundles.remove(getBundleId(state));
}
for (ItemState state : changes.deletedStates()) {
bundles.remove(getBundleId(state));
}
for (ItemState state : changes.addedStates()) {
// There may have been a cache miss entry
bundles.remove(getBundleId(state));
}
}
private NodeId getBundleId(ItemState state) {
if (state.isNode()) {
return (NodeId) state.getId();
} else {
return state.getParentId();
}
}
//----------------------------------------------------------------< spi >---
/**
* Loads a bundle from the underlying system.
*
* @param id the node id of the bundle
* @return the loaded bundle or <code>null</code> if the bundle does not
* exist.
* @throws ItemStateException if an error while loading occurs.
*/
protected abstract NodePropBundle loadBundle(NodeId id)
throws ItemStateException;
/**
* Stores a bundle to the underlying system.
*
* @param bundle the bundle to store
* @throws ItemStateException if an error while storing occurs.
*/
protected abstract void storeBundle(NodePropBundle bundle)
throws ItemStateException;
/**
* Deletes the bundle from the underlying system.
*
* @param bundle the bundle to destroy
*
* @throws ItemStateException if an error while destroying occurs.
*/
protected abstract void destroyBundle(NodePropBundle bundle)
throws ItemStateException;
/**
* Deletes the node references from the underlying system.
*
* @param refs the node references to destroy.
* @throws ItemStateException if an error while destroying occurs.
*/
protected abstract void destroy(NodeReferences refs)
throws ItemStateException;
/**
* Stores a node references to the underlying system.
*
* @param refs the node references to store.
* @throws ItemStateException if an error while storing occurs.
*/
protected abstract void store(NodeReferences refs)
throws ItemStateException;
/**
* Returns the BLOB store used by this persistence manager.
*
* @return BLOB store
*/
protected abstract BLOBStore getBlobStore();
//-------------------------------------------------< PersistenceManager >---
/**
* {@inheritDoc}
*
* Initializes the internal structures of this abstract persistence manager.
*/
public void init(PMContext context) throws Exception {
this.context = context;
// init bundle cache
bundles = new ConcurrentCache<NodeId, NodePropBundle>(context.getHomeDir().getName() + "BundleCache");
bundles.setMaxMemorySize(bundleCacheSize);
bundles.setAccessListener(this);
// statistics
RepositoryStatisticsImpl stats = context.getRepositoryStatistics();
cacheCounter = stats.getCounter(
RepositoryStatistics.Type.BUNDLE_CACHE_COUNTER);
readCounter = stats.getCounter(
RepositoryStatistics.Type.BUNDLE_READ_COUNTER);
readDuration = stats.getCounter(
RepositoryStatistics.Type.BUNDLE_READ_DURATION);
writeCounter = stats.getCounter(
RepositoryStatistics.Type.BUNDLE_WRITE_COUNTER);
writeDuration = stats.getCounter(
RepositoryStatistics.Type.BUNDLE_WRITE_DURATION);
}
/**
* {@inheritDoc}
*
* Closes the persistence manager, release acquired resources.
*/
public void close() throws Exception {
// clear caches
bundles.clear();
}
/**
* {@inheritDoc}
*
* Loads the state via the appropriate NodePropBundle.
*/
public NodeState load(NodeId id) throws NoSuchItemStateException, ItemStateException {
NodePropBundle bundle = getBundle(id);
if (bundle == null) {
throw new NoSuchItemStateException(id.toString());
}
return bundle.createNodeState(this);
}
/**
* {@inheritDoc}
*
* Loads the state via the appropriate NodePropBundle.
*/
public PropertyState load(PropertyId id) throws NoSuchItemStateException, ItemStateException {
NodePropBundle bundle = getBundle(id.getParentId());
if (bundle != null) {
PropertyState state = createNew(id);
PropertyEntry p = bundle.getPropertyEntry(id.getName());
if (p != null) {
state.setMultiValued(p.isMultiValued());
state.setType(p.getType());
state.setValues(p.getValues());
state.setModCount(p.getModCount());
} else if (id.getName().equals(JCR_UUID)) {
state.setType(PropertyType.STRING);
state.setMultiValued(false);
state.setValues(new InternalValue[] {
InternalValue.create(id.getParentId().toString()) });
} else if (id.getName().equals(JCR_PRIMARYTYPE)) {
state.setType(PropertyType.NAME);
state.setMultiValued(false);
state.setValues(new InternalValue[] {
InternalValue.create(bundle.getNodeTypeName()) });
} else if (id.getName().equals(JCR_MIXINTYPES)) {
state.setType(PropertyType.NAME);
state.setMultiValued(true);
Set<Name> mixins = bundle.getMixinTypeNames();
state.setValues(InternalValue.create(
mixins.toArray(new Name[mixins.size()])));
} else {
throw new NoSuchItemStateException(id.toString());
}
return state;
} else {
throw new NoSuchItemStateException(id.toString());
}
}
/**
* {@inheritDoc}
*
* Loads the state via the appropriate NodePropBundle.
*/
public boolean exists(PropertyId id) throws ItemStateException {
NodePropBundle bundle = getBundle(id.getParentId());
if (bundle != null) {
Name name = id.getName();
return bundle.hasProperty(name)
|| JCR_PRIMARYTYPE.equals(name)
|| (JCR_UUID.equals(name) && bundle.isReferenceable())
|| (JCR_MIXINTYPES.equals(name)
&& !bundle.getMixinTypeNames().isEmpty());
} else {
return false;
}
}
/**
* {@inheritDoc}
*
* Checks the existence via the appropriate NodePropBundle.
*/
public boolean exists(NodeId id) throws ItemStateException {
// anticipating a load followed by a exists
return getBundle(id) != null;
}
/**
* {@inheritDoc}
*/
public NodeState createNew(NodeId id) {
return new NodeState(id, null, null, NodeState.STATUS_NEW, false);
}
/**
* {@inheritDoc}
*/
public PropertyState createNew(PropertyId id) {
return new PropertyState(id, PropertyState.STATUS_NEW, false);
}
/**
* Right now, this iterates over all items in the changelog and
* calls the individual methods that handle single item states
* or node references objects. Properly implemented, this method
* should ensure that changes are either written completely to
* the underlying persistence layer, or not at all.
*
* {@inheritDoc}
*/
public synchronized void store(ChangeLog changeLog)
throws ItemStateException {
boolean success = false;
try {
storeInternal(changeLog);
success = true;
} finally {
if (!success) {
bundles.clear();
}
}
}
/**
* Stores the given changelog and updates the bundle cache.
*
* @param changeLog the changelog to store
* @throws ItemStateException on failure
*/
private void storeInternal(ChangeLog changeLog)
throws ItemStateException {
// delete bundles
HashSet<ItemId> deleted = new HashSet<ItemId>();
for (ItemState state : changeLog.deletedStates()) {
if (state.isNode()) {
NodePropBundle bundle = getBundle((NodeId) state.getId());
if (bundle == null) {
throw new NoSuchItemStateException(state.getId().toString());
}
deleteBundle(bundle);
deleted.add(state.getId());
}
}
// gather added node states
HashMap<ItemId, NodePropBundle> modified = new HashMap<ItemId, NodePropBundle>();
for (ItemState state : changeLog.addedStates()) {
if (state.isNode()) {
NodePropBundle bundle = new NodePropBundle((NodeState) state);
modified.put(state.getId(), bundle);
}
}
// gather modified node states
for (ItemState state : changeLog.modifiedStates()) {
if (state.isNode()) {
NodeId nodeId = (NodeId) state.getId();
NodePropBundle bundle = modified.get(nodeId);
if (bundle == null) {
bundle = getBundle(nodeId);
if (bundle == null) {
throw new NoSuchItemStateException(nodeId.toString());
}
modified.put(nodeId, bundle);
}
bundle.update((NodeState) state);
} else {
PropertyId id = (PropertyId) state.getId();
// skip redundant primaryType, mixinTypes and uuid properties
if (id.getName().equals(JCR_PRIMARYTYPE)
|| id.getName().equals(JCR_MIXINTYPES)
|| id.getName().equals(JCR_UUID)) {
continue;
}
NodeId nodeId = id.getParentId();
NodePropBundle bundle = modified.get(nodeId);
if (bundle == null) {
bundle = getBundle(nodeId);
if (bundle == null) {
throw new NoSuchItemStateException(nodeId.toString());
}
modified.put(nodeId, bundle);
}
bundle.addProperty((PropertyState) state, getBlobStore());
}
}
// add removed properties
for (ItemState state : changeLog.deletedStates()) {
if (state.isNode()) {
// check consistency
NodeId parentId = state.getParentId();
if (!modified.containsKey(parentId) && !deleted.contains(parentId)) {
log.warn("Deleted node state's parent is not modified or deleted: " + parentId + "/" + state.getId());
}
} else {
PropertyId id = (PropertyId) state.getId();
NodeId nodeId = id.getParentId();
if (!deleted.contains(nodeId)) {
NodePropBundle bundle = modified.get(nodeId);
if (bundle == null) {
// should actually not happen
log.warn("deleted property state's parent not modified!");
bundle = getBundle(nodeId);
if (bundle == null) {
throw new NoSuchItemStateException(nodeId.toString());
}
modified.put(nodeId, bundle);
}
bundle.removeProperty(id.getName(), getBlobStore());
}
}
}
// add added properties
for (ItemState state : changeLog.addedStates()) {
if (!state.isNode()) {
PropertyId id = (PropertyId) state.getId();
// skip primaryType pr mixinTypes properties
if (id.getName().equals(JCR_PRIMARYTYPE)
|| id.getName().equals(JCR_MIXINTYPES)
|| id.getName().equals(JCR_UUID)) {
continue;
}
NodeId nodeId = id.getParentId();
NodePropBundle bundle = modified.get(nodeId);
if (bundle == null) {
// should actually not happen
log.warn("added property state's parent not modified!");
bundle = getBundle(nodeId);
if (bundle == null) {
throw new NoSuchItemStateException(nodeId.toString());
}
modified.put(nodeId, bundle);
}
bundle.addProperty((PropertyState) state, getBlobStore());
}
}
// now store all modified bundles
for (NodePropBundle bundle : modified.values()) {
putBundle(bundle);
}
// store the refs
for (NodeReferences refs : changeLog.modifiedRefs()) {
if (refs.hasReferences()) {
store(refs);
} else {
destroy(refs);
}
}
}
/**
* Gets the bundle for the given node id. Read/write synchronization
* happens higher up at the SISM level, so we don't need to worry about
* conflicts here.
*
* @param id the id of the bundle to retrieve.
* @return the bundle or <code>null</code> if the bundle does not exist
*
* @throws ItemStateException if an error occurs.
*/
private NodePropBundle getBundle(NodeId id) throws ItemStateException {
NodePropBundle bundle = bundles.get(id);
if (bundle == MISSING) {
return null;
}
if (bundle != null) {
return bundle;
}
// cache miss
return getBundleCacheMiss(id);
}
/**
* Called when the bundle is not present in the cache, so we'll need to load
* it from the PM impl.
*
* This also updates the cache.
*
* @param id
* @return
* @throws ItemStateException
*/
private NodePropBundle getBundleCacheMiss(NodeId id)
throws ItemStateException {
long time = System.nanoTime();
log.debug("Loading bundle {}", id);
NodePropBundle bundle = loadBundle(id);
readDuration.addAndGet(System.nanoTime() - time);
readCounter.incrementAndGet();
if (bundle != null) {
bundle.markOld();
bundles.put(id, bundle, bundle.getSize());
} else {
bundles.put(id, MISSING, 16);
}
return bundle;
}
/**
* Deletes the bundle
*
* @param bundle the bundle to delete
* @throws ItemStateException if an error occurs
*/
private void deleteBundle(NodePropBundle bundle) throws ItemStateException {
destroyBundle(bundle);
bundle.removeAllProperties(getBlobStore());
bundles.put(bundle.getId(), MISSING, 16);
}
/**
* Stores the bundle and puts it to the cache.
*
* @param bundle the bundle to store
* @throws ItemStateException if an error occurs
*/
private void putBundle(NodePropBundle bundle) throws ItemStateException {
long time = System.nanoTime();
log.debug("Storing bundle {}", bundle.getId());
storeBundle(bundle);
writeDuration.addAndGet(System.nanoTime() - time);
writeCounter.incrementAndGet();
bundle.markOld();
// only put to cache if already exists. this is to ensure proper
// overwrite and not creating big contention during bulk loads
if (bundles.containsKey(bundle.getId())) {
bundles.put(bundle.getId(), bundle, bundle.getSize());
}
}
/**
* This implementation does nothing.
*
* {@inheritDoc}
*/
public void checkConsistency(String[] uuids, boolean recursive, boolean fix) {
}
/**
* Evicts the bundle with <code>id</code> from the bundle cache.
*
* @param id the id of the bundle.
*/
protected void evictBundle(NodeId id) {
bundles.remove(id);
}
public void cacheAccessed(long accessCount) {
logCacheStats();
cacheCounter.addAndGet(accessCount);
}
private void logCacheStats() {
if (log.isInfoEnabled()) {
long now = System.currentTimeMillis();
if (now < nextLogStats) {
return;
}
log.info(bundles.getCacheInfoAsString());
nextLogStats = now + minLogStatsInterval;
}
}
public void disposeCache(Cache cache) {
// NOOP
}
}
| jackrabbit-core/src/main/java/org/apache/jackrabbit/core/persistence/bundle/AbstractBundlePersistenceManager.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.core.persistence.bundle;
import static org.apache.jackrabbit.spi.commons.name.NameConstants.JCR_MIXINTYPES;
import static org.apache.jackrabbit.spi.commons.name.NameConstants.JCR_PRIMARYTYPE;
import static org.apache.jackrabbit.spi.commons.name.NameConstants.JCR_UUID;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import javax.jcr.PropertyType;
import org.apache.jackrabbit.api.stats.RepositoryStatistics;
import org.apache.jackrabbit.core.cache.Cache;
import org.apache.jackrabbit.core.cache.CacheAccessListener;
import org.apache.jackrabbit.core.cache.ConcurrentCache;
import org.apache.jackrabbit.core.fs.FileSystem;
import org.apache.jackrabbit.core.fs.FileSystemResource;
import org.apache.jackrabbit.core.id.ItemId;
import org.apache.jackrabbit.core.id.NodeId;
import org.apache.jackrabbit.core.id.PropertyId;
import org.apache.jackrabbit.core.persistence.CachingPersistenceManager;
import org.apache.jackrabbit.core.persistence.IterablePersistenceManager;
import org.apache.jackrabbit.core.persistence.PMContext;
import org.apache.jackrabbit.core.persistence.PersistenceManager;
import org.apache.jackrabbit.core.persistence.util.BLOBStore;
import org.apache.jackrabbit.core.persistence.util.FileBasedIndex;
import org.apache.jackrabbit.core.persistence.util.NodePropBundle;
import org.apache.jackrabbit.core.persistence.util.NodePropBundle.PropertyEntry;
import org.apache.jackrabbit.core.state.ChangeLog;
import org.apache.jackrabbit.core.state.ItemState;
import org.apache.jackrabbit.core.state.ItemStateException;
import org.apache.jackrabbit.core.state.NoSuchItemStateException;
import org.apache.jackrabbit.core.state.NodeReferences;
import org.apache.jackrabbit.core.state.NodeState;
import org.apache.jackrabbit.core.state.PropertyState;
import org.apache.jackrabbit.core.stats.RepositoryStatisticsImpl;
import org.apache.jackrabbit.core.util.StringIndex;
import org.apache.jackrabbit.core.value.InternalValue;
import org.apache.jackrabbit.spi.Name;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The <code>AbstractBundlePersistenceManager</code> acts as base for all
* persistence managers that store the state in a {@link NodePropBundle}.
* <p/>
* The state and all property states of one node are stored together in one
* record. Property values of a certain size can be store outside of the bundle.
* This currently only works for binary properties. NodeReferences are not
* included in the bundle since they are addressed by the target id.
* <p/>
* Some strings like namespaces and local names are additionally managed by
* separate indexes. only the index number is serialized to the records which
* reduces the amount of memory used.
* <p/>
* Special treatment is performed for the properties "jcr:uuid", "jcr:primaryType"
* and "jcr:mixinTypes". As they are also stored in the node state they are not
* included in the bundle but generated when required.
* <p/>
* In order to increase performance, there are 2 caches maintained. One is the
* bundle cache that caches already loaded bundles. The other is the
* {@link LRUNodeIdCache} that caches non-existent bundles. This is useful
* because a lot of {@link #exists(NodeId)} calls are issued that would result
* in a useless SQL execution if the desired bundle does not exist.
* <p/>
* Configuration:<br>
* <ul>
* <li><param name="{@link #setBundleCacheSize(String) bundleCacheSize}" value="8"/>
* </ul>
*/
public abstract class AbstractBundlePersistenceManager implements
PersistenceManager, CachingPersistenceManager, IterablePersistenceManager, CacheAccessListener {
/** the default logger */
private static Logger log = LoggerFactory.getLogger(AbstractBundlePersistenceManager.class);
/** the prefix of a node file */
protected static final String NODEFILENAME = "n";
/** the prefix of a node references file */
protected static final String NODEREFSFILENAME = "r";
/** the name of the names-index resource */
protected static final String RES_NAME_INDEX = "/names.properties";
/** the name of the namespace-index resource */
protected static final String RES_NS_INDEX = "/namespaces.properties";
/** Sentinel instance used to mark a non-existent bundle in the cache */
private static final NodePropBundle MISSING =
new NodePropBundle(NodeId.randomId());
/** the index for namespaces */
private StringIndex nsIndex;
/** the index for local names */
private StringIndex nameIndex;
/** the cache of loaded bundles */
private ConcurrentCache<NodeId, NodePropBundle> bundles;
/** The default minimum stats logging interval (in ms). */
private static final int DEFAULT_LOG_STATS_INTERVAL = 60 * 1000;
/** The minimum interval time between stats are logged */
private long minLogStatsInterval = Long.getLong(
"org.apache.jackrabbit.cacheLogStatsInterval",
DEFAULT_LOG_STATS_INTERVAL);
/** The last time the cache stats were logged. */
private volatile long nextLogStats =
System.currentTimeMillis() + DEFAULT_LOG_STATS_INTERVAL;
/** the persistence manager context */
protected PMContext context;
/** default size of the bundle cache */
private long bundleCacheSize = 8 * 1024 * 1024;
/** Counter of read operations. */
private AtomicLong readCounter;
/** Counter of write operations. */
private AtomicLong writeCounter;
/** Duration of read operations. */
private AtomicLong readDuration;
/** Duration of write operations. */
private AtomicLong writeDuration;
/** Counter of bundle cache accesses. */
private AtomicLong cacheCounter;
/**
* Returns the size of the bundle cache in megabytes.
* @return the size of the bundle cache in megabytes.
*/
public String getBundleCacheSize() {
return String.valueOf(bundleCacheSize / (1024 * 1024));
}
/**
* Sets the size of the bundle cache in megabytes.
* the default is 8.
*
* @param bundleCacheSize the bundle cache size in megabytes.
*/
public void setBundleCacheSize(String bundleCacheSize) {
this.bundleCacheSize = Long.parseLong(bundleCacheSize) * 1024 * 1024;
}
/**
* Creates the folder path for the given node id that is suitable for
* storing states in a filesystem.
*
* @param buf buffer to append to or <code>null</code>
* @param id the id of the node
* @return the buffer with the appended data.
*/
protected StringBuffer buildNodeFolderPath(StringBuffer buf, NodeId id) {
if (buf == null) {
buf = new StringBuffer();
}
char[] chars = id.toString().toCharArray();
int cnt = 0;
for (int i = 0; i < chars.length; i++) {
if (chars[i] == '-') {
continue;
}
//if (cnt > 0 && cnt % 4 == 0) {
if (cnt == 2 || cnt == 4) {
buf.append(FileSystem.SEPARATOR_CHAR);
}
buf.append(chars[i]);
cnt++;
}
return buf;
}
/**
* Creates the folder path for the given property id that is suitable for
* storing states in a filesystem.
*
* @param buf buffer to append to or <code>null</code>
* @param id the id of the property
* @return the buffer with the appended data.
*/
protected StringBuffer buildPropFilePath(StringBuffer buf, PropertyId id) {
if (buf == null) {
buf = new StringBuffer();
}
buildNodeFolderPath(buf, id.getParentId());
buf.append(FileSystem.SEPARATOR);
buf.append(getNsIndex().stringToIndex(id.getName().getNamespaceURI()));
buf.append('.');
buf.append(getNameIndex().stringToIndex(id.getName().getLocalName()));
return buf;
}
/**
* Creates the file path for the given property id and value index that is
* suitable for storing property values in a filesystem.
*
* @param buf buffer to append to or <code>null</code>
* @param id the id of the property
* @param i the index of the property value
* @return the buffer with the appended data.
*/
protected StringBuffer buildBlobFilePath(StringBuffer buf, PropertyId id,
int i) {
if (buf == null) {
buf = new StringBuffer();
}
buildPropFilePath(buf, id);
buf.append('.');
buf.append(i);
return buf;
}
/**
* Creates the file path for the given node id that is
* suitable for storing node states in a filesystem.
*
* @param buf buffer to append to or <code>null</code>
* @param id the id of the node
* @return the buffer with the appended data.
*/
protected StringBuffer buildNodeFilePath(StringBuffer buf, NodeId id) {
if (buf == null) {
buf = new StringBuffer();
}
buildNodeFolderPath(buf, id);
buf.append(FileSystem.SEPARATOR);
buf.append(NODEFILENAME);
return buf;
}
/**
* Creates the file path for the given references id that is
* suitable for storing reference states in a filesystem.
*
* @param buf buffer to append to or <code>null</code>
* @param id the id of the node
* @return the buffer with the appended data.
*/
protected StringBuffer buildNodeReferencesFilePath(
StringBuffer buf, NodeId id) {
if (buf == null) {
buf = new StringBuffer();
}
buildNodeFolderPath(buf, id);
buf.append(FileSystem.SEPARATOR);
buf.append(NODEREFSFILENAME);
return buf;
}
/**
* Returns the namespace index
* @return the namespace index
* @throws IllegalStateException if an error occurs.
*/
public StringIndex getNsIndex() {
try {
if (nsIndex == null) {
// load name and ns index
FileSystemResource nsFile = new FileSystemResource(context.getFileSystem(), RES_NS_INDEX);
if (nsFile.exists()) {
nsIndex = new FileBasedIndex(nsFile);
} else {
nsIndex = (StringIndex) context.getNamespaceRegistry();
}
}
return nsIndex;
} catch (Exception e) {
IllegalStateException e2 = new IllegalStateException("Unable to create nsIndex.");
e2.initCause(e);
throw e2;
}
}
/**
* Returns the local name index
* @return the local name index
* @throws IllegalStateException if an error occurs.
*/
public StringIndex getNameIndex() {
try {
if (nameIndex == null) {
nameIndex = new FileBasedIndex(new FileSystemResource(
context.getFileSystem(), RES_NAME_INDEX));
}
return nameIndex;
} catch (Exception e) {
IllegalStateException e2 = new IllegalStateException("Unable to create nameIndex.");
e2.initCause(e);
throw e2;
}
}
//-----------------------------------------< CacheablePersistenceManager >--
/**
* {@inheritDoc}
*/
public synchronized void onExternalUpdate(ChangeLog changes) {
for (ItemState state : changes.modifiedStates()) {
bundles.remove(getBundleId(state));
}
for (ItemState state : changes.deletedStates()) {
bundles.remove(getBundleId(state));
}
for (ItemState state : changes.addedStates()) {
// There may have been a cache miss entry
bundles.remove(getBundleId(state));
}
}
private NodeId getBundleId(ItemState state) {
if (state.isNode()) {
return (NodeId) state.getId();
} else {
return state.getParentId();
}
}
//----------------------------------------------------------------< spi >---
/**
* Loads a bundle from the underlying system.
*
* @param id the node id of the bundle
* @return the loaded bundle or <code>null</code> if the bundle does not
* exist.
* @throws ItemStateException if an error while loading occurs.
*/
protected abstract NodePropBundle loadBundle(NodeId id)
throws ItemStateException;
/**
* Stores a bundle to the underlying system.
*
* @param bundle the bundle to store
* @throws ItemStateException if an error while storing occurs.
*/
protected abstract void storeBundle(NodePropBundle bundle)
throws ItemStateException;
/**
* Deletes the bundle from the underlying system.
*
* @param bundle the bundle to destroy
*
* @throws ItemStateException if an error while destroying occurs.
*/
protected abstract void destroyBundle(NodePropBundle bundle)
throws ItemStateException;
/**
* Deletes the node references from the underlying system.
*
* @param refs the node references to destroy.
* @throws ItemStateException if an error while destroying occurs.
*/
protected abstract void destroy(NodeReferences refs)
throws ItemStateException;
/**
* Stores a node references to the underlying system.
*
* @param refs the node references to store.
* @throws ItemStateException if an error while storing occurs.
*/
protected abstract void store(NodeReferences refs)
throws ItemStateException;
/**
* Returns the BLOB store used by this persistence manager.
*
* @return BLOB store
*/
protected abstract BLOBStore getBlobStore();
//-------------------------------------------------< PersistenceManager >---
/**
* {@inheritDoc}
*
* Initializes the internal structures of this abstract persistence manager.
*/
public void init(PMContext context) throws Exception {
this.context = context;
// init bundle cache
bundles = new ConcurrentCache<NodeId, NodePropBundle>(context.getHomeDir().getName() + "BundleCache");
bundles.setMaxMemorySize(bundleCacheSize);
bundles.setAccessListener(this);
// statistics
RepositoryStatisticsImpl stats = context.getRepositoryStatistics();
cacheCounter = stats.getCounter(
RepositoryStatistics.Type.BUNDLE_CACHE_COUNTER);
readCounter = stats.getCounter(
RepositoryStatistics.Type.BUNDLE_READ_COUNTER);
readDuration = stats.getCounter(
RepositoryStatistics.Type.BUNDLE_READ_DURATION);
writeCounter = stats.getCounter(
RepositoryStatistics.Type.BUNDLE_WRITE_COUNTER);
writeDuration = stats.getCounter(
RepositoryStatistics.Type.BUNDLE_WRITE_DURATION);
}
/**
* {@inheritDoc}
*
* Closes the persistence manager, release acquired resources.
*/
public void close() throws Exception {
// clear caches
bundles.clear();
}
/**
* {@inheritDoc}
*
* Loads the state via the appropriate NodePropBundle.
*/
public NodeState load(NodeId id) throws NoSuchItemStateException, ItemStateException {
NodePropBundle bundle = getBundle(id);
if (bundle == null) {
throw new NoSuchItemStateException(id.toString());
}
return bundle.createNodeState(this);
}
/**
* {@inheritDoc}
*
* Loads the state via the appropriate NodePropBundle.
*/
public PropertyState load(PropertyId id) throws NoSuchItemStateException, ItemStateException {
NodePropBundle bundle = getBundle(id.getParentId());
if (bundle != null) {
PropertyState state = createNew(id);
PropertyEntry p = bundle.getPropertyEntry(id.getName());
if (p != null) {
state.setMultiValued(p.isMultiValued());
state.setType(p.getType());
state.setValues(p.getValues());
state.setModCount(p.getModCount());
} else if (id.getName().equals(JCR_UUID)) {
state.setType(PropertyType.STRING);
state.setMultiValued(false);
state.setValues(new InternalValue[] {
InternalValue.create(id.getParentId().toString()) });
} else if (id.getName().equals(JCR_PRIMARYTYPE)) {
state.setType(PropertyType.NAME);
state.setMultiValued(false);
state.setValues(new InternalValue[] {
InternalValue.create(bundle.getNodeTypeName()) });
} else if (id.getName().equals(JCR_MIXINTYPES)) {
state.setType(PropertyType.NAME);
state.setMultiValued(true);
Set<Name> mixins = bundle.getMixinTypeNames();
state.setValues(InternalValue.create(
mixins.toArray(new Name[mixins.size()])));
} else {
throw new NoSuchItemStateException(id.toString());
}
return state;
} else {
throw new NoSuchItemStateException(id.toString());
}
}
/**
* {@inheritDoc}
*
* Loads the state via the appropriate NodePropBundle.
*/
public boolean exists(PropertyId id) throws ItemStateException {
NodePropBundle bundle = getBundle(id.getParentId());
if (bundle != null) {
Name name = id.getName();
return bundle.hasProperty(name)
|| JCR_PRIMARYTYPE.equals(name)
|| (JCR_UUID.equals(name) && bundle.isReferenceable())
|| (JCR_MIXINTYPES.equals(name)
&& !bundle.getMixinTypeNames().isEmpty());
} else {
return false;
}
}
/**
* {@inheritDoc}
*
* Checks the existence via the appropriate NodePropBundle.
*/
public boolean exists(NodeId id) throws ItemStateException {
// anticipating a load followed by a exists
return getBundle(id) != null;
}
/**
* {@inheritDoc}
*/
public NodeState createNew(NodeId id) {
return new NodeState(id, null, null, NodeState.STATUS_NEW, false);
}
/**
* {@inheritDoc}
*/
public PropertyState createNew(PropertyId id) {
return new PropertyState(id, PropertyState.STATUS_NEW, false);
}
/**
* Right now, this iterates over all items in the changelog and
* calls the individual methods that handle single item states
* or node references objects. Properly implemented, this method
* should ensure that changes are either written completely to
* the underlying persistence layer, or not at all.
*
* {@inheritDoc}
*/
public synchronized void store(ChangeLog changeLog)
throws ItemStateException {
boolean success = false;
try {
storeInternal(changeLog);
success = true;
} finally {
if (!success) {
bundles.clear();
}
}
}
/**
* Stores the given changelog and updates the bundle cache.
*
* @param changeLog the changelog to store
* @throws ItemStateException on failure
*/
private void storeInternal(ChangeLog changeLog)
throws ItemStateException {
// delete bundles
HashSet<ItemId> deleted = new HashSet<ItemId>();
for (ItemState state : changeLog.deletedStates()) {
if (state.isNode()) {
NodePropBundle bundle = getBundle((NodeId) state.getId());
if (bundle == null) {
throw new NoSuchItemStateException(state.getId().toString());
}
deleteBundle(bundle);
deleted.add(state.getId());
}
}
// gather added node states
HashMap<ItemId, NodePropBundle> modified = new HashMap<ItemId, NodePropBundle>();
for (ItemState state : changeLog.addedStates()) {
if (state.isNode()) {
NodePropBundle bundle = new NodePropBundle((NodeState) state);
modified.put(state.getId(), bundle);
}
}
// gather modified node states
for (ItemState state : changeLog.modifiedStates()) {
if (state.isNode()) {
NodeId nodeId = (NodeId) state.getId();
NodePropBundle bundle = modified.get(nodeId);
if (bundle == null) {
bundle = getBundle(nodeId);
if (bundle == null) {
throw new NoSuchItemStateException(nodeId.toString());
}
modified.put(nodeId, bundle);
}
bundle.update((NodeState) state);
} else {
PropertyId id = (PropertyId) state.getId();
// skip redundant primaryType, mixinTypes and uuid properties
if (id.getName().equals(JCR_PRIMARYTYPE)
|| id.getName().equals(JCR_MIXINTYPES)
|| id.getName().equals(JCR_UUID)) {
continue;
}
NodeId nodeId = id.getParentId();
NodePropBundle bundle = modified.get(nodeId);
if (bundle == null) {
bundle = getBundle(nodeId);
if (bundle == null) {
throw new NoSuchItemStateException(nodeId.toString());
}
modified.put(nodeId, bundle);
}
bundle.addProperty((PropertyState) state, getBlobStore());
}
}
// add removed properties
for (ItemState state : changeLog.deletedStates()) {
if (state.isNode()) {
// check consistency
NodeId parentId = state.getParentId();
if (!modified.containsKey(parentId) && !deleted.contains(parentId)) {
log.warn("Deleted node state's parent is not modified or deleted: " + parentId + "/" + state.getId());
}
} else {
PropertyId id = (PropertyId) state.getId();
NodeId nodeId = id.getParentId();
if (!deleted.contains(nodeId)) {
NodePropBundle bundle = modified.get(nodeId);
if (bundle == null) {
// should actually not happen
log.warn("deleted property state's parent not modified!");
bundle = getBundle(nodeId);
if (bundle == null) {
throw new NoSuchItemStateException(nodeId.toString());
}
modified.put(nodeId, bundle);
}
bundle.removeProperty(id.getName(), getBlobStore());
}
}
}
// add added properties
for (ItemState state : changeLog.addedStates()) {
if (!state.isNode()) {
PropertyId id = (PropertyId) state.getId();
// skip primaryType pr mixinTypes properties
if (id.getName().equals(JCR_PRIMARYTYPE)
|| id.getName().equals(JCR_MIXINTYPES)
|| id.getName().equals(JCR_UUID)) {
continue;
}
NodeId nodeId = id.getParentId();
NodePropBundle bundle = modified.get(nodeId);
if (bundle == null) {
// should actually not happen
log.warn("added property state's parent not modified!");
bundle = getBundle(nodeId);
if (bundle == null) {
throw new NoSuchItemStateException(nodeId.toString());
}
modified.put(nodeId, bundle);
}
bundle.addProperty((PropertyState) state, getBlobStore());
}
}
// now store all modified bundles
for (NodePropBundle bundle : modified.values()) {
putBundle(bundle);
}
// store the refs
for (NodeReferences refs : changeLog.modifiedRefs()) {
if (refs.hasReferences()) {
store(refs);
} else {
destroy(refs);
}
}
}
/**
* Gets the bundle for the given node id. Read/write synchronization
* happens higher up at the SISM level, so we don't need to worry about
* conflicts here.
*
* @param id the id of the bundle to retrieve.
* @return the bundle or <code>null</code> if the bundle does not exist
*
* @throws ItemStateException if an error occurs.
*/
private NodePropBundle getBundle(NodeId id) throws ItemStateException {
NodePropBundle bundle = bundles.get(id);
if (bundle == MISSING) {
return null;
}
if (bundle != null) {
return bundle;
}
// cache miss
return getBundleCacheMiss(id);
}
/**
* Called when the bundle is not present in the cache, so we'll need to load
* it from the PM impl.
*
* This also updates the cache.
*
* @param id
* @return
* @throws ItemStateException
*/
private NodePropBundle getBundleCacheMiss(NodeId id)
throws ItemStateException {
long time = System.nanoTime();
NodePropBundle bundle = loadBundle(id);
readDuration.addAndGet(System.nanoTime() - time);
readCounter.incrementAndGet();
if (bundle != null) {
bundle.markOld();
bundles.put(id, bundle, bundle.getSize());
} else {
bundles.put(id, MISSING, 16);
}
return bundle;
}
/**
* Deletes the bundle
*
* @param bundle the bundle to delete
* @throws ItemStateException if an error occurs
*/
private void deleteBundle(NodePropBundle bundle) throws ItemStateException {
destroyBundle(bundle);
bundle.removeAllProperties(getBlobStore());
bundles.put(bundle.getId(), MISSING, 16);
}
/**
* Stores the bundle and puts it to the cache.
*
* @param bundle the bundle to store
* @throws ItemStateException if an error occurs
*/
private void putBundle(NodePropBundle bundle) throws ItemStateException {
long time = System.nanoTime();
storeBundle(bundle);
writeDuration.addAndGet(System.nanoTime() - time);
writeCounter.incrementAndGet();
bundle.markOld();
// only put to cache if already exists. this is to ensure proper
// overwrite and not creating big contention during bulk loads
if (bundles.containsKey(bundle.getId())) {
bundles.put(bundle.getId(), bundle, bundle.getSize());
}
}
/**
* This implementation does nothing.
*
* {@inheritDoc}
*/
public void checkConsistency(String[] uuids, boolean recursive, boolean fix) {
}
/**
* Evicts the bundle with <code>id</code> from the bundle cache.
*
* @param id the id of the bundle.
*/
protected void evictBundle(NodeId id) {
bundles.remove(id);
}
public void cacheAccessed(long accessCount) {
logCacheStats();
cacheCounter.addAndGet(accessCount);
}
private void logCacheStats() {
if (log.isInfoEnabled()) {
long now = System.currentTimeMillis();
if (now < nextLogStats) {
return;
}
log.info(bundles.getCacheInfoAsString());
nextLogStats = now + minLogStatsInterval;
}
}
public void disposeCache(Cache cache) {
// NOOP
}
}
| JCR-3117: Stats for the PersistenceManager
Restore debug log messages
git-svn-id: 02b679d096242155780e1604e997947d154ee04a@1186716 13f79535-47bb-0310-9956-ffa450edef68
| jackrabbit-core/src/main/java/org/apache/jackrabbit/core/persistence/bundle/AbstractBundlePersistenceManager.java | JCR-3117: Stats for the PersistenceManager | <ide><path>ackrabbit-core/src/main/java/org/apache/jackrabbit/core/persistence/bundle/AbstractBundlePersistenceManager.java
<ide> private NodePropBundle getBundleCacheMiss(NodeId id)
<ide> throws ItemStateException {
<ide> long time = System.nanoTime();
<add> log.debug("Loading bundle {}", id);
<ide> NodePropBundle bundle = loadBundle(id);
<ide> readDuration.addAndGet(System.nanoTime() - time);
<ide> readCounter.incrementAndGet();
<ide> */
<ide> private void putBundle(NodePropBundle bundle) throws ItemStateException {
<ide> long time = System.nanoTime();
<add> log.debug("Storing bundle {}", bundle.getId());
<ide> storeBundle(bundle);
<ide> writeDuration.addAndGet(System.nanoTime() - time);
<ide> writeCounter.incrementAndGet(); |
|
JavaScript | mit | ebd5c02821da7ecc0816c5d69220e26d5afb61b8 | 0 | LinusU/fastfall,mcollina/fastfall | 'use strict'
var empty = []
function fastfall (context, template) {
if (Array.isArray(context)) {
template = context
context = null
}
var head = new Holder(release)
var tail = head
return template ? compiled : fall
function next () {
var holder = head
if (holder.next) {
head = holder.next
} else {
head = new Holder(release)
tail = head
}
holder.next = null
return holder
}
function fall () {
var current = next()
if (arguments.length === 3) {
current.context = arguments[0]
current.list = arguments[1]
current.callback = arguments[2] || noop
} else {
current.context = context
current.list = arguments[0]
current.callback = arguments[1] || noop
}
current.work()
}
function release (holder) {
tail.next = holder
tail = holder
}
function compiled () {
var current = next()
current.list = template
var args = new Array(arguments.length)
var i
args[0] = null // first arg is the error
for (i = 0; i < arguments.length - 1; i++) {
args[i + 1] = arguments[i]
}
current.context = this || context
current.callback = arguments[i] || noop
current.work.apply(null, args)
}
}
function noop () {}
function Holder (release) {
this.list = empty
this.callback = noop
this.count = 0
this.context = undefined
var that = this
this.work = function work () {
if (arguments.length > 0 && arguments[0]) {
return that.callback.call(that.context, arguments[0])
}
var args = []
var i = 0
if (that.count < that.list.length) {
for (i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i]
}
args[args.length] = work
that.list[that.count++].apply(that.context, args)
} else {
for (i = 0; i < arguments.length; i++) {
args[i] = arguments[i]
}
that.callback.apply(that.context, args)
that.context = undefined
that.list = empty
that.count = 0
release(that)
}
}
}
module.exports = fastfall
| fall.js | 'use strict'
var empty = []
function fastfall (context, template) {
if (Array.isArray(context)) {
template = context
context = null
}
var head = new Holder(release)
var tail = head
return template ? compiled : fall
function next () {
var holder = head
if (holder.next) {
head = holder.next
} else {
head = new Holder(release)
tail = head
}
holder.next = null
return holder
}
function fall () {
var current = next()
if (arguments.length === 3) {
current.context = arguments[0]
current.list = arguments[1]
current.callback = arguments[2] || noop
} else {
current.context = context
current.list = arguments[0]
current.callback = arguments[1] || noop
}
current.work()
}
function release (holder) {
tail.next = holder
tail = holder
}
function compiled () {
var current = next()
current.list = template
var args = new Array(arguments.length)
var i
args[0] = null // first arg is the error
for (i = 0; i < arguments.length - 1; i++) {
args[i + 1] = arguments[i]
}
current.context = this || context
current.callback = arguments[i] || noop
current.work.apply(null, args)
}
}
function noop () {}
function Holder (release) {
this.list = empty
this.callback = noop
this.count = 0
this.context = undefined
var that = this
this.work = function work () {
if (arguments.length > 0 && arguments[0]) {
return that.callback.call(that.context, arguments[0])
}
var args = []
var i = 0
if (that.count < that.list.length) {
for (i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i]
}
args[args.length] = work
that.list[that.count++].apply(that.context, args)
} else {
for (i = 0; i < arguments.length; i++) {
args[i] = arguments[i]
}
that.callback.apply(that.context, args)
that.context = undefined
that.list = empty
that.count = 0
release(that)
}
}
}
module.exports = fastfall
| adhere to padded-blocks
| fall.js | adhere to padded-blocks | <ide><path>all.js
<ide> var empty = []
<ide>
<ide> function fastfall (context, template) {
<del>
<ide> if (Array.isArray(context)) {
<ide> template = context
<ide> context = null |
|
Java | apache-2.0 | e13e31e7e04be545c49a7e991395a77132a4d21e | 0 | AndroidX/androidx,aosp-mirror/platform_frameworks_support,AndroidX/androidx,AndroidX/androidx,AndroidX/androidx,androidx/androidx,androidx/androidx,androidx/androidx,androidx/androidx,androidx/androidx,aosp-mirror/platform_frameworks_support,androidx/androidx,AndroidX/androidx,androidx/androidx,androidx/androidx,AndroidX/androidx,androidx/androidx,aosp-mirror/platform_frameworks_support,androidx/androidx,AndroidX/androidx,AndroidX/androidx,AndroidX/androidx,AndroidX/androidx,aosp-mirror/platform_frameworks_support,aosp-mirror/platform_frameworks_support | /*
* 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 android.support.design.widget;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.SystemClock;
import android.support.design.R;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.view.NestedScrollingParent;
import android.support.v4.view.NestedScrollingParentHelper;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.WindowInsetsCompat;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.util.SparseArray;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.ViewTreeObserver;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* CoordinatorLayout is a super-powered {@link android.widget.FrameLayout FrameLayout}.
*
* <p>CoordinatorLayout is intended for two primary use cases:</p>
* <ol>
* <li>As a top-level application decor or chrome layout</li>
* <li>As a container for a specific interaction with one or more child views</li>
* </ol>
*
* <p>By specifying {@link CoordinatorLayout.Behavior Behaviors} for child views of a
* CoordinatorLayout you can provide many different interactions within a single parent and those
* views can also interact with one another. View classes can specify a default behavior when
* used as a child of a CoordinatorLayout using the
* {@link CoordinatorLayout.DefaultBehavior DefaultBehavior} annotation.</p>
*
* <p>Behaviors may be used to implement a variety of interactions and additional layout
* modifications ranging from sliding drawers and panels to swipe-dismissable elements and buttons
* that stick to other elements as they move and animate.</p>
*
* <p>Children of a CoordinatorLayout may have an
* {@link CoordinatorLayout.LayoutParams#setAnchorId(int) anchor}. This view id must correspond
* to an arbitrary descendant of the CoordinatorLayout, but it may not be the anchored child itself
* or a descendant of the anchored child. This can be used to place floating views relative to
* other arbitrary content panes.</p>
*/
public class CoordinatorLayout extends ViewGroup implements NestedScrollingParent {
static final String TAG = "CoordinatorLayout";
static final String WIDGET_PACKAGE_NAME = CoordinatorLayout.class.getPackage().getName();
private static final int TYPE_ON_INTERCEPT = 0;
private static final int TYPE_ON_TOUCH = 1;
static {
if (Build.VERSION.SDK_INT >= 21) {
TOP_SORTED_CHILDREN_COMPARATOR = new ViewElevationComparator();
INSETS_HELPER = new CoordinatorLayoutInsetsHelperLollipop();
} else {
TOP_SORTED_CHILDREN_COMPARATOR = null;
INSETS_HELPER = null;
}
}
static final Class<?>[] CONSTRUCTOR_PARAMS = new Class<?>[] {
Context.class,
AttributeSet.class
};
static final ThreadLocal<Map<String, Constructor<Behavior>>> sConstructors =
new ThreadLocal<>();
final Comparator<View> mLayoutDependencyComparator = new Comparator<View>() {
@Override
public int compare(View lhs, View rhs) {
if (lhs == rhs) {
return 0;
} else if (((LayoutParams) lhs.getLayoutParams()).dependsOn(
CoordinatorLayout.this, lhs, rhs)) {
return 1;
} else if (((LayoutParams) rhs.getLayoutParams()).dependsOn(
CoordinatorLayout.this, rhs, lhs)) {
return -1;
} else {
return 0;
}
}
};
static final Comparator<View> TOP_SORTED_CHILDREN_COMPARATOR;
static final CoordinatorLayoutInsetsHelper INSETS_HELPER;
private final List<View> mDependencySortedChildren = new ArrayList<View>();
private final List<View> mTempList1 = new ArrayList<>();
private final List<View> mTempDependenciesList = new ArrayList<>();
private final Rect mTempRect1 = new Rect();
private final Rect mTempRect2 = new Rect();
private final Rect mTempRect3 = new Rect();
private final int[] mTempIntPair = new int[2];
private Paint mScrimPaint;
private boolean mIsAttachedToWindow;
private int[] mKeylines;
private View mBehaviorTouchView;
private View mNestedScrollingDirectChild;
private View mNestedScrollingTarget;
private OnPreDrawListener mOnPreDrawListener;
private boolean mNeedsPreDrawListener;
private WindowInsetsCompat mLastInsets;
private boolean mDrawStatusBarBackground;
private Drawable mStatusBarBackground;
private OnHierarchyChangeListener mOnHierarchyChangeListener;
private final NestedScrollingParentHelper mNestedScrollingParentHelper =
new NestedScrollingParentHelper(this);
public CoordinatorLayout(Context context) {
this(context, null);
}
public CoordinatorLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CoordinatorLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CoordinatorLayout,
defStyleAttr, R.style.Widget_Design_CoordinatorLayout);
final int keylineArrayRes = a.getResourceId(R.styleable.CoordinatorLayout_keylines, 0);
if (keylineArrayRes != 0) {
final Resources res = context.getResources();
mKeylines = res.getIntArray(keylineArrayRes);
final float density = res.getDisplayMetrics().density;
final int count = mKeylines.length;
for (int i = 0; i < count; i++) {
mKeylines[i] *= density;
}
}
mStatusBarBackground = a.getDrawable(R.styleable.CoordinatorLayout_statusBarBackground);
a.recycle();
if (INSETS_HELPER != null) {
INSETS_HELPER.setupForWindowInsets(this, new ApplyInsetsListener());
}
super.setOnHierarchyChangeListener(new HierarchyChangeListener());
}
@Override
public void setOnHierarchyChangeListener(OnHierarchyChangeListener onHierarchyChangeListener) {
mOnHierarchyChangeListener = onHierarchyChangeListener;
}
@Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
resetTouchBehaviors();
if (mNeedsPreDrawListener) {
if (mOnPreDrawListener == null) {
mOnPreDrawListener = new OnPreDrawListener();
}
final ViewTreeObserver vto = getViewTreeObserver();
vto.addOnPreDrawListener(mOnPreDrawListener);
}
if (mLastInsets == null && ViewCompat.getFitsSystemWindows(this)) {
// We're set to fitSystemWindows but we haven't had any insets yet...
// We should request a new dispatch of window insets
ViewCompat.requestApplyInsets(this);
}
mIsAttachedToWindow = true;
}
@Override
public void onDetachedFromWindow() {
super.onDetachedFromWindow();
resetTouchBehaviors();
if (mNeedsPreDrawListener && mOnPreDrawListener != null) {
final ViewTreeObserver vto = getViewTreeObserver();
vto.removeOnPreDrawListener(mOnPreDrawListener);
}
if (mNestedScrollingTarget != null) {
onStopNestedScroll(mNestedScrollingTarget);
}
mIsAttachedToWindow = false;
}
/**
* Set a drawable to draw in the insets area for the status bar.
* Note that this will only be activated if this DrawerLayout fitsSystemWindows.
*
* @param bg Background drawable to draw behind the status bar
*/
public void setStatusBarBackground(Drawable bg) {
mStatusBarBackground = bg;
invalidate();
}
/**
* Gets the drawable used to draw in the insets area for the status bar.
*
* @return The status bar background drawable, or null if none set
*/
public Drawable getStatusBarBackground() {
return mStatusBarBackground;
}
/**
* Set a drawable to draw in the insets area for the status bar.
* Note that this will only be activated if this DrawerLayout fitsSystemWindows.
*
* @param resId Resource id of a background drawable to draw behind the status bar
*/
public void setStatusBarBackgroundResource(int resId) {
setStatusBarBackground(resId != 0 ? ContextCompat.getDrawable(getContext(), resId) : null);
}
/**
* Set a drawable to draw in the insets area for the status bar.
* Note that this will only be activated if this DrawerLayout fitsSystemWindows.
*
* @param color Color to use as a background drawable to draw behind the status bar
* in 0xAARRGGBB format.
*/
public void setStatusBarBackgroundColor(int color) {
setStatusBarBackground(new ColorDrawable(color));
}
private void setWindowInsets(WindowInsetsCompat insets) {
if (mLastInsets != insets) {
mLastInsets = insets;
mDrawStatusBarBackground = insets != null && insets.getSystemWindowInsetTop() > 0;
setWillNotDraw(!mDrawStatusBarBackground && getBackground() == null);
dispatchChildApplyWindowInsets(insets);
requestLayout();
}
}
/**
* Reset all Behavior-related tracking records either to clean up or in preparation
* for a new event stream. This should be called when attached or detached from a window,
* in response to an UP or CANCEL event, when intercept is request-disallowed
* and similar cases where an event stream in progress will be aborted.
*/
private void resetTouchBehaviors() {
if (mBehaviorTouchView != null) {
final Behavior b = ((LayoutParams) mBehaviorTouchView.getLayoutParams()).getBehavior();
if (b != null) {
final long now = SystemClock.uptimeMillis();
final MotionEvent cancelEvent = MotionEvent.obtain(now, now,
MotionEvent.ACTION_CANCEL, 0.0f, 0.0f, 0);
b.onTouchEvent(this, mBehaviorTouchView, cancelEvent);
cancelEvent.recycle();
}
mBehaviorTouchView = null;
}
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
lp.resetTouchBehaviorTracking();
}
}
/**
* Populate a list with the current child views, sorted such that the topmost views
* in z-order are at the front of the list. Useful for hit testing and event dispatch.
*/
private void getTopSortedChildren(List<View> out) {
out.clear();
final boolean useCustomOrder = isChildrenDrawingOrderEnabled();
final int childCount = getChildCount();
for (int i = childCount - 1; i >= 0; i--) {
final int childIndex = useCustomOrder ? getChildDrawingOrder(childCount, i) : i;
final View child = getChildAt(childIndex);
out.add(child);
}
if (TOP_SORTED_CHILDREN_COMPARATOR != null) {
Collections.sort(out, TOP_SORTED_CHILDREN_COMPARATOR);
}
}
private boolean performIntercept(MotionEvent ev, final int type) {
boolean intercepted = false;
boolean newBlock = false;
MotionEvent cancelEvent = null;
final int action = MotionEventCompat.getActionMasked(ev);
final List<View> topmostChildList = mTempList1;
getTopSortedChildren(topmostChildList);
// Let topmost child views inspect first
final int childCount = topmostChildList.size();
for (int i = 0; i < childCount; i++) {
final View child = topmostChildList.get(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final Behavior b = lp.getBehavior();
if ((intercepted || newBlock) && action != MotionEvent.ACTION_DOWN) {
// Cancel all behaviors beneath the one that intercepted.
// If the event is "down" then we don't have anything to cancel yet.
if (b != null) {
if (cancelEvent == null) {
final long now = SystemClock.uptimeMillis();
cancelEvent = MotionEvent.obtain(now, now,
MotionEvent.ACTION_CANCEL, 0.0f, 0.0f, 0);
}
switch (type) {
case TYPE_ON_INTERCEPT:
b.onInterceptTouchEvent(this, child, cancelEvent);
break;
case TYPE_ON_TOUCH:
b.onTouchEvent(this, child, cancelEvent);
break;
}
}
continue;
}
if (!intercepted && b != null) {
switch (type) {
case TYPE_ON_INTERCEPT:
intercepted = b.onInterceptTouchEvent(this, child, ev);
break;
case TYPE_ON_TOUCH:
intercepted = b.onTouchEvent(this, child, ev);
break;
}
if (intercepted) {
mBehaviorTouchView = child;
}
}
// Don't keep going if we're not allowing interaction below this.
// Setting newBlock will make sure we cancel the rest of the behaviors.
final boolean wasBlocking = lp.didBlockInteraction();
final boolean isBlocking = lp.isBlockingInteractionBelow(this, child);
newBlock = isBlocking && !wasBlocking;
if (isBlocking && !newBlock) {
// Stop here since we don't have anything more to cancel - we already did
// when the behavior first started blocking things below this point.
break;
}
}
topmostChildList.clear();
return intercepted;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
MotionEvent cancelEvent = null;
final int action = MotionEventCompat.getActionMasked(ev);
// Make sure we reset in case we had missed a previous important event.
if (action == MotionEvent.ACTION_DOWN) {
resetTouchBehaviors();
}
final boolean intercepted = performIntercept(ev, TYPE_ON_INTERCEPT);
if (cancelEvent != null) {
cancelEvent.recycle();
}
if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
resetTouchBehaviors();
}
return intercepted;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
boolean handled = false;
boolean cancelSuper = false;
MotionEvent cancelEvent = null;
final int action = MotionEventCompat.getActionMasked(ev);
if (mBehaviorTouchView != null || (cancelSuper = performIntercept(ev, TYPE_ON_TOUCH))) {
// Safe since performIntercept guarantees that
// mBehaviorTouchView != null if it returns true
final LayoutParams lp = (LayoutParams) mBehaviorTouchView.getLayoutParams();
final Behavior b = lp.getBehavior();
if (b != null) {
handled = b.onTouchEvent(this, mBehaviorTouchView, ev);
}
}
// Keep the super implementation correct
if (mBehaviorTouchView == null) {
handled |= super.onTouchEvent(ev);
} else if (cancelSuper) {
if (cancelEvent == null) {
final long now = SystemClock.uptimeMillis();
cancelEvent = MotionEvent.obtain(now, now,
MotionEvent.ACTION_CANCEL, 0.0f, 0.0f, 0);
}
super.onTouchEvent(cancelEvent);
}
if (!handled && action == MotionEvent.ACTION_DOWN) {
}
if (cancelEvent != null) {
cancelEvent.recycle();
}
if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
resetTouchBehaviors();
}
return handled;
}
@Override
public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
super.requestDisallowInterceptTouchEvent(disallowIntercept);
if (disallowIntercept) {
resetTouchBehaviors();
}
}
private int getKeyline(int index) {
if (mKeylines == null) {
Log.e(TAG, "No keylines defined for " + this + " - attempted index lookup " + index);
return 0;
}
if (index < 0 || index >= mKeylines.length) {
Log.e(TAG, "Keyline index " + index + " out of range for " + this);
return 0;
}
return mKeylines[index];
}
static Behavior parseBehavior(Context context, AttributeSet attrs, String name) {
if (TextUtils.isEmpty(name)) {
return null;
}
final String fullName;
if (name.startsWith(".")) {
// Relative to the app package. Prepend the app package name.
fullName = context.getPackageName() + name;
} else if (name.indexOf('.') >= 0) {
// Fully qualified package name.
fullName = name;
} else {
// Assume stock behavior in this package.
fullName = WIDGET_PACKAGE_NAME + '.' + name;
}
try {
Map<String, Constructor<Behavior>> constructors = sConstructors.get();
if (constructors == null) {
constructors = new HashMap<>();
sConstructors.set(constructors);
}
Constructor<Behavior> c = constructors.get(fullName);
if (c == null) {
final Class<Behavior> clazz = (Class<Behavior>) Class.forName(fullName, true,
context.getClassLoader());
c = clazz.getConstructor(CONSTRUCTOR_PARAMS);
c.setAccessible(true);
constructors.put(fullName, c);
}
return c.newInstance(context, attrs);
} catch (Exception e) {
throw new RuntimeException("Could not inflate Behavior subclass " + fullName, e);
}
}
LayoutParams getResolvedLayoutParams(View child) {
final LayoutParams result = (LayoutParams) child.getLayoutParams();
if (!result.mBehaviorResolved) {
Class<?> childClass = child.getClass();
DefaultBehavior defaultBehavior = null;
while (childClass != null &&
(defaultBehavior = childClass.getAnnotation(DefaultBehavior.class)) == null) {
childClass = childClass.getSuperclass();
}
if (defaultBehavior != null) {
try {
result.setBehavior(defaultBehavior.value().newInstance());
} catch (Exception e) {
Log.e(TAG, "Default behavior class " + defaultBehavior.value().getName() +
" could not be instantiated. Did you forget a default constructor?", e);
}
}
result.mBehaviorResolved = true;
}
return result;
}
private void prepareChildren() {
final int childCount = getChildCount();
boolean resortRequired = mDependencySortedChildren.size() != childCount;
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
final LayoutParams lp = getResolvedLayoutParams(child);
if (!resortRequired && lp.isDirty(this, child)) {
resortRequired = true;
}
lp.findAnchorView(this, child);
}
if (resortRequired) {
mDependencySortedChildren.clear();
for (int i = 0; i < childCount; i++) {
mDependencySortedChildren.add(getChildAt(i));
}
Collections.sort(mDependencySortedChildren, mLayoutDependencyComparator);
}
}
/**
* Retrieve the transformed bounding rect of an arbitrary descendant view.
* This does not need to be a direct child.
*
* @param descendant descendant view to reference
* @param out rect to set to the bounds of the descendant view
*/
void getDescendantRect(View descendant, Rect out) {
ViewGroupUtils.getDescendantRect(this, descendant, out);
}
@Override
protected int getSuggestedMinimumWidth() {
return Math.max(super.getSuggestedMinimumWidth(), getPaddingLeft() + getPaddingRight());
}
@Override
protected int getSuggestedMinimumHeight() {
return Math.max(super.getSuggestedMinimumHeight(), getPaddingTop() + getPaddingBottom());
}
/**
* Called to measure each individual child view unless a
* {@link CoordinatorLayout.Behavior Behavior} is present. The Behavior may choose to delegate
* child measurement to this method.
*
* @param child the child to measure
* @param parentWidthMeasureSpec the width requirements for this view
* @param widthUsed extra space that has been used up by the parent
* horizontally (possibly by other children of the parent)
* @param parentHeightMeasureSpec the height requirements for this view
* @param heightUsed extra space that has been used up by the parent
* vertically (possibly by other children of the parent)
*/
public void onMeasureChild(View child, int parentWidthMeasureSpec, int widthUsed,
int parentHeightMeasureSpec, int heightUsed) {
measureChildWithMargins(child, parentWidthMeasureSpec, widthUsed,
parentHeightMeasureSpec, heightUsed);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
prepareChildren();
ensurePreDrawListener();
final int paddingLeft = getPaddingLeft();
final int paddingTop = getPaddingTop();
final int paddingRight = getPaddingRight();
final int paddingBottom = getPaddingBottom();
final int layoutDirection = ViewCompat.getLayoutDirection(this);
final boolean isRtl = layoutDirection == ViewCompat.LAYOUT_DIRECTION_RTL;
final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
final int widthSize = MeasureSpec.getSize(widthMeasureSpec);
final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
final int heightSize = MeasureSpec.getSize(heightMeasureSpec);
final int widthPadding = paddingLeft + paddingRight;
final int heightPadding = paddingTop + paddingBottom;
int widthUsed = getSuggestedMinimumWidth();
int heightUsed = getSuggestedMinimumHeight();
int childState = 0;
final boolean applyInsets = mLastInsets != null && ViewCompat.getFitsSystemWindows(this);
final int childCount = mDependencySortedChildren.size();
for (int i = 0; i < childCount; i++) {
final View child = mDependencySortedChildren.get(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
int keylineWidthUsed = 0;
if (lp.keyline >= 0 && widthMode != MeasureSpec.UNSPECIFIED) {
final int keylinePos = getKeyline(lp.keyline);
final int keylineGravity = GravityCompat.getAbsoluteGravity(
resolveKeylineGravity(lp.gravity), layoutDirection)
& Gravity.HORIZONTAL_GRAVITY_MASK;
if ((keylineGravity == Gravity.LEFT && !isRtl)
|| (keylineGravity == Gravity.RIGHT && isRtl)) {
keylineWidthUsed = Math.max(0, widthSize - paddingRight - keylinePos);
} else if ((keylineGravity == Gravity.RIGHT && !isRtl)
|| (keylineGravity == Gravity.LEFT && isRtl)) {
keylineWidthUsed = Math.max(0, keylinePos - paddingLeft);
}
}
int childWidthMeasureSpec = widthMeasureSpec;
int childHeightMeasureSpec = heightMeasureSpec;
if (applyInsets && !ViewCompat.getFitsSystemWindows(child)) {
// We're set to handle insets but this child isn't, so we will measure the
// child as if there are no insets
final int horizInsets = mLastInsets.getSystemWindowInsetLeft()
+ mLastInsets.getSystemWindowInsetRight();
final int vertInsets = mLastInsets.getSystemWindowInsetTop()
+ mLastInsets.getSystemWindowInsetBottom();
childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(
widthSize - horizInsets, widthMode);
childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
heightSize - vertInsets, heightMode);
}
final Behavior b = lp.getBehavior();
if (b == null || !b.onMeasureChild(this, child, childWidthMeasureSpec, keylineWidthUsed,
childHeightMeasureSpec, 0)) {
onMeasureChild(child, childWidthMeasureSpec, keylineWidthUsed,
childHeightMeasureSpec, 0);
}
widthUsed = Math.max(widthUsed, widthPadding + child.getMeasuredWidth() +
lp.leftMargin + lp.rightMargin);
heightUsed = Math.max(heightUsed, heightPadding + child.getMeasuredHeight() +
lp.topMargin + lp.bottomMargin);
childState = ViewCompat.combineMeasuredStates(childState,
ViewCompat.getMeasuredState(child));
}
final int width = ViewCompat.resolveSizeAndState(widthUsed, widthMeasureSpec,
childState & ViewCompat.MEASURED_STATE_MASK);
final int height = ViewCompat.resolveSizeAndState(heightUsed, heightMeasureSpec,
childState << ViewCompat.MEASURED_HEIGHT_STATE_SHIFT);
setMeasuredDimension(width, height);
}
private void dispatchChildApplyWindowInsets(WindowInsetsCompat insets) {
if (insets.isConsumed()) {
return;
}
for (int i = 0, z = getChildCount(); i < z; i++) {
final View child = getChildAt(i);
if (ViewCompat.getFitsSystemWindows(child)) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final Behavior b = lp.getBehavior();
if (b != null) {
// If the view has a behavior, let it try first
insets = b.onApplyWindowInsets(this, child, insets);
if (insets.isConsumed()) {
// If it consumed the insets, break
break;
}
}
// Now let the view try and consume them
insets = ViewCompat.dispatchApplyWindowInsets(child, insets);
if (insets.isConsumed()) {
break;
}
}
}
}
/**
* Called to lay out each individual child view unless a
* {@link CoordinatorLayout.Behavior Behavior} is present. The Behavior may choose to
* delegate child measurement to this method.
*
* @param child child view to lay out
* @param layoutDirection the resolved layout direction for the CoordinatorLayout, such as
* {@link ViewCompat#LAYOUT_DIRECTION_LTR} or
* {@link ViewCompat#LAYOUT_DIRECTION_RTL}.
*/
public void onLayoutChild(View child, int layoutDirection) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (lp.checkAnchorChanged()) {
throw new IllegalStateException("An anchor may not be changed after CoordinatorLayout"
+ " measurement begins before layout is complete.");
}
if (lp.mAnchorView != null) {
layoutChildWithAnchor(child, lp.mAnchorView, layoutDirection);
} else if (lp.keyline >= 0) {
layoutChildWithKeyline(child, lp.keyline, layoutDirection);
} else {
layoutChild(child, layoutDirection);
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
final int layoutDirection = ViewCompat.getLayoutDirection(this);
final int childCount = mDependencySortedChildren.size();
for (int i = 0; i < childCount; i++) {
final View child = mDependencySortedChildren.get(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final Behavior behavior = lp.getBehavior();
if (behavior == null || !behavior.onLayoutChild(this, child, layoutDirection)) {
onLayoutChild(child, layoutDirection);
}
}
}
@Override
public void onDraw(Canvas c) {
super.onDraw(c);
if (mDrawStatusBarBackground && mStatusBarBackground != null) {
final int inset = mLastInsets != null ? mLastInsets.getSystemWindowInsetTop() : 0;
if (inset > 0) {
mStatusBarBackground.setBounds(0, 0, getWidth(), inset);
mStatusBarBackground.draw(c);
}
}
}
/**
* Mark the last known child position rect for the given child view.
* This will be used when checking if a child view's position has changed between frames.
* The rect used here should be one returned by
* {@link #getChildRect(android.view.View, boolean, android.graphics.Rect)}, with translation
* disabled.
*
* @param child child view to set for
* @param r rect to set
*/
void recordLastChildRect(View child, Rect r) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
lp.setLastChildRect(r);
}
/**
* Get the last known child rect recorded by
* {@link #recordLastChildRect(android.view.View, android.graphics.Rect)}.
*
* @param child child view to retrieve from
* @param out rect to set to the outpur values
*/
void getLastChildRect(View child, Rect out) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
out.set(lp.getLastChildRect());
}
/**
* Get the position rect for the given child. If the child has currently requested layout
* or has a visibility of GONE.
*
* @param child child view to check
* @param transform true to include transformation in the output rect, false to
* only account for the base position
* @param out rect to set to the output values
*/
void getChildRect(View child, boolean transform, Rect out) {
if (child.isLayoutRequested() || child.getVisibility() == View.GONE) {
out.set(0, 0, 0, 0);
return;
}
if (transform) {
getDescendantRect(child, out);
} else {
out.set(child.getLeft(), child.getTop(), child.getRight(), child.getBottom());
}
}
/**
* Calculate the desired child rect relative to an anchor rect, respecting both
* gravity and anchorGravity.
*
* @param child child view to calculate a rect for
* @param layoutDirection the desired layout direction for the CoordinatorLayout
* @param anchorRect rect in CoordinatorLayout coordinates of the anchor view area
* @param out rect to set to the output values
*/
void getDesiredAnchoredChildRect(View child, int layoutDirection, Rect anchorRect, Rect out) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final int absGravity = GravityCompat.getAbsoluteGravity(
resolveAnchoredChildGravity(lp.gravity), layoutDirection);
final int absAnchorGravity = GravityCompat.getAbsoluteGravity(
resolveGravity(lp.anchorGravity),
layoutDirection);
final int hgrav = absGravity & Gravity.HORIZONTAL_GRAVITY_MASK;
final int vgrav = absGravity & Gravity.VERTICAL_GRAVITY_MASK;
final int anchorHgrav = absAnchorGravity & Gravity.HORIZONTAL_GRAVITY_MASK;
final int anchorVgrav = absAnchorGravity & Gravity.VERTICAL_GRAVITY_MASK;
final int childWidth = child.getMeasuredWidth();
final int childHeight = child.getMeasuredHeight();
int left;
int top;
// Align to the anchor. This puts us in an assumed right/bottom child view gravity.
// If this is not the case we will subtract out the appropriate portion of
// the child size below.
switch (anchorHgrav) {
default:
case Gravity.LEFT:
left = anchorRect.left;
break;
case Gravity.RIGHT:
left = anchorRect.right;
break;
case Gravity.CENTER_HORIZONTAL:
left = anchorRect.left + anchorRect.width() / 2;
break;
}
switch (anchorVgrav) {
default:
case Gravity.TOP:
top = anchorRect.top;
break;
case Gravity.BOTTOM:
top = anchorRect.bottom;
break;
case Gravity.CENTER_VERTICAL:
top = anchorRect.top + anchorRect.height() / 2;
break;
}
// Offset by the child view's gravity itself. The above assumed right/bottom gravity.
switch (hgrav) {
default:
case Gravity.LEFT:
left -= childWidth;
break;
case Gravity.RIGHT:
// Do nothing, we're already in position.
break;
case Gravity.CENTER_HORIZONTAL:
left -= childWidth / 2;
break;
}
switch (vgrav) {
default:
case Gravity.TOP:
top -= childHeight;
break;
case Gravity.BOTTOM:
// Do nothing, we're already in position.
break;
case Gravity.CENTER_VERTICAL:
top -= childHeight / 2;
break;
}
final int width = getWidth();
final int height = getHeight();
// Obey margins and padding
left = Math.max(getPaddingLeft() + lp.leftMargin,
Math.min(left,
width - getPaddingRight() - childWidth - lp.rightMargin));
top = Math.max(getPaddingTop() + lp.topMargin,
Math.min(top,
height - getPaddingBottom() - childHeight - lp.bottomMargin));
out.set(left, top, left + childWidth, top + childHeight);
}
/**
* CORE ASSUMPTION: anchor has been laid out by the time this is called for a given child view.
*
* @param child child to lay out
* @param anchor view to anchor child relative to; already laid out.
* @param layoutDirection ViewCompat constant for layout direction
*/
private void layoutChildWithAnchor(View child, View anchor, int layoutDirection) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final Rect anchorRect = mTempRect1;
final Rect childRect = mTempRect2;
getDescendantRect(anchor, anchorRect);
getDesiredAnchoredChildRect(child, layoutDirection, anchorRect, childRect);
child.layout(childRect.left, childRect.top, childRect.right, childRect.bottom);
}
/**
* Lay out a child view with respect to a keyline.
*
* <p>The keyline represents a horizontal offset from the unpadded starting edge of
* the CoordinatorLayout. The child's gravity will affect how it is positioned with
* respect to the keyline.</p>
*
* @param child child to lay out
* @param keyline offset from the starting edge in pixels of the keyline to align with
* @param layoutDirection ViewCompat constant for layout direction
*/
private void layoutChildWithKeyline(View child, int keyline, int layoutDirection) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final int absGravity = GravityCompat.getAbsoluteGravity(
resolveKeylineGravity(lp.gravity), layoutDirection);
final int hgrav = absGravity & Gravity.HORIZONTAL_GRAVITY_MASK;
final int vgrav = absGravity & Gravity.VERTICAL_GRAVITY_MASK;
final int width = getWidth();
final int height = getHeight();
final int childWidth = child.getMeasuredWidth();
final int childHeight = child.getMeasuredHeight();
if (layoutDirection == ViewCompat.LAYOUT_DIRECTION_RTL) {
keyline = width - keyline;
}
int left = getKeyline(keyline) - childWidth;
int top = 0;
switch (hgrav) {
default:
case Gravity.LEFT:
// Nothing to do.
break;
case Gravity.RIGHT:
left += childWidth;
break;
case Gravity.CENTER_HORIZONTAL:
left += childWidth / 2;
break;
}
switch (vgrav) {
default:
case Gravity.TOP:
// Do nothing, we're already in position.
break;
case Gravity.BOTTOM:
top += childHeight;
break;
case Gravity.CENTER_VERTICAL:
top += childHeight / 2;
break;
}
// Obey margins and padding
left = Math.max(getPaddingLeft() + lp.leftMargin,
Math.min(left,
width - getPaddingRight() - childWidth - lp.rightMargin));
top = Math.max(getPaddingTop() + lp.topMargin,
Math.min(top,
height - getPaddingBottom() - childHeight - lp.bottomMargin));
child.layout(left, top, left + childWidth, top + childHeight);
}
/**
* Lay out a child view with no special handling. This will position the child as
* if it were within a FrameLayout or similar simple frame.
*
* @param child child view to lay out
* @param layoutDirection ViewCompat constant for the desired layout direction
*/
private void layoutChild(View child, int layoutDirection) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final Rect parent = mTempRect1;
parent.set(getPaddingLeft() + lp.leftMargin,
getPaddingTop() + lp.topMargin,
getWidth() - getPaddingRight() - lp.rightMargin,
getHeight() - getPaddingBottom() - lp.bottomMargin);
if (mLastInsets != null && ViewCompat.getFitsSystemWindows(this)
&& !ViewCompat.getFitsSystemWindows(child)) {
// If we're set to handle insets but this child isn't, then it has been measured as
// if there are no insets. We need to lay it out to match.
parent.left += mLastInsets.getSystemWindowInsetLeft();
parent.top += mLastInsets.getSystemWindowInsetTop();
parent.right -= mLastInsets.getSystemWindowInsetRight();
parent.bottom -= mLastInsets.getSystemWindowInsetBottom();
}
final Rect out = mTempRect2;
GravityCompat.apply(resolveGravity(lp.gravity), child.getMeasuredWidth(),
child.getMeasuredHeight(), parent, out, layoutDirection);
child.layout(out.left, out.top, out.right, out.bottom);
}
/**
* Return the given gravity value or the default if the passed value is NO_GRAVITY.
* This should be used for children that are not anchored to another view or a keyline.
*/
private static int resolveGravity(int gravity) {
return gravity == Gravity.NO_GRAVITY ? GravityCompat.START | Gravity.TOP : gravity;
}
/**
* Return the given gravity value or the default if the passed value is NO_GRAVITY.
* This should be used for children that are positioned relative to a keyline.
*/
private static int resolveKeylineGravity(int gravity) {
return gravity == Gravity.NO_GRAVITY ? GravityCompat.END | Gravity.TOP : gravity;
}
/**
* Return the given gravity value or the default if the passed value is NO_GRAVITY.
* This should be used for children that are anchored to another view.
*/
private static int resolveAnchoredChildGravity(int gravity) {
return gravity == Gravity.NO_GRAVITY ? Gravity.CENTER : gravity;
}
@Override
protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (lp.mBehavior != null && lp.mBehavior.getScrimOpacity(this, child) > 0.f) {
if (mScrimPaint == null) {
mScrimPaint = new Paint();
}
mScrimPaint.setColor(lp.mBehavior.getScrimColor(this, child));
// TODO: Set the clip appropriately to avoid unnecessary overdraw.
canvas.drawRect(getPaddingLeft(), getPaddingTop(),
getWidth() - getPaddingRight(), getHeight() - getPaddingBottom(), mScrimPaint);
}
return super.drawChild(canvas, child, drawingTime);
}
/**
* Dispatch any dependent view changes to the relevant {@link Behavior} instances.
*
* Usually run as part of the pre-draw step when at least one child view has a reported
* dependency on another view. This allows CoordinatorLayout to account for layout
* changes and animations that occur outside of the normal layout pass.
*
* It can also be ran as part of the nested scrolling dispatch to ensure that any offsetting
* is completed within the correct coordinate window.
*
* The offsetting behavior implemented here does not store the computed offset in
* the LayoutParams; instead it expects that the layout process will always reconstruct
* the proper positioning.
*
* @param fromNestedScroll true if this is being called from one of the nested scroll methods,
* false if run as part of the pre-draw step.
*/
void dispatchOnDependentViewChanged(final boolean fromNestedScroll) {
final int layoutDirection = ViewCompat.getLayoutDirection(this);
final int childCount = mDependencySortedChildren.size();
for (int i = 0; i < childCount; i++) {
final View child = mDependencySortedChildren.get(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
// Check child views before for anchor
for (int j = 0; j < i; j++) {
final View checkChild = mDependencySortedChildren.get(j);
if (lp.mAnchorDirectChild == checkChild) {
offsetChildToAnchor(child, layoutDirection);
}
}
// Did it change? if not continue
final Rect oldRect = mTempRect1;
final Rect newRect = mTempRect2;
getLastChildRect(child, oldRect);
getChildRect(child, true, newRect);
if (oldRect.equals(newRect)) {
continue;
}
recordLastChildRect(child, newRect);
// Update any behavior-dependent views for the change
for (int j = i + 1; j < childCount; j++) {
final View checkChild = mDependencySortedChildren.get(j);
final LayoutParams checkLp = (LayoutParams) checkChild.getLayoutParams();
final Behavior b = checkLp.getBehavior();
if (b != null && b.layoutDependsOn(this, checkChild, child)) {
if (!fromNestedScroll && checkLp.getChangedAfterNestedScroll()) {
// If this is not from a nested scroll and we have already been changed
// from a nested scroll, skip the dispatch and reset the flag
checkLp.resetChangedAfterNestedScroll();
continue;
}
final boolean handled = b.onDependentViewChanged(this, checkChild, child);
if (fromNestedScroll) {
// If this is from a nested scroll, set the flag so that we may skip
// any resulting onPreDraw dispatch (if needed)
checkLp.setChangedAfterNestedScroll(handled);
}
}
}
}
}
void dispatchDependentViewRemoved(View removedChild) {
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final Behavior b = lp.getBehavior();
if (b != null && b.layoutDependsOn(this, child, removedChild)) {
b.onDependentViewRemoved(this, child, removedChild);
}
}
}
/**
* Allows the caller to manually dispatch
* {@link Behavior#onDependentViewChanged(CoordinatorLayout, View, View)} to the associated
* {@link Behavior} instances of views which depend on the provided {@link View}.
*
* <p>You should not normally need to call this method as the it will be automatically done
* when the view has changed.
*
* @param view the View to find dependents of to dispatch the call.
*/
public void dispatchDependentViewsChanged(View view) {
final int childCount = mDependencySortedChildren.size();
boolean viewSeen = false;
for (int i = 0; i < childCount; i++) {
final View child = mDependencySortedChildren.get(i);
if (child == view) {
// We've seen our view, which means that any Views after this could be dependent
viewSeen = true;
continue;
}
if (viewSeen) {
CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams)
child.getLayoutParams();
CoordinatorLayout.Behavior b = lp.getBehavior();
if (b != null && lp.dependsOn(this, child, view)) {
b.onDependentViewChanged(this, child, view);
}
}
}
}
/**
* Returns the list of views which the provided view depends on. Do not store this list as it's
* contents may not be valid beyond the caller.
*
* @param child the view to find dependencies for.
*
* @return the list of views which {@code child} depends on.
*/
public List<View> getDependencies(View child) {
// TODO The result of this is probably a good candidate for caching
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final List<View> list = mTempDependenciesList;
list.clear();
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View other = getChildAt(i);
if (other == child) {
continue;
}
if (lp.dependsOn(this, child, other)) {
list.add(other);
}
}
return list;
}
/**
* Add or remove the pre-draw listener as necessary.
*/
void ensurePreDrawListener() {
boolean hasDependencies = false;
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
if (hasDependencies(child)) {
hasDependencies = true;
break;
}
}
if (hasDependencies != mNeedsPreDrawListener) {
if (hasDependencies) {
addPreDrawListener();
} else {
removePreDrawListener();
}
}
}
/**
* Check if the given child has any layout dependencies on other child views.
*/
boolean hasDependencies(View child) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (lp.mAnchorView != null) {
return true;
}
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View other = getChildAt(i);
if (other == child) {
continue;
}
if (lp.dependsOn(this, child, other)) {
return true;
}
}
return false;
}
/**
* Add the pre-draw listener if we're attached to a window and mark that we currently
* need it when attached.
*/
void addPreDrawListener() {
if (mIsAttachedToWindow) {
// Add the listener
if (mOnPreDrawListener == null) {
mOnPreDrawListener = new OnPreDrawListener();
}
final ViewTreeObserver vto = getViewTreeObserver();
vto.addOnPreDrawListener(mOnPreDrawListener);
}
// Record that we need the listener regardless of whether or not we're attached.
// We'll add the real listener when we become attached.
mNeedsPreDrawListener = true;
}
/**
* Remove the pre-draw listener if we're attached to a window and mark that we currently
* do not need it when attached.
*/
void removePreDrawListener() {
if (mIsAttachedToWindow) {
if (mOnPreDrawListener != null) {
final ViewTreeObserver vto = getViewTreeObserver();
vto.removeOnPreDrawListener(mOnPreDrawListener);
}
}
mNeedsPreDrawListener = false;
}
/**
* Adjust the child left, top, right, bottom rect to the correct anchor view position,
* respecting gravity and anchor gravity.
*
* Note that child translation properties are ignored in this process, allowing children
* to be animated away from their anchor. However, if the anchor view is animated,
* the child will be offset to match the anchor's translated position.
*/
void offsetChildToAnchor(View child, int layoutDirection) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (lp.mAnchorView != null) {
final Rect anchorRect = mTempRect1;
final Rect childRect = mTempRect2;
final Rect desiredChildRect = mTempRect3;
getDescendantRect(lp.mAnchorView, anchorRect);
getChildRect(child, false, childRect);
getDesiredAnchoredChildRect(child, layoutDirection, anchorRect, desiredChildRect);
final int dx = desiredChildRect.left - childRect.left;
final int dy = desiredChildRect.top - childRect.top;
if (dx != 0) {
child.offsetLeftAndRight(dx);
}
if (dy != 0) {
child.offsetTopAndBottom(dy);
}
if (dx != 0 || dy != 0) {
// If we have needed to move, make sure to notify the child's Behavior
final Behavior b = lp.getBehavior();
if (b != null) {
b.onDependentViewChanged(this, child, lp.mAnchorView);
}
}
}
}
/**
* Check if a given point in the CoordinatorLayout's coordinates are within the view bounds
* of the given direct child view.
*
* @param child child view to test
* @param x X coordinate to test, in the CoordinatorLayout's coordinate system
* @param y Y coordinate to test, in the CoordinatorLayout's coordinate system
* @return true if the point is within the child view's bounds, false otherwise
*/
public boolean isPointInChildBounds(View child, int x, int y) {
final Rect r = mTempRect1;
getDescendantRect(child, r);
return r.contains(x, y);
}
/**
* Check whether two views overlap each other. The views need to be descendants of this
* {@link CoordinatorLayout} in the view hierarchy.
*
* @param first first child view to test
* @param second second child view to test
* @return true if both views are visible and overlap each other
*/
public boolean doViewsOverlap(View first, View second) {
if (first.getVisibility() == VISIBLE && second.getVisibility() == VISIBLE) {
final Rect firstRect = mTempRect1;
getChildRect(first, first.getParent() != this, firstRect);
final Rect secondRect = mTempRect2;
getChildRect(second, second.getParent() != this, secondRect);
return !(firstRect.left > secondRect.right || firstRect.top > secondRect.bottom
|| firstRect.right < secondRect.left || firstRect.bottom < secondRect.top);
}
return false;
}
@Override
public LayoutParams generateLayoutParams(AttributeSet attrs) {
return new LayoutParams(getContext(), attrs);
}
@Override
protected LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
if (p instanceof LayoutParams) {
return new LayoutParams((LayoutParams) p);
} else if (p instanceof MarginLayoutParams) {
return new LayoutParams((MarginLayoutParams) p);
}
return new LayoutParams(p);
}
@Override
protected LayoutParams generateDefaultLayoutParams() {
return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
}
@Override
protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
return p instanceof LayoutParams && super.checkLayoutParams(p);
}
public boolean onStartNestedScroll(View child, View target, int nestedScrollAxes) {
boolean handled = false;
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View view = getChildAt(i);
final LayoutParams lp = (LayoutParams) view.getLayoutParams();
final Behavior viewBehavior = lp.getBehavior();
if (viewBehavior != null) {
final boolean accepted = viewBehavior.onStartNestedScroll(this, view, child, target,
nestedScrollAxes);
handled |= accepted;
lp.acceptNestedScroll(accepted);
} else {
lp.acceptNestedScroll(false);
}
}
return handled;
}
public void onNestedScrollAccepted(View child, View target, int nestedScrollAxes) {
mNestedScrollingParentHelper.onNestedScrollAccepted(child, target, nestedScrollAxes);
mNestedScrollingDirectChild = child;
mNestedScrollingTarget = target;
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View view = getChildAt(i);
final LayoutParams lp = (LayoutParams) view.getLayoutParams();
if (!lp.isNestedScrollAccepted()) {
continue;
}
final Behavior viewBehavior = lp.getBehavior();
if (viewBehavior != null) {
viewBehavior.onNestedScrollAccepted(this, view, child, target, nestedScrollAxes);
}
}
}
public void onStopNestedScroll(View target) {
mNestedScrollingParentHelper.onStopNestedScroll(target);
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View view = getChildAt(i);
final LayoutParams lp = (LayoutParams) view.getLayoutParams();
if (!lp.isNestedScrollAccepted()) {
continue;
}
final Behavior viewBehavior = lp.getBehavior();
if (viewBehavior != null) {
viewBehavior.onStopNestedScroll(this, view, target);
}
lp.resetNestedScroll();
lp.resetChangedAfterNestedScroll();
}
mNestedScrollingDirectChild = null;
mNestedScrollingTarget = null;
}
public void onNestedScroll(View target, int dxConsumed, int dyConsumed,
int dxUnconsumed, int dyUnconsumed) {
final int childCount = getChildCount();
boolean accepted = false;
for (int i = 0; i < childCount; i++) {
final View view = getChildAt(i);
final LayoutParams lp = (LayoutParams) view.getLayoutParams();
if (!lp.isNestedScrollAccepted()) {
continue;
}
final Behavior viewBehavior = lp.getBehavior();
if (viewBehavior != null) {
viewBehavior.onNestedScroll(this, view, target, dxConsumed, dyConsumed,
dxUnconsumed, dyUnconsumed);
accepted = true;
}
}
if (accepted) {
dispatchOnDependentViewChanged(true);
}
}
public void onNestedPreScroll(View target, int dx, int dy, int[] consumed) {
int xConsumed = 0;
int yConsumed = 0;
boolean accepted = false;
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View view = getChildAt(i);
final LayoutParams lp = (LayoutParams) view.getLayoutParams();
if (!lp.isNestedScrollAccepted()) {
continue;
}
final Behavior viewBehavior = lp.getBehavior();
if (viewBehavior != null) {
mTempIntPair[0] = mTempIntPair[1] = 0;
viewBehavior.onNestedPreScroll(this, view, target, dx, dy, mTempIntPair);
xConsumed = dx > 0 ? Math.max(xConsumed, mTempIntPair[0])
: Math.min(xConsumed, mTempIntPair[0]);
yConsumed = dy > 0 ? Math.max(yConsumed, mTempIntPair[1])
: Math.min(yConsumed, mTempIntPair[1]);
accepted = true;
}
}
consumed[0] = xConsumed;
consumed[1] = yConsumed;
if (accepted) {
dispatchOnDependentViewChanged(true);
}
}
public boolean onNestedFling(View target, float velocityX, float velocityY, boolean consumed) {
boolean handled = false;
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View view = getChildAt(i);
final LayoutParams lp = (LayoutParams) view.getLayoutParams();
if (!lp.isNestedScrollAccepted()) {
continue;
}
final Behavior viewBehavior = lp.getBehavior();
if (viewBehavior != null) {
handled |= viewBehavior.onNestedFling(this, view, target, velocityX, velocityY,
consumed);
}
}
if (handled) {
dispatchOnDependentViewChanged(true);
}
return handled;
}
public boolean onNestedPreFling(View target, float velocityX, float velocityY) {
boolean handled = false;
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View view = getChildAt(i);
final LayoutParams lp = (LayoutParams) view.getLayoutParams();
if (!lp.isNestedScrollAccepted()) {
continue;
}
final Behavior viewBehavior = lp.getBehavior();
if (viewBehavior != null) {
handled |= viewBehavior.onNestedPreFling(this, view, target, velocityX, velocityY);
}
}
return handled;
}
public int getNestedScrollAxes() {
return mNestedScrollingParentHelper.getNestedScrollAxes();
}
class OnPreDrawListener implements ViewTreeObserver.OnPreDrawListener {
@Override
public boolean onPreDraw() {
dispatchOnDependentViewChanged(false);
return true;
}
}
/**
* Sorts child views with higher Z values to the beginning of a collection.
*/
static class ViewElevationComparator implements Comparator<View> {
@Override
public int compare(View lhs, View rhs) {
final float lz = ViewCompat.getZ(lhs);
final float rz = ViewCompat.getZ(rhs);
if (lz > rz) {
return -1;
} else if (lz < rz) {
return 1;
}
return 0;
}
}
/**
* Defines the default {@link Behavior} of a {@link View} class.
*
* <p>When writing a custom view, use this annotation to define the default behavior
* when used as a direct child of an {@link CoordinatorLayout}. The default behavior
* can be overridden using {@link LayoutParams#setBehavior}.</p>
*
* <p>Example: <code>@DefaultBehavior(MyBehavior.class)</code></p>
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface DefaultBehavior {
Class<? extends Behavior> value();
}
/**
* Interaction behavior plugin for child views of {@link CoordinatorLayout}.
*
* <p>A Behavior implements one or more interactions that a user can take on a child view.
* These interactions may include drags, swipes, flings, or any other gestures.</p>
*
* @param <V> The View type that this Behavior operates on
*/
public static abstract class Behavior<V extends View> {
/**
* Default constructor for instantiating Behaviors.
*/
public Behavior() {
}
/**
* Default constructor for inflating Behaviors from layout. The Behavior will have
* the opportunity to parse specially defined layout parameters. These parameters will
* appear on the child view tag.
*
* @param context
* @param attrs
*/
public Behavior(Context context, AttributeSet attrs) {
}
/**
* Respond to CoordinatorLayout touch events before they are dispatched to child views.
*
* <p>Behaviors can use this to monitor inbound touch events until one decides to
* intercept the rest of the event stream to take an action on its associated child view.
* This method will return false until it detects the proper intercept conditions, then
* return true once those conditions have occurred.</p>
*
* <p>Once a Behavior intercepts touch events, the rest of the event stream will
* be sent to the {@link #onTouchEvent} method.</p>
*
* <p>The default implementation of this method always returns false.</p>
*
* @param parent the parent view currently receiving this touch event
* @param child the child view associated with this Behavior
* @param ev the MotionEvent describing the touch event being processed
* @return true if this Behavior would like to intercept and take over the event stream.
* The default always returns false.
*/
public boolean onInterceptTouchEvent(CoordinatorLayout parent, V child, MotionEvent ev) {
return false;
}
/**
* Respond to CoordinatorLayout touch events after this Behavior has started
* {@link #onInterceptTouchEvent intercepting} them.
*
* <p>Behaviors may intercept touch events in order to help the CoordinatorLayout
* manipulate its child views. For example, a Behavior may allow a user to drag a
* UI pane open or closed. This method should perform actual mutations of view
* layout state.</p>
*
* @param parent the parent view currently receiving this touch event
* @param child the child view associated with this Behavior
* @param ev the MotionEvent describing the touch event being processed
* @return true if this Behavior handled this touch event and would like to continue
* receiving events in this stream. The default always returns false.
*/
public boolean onTouchEvent(CoordinatorLayout parent, V child, MotionEvent ev) {
return false;
}
/**
* Supply a scrim color that will be painted behind the associated child view.
*
* <p>A scrim may be used to indicate that the other elements beneath it are not currently
* interactive or actionable, drawing user focus and attention to the views above the scrim.
* </p>
*
* <p>The default implementation returns {@link Color#BLACK}.</p>
*
* @param parent the parent view of the given child
* @param child the child view above the scrim
* @return the desired scrim color in 0xAARRGGBB format. The default return value is
* {@link Color#BLACK}.
* @see #getScrimOpacity(CoordinatorLayout, android.view.View)
*/
public final int getScrimColor(CoordinatorLayout parent, V child) {
return Color.BLACK;
}
/**
* Determine the current opacity of the scrim behind a given child view
*
* <p>A scrim may be used to indicate that the other elements beneath it are not currently
* interactive or actionable, drawing user focus and attention to the views above the scrim.
* </p>
*
* <p>The default implementation returns 0.0f.</p>
*
* @param parent the parent view of the given child
* @param child the child view above the scrim
* @return the desired scrim opacity from 0.0f to 1.0f. The default return value is 0.0f.
*/
public final float getScrimOpacity(CoordinatorLayout parent, V child) {
return 0.f;
}
/**
* Determine whether interaction with views behind the given child in the child order
* should be blocked.
*
* <p>The default implementation returns true if
* {@link #getScrimOpacity(CoordinatorLayout, android.view.View)} would return > 0.0f.</p>
*
* @param parent the parent view of the given child
* @param child the child view to test
* @return true if {@link #getScrimOpacity(CoordinatorLayout, android.view.View)} would
* return > 0.0f.
*/
public boolean blocksInteractionBelow(CoordinatorLayout parent, V child) {
return getScrimOpacity(parent, child) > 0.f;
}
/**
* Determine whether the supplied child view has another specific sibling view as a
* layout dependency.
*
* <p>This method will be called at least once in response to a layout request. If it
* returns true for a given child and dependency view pair, the parent CoordinatorLayout
* will:</p>
* <ol>
* <li>Always lay out this child after the dependent child is laid out, regardless
* of child order.</li>
* <li>Call {@link #onDependentViewChanged} when the dependency view's layout or
* position changes.</li>
* </ol>
*
* @param parent the parent view of the given child
* @param child the child view to test
* @param dependency the proposed dependency of child
* @return true if child's layout depends on the proposed dependency's layout,
* false otherwise
*
* @see #onDependentViewChanged(CoordinatorLayout, android.view.View, android.view.View)
*/
public boolean layoutDependsOn(CoordinatorLayout parent, V child, View dependency) {
return false;
}
/**
* Respond to a change in a child's dependent view
*
* <p>This method is called whenever a dependent view changes in size or position outside
* of the standard layout flow. A Behavior may use this method to appropriately update
* the child view in response.</p>
*
* <p>A view's dependency is determined by
* {@link #layoutDependsOn(CoordinatorLayout, android.view.View, android.view.View)} or
* if {@code child} has set another view as it's anchor.</p>
*
* <p>Note that if a Behavior changes the layout of a child via this method, it should
* also be able to reconstruct the correct position in
* {@link #onLayoutChild(CoordinatorLayout, android.view.View, int) onLayoutChild}.
* <code>onDependentViewChanged</code> will not be called during normal layout since
* the layout of each child view will always happen in dependency order.</p>
*
* <p>If the Behavior changes the child view's size or position, it should return true.
* The default implementation returns false.</p>
*
* @param parent the parent view of the given child
* @param child the child view to manipulate
* @param dependency the dependent view that changed
* @return true if the Behavior changed the child view's size or position, false otherwise
*/
public boolean onDependentViewChanged(CoordinatorLayout parent, V child, View dependency) {
return false;
}
/**
* Respond to a child's dependent view being removed.
*
* <p>This method is called after a dependent view has been removed from the parent.
* A Behavior may use this method to appropriately update the child view in response.</p>
*
* <p>A view's dependency is determined by
* {@link #layoutDependsOn(CoordinatorLayout, android.view.View, android.view.View)} or
* if {@code child} has set another view as it's anchor.</p>
*
* @param parent the parent view of the given child
* @param child the child view to manipulate
* @param dependency the dependent view that has been removed
*/
public void onDependentViewRemoved(CoordinatorLayout parent, V child, View dependency) {
}
/**
* Determine whether the given child view should be considered dirty.
*
* <p>If a property determined by the Behavior such as other dependent views would change,
* the Behavior should report a child view as dirty. This will prompt the CoordinatorLayout
* to re-query Behavior-determined properties as appropriate.</p>
*
* @param parent the parent view of the given child
* @param child the child view to check
* @return true if child is dirty
*/
public boolean isDirty(CoordinatorLayout parent, V child) {
return false;
}
/**
* Called when the parent CoordinatorLayout is about to measure the given child view.
*
* <p>This method can be used to perform custom or modified measurement of a child view
* in place of the default child measurement behavior. The Behavior's implementation
* can delegate to the standard CoordinatorLayout measurement behavior by calling
* {@link CoordinatorLayout#onMeasureChild(android.view.View, int, int, int, int)
* parent.onMeasureChild}.</p>
*
* @param parent the parent CoordinatorLayout
* @param child the child to measure
* @param parentWidthMeasureSpec the width requirements for this view
* @param widthUsed extra space that has been used up by the parent
* horizontally (possibly by other children of the parent)
* @param parentHeightMeasureSpec the height requirements for this view
* @param heightUsed extra space that has been used up by the parent
* vertically (possibly by other children of the parent)
* @return true if the Behavior measured the child view, false if the CoordinatorLayout
* should perform its default measurement
*/
public boolean onMeasureChild(CoordinatorLayout parent, V child,
int parentWidthMeasureSpec, int widthUsed,
int parentHeightMeasureSpec, int heightUsed) {
return false;
}
/**
* Called when the parent CoordinatorLayout is about the lay out the given child view.
*
* <p>This method can be used to perform custom or modified layout of a child view
* in place of the default child layout behavior. The Behavior's implementation can
* delegate to the standard CoordinatorLayout measurement behavior by calling
* {@link CoordinatorLayout#onLayoutChild(android.view.View, int)
* parent.onMeasureChild}.</p>
*
* <p>If a Behavior implements
* {@link #onDependentViewChanged(CoordinatorLayout, android.view.View, android.view.View)}
* to change the position of a view in response to a dependent view changing, it
* should also implement <code>onLayoutChild</code> in such a way that respects those
* dependent views. <code>onLayoutChild</code> will always be called for a dependent view
* <em>after</em> its dependency has been laid out.</p>
*
* @param parent the parent CoordinatorLayout
* @param child child view to lay out
* @param layoutDirection the resolved layout direction for the CoordinatorLayout, such as
* {@link ViewCompat#LAYOUT_DIRECTION_LTR} or
* {@link ViewCompat#LAYOUT_DIRECTION_RTL}.
* @return true if the Behavior performed layout of the child view, false to request
* default layout behavior
*/
public boolean onLayoutChild(CoordinatorLayout parent, V child, int layoutDirection) {
return false;
}
// Utility methods for accessing child-specific, behavior-modifiable properties.
/**
* Associate a Behavior-specific tag object with the given child view.
* This object will be stored with the child view's LayoutParams.
*
* @param child child view to set tag with
* @param tag tag object to set
*/
public static void setTag(View child, Object tag) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
lp.mBehaviorTag = tag;
}
/**
* Get the behavior-specific tag object with the given child view.
* This object is stored with the child view's LayoutParams.
*
* @param child child view to get tag with
* @return the previously stored tag object
*/
public static Object getTag(View child) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
return lp.mBehaviorTag;
}
/**
* Called when a descendant of the CoordinatorLayout attempts to initiate a nested scroll.
*
* <p>Any Behavior associated with any direct child of the CoordinatorLayout may respond
* to this event and return true to indicate that the CoordinatorLayout should act as
* a nested scrolling parent for this scroll. Only Behaviors that return true from
* this method will receive subsequent nested scroll events.</p>
*
* @param coordinatorLayout the CoordinatorLayout parent of the view this Behavior is
* associated with
* @param child the child view of the CoordinatorLayout this Behavior is associated with
* @param directTargetChild the child view of the CoordinatorLayout that either is or
* contains the target of the nested scroll operation
* @param target the descendant view of the CoordinatorLayout initiating the nested scroll
* @param nestedScrollAxes the axes that this nested scroll applies to. See
* {@link ViewCompat#SCROLL_AXIS_HORIZONTAL},
* {@link ViewCompat#SCROLL_AXIS_VERTICAL}
* @return true if the Behavior wishes to accept this nested scroll
*
* @see NestedScrollingParent#onStartNestedScroll(View, View, int)
*/
public boolean onStartNestedScroll(CoordinatorLayout coordinatorLayout,
V child, View directTargetChild, View target, int nestedScrollAxes) {
return false;
}
/**
* Called when a nested scroll has been accepted by the CoordinatorLayout.
*
* <p>Any Behavior associated with any direct child of the CoordinatorLayout may elect
* to accept the nested scroll as part of {@link #onStartNestedScroll}. Each Behavior
* that returned true will receive subsequent nested scroll events for that nested scroll.
* </p>
*
* @param coordinatorLayout the CoordinatorLayout parent of the view this Behavior is
* associated with
* @param child the child view of the CoordinatorLayout this Behavior is associated with
* @param directTargetChild the child view of the CoordinatorLayout that either is or
* contains the target of the nested scroll operation
* @param target the descendant view of the CoordinatorLayout initiating the nested scroll
* @param nestedScrollAxes the axes that this nested scroll applies to. See
* {@link ViewCompat#SCROLL_AXIS_HORIZONTAL},
* {@link ViewCompat#SCROLL_AXIS_VERTICAL}
*
* @see NestedScrollingParent#onNestedScrollAccepted(View, View, int)
*/
public void onNestedScrollAccepted(CoordinatorLayout coordinatorLayout, V child,
View directTargetChild, View target, int nestedScrollAxes) {
// Do nothing
}
/**
* Called when a nested scroll has ended.
*
* <p>Any Behavior associated with any direct child of the CoordinatorLayout may elect
* to accept the nested scroll as part of {@link #onStartNestedScroll}. Each Behavior
* that returned true will receive subsequent nested scroll events for that nested scroll.
* </p>
*
* <p><code>onStopNestedScroll</code> marks the end of a single nested scroll event
* sequence. This is a good place to clean up any state related to the nested scroll.
* </p>
*
* @param coordinatorLayout the CoordinatorLayout parent of the view this Behavior is
* associated with
* @param child the child view of the CoordinatorLayout this Behavior is associated with
* @param target the descendant view of the CoordinatorLayout that initiated
* the nested scroll
*
* @see NestedScrollingParent#onStopNestedScroll(View)
*/
public void onStopNestedScroll(CoordinatorLayout coordinatorLayout, V child, View target) {
// Do nothing
}
/**
* Called when a nested scroll in progress has updated and the target has scrolled or
* attempted to scroll.
*
* <p>Any Behavior associated with the direct child of the CoordinatorLayout may elect
* to accept the nested scroll as part of {@link #onStartNestedScroll}. Each Behavior
* that returned true will receive subsequent nested scroll events for that nested scroll.
* </p>
*
* <p><code>onNestedScroll</code> is called each time the nested scroll is updated by the
* nested scrolling child, with both consumed and unconsumed components of the scroll
* supplied in pixels. <em>Each Behavior responding to the nested scroll will receive the
* same values.</em>
* </p>
*
* @param coordinatorLayout the CoordinatorLayout parent of the view this Behavior is
* associated with
* @param child the child view of the CoordinatorLayout this Behavior is associated with
* @param target the descendant view of the CoordinatorLayout performing the nested scroll
* @param dxConsumed horizontal pixels consumed by the target's own scrolling operation
* @param dyConsumed vertical pixels consumed by the target's own scrolling operation
* @param dxUnconsumed horizontal pixels not consumed by the target's own scrolling
* operation, but requested by the user
* @param dyUnconsumed vertical pixels not consumed by the target's own scrolling operation,
* but requested by the user
*
* @see NestedScrollingParent#onNestedScroll(View, int, int, int, int)
*/
public void onNestedScroll(CoordinatorLayout coordinatorLayout, V child, View target,
int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed) {
// Do nothing
}
/**
* Called when a nested scroll in progress is about to update, before the target has
* consumed any of the scrolled distance.
*
* <p>Any Behavior associated with the direct child of the CoordinatorLayout may elect
* to accept the nested scroll as part of {@link #onStartNestedScroll}. Each Behavior
* that returned true will receive subsequent nested scroll events for that nested scroll.
* </p>
*
* <p><code>onNestedPreScroll</code> is called each time the nested scroll is updated
* by the nested scrolling child, before the nested scrolling child has consumed the scroll
* distance itself. <em>Each Behavior responding to the nested scroll will receive the
* same values.</em> The CoordinatorLayout will report as consumed the maximum number
* of pixels in either direction that any Behavior responding to the nested scroll reported
* as consumed.</p>
*
* @param coordinatorLayout the CoordinatorLayout parent of the view this Behavior is
* associated with
* @param child the child view of the CoordinatorLayout this Behavior is associated with
* @param target the descendant view of the CoordinatorLayout performing the nested scroll
* @param dx the raw horizontal number of pixels that the user attempted to scroll
* @param dy the raw vertical number of pixels that the user attempted to scroll
* @param consumed out parameter. consumed[0] should be set to the distance of dx that
* was consumed, consumed[1] should be set to the distance of dy that
* was consumed
*
* @see NestedScrollingParent#onNestedPreScroll(View, int, int, int[])
*/
public void onNestedPreScroll(CoordinatorLayout coordinatorLayout, V child, View target,
int dx, int dy, int[] consumed) {
// Do nothing
}
/**
* Called when a nested scrolling child is starting a fling or an action that would
* be a fling.
*
* <p>Any Behavior associated with the direct child of the CoordinatorLayout may elect
* to accept the nested scroll as part of {@link #onStartNestedScroll}. Each Behavior
* that returned true will receive subsequent nested scroll events for that nested scroll.
* </p>
*
* <p><code>onNestedFling</code> is called when the current nested scrolling child view
* detects the proper conditions for a fling. It reports if the child itself consumed
* the fling. If it did not, the child is expected to show some sort of overscroll
* indication. This method should return true if it consumes the fling, so that a child
* that did not itself take an action in response can choose not to show an overfling
* indication.</p>
*
* @param coordinatorLayout the CoordinatorLayout parent of the view this Behavior is
* associated with
* @param child the child view of the CoordinatorLayout this Behavior is associated with
* @param target the descendant view of the CoordinatorLayout performing the nested scroll
* @param velocityX horizontal velocity of the attempted fling
* @param velocityY vertical velocity of the attempted fling
* @param consumed true if the nested child view consumed the fling
* @return true if the Behavior consumed the fling
*
* @see NestedScrollingParent#onNestedFling(View, float, float, boolean)
*/
public boolean onNestedFling(CoordinatorLayout coordinatorLayout, V child, View target,
float velocityX, float velocityY, boolean consumed) {
return false;
}
/**
* Called when a nested scrolling child is about to start a fling.
*
* <p>Any Behavior associated with the direct child of the CoordinatorLayout may elect
* to accept the nested scroll as part of {@link #onStartNestedScroll}. Each Behavior
* that returned true will receive subsequent nested scroll events for that nested scroll.
* </p>
*
* <p><code>onNestedPreFling</code> is called when the current nested scrolling child view
* detects the proper conditions for a fling, but it has not acted on it yet. A
* Behavior can return true to indicate that it consumed the fling. If at least one
* Behavior returns true, the fling should not be acted upon by the child.</p>
*
* @param coordinatorLayout the CoordinatorLayout parent of the view this Behavior is
* associated with
* @param child the child view of the CoordinatorLayout this Behavior is associated with
* @param target the descendant view of the CoordinatorLayout performing the nested scroll
* @param velocityX horizontal velocity of the attempted fling
* @param velocityY vertical velocity of the attempted fling
* @return true if the Behavior consumed the fling
*
* @see NestedScrollingParent#onNestedPreFling(View, float, float)
*/
public boolean onNestedPreFling(CoordinatorLayout coordinatorLayout, V child, View target,
float velocityX, float velocityY) {
return false;
}
/**
* Called when the window insets have changed.
*
* <p>Any Behavior associated with the direct child of the CoordinatorLayout may elect
* to handle the window inset change on behalf of it's associated view.
* </p>
*
* @param coordinatorLayout the CoordinatorLayout parent of the view this Behavior is
* associated with
* @param child the child view of the CoordinatorLayout this Behavior is associated with
* @param insets the new window insets.
*
* @return The insets supplied, minus any insets that were consumed
*/
public WindowInsetsCompat onApplyWindowInsets(CoordinatorLayout coordinatorLayout,
V child, WindowInsetsCompat insets) {
return insets;
}
/**
* Hook allowing a behavior to re-apply a representation of its internal state that had
* previously been generated by {@link #onSaveInstanceState}. This function will never
* be called with a null state.
*
* @param parent the parent CoordinatorLayout
* @param child child view to restore from
* @param state The frozen state that had previously been returned by
* {@link #onSaveInstanceState}.
*
* @see #onSaveInstanceState()
*/
public void onRestoreInstanceState(CoordinatorLayout parent, V child, Parcelable state) {
// no-op
}
/**
* Hook allowing a behavior to generate a representation of its internal state
* that can later be used to create a new instance with that same state.
* This state should only contain information that is not persistent or can
* not be reconstructed later.
*
* <p>Behavior state is only saved when both the parent {@link CoordinatorLayout} and
* a view using this behavior have valid IDs set.</p>
*
* @param parent the parent CoordinatorLayout
* @param child child view to restore from
*
* @return Returns a Parcelable object containing the behavior's current dynamic
* state.
*
* @see #onRestoreInstanceState(android.os.Parcelable)
* @see View#onSaveInstanceState()
*/
public Parcelable onSaveInstanceState(CoordinatorLayout parent, V child) {
return BaseSavedState.EMPTY_STATE;
}
}
/**
* Parameters describing the desired layout for a child of a {@link CoordinatorLayout}.
*/
public static class LayoutParams extends ViewGroup.MarginLayoutParams {
/**
* A {@link Behavior} that the child view should obey.
*/
Behavior mBehavior;
boolean mBehaviorResolved = false;
/**
* A {@link Gravity} value describing how this child view should lay out.
* If an {@link #setAnchorId(int) anchor} is also specified, the gravity describes
* how this child view should be positioned relative to its anchored position.
*/
public int gravity = Gravity.NO_GRAVITY;
/**
* A {@link Gravity} value describing which edge of a child view's
* {@link #getAnchorId() anchor} view the child should position itself relative to.
*/
public int anchorGravity = Gravity.NO_GRAVITY;
/**
* The index of the horizontal keyline specified to the parent CoordinatorLayout that this
* child should align relative to. If an {@link #setAnchorId(int) anchor} is present the
* keyline will be ignored.
*/
public int keyline = -1;
/**
* A {@link View#getId() view id} of a descendant view of the CoordinatorLayout that
* this child should position relative to.
*/
int mAnchorId = View.NO_ID;
View mAnchorView;
View mAnchorDirectChild;
private boolean mDidBlockInteraction;
private boolean mDidAcceptNestedScroll;
private boolean mDidChangeAfterNestedScroll;
final Rect mLastChildRect = new Rect();
Object mBehaviorTag;
public LayoutParams(int width, int height) {
super(width, height);
}
LayoutParams(Context context, AttributeSet attrs) {
super(context, attrs);
final TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.CoordinatorLayout_LayoutParams);
this.gravity = a.getInteger(
R.styleable.CoordinatorLayout_LayoutParams_android_layout_gravity,
Gravity.NO_GRAVITY);
mAnchorId = a.getResourceId(R.styleable.CoordinatorLayout_LayoutParams_layout_anchor,
View.NO_ID);
this.anchorGravity = a.getInteger(
R.styleable.CoordinatorLayout_LayoutParams_layout_anchorGravity,
Gravity.NO_GRAVITY);
this.keyline = a.getInteger(R.styleable.CoordinatorLayout_LayoutParams_layout_keyline,
-1);
mBehaviorResolved = a.hasValue(
R.styleable.CoordinatorLayout_LayoutParams_layout_behavior);
if (mBehaviorResolved) {
mBehavior = parseBehavior(context, attrs, a.getString(
R.styleable.CoordinatorLayout_LayoutParams_layout_behavior));
}
a.recycle();
}
public LayoutParams(LayoutParams p) {
super(p);
}
public LayoutParams(MarginLayoutParams p) {
super(p);
}
public LayoutParams(ViewGroup.LayoutParams p) {
super(p);
}
/**
* Get the id of this view's anchor.
*
* <p>The view with this id must be a descendant of the CoordinatorLayout containing
* the child view this LayoutParams belongs to. It may not be the child view with
* this LayoutParams or a descendant of it.</p>
*
* @return A {@link View#getId() view id} or {@link View#NO_ID} if there is no anchor
*/
public int getAnchorId() {
return mAnchorId;
}
/**
* Get the id of this view's anchor.
*
* <p>The view with this id must be a descendant of the CoordinatorLayout containing
* the child view this LayoutParams belongs to. It may not be the child view with
* this LayoutParams or a descendant of it.</p>
*
* @param id The {@link View#getId() view id} of the anchor or
* {@link View#NO_ID} if there is no anchor
*/
public void setAnchorId(int id) {
invalidateAnchor();
mAnchorId = id;
}
/**
* Get the behavior governing the layout and interaction of the child view within
* a parent CoordinatorLayout.
*
* @return The current behavior or null if no behavior is specified
*/
public Behavior getBehavior() {
return mBehavior;
}
/**
* Set the behavior governing the layout and interaction of the child view within
* a parent CoordinatorLayout.
*
* <p>Setting a new behavior will remove any currently associated
* {@link Behavior#setTag(android.view.View, Object) Behavior tag}.</p>
*
* @param behavior The behavior to set or null for no special behavior
*/
public void setBehavior(Behavior behavior) {
if (mBehavior != behavior) {
mBehavior = behavior;
mBehaviorTag = null;
mBehaviorResolved = true;
}
}
/**
* Set the last known position rect for this child view
* @param r the rect to set
*/
void setLastChildRect(Rect r) {
mLastChildRect.set(r);
}
/**
* Get the last known position rect for this child view.
* Note: do not mutate the result of this call.
*/
Rect getLastChildRect() {
return mLastChildRect;
}
/**
* Returns true if the anchor id changed to another valid view id since the anchor view
* was resolved.
*/
boolean checkAnchorChanged() {
return mAnchorView == null && mAnchorId != View.NO_ID;
}
/**
* Returns true if the associated Behavior previously blocked interaction with other views
* below the associated child since the touch behavior tracking was last
* {@link #resetTouchBehaviorTracking() reset}.
*
* @see #isBlockingInteractionBelow(CoordinatorLayout, android.view.View)
*/
boolean didBlockInteraction() {
if (mBehavior == null) {
mDidBlockInteraction = false;
}
return mDidBlockInteraction;
}
/**
* Check if the associated Behavior wants to block interaction below the given child
* view. The given child view should be the child this LayoutParams is associated with.
*
* <p>Once interaction is blocked, it will remain blocked until touch interaction tracking
* is {@link #resetTouchBehaviorTracking() reset}.</p>
*
* @param parent the parent CoordinatorLayout
* @param child the child view this LayoutParams is associated with
* @return true to block interaction below the given child
*/
boolean isBlockingInteractionBelow(CoordinatorLayout parent, View child) {
if (mDidBlockInteraction) {
return true;
}
return mDidBlockInteraction |= mBehavior != null
? mBehavior.blocksInteractionBelow(parent, child)
: false;
}
/**
* Reset tracking of Behavior-specific touch interactions. This includes
* interaction blocking.
*
* @see #isBlockingInteractionBelow(CoordinatorLayout, android.view.View)
* @see #didBlockInteraction()
*/
void resetTouchBehaviorTracking() {
mDidBlockInteraction = false;
}
void resetNestedScroll() {
mDidAcceptNestedScroll = false;
}
void acceptNestedScroll(boolean accept) {
mDidAcceptNestedScroll = accept;
}
boolean isNestedScrollAccepted() {
return mDidAcceptNestedScroll;
}
boolean getChangedAfterNestedScroll() {
return mDidChangeAfterNestedScroll;
}
void setChangedAfterNestedScroll(boolean changed) {
mDidChangeAfterNestedScroll = changed;
}
void resetChangedAfterNestedScroll() {
mDidChangeAfterNestedScroll = false;
}
/**
* Check if an associated child view depends on another child view of the CoordinatorLayout.
*
* @param parent the parent CoordinatorLayout
* @param child the child to check
* @param dependency the proposed dependency to check
* @return true if child depends on dependency
*/
boolean dependsOn(CoordinatorLayout parent, View child, View dependency) {
return dependency == mAnchorDirectChild
|| (mBehavior != null && mBehavior.layoutDependsOn(parent, child, dependency));
}
/**
* Invalidate the cached anchor view and direct child ancestor of that anchor.
* The anchor will need to be
* {@link #findAnchorView(CoordinatorLayout, android.view.View) found} before
* being used again.
*/
void invalidateAnchor() {
mAnchorView = mAnchorDirectChild = null;
}
/**
* Locate the appropriate anchor view by the current {@link #setAnchorId(int) anchor id}
* or return the cached anchor view if already known.
*
* @param parent the parent CoordinatorLayout
* @param forChild the child this LayoutParams is associated with
* @return the located descendant anchor view, or null if the anchor id is
* {@link View#NO_ID}.
*/
View findAnchorView(CoordinatorLayout parent, View forChild) {
if (mAnchorId == View.NO_ID) {
mAnchorView = mAnchorDirectChild = null;
return null;
}
if (mAnchorView == null || !verifyAnchorView(forChild, parent)) {
resolveAnchorView(forChild, parent);
}
return mAnchorView;
}
/**
* Check if the child associated with this LayoutParams is currently considered
* "dirty" and needs to be updated. A Behavior should consider a child dirty
* whenever a property returned by another Behavior method would have changed,
* such as dependencies.
*
* @param parent the parent CoordinatorLayout
* @param child the child view associated with this LayoutParams
* @return true if this child view should be considered dirty
*/
boolean isDirty(CoordinatorLayout parent, View child) {
return mBehavior != null && mBehavior.isDirty(parent, child);
}
/**
* Determine the anchor view for the child view this LayoutParams is assigned to.
* Assumes mAnchorId is valid.
*/
private void resolveAnchorView(View forChild, CoordinatorLayout parent) {
mAnchorView = parent.findViewById(mAnchorId);
if (mAnchorView != null) {
View directChild = mAnchorView;
for (ViewParent p = mAnchorView.getParent();
p != parent && p != null;
p = p.getParent()) {
if (p == forChild) {
if (parent.isInEditMode()) {
mAnchorView = mAnchorDirectChild = null;
return;
}
throw new IllegalStateException(
"Anchor must not be a descendant of the anchored view");
}
if (p instanceof View) {
directChild = (View) p;
}
}
mAnchorDirectChild = directChild;
} else {
if (parent.isInEditMode()) {
mAnchorView = mAnchorDirectChild = null;
return;
}
throw new IllegalStateException("Could not find CoordinatorLayout descendant view"
+ " with id " + parent.getResources().getResourceName(mAnchorId)
+ " to anchor view " + forChild);
}
}
/**
* Verify that the previously resolved anchor view is still valid - that it is still
* a descendant of the expected parent view, it is not the child this LayoutParams
* is assigned to or a descendant of it, and it has the expected id.
*/
private boolean verifyAnchorView(View forChild, CoordinatorLayout parent) {
if (mAnchorView.getId() != mAnchorId) {
return false;
}
View directChild = mAnchorView;
for (ViewParent p = mAnchorView.getParent();
p != parent;
p = p.getParent()) {
if (p == null || p == forChild) {
mAnchorView = mAnchorDirectChild = null;
return false;
}
if (p instanceof View) {
directChild = (View) p;
}
}
mAnchorDirectChild = directChild;
return true;
}
}
final class ApplyInsetsListener implements android.support.v4.view.OnApplyWindowInsetsListener {
@Override
public WindowInsetsCompat onApplyWindowInsets(View v, WindowInsetsCompat insets) {
setWindowInsets(insets);
return insets.consumeSystemWindowInsets();
}
}
final class HierarchyChangeListener implements OnHierarchyChangeListener {
@Override
public void onChildViewAdded(View parent, View child) {
if (mOnHierarchyChangeListener != null) {
mOnHierarchyChangeListener.onChildViewAdded(parent, child);
}
}
@Override
public void onChildViewRemoved(View parent, View child) {
dispatchDependentViewRemoved(child);
if (mOnHierarchyChangeListener != null) {
mOnHierarchyChangeListener.onChildViewRemoved(parent, child);
}
}
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
final SavedState ss = (SavedState) state;
super.onRestoreInstanceState(ss.getSuperState());
final SparseArray<Parcelable> behaviorStates = ss.behaviorStates;
for (int i = 0, count = getChildCount(); i < count; i++) {
final View child = getChildAt(i);
final int childId = child.getId();
final LayoutParams lp = getResolvedLayoutParams(child);
final Behavior b = lp.getBehavior();
if (childId != NO_ID && b != null) {
Parcelable savedState = behaviorStates.get(childId);
if (savedState != null) {
b.onRestoreInstanceState(this, child, savedState);
}
}
}
}
@Override
protected Parcelable onSaveInstanceState() {
final SavedState ss = new SavedState(super.onSaveInstanceState());
final SparseArray<Parcelable> behaviorStates = new SparseArray<>();
for (int i = 0, count = getChildCount(); i < count; i++) {
final View child = getChildAt(i);
final int childId = child.getId();
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final Behavior b = lp.getBehavior();
if (childId != NO_ID && b != null) {
// If the child has an ID and a Behavior, let it save some state...
Parcelable state = b.onSaveInstanceState(this, child);
if (state != null) {
behaviorStates.append(childId, state);
}
}
}
ss.behaviorStates = behaviorStates;
return ss;
}
protected static class SavedState extends BaseSavedState {
SparseArray<Parcelable> behaviorStates;
public SavedState(Parcel source) {
super(source);
final int size = source.readInt();
final int[] ids = new int[size];
source.readIntArray(ids);
final Parcelable[] states = source.readParcelableArray(
CoordinatorLayout.class.getClassLoader());
behaviorStates = new SparseArray<>(size);
for (int i = 0; i < size; i++) {
behaviorStates.append(ids[i], states[i]);
}
}
public SavedState(Parcelable superState) {
super(superState);
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
final int size = behaviorStates != null ? behaviorStates.size() : 0;
dest.writeInt(size);
final int[] ids = new int[size];
final Parcelable[] states = new Parcelable[size];
for (int i = 0; i < size; i++) {
ids[i] = behaviorStates.keyAt(i);
states[i] = behaviorStates.valueAt(i);
}
dest.writeIntArray(ids);
dest.writeParcelableArray(states, flags);
}
public static final Parcelable.Creator<SavedState> CREATOR =
new Parcelable.Creator<SavedState>() {
@Override
public SavedState createFromParcel(Parcel source) {
return new SavedState(source);
}
@Override
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
}
| design/src/android/support/design/widget/CoordinatorLayout.java | /*
* 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 android.support.design.widget;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.SystemClock;
import android.support.design.R;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.view.NestedScrollingParent;
import android.support.v4.view.NestedScrollingParentHelper;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.WindowInsetsCompat;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.util.SparseArray;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.ViewTreeObserver;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* CoordinatorLayout is a super-powered {@link android.widget.FrameLayout FrameLayout}.
*
* <p>CoordinatorLayout is intended for two primary use cases:</p>
* <ol>
* <li>As a top-level application decor or chrome layout</li>
* <li>As a container for a specific interaction with one or more child views</li>
* </ol>
*
* <p>By specifying {@link CoordinatorLayout.Behavior Behaviors} for child views of a
* CoordinatorLayout you can provide many different interactions within a single parent and those
* views can also interact with one another. View classes can specify a default behavior when
* used as a child of a CoordinatorLayout using the
* {@link CoordinatorLayout.DefaultBehavior DefaultBehavior} annotation.</p>
*
* <p>Behaviors may be used to implement a variety of interactions and additional layout
* modifications ranging from sliding drawers and panels to swipe-dismissable elements and buttons
* that stick to other elements as they move and animate.</p>
*
* <p>Children of a CoordinatorLayout may have an
* {@link CoordinatorLayout.LayoutParams#setAnchorId(int) anchor}. This view id must correspond
* to an arbitrary descendant of the CoordinatorLayout, but it may not be the anchored child itself
* or a descendant of the anchored child. This can be used to place floating views relative to
* other arbitrary content panes.</p>
*/
public class CoordinatorLayout extends ViewGroup implements NestedScrollingParent {
static final String TAG = "CoordinatorLayout";
static final String WIDGET_PACKAGE_NAME = CoordinatorLayout.class.getPackage().getName();
private static final int TYPE_ON_INTERCEPT = 0;
private static final int TYPE_ON_TOUCH = 1;
static {
if (Build.VERSION.SDK_INT >= 21) {
TOP_SORTED_CHILDREN_COMPARATOR = new ViewElevationComparator();
INSETS_HELPER = new CoordinatorLayoutInsetsHelperLollipop();
} else {
TOP_SORTED_CHILDREN_COMPARATOR = null;
INSETS_HELPER = null;
}
}
static final Class<?>[] CONSTRUCTOR_PARAMS = new Class<?>[] {
Context.class,
AttributeSet.class
};
static final ThreadLocal<Map<String, Constructor<Behavior>>> sConstructors =
new ThreadLocal<>();
final Comparator<View> mLayoutDependencyComparator = new Comparator<View>() {
@Override
public int compare(View lhs, View rhs) {
if (lhs == rhs) {
return 0;
} else if (((LayoutParams) lhs.getLayoutParams()).dependsOn(
CoordinatorLayout.this, lhs, rhs)) {
return 1;
} else if (((LayoutParams) rhs.getLayoutParams()).dependsOn(
CoordinatorLayout.this, rhs, lhs)) {
return -1;
} else {
return 0;
}
}
};
static final Comparator<View> TOP_SORTED_CHILDREN_COMPARATOR;
static final CoordinatorLayoutInsetsHelper INSETS_HELPER;
private final List<View> mDependencySortedChildren = new ArrayList<View>();
private final List<View> mTempList1 = new ArrayList<>();
private final List<View> mTempDependenciesList = new ArrayList<>();
private final Rect mTempRect1 = new Rect();
private final Rect mTempRect2 = new Rect();
private final Rect mTempRect3 = new Rect();
private final int[] mTempIntPair = new int[2];
private Paint mScrimPaint;
private boolean mIsAttachedToWindow;
private int[] mKeylines;
private View mBehaviorTouchView;
private View mNestedScrollingDirectChild;
private View mNestedScrollingTarget;
private OnPreDrawListener mOnPreDrawListener;
private boolean mNeedsPreDrawListener;
private WindowInsetsCompat mLastInsets;
private boolean mDrawStatusBarBackground;
private Drawable mStatusBarBackground;
private OnHierarchyChangeListener mOnHierarchyChangeListener;
private final NestedScrollingParentHelper mNestedScrollingParentHelper =
new NestedScrollingParentHelper(this);
public CoordinatorLayout(Context context) {
this(context, null);
}
public CoordinatorLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CoordinatorLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CoordinatorLayout,
defStyleAttr, R.style.Widget_Design_CoordinatorLayout);
final int keylineArrayRes = a.getResourceId(R.styleable.CoordinatorLayout_keylines, 0);
if (keylineArrayRes != 0) {
final Resources res = context.getResources();
mKeylines = res.getIntArray(keylineArrayRes);
final float density = res.getDisplayMetrics().density;
final int count = mKeylines.length;
for (int i = 0; i < count; i++) {
mKeylines[i] *= density;
}
}
mStatusBarBackground = a.getDrawable(R.styleable.CoordinatorLayout_statusBarBackground);
a.recycle();
if (INSETS_HELPER != null) {
INSETS_HELPER.setupForWindowInsets(this, new ApplyInsetsListener());
}
super.setOnHierarchyChangeListener(new HierarchyChangeListener());
}
@Override
public void setOnHierarchyChangeListener(OnHierarchyChangeListener onHierarchyChangeListener) {
mOnHierarchyChangeListener = onHierarchyChangeListener;
}
@Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
resetTouchBehaviors();
if (mNeedsPreDrawListener) {
if (mOnPreDrawListener == null) {
mOnPreDrawListener = new OnPreDrawListener();
}
final ViewTreeObserver vto = getViewTreeObserver();
vto.addOnPreDrawListener(mOnPreDrawListener);
}
if (mLastInsets == null && ViewCompat.getFitsSystemWindows(this)) {
// We're set to fitSystemWindows but we haven't had any insets yet...
// We should request a new dispatch of window insets
ViewCompat.requestApplyInsets(this);
}
mIsAttachedToWindow = true;
}
@Override
public void onDetachedFromWindow() {
super.onDetachedFromWindow();
resetTouchBehaviors();
if (mNeedsPreDrawListener && mOnPreDrawListener != null) {
final ViewTreeObserver vto = getViewTreeObserver();
vto.removeOnPreDrawListener(mOnPreDrawListener);
}
if (mNestedScrollingTarget != null) {
onStopNestedScroll(mNestedScrollingTarget);
}
mIsAttachedToWindow = false;
}
/**
* Set a drawable to draw in the insets area for the status bar.
* Note that this will only be activated if this DrawerLayout fitsSystemWindows.
*
* @param bg Background drawable to draw behind the status bar
*/
public void setStatusBarBackground(Drawable bg) {
mStatusBarBackground = bg;
invalidate();
}
/**
* Gets the drawable used to draw in the insets area for the status bar.
*
* @return The status bar background drawable, or null if none set
*/
public Drawable getStatusBarBackground() {
return mStatusBarBackground;
}
/**
* Set a drawable to draw in the insets area for the status bar.
* Note that this will only be activated if this DrawerLayout fitsSystemWindows.
*
* @param resId Resource id of a background drawable to draw behind the status bar
*/
public void setStatusBarBackgroundResource(int resId) {
setStatusBarBackground(resId != 0 ? ContextCompat.getDrawable(getContext(), resId) : null);
}
/**
* Set a drawable to draw in the insets area for the status bar.
* Note that this will only be activated if this DrawerLayout fitsSystemWindows.
*
* @param color Color to use as a background drawable to draw behind the status bar
* in 0xAARRGGBB format.
*/
public void setStatusBarBackgroundColor(int color) {
setStatusBarBackground(new ColorDrawable(color));
}
private void setWindowInsets(WindowInsetsCompat insets) {
if (mLastInsets != insets) {
mLastInsets = insets;
mDrawStatusBarBackground = insets != null && insets.getSystemWindowInsetTop() > 0;
setWillNotDraw(!mDrawStatusBarBackground && getBackground() == null);
dispatchChildApplyWindowInsets(insets);
requestLayout();
}
}
/**
* Reset all Behavior-related tracking records either to clean up or in preparation
* for a new event stream. This should be called when attached or detached from a window,
* in response to an UP or CANCEL event, when intercept is request-disallowed
* and similar cases where an event stream in progress will be aborted.
*/
private void resetTouchBehaviors() {
if (mBehaviorTouchView != null) {
final Behavior b = ((LayoutParams) mBehaviorTouchView.getLayoutParams()).getBehavior();
if (b != null) {
final long now = SystemClock.uptimeMillis();
final MotionEvent cancelEvent = MotionEvent.obtain(now, now,
MotionEvent.ACTION_CANCEL, 0.0f, 0.0f, 0);
b.onTouchEvent(this, mBehaviorTouchView, cancelEvent);
cancelEvent.recycle();
}
mBehaviorTouchView = null;
}
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
lp.resetTouchBehaviorTracking();
}
}
/**
* Populate a list with the current child views, sorted such that the topmost views
* in z-order are at the front of the list. Useful for hit testing and event dispatch.
*/
private void getTopSortedChildren(List<View> out) {
out.clear();
final boolean useCustomOrder = isChildrenDrawingOrderEnabled();
final int childCount = getChildCount();
for (int i = childCount - 1; i >= 0; i--) {
final int childIndex = useCustomOrder ? getChildDrawingOrder(childCount, i) : i;
final View child = getChildAt(childIndex);
out.add(child);
}
if (TOP_SORTED_CHILDREN_COMPARATOR != null) {
Collections.sort(out, TOP_SORTED_CHILDREN_COMPARATOR);
}
}
private boolean performIntercept(MotionEvent ev, final int type) {
boolean intercepted = false;
boolean newBlock = false;
MotionEvent cancelEvent = null;
final int action = MotionEventCompat.getActionMasked(ev);
final List<View> topmostChildList = mTempList1;
getTopSortedChildren(topmostChildList);
// Let topmost child views inspect first
final int childCount = topmostChildList.size();
for (int i = 0; i < childCount; i++) {
final View child = topmostChildList.get(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final Behavior b = lp.getBehavior();
if ((intercepted || newBlock) && action != MotionEvent.ACTION_DOWN) {
// Cancel all behaviors beneath the one that intercepted.
// If the event is "down" then we don't have anything to cancel yet.
if (b != null) {
if (cancelEvent == null) {
final long now = SystemClock.uptimeMillis();
cancelEvent = MotionEvent.obtain(now, now,
MotionEvent.ACTION_CANCEL, 0.0f, 0.0f, 0);
}
switch (type) {
case TYPE_ON_INTERCEPT:
b.onInterceptTouchEvent(this, child, cancelEvent);
break;
case TYPE_ON_TOUCH:
b.onTouchEvent(this, child, cancelEvent);
break;
}
}
continue;
}
if (!intercepted && b != null) {
switch (type) {
case TYPE_ON_INTERCEPT:
intercepted = b.onInterceptTouchEvent(this, child, ev);
break;
case TYPE_ON_TOUCH:
intercepted = b.onTouchEvent(this, child, ev);
break;
}
if (intercepted) {
mBehaviorTouchView = child;
}
}
// Don't keep going if we're not allowing interaction below this.
// Setting newBlock will make sure we cancel the rest of the behaviors.
final boolean wasBlocking = lp.didBlockInteraction();
final boolean isBlocking = lp.isBlockingInteractionBelow(this, child);
newBlock = isBlocking && !wasBlocking;
if (isBlocking && !newBlock) {
// Stop here since we don't have anything more to cancel - we already did
// when the behavior first started blocking things below this point.
break;
}
}
topmostChildList.clear();
return intercepted;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
MotionEvent cancelEvent = null;
final int action = MotionEventCompat.getActionMasked(ev);
// Make sure we reset in case we had missed a previous important event.
if (action == MotionEvent.ACTION_DOWN) {
resetTouchBehaviors();
}
final boolean intercepted = performIntercept(ev, TYPE_ON_INTERCEPT);
if (cancelEvent != null) {
cancelEvent.recycle();
}
if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
resetTouchBehaviors();
}
return intercepted;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
boolean handled = false;
boolean cancelSuper = false;
MotionEvent cancelEvent = null;
final int action = MotionEventCompat.getActionMasked(ev);
if (mBehaviorTouchView != null || (cancelSuper = performIntercept(ev, TYPE_ON_TOUCH))) {
// Safe since performIntercept guarantees that
// mBehaviorTouchView != null if it returns true
final LayoutParams lp = (LayoutParams) mBehaviorTouchView.getLayoutParams();
final Behavior b = lp.getBehavior();
if (b != null) {
handled = b.onTouchEvent(this, mBehaviorTouchView, ev);
}
}
// Keep the super implementation correct
if (mBehaviorTouchView == null) {
handled |= super.onTouchEvent(ev);
} else if (cancelSuper) {
if (cancelEvent != null) {
final long now = SystemClock.uptimeMillis();
cancelEvent = MotionEvent.obtain(now, now,
MotionEvent.ACTION_CANCEL, 0.0f, 0.0f, 0);
}
super.onTouchEvent(cancelEvent);
}
if (!handled && action == MotionEvent.ACTION_DOWN) {
}
if (cancelEvent != null) {
cancelEvent.recycle();
}
if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
resetTouchBehaviors();
}
return handled;
}
@Override
public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
super.requestDisallowInterceptTouchEvent(disallowIntercept);
if (disallowIntercept) {
resetTouchBehaviors();
}
}
private int getKeyline(int index) {
if (mKeylines == null) {
Log.e(TAG, "No keylines defined for " + this + " - attempted index lookup " + index);
return 0;
}
if (index < 0 || index >= mKeylines.length) {
Log.e(TAG, "Keyline index " + index + " out of range for " + this);
return 0;
}
return mKeylines[index];
}
static Behavior parseBehavior(Context context, AttributeSet attrs, String name) {
if (TextUtils.isEmpty(name)) {
return null;
}
final String fullName;
if (name.startsWith(".")) {
// Relative to the app package. Prepend the app package name.
fullName = context.getPackageName() + name;
} else if (name.indexOf('.') >= 0) {
// Fully qualified package name.
fullName = name;
} else {
// Assume stock behavior in this package.
fullName = WIDGET_PACKAGE_NAME + '.' + name;
}
try {
Map<String, Constructor<Behavior>> constructors = sConstructors.get();
if (constructors == null) {
constructors = new HashMap<>();
sConstructors.set(constructors);
}
Constructor<Behavior> c = constructors.get(fullName);
if (c == null) {
final Class<Behavior> clazz = (Class<Behavior>) Class.forName(fullName, true,
context.getClassLoader());
c = clazz.getConstructor(CONSTRUCTOR_PARAMS);
c.setAccessible(true);
constructors.put(fullName, c);
}
return c.newInstance(context, attrs);
} catch (Exception e) {
throw new RuntimeException("Could not inflate Behavior subclass " + fullName, e);
}
}
LayoutParams getResolvedLayoutParams(View child) {
final LayoutParams result = (LayoutParams) child.getLayoutParams();
if (!result.mBehaviorResolved) {
Class<?> childClass = child.getClass();
DefaultBehavior defaultBehavior = null;
while (childClass != null &&
(defaultBehavior = childClass.getAnnotation(DefaultBehavior.class)) == null) {
childClass = childClass.getSuperclass();
}
if (defaultBehavior != null) {
try {
result.setBehavior(defaultBehavior.value().newInstance());
} catch (Exception e) {
Log.e(TAG, "Default behavior class " + defaultBehavior.value().getName() +
" could not be instantiated. Did you forget a default constructor?", e);
}
}
result.mBehaviorResolved = true;
}
return result;
}
private void prepareChildren() {
final int childCount = getChildCount();
boolean resortRequired = mDependencySortedChildren.size() != childCount;
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
final LayoutParams lp = getResolvedLayoutParams(child);
if (!resortRequired && lp.isDirty(this, child)) {
resortRequired = true;
}
lp.findAnchorView(this, child);
}
if (resortRequired) {
mDependencySortedChildren.clear();
for (int i = 0; i < childCount; i++) {
mDependencySortedChildren.add(getChildAt(i));
}
Collections.sort(mDependencySortedChildren, mLayoutDependencyComparator);
}
}
/**
* Retrieve the transformed bounding rect of an arbitrary descendant view.
* This does not need to be a direct child.
*
* @param descendant descendant view to reference
* @param out rect to set to the bounds of the descendant view
*/
void getDescendantRect(View descendant, Rect out) {
ViewGroupUtils.getDescendantRect(this, descendant, out);
}
@Override
protected int getSuggestedMinimumWidth() {
return Math.max(super.getSuggestedMinimumWidth(), getPaddingLeft() + getPaddingRight());
}
@Override
protected int getSuggestedMinimumHeight() {
return Math.max(super.getSuggestedMinimumHeight(), getPaddingTop() + getPaddingBottom());
}
/**
* Called to measure each individual child view unless a
* {@link CoordinatorLayout.Behavior Behavior} is present. The Behavior may choose to delegate
* child measurement to this method.
*
* @param child the child to measure
* @param parentWidthMeasureSpec the width requirements for this view
* @param widthUsed extra space that has been used up by the parent
* horizontally (possibly by other children of the parent)
* @param parentHeightMeasureSpec the height requirements for this view
* @param heightUsed extra space that has been used up by the parent
* vertically (possibly by other children of the parent)
*/
public void onMeasureChild(View child, int parentWidthMeasureSpec, int widthUsed,
int parentHeightMeasureSpec, int heightUsed) {
measureChildWithMargins(child, parentWidthMeasureSpec, widthUsed,
parentHeightMeasureSpec, heightUsed);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
prepareChildren();
ensurePreDrawListener();
final int paddingLeft = getPaddingLeft();
final int paddingTop = getPaddingTop();
final int paddingRight = getPaddingRight();
final int paddingBottom = getPaddingBottom();
final int layoutDirection = ViewCompat.getLayoutDirection(this);
final boolean isRtl = layoutDirection == ViewCompat.LAYOUT_DIRECTION_RTL;
final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
final int widthSize = MeasureSpec.getSize(widthMeasureSpec);
final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
final int heightSize = MeasureSpec.getSize(heightMeasureSpec);
final int widthPadding = paddingLeft + paddingRight;
final int heightPadding = paddingTop + paddingBottom;
int widthUsed = getSuggestedMinimumWidth();
int heightUsed = getSuggestedMinimumHeight();
int childState = 0;
final boolean applyInsets = mLastInsets != null && ViewCompat.getFitsSystemWindows(this);
final int childCount = mDependencySortedChildren.size();
for (int i = 0; i < childCount; i++) {
final View child = mDependencySortedChildren.get(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
int keylineWidthUsed = 0;
if (lp.keyline >= 0 && widthMode != MeasureSpec.UNSPECIFIED) {
final int keylinePos = getKeyline(lp.keyline);
final int keylineGravity = GravityCompat.getAbsoluteGravity(
resolveKeylineGravity(lp.gravity), layoutDirection)
& Gravity.HORIZONTAL_GRAVITY_MASK;
if ((keylineGravity == Gravity.LEFT && !isRtl)
|| (keylineGravity == Gravity.RIGHT && isRtl)) {
keylineWidthUsed = Math.max(0, widthSize - paddingRight - keylinePos);
} else if ((keylineGravity == Gravity.RIGHT && !isRtl)
|| (keylineGravity == Gravity.LEFT && isRtl)) {
keylineWidthUsed = Math.max(0, keylinePos - paddingLeft);
}
}
int childWidthMeasureSpec = widthMeasureSpec;
int childHeightMeasureSpec = heightMeasureSpec;
if (applyInsets && !ViewCompat.getFitsSystemWindows(child)) {
// We're set to handle insets but this child isn't, so we will measure the
// child as if there are no insets
final int horizInsets = mLastInsets.getSystemWindowInsetLeft()
+ mLastInsets.getSystemWindowInsetRight();
final int vertInsets = mLastInsets.getSystemWindowInsetTop()
+ mLastInsets.getSystemWindowInsetBottom();
childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(
widthSize - horizInsets, widthMode);
childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
heightSize - vertInsets, heightMode);
}
final Behavior b = lp.getBehavior();
if (b == null || !b.onMeasureChild(this, child, childWidthMeasureSpec, keylineWidthUsed,
childHeightMeasureSpec, 0)) {
onMeasureChild(child, childWidthMeasureSpec, keylineWidthUsed,
childHeightMeasureSpec, 0);
}
widthUsed = Math.max(widthUsed, widthPadding + child.getMeasuredWidth() +
lp.leftMargin + lp.rightMargin);
heightUsed = Math.max(heightUsed, heightPadding + child.getMeasuredHeight() +
lp.topMargin + lp.bottomMargin);
childState = ViewCompat.combineMeasuredStates(childState,
ViewCompat.getMeasuredState(child));
}
final int width = ViewCompat.resolveSizeAndState(widthUsed, widthMeasureSpec,
childState & ViewCompat.MEASURED_STATE_MASK);
final int height = ViewCompat.resolveSizeAndState(heightUsed, heightMeasureSpec,
childState << ViewCompat.MEASURED_HEIGHT_STATE_SHIFT);
setMeasuredDimension(width, height);
}
private void dispatchChildApplyWindowInsets(WindowInsetsCompat insets) {
if (insets.isConsumed()) {
return;
}
for (int i = 0, z = getChildCount(); i < z; i++) {
final View child = getChildAt(i);
if (ViewCompat.getFitsSystemWindows(child)) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final Behavior b = lp.getBehavior();
if (b != null) {
// If the view has a behavior, let it try first
insets = b.onApplyWindowInsets(this, child, insets);
if (insets.isConsumed()) {
// If it consumed the insets, break
break;
}
}
// Now let the view try and consume them
insets = ViewCompat.dispatchApplyWindowInsets(child, insets);
if (insets.isConsumed()) {
break;
}
}
}
}
/**
* Called to lay out each individual child view unless a
* {@link CoordinatorLayout.Behavior Behavior} is present. The Behavior may choose to
* delegate child measurement to this method.
*
* @param child child view to lay out
* @param layoutDirection the resolved layout direction for the CoordinatorLayout, such as
* {@link ViewCompat#LAYOUT_DIRECTION_LTR} or
* {@link ViewCompat#LAYOUT_DIRECTION_RTL}.
*/
public void onLayoutChild(View child, int layoutDirection) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (lp.checkAnchorChanged()) {
throw new IllegalStateException("An anchor may not be changed after CoordinatorLayout"
+ " measurement begins before layout is complete.");
}
if (lp.mAnchorView != null) {
layoutChildWithAnchor(child, lp.mAnchorView, layoutDirection);
} else if (lp.keyline >= 0) {
layoutChildWithKeyline(child, lp.keyline, layoutDirection);
} else {
layoutChild(child, layoutDirection);
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
final int layoutDirection = ViewCompat.getLayoutDirection(this);
final int childCount = mDependencySortedChildren.size();
for (int i = 0; i < childCount; i++) {
final View child = mDependencySortedChildren.get(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final Behavior behavior = lp.getBehavior();
if (behavior == null || !behavior.onLayoutChild(this, child, layoutDirection)) {
onLayoutChild(child, layoutDirection);
}
}
}
@Override
public void onDraw(Canvas c) {
super.onDraw(c);
if (mDrawStatusBarBackground && mStatusBarBackground != null) {
final int inset = mLastInsets != null ? mLastInsets.getSystemWindowInsetTop() : 0;
if (inset > 0) {
mStatusBarBackground.setBounds(0, 0, getWidth(), inset);
mStatusBarBackground.draw(c);
}
}
}
/**
* Mark the last known child position rect for the given child view.
* This will be used when checking if a child view's position has changed between frames.
* The rect used here should be one returned by
* {@link #getChildRect(android.view.View, boolean, android.graphics.Rect)}, with translation
* disabled.
*
* @param child child view to set for
* @param r rect to set
*/
void recordLastChildRect(View child, Rect r) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
lp.setLastChildRect(r);
}
/**
* Get the last known child rect recorded by
* {@link #recordLastChildRect(android.view.View, android.graphics.Rect)}.
*
* @param child child view to retrieve from
* @param out rect to set to the outpur values
*/
void getLastChildRect(View child, Rect out) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
out.set(lp.getLastChildRect());
}
/**
* Get the position rect for the given child. If the child has currently requested layout
* or has a visibility of GONE.
*
* @param child child view to check
* @param transform true to include transformation in the output rect, false to
* only account for the base position
* @param out rect to set to the output values
*/
void getChildRect(View child, boolean transform, Rect out) {
if (child.isLayoutRequested() || child.getVisibility() == View.GONE) {
out.set(0, 0, 0, 0);
return;
}
if (transform) {
getDescendantRect(child, out);
} else {
out.set(child.getLeft(), child.getTop(), child.getRight(), child.getBottom());
}
}
/**
* Calculate the desired child rect relative to an anchor rect, respecting both
* gravity and anchorGravity.
*
* @param child child view to calculate a rect for
* @param layoutDirection the desired layout direction for the CoordinatorLayout
* @param anchorRect rect in CoordinatorLayout coordinates of the anchor view area
* @param out rect to set to the output values
*/
void getDesiredAnchoredChildRect(View child, int layoutDirection, Rect anchorRect, Rect out) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final int absGravity = GravityCompat.getAbsoluteGravity(
resolveAnchoredChildGravity(lp.gravity), layoutDirection);
final int absAnchorGravity = GravityCompat.getAbsoluteGravity(
resolveGravity(lp.anchorGravity),
layoutDirection);
final int hgrav = absGravity & Gravity.HORIZONTAL_GRAVITY_MASK;
final int vgrav = absGravity & Gravity.VERTICAL_GRAVITY_MASK;
final int anchorHgrav = absAnchorGravity & Gravity.HORIZONTAL_GRAVITY_MASK;
final int anchorVgrav = absAnchorGravity & Gravity.VERTICAL_GRAVITY_MASK;
final int childWidth = child.getMeasuredWidth();
final int childHeight = child.getMeasuredHeight();
int left;
int top;
// Align to the anchor. This puts us in an assumed right/bottom child view gravity.
// If this is not the case we will subtract out the appropriate portion of
// the child size below.
switch (anchorHgrav) {
default:
case Gravity.LEFT:
left = anchorRect.left;
break;
case Gravity.RIGHT:
left = anchorRect.right;
break;
case Gravity.CENTER_HORIZONTAL:
left = anchorRect.left + anchorRect.width() / 2;
break;
}
switch (anchorVgrav) {
default:
case Gravity.TOP:
top = anchorRect.top;
break;
case Gravity.BOTTOM:
top = anchorRect.bottom;
break;
case Gravity.CENTER_VERTICAL:
top = anchorRect.top + anchorRect.height() / 2;
break;
}
// Offset by the child view's gravity itself. The above assumed right/bottom gravity.
switch (hgrav) {
default:
case Gravity.LEFT:
left -= childWidth;
break;
case Gravity.RIGHT:
// Do nothing, we're already in position.
break;
case Gravity.CENTER_HORIZONTAL:
left -= childWidth / 2;
break;
}
switch (vgrav) {
default:
case Gravity.TOP:
top -= childHeight;
break;
case Gravity.BOTTOM:
// Do nothing, we're already in position.
break;
case Gravity.CENTER_VERTICAL:
top -= childHeight / 2;
break;
}
final int width = getWidth();
final int height = getHeight();
// Obey margins and padding
left = Math.max(getPaddingLeft() + lp.leftMargin,
Math.min(left,
width - getPaddingRight() - childWidth - lp.rightMargin));
top = Math.max(getPaddingTop() + lp.topMargin,
Math.min(top,
height - getPaddingBottom() - childHeight - lp.bottomMargin));
out.set(left, top, left + childWidth, top + childHeight);
}
/**
* CORE ASSUMPTION: anchor has been laid out by the time this is called for a given child view.
*
* @param child child to lay out
* @param anchor view to anchor child relative to; already laid out.
* @param layoutDirection ViewCompat constant for layout direction
*/
private void layoutChildWithAnchor(View child, View anchor, int layoutDirection) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final Rect anchorRect = mTempRect1;
final Rect childRect = mTempRect2;
getDescendantRect(anchor, anchorRect);
getDesiredAnchoredChildRect(child, layoutDirection, anchorRect, childRect);
child.layout(childRect.left, childRect.top, childRect.right, childRect.bottom);
}
/**
* Lay out a child view with respect to a keyline.
*
* <p>The keyline represents a horizontal offset from the unpadded starting edge of
* the CoordinatorLayout. The child's gravity will affect how it is positioned with
* respect to the keyline.</p>
*
* @param child child to lay out
* @param keyline offset from the starting edge in pixels of the keyline to align with
* @param layoutDirection ViewCompat constant for layout direction
*/
private void layoutChildWithKeyline(View child, int keyline, int layoutDirection) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final int absGravity = GravityCompat.getAbsoluteGravity(
resolveKeylineGravity(lp.gravity), layoutDirection);
final int hgrav = absGravity & Gravity.HORIZONTAL_GRAVITY_MASK;
final int vgrav = absGravity & Gravity.VERTICAL_GRAVITY_MASK;
final int width = getWidth();
final int height = getHeight();
final int childWidth = child.getMeasuredWidth();
final int childHeight = child.getMeasuredHeight();
if (layoutDirection == ViewCompat.LAYOUT_DIRECTION_RTL) {
keyline = width - keyline;
}
int left = getKeyline(keyline) - childWidth;
int top = 0;
switch (hgrav) {
default:
case Gravity.LEFT:
// Nothing to do.
break;
case Gravity.RIGHT:
left += childWidth;
break;
case Gravity.CENTER_HORIZONTAL:
left += childWidth / 2;
break;
}
switch (vgrav) {
default:
case Gravity.TOP:
// Do nothing, we're already in position.
break;
case Gravity.BOTTOM:
top += childHeight;
break;
case Gravity.CENTER_VERTICAL:
top += childHeight / 2;
break;
}
// Obey margins and padding
left = Math.max(getPaddingLeft() + lp.leftMargin,
Math.min(left,
width - getPaddingRight() - childWidth - lp.rightMargin));
top = Math.max(getPaddingTop() + lp.topMargin,
Math.min(top,
height - getPaddingBottom() - childHeight - lp.bottomMargin));
child.layout(left, top, left + childWidth, top + childHeight);
}
/**
* Lay out a child view with no special handling. This will position the child as
* if it were within a FrameLayout or similar simple frame.
*
* @param child child view to lay out
* @param layoutDirection ViewCompat constant for the desired layout direction
*/
private void layoutChild(View child, int layoutDirection) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final Rect parent = mTempRect1;
parent.set(getPaddingLeft() + lp.leftMargin,
getPaddingTop() + lp.topMargin,
getWidth() - getPaddingRight() - lp.rightMargin,
getHeight() - getPaddingBottom() - lp.bottomMargin);
if (mLastInsets != null && ViewCompat.getFitsSystemWindows(this)
&& !ViewCompat.getFitsSystemWindows(child)) {
// If we're set to handle insets but this child isn't, then it has been measured as
// if there are no insets. We need to lay it out to match.
parent.left += mLastInsets.getSystemWindowInsetLeft();
parent.top += mLastInsets.getSystemWindowInsetTop();
parent.right -= mLastInsets.getSystemWindowInsetRight();
parent.bottom -= mLastInsets.getSystemWindowInsetBottom();
}
final Rect out = mTempRect2;
GravityCompat.apply(resolveGravity(lp.gravity), child.getMeasuredWidth(),
child.getMeasuredHeight(), parent, out, layoutDirection);
child.layout(out.left, out.top, out.right, out.bottom);
}
/**
* Return the given gravity value or the default if the passed value is NO_GRAVITY.
* This should be used for children that are not anchored to another view or a keyline.
*/
private static int resolveGravity(int gravity) {
return gravity == Gravity.NO_GRAVITY ? GravityCompat.START | Gravity.TOP : gravity;
}
/**
* Return the given gravity value or the default if the passed value is NO_GRAVITY.
* This should be used for children that are positioned relative to a keyline.
*/
private static int resolveKeylineGravity(int gravity) {
return gravity == Gravity.NO_GRAVITY ? GravityCompat.END | Gravity.TOP : gravity;
}
/**
* Return the given gravity value or the default if the passed value is NO_GRAVITY.
* This should be used for children that are anchored to another view.
*/
private static int resolveAnchoredChildGravity(int gravity) {
return gravity == Gravity.NO_GRAVITY ? Gravity.CENTER : gravity;
}
@Override
protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (lp.mBehavior != null && lp.mBehavior.getScrimOpacity(this, child) > 0.f) {
if (mScrimPaint == null) {
mScrimPaint = new Paint();
}
mScrimPaint.setColor(lp.mBehavior.getScrimColor(this, child));
// TODO: Set the clip appropriately to avoid unnecessary overdraw.
canvas.drawRect(getPaddingLeft(), getPaddingTop(),
getWidth() - getPaddingRight(), getHeight() - getPaddingBottom(), mScrimPaint);
}
return super.drawChild(canvas, child, drawingTime);
}
/**
* Dispatch any dependent view changes to the relevant {@link Behavior} instances.
*
* Usually run as part of the pre-draw step when at least one child view has a reported
* dependency on another view. This allows CoordinatorLayout to account for layout
* changes and animations that occur outside of the normal layout pass.
*
* It can also be ran as part of the nested scrolling dispatch to ensure that any offsetting
* is completed within the correct coordinate window.
*
* The offsetting behavior implemented here does not store the computed offset in
* the LayoutParams; instead it expects that the layout process will always reconstruct
* the proper positioning.
*
* @param fromNestedScroll true if this is being called from one of the nested scroll methods,
* false if run as part of the pre-draw step.
*/
void dispatchOnDependentViewChanged(final boolean fromNestedScroll) {
final int layoutDirection = ViewCompat.getLayoutDirection(this);
final int childCount = mDependencySortedChildren.size();
for (int i = 0; i < childCount; i++) {
final View child = mDependencySortedChildren.get(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
// Check child views before for anchor
for (int j = 0; j < i; j++) {
final View checkChild = mDependencySortedChildren.get(j);
if (lp.mAnchorDirectChild == checkChild) {
offsetChildToAnchor(child, layoutDirection);
}
}
// Did it change? if not continue
final Rect oldRect = mTempRect1;
final Rect newRect = mTempRect2;
getLastChildRect(child, oldRect);
getChildRect(child, true, newRect);
if (oldRect.equals(newRect)) {
continue;
}
recordLastChildRect(child, newRect);
// Update any behavior-dependent views for the change
for (int j = i + 1; j < childCount; j++) {
final View checkChild = mDependencySortedChildren.get(j);
final LayoutParams checkLp = (LayoutParams) checkChild.getLayoutParams();
final Behavior b = checkLp.getBehavior();
if (b != null && b.layoutDependsOn(this, checkChild, child)) {
if (!fromNestedScroll && checkLp.getChangedAfterNestedScroll()) {
// If this is not from a nested scroll and we have already been changed
// from a nested scroll, skip the dispatch and reset the flag
checkLp.resetChangedAfterNestedScroll();
continue;
}
final boolean handled = b.onDependentViewChanged(this, checkChild, child);
if (fromNestedScroll) {
// If this is from a nested scroll, set the flag so that we may skip
// any resulting onPreDraw dispatch (if needed)
checkLp.setChangedAfterNestedScroll(handled);
}
}
}
}
}
void dispatchDependentViewRemoved(View removedChild) {
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final Behavior b = lp.getBehavior();
if (b != null && b.layoutDependsOn(this, child, removedChild)) {
b.onDependentViewRemoved(this, child, removedChild);
}
}
}
/**
* Allows the caller to manually dispatch
* {@link Behavior#onDependentViewChanged(CoordinatorLayout, View, View)} to the associated
* {@link Behavior} instances of views which depend on the provided {@link View}.
*
* <p>You should not normally need to call this method as the it will be automatically done
* when the view has changed.
*
* @param view the View to find dependents of to dispatch the call.
*/
public void dispatchDependentViewsChanged(View view) {
final int childCount = mDependencySortedChildren.size();
boolean viewSeen = false;
for (int i = 0; i < childCount; i++) {
final View child = mDependencySortedChildren.get(i);
if (child == view) {
// We've seen our view, which means that any Views after this could be dependent
viewSeen = true;
continue;
}
if (viewSeen) {
CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams)
child.getLayoutParams();
CoordinatorLayout.Behavior b = lp.getBehavior();
if (b != null && lp.dependsOn(this, child, view)) {
b.onDependentViewChanged(this, child, view);
}
}
}
}
/**
* Returns the list of views which the provided view depends on. Do not store this list as it's
* contents may not be valid beyond the caller.
*
* @param child the view to find dependencies for.
*
* @return the list of views which {@code child} depends on.
*/
public List<View> getDependencies(View child) {
// TODO The result of this is probably a good candidate for caching
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final List<View> list = mTempDependenciesList;
list.clear();
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View other = getChildAt(i);
if (other == child) {
continue;
}
if (lp.dependsOn(this, child, other)) {
list.add(other);
}
}
return list;
}
/**
* Add or remove the pre-draw listener as necessary.
*/
void ensurePreDrawListener() {
boolean hasDependencies = false;
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
if (hasDependencies(child)) {
hasDependencies = true;
break;
}
}
if (hasDependencies != mNeedsPreDrawListener) {
if (hasDependencies) {
addPreDrawListener();
} else {
removePreDrawListener();
}
}
}
/**
* Check if the given child has any layout dependencies on other child views.
*/
boolean hasDependencies(View child) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (lp.mAnchorView != null) {
return true;
}
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View other = getChildAt(i);
if (other == child) {
continue;
}
if (lp.dependsOn(this, child, other)) {
return true;
}
}
return false;
}
/**
* Add the pre-draw listener if we're attached to a window and mark that we currently
* need it when attached.
*/
void addPreDrawListener() {
if (mIsAttachedToWindow) {
// Add the listener
if (mOnPreDrawListener == null) {
mOnPreDrawListener = new OnPreDrawListener();
}
final ViewTreeObserver vto = getViewTreeObserver();
vto.addOnPreDrawListener(mOnPreDrawListener);
}
// Record that we need the listener regardless of whether or not we're attached.
// We'll add the real listener when we become attached.
mNeedsPreDrawListener = true;
}
/**
* Remove the pre-draw listener if we're attached to a window and mark that we currently
* do not need it when attached.
*/
void removePreDrawListener() {
if (mIsAttachedToWindow) {
if (mOnPreDrawListener != null) {
final ViewTreeObserver vto = getViewTreeObserver();
vto.removeOnPreDrawListener(mOnPreDrawListener);
}
}
mNeedsPreDrawListener = false;
}
/**
* Adjust the child left, top, right, bottom rect to the correct anchor view position,
* respecting gravity and anchor gravity.
*
* Note that child translation properties are ignored in this process, allowing children
* to be animated away from their anchor. However, if the anchor view is animated,
* the child will be offset to match the anchor's translated position.
*/
void offsetChildToAnchor(View child, int layoutDirection) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (lp.mAnchorView != null) {
final Rect anchorRect = mTempRect1;
final Rect childRect = mTempRect2;
final Rect desiredChildRect = mTempRect3;
getDescendantRect(lp.mAnchorView, anchorRect);
getChildRect(child, false, childRect);
getDesiredAnchoredChildRect(child, layoutDirection, anchorRect, desiredChildRect);
final int dx = desiredChildRect.left - childRect.left;
final int dy = desiredChildRect.top - childRect.top;
if (dx != 0) {
child.offsetLeftAndRight(dx);
}
if (dy != 0) {
child.offsetTopAndBottom(dy);
}
if (dx != 0 || dy != 0) {
// If we have needed to move, make sure to notify the child's Behavior
final Behavior b = lp.getBehavior();
if (b != null) {
b.onDependentViewChanged(this, child, lp.mAnchorView);
}
}
}
}
/**
* Check if a given point in the CoordinatorLayout's coordinates are within the view bounds
* of the given direct child view.
*
* @param child child view to test
* @param x X coordinate to test, in the CoordinatorLayout's coordinate system
* @param y Y coordinate to test, in the CoordinatorLayout's coordinate system
* @return true if the point is within the child view's bounds, false otherwise
*/
public boolean isPointInChildBounds(View child, int x, int y) {
final Rect r = mTempRect1;
getDescendantRect(child, r);
return r.contains(x, y);
}
/**
* Check whether two views overlap each other. The views need to be descendants of this
* {@link CoordinatorLayout} in the view hierarchy.
*
* @param first first child view to test
* @param second second child view to test
* @return true if both views are visible and overlap each other
*/
public boolean doViewsOverlap(View first, View second) {
if (first.getVisibility() == VISIBLE && second.getVisibility() == VISIBLE) {
final Rect firstRect = mTempRect1;
getChildRect(first, first.getParent() != this, firstRect);
final Rect secondRect = mTempRect2;
getChildRect(second, second.getParent() != this, secondRect);
return !(firstRect.left > secondRect.right || firstRect.top > secondRect.bottom
|| firstRect.right < secondRect.left || firstRect.bottom < secondRect.top);
}
return false;
}
@Override
public LayoutParams generateLayoutParams(AttributeSet attrs) {
return new LayoutParams(getContext(), attrs);
}
@Override
protected LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
if (p instanceof LayoutParams) {
return new LayoutParams((LayoutParams) p);
} else if (p instanceof MarginLayoutParams) {
return new LayoutParams((MarginLayoutParams) p);
}
return new LayoutParams(p);
}
@Override
protected LayoutParams generateDefaultLayoutParams() {
return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
}
@Override
protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
return p instanceof LayoutParams && super.checkLayoutParams(p);
}
public boolean onStartNestedScroll(View child, View target, int nestedScrollAxes) {
boolean handled = false;
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View view = getChildAt(i);
final LayoutParams lp = (LayoutParams) view.getLayoutParams();
final Behavior viewBehavior = lp.getBehavior();
if (viewBehavior != null) {
final boolean accepted = viewBehavior.onStartNestedScroll(this, view, child, target,
nestedScrollAxes);
handled |= accepted;
lp.acceptNestedScroll(accepted);
} else {
lp.acceptNestedScroll(false);
}
}
return handled;
}
public void onNestedScrollAccepted(View child, View target, int nestedScrollAxes) {
mNestedScrollingParentHelper.onNestedScrollAccepted(child, target, nestedScrollAxes);
mNestedScrollingDirectChild = child;
mNestedScrollingTarget = target;
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View view = getChildAt(i);
final LayoutParams lp = (LayoutParams) view.getLayoutParams();
if (!lp.isNestedScrollAccepted()) {
continue;
}
final Behavior viewBehavior = lp.getBehavior();
if (viewBehavior != null) {
viewBehavior.onNestedScrollAccepted(this, view, child, target, nestedScrollAxes);
}
}
}
public void onStopNestedScroll(View target) {
mNestedScrollingParentHelper.onStopNestedScroll(target);
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View view = getChildAt(i);
final LayoutParams lp = (LayoutParams) view.getLayoutParams();
if (!lp.isNestedScrollAccepted()) {
continue;
}
final Behavior viewBehavior = lp.getBehavior();
if (viewBehavior != null) {
viewBehavior.onStopNestedScroll(this, view, target);
}
lp.resetNestedScroll();
lp.resetChangedAfterNestedScroll();
}
mNestedScrollingDirectChild = null;
mNestedScrollingTarget = null;
}
public void onNestedScroll(View target, int dxConsumed, int dyConsumed,
int dxUnconsumed, int dyUnconsumed) {
final int childCount = getChildCount();
boolean accepted = false;
for (int i = 0; i < childCount; i++) {
final View view = getChildAt(i);
final LayoutParams lp = (LayoutParams) view.getLayoutParams();
if (!lp.isNestedScrollAccepted()) {
continue;
}
final Behavior viewBehavior = lp.getBehavior();
if (viewBehavior != null) {
viewBehavior.onNestedScroll(this, view, target, dxConsumed, dyConsumed,
dxUnconsumed, dyUnconsumed);
accepted = true;
}
}
if (accepted) {
dispatchOnDependentViewChanged(true);
}
}
public void onNestedPreScroll(View target, int dx, int dy, int[] consumed) {
int xConsumed = 0;
int yConsumed = 0;
boolean accepted = false;
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View view = getChildAt(i);
final LayoutParams lp = (LayoutParams) view.getLayoutParams();
if (!lp.isNestedScrollAccepted()) {
continue;
}
final Behavior viewBehavior = lp.getBehavior();
if (viewBehavior != null) {
mTempIntPair[0] = mTempIntPair[1] = 0;
viewBehavior.onNestedPreScroll(this, view, target, dx, dy, mTempIntPair);
xConsumed = dx > 0 ? Math.max(xConsumed, mTempIntPair[0])
: Math.min(xConsumed, mTempIntPair[0]);
yConsumed = dy > 0 ? Math.max(yConsumed, mTempIntPair[1])
: Math.min(yConsumed, mTempIntPair[1]);
accepted = true;
}
}
consumed[0] = xConsumed;
consumed[1] = yConsumed;
if (accepted) {
dispatchOnDependentViewChanged(true);
}
}
public boolean onNestedFling(View target, float velocityX, float velocityY, boolean consumed) {
boolean handled = false;
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View view = getChildAt(i);
final LayoutParams lp = (LayoutParams) view.getLayoutParams();
if (!lp.isNestedScrollAccepted()) {
continue;
}
final Behavior viewBehavior = lp.getBehavior();
if (viewBehavior != null) {
handled |= viewBehavior.onNestedFling(this, view, target, velocityX, velocityY,
consumed);
}
}
if (handled) {
dispatchOnDependentViewChanged(true);
}
return handled;
}
public boolean onNestedPreFling(View target, float velocityX, float velocityY) {
boolean handled = false;
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View view = getChildAt(i);
final LayoutParams lp = (LayoutParams) view.getLayoutParams();
if (!lp.isNestedScrollAccepted()) {
continue;
}
final Behavior viewBehavior = lp.getBehavior();
if (viewBehavior != null) {
handled |= viewBehavior.onNestedPreFling(this, view, target, velocityX, velocityY);
}
}
return handled;
}
public int getNestedScrollAxes() {
return mNestedScrollingParentHelper.getNestedScrollAxes();
}
class OnPreDrawListener implements ViewTreeObserver.OnPreDrawListener {
@Override
public boolean onPreDraw() {
dispatchOnDependentViewChanged(false);
return true;
}
}
/**
* Sorts child views with higher Z values to the beginning of a collection.
*/
static class ViewElevationComparator implements Comparator<View> {
@Override
public int compare(View lhs, View rhs) {
final float lz = ViewCompat.getZ(lhs);
final float rz = ViewCompat.getZ(rhs);
if (lz > rz) {
return -1;
} else if (lz < rz) {
return 1;
}
return 0;
}
}
/**
* Defines the default {@link Behavior} of a {@link View} class.
*
* <p>When writing a custom view, use this annotation to define the default behavior
* when used as a direct child of an {@link CoordinatorLayout}. The default behavior
* can be overridden using {@link LayoutParams#setBehavior}.</p>
*
* <p>Example: <code>@DefaultBehavior(MyBehavior.class)</code></p>
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface DefaultBehavior {
Class<? extends Behavior> value();
}
/**
* Interaction behavior plugin for child views of {@link CoordinatorLayout}.
*
* <p>A Behavior implements one or more interactions that a user can take on a child view.
* These interactions may include drags, swipes, flings, or any other gestures.</p>
*
* @param <V> The View type that this Behavior operates on
*/
public static abstract class Behavior<V extends View> {
/**
* Default constructor for instantiating Behaviors.
*/
public Behavior() {
}
/**
* Default constructor for inflating Behaviors from layout. The Behavior will have
* the opportunity to parse specially defined layout parameters. These parameters will
* appear on the child view tag.
*
* @param context
* @param attrs
*/
public Behavior(Context context, AttributeSet attrs) {
}
/**
* Respond to CoordinatorLayout touch events before they are dispatched to child views.
*
* <p>Behaviors can use this to monitor inbound touch events until one decides to
* intercept the rest of the event stream to take an action on its associated child view.
* This method will return false until it detects the proper intercept conditions, then
* return true once those conditions have occurred.</p>
*
* <p>Once a Behavior intercepts touch events, the rest of the event stream will
* be sent to the {@link #onTouchEvent} method.</p>
*
* <p>The default implementation of this method always returns false.</p>
*
* @param parent the parent view currently receiving this touch event
* @param child the child view associated with this Behavior
* @param ev the MotionEvent describing the touch event being processed
* @return true if this Behavior would like to intercept and take over the event stream.
* The default always returns false.
*/
public boolean onInterceptTouchEvent(CoordinatorLayout parent, V child, MotionEvent ev) {
return false;
}
/**
* Respond to CoordinatorLayout touch events after this Behavior has started
* {@link #onInterceptTouchEvent intercepting} them.
*
* <p>Behaviors may intercept touch events in order to help the CoordinatorLayout
* manipulate its child views. For example, a Behavior may allow a user to drag a
* UI pane open or closed. This method should perform actual mutations of view
* layout state.</p>
*
* @param parent the parent view currently receiving this touch event
* @param child the child view associated with this Behavior
* @param ev the MotionEvent describing the touch event being processed
* @return true if this Behavior handled this touch event and would like to continue
* receiving events in this stream. The default always returns false.
*/
public boolean onTouchEvent(CoordinatorLayout parent, V child, MotionEvent ev) {
return false;
}
/**
* Supply a scrim color that will be painted behind the associated child view.
*
* <p>A scrim may be used to indicate that the other elements beneath it are not currently
* interactive or actionable, drawing user focus and attention to the views above the scrim.
* </p>
*
* <p>The default implementation returns {@link Color#BLACK}.</p>
*
* @param parent the parent view of the given child
* @param child the child view above the scrim
* @return the desired scrim color in 0xAARRGGBB format. The default return value is
* {@link Color#BLACK}.
* @see #getScrimOpacity(CoordinatorLayout, android.view.View)
*/
public final int getScrimColor(CoordinatorLayout parent, V child) {
return Color.BLACK;
}
/**
* Determine the current opacity of the scrim behind a given child view
*
* <p>A scrim may be used to indicate that the other elements beneath it are not currently
* interactive or actionable, drawing user focus and attention to the views above the scrim.
* </p>
*
* <p>The default implementation returns 0.0f.</p>
*
* @param parent the parent view of the given child
* @param child the child view above the scrim
* @return the desired scrim opacity from 0.0f to 1.0f. The default return value is 0.0f.
*/
public final float getScrimOpacity(CoordinatorLayout parent, V child) {
return 0.f;
}
/**
* Determine whether interaction with views behind the given child in the child order
* should be blocked.
*
* <p>The default implementation returns true if
* {@link #getScrimOpacity(CoordinatorLayout, android.view.View)} would return > 0.0f.</p>
*
* @param parent the parent view of the given child
* @param child the child view to test
* @return true if {@link #getScrimOpacity(CoordinatorLayout, android.view.View)} would
* return > 0.0f.
*/
public boolean blocksInteractionBelow(CoordinatorLayout parent, V child) {
return getScrimOpacity(parent, child) > 0.f;
}
/**
* Determine whether the supplied child view has another specific sibling view as a
* layout dependency.
*
* <p>This method will be called at least once in response to a layout request. If it
* returns true for a given child and dependency view pair, the parent CoordinatorLayout
* will:</p>
* <ol>
* <li>Always lay out this child after the dependent child is laid out, regardless
* of child order.</li>
* <li>Call {@link #onDependentViewChanged} when the dependency view's layout or
* position changes.</li>
* </ol>
*
* @param parent the parent view of the given child
* @param child the child view to test
* @param dependency the proposed dependency of child
* @return true if child's layout depends on the proposed dependency's layout,
* false otherwise
*
* @see #onDependentViewChanged(CoordinatorLayout, android.view.View, android.view.View)
*/
public boolean layoutDependsOn(CoordinatorLayout parent, V child, View dependency) {
return false;
}
/**
* Respond to a change in a child's dependent view
*
* <p>This method is called whenever a dependent view changes in size or position outside
* of the standard layout flow. A Behavior may use this method to appropriately update
* the child view in response.</p>
*
* <p>A view's dependency is determined by
* {@link #layoutDependsOn(CoordinatorLayout, android.view.View, android.view.View)} or
* if {@code child} has set another view as it's anchor.</p>
*
* <p>Note that if a Behavior changes the layout of a child via this method, it should
* also be able to reconstruct the correct position in
* {@link #onLayoutChild(CoordinatorLayout, android.view.View, int) onLayoutChild}.
* <code>onDependentViewChanged</code> will not be called during normal layout since
* the layout of each child view will always happen in dependency order.</p>
*
* <p>If the Behavior changes the child view's size or position, it should return true.
* The default implementation returns false.</p>
*
* @param parent the parent view of the given child
* @param child the child view to manipulate
* @param dependency the dependent view that changed
* @return true if the Behavior changed the child view's size or position, false otherwise
*/
public boolean onDependentViewChanged(CoordinatorLayout parent, V child, View dependency) {
return false;
}
/**
* Respond to a child's dependent view being removed.
*
* <p>This method is called after a dependent view has been removed from the parent.
* A Behavior may use this method to appropriately update the child view in response.</p>
*
* <p>A view's dependency is determined by
* {@link #layoutDependsOn(CoordinatorLayout, android.view.View, android.view.View)} or
* if {@code child} has set another view as it's anchor.</p>
*
* @param parent the parent view of the given child
* @param child the child view to manipulate
* @param dependency the dependent view that has been removed
*/
public void onDependentViewRemoved(CoordinatorLayout parent, V child, View dependency) {
}
/**
* Determine whether the given child view should be considered dirty.
*
* <p>If a property determined by the Behavior such as other dependent views would change,
* the Behavior should report a child view as dirty. This will prompt the CoordinatorLayout
* to re-query Behavior-determined properties as appropriate.</p>
*
* @param parent the parent view of the given child
* @param child the child view to check
* @return true if child is dirty
*/
public boolean isDirty(CoordinatorLayout parent, V child) {
return false;
}
/**
* Called when the parent CoordinatorLayout is about to measure the given child view.
*
* <p>This method can be used to perform custom or modified measurement of a child view
* in place of the default child measurement behavior. The Behavior's implementation
* can delegate to the standard CoordinatorLayout measurement behavior by calling
* {@link CoordinatorLayout#onMeasureChild(android.view.View, int, int, int, int)
* parent.onMeasureChild}.</p>
*
* @param parent the parent CoordinatorLayout
* @param child the child to measure
* @param parentWidthMeasureSpec the width requirements for this view
* @param widthUsed extra space that has been used up by the parent
* horizontally (possibly by other children of the parent)
* @param parentHeightMeasureSpec the height requirements for this view
* @param heightUsed extra space that has been used up by the parent
* vertically (possibly by other children of the parent)
* @return true if the Behavior measured the child view, false if the CoordinatorLayout
* should perform its default measurement
*/
public boolean onMeasureChild(CoordinatorLayout parent, V child,
int parentWidthMeasureSpec, int widthUsed,
int parentHeightMeasureSpec, int heightUsed) {
return false;
}
/**
* Called when the parent CoordinatorLayout is about the lay out the given child view.
*
* <p>This method can be used to perform custom or modified layout of a child view
* in place of the default child layout behavior. The Behavior's implementation can
* delegate to the standard CoordinatorLayout measurement behavior by calling
* {@link CoordinatorLayout#onLayoutChild(android.view.View, int)
* parent.onMeasureChild}.</p>
*
* <p>If a Behavior implements
* {@link #onDependentViewChanged(CoordinatorLayout, android.view.View, android.view.View)}
* to change the position of a view in response to a dependent view changing, it
* should also implement <code>onLayoutChild</code> in such a way that respects those
* dependent views. <code>onLayoutChild</code> will always be called for a dependent view
* <em>after</em> its dependency has been laid out.</p>
*
* @param parent the parent CoordinatorLayout
* @param child child view to lay out
* @param layoutDirection the resolved layout direction for the CoordinatorLayout, such as
* {@link ViewCompat#LAYOUT_DIRECTION_LTR} or
* {@link ViewCompat#LAYOUT_DIRECTION_RTL}.
* @return true if the Behavior performed layout of the child view, false to request
* default layout behavior
*/
public boolean onLayoutChild(CoordinatorLayout parent, V child, int layoutDirection) {
return false;
}
// Utility methods for accessing child-specific, behavior-modifiable properties.
/**
* Associate a Behavior-specific tag object with the given child view.
* This object will be stored with the child view's LayoutParams.
*
* @param child child view to set tag with
* @param tag tag object to set
*/
public static void setTag(View child, Object tag) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
lp.mBehaviorTag = tag;
}
/**
* Get the behavior-specific tag object with the given child view.
* This object is stored with the child view's LayoutParams.
*
* @param child child view to get tag with
* @return the previously stored tag object
*/
public static Object getTag(View child) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
return lp.mBehaviorTag;
}
/**
* Called when a descendant of the CoordinatorLayout attempts to initiate a nested scroll.
*
* <p>Any Behavior associated with any direct child of the CoordinatorLayout may respond
* to this event and return true to indicate that the CoordinatorLayout should act as
* a nested scrolling parent for this scroll. Only Behaviors that return true from
* this method will receive subsequent nested scroll events.</p>
*
* @param coordinatorLayout the CoordinatorLayout parent of the view this Behavior is
* associated with
* @param child the child view of the CoordinatorLayout this Behavior is associated with
* @param directTargetChild the child view of the CoordinatorLayout that either is or
* contains the target of the nested scroll operation
* @param target the descendant view of the CoordinatorLayout initiating the nested scroll
* @param nestedScrollAxes the axes that this nested scroll applies to. See
* {@link ViewCompat#SCROLL_AXIS_HORIZONTAL},
* {@link ViewCompat#SCROLL_AXIS_VERTICAL}
* @return true if the Behavior wishes to accept this nested scroll
*
* @see NestedScrollingParent#onStartNestedScroll(View, View, int)
*/
public boolean onStartNestedScroll(CoordinatorLayout coordinatorLayout,
V child, View directTargetChild, View target, int nestedScrollAxes) {
return false;
}
/**
* Called when a nested scroll has been accepted by the CoordinatorLayout.
*
* <p>Any Behavior associated with any direct child of the CoordinatorLayout may elect
* to accept the nested scroll as part of {@link #onStartNestedScroll}. Each Behavior
* that returned true will receive subsequent nested scroll events for that nested scroll.
* </p>
*
* @param coordinatorLayout the CoordinatorLayout parent of the view this Behavior is
* associated with
* @param child the child view of the CoordinatorLayout this Behavior is associated with
* @param directTargetChild the child view of the CoordinatorLayout that either is or
* contains the target of the nested scroll operation
* @param target the descendant view of the CoordinatorLayout initiating the nested scroll
* @param nestedScrollAxes the axes that this nested scroll applies to. See
* {@link ViewCompat#SCROLL_AXIS_HORIZONTAL},
* {@link ViewCompat#SCROLL_AXIS_VERTICAL}
*
* @see NestedScrollingParent#onNestedScrollAccepted(View, View, int)
*/
public void onNestedScrollAccepted(CoordinatorLayout coordinatorLayout, V child,
View directTargetChild, View target, int nestedScrollAxes) {
// Do nothing
}
/**
* Called when a nested scroll has ended.
*
* <p>Any Behavior associated with any direct child of the CoordinatorLayout may elect
* to accept the nested scroll as part of {@link #onStartNestedScroll}. Each Behavior
* that returned true will receive subsequent nested scroll events for that nested scroll.
* </p>
*
* <p><code>onStopNestedScroll</code> marks the end of a single nested scroll event
* sequence. This is a good place to clean up any state related to the nested scroll.
* </p>
*
* @param coordinatorLayout the CoordinatorLayout parent of the view this Behavior is
* associated with
* @param child the child view of the CoordinatorLayout this Behavior is associated with
* @param target the descendant view of the CoordinatorLayout that initiated
* the nested scroll
*
* @see NestedScrollingParent#onStopNestedScroll(View)
*/
public void onStopNestedScroll(CoordinatorLayout coordinatorLayout, V child, View target) {
// Do nothing
}
/**
* Called when a nested scroll in progress has updated and the target has scrolled or
* attempted to scroll.
*
* <p>Any Behavior associated with the direct child of the CoordinatorLayout may elect
* to accept the nested scroll as part of {@link #onStartNestedScroll}. Each Behavior
* that returned true will receive subsequent nested scroll events for that nested scroll.
* </p>
*
* <p><code>onNestedScroll</code> is called each time the nested scroll is updated by the
* nested scrolling child, with both consumed and unconsumed components of the scroll
* supplied in pixels. <em>Each Behavior responding to the nested scroll will receive the
* same values.</em>
* </p>
*
* @param coordinatorLayout the CoordinatorLayout parent of the view this Behavior is
* associated with
* @param child the child view of the CoordinatorLayout this Behavior is associated with
* @param target the descendant view of the CoordinatorLayout performing the nested scroll
* @param dxConsumed horizontal pixels consumed by the target's own scrolling operation
* @param dyConsumed vertical pixels consumed by the target's own scrolling operation
* @param dxUnconsumed horizontal pixels not consumed by the target's own scrolling
* operation, but requested by the user
* @param dyUnconsumed vertical pixels not consumed by the target's own scrolling operation,
* but requested by the user
*
* @see NestedScrollingParent#onNestedScroll(View, int, int, int, int)
*/
public void onNestedScroll(CoordinatorLayout coordinatorLayout, V child, View target,
int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed) {
// Do nothing
}
/**
* Called when a nested scroll in progress is about to update, before the target has
* consumed any of the scrolled distance.
*
* <p>Any Behavior associated with the direct child of the CoordinatorLayout may elect
* to accept the nested scroll as part of {@link #onStartNestedScroll}. Each Behavior
* that returned true will receive subsequent nested scroll events for that nested scroll.
* </p>
*
* <p><code>onNestedPreScroll</code> is called each time the nested scroll is updated
* by the nested scrolling child, before the nested scrolling child has consumed the scroll
* distance itself. <em>Each Behavior responding to the nested scroll will receive the
* same values.</em> The CoordinatorLayout will report as consumed the maximum number
* of pixels in either direction that any Behavior responding to the nested scroll reported
* as consumed.</p>
*
* @param coordinatorLayout the CoordinatorLayout parent of the view this Behavior is
* associated with
* @param child the child view of the CoordinatorLayout this Behavior is associated with
* @param target the descendant view of the CoordinatorLayout performing the nested scroll
* @param dx the raw horizontal number of pixels that the user attempted to scroll
* @param dy the raw vertical number of pixels that the user attempted to scroll
* @param consumed out parameter. consumed[0] should be set to the distance of dx that
* was consumed, consumed[1] should be set to the distance of dy that
* was consumed
*
* @see NestedScrollingParent#onNestedPreScroll(View, int, int, int[])
*/
public void onNestedPreScroll(CoordinatorLayout coordinatorLayout, V child, View target,
int dx, int dy, int[] consumed) {
// Do nothing
}
/**
* Called when a nested scrolling child is starting a fling or an action that would
* be a fling.
*
* <p>Any Behavior associated with the direct child of the CoordinatorLayout may elect
* to accept the nested scroll as part of {@link #onStartNestedScroll}. Each Behavior
* that returned true will receive subsequent nested scroll events for that nested scroll.
* </p>
*
* <p><code>onNestedFling</code> is called when the current nested scrolling child view
* detects the proper conditions for a fling. It reports if the child itself consumed
* the fling. If it did not, the child is expected to show some sort of overscroll
* indication. This method should return true if it consumes the fling, so that a child
* that did not itself take an action in response can choose not to show an overfling
* indication.</p>
*
* @param coordinatorLayout the CoordinatorLayout parent of the view this Behavior is
* associated with
* @param child the child view of the CoordinatorLayout this Behavior is associated with
* @param target the descendant view of the CoordinatorLayout performing the nested scroll
* @param velocityX horizontal velocity of the attempted fling
* @param velocityY vertical velocity of the attempted fling
* @param consumed true if the nested child view consumed the fling
* @return true if the Behavior consumed the fling
*
* @see NestedScrollingParent#onNestedFling(View, float, float, boolean)
*/
public boolean onNestedFling(CoordinatorLayout coordinatorLayout, V child, View target,
float velocityX, float velocityY, boolean consumed) {
return false;
}
/**
* Called when a nested scrolling child is about to start a fling.
*
* <p>Any Behavior associated with the direct child of the CoordinatorLayout may elect
* to accept the nested scroll as part of {@link #onStartNestedScroll}. Each Behavior
* that returned true will receive subsequent nested scroll events for that nested scroll.
* </p>
*
* <p><code>onNestedPreFling</code> is called when the current nested scrolling child view
* detects the proper conditions for a fling, but it has not acted on it yet. A
* Behavior can return true to indicate that it consumed the fling. If at least one
* Behavior returns true, the fling should not be acted upon by the child.</p>
*
* @param coordinatorLayout the CoordinatorLayout parent of the view this Behavior is
* associated with
* @param child the child view of the CoordinatorLayout this Behavior is associated with
* @param target the descendant view of the CoordinatorLayout performing the nested scroll
* @param velocityX horizontal velocity of the attempted fling
* @param velocityY vertical velocity of the attempted fling
* @return true if the Behavior consumed the fling
*
* @see NestedScrollingParent#onNestedPreFling(View, float, float)
*/
public boolean onNestedPreFling(CoordinatorLayout coordinatorLayout, V child, View target,
float velocityX, float velocityY) {
return false;
}
/**
* Called when the window insets have changed.
*
* <p>Any Behavior associated with the direct child of the CoordinatorLayout may elect
* to handle the window inset change on behalf of it's associated view.
* </p>
*
* @param coordinatorLayout the CoordinatorLayout parent of the view this Behavior is
* associated with
* @param child the child view of the CoordinatorLayout this Behavior is associated with
* @param insets the new window insets.
*
* @return The insets supplied, minus any insets that were consumed
*/
public WindowInsetsCompat onApplyWindowInsets(CoordinatorLayout coordinatorLayout,
V child, WindowInsetsCompat insets) {
return insets;
}
/**
* Hook allowing a behavior to re-apply a representation of its internal state that had
* previously been generated by {@link #onSaveInstanceState}. This function will never
* be called with a null state.
*
* @param parent the parent CoordinatorLayout
* @param child child view to restore from
* @param state The frozen state that had previously been returned by
* {@link #onSaveInstanceState}.
*
* @see #onSaveInstanceState()
*/
public void onRestoreInstanceState(CoordinatorLayout parent, V child, Parcelable state) {
// no-op
}
/**
* Hook allowing a behavior to generate a representation of its internal state
* that can later be used to create a new instance with that same state.
* This state should only contain information that is not persistent or can
* not be reconstructed later.
*
* <p>Behavior state is only saved when both the parent {@link CoordinatorLayout} and
* a view using this behavior have valid IDs set.</p>
*
* @param parent the parent CoordinatorLayout
* @param child child view to restore from
*
* @return Returns a Parcelable object containing the behavior's current dynamic
* state.
*
* @see #onRestoreInstanceState(android.os.Parcelable)
* @see View#onSaveInstanceState()
*/
public Parcelable onSaveInstanceState(CoordinatorLayout parent, V child) {
return BaseSavedState.EMPTY_STATE;
}
}
/**
* Parameters describing the desired layout for a child of a {@link CoordinatorLayout}.
*/
public static class LayoutParams extends ViewGroup.MarginLayoutParams {
/**
* A {@link Behavior} that the child view should obey.
*/
Behavior mBehavior;
boolean mBehaviorResolved = false;
/**
* A {@link Gravity} value describing how this child view should lay out.
* If an {@link #setAnchorId(int) anchor} is also specified, the gravity describes
* how this child view should be positioned relative to its anchored position.
*/
public int gravity = Gravity.NO_GRAVITY;
/**
* A {@link Gravity} value describing which edge of a child view's
* {@link #getAnchorId() anchor} view the child should position itself relative to.
*/
public int anchorGravity = Gravity.NO_GRAVITY;
/**
* The index of the horizontal keyline specified to the parent CoordinatorLayout that this
* child should align relative to. If an {@link #setAnchorId(int) anchor} is present the
* keyline will be ignored.
*/
public int keyline = -1;
/**
* A {@link View#getId() view id} of a descendant view of the CoordinatorLayout that
* this child should position relative to.
*/
int mAnchorId = View.NO_ID;
View mAnchorView;
View mAnchorDirectChild;
private boolean mDidBlockInteraction;
private boolean mDidAcceptNestedScroll;
private boolean mDidChangeAfterNestedScroll;
final Rect mLastChildRect = new Rect();
Object mBehaviorTag;
public LayoutParams(int width, int height) {
super(width, height);
}
LayoutParams(Context context, AttributeSet attrs) {
super(context, attrs);
final TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.CoordinatorLayout_LayoutParams);
this.gravity = a.getInteger(
R.styleable.CoordinatorLayout_LayoutParams_android_layout_gravity,
Gravity.NO_GRAVITY);
mAnchorId = a.getResourceId(R.styleable.CoordinatorLayout_LayoutParams_layout_anchor,
View.NO_ID);
this.anchorGravity = a.getInteger(
R.styleable.CoordinatorLayout_LayoutParams_layout_anchorGravity,
Gravity.NO_GRAVITY);
this.keyline = a.getInteger(R.styleable.CoordinatorLayout_LayoutParams_layout_keyline,
-1);
mBehaviorResolved = a.hasValue(
R.styleable.CoordinatorLayout_LayoutParams_layout_behavior);
if (mBehaviorResolved) {
mBehavior = parseBehavior(context, attrs, a.getString(
R.styleable.CoordinatorLayout_LayoutParams_layout_behavior));
}
a.recycle();
}
public LayoutParams(LayoutParams p) {
super(p);
}
public LayoutParams(MarginLayoutParams p) {
super(p);
}
public LayoutParams(ViewGroup.LayoutParams p) {
super(p);
}
/**
* Get the id of this view's anchor.
*
* <p>The view with this id must be a descendant of the CoordinatorLayout containing
* the child view this LayoutParams belongs to. It may not be the child view with
* this LayoutParams or a descendant of it.</p>
*
* @return A {@link View#getId() view id} or {@link View#NO_ID} if there is no anchor
*/
public int getAnchorId() {
return mAnchorId;
}
/**
* Get the id of this view's anchor.
*
* <p>The view with this id must be a descendant of the CoordinatorLayout containing
* the child view this LayoutParams belongs to. It may not be the child view with
* this LayoutParams or a descendant of it.</p>
*
* @param id The {@link View#getId() view id} of the anchor or
* {@link View#NO_ID} if there is no anchor
*/
public void setAnchorId(int id) {
invalidateAnchor();
mAnchorId = id;
}
/**
* Get the behavior governing the layout and interaction of the child view within
* a parent CoordinatorLayout.
*
* @return The current behavior or null if no behavior is specified
*/
public Behavior getBehavior() {
return mBehavior;
}
/**
* Set the behavior governing the layout and interaction of the child view within
* a parent CoordinatorLayout.
*
* <p>Setting a new behavior will remove any currently associated
* {@link Behavior#setTag(android.view.View, Object) Behavior tag}.</p>
*
* @param behavior The behavior to set or null for no special behavior
*/
public void setBehavior(Behavior behavior) {
if (mBehavior != behavior) {
mBehavior = behavior;
mBehaviorTag = null;
mBehaviorResolved = true;
}
}
/**
* Set the last known position rect for this child view
* @param r the rect to set
*/
void setLastChildRect(Rect r) {
mLastChildRect.set(r);
}
/**
* Get the last known position rect for this child view.
* Note: do not mutate the result of this call.
*/
Rect getLastChildRect() {
return mLastChildRect;
}
/**
* Returns true if the anchor id changed to another valid view id since the anchor view
* was resolved.
*/
boolean checkAnchorChanged() {
return mAnchorView == null && mAnchorId != View.NO_ID;
}
/**
* Returns true if the associated Behavior previously blocked interaction with other views
* below the associated child since the touch behavior tracking was last
* {@link #resetTouchBehaviorTracking() reset}.
*
* @see #isBlockingInteractionBelow(CoordinatorLayout, android.view.View)
*/
boolean didBlockInteraction() {
if (mBehavior == null) {
mDidBlockInteraction = false;
}
return mDidBlockInteraction;
}
/**
* Check if the associated Behavior wants to block interaction below the given child
* view. The given child view should be the child this LayoutParams is associated with.
*
* <p>Once interaction is blocked, it will remain blocked until touch interaction tracking
* is {@link #resetTouchBehaviorTracking() reset}.</p>
*
* @param parent the parent CoordinatorLayout
* @param child the child view this LayoutParams is associated with
* @return true to block interaction below the given child
*/
boolean isBlockingInteractionBelow(CoordinatorLayout parent, View child) {
if (mDidBlockInteraction) {
return true;
}
return mDidBlockInteraction |= mBehavior != null
? mBehavior.blocksInteractionBelow(parent, child)
: false;
}
/**
* Reset tracking of Behavior-specific touch interactions. This includes
* interaction blocking.
*
* @see #isBlockingInteractionBelow(CoordinatorLayout, android.view.View)
* @see #didBlockInteraction()
*/
void resetTouchBehaviorTracking() {
mDidBlockInteraction = false;
}
void resetNestedScroll() {
mDidAcceptNestedScroll = false;
}
void acceptNestedScroll(boolean accept) {
mDidAcceptNestedScroll = accept;
}
boolean isNestedScrollAccepted() {
return mDidAcceptNestedScroll;
}
boolean getChangedAfterNestedScroll() {
return mDidChangeAfterNestedScroll;
}
void setChangedAfterNestedScroll(boolean changed) {
mDidChangeAfterNestedScroll = changed;
}
void resetChangedAfterNestedScroll() {
mDidChangeAfterNestedScroll = false;
}
/**
* Check if an associated child view depends on another child view of the CoordinatorLayout.
*
* @param parent the parent CoordinatorLayout
* @param child the child to check
* @param dependency the proposed dependency to check
* @return true if child depends on dependency
*/
boolean dependsOn(CoordinatorLayout parent, View child, View dependency) {
return dependency == mAnchorDirectChild
|| (mBehavior != null && mBehavior.layoutDependsOn(parent, child, dependency));
}
/**
* Invalidate the cached anchor view and direct child ancestor of that anchor.
* The anchor will need to be
* {@link #findAnchorView(CoordinatorLayout, android.view.View) found} before
* being used again.
*/
void invalidateAnchor() {
mAnchorView = mAnchorDirectChild = null;
}
/**
* Locate the appropriate anchor view by the current {@link #setAnchorId(int) anchor id}
* or return the cached anchor view if already known.
*
* @param parent the parent CoordinatorLayout
* @param forChild the child this LayoutParams is associated with
* @return the located descendant anchor view, or null if the anchor id is
* {@link View#NO_ID}.
*/
View findAnchorView(CoordinatorLayout parent, View forChild) {
if (mAnchorId == View.NO_ID) {
mAnchorView = mAnchorDirectChild = null;
return null;
}
if (mAnchorView == null || !verifyAnchorView(forChild, parent)) {
resolveAnchorView(forChild, parent);
}
return mAnchorView;
}
/**
* Check if the child associated with this LayoutParams is currently considered
* "dirty" and needs to be updated. A Behavior should consider a child dirty
* whenever a property returned by another Behavior method would have changed,
* such as dependencies.
*
* @param parent the parent CoordinatorLayout
* @param child the child view associated with this LayoutParams
* @return true if this child view should be considered dirty
*/
boolean isDirty(CoordinatorLayout parent, View child) {
return mBehavior != null && mBehavior.isDirty(parent, child);
}
/**
* Determine the anchor view for the child view this LayoutParams is assigned to.
* Assumes mAnchorId is valid.
*/
private void resolveAnchorView(View forChild, CoordinatorLayout parent) {
mAnchorView = parent.findViewById(mAnchorId);
if (mAnchorView != null) {
View directChild = mAnchorView;
for (ViewParent p = mAnchorView.getParent();
p != parent && p != null;
p = p.getParent()) {
if (p == forChild) {
if (parent.isInEditMode()) {
mAnchorView = mAnchorDirectChild = null;
return;
}
throw new IllegalStateException(
"Anchor must not be a descendant of the anchored view");
}
if (p instanceof View) {
directChild = (View) p;
}
}
mAnchorDirectChild = directChild;
} else {
if (parent.isInEditMode()) {
mAnchorView = mAnchorDirectChild = null;
return;
}
throw new IllegalStateException("Could not find CoordinatorLayout descendant view"
+ " with id " + parent.getResources().getResourceName(mAnchorId)
+ " to anchor view " + forChild);
}
}
/**
* Verify that the previously resolved anchor view is still valid - that it is still
* a descendant of the expected parent view, it is not the child this LayoutParams
* is assigned to or a descendant of it, and it has the expected id.
*/
private boolean verifyAnchorView(View forChild, CoordinatorLayout parent) {
if (mAnchorView.getId() != mAnchorId) {
return false;
}
View directChild = mAnchorView;
for (ViewParent p = mAnchorView.getParent();
p != parent;
p = p.getParent()) {
if (p == null || p == forChild) {
mAnchorView = mAnchorDirectChild = null;
return false;
}
if (p instanceof View) {
directChild = (View) p;
}
}
mAnchorDirectChild = directChild;
return true;
}
}
final class ApplyInsetsListener implements android.support.v4.view.OnApplyWindowInsetsListener {
@Override
public WindowInsetsCompat onApplyWindowInsets(View v, WindowInsetsCompat insets) {
setWindowInsets(insets);
return insets.consumeSystemWindowInsets();
}
}
final class HierarchyChangeListener implements OnHierarchyChangeListener {
@Override
public void onChildViewAdded(View parent, View child) {
if (mOnHierarchyChangeListener != null) {
mOnHierarchyChangeListener.onChildViewAdded(parent, child);
}
}
@Override
public void onChildViewRemoved(View parent, View child) {
dispatchDependentViewRemoved(child);
if (mOnHierarchyChangeListener != null) {
mOnHierarchyChangeListener.onChildViewRemoved(parent, child);
}
}
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
final SavedState ss = (SavedState) state;
super.onRestoreInstanceState(ss.getSuperState());
final SparseArray<Parcelable> behaviorStates = ss.behaviorStates;
for (int i = 0, count = getChildCount(); i < count; i++) {
final View child = getChildAt(i);
final int childId = child.getId();
final LayoutParams lp = getResolvedLayoutParams(child);
final Behavior b = lp.getBehavior();
if (childId != NO_ID && b != null) {
Parcelable savedState = behaviorStates.get(childId);
if (savedState != null) {
b.onRestoreInstanceState(this, child, savedState);
}
}
}
}
@Override
protected Parcelable onSaveInstanceState() {
final SavedState ss = new SavedState(super.onSaveInstanceState());
final SparseArray<Parcelable> behaviorStates = new SparseArray<>();
for (int i = 0, count = getChildCount(); i < count; i++) {
final View child = getChildAt(i);
final int childId = child.getId();
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final Behavior b = lp.getBehavior();
if (childId != NO_ID && b != null) {
// If the child has an ID and a Behavior, let it save some state...
Parcelable state = b.onSaveInstanceState(this, child);
if (state != null) {
behaviorStates.append(childId, state);
}
}
}
ss.behaviorStates = behaviorStates;
return ss;
}
protected static class SavedState extends BaseSavedState {
SparseArray<Parcelable> behaviorStates;
public SavedState(Parcel source) {
super(source);
final int size = source.readInt();
final int[] ids = new int[size];
source.readIntArray(ids);
final Parcelable[] states = source.readParcelableArray(
CoordinatorLayout.class.getClassLoader());
behaviorStates = new SparseArray<>(size);
for (int i = 0; i < size; i++) {
behaviorStates.append(ids[i], states[i]);
}
}
public SavedState(Parcelable superState) {
super(superState);
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
final int size = behaviorStates != null ? behaviorStates.size() : 0;
dest.writeInt(size);
final int[] ids = new int[size];
final Parcelable[] states = new Parcelable[size];
for (int i = 0; i < size; i++) {
ids[i] = behaviorStates.keyAt(i);
states[i] = behaviorStates.valueAt(i);
}
dest.writeIntArray(ids);
dest.writeParcelableArray(states, flags);
}
public static final Parcelable.Creator<SavedState> CREATOR =
new Parcelable.Creator<SavedState>() {
@Override
public SavedState createFromParcel(Parcel source) {
return new SavedState(source);
}
@Override
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
}
| am 9631f6ff: am 33ca87b7: Merge "Fix NPE in onTouchEvent again" into mnc-dev
* commit '9631f6ffdd51e66e982907f7ddef4fffb0fda74c':
Fix NPE in onTouchEvent again
| design/src/android/support/design/widget/CoordinatorLayout.java | am 9631f6ff: am 33ca87b7: Merge "Fix NPE in onTouchEvent again" into mnc-dev | <ide><path>esign/src/android/support/design/widget/CoordinatorLayout.java
<ide> if (mBehaviorTouchView == null) {
<ide> handled |= super.onTouchEvent(ev);
<ide> } else if (cancelSuper) {
<del> if (cancelEvent != null) {
<add> if (cancelEvent == null) {
<ide> final long now = SystemClock.uptimeMillis();
<ide> cancelEvent = MotionEvent.obtain(now, now,
<ide> MotionEvent.ACTION_CANCEL, 0.0f, 0.0f, 0); |
|
Java | apache-2.0 | 284886bd96c93740a26cac4c6e39a255fecf6062 | 0 | pimtegelaar/commons-io-test3,pimtegelaar/commons-io-test3,apache/commons-io,pimtegelaar/commons-io-test3,apache/commons-io,apache/commons-io | /*
* 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.io.output;
import java.io.Serializable;
import java.io.Writer;
/**
* {@link Writer} implementation that outputs to a {@link StringBuilder}.
* <p>
* <strong>NOTE:</strong> This implementation, as an alternative to
* <code>java.io.StringWriter</code>, provides an <i>un-synchronized</i>
* (i.e. for use in a single thread) implementation for better performance.
* For safe usage with multiple {@link Thread}s then
* <code>java.io.StringWriter</code> should be used.
*
* @version $Id$
* @since 2.0
*/
public class StringBuilderWriter extends Writer implements Serializable {
private static final long serialVersionUID = -146927496096066153L;
private final StringBuilder builder;
/**
* Constructs a new {@link StringBuilder} instance with default capacity.
*/
public StringBuilderWriter() {
this.builder = new StringBuilder();
}
/**
* Constructs a new {@link StringBuilder} instance with the specified capacity.
*
* @param capacity The initial capacity of the underlying {@link StringBuilder}
*/
public StringBuilderWriter(final int capacity) {
this.builder = new StringBuilder(capacity);
}
/**
* Constructs a new instance with the specified {@link StringBuilder}.
*
* <p>If {@code builder} is null a new instance with default capacity will be created.</p>
*
* @param builder The String builder. May be null.
*/
public StringBuilderWriter(final StringBuilder builder) {
this.builder = builder != null ? builder : new StringBuilder();
}
/**
* Appends a single character to this Writer.
*
* @param value The character to append
* @return This writer instance
*/
@Override
public Writer append(final char value) {
builder.append(value);
return this;
}
/**
* Appends a character sequence to this Writer.
*
* @param value The character to append
* @return This writer instance
*/
@Override
public Writer append(final CharSequence value) {
builder.append(value);
return this;
}
/**
* Appends a portion of a character sequence to the {@link StringBuilder}.
*
* @param value The character to append
* @param start The index of the first character
* @param end The index of the last character + 1
* @return This writer instance
*/
@Override
public Writer append(final CharSequence value, final int start, final int end) {
builder.append(value, start, end);
return this;
}
/**
* Closing this writer has no effect.
*/
@Override
public void close() {
// no-op
}
/**
* Flushing this writer has no effect.
*/
@Override
public void flush() {
// no-op
}
/**
* Writes a String to the {@link StringBuilder}.
*
* @param value The value to write
*/
@Override
public void write(final String value) {
if (value != null) {
builder.append(value);
}
}
/**
* Writes a portion of a character array to the {@link StringBuilder}.
*
* @param value The value to write
* @param offset The index of the first character
* @param length The number of characters to write
*/
@Override
public void write(final char[] value, final int offset, final int length) {
if (value != null) {
builder.append(value, offset, length);
}
}
/**
* Returns the underlying builder.
*
* @return The underlying builder
*/
public StringBuilder getBuilder() {
return builder;
}
/**
* Returns {@link StringBuilder#toString()}.
*
* @return The contents of the String builder.
*/
@Override
public String toString() {
return builder.toString();
}
}
| src/main/java/org/apache/commons/io/output/StringBuilderWriter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.output;
import java.io.Serializable;
import java.io.Writer;
/**
* {@link Writer} implementation that outputs to a {@link StringBuilder}.
* <p>
* <strong>NOTE:</strong> This implementation, as an alternative to
* <code>java.io.StringWriter</code>, provides an <i>un-synchronized</i>
* (i.e. for use in a single thread) implementation for better performance.
* For safe usage with multiple {@link Thread}s then
* <code>java.io.StringWriter</code> should be used.
*
* @version $Id$
* @since 2.0
*/
public class StringBuilderWriter extends Writer implements Serializable {
private static final long serialVersionUID = -146927496096066153L;
private final StringBuilder builder;
/**
* Construct a new {@link StringBuilder} instance with default capacity.
*/
public StringBuilderWriter() {
this.builder = new StringBuilder();
}
/**
* Construct a new {@link StringBuilder} instance with the specified capacity.
*
* @param capacity The initial capacity of the underlying {@link StringBuilder}
*/
public StringBuilderWriter(final int capacity) {
this.builder = new StringBuilder(capacity);
}
/**
* Construct a new instance with the specified {@link StringBuilder}.
*
* <p>If {@code builder} is null a new instance with default capacity will be created.</p>
*
* @param builder The String builder. May be null.
*/
public StringBuilderWriter(final StringBuilder builder) {
this.builder = builder != null ? builder : new StringBuilder();
}
/**
* Append a single character to this Writer.
*
* @param value The character to append
* @return This writer instance
*/
@Override
public Writer append(final char value) {
builder.append(value);
return this;
}
/**
* Append a character sequence to this Writer.
*
* @param value The character to append
* @return This writer instance
*/
@Override
public Writer append(final CharSequence value) {
builder.append(value);
return this;
}
/**
* Append a portion of a character sequence to the {@link StringBuilder}.
*
* @param value The character to append
* @param start The index of the first character
* @param end The index of the last character + 1
* @return This writer instance
*/
@Override
public Writer append(final CharSequence value, final int start, final int end) {
builder.append(value, start, end);
return this;
}
/**
* Closing this writer has no effect.
*/
@Override
public void close() {
// no-op
}
/**
* Flushing this writer has no effect.
*/
@Override
public void flush() {
// no-op
}
/**
* Write a String to the {@link StringBuilder}.
*
* @param value The value to write
*/
@Override
public void write(final String value) {
if (value != null) {
builder.append(value);
}
}
/**
* Write a portion of a character array to the {@link StringBuilder}.
*
* @param value The value to write
* @param offset The index of the first character
* @param length The number of characters to write
*/
@Override
public void write(final char[] value, final int offset, final int length) {
if (value != null) {
builder.append(value, offset, length);
}
}
/**
* Return the underlying builder.
*
* @return The underlying builder
*/
public StringBuilder getBuilder() {
return builder;
}
/**
* Returns {@link StringBuilder#toString()}.
*
* @return The contents of the String builder.
*/
@Override
public String toString() {
return builder.toString();
}
}
| Javadoc: Use the active voice.
git-svn-id: cb61607abf5ac23ab48a85ccf5b9d9390a6837ee@1722253 13f79535-47bb-0310-9956-ffa450edef68
| src/main/java/org/apache/commons/io/output/StringBuilderWriter.java | Javadoc: Use the active voice. | <ide><path>rc/main/java/org/apache/commons/io/output/StringBuilderWriter.java
<ide> private final StringBuilder builder;
<ide>
<ide> /**
<del> * Construct a new {@link StringBuilder} instance with default capacity.
<add> * Constructs a new {@link StringBuilder} instance with default capacity.
<ide> */
<ide> public StringBuilderWriter() {
<ide> this.builder = new StringBuilder();
<ide> }
<ide>
<ide> /**
<del> * Construct a new {@link StringBuilder} instance with the specified capacity.
<add> * Constructs a new {@link StringBuilder} instance with the specified capacity.
<ide> *
<ide> * @param capacity The initial capacity of the underlying {@link StringBuilder}
<ide> */
<ide> }
<ide>
<ide> /**
<del> * Construct a new instance with the specified {@link StringBuilder}.
<add> * Constructs a new instance with the specified {@link StringBuilder}.
<ide> *
<ide> * <p>If {@code builder} is null a new instance with default capacity will be created.</p>
<ide> *
<ide> }
<ide>
<ide> /**
<del> * Append a single character to this Writer.
<add> * Appends a single character to this Writer.
<ide> *
<ide> * @param value The character to append
<ide> * @return This writer instance
<ide> }
<ide>
<ide> /**
<del> * Append a character sequence to this Writer.
<add> * Appends a character sequence to this Writer.
<ide> *
<ide> * @param value The character to append
<ide> * @return This writer instance
<ide> }
<ide>
<ide> /**
<del> * Append a portion of a character sequence to the {@link StringBuilder}.
<add> * Appends a portion of a character sequence to the {@link StringBuilder}.
<ide> *
<ide> * @param value The character to append
<ide> * @param start The index of the first character
<ide>
<ide>
<ide> /**
<del> * Write a String to the {@link StringBuilder}.
<add> * Writes a String to the {@link StringBuilder}.
<ide> *
<ide> * @param value The value to write
<ide> */
<ide> }
<ide>
<ide> /**
<del> * Write a portion of a character array to the {@link StringBuilder}.
<add> * Writes a portion of a character array to the {@link StringBuilder}.
<ide> *
<ide> * @param value The value to write
<ide> * @param offset The index of the first character
<ide> }
<ide>
<ide> /**
<del> * Return the underlying builder.
<add> * Returns the underlying builder.
<ide> *
<ide> * @return The underlying builder
<ide> */ |
|
Java | apache-2.0 | 3de2f9f5bbe368add490c0e88a785f0f25af3d8f | 0 | alibaba/fastjson,alibaba/fastjson,alibaba/fastjson,alibaba/fastjson | /*
* Copyright 1999-2018 Alibaba Group.
*
* 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.fastjson.serializer;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Type;
import java.lang.reflect.WildcardType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.annotation.JSONField;
import com.alibaba.fastjson.util.FieldInfo;
import com.alibaba.fastjson.util.TypeUtils;
/**
* @author wenshao[[email protected]]
*/
public class JavaBeanSerializer extends SerializeFilterable implements ObjectSerializer {
// serializers
protected final FieldSerializer[] getters;
protected final FieldSerializer[] sortedGetters;
protected SerializeBeanInfo beanInfo;
private transient volatile long[] hashArray;
private transient volatile short[] hashArrayMapping;
public JavaBeanSerializer(Class<?> beanType){
this(beanType, (Map<String, String>) null);
}
public JavaBeanSerializer(Class<?> beanType, String... aliasList){
this(beanType, createAliasMap(aliasList));
}
static Map<String, String> createAliasMap(String... aliasList) {
Map<String, String> aliasMap = new HashMap<String, String>();
for (String alias : aliasList) {
aliasMap.put(alias, alias);
}
return aliasMap;
}
/**
* @since 1.2.42
*/
public Class<?> getType() {
return beanInfo.beanType;
}
public JavaBeanSerializer(Class<?> beanType, Map<String, String> aliasMap){
this(TypeUtils.buildBeanInfo(beanType, aliasMap, null));
}
public JavaBeanSerializer(SerializeBeanInfo beanInfo) {
this.beanInfo = beanInfo;
sortedGetters = new FieldSerializer[beanInfo.sortedFields.length];
for (int i = 0; i < sortedGetters.length; ++i) {
sortedGetters[i] = new FieldSerializer(beanInfo.beanType, beanInfo.sortedFields[i]);
}
if (beanInfo.fields == beanInfo.sortedFields) {
getters = sortedGetters;
} else {
getters = new FieldSerializer[beanInfo.fields.length];
boolean hashNotMatch = false;
for (int i = 0; i < getters.length; ++i) {
FieldSerializer fieldSerializer = getFieldSerializer(beanInfo.fields[i].name);
if (fieldSerializer == null) {
hashNotMatch = true;
break;
}
getters[i] = fieldSerializer;
}
if (hashNotMatch) {
System.arraycopy(sortedGetters, 0, getters, 0, sortedGetters.length);
}
}
if (beanInfo.jsonType != null) {
for (Class<? extends SerializeFilter> filterClass : beanInfo.jsonType.serialzeFilters()) {
try {
SerializeFilter filter = filterClass.getConstructor().newInstance();
this.addFilter(filter);
} catch (Exception e) {
// skip
}
}
}
if (beanInfo.jsonType != null) {
for (Class<? extends SerializeFilter> filterClass : beanInfo.jsonType.serialzeFilters()) {
try {
SerializeFilter filter = filterClass.getConstructor().newInstance();
this.addFilter(filter);
} catch (Exception e) {
// skip
}
}
}
}
public void writeDirectNonContext(JSONSerializer serializer, //
Object object, //
Object fieldName, //
Type fieldType, //
int features) throws IOException {
write(serializer, object, fieldName, fieldType, features);
}
public void writeAsArray(JSONSerializer serializer, //
Object object, //
Object fieldName, //
Type fieldType, //
int features) throws IOException {
write(serializer, object, fieldName, fieldType, features);
}
public void writeAsArrayNonContext(JSONSerializer serializer, //
Object object, //
Object fieldName, //
Type fieldType, //
int features) throws IOException {
write(serializer, object, fieldName, fieldType, features);
}
public void write(JSONSerializer serializer, //
Object object, //
Object fieldName, //
Type fieldType, //
int features) throws IOException {
write(serializer, object, fieldName, fieldType, features, false);
}
public void writeNoneASM(JSONSerializer serializer, //
Object object, //
Object fieldName, //
Type fieldType, //
int features) throws IOException {
write(serializer, object, fieldName, fieldType, features, false);
}
protected void write(JSONSerializer serializer, //
Object object, //
Object fieldName, //
Type fieldType, //
int features,
boolean unwrapped
) throws IOException {
SerializeWriter out = serializer.out;
if (object == null) {
out.writeNull();
return;
}
if (writeReference(serializer, object, features)) {
return;
}
final FieldSerializer[] getters;
if (out.sortField) {
getters = this.sortedGetters;
} else {
getters = this.getters;
}
SerialContext parent = serializer.context;
if (!this.beanInfo.beanType.isEnum()) {
serializer.setContext(parent, object, fieldName, this.beanInfo.features, features);
}
final boolean writeAsArray = isWriteAsArray(serializer, features);
FieldSerializer errorFieldSerializer = null;
try {
final char startSeperator = writeAsArray ? '[' : '{';
final char endSeperator = writeAsArray ? ']' : '}';
if (!unwrapped) {
out.append(startSeperator);
}
if (getters.length > 0 && out.isEnabled(SerializerFeature.PrettyFormat)) {
serializer.incrementIndent();
serializer.println();
}
boolean commaFlag = false;
if ((this.beanInfo.features & SerializerFeature.WriteClassName.mask) != 0
||(features & SerializerFeature.WriteClassName.mask) != 0
|| serializer.isWriteClassName(fieldType, object)) {
Class<?> objClass = object.getClass();
final Type type;
if (objClass != fieldType && fieldType instanceof WildcardType) {
type = TypeUtils.getClass(fieldType);
} else {
type = fieldType;
}
if (objClass != type) {
writeClassName(serializer, beanInfo.typeKey, object);
commaFlag = true;
}
}
char seperator = commaFlag ? ',' : '\0';
final boolean writeClassName = out.isEnabled(SerializerFeature.WriteClassName);
char newSeperator = this.writeBefore(serializer, object, seperator);
commaFlag = newSeperator == ',';
final boolean skipTransient = out.isEnabled(SerializerFeature.SkipTransientField);
final boolean ignoreNonFieldGetter = out.isEnabled(SerializerFeature.IgnoreNonFieldGetter);
for (int i = 0; i < getters.length; ++i) {
FieldSerializer fieldSerializer = getters[i];
Field field = fieldSerializer.fieldInfo.field;
FieldInfo fieldInfo = fieldSerializer.fieldInfo;
String fieldInfoName = fieldInfo.name;
Class<?> fieldClass = fieldInfo.fieldClass;
final boolean fieldUseSingleQuotes = SerializerFeature.isEnabled(out.features, fieldInfo.serialzeFeatures, SerializerFeature.UseSingleQuotes);
final boolean directWritePrefix = out.quoteFieldNames && !fieldUseSingleQuotes;
if (skipTransient) {
if (fieldInfo != null) {
if (fieldInfo.fieldTransient) {
continue;
}
}
}
if (ignoreNonFieldGetter) {
if (field == null) {
continue;
}
}
boolean notApply = false;
if ((!this.applyName(serializer, object, fieldInfoName)) //
|| !this.applyLabel(serializer, fieldInfo.label)) {
if (writeAsArray) {
notApply = true;
} else {
continue;
}
}
if (beanInfo.typeKey != null
&& fieldInfoName.equals(beanInfo.typeKey)
&& serializer.isWriteClassName(fieldType, object)) {
continue;
}
Object propertyValue;
if (notApply) {
propertyValue = null;
} else {
try {
propertyValue = fieldSerializer.getPropertyValueDirect(object);
} catch (InvocationTargetException ex) {
errorFieldSerializer = fieldSerializer;
if (out.isEnabled(SerializerFeature.IgnoreErrorGetter)) {
propertyValue = null;
} else {
throw ex;
}
}
}
if (!this.apply(serializer, object, fieldInfoName, propertyValue)) {
continue;
}
if (fieldClass == String.class && "trim".equals(fieldInfo.format)) {
if (propertyValue != null) {
propertyValue = ((String) propertyValue).trim();
}
}
String key = fieldInfoName;
key = this.processKey(serializer, object, key, propertyValue);
Object originalValue = propertyValue;
propertyValue = this.processValue(serializer, fieldSerializer.fieldContext, object, fieldInfoName,
propertyValue, features);
if (propertyValue == null) {
int serialzeFeatures = fieldInfo.serialzeFeatures;
if (beanInfo.jsonType != null) {
serialzeFeatures |= SerializerFeature.of(beanInfo.jsonType.serialzeFeatures());
}
// beanInfo.jsonType
if (fieldClass == Boolean.class) {
int defaultMask = SerializerFeature.WriteNullBooleanAsFalse.mask;
final int mask = defaultMask | SerializerFeature.WriteMapNullValue.mask;
if ((!writeAsArray) && (serialzeFeatures & mask) == 0 && (out.features & mask) == 0) {
continue;
} else if ((serialzeFeatures & defaultMask) != 0 || (out.features & defaultMask) != 0) {
propertyValue = false;
}
} else if (fieldClass == String.class) {
int defaultMask = SerializerFeature.WriteNullStringAsEmpty.mask;
final int mask = defaultMask | SerializerFeature.WriteMapNullValue.mask;
if ((!writeAsArray) && (serialzeFeatures & mask) == 0 && (out.features & mask) == 0) {
continue;
} else if ((serialzeFeatures & defaultMask) != 0 || (out.features & defaultMask) != 0) {
propertyValue = "";
}
} else if (Number.class.isAssignableFrom(fieldClass)) {
int defaultMask = SerializerFeature.WriteNullNumberAsZero.mask;
final int mask = defaultMask | SerializerFeature.WriteMapNullValue.mask;
if ((!writeAsArray) && (serialzeFeatures & mask) == 0 && (out.features & mask) == 0) {
continue;
} else if ((serialzeFeatures & defaultMask) != 0 || (out.features & defaultMask) != 0) {
propertyValue = 0;
}
} else if (Collection.class.isAssignableFrom(fieldClass)) {
int defaultMask = SerializerFeature.WriteNullListAsEmpty.mask;
final int mask = defaultMask | SerializerFeature.WriteMapNullValue.mask;
if ((!writeAsArray) && (serialzeFeatures & mask) == 0 && (out.features & mask) == 0) {
continue;
} else if ((serialzeFeatures & defaultMask) != 0 || (out.features & defaultMask) != 0) {
propertyValue = Collections.emptyList();
}
} else if ((!writeAsArray) && (!fieldSerializer.writeNull) && !out.isEnabled(SerializerFeature.WriteMapNullValue.mask)){
continue;
}
}
if (propertyValue != null //
&& (out.notWriteDefaultValue //
|| (fieldInfo.serialzeFeatures & SerializerFeature.NotWriteDefaultValue.mask) != 0 //
|| (beanInfo.features & SerializerFeature.NotWriteDefaultValue.mask) != 0 //
)) {
Class<?> fieldCLass = fieldInfo.fieldClass;
if (fieldCLass == byte.class && propertyValue instanceof Byte
&& ((Byte) propertyValue).byteValue() == 0) {
continue;
} else if (fieldCLass == short.class && propertyValue instanceof Short
&& ((Short) propertyValue).shortValue() == 0) {
continue;
} else if (fieldCLass == int.class && propertyValue instanceof Integer
&& ((Integer) propertyValue).intValue() == 0) {
continue;
} else if (fieldCLass == long.class && propertyValue instanceof Long
&& ((Long) propertyValue).longValue() == 0L) {
continue;
} else if (fieldCLass == float.class && propertyValue instanceof Float
&& ((Float) propertyValue).floatValue() == 0F) {
continue;
} else if (fieldCLass == double.class && propertyValue instanceof Double
&& ((Double) propertyValue).doubleValue() == 0D) {
continue;
} else if (fieldCLass == boolean.class && propertyValue instanceof Boolean
&& !((Boolean) propertyValue).booleanValue()) {
continue;
}
}
if (commaFlag) {
if (fieldInfo.unwrapped
&& propertyValue instanceof Map
&& ((Map) propertyValue).size() == 0) {
continue;
}
out.write(',');
if (out.isEnabled(SerializerFeature.PrettyFormat)) {
serializer.println();
}
}
if (key != fieldInfoName) {
if (!writeAsArray) {
out.writeFieldName(key, true);
}
serializer.write(propertyValue);
} else if (originalValue != propertyValue) {
if (!writeAsArray) {
fieldSerializer.writePrefix(serializer);
}
serializer.write(propertyValue);
} else {
if (!writeAsArray) {
boolean isMap = Map.class.isAssignableFrom(fieldClass);
boolean isJavaBean = !fieldClass.isPrimitive() && !fieldClass.getName().startsWith("java.") || fieldClass == Object.class;
if (writeClassName || !fieldInfo.unwrapped || !(isMap || isJavaBean)) {
if (directWritePrefix) {
out.write(fieldInfo.name_chars, 0, fieldInfo.name_chars.length);
} else {
fieldSerializer.writePrefix(serializer);
}
}
}
if (!writeAsArray) {
JSONField fieldAnnotation = fieldInfo.getAnnotation();
if (fieldClass == String.class && (fieldAnnotation == null || fieldAnnotation.serializeUsing() == Void.class)) {
if (propertyValue == null) {
if ((out.features & SerializerFeature.WriteNullStringAsEmpty.mask) != 0
|| (fieldSerializer.features & SerializerFeature.WriteNullStringAsEmpty.mask) != 0) {
out.writeString("");
} else {
out.writeNull();
}
} else {
String propertyValueString = (String) propertyValue;
if (fieldUseSingleQuotes) {
out.writeStringWithSingleQuote(propertyValueString);
} else {
out.writeStringWithDoubleQuote(propertyValueString, (char) 0);
}
}
} else {
if (fieldInfo.unwrapped
&& propertyValue instanceof Map
&& ((Map) propertyValue).size() == 0) {
commaFlag = false;
continue;
}
fieldSerializer.writeValue(serializer, propertyValue);
}
} else {
fieldSerializer.writeValue(serializer, propertyValue);
}
}
boolean fieldUnwrappedNull = false;
if (fieldInfo.unwrapped
&& propertyValue instanceof Map) {
Map map = ((Map) propertyValue);
if (map.size() == 0) {
fieldUnwrappedNull = true;
} else if (!serializer.isEnabled(SerializerFeature.WriteMapNullValue)){
boolean hasNotNull = false;
for (Object value : map.values()) {
if (value != null) {
hasNotNull = true;
break;
}
}
if (!hasNotNull) {
fieldUnwrappedNull = true;
}
}
}
if (!fieldUnwrappedNull) {
commaFlag = true;
}
}
this.writeAfter(serializer, object, commaFlag ? ',' : '\0');
if (getters.length > 0 && out.isEnabled(SerializerFeature.PrettyFormat)) {
serializer.decrementIdent();
serializer.println();
}
if (!unwrapped) {
out.append(endSeperator);
}
} catch (Exception e) {
String errorMessage = "write javaBean error, fastjson version " + JSON.VERSION;
if (object != null) {
errorMessage += ", class " + object.getClass().getName();
}
if (fieldName != null) {
errorMessage += ", fieldName : " + fieldName;
} else if (errorFieldSerializer != null && errorFieldSerializer.fieldInfo != null) {
FieldInfo fieldInfo = errorFieldSerializer.fieldInfo;
if (fieldInfo.method != null) {
errorMessage += ", method : " + fieldInfo.method.getName();
} else {
errorMessage += ", fieldName : " + errorFieldSerializer.fieldInfo.name;
}
}
if (e.getMessage() != null) {
errorMessage += (", " + e.getMessage());
}
Throwable cause = null;
if (e instanceof InvocationTargetException) {
cause = e.getCause();
}
if (cause == null) {
cause = e;
}
throw new JSONException(errorMessage, cause);
} finally {
serializer.context = parent;
}
}
protected void writeClassName(JSONSerializer serializer, String typeKey, Object object) {
if (typeKey == null) {
typeKey = serializer.config.typeKey;
}
serializer.out.writeFieldName(typeKey, false);
String typeName = this.beanInfo.typeName;
if (typeName == null) {
Class<?> clazz = object.getClass();
if (TypeUtils.isProxy(clazz)) {
clazz = clazz.getSuperclass();
}
typeName = clazz.getName();
}
serializer.write(typeName);
}
public boolean writeReference(JSONSerializer serializer, Object object, int fieldFeatures) {
SerialContext context = serializer.context;
int mask = SerializerFeature.DisableCircularReferenceDetect.mask;
if (context == null || (context.features & mask) != 0 || (fieldFeatures & mask) != 0) {
return false;
}
if (serializer.references != null && serializer.references.containsKey(object)) {
serializer.writeReference(object);
return true;
} else {
return false;
}
}
protected boolean isWriteAsArray(JSONSerializer serializer) {
return isWriteAsArray(serializer, 0);
}
protected boolean isWriteAsArray(JSONSerializer serializer, int fieldFeatrues) {
final int mask = SerializerFeature.BeanToArray.mask;
return (beanInfo.features & mask) != 0 //
|| serializer.out.beanToArray //
|| (fieldFeatrues & mask) != 0;
}
public Object getFieldValue(Object object, String key) {
FieldSerializer fieldDeser = getFieldSerializer(key);
if (fieldDeser == null) {
throw new JSONException("field not found. " + key);
}
try {
return fieldDeser.getPropertyValue(object);
} catch (InvocationTargetException ex) {
throw new JSONException("getFieldValue error." + key, ex);
} catch (IllegalAccessException ex) {
throw new JSONException("getFieldValue error." + key, ex);
}
}
public Object getFieldValue(Object object, String key, long keyHash, boolean throwFieldNotFoundException) {
FieldSerializer fieldDeser = getFieldSerializer(keyHash);
if (fieldDeser == null) {
if (throwFieldNotFoundException) {
throw new JSONException("field not found. " + key);
}
return null;
}
try {
return fieldDeser.getPropertyValue(object);
} catch (InvocationTargetException ex) {
throw new JSONException("getFieldValue error." + key, ex);
} catch (IllegalAccessException ex) {
throw new JSONException("getFieldValue error." + key, ex);
}
}
public FieldSerializer getFieldSerializer(String key) {
if (key == null) {
return null;
}
int low = 0;
int high = sortedGetters.length - 1;
while (low <= high) {
int mid = (low + high) >>> 1;
String fieldName = sortedGetters[mid].fieldInfo.name;
int cmp = fieldName.compareTo(key);
if (cmp < 0) {
low = mid + 1;
} else if (cmp > 0) {
high = mid - 1;
} else {
return sortedGetters[mid]; // key found
}
}
return null; // key not found.
}
public FieldSerializer getFieldSerializer(long hash) {
PropertyNamingStrategy[] namingStrategies = null;
if (this.hashArray == null) {
namingStrategies = PropertyNamingStrategy.values();
long[] hashArray = new long[sortedGetters.length * namingStrategies.length];
int index = 0;
for (int i = 0; i < sortedGetters.length; i++) {
String name = sortedGetters[i].fieldInfo.name;
hashArray[index++] = TypeUtils.fnv1a_64(name);
for (int j = 0; j < namingStrategies.length; j++) {
String name_t = namingStrategies[j].translate(name);
if (name.equals(name_t)) {
continue;
}
hashArray[index++] = TypeUtils.fnv1a_64(name_t);
}
}
Arrays.sort(hashArray, 0, index);
this.hashArray = new long[index];
System.arraycopy(hashArray, 0, this.hashArray, 0, index);
}
int pos = Arrays.binarySearch(hashArray, hash);
if (pos < 0) {
return null;
}
if (hashArrayMapping == null) {
if (namingStrategies == null) {
namingStrategies = PropertyNamingStrategy.values();
}
short[] mapping = new short[hashArray.length];
Arrays.fill(mapping, (short) -1);
for (int i = 0; i < sortedGetters.length; i++) {
String name = sortedGetters[i].fieldInfo.name;
int p = Arrays.binarySearch(hashArray
, TypeUtils.fnv1a_64(name));
if (p >= 0) {
mapping[p] = (short) i;
}
for (int j = 0; j < namingStrategies.length; j++) {
String name_t = namingStrategies[j].translate(name);
if (name.equals(name_t)) {
continue;
}
int p_t = Arrays.binarySearch(hashArray
, TypeUtils.fnv1a_64(name_t));
if (p_t >= 0) {
mapping[p_t] = (short) i;
}
}
}
hashArrayMapping = mapping;
}
int getterIndex = hashArrayMapping[pos];
if (getterIndex != -1) {
return sortedGetters[getterIndex];
}
return null; // key not found.
}
public List<Object> getFieldValues(Object object) throws Exception {
List<Object> fieldValues = new ArrayList<Object>(sortedGetters.length);
for (FieldSerializer getter : sortedGetters) {
fieldValues.add(getter.getPropertyValue(object));
}
return fieldValues;
}
// for jsonpath deepSet
public List<Object> getObjectFieldValues(Object object) throws Exception {
List<Object> fieldValues = new ArrayList<Object>(sortedGetters.length);
for (FieldSerializer getter : sortedGetters) {
Class fieldClass = getter.fieldInfo.fieldClass;
if (fieldClass.isPrimitive()) {
continue;
}
if (fieldClass.getName().startsWith("java.lang.")) {
continue;
}
fieldValues.add(getter.getPropertyValue(object));
}
return fieldValues;
}
public int getSize(Object object) throws Exception {
int size = 0;
for (FieldSerializer getter : sortedGetters) {
Object value = getter.getPropertyValueDirect(object);
if (value != null) {
size ++;
}
}
return size;
}
/**
* Get field names of not null fields. Keep the same logic as getSize.
*
* @param object the object to be checked
* @return field name set
* @throws Exception
* @see #getSize(Object)
*/
public Set<String> getFieldNames(Object object) throws Exception {
Set<String> fieldNames = new HashSet<String>();
for (FieldSerializer getter : sortedGetters) {
Object value = getter.getPropertyValueDirect(object);
if (value != null) {
fieldNames.add(getter.fieldInfo.name);
}
}
return fieldNames;
}
public Map<String, Object> getFieldValuesMap(Object object) throws Exception {
Map<String, Object> map = new LinkedHashMap<String, Object>(sortedGetters.length);
boolean skipTransient = true;
FieldInfo fieldInfo = null;
for (FieldSerializer getter : sortedGetters) {
skipTransient = SerializerFeature.isEnabled(getter.features, SerializerFeature.SkipTransientField);
fieldInfo = getter.fieldInfo;
if (skipTransient && fieldInfo != null && fieldInfo.fieldTransient) {
continue;
}
map.put(getter.fieldInfo.name, getter.getPropertyValue(object));
}
return map;
}
protected BeanContext getBeanContext(int orinal) {
return sortedGetters[orinal].fieldContext;
}
protected Type getFieldType(int ordinal) {
return sortedGetters[ordinal].fieldInfo.fieldType;
}
protected char writeBefore(JSONSerializer jsonBeanDeser, //
Object object, char seperator) {
if (jsonBeanDeser.beforeFilters != null) {
for (BeforeFilter beforeFilter : jsonBeanDeser.beforeFilters) {
seperator = beforeFilter.writeBefore(jsonBeanDeser, object, seperator);
}
}
if (this.beforeFilters != null) {
for (BeforeFilter beforeFilter : this.beforeFilters) {
seperator = beforeFilter.writeBefore(jsonBeanDeser, object, seperator);
}
}
return seperator;
}
protected char writeAfter(JSONSerializer jsonBeanDeser, //
Object object, char seperator) {
if (jsonBeanDeser.afterFilters != null) {
for (AfterFilter afterFilter : jsonBeanDeser.afterFilters) {
seperator = afterFilter.writeAfter(jsonBeanDeser, object, seperator);
}
}
if (this.afterFilters != null) {
for (AfterFilter afterFilter : this.afterFilters) {
seperator = afterFilter.writeAfter(jsonBeanDeser, object, seperator);
}
}
return seperator;
}
protected boolean applyLabel(JSONSerializer jsonBeanDeser, String label) {
if (jsonBeanDeser.labelFilters != null) {
for (LabelFilter propertyFilter : jsonBeanDeser.labelFilters) {
if (!propertyFilter.apply(label)) {
return false;
}
}
}
if (this.labelFilters != null) {
for (LabelFilter propertyFilter : this.labelFilters) {
if (!propertyFilter.apply(label)) {
return false;
}
}
}
return true;
}
}
| src/main/java/com/alibaba/fastjson/serializer/JavaBeanSerializer.java | /*
* Copyright 1999-2018 Alibaba Group.
*
* 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.fastjson.serializer;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Type;
import java.lang.reflect.WildcardType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.annotation.JSONField;
import com.alibaba.fastjson.util.FieldInfo;
import com.alibaba.fastjson.util.TypeUtils;
/**
* @author wenshao[[email protected]]
*/
public class JavaBeanSerializer extends SerializeFilterable implements ObjectSerializer {
// serializers
protected final FieldSerializer[] getters;
protected final FieldSerializer[] sortedGetters;
protected SerializeBeanInfo beanInfo;
private transient volatile long[] hashArray;
private transient volatile short[] hashArrayMapping;
public JavaBeanSerializer(Class<?> beanType){
this(beanType, (Map<String, String>) null);
}
public JavaBeanSerializer(Class<?> beanType, String... aliasList){
this(beanType, createAliasMap(aliasList));
}
static Map<String, String> createAliasMap(String... aliasList) {
Map<String, String> aliasMap = new HashMap<String, String>();
for (String alias : aliasList) {
aliasMap.put(alias, alias);
}
return aliasMap;
}
/**
* @since 1.2.42
*/
public Class<?> getType() {
return beanInfo.beanType;
}
public JavaBeanSerializer(Class<?> beanType, Map<String, String> aliasMap){
this(TypeUtils.buildBeanInfo(beanType, aliasMap, null));
}
public JavaBeanSerializer(SerializeBeanInfo beanInfo) {
this.beanInfo = beanInfo;
sortedGetters = new FieldSerializer[beanInfo.sortedFields.length];
for (int i = 0; i < sortedGetters.length; ++i) {
sortedGetters[i] = new FieldSerializer(beanInfo.beanType, beanInfo.sortedFields[i]);
}
if (beanInfo.fields == beanInfo.sortedFields) {
getters = sortedGetters;
} else {
getters = new FieldSerializer[beanInfo.fields.length];
boolean hashNotMatch = false;
for (int i = 0; i < getters.length; ++i) {
FieldSerializer fieldSerializer = getFieldSerializer(beanInfo.fields[i].name);
if (fieldSerializer == null) {
hashNotMatch = true;
break;
}
getters[i] = fieldSerializer;
}
if (hashNotMatch) {
System.arraycopy(sortedGetters, 0, getters, 0, sortedGetters.length);
}
}
if (beanInfo.jsonType != null) {
for (Class<? extends SerializeFilter> filterClass : beanInfo.jsonType.serialzeFilters()) {
try {
SerializeFilter filter = filterClass.getConstructor().newInstance();
this.addFilter(filter);
} catch (Exception e) {
// skip
}
}
}
if (beanInfo.jsonType != null) {
for (Class<? extends SerializeFilter> filterClass : beanInfo.jsonType.serialzeFilters()) {
try {
SerializeFilter filter = filterClass.getConstructor().newInstance();
this.addFilter(filter);
} catch (Exception e) {
// skip
}
}
}
}
public void writeDirectNonContext(JSONSerializer serializer, //
Object object, //
Object fieldName, //
Type fieldType, //
int features) throws IOException {
write(serializer, object, fieldName, fieldType, features);
}
public void writeAsArray(JSONSerializer serializer, //
Object object, //
Object fieldName, //
Type fieldType, //
int features) throws IOException {
write(serializer, object, fieldName, fieldType, features);
}
public void writeAsArrayNonContext(JSONSerializer serializer, //
Object object, //
Object fieldName, //
Type fieldType, //
int features) throws IOException {
write(serializer, object, fieldName, fieldType, features);
}
public void write(JSONSerializer serializer, //
Object object, //
Object fieldName, //
Type fieldType, //
int features) throws IOException {
write(serializer, object, fieldName, fieldType, features, false);
}
public void writeNoneASM(JSONSerializer serializer, //
Object object, //
Object fieldName, //
Type fieldType, //
int features) throws IOException {
write(serializer, object, fieldName, fieldType, features, false);
}
protected void write(JSONSerializer serializer, //
Object object, //
Object fieldName, //
Type fieldType, //
int features,
boolean unwrapped
) throws IOException {
SerializeWriter out = serializer.out;
if (object == null) {
out.writeNull();
return;
}
if (writeReference(serializer, object, features)) {
return;
}
final FieldSerializer[] getters;
if (out.sortField) {
getters = this.sortedGetters;
} else {
getters = this.getters;
}
SerialContext parent = serializer.context;
if (!this.beanInfo.beanType.isEnum()) {
serializer.setContext(parent, object, fieldName, this.beanInfo.features, features);
}
final boolean writeAsArray = isWriteAsArray(serializer, features);
FieldSerializer errorFieldSerializer = null;
try {
final char startSeperator = writeAsArray ? '[' : '{';
final char endSeperator = writeAsArray ? ']' : '}';
if (!unwrapped) {
out.append(startSeperator);
}
if (getters.length > 0 && out.isEnabled(SerializerFeature.PrettyFormat)) {
serializer.incrementIndent();
serializer.println();
}
boolean commaFlag = false;
if ((this.beanInfo.features & SerializerFeature.WriteClassName.mask) != 0
||(features & SerializerFeature.WriteClassName.mask) != 0
|| serializer.isWriteClassName(fieldType, object)) {
Class<?> objClass = object.getClass();
final Type type;
if (objClass != fieldType && fieldType instanceof WildcardType) {
type = TypeUtils.getClass(fieldType);
} else {
type = fieldType;
}
if (objClass != type) {
writeClassName(serializer, beanInfo.typeKey, object);
commaFlag = true;
}
}
char seperator = commaFlag ? ',' : '\0';
final boolean writeClassName = out.isEnabled(SerializerFeature.WriteClassName);
char newSeperator = this.writeBefore(serializer, object, seperator);
commaFlag = newSeperator == ',';
final boolean skipTransient = out.isEnabled(SerializerFeature.SkipTransientField);
final boolean ignoreNonFieldGetter = out.isEnabled(SerializerFeature.IgnoreNonFieldGetter);
for (int i = 0; i < getters.length; ++i) {
FieldSerializer fieldSerializer = getters[i];
Field field = fieldSerializer.fieldInfo.field;
FieldInfo fieldInfo = fieldSerializer.fieldInfo;
String fieldInfoName = fieldInfo.name;
Class<?> fieldClass = fieldInfo.fieldClass;
final boolean fieldUseSingleQuotes = SerializerFeature.isEnabled(out.features, fieldInfo.serialzeFeatures, SerializerFeature.UseSingleQuotes);
final boolean directWritePrefix = out.quoteFieldNames && !fieldUseSingleQuotes;
if (skipTransient) {
if (fieldInfo != null) {
if (fieldInfo.fieldTransient) {
continue;
}
}
}
if (ignoreNonFieldGetter) {
if (field == null) {
continue;
}
}
boolean notApply = false;
if ((!this.applyName(serializer, object, fieldInfoName)) //
|| !this.applyLabel(serializer, fieldInfo.label)) {
if (writeAsArray) {
notApply = true;
} else {
continue;
}
}
if (beanInfo.typeKey != null
&& fieldInfoName.equals(beanInfo.typeKey)
&& serializer.isWriteClassName(fieldType, object)) {
continue;
}
Object propertyValue;
if (notApply) {
propertyValue = null;
} else {
try {
propertyValue = fieldSerializer.getPropertyValueDirect(object);
} catch (InvocationTargetException ex) {
errorFieldSerializer = fieldSerializer;
if (out.isEnabled(SerializerFeature.IgnoreErrorGetter)) {
propertyValue = null;
} else {
throw ex;
}
}
}
if (!this.apply(serializer, object, fieldInfoName, propertyValue)) {
continue;
}
if (fieldClass == String.class && "trim".equals(fieldInfo.format)) {
if (propertyValue != null) {
propertyValue = ((String) propertyValue).trim();
}
}
String key = fieldInfoName;
key = this.processKey(serializer, object, key, propertyValue);
Object originalValue = propertyValue;
propertyValue = this.processValue(serializer, fieldSerializer.fieldContext, object, fieldInfoName,
propertyValue, features);
if (propertyValue == null) {
int serialzeFeatures = fieldInfo.serialzeFeatures;
if (beanInfo.jsonType != null) {
serialzeFeatures |= SerializerFeature.of(beanInfo.jsonType.serialzeFeatures());
}
// beanInfo.jsonType
if (fieldClass == Boolean.class) {
int defaultMask = SerializerFeature.WriteNullBooleanAsFalse.mask;
final int mask = defaultMask | SerializerFeature.WriteMapNullValue.mask;
if ((!writeAsArray) && (serialzeFeatures & mask) == 0 && (out.features & mask) == 0) {
continue;
} else if ((serialzeFeatures & defaultMask) != 0 || (out.features & defaultMask) != 0) {
propertyValue = false;
}
} else if (fieldClass == String.class) {
int defaultMask = SerializerFeature.WriteNullStringAsEmpty.mask;
final int mask = defaultMask | SerializerFeature.WriteMapNullValue.mask;
if ((!writeAsArray) && (serialzeFeatures & mask) == 0 && (out.features & mask) == 0) {
continue;
} else if ((serialzeFeatures & defaultMask) != 0 || (out.features & defaultMask) != 0) {
propertyValue = "";
}
} else if (Number.class.isAssignableFrom(fieldClass)) {
int defaultMask = SerializerFeature.WriteNullNumberAsZero.mask;
final int mask = defaultMask | SerializerFeature.WriteMapNullValue.mask;
if ((!writeAsArray) && (serialzeFeatures & mask) == 0 && (out.features & mask) == 0) {
continue;
} else if ((serialzeFeatures & defaultMask) != 0 || (out.features & defaultMask) != 0) {
propertyValue = 0;
}
} else if (Collection.class.isAssignableFrom(fieldClass)) {
int defaultMask = SerializerFeature.WriteNullListAsEmpty.mask;
final int mask = defaultMask | SerializerFeature.WriteMapNullValue.mask;
if ((!writeAsArray) && (serialzeFeatures & mask) == 0 && (out.features & mask) == 0) {
continue;
} else if ((serialzeFeatures & defaultMask) != 0 || (out.features & defaultMask) != 0) {
propertyValue = Collections.emptyList();
}
} else if ((!writeAsArray) && (!fieldSerializer.writeNull) && !out.isEnabled(SerializerFeature.WriteMapNullValue.mask)){
continue;
}
}
if (propertyValue != null //
&& (out.notWriteDefaultValue //
|| (fieldInfo.serialzeFeatures & SerializerFeature.NotWriteDefaultValue.mask) != 0 //
|| (beanInfo.features & SerializerFeature.NotWriteDefaultValue.mask) != 0 //
)) {
Class<?> fieldCLass = fieldInfo.fieldClass;
if (fieldCLass == byte.class && propertyValue instanceof Byte
&& ((Byte) propertyValue).byteValue() == 0) {
continue;
} else if (fieldCLass == short.class && propertyValue instanceof Short
&& ((Short) propertyValue).shortValue() == 0) {
continue;
} else if (fieldCLass == int.class && propertyValue instanceof Integer
&& ((Integer) propertyValue).intValue() == 0) {
continue;
} else if (fieldCLass == long.class && propertyValue instanceof Long
&& ((Long) propertyValue).longValue() == 0L) {
continue;
} else if (fieldCLass == float.class && propertyValue instanceof Float
&& ((Float) propertyValue).floatValue() == 0F) {
continue;
} else if (fieldCLass == double.class && propertyValue instanceof Double
&& ((Double) propertyValue).doubleValue() == 0D) {
continue;
} else if (fieldCLass == boolean.class && propertyValue instanceof Boolean
&& !((Boolean) propertyValue).booleanValue()) {
continue;
}
}
if (commaFlag) {
if (fieldInfo.unwrapped
&& propertyValue instanceof Map
&& ((Map) propertyValue).size() == 0) {
continue;
}
out.write(',');
if (out.isEnabled(SerializerFeature.PrettyFormat)) {
serializer.println();
}
}
if (key != fieldInfoName) {
if (!writeAsArray) {
out.writeFieldName(key, true);
}
serializer.write(propertyValue);
} else if (originalValue != propertyValue) {
if (!writeAsArray) {
fieldSerializer.writePrefix(serializer);
}
serializer.write(propertyValue);
} else {
if (!writeAsArray) {
if (writeClassName || !fieldInfo.unwrapped) {
if (directWritePrefix) {
out.write(fieldInfo.name_chars, 0, fieldInfo.name_chars.length);
} else {
fieldSerializer.writePrefix(serializer);
}
}
}
if (!writeAsArray) {
JSONField fieldAnnotation = fieldInfo.getAnnotation();
if (fieldClass == String.class && (fieldAnnotation == null || fieldAnnotation.serializeUsing() == Void.class)) {
if (propertyValue == null) {
if ((out.features & SerializerFeature.WriteNullStringAsEmpty.mask) != 0
|| (fieldSerializer.features & SerializerFeature.WriteNullStringAsEmpty.mask) != 0) {
out.writeString("");
} else {
out.writeNull();
}
} else {
String propertyValueString = (String) propertyValue;
if (fieldUseSingleQuotes) {
out.writeStringWithSingleQuote(propertyValueString);
} else {
out.writeStringWithDoubleQuote(propertyValueString, (char) 0);
}
}
} else {
if (fieldInfo.unwrapped
&& propertyValue instanceof Map
&& ((Map) propertyValue).size() == 0) {
commaFlag = false;
continue;
}
fieldSerializer.writeValue(serializer, propertyValue);
}
} else {
fieldSerializer.writeValue(serializer, propertyValue);
}
}
boolean fieldUnwrappedNull = false;
if (fieldInfo.unwrapped
&& propertyValue instanceof Map) {
Map map = ((Map) propertyValue);
if (map.size() == 0) {
fieldUnwrappedNull = true;
} else if (!serializer.isEnabled(SerializerFeature.WriteMapNullValue)){
boolean hasNotNull = false;
for (Object value : map.values()) {
if (value != null) {
hasNotNull = true;
break;
}
}
if (!hasNotNull) {
fieldUnwrappedNull = true;
}
}
}
if (!fieldUnwrappedNull) {
commaFlag = true;
}
}
this.writeAfter(serializer, object, commaFlag ? ',' : '\0');
if (getters.length > 0 && out.isEnabled(SerializerFeature.PrettyFormat)) {
serializer.decrementIdent();
serializer.println();
}
if (!unwrapped) {
out.append(endSeperator);
}
} catch (Exception e) {
String errorMessage = "write javaBean error, fastjson version " + JSON.VERSION;
if (object != null) {
errorMessage += ", class " + object.getClass().getName();
}
if (fieldName != null) {
errorMessage += ", fieldName : " + fieldName;
} else if (errorFieldSerializer != null && errorFieldSerializer.fieldInfo != null) {
FieldInfo fieldInfo = errorFieldSerializer.fieldInfo;
if (fieldInfo.method != null) {
errorMessage += ", method : " + fieldInfo.method.getName();
} else {
errorMessage += ", fieldName : " + errorFieldSerializer.fieldInfo.name;
}
}
if (e.getMessage() != null) {
errorMessage += (", " + e.getMessage());
}
Throwable cause = null;
if (e instanceof InvocationTargetException) {
cause = e.getCause();
}
if (cause == null) {
cause = e;
}
throw new JSONException(errorMessage, cause);
} finally {
serializer.context = parent;
}
}
protected void writeClassName(JSONSerializer serializer, String typeKey, Object object) {
if (typeKey == null) {
typeKey = serializer.config.typeKey;
}
serializer.out.writeFieldName(typeKey, false);
String typeName = this.beanInfo.typeName;
if (typeName == null) {
Class<?> clazz = object.getClass();
if (TypeUtils.isProxy(clazz)) {
clazz = clazz.getSuperclass();
}
typeName = clazz.getName();
}
serializer.write(typeName);
}
public boolean writeReference(JSONSerializer serializer, Object object, int fieldFeatures) {
SerialContext context = serializer.context;
int mask = SerializerFeature.DisableCircularReferenceDetect.mask;
if (context == null || (context.features & mask) != 0 || (fieldFeatures & mask) != 0) {
return false;
}
if (serializer.references != null && serializer.references.containsKey(object)) {
serializer.writeReference(object);
return true;
} else {
return false;
}
}
protected boolean isWriteAsArray(JSONSerializer serializer) {
return isWriteAsArray(serializer, 0);
}
protected boolean isWriteAsArray(JSONSerializer serializer, int fieldFeatrues) {
final int mask = SerializerFeature.BeanToArray.mask;
return (beanInfo.features & mask) != 0 //
|| serializer.out.beanToArray //
|| (fieldFeatrues & mask) != 0;
}
public Object getFieldValue(Object object, String key) {
FieldSerializer fieldDeser = getFieldSerializer(key);
if (fieldDeser == null) {
throw new JSONException("field not found. " + key);
}
try {
return fieldDeser.getPropertyValue(object);
} catch (InvocationTargetException ex) {
throw new JSONException("getFieldValue error." + key, ex);
} catch (IllegalAccessException ex) {
throw new JSONException("getFieldValue error." + key, ex);
}
}
public Object getFieldValue(Object object, String key, long keyHash, boolean throwFieldNotFoundException) {
FieldSerializer fieldDeser = getFieldSerializer(keyHash);
if (fieldDeser == null) {
if (throwFieldNotFoundException) {
throw new JSONException("field not found. " + key);
}
return null;
}
try {
return fieldDeser.getPropertyValue(object);
} catch (InvocationTargetException ex) {
throw new JSONException("getFieldValue error." + key, ex);
} catch (IllegalAccessException ex) {
throw new JSONException("getFieldValue error." + key, ex);
}
}
public FieldSerializer getFieldSerializer(String key) {
if (key == null) {
return null;
}
int low = 0;
int high = sortedGetters.length - 1;
while (low <= high) {
int mid = (low + high) >>> 1;
String fieldName = sortedGetters[mid].fieldInfo.name;
int cmp = fieldName.compareTo(key);
if (cmp < 0) {
low = mid + 1;
} else if (cmp > 0) {
high = mid - 1;
} else {
return sortedGetters[mid]; // key found
}
}
return null; // key not found.
}
public FieldSerializer getFieldSerializer(long hash) {
PropertyNamingStrategy[] namingStrategies = null;
if (this.hashArray == null) {
namingStrategies = PropertyNamingStrategy.values();
long[] hashArray = new long[sortedGetters.length * namingStrategies.length];
int index = 0;
for (int i = 0; i < sortedGetters.length; i++) {
String name = sortedGetters[i].fieldInfo.name;
hashArray[index++] = TypeUtils.fnv1a_64(name);
for (int j = 0; j < namingStrategies.length; j++) {
String name_t = namingStrategies[j].translate(name);
if (name.equals(name_t)) {
continue;
}
hashArray[index++] = TypeUtils.fnv1a_64(name_t);
}
}
Arrays.sort(hashArray, 0, index);
this.hashArray = new long[index];
System.arraycopy(hashArray, 0, this.hashArray, 0, index);
}
int pos = Arrays.binarySearch(hashArray, hash);
if (pos < 0) {
return null;
}
if (hashArrayMapping == null) {
if (namingStrategies == null) {
namingStrategies = PropertyNamingStrategy.values();
}
short[] mapping = new short[hashArray.length];
Arrays.fill(mapping, (short) -1);
for (int i = 0; i < sortedGetters.length; i++) {
String name = sortedGetters[i].fieldInfo.name;
int p = Arrays.binarySearch(hashArray
, TypeUtils.fnv1a_64(name));
if (p >= 0) {
mapping[p] = (short) i;
}
for (int j = 0; j < namingStrategies.length; j++) {
String name_t = namingStrategies[j].translate(name);
if (name.equals(name_t)) {
continue;
}
int p_t = Arrays.binarySearch(hashArray
, TypeUtils.fnv1a_64(name_t));
if (p_t >= 0) {
mapping[p_t] = (short) i;
}
}
}
hashArrayMapping = mapping;
}
int getterIndex = hashArrayMapping[pos];
if (getterIndex != -1) {
return sortedGetters[getterIndex];
}
return null; // key not found.
}
public List<Object> getFieldValues(Object object) throws Exception {
List<Object> fieldValues = new ArrayList<Object>(sortedGetters.length);
for (FieldSerializer getter : sortedGetters) {
fieldValues.add(getter.getPropertyValue(object));
}
return fieldValues;
}
// for jsonpath deepSet
public List<Object> getObjectFieldValues(Object object) throws Exception {
List<Object> fieldValues = new ArrayList<Object>(sortedGetters.length);
for (FieldSerializer getter : sortedGetters) {
Class fieldClass = getter.fieldInfo.fieldClass;
if (fieldClass.isPrimitive()) {
continue;
}
if (fieldClass.getName().startsWith("java.lang.")) {
continue;
}
fieldValues.add(getter.getPropertyValue(object));
}
return fieldValues;
}
public int getSize(Object object) throws Exception {
int size = 0;
for (FieldSerializer getter : sortedGetters) {
Object value = getter.getPropertyValueDirect(object);
if (value != null) {
size ++;
}
}
return size;
}
/**
* Get field names of not null fields. Keep the same logic as getSize.
*
* @param object the object to be checked
* @return field name set
* @throws Exception
* @see #getSize(Object)
*/
public Set<String> getFieldNames(Object object) throws Exception {
Set<String> fieldNames = new HashSet<String>();
for (FieldSerializer getter : sortedGetters) {
Object value = getter.getPropertyValueDirect(object);
if (value != null) {
fieldNames.add(getter.fieldInfo.name);
}
}
return fieldNames;
}
public Map<String, Object> getFieldValuesMap(Object object) throws Exception {
Map<String, Object> map = new LinkedHashMap<String, Object>(sortedGetters.length);
boolean skipTransient = true;
FieldInfo fieldInfo = null;
for (FieldSerializer getter : sortedGetters) {
skipTransient = SerializerFeature.isEnabled(getter.features, SerializerFeature.SkipTransientField);
fieldInfo = getter.fieldInfo;
if (skipTransient && fieldInfo != null && fieldInfo.fieldTransient) {
continue;
}
map.put(getter.fieldInfo.name, getter.getPropertyValue(object));
}
return map;
}
protected BeanContext getBeanContext(int orinal) {
return sortedGetters[orinal].fieldContext;
}
protected Type getFieldType(int ordinal) {
return sortedGetters[ordinal].fieldInfo.fieldType;
}
protected char writeBefore(JSONSerializer jsonBeanDeser, //
Object object, char seperator) {
if (jsonBeanDeser.beforeFilters != null) {
for (BeforeFilter beforeFilter : jsonBeanDeser.beforeFilters) {
seperator = beforeFilter.writeBefore(jsonBeanDeser, object, seperator);
}
}
if (this.beforeFilters != null) {
for (BeforeFilter beforeFilter : this.beforeFilters) {
seperator = beforeFilter.writeBefore(jsonBeanDeser, object, seperator);
}
}
return seperator;
}
protected char writeAfter(JSONSerializer jsonBeanDeser, //
Object object, char seperator) {
if (jsonBeanDeser.afterFilters != null) {
for (AfterFilter afterFilter : jsonBeanDeser.afterFilters) {
seperator = afterFilter.writeAfter(jsonBeanDeser, object, seperator);
}
}
if (this.afterFilters != null) {
for (AfterFilter afterFilter : this.afterFilters) {
seperator = afterFilter.writeAfter(jsonBeanDeser, object, seperator);
}
}
return seperator;
}
protected boolean applyLabel(JSONSerializer jsonBeanDeser, String label) {
if (jsonBeanDeser.labelFilters != null) {
for (LabelFilter propertyFilter : jsonBeanDeser.labelFilters) {
if (!propertyFilter.apply(label)) {
return false;
}
}
}
if (this.labelFilters != null) {
for (LabelFilter propertyFilter : this.labelFilters) {
if (!propertyFilter.apply(label)) {
return false;
}
}
}
return true;
}
}
| bug fixed for unwrapped_lost_name
| src/main/java/com/alibaba/fastjson/serializer/JavaBeanSerializer.java | bug fixed for unwrapped_lost_name | <ide><path>rc/main/java/com/alibaba/fastjson/serializer/JavaBeanSerializer.java
<ide> serializer.write(propertyValue);
<ide> } else {
<ide> if (!writeAsArray) {
<del> if (writeClassName || !fieldInfo.unwrapped) {
<add> boolean isMap = Map.class.isAssignableFrom(fieldClass);
<add> boolean isJavaBean = !fieldClass.isPrimitive() && !fieldClass.getName().startsWith("java.") || fieldClass == Object.class;
<add> if (writeClassName || !fieldInfo.unwrapped || !(isMap || isJavaBean)) {
<ide> if (directWritePrefix) {
<ide> out.write(fieldInfo.name_chars, 0, fieldInfo.name_chars.length);
<ide> } else { |
|
Java | apache-2.0 | c93e949822222b3ee94a5b702d0af0c8ef2d51e3 | 0 | kickstarter/android-oss,kickstarter/android-oss,kickstarter/android-oss,kickstarter/android-oss | package com.kickstarter.libs;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Pair;
import com.jakewharton.rxbinding.support.v7.widget.RxRecyclerView;
import rx.Subscription;
import rx.functions.Action0;
public final class Paginator {
@NonNull private final RecyclerView recyclerView;
@NonNull private final Action0 nextPage;
private Subscription subscription = null;
public Paginator(@NonNull final RecyclerView recyclerView, @NonNull final Action0 nextPage) {
this.recyclerView = recyclerView;
this.nextPage = nextPage;
start();
}
public void start() {
stop();
subscription = RxRecyclerView.scrollEvents(recyclerView)
.map(__ -> recyclerView.getLayoutManager())
.ofType(LinearLayoutManager.class)
.map(this::displayedItemFromLinearLayout)
.distinctUntilChanged()
.filter(this::visibleItemIsCloseToBottom)
.subscribe(__ -> nextPage.call());
}
public void stop() {
if (subscription != null) {
subscription.unsubscribe();
}
}
/**
* Returns a (visibleItem, totalItemCount) pair given a linear layout manager.
*/
@NonNull private Pair<Integer, Integer> displayedItemFromLinearLayout(@NonNull final LinearLayoutManager manager) {
final int visibleItemCount = manager.getChildCount();
final int totalItemCount = manager.getItemCount();
final int pastVisibleItems = manager.findFirstVisibleItemPosition();
return new Pair<>(visibleItemCount + pastVisibleItems, totalItemCount);
}
private boolean visibleItemIsCloseToBottom(@NonNull final Pair<Integer, Integer> visibleItemOfTotal) {
return visibleItemOfTotal.first == visibleItemOfTotal.second - 2;
}
}
| app/src/main/java/com/kickstarter/libs/Paginator.java | package com.kickstarter.libs;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Pair;
import com.jakewharton.rxbinding.support.v7.widget.RxRecyclerView;
import rx.Subscription;
import rx.functions.Action0;
public final class Paginator {
@NonNull private final RecyclerView recyclerView;
@NonNull private final Action0 nextPage;
private Subscription subscription = null;
public Paginator(@NonNull final RecyclerView recyclerView, @NonNull final Action0 nextPage) {
this.recyclerView = recyclerView;
this.nextPage = nextPage;
start();
}
public void start() {
stop();
subscription = RxRecyclerView.scrollEvents(recyclerView)
.map(__ -> recyclerView.getLayoutManager())
.ofType(LinearLayoutManager.class)
.map(this::displayedItemFromLinearLayout)
.distinctUntilChanged()
.filter(this::visibleItemIsCloseToBottom)
.subscribe(__ -> nextPage.call());
}
public void stop() {
if (subscription != null) {
subscription.unsubscribe();
}
}
/**
* Returns a (visibleItem, totalItemCount) pair given a linear layout manager.
*/
@NonNull private Pair<Integer, Integer> displayedItemFromLinearLayout(@NonNull final LinearLayoutManager manager) {
final int visibleItemCount = manager.getChildCount();
final int totalItemCount = manager.getItemCount();
final int pastVisibleItems = manager.findFirstVisibleItemPosition();
return new Pair<>(visibleItemCount + pastVisibleItems, totalItemCount);
}
/**
* Returns `true` when the visible item gets "close" to the bottom.
*/
private boolean visibleItemIsCloseToBottom(@NonNull final Pair<Integer, Integer> visibleItemOfTotal) {
return visibleItemOfTotal.first == visibleItemOfTotal.second - 2;
}
}
| Seriously don't need a comment on this obvious method.
| app/src/main/java/com/kickstarter/libs/Paginator.java | Seriously don't need a comment on this obvious method. | <ide><path>pp/src/main/java/com/kickstarter/libs/Paginator.java
<ide> return new Pair<>(visibleItemCount + pastVisibleItems, totalItemCount);
<ide> }
<ide>
<del> /**
<del> * Returns `true` when the visible item gets "close" to the bottom.
<del> */
<ide> private boolean visibleItemIsCloseToBottom(@NonNull final Pair<Integer, Integer> visibleItemOfTotal) {
<ide> return visibleItemOfTotal.first == visibleItemOfTotal.second - 2;
<ide> } |
|
Java | apache-2.0 | f9a9a43366931e83e737ac7e772b9d78ff251394 | 0 | qiangber/symphony,qiangber/symphony,billho/symphony,qiangber/symphony,billho/symphony,billho/symphony | /*
* Copyright (c) 2012-2016, b3log.org & hacpai.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.b3log.symphony.service;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.inject.Inject;
import org.b3log.latke.Keys;
import org.b3log.latke.logging.Level;
import org.b3log.latke.logging.Logger;
import org.b3log.latke.model.Pagination;
import org.b3log.latke.model.User;
import org.b3log.latke.repository.CompositeFilter;
import org.b3log.latke.repository.CompositeFilterOperator;
import org.b3log.latke.repository.Filter;
import org.b3log.latke.repository.FilterOperator;
import org.b3log.latke.repository.PropertyFilter;
import org.b3log.latke.repository.Query;
import org.b3log.latke.repository.RepositoryException;
import org.b3log.latke.repository.SortDirection;
import org.b3log.latke.service.LangPropsService;
import org.b3log.latke.service.ServiceException;
import org.b3log.latke.service.annotation.Service;
import org.b3log.latke.util.CollectionUtils;
import org.b3log.symphony.model.Article;
import org.b3log.symphony.model.Comment;
import org.b3log.symphony.model.Common;
import org.b3log.symphony.model.Pointtransfer;
import org.b3log.symphony.model.Reward;
import org.b3log.symphony.model.UserExt;
import org.b3log.symphony.repository.ArticleRepository;
import org.b3log.symphony.repository.CommentRepository;
import org.b3log.symphony.repository.PointtransferRepository;
import org.b3log.symphony.repository.RewardRepository;
import org.b3log.symphony.repository.UserRepository;
import org.b3log.symphony.util.Emotions;
import org.json.JSONArray;
import org.json.JSONObject;
/**
* Pointtransfer query service.
*
* @author <a href="http://88250.b3log.org">Liang Ding</a>
* @version 1.9.2.1, Mar 2, 2016
* @since 1.3.0
*/
@Service
public class PointtransferQueryService {
/**
* Logger.
*/
private static final Logger LOGGER = Logger.getLogger(PointtransferQueryService.class.getName());
/**
* Pointtransfer repository.
*/
@Inject
private PointtransferRepository pointtransferRepository;
/**
* Article repository.
*/
@Inject
private ArticleRepository articleRepository;
/**
* User repository.
*/
@Inject
private UserRepository userRepository;
/**
* Comment repository.
*/
@Inject
private CommentRepository commentRepository;
/**
* Reward repository.
*/
@Inject
private RewardRepository rewardRepository;
/**
* Language service.
*/
@Inject
private LangPropsService langPropsService;
/**
* Avatar query service.
*/
@Inject
private AvatarQueryService avatarQueryService;
/**
* Gets the latest pointtransfers with the specified user id, type and fetch size.
*
* @param userId the specified user id
* @param type the specified type
* @param fetchSize the specified fetch size
* @return pointtransfers, returns an empty list if not found
*/
public List<JSONObject> getLatestPointtransfers(final String userId, final int type, final int fetchSize) {
final List<JSONObject> ret = new ArrayList<JSONObject>();
final List<Filter> userFilters = new ArrayList<Filter>();
userFilters.add(new PropertyFilter(Pointtransfer.FROM_ID, FilterOperator.EQUAL, userId));
userFilters.add(new PropertyFilter(Pointtransfer.TO_ID, FilterOperator.EQUAL, userId));
final List<Filter> filters = new ArrayList<Filter>();
filters.add(new CompositeFilter(CompositeFilterOperator.OR, userFilters));
filters.add(new PropertyFilter(Pointtransfer.TYPE, FilterOperator.EQUAL, type));
final Query query = new Query().addSort(Keys.OBJECT_ID, SortDirection.DESCENDING).setCurrentPageNum(1)
.setPageSize(fetchSize).setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters));
try {
final JSONObject result = pointtransferRepository.get(query);
return CollectionUtils.jsonArrayToList(result.optJSONArray(Keys.RESULTS));
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets latest pointtransfers error", e);
}
return ret;
}
/**
* Gets the top balance users with the specified fetch size.
*
* @param fetchSize the specified fetch size
* @return users, returns an empty list if not found
*/
public List<JSONObject> getTopBalanceUsers(final int fetchSize) {
final List<JSONObject> ret = new ArrayList<JSONObject>();
final Query query = new Query().addSort(UserExt.USER_POINT, SortDirection.DESCENDING).setCurrentPageNum(1)
.setPageSize(fetchSize);
try {
final JSONObject result = userRepository.get(query);
final List<JSONObject> users = CollectionUtils.jsonArrayToList(result.optJSONArray(Keys.RESULTS));
for (final JSONObject user : users) {
if (UserExt.USER_APP_ROLE_C_HACKER == user.optInt(UserExt.USER_APP_ROLE)) {
user.put(UserExt.USER_T_POINT_HEX, Integer.toHexString(user.optInt(UserExt.USER_POINT)));
} else {
user.put(UserExt.USER_T_POINT_CC, UserExt.toCCString(user.optInt(UserExt.USER_POINT)));
}
avatarQueryService.fillUserAvatarURL(user);
ret.add(user);
}
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets top balance users error", e);
}
return ret;
}
/**
* Gets the user points with the specified user id, page number and page size.
*
* @param userId the specified user id
* @param currentPageNum the specified page number
* @param pageSize the specified page size
* @return result json object, for example, <pre>
* {
* "paginationRecordCount": int,
* "rslts": java.util.List[{
* Pointtransfer
* }, ....]
* }
* </pre>
*
* @throws ServiceException service exception
*/
public JSONObject getUserPoints(final String userId, final int currentPageNum, final int pageSize) throws ServiceException {
final Query query = new Query().addSort(Keys.OBJECT_ID, SortDirection.DESCENDING)
.setCurrentPageNum(currentPageNum).setPageSize(pageSize);
final List<Filter> filters = new ArrayList<Filter>();
filters.add(new PropertyFilter(Pointtransfer.FROM_ID, FilterOperator.EQUAL, userId));
filters.add(new PropertyFilter(Pointtransfer.TO_ID, FilterOperator.EQUAL, userId));
query.setFilter(new CompositeFilter(CompositeFilterOperator.OR, filters));
try {
final JSONObject ret = pointtransferRepository.get(query);
final JSONArray records = ret.optJSONArray(Keys.RESULTS);
for (int i = 0; i < records.length(); i++) {
final JSONObject record = records.optJSONObject(i);
record.put(Common.CREATE_TIME, new Date(record.optLong(Pointtransfer.TIME)));
final String toId = record.optString(Pointtransfer.TO_ID);
final String fromId = record.optString(Pointtransfer.FROM_ID);
String typeStr = record.optString(Pointtransfer.TYPE);
if (("3".equals(typeStr) && userId.equals(toId))
|| ("5".equals(typeStr) && userId.equals(fromId))
|| ("9".equals(typeStr) && userId.equals(toId))
|| ("14".equals(typeStr) && userId.equals(toId))) {
typeStr += "In";
}
if (fromId.equals(userId)) {
record.put(Common.BALANCE, record.optInt(Pointtransfer.FROM_BALANCE));
record.put(Common.OPERATION, "-");
} else {
record.put(Common.BALANCE, record.optInt(Pointtransfer.TO_BALANCE));
record.put(Common.OPERATION, "+");
}
record.put(Common.DISPLAY_TYPE, langPropsService.get("pointType" + typeStr + "Label"));
final int type = record.optInt(Pointtransfer.TYPE);
final String dataId = record.optString(Pointtransfer.DATA_ID);
String desTemplate = langPropsService.get("pointType" + typeStr + "DesLabel");
switch (type) {
case Pointtransfer.TRANSFER_TYPE_C_INIT:
desTemplate = desTemplate.replace("{point}", record.optString(Pointtransfer.SUM));
break;
case Pointtransfer.TRANSFER_TYPE_C_ADD_ARTICLE:
final JSONObject addArticle = articleRepository.get(dataId);
final String addArticleLink = "<a href=\""
+ addArticle.optString(Article.ARTICLE_PERMALINK) + "\">"
+ addArticle.optString(Article.ARTICLE_TITLE) + "</a>";
desTemplate = desTemplate.replace("{article}", addArticleLink);
break;
case Pointtransfer.TRANSFER_TYPE_C_UPDATE_ARTICLE:
final JSONObject updateArticle = articleRepository.get(dataId);
final String updateArticleLink = "<a href=\""
+ updateArticle.optString(Article.ARTICLE_PERMALINK) + "\">"
+ updateArticle.optString(Article.ARTICLE_TITLE) + "</a>";
desTemplate = desTemplate.replace("{article}", updateArticleLink);
break;
case Pointtransfer.TRANSFER_TYPE_C_ADD_COMMENT:
final JSONObject comment = commentRepository.get(dataId);
final String articleId = comment.optString(Comment.COMMENT_ON_ARTICLE_ID);
final JSONObject commentArticle = articleRepository.get(articleId);
final String commentArticleLink = "<a href=\""
+ commentArticle.optString(Article.ARTICLE_PERMALINK) + "\">"
+ commentArticle.optString(Article.ARTICLE_TITLE) + "</a>";
desTemplate = desTemplate.replace("{article}", commentArticleLink);
if ("3In".equals(typeStr)) {
final JSONObject commenter = userRepository.get(fromId);
final String commenterLink = "<a href=\"/member/" + commenter.optString(User.USER_NAME) + "\">"
+ commenter.optString(User.USER_NAME) + "</a>";
desTemplate = desTemplate.replace("{user}", commenterLink);
}
break;
case Pointtransfer.TRANSFER_TYPE_C_ADD_ARTICLE_REWARD:
final JSONObject addArticleReword = articleRepository.get(dataId);
final String addArticleRewordLink = "<a href=\""
+ addArticleReword.optString(Article.ARTICLE_PERMALINK) + "\">"
+ addArticleReword.optString(Article.ARTICLE_TITLE) + "</a>";
desTemplate = desTemplate.replace("{article}", addArticleRewordLink);
break;
case Pointtransfer.TRANSFER_TYPE_C_ARTICLE_REWARD:
final JSONObject reward = rewardRepository.get(dataId);
String senderId = reward.optString(Reward.SENDER_ID);
if ("5In".equals(typeStr)) {
senderId = toId;
}
final String rewardAArticleId = reward.optString(Reward.DATA_ID);
final JSONObject sender = userRepository.get(senderId);
final String senderLink = "<a href=\"/member/" + sender.optString(User.USER_NAME) + "\">"
+ sender.optString(User.USER_NAME) + "</a>";
desTemplate = desTemplate.replace("{user}", senderLink);
final JSONObject articleReward = articleRepository.get(rewardAArticleId);
final String articleRewardLink = "<a href=\""
+ articleReward.optString(Article.ARTICLE_PERMALINK) + "\">"
+ articleReward.optString(Article.ARTICLE_TITLE) + "</a>";
desTemplate = desTemplate.replace("{article}", articleRewardLink);
break;
case Pointtransfer.TRANSFER_TYPE_C_COMMENT_REWARD:
final JSONObject reward14 = rewardRepository.get(dataId);
JSONObject user14;
if ("14In".equals(typeStr)) {
user14 = userRepository.get(fromId);
} else {
user14 = userRepository.get(toId);
}
final String commentId14 = reward14.optString(Reward.DATA_ID);
final JSONObject comment14 = commentRepository.get(commentId14);
final String articleId14 = comment14.optString(Comment.COMMENT_ON_ARTICLE_ID);
final String userLink14 = "<a href=\"/member/" + user14.optString(User.USER_NAME) + "\">"
+ user14.optString(User.USER_NAME) + "</a>";
desTemplate = desTemplate.replace("{user}", userLink14);
final JSONObject article = articleRepository.get(articleId14);
final String articleLink = "<a href=\""
+ article.optString(Article.ARTICLE_PERMALINK) + "\">"
+ article.optString(Article.ARTICLE_TITLE) + "</a>";
desTemplate = desTemplate.replace("{article}", articleLink);
break;
case Pointtransfer.TRANSFER_TYPE_C_INVITE_REGISTER:
final JSONObject newUser = userRepository.get(dataId);
final String newUserLink = "<a href=\"/member/" + newUser.optString(User.USER_NAME) + "\">"
+ newUser.optString(User.USER_NAME) + "</a>";
desTemplate = desTemplate.replace("{user}", newUserLink);
break;
case Pointtransfer.TRANSFER_TYPE_C_INVITED_REGISTER:
final JSONObject referralUser = userRepository.get(dataId);
final String referralUserLink = "<a href=\"/member/" + referralUser.optString(User.USER_NAME) + "\">"
+ referralUser.optString(User.USER_NAME) + "</a>";
desTemplate = desTemplate.replace("{user}", referralUserLink);
break;
case Pointtransfer.TRANSFER_TYPE_C_ACTIVITY_CHECKIN:
case Pointtransfer.TRANSFER_TYPE_C_ACTIVITY_1A0001:
case Pointtransfer.TRANSFER_TYPE_C_ACTIVITY_1A0001_COLLECT:
break;
case Pointtransfer.TRANSFER_TYPE_C_ACCOUNT2ACCOUNT:
JSONObject user9;
if ("9In".equals(typeStr)) {
user9 = userRepository.get(fromId);
} else {
user9 = userRepository.get(toId);
}
final String userLink = "<a href=\"/member/" + user9.optString(User.USER_NAME) + "\">"
+ user9.optString(User.USER_NAME) + "</a>";
desTemplate = desTemplate.replace("{user}", userLink);
break;
case Pointtransfer.TRANSFER_TYPE_C_ACTIVITY_CHECKIN_STREAK:
desTemplate = desTemplate.replace("{point}",
String.valueOf(Pointtransfer.TRANSFER_SUM_C_ACTIVITY_CHECKINT_STREAK));
break;
case Pointtransfer.TRANSFER_TYPE_C_CHARGE:
final String yuan = dataId.split("-")[0];
desTemplate = desTemplate.replace("{yuan}", yuan);
break;
case Pointtransfer.TRANSFER_TYPE_C_EXCHANGE:
final String exYuan = dataId;
desTemplate = desTemplate.replace("{yuan}", exYuan);
break;
case Pointtransfer.TRANSFER_TYPE_C_ABUSE_DEDUCT:
desTemplate = desTemplate.replace("{action}", dataId);
desTemplate = desTemplate.replace("{point}", record.optString(Pointtransfer.SUM));
break;
case Pointtransfer.TRANSFER_TYPE_C_ADD_ARTICLE_BROADCAST:
final JSONObject addArticleBroadcast = articleRepository.get(dataId);
final String addArticleBroadcastLink = "<a href=\""
+ addArticleBroadcast.optString(Article.ARTICLE_PERMALINK) + "\">"
+ addArticleBroadcast.optString(Article.ARTICLE_TITLE) + "</a>";
desTemplate = desTemplate.replace("{article}", addArticleBroadcastLink);
break;
default:
LOGGER.warn("Invalid point type [" + type + "]");
}
desTemplate = Emotions.convert(desTemplate);
record.put(Common.DESCRIPTION, desTemplate);
}
final int recordCnt = ret.optJSONObject(Pagination.PAGINATION).optInt(Pagination.PAGINATION_RECORD_COUNT);
ret.remove(Pagination.PAGINATION);
ret.put(Pagination.PAGINATION_RECORD_COUNT, recordCnt);
return ret;
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets user points failed", e);
throw new ServiceException(e);
}
}
}
| src/main/java/org/b3log/symphony/service/PointtransferQueryService.java | /*
* Copyright (c) 2012-2016, b3log.org & hacpai.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.b3log.symphony.service;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.inject.Inject;
import org.b3log.latke.Keys;
import org.b3log.latke.logging.Level;
import org.b3log.latke.logging.Logger;
import org.b3log.latke.model.Pagination;
import org.b3log.latke.model.User;
import org.b3log.latke.repository.CompositeFilter;
import org.b3log.latke.repository.CompositeFilterOperator;
import org.b3log.latke.repository.Filter;
import org.b3log.latke.repository.FilterOperator;
import org.b3log.latke.repository.PropertyFilter;
import org.b3log.latke.repository.Query;
import org.b3log.latke.repository.RepositoryException;
import org.b3log.latke.repository.SortDirection;
import org.b3log.latke.service.LangPropsService;
import org.b3log.latke.service.ServiceException;
import org.b3log.latke.service.annotation.Service;
import org.b3log.latke.util.CollectionUtils;
import org.b3log.symphony.model.Article;
import org.b3log.symphony.model.Comment;
import org.b3log.symphony.model.Common;
import org.b3log.symphony.model.Pointtransfer;
import org.b3log.symphony.model.Reward;
import org.b3log.symphony.model.UserExt;
import org.b3log.symphony.repository.ArticleRepository;
import org.b3log.symphony.repository.CommentRepository;
import org.b3log.symphony.repository.PointtransferRepository;
import org.b3log.symphony.repository.RewardRepository;
import org.b3log.symphony.repository.UserRepository;
import org.json.JSONArray;
import org.json.JSONObject;
/**
* Pointtransfer query service.
*
* @author <a href="http://88250.b3log.org">Liang Ding</a>
* @version 1.9.1.1, Feb 23, 2016
* @since 1.3.0
*/
@Service
public class PointtransferQueryService {
/**
* Logger.
*/
private static final Logger LOGGER = Logger.getLogger(PointtransferQueryService.class.getName());
/**
* Pointtransfer repository.
*/
@Inject
private PointtransferRepository pointtransferRepository;
/**
* Article repository.
*/
@Inject
private ArticleRepository articleRepository;
/**
* User repository.
*/
@Inject
private UserRepository userRepository;
/**
* Comment repository.
*/
@Inject
private CommentRepository commentRepository;
/**
* Reward repository.
*/
@Inject
private RewardRepository rewardRepository;
/**
* Language service.
*/
@Inject
private LangPropsService langPropsService;
/**
* Avatar query service.
*/
@Inject
private AvatarQueryService avatarQueryService;
/**
* Gets the latest pointtransfers with the specified user id, type and fetch size.
*
* @param userId the specified user id
* @param type the specified type
* @param fetchSize the specified fetch size
* @return pointtransfers, returns an empty list if not found
*/
public List<JSONObject> getLatestPointtransfers(final String userId, final int type, final int fetchSize) {
final List<JSONObject> ret = new ArrayList<JSONObject>();
final List<Filter> userFilters = new ArrayList<Filter>();
userFilters.add(new PropertyFilter(Pointtransfer.FROM_ID, FilterOperator.EQUAL, userId));
userFilters.add(new PropertyFilter(Pointtransfer.TO_ID, FilterOperator.EQUAL, userId));
final List<Filter> filters = new ArrayList<Filter>();
filters.add(new CompositeFilter(CompositeFilterOperator.OR, userFilters));
filters.add(new PropertyFilter(Pointtransfer.TYPE, FilterOperator.EQUAL, type));
final Query query = new Query().addSort(Keys.OBJECT_ID, SortDirection.DESCENDING).setCurrentPageNum(1)
.setPageSize(fetchSize).setFilter(new CompositeFilter(CompositeFilterOperator.AND, filters));
try {
final JSONObject result = pointtransferRepository.get(query);
return CollectionUtils.jsonArrayToList(result.optJSONArray(Keys.RESULTS));
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets latest pointtransfers error", e);
}
return ret;
}
/**
* Gets the top balance users with the specified fetch size.
*
* @param fetchSize the specified fetch size
* @return users, returns an empty list if not found
*/
public List<JSONObject> getTopBalanceUsers(final int fetchSize) {
final List<JSONObject> ret = new ArrayList<JSONObject>();
final Query query = new Query().addSort(UserExt.USER_POINT, SortDirection.DESCENDING).setCurrentPageNum(1)
.setPageSize(fetchSize);
try {
final JSONObject result = userRepository.get(query);
final List<JSONObject> users = CollectionUtils.jsonArrayToList(result.optJSONArray(Keys.RESULTS));
for (final JSONObject user : users) {
if (UserExt.USER_APP_ROLE_C_HACKER == user.optInt(UserExt.USER_APP_ROLE)) {
user.put(UserExt.USER_T_POINT_HEX, Integer.toHexString(user.optInt(UserExt.USER_POINT)));
} else {
user.put(UserExt.USER_T_POINT_CC, UserExt.toCCString(user.optInt(UserExt.USER_POINT)));
}
avatarQueryService.fillUserAvatarURL(user);
ret.add(user);
}
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets top balance users error", e);
}
return ret;
}
/**
* Gets the user points with the specified user id, page number and page size.
*
* @param userId the specified user id
* @param currentPageNum the specified page number
* @param pageSize the specified page size
* @return result json object, for example, <pre>
* {
* "paginationRecordCount": int,
* "rslts": java.util.List[{
* Pointtransfer
* }, ....]
* }
* </pre>
*
* @throws ServiceException service exception
*/
public JSONObject getUserPoints(final String userId, final int currentPageNum, final int pageSize) throws ServiceException {
final Query query = new Query().addSort(Keys.OBJECT_ID, SortDirection.DESCENDING)
.setCurrentPageNum(currentPageNum).setPageSize(pageSize);
final List<Filter> filters = new ArrayList<Filter>();
filters.add(new PropertyFilter(Pointtransfer.FROM_ID, FilterOperator.EQUAL, userId));
filters.add(new PropertyFilter(Pointtransfer.TO_ID, FilterOperator.EQUAL, userId));
query.setFilter(new CompositeFilter(CompositeFilterOperator.OR, filters));
try {
final JSONObject ret = pointtransferRepository.get(query);
final JSONArray records = ret.optJSONArray(Keys.RESULTS);
for (int i = 0; i < records.length(); i++) {
final JSONObject record = records.optJSONObject(i);
record.put(Common.CREATE_TIME, new Date(record.optLong(Pointtransfer.TIME)));
final String toId = record.optString(Pointtransfer.TO_ID);
final String fromId = record.optString(Pointtransfer.FROM_ID);
String typeStr = record.optString(Pointtransfer.TYPE);
if (("3".equals(typeStr) && userId.equals(toId))
|| ("5".equals(typeStr) && userId.equals(fromId))
|| ("9".equals(typeStr) && userId.equals(toId))
|| ("14".equals(typeStr) && userId.equals(toId))) {
typeStr += "In";
}
if (fromId.equals(userId)) {
record.put(Common.BALANCE, record.optInt(Pointtransfer.FROM_BALANCE));
record.put(Common.OPERATION, "-");
} else {
record.put(Common.BALANCE, record.optInt(Pointtransfer.TO_BALANCE));
record.put(Common.OPERATION, "+");
}
record.put(Common.DISPLAY_TYPE, langPropsService.get("pointType" + typeStr + "Label"));
final int type = record.optInt(Pointtransfer.TYPE);
final String dataId = record.optString(Pointtransfer.DATA_ID);
String desTemplate = langPropsService.get("pointType" + typeStr + "DesLabel");
switch (type) {
case Pointtransfer.TRANSFER_TYPE_C_INIT:
desTemplate = desTemplate.replace("{point}", record.optString(Pointtransfer.SUM));
break;
case Pointtransfer.TRANSFER_TYPE_C_ADD_ARTICLE:
final JSONObject addArticle = articleRepository.get(dataId);
final String addArticleLink = "<a href=\""
+ addArticle.optString(Article.ARTICLE_PERMALINK) + "\">"
+ addArticle.optString(Article.ARTICLE_TITLE) + "</a>";
desTemplate = desTemplate.replace("{article}", addArticleLink);
break;
case Pointtransfer.TRANSFER_TYPE_C_UPDATE_ARTICLE:
final JSONObject updateArticle = articleRepository.get(dataId);
final String updateArticleLink = "<a href=\""
+ updateArticle.optString(Article.ARTICLE_PERMALINK) + "\">"
+ updateArticle.optString(Article.ARTICLE_TITLE) + "</a>";
desTemplate = desTemplate.replace("{article}", updateArticleLink);
break;
case Pointtransfer.TRANSFER_TYPE_C_ADD_COMMENT:
final JSONObject comment = commentRepository.get(dataId);
final String articleId = comment.optString(Comment.COMMENT_ON_ARTICLE_ID);
final JSONObject commentArticle = articleRepository.get(articleId);
final String commentArticleLink = "<a href=\""
+ commentArticle.optString(Article.ARTICLE_PERMALINK) + "\">"
+ commentArticle.optString(Article.ARTICLE_TITLE) + "</a>";
desTemplate = desTemplate.replace("{article}", commentArticleLink);
if ("3In".equals(typeStr)) {
final JSONObject commenter = userRepository.get(fromId);
final String commenterLink = "<a href=\"/member/" + commenter.optString(User.USER_NAME) + "\">"
+ commenter.optString(User.USER_NAME) + "</a>";
desTemplate = desTemplate.replace("{user}", commenterLink);
}
break;
case Pointtransfer.TRANSFER_TYPE_C_ADD_ARTICLE_REWARD:
final JSONObject addArticleReword = articleRepository.get(dataId);
final String addArticleRewordLink = "<a href=\""
+ addArticleReword.optString(Article.ARTICLE_PERMALINK) + "\">"
+ addArticleReword.optString(Article.ARTICLE_TITLE) + "</a>";
desTemplate = desTemplate.replace("{article}", addArticleRewordLink);
break;
case Pointtransfer.TRANSFER_TYPE_C_ARTICLE_REWARD:
final JSONObject reward = rewardRepository.get(dataId);
String senderId = reward.optString(Reward.SENDER_ID);
if ("5In".equals(typeStr)) {
senderId = toId;
}
final String rewardAArticleId = reward.optString(Reward.DATA_ID);
final JSONObject sender = userRepository.get(senderId);
final String senderLink = "<a href=\"/member/" + sender.optString(User.USER_NAME) + "\">"
+ sender.optString(User.USER_NAME) + "</a>";
desTemplate = desTemplate.replace("{user}", senderLink);
final JSONObject articleReward = articleRepository.get(rewardAArticleId);
final String articleRewardLink = "<a href=\""
+ articleReward.optString(Article.ARTICLE_PERMALINK) + "\">"
+ articleReward.optString(Article.ARTICLE_TITLE) + "</a>";
desTemplate = desTemplate.replace("{article}", articleRewardLink);
break;
case Pointtransfer.TRANSFER_TYPE_C_COMMENT_REWARD:
final JSONObject reward14 = rewardRepository.get(dataId);
JSONObject user14;
if ("14In".equals(typeStr)) {
user14 = userRepository.get(fromId);
} else {
user14 = userRepository.get(toId);
}
final String commentId14 = reward14.optString(Reward.DATA_ID);
final JSONObject comment14 = commentRepository.get(commentId14);
final String articleId14 = comment14.optString(Comment.COMMENT_ON_ARTICLE_ID);
final String userLink14 = "<a href=\"/member/" + user14.optString(User.USER_NAME) + "\">"
+ user14.optString(User.USER_NAME) + "</a>";
desTemplate = desTemplate.replace("{user}", userLink14);
final JSONObject article = articleRepository.get(articleId14);
final String articleLink = "<a href=\""
+ article.optString(Article.ARTICLE_PERMALINK) + "\">"
+ article.optString(Article.ARTICLE_TITLE) + "</a>";
desTemplate = desTemplate.replace("{article}", articleLink);
break;
case Pointtransfer.TRANSFER_TYPE_C_INVITE_REGISTER:
final JSONObject newUser = userRepository.get(dataId);
final String newUserLink = "<a href=\"/member/" + newUser.optString(User.USER_NAME) + "\">"
+ newUser.optString(User.USER_NAME) + "</a>";
desTemplate = desTemplate.replace("{user}", newUserLink);
break;
case Pointtransfer.TRANSFER_TYPE_C_INVITED_REGISTER:
final JSONObject referralUser = userRepository.get(dataId);
final String referralUserLink = "<a href=\"/member/" + referralUser.optString(User.USER_NAME) + "\">"
+ referralUser.optString(User.USER_NAME) + "</a>";
desTemplate = desTemplate.replace("{user}", referralUserLink);
break;
case Pointtransfer.TRANSFER_TYPE_C_ACTIVITY_CHECKIN:
case Pointtransfer.TRANSFER_TYPE_C_ACTIVITY_1A0001:
case Pointtransfer.TRANSFER_TYPE_C_ACTIVITY_1A0001_COLLECT:
break;
case Pointtransfer.TRANSFER_TYPE_C_ACCOUNT2ACCOUNT:
JSONObject user9;
if ("9In".equals(typeStr)) {
user9 = userRepository.get(fromId);
} else {
user9 = userRepository.get(toId);
}
final String userLink = "<a href=\"/member/" + user9.optString(User.USER_NAME) + "\">"
+ user9.optString(User.USER_NAME) + "</a>";
desTemplate = desTemplate.replace("{user}", userLink);
break;
case Pointtransfer.TRANSFER_TYPE_C_ACTIVITY_CHECKIN_STREAK:
desTemplate = desTemplate.replace("{point}",
String.valueOf(Pointtransfer.TRANSFER_SUM_C_ACTIVITY_CHECKINT_STREAK));
break;
case Pointtransfer.TRANSFER_TYPE_C_CHARGE:
final String yuan = dataId.split("-")[0];
desTemplate = desTemplate.replace("{yuan}", yuan);
break;
case Pointtransfer.TRANSFER_TYPE_C_EXCHANGE:
final String exYuan = dataId;
desTemplate = desTemplate.replace("{yuan}", exYuan);
break;
case Pointtransfer.TRANSFER_TYPE_C_ABUSE_DEDUCT:
desTemplate = desTemplate.replace("{action}", dataId);
desTemplate = desTemplate.replace("{point}", record.optString(Pointtransfer.SUM));
break;
case Pointtransfer.TRANSFER_TYPE_C_ADD_ARTICLE_BROADCAST:
final JSONObject addArticleBroadcast = articleRepository.get(dataId);
final String addArticleBroadcastLink = "<a href=\""
+ addArticleBroadcast.optString(Article.ARTICLE_PERMALINK) + "\">"
+ addArticleBroadcast.optString(Article.ARTICLE_TITLE) + "</a>";
desTemplate = desTemplate.replace("{article}", addArticleBroadcastLink);
break;
default:
LOGGER.warn("Invalid point type [" + type + "]");
}
record.put(Common.DESCRIPTION, desTemplate);
}
final int recordCnt = ret.optJSONObject(Pagination.PAGINATION).optInt(Pagination.PAGINATION_RECORD_COUNT);
ret.remove(Pagination.PAGINATION);
ret.put(Pagination.PAGINATION_RECORD_COUNT, recordCnt);
return ret;
} catch (final RepositoryException e) {
LOGGER.log(Level.ERROR, "Gets user points failed", e);
throw new ServiceException(e);
}
}
}
| 积分页面 emoji 转义
| src/main/java/org/b3log/symphony/service/PointtransferQueryService.java | 积分页面 emoji 转义 | <ide><path>rc/main/java/org/b3log/symphony/service/PointtransferQueryService.java
<ide> import org.b3log.symphony.repository.PointtransferRepository;
<ide> import org.b3log.symphony.repository.RewardRepository;
<ide> import org.b3log.symphony.repository.UserRepository;
<add>import org.b3log.symphony.util.Emotions;
<ide> import org.json.JSONArray;
<ide> import org.json.JSONObject;
<ide>
<ide> * Pointtransfer query service.
<ide> *
<ide> * @author <a href="http://88250.b3log.org">Liang Ding</a>
<del> * @version 1.9.1.1, Feb 23, 2016
<add> * @version 1.9.2.1, Mar 2, 2016
<ide> * @since 1.3.0
<ide> */
<ide> @Service
<ide> LOGGER.warn("Invalid point type [" + type + "]");
<ide> }
<ide>
<add> desTemplate = Emotions.convert(desTemplate);
<add>
<ide> record.put(Common.DESCRIPTION, desTemplate);
<ide> }
<ide> |
|
Java | mit | f1979955857fcfe162ebaadbb685c4235cb41a93 | 0 | Nishchal123/assignment7 | package nineCoins;
import java.util.Scanner;
public class Ninecoins {
public static void main(String[] args) {
// Use binary number and bitwise operator to shift the bit to the right and
// use masking to extract the last digit
Scanner input = new Scanner(System.in);
System.out.print("Enter a number between 0 and 511: ");
short n = input.nextShort();
int intArray[][] = new int[3][3];
short mask = 0b1; // to extract the last bit after shifting
for (int i = 0; i < 9; i++) {
//
short bit = (short) (n & mask);
// extracting last bit i.e the remainder of division by 2
intArray[2-i / 3][2-i % 3] = bit;
n = (byte) (n >> 1); // Shifting right is dividing by 2. The last
// bit is the remainder of the next shift.
}
//displayArray(intArray);
}
// custom method has to be added to display the arrays
}
| nineCoins/src/nineCoins/Ninecoins.java | package nineCoins;
import java.util.Scanner;
public class Ninecoins {
public static void main(String[] args) {
// Use binary number and bitwise operator to shift the bit to the right and
// use masking to extract the last digit
Scanner input = new Scanner(System.in);
System.out.print("Enter a number between 0 and 511: ");
short n = input.nextShort();
int intArray[][] = new int[3][3];
short mask = 0b1; // to extract the last bit after shifting
for (int i = 0; i < 9; i++) {
//
short bit = (short) (n & mask);
// extracting last bit i.e the remainder of division by 2
intArray[2-i / 3][2-i % 3] = bit;
n = (byte) (n >> 1); // Shifting right is dividing by 2. The last
// bit is the remainder of the next shift.
}
displayArray(intArray);
}
// custom method has to be added to display the arrays
}
| made modifications int he program
| nineCoins/src/nineCoins/Ninecoins.java | made modifications int he program | <ide><path>ineCoins/src/nineCoins/Ninecoins.java
<ide>
<ide> }
<ide>
<del> displayArray(intArray);
<add> //displayArray(intArray);
<ide>
<ide> }
<ide> |
|
Java | apache-2.0 | 9fbb664db6edb238aa48da93f1a5883b85909df4 | 0 | Buzzardo/spring-boot,spring-projects/spring-boot,aahlenst/spring-boot,mbenson/spring-boot,NetoDevel/spring-boot,htynkn/spring-boot,chrylis/spring-boot,spring-projects/spring-boot,philwebb/spring-boot,yangdd1205/spring-boot,mdeinum/spring-boot,shakuzen/spring-boot,ilayaperumalg/spring-boot,ilayaperumalg/spring-boot,ilayaperumalg/spring-boot,Buzzardo/spring-boot,spring-projects/spring-boot,dreis2211/spring-boot,ilayaperumalg/spring-boot,mdeinum/spring-boot,scottfrederick/spring-boot,philwebb/spring-boot,jxblum/spring-boot,mbenson/spring-boot,spring-projects/spring-boot,mbenson/spring-boot,vpavic/spring-boot,royclarkson/spring-boot,joshiste/spring-boot,NetoDevel/spring-boot,dreis2211/spring-boot,NetoDevel/spring-boot,wilkinsona/spring-boot,jxblum/spring-boot,joshiste/spring-boot,chrylis/spring-boot,wilkinsona/spring-boot,joshiste/spring-boot,dreis2211/spring-boot,scottfrederick/spring-boot,joshiste/spring-boot,aahlenst/spring-boot,Buzzardo/spring-boot,philwebb/spring-boot,mdeinum/spring-boot,chrylis/spring-boot,mdeinum/spring-boot,ilayaperumalg/spring-boot,wilkinsona/spring-boot,mbenson/spring-boot,jxblum/spring-boot,chrylis/spring-boot,jxblum/spring-boot,vpavic/spring-boot,joshiste/spring-boot,mdeinum/spring-boot,dreis2211/spring-boot,spring-projects/spring-boot,htynkn/spring-boot,philwebb/spring-boot,spring-projects/spring-boot,aahlenst/spring-boot,jxblum/spring-boot,vpavic/spring-boot,royclarkson/spring-boot,Buzzardo/spring-boot,Buzzardo/spring-boot,shakuzen/spring-boot,michael-simons/spring-boot,royclarkson/spring-boot,aahlenst/spring-boot,Buzzardo/spring-boot,scottfrederick/spring-boot,shakuzen/spring-boot,scottfrederick/spring-boot,shakuzen/spring-boot,wilkinsona/spring-boot,dreis2211/spring-boot,philwebb/spring-boot,NetoDevel/spring-boot,mbenson/spring-boot,michael-simons/spring-boot,royclarkson/spring-boot,chrylis/spring-boot,yangdd1205/spring-boot,aahlenst/spring-boot,htynkn/spring-boot,mbenson/spring-boot,scottfrederick/spring-boot,chrylis/spring-boot,mdeinum/spring-boot,htynkn/spring-boot,wilkinsona/spring-boot,michael-simons/spring-boot,wilkinsona/spring-boot,joshiste/spring-boot,aahlenst/spring-boot,dreis2211/spring-boot,yangdd1205/spring-boot,htynkn/spring-boot,shakuzen/spring-boot,philwebb/spring-boot,scottfrederick/spring-boot,jxblum/spring-boot,vpavic/spring-boot,royclarkson/spring-boot,ilayaperumalg/spring-boot,michael-simons/spring-boot,shakuzen/spring-boot,vpavic/spring-boot,htynkn/spring-boot,vpavic/spring-boot,michael-simons/spring-boot,NetoDevel/spring-boot,michael-simons/spring-boot | /*
* Copyright 2012-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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.devtools.autoconfigure;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import javax.sql.DataSource;
import org.apache.derby.jdbc.EmbeddedDriver;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionMessage;
import org.springframework.boot.autoconfigure.condition.ConditionOutcome;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.SpringBootCondition;
import org.springframework.boot.autoconfigure.data.jpa.EntityManagerFactoryDependsOnPostProcessor;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.devtools.autoconfigure.DevToolsDataSourceAutoConfiguration.DatabaseShutdownExecutorEntityManagerFactoryDependsOnPostProcessor;
import org.springframework.boot.devtools.autoconfigure.DevToolsDataSourceAutoConfiguration.DevToolsDataSourceCondition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ConfigurationCondition;
import org.springframework.context.annotation.Import;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.orm.jpa.AbstractEntityManagerFactoryBean;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
/**
* {@link EnableAutoConfiguration Auto-configuration} for DevTools-specific
* {@link DataSource} configuration.
*
* @author Andy Wilkinson
* @since 1.3.3
*/
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
@Conditional({ OnEnabledDevToolsCondition.class, DevToolsDataSourceCondition.class })
@Configuration(proxyBeanMethods = false)
@Import(DatabaseShutdownExecutorEntityManagerFactoryDependsOnPostProcessor.class)
public class DevToolsDataSourceAutoConfiguration {
@Bean
NonEmbeddedInMemoryDatabaseShutdownExecutor inMemoryDatabaseShutdownExecutor(DataSource dataSource,
DataSourceProperties dataSourceProperties) {
return new NonEmbeddedInMemoryDatabaseShutdownExecutor(dataSource, dataSourceProperties);
}
/**
* Post processor to ensure that {@link javax.persistence.EntityManagerFactory} beans
* depend on the {@code inMemoryDatabaseShutdownExecutor} bean.
*/
@ConditionalOnClass(LocalContainerEntityManagerFactoryBean.class)
@ConditionalOnBean(AbstractEntityManagerFactoryBean.class)
static class DatabaseShutdownExecutorEntityManagerFactoryDependsOnPostProcessor
extends EntityManagerFactoryDependsOnPostProcessor {
DatabaseShutdownExecutorEntityManagerFactoryDependsOnPostProcessor() {
super("inMemoryDatabaseShutdownExecutor");
}
}
static final class NonEmbeddedInMemoryDatabaseShutdownExecutor implements DisposableBean {
private final DataSource dataSource;
private final DataSourceProperties dataSourceProperties;
NonEmbeddedInMemoryDatabaseShutdownExecutor(DataSource dataSource, DataSourceProperties dataSourceProperties) {
this.dataSource = dataSource;
this.dataSourceProperties = dataSourceProperties;
}
@Override
public void destroy() throws Exception {
for (InMemoryDatabase inMemoryDatabase : InMemoryDatabase.values()) {
if (inMemoryDatabase.matches(this.dataSourceProperties)) {
inMemoryDatabase.shutdown(this.dataSource);
return;
}
}
}
private enum InMemoryDatabase {
DERBY(null, new HashSet<>(Arrays.asList("org.apache.derby.jdbc.EmbeddedDriver")), (dataSource) -> {
String url = dataSource.getConnection().getMetaData().getURL();
try {
new EmbeddedDriver().connect(url + ";drop=true", new Properties());
}
catch (SQLException ex) {
if (!"08006".equals(ex.getSQLState())) {
throw ex;
}
}
}),
H2("jdbc:h2:mem:", new HashSet<>(Arrays.asList("org.h2.Driver", "org.h2.jdbcx.JdbcDataSource"))),
HSQLDB("jdbc:hsqldb:mem:", new HashSet<>(Arrays.asList("org.hsqldb.jdbcDriver",
"org.hsqldb.jdbc.JDBCDriver", "org.hsqldb.jdbc.pool.JDBCXADataSource")));
private final String urlPrefix;
private final ShutdownHandler shutdownHandler;
private final Set<String> driverClassNames;
InMemoryDatabase(String urlPrefix, Set<String> driverClassNames) {
this(urlPrefix, driverClassNames, (dataSource) -> {
try (Connection connection = dataSource.getConnection()) {
try (Statement statement = connection.createStatement()) {
statement.execute("SHUTDOWN");
}
}
});
}
InMemoryDatabase(String urlPrefix, Set<String> driverClassNames, ShutdownHandler shutdownHandler) {
this.urlPrefix = urlPrefix;
this.driverClassNames = driverClassNames;
this.shutdownHandler = shutdownHandler;
}
boolean matches(DataSourceProperties properties) {
String url = properties.getUrl();
return (url == null || this.urlPrefix == null || url.startsWith(this.urlPrefix))
&& this.driverClassNames.contains(properties.determineDriverClassName());
}
void shutdown(DataSource dataSource) throws SQLException {
this.shutdownHandler.shutdown(dataSource);
}
@FunctionalInterface
interface ShutdownHandler {
void shutdown(DataSource dataSource) throws SQLException;
}
}
}
static class DevToolsDataSourceCondition extends SpringBootCondition implements ConfigurationCondition {
@Override
public ConfigurationPhase getConfigurationPhase() {
return ConfigurationPhase.REGISTER_BEAN;
}
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
ConditionMessage.Builder message = ConditionMessage.forCondition("DevTools DataSource Condition");
String[] dataSourceBeanNames = context.getBeanFactory().getBeanNamesForType(DataSource.class, true, false);
if (dataSourceBeanNames.length != 1) {
return ConditionOutcome.noMatch(message.didNotFind("a single DataSource bean").atAll());
}
if (context.getBeanFactory().getBeanNamesForType(DataSourceProperties.class, true, false).length != 1) {
return ConditionOutcome.noMatch(message.didNotFind("a single DataSourceProperties bean").atAll());
}
BeanDefinition dataSourceDefinition = context.getRegistry().getBeanDefinition(dataSourceBeanNames[0]);
if (dataSourceDefinition instanceof AnnotatedBeanDefinition
&& ((AnnotatedBeanDefinition) dataSourceDefinition).getFactoryMethodMetadata() != null
&& ((AnnotatedBeanDefinition) dataSourceDefinition).getFactoryMethodMetadata()
.getDeclaringClassName().startsWith(DataSourceAutoConfiguration.class.getPackage().getName()
+ ".DataSourceConfiguration$")) {
return ConditionOutcome.match(message.foundExactly("auto-configured DataSource"));
}
return ConditionOutcome.noMatch(message.didNotFind("an auto-configured DataSource").atAll());
}
}
}
| spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/DevToolsDataSourceAutoConfiguration.java | /*
* Copyright 2012-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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.devtools.autoconfigure;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import javax.sql.DataSource;
import org.apache.derby.jdbc.EmbeddedDriver;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionMessage;
import org.springframework.boot.autoconfigure.condition.ConditionOutcome;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.SpringBootCondition;
import org.springframework.boot.autoconfigure.data.jpa.EntityManagerFactoryDependsOnPostProcessor;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.devtools.autoconfigure.DevToolsDataSourceAutoConfiguration.DatabaseShutdownExecutorEntityManagerFactoryDependsOnPostProcessor;
import org.springframework.boot.devtools.autoconfigure.DevToolsDataSourceAutoConfiguration.DevToolsDataSourceCondition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ConfigurationCondition;
import org.springframework.context.annotation.Import;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.orm.jpa.AbstractEntityManagerFactoryBean;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
/**
* {@link EnableAutoConfiguration Auto-configuration} for DevTools-specific
* {@link DataSource} configuration.
*
* @author Andy Wilkinson
* @since 1.3.3
*/
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
@Conditional({ OnEnabledDevToolsCondition.class, DevToolsDataSourceCondition.class })
@Configuration(proxyBeanMethods = false)
@Import(DatabaseShutdownExecutorEntityManagerFactoryDependsOnPostProcessor.class)
public class DevToolsDataSourceAutoConfiguration {
@Bean
NonEmbeddedInMemoryDatabaseShutdownExecutor inMemoryDatabaseShutdownExecutor(DataSource dataSource,
DataSourceProperties dataSourceProperties) {
return new NonEmbeddedInMemoryDatabaseShutdownExecutor(dataSource, dataSourceProperties);
}
/**
* Post processor to ensure that {@link javax.persistence.EntityManagerFactory} beans
* depend on the {@code inMemoryDatabaseShutdownExecutor} bean.
*/
@ConditionalOnClass(LocalContainerEntityManagerFactoryBean.class)
@ConditionalOnBean(AbstractEntityManagerFactoryBean.class)
static class DatabaseShutdownExecutorEntityManagerFactoryDependsOnPostProcessor
extends EntityManagerFactoryDependsOnPostProcessor {
DatabaseShutdownExecutorEntityManagerFactoryDependsOnPostProcessor() {
super("inMemoryDatabaseShutdownExecutor");
}
}
static final class NonEmbeddedInMemoryDatabaseShutdownExecutor implements DisposableBean {
private final DataSource dataSource;
private final DataSourceProperties dataSourceProperties;
NonEmbeddedInMemoryDatabaseShutdownExecutor(DataSource dataSource, DataSourceProperties dataSourceProperties) {
this.dataSource = dataSource;
this.dataSourceProperties = dataSourceProperties;
}
@Override
public void destroy() throws Exception {
for (InMemoryDatabase inMemoryDatabase : InMemoryDatabase.values()) {
if (inMemoryDatabase.matches(this.dataSourceProperties)) {
inMemoryDatabase.shutdown(this.dataSource);
return;
}
}
}
private enum InMemoryDatabase {
DERBY(null, new HashSet<>(Arrays.asList("org.apache.derby.jdbc.EmbeddedDriver")), (dataSource) -> {
String url = dataSource.getConnection().getMetaData().getURL();
try {
new EmbeddedDriver().connect(url + ";drop=true", new Properties());
}
catch (SQLException ex) {
if (!"08006".equals(ex.getSQLState())) {
throw ex;
}
}
}),
H2("jdbc:h2:mem:", new HashSet<>(Arrays.asList("org.h2.Driver", "org.h2.jdbcx.JdbcDataSource"))),
HSQLDB("jdbc:hsqldb:mem:", new HashSet<>(Arrays.asList("org.hsqldb.jdbcDriver",
"org.hsqldb.jdbc.JDBCDriver", "org.hsqldb.jdbc.pool.JDBCXADataSource")));
private final String urlPrefix;
private final ShutdownHandler shutdownHandler;
private final Set<String> driverClassNames;
InMemoryDatabase(String urlPrefix, Set<String> driverClassNames) {
this(urlPrefix, driverClassNames, (dataSource) -> {
try (Connection connection = dataSource.getConnection()) {
try (Statement statement = connection.createStatement()) {
statement.execute("SHUTDOWN");
}
}
});
}
InMemoryDatabase(String urlPrefix, Set<String> driverClassNames, ShutdownHandler shutdownHandler) {
this.urlPrefix = urlPrefix;
this.driverClassNames = driverClassNames;
this.shutdownHandler = shutdownHandler;
}
boolean matches(DataSourceProperties properties) {
String url = properties.getUrl();
return (url == null || this.urlPrefix == null || url.startsWith(this.urlPrefix))
&& this.driverClassNames.contains(properties.determineDriverClassName());
}
void shutdown(DataSource dataSource) throws SQLException {
this.shutdownHandler.shutdown(dataSource);
}
@FunctionalInterface
interface ShutdownHandler {
void shutdown(DataSource dataSource) throws SQLException;
}
}
}
static class DevToolsDataSourceCondition extends SpringBootCondition implements ConfigurationCondition {
@Override
public ConfigurationPhase getConfigurationPhase() {
return ConfigurationPhase.REGISTER_BEAN;
}
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
ConditionMessage.Builder message = ConditionMessage.forCondition("DevTools DataSource Condition");
String[] dataSourceBeanNames = context.getBeanFactory().getBeanNamesForType(DataSource.class);
if (dataSourceBeanNames.length != 1) {
return ConditionOutcome.noMatch(message.didNotFind("a single DataSource bean").atAll());
}
if (context.getBeanFactory().getBeanNamesForType(DataSourceProperties.class).length != 1) {
return ConditionOutcome.noMatch(message.didNotFind("a single DataSourceProperties bean").atAll());
}
BeanDefinition dataSourceDefinition = context.getRegistry().getBeanDefinition(dataSourceBeanNames[0]);
if (dataSourceDefinition instanceof AnnotatedBeanDefinition
&& ((AnnotatedBeanDefinition) dataSourceDefinition).getFactoryMethodMetadata() != null
&& ((AnnotatedBeanDefinition) dataSourceDefinition).getFactoryMethodMetadata()
.getDeclaringClassName().startsWith(DataSourceAutoConfiguration.class.getPackage().getName()
+ ".DataSourceConfiguration$")) {
return ConditionOutcome.match(message.foundExactly("auto-configured DataSource"));
}
return ConditionOutcome.noMatch(message.didNotFind("an auto-configured DataSource").atAll());
}
}
}
| Avoid eager init when evaluating DevToolsDataSourceCondition
Previously, DevToolsDataSourceCondition called
getBeanNamesForType(Class) which could trigger unwanted initialization
of lazy init singletons and objects created by FactoryBeans.
This commit updates DevToolsDataSourceCondition to prohibit eager
init when getting the names of the beans of a particular type.
Fixes gh-20430
| spring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/DevToolsDataSourceAutoConfiguration.java | Avoid eager init when evaluating DevToolsDataSourceCondition | <ide><path>pring-boot-project/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/DevToolsDataSourceAutoConfiguration.java
<ide> @Override
<ide> public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
<ide> ConditionMessage.Builder message = ConditionMessage.forCondition("DevTools DataSource Condition");
<del> String[] dataSourceBeanNames = context.getBeanFactory().getBeanNamesForType(DataSource.class);
<add> String[] dataSourceBeanNames = context.getBeanFactory().getBeanNamesForType(DataSource.class, true, false);
<ide> if (dataSourceBeanNames.length != 1) {
<ide> return ConditionOutcome.noMatch(message.didNotFind("a single DataSource bean").atAll());
<ide> }
<del> if (context.getBeanFactory().getBeanNamesForType(DataSourceProperties.class).length != 1) {
<add> if (context.getBeanFactory().getBeanNamesForType(DataSourceProperties.class, true, false).length != 1) {
<ide> return ConditionOutcome.noMatch(message.didNotFind("a single DataSourceProperties bean").atAll());
<ide> }
<ide> BeanDefinition dataSourceDefinition = context.getRegistry().getBeanDefinition(dataSourceBeanNames[0]); |
|
JavaScript | mit | e98eca790b075cb57873f06ba14f120db40bc4b9 | 0 | psyntium/node-red-contrib-http-request-multipart,psyntium/node-red-contrib-http-request-multipart | "use strict";
var request = require('request');
module.exports = function (RED) {
function HTTPRequest(n) {
RED.nodes.createNode(this, n);
var node = this;
var nodeUrl = n.url;
var nodeFollowRedirects = n["follow-redirects"];
var isTemplatedUrl = (nodeUrl || "").indexOf("{{") != -1;
var nodeMethod = n.method || "GET";
if (n.tls) {
var tlsNode = RED.nodes.getNode(n.tls);
}
this.ret = n.ret || "txt";
if (RED.settings.httpRequestTimeout) {
this.reqTimeout = parseInt(RED.settings.httpRequestTimeout) || 120000;
} else {
this.reqTimeout = 120000;
}
this.on("input", function (msg) {
var preRequestTimestamp = process.hrtime();
node.status({
fill: "blue",
shape: "dot",
text: "httpin.status.requesting"
});
var url = nodeUrl || msg.url;
if (msg.url && nodeUrl && (nodeUrl !== msg.url)) { // revert change below when warning is finally removed
node.warn(RED._("common.errors.nooverride"));
}
var re = new RegExp("\\{\\{\\{(" + Object.keys(msg).join("|") + ")\\}\\}\\}", "g");
url = url.replace(re, function (a, b) {
return msg[b];
});
if (!url) {
node.error(RED._("httpin.errors.no-url"), msg);
node.status({
fill: "red",
shape: "ring",
text: (RED._("httpin.errors.no-url"))
});
return;
}
// url must start http:// or https:// so assume http:// if not set
if (!((url.indexOf("http://") === 0) || (url.indexOf("https://") === 0))) {
if (tlsNode) {
url = "https://" + url;
} else {
url = "http://" + url;
}
}
var method = nodeMethod.toUpperCase() || "GET";
if (msg.method && n.method && (n.method !== "use")) { // warn if override option not set
node.warn(RED._("common.errors.nooverride"));
}
if (msg.method && n.method && (n.method === "use")) {
method = msg.method.toUpperCase(); // use the msg parameter
}
var opts = {
method: method,
url: url,
timeout: node.reqTimeout,
followRedirect: nodeFollowRedirects,
headers: {}
};
if (msg.headers) {
for (var v in msg.headers) {
if (msg.headers.hasOwnProperty(v)) {
var name = v.toLowerCase();
if (name !== "content-type" && name !== "content-length") {
// only normalise the known headers used later in this
// function. Otherwise leave them alone.
name = v;
}
opts.headers[name] = msg.headers[v];
}
}
}
if (msg.payload && (method == "POST" || method == "PUT" || method == "PATCH")) {
if (opts.headers['content-type'] == 'application/x-www-form-urlencoded') {
opts.form = msg.payload;
} else if (opts.headers['content-type'] == 'multipart/form-data') {
opts.formData = msg.payload;
} else {
if (typeof msg.payload === "string" || Buffer.isBuffer(msg.payload)) {
opts.body = msg.payload;
} else if (typeof msg.payload == "number") {
opts.body = msg.payload + "";
} else {
opts.body = JSON.stringify(msg.payload);
if (opts.headers['content-type'] == null) {
opts.headers['content-type'] = "application/json";
}
}
}
}
if (this.credentials && this.credentials.user) {
opts.auth = {
user: this.credentials.user,
pass: this.credentials.password,
sendImmediately: false
}
}
if (tlsNode) {
tlsNode.addTLSOptions(opts);
}
request(opts, function (error, response, body) {
node.status({});
if (error) {
if (error.code === 'ETIMEDOUT') {
node.error(RED._("common.notification.errors.no-response"), msg);
setTimeout(function () {
node.status({
fill: "red",
shape: "ring",
text: "common.notification.errors.no-response"
});
}, 10);
} else {
node.error(error, msg);
msg.payload = error.toString() + " : " + url;
msg.statusCode = error.code;
node.send(msg);
node.status({
fill: "red",
shape: "ring",
text: error.code
});
}
} else {
msg.payload = body;
msg.headers = response.headers;
msg.statusCode = response.statusCode;
if (node.metric()) {
// Calculate request time
var diff = process.hrtime(preRequestTimestamp);
var ms = diff[0] * 1e3 + diff[1] * 1e-6;
var metricRequestDurationMillis = ms.toFixed(3);
node.metric("duration.millis", msg, metricRequestDurationMillis);
if (response.connection && response.connection.bytesRead) {
node.metric("size.bytes", msg, response.connection.bytesRead);
}
}
if (node.ret === "bin") {
msg.payload = new Buffer(msg.payload, "binary");
} else if (node.ret === "obj") {
try {
msg.payload = JSON.parse(msg.payload);
} catch (e) {
node.warn(RED._("httpin.errors.json-error"));
}
}
node.send(msg);
}
})
});
}
RED.nodes.registerType("www-request-multipart", HTTPRequest, {
credentials: {
user: {
type: "text"
},
password: {
type: "password"
}
}
});
}
| www-request-multipart.js | "use strict";
var request = require('request');
var mustache = require('mustache');
module.exports = function (RED) {
function HTTPRequest(n) {
RED.nodes.createNode(this, n);
var node = this;
var nodeUrl = n.url;
var nodeFollowRedirects = n["follow-redirects"];
var isTemplatedUrl = (nodeUrl || "").indexOf("{{") != -1;
var nodeMethod = n.method || "GET";
if (n.tls) {
var tlsNode = RED.nodes.getNode(n.tls);
}
this.ret = n.ret || "txt";
if (RED.settings.httpRequestTimeout) {
this.reqTimeout = parseInt(RED.settings.httpRequestTimeout) || 120000;
} else {
this.reqTimeout = 120000;
}
this.on("input", function (msg) {
var preRequestTimestamp = process.hrtime();
node.status({
fill: "blue",
shape: "dot",
text: "httpin.status.requesting"
});
var url = nodeUrl || msg.url;
if (msg.url && nodeUrl && (nodeUrl !== msg.url)) { // revert change below when warning is finally removed
node.warn(RED._("common.errors.nooverride"));
}
if (isTemplatedUrl) {
url = mustache.render(nodeUrl, msg);
}
if (!url) {
node.error(RED._("httpin.errors.no-url"), msg);
node.status({
fill: "red",
shape: "ring",
text: (RED._("httpin.errors.no-url"))
});
return;
}
// url must start http:// or https:// so assume http:// if not set
if (!((url.indexOf("http://") === 0) || (url.indexOf("https://") === 0))) {
if (tlsNode) {
url = "https://" + url;
} else {
url = "http://" + url;
}
}
var method = nodeMethod.toUpperCase() || "GET";
if (msg.method && n.method && (n.method !== "use")) { // warn if override option not set
node.warn(RED._("common.errors.nooverride"));
}
if (msg.method && n.method && (n.method === "use")) {
method = msg.method.toUpperCase(); // use the msg parameter
}
var opts = {
method: method,
url: url,
timeout: node.reqTimeout,
followRedirect: nodeFollowRedirects,
headers: {}
};
if (msg.headers) {
for (var v in msg.headers) {
if (msg.headers.hasOwnProperty(v)) {
var name = v.toLowerCase();
if (name !== "content-type" && name !== "content-length") {
// only normalise the known headers used later in this
// function. Otherwise leave them alone.
name = v;
}
opts.headers[name] = msg.headers[v];
}
}
}
if (msg.payload && (method == "POST" || method == "PUT" || method == "PATCH")) {
if (opts.headers['content-type'] == 'application/x-www-form-urlencoded') {
opts.form = msg.payload;
} else if (opts.headers['content-type'] == 'multipart/form-data') {
opts.formData = msg.payload;
} else {
if (typeof msg.payload === "string" || Buffer.isBuffer(msg.payload)) {
opts.body = msg.payload;
} else if (typeof msg.payload == "number") {
opts.body = msg.payload + "";
} else {
opts.body = JSON.stringify(msg.payload);
if (opts.headers['content-type'] == null) {
opts.headers['content-type'] = "application/json";
}
}
}
}
if (this.credentials && this.credentials.user) {
opts.auth = {
user: this.credentials.user,
pass: this.credentials.password,
sendImmediately: false
}
}
if (tlsNode) {
tlsNode.addTLSOptions(opts);
}
request(opts, function (error, response, body) {
node.status({});
if (error) {
if (error.code === 'ETIMEDOUT') {
node.error(RED._("common.notification.errors.no-response"), msg);
setTimeout(function () {
node.status({
fill: "red",
shape: "ring",
text: "common.notification.errors.no-response"
});
}, 10);
} else {
node.error(error, msg);
msg.payload = error.toString() + " : " + url;
msg.statusCode = error.code;
node.send(msg);
node.status({
fill: "red",
shape: "ring",
text: error.code
});
}
} else {
msg.payload = body;
msg.headers = response.headers;
msg.statusCode = response.statusCode;
if (node.metric()) {
// Calculate request time
var diff = process.hrtime(preRequestTimestamp);
var ms = diff[0] * 1e3 + diff[1] * 1e-6;
var metricRequestDurationMillis = ms.toFixed(3);
node.metric("duration.millis", msg, metricRequestDurationMillis);
if (response.connection && response.connection.bytesRead) {
node.metric("size.bytes", msg, response.connection.bytesRead);
}
}
if (node.ret === "bin") {
msg.payload = new Buffer(msg.payload, "binary");
} else if (node.ret === "obj") {
try {
msg.payload = JSON.parse(msg.payload);
} catch (e) {
node.warn(RED._("httpin.errors.json-error"));
}
}
node.send(msg);
}
})
});
}
RED.nodes.registerType("www-request-multipart", HTTPRequest, {
credentials: {
user: {
type: "text"
},
password: {
type: "password"
}
}
});
}
| removed mustache
| www-request-multipart.js | removed mustache | <ide><path>ww-request-multipart.js
<ide> "use strict";
<ide>
<ide> var request = require('request');
<del>var mustache = require('mustache');
<ide>
<ide> module.exports = function (RED) {
<ide>
<ide> if (msg.url && nodeUrl && (nodeUrl !== msg.url)) { // revert change below when warning is finally removed
<ide> node.warn(RED._("common.errors.nooverride"));
<ide> }
<del> if (isTemplatedUrl) {
<del> url = mustache.render(nodeUrl, msg);
<del> }
<add>
<add> var re = new RegExp("\\{\\{\\{(" + Object.keys(msg).join("|") + ")\\}\\}\\}", "g");
<add> url = url.replace(re, function (a, b) {
<add> return msg[b];
<add> });
<add>
<ide> if (!url) {
<ide> node.error(RED._("httpin.errors.no-url"), msg);
<ide> node.status({ |
|
Java | apache-2.0 | 55e9dfb95e8bf747591e8a067cf518ed68f39714 | 0 | dashorst/wicket,dashorst/wicket,mosoft521/wicket,topicusonderwijs/wicket,freiheit-com/wicket,aldaris/wicket,zwsong/wicket,mafulafunk/wicket,zwsong/wicket,Servoy/wicket,martin-g/wicket-osgi,klopfdreh/wicket,zwsong/wicket,apache/wicket,selckin/wicket,zwsong/wicket,freiheit-com/wicket,topicusonderwijs/wicket,topicusonderwijs/wicket,martin-g/wicket-osgi,AlienQueen/wicket,aldaris/wicket,klopfdreh/wicket,astrapi69/wicket,astrapi69/wicket,Servoy/wicket,selckin/wicket,mosoft521/wicket,freiheit-com/wicket,mosoft521/wicket,selckin/wicket,Servoy/wicket,freiheit-com/wicket,dashorst/wicket,mosoft521/wicket,bitstorm/wicket,dashorst/wicket,dashorst/wicket,bitstorm/wicket,freiheit-com/wicket,klopfdreh/wicket,aldaris/wicket,aldaris/wicket,topicusonderwijs/wicket,AlienQueen/wicket,selckin/wicket,topicusonderwijs/wicket,AlienQueen/wicket,selckin/wicket,bitstorm/wicket,AlienQueen/wicket,astrapi69/wicket,mafulafunk/wicket,astrapi69/wicket,apache/wicket,apache/wicket,Servoy/wicket,bitstorm/wicket,apache/wicket,AlienQueen/wicket,mosoft521/wicket,klopfdreh/wicket,aldaris/wicket,bitstorm/wicket,mafulafunk/wicket,Servoy/wicket,martin-g/wicket-osgi,klopfdreh/wicket,apache/wicket | /*
* 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 wicket.markup.parser.filter;
import java.text.ParseException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import wicket.Application;
import wicket.markup.ComponentTag;
import wicket.markup.MarkupElement;
import wicket.markup.parser.AbstractMarkupFilter;
/**
* This is a markup inline filter which by default is added to the list of
* markup filters.
* <p>
* The purpose of the filter is to prepend the web apps context path to all href
* and src attributes found in the markup which contain a relative URL like
* "myDir/myPage.gif". It is applied to all non wicket component tags
* (attributes).
*
* @author Juergen Donnerstag
*/
public final class PrependContextPathHandler extends AbstractMarkupFilter
{
/** Logging */
@SuppressWarnings("unused")
private static final Log log = LogFactory.getLog(PrependContextPathHandler.class);
/** List of attribute names considered */
private static final String attributeNames[] = new String[] { "href", "src", "background" };
/** == application.getApplicationSettings().getContextPath(); */
private final String contextPath;
/**
* This constructor will get the context path from the application settings.
* When it is not set the context path will be automatically resolved. This
* should work in most cases, and support the following clustering scheme
*
* <pre>
* node1.mydomain.com[/appcontext]
* node2.mydomain.com[/appcontext]
* node3.mydomain.com[/appcontext]
* </pre>
*
* If it is set then you can map to other context like in clusters
*
* <pre>
* node1.mydomain.com/mycontext1/
* node2.mydomain.com/mycontext2/
* node3.mydomain.com/mycontext3/
* mydomain.com/mycontext (load balancer)
* </pre>
*
* or as a virtual server (app server and webserver)
*
* <pre>
* appserver.com/context mapped to webserver/ (context path should be '/')
* </pre>
*
* @param application
* The application object
*
*/
public PrependContextPathHandler(final Application application)
{
String contextPath = application.getApplicationSettings().getContextPath();
if (contextPath != null)
{
if (contextPath.length() == 0)
{
contextPath = null;
}
else if (contextPath.endsWith("/") == false)
{
contextPath += "/";
}
}
this.contextPath = contextPath;
}
/**
* Get the next MarkupElement from the parent MarkupFilter and handle it if
* the specific filter criteria are met. Depending on the filter, it may
* return the MarkupElement unchanged, modified or it remove by asking the
* parent handler for the next tag.
*
* @see wicket.markup.parser.IMarkupFilter#nextTag()
* @return Return the next eligible MarkupElement
*/
public MarkupElement nextTag() throws ParseException
{
// Get the next tag. If null, no more tags are available
final ComponentTag tag = nextComponentTag();
if (tag == null || tag.getId() != null)
{
return tag;
}
// Don't touch any wicket:id component
if (tag.getId() != null)
{
return tag;
}
// this call should always get the default of the application or the
// overriden one.
if (contextPath != null)
{
for (final String attrName : attributeNames)
{
final String attrValue = tag.getAttributes().getString(attrName);
if ((attrValue != null) && (attrValue.startsWith("/") == false)
&& (attrValue.indexOf(":") < 0) && !(attrValue.startsWith("#")))
{
final String url;
if (this.contextPath != null)
{
url = contextPath + attrValue;
}
else
{
url = attrValue;
}
tag.getAttributes().put(attrName, url);
tag.setModified(true);
}
}
}
return tag;
}
}
| wicket/src/main/java/wicket/markup/parser/filter/PrependContextPathHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package wicket.markup.parser.filter;
import java.text.ParseException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import wicket.Application;
import wicket.markup.ComponentTag;
import wicket.markup.MarkupElement;
import wicket.markup.parser.AbstractMarkupFilter;
/**
* This is a markup inline filter which by default is added to the list of
* markup filters.
* <p>
* The purpose of the filter is to prepend the web apps context path to all href
* and src attributes found in the markup which contain a relative URL like
* "myDir/myPage.gif". It is applied to all non wicket component tags
* (attributes).
*
* @author Juergen Donnerstag
*/
public final class PrependContextPathHandler extends AbstractMarkupFilter
{
/** Logging */
@SuppressWarnings("unused")
private static final Log log = LogFactory.getLog(PrependContextPathHandler.class);
/** List of attribute names considered */
private static final String attributeNames[] = new String[] { "href", "src" };
/** == application.getApplicationSettings().getContextPath(); */
private final String contextPath;
/**
* This constructor will get the context path from the application settings.
* When it is not set the context path will be automatically resolved. This
* should work in most cases, and support the following clustering scheme
*
* <pre>
* node1.mydomain.com[/appcontext]
* node2.mydomain.com[/appcontext]
* node3.mydomain.com[/appcontext]
* </pre>
*
* If it is set then you can map to other context like in clusters
*
* <pre>
* node1.mydomain.com/mycontext1/
* node2.mydomain.com/mycontext2/
* node3.mydomain.com/mycontext3/
* mydomain.com/mycontext (load balancer)
* </pre>
*
* or as a virtual server (app server and webserver)
*
* <pre>
* appserver.com/context mapped to webserver/ (context path should be '/')
* </pre>
*
* @param application
* The application object
*
*/
public PrependContextPathHandler(final Application application)
{
String contextPath = application.getApplicationSettings().getContextPath();
if (contextPath != null)
{
if (contextPath.length() == 0)
{
contextPath = null;
}
else if (contextPath.endsWith("/") == false)
{
contextPath += "/";
}
}
this.contextPath = contextPath;
}
/**
* Get the next MarkupElement from the parent MarkupFilter and handle it if
* the specific filter criteria are met. Depending on the filter, it may
* return the MarkupElement unchanged, modified or it remove by asking the
* parent handler for the next tag.
*
* @see wicket.markup.parser.IMarkupFilter#nextTag()
* @return Return the next eligible MarkupElement
*/
public MarkupElement nextTag() throws ParseException
{
// Get the next tag. If null, no more tags are available
final ComponentTag tag = nextComponentTag();
if (tag == null || tag.getId() != null)
{
return tag;
}
// Don't touch any wicket:id component
if (tag.getId() != null)
{
return tag;
}
// this call should always get the default of the application or the
// overriden one.
if (contextPath != null)
{
for (final String attrName : attributeNames)
{
final String attrValue = tag.getAttributes().getString(attrName);
if ((attrValue != null) && (attrValue.startsWith("/") == false)
&& (attrValue.indexOf(":") < 0) && !(attrValue.startsWith("#")))
{
final String url;
if (this.contextPath != null)
{
url = contextPath + attrValue;
}
else
{
url = attrValue;
}
tag.getAttributes().put(attrName, url);
tag.setModified(true);
}
}
}
return tag;
}
}
| WICKET-171
git-svn-id: ac804e38dcddf5e42ac850d29d9218b7df6087b7@490395 13f79535-47bb-0310-9956-ffa450edef68
| wicket/src/main/java/wicket/markup/parser/filter/PrependContextPathHandler.java | WICKET-171 | <ide><path>icket/src/main/java/wicket/markup/parser/filter/PrependContextPathHandler.java
<ide> private static final Log log = LogFactory.getLog(PrependContextPathHandler.class);
<ide>
<ide> /** List of attribute names considered */
<del> private static final String attributeNames[] = new String[] { "href", "src" };
<add> private static final String attributeNames[] = new String[] { "href", "src", "background" };
<ide>
<ide> /** == application.getApplicationSettings().getContextPath(); */
<ide> private final String contextPath; |
|
Java | epl-1.0 | error: pathspec 'qp-enterprise-integration-platform/eip-generator-plugin/src/main/java/com/qpark/maven/plugin/springconfig/Jaxb2MarshallerConfigMojo.java' did not match any file(s) known to git
| 5e0a2d8d63340d4cf57ad5cba726d109f803496f | 1 | QPark/EIP | /*******************************************************************************
* Copyright (c) 2013, 2014, 2015 QPark Consulting S.a r.l. This program and the
* accompanying materials are made available under the terms of the Eclipse
* Public License v1.0. The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html.
******************************************************************************/
package com.qpark.maven.plugin.springconfig;
import java.io.File;
import java.util.List;
import java.util.Objects;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecution;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.slf4j.impl.StaticLoggerBinder;
import com.qpark.maven.Util;
import com.qpark.maven.xmlbeans.ServiceIdRegistry;
import com.qpark.maven.xmlbeans.XsdsUtil;
/**
* This plugin creates a org.springframework.oxm.jaxb.Jaxb2Marshaller for all
* given serviceIds.
*
* @author bhausen
*/
@Mojo(name = "generate-mashaller-config", defaultPhase = LifecyclePhase.GENERATE_RESOURCES)
public class Jaxb2MarshallerConfigMojo extends AbstractMojo {
/** The base directory where to start the scan of xsd files. */
@Parameter(property = "baseDirectory", defaultValue = "${project.build.directory}/model")
protected File baseDirectory;
/** The base directory where to start the scan of xsd files. */
@Parameter(property = "outputDirectory", defaultValue = "${project.build.directory}/generated-sources")
protected File outputDirectory;
/**
* The package name of the messages should end with this. Default is
* <code>msg flow</code>.
*/
@Parameter(property = "messagePackageNameSuffix", defaultValue = "msg flow")
protected String messagePackageNameSuffix;
/**
* The package name of the delta should contain this. Default is
* <code>delta</code>.
*/
@Parameter(property = "deltaPackageNameSuffix", defaultValue = "delta")
protected String deltaPackageNameSuffix;
/** The base package name where to place the object factories. */
@Parameter(property = "basePackageName", defaultValue = "")
protected String basePackageName;
/**
* The service request name need to end with this suffix (Default
* <code>Request</code>).
*/
@Parameter(property = "serviceRequestSuffix", defaultValue = "Request")
protected String serviceRequestSuffix;
/**
* The service response name need to end with this suffix (Default
* <code>Response</code>).
*/
@Parameter(property = "serviceResponseSuffix", defaultValue = "Response")
protected String serviceResponseSuffix;
@Parameter(defaultValue = "${project}", readonly = true)
protected MavenProject project;
@Parameter(defaultValue = "${mojoExecution}", readonly = true)
protected MojoExecution execution;
/** The name of the service id to generate. If empty use all. */
@Parameter(property = "serviceId", defaultValue = "")
protected String serviceId;
/**
* @see org.apache.maven.plugin.Mojo#execute()
*/
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
StaticLoggerBinder.getSingleton().setLog(this.getLog());
this.getLog().debug("+execute");
this.getLog().debug("get xsds");
XsdsUtil xsds = XsdsUtil.getInstance(this.baseDirectory,
this.basePackageName, this.messagePackageNameSuffix,
this.deltaPackageNameSuffix, this.serviceRequestSuffix,
this.serviceResponseSuffix);
this.generate(xsds);
this.getLog().debug("-execute");
}
protected void generate(final XsdsUtil xsds) {
this.getLog().debug("+generateService");
String eipVersion = this.getEipVersion();
StringBuffer capitalizeName = new StringBuffer(
Util.capitalizePackageName(this.basePackageName));
StringBuffer fileName = new StringBuffer(64)
.append(this.basePackageName);
if (Objects.nonNull(this.serviceId)
&& this.serviceId.trim().length() > 0) {
fileName.append(".").append(this.serviceId.trim());
capitalizeName.append(
ServiceIdRegistry.capitalize(this.serviceId.trim()));
}
fileName.append("-jaxb2marshaller-spring-config.xml");
StringBuffer xml = new StringBuffer();
xml.append(this.getXmlDefinition());
xml.append(Util.getGeneratedAtXmlComment(this.getClass(), eipVersion));
xml.append("\t<!-- Marshaller of services -->\n");
xml.append("\t<bean id=\"eipCaller").append(capitalizeName)
.append("Marshaller\"");
xml.append(
" class=\"org.springframework.oxm.jaxb.Jaxb2Marshaller\">\n");
xml.append("\t\t<property name=\"packagesToScan\">\n");
xml.append("\t\t\t<list>\n");
List<String> sids = ServiceIdRegistry.splitServiceIds(this.serviceId);
if (sids.isEmpty()) {
sids.addAll(xsds.getServiceIdRegistry().getAllServiceIds());
}
sids.stream()
.map(sid -> xsds.getServiceIdRegistry().getServiceIdEntry(sid))
.forEach(side -> {
xml.append("\t\t\t\t<value>");
xml.append(side.getPackageName());
xml.append("</value>\n");
});
xml.append("\t\t\t</list>\n");
xml.append("\t\t</property>\n");
xml.append("\t</bean>\n");
xml.append("\n</beans>\n");
File f = Util.getFile(this.outputDirectory, "", fileName.toString());
this.getLog().info(new StringBuffer().append("Write ")
.append(f.getAbsolutePath()));
try {
Util.writeToFile(f, xml.toString());
} catch (Exception e) {
this.getLog().error(e.getMessage());
e.printStackTrace();
}
this.getLog().debug("-generateService");
}
/**
* Get the executing plugin version - the EIP version.
*
* @return the EIP version.
*/
protected String getEipVersion() {
return this.execution.getVersion();
}
private String getXmlDefinition() {
StringBuffer sb = new StringBuffer(1024);
sb.append(
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n");
sb.append(
"<beans xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n");
sb.append("\txmlns=\"http://www.springframework.org/schema/beans\"\n");
sb.append(
"\txmlns:int=\"http://www.springframework.org/schema/integration\"\n");
sb.append(
"\txmlns:int-ws=\"http://www.springframework.org/schema/integration/ws\"\n");
sb.append(
"\txmlns:oxm=\"http://www.springframework.org/schema/oxm\" \n");
sb.append(
"\txmlns:util=\"http://www.springframework.org/schema/util\"\n");
sb.append("\txsi:schemaLocation=\"\n");
String springVersion = this.project.getProperties()
.getProperty("org.springframework.version.xsd.version");
sb.append(
"\t\thttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans");
if (springVersion != null) {
sb.append("-").append(springVersion);
}
sb.append(".xsd\n");
sb.append(
"\t\thttp://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm");
if (springVersion != null) {
sb.append("-").append(springVersion);
}
sb.append(".xsd\n");
sb.append(
"\t\thttp://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util");
if (springVersion != null) {
sb.append("-").append(springVersion);
}
sb.append(".xsd\n");
springVersion = this.project.getProperties().getProperty(
"org.springframework.integration.version.xsd.version");
sb.append(
"\t\thttp://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration");
if (springVersion != null) {
sb.append("-").append(springVersion);
}
sb.append(".xsd\n");
sb.append(
"\t\thttp://www.springframework.org/schema/integration/ws http://www.springframework.org/schema/integration/ws/spring-integration-ws");
if (springVersion != null) {
sb.append("-").append(springVersion);
}
sb.append(".xsd\n");
sb.append("\t\"\n>\n");
return sb.toString();
}
}
| qp-enterprise-integration-platform/eip-generator-plugin/src/main/java/com/qpark/maven/plugin/springconfig/Jaxb2MarshallerConfigMojo.java | Added spring Jaxb2Mashaller config generator
| qp-enterprise-integration-platform/eip-generator-plugin/src/main/java/com/qpark/maven/plugin/springconfig/Jaxb2MarshallerConfigMojo.java | Added spring Jaxb2Mashaller config generator | <ide><path>p-enterprise-integration-platform/eip-generator-plugin/src/main/java/com/qpark/maven/plugin/springconfig/Jaxb2MarshallerConfigMojo.java
<add>/*******************************************************************************
<add> * Copyright (c) 2013, 2014, 2015 QPark Consulting S.a r.l. This program and the
<add> * accompanying materials are made available under the terms of the Eclipse
<add> * Public License v1.0. The Eclipse Public License is available at
<add> * http://www.eclipse.org/legal/epl-v10.html.
<add> ******************************************************************************/
<add>package com.qpark.maven.plugin.springconfig;
<add>
<add>import java.io.File;
<add>import java.util.List;
<add>import java.util.Objects;
<add>
<add>import org.apache.maven.plugin.AbstractMojo;
<add>import org.apache.maven.plugin.MojoExecution;
<add>import org.apache.maven.plugin.MojoExecutionException;
<add>import org.apache.maven.plugin.MojoFailureException;
<add>import org.apache.maven.plugins.annotations.LifecyclePhase;
<add>import org.apache.maven.plugins.annotations.Mojo;
<add>import org.apache.maven.plugins.annotations.Parameter;
<add>import org.apache.maven.project.MavenProject;
<add>import org.slf4j.impl.StaticLoggerBinder;
<add>
<add>import com.qpark.maven.Util;
<add>import com.qpark.maven.xmlbeans.ServiceIdRegistry;
<add>import com.qpark.maven.xmlbeans.XsdsUtil;
<add>
<add>/**
<add> * This plugin creates a org.springframework.oxm.jaxb.Jaxb2Marshaller for all
<add> * given serviceIds.
<add> *
<add> * @author bhausen
<add> */
<add>@Mojo(name = "generate-mashaller-config", defaultPhase = LifecyclePhase.GENERATE_RESOURCES)
<add>public class Jaxb2MarshallerConfigMojo extends AbstractMojo {
<add> /** The base directory where to start the scan of xsd files. */
<add> @Parameter(property = "baseDirectory", defaultValue = "${project.build.directory}/model")
<add> protected File baseDirectory;
<add> /** The base directory where to start the scan of xsd files. */
<add> @Parameter(property = "outputDirectory", defaultValue = "${project.build.directory}/generated-sources")
<add> protected File outputDirectory;
<add> /**
<add> * The package name of the messages should end with this. Default is
<add> * <code>msg flow</code>.
<add> */
<add> @Parameter(property = "messagePackageNameSuffix", defaultValue = "msg flow")
<add> protected String messagePackageNameSuffix;
<add> /**
<add> * The package name of the delta should contain this. Default is
<add> * <code>delta</code>.
<add> */
<add> @Parameter(property = "deltaPackageNameSuffix", defaultValue = "delta")
<add> protected String deltaPackageNameSuffix;
<add> /** The base package name where to place the object factories. */
<add> @Parameter(property = "basePackageName", defaultValue = "")
<add> protected String basePackageName;
<add> /**
<add> * The service request name need to end with this suffix (Default
<add> * <code>Request</code>).
<add> */
<add> @Parameter(property = "serviceRequestSuffix", defaultValue = "Request")
<add> protected String serviceRequestSuffix;
<add> /**
<add> * The service response name need to end with this suffix (Default
<add> * <code>Response</code>).
<add> */
<add> @Parameter(property = "serviceResponseSuffix", defaultValue = "Response")
<add> protected String serviceResponseSuffix;
<add> @Parameter(defaultValue = "${project}", readonly = true)
<add> protected MavenProject project;
<add> @Parameter(defaultValue = "${mojoExecution}", readonly = true)
<add> protected MojoExecution execution;
<add> /** The name of the service id to generate. If empty use all. */
<add> @Parameter(property = "serviceId", defaultValue = "")
<add> protected String serviceId;
<add>
<add> /**
<add> * @see org.apache.maven.plugin.Mojo#execute()
<add> */
<add> @Override
<add> public void execute() throws MojoExecutionException, MojoFailureException {
<add> StaticLoggerBinder.getSingleton().setLog(this.getLog());
<add> this.getLog().debug("+execute");
<add> this.getLog().debug("get xsds");
<add> XsdsUtil xsds = XsdsUtil.getInstance(this.baseDirectory,
<add> this.basePackageName, this.messagePackageNameSuffix,
<add> this.deltaPackageNameSuffix, this.serviceRequestSuffix,
<add> this.serviceResponseSuffix);
<add>
<add> this.generate(xsds);
<add>
<add> this.getLog().debug("-execute");
<add> }
<add>
<add> protected void generate(final XsdsUtil xsds) {
<add> this.getLog().debug("+generateService");
<add>
<add> String eipVersion = this.getEipVersion();
<add> StringBuffer capitalizeName = new StringBuffer(
<add> Util.capitalizePackageName(this.basePackageName));
<add> StringBuffer fileName = new StringBuffer(64)
<add> .append(this.basePackageName);
<add> if (Objects.nonNull(this.serviceId)
<add> && this.serviceId.trim().length() > 0) {
<add> fileName.append(".").append(this.serviceId.trim());
<add> capitalizeName.append(
<add> ServiceIdRegistry.capitalize(this.serviceId.trim()));
<add> }
<add> fileName.append("-jaxb2marshaller-spring-config.xml");
<add>
<add> StringBuffer xml = new StringBuffer();
<add>
<add> xml.append(this.getXmlDefinition());
<add> xml.append(Util.getGeneratedAtXmlComment(this.getClass(), eipVersion));
<add>
<add> xml.append("\t<!-- Marshaller of services -->\n");
<add> xml.append("\t<bean id=\"eipCaller").append(capitalizeName)
<add> .append("Marshaller\"");
<add> xml.append(
<add> " class=\"org.springframework.oxm.jaxb.Jaxb2Marshaller\">\n");
<add>
<add> xml.append("\t\t<property name=\"packagesToScan\">\n");
<add> xml.append("\t\t\t<list>\n");
<add> List<String> sids = ServiceIdRegistry.splitServiceIds(this.serviceId);
<add> if (sids.isEmpty()) {
<add> sids.addAll(xsds.getServiceIdRegistry().getAllServiceIds());
<add> }
<add> sids.stream()
<add> .map(sid -> xsds.getServiceIdRegistry().getServiceIdEntry(sid))
<add> .forEach(side -> {
<add> xml.append("\t\t\t\t<value>");
<add> xml.append(side.getPackageName());
<add> xml.append("</value>\n");
<add> });
<add> xml.append("\t\t\t</list>\n");
<add> xml.append("\t\t</property>\n");
<add>
<add> xml.append("\t</bean>\n");
<add> xml.append("\n</beans>\n");
<add>
<add> File f = Util.getFile(this.outputDirectory, "", fileName.toString());
<add> this.getLog().info(new StringBuffer().append("Write ")
<add> .append(f.getAbsolutePath()));
<add> try {
<add> Util.writeToFile(f, xml.toString());
<add> } catch (Exception e) {
<add> this.getLog().error(e.getMessage());
<add> e.printStackTrace();
<add> }
<add>
<add> this.getLog().debug("-generateService");
<add> }
<add>
<add> /**
<add> * Get the executing plugin version - the EIP version.
<add> *
<add> * @return the EIP version.
<add> */
<add> protected String getEipVersion() {
<add> return this.execution.getVersion();
<add> }
<add>
<add> private String getXmlDefinition() {
<add> StringBuffer sb = new StringBuffer(1024);
<add> sb.append(
<add> "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n");
<add> sb.append(
<add> "<beans xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n");
<add> sb.append("\txmlns=\"http://www.springframework.org/schema/beans\"\n");
<add> sb.append(
<add> "\txmlns:int=\"http://www.springframework.org/schema/integration\"\n");
<add> sb.append(
<add> "\txmlns:int-ws=\"http://www.springframework.org/schema/integration/ws\"\n");
<add> sb.append(
<add> "\txmlns:oxm=\"http://www.springframework.org/schema/oxm\" \n");
<add> sb.append(
<add> "\txmlns:util=\"http://www.springframework.org/schema/util\"\n");
<add> sb.append("\txsi:schemaLocation=\"\n");
<add> String springVersion = this.project.getProperties()
<add> .getProperty("org.springframework.version.xsd.version");
<add> sb.append(
<add> "\t\thttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans");
<add> if (springVersion != null) {
<add> sb.append("-").append(springVersion);
<add> }
<add> sb.append(".xsd\n");
<add> sb.append(
<add> "\t\thttp://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm");
<add> if (springVersion != null) {
<add> sb.append("-").append(springVersion);
<add> }
<add> sb.append(".xsd\n");
<add> sb.append(
<add> "\t\thttp://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util");
<add> if (springVersion != null) {
<add> sb.append("-").append(springVersion);
<add> }
<add> sb.append(".xsd\n");
<add>
<add> springVersion = this.project.getProperties().getProperty(
<add> "org.springframework.integration.version.xsd.version");
<add> sb.append(
<add> "\t\thttp://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration");
<add> if (springVersion != null) {
<add> sb.append("-").append(springVersion);
<add> }
<add> sb.append(".xsd\n");
<add> sb.append(
<add> "\t\thttp://www.springframework.org/schema/integration/ws http://www.springframework.org/schema/integration/ws/spring-integration-ws");
<add> if (springVersion != null) {
<add> sb.append("-").append(springVersion);
<add> }
<add> sb.append(".xsd\n");
<add> sb.append("\t\"\n>\n");
<add> return sb.toString();
<add> }
<add>} |
|
Java | apache-2.0 | 2ad6a4b93b710b51d24e0c93b27112dd04b18ad5 | 0 | bobdenardd/twttwinbot,bobdenardd/twttwinbot | package com.pject.sources.parsing;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
import com.google.common.primitives.Ints;
import com.pject.helpers.LogFormatHelper;
import com.pject.helpers.StatsHelper;
import com.pject.sources.Source;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.List;
import java.util.Random;
/**
* InstagramSource - Short description of the class
*
* @author Camille
* Last: 29/09/2015 15:06
* @version $Id$
*/
public class InstagramSource implements Source {
private static final Logger LOGGER = Logger.getLogger(InstagramSource.class);
private static final String NAME = "instagram";
private static final List<String> INSTA_URLS = Lists.newArrayList(
"http://www.hashtagig.com/analytics/instagood",
"http://www.hashtagig.com/analytics/love",
"http://www.hashtagig.com/analytics/photooftheday",
"http://www.hashtagig.com/analytics/beautiful"
);
private static final int MAX_INSTAS_PER_TAG = 35;
private List<String> sources = Lists.newArrayList();
public InstagramSource() {
LOGGER.info("Initializing instagram source");
long start = System.currentTimeMillis();
for(String instaUrl : INSTA_URLS) {
processHashTag(instaUrl);
}
StatsHelper.registerSource(NAME, System.currentTimeMillis() - start, this.sources.size());
LOGGER.info("Got " + this.sources.size() + " sources");
}
private void processHashTag(String hashTagUrl) {
if(LOGGER.isDebugEnabled()) {
LOGGER.debug("Processing hashtag analytics " + hashTagUrl);
}
HttpGet httpGet = new HttpGet(hashTagUrl);
try (CloseableHttpClient httpclient = HttpClients.createDefault(); CloseableHttpResponse response = httpclient.execute(httpGet)){
if(response.getStatusLine().getStatusCode() == 200) {
String raw = EntityUtils.toString(response.getEntity());
Document doc = Jsoup.parse(raw);
int i = 0;
for(Element element : doc.select("div.snapshot")) {
if(i > MAX_INSTAS_PER_TAG) {
break;
}
// Retrieving image
String imageUrl = null;
List<String> hashtags = null;
Elements elements = element.select("img");
if(elements.size() > 0) {
imageUrl = elements.get(0).attr("src");
hashtags = extractHashTags(elements.get(0).attr("title"));
}
// Building source
String source = mergeTagsWithPicture(imageUrl, hashtags);
if(source != null &&StringUtils.isNotEmpty(source)) {
this.sources.add(source.replace("s150x150", "510x510"));
i++;
}
}
}
} catch(IOException e) {
LOGGER.error("Could not load instagram links: " + LogFormatHelper.formatExceptionMessage(e));
}
}
private List<String> extractHashTags(String text) {
List<String> result = Lists.newArrayList();
if(StringUtils.isNotEmpty(text) && text.contains("#")) {
for(String token : text.split("#")) {
String potentialToken = StringUtils.trimToEmpty(token.replaceAll(" .*", StringUtils.EMPTY));
if(StringUtils.isNotEmpty(potentialToken)) {
result.add("#" + potentialToken);
}
}
}
return result;
}
private String mergeTagsWithPicture(String pictureUrl, List<String> hashtags) {
if(StringUtils.isEmpty(pictureUrl) || hashtags == null) {
return null;
}
// Preordering the list of hashtags
Ordering<String> o = new Ordering<String>() {
@Override
public int compare(String left, String right) {
return Ints.compare(left.length(), right.length());
}
};
// Merging stuff depending on the size
int possible = 139 - pictureUrl.length();
StringBuilder source = new StringBuilder();
while (possible > 0 && hashtags.size() > 0) {
String hash = o.min(hashtags);
if(possible - hash.length() - 1 > 0) {
source.append(hash).append(" ");
hashtags.remove(hash);
possible = possible - hash.length() - 1;
} else {
break;
}
}
source.setLength(Math.max(source.length() - 1, 0));
source.append(" ").append(pictureUrl);
return source.toString();
}
@Override
public String getTweet() {
if(this.sources.size() > 0) {
String source = this.sources.get(new Random().nextInt(this.sources.size()));
this.sources.remove(source);
return source;
}
return null;
}
}
| src/main/java/com/pject/sources/parsing/InstagramSource.java | package com.pject.sources.parsing;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
import com.google.common.primitives.Ints;
import com.pject.helpers.LogFormatHelper;
import com.pject.helpers.StatsHelper;
import com.pject.sources.Source;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.List;
import java.util.Random;
/**
* InstagramSource - Short description of the class
*
* @author Camille
* Last: 29/09/2015 15:06
* @version $Id$
*/
public class InstagramSource implements Source {
private static final Logger LOGGER = Logger.getLogger(InstagramSource.class);
private static final String NAME = "instagram";
private static final List<String> INSTA_URLS = Lists.newArrayList(
"http://www.hashtagig.com/analytics/instagood",
"http://www.hashtagig.com/analytics/love",
"http://www.hashtagig.com/analytics/photooftheday",
"http://www.hashtagig.com/analytics/beautiful"
);
private static final int MAX_INSTAS_PER_TAG = 35;
private List<String> sources = Lists.newArrayList();
public InstagramSource() {
LOGGER.info("Initializing instagram source");
long start = System.currentTimeMillis();
for(String instaUrl : INSTA_URLS) {
processHashTag(instaUrl);
}
StatsHelper.registerSource(NAME, System.currentTimeMillis() - start, this.sources.size());
LOGGER.info("Got " + this.sources.size() + " sources");
}
private void processHashTag(String hashTagUrl) {
if(LOGGER.isDebugEnabled()) {
LOGGER.debug("Processing hashtag analytics " + hashTagUrl);
}
HttpGet httpGet = new HttpGet(hashTagUrl);
try (CloseableHttpClient httpclient = HttpClients.createDefault(); CloseableHttpResponse response = httpclient.execute(httpGet)){
if(response.getStatusLine().getStatusCode() == 200) {
String raw = EntityUtils.toString(response.getEntity());
Document doc = Jsoup.parse(raw);
int i = 0;
for(Element element : doc.select("div.snapshot")) {
if(i > MAX_INSTAS_PER_TAG) {
break;
}
// Retrieving image
String imageUrl = null;
List<String> hashtags = null;
Elements elements = element.select("img");
if(elements.size() > 0) {
imageUrl = elements.get(0).attr("src");
hashtags = extractHashTags(elements.get(0).attr("title"));
}
// Building source
String source = mergeTagsWithPicture(imageUrl, hashtags);
if(StringUtils.isNotEmpty(source)) {
this.sources.add(source);
i++;
}
}
}
} catch(IOException e) {
LOGGER.error("Could not load instagram links: " + LogFormatHelper.formatExceptionMessage(e));
}
}
private List<String> extractHashTags(String text) {
List<String> result = Lists.newArrayList();
if(StringUtils.isNotEmpty(text) && text.contains("#")) {
for(String token : text.split("#")) {
String potentialToken = StringUtils.trimToEmpty(token.replaceAll(" .*", StringUtils.EMPTY));
if(StringUtils.isNotEmpty(potentialToken)) {
result.add("#" + potentialToken);
}
}
}
return result;
}
private String mergeTagsWithPicture(String pictureUrl, List<String> hashtags) {
if(StringUtils.isEmpty(pictureUrl) || hashtags == null) {
return null;
}
// Preordering the list of hashtags
Ordering<String> o = new Ordering<String>() {
@Override
public int compare(String left, String right) {
return Ints.compare(left.length(), right.length());
}
};
// Merging stuff depending on the size
int possible = 139 - pictureUrl.length();
StringBuilder source = new StringBuilder();
while (possible > 0 && hashtags.size() > 0) {
String hash = o.min(hashtags);
if(possible - hash.length() - 1 > 0) {
source.append(hash).append(" ");
hashtags.remove(hash);
possible = possible - hash.length() - 1;
} else {
break;
}
}
source.setLength(Math.max(source.length() - 1, 0));
source.append(" ").append(pictureUrl);
return source.toString();
}
@Override
public String getTweet() {
if(this.sources.size() > 0) {
String source = this.sources.get(new Random().nextInt(this.sources.size()));
this.sources.remove(source);
return source;
}
return null;
}
}
| Quick hack for instagram photo size
| src/main/java/com/pject/sources/parsing/InstagramSource.java | Quick hack for instagram photo size | <ide><path>rc/main/java/com/pject/sources/parsing/InstagramSource.java
<ide>
<ide> // Building source
<ide> String source = mergeTagsWithPicture(imageUrl, hashtags);
<del> if(StringUtils.isNotEmpty(source)) {
<del> this.sources.add(source);
<add> if(source != null &&StringUtils.isNotEmpty(source)) {
<add> this.sources.add(source.replace("s150x150", "510x510"));
<ide> i++;
<ide> }
<ide> } |
|
Java | apache-2.0 | c0bba189f627fd47c61e79b271b6ca71d5362275 | 0 | farmerbb/Taskbar,farmerbb/Taskbar | /* Copyright 2016 Braden Farmer
*
* 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.farmerbb.taskbar.util;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.LauncherActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.UserManager;
import android.util.LruCache;
import com.farmerbb.taskbar.BuildConfig;
public class IconCache {
private final LruCache<String, BitmapDrawable> drawables;
private static IconCache theInstance;
private IconCache(Context context) {
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
final int memClass = am.getMemoryClass();
final int cacheSize = (1024 * 1024 * memClass) / 8;
drawables = new LruCache<String, BitmapDrawable>(cacheSize) {
@Override
protected int sizeOf(String key, BitmapDrawable value) {
return value.getBitmap().getByteCount();
}
};
}
public static IconCache getInstance(Context context) {
if(theInstance == null) theInstance = new IconCache(context);
return theInstance;
}
public BitmapDrawable getIcon(Context context, LauncherActivityInfo appInfo) {
return getIcon(context, context.getPackageManager(), appInfo);
}
public BitmapDrawable getIcon(Context context, PackageManager pm, LauncherActivityInfo appInfo) {
UserManager userManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
String name = appInfo.getComponentName().flattenToString() + ":" + userManager.getSerialNumberForUser(appInfo.getUser());
BitmapDrawable drawable;
synchronized (drawables) {
drawable = drawables.get(name);
if(drawable == null) {
Drawable loadedIcon = loadIcon(context, pm, appInfo);
if(loadedIcon instanceof BitmapDrawable)
drawable = (BitmapDrawable) loadedIcon;
else {
int width = Math.max(loadedIcon.getIntrinsicWidth(), 1);
int height = Math.max(loadedIcon.getIntrinsicHeight(), 1);
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
loadedIcon.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
loadedIcon.draw(canvas);
drawable = new BitmapDrawable(context.getResources(), bitmap);
}
drawables.put(name, drawable);
}
}
return drawable;
}
private Drawable loadIcon(Context context, PackageManager pm, LauncherActivityInfo appInfo) {
SharedPreferences pref = U.getSharedPreferences(context);
String iconPackPackage = pref.getString("icon_pack", context.getPackageName());
boolean useMask = pref.getBoolean("icon_pack_use_mask", false);
IconPackManager iconPackManager = IconPackManager.getInstance();
try {
pm.getPackageInfo(iconPackPackage, 0);
} catch (PackageManager.NameNotFoundException e) {
iconPackPackage = context.getPackageName();
pref.edit().putString("icon_pack", iconPackPackage).apply();
U.refreshPinnedIcons(context);
}
if(iconPackPackage.equals(context.getPackageName()))
return getIcon(pm, appInfo);
else {
IconPack iconPack = iconPackManager.getIconPack(iconPackPackage);
String componentName = new ComponentName(appInfo.getApplicationInfo().packageName, appInfo.getName()).toString();
if(!useMask) {
Drawable icon = iconPack.getDrawableIconForPackage(context, componentName);
return icon == null ? getIcon(pm, appInfo) : icon;
} else {
Drawable drawable = getIcon(pm, appInfo);
if(drawable instanceof BitmapDrawable) {
return new BitmapDrawable(context.getResources(),
iconPack.getIconForPackage(context, componentName, ((BitmapDrawable) drawable).getBitmap()));
} else {
Drawable icon = iconPack.getDrawableIconForPackage(context, componentName);
return icon == null ? drawable : icon;
}
}
}
}
public void clearCache() {
drawables.evictAll();
IconPackManager.getInstance().nullify();
System.gc();
}
private Drawable getIcon(PackageManager pm, LauncherActivityInfo appInfo) {
try {
return appInfo.getBadgedIcon(0);
} catch (NullPointerException e) {
return pm.getDefaultActivityIcon();
}
}
}
| app/src/main/java/com/farmerbb/taskbar/util/IconCache.java | /* Copyright 2016 Braden Farmer
*
* 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.farmerbb.taskbar.util;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.LauncherActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.UserManager;
import android.util.LruCache;
import com.farmerbb.taskbar.BuildConfig;
public class IconCache {
private final LruCache<String, BitmapDrawable> drawables;
private static IconCache theInstance;
private IconCache(Context context) {
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
final int memClass = am.getMemoryClass();
final int cacheSize = (1024 * 1024 * memClass) / 8;
drawables = new LruCache<String, BitmapDrawable>(cacheSize) {
@Override
protected int sizeOf(String key, BitmapDrawable value) {
return value.getBitmap().getByteCount();
}
};
}
public static IconCache getInstance(Context context) {
if(theInstance == null) theInstance = new IconCache(context);
return theInstance;
}
public Drawable getIcon(Context context, LauncherActivityInfo appInfo) {
return getIcon(context, context.getPackageManager(), appInfo);
}
public Drawable getIcon(Context context, PackageManager pm, LauncherActivityInfo appInfo) {
UserManager userManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
String name = appInfo.getComponentName().flattenToString() + ":" + userManager.getSerialNumberForUser(appInfo.getUser());
BitmapDrawable drawable;
synchronized (drawables) {
drawable = drawables.get(name);
if(drawable == null) {
Drawable loadedIcon = loadIcon(context, pm, appInfo);
if(loadedIcon instanceof BitmapDrawable)
drawable = (BitmapDrawable) loadedIcon;
else {
int width = Math.max(loadedIcon.getIntrinsicWidth(), 1);
int height = Math.max(loadedIcon.getIntrinsicHeight(), 1);
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
loadedIcon.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
loadedIcon.draw(canvas);
drawable = new BitmapDrawable(context.getResources(), bitmap);
}
drawables.put(name, drawable);
}
}
return drawable;
}
private Drawable loadIcon(Context context, PackageManager pm, LauncherActivityInfo appInfo) {
SharedPreferences pref = U.getSharedPreferences(context);
String iconPackPackage = pref.getString("icon_pack", context.getPackageName());
boolean useMask = pref.getBoolean("icon_pack_use_mask", false);
IconPackManager iconPackManager = IconPackManager.getInstance();
try {
pm.getPackageInfo(iconPackPackage, 0);
} catch (PackageManager.NameNotFoundException e) {
iconPackPackage = context.getPackageName();
pref.edit().putString("icon_pack", iconPackPackage).apply();
U.refreshPinnedIcons(context);
}
if(iconPackPackage.equals(context.getPackageName()))
return getIcon(pm, appInfo);
else {
IconPack iconPack = iconPackManager.getIconPack(iconPackPackage);
String componentName = new ComponentName(appInfo.getApplicationInfo().packageName, appInfo.getName()).toString();
if(!useMask) {
Drawable icon = iconPack.getDrawableIconForPackage(context, componentName);
return icon == null ? getIcon(pm, appInfo) : icon;
} else {
Drawable drawable = getIcon(pm, appInfo);
if(drawable instanceof BitmapDrawable) {
return new BitmapDrawable(context.getResources(),
iconPack.getIconForPackage(context, componentName, ((BitmapDrawable) drawable).getBitmap()));
} else {
Drawable icon = iconPack.getDrawableIconForPackage(context, componentName);
return icon == null ? drawable : icon;
}
}
}
}
public void clearCache() {
drawables.evictAll();
IconPackManager.getInstance().nullify();
System.gc();
}
private Drawable getIcon(PackageManager pm, LauncherActivityInfo appInfo) {
try {
return appInfo.getBadgedIcon(0);
} catch (NullPointerException e) {
return pm.getDefaultActivityIcon();
}
}
}
| Expose BitmapDrawable as the return type for IconCache.getIcon()
| app/src/main/java/com/farmerbb/taskbar/util/IconCache.java | Expose BitmapDrawable as the return type for IconCache.getIcon() | <ide><path>pp/src/main/java/com/farmerbb/taskbar/util/IconCache.java
<ide> return theInstance;
<ide> }
<ide>
<del> public Drawable getIcon(Context context, LauncherActivityInfo appInfo) {
<add> public BitmapDrawable getIcon(Context context, LauncherActivityInfo appInfo) {
<ide> return getIcon(context, context.getPackageManager(), appInfo);
<ide> }
<ide>
<del> public Drawable getIcon(Context context, PackageManager pm, LauncherActivityInfo appInfo) {
<add> public BitmapDrawable getIcon(Context context, PackageManager pm, LauncherActivityInfo appInfo) {
<ide> UserManager userManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
<ide> String name = appInfo.getComponentName().flattenToString() + ":" + userManager.getSerialNumberForUser(appInfo.getUser());
<ide> |
|
JavaScript | mit | 74d3bc3824fcce08ddae21e3e7509caa4ef10500 | 0 | severe-island/testero,severe-island/testero,severe-island/testero | var express = require('express');
var router = express.Router();
var db = require('../db');
var conf = require('../../../config');
router.post('/login', function(req, res, next) {
if (req.session.login) {
var status, level;
if (req.session.email === req.body.email) {
status = true;
level = "info";
}
else {
status = false;
level = "warning";
}
res.json({
msg: "Вы уже зашли с почтой " + req.session.email + ".",
status: status,
level: level
});
return;
}
var email = req.body.email;
var password = req.body.password;
var remember = (req.body.remember !== undefined);
db.findUserByEmail(email, function(err, data){
if(err || data==null) {
res.json({
msg: "Пользователь не найден!",
status: false,
level: "info"
})
return;
}
if(data.removed) {
res.json({
status: false,
level: "info",
msg: "Ваш пользователь удалён!"
});
return;
}
if(data.password != password) {
res.json({
msg: "Неверный пароль!",
status: false,
level: "info"
});
return;
}
var msg = "Вы вошли!"
if(remember){
msg+=" Я постараюсь вас запомнить."
req.session.cookie.originalMaxAge = 1000*60*60;
}
else {
req.session.cookie.originalMaxAge = null
req.session.cookie.expires = false
}
req.session.login = true
req.session.email = email
res.json({
msg: msg,
status: true,
level: "success"
});
});
});
router.post('/logout', function(req, res, next) {
if (req.session.login) {
delete req.session.login;
var email = req.session.email;
delete req.session.email;
res.json({
msg: "Вы вышли и теперь больше не " + email + ".",
status: true,
level: "success"
});
}
else {
res.json({
msg: "Так ведь вы и не входили!",
status: true,
level: "info"
});
}
});
router.post('/signup', function(req, res, next) {
if(req.session.login)
{
res.json({
msg: "Вы уже вошли как "+ req.session.email +"! Зачем вам регистрироваться?",
status: false,
level: "warning"
});
return;
}
if(!req.body.email || !req.body.password || !req.body.passwordDuplicate) {
res.json({
msg: "Указаны не все данные.",
status: false,
level: "danger"
});
return;
}
var email = req.body.email;
var password = req.body.password;
var passwordDuplicate = req.body.passwordDuplicate;
db.findUserByEmail(email, function(err, data) {
if(err)
{
res.json({
msg: "Ошибка БД: " + err.message,
status: false,
level: "danger"
});
return;
}
if(data!=null)
{
res.json({
msg: "Такой пользователь с этой почтой уже есть!",
status: false,
level: "danger"
});
return;
}
if (password != passwordDuplicate)
{
res.json({
msg: "Пароли не совпадают!",
status: false,
level: "danger"
});
return;
}
if(email.indexOf('@')<0)
{
res.json({
msg: "Некорректный email!",
status: false,
level: "danger"
});
}
db.addNewUser(email, password, false, function(err, newUser) {
if(err)
{
res.json({
msg: "Ошибка БД: " + err.message,
status: false,
level: "danger"
});
return;
}
delete newUser.password;
req.session.login = true;
req.session.email = email;
res.json({
msg: "Пользователь успешно зарегистрирован!",
status: true,
level: "success",
user: newUser
});
});
});
});
router.post('/registerUser', function(req, res, next) {
if (!req.session.login) {
res.json({
msg: "Вы должны быть авторизованным пользователем",
status: false,
level: "danger"
});
return;
}
db.findUserByEmail(req.session.email, function(err, data){
if (err || data === null) {
res.json({
msg: "Вы не являетесь пользователем системы",
status: false,
level: "danger"
});
return;
}
var initiator = data;
if (initiator.removed) {
res.json({
msg: "Ваш аккаунт " + email + " был удалён",
status: false,
level: "danger"
});
return;
}
if (!initiator.isAdministrator) {
res.json({
msg: "Только администратор может добавлять новых пользователей",
status: false,
level: "danger"
});
return;
}
var email = req.body.email;
var password = req.body.password;
var passwordDuplicate = req.body.passwordDuplicate;
var isAdministrator = req.body.isAdministrator;
var registeredBy = initiator.email;
if(!email) {
res.json({
msg: "Не задан email нового пользователя",
status: false,
level: "danger"
});
return;
}
if (email.indexOf('@') < 0) {
res.json({
msg: "Некорректный email",
status: false,
level: "danger"
});
return;
}
if (!password) {
res.json({
msg: "Не задан пароль нового пользователя",
status: false,
level: "danger"
});
return;
}
if (!passwordDuplicate) {
res.json({
msg: "Не задан повтор пароля нового пользователя",
status: false,
level: "danger"
});
return;
}
if (password !== passwordDuplicate) {
res.json({
msg: "Пароли не совпадают",
status: false,
level: "danger"
});
return;
}
db.findUserByEmail(email, function(err, data) {
if (err) {
var msg;
if (initiator.isAdministrator) {
msg = "Ошибка БД: " + err.message;
}
else {
msg = "Внутренняя ошибка сервера";
}
res.json({
msg: msg,
status: false,
level: "danger"
});
return;
}
if (data !== null) {
res.json({
msg: "Пользователь " + email + " уже есть",
status: false,
level: "warning"
});
return;
}
var user = {
email: email,
password: password,
isAdministrator: isAdministrator,
registeredBy: registeredBy
};
db.registerUser(user, function(err, newUser) {
if (err) {
res.json({
msg: "Ошибка БД: " + err.message,
status: false,
level: "danger"
});
return;
}
delete newUser.password;
/*req.session.login = true;
req.session.email = email;*/
res.json({
msg: "Пользователь " + email + " успешно зарегистрирован!",
status: true,
level: "success",
user: newUser
});
});
});
});
});
router.post('/requestRemoving', function(req, res, next) {
if(!req.session.login) {
res.json({
status: true,
level: "info",
msg: "Вы не вошли, поэтому не можете себя удалить."
});
return;
}
db.updateUser(req.session.email, { removingRequested: true }, req.session.email, function(err) {
if(err) {
res.json({
status: true,
level: "info",
msg: "Ошибка БД: " + err.message
});
return;
}
delete req.session.login;
delete req.session.email;
res.json({
status: true,
level: "info",
msg: "Запрос на удаление оставлен."
});
})
});
router.post('/removeUser', function(req, res, next) {
if(!req.session.login) {
res.json({
status: false,
level: "danger",
msg: "Сначала войдите в систему!"
})
return
}
if(!req.body.email) {
res.json({
status: false,
level: "danger",
msg: "Укажите email!"
});
return;
}
var targetEmail = req.body.email
db.findUserByEmail(req.session.email, function(err, user) {
if(err) {
res.json({
msg: "Ошибка БД: " + err.message,
status: false,
level: "danger"
});
return;
}
if(!user) {
res.json({
status: false,
level: "danger",
msg: "Сначала войдите в систему!"
})
return
}
if(!user.isAdministrator && user.email!==targetEmail) {
res.json({
msg: "Пользователя может удалить только администратор или сам пользователь",
status: false,
level: "danger"
});
return;
}
db.removeUser(targetEmail, function(err) {
if(err) {
res.json({
msg: "Ошибка БД: " + err.message,
status: false,
level: "danger"
});
return;
}
res.json({
msg: "Пользователь был удалён!: ",
status: true,
level: "success"
});
return;
})
})
})
router.post('/clearUsers', function(req, res, next) {
if(!req.session.login) {
res.json({
status: false,
level: "danger",
msg: "Сначала войдите в систему!"
})
return
}
db.findUserByEmail(req.session.email, function(err, user) {
if(err) {
res.json({
msg: "Ошибка БД: " + err.message,
status: false,
level: "danger"
});
return;
}
if(!user) {
res.json({
status: false,
level: "danger",
msg: "Сначала войдите в систему!"
})
return
}
if(!user.isAdministrator) {
res.json({
msg: "Очистить базу пользователей может только администратор!",
status: false,
level: "danger"
});
return;
}
db.clearUsers(function(err) {
if(err) {
res.json({
msg: "Ошибка БД: " + err.message,
status: false,
level: "danger"
});
return;
}
res.json({
msg: "Все пользователи были удалены!",
status: true,
level: "success"
});
})
})
})
router.post('/getMe', function(req, res, next) {
if(!req.session.login) {
res.json({
status: false,
level: "info",
msg: "Вы ещё не вошли в систему."
})
return;
}
db.findUserByEmailWithoutPassword(req.session.email, true, function(err, user) {
if(err) {
res.json({
status: false,
level: "danger",
msg: "Ошибка БД: " + err.message
})
return;
}
if(!user) {
res.json({
status: false,
level: "danger",
msg: "Пользователь не найден! Скорее всего, ошибка с сессией."
})
return;
}
res.json({
status: true,
level: "info",
msg: "Пользователь найден!",
user: user
})
})
})
module.exports = router;
| modules/users/route/index.js | var express = require('express');
var router = express.Router();
var db = require('../db');
var conf = require('../../../config');
router.post('/login', function(req, res, next) {
if (req.session.login) {
var status, level;
if (req.session.email === req.body.email) {
status = true;
level = "info";
}
else {
status = false;
level = "warning";
}
res.json({
msg: "Вы уже зашли с почтой " + req.session.email + ".",
status: status,
level: level
});
return;
}
var email = req.body.email;
var password = req.body.password;
var remember = (req.body.remember !== undefined);
db.findUserByEmail(email, function(err, data){
if(err || data==null) {
res.json({
msg: "Пользователь не найден!",
status: false,
level: "info"
})
return;
}
if(data.removed) {
res.json({
status: false,
level: "info",
msg: "Ваш пользователь удалён!"
});
return;
}
if(data.password != password) {
res.json({
msg: "Неверный пароль!",
status: false,
level: "info"
});
return;
}
var msg = "Вы вошли!"
if(remember){
msg+=" Я постараюсь вас запомнить."
req.session.cookie.originalMaxAge = 1000*60*60;
}
else {
req.session.cookie.originalMaxAge = null
req.session.cookie.expires = false
}
req.session.login = true
req.session.email = email
res.json({
msg: msg,
status: true,
level: "success"
});
});
});
router.post('/logout', function(req, res, next) {
if (req.session.login) {
delete req.session.login;
var email = req.session.email;
delete req.session.email;
res.json({
msg: "Вы вышли и теперь больше не " + email + ".",
status: true,
level: "success"
});
}
else {
res.json({
msg: "Так ведь вы и не входили!",
status: true,
level: "info"
});
}
});
router.post('/signup', function(req, res, next) {
if(!req.body.email || !req.body.password || !req.body.passwordDuplicate) {
res.json({
msg: "Указаны не все данные.",
status: false,
level: "danger"
});
return;
}
var email = req.body.email;
var password = req.body.password;
var passwordDuplicate = req.body.passwordDuplicate;
db.findUserByEmail(email, function(err, data) {
if(err)
{
res.json({
msg: "Ошибка БД: " + err.message,
status: false,
level: "danger"
});
return;
}
if(data!=null)
{
res.json({
msg: "Такой пользователь с этой почтой уже есть!",
status: false,
level: "danger"
});
return;
}
if (password != passwordDuplicate)
{
res.json({
msg: "Пароли не совпадают!",
status: false,
level: "danger"
});
return;
}
if(email.indexOf('@')<0)
{
res.json({
msg: "Некорректный email!",
status: false,
level: "danger"
});
}
db.addNewUser(email, password, false, function(err, newUser) {
if(err)
{
res.json({
msg: "Ошибка БД: " + err.message,
status: false,
level: "danger"
});
return;
}
delete newUser.password;
req.session.login = true;
req.session.email = email;
res.json({
msg: "Пользователь успешно зарегистрирован!",
status: true,
level: "success",
user: newUser
});
});
});
});
router.post('/registerUser', function(req, res, next) {
if (!req.session.login) {
res.json({
msg: "Вы должны быть авторизованным пользователем",
status: false,
level: "danger"
});
return;
}
db.findUserByEmail(req.session.email, function(err, data){
if (err || data === null) {
res.json({
msg: "Вы не являетесь пользователем системы",
status: false,
level: "danger"
});
return;
}
var initiator = data;
if (initiator.removed) {
res.json({
msg: "Ваш аккаунт " + email + " был удалён",
status: false,
level: "danger"
});
return;
}
if (!initiator.isAdministrator) {
res.json({
msg: "Только администратор может добавлять новых пользователей",
status: false,
level: "danger"
});
return;
}
var email = req.body.email;
var password = req.body.password;
var passwordDuplicate = req.body.passwordDuplicate;
var isAdministrator = req.body.isAdministrator;
var registeredBy = initiator.email;
if(!email) {
res.json({
msg: "Не задан email нового пользователя",
status: false,
level: "danger"
});
return;
}
if (email.indexOf('@') < 0) {
res.json({
msg: "Некорректный email",
status: false,
level: "danger"
});
return;
}
if (!password) {
res.json({
msg: "Не задан пароль нового пользователя",
status: false,
level: "danger"
});
return;
}
if (!passwordDuplicate) {
res.json({
msg: "Не задан повтор пароля нового пользователя",
status: false,
level: "danger"
});
return;
}
if (password !== passwordDuplicate) {
res.json({
msg: "Пароли не совпадают",
status: false,
level: "danger"
});
return;
}
db.findUserByEmail(email, function(err, data) {
if (err) {
var msg;
if (initiator.isAdministrator) {
msg = "Ошибка БД: " + err.message;
}
else {
msg = "Внутренняя ошибка сервера";
}
res.json({
msg: msg,
status: false,
level: "danger"
});
return;
}
if (data !== null) {
res.json({
msg: "Пользователь " + email + " уже есть",
status: false,
level: "warning"
});
return;
}
var user = {
email: email,
password: password,
isAdministrator: isAdministrator,
registeredBy: registeredBy
};
db.registerUser(user, function(err, newUser) {
if (err) {
res.json({
msg: "Ошибка БД: " + err.message,
status: false,
level: "danger"
});
return;
}
delete newUser.password;
/*req.session.login = true;
req.session.email = email;*/
res.json({
msg: "Пользователь " + email + " успешно зарегистрирован!",
status: true,
level: "success",
user: newUser
});
});
});
});
});
router.post('/requestRemoving', function(req, res, next) {
if(!req.session.login) {
res.json({
status: true,
level: "info",
msg: "Вы не вошли, поэтому не можете себя удалить."
});
return;
}
db.updateUser(req.session.email, { removingRequested: true }, req.session.email, function(err) {
if(err) {
res.json({
status: true,
level: "info",
msg: "Ошибка БД: " + err.message
});
return;
}
delete req.session.login;
delete req.session.email;
res.json({
status: true,
level: "info",
msg: "Запрос на удаление оставлен."
});
})
});
router.post('/removeUser', function(req, res, next) {
if(!req.session.login) {
res.json({
status: false,
level: "danger",
msg: "Сначала войдите в систему!"
})
return
}
if(!req.body.email) {
res.json({
status: false,
level: "danger",
msg: "Укажите email!"
});
return;
}
var targetEmail = req.body.email
db.findUserByEmail(req.session.email, function(err, user) {
if(err) {
res.json({
msg: "Ошибка БД: " + err.message,
status: false,
level: "danger"
});
return;
}
if(!user) {
res.json({
status: false,
level: "danger",
msg: "Сначала войдите в систему!"
})
return
}
if(!user.isAdministrator && user.email!==targetEmail) {
res.json({
msg: "Пользователя может удалить только администратор или сам пользователь",
status: false,
level: "danger"
});
return;
}
db.removeUser(targetEmail, function(err) {
if(err) {
res.json({
msg: "Ошибка БД: " + err.message,
status: false,
level: "danger"
});
return;
}
res.json({
msg: "Пользователь был удалён!: ",
status: true,
level: "success"
});
return;
})
})
})
router.post('/clearUsers', function(req, res, next) {
if(!req.session.login) {
res.json({
status: false,
level: "danger",
msg: "Сначала войдите в систему!"
})
return
}
db.findUserByEmail(req.session.email, function(err, user) {
if(err) {
res.json({
msg: "Ошибка БД: " + err.message,
status: false,
level: "danger"
});
return;
}
if(!user) {
res.json({
status: false,
level: "danger",
msg: "Сначала войдите в систему!"
})
return
}
if(!user.isAdministrator) {
res.json({
msg: "Очистить базу пользователей может только администратор!",
status: false,
level: "danger"
});
return;
}
db.clearUsers(function(err) {
if(err) {
res.json({
msg: "Ошибка БД: " + err.message,
status: false,
level: "danger"
});
return;
}
res.json({
msg: "Все пользователи были удалены!",
status: true,
level: "success"
});
})
})
})
router.post('/getMe', function(req, res, next) {
if(!req.session.login) {
res.json({
status: false,
level: "info",
msg: "Вы ещё не вошли в систему."
})
return;
}
db.findUserByEmailWithoutPassword(req.session.email, true, function(err, user) {
if(err) {
res.json({
status: false,
level: "danger",
msg: "Ошибка БД: " + err.message
})
return;
}
if(!user) {
res.json({
status: false,
level: "danger",
msg: "Пользователь не найден! Скорее всего, ошибка с сессией."
})
return;
}
res.json({
status: true,
level: "info",
msg: "Пользователь найден!",
user: user
})
})
})
module.exports = router;
| Вернул проверку неавторизованности пользователя при регистрации.
| modules/users/route/index.js | Вернул проверку неавторизованности пользователя при регистрации. | <ide><path>odules/users/route/index.js
<ide> });
<ide>
<ide> router.post('/signup', function(req, res, next) {
<add> if(req.session.login)
<add> {
<add> res.json({
<add> msg: "Вы уже вошли как "+ req.session.email +"! Зачем вам регистрироваться?",
<add> status: false,
<add> level: "warning"
<add> });
<add> return;
<add> }
<ide> if(!req.body.email || !req.body.password || !req.body.passwordDuplicate) {
<ide> res.json({
<ide> msg: "Указаны не все данные.", |
|
Java | bsd-2-clause | d70b2d9f3d3d510480fd17088b5f5a1a770b65d7 | 0 | RCRS-ADF/core,RCRS-ADF/core | package adf.component.module.algorithm;
import adf.agent.communication.MessageManager;
import adf.agent.develop.DevelopData;
import adf.agent.info.AgentInfo;
import adf.agent.info.ScenarioInfo;
import adf.agent.info.WorldInfo;
import adf.agent.module.ModuleManager;
import adf.agent.precompute.PrecomputeData;
import adf.component.module.AbstractModule;
import rescuecore2.standard.entities.StandardEntity;
import rescuecore2.worldmodel.EntityID;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public abstract class Clustering extends AbstractModule{
public Clustering(AgentInfo ai, WorldInfo wi, ScenarioInfo si, ModuleManager moduleManager, DevelopData developData) {
super(ai, wi, si, moduleManager, developData);
}
public abstract int getClusterNumber();
public abstract int getClusterIndex(StandardEntity entity);
public abstract int getClusterIndex(EntityID id);
public abstract Collection<StandardEntity> getClusterEntities(int index);
public abstract List<Collection<StandardEntity>> getClusterEntitiesTable();
public abstract Collection<EntityID> getClusterEntityIDs(int index);
public abstract List<Collection<EntityID>> getClusterEintityIDsTable();
public List<Collection<StandardEntity>> getAllClusterEntities() {
int number = this.getClusterNumber();
List<Collection<StandardEntity>> result = new ArrayList<>(number);
for(int i = 0; i < number; i++) {
result.add(i, this.getClusterEntities(i));
}
return result;
}
public List<Collection<EntityID>> getAllClusterEntityIDs() {
int number = this.getClusterNumber();
List<Collection<EntityID>> result = new ArrayList<>(number);
for(int i = 0; i < number; i++) {
result.add(i, this.getClusterEntityIDs(i));
}
return result;
}
@Override
public Clustering precompute(PrecomputeData precomputeData) {
super.precompute(precomputeData);
return this;
}
@Override
public Clustering resume(PrecomputeData precomputeData) {
super.resume(precomputeData);
return this;
}
@Override
public Clustering preparate() {
super.preparate();
return this;
}
@Override
public Clustering updateInfo(MessageManager messageManager) {
super.updateInfo(messageManager);
return this;
}
@Override
public abstract Clustering calc();
}
| src/main/java/adf/component/module/algorithm/Clustering.java | package adf.component.module.algorithm;
import adf.agent.communication.MessageManager;
import adf.agent.develop.DevelopData;
import adf.agent.info.AgentInfo;
import adf.agent.info.ScenarioInfo;
import adf.agent.info.WorldInfo;
import adf.agent.module.ModuleManager;
import adf.agent.precompute.PrecomputeData;
import adf.component.module.AbstractModule;
import rescuecore2.standard.entities.StandardEntity;
import rescuecore2.worldmodel.EntityID;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public abstract class Clustering extends AbstractModule{
public Clustering(AgentInfo ai, WorldInfo wi, ScenarioInfo si, ModuleManager moduleManager, DevelopData developData) {
super(ai, wi, si, moduleManager, developData);
}
public abstract int getClusterNumber();
public abstract int getClusterIndex(StandardEntity entity);
public abstract int getClusterIndex(EntityID id);
public abstract Collection<StandardEntity> getClusterEntities(int index);
public abstract Collection<EntityID> getClusterEntityIDs(int index);
public List<Collection<StandardEntity>> getAllClusterEntities() {
int number = this.getClusterNumber();
List<Collection<StandardEntity>> result = new ArrayList<>(number);
for(int i = 0; i < number; i++) {
result.add(i, this.getClusterEntities(i));
}
return result;
}
public List<Collection<EntityID>> getAllClusterEntityIDs() {
int number = this.getClusterNumber();
List<Collection<EntityID>> result = new ArrayList<>(number);
for(int i = 0; i < number; i++) {
result.add(i, this.getClusterEntityIDs(i));
}
return result;
}
@Override
public Clustering precompute(PrecomputeData precomputeData) {
super.precompute(precomputeData);
return this;
}
@Override
public Clustering resume(PrecomputeData precomputeData) {
super.resume(precomputeData);
return this;
}
@Override
public Clustering preparate() {
super.preparate();
return this;
}
@Override
public Clustering updateInfo(MessageManager messageManager) {
super.updateInfo(messageManager);
return this;
}
@Override
public abstract Clustering calc();
}
| add dump methods to Clustering
| src/main/java/adf/component/module/algorithm/Clustering.java | add dump methods to Clustering | <ide><path>rc/main/java/adf/component/module/algorithm/Clustering.java
<ide>
<ide> public abstract Collection<StandardEntity> getClusterEntities(int index);
<ide>
<add> public abstract List<Collection<StandardEntity>> getClusterEntitiesTable();
<add>
<ide> public abstract Collection<EntityID> getClusterEntityIDs(int index);
<add>
<add> public abstract List<Collection<EntityID>> getClusterEintityIDsTable();
<ide>
<ide> public List<Collection<StandardEntity>> getAllClusterEntities() {
<ide> int number = this.getClusterNumber(); |
|
Java | apache-2.0 | cbed627d0b0dd84de3526d537417051a13aed477 | 0 | ambraspace/nd4j,deeplearning4j/nd4j,huitseeker/nd4j,smarthi/nd4j,deeplearning4j/nd4j,gagatust/nd4j,ambraspace/nd4j,gagatust/nd4j,huitseeker/nd4j,smarthi/nd4j | package org.nd4j.linalg.learning;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.ops.impl.transforms.arithmetic.AddOp;
import org.nd4j.linalg.factory.Nd4j;
import java.io.Serializable;
/**
* Nesterov's momentum.
* Keep track of the previous layer's gradient
* and use it as a way of updating the gradient.
*
* @author Adam Gibson
*/
@Data
@NoArgsConstructor
public class Nesterovs implements Serializable,GradientUpdater {
private double momentum = 0.5;
private INDArray v;
private double learningRate = 0.1;
public Nesterovs(double momentum, double learningRate) {
this.momentum = momentum;
this.learningRate = learningRate;
}
public Nesterovs(double momentum) {
this.momentum = momentum;
}
@Override
public void update(Object... args) {
if(args.length > 0) {
learningRate = (Double) args[0];
momentum = (Double) args[1];
}
}
/**
* Get the nesterov update
* @param gradient the gradient to get the update for
* @param iteration
* @return
*/
@Override
public INDArray getGradient(INDArray gradient, int iteration) {
if(v == null)
v = Nd4j.zeros(gradient.shape());
INDArray vPrev = v;
v = vPrev.mul(momentum).subi(gradient.mul(learningRate));
//reference https://cs231n.github.io/neural-networks-3/#sgd 2nd equation
//DL4J default is negative step function thus we flipped the signs:
// x += mu * v_prev + (-1 - mu) * v
//i.e., we do params -= updatedGradient, not params += updatedGradient
INDArray ret = vPrev.muli(momentum).addi(v.mul(-momentum - 1));
gradient.assign(ret);
return gradient;
}
@Override
public GradientUpdaterAggregator getAggregator(boolean addThis){
NesterovsAggregator ag = new NesterovsAggregator();
if(addThis) ag.aggregate(this);
return ag;
}
public static class NesterovsAggregator implements GradientUpdaterAggregator {
private INDArray vSum;
private double lrSum;
private double momentumSum;
private int count = 0;
@Override
public GradientUpdater getUpdater() {
Nesterovs nesterovs = new Nesterovs(momentumSum/count,lrSum/count);
nesterovs.setV(vSum.div(count));
return nesterovs;
}
@Override
public void aggregate(GradientUpdater updater) {
if(!(updater instanceof Nesterovs)) throw new UnsupportedOperationException("Cannot aggregate Nesterovs with updater: " + updater);
Nesterovs nesterovs = (Nesterovs)updater;
if(vSum == null){
vSum = nesterovs.v.dup();
lrSum = nesterovs.learningRate;
momentumSum = nesterovs.momentum;
} else {
vSum.addi(nesterovs.v);
lrSum += nesterovs.learningRate;
momentumSum += nesterovs.momentum;
}
count++;
}
@Override
public GradientUpdaterAggregator combine(GradientUpdaterAggregator other) {
if(!(other instanceof NesterovsAggregator))
throw new IllegalArgumentException("Cannot combine NesterovsAggregator with aggregator: " + other);
NesterovsAggregator aggregator = (NesterovsAggregator)other;
vSum.addi(aggregator.vSum);
lrSum += aggregator.lrSum;
momentumSum += aggregator.momentumSum;
count += aggregator.count;
return this;
}
}
}
| nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/learning/Nesterovs.java | package org.nd4j.linalg.learning;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.ops.impl.transforms.arithmetic.AddOp;
import org.nd4j.linalg.factory.Nd4j;
import java.io.Serializable;
/**
* Nesterov's momentum.
* Keep track of the previous layer's gradient
* and use it as a way of updating the gradient.
*
* @author Adam Gibson
*/
@Data
@NoArgsConstructor
public class Nesterovs implements Serializable,GradientUpdater {
private double momentum = 0.5;
private INDArray v;
private double learningRate = 0.1;
public Nesterovs(double momentum, double learningRate) {
this.momentum = momentum;
this.learningRate = learningRate;
}
public Nesterovs(double momentum) {
this.momentum = momentum;
}
@Override
public void update(Object... args) {
if(args.length > 0) {
learningRate = (Double) args[0];
momentum = (Double) args[1];
}
}
/**
* Get the nesterov update
* @param gradient the gradient to get the update for
* @param iteration
* @return
*/
@Override
public INDArray getGradient(INDArray gradient, int iteration) {
if(v == null)
v = Nd4j.zeros(gradient.shape());
INDArray vPrev = v;
v = vPrev.mul(momentum).subi(gradient.mul(learningRate));
//reference https://cs231n.github.io/neural-networks-3/#sgd 2nd equation
//DL4J default is negative step function thus we flipped the signs:
// x += mu * v_prev + (-1 - mu) * v
//i.e., we do params -= updatedGradient, not params += updatedGradient
Nd4j.getExecutioner().execAndReturn(new AddOp(vPrev.muli(momentum), v.mul(-momentum - 1), gradient ));
//Above line: equivalent to the following, but one less op
//INDArray ret = vPrev.muli(momentum).addi(v.mul(-momentum - 1));
//gradient.assign(ret)
return gradient;
}
@Override
public GradientUpdaterAggregator getAggregator(boolean addThis){
NesterovsAggregator ag = new NesterovsAggregator();
if(addThis) ag.aggregate(this);
return ag;
}
public static class NesterovsAggregator implements GradientUpdaterAggregator {
private INDArray vSum;
private double lrSum;
private double momentumSum;
private int count = 0;
@Override
public GradientUpdater getUpdater() {
Nesterovs nesterovs = new Nesterovs(momentumSum/count,lrSum/count);
nesterovs.setV(vSum.div(count));
return nesterovs;
}
@Override
public void aggregate(GradientUpdater updater) {
if(!(updater instanceof Nesterovs)) throw new UnsupportedOperationException("Cannot aggregate Nesterovs with updater: " + updater);
Nesterovs nesterovs = (Nesterovs)updater;
if(vSum == null){
vSum = nesterovs.v.dup();
lrSum = nesterovs.learningRate;
momentumSum = nesterovs.momentum;
} else {
vSum.addi(nesterovs.v);
lrSum += nesterovs.learningRate;
momentumSum += nesterovs.momentum;
}
count++;
}
@Override
public GradientUpdaterAggregator combine(GradientUpdaterAggregator other) {
if(!(other instanceof NesterovsAggregator))
throw new IllegalArgumentException("Cannot combine NesterovsAggregator with aggregator: " + other);
NesterovsAggregator aggregator = (NesterovsAggregator)other;
vSum.addi(aggregator.vSum);
lrSum += aggregator.lrSum;
momentumSum += aggregator.momentumSum;
count += aggregator.count;
return this;
}
}
}
| Fix bug in momentum introduced during earlier changes
| nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/learning/Nesterovs.java | Fix bug in momentum introduced during earlier changes | <ide><path>d4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/learning/Nesterovs.java
<ide> // x += mu * v_prev + (-1 - mu) * v
<ide> //i.e., we do params -= updatedGradient, not params += updatedGradient
<ide>
<del>
<del> Nd4j.getExecutioner().execAndReturn(new AddOp(vPrev.muli(momentum), v.mul(-momentum - 1), gradient ));
<del> //Above line: equivalent to the following, but one less op
<del> //INDArray ret = vPrev.muli(momentum).addi(v.mul(-momentum - 1));
<del> //gradient.assign(ret)
<add> INDArray ret = vPrev.muli(momentum).addi(v.mul(-momentum - 1));
<add> gradient.assign(ret);
<ide>
<ide> return gradient;
<ide> } |
|
Java | apache-2.0 | d1d9f5a63ac3394b197d31819e92738c1bd8c6f7 | 0 | maboelhassan/alluxio,jswudi/alluxio,jsimsa/alluxio,bf8086/alluxio,ShailShah/alluxio,bf8086/alluxio,ChangerYoung/alluxio,apc999/alluxio,ChangerYoung/alluxio,maobaolong/alluxio,apc999/alluxio,calvinjia/tachyon,madanadit/alluxio,EvilMcJerkface/alluxio,EvilMcJerkface/alluxio,EvilMcJerkface/alluxio,aaudiber/alluxio,calvinjia/tachyon,PasaLab/tachyon,maobaolong/alluxio,PasaLab/tachyon,wwjiang007/alluxio,jsimsa/alluxio,Alluxio/alluxio,maboelhassan/alluxio,maobaolong/alluxio,Alluxio/alluxio,WilliamZapata/alluxio,Reidddddd/mo-alluxio,Alluxio/alluxio,madanadit/alluxio,madanadit/alluxio,maobaolong/alluxio,Reidddddd/alluxio,EvilMcJerkface/alluxio,riversand963/alluxio,WilliamZapata/alluxio,Reidddddd/mo-alluxio,wwjiang007/alluxio,Reidddddd/alluxio,Reidddddd/mo-alluxio,bf8086/alluxio,PasaLab/tachyon,aaudiber/alluxio,Reidddddd/alluxio,jswudi/alluxio,Reidddddd/alluxio,yuluo-ding/alluxio,WilliamZapata/alluxio,bf8086/alluxio,madanadit/alluxio,Alluxio/alluxio,yuluo-ding/alluxio,madanadit/alluxio,jsimsa/alluxio,ShailShah/alluxio,Alluxio/alluxio,maobaolong/alluxio,Reidddddd/mo-alluxio,aaudiber/alluxio,Reidddddd/alluxio,wwjiang007/alluxio,yuluo-ding/alluxio,jswudi/alluxio,calvinjia/tachyon,apc999/alluxio,bf8086/alluxio,Alluxio/alluxio,Reidddddd/mo-alluxio,ShailShah/alluxio,wwjiang007/alluxio,calvinjia/tachyon,maboelhassan/alluxio,jsimsa/alluxio,uronce-cc/alluxio,maobaolong/alluxio,bf8086/alluxio,aaudiber/alluxio,yuluo-ding/alluxio,calvinjia/tachyon,maobaolong/alluxio,yuluo-ding/alluxio,EvilMcJerkface/alluxio,Alluxio/alluxio,EvilMcJerkface/alluxio,riversand963/alluxio,ShailShah/alluxio,bf8086/alluxio,aaudiber/alluxio,Alluxio/alluxio,maobaolong/alluxio,maobaolong/alluxio,jsimsa/alluxio,Alluxio/alluxio,apc999/alluxio,ChangerYoung/alluxio,uronce-cc/alluxio,wwjiang007/alluxio,bf8086/alluxio,madanadit/alluxio,aaudiber/alluxio,WilliamZapata/alluxio,madanadit/alluxio,wwjiang007/alluxio,uronce-cc/alluxio,ShailShah/alluxio,PasaLab/tachyon,maboelhassan/alluxio,Reidddddd/alluxio,calvinjia/tachyon,uronce-cc/alluxio,jswudi/alluxio,Alluxio/alluxio,wwjiang007/alluxio,maboelhassan/alluxio,PasaLab/tachyon,riversand963/alluxio,WilliamZapata/alluxio,apc999/alluxio,ChangerYoung/alluxio,wwjiang007/alluxio,maobaolong/alluxio,WilliamZapata/alluxio,Reidddddd/alluxio,ShailShah/alluxio,jswudi/alluxio,EvilMcJerkface/alluxio,apc999/alluxio,maboelhassan/alluxio,riversand963/alluxio,calvinjia/tachyon,PasaLab/tachyon,riversand963/alluxio,jsimsa/alluxio,uronce-cc/alluxio,Reidddddd/mo-alluxio,madanadit/alluxio,apc999/alluxio,calvinjia/tachyon,wwjiang007/alluxio,ChangerYoung/alluxio,PasaLab/tachyon,EvilMcJerkface/alluxio,yuluo-ding/alluxio,uronce-cc/alluxio,riversand963/alluxio,aaudiber/alluxio,ChangerYoung/alluxio,wwjiang007/alluxio,maboelhassan/alluxio,jswudi/alluxio | /*
* Licensed to the University of California, Berkeley 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 tachyon.worker.block.allocator;
import com.google.common.base.Preconditions;
import tachyon.worker.block.BlockMetadataManagerView;
import tachyon.worker.block.BlockStoreLocation;
import tachyon.worker.block.meta.StorageDirView;
import tachyon.worker.block.meta.StorageTierView;
/**
* A greedy allocator that returns the first Storage dir fitting the size of block to allocate. This
* class serves as an example how to implement an allocator.
*/
public final class GreedyAllocator implements Allocator {
private BlockMetadataManagerView mManagerView;
public GreedyAllocator(BlockMetadataManagerView view) {
mManagerView = Preconditions.checkNotNull(view);
}
@Override
public StorageDirView allocateBlockWithView(long sessionId, long blockSize,
BlockStoreLocation location, BlockMetadataManagerView view) {
mManagerView = Preconditions.checkNotNull(view);
return allocateBlock(sessionId, blockSize, location);
}
/**
* Should only be accessed by
* {@link #allocateBlockWithView(long, long, BlockStoreLocation, BlockMetadataManagerView)}
* inside class. Allocates a block from the given block store location. The location can be a
* specific location, or
* {@link BlockStoreLocation#anyTier()} or {@link BlockStoreLocation#anyDirInTier(String)}.
*
* @param sessionId the ID of session to apply for the block allocation
* @param blockSize the size of block in bytes
* @param location the location in block store
* @return a StorageDirView in which to create the temp block meta if success, null otherwise
* @throws IllegalArgumentException if block location is invalid
*/
private StorageDirView allocateBlock(long sessionId, long blockSize,
BlockStoreLocation location) {
Preconditions.checkNotNull(location);
if (location.equals(BlockStoreLocation.anyTier())) {
// When any tier is ok, loop over all tier views and dir views,
// and return a temp block meta from the first available dirview.
for (StorageTierView tierView : mManagerView.getTierViews()) {
for (StorageDirView dirView : tierView.getDirViews()) {
if (dirView.getAvailableBytes() >= blockSize) {
return dirView;
}
}
}
return null;
}
String tierAlias = location.tierAlias();
StorageTierView tierView = mManagerView.getTierView(tierAlias);
if (location.equals(BlockStoreLocation.anyDirInTier(tierAlias))) {
// Loop over all dir views in the given tier
for (StorageDirView dirView : tierView.getDirViews()) {
if (dirView.getAvailableBytes() >= blockSize) {
return dirView;
}
}
return null;
}
int dirIndex = location.dir();
StorageDirView dirView = tierView.getDirView(dirIndex);
if (dirView.getAvailableBytes() >= blockSize) {
return dirView;
}
return null;
}
}
| servers/src/main/java/tachyon/worker/block/allocator/GreedyAllocator.java | /*
* Licensed to the University of California, Berkeley 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 tachyon.worker.block.allocator;
import com.google.common.base.Preconditions;
import tachyon.worker.block.BlockMetadataManagerView;
import tachyon.worker.block.BlockStoreLocation;
import tachyon.worker.block.meta.StorageDirView;
import tachyon.worker.block.meta.StorageTierView;
/**
* A greedy allocator that returns the first Storage dir fitting the size of block to allocate. This
* class serves as an example how to implement an allocator.
*/
public final class GreedyAllocator implements Allocator {
private BlockMetadataManagerView mManagerView;
public GreedyAllocator(BlockMetadataManagerView view) {
mManagerView = Preconditions.checkNotNull(view);
}
@Override
public StorageDirView allocateBlockWithView(long sessionId, long blockSize,
BlockStoreLocation location, BlockMetadataManagerView view) {
mManagerView = Preconditions.checkNotNull(view);
return allocateBlock(sessionId, blockSize, location);
}
/**
* Should only be accessed by {@link allocateBlockWithView} inside class. Allocates a block from
* the given block store location. The location can be a specific location, or
* {@link BlockStoreLocation#anyTier()} or {@link BlockStoreLocation#anyDirInTier(String)}.
*
* @param sessionId the ID of session to apply for the block allocation
* @param blockSize the size of block in bytes
* @param location the location in block store
* @return a StorageDirView in which to create the temp block meta if success, null otherwise
* @throws IllegalArgumentException if block location is invalid
*/
private StorageDirView allocateBlock(long sessionId, long blockSize,
BlockStoreLocation location) {
Preconditions.checkNotNull(location);
if (location.equals(BlockStoreLocation.anyTier())) {
// When any tier is ok, loop over all tier views and dir views,
// and return a temp block meta from the first available dirview.
for (StorageTierView tierView : mManagerView.getTierViews()) {
for (StorageDirView dirView : tierView.getDirViews()) {
if (dirView.getAvailableBytes() >= blockSize) {
return dirView;
}
}
}
return null;
}
String tierAlias = location.tierAlias();
StorageTierView tierView = mManagerView.getTierView(tierAlias);
if (location.equals(BlockStoreLocation.anyDirInTier(tierAlias))) {
// Loop over all dir views in the given tier
for (StorageDirView dirView : tierView.getDirViews()) {
if (dirView.getAvailableBytes() >= blockSize) {
return dirView;
}
}
return null;
}
int dirIndex = location.dir();
StorageDirView dirView = tierView.getDirView(dirIndex);
if (dirView.getAvailableBytes() >= blockSize) {
return dirView;
}
return null;
}
}
| [SMALLFIX] Fixed link in documentation in 'GreedyAllocator'
| servers/src/main/java/tachyon/worker/block/allocator/GreedyAllocator.java | [SMALLFIX] Fixed link in documentation in 'GreedyAllocator' | <ide><path>ervers/src/main/java/tachyon/worker/block/allocator/GreedyAllocator.java
<ide> }
<ide>
<ide> /**
<del> * Should only be accessed by {@link allocateBlockWithView} inside class. Allocates a block from
<del> * the given block store location. The location can be a specific location, or
<add> * Should only be accessed by
<add> * {@link #allocateBlockWithView(long, long, BlockStoreLocation, BlockMetadataManagerView)}
<add> * inside class. Allocates a block from the given block store location. The location can be a
<add> * specific location, or
<ide> * {@link BlockStoreLocation#anyTier()} or {@link BlockStoreLocation#anyDirInTier(String)}.
<ide> *
<ide> * @param sessionId the ID of session to apply for the block allocation |
|
Java | apache-2.0 | c72fa84911380c7ccc2c5e5e3b4449f507dd3b2d | 0 | bitstorm/wicket,bitstorm/wicket,mosoft521/wicket,mosoft521/wicket,bitstorm/wicket,Servoy/wicket,klopfdreh/wicket,freiheit-com/wicket,freiheit-com/wicket,aldaris/wicket,zwsong/wicket,martin-g/wicket-osgi,dashorst/wicket,Servoy/wicket,Servoy/wicket,klopfdreh/wicket,selckin/wicket,apache/wicket,astrapi69/wicket,bitstorm/wicket,mafulafunk/wicket,selckin/wicket,dashorst/wicket,aldaris/wicket,aldaris/wicket,AlienQueen/wicket,astrapi69/wicket,AlienQueen/wicket,bitstorm/wicket,apache/wicket,apache/wicket,AlienQueen/wicket,topicusonderwijs/wicket,apache/wicket,astrapi69/wicket,klopfdreh/wicket,mosoft521/wicket,AlienQueen/wicket,mafulafunk/wicket,zwsong/wicket,selckin/wicket,freiheit-com/wicket,freiheit-com/wicket,apache/wicket,zwsong/wicket,martin-g/wicket-osgi,topicusonderwijs/wicket,dashorst/wicket,Servoy/wicket,klopfdreh/wicket,mosoft521/wicket,mafulafunk/wicket,klopfdreh/wicket,astrapi69/wicket,martin-g/wicket-osgi,dashorst/wicket,topicusonderwijs/wicket,topicusonderwijs/wicket,aldaris/wicket,mosoft521/wicket,AlienQueen/wicket,selckin/wicket,freiheit-com/wicket,zwsong/wicket,dashorst/wicket,topicusonderwijs/wicket,selckin/wicket,Servoy/wicket,aldaris/wicket | /*
* 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 wicket.settings;
import java.util.List;
import wicket.IResponseFilter;
import wicket.RequestCycle;
import wicket.Session;
import wicket.markup.html.pages.BrowserInfoPage;
import wicket.protocol.http.WebRequestCycle;
import wicket.settings.IExceptionSettings.UnexpectedExceptionDisplay;
import wicket.util.lang.EnumeratedType;
import wicket.util.time.Duration;
/**
* Inteface for request related settings
* <p>
* <i>bufferResponse </i> (defaults to true) - True if the application should
* buffer responses. This does require some additional memory, but helps keep
* exception displays accurate because the whole rendering process completes
* before the page is sent to the user, thus avoiding the possibility of a
* partially rendered page.
* <p>
* <i>renderStrategy </i>- Sets in what way the render part of a request is
* handled. Basically, there are two different options:
* <ul>
* <li>Direct, ApplicationSettings.ONE_PASS_RENDER. Everything is handled in
* one physical request. This is efficient, and is the best option if you want
* to do sophisticated clustering. It does not however, shield you from what is
* commonly known as the <i>Double submit problem </i></li>
* <li>Using a redirect. This follows the pattern <a
* href="http://www.theserverside.com/articles/article.tss?l=RedirectAfterPost"
* >as described at the serverside </a> and that is commonly known as Redirect
* after post. Wicket takes it one step further to do any rendering after a
* redirect, so that not only form submits are shielded from the double submit
* problem, but also the IRequestListener handlers (that could be e.g. a link
* that deletes a row). With this pattern, you have two options to choose from:
* <ul>
* <li>ApplicationSettings.REDIRECT_TO_RENDER. This option first handles the
* 'action' part of the request, which is either page construction (bookmarkable
* pages or the home page) or calling a IRequestListener handler, such as
* Link.onClick. When that part is done, a redirect is issued to the render
* part, which does all the rendering of the page and its components. <strong>Be
* aware </strong> that this may mean, depending on whether you access any
* models in the action part of the request, that attachement and detachement of
* some models is done twice for a request.</li>
* <li>ApplicationSettings.REDIRECT_TO_BUFFER. This option handles both the
* action- and the render part of the request in one physical request, but
* instead of streaming the result to the browser directly, it is kept in
* memory, and a redirect is issue to get this buffered result (after which it
* is immediately removed). This option currently is the default render
* strategy, as it shields you from the double submit problem, while being more
* efficient and less error prone regarding to detachable models.</li>
* </ul>
* </li>
* </ul>
* Note that this parameter sets the default behavior, but that you can manually
* set whether any redirecting is done by calling method
* RequestCycle.setRedirect. Setting the redirect flag when the application is
* configured to use ONE_PASS_RENDER, will result in a redirect of type
* REDIRECT_TO_RENDER. When the application is configured to use
* REDIRECT_TO_RENDER or REDIRECT_TO_BUFFER, setting the redirect flag to false,
* will result in that request begin rendered and streamed in one pass.
* <p>
* More documentation is available about each setting in the setter method for
* the property.
*
* @author Igor Vaynberg (ivaynberg)
*/
public interface IRequestCycleSettings
{
/**
* Enumerated type for different ways of handling the render part of
* requests.
*/
public static class RenderStrategy extends EnumeratedType
{
private static final long serialVersionUID = 1L;
RenderStrategy(final String name)
{
super(name);
}
}
/**
* All logical parts of a request (the action and render part) are handled
* within the same request. To enable a the client side redirect for a
* request, users can set the 'redirect' property of {@link RequestCycle}to
* true (getRequestCycle.setRedirect(true)), after which the behavior will
* be like RenderStragegy 'REDIRECT_TO_RENDER'.
* <p>
* This strategy is more efficient than the 'REDIRECT_TO_RENDER' strategy,
* and doesn't have some of the potential problems of it, it also does not
* solve the double submit problem. It is however the best option to use
* when you want to do sophisticated (non-sticky session) clustering.
* </p>
*/
public static final IRequestCycleSettings.RenderStrategy ONE_PASS_RENDER = new IRequestCycleSettings.RenderStrategy(
"ONE_PASS_RENDER");
/**
* All logical parts of a request (the action and render part) are handled
* within the same request, but instead of streaming the render result to
* the browser directly, the result is cached on the server. A client side
* redirect command is issued to the browser specifically to render this
* request.
*/
public static final IRequestCycleSettings.RenderStrategy REDIRECT_TO_BUFFER = new IRequestCycleSettings.RenderStrategy(
"REDIRECT_BUFFER");
/**
* The render part of a request (opposed to the 'action part' which is
* either the construction of a bookmarkable page or the execution of a
* IRequestListener handler) is handled by a seperate request by issueing a
* redirect request to the browser. This is commonly known as the 'redirect
* after submit' pattern, though in our case, we use it for GET and POST
* requests instead of just the POST requests. To cancel the client side
* redirect for a request, users can set the 'redirect' property of
* {@link RequestCycle}to false (getRequestCycle.setRedirect(false)).
* <p>
* This pattern solves the 'refresh' problem. While it is a common feature
* of browsers to refresh/ reload a web page, this results in problems in
* many dynamic web applications. For example, when you have a link with an
* event handler that e.g. deletes a row from a list, you usually want to
* ignore refresh requests after that link is clicked on. By using this
* strategy, the refresh request only results in the re-rendering of the
* page without executing the event handler again.
* </p>
* <p>
* Though it solves the refresh problem, it introduces potential problems,
* as the request that is logically one, are actually two seperate request.
* Not only is this less efficient, but this also can mean that within the
* same request attachement/ detachement of models is done twice (in case
* you use models in the bookmarkable page constructors and IRequestListener
* handlers). If you use this strategy, you should be aware of this
* possibily, and should also be aware that for one logical request,
* actually two instances of RequestCycle are created and processed.
* </p>
*/
public static final IRequestCycleSettings.RenderStrategy REDIRECT_TO_RENDER = new IRequestCycleSettings.RenderStrategy(
"CLIENT_SIDE_REDIRECT");
/**
* Adds a response filter to the list. Filters are evaluated in the order
* they have been added.
*
* @param responseFilter
* The {@link IResponseFilter} that is added
*/
void addResponseFilter(IResponseFilter responseFilter);
/**
* @return True if this application buffers its responses
*/
boolean getBufferResponse();
/**
* Gets whether Wicket should try to get extensive client info by
* redirecting to
* {@link BrowserInfoPage a page that polls for client capabilities}. This
* method is used by the default implementation of
* {@link WebRequestCycle#newClientInfo()}, so if that method is overriden,
* there is no guarantee this method will be taken into account.
*
* @return Whether to gather extensive client info
*/
boolean getGatherExtendedBrowserInfo();
/**
* Gets in what way the render part of a request is handled.
*
* @return the render strategy
*/
IRequestCycleSettings.RenderStrategy getRenderStrategy();
/**
* @return an unmodifiable list of added response filters, null if none
*/
List getResponseFilters();
/**
* In order to do proper form parameter decoding it is important that the
* response and the following request have the same encoding. see
* http://www.crazysquirrel.com/computing/general/form-encoding.jspx for
* additional information.
*
* @return The request and response encoding
*/
String getResponseRequestEncoding();
/**
* Gets the time that a request will by default be waiting for the previous
* request to be handled before giving up.
*
* @return The time out
*/
Duration getTimeout();
/**
* @see wicket.settings.IExceptionSettings#getUnexpectedExceptionDisplay()
*
* @return UnexpectedExceptionDisplay
*/
UnexpectedExceptionDisplay getUnexpectedExceptionDisplay();
/**
* @param bufferResponse
* True if this application should buffer responses.
*/
void setBufferResponse(boolean bufferResponse);
/**
* Sets whether Wicket should try to get extensive client info by
* redirecting to
* {@link BrowserInfoPage a page that polls for client capabilities}. This
* method is used by the default implementation of
* {@link WebRequestCycle#newClientInfo()}, so if that method is overriden,
* there is no guarantee this method will be taken into account.
*
* <p>
* <strong>WARNING: </strong> though this facility should work transparently
* in most cases, it is recommended that you trigger the roundtrip to get
* the browser info somewhere where it hurts the least. The roundtrip will
* be triggered the first time you call {@link Session#getClientInfo()} for
* a session, and after the roundtrip a new request with the same info (url,
* post parameters) is handled. So rather than calling this in the middle of
* an implementation of a form submit method, which would result in the code
* of that method before the call to {@link Session#getClientInfo()} to be
* executed twice, you best call {@link Session#getClientInfo()} e.g. in a
* page constructor or somewhere else where you didn't do a lot of
* processing first.
* </p>
*
* @param gatherExtendedBrowserInfo
* Whether to gather extensive client info
*/
void setGatherExtendedBrowserInfo(boolean gatherExtendedBrowserInfo);
/**
* Sets in what way the render part of a request is handled. Basically,
* there are two different options:
* <ul>
* <li>Direct, ApplicationSettings.ONE_PASS_RENDER. Everything is handled
* in one physical request. This is efficient, and is the best option if you
* want to do sophisticated clustering. It does not however, shield you from
* what is commonly known as the <i>Double submit problem </i></li>
* <li>Using a redirect. This follows the pattern <a
* href="http://www.theserverside.com/articles/article.tss?l=RedirectAfterPost"
* >as described at the serverside </a> and that is commonly known as
* Redirect after post. Wicket takes it one step further to do any rendering
* after a redirect, so that not only form submits are shielded from the
* double submit problem, but also the IRequestListener handlers (that could
* be e.g. a link that deletes a row). With this pattern, you have two
* options to choose from:
* <ul>
* <li>ApplicationSettings.REDIRECT_TO_RENDER. This option first handles
* the 'action' part of the request, which is either page construction
* (bookmarkable pages or the home page) or calling a IRequestListener
* handler, such as Link.onClick. When that part is done, a redirect is
* issued to the render part, which does all the rendering of the page and
* its components. <strong>Be aware </strong> that this may mean, depending
* on whether you access any models in the action part of the request, that
* attachement and detachement of some models is done twice for a request.
* </li>
* <li>ApplicationSettings.REDIRECT_TO_BUFFER. This option handles both the
* action- and the render part of the request in one physical request, but
* instead of streaming the result to the browser directly, it is kept in
* memory, and a redirect is issue to get this buffered result (after which
* it is immediately removed). This option currently is the default render
* strategy, as it shields you from the double submit problem, while being
* more efficient and less error prone regarding to detachable models.</li>
* </ul>
* Note that this parameter sets the default behavior, but that you can
* manually set whether any redirecting is done by calling method
* RequestCycle.setRedirect. Setting the redirect flag when the application
* is configured to use ONE_PASS_RENDER, will result in a redirect of type
* REDIRECT_TO_RENDER. When the application is configured to use
* REDIRECT_TO_RENDER or REDIRECT_TO_BUFFER, setting the redirect flag to
* false, will result in that request begin rendered and streamed in one
* pass.
*
* @param renderStrategy
* the render strategy that should be used by default.
*/
void setRenderStrategy(IRequestCycleSettings.RenderStrategy renderStrategy);
/**
* In order to do proper form parameter decoding it is important that the
* response and the following request have the same encoding. see
* http://www.crazysquirrel.com/computing/general/form-encoding.jspx for
* additional information.
*
* Default encoding: UTF-8
*
* @param responseRequestEncoding
* The request and response encoding to be used.
*/
void setResponseRequestEncoding(final String responseRequestEncoding);
/**
* Sets the time that a request will by default be waiting for the previous
* request to be handled before giving up.
*
* @param timeout
*/
void setTimeout(Duration timeout);
/**
* @see wicket.settings.IExceptionSettings#setUnexpectedExceptionDisplay(wicket.settings.Settings.UnexpectedExceptionDisplay)
*
* @param unexpectedExceptionDisplay
*/
void setUnexpectedExceptionDisplay(final UnexpectedExceptionDisplay unexpectedExceptionDisplay);
} | wicket/src/main/java/wicket/settings/IRequestCycleSettings.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package wicket.settings;
import java.util.List;
import wicket.IResponseFilter;
import wicket.RequestCycle;
import wicket.markup.html.pages.BrowserInfoPage;
import wicket.protocol.http.WebRequestCycle;
import wicket.settings.IExceptionSettings.UnexpectedExceptionDisplay;
import wicket.util.lang.EnumeratedType;
import wicket.util.time.Duration;
/**
* Inteface for request related settings
* <p>
* <i>bufferResponse </i> (defaults to true) - True if the application should
* buffer responses. This does require some additional memory, but helps keep
* exception displays accurate because the whole rendering process completes
* before the page is sent to the user, thus avoiding the possibility of a
* partially rendered page.
* <p>
* <i>renderStrategy </i>- Sets in what way the render part of a request is
* handled. Basically, there are two different options:
* <ul>
* <li>Direct, ApplicationSettings.ONE_PASS_RENDER. Everything is handled in
* one physical request. This is efficient, and is the best option if you want
* to do sophisticated clustering. It does not however, shield you from what is
* commonly known as the <i>Double submit problem </i></li>
* <li>Using a redirect. This follows the pattern <a
* href="http://www.theserverside.com/articles/article.tss?l=RedirectAfterPost"
* >as described at the serverside </a> and that is commonly known as Redirect
* after post. Wicket takes it one step further to do any rendering after a
* redirect, so that not only form submits are shielded from the double submit
* problem, but also the IRequestListener handlers (that could be e.g. a link
* that deletes a row). With this pattern, you have two options to choose from:
* <ul>
* <li>ApplicationSettings.REDIRECT_TO_RENDER. This option first handles the
* 'action' part of the request, which is either page construction (bookmarkable
* pages or the home page) or calling a IRequestListener handler, such as
* Link.onClick. When that part is done, a redirect is issued to the render
* part, which does all the rendering of the page and its components. <strong>Be
* aware </strong> that this may mean, depending on whether you access any
* models in the action part of the request, that attachement and detachement of
* some models is done twice for a request.</li>
* <li>ApplicationSettings.REDIRECT_TO_BUFFER. This option handles both the
* action- and the render part of the request in one physical request, but
* instead of streaming the result to the browser directly, it is kept in
* memory, and a redirect is issue to get this buffered result (after which it
* is immediately removed). This option currently is the default render
* strategy, as it shields you from the double submit problem, while being more
* efficient and less error prone regarding to detachable models.</li>
* </ul>
* </li>
* </ul>
* Note that this parameter sets the default behavior, but that you can manually
* set whether any redirecting is done by calling method
* RequestCycle.setRedirect. Setting the redirect flag when the application is
* configured to use ONE_PASS_RENDER, will result in a redirect of type
* REDIRECT_TO_RENDER. When the application is configured to use
* REDIRECT_TO_RENDER or REDIRECT_TO_BUFFER, setting the redirect flag to false,
* will result in that request begin rendered and streamed in one pass.
* <p>
* More documentation is available about each setting in the setter method for
* the property.
*
* @author Igor Vaynberg (ivaynberg)
*/
public interface IRequestCycleSettings
{
/**
* Enumerated type for different ways of handling the render part of
* requests.
*/
public static class RenderStrategy extends EnumeratedType
{
private static final long serialVersionUID = 1L;
RenderStrategy(final String name)
{
super(name);
}
}
/**
* All logical parts of a request (the action and render part) are handled
* within the same request. To enable a the client side redirect for a
* request, users can set the 'redirect' property of {@link RequestCycle}to
* true (getRequestCycle.setRedirect(true)), after which the behavior will
* be like RenderStragegy 'REDIRECT_TO_RENDER'.
* <p>
* This strategy is more efficient than the 'REDIRECT_TO_RENDER' strategy,
* and doesn't have some of the potential problems of it, it also does not
* solve the double submit problem. It is however the best option to use
* when you want to do sophisticated (non-sticky session) clustering.
* </p>
*/
public static final IRequestCycleSettings.RenderStrategy ONE_PASS_RENDER = new IRequestCycleSettings.RenderStrategy(
"ONE_PASS_RENDER");
/**
* All logical parts of a request (the action and render part) are handled
* within the same request, but instead of streaming the render result to
* the browser directly, the result is cached on the server. A client side
* redirect command is issued to the browser specifically to render this
* request.
*/
public static final IRequestCycleSettings.RenderStrategy REDIRECT_TO_BUFFER = new IRequestCycleSettings.RenderStrategy(
"REDIRECT_BUFFER");
/**
* The render part of a request (opposed to the 'action part' which is
* either the construction of a bookmarkable page or the execution of a
* IRequestListener handler) is handled by a seperate request by issueing a
* redirect request to the browser. This is commonly known as the 'redirect
* after submit' pattern, though in our case, we use it for GET and POST
* requests instead of just the POST requests. To cancel the client side
* redirect for a request, users can set the 'redirect' property of
* {@link RequestCycle}to false (getRequestCycle.setRedirect(false)).
* <p>
* This pattern solves the 'refresh' problem. While it is a common feature
* of browsers to refresh/ reload a web page, this results in problems in
* many dynamic web applications. For example, when you have a link with an
* event handler that e.g. deletes a row from a list, you usually want to
* ignore refresh requests after that link is clicked on. By using this
* strategy, the refresh request only results in the re-rendering of the
* page without executing the event handler again.
* </p>
* <p>
* Though it solves the refresh problem, it introduces potential problems,
* as the request that is logically one, are actually two seperate request.
* Not only is this less efficient, but this also can mean that within the
* same request attachement/ detachement of models is done twice (in case
* you use models in the bookmarkable page constructors and IRequestListener
* handlers). If you use this strategy, you should be aware of this
* possibily, and should also be aware that for one logical request,
* actually two instances of RequestCycle are created and processed.
* </p>
*/
public static final IRequestCycleSettings.RenderStrategy REDIRECT_TO_RENDER = new IRequestCycleSettings.RenderStrategy(
"CLIENT_SIDE_REDIRECT");
/**
* Adds a response filter to the list. Filters are evaluated in the order
* they have been added.
*
* @param responseFilter
* The {@link IResponseFilter} that is added
*/
void addResponseFilter(IResponseFilter responseFilter);
/**
* @return True if this application buffers its responses
*/
boolean getBufferResponse();
/**
* Gets whether Wicket should try to get extensive client info by
* redirecting to
* {@link BrowserInfoPage a page that polls for client capabilities}. This
* method is used by the default implementation of
* {@link WebRequestCycle#newClientInfo()}, so if that method is overriden,
* there is no guarantee this method will be taken into account.
*
* @return Whether to gather extensive client info
*/
boolean getGatherExtendedBrowserInfo();
/**
* Gets in what way the render part of a request is handled.
*
* @return the render strategy
*/
IRequestCycleSettings.RenderStrategy getRenderStrategy();
/**
* @return an unmodifiable list of added response filters, null if none
*/
List getResponseFilters();
/**
* In order to do proper form parameter decoding it is important that the
* response and the following request have the same encoding. see
* http://www.crazysquirrel.com/computing/general/form-encoding.jspx for
* additional information.
*
* @return The request and response encoding
*/
String getResponseRequestEncoding();
/**
* Gets the time that a request will by default be waiting for the previous
* request to be handled before giving up.
*
* @return The time out
*/
Duration getTimeout();
/**
* @see wicket.settings.IExceptionSettings#getUnexpectedExceptionDisplay()
*
* @return UnexpectedExceptionDisplay
*/
UnexpectedExceptionDisplay getUnexpectedExceptionDisplay();
/**
* @param bufferResponse
* True if this application should buffer responses.
*/
void setBufferResponse(boolean bufferResponse);
/**
* Sets whether Wicket should try to get extensive client info by
* redirecting to
* {@link BrowserInfoPage a page that polls for client capabilities}. This
* method is used by the default implementation of
* {@link WebRequestCycle#newClientInfo()}, so if that method is overriden,
* there is no guarantee this method will be taken into account.
*
* @param gatherExtendedBrowserInfo
* Whether to gather extensive client info
*/
void setGatherExtendedBrowserInfo(boolean gatherExtendedBrowserInfo);
/**
* Sets in what way the render part of a request is handled. Basically,
* there are two different options:
* <ul>
* <li>Direct, ApplicationSettings.ONE_PASS_RENDER. Everything is handled
* in one physical request. This is efficient, and is the best option if you
* want to do sophisticated clustering. It does not however, shield you from
* what is commonly known as the <i>Double submit problem </i></li>
* <li>Using a redirect. This follows the pattern <a
* href="http://www.theserverside.com/articles/article.tss?l=RedirectAfterPost"
* >as described at the serverside </a> and that is commonly known as
* Redirect after post. Wicket takes it one step further to do any rendering
* after a redirect, so that not only form submits are shielded from the
* double submit problem, but also the IRequestListener handlers (that could
* be e.g. a link that deletes a row). With this pattern, you have two
* options to choose from:
* <ul>
* <li>ApplicationSettings.REDIRECT_TO_RENDER. This option first handles
* the 'action' part of the request, which is either page construction
* (bookmarkable pages or the home page) or calling a IRequestListener
* handler, such as Link.onClick. When that part is done, a redirect is
* issued to the render part, which does all the rendering of the page and
* its components. <strong>Be aware </strong> that this may mean, depending
* on whether you access any models in the action part of the request, that
* attachement and detachement of some models is done twice for a request.
* </li>
* <li>ApplicationSettings.REDIRECT_TO_BUFFER. This option handles both the
* action- and the render part of the request in one physical request, but
* instead of streaming the result to the browser directly, it is kept in
* memory, and a redirect is issue to get this buffered result (after which
* it is immediately removed). This option currently is the default render
* strategy, as it shields you from the double submit problem, while being
* more efficient and less error prone regarding to detachable models.</li>
* </ul>
* Note that this parameter sets the default behavior, but that you can
* manually set whether any redirecting is done by calling method
* RequestCycle.setRedirect. Setting the redirect flag when the application
* is configured to use ONE_PASS_RENDER, will result in a redirect of type
* REDIRECT_TO_RENDER. When the application is configured to use
* REDIRECT_TO_RENDER or REDIRECT_TO_BUFFER, setting the redirect flag to
* false, will result in that request begin rendered and streamed in one
* pass.
*
* @param renderStrategy
* the render strategy that should be used by default.
*/
void setRenderStrategy(IRequestCycleSettings.RenderStrategy renderStrategy);
/**
* In order to do proper form parameter decoding it is important that the
* response and the following request have the same encoding. see
* http://www.crazysquirrel.com/computing/general/form-encoding.jspx for
* additional information.
*
* Default encoding: UTF-8
*
* @param responseRequestEncoding
* The request and response encoding to be used.
*/
void setResponseRequestEncoding(final String responseRequestEncoding);
/**
* Sets the time that a request will by default be waiting for the previous
* request to be handled before giving up.
*
* @param timeout
*/
void setTimeout(Duration timeout);
/**
* @see wicket.settings.IExceptionSettings#setUnexpectedExceptionDisplay(wicket.settings.Settings.UnexpectedExceptionDisplay)
*
* @param unexpectedExceptionDisplay
*/
void setUnexpectedExceptionDisplay(final UnexpectedExceptionDisplay unexpectedExceptionDisplay);
} | javadoc improvement
git-svn-id: 6d6ade8e88b1292e17cba3559b7335a947e495e0@501754 13f79535-47bb-0310-9956-ffa450edef68
| wicket/src/main/java/wicket/settings/IRequestCycleSettings.java | javadoc improvement | <ide><path>icket/src/main/java/wicket/settings/IRequestCycleSettings.java
<ide>
<ide> import wicket.IResponseFilter;
<ide> import wicket.RequestCycle;
<add>import wicket.Session;
<ide> import wicket.markup.html.pages.BrowserInfoPage;
<ide> import wicket.protocol.http.WebRequestCycle;
<ide> import wicket.settings.IExceptionSettings.UnexpectedExceptionDisplay;
<ide> * {@link WebRequestCycle#newClientInfo()}, so if that method is overriden,
<ide> * there is no guarantee this method will be taken into account.
<ide> *
<add> * <p>
<add> * <strong>WARNING: </strong> though this facility should work transparently
<add> * in most cases, it is recommended that you trigger the roundtrip to get
<add> * the browser info somewhere where it hurts the least. The roundtrip will
<add> * be triggered the first time you call {@link Session#getClientInfo()} for
<add> * a session, and after the roundtrip a new request with the same info (url,
<add> * post parameters) is handled. So rather than calling this in the middle of
<add> * an implementation of a form submit method, which would result in the code
<add> * of that method before the call to {@link Session#getClientInfo()} to be
<add> * executed twice, you best call {@link Session#getClientInfo()} e.g. in a
<add> * page constructor or somewhere else where you didn't do a lot of
<add> * processing first.
<add> * </p>
<add> *
<ide> * @param gatherExtendedBrowserInfo
<ide> * Whether to gather extensive client info
<ide> */ |
|
Java | mit | 42dac9a49d7b17bd8f0333b4bd3806464605f814 | 0 | FIRST-Team-339/2016 | /*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
// ====================================================================
// FILE NAME: Autonomous.java (Team 339 - Kilroy)
//
// CREATED ON: Jan 13, 2015
// CREATED BY: Nathanial Lydick
// MODIFIED ON:
// MODIFIED BY:
// ABSTRACT:
// This file is where almost all code for Kilroy will be
// written. All of these functions are functions that should
// override methods in the base class (IterativeRobot). The
// functions are as follows:
// -----------------------------------------------------
// Init() - Initialization code for teleop mode
// should go here. Will be called each time the robot enters
// teleop mode.
// -----------------------------------------------------
// Periodic() - Periodic code for teleop mode should
// go here. Will be called periodically at a regular rate while
// the robot is in teleop mode.
// -----------------------------------------------------
//
// NOTE: Please do not release this code without permission from
// Team 339.
// ====================================================================
package org.usfirst.frc.team339.robot;
import org.usfirst.frc.team339.Hardware.Hardware;
import org.usfirst.frc.team339.Utils.ManipulatorArm;
import edu.wpi.first.wpilibj.CameraServer;
import edu.wpi.first.wpilibj.DoubleSolenoid;
import edu.wpi.first.wpilibj.Relay.Value;
import edu.wpi.first.wpilibj.image.NIVisionException;
/**
* This class contains all of the user code for the Autonomous
* part of the match, namely, the Init and Periodic code
*
* @author Nathanial Lydick
* @written Jan 13, 2015
*/
public class Teleop
{
/**
* User Initialization code for teleop mode should go here. Will be
* called once when the robot enters teleop mode.
*
* @author Nathanial Lydick
* @written Jan 13, 2015
*/
public static void init ()
{
CameraServer.getInstance().setSize(1);
Hardware.axisCamera
.writeBrightness(Hardware.NORMAL_AXIS_CAMERA_BRIGHTNESS);
// set max speed. change by gear?
Hardware.drive.setMaxSpeed(MAXIMUM_TELEOP_SPEED);
Hardware.transmission.setFirstGearPercentage(FIRST_GEAR_PERCENTAGE);
Hardware.transmission
.setSecondGearPercentage(SECOND_GEAR_PERCENTAGE);
Hardware.transmission.setGear(1);
Hardware.transmission.setJoystickDeadbandRange(.20);
Hardware.transmission.setJoysticksAreReversed(false);
Hardware.ringLightRelay.set(Value.kOff);
// armEncoder needs to be set to 0
Hardware.delayTimer.reset();
Hardware.rightRearEncoder.reset();
Hardware.leftRearEncoder.reset();
Hardware.leftFrontMotor.set(0.0);
Hardware.leftRearMotor.set(0.0);
Hardware.rightFrontMotor.set(0.0);
Hardware.rightRearMotor.set(0.0);
Hardware.armMotor.set(0.0);
Hardware.armIntakeMotor.set(0.0);
} // end Init
private char[] reports;
private static boolean done = false;
private static boolean done2 = false;
private static edu.wpi.first.wpilibj.DoubleSolenoid.Value Reverse;
private static edu.wpi.first.wpilibj.DoubleSolenoid.Value Forward;
/**
* User Periodic code for teleop mode should go here. Will be called
* periodically at a regular rate while the robot is in teleop mode.
*
* @author Nathanial Lydick
* @written Jan 13, 2015
*/
public static void periodic ()
{
//block of code to move the arm
//TODO set deadzone to variable
if (Math.abs(Hardware.rightOperator.getY()) >= .2)
{
//use the formula for the sign (value/abs(value)) to get the direction we want the motor to go in,
//and round it just in case it isn't exactly 1, then cast to an int to make the compiler happy
Hardware.pickupArm
.moveFast((int) Math.round(Hardware.rightOperator.getY()
/ Math.abs(Hardware.rightOperator.getY())));
}
//Block of code to toggle the camera up or down
//If the camera is down and we press the button.
if (cameraIsUp == false
&& Hardware.cameraToggleButton.isOn() == true)
{
//raise the camera and tell the code that it's up
Hardware.cameraSolenoid.set(Forward);
cameraIsUp = true;
}
//If the camera is up and we press the toggle button.
if (cameraIsUp == true
&& Hardware.cameraToggleButton.isOn() == true)
{
//Drop the camera and tell the code that it's down
Hardware.cameraSolenoid.set(Reverse);
cameraIsUp = false;
}
//Block of code to align us on the goal using the camera
if (Hardware.rightOperator.getTrigger() == true)
{
//Tell the code to align us to the camera
isAligningByCamera = true;
}
//If we want to point at the goal using the camera
if (isAligningByCamera == true)
{
//TODO outsource both to a variable
//Keep trying to point at the goal
if (Hardware.drive.alignByCamera(.15, .45) == true)
{
//Once we're in the center, tell the code we no longer care about steering towards the goal
isAligningByCamera = false;
}
}
//Block of code to pick up ball or push it out
//pull in the ball if the pull in button is pressed.
if (Hardware.rightOperator
.getRawButton(TAKE_IN_BALL_BUTTON) == true)
{
Hardware.pickupArm.pullInBall();
}
//push out the ball if the push out button is pressed
else if (Hardware.rightOperator
.getRawButton(PUSH_OUT_BALL_BUTTON) == true)
{
Hardware.pickupArm.pushOutBall();
}
//If neither the pull in or the push out button are pressed, stop the intake motors
else
{
Hardware.pickupArm.stopIntakeArms();
}
//block of code to fire
if (Hardware.leftOperator.getTrigger() == true)
{
//Tell the code to start firing
fireRequested = true;
}
//cancel the fire request
if (Hardware.rightOperator.getRawButton(FIRE_CANCEL_BUTTON) == true)
{
fireRequested = false;
}
//if we want to fire
if (fireRequested == true)
{
//fire
if (fire(3) == true)
//if we're done firing, drop the request
fireRequested = false;
}
// Print statements to test Hardware on the Robot
printStatements();
// Tests the Camera
// takePicture();
// Driving the Robot
driveRobot();
runCameraSolenoid(Hardware.rightOperator.getRawButton(11),
Hardware.rightOperator.getRawButton(10), false, true);
} // end Periodic
/**
* Hand the transmission class the joystick values and motor controllers for
* four wheel drive.
*
*/
public static void driveRobot ()
{
//
// Hardware.transmission.controls(Hardware.rightDriver.getY(),
// Hardware.leftDriver.getY());
Hardware.transmission.setJoysticksAreReversed(true);
if (Hardware.rightDriver.getTrigger() == true && done == false)
{
done = Hardware.drive.turnLeftDegrees(90);
// done = Hardware.drive.driveForwardInches(48.0);
}
// If we're pressing the upshift button, shift up.
Hardware.transmission.controls(Hardware.rightDriver.getY(),
Hardware.leftDriver.getY());
// If we're pressing the upshift button, shift up.
if (Hardware.rightDriver
.getRawButton(GEAR_UPSHIFT_JOYSTICK_BUTTON) == true)
{
Hardware.transmission.upshift(1);
}
// If we press the downshift button, shift down.
if (Hardware.rightDriver
.getRawButton(GEAR_DOWNSHIFT_JOYSTICK_BUTTON) == true)
{
Hardware.transmission.downshift(1);
}
}
public static boolean armIsUp = false;
/**
* ^^^Bring the boolean armIsUp
* if method is moved to a different class.^^^
*
* @param upState
* @param downState
* @param holdState
* @param toggle
*
* When in toggle mode, one boolean raises the arm and one lowers.
* When not in toggle mode, only use boolean holdState. This will
* keep the arm up for the duration that the holdState is true.
*
* NOTE: if a parameter is not applicable, set it to false.
*
*
*
* @author Ryan McGee
* @written 2/13/16
*
*/
public static void runCameraSolenoid (boolean upState,
boolean downState, boolean holdState, boolean toggle)
{
if (upState && toggle == true && armIsUp == false)
{
Hardware.cameraSolenoid.set(DoubleSolenoid.Value.kForward);
armIsUp = true;
}
else if (downState && toggle == true && armIsUp == true)
{
Hardware.cameraSolenoid.set(DoubleSolenoid.Value.kReverse);
armIsUp = false;
}
else if (holdState && toggle == false)
{
Hardware.cameraSolenoid.set(DoubleSolenoid.Value.kForward);
}
else
{
Hardware.cameraSolenoid.set(DoubleSolenoid.Value.kReverse);
}
}
/**
* Fires the catapult.
*
* @param power
* -Can be 1, 2, or 3; corresponds to the amount of solenoids used to
* fire.
* @return
* -False if we're not yet done firing, true otherwise.
*/
public static boolean fire (int power)
{
if (Hardware.transducer.get() >= 100)
{
if (Hardware.pickupArm.moveToPosition(
ManipulatorArm.ArmPosition.CLEAR_OF_FIRING_ARM) == true)
{
Hardware.fireTimer.reset();
Hardware.fireTimer.start();
switch (power)
{
case 1:
Hardware.catapultSolenoid0.set(true);
break;
case 2:
Hardware.catapultSolenoid1.set(true);
Hardware.catapultSolenoid0.set(true);
break;
default:
case 3:
Hardware.catapultSolenoid0.set(true);
Hardware.catapultSolenoid1.set(true);
Hardware.catapultSolenoid2.set(true);
break;
}
}
}
//TODO reduce time to minimum possible
if (Hardware.fireTimer.get() >= 1.0)
{
Hardware.fireTimer.stop();
return true;
}
return false;
}
/**
* Takes a picture, processes it and saves it with left operator joystick
* take unlit picture: 6&7
* take lit picture: 10&11
*/
public static void takePicture ()
{
// If we click buttons 6+7 on the left operator joystick, we dim the
// brightness a lot, turn the ringlight on, and then if we haven't
// already taken an image then we do and set the boolean to true to
// prevent us taking more images. Otherwise we don't turn on the
// ringlight and we don't take a picture. We added a timer to delay
// taking the picture for the brightness to dim and for the ring
// light to turn on.
if (Hardware.leftOperator.getRawButton(6) == true
&& Hardware.leftOperator.getRawButton(7) == true)
{
if (prepPic == false)
{
Hardware.axisCamera.writeBrightness(
Hardware.MINIMUM_AXIS_CAMERA_BRIGHTNESS);
Hardware.ringLightRelay.set(Value.kOn);
Hardware.delayTimer.start();
prepPic = true;
takingLitImage = true;
}
}
// --------------------------------------------------------------------------
// ---CAMERA
// TEST------------------------------------------------------------
// Once the brightness is down and the ring light is on then the
// picture is taken, the brightness returns to normal, the ringlight
// is turned off, and the timer is stopped and reset.
// @TODO Change .25 to a constant, see line 65 under Hardware
// Replaced '.25' with Hardware.CAMERA_DELAY_TIME' change back if camera
// fails
// if (Hardware.delayTimer.get() >= Hardware.CAMERA_DELAY_TIME
// && prepPic == true && takingLitImage == true)
// {
// Hardware.axisCamera.saveImagesSafely();
// prepPic = false;
// takingLitImage = false;
// }
//
// if (takingLitImage == false && Hardware.delayTimer.get() >= 1)
// {
// Hardware.axisCamera.writeBrightness(
// Hardware.NORMAL_AXIS_CAMERA_BRIGHTNESS);
// Hardware.ringLightRelay.set(Value.kOff);
// Hardware.delayTimer.stop();
// Hardware.delayTimer.reset();
// }
// If we click buttons 10+11, we take a picture without the
// ringlight and set the boolean to true so we don't take a bunch of
// other pictures.
if (Hardware.leftOperator.getRawButton(10) == true &&
Hardware.leftOperator.getRawButton(11) == true)
{
if (takingUnlitImage == false)
{
takingUnlitImage = true;
Hardware.axisCamera.saveImagesSafely();
}
}
else
takingUnlitImage = false;
// if the left operator trigger is pressed, then we check to see if
// we're taking a processed picture through the boolean. If we are
// not currently taking a processed picture, then it lets us take a
// picture and sets the boolean to true so we don't take multiple
// pictures. If it is true, then it does nothing. If we don't click
// the trigger, then the boolean resets itself to false to take
// pictures again.
if (Hardware.leftOperator.getTrigger() == true)
{
if (processingImage == true)
{
processImage();
processingImage = false;
}
}
// TODO TESTING CODE. REMOVE ASAP.
// If we're pressing button 4
if (Hardware.leftOperator.getRawButton(4) == true)
{
if (Hardware.delayTimer.get() == 0)
{
Hardware.axisCamera.writeBrightness(
Hardware.MINIMUM_AXIS_CAMERA_BRIGHTNESS);
Hardware.delayTimer.start();
Hardware.ringLightRelay.set(Value.kOn);
}
// process taken images
// print out the center of mass of the largest blob
// if (Hardware.imageProcessor.getNumBlobs() > 0)
// {
// }
}
// System.out.println(
// "The delay timer is " + Hardware.delayTimer.get());
if (Hardware.delayTimer.get() >= 1.0)
{
// Hardware.axisCamera.writeBrightness(
// Hardware.NORMAL_AXIS_CAMERA_BRIGHTNESS);
Hardware.axisCamera.saveImagesSafely();
// Updates image when the 4th button is pressed and prints number
// of blobs
try
{
Hardware.imageProcessor
.updateImage(Hardware.axisCamera.getImage());
}
catch (NIVisionException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
Hardware.imageProcessor.updateParticleAnalysisReports();
System.out.println("Number of blobs equals: "
+ Hardware.imageProcessor.getNumBlobs());
Hardware.ringLightRelay.set(Value.kOff);
Hardware.delayTimer.stop();
Hardware.delayTimer.reset();
}
} // end Periodic
static boolean hasBegunTurning = true;
/**
*
* Processes images with the Axis Camera for use in autonomous when
* trying to score. Will eventually be moved to a Shoot class when
* one is made.
*
* @author Marlene McGraw
* @written 2/6/16
*
*/
public static void processImage ()
{
// If we took a picture, we set the boolean to true to prevent
// taking more pictures and create an image processor to process
// images.
// processingImage = true;
// Hardware.imageProcessor.processImage();
// System.out.println("Length: " +
// Hardware.imageProcessor.reports.length);
// System.out.println("Center of Mass Y: ");
}
// End processImage
/**
* stores print statements for future use in the print "bank", statements are
* commented out when
* not in use, when you write a new print statement, "deposit" the statement in
* the "bank"
* do not "withdraw" statements, unless directed to
*
* @author Ashley Espeland
* @written 1/28/16
*
* Edited by Ryan McGee
*
*/
public static void printStatements ()
{
// Joysticks------------
// System.out.println("Left Joystick: " + Hardware.leftDriver.getY());
// System.out
// .println("Right Joystick: " + Hardware.rightDriver.getY());
// System.out.println("Left Operator: " + Hardware.leftOperator.getY());
// System.out.println("Right Operator: " + Hardware.rightOperator.getY());
// IR sensors-----------
// System.out.println("left IR = " + Hardware.leftIR.isOn());
// System.out.println("right IR = " + Hardware.rightIR.isOn());
System.out.println("Has ball IR = " + Hardware.armIR.isOn());
// pots-----------------
System.out.println("delay pot = " + (int) Hardware.delayPot.get());
// prints the value of the transducer- (range in code is 50)
// hits psi of 100 accurately
System.out.println("transducer = " + Hardware.transducer.get());
System.out.println("Arm Pot = " + Hardware.armPot.get());
// Motor controllers-----
// prints value of the motors
// System.out.println("RR Motor T = " + Hardware.rightRearMotor.get());
// System.out.println("LR Motor T = " + Hardware.leftRearMotor.get());
// System.out.println("RF Motor T = " + Hardware.rightFrontMotor.get());
// System.out.println("LF Motor T = " + Hardware.leftFrontMotor.get());
// System.out.println("Arm Motor V = " + Hardware.armMotor.get());
// System.out.println("Starboard Intake Motor V = " +
// Hardware.starboardArmIntakeMotor.get());
// System.out.println("Port Intake Motor V = " +
// Hardware.portArmIntakeMotor.get());
// Solenoids-------------
// prints the state of the solenoids
// System.out.println("cameraSolenoid = " + Hardware.cameraSolenoid.get());
System.out.println("catapultSolenoid0 = " +
Hardware.catapultSolenoid0.get());
System.out.println("catapultSolenoid1 = " +
Hardware.catapultSolenoid1.get());
System.out.println("catapultSolenoid2 = " +
Hardware.catapultSolenoid2.get());
// Encoders-------------
// System.out.println(
// "RR distance = " + Hardware.rightRearEncoder.getDistance());
// System.out.println(
// "LR distance = " + Hardware.leftRearEncoder.getDistance());
// System.out.println("Arm Motor = " + Hardware.armMotor.getDistance());
// Switches--------------
// prints state of switches
// System.out.println("Autonomous Enabled Switch: " +
// Hardware.autonomousEnabled.isOn());
// System.out.println("Shoot High Switch: " + Hardware.shootHigh.isOn());
// System.out.println("Shoot Low Switch: " + Hardware.shootLow.isOn());
// print the position of the 6 position switch------------
// System.out.println("Position: " +
// Hardware.startingPositionDial.getPosition());
// Relay-----------------
// System.out.println(Hardware.ringLightRelay.get());
} // end printStatements
/*
* ===============================================
* Constants
* ===============================================
*/
private static final double MAXIMUM_TELEOP_SPEED = 1.0;
private static final double FIRST_GEAR_PERCENTAGE = 0.5;
private static final double SECOND_GEAR_PERCENTAGE =
MAXIMUM_TELEOP_SPEED;
//right driver 3
private static final int GEAR_UPSHIFT_JOYSTICK_BUTTON = 3;
//right driver 2
private static final int GEAR_DOWNSHIFT_JOYSTICK_BUTTON = 2;
//left operator 2
private static final int CAMERA_TOGGLE_BUTTON = 2;
//Right operator 2
private static final int FIRE_OVERRIDE_BUTTON = 2;
//Right operator 3
private static final int FIRE_CANCEL_BUTTON = 3;
//left operator 4
private static final int TAKE_IN_BALL_BUTTON = 4;
//right operator 5
private static final int PUSH_OUT_BALL_BUTTON = 5;
//TODO completely arbitrary and move to manipulator arm class
private static final double MAX_SOFT_ARM_STOP = 200;
private static final int MIN_SOFT_ARM_STOP = 0;
// ==========================================
// TUNEABLES
// ==========================================
private static boolean isAligningByCamera = false;
private static boolean cameraIsUp = false;
private static boolean isDrivingByCamera = false;
private static boolean fireRequested = false;
private static boolean processingImage = true;
// Boolean to check if we're taking a lit picture
private static boolean takingLitImage = false;
// Boolean to check if we're taking an unlit picture
private static boolean takingUnlitImage = false;
// this is for preparing to take a picture with the timer; changes
// brightness, turns on ringlight, starts timer
private static boolean prepPic = false;
} // end class
| src/org/usfirst/frc/team339/robot/Teleop.java | /*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
// ====================================================================
// FILE NAME: Autonomous.java (Team 339 - Kilroy)
//
// CREATED ON: Jan 13, 2015
// CREATED BY: Nathanial Lydick
// MODIFIED ON:
// MODIFIED BY:
// ABSTRACT:
// This file is where almost all code for Kilroy will be
// written. All of these functions are functions that should
// override methods in the base class (IterativeRobot). The
// functions are as follows:
// -----------------------------------------------------
// Init() - Initialization code for teleop mode
// should go here. Will be called each time the robot enters
// teleop mode.
// -----------------------------------------------------
// Periodic() - Periodic code for teleop mode should
// go here. Will be called periodically at a regular rate while
// the robot is in teleop mode.
// -----------------------------------------------------
//
// NOTE: Please do not release this code without permission from
// Team 339.
// ====================================================================
package org.usfirst.frc.team339.robot;
import org.usfirst.frc.team339.Hardware.Hardware;
import org.usfirst.frc.team339.Utils.ManipulatorArm;
import edu.wpi.first.wpilibj.CameraServer;
import edu.wpi.first.wpilibj.DoubleSolenoid;
import edu.wpi.first.wpilibj.Relay.Value;
import edu.wpi.first.wpilibj.image.NIVisionException;
/**
* This class contains all of the user code for the Autonomous
* part of the match, namely, the Init and Periodic code
*
* @author Nathanial Lydick
* @written Jan 13, 2015
*/
public class Teleop
{
/**
* User Initialization code for teleop mode should go here. Will be
* called once when the robot enters teleop mode.
*
* @author Nathanial Lydick
* @written Jan 13, 2015
*/
public static void init ()
{
CameraServer.getInstance().setSize(1);
Hardware.axisCamera
.writeBrightness(Hardware.NORMAL_AXIS_CAMERA_BRIGHTNESS);
// set max speed. change by gear?
Hardware.drive.setMaxSpeed(MAXIMUM_TELEOP_SPEED);
Hardware.transmission.setFirstGearPercentage(FIRST_GEAR_PERCENTAGE);
Hardware.transmission
.setSecondGearPercentage(SECOND_GEAR_PERCENTAGE);
Hardware.transmission.setGear(1);
Hardware.transmission.setJoystickDeadbandRange(.20);
Hardware.transmission.setJoysticksAreReversed(false);
Hardware.ringLightRelay.set(Value.kOff);
// armEncoder needs to be set to 0
Hardware.delayTimer.reset();
Hardware.rightRearEncoder.reset();
Hardware.leftRearEncoder.reset();
Hardware.leftFrontMotor.set(0.0);
Hardware.leftRearMotor.set(0.0);
Hardware.rightFrontMotor.set(0.0);
Hardware.rightRearMotor.set(0.0);
Hardware.armMotor.set(0.0);
Hardware.armIntakeMotor.set(0.0);
} // end Init
private char[] reports;
private static boolean done = false;
private static boolean done2 = false;
private static edu.wpi.first.wpilibj.DoubleSolenoid.Value Reverse;
private static edu.wpi.first.wpilibj.DoubleSolenoid.Value Forward;
/**
* User Periodic code for teleop mode should go here. Will be called
* periodically at a regular rate while the robot is in teleop mode.
*
* @author Nathanial Lydick
* @written Jan 13, 2015
*/
public static void periodic ()
{
//block of code to move the arm
//TODO set deadzone to variable
if (Math.abs(Hardware.rightOperator.getY()) >= .2)
{
//use the formula for the sign (value/abs(value)) to get the direction we want the motor to go in,
//and round it just in case it isn't exactly 1, then cast to an int to make the compiler happy
Hardware.pickupArm
.moveFast((int) Math.round(Hardware.rightOperator.getY()
/ Math.abs(Hardware.rightOperator.getY())));
}
//Block of code to toggle the camera up or down
if (cameraIsUp == false
&& Hardware.cameraToggleButton.isOn() == true)
{
Hardware.cameraSolenoid.set(Forward);
cameraIsUp = true;
}
if (cameraIsUp == true
&& Hardware.cameraToggleButton.isOn() == true)
{
Hardware.cameraSolenoid.set(Reverse);
cameraIsUp = false;
}
//Block of code to align us on the goal using the camera
if (Hardware.rightOperator.getTrigger() == true)
{
isAligningByCamera = true;
}
if (isAligningByCamera == true)
{
//TODO outsource both to a variable
if (Hardware.drive.alignByCamera(.15, .45) == true)
{
isAligningByCamera = false;
}
}
//Block of code to pick up ball or push it out
//pull in the ball if the pull in button is pressed.
if (Hardware.rightOperator
.getRawButton(TAKE_IN_BALL_BUTTON) == true)
{
Hardware.pickupArm.pullInBall();
}
//push out the ball if the push out button is pressed
else if (Hardware.rightOperator
.getRawButton(PUSH_OUT_BALL_BUTTON) == true)
{
Hardware.pickupArm.pushOutBall();
}
//If neither the pull in or the push out button are pressed, stop the intake motors
else
{
Hardware.pickupArm.stopIntakeArms();
}
//block of code to fire
if (Hardware.leftOperator.getTrigger() == true)
{
fireRequested = true;
}
//cancel the fire request
if (Hardware.rightOperator.getRawButton(FIRE_CANCEL_BUTTON) == true)
{
fireRequested = false;
}
//if we want to fire
if (fireRequested == true)
{
//fire
if (fire(3) == true)
//if we're done firing, drop the request
fireRequested = false;
}
// Print statements to test Hardware on the Robot
printStatements();
// Tests the Camera
// takePicture();
// Driving the Robot
driveRobot();
runCameraSolenoid(Hardware.rightOperator.getRawButton(11),
Hardware.rightOperator.getRawButton(10), false, true);
} // end Periodic
/**
* Hand the transmission class the joystick values and motor controllers for
* four wheel drive.
*
*/
public static void driveRobot ()
{
//
// Hardware.transmission.controls(Hardware.rightDriver.getY(),
// Hardware.leftDriver.getY());
Hardware.transmission.setJoysticksAreReversed(true);
if (Hardware.rightDriver.getTrigger() == true && done == false)
{
done = Hardware.drive.turnLeftDegrees(90);
// done = Hardware.drive.driveForwardInches(48.0);
}
// If we're pressing the upshift button, shift up.
Hardware.transmission.controls(Hardware.rightDriver.getY(),
Hardware.leftDriver.getY());
// If we're pressing the upshift button, shift up.
if (Hardware.rightDriver
.getRawButton(GEAR_UPSHIFT_JOYSTICK_BUTTON) == true)
{
Hardware.transmission.upshift(1);
}
// If we press the downshift button, shift down.
if (Hardware.rightDriver
.getRawButton(GEAR_DOWNSHIFT_JOYSTICK_BUTTON) == true)
{
Hardware.transmission.downshift(1);
}
}
public static boolean armIsUp = false;
/**
* ^^^Bring the boolean armIsUp
* if method is moved to a different class.^^^
*
* @param upState
* @param downState
* @param holdState
* @param toggle
*
* When in toggle mode, one boolean raises the arm and one lowers.
* When not in toggle mode, only use boolean holdState. This will
* keep the arm up for the duration that the holdState is true.
*
* NOTE: if a parameter is not applicable, set it to false.
*
*
*
* @author Ryan McGee
* @written 2/13/16
*
*/
public static void runCameraSolenoid (boolean upState,
boolean downState, boolean holdState, boolean toggle)
{
if (upState && toggle == true && armIsUp == false)
{
Hardware.cameraSolenoid.set(DoubleSolenoid.Value.kForward);
armIsUp = true;
}
else if (downState && toggle == true && armIsUp == true)
{
Hardware.cameraSolenoid.set(DoubleSolenoid.Value.kReverse);
armIsUp = false;
}
else if (holdState && toggle == false)
{
Hardware.cameraSolenoid.set(DoubleSolenoid.Value.kForward);
}
else
{
Hardware.cameraSolenoid.set(DoubleSolenoid.Value.kReverse);
}
}
/**
* Fires the catapult.
*
* @param power
* -Can be 1, 2, or 3; corresponds to the amount of solenoids used to
* fire.
* @return
* -False if we're not yet done firing, true otherwise.
*/
public static boolean fire (int power)
{
if (Hardware.transducer.get() >= 100)
{
if (Hardware.pickupArm.moveToPosition(
ManipulatorArm.ArmPosition.CLEAR_OF_FIRING_ARM) == true)
{
Hardware.fireTimer.reset();
Hardware.fireTimer.start();
switch (power)
{
case 1:
Hardware.catapultSolenoid0.set(true);
break;
case 2:
Hardware.catapultSolenoid1.set(true);
Hardware.catapultSolenoid0.set(true);
break;
default:
case 3:
Hardware.catapultSolenoid0.set(true);
Hardware.catapultSolenoid1.set(true);
Hardware.catapultSolenoid2.set(true);
break;
}
}
}
//TODO reduce time to minimum possible
if (Hardware.fireTimer.get() >= 1.0)
{
Hardware.fireTimer.stop();
return true;
}
return false;
}
/**
* Takes a picture, processes it and saves it with left operator joystick
* take unlit picture: 6&7
* take lit picture: 10&11
*/
public static void takePicture ()
{
// If we click buttons 6+7 on the left operator joystick, we dim the
// brightness a lot, turn the ringlight on, and then if we haven't
// already taken an image then we do and set the boolean to true to
// prevent us taking more images. Otherwise we don't turn on the
// ringlight and we don't take a picture. We added a timer to delay
// taking the picture for the brightness to dim and for the ring
// light to turn on.
if (Hardware.leftOperator.getRawButton(6) == true
&& Hardware.leftOperator.getRawButton(7) == true)
{
if (prepPic == false)
{
Hardware.axisCamera.writeBrightness(
Hardware.MINIMUM_AXIS_CAMERA_BRIGHTNESS);
Hardware.ringLightRelay.set(Value.kOn);
Hardware.delayTimer.start();
prepPic = true;
takingLitImage = true;
}
}
// --------------------------------------------------------------------------
// ---CAMERA
// TEST------------------------------------------------------------
// Once the brightness is down and the ring light is on then the
// picture is taken, the brightness returns to normal, the ringlight
// is turned off, and the timer is stopped and reset.
// @TODO Change .25 to a constant, see line 65 under Hardware
// Replaced '.25' with Hardware.CAMERA_DELAY_TIME' change back if camera
// fails
// if (Hardware.delayTimer.get() >= Hardware.CAMERA_DELAY_TIME
// && prepPic == true && takingLitImage == true)
// {
// Hardware.axisCamera.saveImagesSafely();
// prepPic = false;
// takingLitImage = false;
// }
//
// if (takingLitImage == false && Hardware.delayTimer.get() >= 1)
// {
// Hardware.axisCamera.writeBrightness(
// Hardware.NORMAL_AXIS_CAMERA_BRIGHTNESS);
// Hardware.ringLightRelay.set(Value.kOff);
// Hardware.delayTimer.stop();
// Hardware.delayTimer.reset();
// }
// If we click buttons 10+11, we take a picture without the
// ringlight and set the boolean to true so we don't take a bunch of
// other pictures.
if (Hardware.leftOperator.getRawButton(10) == true &&
Hardware.leftOperator.getRawButton(11) == true)
{
if (takingUnlitImage == false)
{
takingUnlitImage = true;
Hardware.axisCamera.saveImagesSafely();
}
}
else
takingUnlitImage = false;
// if the left operator trigger is pressed, then we check to see if
// we're taking a processed picture through the boolean. If we are
// not currently taking a processed picture, then it lets us take a
// picture and sets the boolean to true so we don't take multiple
// pictures. If it is true, then it does nothing. If we don't click
// the trigger, then the boolean resets itself to false to take
// pictures again.
if (Hardware.leftOperator.getTrigger() == true)
{
if (processingImage == true)
{
processImage();
processingImage = false;
}
}
// TODO TESTING CODE. REMOVE ASAP.
// If we're pressing button 4
if (Hardware.leftOperator.getRawButton(4) == true)
{
if (Hardware.delayTimer.get() == 0)
{
Hardware.axisCamera.writeBrightness(
Hardware.MINIMUM_AXIS_CAMERA_BRIGHTNESS);
Hardware.delayTimer.start();
Hardware.ringLightRelay.set(Value.kOn);
}
// process taken images
// print out the center of mass of the largest blob
// if (Hardware.imageProcessor.getNumBlobs() > 0)
// {
// }
}
// System.out.println(
// "The delay timer is " + Hardware.delayTimer.get());
if (Hardware.delayTimer.get() >= 1.0)
{
// Hardware.axisCamera.writeBrightness(
// Hardware.NORMAL_AXIS_CAMERA_BRIGHTNESS);
Hardware.axisCamera.saveImagesSafely();
// Updates image when the 4th button is pressed and prints number
// of blobs
try
{
Hardware.imageProcessor
.updateImage(Hardware.axisCamera.getImage());
}
catch (NIVisionException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
Hardware.imageProcessor.updateParticleAnalysisReports();
System.out.println("Number of blobs equals: "
+ Hardware.imageProcessor.getNumBlobs());
Hardware.ringLightRelay.set(Value.kOff);
Hardware.delayTimer.stop();
Hardware.delayTimer.reset();
}
} // end Periodic
static boolean hasBegunTurning = true;
/**
*
* Processes images with the Axis Camera for use in autonomous when
* trying to score. Will eventually be moved to a Shoot class when
* one is made.
*
* @author Marlene McGraw
* @written 2/6/16
*
*/
public static void processImage ()
{
// If we took a picture, we set the boolean to true to prevent
// taking more pictures and create an image processor to process
// images.
// processingImage = true;
// Hardware.imageProcessor.processImage();
// System.out.println("Length: " +
// Hardware.imageProcessor.reports.length);
// System.out.println("Center of Mass Y: ");
}
// End processImage
/**
* stores print statements for future use in the print "bank", statements are
* commented out when
* not in use, when you write a new print statement, "deposit" the statement in
* the "bank"
* do not "withdraw" statements, unless directed to
*
* @author Ashley Espeland
* @written 1/28/16
*
* Edited by Ryan McGee
*
*/
public static void printStatements ()
{
// Joysticks------------
// System.out.println("Left Joystick: " + Hardware.leftDriver.getY());
// System.out
// .println("Right Joystick: " + Hardware.rightDriver.getY());
// System.out.println("Left Operator: " + Hardware.leftOperator.getY());
// System.out.println("Right Operator: " + Hardware.rightOperator.getY());
// IR sensors-----------
// System.out.println("left IR = " + Hardware.leftIR.isOn());
// System.out.println("right IR = " + Hardware.rightIR.isOn());
System.out.println("Has ball IR = " + Hardware.armIR.isOn());
// pots-----------------
System.out.println("delay pot = " + (int) Hardware.delayPot.get());
// prints the value of the transducer- (range in code is 50)
// hits psi of 100 accurately
System.out.println("transducer = " + Hardware.transducer.get());
System.out.println("Arm Pot = " + Hardware.armPot.get());
// Motor controllers-----
// prints value of the motors
// System.out.println("RR Motor T = " + Hardware.rightRearMotor.get());
// System.out.println("LR Motor T = " + Hardware.leftRearMotor.get());
// System.out.println("RF Motor T = " + Hardware.rightFrontMotor.get());
// System.out.println("LF Motor T = " + Hardware.leftFrontMotor.get());
// System.out.println("Arm Motor V = " + Hardware.armMotor.get());
// System.out.println("Starboard Intake Motor V = " +
// Hardware.starboardArmIntakeMotor.get());
// System.out.println("Port Intake Motor V = " +
// Hardware.portArmIntakeMotor.get());
// Solenoids-------------
// prints the state of the solenoids
// System.out.println("cameraSolenoid = " + Hardware.cameraSolenoid.get());
System.out.println("catapultSolenoid0 = " +
Hardware.catapultSolenoid0.get());
System.out.println("catapultSolenoid1 = " +
Hardware.catapultSolenoid1.get());
System.out.println("catapultSolenoid2 = " +
Hardware.catapultSolenoid2.get());
// Encoders-------------
// System.out.println(
// "RR distance = " + Hardware.rightRearEncoder.getDistance());
// System.out.println(
// "LR distance = " + Hardware.leftRearEncoder.getDistance());
// System.out.println("Arm Motor = " + Hardware.armMotor.getDistance());
// Switches--------------
// prints state of switches
// System.out.println("Autonomous Enabled Switch: " +
// Hardware.autonomousEnabled.isOn());
// System.out.println("Shoot High Switch: " + Hardware.shootHigh.isOn());
// System.out.println("Shoot Low Switch: " + Hardware.shootLow.isOn());
// print the position of the 6 position switch------------
// System.out.println("Position: " +
// Hardware.startingPositionDial.getPosition());
// Relay-----------------
// System.out.println(Hardware.ringLightRelay.get());
} // end printStatements
/*
* ===============================================
* Constants
* ===============================================
*/
private static final double MAXIMUM_TELEOP_SPEED = 1.0;
private static final double FIRST_GEAR_PERCENTAGE = 0.5;
private static final double SECOND_GEAR_PERCENTAGE =
MAXIMUM_TELEOP_SPEED;
//right driver 3
private static final int GEAR_UPSHIFT_JOYSTICK_BUTTON = 3;
//right driver 2
private static final int GEAR_DOWNSHIFT_JOYSTICK_BUTTON = 2;
//left operator 2
private static final int CAMERA_TOGGLE_BUTTON = 2;
//Right operator 2
private static final int FIRE_OVERRIDE_BUTTON = 2;
//Right operator 3
private static final int FIRE_CANCEL_BUTTON = 3;
//left operator 4
private static final int TAKE_IN_BALL_BUTTON = 4;
//right operator 5
private static final int PUSH_OUT_BALL_BUTTON = 5;
//TODO completely arbitrary and move to manipulator arm class
private static final double MAX_SOFT_ARM_STOP = 200;
private static final int MIN_SOFT_ARM_STOP = 0;
// ==========================================
// TUNEABLES
// ==========================================
private static boolean isAligningByCamera = false;
private static boolean cameraIsUp = false;
private static boolean isDrivingByCamera = false;
private static boolean fireRequested = false;
private static boolean processingImage = true;
// Boolean to check if we're taking a lit picture
private static boolean takingLitImage = false;
// Boolean to check if we're taking an unlit picture
private static boolean takingUnlitImage = false;
// this is for preparing to take a picture with the timer; changes
// brightness, turns on ringlight, starts timer
private static boolean prepPic = false;
} // end class
| Commented all my teleop stuff. | src/org/usfirst/frc/team339/robot/Teleop.java | Commented all my teleop stuff. | <ide><path>rc/org/usfirst/frc/team339/robot/Teleop.java
<ide> / Math.abs(Hardware.rightOperator.getY())));
<ide> }
<ide> //Block of code to toggle the camera up or down
<add> //If the camera is down and we press the button.
<ide> if (cameraIsUp == false
<ide> && Hardware.cameraToggleButton.isOn() == true)
<ide> {
<add> //raise the camera and tell the code that it's up
<ide> Hardware.cameraSolenoid.set(Forward);
<ide> cameraIsUp = true;
<ide> }
<add> //If the camera is up and we press the toggle button.
<ide> if (cameraIsUp == true
<ide> && Hardware.cameraToggleButton.isOn() == true)
<ide> {
<add> //Drop the camera and tell the code that it's down
<ide> Hardware.cameraSolenoid.set(Reverse);
<ide> cameraIsUp = false;
<ide> }
<ide> //Block of code to align us on the goal using the camera
<ide> if (Hardware.rightOperator.getTrigger() == true)
<ide> {
<add> //Tell the code to align us to the camera
<ide> isAligningByCamera = true;
<ide> }
<del>
<add> //If we want to point at the goal using the camera
<ide> if (isAligningByCamera == true)
<ide> {
<ide> //TODO outsource both to a variable
<add> //Keep trying to point at the goal
<ide> if (Hardware.drive.alignByCamera(.15, .45) == true)
<ide> {
<add> //Once we're in the center, tell the code we no longer care about steering towards the goal
<ide> isAligningByCamera = false;
<ide> }
<ide> }
<ide> //block of code to fire
<ide> if (Hardware.leftOperator.getTrigger() == true)
<ide> {
<add> //Tell the code to start firing
<ide> fireRequested = true;
<ide> }
<ide> //cancel the fire request |
|
Java | apache-2.0 | dd637c350b388e31aadad85f3616f6f0a1d07272 | 0 | milleruntime/accumulo,mjwall/accumulo,mjwall/accumulo,ctubbsii/accumulo,ctubbsii/accumulo,phrocker/accumulo-1,apache/accumulo,apache/accumulo,mjwall/accumulo,phrocker/accumulo-1,ctubbsii/accumulo,milleruntime/accumulo,phrocker/accumulo-1,ctubbsii/accumulo,phrocker/accumulo-1,milleruntime/accumulo,phrocker/accumulo-1,apache/accumulo,mjwall/accumulo,mjwall/accumulo,milleruntime/accumulo,apache/accumulo,apache/accumulo,phrocker/accumulo-1,milleruntime/accumulo,ctubbsii/accumulo,milleruntime/accumulo,apache/accumulo,ctubbsii/accumulo,milleruntime/accumulo,ctubbsii/accumulo,apache/accumulo,mjwall/accumulo,phrocker/accumulo-1,mjwall/accumulo | /*
* 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.accumulo.test.functional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.apache.accumulo.core.client.Accumulo;
import org.apache.accumulo.core.client.AccumuloClient;
import org.apache.accumulo.core.client.AccumuloException;
import org.apache.accumulo.core.client.AccumuloSecurityException;
import org.apache.accumulo.core.client.BatchWriter;
import org.apache.accumulo.core.client.MutationsRejectedException;
import org.apache.accumulo.core.client.TableNotFoundException;
import org.apache.accumulo.core.client.TableOfflineException;
import org.apache.accumulo.core.client.admin.CompactionConfig;
import org.apache.accumulo.core.clientImpl.ClientContext;
import org.apache.accumulo.core.data.Mutation;
import org.apache.accumulo.core.security.Authorizations;
import org.apache.accumulo.harness.AccumuloClusterHarness;
import org.apache.hadoop.io.Text;
import org.junit.Test;
public class ConcurrentDeleteTableIT extends AccumuloClusterHarness {
@Override
protected int defaultTimeoutSeconds() {
return 7 * 60;
}
@Test
public void testConcurrentDeleteTablesOps() throws Exception {
try (AccumuloClient c = Accumulo.newClient().from(getClientProps()).build()) {
String[] tables = getUniqueNames(2);
TreeSet<Text> splits = createSplits();
ExecutorService es = Executors.newFixedThreadPool(20);
int count = 0;
for (final String table : tables) {
c.tableOperations().create(table);
c.tableOperations().addSplits(table, splits);
writeData(c, table);
if (count == 1) {
c.tableOperations().flush(table, null, null, true);
}
count++;
int numDeleteOps = 20;
final CountDownLatch cdl = new CountDownLatch(numDeleteOps);
List<Future<?>> futures = new ArrayList<>();
for (int i = 0; i < numDeleteOps; i++) {
Future<?> future = es.submit(new Runnable() {
@Override
public void run() {
try {
cdl.countDown();
cdl.await();
c.tableOperations().delete(table);
} catch (TableNotFoundException e) {
// expected
} catch (InterruptedException | AccumuloException | AccumuloSecurityException e) {
throw new RuntimeException(e);
}
}
});
futures.add(future);
}
for (Future<?> future : futures) {
future.get();
}
try {
c.createScanner(table, Authorizations.EMPTY);
fail("Expected table " + table + " to be gone.");
} catch (TableNotFoundException tnfe) {
// expected
}
FunctionalTestUtils.assertNoDanglingFateLocks((ClientContext) c, getCluster());
}
es.shutdown();
}
}
private TreeSet<Text> createSplits() {
TreeSet<Text> splits = new TreeSet<>();
for (int i = 0; i < 1000; i++) {
Text split = new Text(String.format("%09x", i * 100000));
splits.add(split);
}
return splits;
}
private abstract static class DelayedTableOp implements Runnable {
private CountDownLatch cdl;
DelayedTableOp(CountDownLatch cdl) {
this.cdl = cdl;
}
@Override
public void run() {
try {
cdl.countDown();
cdl.await();
Thread.sleep(10);
doTableOp();
} catch (TableNotFoundException | TableOfflineException e) {
// expected
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
protected abstract void doTableOp() throws Exception;
}
@Test
public void testConcurrentFateOpsWithDelete() throws Exception {
try (AccumuloClient c = Accumulo.newClient().from(getClientProps()).build()) {
String[] tables = getUniqueNames(2);
TreeSet<Text> splits = createSplits();
int numOperations = 8;
ExecutorService es = Executors.newFixedThreadPool(numOperations);
int count = 0;
for (final String table : tables) {
c.tableOperations().create(table);
c.tableOperations().addSplits(table, splits);
writeData(c, table);
if (count == 1) {
c.tableOperations().flush(table, null, null, true);
}
count++;
// increment this for each test
final CountDownLatch cdl = new CountDownLatch(numOperations);
List<Future<?>> futures = new ArrayList<>();
futures.add(es.submit(new Runnable() {
@Override
public void run() {
try {
cdl.countDown();
cdl.await();
c.tableOperations().delete(table);
} catch (TableNotFoundException | TableOfflineException e) {
// expected
} catch (InterruptedException | AccumuloException | AccumuloSecurityException e) {
throw new RuntimeException(e);
}
}
}));
futures.add(es.submit(new DelayedTableOp(cdl) {
@Override
protected void doTableOp() throws Exception {
c.tableOperations().compact(table, new CompactionConfig());
}
}));
futures.add(es.submit(new DelayedTableOp(cdl) {
@Override
protected void doTableOp() throws Exception {
c.tableOperations().merge(table, null, null);
}
}));
futures.add(es.submit(new DelayedTableOp(cdl) {
@Override
protected void doTableOp() throws Exception {
Map<String,String> m = Collections.emptyMap();
Set<String> s = Collections.emptySet();
c.tableOperations().clone(table, table + "_clone", true, m, s);
}
}));
futures.add(es.submit(new DelayedTableOp(cdl) {
@Override
protected void doTableOp() throws Exception {
c.tableOperations().deleteRows(table, null, null);
}
}));
futures.add(es.submit(new DelayedTableOp(cdl) {
@Override
protected void doTableOp() throws Exception {
c.tableOperations().cancelCompaction(table);
}
}));
futures.add(es.submit(new DelayedTableOp(cdl) {
@Override
protected void doTableOp() throws Exception {
c.tableOperations().rename(table, table + "_renamed");
}
}));
futures.add(es.submit(new DelayedTableOp(cdl) {
@Override
protected void doTableOp() throws Exception {
c.tableOperations().offline(table);
}
}));
assertEquals(numOperations, futures.size());
for (Future<?> future : futures) {
future.get();
}
try {
c.createScanner(table, Authorizations.EMPTY);
fail("Expected table " + table + " to be gone.");
} catch (TableNotFoundException tnfe) {
// expected
}
FunctionalTestUtils.assertNoDanglingFateLocks((ClientContext) c, getCluster());
}
es.shutdown();
}
}
private void writeData(AccumuloClient c, String table)
throws TableNotFoundException, MutationsRejectedException {
try (BatchWriter bw = c.createBatchWriter(table)) {
Random rand = new SecureRandom();
for (int i = 0; i < 1000; i++) {
Mutation m = new Mutation(String.format("%09x", rand.nextInt(100000 * 1000)));
m.put("m", "order", "" + i);
bw.addMutation(m);
}
}
}
}
| test/src/main/java/org/apache/accumulo/test/functional/ConcurrentDeleteTableIT.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.accumulo.test.functional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.apache.accumulo.core.client.Accumulo;
import org.apache.accumulo.core.client.AccumuloClient;
import org.apache.accumulo.core.client.AccumuloException;
import org.apache.accumulo.core.client.AccumuloSecurityException;
import org.apache.accumulo.core.client.BatchWriter;
import org.apache.accumulo.core.client.MutationsRejectedException;
import org.apache.accumulo.core.client.TableNotFoundException;
import org.apache.accumulo.core.client.TableOfflineException;
import org.apache.accumulo.core.client.admin.CompactionConfig;
import org.apache.accumulo.core.clientImpl.ClientContext;
import org.apache.accumulo.core.data.Mutation;
import org.apache.accumulo.core.security.Authorizations;
import org.apache.accumulo.harness.AccumuloClusterHarness;
import org.apache.hadoop.io.Text;
import org.junit.Test;
public class ConcurrentDeleteTableIT extends AccumuloClusterHarness {
@Test
public void testConcurrentDeleteTablesOps() throws Exception {
try (AccumuloClient c = Accumulo.newClient().from(getClientProps()).build()) {
String[] tables = getUniqueNames(2);
TreeSet<Text> splits = createSplits();
ExecutorService es = Executors.newFixedThreadPool(20);
int count = 0;
for (final String table : tables) {
c.tableOperations().create(table);
c.tableOperations().addSplits(table, splits);
writeData(c, table);
if (count == 1) {
c.tableOperations().flush(table, null, null, true);
}
count++;
int numDeleteOps = 20;
final CountDownLatch cdl = new CountDownLatch(numDeleteOps);
List<Future<?>> futures = new ArrayList<>();
for (int i = 0; i < numDeleteOps; i++) {
Future<?> future = es.submit(new Runnable() {
@Override
public void run() {
try {
cdl.countDown();
cdl.await();
c.tableOperations().delete(table);
} catch (TableNotFoundException e) {
// expected
} catch (InterruptedException | AccumuloException | AccumuloSecurityException e) {
throw new RuntimeException(e);
}
}
});
futures.add(future);
}
for (Future<?> future : futures) {
future.get();
}
try {
c.createScanner(table, Authorizations.EMPTY);
fail("Expected table " + table + " to be gone.");
} catch (TableNotFoundException tnfe) {
// expected
}
FunctionalTestUtils.assertNoDanglingFateLocks((ClientContext) c, getCluster());
}
es.shutdown();
}
}
private TreeSet<Text> createSplits() {
TreeSet<Text> splits = new TreeSet<>();
for (int i = 0; i < 1000; i++) {
Text split = new Text(String.format("%09x", i * 100000));
splits.add(split);
}
return splits;
}
private abstract static class DelayedTableOp implements Runnable {
private CountDownLatch cdl;
DelayedTableOp(CountDownLatch cdl) {
this.cdl = cdl;
}
@Override
public void run() {
try {
cdl.countDown();
cdl.await();
Thread.sleep(10);
doTableOp();
} catch (TableNotFoundException | TableOfflineException e) {
// expected
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
protected abstract void doTableOp() throws Exception;
}
@Test
public void testConcurrentFateOpsWithDelete() throws Exception {
try (AccumuloClient c = Accumulo.newClient().from(getClientProps()).build()) {
String[] tables = getUniqueNames(2);
TreeSet<Text> splits = createSplits();
int numOperations = 8;
ExecutorService es = Executors.newFixedThreadPool(numOperations);
int count = 0;
for (final String table : tables) {
c.tableOperations().create(table);
c.tableOperations().addSplits(table, splits);
writeData(c, table);
if (count == 1) {
c.tableOperations().flush(table, null, null, true);
}
count++;
// increment this for each test
final CountDownLatch cdl = new CountDownLatch(numOperations);
List<Future<?>> futures = new ArrayList<>();
futures.add(es.submit(new Runnable() {
@Override
public void run() {
try {
cdl.countDown();
cdl.await();
c.tableOperations().delete(table);
} catch (TableNotFoundException | TableOfflineException e) {
// expected
} catch (InterruptedException | AccumuloException | AccumuloSecurityException e) {
throw new RuntimeException(e);
}
}
}));
futures.add(es.submit(new DelayedTableOp(cdl) {
@Override
protected void doTableOp() throws Exception {
c.tableOperations().compact(table, new CompactionConfig());
}
}));
futures.add(es.submit(new DelayedTableOp(cdl) {
@Override
protected void doTableOp() throws Exception {
c.tableOperations().merge(table, null, null);
}
}));
futures.add(es.submit(new DelayedTableOp(cdl) {
@Override
protected void doTableOp() throws Exception {
Map<String,String> m = Collections.emptyMap();
Set<String> s = Collections.emptySet();
c.tableOperations().clone(table, table + "_clone", true, m, s);
}
}));
futures.add(es.submit(new DelayedTableOp(cdl) {
@Override
protected void doTableOp() throws Exception {
c.tableOperations().deleteRows(table, null, null);
}
}));
futures.add(es.submit(new DelayedTableOp(cdl) {
@Override
protected void doTableOp() throws Exception {
c.tableOperations().cancelCompaction(table);
}
}));
futures.add(es.submit(new DelayedTableOp(cdl) {
@Override
protected void doTableOp() throws Exception {
c.tableOperations().rename(table, table + "_renamed");
}
}));
futures.add(es.submit(new DelayedTableOp(cdl) {
@Override
protected void doTableOp() throws Exception {
c.tableOperations().offline(table);
}
}));
assertEquals(numOperations, futures.size());
for (Future<?> future : futures) {
future.get();
}
try {
c.createScanner(table, Authorizations.EMPTY);
fail("Expected table " + table + " to be gone.");
} catch (TableNotFoundException tnfe) {
// expected
}
FunctionalTestUtils.assertNoDanglingFateLocks((ClientContext) c, getCluster());
}
es.shutdown();
}
}
private void writeData(AccumuloClient c, String table)
throws TableNotFoundException, MutationsRejectedException {
try (BatchWriter bw = c.createBatchWriter(table)) {
Random rand = new SecureRandom();
for (int i = 0; i < 1000; i++) {
Mutation m = new Mutation(String.format("%09x", rand.nextInt(100000 * 1000)));
m.put("m", "order", "" + i);
bw.addMutation(m);
}
}
}
}
| Re #1841 Add timeout to ConcurrentDeleteTableIT
* added a default 7min timeout | test/src/main/java/org/apache/accumulo/test/functional/ConcurrentDeleteTableIT.java | Re #1841 Add timeout to ConcurrentDeleteTableIT | <ide><path>est/src/main/java/org/apache/accumulo/test/functional/ConcurrentDeleteTableIT.java
<ide>
<ide> public class ConcurrentDeleteTableIT extends AccumuloClusterHarness {
<ide>
<add> @Override
<add> protected int defaultTimeoutSeconds() {
<add> return 7 * 60;
<add> }
<add>
<ide> @Test
<ide> public void testConcurrentDeleteTablesOps() throws Exception {
<ide> try (AccumuloClient c = Accumulo.newClient().from(getClientProps()).build()) { |
|
Java | apache-2.0 | 35a99ca46d7c9576ebfd03a7c9209a3b6fb3cd49 | 0 | bmaupin/android-sms-plus | /*
* Copyright (C) 2008 Esmertec AG.
* Copyright (C) 2008 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.android.mms.ui;
import static android.content.res.Configuration.KEYBOARDHIDDEN_NO;
import static com.android.mms.transaction.ProgressCallbackEntity.PROGRESS_ABORT;
import static com.android.mms.transaction.ProgressCallbackEntity.PROGRESS_COMPLETE;
import static com.android.mms.transaction.ProgressCallbackEntity.PROGRESS_START;
import static com.android.mms.transaction.ProgressCallbackEntity.PROGRESS_STATUS_ACTION;
import static com.android.mms.ui.MessageListAdapter.COLUMN_ID;
import static com.android.mms.ui.MessageListAdapter.COLUMN_MSG_TYPE;
import static com.android.mms.ui.MessageListAdapter.PROJECTION;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.DialogInterface.OnClickListener;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SqliteWrapper;
import android.drm.DrmStore;
import android.graphics.drawable.Drawable;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.os.SystemProperties;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.Contacts;
import android.provider.Settings;
import android.provider.ContactsContract.Intents;
import android.provider.MediaStore.Images;
import android.provider.MediaStore.Video;
import android.provider.Telephony.Mms;
import android.provider.Telephony.Sms;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.telephony.PhoneNumberUtils;
import android.telephony.SmsMessage;
import android.content.ClipboardManager;
import android.text.Editable;
import android.text.InputFilter;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.TextKeyListener;
import android.text.style.URLSpan;
import android.text.util.Linkify;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewStub;
import android.view.WindowManager;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnCreateContextMenuListener;
import android.view.View.OnKeyListener;
import android.view.inputmethod.InputMethodManager;
import android.webkit.MimeTypeMap;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.android.internal.telephony.TelephonyIntents;
import com.android.internal.telephony.TelephonyProperties;
import com.android.mms.LogTag;
import com.android.mms.MmsApp;
import com.android.mms.MmsConfig;
import com.android.mms.R;
import com.android.mms.TempFileProvider;
import com.android.mms.data.Contact;
import com.android.mms.data.ContactList;
import com.android.mms.data.Conversation;
import com.android.mms.data.Conversation.ConversationQueryHandler;
import com.android.mms.data.WorkingMessage;
import com.android.mms.data.WorkingMessage.MessageStatusListener;
import com.android.mms.drm.DrmUtils;
import com.google.android.mms.ContentType;
import com.google.android.mms.pdu.EncodedStringValue;
import com.google.android.mms.MmsException;
import com.google.android.mms.pdu.PduBody;
import com.google.android.mms.pdu.PduPart;
import com.google.android.mms.pdu.PduPersister;
import com.google.android.mms.pdu.SendReq;
import com.android.mms.model.SlideModel;
import com.android.mms.model.SlideshowModel;
import com.android.mms.transaction.MessagingNotification;
import com.android.mms.ui.MessageListView.OnSizeChangedListener;
import com.android.mms.ui.MessageUtils.ResizeImageResultCallback;
import com.android.mms.ui.RecipientsEditor.RecipientContextMenuInfo;
import com.android.mms.util.AddressUtils;
import com.android.mms.util.PhoneNumberFormatter;
import com.android.mms.util.SendingProgressTokenManager;
import com.android.mms.util.SmileyParser;
import android.text.InputFilter.LengthFilter;
/**
* This is the main UI for:
* 1. Composing a new message;
* 2. Viewing/managing message history of a conversation.
*
* This activity can handle following parameters from the intent
* by which it's launched.
* thread_id long Identify the conversation to be viewed. When creating a
* new message, this parameter shouldn't be present.
* msg_uri Uri The message which should be opened for editing in the editor.
* address String The addresses of the recipients in current conversation.
* exit_on_sent boolean Exit this activity after the message is sent.
*/
public class ComposeMessageActivity extends Activity
implements View.OnClickListener, TextView.OnEditorActionListener,
MessageStatusListener, Contact.UpdateListener {
public static final int REQUEST_CODE_ATTACH_IMAGE = 100;
public static final int REQUEST_CODE_TAKE_PICTURE = 101;
public static final int REQUEST_CODE_ATTACH_VIDEO = 102;
public static final int REQUEST_CODE_TAKE_VIDEO = 103;
public static final int REQUEST_CODE_ATTACH_SOUND = 104;
public static final int REQUEST_CODE_RECORD_SOUND = 105;
public static final int REQUEST_CODE_CREATE_SLIDESHOW = 106;
public static final int REQUEST_CODE_ECM_EXIT_DIALOG = 107;
public static final int REQUEST_CODE_ADD_CONTACT = 108;
public static final int REQUEST_CODE_PICK = 109;
private static final String TAG = "Mms/compose";
private static final boolean DEBUG = false;
private static final boolean TRACE = false;
private static final boolean LOCAL_LOGV = false;
// Menu ID
private static final int MENU_ADD_SUBJECT = 0;
private static final int MENU_DELETE_THREAD = 1;
private static final int MENU_ADD_ATTACHMENT = 2;
private static final int MENU_DISCARD = 3;
private static final int MENU_SEND = 4;
private static final int MENU_CALL_RECIPIENT = 5;
private static final int MENU_CONVERSATION_LIST = 6;
private static final int MENU_DEBUG_DUMP = 7;
// Context menu ID
private static final int MENU_VIEW_CONTACT = 12;
private static final int MENU_ADD_TO_CONTACTS = 13;
private static final int MENU_EDIT_MESSAGE = 14;
private static final int MENU_VIEW_SLIDESHOW = 16;
private static final int MENU_VIEW_MESSAGE_DETAILS = 17;
private static final int MENU_DELETE_MESSAGE = 18;
private static final int MENU_SEARCH = 19;
private static final int MENU_DELIVERY_REPORT = 20;
private static final int MENU_FORWARD_MESSAGE = 21;
private static final int MENU_CALL_BACK = 22;
private static final int MENU_SEND_EMAIL = 23;
private static final int MENU_COPY_MESSAGE_TEXT = 24;
private static final int MENU_COPY_TO_SDCARD = 25;
private static final int MENU_INSERT_SMILEY = 26;
private static final int MENU_ADD_ADDRESS_TO_CONTACTS = 27;
private static final int MENU_LOCK_MESSAGE = 28;
private static final int MENU_UNLOCK_MESSAGE = 29;
private static final int MENU_SAVE_RINGTONE = 30;
private static final int MENU_PREFERENCES = 31;
private static final int RECIPIENTS_MAX_LENGTH = 312;
private static final int MESSAGE_LIST_QUERY_TOKEN = 9527;
private static final int MESSAGE_LIST_QUERY_AFTER_DELETE_TOKEN = 9528;
private static final int DELETE_MESSAGE_TOKEN = 9700;
private static final int CHARS_REMAINING_BEFORE_COUNTER_SHOWN = 10;
private static final long NO_DATE_FOR_DIALOG = -1L;
private static final String EXIT_ECM_RESULT = "exit_ecm_result";
// When the conversation has a lot of messages and a new message is sent, the list is scrolled
// so the user sees the just sent message. If we have to scroll the list more than 20 items,
// then a scroll shortcut is invoked to move the list near the end before scrolling.
private static final int MAX_ITEMS_TO_INVOKE_SCROLL_SHORTCUT = 20;
// Any change in height in the message list view greater than this threshold will not
// cause a smooth scroll. Instead, we jump the list directly to the desired position.
private static final int SMOOTH_SCROLL_THRESHOLD = 200;
private ContentResolver mContentResolver;
private BackgroundQueryHandler mBackgroundQueryHandler;
private Conversation mConversation; // Conversation we are working in
private boolean mExitOnSent; // Should we finish() after sending a message?
// TODO: mExitOnSent is obsolete -- remove
private View mTopPanel; // View containing the recipient and subject editors
private View mBottomPanel; // View containing the text editor, send button, ec.
private EditText mTextEditor; // Text editor to type your message into
private TextView mTextCounter; // Shows the number of characters used in text editor
private TextView mSendButtonMms; // Press to send mms
private ImageButton mSendButtonSms; // Press to send sms
private EditText mSubjectTextEditor; // Text editor for MMS subject
private AttachmentEditor mAttachmentEditor;
private View mAttachmentEditorScrollView;
private MessageListView mMsgListView; // ListView for messages in this conversation
public MessageListAdapter mMsgListAdapter; // and its corresponding ListAdapter
private RecipientsEditor mRecipientsEditor; // UI control for editing recipients
private ImageButton mRecipientsPicker; // UI control for recipients picker
private boolean mIsKeyboardOpen; // Whether the hardware keyboard is visible
private boolean mIsLandscape; // Whether we're in landscape mode
private boolean mPossiblePendingNotification; // If the message list has changed, we may have
// a pending notification to deal with.
private boolean mToastForDraftSave; // Whether to notify the user that a draft is being saved
private boolean mSentMessage; // true if the user has sent a message while in this
// activity. On a new compose message case, when the first
// message is sent is a MMS w/ attachment, the list blanks
// for a second before showing the sent message. But we'd
// think the message list is empty, thus show the recipients
// editor thinking it's a draft message. This flag should
// help clarify the situation.
private WorkingMessage mWorkingMessage; // The message currently being composed.
private AlertDialog mSmileyDialog;
private boolean mWaitingForSubActivity;
private int mLastRecipientCount; // Used for warning the user on too many recipients.
private AttachmentTypeSelectorAdapter mAttachmentTypeSelectorAdapter;
private boolean mSendingMessage; // Indicates the current message is sending, and shouldn't send again.
private Intent mAddContactIntent; // Intent used to add a new contact
private Uri mTempMmsUri; // Only used as a temporary to hold a slideshow uri
private long mTempThreadId; // Only used as a temporary to hold a threadId
private AsyncDialog mAsyncDialog; // Used for background tasks.
private String mDebugRecipients;
private int mLastSmoothScrollPosition;
private boolean mScrollOnSend; // Flag that we need to scroll the list to the end.
private int mSavedScrollPosition = -1; // we save the ListView's scroll position in onPause(),
// so we can remember it after re-entering the activity.
/**
* Whether this activity is currently running (i.e. not paused)
*/
private boolean mIsRunning;
@SuppressWarnings("unused")
public static void log(String logMsg) {
Thread current = Thread.currentThread();
long tid = current.getId();
StackTraceElement[] stack = current.getStackTrace();
String methodName = stack[3].getMethodName();
// Prepend current thread ID and name of calling method to the message.
logMsg = "[" + tid + "] [" + methodName + "] " + logMsg;
Log.d(TAG, logMsg);
}
//==========================================================
// Inner classes
//==========================================================
private void editSlideshow() {
// The user wants to edit the slideshow. That requires us to persist the slideshow to
// disk as a PDU in saveAsMms. This code below does that persisting in a background
// task. If the task takes longer than a half second, a progress dialog is displayed.
// Once the PDU persisting is done, another runnable on the UI thread get executed to start
// the SlideshowEditActivity.
getAsyncDialog().runAsync(new Runnable() {
@Override
public void run() {
// This runnable gets run in a background thread.
mTempMmsUri = mWorkingMessage.saveAsMms(false);
}
}, new Runnable() {
@Override
public void run() {
// Once the above background thread is complete, this runnable is run
// on the UI thread.
if (mTempMmsUri == null) {
return;
}
Intent intent = new Intent(ComposeMessageActivity.this,
SlideshowEditActivity.class);
intent.setData(mTempMmsUri);
startActivityForResult(intent, REQUEST_CODE_CREATE_SLIDESHOW);
}
}, R.string.building_slideshow_title);
}
private final Handler mAttachmentEditorHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case AttachmentEditor.MSG_EDIT_SLIDESHOW: {
editSlideshow();
break;
}
case AttachmentEditor.MSG_SEND_SLIDESHOW: {
if (isPreparedForSending()) {
ComposeMessageActivity.this.confirmSendMessageIfNeeded();
}
break;
}
case AttachmentEditor.MSG_VIEW_IMAGE:
case AttachmentEditor.MSG_PLAY_VIDEO:
case AttachmentEditor.MSG_PLAY_AUDIO:
case AttachmentEditor.MSG_PLAY_SLIDESHOW:
viewMmsMessageAttachment(msg.what);
break;
case AttachmentEditor.MSG_REPLACE_IMAGE:
case AttachmentEditor.MSG_REPLACE_VIDEO:
case AttachmentEditor.MSG_REPLACE_AUDIO:
showAddAttachmentDialog(true);
break;
case AttachmentEditor.MSG_REMOVE_ATTACHMENT:
mWorkingMessage.removeAttachment(true);
break;
default:
break;
}
}
};
private void viewMmsMessageAttachment(final int requestCode) {
SlideshowModel slideshow = mWorkingMessage.getSlideshow();
if (slideshow == null) {
throw new IllegalStateException("mWorkingMessage.getSlideshow() == null");
}
if (slideshow.isSimple()) {
MessageUtils.viewSimpleSlideshow(this, slideshow);
} else {
// The user wants to view the slideshow. That requires us to persist the slideshow to
// disk as a PDU in saveAsMms. This code below does that persisting in a background
// task. If the task takes longer than a half second, a progress dialog is displayed.
// Once the PDU persisting is done, another runnable on the UI thread get executed to
// start the SlideshowActivity.
getAsyncDialog().runAsync(new Runnable() {
@Override
public void run() {
// This runnable gets run in a background thread.
mTempMmsUri = mWorkingMessage.saveAsMms(false);
}
}, new Runnable() {
@Override
public void run() {
// Once the above background thread is complete, this runnable is run
// on the UI thread.
if (mTempMmsUri == null) {
return;
}
MessageUtils.launchSlideshowActivity(ComposeMessageActivity.this, mTempMmsUri,
requestCode);
}
}, R.string.building_slideshow_title);
}
}
private final Handler mMessageListItemHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
MessageItem msgItem = (MessageItem) msg.obj;
if (msgItem != null) {
switch (msg.what) {
case MessageListItem.MSG_LIST_DETAILS:
showMessageDetails(msgItem);
break;
case MessageListItem.MSG_LIST_EDIT:
editMessageItem(msgItem);
drawBottomPanel();
break;
case MessageListItem.MSG_LIST_PLAY:
switch (msgItem.mAttachmentType) {
case WorkingMessage.IMAGE:
case WorkingMessage.VIDEO:
case WorkingMessage.AUDIO:
case WorkingMessage.SLIDESHOW:
MessageUtils.viewMmsMessageAttachment(ComposeMessageActivity.this,
msgItem.mMessageUri, msgItem.mSlideshow,
getAsyncDialog());
break;
}
break;
default:
Log.w(TAG, "Unknown message: " + msg.what);
return;
}
}
}
};
private boolean showMessageDetails(MessageItem msgItem) {
Cursor cursor = mMsgListAdapter.getCursorForItem(msgItem);
if (cursor == null) {
return false;
}
String messageDetails = MessageUtils.getMessageDetails(
ComposeMessageActivity.this, cursor, msgItem.mMessageSize);
new AlertDialog.Builder(ComposeMessageActivity.this)
.setTitle(R.string.message_details_title)
.setMessage(messageDetails)
.setCancelable(true)
.show();
return true;
}
private final OnKeyListener mSubjectKeyListener = new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() != KeyEvent.ACTION_DOWN) {
return false;
}
// When the subject editor is empty, press "DEL" to hide the input field.
if ((keyCode == KeyEvent.KEYCODE_DEL) && (mSubjectTextEditor.length() == 0)) {
showSubjectEditor(false);
mWorkingMessage.setSubject(null, true);
return true;
}
return false;
}
};
/**
* Return the messageItem associated with the type ("mms" or "sms") and message id.
* @param type Type of the message: "mms" or "sms"
* @param msgId Message id of the message. This is the _id of the sms or pdu row and is
* stored in the MessageItem
* @param createFromCursorIfNotInCache true if the item is not found in the MessageListAdapter's
* cache and the code can create a new MessageItem based on the position of the current cursor.
* If false, the function returns null if the MessageItem isn't in the cache.
* @return MessageItem or null if not found and createFromCursorIfNotInCache is false
*/
private MessageItem getMessageItem(String type, long msgId,
boolean createFromCursorIfNotInCache) {
return mMsgListAdapter.getCachedMessageItem(type, msgId,
createFromCursorIfNotInCache ? mMsgListAdapter.getCursor() : null);
}
private boolean isCursorValid() {
// Check whether the cursor is valid or not.
Cursor cursor = mMsgListAdapter.getCursor();
if (cursor.isClosed() || cursor.isBeforeFirst() || cursor.isAfterLast()) {
Log.e(TAG, "Bad cursor.", new RuntimeException());
return false;
}
return true;
}
private void resetCounter() {
mTextCounter.setText("");
mTextCounter.setVisibility(View.GONE);
}
private void updateCounter(CharSequence text, int start, int before, int count) {
WorkingMessage workingMessage = mWorkingMessage;
if (workingMessage.requiresMms()) {
// If we're not removing text (i.e. no chance of converting back to SMS
// because of this change) and we're in MMS mode, just bail out since we
// then won't have to calculate the length unnecessarily.
final boolean textRemoved = (before > count);
if (!textRemoved) {
showSmsOrMmsSendButton(workingMessage.requiresMms());
return;
}
}
int[] params = SmsMessage.calculateLength(text, false);
/* SmsMessage.calculateLength returns an int[4] with:
* int[0] being the number of SMS's required,
* int[1] the number of code units used,
* int[2] is the number of code units remaining until the next message.
* int[3] is the encoding type that should be used for the message.
*/
int msgCount = params[0];
int remainingInCurrentMessage = params[2];
if (!MmsConfig.getMultipartSmsEnabled()) {
// The provider doesn't support multi-part sms's so as soon as the user types
// an sms longer than one segment, we have to turn the message into an mms.
mWorkingMessage.setLengthRequiresMms(msgCount > 1, true);
}
// Show the counter only if:
// - We are not in MMS mode
// - We are going to send more than one message OR we are getting close
boolean showCounter = false;
if (!workingMessage.requiresMms() &&
(msgCount > 1 ||
remainingInCurrentMessage <= CHARS_REMAINING_BEFORE_COUNTER_SHOWN)) {
showCounter = true;
}
showSmsOrMmsSendButton(workingMessage.requiresMms());
if (showCounter) {
// Update the remaining characters and number of messages required.
String counterText = msgCount > 1 ? remainingInCurrentMessage + " / " + msgCount
: String.valueOf(remainingInCurrentMessage);
mTextCounter.setText(counterText);
mTextCounter.setVisibility(View.VISIBLE);
} else {
mTextCounter.setVisibility(View.GONE);
}
}
@Override
public void startActivityForResult(Intent intent, int requestCode)
{
// requestCode >= 0 means the activity in question is a sub-activity.
if (requestCode >= 0) {
mWaitingForSubActivity = true;
}
if (mIsKeyboardOpen) {
hideKeyboard(); // camera and other activities take a long time to hide the keyboard
}
super.startActivityForResult(intent, requestCode);
}
private void toastConvertInfo(boolean toMms) {
final int resId = toMms ? R.string.converting_to_picture_message
: R.string.converting_to_text_message;
Toast.makeText(this, resId, Toast.LENGTH_SHORT).show();
}
private class DeleteMessageListener implements OnClickListener {
private final MessageItem mMessageItem;
public DeleteMessageListener(MessageItem messageItem) {
mMessageItem = messageItem;
}
@Override
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
new AsyncTask<Void, Void, Void>() {
protected Void doInBackground(Void... none) {
if (mMessageItem.isMms()) {
WorkingMessage.removeThumbnailsFromCache(mMessageItem.getSlideshow());
MmsApp.getApplication().getPduLoaderManager()
.removePdu(mMessageItem.mMessageUri);
// Delete the message *after* we've removed the thumbnails because we
// need the pdu and slideshow for removeThumbnailsFromCache to work.
}
mBackgroundQueryHandler.startDelete(DELETE_MESSAGE_TOKEN,
null, mMessageItem.mMessageUri,
mMessageItem.mLocked ? null : "locked=0", null);
return null;
}
}.execute();
}
}
private class DiscardDraftListener implements OnClickListener {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
mWorkingMessage.discard();
dialog.dismiss();
finish();
}
}
private class SendIgnoreInvalidRecipientListener implements OnClickListener {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
sendMessage(true);
dialog.dismiss();
}
}
private class CancelSendingListener implements OnClickListener {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
if (isRecipientsEditorVisible()) {
mRecipientsEditor.requestFocus();
}
dialog.dismiss();
}
}
private void confirmSendMessageIfNeeded() {
if (!isRecipientsEditorVisible()) {
sendMessage(true);
return;
}
boolean isMms = mWorkingMessage.requiresMms();
if (mRecipientsEditor.hasInvalidRecipient(isMms)) {
if (mRecipientsEditor.hasValidRecipient(isMms)) {
String title = getResourcesString(R.string.has_invalid_recipient,
mRecipientsEditor.formatInvalidNumbers(isMms));
new AlertDialog.Builder(this)
.setTitle(title)
.setMessage(R.string.invalid_recipient_message)
.setPositiveButton(R.string.try_to_send,
new SendIgnoreInvalidRecipientListener())
.setNegativeButton(R.string.no, new CancelSendingListener())
.show();
} else {
new AlertDialog.Builder(this)
.setTitle(R.string.cannot_send_message)
.setMessage(R.string.cannot_send_message_reason)
.setPositiveButton(R.string.yes, new CancelSendingListener())
.show();
}
} else {
sendMessage(true);
}
}
private final TextWatcher mRecipientsWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// This is a workaround for bug 1609057. Since onUserInteraction() is
// not called when the user touches the soft keyboard, we pretend it was
// called when textfields changes. This should be removed when the bug
// is fixed.
onUserInteraction();
}
@Override
public void afterTextChanged(Editable s) {
// Bug 1474782 describes a situation in which we send to
// the wrong recipient. We have been unable to reproduce this,
// but the best theory we have so far is that the contents of
// mRecipientList somehow become stale when entering
// ComposeMessageActivity via onNewIntent(). This assertion is
// meant to catch one possible path to that, of a non-visible
// mRecipientsEditor having its TextWatcher fire and refreshing
// mRecipientList with its stale contents.
if (!isRecipientsEditorVisible()) {
IllegalStateException e = new IllegalStateException(
"afterTextChanged called with invisible mRecipientsEditor");
// Make sure the crash is uploaded to the service so we
// can see if this is happening in the field.
Log.w(TAG,
"RecipientsWatcher: afterTextChanged called with invisible mRecipientsEditor");
return;
}
mWorkingMessage.setWorkingRecipients(mRecipientsEditor.getNumbers());
mWorkingMessage.setHasEmail(mRecipientsEditor.containsEmail(), true);
checkForTooManyRecipients();
// Walk backwards in the text box, skipping spaces. If the last
// character is a comma, update the title bar.
for (int pos = s.length() - 1; pos >= 0; pos--) {
char c = s.charAt(pos);
if (c == ' ')
continue;
if (c == ',') {
ContactList contacts = mRecipientsEditor.constructContactsFromInput(false);
updateTitle(contacts);
}
break;
}
// If we have gone to zero recipients, disable send button.
updateSendButtonState();
}
};
private void checkForTooManyRecipients() {
final int recipientLimit = MmsConfig.getRecipientLimit();
if (recipientLimit != Integer.MAX_VALUE) {
final int recipientCount = recipientCount();
boolean tooMany = recipientCount > recipientLimit;
if (recipientCount != mLastRecipientCount) {
// Don't warn the user on every character they type when they're over the limit,
// only when the actual # of recipients changes.
mLastRecipientCount = recipientCount;
if (tooMany) {
String tooManyMsg = getString(R.string.too_many_recipients, recipientCount,
recipientLimit);
Toast.makeText(ComposeMessageActivity.this,
tooManyMsg, Toast.LENGTH_LONG).show();
}
}
}
}
private final OnCreateContextMenuListener mRecipientsMenuCreateListener =
new OnCreateContextMenuListener() {
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
if (menuInfo != null) {
Contact c = ((RecipientContextMenuInfo) menuInfo).recipient;
RecipientsMenuClickListener l = new RecipientsMenuClickListener(c);
menu.setHeaderTitle(c.getName());
if (c.existsInDatabase()) {
menu.add(0, MENU_VIEW_CONTACT, 0, R.string.menu_view_contact)
.setOnMenuItemClickListener(l);
} else if (canAddToContacts(c)){
menu.add(0, MENU_ADD_TO_CONTACTS, 0, R.string.menu_add_to_contacts)
.setOnMenuItemClickListener(l);
}
}
}
};
private final class RecipientsMenuClickListener implements MenuItem.OnMenuItemClickListener {
private final Contact mRecipient;
RecipientsMenuClickListener(Contact recipient) {
mRecipient = recipient;
}
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
// Context menu handlers for the recipients editor.
case MENU_VIEW_CONTACT: {
Uri contactUri = mRecipient.getUri();
Intent intent = new Intent(Intent.ACTION_VIEW, contactUri);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
startActivity(intent);
return true;
}
case MENU_ADD_TO_CONTACTS: {
mAddContactIntent = ConversationList.createAddContactIntent(
mRecipient.getNumber());
ComposeMessageActivity.this.startActivityForResult(mAddContactIntent,
REQUEST_CODE_ADD_CONTACT);
return true;
}
}
return false;
}
}
private boolean canAddToContacts(Contact contact) {
// There are some kind of automated messages, like STK messages, that we don't want
// to add to contacts. These names begin with special characters, like, "*Info".
final String name = contact.getName();
if (!TextUtils.isEmpty(contact.getNumber())) {
char c = contact.getNumber().charAt(0);
if (isSpecialChar(c)) {
return false;
}
}
if (!TextUtils.isEmpty(name)) {
char c = name.charAt(0);
if (isSpecialChar(c)) {
return false;
}
}
if (!(Mms.isEmailAddress(name) ||
AddressUtils.isPossiblePhoneNumber(name) ||
contact.isMe())) {
return false;
}
return true;
}
private boolean isSpecialChar(char c) {
return c == '*' || c == '%' || c == '$';
}
private void addPositionBasedMenuItems(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
AdapterView.AdapterContextMenuInfo info;
try {
info = (AdapterView.AdapterContextMenuInfo) menuInfo;
} catch (ClassCastException e) {
Log.e(TAG, "bad menuInfo");
return;
}
final int position = info.position;
addUriSpecificMenuItems(menu, v, position);
}
private Uri getSelectedUriFromMessageList(ListView listView, int position) {
// If the context menu was opened over a uri, get that uri.
MessageListItem msglistItem = (MessageListItem) listView.getChildAt(position);
if (msglistItem == null) {
// FIXME: Should get the correct view. No such interface in ListView currently
// to get the view by position. The ListView.getChildAt(position) cannot
// get correct view since the list doesn't create one child for each item.
// And if setSelection(position) then getSelectedView(),
// cannot get corrent view when in touch mode.
return null;
}
TextView textView;
CharSequence text = null;
int selStart = -1;
int selEnd = -1;
//check if message sender is selected
textView = (TextView) msglistItem.findViewById(R.id.text_view);
if (textView != null) {
text = textView.getText();
selStart = textView.getSelectionStart();
selEnd = textView.getSelectionEnd();
}
// Check that some text is actually selected, rather than the cursor
// just being placed within the TextView.
if (selStart != selEnd) {
int min = Math.min(selStart, selEnd);
int max = Math.max(selStart, selEnd);
URLSpan[] urls = ((Spanned) text).getSpans(min, max,
URLSpan.class);
if (urls.length == 1) {
return Uri.parse(urls[0].getURL());
}
}
//no uri was selected
return null;
}
private void addUriSpecificMenuItems(ContextMenu menu, View v, int position) {
Uri uri = getSelectedUriFromMessageList((ListView) v, position);
if (uri != null) {
Intent intent = new Intent(null, uri);
intent.addCategory(Intent.CATEGORY_SELECTED_ALTERNATIVE);
menu.addIntentOptions(0, 0, 0,
new android.content.ComponentName(this, ComposeMessageActivity.class),
null, intent, 0, null);
}
}
private final void addCallAndContactMenuItems(
ContextMenu menu, MsgListMenuClickListener l, MessageItem msgItem) {
if (TextUtils.isEmpty(msgItem.mBody)) {
return;
}
SpannableString msg = new SpannableString(msgItem.mBody);
Linkify.addLinks(msg, Linkify.ALL);
ArrayList<String> uris =
MessageUtils.extractUris(msg.getSpans(0, msg.length(), URLSpan.class));
// Remove any dupes so they don't get added to the menu multiple times
HashSet<String> collapsedUris = new HashSet<String>();
for (String uri : uris) {
collapsedUris.add(uri.toLowerCase());
}
for (String uriString : collapsedUris) {
String prefix = null;
int sep = uriString.indexOf(":");
if (sep >= 0) {
prefix = uriString.substring(0, sep);
uriString = uriString.substring(sep + 1);
}
Uri contactUri = null;
boolean knownPrefix = true;
if ("mailto".equalsIgnoreCase(prefix)) {
contactUri = getContactUriForEmail(uriString);
} else if ("tel".equalsIgnoreCase(prefix)) {
contactUri = getContactUriForPhoneNumber(uriString);
} else {
knownPrefix = false;
}
if (knownPrefix && contactUri == null) {
Intent intent = ConversationList.createAddContactIntent(uriString);
String addContactString = getString(R.string.menu_add_address_to_contacts,
uriString);
menu.add(0, MENU_ADD_ADDRESS_TO_CONTACTS, 0, addContactString)
.setOnMenuItemClickListener(l)
.setIntent(intent);
}
}
}
private Uri getContactUriForEmail(String emailAddress) {
Cursor cursor = SqliteWrapper.query(this, getContentResolver(),
Uri.withAppendedPath(Email.CONTENT_LOOKUP_URI, Uri.encode(emailAddress)),
new String[] { Email.CONTACT_ID, Contacts.DISPLAY_NAME }, null, null, null);
if (cursor != null) {
try {
while (cursor.moveToNext()) {
String name = cursor.getString(1);
if (!TextUtils.isEmpty(name)) {
return ContentUris.withAppendedId(Contacts.CONTENT_URI, cursor.getLong(0));
}
}
} finally {
cursor.close();
}
}
return null;
}
private Uri getContactUriForPhoneNumber(String phoneNumber) {
Contact contact = Contact.get(phoneNumber, false);
if (contact.existsInDatabase()) {
return contact.getUri();
}
return null;
}
private final OnCreateContextMenuListener mMsgListMenuCreateListener =
new OnCreateContextMenuListener() {
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
if (!isCursorValid()) {
return;
}
Cursor cursor = mMsgListAdapter.getCursor();
String type = cursor.getString(COLUMN_MSG_TYPE);
long msgId = cursor.getLong(COLUMN_ID);
addPositionBasedMenuItems(menu, v, menuInfo);
MessageItem msgItem = mMsgListAdapter.getCachedMessageItem(type, msgId, cursor);
if (msgItem == null) {
Log.e(TAG, "Cannot load message item for type = " + type
+ ", msgId = " + msgId);
return;
}
menu.setHeaderTitle(R.string.message_options);
MsgListMenuClickListener l = new MsgListMenuClickListener(msgItem);
// It is unclear what would make most sense for copying an MMS message
// to the clipboard, so we currently do SMS only.
if (msgItem.isSms()) {
// Message type is sms. Only allow "edit" if the message has a single recipient
if (getRecipients().size() == 1 &&
(msgItem.mBoxId == Sms.MESSAGE_TYPE_OUTBOX ||
msgItem.mBoxId == Sms.MESSAGE_TYPE_FAILED)) {
menu.add(0, MENU_EDIT_MESSAGE, 0, R.string.menu_edit)
.setOnMenuItemClickListener(l);
}
menu.add(0, MENU_COPY_MESSAGE_TEXT, 0, R.string.copy_message_text)
.setOnMenuItemClickListener(l);
}
addCallAndContactMenuItems(menu, l, msgItem);
// Forward is not available for undownloaded messages.
if (msgItem.isDownloaded() && (msgItem.isSms() || isForwardable(msgId))) {
menu.add(0, MENU_FORWARD_MESSAGE, 0, R.string.menu_forward)
.setOnMenuItemClickListener(l);
}
if (msgItem.isMms()) {
switch (msgItem.mBoxId) {
case Mms.MESSAGE_BOX_INBOX:
break;
case Mms.MESSAGE_BOX_OUTBOX:
// Since we currently break outgoing messages to multiple
// recipients into one message per recipient, only allow
// editing a message for single-recipient conversations.
if (getRecipients().size() == 1) {
menu.add(0, MENU_EDIT_MESSAGE, 0, R.string.menu_edit)
.setOnMenuItemClickListener(l);
}
break;
}
switch (msgItem.mAttachmentType) {
case WorkingMessage.TEXT:
break;
case WorkingMessage.VIDEO:
case WorkingMessage.IMAGE:
if (haveSomethingToCopyToSDCard(msgItem.mMsgId)) {
menu.add(0, MENU_COPY_TO_SDCARD, 0, R.string.copy_to_sdcard)
.setOnMenuItemClickListener(l);
}
break;
case WorkingMessage.SLIDESHOW:
default:
menu.add(0, MENU_VIEW_SLIDESHOW, 0, R.string.view_slideshow)
.setOnMenuItemClickListener(l);
if (haveSomethingToCopyToSDCard(msgItem.mMsgId)) {
menu.add(0, MENU_COPY_TO_SDCARD, 0, R.string.copy_to_sdcard)
.setOnMenuItemClickListener(l);
}
if (isDrmRingtoneWithRights(msgItem.mMsgId)) {
menu.add(0, MENU_SAVE_RINGTONE, 0,
getDrmMimeMenuStringRsrc(msgItem.mMsgId))
.setOnMenuItemClickListener(l);
}
break;
}
}
if (msgItem.mLocked) {
menu.add(0, MENU_UNLOCK_MESSAGE, 0, R.string.menu_unlock)
.setOnMenuItemClickListener(l);
} else {
menu.add(0, MENU_LOCK_MESSAGE, 0, R.string.menu_lock)
.setOnMenuItemClickListener(l);
}
menu.add(0, MENU_VIEW_MESSAGE_DETAILS, 0, R.string.view_message_details)
.setOnMenuItemClickListener(l);
if (msgItem.mDeliveryStatus != MessageItem.DeliveryStatus.NONE || msgItem.mReadReport) {
menu.add(0, MENU_DELIVERY_REPORT, 0, R.string.view_delivery_report)
.setOnMenuItemClickListener(l);
}
menu.add(0, MENU_DELETE_MESSAGE, 0, R.string.delete_message)
.setOnMenuItemClickListener(l);
}
};
private void editMessageItem(MessageItem msgItem) {
if ("sms".equals(msgItem.mType)) {
editSmsMessageItem(msgItem);
} else {
editMmsMessageItem(msgItem);
}
if (msgItem.isFailedMessage() && mMsgListAdapter.getCount() <= 1) {
// For messages with bad addresses, let the user re-edit the recipients.
initRecipientsEditor();
}
}
private void editSmsMessageItem(MessageItem msgItem) {
// When the message being edited is the only message in the conversation, the delete
// below does something subtle. The trigger "delete_obsolete_threads_pdu" sees that a
// thread contains no messages and silently deletes the thread. Meanwhile, the mConversation
// object still holds onto the old thread_id and code thinks there's a backing thread in
// the DB when it really has been deleted. Here we try and notice that situation and
// clear out the thread_id. Later on, when Conversation.ensureThreadId() is called, we'll
// create a new thread if necessary.
synchronized(mConversation) {
if (mConversation.getMessageCount() <= 1) {
mConversation.clearThreadId();
MessagingNotification.setCurrentlyDisplayedThreadId(
MessagingNotification.THREAD_NONE);
}
}
// Delete the old undelivered SMS and load its content.
Uri uri = ContentUris.withAppendedId(Sms.CONTENT_URI, msgItem.mMsgId);
SqliteWrapper.delete(ComposeMessageActivity.this,
mContentResolver, uri, null, null);
mWorkingMessage.setText(msgItem.mBody);
}
private void editMmsMessageItem(MessageItem msgItem) {
// Load the selected message in as the working message.
WorkingMessage newWorkingMessage = WorkingMessage.load(this, msgItem.mMessageUri);
if (newWorkingMessage == null) {
return;
}
// Discard the current message in progress.
mWorkingMessage.discard();
mWorkingMessage = newWorkingMessage;
mWorkingMessage.setConversation(mConversation);
invalidateOptionsMenu();
drawTopPanel(false);
// WorkingMessage.load() above only loads the slideshow. Set the
// subject here because we already know what it is and avoid doing
// another DB lookup in load() just to get it.
mWorkingMessage.setSubject(msgItem.mSubject, false);
if (mWorkingMessage.hasSubject()) {
showSubjectEditor(true);
}
}
private void copyToClipboard(String str) {
ClipboardManager clipboard = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setPrimaryClip(ClipData.newPlainText(null, str));
}
private void forwardMessage(final MessageItem msgItem) {
mTempThreadId = 0;
// The user wants to forward the message. If the message is an mms message, we need to
// persist the pdu to disk. This is done in a background task.
// If the task takes longer than a half second, a progress dialog is displayed.
// Once the PDU persisting is done, another runnable on the UI thread get executed to start
// the ForwardMessageActivity.
getAsyncDialog().runAsync(new Runnable() {
@Override
public void run() {
// This runnable gets run in a background thread.
if (msgItem.mType.equals("mms")) {
SendReq sendReq = new SendReq();
String subject = getString(R.string.forward_prefix);
if (msgItem.mSubject != null) {
subject += msgItem.mSubject;
}
sendReq.setSubject(new EncodedStringValue(subject));
sendReq.setBody(msgItem.mSlideshow.makeCopy());
mTempMmsUri = null;
try {
PduPersister persister =
PduPersister.getPduPersister(ComposeMessageActivity.this);
// Copy the parts of the message here.
mTempMmsUri = persister.persist(sendReq, Mms.Draft.CONTENT_URI);
mTempThreadId = MessagingNotification.getThreadId(
ComposeMessageActivity.this, mTempMmsUri);
} catch (MmsException e) {
Log.e(TAG, "Failed to copy message: " + msgItem.mMessageUri);
Toast.makeText(ComposeMessageActivity.this,
R.string.cannot_save_message, Toast.LENGTH_SHORT).show();
return;
}
}
}
}, new Runnable() {
@Override
public void run() {
// Once the above background thread is complete, this runnable is run
// on the UI thread.
Intent intent = createIntent(ComposeMessageActivity.this, 0);
intent.putExtra("exit_on_sent", true);
intent.putExtra("forwarded_message", true);
if (mTempThreadId > 0) {
intent.putExtra("thread_id", mTempThreadId);
}
if (msgItem.mType.equals("sms")) {
intent.putExtra("sms_body", msgItem.mBody);
} else {
intent.putExtra("msg_uri", mTempMmsUri);
String subject = getString(R.string.forward_prefix);
if (msgItem.mSubject != null) {
subject += msgItem.mSubject;
}
intent.putExtra("subject", subject);
}
// ForwardMessageActivity is simply an alias in the manifest for
// ComposeMessageActivity. We have to make an alias because ComposeMessageActivity
// launch flags specify singleTop. When we forward a message, we want to start a
// separate ComposeMessageActivity. The only way to do that is to override the
// singleTop flag, which is impossible to do in code. By creating an alias to the
// activity, without the singleTop flag, we can launch a separate
// ComposeMessageActivity to edit the forward message.
intent.setClassName(ComposeMessageActivity.this,
"com.android.mms.ui.ForwardMessageActivity");
startActivity(intent);
}
}, R.string.building_slideshow_title);
}
/**
* Context menu handlers for the message list view.
*/
private final class MsgListMenuClickListener implements MenuItem.OnMenuItemClickListener {
private MessageItem mMsgItem;
public MsgListMenuClickListener(MessageItem msgItem) {
mMsgItem = msgItem;
}
@Override
public boolean onMenuItemClick(MenuItem item) {
if (mMsgItem == null) {
return false;
}
switch (item.getItemId()) {
case MENU_EDIT_MESSAGE:
editMessageItem(mMsgItem);
drawBottomPanel();
return true;
case MENU_COPY_MESSAGE_TEXT:
copyToClipboard(mMsgItem.mBody);
return true;
case MENU_FORWARD_MESSAGE:
forwardMessage(mMsgItem);
return true;
case MENU_VIEW_SLIDESHOW:
MessageUtils.viewMmsMessageAttachment(ComposeMessageActivity.this,
ContentUris.withAppendedId(Mms.CONTENT_URI, mMsgItem.mMsgId), null,
getAsyncDialog());
return true;
case MENU_VIEW_MESSAGE_DETAILS:
return showMessageDetails(mMsgItem);
case MENU_DELETE_MESSAGE: {
DeleteMessageListener l = new DeleteMessageListener(mMsgItem);
confirmDeleteDialog(l, mMsgItem.mLocked);
return true;
}
case MENU_DELIVERY_REPORT:
showDeliveryReport(mMsgItem.mMsgId, mMsgItem.mType);
return true;
case MENU_COPY_TO_SDCARD: {
int resId = copyMedia(mMsgItem.mMsgId) ? R.string.copy_to_sdcard_success :
R.string.copy_to_sdcard_fail;
Toast.makeText(ComposeMessageActivity.this, resId, Toast.LENGTH_SHORT).show();
return true;
}
case MENU_SAVE_RINGTONE: {
int resId = getDrmMimeSavedStringRsrc(mMsgItem.mMsgId,
saveRingtone(mMsgItem.mMsgId));
Toast.makeText(ComposeMessageActivity.this, resId, Toast.LENGTH_SHORT).show();
return true;
}
case MENU_LOCK_MESSAGE: {
lockMessage(mMsgItem, true);
return true;
}
case MENU_UNLOCK_MESSAGE: {
lockMessage(mMsgItem, false);
return true;
}
default:
return false;
}
}
}
private void lockMessage(MessageItem msgItem, boolean locked) {
Uri uri;
if ("sms".equals(msgItem.mType)) {
uri = Sms.CONTENT_URI;
} else {
uri = Mms.CONTENT_URI;
}
final Uri lockUri = ContentUris.withAppendedId(uri, msgItem.mMsgId);
final ContentValues values = new ContentValues(1);
values.put("locked", locked ? 1 : 0);
new Thread(new Runnable() {
@Override
public void run() {
getContentResolver().update(lockUri,
values, null, null);
}
}, "ComposeMessageActivity.lockMessage").start();
}
/**
* Looks to see if there are any valid parts of the attachment that can be copied to a SD card.
* @param msgId
*/
private boolean haveSomethingToCopyToSDCard(long msgId) {
PduBody body = null;
try {
body = SlideshowModel.getPduBody(this,
ContentUris.withAppendedId(Mms.CONTENT_URI, msgId));
} catch (MmsException e) {
Log.e(TAG, "haveSomethingToCopyToSDCard can't load pdu body: " + msgId);
}
if (body == null) {
return false;
}
boolean result = false;
int partNum = body.getPartsNum();
for(int i = 0; i < partNum; i++) {
PduPart part = body.getPart(i);
String type = new String(part.getContentType());
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("[CMA] haveSomethingToCopyToSDCard: part[" + i + "] contentType=" + type);
}
if (ContentType.isImageType(type) || ContentType.isVideoType(type) ||
ContentType.isAudioType(type) || DrmUtils.isDrmType(type)) {
result = true;
break;
}
}
return result;
}
/**
* Copies media from an Mms to the DrmProvider
* @param msgId
*/
private boolean saveRingtone(long msgId) {
boolean result = true;
PduBody body = null;
try {
body = SlideshowModel.getPduBody(this,
ContentUris.withAppendedId(Mms.CONTENT_URI, msgId));
} catch (MmsException e) {
Log.e(TAG, "copyToDrmProvider can't load pdu body: " + msgId);
}
if (body == null) {
return false;
}
int partNum = body.getPartsNum();
for(int i = 0; i < partNum; i++) {
PduPart part = body.getPart(i);
String type = new String(part.getContentType());
if (DrmUtils.isDrmType(type)) {
// All parts (but there's probably only a single one) have to be successful
// for a valid result.
result &= copyPart(part, Long.toHexString(msgId));
}
}
return result;
}
/**
* Returns true if any part is drm'd audio with ringtone rights.
* @param msgId
* @return true if one of the parts is drm'd audio with rights to save as a ringtone.
*/
private boolean isDrmRingtoneWithRights(long msgId) {
PduBody body = null;
try {
body = SlideshowModel.getPduBody(this,
ContentUris.withAppendedId(Mms.CONTENT_URI, msgId));
} catch (MmsException e) {
Log.e(TAG, "isDrmRingtoneWithRights can't load pdu body: " + msgId);
}
if (body == null) {
return false;
}
int partNum = body.getPartsNum();
for (int i = 0; i < partNum; i++) {
PduPart part = body.getPart(i);
String type = new String(part.getContentType());
if (DrmUtils.isDrmType(type)) {
String mimeType = MmsApp.getApplication().getDrmManagerClient()
.getOriginalMimeType(part.getDataUri());
if (ContentType.isAudioType(mimeType) && DrmUtils.haveRightsForAction(part.getDataUri(),
DrmStore.Action.RINGTONE)) {
return true;
}
}
}
return false;
}
/**
* Returns true if all drm'd parts are forwardable.
* @param msgId
* @return true if all drm'd parts are forwardable.
*/
private boolean isForwardable(long msgId) {
PduBody body = null;
try {
body = SlideshowModel.getPduBody(this,
ContentUris.withAppendedId(Mms.CONTENT_URI, msgId));
} catch (MmsException e) {
Log.e(TAG, "getDrmMimeType can't load pdu body: " + msgId);
}
if (body == null) {
return false;
}
int partNum = body.getPartsNum();
for (int i = 0; i < partNum; i++) {
PduPart part = body.getPart(i);
String type = new String(part.getContentType());
if (DrmUtils.isDrmType(type) && !DrmUtils.haveRightsForAction(part.getDataUri(),
DrmStore.Action.TRANSFER)) {
return false;
}
}
return true;
}
private int getDrmMimeMenuStringRsrc(long msgId) {
if (isDrmRingtoneWithRights(msgId)) {
return R.string.save_ringtone;
}
return 0;
}
private int getDrmMimeSavedStringRsrc(long msgId, boolean success) {
if (isDrmRingtoneWithRights(msgId)) {
return success ? R.string.saved_ringtone : R.string.saved_ringtone_fail;
}
return 0;
}
/**
* Copies media from an Mms to the "download" directory on the SD card. If any of the parts
* are audio types, drm'd or not, they're copied to the "Ringtones" directory.
* @param msgId
*/
private boolean copyMedia(long msgId) {
boolean result = true;
PduBody body = null;
try {
body = SlideshowModel.getPduBody(this,
ContentUris.withAppendedId(Mms.CONTENT_URI, msgId));
} catch (MmsException e) {
Log.e(TAG, "copyMedia can't load pdu body: " + msgId);
}
if (body == null) {
return false;
}
int partNum = body.getPartsNum();
for(int i = 0; i < partNum; i++) {
PduPart part = body.getPart(i);
// all parts have to be successful for a valid result.
result &= copyPart(part, Long.toHexString(msgId));
}
return result;
}
private boolean copyPart(PduPart part, String fallback) {
Uri uri = part.getDataUri();
String type = new String(part.getContentType());
boolean isDrm = DrmUtils.isDrmType(type);
if (isDrm) {
type = MmsApp.getApplication().getDrmManagerClient()
.getOriginalMimeType(part.getDataUri());
}
if (!ContentType.isImageType(type) && !ContentType.isVideoType(type) &&
!ContentType.isAudioType(type)) {
return true; // we only save pictures, videos, and sounds. Skip the text parts,
// the app (smil) parts, and other type that we can't handle.
// Return true to pretend that we successfully saved the part so
// the whole save process will be counted a success.
}
InputStream input = null;
FileOutputStream fout = null;
try {
input = mContentResolver.openInputStream(uri);
if (input instanceof FileInputStream) {
FileInputStream fin = (FileInputStream) input;
byte[] location = part.getName();
if (location == null) {
location = part.getFilename();
}
if (location == null) {
location = part.getContentLocation();
}
String fileName;
if (location == null) {
// Use fallback name.
fileName = fallback;
} else {
// For locally captured videos, fileName can end up being something like this:
// /mnt/sdcard/Android/data/com.android.mms/cache/.temp1.3gp
fileName = new String(location);
}
File originalFile = new File(fileName);
fileName = originalFile.getName(); // Strip the full path of where the "part" is
// stored down to just the leaf filename.
// Depending on the location, there may be an
// extension already on the name or not. If we've got audio, put the attachment
// in the Ringtones directory.
String dir = Environment.getExternalStorageDirectory() + "/"
+ (ContentType.isAudioType(type) ? Environment.DIRECTORY_RINGTONES :
Environment.DIRECTORY_DOWNLOADS) + "/";
String extension;
int index;
if ((index = fileName.lastIndexOf('.')) == -1) {
extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(type);
} else {
extension = fileName.substring(index + 1, fileName.length());
fileName = fileName.substring(0, index);
}
if (isDrm) {
extension += DrmUtils.getConvertExtension(type);
}
File file = getUniqueDestination(dir + fileName, extension);
// make sure the path is valid and directories created for this file.
File parentFile = file.getParentFile();
if (!parentFile.exists() && !parentFile.mkdirs()) {
Log.e(TAG, "[MMS] copyPart: mkdirs for " + parentFile.getPath() + " failed!");
return false;
}
fout = new FileOutputStream(file);
byte[] buffer = new byte[8000];
int size = 0;
while ((size=fin.read(buffer)) != -1) {
fout.write(buffer, 0, size);
}
// Notify other applications listening to scanner events
// that a media file has been added to the sd card
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
Uri.fromFile(file)));
}
} catch (IOException e) {
// Ignore
Log.e(TAG, "IOException caught while opening or reading stream", e);
return false;
} finally {
if (null != input) {
try {
input.close();
} catch (IOException e) {
// Ignore
Log.e(TAG, "IOException caught while closing stream", e);
return false;
}
}
if (null != fout) {
try {
fout.close();
} catch (IOException e) {
// Ignore
Log.e(TAG, "IOException caught while closing stream", e);
return false;
}
}
}
return true;
}
private File getUniqueDestination(String base, String extension) {
File file = new File(base + "." + extension);
for (int i = 2; file.exists(); i++) {
file = new File(base + "_" + i + "." + extension);
}
return file;
}
private void showDeliveryReport(long messageId, String type) {
Intent intent = new Intent(this, DeliveryReportActivity.class);
intent.putExtra("message_id", messageId);
intent.putExtra("message_type", type);
startActivity(intent);
}
private final IntentFilter mHttpProgressFilter = new IntentFilter(PROGRESS_STATUS_ACTION);
private final BroadcastReceiver mHttpProgressReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (PROGRESS_STATUS_ACTION.equals(intent.getAction())) {
long token = intent.getLongExtra("token",
SendingProgressTokenManager.NO_TOKEN);
if (token != mConversation.getThreadId()) {
return;
}
int progress = intent.getIntExtra("progress", 0);
switch (progress) {
case PROGRESS_START:
setProgressBarVisibility(true);
break;
case PROGRESS_ABORT:
case PROGRESS_COMPLETE:
setProgressBarVisibility(false);
break;
default:
setProgress(100 * progress);
}
}
}
};
private static ContactList sEmptyContactList;
private ContactList getRecipients() {
// If the recipients editor is visible, the conversation has
// not really officially 'started' yet. Recipients will be set
// on the conversation once it has been saved or sent. In the
// meantime, let anyone who needs the recipient list think it
// is empty rather than giving them a stale one.
if (isRecipientsEditorVisible()) {
if (sEmptyContactList == null) {
sEmptyContactList = new ContactList();
}
return sEmptyContactList;
}
return mConversation.getRecipients();
}
private void updateTitle(ContactList list) {
String title = null;
String subTitle = null;
int cnt = list.size();
switch (cnt) {
case 0: {
String recipient = null;
if (mRecipientsEditor != null) {
recipient = mRecipientsEditor.getText().toString();
}
title = TextUtils.isEmpty(recipient) ? getString(R.string.new_message) : recipient;
break;
}
case 1: {
title = list.get(0).getName(); // get name returns the number if there's no
// name available.
String number = list.get(0).getNumber();
if (!title.equals(number)) {
subTitle = PhoneNumberUtils.formatNumber(number, number,
MmsApp.getApplication().getCurrentCountryIso());
}
break;
}
default: {
// Handle multiple recipients
title = list.formatNames(", ");
subTitle = getResources().getQuantityString(R.plurals.recipient_count, cnt, cnt);
break;
}
}
mDebugRecipients = list.serialize();
ActionBar actionBar = getActionBar();
actionBar.setTitle(title);
actionBar.setSubtitle(subTitle);
}
// Get the recipients editor ready to be displayed onscreen.
private void initRecipientsEditor() {
if (isRecipientsEditorVisible()) {
return;
}
// Must grab the recipients before the view is made visible because getRecipients()
// returns empty recipients when the editor is visible.
ContactList recipients = getRecipients();
ViewStub stub = (ViewStub)findViewById(R.id.recipients_editor_stub);
if (stub != null) {
View stubView = stub.inflate();
mRecipientsEditor = (RecipientsEditor) stubView.findViewById(R.id.recipients_editor);
mRecipientsPicker = (ImageButton) stubView.findViewById(R.id.recipients_picker);
} else {
mRecipientsEditor = (RecipientsEditor)findViewById(R.id.recipients_editor);
mRecipientsEditor.setVisibility(View.VISIBLE);
mRecipientsPicker = (ImageButton)findViewById(R.id.recipients_picker);
}
mRecipientsPicker.setOnClickListener(this);
mRecipientsEditor.setAdapter(new ChipsRecipientAdapter(this));
mRecipientsEditor.populate(recipients);
mRecipientsEditor.setOnCreateContextMenuListener(mRecipientsMenuCreateListener);
mRecipientsEditor.addTextChangedListener(mRecipientsWatcher);
// TODO : Remove the max length limitation due to the multiple phone picker is added and the
// user is able to select a large number of recipients from the Contacts. The coming
// potential issue is that it is hard for user to edit a recipient from hundred of
// recipients in the editor box. We may redesign the editor box UI for this use case.
// mRecipientsEditor.setFilters(new InputFilter[] {
// new InputFilter.LengthFilter(RECIPIENTS_MAX_LENGTH) });
mRecipientsEditor.setOnSelectChipRunnable(new Runnable() {
@Override
public void run() {
// After the user selects an item in the pop-up contacts list, move the
// focus to the text editor if there is only one recipient. This helps
// the common case of selecting one recipient and then typing a message,
// but avoids annoying a user who is trying to add five recipients and
// keeps having focus stolen away.
if (mRecipientsEditor.getRecipientCount() == 1) {
// if we're in extract mode then don't request focus
final InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputManager == null || !inputManager.isFullscreenMode()) {
mTextEditor.requestFocus();
}
}
}
});
mRecipientsEditor.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
RecipientsEditor editor = (RecipientsEditor) v;
ContactList contacts = editor.constructContactsFromInput(false);
updateTitle(contacts);
}
}
});
PhoneNumberFormatter.setPhoneNumberFormattingTextWatcher(this, mRecipientsEditor);
mTopPanel.setVisibility(View.VISIBLE);
}
//==========================================================
// Activity methods
//==========================================================
public static boolean cancelFailedToDeliverNotification(Intent intent, Context context) {
if (MessagingNotification.isFailedToDeliver(intent)) {
// Cancel any failed message notifications
MessagingNotification.cancelNotification(context,
MessagingNotification.MESSAGE_FAILED_NOTIFICATION_ID);
return true;
}
return false;
}
public static boolean cancelFailedDownloadNotification(Intent intent, Context context) {
if (MessagingNotification.isFailedToDownload(intent)) {
// Cancel any failed download notifications
MessagingNotification.cancelNotification(context,
MessagingNotification.DOWNLOAD_FAILED_NOTIFICATION_ID);
return true;
}
return false;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
resetConfiguration(getResources().getConfiguration());
setContentView(R.layout.compose_message_activity);
setProgressBarVisibility(false);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE |
WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
// Initialize members for UI elements.
initResourceRefs();
mContentResolver = getContentResolver();
mBackgroundQueryHandler = new BackgroundQueryHandler(mContentResolver);
initialize(savedInstanceState, 0);
if (TRACE) {
android.os.Debug.startMethodTracing("compose");
}
}
private void showSubjectEditor(boolean show) {
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("" + show);
}
if (mSubjectTextEditor == null) {
// Don't bother to initialize the subject editor if
// we're just going to hide it.
if (show == false) {
return;
}
mSubjectTextEditor = (EditText)findViewById(R.id.subject);
mSubjectTextEditor.setFilters(new InputFilter[] {
new LengthFilter(MmsConfig.getMaxSubjectLength())});
}
mSubjectTextEditor.setOnKeyListener(show ? mSubjectKeyListener : null);
if (show) {
mSubjectTextEditor.addTextChangedListener(mSubjectEditorWatcher);
} else {
mSubjectTextEditor.removeTextChangedListener(mSubjectEditorWatcher);
}
mSubjectTextEditor.setText(mWorkingMessage.getSubject());
mSubjectTextEditor.setVisibility(show ? View.VISIBLE : View.GONE);
hideOrShowTopPanel();
}
private void hideOrShowTopPanel() {
boolean anySubViewsVisible = (isSubjectEditorVisible() || isRecipientsEditorVisible());
mTopPanel.setVisibility(anySubViewsVisible ? View.VISIBLE : View.GONE);
}
public void initialize(Bundle savedInstanceState, long originalThreadId) {
// Create a new empty working message.
mWorkingMessage = WorkingMessage.createEmpty(this);
// Read parameters or previously saved state of this activity. This will load a new
// mConversation
initActivityState(savedInstanceState);
if (LogTag.SEVERE_WARNING && originalThreadId != 0 &&
originalThreadId == mConversation.getThreadId()) {
LogTag.warnPossibleRecipientMismatch("ComposeMessageActivity.initialize: " +
" threadId didn't change from: " + originalThreadId, this);
}
log("savedInstanceState = " + savedInstanceState +
" intent = " + getIntent() +
" mConversation = " + mConversation);
if (cancelFailedToDeliverNotification(getIntent(), this)) {
// Show a pop-up dialog to inform user the message was
// failed to deliver.
undeliveredMessageDialog(getMessageDate(null));
}
cancelFailedDownloadNotification(getIntent(), this);
// Set up the message history ListAdapter
initMessageList();
// Load the draft for this thread, if we aren't already handling
// existing data, such as a shared picture or forwarded message.
boolean isForwardedMessage = false;
// We don't attempt to handle the Intent.ACTION_SEND when saveInstanceState is non-null.
// saveInstanceState is non-null when this activity is killed. In that case, we already
// handled the attachment or the send, so we don't try and parse the intent again.
boolean intentHandled = savedInstanceState == null &&
(handleSendIntent() || handleForwardedMessage());
if (!intentHandled) {
loadDraft();
}
// Let the working message know what conversation it belongs to
mWorkingMessage.setConversation(mConversation);
// Show the recipients editor if we don't have a valid thread. Hide it otherwise.
if (mConversation.getThreadId() <= 0) {
// Hide the recipients editor so the call to initRecipientsEditor won't get
// short-circuited.
hideRecipientEditor();
initRecipientsEditor();
// Bring up the softkeyboard so the user can immediately enter recipients. This
// call won't do anything on devices with a hard keyboard.
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE |
WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
} else {
hideRecipientEditor();
}
invalidateOptionsMenu(); // do after show/hide of recipients editor because the options
// menu depends on the recipients, which depending upon the
// visibility of the recipients editor, returns a different
// value (see getRecipients()).
updateSendButtonState();
drawTopPanel(false);
if (intentHandled) {
// We're not loading a draft, so we can draw the bottom panel immediately.
drawBottomPanel();
}
onKeyboardStateChanged(mIsKeyboardOpen);
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("update title, mConversation=" + mConversation.toString());
}
updateTitle(mConversation.getRecipients());
if (isForwardedMessage && isRecipientsEditorVisible()) {
// The user is forwarding the message to someone. Put the focus on the
// recipient editor rather than in the message editor.
mRecipientsEditor.requestFocus();
}
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
Conversation conversation = null;
mSentMessage = false;
// If we have been passed a thread_id, use that to find our
// conversation.
// Note that originalThreadId might be zero but if this is a draft and we save the
// draft, ensureThreadId gets called async from WorkingMessage.asyncUpdateDraftSmsMessage
// the thread will get a threadId behind the UI thread's back.
long originalThreadId = mConversation.getThreadId();
long threadId = intent.getLongExtra("thread_id", 0);
Uri intentUri = intent.getData();
boolean sameThread = false;
if (threadId > 0) {
conversation = Conversation.get(this, threadId, false);
} else {
if (mConversation.getThreadId() == 0) {
// We've got a draft. Make sure the working recipients are synched
// to the conversation so when we compare conversations later in this function,
// the compare will work.
mWorkingMessage.syncWorkingRecipients();
}
// Get the "real" conversation based on the intentUri. The intentUri might specify
// the conversation by a phone number or by a thread id. We'll typically get a threadId
// based uri when the user pulls down a notification while in ComposeMessageActivity and
// we end up here in onNewIntent. mConversation can have a threadId of zero when we're
// working on a draft. When a new message comes in for that same recipient, a
// conversation will get created behind CMA's back when the message is inserted into
// the database and the corresponding entry made in the threads table. The code should
// use the real conversation as soon as it can rather than finding out the threadId
// when sending with "ensureThreadId".
conversation = Conversation.get(this, intentUri, false);
}
if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("onNewIntent: data=" + intentUri + ", thread_id extra is " + threadId +
", new conversation=" + conversation + ", mConversation=" + mConversation);
}
// this is probably paranoid to compare both thread_ids and recipient lists,
// but we want to make double sure because this is a last minute fix for Froyo
// and the previous code checked thread ids only.
// (we cannot just compare thread ids because there is a case where mConversation
// has a stale/obsolete thread id (=1) that could collide against the new thread_id(=1),
// even though the recipient lists are different)
sameThread = ((conversation.getThreadId() == mConversation.getThreadId() ||
mConversation.getThreadId() == 0) &&
conversation.equals(mConversation));
if (sameThread) {
log("onNewIntent: same conversation");
if (mConversation.getThreadId() == 0) {
mConversation = conversation;
mWorkingMessage.setConversation(mConversation);
updateThreadIdIfRunning();
invalidateOptionsMenu();
}
} else {
if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("onNewIntent: different conversation");
}
saveDraft(false); // if we've got a draft, save it first
initialize(null, originalThreadId);
}
loadMessageContent();
}
private void sanityCheckConversation() {
if (mWorkingMessage.getConversation() != mConversation) {
LogTag.warnPossibleRecipientMismatch(
"ComposeMessageActivity: mWorkingMessage.mConversation=" +
mWorkingMessage.getConversation() + ", mConversation=" +
mConversation + ", MISMATCH!", this);
}
}
@Override
protected void onRestart() {
super.onRestart();
if (mWorkingMessage.isDiscarded()) {
// If the message isn't worth saving, don't resurrect it. Doing so can lead to
// a situation where a new incoming message gets the old thread id of the discarded
// draft. This activity can end up displaying the recipients of the old message with
// the contents of the new message. Recognize that dangerous situation and bail out
// to the ConversationList where the user can enter this in a clean manner.
if (mWorkingMessage.isWorthSaving()) {
if (LogTag.VERBOSE) {
log("onRestart: mWorkingMessage.unDiscard()");
}
mWorkingMessage.unDiscard(); // it was discarded in onStop().
sanityCheckConversation();
} else if (isRecipientsEditorVisible()) {
if (LogTag.VERBOSE) {
log("onRestart: goToConversationList");
}
goToConversationList();
} else {
if (LogTag.VERBOSE) {
log("onRestart: loadDraft");
}
loadDraft();
mWorkingMessage.setConversation(mConversation);
mAttachmentEditor.update(mWorkingMessage);
invalidateOptionsMenu();
}
}
}
@Override
protected void onStart() {
super.onStart();
initFocus();
// Register a BroadcastReceiver to listen on HTTP I/O process.
registerReceiver(mHttpProgressReceiver, mHttpProgressFilter);
loadMessageContent();
// Update the fasttrack info in case any of the recipients' contact info changed
// while we were paused. This can happen, for example, if a user changes or adds
// an avatar associated with a contact.
mWorkingMessage.syncWorkingRecipients();
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("update title, mConversation=" + mConversation.toString());
}
updateTitle(mConversation.getRecipients());
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
}
public void loadMessageContent() {
// Don't let any markAsRead DB updates occur before we've loaded the messages for
// the thread. Unblocking occurs when we're done querying for the conversation
// items.
mConversation.blockMarkAsRead(true);
mConversation.markAsRead(); // dismiss any notifications for this convo
startMsgListQuery();
updateSendFailedNotification();
drawBottomPanel();
}
private void updateSendFailedNotification() {
final long threadId = mConversation.getThreadId();
if (threadId <= 0)
return;
// updateSendFailedNotificationForThread makes a database call, so do the work off
// of the ui thread.
new Thread(new Runnable() {
@Override
public void run() {
MessagingNotification.updateSendFailedNotificationForThread(
ComposeMessageActivity.this, threadId);
}
}, "ComposeMessageActivity.updateSendFailedNotification").start();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("recipients", getRecipients().serialize());
mWorkingMessage.writeStateToBundle(outState);
if (mExitOnSent) {
outState.putBoolean("exit_on_sent", mExitOnSent);
}
}
@Override
protected void onResume() {
super.onResume();
// OLD: get notified of presence updates to update the titlebar.
// NEW: we are using ContactHeaderWidget which displays presence, but updating presence
// there is out of our control.
//Contact.startPresenceObserver();
addRecipientsListeners();
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("update title, mConversation=" + mConversation.toString());
}
// There seems to be a bug in the framework such that setting the title
// here gets overwritten to the original title. Do this delayed as a
// workaround.
mMessageListItemHandler.postDelayed(new Runnable() {
@Override
public void run() {
ContactList recipients = isRecipientsEditorVisible() ?
mRecipientsEditor.constructContactsFromInput(false) : getRecipients();
updateTitle(recipients);
}
}, 100);
mIsRunning = true;
updateThreadIdIfRunning();
}
@Override
protected void onPause() {
super.onPause();
// OLD: stop getting notified of presence updates to update the titlebar.
// NEW: we are using ContactHeaderWidget which displays presence, but updating presence
// there is out of our control.
//Contact.stopPresenceObserver();
removeRecipientsListeners();
// remove any callback to display a progress spinner
if (mAsyncDialog != null) {
mAsyncDialog.clearPendingProgressDialog();
}
MessagingNotification.setCurrentlyDisplayedThreadId(MessagingNotification.THREAD_NONE);
mSavedScrollPosition = mMsgListView.getFirstVisiblePosition();
if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
Log.v(TAG, "onPause: mSavedScrollPosition=" + mSavedScrollPosition);
}
mIsRunning = false;
}
@Override
protected void onStop() {
super.onStop();
// No need to do the querying when finished this activity
mBackgroundQueryHandler.cancelOperation(MESSAGE_LIST_QUERY_TOKEN);
// Allow any blocked calls to update the thread's read status.
mConversation.blockMarkAsRead(false);
if (mMsgListAdapter != null) {
// Close the cursor in the ListAdapter if the activity stopped.
Cursor cursor = mMsgListAdapter.getCursor();
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
mMsgListAdapter.changeCursor(null);
mMsgListAdapter.cancelBackgroundLoading();
}
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("save draft");
}
saveDraft(true);
// Cleanup the BroadcastReceiver.
unregisterReceiver(mHttpProgressReceiver);
}
@Override
protected void onDestroy() {
if (TRACE) {
android.os.Debug.stopMethodTracing();
}
super.onDestroy();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (LOCAL_LOGV) {
Log.v(TAG, "onConfigurationChanged: " + newConfig);
}
if (resetConfiguration(newConfig)) {
// Have to re-layout the attachment editor because we have different layouts
// depending on whether we're portrait or landscape.
drawTopPanel(isSubjectEditorVisible());
}
onKeyboardStateChanged(mIsKeyboardOpen);
}
// returns true if landscape/portrait configuration has changed
private boolean resetConfiguration(Configuration config) {
mIsKeyboardOpen = config.keyboardHidden == KEYBOARDHIDDEN_NO;
boolean isLandscape = config.orientation == Configuration.ORIENTATION_LANDSCAPE;
if (mIsLandscape != isLandscape) {
mIsLandscape = isLandscape;
return true;
}
return false;
}
private void onKeyboardStateChanged(boolean isKeyboardOpen) {
// If the keyboard is hidden, don't show focus highlights for
// things that cannot receive input.
if (isKeyboardOpen) {
if (mRecipientsEditor != null) {
mRecipientsEditor.setFocusableInTouchMode(true);
}
if (mSubjectTextEditor != null) {
mSubjectTextEditor.setFocusableInTouchMode(true);
}
mTextEditor.setFocusableInTouchMode(true);
mTextEditor.setHint(R.string.type_to_compose_text_enter_to_send);
} else {
if (mRecipientsEditor != null) {
mRecipientsEditor.setFocusable(false);
}
if (mSubjectTextEditor != null) {
mSubjectTextEditor.setFocusable(false);
}
mTextEditor.setFocusable(false);
mTextEditor.setHint(R.string.open_keyboard_to_compose_message);
}
}
@Override
public void onUserInteraction() {
checkPendingNotification();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_DEL:
if ((mMsgListAdapter != null) && mMsgListView.isFocused()) {
Cursor cursor;
try {
cursor = (Cursor) mMsgListView.getSelectedItem();
} catch (ClassCastException e) {
Log.e(TAG, "Unexpected ClassCastException.", e);
return super.onKeyDown(keyCode, event);
}
if (cursor != null) {
String type = cursor.getString(COLUMN_MSG_TYPE);
long msgId = cursor.getLong(COLUMN_ID);
MessageItem msgItem = mMsgListAdapter.getCachedMessageItem(type, msgId,
cursor);
if (msgItem != null) {
DeleteMessageListener l = new DeleteMessageListener(msgItem);
confirmDeleteDialog(l, msgItem.mLocked);
}
return true;
}
}
break;
case KeyEvent.KEYCODE_DPAD_CENTER:
case KeyEvent.KEYCODE_ENTER:
if (isPreparedForSending()) {
confirmSendMessageIfNeeded();
return true;
}
break;
case KeyEvent.KEYCODE_BACK:
exitComposeMessageActivity(new Runnable() {
@Override
public void run() {
finish();
}
});
return true;
}
return super.onKeyDown(keyCode, event);
}
private void exitComposeMessageActivity(final Runnable exit) {
// If the message is empty, just quit -- finishing the
// activity will cause an empty draft to be deleted.
if (!mWorkingMessage.isWorthSaving()) {
exit.run();
return;
}
if (isRecipientsEditorVisible() &&
!mRecipientsEditor.hasValidRecipient(mWorkingMessage.requiresMms())) {
MessageUtils.showDiscardDraftConfirmDialog(this, new DiscardDraftListener());
return;
}
mToastForDraftSave = true;
exit.run();
}
private void goToConversationList() {
finish();
startActivity(new Intent(this, ConversationList.class));
}
private void hideRecipientEditor() {
if (mRecipientsEditor != null) {
mRecipientsEditor.removeTextChangedListener(mRecipientsWatcher);
mRecipientsEditor.setVisibility(View.GONE);
hideOrShowTopPanel();
}
}
private boolean isRecipientsEditorVisible() {
return (null != mRecipientsEditor)
&& (View.VISIBLE == mRecipientsEditor.getVisibility());
}
private boolean isSubjectEditorVisible() {
return (null != mSubjectTextEditor)
&& (View.VISIBLE == mSubjectTextEditor.getVisibility());
}
@Override
public void onAttachmentChanged() {
// Have to make sure we're on the UI thread. This function can be called off of the UI
// thread when we're adding multi-attachments
runOnUiThread(new Runnable() {
@Override
public void run() {
drawBottomPanel();
updateSendButtonState();
drawTopPanel(isSubjectEditorVisible());
}
});
}
@Override
public void onProtocolChanged(final boolean mms) {
// Have to make sure we're on the UI thread. This function can be called off of the UI
// thread when we're adding multi-attachments
runOnUiThread(new Runnable() {
@Override
public void run() {
toastConvertInfo(mms);
showSmsOrMmsSendButton(mms);
if (mms) {
// In the case we went from a long sms with a counter to an mms because
// the user added an attachment or a subject, hide the counter --
// it doesn't apply to mms.
mTextCounter.setVisibility(View.GONE);
}
}
});
}
// Show or hide the Sms or Mms button as appropriate. Return the view so that the caller
// can adjust the enableness and focusability.
private View showSmsOrMmsSendButton(boolean isMms) {
View showButton;
View hideButton;
if (isMms) {
showButton = mSendButtonMms;
hideButton = mSendButtonSms;
} else {
showButton = mSendButtonSms;
hideButton = mSendButtonMms;
}
showButton.setVisibility(View.VISIBLE);
hideButton.setVisibility(View.GONE);
return showButton;
}
Runnable mResetMessageRunnable = new Runnable() {
@Override
public void run() {
resetMessage();
}
};
@Override
public void onPreMessageSent() {
runOnUiThread(mResetMessageRunnable);
}
@Override
public void onMessageSent() {
// This callback can come in on any thread; put it on the main thread to avoid
// concurrency problems
runOnUiThread(new Runnable() {
@Override
public void run() {
// If we already have messages in the list adapter, it
// will be auto-requerying; don't thrash another query in.
// TODO: relying on auto-requerying seems unreliable when priming an MMS into the
// outbox. Need to investigate.
// if (mMsgListAdapter.getCount() == 0) {
if (LogTag.VERBOSE) {
log("onMessageSent");
}
startMsgListQuery();
// }
// The thread ID could have changed if this is a new message that we just inserted
// into the database (and looked up or created a thread for it)
updateThreadIdIfRunning();
}
});
}
@Override
public void onMaxPendingMessagesReached() {
saveDraft(false);
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(ComposeMessageActivity.this, R.string.too_many_unsent_mms,
Toast.LENGTH_LONG).show();
}
});
}
@Override
public void onAttachmentError(final int error) {
runOnUiThread(new Runnable() {
@Override
public void run() {
handleAddAttachmentError(error, R.string.type_picture);
onMessageSent(); // now requery the list of messages
}
});
}
// We don't want to show the "call" option unless there is only one
// recipient and it's a phone number.
private boolean isRecipientCallable() {
ContactList recipients = getRecipients();
return (recipients.size() == 1 && !recipients.containsEmail());
}
private void dialRecipient() {
if (isRecipientCallable()) {
String number = getRecipients().get(0).getNumber();
Intent dialIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + number));
startActivity(dialIntent);
}
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu) ;
menu.clear();
if (isRecipientCallable()) {
MenuItem item = menu.add(0, MENU_CALL_RECIPIENT, 0, R.string.menu_call)
.setIcon(R.drawable.ic_menu_call)
.setTitle(R.string.menu_call);
if (!isRecipientsEditorVisible()) {
// If we're not composing a new message, show the call icon in the actionbar
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
}
}
if (MmsConfig.getMmsEnabled()) {
if (!isSubjectEditorVisible()) {
menu.add(0, MENU_ADD_SUBJECT, 0, R.string.add_subject).setIcon(
R.drawable.ic_menu_edit);
}
menu.add(0, MENU_ADD_ATTACHMENT, 0, R.string.add_attachment)
.setIcon(R.drawable.ic_menu_attachment)
.setTitle(R.string.add_attachment)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); // add to actionbar
}
if (isPreparedForSending()) {
menu.add(0, MENU_SEND, 0, R.string.send).setIcon(android.R.drawable.ic_menu_send);
}
if (!mWorkingMessage.hasSlideshow()) {
menu.add(0, MENU_INSERT_SMILEY, 0, R.string.menu_insert_smiley).setIcon(
R.drawable.ic_menu_emoticons);
}
if (mMsgListAdapter.getCount() > 0) {
// Removed search as part of b/1205708
//menu.add(0, MENU_SEARCH, 0, R.string.menu_search).setIcon(
// R.drawable.ic_menu_search);
Cursor cursor = mMsgListAdapter.getCursor();
if ((null != cursor) && (cursor.getCount() > 0)) {
menu.add(0, MENU_DELETE_THREAD, 0, R.string.delete_thread).setIcon(
android.R.drawable.ic_menu_delete);
}
} else {
menu.add(0, MENU_DISCARD, 0, R.string.discard).setIcon(android.R.drawable.ic_menu_delete);
}
buildAddAddressToContactMenuItem(menu);
menu.add(0, MENU_PREFERENCES, 0, R.string.menu_preferences).setIcon(
android.R.drawable.ic_menu_preferences);
if (LogTag.DEBUG_DUMP) {
menu.add(0, MENU_DEBUG_DUMP, 0, R.string.menu_debug_dump);
}
return true;
}
private void buildAddAddressToContactMenuItem(Menu menu) {
// Look for the first recipient we don't have a contact for and create a menu item to
// add the number to contacts.
for (Contact c : getRecipients()) {
if (!c.existsInDatabase() && canAddToContacts(c)) {
Intent intent = ConversationList.createAddContactIntent(c.getNumber());
menu.add(0, MENU_ADD_ADDRESS_TO_CONTACTS, 0, R.string.menu_add_to_contacts)
.setIcon(android.R.drawable.ic_menu_add)
.setIntent(intent);
break;
}
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_ADD_SUBJECT:
showSubjectEditor(true);
mWorkingMessage.setSubject("", true);
updateSendButtonState();
mSubjectTextEditor.requestFocus();
break;
case MENU_ADD_ATTACHMENT:
// Launch the add-attachment list dialog
showAddAttachmentDialog(false);
break;
case MENU_DISCARD:
mWorkingMessage.discard();
finish();
break;
case MENU_SEND:
if (isPreparedForSending()) {
confirmSendMessageIfNeeded();
}
break;
case MENU_SEARCH:
onSearchRequested();
break;
case MENU_DELETE_THREAD:
confirmDeleteThread(mConversation.getThreadId());
break;
case android.R.id.home:
case MENU_CONVERSATION_LIST:
exitComposeMessageActivity(new Runnable() {
@Override
public void run() {
goToConversationList();
}
});
break;
case MENU_CALL_RECIPIENT:
dialRecipient();
break;
case MENU_INSERT_SMILEY:
showSmileyDialog();
break;
case MENU_VIEW_CONTACT: {
// View the contact for the first (and only) recipient.
ContactList list = getRecipients();
if (list.size() == 1 && list.get(0).existsInDatabase()) {
Uri contactUri = list.get(0).getUri();
Intent intent = new Intent(Intent.ACTION_VIEW, contactUri);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
startActivity(intent);
}
break;
}
case MENU_ADD_ADDRESS_TO_CONTACTS:
mAddContactIntent = item.getIntent();
startActivityForResult(mAddContactIntent, REQUEST_CODE_ADD_CONTACT);
break;
case MENU_PREFERENCES: {
Intent intent = new Intent(this, MessagingPreferenceActivity.class);
startActivityIfNeeded(intent, -1);
break;
}
case MENU_DEBUG_DUMP:
mWorkingMessage.dump();
Conversation.dump();
LogTag.dumpInternalTables(this);
break;
}
return true;
}
private void confirmDeleteThread(long threadId) {
Conversation.startQueryHaveLockedMessages(mBackgroundQueryHandler,
threadId, ConversationList.HAVE_LOCKED_MESSAGES_TOKEN);
}
// static class SystemProperties { // TODO, temp class to get unbundling working
// static int getInt(String s, int value) {
// return value; // just return the default value or now
// }
// }
private void addAttachment(int type, boolean replace) {
// Calculate the size of the current slide if we're doing a replace so the
// slide size can optionally be used in computing how much room is left for an attachment.
int currentSlideSize = 0;
SlideshowModel slideShow = mWorkingMessage.getSlideshow();
if (replace && slideShow != null) {
WorkingMessage.removeThumbnailsFromCache(slideShow);
SlideModel slide = slideShow.get(0);
currentSlideSize = slide.getSlideSize();
}
switch (type) {
case AttachmentTypeSelectorAdapter.ADD_IMAGE:
MessageUtils.selectImage(this, REQUEST_CODE_ATTACH_IMAGE);
break;
case AttachmentTypeSelectorAdapter.TAKE_PICTURE: {
MessageUtils.capturePicture(this, REQUEST_CODE_TAKE_PICTURE);
break;
}
case AttachmentTypeSelectorAdapter.ADD_VIDEO:
MessageUtils.selectVideo(this, REQUEST_CODE_ATTACH_VIDEO);
break;
case AttachmentTypeSelectorAdapter.RECORD_VIDEO: {
long sizeLimit = computeAttachmentSizeLimit(slideShow, currentSlideSize);
if (sizeLimit > 0) {
MessageUtils.recordVideo(this, REQUEST_CODE_TAKE_VIDEO, sizeLimit);
} else {
Toast.makeText(this,
getString(R.string.message_too_big_for_video),
Toast.LENGTH_SHORT).show();
}
}
break;
case AttachmentTypeSelectorAdapter.ADD_SOUND:
MessageUtils.selectAudio(this, REQUEST_CODE_ATTACH_SOUND);
break;
case AttachmentTypeSelectorAdapter.RECORD_SOUND:
long sizeLimit = computeAttachmentSizeLimit(slideShow, currentSlideSize);
MessageUtils.recordSound(this, REQUEST_CODE_RECORD_SOUND, sizeLimit);
break;
case AttachmentTypeSelectorAdapter.ADD_SLIDESHOW:
editSlideshow();
break;
default:
break;
}
}
public static long computeAttachmentSizeLimit(SlideshowModel slideShow, int currentSlideSize) {
// Computer attachment size limit. Subtract 1K for some text.
long sizeLimit = MmsConfig.getMaxMessageSize() - SlideshowModel.SLIDESHOW_SLOP;
if (slideShow != null) {
sizeLimit -= slideShow.getCurrentMessageSize();
// We're about to ask the camera to capture some video (or the sound recorder
// to record some audio) which will eventually replace the content on the current
// slide. Since the current slide already has some content (which was subtracted
// out just above) and that content is going to get replaced, we can add the size of the
// current slide into the available space used to capture a video (or audio).
sizeLimit += currentSlideSize;
}
return sizeLimit;
}
private void showAddAttachmentDialog(final boolean replace) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setIcon(R.drawable.ic_dialog_attach);
builder.setTitle(R.string.add_attachment);
if (mAttachmentTypeSelectorAdapter == null) {
mAttachmentTypeSelectorAdapter = new AttachmentTypeSelectorAdapter(
this, AttachmentTypeSelectorAdapter.MODE_WITH_SLIDESHOW);
}
builder.setAdapter(mAttachmentTypeSelectorAdapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
addAttachment(mAttachmentTypeSelectorAdapter.buttonToCommand(which), replace);
dialog.dismiss();
}
});
builder.show();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (LogTag.VERBOSE) {
log("requestCode=" + requestCode + ", resultCode=" + resultCode + ", data=" + data);
}
mWaitingForSubActivity = false; // We're back!
if (mWorkingMessage.isFakeMmsForDraft()) {
// We no longer have to fake the fact we're an Mms. At this point we are or we aren't,
// based on attachments and other Mms attrs.
mWorkingMessage.removeFakeMmsForDraft();
}
if (requestCode == REQUEST_CODE_PICK) {
mWorkingMessage.asyncDeleteDraftSmsMessage(mConversation);
}
if (requestCode == REQUEST_CODE_ADD_CONTACT) {
// The user might have added a new contact. When we tell contacts to add a contact
// and tap "Done", we're not returned to Messaging. If we back out to return to
// messaging after adding a contact, the resultCode is RESULT_CANCELED. Therefore,
// assume a contact was added and get the contact and force our cached contact to
// get reloaded with the new info (such as contact name). After the
// contact is reloaded, the function onUpdate() in this file will get called
// and it will update the title bar, etc.
if (mAddContactIntent != null) {
String address =
mAddContactIntent.getStringExtra(ContactsContract.Intents.Insert.EMAIL);
if (address == null) {
address =
mAddContactIntent.getStringExtra(ContactsContract.Intents.Insert.PHONE);
}
if (address != null) {
Contact contact = Contact.get(address, false);
if (contact != null) {
contact.reload();
}
}
}
}
if (resultCode != RESULT_OK){
if (LogTag.VERBOSE) log("bail due to resultCode=" + resultCode);
return;
}
switch (requestCode) {
case REQUEST_CODE_CREATE_SLIDESHOW:
if (data != null) {
WorkingMessage newMessage = WorkingMessage.load(this, data.getData());
if (newMessage != null) {
mWorkingMessage = newMessage;
mWorkingMessage.setConversation(mConversation);
updateThreadIdIfRunning();
drawTopPanel(false);
updateSendButtonState();
invalidateOptionsMenu();
}
}
break;
case REQUEST_CODE_TAKE_PICTURE: {
// create a file based uri and pass to addImage(). We want to read the JPEG
// data directly from file (using UriImage) instead of decoding it into a Bitmap,
// which takes up too much memory and could easily lead to OOM.
File file = new File(TempFileProvider.getScrapPath(this));
Uri uri = Uri.fromFile(file);
// Remove the old captured picture's thumbnail from the cache
MmsApp.getApplication().getThumbnailManager().removeThumbnail(uri);
addImageAsync(uri, false);
break;
}
case REQUEST_CODE_ATTACH_IMAGE: {
if (data != null) {
addImageAsync(data.getData(), false);
}
break;
}
case REQUEST_CODE_TAKE_VIDEO:
Uri videoUri = TempFileProvider.renameScrapFile(".3gp", null, this);
// Remove the old captured video's thumbnail from the cache
MmsApp.getApplication().getThumbnailManager().removeThumbnail(videoUri);
addVideoAsync(videoUri, false); // can handle null videoUri
break;
case REQUEST_CODE_ATTACH_VIDEO:
if (data != null) {
addVideoAsync(data.getData(), false);
}
break;
case REQUEST_CODE_ATTACH_SOUND: {
Uri uri = (Uri) data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
if (Settings.System.DEFAULT_RINGTONE_URI.equals(uri)) {
break;
}
addAudio(uri);
break;
}
case REQUEST_CODE_RECORD_SOUND:
if (data != null) {
addAudio(data.getData());
}
break;
case REQUEST_CODE_ECM_EXIT_DIALOG:
boolean outOfEmergencyMode = data.getBooleanExtra(EXIT_ECM_RESULT, false);
if (outOfEmergencyMode) {
sendMessage(false);
}
break;
case REQUEST_CODE_PICK:
if (data != null) {
processPickResult(data);
}
break;
default:
if (LogTag.VERBOSE) log("bail due to unknown requestCode=" + requestCode);
break;
}
}
private void processPickResult(final Intent data) {
// The EXTRA_PHONE_URIS stores the phone's urls that were selected by user in the
// multiple phone picker.
final Parcelable[] uris =
data.getParcelableArrayExtra(Intents.EXTRA_PHONE_URIS);
final int recipientCount = uris != null ? uris.length : 0;
final int recipientLimit = MmsConfig.getRecipientLimit();
if (recipientLimit != Integer.MAX_VALUE && recipientCount > recipientLimit) {
new AlertDialog.Builder(this)
.setMessage(getString(R.string.too_many_recipients, recipientCount, recipientLimit))
.setPositiveButton(android.R.string.ok, null)
.create().show();
return;
}
final Handler handler = new Handler();
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle(getText(R.string.pick_too_many_recipients));
progressDialog.setMessage(getText(R.string.adding_recipients));
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);
final Runnable showProgress = new Runnable() {
@Override
public void run() {
progressDialog.show();
}
};
// Only show the progress dialog if we can not finish off parsing the return data in 1s,
// otherwise the dialog could flicker.
handler.postDelayed(showProgress, 1000);
new Thread(new Runnable() {
@Override
public void run() {
final ContactList list;
try {
list = ContactList.blockingGetByUris(uris);
} finally {
handler.removeCallbacks(showProgress);
progressDialog.dismiss();
}
// TODO: there is already code to update the contact header widget and recipients
// editor if the contacts change. we can re-use that code.
final Runnable populateWorker = new Runnable() {
@Override
public void run() {
mRecipientsEditor.populate(list);
updateTitle(list);
}
};
handler.post(populateWorker);
}
}, "ComoseMessageActivity.processPickResult").start();
}
private final ResizeImageResultCallback mResizeImageCallback = new ResizeImageResultCallback() {
// TODO: make this produce a Uri, that's what we want anyway
@Override
public void onResizeResult(PduPart part, boolean append) {
if (part == null) {
handleAddAttachmentError(WorkingMessage.UNKNOWN_ERROR, R.string.type_picture);
return;
}
Context context = ComposeMessageActivity.this;
PduPersister persister = PduPersister.getPduPersister(context);
int result;
Uri messageUri = mWorkingMessage.saveAsMms(true);
if (messageUri == null) {
result = WorkingMessage.UNKNOWN_ERROR;
} else {
try {
Uri dataUri = persister.persistPart(part, ContentUris.parseId(messageUri));
result = mWorkingMessage.setAttachment(WorkingMessage.IMAGE, dataUri, append);
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("ResizeImageResultCallback: dataUri=" + dataUri);
}
} catch (MmsException e) {
result = WorkingMessage.UNKNOWN_ERROR;
}
}
handleAddAttachmentError(result, R.string.type_picture);
}
};
private void handleAddAttachmentError(final int error, final int mediaTypeStringId) {
if (error == WorkingMessage.OK) {
return;
}
Log.d(TAG, "handleAddAttachmentError: " + error);
runOnUiThread(new Runnable() {
@Override
public void run() {
Resources res = getResources();
String mediaType = res.getString(mediaTypeStringId);
String title, message;
switch(error) {
case WorkingMessage.UNKNOWN_ERROR:
message = res.getString(R.string.failed_to_add_media, mediaType);
Toast.makeText(ComposeMessageActivity.this, message, Toast.LENGTH_SHORT).show();
return;
case WorkingMessage.UNSUPPORTED_TYPE:
title = res.getString(R.string.unsupported_media_format, mediaType);
message = res.getString(R.string.select_different_media, mediaType);
break;
case WorkingMessage.MESSAGE_SIZE_EXCEEDED:
title = res.getString(R.string.exceed_message_size_limitation, mediaType);
message = res.getString(R.string.failed_to_add_media, mediaType);
break;
case WorkingMessage.IMAGE_TOO_LARGE:
title = res.getString(R.string.failed_to_resize_image);
message = res.getString(R.string.resize_image_error_information);
break;
default:
throw new IllegalArgumentException("unknown error " + error);
}
MessageUtils.showErrorDialog(ComposeMessageActivity.this, title, message);
}
});
}
private void addImageAsync(final Uri uri, final boolean append) {
getAsyncDialog().runAsync(new Runnable() {
@Override
public void run() {
addImage(uri, append);
}
}, null, R.string.adding_attachments_title);
}
private void addImage(Uri uri, boolean append) {
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("append=" + append + ", uri=" + uri);
}
int result = mWorkingMessage.setAttachment(WorkingMessage.IMAGE, uri, append);
if (result == WorkingMessage.IMAGE_TOO_LARGE ||
result == WorkingMessage.MESSAGE_SIZE_EXCEEDED) {
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("resize image " + uri);
}
MessageUtils.resizeImageAsync(ComposeMessageActivity.this,
uri, mAttachmentEditorHandler, mResizeImageCallback, append);
return;
}
handleAddAttachmentError(result, R.string.type_picture);
}
private void addVideoAsync(final Uri uri, final boolean append) {
getAsyncDialog().runAsync(new Runnable() {
@Override
public void run() {
addVideo(uri, append);
}
}, null, R.string.adding_attachments_title);
}
private void addVideo(Uri uri, boolean append) {
if (uri != null) {
int result = mWorkingMessage.setAttachment(WorkingMessage.VIDEO, uri, append);
handleAddAttachmentError(result, R.string.type_video);
}
}
private void addAudio(Uri uri) {
int result = mWorkingMessage.setAttachment(WorkingMessage.AUDIO, uri, false);
handleAddAttachmentError(result, R.string.type_audio);
}
AsyncDialog getAsyncDialog() {
if (mAsyncDialog == null) {
mAsyncDialog = new AsyncDialog(this);
}
return mAsyncDialog;
}
private boolean handleForwardedMessage() {
Intent intent = getIntent();
// If this is a forwarded message, it will have an Intent extra
// indicating so. If not, bail out.
if (intent.getBooleanExtra("forwarded_message", false) == false) {
return false;
}
Uri uri = intent.getParcelableExtra("msg_uri");
if (Log.isLoggable(LogTag.APP, Log.DEBUG)) {
log("" + uri);
}
if (uri != null) {
mWorkingMessage = WorkingMessage.load(this, uri);
mWorkingMessage.setSubject(intent.getStringExtra("subject"), false);
} else {
mWorkingMessage.setText(intent.getStringExtra("sms_body"));
}
// let's clear the message thread for forwarded messages
mMsgListAdapter.changeCursor(null);
return true;
}
// Handle send actions, where we're told to send a picture(s) or text.
private boolean handleSendIntent() {
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras == null) {
return false;
}
final String mimeType = intent.getType();
String action = intent.getAction();
if (Intent.ACTION_SEND.equals(action)) {
if (extras.containsKey(Intent.EXTRA_STREAM)) {
final Uri uri = (Uri)extras.getParcelable(Intent.EXTRA_STREAM);
getAsyncDialog().runAsync(new Runnable() {
@Override
public void run() {
addAttachment(mimeType, uri, false);
}
}, null, R.string.adding_attachments_title);
return true;
} else if (extras.containsKey(Intent.EXTRA_TEXT)) {
mWorkingMessage.setText(extras.getString(Intent.EXTRA_TEXT));
return true;
}
} else if (Intent.ACTION_SEND_MULTIPLE.equals(action) &&
extras.containsKey(Intent.EXTRA_STREAM)) {
SlideshowModel slideShow = mWorkingMessage.getSlideshow();
final ArrayList<Parcelable> uris = extras.getParcelableArrayList(Intent.EXTRA_STREAM);
int currentSlideCount = slideShow != null ? slideShow.size() : 0;
int importCount = uris.size();
if (importCount + currentSlideCount > SlideshowEditor.MAX_SLIDE_NUM) {
importCount = Math.min(SlideshowEditor.MAX_SLIDE_NUM - currentSlideCount,
importCount);
Toast.makeText(ComposeMessageActivity.this,
getString(R.string.too_many_attachments,
SlideshowEditor.MAX_SLIDE_NUM, importCount),
Toast.LENGTH_LONG).show();
}
// Attach all the pictures/videos asynchronously off of the UI thread.
// Show a progress dialog if adding all the slides hasn't finished
// within half a second.
final int numberToImport = importCount;
getAsyncDialog().runAsync(new Runnable() {
@Override
public void run() {
for (int i = 0; i < numberToImport; i++) {
Parcelable uri = uris.get(i);
addAttachment(mimeType, (Uri) uri, true);
}
}
}, null, R.string.adding_attachments_title);
return true;
}
return false;
}
// mVideoUri will look like this: content://media/external/video/media
private static final String mVideoUri = Video.Media.getContentUri("external").toString();
// mImageUri will look like this: content://media/external/images/media
private static final String mImageUri = Images.Media.getContentUri("external").toString();
private void addAttachment(String type, Uri uri, boolean append) {
if (uri != null) {
// When we're handling Intent.ACTION_SEND_MULTIPLE, the passed in items can be
// videos, and/or images, and/or some other unknown types we don't handle. When
// a single attachment is "shared" the type will specify an image or video. When
// there are multiple types, the type passed in is "*/*". In that case, we've got
// to look at the uri to figure out if it is an image or video.
boolean wildcard = "*/*".equals(type);
if (type.startsWith("image/") || (wildcard && uri.toString().startsWith(mImageUri))) {
addImage(uri, append);
} else if (type.startsWith("video/") ||
(wildcard && uri.toString().startsWith(mVideoUri))) {
addVideo(uri, append);
}
}
}
private String getResourcesString(int id, String mediaName) {
Resources r = getResources();
return r.getString(id, mediaName);
}
private void drawBottomPanel() {
// Reset the counter for text editor.
resetCounter();
if (mWorkingMessage.hasSlideshow()) {
mBottomPanel.setVisibility(View.GONE);
mAttachmentEditor.requestFocus();
return;
}
mBottomPanel.setVisibility(View.VISIBLE);
CharSequence text = mWorkingMessage.getText();
// TextView.setTextKeepState() doesn't like null input.
if (text != null) {
mTextEditor.setTextKeepState(text);
} else {
mTextEditor.setText("");
}
}
private void drawTopPanel(boolean showSubjectEditor) {
boolean showingAttachment = mAttachmentEditor.update(mWorkingMessage);
mAttachmentEditorScrollView.setVisibility(showingAttachment ? View.VISIBLE : View.GONE);
showSubjectEditor(showSubjectEditor || mWorkingMessage.hasSubject());
}
//==========================================================
// Interface methods
//==========================================================
@Override
public void onClick(View v) {
if ((v == mSendButtonSms || v == mSendButtonMms) && isPreparedForSending()) {
confirmSendMessageIfNeeded();
} else if ((v == mRecipientsPicker)) {
launchMultiplePhonePicker();
}
}
private void launchMultiplePhonePicker() {
Intent intent = new Intent(Intents.ACTION_GET_MULTIPLE_PHONES);
intent.addCategory("android.intent.category.DEFAULT");
intent.setType(Phone.CONTENT_TYPE);
// We have to wait for the constructing complete.
ContactList contacts = mRecipientsEditor.constructContactsFromInput(true);
int urisCount = 0;
Uri[] uris = new Uri[contacts.size()];
urisCount = 0;
for (Contact contact : contacts) {
if (Contact.CONTACT_METHOD_TYPE_PHONE == contact.getContactMethodType()) {
uris[urisCount++] = contact.getPhoneUri();
}
}
if (urisCount > 0) {
intent.putExtra(Intents.EXTRA_PHONE_URIS, uris);
}
startActivityForResult(intent, REQUEST_CODE_PICK);
}
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (event != null) {
// if shift key is down, then we want to insert the '\n' char in the TextView;
// otherwise, the default action is to send the message.
if (!event.isShiftPressed()) {
if (isPreparedForSending()) {
confirmSendMessageIfNeeded();
}
return true;
}
return false;
}
if (isPreparedForSending()) {
confirmSendMessageIfNeeded();
}
return true;
}
private final TextWatcher mTextEditorWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// This is a workaround for bug 1609057. Since onUserInteraction() is
// not called when the user touches the soft keyboard, we pretend it was
// called when textfields changes. This should be removed when the bug
// is fixed.
onUserInteraction();
mWorkingMessage.setText(s);
updateSendButtonState();
updateCounter(s, start, before, count);
ensureCorrectButtonHeight();
}
@Override
public void afterTextChanged(Editable s) {
}
};
/**
* Ensures that if the text edit box extends past two lines then the
* button will be shifted up to allow enough space for the character
* counter string to be placed beneath it.
*/
private void ensureCorrectButtonHeight() {
int currentTextLines = mTextEditor.getLineCount();
if (currentTextLines <= 2) {
mTextCounter.setVisibility(View.GONE);
}
else if (currentTextLines > 2 && mTextCounter.getVisibility() == View.GONE) {
// Making the counter invisible ensures that it is used to correctly
// calculate the position of the send button even if we choose not to
// display the text.
mTextCounter.setVisibility(View.INVISIBLE);
}
}
private final TextWatcher mSubjectEditorWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
mWorkingMessage.setSubject(s, true);
updateSendButtonState();
}
@Override
public void afterTextChanged(Editable s) { }
};
//==========================================================
// Private methods
//==========================================================
/**
* Initialize all UI elements from resources.
*/
private void initResourceRefs() {
mMsgListView = (MessageListView) findViewById(R.id.history);
mMsgListView.setDivider(null); // no divider so we look like IM conversation.
// called to enable us to show some padding between the message list and the
// input field but when the message list is scrolled that padding area is filled
// in with message content
mMsgListView.setClipToPadding(false);
mMsgListView.setOnSizeChangedListener(new OnSizeChangedListener() {
public void onSizeChanged(int width, int height, int oldWidth, int oldHeight) {
// The message list view changed size, most likely because the keyboard
// appeared or disappeared or the user typed/deleted chars in the message
// box causing it to change its height when expanding/collapsing to hold more
// lines of text.
smoothScrollToEnd(false, height - oldHeight);
}
});
mBottomPanel = findViewById(R.id.bottom_panel);
mTextEditor = (EditText) findViewById(R.id.embedded_text_editor);
mTextEditor.setOnEditorActionListener(this);
mTextEditor.addTextChangedListener(mTextEditorWatcher);
mTextEditor.setFilters(new InputFilter[] {
new LengthFilter(MmsConfig.getMaxTextLimit())});
mTextCounter = (TextView) findViewById(R.id.text_counter);
mSendButtonMms = (TextView) findViewById(R.id.send_button_mms);
mSendButtonSms = (ImageButton) findViewById(R.id.send_button_sms);
mSendButtonMms.setOnClickListener(this);
mSendButtonSms.setOnClickListener(this);
mTopPanel = findViewById(R.id.recipients_subject_linear);
mTopPanel.setFocusable(false);
mAttachmentEditor = (AttachmentEditor) findViewById(R.id.attachment_editor);
mAttachmentEditor.setHandler(mAttachmentEditorHandler);
mAttachmentEditorScrollView = findViewById(R.id.attachment_editor_scroll_view);
}
private void confirmDeleteDialog(OnClickListener listener, boolean locked) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setMessage(locked ? R.string.confirm_delete_locked_message :
R.string.confirm_delete_message);
builder.setPositiveButton(R.string.delete, listener);
builder.setNegativeButton(R.string.no, null);
builder.show();
}
void undeliveredMessageDialog(long date) {
String body;
if (date >= 0) {
body = getString(R.string.undelivered_msg_dialog_body,
MessageUtils.formatTimeStampString(this, date));
} else {
// FIXME: we can not get sms retry time.
body = getString(R.string.undelivered_sms_dialog_body);
}
Toast.makeText(this, body, Toast.LENGTH_LONG).show();
}
private void startMsgListQuery() {
startMsgListQuery(MESSAGE_LIST_QUERY_TOKEN);
}
private void startMsgListQuery(int token) {
Uri conversationUri = mConversation.getUri();
if (conversationUri == null) {
log("##### startMsgListQuery: conversationUri is null, bail!");
return;
}
long threadId = mConversation.getThreadId();
if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("startMsgListQuery for " + conversationUri + ", threadId=" + threadId +
" token: " + token + " mConversation: " + mConversation);
}
// Cancel any pending queries
mBackgroundQueryHandler.cancelOperation(token);
try {
// Kick off the new query
mBackgroundQueryHandler.startQuery(
token,
threadId /* cookie */,
conversationUri,
PROJECTION,
null, null, null);
} catch (SQLiteException e) {
SqliteWrapper.checkSQLiteException(this, e);
}
}
private void initMessageList() {
if (mMsgListAdapter != null) {
return;
}
String highlightString = getIntent().getStringExtra("highlight");
Pattern highlight = highlightString == null
? null
: Pattern.compile("\\b" + Pattern.quote(highlightString), Pattern.CASE_INSENSITIVE);
// Initialize the list adapter with a null cursor.
mMsgListAdapter = new MessageListAdapter(this, null, mMsgListView, true, highlight);
mMsgListAdapter.setOnDataSetChangedListener(mDataSetChangedListener);
mMsgListAdapter.setMsgListItemHandler(mMessageListItemHandler);
mMsgListView.setAdapter(mMsgListAdapter);
mMsgListView.setItemsCanFocus(false);
mMsgListView.setVisibility(View.VISIBLE);
mMsgListView.setOnCreateContextMenuListener(mMsgListMenuCreateListener);
mMsgListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (view != null) {
((MessageListItem) view).onMessageListItemClick();
}
}
});
}
private void loadDraft() {
if (mWorkingMessage.isWorthSaving()) {
Log.w(TAG, "called with non-empty working message");
return;
}
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("call WorkingMessage.loadDraft");
}
mWorkingMessage = WorkingMessage.loadDraft(this, mConversation,
new Runnable() {
@Override
public void run() {
drawTopPanel(false);
drawBottomPanel();
}
});
}
private void saveDraft(boolean isStopping) {
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
LogTag.debug("saveDraft");
}
// TODO: Do something better here. Maybe make discard() legal
// to call twice and make isEmpty() return true if discarded
// so it is caught in the clause above this one?
if (mWorkingMessage.isDiscarded()) {
return;
}
if (!mWaitingForSubActivity &&
!mWorkingMessage.isWorthSaving() &&
(!isRecipientsEditorVisible() || recipientCount() == 0)) {
if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("not worth saving, discard WorkingMessage and bail");
}
mWorkingMessage.discard();
return;
}
mWorkingMessage.saveDraft(isStopping);
if (mToastForDraftSave) {
Toast.makeText(this, R.string.message_saved_as_draft,
Toast.LENGTH_SHORT).show();
}
}
private boolean isPreparedForSending() {
int recipientCount = recipientCount();
return recipientCount > 0 && recipientCount <= MmsConfig.getRecipientLimit() &&
(mWorkingMessage.hasAttachment() ||
mWorkingMessage.hasText() ||
mWorkingMessage.hasSubject());
}
private int recipientCount() {
int recipientCount;
// To avoid creating a bunch of invalid Contacts when the recipients
// editor is in flux, we keep the recipients list empty. So if the
// recipients editor is showing, see if there is anything in it rather
// than consulting the empty recipient list.
if (isRecipientsEditorVisible()) {
recipientCount = mRecipientsEditor.getRecipientCount();
} else {
recipientCount = getRecipients().size();
}
return recipientCount;
}
private void sendMessage(boolean bCheckEcmMode) {
if (bCheckEcmMode) {
// TODO: expose this in telephony layer for SDK build
String inEcm = SystemProperties.get(TelephonyProperties.PROPERTY_INECM_MODE);
if (Boolean.parseBoolean(inEcm)) {
try {
startActivityForResult(
new Intent(TelephonyIntents.ACTION_SHOW_NOTICE_ECM_BLOCK_OTHERS, null),
REQUEST_CODE_ECM_EXIT_DIALOG);
return;
} catch (ActivityNotFoundException e) {
// continue to send message
Log.e(TAG, "Cannot find EmergencyCallbackModeExitDialog", e);
}
}
}
if (!mSendingMessage) {
if (LogTag.SEVERE_WARNING) {
String sendingRecipients = mConversation.getRecipients().serialize();
if (!sendingRecipients.equals(mDebugRecipients)) {
String workingRecipients = mWorkingMessage.getWorkingRecipients();
if (!mDebugRecipients.equals(workingRecipients)) {
LogTag.warnPossibleRecipientMismatch("ComposeMessageActivity.sendMessage" +
" recipients in window: \"" +
mDebugRecipients + "\" differ from recipients from conv: \"" +
sendingRecipients + "\" and working recipients: " +
workingRecipients, this);
}
}
sanityCheckConversation();
}
// send can change the recipients. Make sure we remove the listeners first and then add
// them back once the recipient list has settled.
removeRecipientsListeners();
mWorkingMessage.send(mDebugRecipients);
mSentMessage = true;
mSendingMessage = true;
addRecipientsListeners();
mScrollOnSend = true; // in the next onQueryComplete, scroll the list to the end.
}
// But bail out if we are supposed to exit after the message is sent.
if (mExitOnSent) {
finish();
}
}
private void resetMessage() {
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("");
}
// Make the attachment editor hide its view.
mAttachmentEditor.hideView();
mAttachmentEditorScrollView.setVisibility(View.GONE);
// Hide the subject editor.
showSubjectEditor(false);
// Focus to the text editor.
mTextEditor.requestFocus();
// We have to remove the text change listener while the text editor gets cleared and
// we subsequently turn the message back into SMS. When the listener is listening while
// doing the clearing, it's fighting to update its counts and itself try and turn
// the message one way or the other.
mTextEditor.removeTextChangedListener(mTextEditorWatcher);
// Clear the text box.
TextKeyListener.clear(mTextEditor.getText());
mWorkingMessage.clearConversation(mConversation, false);
mWorkingMessage = WorkingMessage.createEmpty(this);
mWorkingMessage.setConversation(mConversation);
hideRecipientEditor();
drawBottomPanel();
// "Or not", in this case.
updateSendButtonState();
// Our changes are done. Let the listener respond to text changes once again.
mTextEditor.addTextChangedListener(mTextEditorWatcher);
// Close the soft on-screen keyboard if we're in landscape mode so the user can see the
// conversation.
if (mIsLandscape) {
hideKeyboard();
}
mLastRecipientCount = 0;
mSendingMessage = false;
invalidateOptionsMenu();
}
private void hideKeyboard() {
InputMethodManager inputMethodManager =
(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(mTextEditor.getWindowToken(), 0);
}
private void updateSendButtonState() {
boolean enable = false;
if (isPreparedForSending()) {
// When the type of attachment is slideshow, we should
// also hide the 'Send' button since the slideshow view
// already has a 'Send' button embedded.
if (!mWorkingMessage.hasSlideshow()) {
enable = true;
} else {
mAttachmentEditor.setCanSend(true);
}
} else if (null != mAttachmentEditor){
mAttachmentEditor.setCanSend(false);
}
boolean requiresMms = mWorkingMessage.requiresMms();
View sendButton = showSmsOrMmsSendButton(requiresMms);
sendButton.setEnabled(enable);
sendButton.setFocusable(enable);
}
private long getMessageDate(Uri uri) {
if (uri != null) {
Cursor cursor = SqliteWrapper.query(this, mContentResolver,
uri, new String[] { Mms.DATE }, null, null, null);
if (cursor != null) {
try {
if ((cursor.getCount() == 1) && cursor.moveToFirst()) {
return cursor.getLong(0) * 1000L;
}
} finally {
cursor.close();
}
}
}
return NO_DATE_FOR_DIALOG;
}
private void initActivityState(Bundle bundle) {
Intent intent = getIntent();
if (bundle != null) {
setIntent(getIntent().setAction(Intent.ACTION_VIEW));
String recipients = bundle.getString("recipients");
if (LogTag.VERBOSE) log("get mConversation by recipients " + recipients);
mConversation = Conversation.get(this,
ContactList.getByNumbers(recipients,
false /* don't block */, true /* replace number */), false);
addRecipientsListeners();
mExitOnSent = bundle.getBoolean("exit_on_sent", false);
mWorkingMessage.readStateFromBundle(bundle);
return;
}
// If we have been passed a thread_id, use that to find our conversation.
long threadId = intent.getLongExtra("thread_id", 0);
if (threadId > 0) {
if (LogTag.VERBOSE) log("get mConversation by threadId " + threadId);
mConversation = Conversation.get(this, threadId, false);
} else {
Uri intentData = intent.getData();
if (intentData != null) {
// try to get a conversation based on the data URI passed to our intent.
if (LogTag.VERBOSE) log("get mConversation by intentData " + intentData);
mConversation = Conversation.get(this, intentData, false);
mWorkingMessage.setText(getBody(intentData));
} else {
// special intent extra parameter to specify the address
String address = intent.getStringExtra("address");
if (!TextUtils.isEmpty(address)) {
if (LogTag.VERBOSE) log("get mConversation by address " + address);
mConversation = Conversation.get(this, ContactList.getByNumbers(address,
false /* don't block */, true /* replace number */), false);
} else {
if (LogTag.VERBOSE) log("create new conversation");
mConversation = Conversation.createNew(this);
}
}
}
addRecipientsListeners();
updateThreadIdIfRunning();
mExitOnSent = intent.getBooleanExtra("exit_on_sent", false);
if (intent.hasExtra("sms_body")) {
mWorkingMessage.setText(intent.getStringExtra("sms_body"));
}
mWorkingMessage.setSubject(intent.getStringExtra("subject"), false);
}
private void initFocus() {
if (!mIsKeyboardOpen) {
return;
}
// If the recipients editor is visible, there is nothing in it,
// and the text editor is not already focused, focus the
// recipients editor.
if (isRecipientsEditorVisible()
&& TextUtils.isEmpty(mRecipientsEditor.getText())
&& !mTextEditor.isFocused()) {
mRecipientsEditor.requestFocus();
return;
}
// If we decided not to focus the recipients editor, focus the text editor.
mTextEditor.requestFocus();
}
private final MessageListAdapter.OnDataSetChangedListener
mDataSetChangedListener = new MessageListAdapter.OnDataSetChangedListener() {
@Override
public void onDataSetChanged(MessageListAdapter adapter) {
mPossiblePendingNotification = true;
checkPendingNotification();
}
@Override
public void onContentChanged(MessageListAdapter adapter) {
startMsgListQuery();
}
};
private void checkPendingNotification() {
if (mPossiblePendingNotification && hasWindowFocus()) {
mConversation.markAsRead();
mPossiblePendingNotification = false;
}
}
/**
* smoothScrollToEnd will scroll the message list to the bottom if the list is already near
* the bottom. Typically this is called to smooth scroll a newly received message into view.
* It's also called when sending to scroll the list to the bottom, regardless of where it is,
* so the user can see the just sent message. This function is also called when the message
* list view changes size because the keyboard state changed or the compose message field grew.
*
* @param force always scroll to the bottom regardless of current list position
* @param listSizeChange the amount the message list view size has vertically changed
*/
private void smoothScrollToEnd(boolean force, int listSizeChange) {
int last = mMsgListView.getLastVisiblePosition();
if (last <= 0) {
if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
Log.v(TAG, "smoothScrollToEnd: last=" + last + ", mMsgListView not ready");
}
return;
}
View lastChild = mMsgListView.getChildAt(last - mMsgListView.getFirstVisiblePosition());
int bottom = 0;
if (lastChild != null) {
bottom = lastChild.getBottom();
}
int newPosition = mMsgListAdapter.getCount() - 1;
if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
Log.v(TAG, "smoothScrollToEnd newPosition: " + newPosition +
" mLastSmoothScrollPosition: " + mLastSmoothScrollPosition +
" first: " + mMsgListView.getFirstVisiblePosition() +
" last: " + last +
" bottom: " + bottom +
" bottom + listSizeChange: " + (bottom + listSizeChange) +
" mMsgListView.getHeight() - mMsgListView.getPaddingBottom(): " +
(mMsgListView.getHeight() - mMsgListView.getPaddingBottom()) +
" listSizeChange: " + listSizeChange);
}
// Only scroll if the list if we're responding to a newly sent message (force == true) or
// the list is already scrolled to the end. This code also has to handle the case where
// the listview has changed size (from the keyboard coming up or down or the message entry
// field growing/shrinking) and it uses that grow/shrink factor in listSizeChange to
// compute whether the list was at the end before the resize took place.
// For example, when the keyboard comes up, listSizeChange will be negative, something
// like -524. The lastChild listitem's bottom value will be the old value before the
// keyboard became visible but the size of the list will have changed. The test below
// add listSizeChange to bottom to figure out if the old position was already scrolled
// to the bottom.
if (force || ((listSizeChange != 0 || newPosition != mLastSmoothScrollPosition) &&
bottom + listSizeChange <=
mMsgListView.getHeight() - mMsgListView.getPaddingBottom())) {
if (Math.abs(listSizeChange) > SMOOTH_SCROLL_THRESHOLD) {
// When the keyboard comes up, the window manager initiates a cross fade
// animation that conflicts with smooth scroll. Handle that case by jumping the
// list directly to the end.
if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
Log.v(TAG, "keyboard state changed. setSelection=" + newPosition);
}
mMsgListView.setSelection(newPosition);
} else if (newPosition - last > MAX_ITEMS_TO_INVOKE_SCROLL_SHORTCUT) {
if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
Log.v(TAG, "too many to scroll, setSelection=" + newPosition);
}
mMsgListView.setSelection(newPosition);
} else {
if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
Log.v(TAG, "smooth scroll to " + newPosition);
}
mMsgListView.smoothScrollToPosition(newPosition);
mLastSmoothScrollPosition = newPosition;
}
}
}
private final class BackgroundQueryHandler extends ConversationQueryHandler {
public BackgroundQueryHandler(ContentResolver contentResolver) {
super(contentResolver);
}
@Override
protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
switch(token) {
case MESSAGE_LIST_QUERY_TOKEN:
mConversation.blockMarkAsRead(false);
// check consistency between the query result and 'mConversation'
long tid = (Long) cookie;
if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("##### onQueryComplete: msg history result for threadId " + tid);
}
if (tid != mConversation.getThreadId()) {
log("onQueryComplete: msg history query result is for threadId " +
tid + ", but mConversation has threadId " +
mConversation.getThreadId() + " starting a new query");
if (cursor != null) {
cursor.close();
}
startMsgListQuery();
return;
}
// check consistency b/t mConversation & mWorkingMessage.mConversation
ComposeMessageActivity.this.sanityCheckConversation();
int newSelectionPos = -1;
long targetMsgId = getIntent().getLongExtra("select_id", -1);
if (targetMsgId != -1) {
cursor.moveToPosition(-1);
while (cursor.moveToNext()) {
long msgId = cursor.getLong(COLUMN_ID);
if (msgId == targetMsgId) {
newSelectionPos = cursor.getPosition();
break;
}
}
} else if (mSavedScrollPosition != -1) {
// remember the saved scroll position before the activity is paused.
// reset it after the message list query is done
newSelectionPos = mSavedScrollPosition;
mSavedScrollPosition = -1;
}
mMsgListAdapter.changeCursor(cursor);
if (newSelectionPos != -1) {
mMsgListView.setSelection(newSelectionPos);
} else {
// mScrollOnSend is set when we send a message. We always want to scroll
// the message list to the end when we send a message, but have to wait
// until the DB has changed.
smoothScrollToEnd(mScrollOnSend, 0);
mScrollOnSend = false;
}
// Adjust the conversation's message count to match reality. The
// conversation's message count is eventually used in
// WorkingMessage.clearConversation to determine whether to delete
// the conversation or not.
mConversation.setMessageCount(mMsgListAdapter.getCount());
// Once we have completed the query for the message history, if
// there is nothing in the cursor and we are not composing a new
// message, we must be editing a draft in a new conversation (unless
// mSentMessage is true).
// Show the recipients editor to give the user a chance to add
// more people before the conversation begins.
if (cursor.getCount() == 0 && !isRecipientsEditorVisible() && !mSentMessage) {
initRecipientsEditor();
}
// FIXME: freshing layout changes the focused view to an unexpected
// one, set it back to TextEditor forcely.
mTextEditor.requestFocus();
invalidateOptionsMenu(); // some menu items depend on the adapter's count
return;
case ConversationList.HAVE_LOCKED_MESSAGES_TOKEN:
@SuppressWarnings("unchecked")
ArrayList<Long> threadIds = (ArrayList<Long>)cookie;
ConversationList.confirmDeleteThreadDialog(
new ConversationList.DeleteThreadListener(threadIds,
mBackgroundQueryHandler, ComposeMessageActivity.this),
threadIds,
cursor != null && cursor.getCount() > 0,
ComposeMessageActivity.this);
if (cursor != null) {
cursor.close();
}
break;
case MESSAGE_LIST_QUERY_AFTER_DELETE_TOKEN:
// check consistency between the query result and 'mConversation'
tid = (Long) cookie;
if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("##### onQueryComplete (after delete): msg history result for threadId "
+ tid);
}
if (cursor == null) {
return;
}
if (tid > 0 && cursor.getCount() == 0) {
// We just deleted the last message and the thread will get deleted
// by a trigger in the database. Clear the threadId so next time we
// need the threadId a new thread will get created.
log("##### MESSAGE_LIST_QUERY_AFTER_DELETE_TOKEN clearing thread id: "
+ tid);
Conversation conv = Conversation.get(ComposeMessageActivity.this, tid,
false);
if (conv != null) {
conv.clearThreadId();
conv.setDraftState(false);
}
}
cursor.close();
}
}
@Override
protected void onDeleteComplete(int token, Object cookie, int result) {
super.onDeleteComplete(token, cookie, result);
switch(token) {
case ConversationList.DELETE_CONVERSATION_TOKEN:
mConversation.setMessageCount(0);
// fall through
case DELETE_MESSAGE_TOKEN:
// Update the notification for new messages since they
// may be deleted.
MessagingNotification.nonBlockingUpdateNewMessageIndicator(
ComposeMessageActivity.this, MessagingNotification.THREAD_NONE, false);
// Update the notification for failed messages since they
// may be deleted.
updateSendFailedNotification();
break;
}
// If we're deleting the whole conversation, throw away
// our current working message and bail.
if (token == ConversationList.DELETE_CONVERSATION_TOKEN) {
ContactList recipients = mConversation.getRecipients();
mWorkingMessage.discard();
// Remove any recipients referenced by this single thread from the
// contacts cache. It's possible for two or more threads to reference
// the same contact. That's ok if we remove it. We'll recreate that contact
// when we init all Conversations below.
if (recipients != null) {
for (Contact contact : recipients) {
contact.removeFromCache();
}
}
// Make sure the conversation cache reflects the threads in the DB.
Conversation.init(ComposeMessageActivity.this);
finish();
} else if (token == DELETE_MESSAGE_TOKEN) {
// Check to see if we just deleted the last message
startMsgListQuery(MESSAGE_LIST_QUERY_AFTER_DELETE_TOKEN);
}
}
}
private void showSmileyDialog() {
if (mSmileyDialog == null) {
int[] icons = SmileyParser.DEFAULT_SMILEY_RES_IDS;
String[] names = getResources().getStringArray(
SmileyParser.DEFAULT_SMILEY_NAMES);
final String[] texts = getResources().getStringArray(
SmileyParser.DEFAULT_SMILEY_TEXTS);
final int N = names.length;
List<Map<String, ?>> entries = new ArrayList<Map<String, ?>>();
for (int i = 0; i < N; i++) {
// We might have different ASCII for the same icon, skip it if
// the icon is already added.
boolean added = false;
for (int j = 0; j < i; j++) {
if (icons[i] == icons[j]) {
added = true;
break;
}
}
if (!added) {
HashMap<String, Object> entry = new HashMap<String, Object>();
entry. put("icon", icons[i]);
entry. put("name", names[i]);
entry.put("text", texts[i]);
entries.add(entry);
}
}
final SimpleAdapter a = new SimpleAdapter(
this,
entries,
R.layout.smiley_menu_item,
new String[] {"icon", "name", "text"},
new int[] {R.id.smiley_icon, R.id.smiley_name, R.id.smiley_text});
SimpleAdapter.ViewBinder viewBinder = new SimpleAdapter.ViewBinder() {
@Override
public boolean setViewValue(View view, Object data, String textRepresentation) {
if (view instanceof ImageView) {
Drawable img = getResources().getDrawable((Integer)data);
((ImageView)view).setImageDrawable(img);
return true;
}
return false;
}
};
a.setViewBinder(viewBinder);
AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setTitle(getString(R.string.menu_insert_smiley));
b.setCancelable(true);
b.setAdapter(a, new DialogInterface.OnClickListener() {
@Override
@SuppressWarnings("unchecked")
public final void onClick(DialogInterface dialog, int which) {
HashMap<String, Object> item = (HashMap<String, Object>) a.getItem(which);
String smiley = (String)item.get("text");
if (mSubjectTextEditor != null && mSubjectTextEditor.hasFocus()) {
mSubjectTextEditor.append(smiley);
} else {
mTextEditor.append(smiley);
}
dialog.dismiss();
}
});
mSmileyDialog = b.create();
}
mSmileyDialog.show();
}
@Override
public void onUpdate(final Contact updated) {
// Using an existing handler for the post, rather than conjuring up a new one.
mMessageListItemHandler.post(new Runnable() {
@Override
public void run() {
ContactList recipients = isRecipientsEditorVisible() ?
mRecipientsEditor.constructContactsFromInput(false) : getRecipients();
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("[CMA] onUpdate contact updated: " + updated);
log("[CMA] onUpdate recipients: " + recipients);
}
updateTitle(recipients);
// The contact information for one (or more) of the recipients has changed.
// Rebuild the message list so each MessageItem will get the last contact info.
ComposeMessageActivity.this.mMsgListAdapter.notifyDataSetChanged();
// Don't do this anymore. When we're showing chips, we don't want to switch from
// chips to text.
// if (mRecipientsEditor != null) {
// mRecipientsEditor.populate(recipients);
// }
}
});
}
private void addRecipientsListeners() {
Contact.addListener(this);
}
private void removeRecipientsListeners() {
Contact.removeListener(this);
}
public static Intent createIntent(Context context, long threadId) {
Intent intent = new Intent(context, ComposeMessageActivity.class);
if (threadId > 0) {
intent.setData(Conversation.getUri(threadId));
}
return intent;
}
private String getBody(Uri uri) {
if (uri == null) {
return null;
}
String urlStr = uri.getSchemeSpecificPart();
if (!urlStr.contains("?")) {
return null;
}
urlStr = urlStr.substring(urlStr.indexOf('?') + 1);
String[] params = urlStr.split("&");
for (String p : params) {
if (p.startsWith("body=")) {
try {
return URLDecoder.decode(p.substring(5), "UTF-8");
} catch (UnsupportedEncodingException e) { }
}
}
return null;
}
private void updateThreadIdIfRunning() {
if (mIsRunning && mConversation != null) {
MessagingNotification.setCurrentlyDisplayedThreadId(mConversation.getThreadId());
}
// If we're not running, but resume later, the current thread ID will be set in onResume()
}
}
| src/com/android/mms/ui/ComposeMessageActivity.java | /*
* Copyright (C) 2008 Esmertec AG.
* Copyright (C) 2008 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.android.mms.ui;
import static android.content.res.Configuration.KEYBOARDHIDDEN_NO;
import static com.android.mms.transaction.ProgressCallbackEntity.PROGRESS_ABORT;
import static com.android.mms.transaction.ProgressCallbackEntity.PROGRESS_COMPLETE;
import static com.android.mms.transaction.ProgressCallbackEntity.PROGRESS_START;
import static com.android.mms.transaction.ProgressCallbackEntity.PROGRESS_STATUS_ACTION;
import static com.android.mms.ui.MessageListAdapter.COLUMN_ID;
import static com.android.mms.ui.MessageListAdapter.COLUMN_MSG_TYPE;
import static com.android.mms.ui.MessageListAdapter.PROJECTION;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.DialogInterface.OnClickListener;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SqliteWrapper;
import android.drm.DrmStore;
import android.graphics.drawable.Drawable;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.os.SystemProperties;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.Contacts;
import android.provider.Settings;
import android.provider.ContactsContract.Intents;
import android.provider.MediaStore.Images;
import android.provider.MediaStore.Video;
import android.provider.Telephony.Mms;
import android.provider.Telephony.Sms;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.telephony.PhoneNumberUtils;
import android.telephony.SmsMessage;
import android.content.ClipboardManager;
import android.text.Editable;
import android.text.InputFilter;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.TextKeyListener;
import android.text.style.URLSpan;
import android.text.util.Linkify;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewStub;
import android.view.WindowManager;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnCreateContextMenuListener;
import android.view.View.OnKeyListener;
import android.view.inputmethod.InputMethodManager;
import android.webkit.MimeTypeMap;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.android.internal.telephony.TelephonyIntents;
import com.android.internal.telephony.TelephonyProperties;
import com.android.mms.LogTag;
import com.android.mms.MmsApp;
import com.android.mms.MmsConfig;
import com.android.mms.R;
import com.android.mms.TempFileProvider;
import com.android.mms.data.Contact;
import com.android.mms.data.ContactList;
import com.android.mms.data.Conversation;
import com.android.mms.data.Conversation.ConversationQueryHandler;
import com.android.mms.data.WorkingMessage;
import com.android.mms.data.WorkingMessage.MessageStatusListener;
import com.android.mms.drm.DrmUtils;
import com.google.android.mms.ContentType;
import com.google.android.mms.pdu.EncodedStringValue;
import com.google.android.mms.MmsException;
import com.google.android.mms.pdu.PduBody;
import com.google.android.mms.pdu.PduPart;
import com.google.android.mms.pdu.PduPersister;
import com.google.android.mms.pdu.SendReq;
import com.android.mms.model.SlideModel;
import com.android.mms.model.SlideshowModel;
import com.android.mms.transaction.MessagingNotification;
import com.android.mms.ui.MessageListView.OnSizeChangedListener;
import com.android.mms.ui.MessageUtils.ResizeImageResultCallback;
import com.android.mms.ui.RecipientsEditor.RecipientContextMenuInfo;
import com.android.mms.util.AddressUtils;
import com.android.mms.util.PhoneNumberFormatter;
import com.android.mms.util.SendingProgressTokenManager;
import com.android.mms.util.SmileyParser;
import android.text.InputFilter.LengthFilter;
/**
* This is the main UI for:
* 1. Composing a new message;
* 2. Viewing/managing message history of a conversation.
*
* This activity can handle following parameters from the intent
* by which it's launched.
* thread_id long Identify the conversation to be viewed. When creating a
* new message, this parameter shouldn't be present.
* msg_uri Uri The message which should be opened for editing in the editor.
* address String The addresses of the recipients in current conversation.
* exit_on_sent boolean Exit this activity after the message is sent.
*/
public class ComposeMessageActivity extends Activity
implements View.OnClickListener, TextView.OnEditorActionListener,
MessageStatusListener, Contact.UpdateListener {
public static final int REQUEST_CODE_ATTACH_IMAGE = 100;
public static final int REQUEST_CODE_TAKE_PICTURE = 101;
public static final int REQUEST_CODE_ATTACH_VIDEO = 102;
public static final int REQUEST_CODE_TAKE_VIDEO = 103;
public static final int REQUEST_CODE_ATTACH_SOUND = 104;
public static final int REQUEST_CODE_RECORD_SOUND = 105;
public static final int REQUEST_CODE_CREATE_SLIDESHOW = 106;
public static final int REQUEST_CODE_ECM_EXIT_DIALOG = 107;
public static final int REQUEST_CODE_ADD_CONTACT = 108;
public static final int REQUEST_CODE_PICK = 109;
private static final String TAG = "Mms/compose";
private static final boolean DEBUG = false;
private static final boolean TRACE = false;
private static final boolean LOCAL_LOGV = false;
// Menu ID
private static final int MENU_ADD_SUBJECT = 0;
private static final int MENU_DELETE_THREAD = 1;
private static final int MENU_ADD_ATTACHMENT = 2;
private static final int MENU_DISCARD = 3;
private static final int MENU_SEND = 4;
private static final int MENU_CALL_RECIPIENT = 5;
private static final int MENU_CONVERSATION_LIST = 6;
private static final int MENU_DEBUG_DUMP = 7;
// Context menu ID
private static final int MENU_VIEW_CONTACT = 12;
private static final int MENU_ADD_TO_CONTACTS = 13;
private static final int MENU_EDIT_MESSAGE = 14;
private static final int MENU_VIEW_SLIDESHOW = 16;
private static final int MENU_VIEW_MESSAGE_DETAILS = 17;
private static final int MENU_DELETE_MESSAGE = 18;
private static final int MENU_SEARCH = 19;
private static final int MENU_DELIVERY_REPORT = 20;
private static final int MENU_FORWARD_MESSAGE = 21;
private static final int MENU_CALL_BACK = 22;
private static final int MENU_SEND_EMAIL = 23;
private static final int MENU_COPY_MESSAGE_TEXT = 24;
private static final int MENU_COPY_TO_SDCARD = 25;
private static final int MENU_INSERT_SMILEY = 26;
private static final int MENU_ADD_ADDRESS_TO_CONTACTS = 27;
private static final int MENU_LOCK_MESSAGE = 28;
private static final int MENU_UNLOCK_MESSAGE = 29;
private static final int MENU_SAVE_RINGTONE = 30;
private static final int MENU_PREFERENCES = 31;
private static final int RECIPIENTS_MAX_LENGTH = 312;
private static final int MESSAGE_LIST_QUERY_TOKEN = 9527;
private static final int MESSAGE_LIST_QUERY_AFTER_DELETE_TOKEN = 9528;
private static final int DELETE_MESSAGE_TOKEN = 9700;
private static final int CHARS_REMAINING_BEFORE_COUNTER_SHOWN = 10;
private static final long NO_DATE_FOR_DIALOG = -1L;
private static final String EXIT_ECM_RESULT = "exit_ecm_result";
// When the conversation has a lot of messages and a new message is sent, the list is scrolled
// so the user sees the just sent message. If we have to scroll the list more than 20 items,
// then a scroll shortcut is invoked to move the list near the end before scrolling.
private static final int MAX_ITEMS_TO_INVOKE_SCROLL_SHORTCUT = 20;
// Any change in height in the message list view greater than this threshold will not
// cause a smooth scroll. Instead, we jump the list directly to the desired position.
private static final int SMOOTH_SCROLL_THRESHOLD = 200;
private ContentResolver mContentResolver;
private BackgroundQueryHandler mBackgroundQueryHandler;
private Conversation mConversation; // Conversation we are working in
private boolean mExitOnSent; // Should we finish() after sending a message?
// TODO: mExitOnSent is obsolete -- remove
private View mTopPanel; // View containing the recipient and subject editors
private View mBottomPanel; // View containing the text editor, send button, ec.
private EditText mTextEditor; // Text editor to type your message into
private TextView mTextCounter; // Shows the number of characters used in text editor
private TextView mSendButtonMms; // Press to send mms
private ImageButton mSendButtonSms; // Press to send sms
private EditText mSubjectTextEditor; // Text editor for MMS subject
private AttachmentEditor mAttachmentEditor;
private View mAttachmentEditorScrollView;
private MessageListView mMsgListView; // ListView for messages in this conversation
public MessageListAdapter mMsgListAdapter; // and its corresponding ListAdapter
private RecipientsEditor mRecipientsEditor; // UI control for editing recipients
private ImageButton mRecipientsPicker; // UI control for recipients picker
private boolean mIsKeyboardOpen; // Whether the hardware keyboard is visible
private boolean mIsLandscape; // Whether we're in landscape mode
private boolean mPossiblePendingNotification; // If the message list has changed, we may have
// a pending notification to deal with.
private boolean mToastForDraftSave; // Whether to notify the user that a draft is being saved
private boolean mSentMessage; // true if the user has sent a message while in this
// activity. On a new compose message case, when the first
// message is sent is a MMS w/ attachment, the list blanks
// for a second before showing the sent message. But we'd
// think the message list is empty, thus show the recipients
// editor thinking it's a draft message. This flag should
// help clarify the situation.
private WorkingMessage mWorkingMessage; // The message currently being composed.
private AlertDialog mSmileyDialog;
private boolean mWaitingForSubActivity;
private int mLastRecipientCount; // Used for warning the user on too many recipients.
private AttachmentTypeSelectorAdapter mAttachmentTypeSelectorAdapter;
private boolean mSendingMessage; // Indicates the current message is sending, and shouldn't send again.
private Intent mAddContactIntent; // Intent used to add a new contact
private Uri mTempMmsUri; // Only used as a temporary to hold a slideshow uri
private long mTempThreadId; // Only used as a temporary to hold a threadId
private AsyncDialog mAsyncDialog; // Used for background tasks.
private String mDebugRecipients;
private int mLastSmoothScrollPosition;
private boolean mScrollOnSend; // Flag that we need to scroll the list to the end.
private int mSavedScrollPosition = -1; // we save the ListView's scroll position in onPause(),
// so we can remember it after re-entering the activity.
/**
* Whether this activity is currently running (i.e. not paused)
*/
private boolean mIsRunning;
@SuppressWarnings("unused")
public static void log(String logMsg) {
Thread current = Thread.currentThread();
long tid = current.getId();
StackTraceElement[] stack = current.getStackTrace();
String methodName = stack[3].getMethodName();
// Prepend current thread ID and name of calling method to the message.
logMsg = "[" + tid + "] [" + methodName + "] " + logMsg;
Log.d(TAG, logMsg);
}
//==========================================================
// Inner classes
//==========================================================
private void editSlideshow() {
// The user wants to edit the slideshow. That requires us to persist the slideshow to
// disk as a PDU in saveAsMms. This code below does that persisting in a background
// task. If the task takes longer than a half second, a progress dialog is displayed.
// Once the PDU persisting is done, another runnable on the UI thread get executed to start
// the SlideshowEditActivity.
getAsyncDialog().runAsync(new Runnable() {
@Override
public void run() {
// This runnable gets run in a background thread.
mTempMmsUri = mWorkingMessage.saveAsMms(false);
}
}, new Runnable() {
@Override
public void run() {
// Once the above background thread is complete, this runnable is run
// on the UI thread.
if (mTempMmsUri == null) {
return;
}
Intent intent = new Intent(ComposeMessageActivity.this,
SlideshowEditActivity.class);
intent.setData(mTempMmsUri);
startActivityForResult(intent, REQUEST_CODE_CREATE_SLIDESHOW);
}
}, R.string.building_slideshow_title);
}
private final Handler mAttachmentEditorHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case AttachmentEditor.MSG_EDIT_SLIDESHOW: {
editSlideshow();
break;
}
case AttachmentEditor.MSG_SEND_SLIDESHOW: {
if (isPreparedForSending()) {
ComposeMessageActivity.this.confirmSendMessageIfNeeded();
}
break;
}
case AttachmentEditor.MSG_VIEW_IMAGE:
case AttachmentEditor.MSG_PLAY_VIDEO:
case AttachmentEditor.MSG_PLAY_AUDIO:
case AttachmentEditor.MSG_PLAY_SLIDESHOW:
viewMmsMessageAttachment(msg.what);
break;
case AttachmentEditor.MSG_REPLACE_IMAGE:
case AttachmentEditor.MSG_REPLACE_VIDEO:
case AttachmentEditor.MSG_REPLACE_AUDIO:
showAddAttachmentDialog(true);
break;
case AttachmentEditor.MSG_REMOVE_ATTACHMENT:
mWorkingMessage.removeAttachment(true);
break;
default:
break;
}
}
};
private void viewMmsMessageAttachment(final int requestCode) {
SlideshowModel slideshow = mWorkingMessage.getSlideshow();
if (slideshow == null) {
throw new IllegalStateException("mWorkingMessage.getSlideshow() == null");
}
if (slideshow.isSimple()) {
MessageUtils.viewSimpleSlideshow(this, slideshow);
} else {
// The user wants to view the slideshow. That requires us to persist the slideshow to
// disk as a PDU in saveAsMms. This code below does that persisting in a background
// task. If the task takes longer than a half second, a progress dialog is displayed.
// Once the PDU persisting is done, another runnable on the UI thread get executed to
// start the SlideshowActivity.
getAsyncDialog().runAsync(new Runnable() {
@Override
public void run() {
// This runnable gets run in a background thread.
mTempMmsUri = mWorkingMessage.saveAsMms(false);
}
}, new Runnable() {
@Override
public void run() {
// Once the above background thread is complete, this runnable is run
// on the UI thread.
if (mTempMmsUri == null) {
return;
}
MessageUtils.launchSlideshowActivity(ComposeMessageActivity.this, mTempMmsUri,
requestCode);
}
}, R.string.building_slideshow_title);
}
}
private final Handler mMessageListItemHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
MessageItem msgItem = (MessageItem) msg.obj;
if (msgItem != null) {
switch (msg.what) {
case MessageListItem.MSG_LIST_DETAILS:
showMessageDetails(msgItem);
break;
case MessageListItem.MSG_LIST_EDIT:
editMessageItem(msgItem);
drawBottomPanel();
break;
case MessageListItem.MSG_LIST_PLAY:
switch (msgItem.mAttachmentType) {
case WorkingMessage.IMAGE:
case WorkingMessage.VIDEO:
case WorkingMessage.AUDIO:
case WorkingMessage.SLIDESHOW:
MessageUtils.viewMmsMessageAttachment(ComposeMessageActivity.this,
msgItem.mMessageUri, msgItem.mSlideshow,
getAsyncDialog());
break;
}
break;
default:
Log.w(TAG, "Unknown message: " + msg.what);
return;
}
}
}
};
private boolean showMessageDetails(MessageItem msgItem) {
Cursor cursor = mMsgListAdapter.getCursorForItem(msgItem);
if (cursor == null) {
return false;
}
String messageDetails = MessageUtils.getMessageDetails(
ComposeMessageActivity.this, cursor, msgItem.mMessageSize);
new AlertDialog.Builder(ComposeMessageActivity.this)
.setTitle(R.string.message_details_title)
.setMessage(messageDetails)
.setCancelable(true)
.show();
return true;
}
private final OnKeyListener mSubjectKeyListener = new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() != KeyEvent.ACTION_DOWN) {
return false;
}
// When the subject editor is empty, press "DEL" to hide the input field.
if ((keyCode == KeyEvent.KEYCODE_DEL) && (mSubjectTextEditor.length() == 0)) {
showSubjectEditor(false);
mWorkingMessage.setSubject(null, true);
return true;
}
return false;
}
};
/**
* Return the messageItem associated with the type ("mms" or "sms") and message id.
* @param type Type of the message: "mms" or "sms"
* @param msgId Message id of the message. This is the _id of the sms or pdu row and is
* stored in the MessageItem
* @param createFromCursorIfNotInCache true if the item is not found in the MessageListAdapter's
* cache and the code can create a new MessageItem based on the position of the current cursor.
* If false, the function returns null if the MessageItem isn't in the cache.
* @return MessageItem or null if not found and createFromCursorIfNotInCache is false
*/
private MessageItem getMessageItem(String type, long msgId,
boolean createFromCursorIfNotInCache) {
return mMsgListAdapter.getCachedMessageItem(type, msgId,
createFromCursorIfNotInCache ? mMsgListAdapter.getCursor() : null);
}
private boolean isCursorValid() {
// Check whether the cursor is valid or not.
Cursor cursor = mMsgListAdapter.getCursor();
if (cursor.isClosed() || cursor.isBeforeFirst() || cursor.isAfterLast()) {
Log.e(TAG, "Bad cursor.", new RuntimeException());
return false;
}
return true;
}
private void resetCounter() {
mTextCounter.setText("");
mTextCounter.setVisibility(View.GONE);
}
private void updateCounter(CharSequence text, int start, int before, int count) {
WorkingMessage workingMessage = mWorkingMessage;
if (workingMessage.requiresMms()) {
// If we're not removing text (i.e. no chance of converting back to SMS
// because of this change) and we're in MMS mode, just bail out since we
// then won't have to calculate the length unnecessarily.
final boolean textRemoved = (before > count);
if (!textRemoved) {
showSmsOrMmsSendButton(workingMessage.requiresMms());
return;
}
}
int[] params = SmsMessage.calculateLength(text, false);
/* SmsMessage.calculateLength returns an int[4] with:
* int[0] being the number of SMS's required,
* int[1] the number of code units used,
* int[2] is the number of code units remaining until the next message.
* int[3] is the encoding type that should be used for the message.
*/
int msgCount = params[0];
int remainingInCurrentMessage = params[2];
if (!MmsConfig.getMultipartSmsEnabled()) {
// The provider doesn't support multi-part sms's so as soon as the user types
// an sms longer than one segment, we have to turn the message into an mms.
mWorkingMessage.setLengthRequiresMms(msgCount > 1, true);
}
// Show the counter only if:
// - We are not in MMS mode
// - We are going to send more than one message OR we are getting close
boolean showCounter = false;
if (!workingMessage.requiresMms() &&
(msgCount > 1 ||
remainingInCurrentMessage <= CHARS_REMAINING_BEFORE_COUNTER_SHOWN)) {
showCounter = true;
}
showSmsOrMmsSendButton(workingMessage.requiresMms());
if (showCounter) {
// Update the remaining characters and number of messages required.
String counterText = msgCount > 1 ? remainingInCurrentMessage + " / " + msgCount
: String.valueOf(remainingInCurrentMessage);
mTextCounter.setText(counterText);
mTextCounter.setVisibility(View.VISIBLE);
} else {
mTextCounter.setVisibility(View.GONE);
}
}
@Override
public void startActivityForResult(Intent intent, int requestCode)
{
// requestCode >= 0 means the activity in question is a sub-activity.
if (requestCode >= 0) {
mWaitingForSubActivity = true;
}
if (mIsKeyboardOpen) {
hideKeyboard(); // camera and other activities take a long time to hide the keyboard
}
super.startActivityForResult(intent, requestCode);
}
private void toastConvertInfo(boolean toMms) {
final int resId = toMms ? R.string.converting_to_picture_message
: R.string.converting_to_text_message;
Toast.makeText(this, resId, Toast.LENGTH_SHORT).show();
}
private class DeleteMessageListener implements OnClickListener {
private final MessageItem mMessageItem;
public DeleteMessageListener(MessageItem messageItem) {
mMessageItem = messageItem;
}
@Override
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
new AsyncTask<Void, Void, Void>() {
protected Void doInBackground(Void... none) {
if (mMessageItem.isMms()) {
WorkingMessage.removeThumbnailsFromCache(mMessageItem.getSlideshow());
MmsApp.getApplication().getPduLoaderManager()
.removePdu(mMessageItem.mMessageUri);
// Delete the message *after* we've removed the thumbnails because we
// need the pdu and slideshow for removeThumbnailsFromCache to work.
}
mBackgroundQueryHandler.startDelete(DELETE_MESSAGE_TOKEN,
null, mMessageItem.mMessageUri,
mMessageItem.mLocked ? null : "locked=0", null);
return null;
}
}.execute();
}
}
private class DiscardDraftListener implements OnClickListener {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
mWorkingMessage.discard();
dialog.dismiss();
finish();
}
}
private class SendIgnoreInvalidRecipientListener implements OnClickListener {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
sendMessage(true);
dialog.dismiss();
}
}
private class CancelSendingListener implements OnClickListener {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
if (isRecipientsEditorVisible()) {
mRecipientsEditor.requestFocus();
}
dialog.dismiss();
}
}
private void confirmSendMessageIfNeeded() {
if (!isRecipientsEditorVisible()) {
sendMessage(true);
return;
}
boolean isMms = mWorkingMessage.requiresMms();
if (mRecipientsEditor.hasInvalidRecipient(isMms)) {
if (mRecipientsEditor.hasValidRecipient(isMms)) {
String title = getResourcesString(R.string.has_invalid_recipient,
mRecipientsEditor.formatInvalidNumbers(isMms));
new AlertDialog.Builder(this)
.setTitle(title)
.setMessage(R.string.invalid_recipient_message)
.setPositiveButton(R.string.try_to_send,
new SendIgnoreInvalidRecipientListener())
.setNegativeButton(R.string.no, new CancelSendingListener())
.show();
} else {
new AlertDialog.Builder(this)
.setTitle(R.string.cannot_send_message)
.setMessage(R.string.cannot_send_message_reason)
.setPositiveButton(R.string.yes, new CancelSendingListener())
.show();
}
} else {
sendMessage(true);
}
}
private final TextWatcher mRecipientsWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// This is a workaround for bug 1609057. Since onUserInteraction() is
// not called when the user touches the soft keyboard, we pretend it was
// called when textfields changes. This should be removed when the bug
// is fixed.
onUserInteraction();
}
@Override
public void afterTextChanged(Editable s) {
// Bug 1474782 describes a situation in which we send to
// the wrong recipient. We have been unable to reproduce this,
// but the best theory we have so far is that the contents of
// mRecipientList somehow become stale when entering
// ComposeMessageActivity via onNewIntent(). This assertion is
// meant to catch one possible path to that, of a non-visible
// mRecipientsEditor having its TextWatcher fire and refreshing
// mRecipientList with its stale contents.
if (!isRecipientsEditorVisible()) {
IllegalStateException e = new IllegalStateException(
"afterTextChanged called with invisible mRecipientsEditor");
// Make sure the crash is uploaded to the service so we
// can see if this is happening in the field.
Log.w(TAG,
"RecipientsWatcher: afterTextChanged called with invisible mRecipientsEditor");
return;
}
mWorkingMessage.setWorkingRecipients(mRecipientsEditor.getNumbers());
mWorkingMessage.setHasEmail(mRecipientsEditor.containsEmail(), true);
checkForTooManyRecipients();
// Walk backwards in the text box, skipping spaces. If the last
// character is a comma, update the title bar.
for (int pos = s.length() - 1; pos >= 0; pos--) {
char c = s.charAt(pos);
if (c == ' ')
continue;
if (c == ',') {
updateTitle(mConversation.getRecipients());
}
break;
}
// If we have gone to zero recipients, disable send button.
updateSendButtonState();
}
};
private void checkForTooManyRecipients() {
final int recipientLimit = MmsConfig.getRecipientLimit();
if (recipientLimit != Integer.MAX_VALUE) {
final int recipientCount = recipientCount();
boolean tooMany = recipientCount > recipientLimit;
if (recipientCount != mLastRecipientCount) {
// Don't warn the user on every character they type when they're over the limit,
// only when the actual # of recipients changes.
mLastRecipientCount = recipientCount;
if (tooMany) {
String tooManyMsg = getString(R.string.too_many_recipients, recipientCount,
recipientLimit);
Toast.makeText(ComposeMessageActivity.this,
tooManyMsg, Toast.LENGTH_LONG).show();
}
}
}
}
private final OnCreateContextMenuListener mRecipientsMenuCreateListener =
new OnCreateContextMenuListener() {
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
if (menuInfo != null) {
Contact c = ((RecipientContextMenuInfo) menuInfo).recipient;
RecipientsMenuClickListener l = new RecipientsMenuClickListener(c);
menu.setHeaderTitle(c.getName());
if (c.existsInDatabase()) {
menu.add(0, MENU_VIEW_CONTACT, 0, R.string.menu_view_contact)
.setOnMenuItemClickListener(l);
} else if (canAddToContacts(c)){
menu.add(0, MENU_ADD_TO_CONTACTS, 0, R.string.menu_add_to_contacts)
.setOnMenuItemClickListener(l);
}
}
}
};
private final class RecipientsMenuClickListener implements MenuItem.OnMenuItemClickListener {
private final Contact mRecipient;
RecipientsMenuClickListener(Contact recipient) {
mRecipient = recipient;
}
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
// Context menu handlers for the recipients editor.
case MENU_VIEW_CONTACT: {
Uri contactUri = mRecipient.getUri();
Intent intent = new Intent(Intent.ACTION_VIEW, contactUri);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
startActivity(intent);
return true;
}
case MENU_ADD_TO_CONTACTS: {
mAddContactIntent = ConversationList.createAddContactIntent(
mRecipient.getNumber());
ComposeMessageActivity.this.startActivityForResult(mAddContactIntent,
REQUEST_CODE_ADD_CONTACT);
return true;
}
}
return false;
}
}
private boolean canAddToContacts(Contact contact) {
// There are some kind of automated messages, like STK messages, that we don't want
// to add to contacts. These names begin with special characters, like, "*Info".
final String name = contact.getName();
if (!TextUtils.isEmpty(contact.getNumber())) {
char c = contact.getNumber().charAt(0);
if (isSpecialChar(c)) {
return false;
}
}
if (!TextUtils.isEmpty(name)) {
char c = name.charAt(0);
if (isSpecialChar(c)) {
return false;
}
}
if (!(Mms.isEmailAddress(name) ||
AddressUtils.isPossiblePhoneNumber(name) ||
contact.isMe())) {
return false;
}
return true;
}
private boolean isSpecialChar(char c) {
return c == '*' || c == '%' || c == '$';
}
private void addPositionBasedMenuItems(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
AdapterView.AdapterContextMenuInfo info;
try {
info = (AdapterView.AdapterContextMenuInfo) menuInfo;
} catch (ClassCastException e) {
Log.e(TAG, "bad menuInfo");
return;
}
final int position = info.position;
addUriSpecificMenuItems(menu, v, position);
}
private Uri getSelectedUriFromMessageList(ListView listView, int position) {
// If the context menu was opened over a uri, get that uri.
MessageListItem msglistItem = (MessageListItem) listView.getChildAt(position);
if (msglistItem == null) {
// FIXME: Should get the correct view. No such interface in ListView currently
// to get the view by position. The ListView.getChildAt(position) cannot
// get correct view since the list doesn't create one child for each item.
// And if setSelection(position) then getSelectedView(),
// cannot get corrent view when in touch mode.
return null;
}
TextView textView;
CharSequence text = null;
int selStart = -1;
int selEnd = -1;
//check if message sender is selected
textView = (TextView) msglistItem.findViewById(R.id.text_view);
if (textView != null) {
text = textView.getText();
selStart = textView.getSelectionStart();
selEnd = textView.getSelectionEnd();
}
// Check that some text is actually selected, rather than the cursor
// just being placed within the TextView.
if (selStart != selEnd) {
int min = Math.min(selStart, selEnd);
int max = Math.max(selStart, selEnd);
URLSpan[] urls = ((Spanned) text).getSpans(min, max,
URLSpan.class);
if (urls.length == 1) {
return Uri.parse(urls[0].getURL());
}
}
//no uri was selected
return null;
}
private void addUriSpecificMenuItems(ContextMenu menu, View v, int position) {
Uri uri = getSelectedUriFromMessageList((ListView) v, position);
if (uri != null) {
Intent intent = new Intent(null, uri);
intent.addCategory(Intent.CATEGORY_SELECTED_ALTERNATIVE);
menu.addIntentOptions(0, 0, 0,
new android.content.ComponentName(this, ComposeMessageActivity.class),
null, intent, 0, null);
}
}
private final void addCallAndContactMenuItems(
ContextMenu menu, MsgListMenuClickListener l, MessageItem msgItem) {
if (TextUtils.isEmpty(msgItem.mBody)) {
return;
}
SpannableString msg = new SpannableString(msgItem.mBody);
Linkify.addLinks(msg, Linkify.ALL);
ArrayList<String> uris =
MessageUtils.extractUris(msg.getSpans(0, msg.length(), URLSpan.class));
// Remove any dupes so they don't get added to the menu multiple times
HashSet<String> collapsedUris = new HashSet<String>();
for (String uri : uris) {
collapsedUris.add(uri.toLowerCase());
}
for (String uriString : collapsedUris) {
String prefix = null;
int sep = uriString.indexOf(":");
if (sep >= 0) {
prefix = uriString.substring(0, sep);
uriString = uriString.substring(sep + 1);
}
Uri contactUri = null;
boolean knownPrefix = true;
if ("mailto".equalsIgnoreCase(prefix)) {
contactUri = getContactUriForEmail(uriString);
} else if ("tel".equalsIgnoreCase(prefix)) {
contactUri = getContactUriForPhoneNumber(uriString);
} else {
knownPrefix = false;
}
if (knownPrefix && contactUri == null) {
Intent intent = ConversationList.createAddContactIntent(uriString);
String addContactString = getString(R.string.menu_add_address_to_contacts,
uriString);
menu.add(0, MENU_ADD_ADDRESS_TO_CONTACTS, 0, addContactString)
.setOnMenuItemClickListener(l)
.setIntent(intent);
}
}
}
private Uri getContactUriForEmail(String emailAddress) {
Cursor cursor = SqliteWrapper.query(this, getContentResolver(),
Uri.withAppendedPath(Email.CONTENT_LOOKUP_URI, Uri.encode(emailAddress)),
new String[] { Email.CONTACT_ID, Contacts.DISPLAY_NAME }, null, null, null);
if (cursor != null) {
try {
while (cursor.moveToNext()) {
String name = cursor.getString(1);
if (!TextUtils.isEmpty(name)) {
return ContentUris.withAppendedId(Contacts.CONTENT_URI, cursor.getLong(0));
}
}
} finally {
cursor.close();
}
}
return null;
}
private Uri getContactUriForPhoneNumber(String phoneNumber) {
Contact contact = Contact.get(phoneNumber, false);
if (contact.existsInDatabase()) {
return contact.getUri();
}
return null;
}
private final OnCreateContextMenuListener mMsgListMenuCreateListener =
new OnCreateContextMenuListener() {
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
if (!isCursorValid()) {
return;
}
Cursor cursor = mMsgListAdapter.getCursor();
String type = cursor.getString(COLUMN_MSG_TYPE);
long msgId = cursor.getLong(COLUMN_ID);
addPositionBasedMenuItems(menu, v, menuInfo);
MessageItem msgItem = mMsgListAdapter.getCachedMessageItem(type, msgId, cursor);
if (msgItem == null) {
Log.e(TAG, "Cannot load message item for type = " + type
+ ", msgId = " + msgId);
return;
}
menu.setHeaderTitle(R.string.message_options);
MsgListMenuClickListener l = new MsgListMenuClickListener(msgItem);
// It is unclear what would make most sense for copying an MMS message
// to the clipboard, so we currently do SMS only.
if (msgItem.isSms()) {
// Message type is sms. Only allow "edit" if the message has a single recipient
if (getRecipients().size() == 1 &&
(msgItem.mBoxId == Sms.MESSAGE_TYPE_OUTBOX ||
msgItem.mBoxId == Sms.MESSAGE_TYPE_FAILED)) {
menu.add(0, MENU_EDIT_MESSAGE, 0, R.string.menu_edit)
.setOnMenuItemClickListener(l);
}
menu.add(0, MENU_COPY_MESSAGE_TEXT, 0, R.string.copy_message_text)
.setOnMenuItemClickListener(l);
}
addCallAndContactMenuItems(menu, l, msgItem);
// Forward is not available for undownloaded messages.
if (msgItem.isDownloaded() && (msgItem.isSms() || isForwardable(msgId))) {
menu.add(0, MENU_FORWARD_MESSAGE, 0, R.string.menu_forward)
.setOnMenuItemClickListener(l);
}
if (msgItem.isMms()) {
switch (msgItem.mBoxId) {
case Mms.MESSAGE_BOX_INBOX:
break;
case Mms.MESSAGE_BOX_OUTBOX:
// Since we currently break outgoing messages to multiple
// recipients into one message per recipient, only allow
// editing a message for single-recipient conversations.
if (getRecipients().size() == 1) {
menu.add(0, MENU_EDIT_MESSAGE, 0, R.string.menu_edit)
.setOnMenuItemClickListener(l);
}
break;
}
switch (msgItem.mAttachmentType) {
case WorkingMessage.TEXT:
break;
case WorkingMessage.VIDEO:
case WorkingMessage.IMAGE:
if (haveSomethingToCopyToSDCard(msgItem.mMsgId)) {
menu.add(0, MENU_COPY_TO_SDCARD, 0, R.string.copy_to_sdcard)
.setOnMenuItemClickListener(l);
}
break;
case WorkingMessage.SLIDESHOW:
default:
menu.add(0, MENU_VIEW_SLIDESHOW, 0, R.string.view_slideshow)
.setOnMenuItemClickListener(l);
if (haveSomethingToCopyToSDCard(msgItem.mMsgId)) {
menu.add(0, MENU_COPY_TO_SDCARD, 0, R.string.copy_to_sdcard)
.setOnMenuItemClickListener(l);
}
if (isDrmRingtoneWithRights(msgItem.mMsgId)) {
menu.add(0, MENU_SAVE_RINGTONE, 0,
getDrmMimeMenuStringRsrc(msgItem.mMsgId))
.setOnMenuItemClickListener(l);
}
break;
}
}
if (msgItem.mLocked) {
menu.add(0, MENU_UNLOCK_MESSAGE, 0, R.string.menu_unlock)
.setOnMenuItemClickListener(l);
} else {
menu.add(0, MENU_LOCK_MESSAGE, 0, R.string.menu_lock)
.setOnMenuItemClickListener(l);
}
menu.add(0, MENU_VIEW_MESSAGE_DETAILS, 0, R.string.view_message_details)
.setOnMenuItemClickListener(l);
if (msgItem.mDeliveryStatus != MessageItem.DeliveryStatus.NONE || msgItem.mReadReport) {
menu.add(0, MENU_DELIVERY_REPORT, 0, R.string.view_delivery_report)
.setOnMenuItemClickListener(l);
}
menu.add(0, MENU_DELETE_MESSAGE, 0, R.string.delete_message)
.setOnMenuItemClickListener(l);
}
};
private void editMessageItem(MessageItem msgItem) {
if ("sms".equals(msgItem.mType)) {
editSmsMessageItem(msgItem);
} else {
editMmsMessageItem(msgItem);
}
if (msgItem.isFailedMessage() && mMsgListAdapter.getCount() <= 1) {
// For messages with bad addresses, let the user re-edit the recipients.
initRecipientsEditor();
}
}
private void editSmsMessageItem(MessageItem msgItem) {
// When the message being edited is the only message in the conversation, the delete
// below does something subtle. The trigger "delete_obsolete_threads_pdu" sees that a
// thread contains no messages and silently deletes the thread. Meanwhile, the mConversation
// object still holds onto the old thread_id and code thinks there's a backing thread in
// the DB when it really has been deleted. Here we try and notice that situation and
// clear out the thread_id. Later on, when Conversation.ensureThreadId() is called, we'll
// create a new thread if necessary.
synchronized(mConversation) {
if (mConversation.getMessageCount() <= 1) {
mConversation.clearThreadId();
MessagingNotification.setCurrentlyDisplayedThreadId(
MessagingNotification.THREAD_NONE);
}
}
// Delete the old undelivered SMS and load its content.
Uri uri = ContentUris.withAppendedId(Sms.CONTENT_URI, msgItem.mMsgId);
SqliteWrapper.delete(ComposeMessageActivity.this,
mContentResolver, uri, null, null);
mWorkingMessage.setText(msgItem.mBody);
}
private void editMmsMessageItem(MessageItem msgItem) {
// Load the selected message in as the working message.
WorkingMessage newWorkingMessage = WorkingMessage.load(this, msgItem.mMessageUri);
if (newWorkingMessage == null) {
return;
}
// Discard the current message in progress.
mWorkingMessage.discard();
mWorkingMessage = newWorkingMessage;
mWorkingMessage.setConversation(mConversation);
invalidateOptionsMenu();
drawTopPanel(false);
// WorkingMessage.load() above only loads the slideshow. Set the
// subject here because we already know what it is and avoid doing
// another DB lookup in load() just to get it.
mWorkingMessage.setSubject(msgItem.mSubject, false);
if (mWorkingMessage.hasSubject()) {
showSubjectEditor(true);
}
}
private void copyToClipboard(String str) {
ClipboardManager clipboard = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setPrimaryClip(ClipData.newPlainText(null, str));
}
private void forwardMessage(final MessageItem msgItem) {
mTempThreadId = 0;
// The user wants to forward the message. If the message is an mms message, we need to
// persist the pdu to disk. This is done in a background task.
// If the task takes longer than a half second, a progress dialog is displayed.
// Once the PDU persisting is done, another runnable on the UI thread get executed to start
// the ForwardMessageActivity.
getAsyncDialog().runAsync(new Runnable() {
@Override
public void run() {
// This runnable gets run in a background thread.
if (msgItem.mType.equals("mms")) {
SendReq sendReq = new SendReq();
String subject = getString(R.string.forward_prefix);
if (msgItem.mSubject != null) {
subject += msgItem.mSubject;
}
sendReq.setSubject(new EncodedStringValue(subject));
sendReq.setBody(msgItem.mSlideshow.makeCopy());
mTempMmsUri = null;
try {
PduPersister persister =
PduPersister.getPduPersister(ComposeMessageActivity.this);
// Copy the parts of the message here.
mTempMmsUri = persister.persist(sendReq, Mms.Draft.CONTENT_URI);
mTempThreadId = MessagingNotification.getThreadId(
ComposeMessageActivity.this, mTempMmsUri);
} catch (MmsException e) {
Log.e(TAG, "Failed to copy message: " + msgItem.mMessageUri);
Toast.makeText(ComposeMessageActivity.this,
R.string.cannot_save_message, Toast.LENGTH_SHORT).show();
return;
}
}
}
}, new Runnable() {
@Override
public void run() {
// Once the above background thread is complete, this runnable is run
// on the UI thread.
Intent intent = createIntent(ComposeMessageActivity.this, 0);
intent.putExtra("exit_on_sent", true);
intent.putExtra("forwarded_message", true);
if (mTempThreadId > 0) {
intent.putExtra("thread_id", mTempThreadId);
}
if (msgItem.mType.equals("sms")) {
intent.putExtra("sms_body", msgItem.mBody);
} else {
intent.putExtra("msg_uri", mTempMmsUri);
String subject = getString(R.string.forward_prefix);
if (msgItem.mSubject != null) {
subject += msgItem.mSubject;
}
intent.putExtra("subject", subject);
}
// ForwardMessageActivity is simply an alias in the manifest for
// ComposeMessageActivity. We have to make an alias because ComposeMessageActivity
// launch flags specify singleTop. When we forward a message, we want to start a
// separate ComposeMessageActivity. The only way to do that is to override the
// singleTop flag, which is impossible to do in code. By creating an alias to the
// activity, without the singleTop flag, we can launch a separate
// ComposeMessageActivity to edit the forward message.
intent.setClassName(ComposeMessageActivity.this,
"com.android.mms.ui.ForwardMessageActivity");
startActivity(intent);
}
}, R.string.building_slideshow_title);
}
/**
* Context menu handlers for the message list view.
*/
private final class MsgListMenuClickListener implements MenuItem.OnMenuItemClickListener {
private MessageItem mMsgItem;
public MsgListMenuClickListener(MessageItem msgItem) {
mMsgItem = msgItem;
}
@Override
public boolean onMenuItemClick(MenuItem item) {
if (mMsgItem == null) {
return false;
}
switch (item.getItemId()) {
case MENU_EDIT_MESSAGE:
editMessageItem(mMsgItem);
drawBottomPanel();
return true;
case MENU_COPY_MESSAGE_TEXT:
copyToClipboard(mMsgItem.mBody);
return true;
case MENU_FORWARD_MESSAGE:
forwardMessage(mMsgItem);
return true;
case MENU_VIEW_SLIDESHOW:
MessageUtils.viewMmsMessageAttachment(ComposeMessageActivity.this,
ContentUris.withAppendedId(Mms.CONTENT_URI, mMsgItem.mMsgId), null,
getAsyncDialog());
return true;
case MENU_VIEW_MESSAGE_DETAILS:
return showMessageDetails(mMsgItem);
case MENU_DELETE_MESSAGE: {
DeleteMessageListener l = new DeleteMessageListener(mMsgItem);
confirmDeleteDialog(l, mMsgItem.mLocked);
return true;
}
case MENU_DELIVERY_REPORT:
showDeliveryReport(mMsgItem.mMsgId, mMsgItem.mType);
return true;
case MENU_COPY_TO_SDCARD: {
int resId = copyMedia(mMsgItem.mMsgId) ? R.string.copy_to_sdcard_success :
R.string.copy_to_sdcard_fail;
Toast.makeText(ComposeMessageActivity.this, resId, Toast.LENGTH_SHORT).show();
return true;
}
case MENU_SAVE_RINGTONE: {
int resId = getDrmMimeSavedStringRsrc(mMsgItem.mMsgId,
saveRingtone(mMsgItem.mMsgId));
Toast.makeText(ComposeMessageActivity.this, resId, Toast.LENGTH_SHORT).show();
return true;
}
case MENU_LOCK_MESSAGE: {
lockMessage(mMsgItem, true);
return true;
}
case MENU_UNLOCK_MESSAGE: {
lockMessage(mMsgItem, false);
return true;
}
default:
return false;
}
}
}
private void lockMessage(MessageItem msgItem, boolean locked) {
Uri uri;
if ("sms".equals(msgItem.mType)) {
uri = Sms.CONTENT_URI;
} else {
uri = Mms.CONTENT_URI;
}
final Uri lockUri = ContentUris.withAppendedId(uri, msgItem.mMsgId);
final ContentValues values = new ContentValues(1);
values.put("locked", locked ? 1 : 0);
new Thread(new Runnable() {
@Override
public void run() {
getContentResolver().update(lockUri,
values, null, null);
}
}, "ComposeMessageActivity.lockMessage").start();
}
/**
* Looks to see if there are any valid parts of the attachment that can be copied to a SD card.
* @param msgId
*/
private boolean haveSomethingToCopyToSDCard(long msgId) {
PduBody body = null;
try {
body = SlideshowModel.getPduBody(this,
ContentUris.withAppendedId(Mms.CONTENT_URI, msgId));
} catch (MmsException e) {
Log.e(TAG, "haveSomethingToCopyToSDCard can't load pdu body: " + msgId);
}
if (body == null) {
return false;
}
boolean result = false;
int partNum = body.getPartsNum();
for(int i = 0; i < partNum; i++) {
PduPart part = body.getPart(i);
String type = new String(part.getContentType());
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("[CMA] haveSomethingToCopyToSDCard: part[" + i + "] contentType=" + type);
}
if (ContentType.isImageType(type) || ContentType.isVideoType(type) ||
ContentType.isAudioType(type) || DrmUtils.isDrmType(type)) {
result = true;
break;
}
}
return result;
}
/**
* Copies media from an Mms to the DrmProvider
* @param msgId
*/
private boolean saveRingtone(long msgId) {
boolean result = true;
PduBody body = null;
try {
body = SlideshowModel.getPduBody(this,
ContentUris.withAppendedId(Mms.CONTENT_URI, msgId));
} catch (MmsException e) {
Log.e(TAG, "copyToDrmProvider can't load pdu body: " + msgId);
}
if (body == null) {
return false;
}
int partNum = body.getPartsNum();
for(int i = 0; i < partNum; i++) {
PduPart part = body.getPart(i);
String type = new String(part.getContentType());
if (DrmUtils.isDrmType(type)) {
// All parts (but there's probably only a single one) have to be successful
// for a valid result.
result &= copyPart(part, Long.toHexString(msgId));
}
}
return result;
}
/**
* Returns true if any part is drm'd audio with ringtone rights.
* @param msgId
* @return true if one of the parts is drm'd audio with rights to save as a ringtone.
*/
private boolean isDrmRingtoneWithRights(long msgId) {
PduBody body = null;
try {
body = SlideshowModel.getPduBody(this,
ContentUris.withAppendedId(Mms.CONTENT_URI, msgId));
} catch (MmsException e) {
Log.e(TAG, "isDrmRingtoneWithRights can't load pdu body: " + msgId);
}
if (body == null) {
return false;
}
int partNum = body.getPartsNum();
for (int i = 0; i < partNum; i++) {
PduPart part = body.getPart(i);
String type = new String(part.getContentType());
if (DrmUtils.isDrmType(type)) {
String mimeType = MmsApp.getApplication().getDrmManagerClient()
.getOriginalMimeType(part.getDataUri());
if (ContentType.isAudioType(mimeType) && DrmUtils.haveRightsForAction(part.getDataUri(),
DrmStore.Action.RINGTONE)) {
return true;
}
}
}
return false;
}
/**
* Returns true if all drm'd parts are forwardable.
* @param msgId
* @return true if all drm'd parts are forwardable.
*/
private boolean isForwardable(long msgId) {
PduBody body = null;
try {
body = SlideshowModel.getPduBody(this,
ContentUris.withAppendedId(Mms.CONTENT_URI, msgId));
} catch (MmsException e) {
Log.e(TAG, "getDrmMimeType can't load pdu body: " + msgId);
}
if (body == null) {
return false;
}
int partNum = body.getPartsNum();
for (int i = 0; i < partNum; i++) {
PduPart part = body.getPart(i);
String type = new String(part.getContentType());
if (DrmUtils.isDrmType(type) && !DrmUtils.haveRightsForAction(part.getDataUri(),
DrmStore.Action.TRANSFER)) {
return false;
}
}
return true;
}
private int getDrmMimeMenuStringRsrc(long msgId) {
if (isDrmRingtoneWithRights(msgId)) {
return R.string.save_ringtone;
}
return 0;
}
private int getDrmMimeSavedStringRsrc(long msgId, boolean success) {
if (isDrmRingtoneWithRights(msgId)) {
return success ? R.string.saved_ringtone : R.string.saved_ringtone_fail;
}
return 0;
}
/**
* Copies media from an Mms to the "download" directory on the SD card. If any of the parts
* are audio types, drm'd or not, they're copied to the "Ringtones" directory.
* @param msgId
*/
private boolean copyMedia(long msgId) {
boolean result = true;
PduBody body = null;
try {
body = SlideshowModel.getPduBody(this,
ContentUris.withAppendedId(Mms.CONTENT_URI, msgId));
} catch (MmsException e) {
Log.e(TAG, "copyMedia can't load pdu body: " + msgId);
}
if (body == null) {
return false;
}
int partNum = body.getPartsNum();
for(int i = 0; i < partNum; i++) {
PduPart part = body.getPart(i);
// all parts have to be successful for a valid result.
result &= copyPart(part, Long.toHexString(msgId));
}
return result;
}
private boolean copyPart(PduPart part, String fallback) {
Uri uri = part.getDataUri();
String type = new String(part.getContentType());
boolean isDrm = DrmUtils.isDrmType(type);
if (isDrm) {
type = MmsApp.getApplication().getDrmManagerClient()
.getOriginalMimeType(part.getDataUri());
}
if (!ContentType.isImageType(type) && !ContentType.isVideoType(type) &&
!ContentType.isAudioType(type)) {
return true; // we only save pictures, videos, and sounds. Skip the text parts,
// the app (smil) parts, and other type that we can't handle.
// Return true to pretend that we successfully saved the part so
// the whole save process will be counted a success.
}
InputStream input = null;
FileOutputStream fout = null;
try {
input = mContentResolver.openInputStream(uri);
if (input instanceof FileInputStream) {
FileInputStream fin = (FileInputStream) input;
byte[] location = part.getName();
if (location == null) {
location = part.getFilename();
}
if (location == null) {
location = part.getContentLocation();
}
String fileName;
if (location == null) {
// Use fallback name.
fileName = fallback;
} else {
// For locally captured videos, fileName can end up being something like this:
// /mnt/sdcard/Android/data/com.android.mms/cache/.temp1.3gp
fileName = new String(location);
}
File originalFile = new File(fileName);
fileName = originalFile.getName(); // Strip the full path of where the "part" is
// stored down to just the leaf filename.
// Depending on the location, there may be an
// extension already on the name or not. If we've got audio, put the attachment
// in the Ringtones directory.
String dir = Environment.getExternalStorageDirectory() + "/"
+ (ContentType.isAudioType(type) ? Environment.DIRECTORY_RINGTONES :
Environment.DIRECTORY_DOWNLOADS) + "/";
String extension;
int index;
if ((index = fileName.lastIndexOf('.')) == -1) {
extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(type);
} else {
extension = fileName.substring(index + 1, fileName.length());
fileName = fileName.substring(0, index);
}
if (isDrm) {
extension += DrmUtils.getConvertExtension(type);
}
File file = getUniqueDestination(dir + fileName, extension);
// make sure the path is valid and directories created for this file.
File parentFile = file.getParentFile();
if (!parentFile.exists() && !parentFile.mkdirs()) {
Log.e(TAG, "[MMS] copyPart: mkdirs for " + parentFile.getPath() + " failed!");
return false;
}
fout = new FileOutputStream(file);
byte[] buffer = new byte[8000];
int size = 0;
while ((size=fin.read(buffer)) != -1) {
fout.write(buffer, 0, size);
}
// Notify other applications listening to scanner events
// that a media file has been added to the sd card
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
Uri.fromFile(file)));
}
} catch (IOException e) {
// Ignore
Log.e(TAG, "IOException caught while opening or reading stream", e);
return false;
} finally {
if (null != input) {
try {
input.close();
} catch (IOException e) {
// Ignore
Log.e(TAG, "IOException caught while closing stream", e);
return false;
}
}
if (null != fout) {
try {
fout.close();
} catch (IOException e) {
// Ignore
Log.e(TAG, "IOException caught while closing stream", e);
return false;
}
}
}
return true;
}
private File getUniqueDestination(String base, String extension) {
File file = new File(base + "." + extension);
for (int i = 2; file.exists(); i++) {
file = new File(base + "_" + i + "." + extension);
}
return file;
}
private void showDeliveryReport(long messageId, String type) {
Intent intent = new Intent(this, DeliveryReportActivity.class);
intent.putExtra("message_id", messageId);
intent.putExtra("message_type", type);
startActivity(intent);
}
private final IntentFilter mHttpProgressFilter = new IntentFilter(PROGRESS_STATUS_ACTION);
private final BroadcastReceiver mHttpProgressReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (PROGRESS_STATUS_ACTION.equals(intent.getAction())) {
long token = intent.getLongExtra("token",
SendingProgressTokenManager.NO_TOKEN);
if (token != mConversation.getThreadId()) {
return;
}
int progress = intent.getIntExtra("progress", 0);
switch (progress) {
case PROGRESS_START:
setProgressBarVisibility(true);
break;
case PROGRESS_ABORT:
case PROGRESS_COMPLETE:
setProgressBarVisibility(false);
break;
default:
setProgress(100 * progress);
}
}
}
};
private static ContactList sEmptyContactList;
private ContactList getRecipients() {
// If the recipients editor is visible, the conversation has
// not really officially 'started' yet. Recipients will be set
// on the conversation once it has been saved or sent. In the
// meantime, let anyone who needs the recipient list think it
// is empty rather than giving them a stale one.
if (isRecipientsEditorVisible()) {
if (sEmptyContactList == null) {
sEmptyContactList = new ContactList();
}
return sEmptyContactList;
}
return mConversation.getRecipients();
}
private void updateTitle(ContactList list) {
String title = null;
String subTitle = null;
int cnt = list.size();
switch (cnt) {
case 0: {
String recipient = null;
if (mRecipientsEditor != null) {
recipient = mRecipientsEditor.getText().toString();
}
title = TextUtils.isEmpty(recipient) ? getString(R.string.new_message) : recipient;
break;
}
case 1: {
title = list.get(0).getName(); // get name returns the number if there's no
// name available.
String number = list.get(0).getNumber();
if (!title.equals(number)) {
subTitle = PhoneNumberUtils.formatNumber(number, number,
MmsApp.getApplication().getCurrentCountryIso());
}
break;
}
default: {
// Handle multiple recipients
title = list.formatNames(", ");
subTitle = getResources().getQuantityString(R.plurals.recipient_count, cnt, cnt);
break;
}
}
mDebugRecipients = list.serialize();
ActionBar actionBar = getActionBar();
actionBar.setTitle(title);
actionBar.setSubtitle(subTitle);
}
// Get the recipients editor ready to be displayed onscreen.
private void initRecipientsEditor() {
if (isRecipientsEditorVisible()) {
return;
}
// Must grab the recipients before the view is made visible because getRecipients()
// returns empty recipients when the editor is visible.
ContactList recipients = getRecipients();
ViewStub stub = (ViewStub)findViewById(R.id.recipients_editor_stub);
if (stub != null) {
View stubView = stub.inflate();
mRecipientsEditor = (RecipientsEditor) stubView.findViewById(R.id.recipients_editor);
mRecipientsPicker = (ImageButton) stubView.findViewById(R.id.recipients_picker);
} else {
mRecipientsEditor = (RecipientsEditor)findViewById(R.id.recipients_editor);
mRecipientsEditor.setVisibility(View.VISIBLE);
mRecipientsPicker = (ImageButton)findViewById(R.id.recipients_picker);
}
mRecipientsPicker.setOnClickListener(this);
mRecipientsEditor.setAdapter(new ChipsRecipientAdapter(this));
mRecipientsEditor.populate(recipients);
mRecipientsEditor.setOnCreateContextMenuListener(mRecipientsMenuCreateListener);
mRecipientsEditor.addTextChangedListener(mRecipientsWatcher);
// TODO : Remove the max length limitation due to the multiple phone picker is added and the
// user is able to select a large number of recipients from the Contacts. The coming
// potential issue is that it is hard for user to edit a recipient from hundred of
// recipients in the editor box. We may redesign the editor box UI for this use case.
// mRecipientsEditor.setFilters(new InputFilter[] {
// new InputFilter.LengthFilter(RECIPIENTS_MAX_LENGTH) });
mRecipientsEditor.setOnSelectChipRunnable(new Runnable() {
@Override
public void run() {
// After the user selects an item in the pop-up contacts list, move the
// focus to the text editor if there is only one recipient. This helps
// the common case of selecting one recipient and then typing a message,
// but avoids annoying a user who is trying to add five recipients and
// keeps having focus stolen away.
if (mRecipientsEditor.getRecipientCount() == 1) {
// if we're in extract mode then don't request focus
final InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputManager == null || !inputManager.isFullscreenMode()) {
mTextEditor.requestFocus();
}
}
}
});
mRecipientsEditor.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
RecipientsEditor editor = (RecipientsEditor) v;
ContactList contacts = editor.constructContactsFromInput(false);
updateTitle(contacts);
}
}
});
PhoneNumberFormatter.setPhoneNumberFormattingTextWatcher(this, mRecipientsEditor);
mTopPanel.setVisibility(View.VISIBLE);
}
//==========================================================
// Activity methods
//==========================================================
public static boolean cancelFailedToDeliverNotification(Intent intent, Context context) {
if (MessagingNotification.isFailedToDeliver(intent)) {
// Cancel any failed message notifications
MessagingNotification.cancelNotification(context,
MessagingNotification.MESSAGE_FAILED_NOTIFICATION_ID);
return true;
}
return false;
}
public static boolean cancelFailedDownloadNotification(Intent intent, Context context) {
if (MessagingNotification.isFailedToDownload(intent)) {
// Cancel any failed download notifications
MessagingNotification.cancelNotification(context,
MessagingNotification.DOWNLOAD_FAILED_NOTIFICATION_ID);
return true;
}
return false;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
resetConfiguration(getResources().getConfiguration());
setContentView(R.layout.compose_message_activity);
setProgressBarVisibility(false);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE |
WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
// Initialize members for UI elements.
initResourceRefs();
mContentResolver = getContentResolver();
mBackgroundQueryHandler = new BackgroundQueryHandler(mContentResolver);
initialize(savedInstanceState, 0);
if (TRACE) {
android.os.Debug.startMethodTracing("compose");
}
}
private void showSubjectEditor(boolean show) {
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("" + show);
}
if (mSubjectTextEditor == null) {
// Don't bother to initialize the subject editor if
// we're just going to hide it.
if (show == false) {
return;
}
mSubjectTextEditor = (EditText)findViewById(R.id.subject);
mSubjectTextEditor.setFilters(new InputFilter[] {
new LengthFilter(MmsConfig.getMaxSubjectLength())});
}
mSubjectTextEditor.setOnKeyListener(show ? mSubjectKeyListener : null);
if (show) {
mSubjectTextEditor.addTextChangedListener(mSubjectEditorWatcher);
} else {
mSubjectTextEditor.removeTextChangedListener(mSubjectEditorWatcher);
}
mSubjectTextEditor.setText(mWorkingMessage.getSubject());
mSubjectTextEditor.setVisibility(show ? View.VISIBLE : View.GONE);
hideOrShowTopPanel();
}
private void hideOrShowTopPanel() {
boolean anySubViewsVisible = (isSubjectEditorVisible() || isRecipientsEditorVisible());
mTopPanel.setVisibility(anySubViewsVisible ? View.VISIBLE : View.GONE);
}
public void initialize(Bundle savedInstanceState, long originalThreadId) {
// Create a new empty working message.
mWorkingMessage = WorkingMessage.createEmpty(this);
// Read parameters or previously saved state of this activity. This will load a new
// mConversation
initActivityState(savedInstanceState);
if (LogTag.SEVERE_WARNING && originalThreadId != 0 &&
originalThreadId == mConversation.getThreadId()) {
LogTag.warnPossibleRecipientMismatch("ComposeMessageActivity.initialize: " +
" threadId didn't change from: " + originalThreadId, this);
}
log("savedInstanceState = " + savedInstanceState +
" intent = " + getIntent() +
" mConversation = " + mConversation);
if (cancelFailedToDeliverNotification(getIntent(), this)) {
// Show a pop-up dialog to inform user the message was
// failed to deliver.
undeliveredMessageDialog(getMessageDate(null));
}
cancelFailedDownloadNotification(getIntent(), this);
// Set up the message history ListAdapter
initMessageList();
// Load the draft for this thread, if we aren't already handling
// existing data, such as a shared picture or forwarded message.
boolean isForwardedMessage = false;
// We don't attempt to handle the Intent.ACTION_SEND when saveInstanceState is non-null.
// saveInstanceState is non-null when this activity is killed. In that case, we already
// handled the attachment or the send, so we don't try and parse the intent again.
boolean intentHandled = savedInstanceState == null &&
(handleSendIntent() || handleForwardedMessage());
if (!intentHandled) {
loadDraft();
}
// Let the working message know what conversation it belongs to
mWorkingMessage.setConversation(mConversation);
// Show the recipients editor if we don't have a valid thread. Hide it otherwise.
if (mConversation.getThreadId() <= 0) {
// Hide the recipients editor so the call to initRecipientsEditor won't get
// short-circuited.
hideRecipientEditor();
initRecipientsEditor();
// Bring up the softkeyboard so the user can immediately enter recipients. This
// call won't do anything on devices with a hard keyboard.
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE |
WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
} else {
hideRecipientEditor();
}
invalidateOptionsMenu(); // do after show/hide of recipients editor because the options
// menu depends on the recipients, which depending upon the
// visibility of the recipients editor, returns a different
// value (see getRecipients()).
updateSendButtonState();
drawTopPanel(false);
if (intentHandled) {
// We're not loading a draft, so we can draw the bottom panel immediately.
drawBottomPanel();
}
onKeyboardStateChanged(mIsKeyboardOpen);
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("update title, mConversation=" + mConversation.toString());
}
updateTitle(mConversation.getRecipients());
if (isForwardedMessage && isRecipientsEditorVisible()) {
// The user is forwarding the message to someone. Put the focus on the
// recipient editor rather than in the message editor.
mRecipientsEditor.requestFocus();
}
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
Conversation conversation = null;
mSentMessage = false;
// If we have been passed a thread_id, use that to find our
// conversation.
// Note that originalThreadId might be zero but if this is a draft and we save the
// draft, ensureThreadId gets called async from WorkingMessage.asyncUpdateDraftSmsMessage
// the thread will get a threadId behind the UI thread's back.
long originalThreadId = mConversation.getThreadId();
long threadId = intent.getLongExtra("thread_id", 0);
Uri intentUri = intent.getData();
boolean sameThread = false;
if (threadId > 0) {
conversation = Conversation.get(this, threadId, false);
} else {
if (mConversation.getThreadId() == 0) {
// We've got a draft. Make sure the working recipients are synched
// to the conversation so when we compare conversations later in this function,
// the compare will work.
mWorkingMessage.syncWorkingRecipients();
}
// Get the "real" conversation based on the intentUri. The intentUri might specify
// the conversation by a phone number or by a thread id. We'll typically get a threadId
// based uri when the user pulls down a notification while in ComposeMessageActivity and
// we end up here in onNewIntent. mConversation can have a threadId of zero when we're
// working on a draft. When a new message comes in for that same recipient, a
// conversation will get created behind CMA's back when the message is inserted into
// the database and the corresponding entry made in the threads table. The code should
// use the real conversation as soon as it can rather than finding out the threadId
// when sending with "ensureThreadId".
conversation = Conversation.get(this, intentUri, false);
}
if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("onNewIntent: data=" + intentUri + ", thread_id extra is " + threadId +
", new conversation=" + conversation + ", mConversation=" + mConversation);
}
// this is probably paranoid to compare both thread_ids and recipient lists,
// but we want to make double sure because this is a last minute fix for Froyo
// and the previous code checked thread ids only.
// (we cannot just compare thread ids because there is a case where mConversation
// has a stale/obsolete thread id (=1) that could collide against the new thread_id(=1),
// even though the recipient lists are different)
sameThread = ((conversation.getThreadId() == mConversation.getThreadId() ||
mConversation.getThreadId() == 0) &&
conversation.equals(mConversation));
if (sameThread) {
log("onNewIntent: same conversation");
if (mConversation.getThreadId() == 0) {
mConversation = conversation;
mWorkingMessage.setConversation(mConversation);
updateThreadIdIfRunning();
invalidateOptionsMenu();
}
} else {
if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("onNewIntent: different conversation");
}
saveDraft(false); // if we've got a draft, save it first
initialize(null, originalThreadId);
}
loadMessageContent();
}
private void sanityCheckConversation() {
if (mWorkingMessage.getConversation() != mConversation) {
LogTag.warnPossibleRecipientMismatch(
"ComposeMessageActivity: mWorkingMessage.mConversation=" +
mWorkingMessage.getConversation() + ", mConversation=" +
mConversation + ", MISMATCH!", this);
}
}
@Override
protected void onRestart() {
super.onRestart();
if (mWorkingMessage.isDiscarded()) {
// If the message isn't worth saving, don't resurrect it. Doing so can lead to
// a situation where a new incoming message gets the old thread id of the discarded
// draft. This activity can end up displaying the recipients of the old message with
// the contents of the new message. Recognize that dangerous situation and bail out
// to the ConversationList where the user can enter this in a clean manner.
if (mWorkingMessage.isWorthSaving()) {
if (LogTag.VERBOSE) {
log("onRestart: mWorkingMessage.unDiscard()");
}
mWorkingMessage.unDiscard(); // it was discarded in onStop().
sanityCheckConversation();
} else if (isRecipientsEditorVisible()) {
if (LogTag.VERBOSE) {
log("onRestart: goToConversationList");
}
goToConversationList();
} else {
if (LogTag.VERBOSE) {
log("onRestart: loadDraft");
}
loadDraft();
mWorkingMessage.setConversation(mConversation);
mAttachmentEditor.update(mWorkingMessage);
invalidateOptionsMenu();
}
}
}
@Override
protected void onStart() {
super.onStart();
initFocus();
// Register a BroadcastReceiver to listen on HTTP I/O process.
registerReceiver(mHttpProgressReceiver, mHttpProgressFilter);
loadMessageContent();
// Update the fasttrack info in case any of the recipients' contact info changed
// while we were paused. This can happen, for example, if a user changes or adds
// an avatar associated with a contact.
mWorkingMessage.syncWorkingRecipients();
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("update title, mConversation=" + mConversation.toString());
}
updateTitle(mConversation.getRecipients());
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
}
public void loadMessageContent() {
// Don't let any markAsRead DB updates occur before we've loaded the messages for
// the thread. Unblocking occurs when we're done querying for the conversation
// items.
mConversation.blockMarkAsRead(true);
mConversation.markAsRead(); // dismiss any notifications for this convo
startMsgListQuery();
updateSendFailedNotification();
drawBottomPanel();
}
private void updateSendFailedNotification() {
final long threadId = mConversation.getThreadId();
if (threadId <= 0)
return;
// updateSendFailedNotificationForThread makes a database call, so do the work off
// of the ui thread.
new Thread(new Runnable() {
@Override
public void run() {
MessagingNotification.updateSendFailedNotificationForThread(
ComposeMessageActivity.this, threadId);
}
}, "ComposeMessageActivity.updateSendFailedNotification").start();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("recipients", getRecipients().serialize());
mWorkingMessage.writeStateToBundle(outState);
if (mExitOnSent) {
outState.putBoolean("exit_on_sent", mExitOnSent);
}
}
@Override
protected void onResume() {
super.onResume();
// OLD: get notified of presence updates to update the titlebar.
// NEW: we are using ContactHeaderWidget which displays presence, but updating presence
// there is out of our control.
//Contact.startPresenceObserver();
addRecipientsListeners();
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("update title, mConversation=" + mConversation.toString());
}
// There seems to be a bug in the framework such that setting the title
// here gets overwritten to the original title. Do this delayed as a
// workaround.
mMessageListItemHandler.postDelayed(new Runnable() {
@Override
public void run() {
ContactList recipients = isRecipientsEditorVisible() ?
mRecipientsEditor.constructContactsFromInput(false) : getRecipients();
updateTitle(recipients);
}
}, 100);
mIsRunning = true;
updateThreadIdIfRunning();
}
@Override
protected void onPause() {
super.onPause();
// OLD: stop getting notified of presence updates to update the titlebar.
// NEW: we are using ContactHeaderWidget which displays presence, but updating presence
// there is out of our control.
//Contact.stopPresenceObserver();
removeRecipientsListeners();
// remove any callback to display a progress spinner
if (mAsyncDialog != null) {
mAsyncDialog.clearPendingProgressDialog();
}
MessagingNotification.setCurrentlyDisplayedThreadId(MessagingNotification.THREAD_NONE);
mSavedScrollPosition = mMsgListView.getFirstVisiblePosition();
if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
Log.v(TAG, "onPause: mSavedScrollPosition=" + mSavedScrollPosition);
}
mIsRunning = false;
}
@Override
protected void onStop() {
super.onStop();
// No need to do the querying when finished this activity
mBackgroundQueryHandler.cancelOperation(MESSAGE_LIST_QUERY_TOKEN);
// Allow any blocked calls to update the thread's read status.
mConversation.blockMarkAsRead(false);
if (mMsgListAdapter != null) {
// Close the cursor in the ListAdapter if the activity stopped.
Cursor cursor = mMsgListAdapter.getCursor();
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
mMsgListAdapter.changeCursor(null);
mMsgListAdapter.cancelBackgroundLoading();
}
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("save draft");
}
saveDraft(true);
// Cleanup the BroadcastReceiver.
unregisterReceiver(mHttpProgressReceiver);
}
@Override
protected void onDestroy() {
if (TRACE) {
android.os.Debug.stopMethodTracing();
}
super.onDestroy();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (LOCAL_LOGV) {
Log.v(TAG, "onConfigurationChanged: " + newConfig);
}
if (resetConfiguration(newConfig)) {
// Have to re-layout the attachment editor because we have different layouts
// depending on whether we're portrait or landscape.
drawTopPanel(isSubjectEditorVisible());
}
onKeyboardStateChanged(mIsKeyboardOpen);
}
// returns true if landscape/portrait configuration has changed
private boolean resetConfiguration(Configuration config) {
mIsKeyboardOpen = config.keyboardHidden == KEYBOARDHIDDEN_NO;
boolean isLandscape = config.orientation == Configuration.ORIENTATION_LANDSCAPE;
if (mIsLandscape != isLandscape) {
mIsLandscape = isLandscape;
return true;
}
return false;
}
private void onKeyboardStateChanged(boolean isKeyboardOpen) {
// If the keyboard is hidden, don't show focus highlights for
// things that cannot receive input.
if (isKeyboardOpen) {
if (mRecipientsEditor != null) {
mRecipientsEditor.setFocusableInTouchMode(true);
}
if (mSubjectTextEditor != null) {
mSubjectTextEditor.setFocusableInTouchMode(true);
}
mTextEditor.setFocusableInTouchMode(true);
mTextEditor.setHint(R.string.type_to_compose_text_enter_to_send);
} else {
if (mRecipientsEditor != null) {
mRecipientsEditor.setFocusable(false);
}
if (mSubjectTextEditor != null) {
mSubjectTextEditor.setFocusable(false);
}
mTextEditor.setFocusable(false);
mTextEditor.setHint(R.string.open_keyboard_to_compose_message);
}
}
@Override
public void onUserInteraction() {
checkPendingNotification();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_DEL:
if ((mMsgListAdapter != null) && mMsgListView.isFocused()) {
Cursor cursor;
try {
cursor = (Cursor) mMsgListView.getSelectedItem();
} catch (ClassCastException e) {
Log.e(TAG, "Unexpected ClassCastException.", e);
return super.onKeyDown(keyCode, event);
}
if (cursor != null) {
String type = cursor.getString(COLUMN_MSG_TYPE);
long msgId = cursor.getLong(COLUMN_ID);
MessageItem msgItem = mMsgListAdapter.getCachedMessageItem(type, msgId,
cursor);
if (msgItem != null) {
DeleteMessageListener l = new DeleteMessageListener(msgItem);
confirmDeleteDialog(l, msgItem.mLocked);
}
return true;
}
}
break;
case KeyEvent.KEYCODE_DPAD_CENTER:
case KeyEvent.KEYCODE_ENTER:
if (isPreparedForSending()) {
confirmSendMessageIfNeeded();
return true;
}
break;
case KeyEvent.KEYCODE_BACK:
exitComposeMessageActivity(new Runnable() {
@Override
public void run() {
finish();
}
});
return true;
}
return super.onKeyDown(keyCode, event);
}
private void exitComposeMessageActivity(final Runnable exit) {
// If the message is empty, just quit -- finishing the
// activity will cause an empty draft to be deleted.
if (!mWorkingMessage.isWorthSaving()) {
exit.run();
return;
}
if (isRecipientsEditorVisible() &&
!mRecipientsEditor.hasValidRecipient(mWorkingMessage.requiresMms())) {
MessageUtils.showDiscardDraftConfirmDialog(this, new DiscardDraftListener());
return;
}
mToastForDraftSave = true;
exit.run();
}
private void goToConversationList() {
finish();
startActivity(new Intent(this, ConversationList.class));
}
private void hideRecipientEditor() {
if (mRecipientsEditor != null) {
mRecipientsEditor.removeTextChangedListener(mRecipientsWatcher);
mRecipientsEditor.setVisibility(View.GONE);
hideOrShowTopPanel();
}
}
private boolean isRecipientsEditorVisible() {
return (null != mRecipientsEditor)
&& (View.VISIBLE == mRecipientsEditor.getVisibility());
}
private boolean isSubjectEditorVisible() {
return (null != mSubjectTextEditor)
&& (View.VISIBLE == mSubjectTextEditor.getVisibility());
}
@Override
public void onAttachmentChanged() {
// Have to make sure we're on the UI thread. This function can be called off of the UI
// thread when we're adding multi-attachments
runOnUiThread(new Runnable() {
@Override
public void run() {
drawBottomPanel();
updateSendButtonState();
drawTopPanel(isSubjectEditorVisible());
}
});
}
@Override
public void onProtocolChanged(final boolean mms) {
// Have to make sure we're on the UI thread. This function can be called off of the UI
// thread when we're adding multi-attachments
runOnUiThread(new Runnable() {
@Override
public void run() {
toastConvertInfo(mms);
showSmsOrMmsSendButton(mms);
if (mms) {
// In the case we went from a long sms with a counter to an mms because
// the user added an attachment or a subject, hide the counter --
// it doesn't apply to mms.
mTextCounter.setVisibility(View.GONE);
}
}
});
}
// Show or hide the Sms or Mms button as appropriate. Return the view so that the caller
// can adjust the enableness and focusability.
private View showSmsOrMmsSendButton(boolean isMms) {
View showButton;
View hideButton;
if (isMms) {
showButton = mSendButtonMms;
hideButton = mSendButtonSms;
} else {
showButton = mSendButtonSms;
hideButton = mSendButtonMms;
}
showButton.setVisibility(View.VISIBLE);
hideButton.setVisibility(View.GONE);
return showButton;
}
Runnable mResetMessageRunnable = new Runnable() {
@Override
public void run() {
resetMessage();
}
};
@Override
public void onPreMessageSent() {
runOnUiThread(mResetMessageRunnable);
}
@Override
public void onMessageSent() {
// This callback can come in on any thread; put it on the main thread to avoid
// concurrency problems
runOnUiThread(new Runnable() {
@Override
public void run() {
// If we already have messages in the list adapter, it
// will be auto-requerying; don't thrash another query in.
// TODO: relying on auto-requerying seems unreliable when priming an MMS into the
// outbox. Need to investigate.
// if (mMsgListAdapter.getCount() == 0) {
if (LogTag.VERBOSE) {
log("onMessageSent");
}
startMsgListQuery();
// }
// The thread ID could have changed if this is a new message that we just inserted
// into the database (and looked up or created a thread for it)
updateThreadIdIfRunning();
}
});
}
@Override
public void onMaxPendingMessagesReached() {
saveDraft(false);
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(ComposeMessageActivity.this, R.string.too_many_unsent_mms,
Toast.LENGTH_LONG).show();
}
});
}
@Override
public void onAttachmentError(final int error) {
runOnUiThread(new Runnable() {
@Override
public void run() {
handleAddAttachmentError(error, R.string.type_picture);
onMessageSent(); // now requery the list of messages
}
});
}
// We don't want to show the "call" option unless there is only one
// recipient and it's a phone number.
private boolean isRecipientCallable() {
ContactList recipients = getRecipients();
return (recipients.size() == 1 && !recipients.containsEmail());
}
private void dialRecipient() {
if (isRecipientCallable()) {
String number = getRecipients().get(0).getNumber();
Intent dialIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + number));
startActivity(dialIntent);
}
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu) ;
menu.clear();
if (isRecipientCallable()) {
MenuItem item = menu.add(0, MENU_CALL_RECIPIENT, 0, R.string.menu_call)
.setIcon(R.drawable.ic_menu_call)
.setTitle(R.string.menu_call);
if (!isRecipientsEditorVisible()) {
// If we're not composing a new message, show the call icon in the actionbar
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
}
}
if (MmsConfig.getMmsEnabled()) {
if (!isSubjectEditorVisible()) {
menu.add(0, MENU_ADD_SUBJECT, 0, R.string.add_subject).setIcon(
R.drawable.ic_menu_edit);
}
menu.add(0, MENU_ADD_ATTACHMENT, 0, R.string.add_attachment)
.setIcon(R.drawable.ic_menu_attachment)
.setTitle(R.string.add_attachment)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); // add to actionbar
}
if (isPreparedForSending()) {
menu.add(0, MENU_SEND, 0, R.string.send).setIcon(android.R.drawable.ic_menu_send);
}
if (!mWorkingMessage.hasSlideshow()) {
menu.add(0, MENU_INSERT_SMILEY, 0, R.string.menu_insert_smiley).setIcon(
R.drawable.ic_menu_emoticons);
}
if (mMsgListAdapter.getCount() > 0) {
// Removed search as part of b/1205708
//menu.add(0, MENU_SEARCH, 0, R.string.menu_search).setIcon(
// R.drawable.ic_menu_search);
Cursor cursor = mMsgListAdapter.getCursor();
if ((null != cursor) && (cursor.getCount() > 0)) {
menu.add(0, MENU_DELETE_THREAD, 0, R.string.delete_thread).setIcon(
android.R.drawable.ic_menu_delete);
}
} else {
menu.add(0, MENU_DISCARD, 0, R.string.discard).setIcon(android.R.drawable.ic_menu_delete);
}
buildAddAddressToContactMenuItem(menu);
menu.add(0, MENU_PREFERENCES, 0, R.string.menu_preferences).setIcon(
android.R.drawable.ic_menu_preferences);
if (LogTag.DEBUG_DUMP) {
menu.add(0, MENU_DEBUG_DUMP, 0, R.string.menu_debug_dump);
}
return true;
}
private void buildAddAddressToContactMenuItem(Menu menu) {
// Look for the first recipient we don't have a contact for and create a menu item to
// add the number to contacts.
for (Contact c : getRecipients()) {
if (!c.existsInDatabase() && canAddToContacts(c)) {
Intent intent = ConversationList.createAddContactIntent(c.getNumber());
menu.add(0, MENU_ADD_ADDRESS_TO_CONTACTS, 0, R.string.menu_add_to_contacts)
.setIcon(android.R.drawable.ic_menu_add)
.setIntent(intent);
break;
}
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_ADD_SUBJECT:
showSubjectEditor(true);
mWorkingMessage.setSubject("", true);
updateSendButtonState();
mSubjectTextEditor.requestFocus();
break;
case MENU_ADD_ATTACHMENT:
// Launch the add-attachment list dialog
showAddAttachmentDialog(false);
break;
case MENU_DISCARD:
mWorkingMessage.discard();
finish();
break;
case MENU_SEND:
if (isPreparedForSending()) {
confirmSendMessageIfNeeded();
}
break;
case MENU_SEARCH:
onSearchRequested();
break;
case MENU_DELETE_THREAD:
confirmDeleteThread(mConversation.getThreadId());
break;
case android.R.id.home:
case MENU_CONVERSATION_LIST:
exitComposeMessageActivity(new Runnable() {
@Override
public void run() {
goToConversationList();
}
});
break;
case MENU_CALL_RECIPIENT:
dialRecipient();
break;
case MENU_INSERT_SMILEY:
showSmileyDialog();
break;
case MENU_VIEW_CONTACT: {
// View the contact for the first (and only) recipient.
ContactList list = getRecipients();
if (list.size() == 1 && list.get(0).existsInDatabase()) {
Uri contactUri = list.get(0).getUri();
Intent intent = new Intent(Intent.ACTION_VIEW, contactUri);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
startActivity(intent);
}
break;
}
case MENU_ADD_ADDRESS_TO_CONTACTS:
mAddContactIntent = item.getIntent();
startActivityForResult(mAddContactIntent, REQUEST_CODE_ADD_CONTACT);
break;
case MENU_PREFERENCES: {
Intent intent = new Intent(this, MessagingPreferenceActivity.class);
startActivityIfNeeded(intent, -1);
break;
}
case MENU_DEBUG_DUMP:
mWorkingMessage.dump();
Conversation.dump();
LogTag.dumpInternalTables(this);
break;
}
return true;
}
private void confirmDeleteThread(long threadId) {
Conversation.startQueryHaveLockedMessages(mBackgroundQueryHandler,
threadId, ConversationList.HAVE_LOCKED_MESSAGES_TOKEN);
}
// static class SystemProperties { // TODO, temp class to get unbundling working
// static int getInt(String s, int value) {
// return value; // just return the default value or now
// }
// }
private void addAttachment(int type, boolean replace) {
// Calculate the size of the current slide if we're doing a replace so the
// slide size can optionally be used in computing how much room is left for an attachment.
int currentSlideSize = 0;
SlideshowModel slideShow = mWorkingMessage.getSlideshow();
if (replace && slideShow != null) {
WorkingMessage.removeThumbnailsFromCache(slideShow);
SlideModel slide = slideShow.get(0);
currentSlideSize = slide.getSlideSize();
}
switch (type) {
case AttachmentTypeSelectorAdapter.ADD_IMAGE:
MessageUtils.selectImage(this, REQUEST_CODE_ATTACH_IMAGE);
break;
case AttachmentTypeSelectorAdapter.TAKE_PICTURE: {
MessageUtils.capturePicture(this, REQUEST_CODE_TAKE_PICTURE);
break;
}
case AttachmentTypeSelectorAdapter.ADD_VIDEO:
MessageUtils.selectVideo(this, REQUEST_CODE_ATTACH_VIDEO);
break;
case AttachmentTypeSelectorAdapter.RECORD_VIDEO: {
long sizeLimit = computeAttachmentSizeLimit(slideShow, currentSlideSize);
if (sizeLimit > 0) {
MessageUtils.recordVideo(this, REQUEST_CODE_TAKE_VIDEO, sizeLimit);
} else {
Toast.makeText(this,
getString(R.string.message_too_big_for_video),
Toast.LENGTH_SHORT).show();
}
}
break;
case AttachmentTypeSelectorAdapter.ADD_SOUND:
MessageUtils.selectAudio(this, REQUEST_CODE_ATTACH_SOUND);
break;
case AttachmentTypeSelectorAdapter.RECORD_SOUND:
long sizeLimit = computeAttachmentSizeLimit(slideShow, currentSlideSize);
MessageUtils.recordSound(this, REQUEST_CODE_RECORD_SOUND, sizeLimit);
break;
case AttachmentTypeSelectorAdapter.ADD_SLIDESHOW:
editSlideshow();
break;
default:
break;
}
}
public static long computeAttachmentSizeLimit(SlideshowModel slideShow, int currentSlideSize) {
// Computer attachment size limit. Subtract 1K for some text.
long sizeLimit = MmsConfig.getMaxMessageSize() - SlideshowModel.SLIDESHOW_SLOP;
if (slideShow != null) {
sizeLimit -= slideShow.getCurrentMessageSize();
// We're about to ask the camera to capture some video (or the sound recorder
// to record some audio) which will eventually replace the content on the current
// slide. Since the current slide already has some content (which was subtracted
// out just above) and that content is going to get replaced, we can add the size of the
// current slide into the available space used to capture a video (or audio).
sizeLimit += currentSlideSize;
}
return sizeLimit;
}
private void showAddAttachmentDialog(final boolean replace) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setIcon(R.drawable.ic_dialog_attach);
builder.setTitle(R.string.add_attachment);
if (mAttachmentTypeSelectorAdapter == null) {
mAttachmentTypeSelectorAdapter = new AttachmentTypeSelectorAdapter(
this, AttachmentTypeSelectorAdapter.MODE_WITH_SLIDESHOW);
}
builder.setAdapter(mAttachmentTypeSelectorAdapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
addAttachment(mAttachmentTypeSelectorAdapter.buttonToCommand(which), replace);
dialog.dismiss();
}
});
builder.show();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (LogTag.VERBOSE) {
log("requestCode=" + requestCode + ", resultCode=" + resultCode + ", data=" + data);
}
mWaitingForSubActivity = false; // We're back!
if (mWorkingMessage.isFakeMmsForDraft()) {
// We no longer have to fake the fact we're an Mms. At this point we are or we aren't,
// based on attachments and other Mms attrs.
mWorkingMessage.removeFakeMmsForDraft();
}
if (requestCode == REQUEST_CODE_PICK) {
mWorkingMessage.asyncDeleteDraftSmsMessage(mConversation);
}
if (requestCode == REQUEST_CODE_ADD_CONTACT) {
// The user might have added a new contact. When we tell contacts to add a contact
// and tap "Done", we're not returned to Messaging. If we back out to return to
// messaging after adding a contact, the resultCode is RESULT_CANCELED. Therefore,
// assume a contact was added and get the contact and force our cached contact to
// get reloaded with the new info (such as contact name). After the
// contact is reloaded, the function onUpdate() in this file will get called
// and it will update the title bar, etc.
if (mAddContactIntent != null) {
String address =
mAddContactIntent.getStringExtra(ContactsContract.Intents.Insert.EMAIL);
if (address == null) {
address =
mAddContactIntent.getStringExtra(ContactsContract.Intents.Insert.PHONE);
}
if (address != null) {
Contact contact = Contact.get(address, false);
if (contact != null) {
contact.reload();
}
}
}
}
if (resultCode != RESULT_OK){
if (LogTag.VERBOSE) log("bail due to resultCode=" + resultCode);
return;
}
switch (requestCode) {
case REQUEST_CODE_CREATE_SLIDESHOW:
if (data != null) {
WorkingMessage newMessage = WorkingMessage.load(this, data.getData());
if (newMessage != null) {
mWorkingMessage = newMessage;
mWorkingMessage.setConversation(mConversation);
updateThreadIdIfRunning();
drawTopPanel(false);
updateSendButtonState();
invalidateOptionsMenu();
}
}
break;
case REQUEST_CODE_TAKE_PICTURE: {
// create a file based uri and pass to addImage(). We want to read the JPEG
// data directly from file (using UriImage) instead of decoding it into a Bitmap,
// which takes up too much memory and could easily lead to OOM.
File file = new File(TempFileProvider.getScrapPath(this));
Uri uri = Uri.fromFile(file);
// Remove the old captured picture's thumbnail from the cache
MmsApp.getApplication().getThumbnailManager().removeThumbnail(uri);
addImageAsync(uri, false);
break;
}
case REQUEST_CODE_ATTACH_IMAGE: {
if (data != null) {
addImageAsync(data.getData(), false);
}
break;
}
case REQUEST_CODE_TAKE_VIDEO:
Uri videoUri = TempFileProvider.renameScrapFile(".3gp", null, this);
// Remove the old captured video's thumbnail from the cache
MmsApp.getApplication().getThumbnailManager().removeThumbnail(videoUri);
addVideoAsync(videoUri, false); // can handle null videoUri
break;
case REQUEST_CODE_ATTACH_VIDEO:
if (data != null) {
addVideoAsync(data.getData(), false);
}
break;
case REQUEST_CODE_ATTACH_SOUND: {
Uri uri = (Uri) data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
if (Settings.System.DEFAULT_RINGTONE_URI.equals(uri)) {
break;
}
addAudio(uri);
break;
}
case REQUEST_CODE_RECORD_SOUND:
if (data != null) {
addAudio(data.getData());
}
break;
case REQUEST_CODE_ECM_EXIT_DIALOG:
boolean outOfEmergencyMode = data.getBooleanExtra(EXIT_ECM_RESULT, false);
if (outOfEmergencyMode) {
sendMessage(false);
}
break;
case REQUEST_CODE_PICK:
if (data != null) {
processPickResult(data);
}
break;
default:
if (LogTag.VERBOSE) log("bail due to unknown requestCode=" + requestCode);
break;
}
}
private void processPickResult(final Intent data) {
// The EXTRA_PHONE_URIS stores the phone's urls that were selected by user in the
// multiple phone picker.
final Parcelable[] uris =
data.getParcelableArrayExtra(Intents.EXTRA_PHONE_URIS);
final int recipientCount = uris != null ? uris.length : 0;
final int recipientLimit = MmsConfig.getRecipientLimit();
if (recipientLimit != Integer.MAX_VALUE && recipientCount > recipientLimit) {
new AlertDialog.Builder(this)
.setMessage(getString(R.string.too_many_recipients, recipientCount, recipientLimit))
.setPositiveButton(android.R.string.ok, null)
.create().show();
return;
}
final Handler handler = new Handler();
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle(getText(R.string.pick_too_many_recipients));
progressDialog.setMessage(getText(R.string.adding_recipients));
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);
final Runnable showProgress = new Runnable() {
@Override
public void run() {
progressDialog.show();
}
};
// Only show the progress dialog if we can not finish off parsing the return data in 1s,
// otherwise the dialog could flicker.
handler.postDelayed(showProgress, 1000);
new Thread(new Runnable() {
@Override
public void run() {
final ContactList list;
try {
list = ContactList.blockingGetByUris(uris);
} finally {
handler.removeCallbacks(showProgress);
progressDialog.dismiss();
}
// TODO: there is already code to update the contact header widget and recipients
// editor if the contacts change. we can re-use that code.
final Runnable populateWorker = new Runnable() {
@Override
public void run() {
mRecipientsEditor.populate(list);
updateTitle(list);
}
};
handler.post(populateWorker);
}
}, "ComoseMessageActivity.processPickResult").start();
}
private final ResizeImageResultCallback mResizeImageCallback = new ResizeImageResultCallback() {
// TODO: make this produce a Uri, that's what we want anyway
@Override
public void onResizeResult(PduPart part, boolean append) {
if (part == null) {
handleAddAttachmentError(WorkingMessage.UNKNOWN_ERROR, R.string.type_picture);
return;
}
Context context = ComposeMessageActivity.this;
PduPersister persister = PduPersister.getPduPersister(context);
int result;
Uri messageUri = mWorkingMessage.saveAsMms(true);
if (messageUri == null) {
result = WorkingMessage.UNKNOWN_ERROR;
} else {
try {
Uri dataUri = persister.persistPart(part, ContentUris.parseId(messageUri));
result = mWorkingMessage.setAttachment(WorkingMessage.IMAGE, dataUri, append);
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("ResizeImageResultCallback: dataUri=" + dataUri);
}
} catch (MmsException e) {
result = WorkingMessage.UNKNOWN_ERROR;
}
}
handleAddAttachmentError(result, R.string.type_picture);
}
};
private void handleAddAttachmentError(final int error, final int mediaTypeStringId) {
if (error == WorkingMessage.OK) {
return;
}
Log.d(TAG, "handleAddAttachmentError: " + error);
runOnUiThread(new Runnable() {
@Override
public void run() {
Resources res = getResources();
String mediaType = res.getString(mediaTypeStringId);
String title, message;
switch(error) {
case WorkingMessage.UNKNOWN_ERROR:
message = res.getString(R.string.failed_to_add_media, mediaType);
Toast.makeText(ComposeMessageActivity.this, message, Toast.LENGTH_SHORT).show();
return;
case WorkingMessage.UNSUPPORTED_TYPE:
title = res.getString(R.string.unsupported_media_format, mediaType);
message = res.getString(R.string.select_different_media, mediaType);
break;
case WorkingMessage.MESSAGE_SIZE_EXCEEDED:
title = res.getString(R.string.exceed_message_size_limitation, mediaType);
message = res.getString(R.string.failed_to_add_media, mediaType);
break;
case WorkingMessage.IMAGE_TOO_LARGE:
title = res.getString(R.string.failed_to_resize_image);
message = res.getString(R.string.resize_image_error_information);
break;
default:
throw new IllegalArgumentException("unknown error " + error);
}
MessageUtils.showErrorDialog(ComposeMessageActivity.this, title, message);
}
});
}
private void addImageAsync(final Uri uri, final boolean append) {
getAsyncDialog().runAsync(new Runnable() {
@Override
public void run() {
addImage(uri, append);
}
}, null, R.string.adding_attachments_title);
}
private void addImage(Uri uri, boolean append) {
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("append=" + append + ", uri=" + uri);
}
int result = mWorkingMessage.setAttachment(WorkingMessage.IMAGE, uri, append);
if (result == WorkingMessage.IMAGE_TOO_LARGE ||
result == WorkingMessage.MESSAGE_SIZE_EXCEEDED) {
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("resize image " + uri);
}
MessageUtils.resizeImageAsync(ComposeMessageActivity.this,
uri, mAttachmentEditorHandler, mResizeImageCallback, append);
return;
}
handleAddAttachmentError(result, R.string.type_picture);
}
private void addVideoAsync(final Uri uri, final boolean append) {
getAsyncDialog().runAsync(new Runnable() {
@Override
public void run() {
addVideo(uri, append);
}
}, null, R.string.adding_attachments_title);
}
private void addVideo(Uri uri, boolean append) {
if (uri != null) {
int result = mWorkingMessage.setAttachment(WorkingMessage.VIDEO, uri, append);
handleAddAttachmentError(result, R.string.type_video);
}
}
private void addAudio(Uri uri) {
int result = mWorkingMessage.setAttachment(WorkingMessage.AUDIO, uri, false);
handleAddAttachmentError(result, R.string.type_audio);
}
AsyncDialog getAsyncDialog() {
if (mAsyncDialog == null) {
mAsyncDialog = new AsyncDialog(this);
}
return mAsyncDialog;
}
private boolean handleForwardedMessage() {
Intent intent = getIntent();
// If this is a forwarded message, it will have an Intent extra
// indicating so. If not, bail out.
if (intent.getBooleanExtra("forwarded_message", false) == false) {
return false;
}
Uri uri = intent.getParcelableExtra("msg_uri");
if (Log.isLoggable(LogTag.APP, Log.DEBUG)) {
log("" + uri);
}
if (uri != null) {
mWorkingMessage = WorkingMessage.load(this, uri);
mWorkingMessage.setSubject(intent.getStringExtra("subject"), false);
} else {
mWorkingMessage.setText(intent.getStringExtra("sms_body"));
}
// let's clear the message thread for forwarded messages
mMsgListAdapter.changeCursor(null);
return true;
}
// Handle send actions, where we're told to send a picture(s) or text.
private boolean handleSendIntent() {
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras == null) {
return false;
}
final String mimeType = intent.getType();
String action = intent.getAction();
if (Intent.ACTION_SEND.equals(action)) {
if (extras.containsKey(Intent.EXTRA_STREAM)) {
final Uri uri = (Uri)extras.getParcelable(Intent.EXTRA_STREAM);
getAsyncDialog().runAsync(new Runnable() {
@Override
public void run() {
addAttachment(mimeType, uri, false);
}
}, null, R.string.adding_attachments_title);
return true;
} else if (extras.containsKey(Intent.EXTRA_TEXT)) {
mWorkingMessage.setText(extras.getString(Intent.EXTRA_TEXT));
return true;
}
} else if (Intent.ACTION_SEND_MULTIPLE.equals(action) &&
extras.containsKey(Intent.EXTRA_STREAM)) {
SlideshowModel slideShow = mWorkingMessage.getSlideshow();
final ArrayList<Parcelable> uris = extras.getParcelableArrayList(Intent.EXTRA_STREAM);
int currentSlideCount = slideShow != null ? slideShow.size() : 0;
int importCount = uris.size();
if (importCount + currentSlideCount > SlideshowEditor.MAX_SLIDE_NUM) {
importCount = Math.min(SlideshowEditor.MAX_SLIDE_NUM - currentSlideCount,
importCount);
Toast.makeText(ComposeMessageActivity.this,
getString(R.string.too_many_attachments,
SlideshowEditor.MAX_SLIDE_NUM, importCount),
Toast.LENGTH_LONG).show();
}
// Attach all the pictures/videos asynchronously off of the UI thread.
// Show a progress dialog if adding all the slides hasn't finished
// within half a second.
final int numberToImport = importCount;
getAsyncDialog().runAsync(new Runnable() {
@Override
public void run() {
for (int i = 0; i < numberToImport; i++) {
Parcelable uri = uris.get(i);
addAttachment(mimeType, (Uri) uri, true);
}
}
}, null, R.string.adding_attachments_title);
return true;
}
return false;
}
// mVideoUri will look like this: content://media/external/video/media
private static final String mVideoUri = Video.Media.getContentUri("external").toString();
// mImageUri will look like this: content://media/external/images/media
private static final String mImageUri = Images.Media.getContentUri("external").toString();
private void addAttachment(String type, Uri uri, boolean append) {
if (uri != null) {
// When we're handling Intent.ACTION_SEND_MULTIPLE, the passed in items can be
// videos, and/or images, and/or some other unknown types we don't handle. When
// a single attachment is "shared" the type will specify an image or video. When
// there are multiple types, the type passed in is "*/*". In that case, we've got
// to look at the uri to figure out if it is an image or video.
boolean wildcard = "*/*".equals(type);
if (type.startsWith("image/") || (wildcard && uri.toString().startsWith(mImageUri))) {
addImage(uri, append);
} else if (type.startsWith("video/") ||
(wildcard && uri.toString().startsWith(mVideoUri))) {
addVideo(uri, append);
}
}
}
private String getResourcesString(int id, String mediaName) {
Resources r = getResources();
return r.getString(id, mediaName);
}
private void drawBottomPanel() {
// Reset the counter for text editor.
resetCounter();
if (mWorkingMessage.hasSlideshow()) {
mBottomPanel.setVisibility(View.GONE);
mAttachmentEditor.requestFocus();
return;
}
mBottomPanel.setVisibility(View.VISIBLE);
CharSequence text = mWorkingMessage.getText();
// TextView.setTextKeepState() doesn't like null input.
if (text != null) {
mTextEditor.setTextKeepState(text);
} else {
mTextEditor.setText("");
}
}
private void drawTopPanel(boolean showSubjectEditor) {
boolean showingAttachment = mAttachmentEditor.update(mWorkingMessage);
mAttachmentEditorScrollView.setVisibility(showingAttachment ? View.VISIBLE : View.GONE);
showSubjectEditor(showSubjectEditor || mWorkingMessage.hasSubject());
}
//==========================================================
// Interface methods
//==========================================================
@Override
public void onClick(View v) {
if ((v == mSendButtonSms || v == mSendButtonMms) && isPreparedForSending()) {
confirmSendMessageIfNeeded();
} else if ((v == mRecipientsPicker)) {
launchMultiplePhonePicker();
}
}
private void launchMultiplePhonePicker() {
Intent intent = new Intent(Intents.ACTION_GET_MULTIPLE_PHONES);
intent.addCategory("android.intent.category.DEFAULT");
intent.setType(Phone.CONTENT_TYPE);
// We have to wait for the constructing complete.
ContactList contacts = mRecipientsEditor.constructContactsFromInput(true);
int urisCount = 0;
Uri[] uris = new Uri[contacts.size()];
urisCount = 0;
for (Contact contact : contacts) {
if (Contact.CONTACT_METHOD_TYPE_PHONE == contact.getContactMethodType()) {
uris[urisCount++] = contact.getPhoneUri();
}
}
if (urisCount > 0) {
intent.putExtra(Intents.EXTRA_PHONE_URIS, uris);
}
startActivityForResult(intent, REQUEST_CODE_PICK);
}
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (event != null) {
// if shift key is down, then we want to insert the '\n' char in the TextView;
// otherwise, the default action is to send the message.
if (!event.isShiftPressed()) {
if (isPreparedForSending()) {
confirmSendMessageIfNeeded();
}
return true;
}
return false;
}
if (isPreparedForSending()) {
confirmSendMessageIfNeeded();
}
return true;
}
private final TextWatcher mTextEditorWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// This is a workaround for bug 1609057. Since onUserInteraction() is
// not called when the user touches the soft keyboard, we pretend it was
// called when textfields changes. This should be removed when the bug
// is fixed.
onUserInteraction();
mWorkingMessage.setText(s);
updateSendButtonState();
updateCounter(s, start, before, count);
ensureCorrectButtonHeight();
}
@Override
public void afterTextChanged(Editable s) {
}
};
/**
* Ensures that if the text edit box extends past two lines then the
* button will be shifted up to allow enough space for the character
* counter string to be placed beneath it.
*/
private void ensureCorrectButtonHeight() {
int currentTextLines = mTextEditor.getLineCount();
if (currentTextLines <= 2) {
mTextCounter.setVisibility(View.GONE);
}
else if (currentTextLines > 2 && mTextCounter.getVisibility() == View.GONE) {
// Making the counter invisible ensures that it is used to correctly
// calculate the position of the send button even if we choose not to
// display the text.
mTextCounter.setVisibility(View.INVISIBLE);
}
}
private final TextWatcher mSubjectEditorWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
mWorkingMessage.setSubject(s, true);
updateSendButtonState();
}
@Override
public void afterTextChanged(Editable s) { }
};
//==========================================================
// Private methods
//==========================================================
/**
* Initialize all UI elements from resources.
*/
private void initResourceRefs() {
mMsgListView = (MessageListView) findViewById(R.id.history);
mMsgListView.setDivider(null); // no divider so we look like IM conversation.
// called to enable us to show some padding between the message list and the
// input field but when the message list is scrolled that padding area is filled
// in with message content
mMsgListView.setClipToPadding(false);
mMsgListView.setOnSizeChangedListener(new OnSizeChangedListener() {
public void onSizeChanged(int width, int height, int oldWidth, int oldHeight) {
// The message list view changed size, most likely because the keyboard
// appeared or disappeared or the user typed/deleted chars in the message
// box causing it to change its height when expanding/collapsing to hold more
// lines of text.
smoothScrollToEnd(false, height - oldHeight);
}
});
mBottomPanel = findViewById(R.id.bottom_panel);
mTextEditor = (EditText) findViewById(R.id.embedded_text_editor);
mTextEditor.setOnEditorActionListener(this);
mTextEditor.addTextChangedListener(mTextEditorWatcher);
mTextEditor.setFilters(new InputFilter[] {
new LengthFilter(MmsConfig.getMaxTextLimit())});
mTextCounter = (TextView) findViewById(R.id.text_counter);
mSendButtonMms = (TextView) findViewById(R.id.send_button_mms);
mSendButtonSms = (ImageButton) findViewById(R.id.send_button_sms);
mSendButtonMms.setOnClickListener(this);
mSendButtonSms.setOnClickListener(this);
mTopPanel = findViewById(R.id.recipients_subject_linear);
mTopPanel.setFocusable(false);
mAttachmentEditor = (AttachmentEditor) findViewById(R.id.attachment_editor);
mAttachmentEditor.setHandler(mAttachmentEditorHandler);
mAttachmentEditorScrollView = findViewById(R.id.attachment_editor_scroll_view);
}
private void confirmDeleteDialog(OnClickListener listener, boolean locked) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setMessage(locked ? R.string.confirm_delete_locked_message :
R.string.confirm_delete_message);
builder.setPositiveButton(R.string.delete, listener);
builder.setNegativeButton(R.string.no, null);
builder.show();
}
void undeliveredMessageDialog(long date) {
String body;
if (date >= 0) {
body = getString(R.string.undelivered_msg_dialog_body,
MessageUtils.formatTimeStampString(this, date));
} else {
// FIXME: we can not get sms retry time.
body = getString(R.string.undelivered_sms_dialog_body);
}
Toast.makeText(this, body, Toast.LENGTH_LONG).show();
}
private void startMsgListQuery() {
startMsgListQuery(MESSAGE_LIST_QUERY_TOKEN);
}
private void startMsgListQuery(int token) {
Uri conversationUri = mConversation.getUri();
if (conversationUri == null) {
log("##### startMsgListQuery: conversationUri is null, bail!");
return;
}
long threadId = mConversation.getThreadId();
if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("startMsgListQuery for " + conversationUri + ", threadId=" + threadId +
" token: " + token + " mConversation: " + mConversation);
}
// Cancel any pending queries
mBackgroundQueryHandler.cancelOperation(token);
try {
// Kick off the new query
mBackgroundQueryHandler.startQuery(
token,
threadId /* cookie */,
conversationUri,
PROJECTION,
null, null, null);
} catch (SQLiteException e) {
SqliteWrapper.checkSQLiteException(this, e);
}
}
private void initMessageList() {
if (mMsgListAdapter != null) {
return;
}
String highlightString = getIntent().getStringExtra("highlight");
Pattern highlight = highlightString == null
? null
: Pattern.compile("\\b" + Pattern.quote(highlightString), Pattern.CASE_INSENSITIVE);
// Initialize the list adapter with a null cursor.
mMsgListAdapter = new MessageListAdapter(this, null, mMsgListView, true, highlight);
mMsgListAdapter.setOnDataSetChangedListener(mDataSetChangedListener);
mMsgListAdapter.setMsgListItemHandler(mMessageListItemHandler);
mMsgListView.setAdapter(mMsgListAdapter);
mMsgListView.setItemsCanFocus(false);
mMsgListView.setVisibility(View.VISIBLE);
mMsgListView.setOnCreateContextMenuListener(mMsgListMenuCreateListener);
mMsgListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (view != null) {
((MessageListItem) view).onMessageListItemClick();
}
}
});
}
private void loadDraft() {
if (mWorkingMessage.isWorthSaving()) {
Log.w(TAG, "called with non-empty working message");
return;
}
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("call WorkingMessage.loadDraft");
}
mWorkingMessage = WorkingMessage.loadDraft(this, mConversation,
new Runnable() {
@Override
public void run() {
drawTopPanel(false);
drawBottomPanel();
}
});
}
private void saveDraft(boolean isStopping) {
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
LogTag.debug("saveDraft");
}
// TODO: Do something better here. Maybe make discard() legal
// to call twice and make isEmpty() return true if discarded
// so it is caught in the clause above this one?
if (mWorkingMessage.isDiscarded()) {
return;
}
if (!mWaitingForSubActivity &&
!mWorkingMessage.isWorthSaving() &&
(!isRecipientsEditorVisible() || recipientCount() == 0)) {
if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("not worth saving, discard WorkingMessage and bail");
}
mWorkingMessage.discard();
return;
}
mWorkingMessage.saveDraft(isStopping);
if (mToastForDraftSave) {
Toast.makeText(this, R.string.message_saved_as_draft,
Toast.LENGTH_SHORT).show();
}
}
private boolean isPreparedForSending() {
int recipientCount = recipientCount();
return recipientCount > 0 && recipientCount <= MmsConfig.getRecipientLimit() &&
(mWorkingMessage.hasAttachment() ||
mWorkingMessage.hasText() ||
mWorkingMessage.hasSubject());
}
private int recipientCount() {
int recipientCount;
// To avoid creating a bunch of invalid Contacts when the recipients
// editor is in flux, we keep the recipients list empty. So if the
// recipients editor is showing, see if there is anything in it rather
// than consulting the empty recipient list.
if (isRecipientsEditorVisible()) {
recipientCount = mRecipientsEditor.getRecipientCount();
} else {
recipientCount = getRecipients().size();
}
return recipientCount;
}
private void sendMessage(boolean bCheckEcmMode) {
if (bCheckEcmMode) {
// TODO: expose this in telephony layer for SDK build
String inEcm = SystemProperties.get(TelephonyProperties.PROPERTY_INECM_MODE);
if (Boolean.parseBoolean(inEcm)) {
try {
startActivityForResult(
new Intent(TelephonyIntents.ACTION_SHOW_NOTICE_ECM_BLOCK_OTHERS, null),
REQUEST_CODE_ECM_EXIT_DIALOG);
return;
} catch (ActivityNotFoundException e) {
// continue to send message
Log.e(TAG, "Cannot find EmergencyCallbackModeExitDialog", e);
}
}
}
if (!mSendingMessage) {
if (LogTag.SEVERE_WARNING) {
String sendingRecipients = mConversation.getRecipients().serialize();
if (!sendingRecipients.equals(mDebugRecipients)) {
String workingRecipients = mWorkingMessage.getWorkingRecipients();
if (!mDebugRecipients.equals(workingRecipients)) {
LogTag.warnPossibleRecipientMismatch("ComposeMessageActivity.sendMessage" +
" recipients in window: \"" +
mDebugRecipients + "\" differ from recipients from conv: \"" +
sendingRecipients + "\" and working recipients: " +
workingRecipients, this);
}
}
sanityCheckConversation();
}
// send can change the recipients. Make sure we remove the listeners first and then add
// them back once the recipient list has settled.
removeRecipientsListeners();
mWorkingMessage.send(mDebugRecipients);
mSentMessage = true;
mSendingMessage = true;
addRecipientsListeners();
mScrollOnSend = true; // in the next onQueryComplete, scroll the list to the end.
}
// But bail out if we are supposed to exit after the message is sent.
if (mExitOnSent) {
finish();
}
}
private void resetMessage() {
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("");
}
// Make the attachment editor hide its view.
mAttachmentEditor.hideView();
mAttachmentEditorScrollView.setVisibility(View.GONE);
// Hide the subject editor.
showSubjectEditor(false);
// Focus to the text editor.
mTextEditor.requestFocus();
// We have to remove the text change listener while the text editor gets cleared and
// we subsequently turn the message back into SMS. When the listener is listening while
// doing the clearing, it's fighting to update its counts and itself try and turn
// the message one way or the other.
mTextEditor.removeTextChangedListener(mTextEditorWatcher);
// Clear the text box.
TextKeyListener.clear(mTextEditor.getText());
mWorkingMessage.clearConversation(mConversation, false);
mWorkingMessage = WorkingMessage.createEmpty(this);
mWorkingMessage.setConversation(mConversation);
hideRecipientEditor();
drawBottomPanel();
// "Or not", in this case.
updateSendButtonState();
// Our changes are done. Let the listener respond to text changes once again.
mTextEditor.addTextChangedListener(mTextEditorWatcher);
// Close the soft on-screen keyboard if we're in landscape mode so the user can see the
// conversation.
if (mIsLandscape) {
hideKeyboard();
}
mLastRecipientCount = 0;
mSendingMessage = false;
invalidateOptionsMenu();
}
private void hideKeyboard() {
InputMethodManager inputMethodManager =
(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(mTextEditor.getWindowToken(), 0);
}
private void updateSendButtonState() {
boolean enable = false;
if (isPreparedForSending()) {
// When the type of attachment is slideshow, we should
// also hide the 'Send' button since the slideshow view
// already has a 'Send' button embedded.
if (!mWorkingMessage.hasSlideshow()) {
enable = true;
} else {
mAttachmentEditor.setCanSend(true);
}
} else if (null != mAttachmentEditor){
mAttachmentEditor.setCanSend(false);
}
boolean requiresMms = mWorkingMessage.requiresMms();
View sendButton = showSmsOrMmsSendButton(requiresMms);
sendButton.setEnabled(enable);
sendButton.setFocusable(enable);
}
private long getMessageDate(Uri uri) {
if (uri != null) {
Cursor cursor = SqliteWrapper.query(this, mContentResolver,
uri, new String[] { Mms.DATE }, null, null, null);
if (cursor != null) {
try {
if ((cursor.getCount() == 1) && cursor.moveToFirst()) {
return cursor.getLong(0) * 1000L;
}
} finally {
cursor.close();
}
}
}
return NO_DATE_FOR_DIALOG;
}
private void initActivityState(Bundle bundle) {
Intent intent = getIntent();
if (bundle != null) {
setIntent(getIntent().setAction(Intent.ACTION_VIEW));
String recipients = bundle.getString("recipients");
if (LogTag.VERBOSE) log("get mConversation by recipients " + recipients);
mConversation = Conversation.get(this,
ContactList.getByNumbers(recipients,
false /* don't block */, true /* replace number */), false);
addRecipientsListeners();
mExitOnSent = bundle.getBoolean("exit_on_sent", false);
mWorkingMessage.readStateFromBundle(bundle);
return;
}
// If we have been passed a thread_id, use that to find our conversation.
long threadId = intent.getLongExtra("thread_id", 0);
if (threadId > 0) {
if (LogTag.VERBOSE) log("get mConversation by threadId " + threadId);
mConversation = Conversation.get(this, threadId, false);
} else {
Uri intentData = intent.getData();
if (intentData != null) {
// try to get a conversation based on the data URI passed to our intent.
if (LogTag.VERBOSE) log("get mConversation by intentData " + intentData);
mConversation = Conversation.get(this, intentData, false);
mWorkingMessage.setText(getBody(intentData));
} else {
// special intent extra parameter to specify the address
String address = intent.getStringExtra("address");
if (!TextUtils.isEmpty(address)) {
if (LogTag.VERBOSE) log("get mConversation by address " + address);
mConversation = Conversation.get(this, ContactList.getByNumbers(address,
false /* don't block */, true /* replace number */), false);
} else {
if (LogTag.VERBOSE) log("create new conversation");
mConversation = Conversation.createNew(this);
}
}
}
addRecipientsListeners();
updateThreadIdIfRunning();
mExitOnSent = intent.getBooleanExtra("exit_on_sent", false);
if (intent.hasExtra("sms_body")) {
mWorkingMessage.setText(intent.getStringExtra("sms_body"));
}
mWorkingMessage.setSubject(intent.getStringExtra("subject"), false);
}
private void initFocus() {
if (!mIsKeyboardOpen) {
return;
}
// If the recipients editor is visible, there is nothing in it,
// and the text editor is not already focused, focus the
// recipients editor.
if (isRecipientsEditorVisible()
&& TextUtils.isEmpty(mRecipientsEditor.getText())
&& !mTextEditor.isFocused()) {
mRecipientsEditor.requestFocus();
return;
}
// If we decided not to focus the recipients editor, focus the text editor.
mTextEditor.requestFocus();
}
private final MessageListAdapter.OnDataSetChangedListener
mDataSetChangedListener = new MessageListAdapter.OnDataSetChangedListener() {
@Override
public void onDataSetChanged(MessageListAdapter adapter) {
mPossiblePendingNotification = true;
checkPendingNotification();
}
@Override
public void onContentChanged(MessageListAdapter adapter) {
startMsgListQuery();
}
};
private void checkPendingNotification() {
if (mPossiblePendingNotification && hasWindowFocus()) {
mConversation.markAsRead();
mPossiblePendingNotification = false;
}
}
/**
* smoothScrollToEnd will scroll the message list to the bottom if the list is already near
* the bottom. Typically this is called to smooth scroll a newly received message into view.
* It's also called when sending to scroll the list to the bottom, regardless of where it is,
* so the user can see the just sent message. This function is also called when the message
* list view changes size because the keyboard state changed or the compose message field grew.
*
* @param force always scroll to the bottom regardless of current list position
* @param listSizeChange the amount the message list view size has vertically changed
*/
private void smoothScrollToEnd(boolean force, int listSizeChange) {
int last = mMsgListView.getLastVisiblePosition();
if (last <= 0) {
if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
Log.v(TAG, "smoothScrollToEnd: last=" + last + ", mMsgListView not ready");
}
return;
}
View lastChild = mMsgListView.getChildAt(last - mMsgListView.getFirstVisiblePosition());
int bottom = 0;
if (lastChild != null) {
bottom = lastChild.getBottom();
}
int newPosition = mMsgListAdapter.getCount() - 1;
if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
Log.v(TAG, "smoothScrollToEnd newPosition: " + newPosition +
" mLastSmoothScrollPosition: " + mLastSmoothScrollPosition +
" first: " + mMsgListView.getFirstVisiblePosition() +
" last: " + last +
" bottom: " + bottom +
" bottom + listSizeChange: " + (bottom + listSizeChange) +
" mMsgListView.getHeight() - mMsgListView.getPaddingBottom(): " +
(mMsgListView.getHeight() - mMsgListView.getPaddingBottom()) +
" listSizeChange: " + listSizeChange);
}
// Only scroll if the list if we're responding to a newly sent message (force == true) or
// the list is already scrolled to the end. This code also has to handle the case where
// the listview has changed size (from the keyboard coming up or down or the message entry
// field growing/shrinking) and it uses that grow/shrink factor in listSizeChange to
// compute whether the list was at the end before the resize took place.
// For example, when the keyboard comes up, listSizeChange will be negative, something
// like -524. The lastChild listitem's bottom value will be the old value before the
// keyboard became visible but the size of the list will have changed. The test below
// add listSizeChange to bottom to figure out if the old position was already scrolled
// to the bottom.
if (force || ((listSizeChange != 0 || newPosition != mLastSmoothScrollPosition) &&
bottom + listSizeChange <=
mMsgListView.getHeight() - mMsgListView.getPaddingBottom())) {
if (Math.abs(listSizeChange) > SMOOTH_SCROLL_THRESHOLD) {
// When the keyboard comes up, the window manager initiates a cross fade
// animation that conflicts with smooth scroll. Handle that case by jumping the
// list directly to the end.
if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
Log.v(TAG, "keyboard state changed. setSelection=" + newPosition);
}
mMsgListView.setSelection(newPosition);
} else if (newPosition - last > MAX_ITEMS_TO_INVOKE_SCROLL_SHORTCUT) {
if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
Log.v(TAG, "too many to scroll, setSelection=" + newPosition);
}
mMsgListView.setSelection(newPosition);
} else {
if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
Log.v(TAG, "smooth scroll to " + newPosition);
}
mMsgListView.smoothScrollToPosition(newPosition);
mLastSmoothScrollPosition = newPosition;
}
}
}
private final class BackgroundQueryHandler extends ConversationQueryHandler {
public BackgroundQueryHandler(ContentResolver contentResolver) {
super(contentResolver);
}
@Override
protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
switch(token) {
case MESSAGE_LIST_QUERY_TOKEN:
mConversation.blockMarkAsRead(false);
// check consistency between the query result and 'mConversation'
long tid = (Long) cookie;
if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("##### onQueryComplete: msg history result for threadId " + tid);
}
if (tid != mConversation.getThreadId()) {
log("onQueryComplete: msg history query result is for threadId " +
tid + ", but mConversation has threadId " +
mConversation.getThreadId() + " starting a new query");
if (cursor != null) {
cursor.close();
}
startMsgListQuery();
return;
}
// check consistency b/t mConversation & mWorkingMessage.mConversation
ComposeMessageActivity.this.sanityCheckConversation();
int newSelectionPos = -1;
long targetMsgId = getIntent().getLongExtra("select_id", -1);
if (targetMsgId != -1) {
cursor.moveToPosition(-1);
while (cursor.moveToNext()) {
long msgId = cursor.getLong(COLUMN_ID);
if (msgId == targetMsgId) {
newSelectionPos = cursor.getPosition();
break;
}
}
} else if (mSavedScrollPosition != -1) {
// remember the saved scroll position before the activity is paused.
// reset it after the message list query is done
newSelectionPos = mSavedScrollPosition;
mSavedScrollPosition = -1;
}
mMsgListAdapter.changeCursor(cursor);
if (newSelectionPos != -1) {
mMsgListView.setSelection(newSelectionPos);
} else {
// mScrollOnSend is set when we send a message. We always want to scroll
// the message list to the end when we send a message, but have to wait
// until the DB has changed.
smoothScrollToEnd(mScrollOnSend, 0);
mScrollOnSend = false;
}
// Adjust the conversation's message count to match reality. The
// conversation's message count is eventually used in
// WorkingMessage.clearConversation to determine whether to delete
// the conversation or not.
mConversation.setMessageCount(mMsgListAdapter.getCount());
// Once we have completed the query for the message history, if
// there is nothing in the cursor and we are not composing a new
// message, we must be editing a draft in a new conversation (unless
// mSentMessage is true).
// Show the recipients editor to give the user a chance to add
// more people before the conversation begins.
if (cursor.getCount() == 0 && !isRecipientsEditorVisible() && !mSentMessage) {
initRecipientsEditor();
}
// FIXME: freshing layout changes the focused view to an unexpected
// one, set it back to TextEditor forcely.
mTextEditor.requestFocus();
invalidateOptionsMenu(); // some menu items depend on the adapter's count
return;
case ConversationList.HAVE_LOCKED_MESSAGES_TOKEN:
@SuppressWarnings("unchecked")
ArrayList<Long> threadIds = (ArrayList<Long>)cookie;
ConversationList.confirmDeleteThreadDialog(
new ConversationList.DeleteThreadListener(threadIds,
mBackgroundQueryHandler, ComposeMessageActivity.this),
threadIds,
cursor != null && cursor.getCount() > 0,
ComposeMessageActivity.this);
if (cursor != null) {
cursor.close();
}
break;
case MESSAGE_LIST_QUERY_AFTER_DELETE_TOKEN:
// check consistency between the query result and 'mConversation'
tid = (Long) cookie;
if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("##### onQueryComplete (after delete): msg history result for threadId "
+ tid);
}
if (cursor == null) {
return;
}
if (tid > 0 && cursor.getCount() == 0) {
// We just deleted the last message and the thread will get deleted
// by a trigger in the database. Clear the threadId so next time we
// need the threadId a new thread will get created.
log("##### MESSAGE_LIST_QUERY_AFTER_DELETE_TOKEN clearing thread id: "
+ tid);
Conversation conv = Conversation.get(ComposeMessageActivity.this, tid,
false);
if (conv != null) {
conv.clearThreadId();
conv.setDraftState(false);
}
}
cursor.close();
}
}
@Override
protected void onDeleteComplete(int token, Object cookie, int result) {
super.onDeleteComplete(token, cookie, result);
switch(token) {
case ConversationList.DELETE_CONVERSATION_TOKEN:
mConversation.setMessageCount(0);
// fall through
case DELETE_MESSAGE_TOKEN:
// Update the notification for new messages since they
// may be deleted.
MessagingNotification.nonBlockingUpdateNewMessageIndicator(
ComposeMessageActivity.this, MessagingNotification.THREAD_NONE, false);
// Update the notification for failed messages since they
// may be deleted.
updateSendFailedNotification();
break;
}
// If we're deleting the whole conversation, throw away
// our current working message and bail.
if (token == ConversationList.DELETE_CONVERSATION_TOKEN) {
ContactList recipients = mConversation.getRecipients();
mWorkingMessage.discard();
// Remove any recipients referenced by this single thread from the
// contacts cache. It's possible for two or more threads to reference
// the same contact. That's ok if we remove it. We'll recreate that contact
// when we init all Conversations below.
if (recipients != null) {
for (Contact contact : recipients) {
contact.removeFromCache();
}
}
// Make sure the conversation cache reflects the threads in the DB.
Conversation.init(ComposeMessageActivity.this);
finish();
} else if (token == DELETE_MESSAGE_TOKEN) {
// Check to see if we just deleted the last message
startMsgListQuery(MESSAGE_LIST_QUERY_AFTER_DELETE_TOKEN);
}
}
}
private void showSmileyDialog() {
if (mSmileyDialog == null) {
int[] icons = SmileyParser.DEFAULT_SMILEY_RES_IDS;
String[] names = getResources().getStringArray(
SmileyParser.DEFAULT_SMILEY_NAMES);
final String[] texts = getResources().getStringArray(
SmileyParser.DEFAULT_SMILEY_TEXTS);
final int N = names.length;
List<Map<String, ?>> entries = new ArrayList<Map<String, ?>>();
for (int i = 0; i < N; i++) {
// We might have different ASCII for the same icon, skip it if
// the icon is already added.
boolean added = false;
for (int j = 0; j < i; j++) {
if (icons[i] == icons[j]) {
added = true;
break;
}
}
if (!added) {
HashMap<String, Object> entry = new HashMap<String, Object>();
entry. put("icon", icons[i]);
entry. put("name", names[i]);
entry.put("text", texts[i]);
entries.add(entry);
}
}
final SimpleAdapter a = new SimpleAdapter(
this,
entries,
R.layout.smiley_menu_item,
new String[] {"icon", "name", "text"},
new int[] {R.id.smiley_icon, R.id.smiley_name, R.id.smiley_text});
SimpleAdapter.ViewBinder viewBinder = new SimpleAdapter.ViewBinder() {
@Override
public boolean setViewValue(View view, Object data, String textRepresentation) {
if (view instanceof ImageView) {
Drawable img = getResources().getDrawable((Integer)data);
((ImageView)view).setImageDrawable(img);
return true;
}
return false;
}
};
a.setViewBinder(viewBinder);
AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setTitle(getString(R.string.menu_insert_smiley));
b.setCancelable(true);
b.setAdapter(a, new DialogInterface.OnClickListener() {
@Override
@SuppressWarnings("unchecked")
public final void onClick(DialogInterface dialog, int which) {
HashMap<String, Object> item = (HashMap<String, Object>) a.getItem(which);
String smiley = (String)item.get("text");
if (mSubjectTextEditor != null && mSubjectTextEditor.hasFocus()) {
mSubjectTextEditor.append(smiley);
} else {
mTextEditor.append(smiley);
}
dialog.dismiss();
}
});
mSmileyDialog = b.create();
}
mSmileyDialog.show();
}
@Override
public void onUpdate(final Contact updated) {
// Using an existing handler for the post, rather than conjuring up a new one.
mMessageListItemHandler.post(new Runnable() {
@Override
public void run() {
ContactList recipients = isRecipientsEditorVisible() ?
mRecipientsEditor.constructContactsFromInput(false) : getRecipients();
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("[CMA] onUpdate contact updated: " + updated);
log("[CMA] onUpdate recipients: " + recipients);
}
updateTitle(recipients);
// The contact information for one (or more) of the recipients has changed.
// Rebuild the message list so each MessageItem will get the last contact info.
ComposeMessageActivity.this.mMsgListAdapter.notifyDataSetChanged();
// Don't do this anymore. When we're showing chips, we don't want to switch from
// chips to text.
// if (mRecipientsEditor != null) {
// mRecipientsEditor.populate(recipients);
// }
}
});
}
private void addRecipientsListeners() {
Contact.addListener(this);
}
private void removeRecipientsListeners() {
Contact.removeListener(this);
}
public static Intent createIntent(Context context, long threadId) {
Intent intent = new Intent(context, ComposeMessageActivity.class);
if (threadId > 0) {
intent.setData(Conversation.getUri(threadId));
}
return intent;
}
private String getBody(Uri uri) {
if (uri == null) {
return null;
}
String urlStr = uri.getSchemeSpecificPart();
if (!urlStr.contains("?")) {
return null;
}
urlStr = urlStr.substring(urlStr.indexOf('?') + 1);
String[] params = urlStr.split("&");
for (String p : params) {
if (p.startsWith("body=")) {
try {
return URLDecoder.decode(p.substring(5), "UTF-8");
} catch (UnsupportedEncodingException e) { }
}
}
return null;
}
private void updateThreadIdIfRunning() {
if (mIsRunning && mConversation != null) {
MessagingNotification.setCurrentlyDisplayedThreadId(mConversation.getThreadId());
}
// If we're not running, but resume later, the current thread ID will be set in onResume()
}
}
| am a71358d3: Action bar showing inconsistent information about recipients
* commit 'a71358d3489f50d4fb2a1d522a93feb78ec55a7e':
Action bar showing inconsistent information about recipients
| src/com/android/mms/ui/ComposeMessageActivity.java | am a71358d3: Action bar showing inconsistent information about recipients | <ide><path>rc/com/android/mms/ui/ComposeMessageActivity.java
<ide> continue;
<ide>
<ide> if (c == ',') {
<del> updateTitle(mConversation.getRecipients());
<add> ContactList contacts = mRecipientsEditor.constructContactsFromInput(false);
<add> updateTitle(contacts);
<ide> }
<ide>
<ide> break; |
|
Java | apache-2.0 | 2e4a49a6d425704eb24b7bb8e528c73c4a91a317 | 0 | OpenHFT/Chronicle-Bytes | /*
* Copyright 2016-2020 chronicle.software
*
* https://chronicle.software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.openhft.chronicle.bytes;
import net.openhft.chronicle.bytes.internal.BytesInternal;
import net.openhft.chronicle.bytes.internal.EnbeddedBytes;
import net.openhft.chronicle.core.Maths;
import net.openhft.chronicle.core.annotation.UsedViaReflection;
import net.openhft.chronicle.core.io.IORuntimeException;
import net.openhft.chronicle.core.io.ReferenceOwner;
import net.openhft.chronicle.core.util.ObjectUtils;
import net.openhft.chronicle.core.util.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.BufferOverflowException;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
/**
* Bytes is a pointer to a region of memory within a BytesStore. It can be for a fixed region of
* memory or an "elastic" buffer which can be resized, but not for a fixed region. <p></p> This is a
* BytesStore which is mutable and not thread safe. It has a write position and read position which
* must follow these constraints <p></p> {@code start() <= readPosition() <= writePosition() <= writeLimit() <= capacity()}
* <p></p> Also {@code readLimit() == writePosition() && readPosition() <= safeLimit()}
* <p></p>
*
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public interface Bytes<Underlying> extends
BytesStore<Bytes<Underlying>, Underlying>,
BytesIn<Underlying>,
BytesOut<Underlying> {
long MAX_CAPACITY = Long.MAX_VALUE & ~0xF; // 8 EiB - 16
int MAX_HEAP_CAPACITY = Integer.MAX_VALUE & ~0xF; // 2 GiB - 16
int DEFAULT_BYTE_BUFFER_CAPACITY = 256;
/**
* Creates and returns a new elastic wrapper for a direct (off-heap) ByteBuffer with a default capacity
* which will be resized as required.
*
* @return a new elastic wrapper for a direct (off-heap) ByteBuffer with a default capacity
* which will be resized as required
*/
@NotNull
static Bytes<ByteBuffer> elasticByteBuffer() {
return elasticByteBuffer(DEFAULT_BYTE_BUFFER_CAPACITY);
}
/**
* Creates and returns a new elastic wrapper for a direct (off-heap) ByteBuffer with
* the given {@code initialCapacity} which will be resized as required.
*
* @param initialCapacity the initial non-negative capacity given in bytes
* @return a new elastic wrapper for a direct (off-heap) ByteBuffer with
* the given {@code initialCapacity} which will be resized as required
*/
@NotNull
static Bytes<ByteBuffer> elasticByteBuffer(int initialCapacity) {
return elasticByteBuffer(initialCapacity, MAX_HEAP_CAPACITY);
}
/**
* Creates and returns a new elastic wrapper for a direct (off-heap) ByteBuffer with
* the given {@code initialCapacity} which will be resized as required up
* to the given {@code maxSize}.
*
* @param initialCapacity the initial non-negative capacity given in bytes
* @param maxCapacity the max capacity given in bytes equal or greater than initialCapacity
* @return a new elastic wrapper for a direct (off-heap) ByteBuffer with
* the given {@code initialCapacity} which will be resized as required up
* to the given {@code maxCapacity}
*/
@NotNull
static Bytes<ByteBuffer> elasticByteBuffer(int initialCapacity, int maxCapacity) {
@NotNull BytesStore<?, ByteBuffer> bs = BytesStore.elasticByteBuffer(initialCapacity, maxCapacity);
try {
try {
return bs.bytesForWrite();
} finally {
bs.release(ReferenceOwner.INIT);
}
} catch (IllegalStateException ise) {
throw new AssertionError(ise);
}
}
/**
* Creates and returns a new elastic wrapper for a heap ByteBuffer with
* the given {@code initialCapacity} which will be resized as required.
*
* @param initialCapacity the initial non-negative capacity given in bytes
* @return a new elastic wrapper for a heap ByteBuffer with
* the given {@code initialCapacity} which will be resized as required
*/
@NotNull
static Bytes<ByteBuffer> elasticHeapByteBuffer(int initialCapacity) {
@NotNull BytesStore<?, ByteBuffer> bs = BytesStore.wrap(ByteBuffer.allocate(initialCapacity));
try {
return NativeBytes.wrapWithNativeBytes(bs, Bytes.MAX_HEAP_CAPACITY);
} catch (IllegalArgumentException | IllegalStateException e) {
throw new AssertionError(e);
} finally {
try {
bs.release(INIT);
} catch (IllegalStateException ise) {
throw new AssertionError(ise);
}
}
}
/**
* Creates and returns a new elastic wrapper for a heap ByteBuffer with
* the {@code initialCapacity} 128 bytes which will be resized as required.
*
* @return a new elastic wrapper for a heap ByteBuffer with the {@code initialCapacity}
* 128 bytes which will be resized as required
*/
@NotNull
static Bytes<ByteBuffer> elasticHeapByteBuffer() {
return elasticHeapByteBuffer(128);
}
static <T> Bytes<T> forFieldGroup(T t, String groupName) {
@NotNull BytesStore<?, T> bs = BytesStore.forFields(t, groupName, 1);
try {
final EnbeddedBytes<T> bytes = EnbeddedBytes.wrap(bs);
return bytes.writeLimit(bs.writeLimit());
} catch (IllegalArgumentException | IllegalStateException e) {
throw new AssertionError(e);
} finally {
try {
bs.release(INIT);
} catch (IllegalStateException ise) {
throw new AssertionError(ise);
}
}
}
/**
* Wrap the ByteBuffer ready for reading
* Method for convenience only - might not be ideal for performance (creates garbage).
* To avoid garbage, use something like this example:
* <pre>{@code
* import net.openhft.chronicle.bytes.Bytes;
* import java.nio.ByteBuffer;
*
* public class ChronicleBytesWithByteBufferExampleTest {
* private static final String HELLO_WORLD = "hello world";
*
* public static void main(String[] args)
* throws InterruptedException {
* //setup Bytes and ByteBuffer to write from
* Bytes b = Bytes.elasticByteBuffer();
* ByteBuffer toWriteFrom = ByteBuffer.allocate(HELLO_WORLD.length());
* toWriteFrom.put(HELLO_WORLD.getBytes(), 0, HELLO_WORLD.length());
* toWriteFrom.flip();
* byte[] toReadTo = new byte[HELLO_WORLD.length()];
*
* doWrite(b, toWriteFrom);
* ByteBuffer byteBuffer = doRead(b);
*
* //check result
* final StringBuilder sb = new StringBuilder();
* for (int i = 0; i < HELLO_WORLD.length(); i++) {
* sb.append((char) byteBuffer.get());
* }
* assert sb.toString().equals(HELLO_WORLD): "Failed - strings not equal!";
* }
*
* private static void doWrite(Bytes b, ByteBuffer toWrite) {
* //no garbage when writing to Bytes from ByteBuffer
* b.clear();
* b.write(b.writePosition(), toWrite, toWrite.position(), toWrite.limit());
* }
*
* private static ByteBuffer doRead(Bytes b) {
* //no garbage when getting the underlying ByteBuffer
* assert b.underlyingObject() instanceof ByteBuffer;
* ByteBuffer byteBuffer = (ByteBuffer) b.underlyingObject();
* return byteBuffer;
* }
* }
* }</pre>
*
* @param byteBuffer to wrap
* @return a Bytes which wraps the provided ByteBuffer and is ready for reading.
*/
@NotNull
static Bytes<ByteBuffer> wrapForRead(@NotNull ByteBuffer byteBuffer) {
BytesStore<?, ByteBuffer> bs = BytesStore.wrap(byteBuffer);
try {
try {
Bytes<ByteBuffer> bbb = bs.bytesForRead();
bbb.readLimit(byteBuffer.limit());
bbb.readPosition(byteBuffer.position());
return bbb;
} finally {
bs.release(INIT);
}
} catch (IllegalStateException | BufferUnderflowException ise) {
throw new AssertionError(ise);
}
}
/**
* Wraps the ByteBuffer ready for writing
* Method for convenience only - might not be ideal for performance (creates garbage).
* To avoid garbage, use something like this example:
* <pre>{@code
* import net.openhft.chronicle.bytes.Bytes;
* import java.nio.ByteBuffer;
*
* public class ChronicleBytesWithByteBufferExampleTest {
* private static final String HELLO_WORLD = "hello world";
*
* public static void main(String[] args)
* throws InterruptedException {
* //setup Bytes and ByteBuffer to write from
* Bytes b = Bytes.elasticByteBuffer();
* ByteBuffer toWriteFrom = ByteBuffer.allocate(HELLO_WORLD.length());
* toWriteFrom.put(HELLO_WORLD.getBytes(), 0, HELLO_WORLD.length());
* toWriteFrom.flip();
* byte[] toReadTo = new byte[HELLO_WORLD.length()];
*
* doWrite(b, toWriteFrom);
* ByteBuffer byteBuffer = doRead(b);
*
* //check result
* final StringBuilder sb = new StringBuilder();
* for (int i = 0; i < HELLO_WORLD.length(); i++) {
* sb.append((char) byteBuffer.get());
* }
* assert sb.toString().equals(HELLO_WORLD): "Failed - strings not equal!";
* }
*
* private static void doWrite(Bytes b, ByteBuffer toWrite) {
* //no garbage when writing to Bytes from ByteBuffer
* b.clear();
* b.write(b.writePosition(), toWrite, toWrite.position(), toWrite.limit());
* }
*
* private static ByteBuffer doRead(Bytes b) {
* //no garbage when getting the underlying ByteBuffer
* assert b.underlyingObject() instanceof ByteBuffer;
* ByteBuffer byteBuffer = (ByteBuffer) b.underlyingObject();
* return byteBuffer;
* }
* }
* }</pre>
*
* @param byteBuffer to wrap
* @return a Bytes which wraps the provided ByteBuffer and is ready for writing.
*/
@NotNull
static Bytes<ByteBuffer> wrapForWrite(@NotNull ByteBuffer byteBuffer) {
BytesStore<?, ByteBuffer> bs = BytesStore.wrap(byteBuffer);
try {
try {
Bytes<ByteBuffer> bbb = bs.bytesForWrite();
bbb.writePosition(byteBuffer.position());
bbb.writeLimit(byteBuffer.limit());
return bbb;
} finally {
bs.release(INIT);
}
} catch (IllegalStateException | BufferOverflowException ise) {
throw new AssertionError(ise);
}
}
/**
* Wraps the byte[] ready for reading
* Method for convenience only - might not be ideal for performance (creates garbage).
* To avoid garbage, use something like this example:
* <pre>{@code
* import net.openhft.chronicle.bytes.Bytes;
* import java.nio.charset.Charset;
*
* public class ChronicleBytesWithPrimByteArrayExampleTest {
* private static final Charset ISO_8859 = Charset.forName("ISO-8859-1");
* private static final String HELLO_WORLD = "hello world";
*
* public static void main(String[] args) {
* //setup Bytes and byte[]s to write from and read to
* Bytes b = Bytes.elasticByteBuffer();
* byte[] toWriteFrom = HELLO_WORLD.getBytes(ISO_8859);
* byte[] toReadTo = new byte[HELLO_WORLD.length()];
*
* doWrite(b, toWriteFrom);
* doRead(b, toReadTo);
*
* //check result
* final StringBuilder sb = new StringBuilder();
* for (int i = 0; i < HELLO_WORLD.length(); i++) {
* sb.append((char) toReadTo[i]);
* }
* assert sb.toString().equals(HELLO_WORLD): "Failed - strings not equal!";
* }
*
* private static void doWrite(Bytes b, byte[] toWrite) {
* //no garbage when writing to Bytes from byte[]
* b.clear();
* b.write(toWrite);
* }
*
* private static void doRead(Bytes b, byte[] toReadTo) {
* //no garbage when reading from Bytes into byte[]
* b.read( toReadTo, 0, HELLO_WORLD.length());
* }
* }
* }</pre>
*
* @param byteArray to wrap
* @return the Bytes ready for reading.
*/
@NotNull
static Bytes<byte[]> wrapForRead(@NotNull byte[] byteArray) {
@NotNull BytesStore<?, byte[]> bs = BytesStore.wrap(byteArray);
try {
try {
return bs.bytesForRead();
} finally {
bs.release(INIT);
}
} catch (IllegalStateException ise) {
throw new AssertionError(ise);
}
}
/**
* Wraps the byte[] ready for writing
* Method for convenience only - might not be ideal for performance (creates garbage).
* To avoid garbage, use something like this example:
* <pre>{@code
* import net.openhft.chronicle.bytes.Bytes;
* import java.nio.charset.Charset;
*
* public class ChronicleBytesWithPrimByteArrayExampleTest {
* private static final Charset ISO_8859 = Charset.forName("ISO-8859-1");
* private static final String HELLO_WORLD = "hello world";
*
* public static void main(String[] args) {
* //setup Bytes and byte[]s to write from and read to
* Bytes b = Bytes.elasticByteBuffer();
* byte[] toWriteFrom = HELLO_WORLD.getBytes(ISO_8859);
* byte[] toReadTo = new byte[HELLO_WORLD.length()];
*
* doWrite(b, toWriteFrom);
* doRead(b, toReadTo);
*
* //check result
* final StringBuilder sb = new StringBuilder();
* for (int i = 0; i < HELLO_WORLD.length(); i++) {
* sb.append((char) toReadTo[i]);
* }
* assert sb.toString().equals(HELLO_WORLD): "Failed - strings not equal!";
* }
*
* private static void doWrite(Bytes b, byte[] toWrite) {
* //no garbage when writing to Bytes from byte[]
* b.clear();
* b.write(toWrite);
* }
*
* private static void doRead(Bytes b, byte[] toReadTo) {
* //no garbage when reading from Bytes into byte[]
* b.read( toReadTo, 0, HELLO_WORLD.length());
* }
* }
* }</pre>
*
* @param byteArray to wrap
* @return the Bytes ready for writing.
*/
@NotNull
static Bytes<byte[]> wrapForWrite(@NotNull byte[] byteArray) {
@NotNull BytesStore bs = BytesStore.wrap(byteArray);
try {
try {
return bs.bytesForWrite();
} finally {
bs.release(INIT);
}
} catch (IllegalStateException ise) {
throw new AssertionError(ise);
}
}
/**
* Converts text to bytes using ISO-8859-1 encoding and returns a Bytes ready for reading.
* <p>
* Note: this returns a direct Bytes now
*
* @param text to convert
* @return Bytes ready for reading.
*/
@NotNull
static Bytes<?> from(@NotNull CharSequence text) {
return from(text.toString());
}
static Bytes<?> fromDirect(@NotNull CharSequence text) {
return NativeBytes.nativeBytes(text.length()).append(text);
}
/**
* Converts text to bytes using ISO-8859-1 encoding and return a Bytes ready for reading.
* <p>
* Note: this returns a direct Bytes now
*
* @param text to convert
* @return Bytes ready for reading.
*/
@NotNull
static Bytes<?> directFrom(@NotNull String text) {
BytesStore from = BytesStore.from(text);
try {
try {
return from.bytesForRead();
} finally {
from.release(INIT);
}
} catch (IllegalStateException ise) {
throw new AssertionError(ise);
}
}
/**
* Converts text to bytes using ISO-8859-1 encoding and returns a Bytes ready for reading.
* <p>
* Note: this returns a heap Bytes
*
* @param text to convert
* @return Bytes ready for reading.
*/
@NotNull
static Bytes<byte[]> from(@NotNull String text) {
return wrapForRead(text.getBytes(StandardCharsets.ISO_8859_1));
}
@UsedViaReflection
static Bytes<byte[]> valueOf(String text) {
return from(text);
}
/**
* Creates and returns a new fix sized wrapper for native (64-bit address)
* memory with the given {@code capacity}.
*
* @param capacity the non-negative capacity given in bytes
* @return a new fix sized wrapper for native (64-bit address)
* memory with the given {@code capacity}
*/
@NotNull
static VanillaBytes<Void> allocateDirect(long capacity)
throws IllegalArgumentException {
@NotNull BytesStore<?, Void> bs = BytesStore.nativeStoreWithFixedCapacity(capacity);
try {
try {
return new NativeBytes<>(bs);
} finally {
bs.release(INIT);
}
} catch (IllegalStateException ise) {
throw new AssertionError(ise);
}
}
/**
* Creates and returns a new elastic wrapper for native (64-bit address)
* memory with zero initial capacity which will be resized as required.
*
* @return a new elastic wrapper for native (64-bit address)
* memory with zero initial capacity which will be resized as required
*/
@NotNull
static NativeBytes<Void> allocateElasticDirect() {
return NativeBytes.nativeBytes();
}
/**
* Creates and returns a new elastic wrapper for native (64-bit address)
* memory with the given {@code initialCapacity} which will be resized as required.
*
* @param initialCapacity the initial non-negative capacity given in bytes
* @return a new elastic wrapper for native (64-bit address)
* memory with the given {@code initialCapacity} which will be resized as required
*/
@NotNull
static NativeBytes<Void> allocateElasticDirect(long initialCapacity)
throws IllegalArgumentException {
return NativeBytes.nativeBytes(initialCapacity);
}
/**
* Creates and returns a new elastic wrapper for on heap memory with the
* {@code initialCapacity} 32 bytes which will be resized as required.
*
* @return a new elastic wrapper for on heap memory
*/
@NotNull
static OnHeapBytes allocateElasticOnHeap() {
return allocateElasticOnHeap(32);
}
/**
* Creates and returns a new elastic wrapper for on heap memory with the specified
* {@code initialCapacity} which will be resized as required.
*
* @param initialCapacity the initial capacity of the wrapper in bytes
* @return a new elastic wrapper for on-heap memory with an initial capacity of initialCapacity
*/
@NotNull
static OnHeapBytes allocateElasticOnHeap(int initialCapacity) {
BytesStore<?, byte[]> wrap = BytesStore.wrap(new byte[initialCapacity]);
try {
try {
return new OnHeapBytes(wrap, true);
} finally {
wrap.release(INIT);
}
} catch (IllegalStateException | IllegalArgumentException ise) {
throw new AssertionError(ise);
}
}
/**
* Creates and returns a string from the {@code readPosition} to the {@code readLimit}, The buffer is not modified
* by this call
*
* @param buffer the buffer to use
* @return a string contain the text from the {@code readPosition} to the {@code readLimit}
*/
@NotNull
static String toString(@NotNull final Bytes<?> buffer)
throws BufferUnderflowException, IllegalStateException, IllegalArgumentException {
return toString(buffer, MAX_HEAP_CAPACITY);
}
/**
* Creates and returns a string from the {@code readPosition} to the {@code readLimit} with a specified maximum length, The buffer is not modified
* by this call.
* <p>
* If the length of the string between {@code readPosition} to {@code readLimit} is greater than the specified maximum length,
* the "..." will be appended to the resulting string; in this case the length of the resulting string will be the specified maximum length+3.
*
* @param buffer the buffer to use
* @param maxLen the maximum length from the buffer, used to create a new string
* @return a string contain the text from the {@code readPosition} to the {@code readLimit} of the buffer
*/
@NotNull
static String toString(@NotNull final Bytes<?> buffer, long maxLen) throws
BufferUnderflowException, IllegalStateException, IllegalArgumentException {
if (buffer.refCount() < 1)
// added because something is crashing the JVM
return "<unknown>";
ReferenceOwner toString = ReferenceOwner.temporary("toString");
buffer.reserve(toString);
try {
if (buffer.readRemaining() == 0)
return "";
final long length = Math.min(maxLen + 1, buffer.readRemaining());
@NotNull final StringBuilder builder = new StringBuilder();
try {
buffer.readWithLength(length, b -> {
while (buffer.readRemaining() > 0) {
if (builder.length() >= maxLen) {
builder.append("...");
break;
}
builder.append((char) buffer.readByte());
}
});
} catch (Exception e) {
builder.append(' ').append(e);
}
return builder.toString();
} finally {
buffer.release(toString);
}
}
/**
* Creates and returns a string from the bytes of a given buffer with a specified length and from an specified offset.
* The buffer is not modified by this call.
*
* @param buffer the buffer to use
* @param position the offset position to create the string from
* @param len the number of characters to include in the string
* @return a string with length len contain the text from offset position
*/
@NotNull
static String toString(@NotNull final Bytes buffer, long position, long len) {
try {
final long pos = buffer.readPosition();
final long limit = buffer.readLimit();
buffer.readPositionRemaining(position, len);
try {
@NotNull final StringBuilder builder = new StringBuilder();
while (buffer.readRemaining() > 0) {
builder.append((char) buffer.readByte());
}
// remove the last comma
return builder.toString();
} finally {
buffer.readLimit(limit);
buffer.readPosition(pos);
}
} catch (Exception e) {
return e.toString();
}
}
/**
* Creates and returns a new fix sized wrapper for native (64-bit address)
* memory with the contents copied from the given {@code bytes} array.
* <p>
* Changes in the given {@code bytes} will not be affected by writes in
* the returned wrapper or vice versa.
*
* @param bytes array to copy
* @return a new fix sized wrapper for native (64-bit address)
* memory with the contents copied from the given {@code bytes} array
*/
@NotNull
static VanillaBytes allocateDirect(@NotNull byte[] bytes)
throws IllegalArgumentException {
VanillaBytes<Void> result = allocateDirect(bytes.length);
try {
result.write(bytes);
} catch (BufferOverflowException | IllegalStateException e) {
throw new AssertionError(e);
}
return result;
}
@NotNull
static Bytes fromHexString(@NotNull String s) {
return BytesInternal.fromHexString(s);
}
/**
* Code shared by String and StringBuffer to do searches. The
* source is the character array being searched, and the target
* is the string being searched for.
*
* @param source the read bytes being searched.
* @param target the read bytes being searched for.
* @param fromIndex the index to begin searching from,
* @return the index of where the text was found.
*/
static int indexOf(@NotNull BytesStore source, @NotNull BytesStore target, int fromIndex)
throws IllegalStateException {
long sourceOffset = source.readPosition();
long targetOffset = target.readPosition();
long sourceCount = source.readRemaining();
long targetCount = target.readRemaining();
if (fromIndex >= sourceCount) {
return Math.toIntExact(targetCount == 0 ? sourceCount : -1);
}
if (fromIndex < 0) {
fromIndex = 0;
}
if (targetCount == 0) {
return fromIndex;
}
try {
byte firstByte = target.readByte(targetOffset);
long max = sourceOffset + (sourceCount - targetCount);
for (long i = sourceOffset + fromIndex; i <= max; i++) {
/* Look for first character. */
if (source.readByte(i) != firstByte) {
while (++i <= max && source.readByte(i) != firstByte) ;
}
/* Found first character, now look at the rest of v2 */
if (i <= max) {
long j = i + 1;
long end = j + targetCount - 1;
for (long k = targetOffset + 1; j < end && source.readByte(j) == target.readByte(k); j++, k++) {
}
if (j == end) {
/* Found whole string. */
return Math.toIntExact(i - sourceOffset);
}
}
}
return -1;
} catch (BufferUnderflowException e) {
throw new AssertionError(e);
}
}
/**
* Returns a Bytes which is optionally unchecked. This allows bounds checks to be turned off.
* Note: this means that the result is no longer elastic, even if <code>this</code> is elastic.
*
* @param unchecked if true, minimal bounds checks will be performed
* @return Bytes without bounds checking
* @throws IllegalStateException if the underlying BytesStore has been released
*/
@NotNull
default Bytes<Underlying> unchecked(boolean unchecked)
throws IllegalStateException {
if (unchecked) {
if (isElastic())
BytesUtil.WarnUncheckedElasticBytes.warn();
Bytes<Underlying> underlyingBytes = start() == 0 && bytesStore().isDirectMemory() ?
new UncheckedNativeBytes<>(this) :
new UncheckedBytes<>(this);
release(INIT);
return underlyingBytes;
}
return this;
}
default boolean unchecked() {
return false;
}
/**
* @inheritDoc <P>
* If this Bytes {@link #isElastic()} the {@link #safeLimit()} can be
* lower than the point it can safely write.
*/
@Override
default long safeLimit() {
return bytesStore().safeLimit();
}
@Override
default boolean isClear() {
return start() == readPosition() && writeLimit() == capacity();
}
/**
* @inheritDoc <P>
* If this Bytes {@link #isElastic()} the {@link #realCapacity()} can be
* lower than the virtual {@link #capacity()}.
*/
@Override
default long realCapacity() {
return BytesStore.super.realCapacity();
}
/**
* @return a copy of this Bytes from position() to limit().
*/
@Override
BytesStore<Bytes<Underlying>, Underlying> copy()
throws IllegalStateException;
@NotNull
default String toHexString() {
return toHexString(1024);
}
/**
* Displays the hex data of {@link Bytes} from the {@code readPosition} up to the specified length.
*
* @param maxLength limit the number of bytes to be dumped
* @return hex representation of the buffer, from example [0D ,OA, FF]
*/
@NotNull
default String toHexString(long maxLength) {
return toHexString(readPosition(), maxLength);
}
/**
* Displays the hex data of {@link Bytes} with the specified maximum length from the specified offset.
*
* @param offset the specified offset to start from
* @param maxLength limit the number of bytes to be dumped
* @return hex representation of the buffer, from example [0D ,OA, FF]
*/
@NotNull
default String toHexString(long offset, long maxLength) {
// if (Jvm.isDebug() && Jvm.stackTraceEndsWith("Bytes", 3))
// return "Not Available";
long maxLength2 = Math.min(maxLength, readLimit() - offset);
try {
@NotNull String ret = BytesInternal.toHexString(this, offset, maxLength2);
return maxLength2 < readLimit() - offset ? ret + "... truncated" : ret;
} catch (BufferUnderflowException | IllegalStateException e) {
return e.toString();
}
}
/**
* Returns if this Bytes is elastic. I.e. it can resize when more data is written
* than it's {@link #realCapacity()}.
*
* @return if this Bytes is elastic
*/
boolean isElastic();
/**
* Grows the buffer if the buffer is elastic, if the buffer is not elastic and there is not
* enough capacity then this method will
* throws {@link java.nio.BufferOverflowException}
*
* @param desiredCapacity the capacity that you required
* @throws IllegalArgumentException if the buffer is not elastic and there is not enough space
*/
default void ensureCapacity(long desiredCapacity)
throws IllegalArgumentException, IllegalStateException {
if (desiredCapacity > capacity())
throw new IllegalArgumentException(isElastic() ? "todo" : "not elastic");
}
/**
* Creates a slice of the current Bytes based on its readPosition and limit. As a sub-section
* of a Bytes it cannot be elastic.
*
* @return a slice of the existing Bytes where the start is moved to the readPosition and the
* current limit determines the capacity.
* @throws IllegalStateException if the underlying BytesStore has been released
*/
@NotNull
@Override
default Bytes<Underlying> bytesForRead()
throws IllegalStateException {
try {
return isClear() ? BytesStore.super.bytesForRead() : new SubBytes<>(this, readPosition(), readLimit() + start());
} catch (IllegalArgumentException | BufferUnderflowException e) {
throw new AssertionError(e);
}
}
/**
* @return the ByteStore this Bytes wraps.
*/
@Override
@Nullable
BytesStore bytesStore();
default boolean isEqual(String s)
throws IllegalStateException {
return StringUtils.isEqual(this, s);
}
/**
* Compact these Bytes by moving the readPosition to the start.
*
* @return this
*/
@NotNull
Bytes<Underlying> compact()
throws IllegalStateException;
/**
* Copies bytes from this Bytes to another ByteStore.
*
* @param store the BytesStore to copy to
* @return the number of bytes copied
*/
@Override
default long copyTo(@NotNull BytesStore store)
throws IllegalStateException {
return BytesStore.super.copyTo(store);
}
/**
* Copies bytes from this Bytes to a specified OutputStream.
*
* @param out the specified OutputStream that this BytesStore is copied to
* @throws IllegalStateException if this Bytes has been released
* @throws IOException if an I/O error occurs
*/
@Override
default void copyTo(@NotNull OutputStream out)
throws IOException, IllegalStateException {
BytesStore.super.copyTo(out);
}
@Override
default boolean sharedMemory() {
return bytesStore().sharedMemory();
}
/**
* Will un-write a specified number of bytes from an offset from this Bytes.
* <p>
* Calling this method will update the cursors of this Bytes.
*
* @param fromOffset the offset from the target bytes
* @param count the number of bytes to un-write
*/
default void unwrite(long fromOffset, int count)
throws BufferUnderflowException, BufferOverflowException, IllegalStateException {
long wp = writePosition();
if (wp < fromOffset)
return;
write(fromOffset, this, fromOffset + count, wp - fromOffset - count);
writePosition(wp - count);
}
@NotNull
default BigDecimal readBigDecimal()
throws ArithmeticException, BufferUnderflowException, IllegalStateException {
return new BigDecimal(readBigInteger(), Maths.toUInt31(readStopBit()));
}
@NotNull
default BigInteger readBigInteger()
throws ArithmeticException, BufferUnderflowException, IllegalStateException {
int length = Maths.toUInt31(readStopBit());
if (length == 0)
if (lenient())
return BigInteger.ZERO;
else
throw new BufferUnderflowException();
@NotNull byte[] bytes = new byte[length];
read(bytes);
return new BigInteger(bytes);
}
/**
* Returns the index within this Bytes of the first occurrence of the
* specified sub-bytes.
* <p>
* The returned index is the smallest value <i>k</i> for which:
* <blockquote><pre>
* this.startsWith(bytes, <i>k</i>)
* </pre></blockquote>
* If no such value of <i>k</i> exists, then {@code -1} is returned.
*
* @param source the sub-bytes to search for.
* @return the index of the first occurrence of the specified sub-bytes,
* or {@code -1} if there is no such occurrence.
*/
default long indexOf(@NotNull Bytes source)
throws IllegalStateException {
return indexOf(this, source, 0);
}
/**
* Returns the index within this Bytes of the first occurrence of the
* specified sub-bytes.
* <p>
* The returned index is the smallest value <i>k</i> for which:
* <blockquote><pre>
* this.startsWith(bytes, <i>k</i>)
* </pre></blockquote>
* If no such value of <i>k</i> exists, then {@code -1} is returned.
*
* @param source the sub-bytes to search for.
* @param fromIndex start the search from this offset
* @return the index of the first occurrence of the specified sub-bytes,
* or {@code -1} if there is no such occurrence.
*/
default int indexOf(@NotNull BytesStore source, int fromIndex)
throws IllegalStateException {
return indexOf(this, source, fromIndex);
}
@Override
@NotNull
Bytes<Underlying> clear()
throws IllegalStateException;
@Override
default boolean readWrite() {
return bytesStore().readWrite();
}
default void readWithLength(long length, @NotNull BytesOut<Underlying> bytesOut)
throws BufferUnderflowException, IORuntimeException, BufferOverflowException, IllegalStateException {
if (length > readRemaining())
throw new BufferUnderflowException();
long limit0 = readLimit();
long limit = readPosition() + length;
boolean lenient = lenient();
try {
lenient(true);
readLimit(limit);
bytesOut.write(this);
} finally {
readLimit(limit0);
readPosition(limit);
lenient(lenient);
}
}
default <T extends ReadBytesMarshallable> T readMarshallableLength16(Class<T> tClass, T object)
throws BufferUnderflowException, IllegalStateException {
if (object == null) object = ObjectUtils.newInstance(tClass);
int length = readUnsignedShort();
long limit = readLimit();
long end = readPosition() + length;
boolean lenient = lenient();
try {
lenient(true);
readLimit(end);
object.readMarshallable(this);
} finally {
readPosition(end);
readLimit(limit);
lenient(lenient);
}
return object;
}
default void writeMarshallableLength16(WriteBytesMarshallable marshallable)
throws IllegalArgumentException, BufferOverflowException, IllegalStateException, BufferUnderflowException {
long position = writePosition();
try {
writeUnsignedShort(0);
marshallable.writeMarshallable(this);
long length = writePosition() - position - 2;
if (length >= 1 << 16)
throw new IllegalStateException("Marshallable " + marshallable.getClass() + " too long was " + length);
writeUnsignedShort(position, (int) length);
} catch (ArithmeticException e) {
throw new AssertionError(e);
}
}
default Bytes write(final InputStream inputStream)
throws IOException, BufferOverflowException, IllegalStateException {
for (; ; ) {
int read;
read = inputStream.read();
if (read == -1)
break;
writeByte((byte) read);
}
return this;
}
} | src/main/java/net/openhft/chronicle/bytes/Bytes.java | /*
* Copyright 2016-2020 chronicle.software
*
* https://chronicle.software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.openhft.chronicle.bytes;
import net.openhft.chronicle.bytes.internal.BytesInternal;
import net.openhft.chronicle.bytes.internal.EnbeddedBytes;
import net.openhft.chronicle.core.Maths;
import net.openhft.chronicle.core.annotation.UsedViaReflection;
import net.openhft.chronicle.core.io.IORuntimeException;
import net.openhft.chronicle.core.io.ReferenceOwner;
import net.openhft.chronicle.core.util.ObjectUtils;
import net.openhft.chronicle.core.util.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.BufferOverflowException;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
/**
* Bytes is a pointer to a region of memory within a BytesStore. It can be for a fixed region of
* memory or an "elastic" buffer which can be resized, but not for a fixed region. <p></p> This is a
* BytesStore which is mutable and not thread safe. It has a write position and read position which
* must follow these constraints <p></p> {@code start() <= readPosition() <= writePosition() <= writeLimit() <= capacity()}
* <p></p> Also {@code readLimit() == writePosition() && readPosition() <= safeLimit()}
* <p></p>
*
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public interface Bytes<Underlying> extends
BytesStore<Bytes<Underlying>, Underlying>,
BytesIn<Underlying>,
BytesOut<Underlying> {
long MAX_CAPACITY = Long.MAX_VALUE & ~0xF; // 8 EiB - 16
int MAX_HEAP_CAPACITY = Integer.MAX_VALUE & ~0xF; // 2 GiB - 16
int DEFAULT_BYTE_BUFFER_CAPACITY = 256;
/**
* Creates and returns a new elastic wrapper for a direct (off-heap) ByteBuffer with a default capacity
* which will be resized as required.
*
* @return a new elastic wrapper for a direct (off-heap) ByteBuffer with a default capacity
* which will be resized as required
*/
@NotNull
static Bytes<ByteBuffer> elasticByteBuffer() {
return elasticByteBuffer(DEFAULT_BYTE_BUFFER_CAPACITY);
}
/**
* Creates and returns a new elastic wrapper for a direct (off-heap) ByteBuffer with
* the given {@code initialCapacity} which will be resized as required.
*
* @param initialCapacity the initial non-negative capacity given in bytes
* @return a new elastic wrapper for a direct (off-heap) ByteBuffer with
* the given {@code initialCapacity} which will be resized as required
*/
@NotNull
static Bytes<ByteBuffer> elasticByteBuffer(int initialCapacity) {
return elasticByteBuffer(initialCapacity, MAX_HEAP_CAPACITY);
}
/**
* Creates and returns a new elastic wrapper for a direct (off-heap) ByteBuffer with
* the given {@code initialCapacity} which will be resized as required up
* to the given {@code maxSize}.
*
* @param initialCapacity the initial non-negative capacity given in bytes
* @param maxCapacity the max capacity given in bytes equal or greater than initialCapacity
* @return a new elastic wrapper for a direct (off-heap) ByteBuffer with
* the given {@code initialCapacity} which will be resized as required up
* to the given {@code maxCapacity}
*/
@NotNull
static Bytes<ByteBuffer> elasticByteBuffer(int initialCapacity, int maxCapacity) {
@NotNull BytesStore<?, ByteBuffer> bs = BytesStore.elasticByteBuffer(initialCapacity, maxCapacity);
try {
try {
return bs.bytesForWrite();
} finally {
bs.release(ReferenceOwner.INIT);
}
} catch (IllegalStateException ise) {
throw new AssertionError(ise);
}
}
/**
* Creates and returns a new elastic wrapper for a heap ByteBuffer with
* the given {@code initialCapacity} which will be resized as required.
*
* @param initialCapacity the initial non-negative capacity given in bytes
* @return a new elastic wrapper for a heap ByteBuffer with
* the given {@code initialCapacity} which will be resized as required
*/
@NotNull
static Bytes<ByteBuffer> elasticHeapByteBuffer(int initialCapacity) {
@NotNull BytesStore<?, ByteBuffer> bs = BytesStore.wrap(ByteBuffer.allocate(initialCapacity));
try {
return NativeBytes.wrapWithNativeBytes(bs, Bytes.MAX_HEAP_CAPACITY);
} catch (IllegalArgumentException | IllegalStateException e) {
throw new AssertionError(e);
} finally {
try {
bs.release(INIT);
} catch (IllegalStateException ise) {
throw new AssertionError(ise);
}
}
}
/**
* Creates and returns a new elastic wrapper for a heap ByteBuffer with
* the {@code initialCapacity} 128 bytes which will be resized as required.
*
* @return a new elastic wrapper for a heap ByteBuffer with the {@code initialCapacity}
* 128 bytes which will be resized as required
*/
@NotNull
static Bytes<ByteBuffer> elasticHeapByteBuffer() {
return elasticHeapByteBuffer(128);
}
static <T> Bytes<T> forFieldGroup(T t, String groupName) {
@NotNull BytesStore<?, T> bs = BytesStore.forFields(t, groupName, 1);
try {
final EnbeddedBytes<T> bytes = EnbeddedBytes.wrap(bs);
return bytes.writeLimit(bs.writeLimit());
} catch (IllegalArgumentException | IllegalStateException e) {
throw new AssertionError(e);
} finally {
try {
bs.release(INIT);
} catch (IllegalStateException ise) {
throw new AssertionError(ise);
}
}
}
/**
* Wrap the ByteBuffer ready for reading
* Method for convenience only - might not be ideal for performance (creates garbage).
* To avoid garbage, use something like this example:
* <pre>{@code
* import net.openhft.chronicle.bytes.Bytes;
* import java.nio.ByteBuffer;
*
* public class ChronicleBytesWithByteBufferExampleTest {
* private static final String HELLO_WORLD = "hello world";
*
* public static void main(String[] args)
* throws InterruptedException {
* //setup Bytes and ByteBuffer to write from
* Bytes b = Bytes.elasticByteBuffer();
* ByteBuffer toWriteFrom = ByteBuffer.allocate(HELLO_WORLD.length());
* toWriteFrom.put(HELLO_WORLD.getBytes(), 0, HELLO_WORLD.length());
* toWriteFrom.flip();
* byte[] toReadTo = new byte[HELLO_WORLD.length()];
*
* doWrite(b, toWriteFrom);
* ByteBuffer byteBuffer = doRead(b);
*
* //check result
* final StringBuilder sb = new StringBuilder();
* for (int i = 0; i < HELLO_WORLD.length(); i++) {
* sb.append((char) byteBuffer.get());
* }
* assert sb.toString().equals(HELLO_WORLD): "Failed - strings not equal!";
* }
*
* private static void doWrite(Bytes b, ByteBuffer toWrite) {
* //no garbage when writing to Bytes from ByteBuffer
* b.clear();
* b.write(b.writePosition(), toWrite, toWrite.position(), toWrite.limit());
* }
*
* private static ByteBuffer doRead(Bytes b) {
* //no garbage when getting the underlying ByteBuffer
* assert b.underlyingObject() instanceof ByteBuffer;
* ByteBuffer byteBuffer = (ByteBuffer) b.underlyingObject();
* return byteBuffer;
* }
* }
* }</pre>
*
* @param byteBuffer to wrap
* @return a Bytes which wraps the provided ByteBuffer and is ready for reading.
*/
@NotNull
static Bytes<ByteBuffer> wrapForRead(@NotNull ByteBuffer byteBuffer) {
BytesStore<?, ByteBuffer> bs = BytesStore.wrap(byteBuffer);
try {
try {
Bytes<ByteBuffer> bbb = bs.bytesForRead();
bbb.readLimit(byteBuffer.limit());
bbb.readPosition(byteBuffer.position());
return bbb;
} finally {
bs.release(INIT);
}
} catch (IllegalStateException | BufferUnderflowException ise) {
throw new AssertionError(ise);
}
}
/**
* Wraps the ByteBuffer ready for writing
* Method for convenience only - might not be ideal for performance (creates garbage).
* To avoid garbage, use something like this example:
* <pre>{@code
* import net.openhft.chronicle.bytes.Bytes;
* import java.nio.ByteBuffer;
*
* public class ChronicleBytesWithByteBufferExampleTest {
* private static final String HELLO_WORLD = "hello world";
*
* public static void main(String[] args)
* throws InterruptedException {
* //setup Bytes and ByteBuffer to write from
* Bytes b = Bytes.elasticByteBuffer();
* ByteBuffer toWriteFrom = ByteBuffer.allocate(HELLO_WORLD.length());
* toWriteFrom.put(HELLO_WORLD.getBytes(), 0, HELLO_WORLD.length());
* toWriteFrom.flip();
* byte[] toReadTo = new byte[HELLO_WORLD.length()];
*
* doWrite(b, toWriteFrom);
* ByteBuffer byteBuffer = doRead(b);
*
* //check result
* final StringBuilder sb = new StringBuilder();
* for (int i = 0; i < HELLO_WORLD.length(); i++) {
* sb.append((char) byteBuffer.get());
* }
* assert sb.toString().equals(HELLO_WORLD): "Failed - strings not equal!";
* }
*
* private static void doWrite(Bytes b, ByteBuffer toWrite) {
* //no garbage when writing to Bytes from ByteBuffer
* b.clear();
* b.write(b.writePosition(), toWrite, toWrite.position(), toWrite.limit());
* }
*
* private static ByteBuffer doRead(Bytes b) {
* //no garbage when getting the underlying ByteBuffer
* assert b.underlyingObject() instanceof ByteBuffer;
* ByteBuffer byteBuffer = (ByteBuffer) b.underlyingObject();
* return byteBuffer;
* }
* }
* }</pre>
*
* @param byteBuffer to wrap
* @return a Bytes which wraps the provided ByteBuffer and is ready for writing.
*/
@NotNull
static Bytes<ByteBuffer> wrapForWrite(@NotNull ByteBuffer byteBuffer) {
BytesStore<?, ByteBuffer> bs = BytesStore.wrap(byteBuffer);
try {
try {
Bytes<ByteBuffer> bbb = bs.bytesForWrite();
bbb.writePosition(byteBuffer.position());
bbb.writeLimit(byteBuffer.limit());
return bbb;
} finally {
bs.release(INIT);
}
} catch (IllegalStateException | BufferOverflowException ise) {
throw new AssertionError(ise);
}
}
/**
* Wraps the byte[] ready for reading
* Method for convenience only - might not be ideal for performance (creates garbage).
* To avoid garbage, use something like this example:
* <pre>{@code
* import net.openhft.chronicle.bytes.Bytes;
* import java.nio.charset.Charset;
*
* public class ChronicleBytesWithPrimByteArrayExampleTest {
* private static final Charset ISO_8859 = Charset.forName("ISO-8859-1");
* private static final String HELLO_WORLD = "hello world";
*
* public static void main(String[] args) {
* //setup Bytes and byte[]s to write from and read to
* Bytes b = Bytes.elasticByteBuffer();
* byte[] toWriteFrom = HELLO_WORLD.getBytes(ISO_8859);
* byte[] toReadTo = new byte[HELLO_WORLD.length()];
*
* doWrite(b, toWriteFrom);
* doRead(b, toReadTo);
*
* //check result
* final StringBuilder sb = new StringBuilder();
* for (int i = 0; i < HELLO_WORLD.length(); i++) {
* sb.append((char) toReadTo[i]);
* }
* assert sb.toString().equals(HELLO_WORLD): "Failed - strings not equal!";
* }
*
* private static void doWrite(Bytes b, byte[] toWrite) {
* //no garbage when writing to Bytes from byte[]
* b.clear();
* b.write(toWrite);
* }
*
* private static void doRead(Bytes b, byte[] toReadTo) {
* //no garbage when reading from Bytes into byte[]
* b.read( toReadTo, 0, HELLO_WORLD.length());
* }
* }
* }</pre>
*
* @param byteArray to wrap
* @return the Bytes ready for reading.
*/
@NotNull
static Bytes<byte[]> wrapForRead(@NotNull byte[] byteArray) {
@NotNull BytesStore<?, byte[]> bs = BytesStore.wrap(byteArray);
try {
try {
return bs.bytesForRead();
} finally {
bs.release(INIT);
}
} catch (IllegalStateException ise) {
throw new AssertionError(ise);
}
}
/**
* Wraps the byte[] ready for writing
* Method for convenience only - might not be ideal for performance (creates garbage).
* To avoid garbage, use something like this example:
* <pre>{@code
* import net.openhft.chronicle.bytes.Bytes;
* import java.nio.charset.Charset;
*
* public class ChronicleBytesWithPrimByteArrayExampleTest {
* private static final Charset ISO_8859 = Charset.forName("ISO-8859-1");
* private static final String HELLO_WORLD = "hello world";
*
* public static void main(String[] args) {
* //setup Bytes and byte[]s to write from and read to
* Bytes b = Bytes.elasticByteBuffer();
* byte[] toWriteFrom = HELLO_WORLD.getBytes(ISO_8859);
* byte[] toReadTo = new byte[HELLO_WORLD.length()];
*
* doWrite(b, toWriteFrom);
* doRead(b, toReadTo);
*
* //check result
* final StringBuilder sb = new StringBuilder();
* for (int i = 0; i < HELLO_WORLD.length(); i++) {
* sb.append((char) toReadTo[i]);
* }
* assert sb.toString().equals(HELLO_WORLD): "Failed - strings not equal!";
* }
*
* private static void doWrite(Bytes b, byte[] toWrite) {
* //no garbage when writing to Bytes from byte[]
* b.clear();
* b.write(toWrite);
* }
*
* private static void doRead(Bytes b, byte[] toReadTo) {
* //no garbage when reading from Bytes into byte[]
* b.read( toReadTo, 0, HELLO_WORLD.length());
* }
* }
* }</pre>
*
* @param byteArray to wrap
* @return the Bytes ready for writing.
*/
@NotNull
static Bytes<byte[]> wrapForWrite(@NotNull byte[] byteArray) {
@NotNull BytesStore bs = BytesStore.wrap(byteArray);
try {
try {
return bs.bytesForWrite();
} finally {
bs.release(INIT);
}
} catch (IllegalStateException ise) {
throw new AssertionError(ise);
}
}
/**
* Converts text to bytes using ISO-8859-1 encoding and returns a Bytes ready for reading.
* <p>
* Note: this returns a direct Bytes now
*
* @param text to convert
* @return Bytes ready for reading.
*/
@NotNull
static Bytes<?> from(@NotNull CharSequence text) {
return from(text.toString());
}
static Bytes<?> fromDirect(@NotNull CharSequence text) {
return NativeBytes.nativeBytes(text.length()).append(text);
}
/**
* Converts text to bytes using ISO-8859-1 encoding and return a Bytes ready for reading.
* <p>
* Note: this returns a direct Bytes now
*
* @param text to convert
* @return Bytes ready for reading.
*/
@NotNull
static Bytes<?> directFrom(@NotNull String text) {
BytesStore from = BytesStore.from(text);
try {
try {
return from.bytesForRead();
} finally {
from.release(INIT);
}
} catch (IllegalStateException ise) {
throw new AssertionError(ise);
}
}
/**
* Converts text to bytes using ISO-8859-1 encoding and returns a Bytes ready for reading.
* <p>
* Note: this returns a heap Bytes
*
* @param text to convert
* @return Bytes ready for reading.
*/
@NotNull
static Bytes<byte[]> from(@NotNull String text) {
return wrapForRead(text.getBytes(StandardCharsets.ISO_8859_1));
}
@UsedViaReflection
static Bytes<byte[]> valueOf(String text) {
return from(text);
}
/**
* Creates and returns a new fix sized wrapper for native (64-bit address)
* memory with the given {@code capacity}.
*
* @param capacity the non-negative capacity given in bytes
* @return a new fix sized wrapper for native (64-bit address)
* memory with the given {@code capacity}
*/
@NotNull
static VanillaBytes<Void> allocateDirect(long capacity)
throws IllegalArgumentException {
@NotNull BytesStore<?, Void> bs = BytesStore.nativeStoreWithFixedCapacity(capacity);
try {
try {
return new NativeBytes<>(bs);
} finally {
bs.release(INIT);
}
} catch (IllegalStateException ise) {
throw new AssertionError(ise);
}
}
/**
* Creates and returns a new elastic wrapper for native (64-bit address)
* memory with zero initial capacity which will be resized as required.
*
* @return a new elastic wrapper for native (64-bit address)
* memory with zero initial capacity which will be resized as required
*/
@NotNull
static NativeBytes<Void> allocateElasticDirect() {
return NativeBytes.nativeBytes();
}
/**
* Creates and returns a new elastic wrapper for native (64-bit address)
* memory with the given {@code initialCapacity} which will be resized as required.
*
* @param initialCapacity the initial non-negative capacity given in bytes
* @return a new elastic wrapper for native (64-bit address)
* memory with the given {@code initialCapacity} which will be resized as required
*/
@NotNull
static NativeBytes<Void> allocateElasticDirect(long initialCapacity)
throws IllegalArgumentException {
return NativeBytes.nativeBytes(initialCapacity);
}
/**
* Creates and returns a new elastic wrapper for on heap memory with the
* {@code initialCapacity} 32 bytes which will be resized as required.
*
* @return a new elastic wrapper for on heap memory
*/
@NotNull
static OnHeapBytes allocateElasticOnHeap() {
return allocateElasticOnHeap(32);
}
/**
* Creates and returns a new elastic wrapper for on heap memory with the specified
* {@code initialCapacity} which will be resized as required.
*
* @param initialCapacity the initial capacity of the wrapper in bytes
* @return a new elastic wrapper for on-heap memory with an initial capacity of initialCapacity
*/
@NotNull
static OnHeapBytes allocateElasticOnHeap(int initialCapacity) {
BytesStore<?, byte[]> wrap = BytesStore.wrap(new byte[initialCapacity]);
try {
try {
return new OnHeapBytes(wrap, true);
} finally {
wrap.release(INIT);
}
} catch (IllegalStateException | IllegalArgumentException ise) {
throw new AssertionError(ise);
}
}
/**
* Creates and returns a string from the {@code readPosition} to the {@code readLimit}, The buffer is not modified
* by this call
*
* @param buffer the buffer to use
* @return a string contain the text from the {@code readPosition} to the {@code readLimit}
*/
@NotNull
static String toString(@NotNull final Bytes<?> buffer)
throws BufferUnderflowException, IllegalStateException, IllegalArgumentException {
return toString(buffer, MAX_HEAP_CAPACITY);
}
/**
* Creates and returns a string from the {@code readPosition} to the {@code readLimit} with a specified maximum length, The buffer is not modified
* by this call.
* <p>
* If the length of the string between {@code readPosition} to {@code readLimit} is greater than the specified maximum length,
* the "..." will be appended to the resulting string; in this case the length of the resulting string will be the specified maximum length+3.
*
* @param buffer the buffer to use
* @param maxLen the maximum length from the buffer, used to create a new string
* @return a string contain the text from the {@code readPosition} to the {@code readLimit} of the buffer
*/
@NotNull
static String toString(@NotNull final Bytes<?> buffer, long maxLen) throws
BufferUnderflowException, IllegalStateException, IllegalArgumentException {
if (buffer.refCount() < 1)
// added because something is crashing the JVM
return "<unknown>";
ReferenceOwner toString = ReferenceOwner.temporary("toString");
buffer.reserve(toString);
try {
if (buffer.readRemaining() == 0)
return "";
final long length = Math.min(maxLen + 1, buffer.readRemaining());
@NotNull final StringBuilder builder = new StringBuilder();
try {
buffer.readWithLength(length, b -> {
while (buffer.readRemaining() > 0) {
if (builder.length() >= maxLen) {
builder.append("...");
break;
}
builder.append((char) buffer.readByte());
}
});
} catch (Exception e) {
builder.append(' ').append(e);
}
return builder.toString();
} finally {
buffer.release(toString);
}
}
/**
* Creates and returns a string from the bytes of a given buffer with a specified length and from an specified offset.
* The buffer is not modified by this call.
*
* @param buffer the buffer to use
* @param position the offset position to create the string from
* @param len the number of characters to include in the string
* @return a string with length len contain the text from offset position
*/
@NotNull
static String toString(@NotNull final Bytes buffer, long position, long len) {
try {
final long pos = buffer.readPosition();
final long limit = buffer.readLimit();
buffer.readPositionRemaining(position, len);
try {
@NotNull final StringBuilder builder = new StringBuilder();
while (buffer.readRemaining() > 0) {
builder.append((char) buffer.readByte());
}
// remove the last comma
return builder.toString();
} finally {
buffer.readLimit(limit);
buffer.readPosition(pos);
}
} catch (Exception e) {
return e.toString();
}
}
/**
* Creates and returns a new fix sized wrapper for native (64-bit address)
* memory with the contents copied from the given {@code bytes} array.
* <p>
* Changes in the given {@code bytes} will not be affected by writes in
* the returned wrapper or vice versa.
*
* @param bytes array to copy
* @return a new fix sized wrapper for native (64-bit address)
* memory with the contents copied from the given {@code bytes} array
*/
@NotNull
static VanillaBytes allocateDirect(@NotNull byte[] bytes)
throws IllegalArgumentException {
VanillaBytes<Void> result = allocateDirect(bytes.length);
try {
result.write(bytes);
} catch (BufferOverflowException | IllegalStateException e) {
throw new AssertionError(e);
}
return result;
}
@NotNull
static Bytes fromHexString(@NotNull String s) {
return BytesInternal.fromHexString(s);
}
/**
* Code shared by String and StringBuffer to do searches. The
* source is the character array being searched, and the target
* is the string being searched for.
*
* @param source the read bytes being searched.
* @param target the read bytes being searched for.
* @param fromIndex the index to begin searching from,
* @return the index of where the text was found.
*/
static int indexOf(@NotNull BytesStore source, @NotNull BytesStore target, int fromIndex)
throws IllegalStateException {
long sourceOffset = source.readPosition();
long targetOffset = target.readPosition();
long sourceCount = source.readRemaining();
long targetCount = target.readRemaining();
if (fromIndex >= sourceCount) {
return Math.toIntExact(targetCount == 0 ? sourceCount : -1);
}
if (fromIndex < 0) {
fromIndex = 0;
}
if (targetCount == 0) {
return fromIndex;
}
try {
byte firstByte = target.readByte(targetOffset);
long max = sourceOffset + (sourceCount - targetCount);
for (long i = sourceOffset + fromIndex; i <= max; i++) {
/* Look for first character. */
if (source.readByte(i) != firstByte) {
while (++i <= max && source.readByte(i) != firstByte) ;
}
/* Found first character, now look at the rest of v2 */
if (i <= max) {
long j = i + 1;
long end = j + targetCount - 1;
for (long k = targetOffset + 1; j < end && source.readByte(j) == target.readByte(k); j++, k++) {
}
if (j == end) {
/* Found whole string. */
return Math.toIntExact(i - sourceOffset);
}
}
}
return -1;
} catch (BufferUnderflowException e) {
throw new AssertionError(e);
}
}
/**
* Returns a Bytes which is optionally unchecked. This allows bounds checks to be turned off.
* Note: this means that the result is no longer elastic, even if <code>this</code> is elastic.
*
* @param unchecked if true, minimal bounds checks will be performed
* @return Bytes without bounds checking
* @throws IllegalStateException if the underlying BytesStore has been released
*/
@NotNull
default Bytes<Underlying> unchecked(boolean unchecked)
throws IllegalStateException {
if (unchecked) {
if (isElastic())
BytesUtil.WarnUncheckedElasticBytes.warn();
Bytes<Underlying> underlyingBytes = start() == 0 && bytesStore().isDirectMemory() ?
new UncheckedNativeBytes<>(this) :
new UncheckedBytes<>(this);
release(INIT);
return underlyingBytes;
}
return this;
}
default boolean unchecked() {
return false;
}
/**
* @inheritDoc <P>
* If this Bytes {@link #isElastic()} the {@link #safeLimit()} can be
* lower than the point it can safely write.
*/
@Override
default long safeLimit() {
return bytesStore().safeLimit();
}
@Override
default boolean isClear() {
return start() == readPosition() && writeLimit() == capacity();
}
/**
* @inheritDoc <P>
* If this Bytes {@link #isElastic()} the {@link #realCapacity()} can be
* lower than the virtual {@link #capacity()}.
*/
@Override
default long realCapacity() {
return BytesStore.super.realCapacity();
}
/**
* @return a copy of this Bytes from position() to limit().
*/
@Override
BytesStore<Bytes<Underlying>, Underlying> copy()
throws IllegalStateException;
@NotNull
default String toHexString() {
return toHexString(1024);
}
/**
* Displays the hex data of {@link Bytes} from the {@code readPosition} up to the specified length.
*
* @param maxLength limit the number of bytes to be dumped
* @return hex representation of the buffer, from example [0D ,OA, FF]
*/
@NotNull
default String toHexString(long maxLength) {
return toHexString(readPosition(), maxLength);
}
/**
* Displays the hex data of {@link Bytes} with the specified maximum length from the specified offset.
*
* @param offset the specified offset to start from
* @param maxLength limit the number of bytes to be dumped
* @return hex representation of the buffer, from example [0D ,OA, FF]
*/
@NotNull
default String toHexString(long offset, long maxLength) {
// if (Jvm.isDebug() && Jvm.stackTraceEndsWith("Bytes", 3))
// return "Not Available";
long maxLength2 = Math.min(maxLength, readLimit() - offset);
try {
@NotNull String ret = BytesInternal.toHexString(this, offset, maxLength2);
return maxLength2 < readLimit() - offset ? ret + "... truncated" : ret;
} catch (BufferUnderflowException | IllegalStateException e) {
return e.toString();
}
}
/**
* Returns if this Bytes is elastic. I.e. it can resize when more data is written
* than it's {@link #realCapacity()}.
*
* @return if this Bytes is elastic
*/
boolean isElastic();
/**
* Grows the buffer if the buffer is elastic, if the buffer is not elastic and there is not
* enough capacity then this method will
* throws {@link java.nio.BufferOverflowException}
*
* @param desiredCapacity the capacity that you required
* @throws IllegalArgumentException if the buffer is not elastic and there is not enough space
*/
default void ensureCapacity(long desiredCapacity)
throws IllegalArgumentException, IllegalStateException {
if (desiredCapacity > capacity())
throw new IllegalArgumentException(isElastic() ? "todo" : "not elastic");
}
/**
* Creates a slice of the current Bytes based on its readPosition and limit. As a sub-section
* of a Bytes it cannot be elastic.
*
* @return a slice of the existing Bytes where the start is moved to the readPosition and the
* current limit determines the capacity.
* @throws IllegalStateException if the underlying BytesStore has been released
*/
@NotNull
@Override
default Bytes<Underlying> bytesForRead()
throws IllegalStateException {
try {
return isClear() ? BytesStore.super.bytesForRead() : new SubBytes<>(this, readPosition(), readLimit() + start());
} catch (IllegalArgumentException | BufferUnderflowException e) {
throw new AssertionError(e);
}
}
/**
* @return the ByteStore this Bytes wraps.
*/
@Override
@Nullable
BytesStore bytesStore();
default boolean isEqual(String s)
throws IllegalStateException {
return StringUtils.isEqual(this, s);
}
/**
* Compact these Bytes by moving the readPosition to the start.
*
* @return this
*/
@NotNull
Bytes<Underlying> compact()
throws IllegalStateException;
/**
* Copies bytes from this Bytes to another ByteStore.
*
* @param store the BytesStore to copy to
* @return the number of bytes copied
*/
@Override
default long copyTo(@NotNull BytesStore store)
throws IllegalStateException {
return BytesStore.super.copyTo(store);
}
/**
* Copies bytes from this Bytes to a specified OutputStream.
*
* @param out the specified OutputStream that this BytesStore is copied to
* @throws IllegalStateException if this Bytes has been released
* @throws IOException if an I/O error occurs
*/
@Override
default void copyTo(@NotNull OutputStream out)
throws IOException, IllegalStateException {
BytesStore.super.copyTo(out);
}
@Override
default boolean sharedMemory() {
return bytesStore().sharedMemory();
}
/**
* Will un-write a specified number of bytes from an offset from this Bytes.
* <p>
* Calling this method will update the cursors of this Bytes.
*
* @param fromOffset the offset from the target bytes
* @param count the number of bytes to un-write
*/
default void unwrite(long fromOffset, int count)
throws BufferUnderflowException, BufferOverflowException, IllegalStateException {
long wp = writePosition();
if (wp < fromOffset)
return;
write(fromOffset, this, fromOffset + count, wp - fromOffset - count);
writeSkip(-count);
}
@NotNull
default BigDecimal readBigDecimal()
throws ArithmeticException, BufferUnderflowException, IllegalStateException {
return new BigDecimal(readBigInteger(), Maths.toUInt31(readStopBit()));
}
@NotNull
default BigInteger readBigInteger()
throws ArithmeticException, BufferUnderflowException, IllegalStateException {
int length = Maths.toUInt31(readStopBit());
if (length == 0)
if (lenient())
return BigInteger.ZERO;
else
throw new BufferUnderflowException();
@NotNull byte[] bytes = new byte[length];
read(bytes);
return new BigInteger(bytes);
}
/**
* Returns the index within this Bytes of the first occurrence of the
* specified sub-bytes.
* <p>
* The returned index is the smallest value <i>k</i> for which:
* <blockquote><pre>
* this.startsWith(bytes, <i>k</i>)
* </pre></blockquote>
* If no such value of <i>k</i> exists, then {@code -1} is returned.
*
* @param source the sub-bytes to search for.
* @return the index of the first occurrence of the specified sub-bytes,
* or {@code -1} if there is no such occurrence.
*/
default long indexOf(@NotNull Bytes source)
throws IllegalStateException {
return indexOf(this, source, 0);
}
/**
* Returns the index within this Bytes of the first occurrence of the
* specified sub-bytes.
* <p>
* The returned index is the smallest value <i>k</i> for which:
* <blockquote><pre>
* this.startsWith(bytes, <i>k</i>)
* </pre></blockquote>
* If no such value of <i>k</i> exists, then {@code -1} is returned.
*
* @param source the sub-bytes to search for.
* @param fromIndex start the search from this offset
* @return the index of the first occurrence of the specified sub-bytes,
* or {@code -1} if there is no such occurrence.
*/
default int indexOf(@NotNull BytesStore source, int fromIndex)
throws IllegalStateException {
return indexOf(this, source, fromIndex);
}
@Override
@NotNull
Bytes<Underlying> clear()
throws IllegalStateException;
@Override
default boolean readWrite() {
return bytesStore().readWrite();
}
default void readWithLength(long length, @NotNull BytesOut<Underlying> bytesOut)
throws BufferUnderflowException, IORuntimeException, BufferOverflowException, IllegalStateException {
if (length > readRemaining())
throw new BufferUnderflowException();
long limit0 = readLimit();
long limit = readPosition() + length;
boolean lenient = lenient();
try {
lenient(true);
readLimit(limit);
bytesOut.write(this);
} finally {
readLimit(limit0);
readPosition(limit);
lenient(lenient);
}
}
default <T extends ReadBytesMarshallable> T readMarshallableLength16(Class<T> tClass, T object)
throws BufferUnderflowException, IllegalStateException {
if (object == null) object = ObjectUtils.newInstance(tClass);
int length = readUnsignedShort();
long limit = readLimit();
long end = readPosition() + length;
boolean lenient = lenient();
try {
lenient(true);
readLimit(end);
object.readMarshallable(this);
} finally {
readPosition(end);
readLimit(limit);
lenient(lenient);
}
return object;
}
default void writeMarshallableLength16(WriteBytesMarshallable marshallable)
throws IllegalArgumentException, BufferOverflowException, IllegalStateException, BufferUnderflowException {
long position = writePosition();
try {
writeUnsignedShort(0);
marshallable.writeMarshallable(this);
long length = writePosition() - position - 2;
if (length >= 1 << 16)
throw new IllegalStateException("Marshallable " + marshallable.getClass() + " too long was " + length);
writeUnsignedShort(position, (int) length);
} catch (ArithmeticException e) {
throw new AssertionError(e);
}
}
default Bytes write(final InputStream inputStream)
throws IOException, BufferOverflowException, IllegalStateException {
for (; ; ) {
int read;
read = inputStream.read();
if (read == -1)
break;
writeByte((byte) read);
}
return this;
}
} | Fix CQ with delta wire, closes https://github.com/ChronicleEnterprise/Chronicle-Queue-Enterprise/issues/262
| src/main/java/net/openhft/chronicle/bytes/Bytes.java | Fix CQ with delta wire, closes https://github.com/ChronicleEnterprise/Chronicle-Queue-Enterprise/issues/262 | <ide><path>rc/main/java/net/openhft/chronicle/bytes/Bytes.java
<ide> return;
<ide>
<ide> write(fromOffset, this, fromOffset + count, wp - fromOffset - count);
<del> writeSkip(-count);
<add> writePosition(wp - count);
<ide> }
<ide>
<ide> @NotNull |
|
JavaScript | mit | 7c23802b5821c8bfb7cd7a2ef161bf11dc2946a4 | 0 | nclandrei/Algorithm-Animator,nclandrei/Palgo,nclandrei/Palgo,nclandrei/Algorithm-Animator | var Vis = require('vis');
var remote = require('remote');
var dialog = remote.require('dialog');
var fs = require('fs');
var network;
var inc = 0;
$(document).ready(function () {
$('#submit-btn').click(function () {
if (network.body.data.nodes.get().length == 0) {
createAlert("You have not added any nodes to the graph.");
return;
}
if (network.body.data.edges.get().length == 0) {
createAlert("You have not added any edges to the graph.");
return;
}
var rootNode = findRootNode(network.body.data.nodes.get());
if (!rootNode) {
rootNode = network.body.data.nodes.get()[0];
rootNode.root = true;
$("#algo-panel").prepend(alertUserThatNoRoot());
}
var obj = getBFSPath(rootNode);
obj.path = markAllNodesAsUnvisited(obj.path);
bfsRootAnimation(obj.path);
rootCodeLineAnimation();
setTimeout(function () {
bfsNodesAnimation(obj.path, obj.iter - 1);
}, 3000);
});
});
// create a network
var container = $('#tree-simple')[0];
var options = {
autoResize: true,
manipulation: {
enabled: true,
initiallyActive: true,
addNode: function (nodeData, callback) {
if (network.body.nodes === {}) {
inc = 1;
}
else {
inc++;
}
nodeData.root = false;
nodeData.label = inc;
nodeData.color = '#009688';
nodeData.font = {
color: '#fff'
};
nodeData.visited = false;
nodeData.adjacencyList = [];
nodeData.predecessor = null;
callback(nodeData);
},
editNode: function (nodeData, callback) {
editNode(nodeData, callback);
},
addEdge: function (edgeData, callback) {
var fromNode = network.body.data.nodes.get().filter(function (x) {
return x.id === edgeData.from;
}
);
var toNode = network.body.data.nodes.get().filter(function (x) {
return x.id === edgeData.to;
}
);
fromNode[0].adjacencyList.push(toNode[0]);
if ($('#directed-chechbox').prop('checked')){
edgeData.arrows = {};
edgeData.arrows.to = true;
}
if (edgeData.from === edgeData.to) {
var r = confirm('Do you want to connect the node to itself?');
if (r === true) {
callback(edgeData);
}
}
else {
callback(edgeData);
}
},
editEdge: {
editWithoutDrag: function (data, callback) {
editEdgeWithoutDrag(data, callback);
}
}
},
interaction: {
navigationButtons: true
},
physics: {
enabled: false
}
};
network = new Vis.Network(container, [], options);
function bfsRootAnimation(path) {
var root = findRootNode(path);
for (var index = 1; index < 3; index++) {
(function (ind) {
setTimeout(function () {
if (ind === 1) {
root.visited = true;
root.color = '#3f51b5';
network = rebuildNetwork(path);
}
else {
appendToQueue(root.label);
}
}, (1000 * ind));
})(index);
}
}
// TODO: add code for line animation here instead of keeping 2 different functions
function bfsNodesAnimation(path, iter) {
var queue = [path[0]];
highlightCodeLine(3);
console.log("iter: " + iter);
for (var index = 0; index < iter; index++) {
(function (ind) {
setTimeout(function () {
var u = queue.shift();
unHighlightAllCodeLines();
highlightCodeLine(4);
highlightCodeLine(3);
removeFromQueue();
if (u && u.adjacencyList && u.adjacencyList.length > 0) {
var adjacencyList = u.adjacencyList;
for (var index1 = 0; index1 < adjacencyList.length; index1++) {
(function (ind1) {
setTimeout(function () {
unHighlightCodeLine(4);
unHighlightCodeLine(9);
highlightCodeLine(5);
if (!adjacencyList[ind1].visited) {
for (var index2 = 0; index2 < 3; index2++) {
(function (ind2) {
setTimeout(function() {
highlightCodeLine(6);
if (ind2 == 0) {
adjacencyList[ind1].predecessor = u;
adjacencyList[ind1].visited = true;
adjacencyList[ind1].color = '#3f51b5';
network = rebuildNetwork(path);
highlightCodeLine(7);
}
else if (ind2 == 1) {
unHighlightCodeLine(7);
highlightCodeLine(8)
}
else {
queue.push(adjacencyList[ind1]);
appendToQueue(adjacencyList[ind1].label);
unHighlightCodeLine(8);
highlightCodeLine(9);
}
}, 8000 * ind + ind1 * (1.0 * 7800 / adjacencyList.length) + ind2 * (1.0 * 7800 / adjacencyList.length / 3));
})(index2);
}
}
}, (1000 + 7000 * ind + ind1 * (1.0 * 7800 / adjacencyList.length)));
})(index1);
}
}
console.log((new Date()).getTime());
}, 8000 * ind);
})(index);
}
}
function rootCodeLineAnimation() {
for (var index1 = 0; index1 < 3; index1++) {
(function (ind1) {
setTimeout(function () {
unHighlightCodeLine(ind1 - 1);
highlightCodeLine(ind1);
}, (1000 * ind1));
})(index1);
}
}
// function bfsNodesCodeLineAnimation(clonePath, iter) {
// clonePath[0].visited = true;
// var queue1 = [];
// queue1.push(clonePath[0]);
// for (var indexCode = 0; indexCode < iter; indexCode++) {
// (function (indCode) {
// setTimeout(function () {
// console.log("hit");
// var u1 = queue1.shift();
// unHighlightAllCodeLines();
// highlightMultipleCodeLines([3, 4]);
// if (u1 && u1.adjacencyList && u1.adjacencyList.length > 0) {
// var adjacencyList1 = u1.adjacencyList;
// for (var indexCode1 = 0; indexCode1 < adjacencyList1.length; indexCode1++) {
// (function (indCode1) {
// set
// unHighlightAllCodeLines();
// highlightMultipleCodeLines([3, 5]);
// if (adjacencyList1[indCode1].visited === false) {
// for (var indexCode2 = 0; indexCode2 < 3; indexCode2++) {
// (function (indCode2) {
// setTimeout(function () {
// unHighlightAllCodeLines();
// highlightMultipleCodeLines([3, 5, 6]);
// var d = new Date();
// console.log(d.getTime());
// if (indCode2 == 0) {
// unHighlightAllCodeLines();
// highlightMultipleCodeLines([3, 5, 6, 7]);
// adjacencyList1[indCode1].visited = true;
// adjacencyList1[indCode1].color = '#3f51b5';
// }
// else if (indCode2 == 1) {
// adjacencyList1[indCode1].predecessor = u1;
// unHighlightAllCodeLines();
// highlightMultipleCodeLines([3, 5, 6,8]);
// }
// else if (indCode2 == 2) {
// unHighlightAllCodeLines();
// highlightMultipleCodeLines([3, 5, 6, 9]);
// queue1.push(adjacencyList1[indCode1]);
// }
// }, (8000 * indCode + indCode1 * (parseFloat(7900) / adjacencyList1.length) + indCode2 * (parseFloat(7800) / adjacencyList1.length / 3)));
// })(indexCode2);
// }
// }
// }, (8000 * indCode + indCode1 * (parseFloat(7900) / adjacencyList1.length)));
// })(indexCode1);
// }
// }
// }, 8000 * indCode);
// })(indexCode);
// }
// }
function getBFSPath(root) {
var queue = [root];
var numberOfQueueIterations = 0;
var path = [root];
queue.push(root);
while (queue.length > 0) {
var u = queue.shift();
var adjacencyList = u.adjacencyList;
for (var i = 0; i < adjacencyList.length; i++) {
if (!adjacencyList[i].visited) {
adjacencyList[i].visited = true;
adjacencyList[i].predecessor = u;
queue.push(adjacencyList[i]);
path.push(adjacencyList[i]);
}
}
numberOfQueueIterations++;
}
return {path: path, iter: numberOfQueueIterations};
}
function highlightCodeLine(number) {
$('#line-' + number).css('color', 'red');
}
function unHighlightCodeLine(number) {
$('#line-' + number).css('color', '#3f51b5');
}
function unHighlightAllCodeLines() {
for (var i = 0; i < 10; i++) {
unHighlightCodeLine(i);
}
}
function highlightMultipleCodeLines(array) {
for (var i = 0; i < array.length; i++) {
highlightCodeLine(array[i]);
}
}
function appendToQueue(text) {
var th = '<th>' + text + '</th>';
$('#queue-row').append(th);
}
function removeFromQueue() {
$('#queue-row').find('th:first').remove();
}
function markAllNodesAsUnvisited(path) {
for (var i = 0; i < path.length; i++) {
path[i].visited = false;
}
return path;
}
function createAlert(alertText) {
var alert = "<div id='customAlert' class='alert alert-dismissible alert-danger'> <button type='button' class='close' data-dismiss='alert'> x </button> <strong>Oh snap!</strong> " + alertText + ' </div>';
$('#algo-panel').prepend(alert);
}
function alertUserThatNoRoot() {
var alert = "<div class='alert alert-dismissible alert-info'> \
<button type='button' class='close' data-dismiss='alert'>x</button> \
<strong>Heads up!</strong> You have not selected any \
root node, so the first node will be automatically set as root. \
</div>";
return alert;
}
function rebuildNetwork(nodes) {
var data = {
nodes: nodes,
edges: network.body.data.edges
};
network.destroy();
network = new Vis.Network(container, data, options);
return network;
}
function editEdgeWithoutDrag(data, callback) {
$('#edge-label-text').removeClass('is-empty');
$('#edge-label').val(data.label);
$('#edge-saveButton').click(saveEdgeData.bind(this, data, callback));
$('#edge-cancelButton').click(cancelEdgeEdit.bind(this,callback));
$('#close-x').click(cancelEdgeEdit.bind(this,callback));
$('#edge-popUp').css('display', 'block');
}
function clearEdgePopUp() {
$('#edge-saveButton').click(null);
$('#edge-cancelButton').click(null);
$('#close-x').click(null);
$('#edge-popUp').css('display', 'none');
}
function cancelEdgeEdit(callback) {
clearEdgePopUp();
callback(null);
}
function saveEdgeData(data, callback) {
if (typeof data.to === 'object')
data.to = data.to.id;
if (typeof data.from === 'object')
data.from = data.from.id;
data.label = $('#edge-label').val();
clearEdgePopUp();
callback(data);
}
function editNode(data, callback) {
var nodeInData = network.body.data.nodes.get().filter(function (x) {
return x.id === data.id;
});
data.adjacencyList = nodeInData[0].adjacencyList;
if (data.root) {
$('#node-root-checkbox').prop('checked', true);
}
else {
$('#node-root-checkbox').prop('checked', false);
}
$('#node-label-text').removeClass('is-empty');
$('#node-label').val(data.label);
$('#node-saveButton').click(saveNodeData.bind(this, data, callback));
$('#node-cancelButton').click(cancelNodeEdit.bind(this, callback));
$('#close-x1').click(cancelNodeEdit.bind(this, callback));
$('#node-popUp').css('display', 'block');
}
function clearNodePopUp() {
$('#node-saveButton').click(null);
$('#node-cancelButton').click(null);
$('#close-x1').click(null);
$('#node-popUp').css('display', 'none');
}
function cancelNodeEdit(callback) {
clearNodePopUp();
callback(null);
}
function saveNodeData(data, callback) {
data.label = parseInt($('#node-label').val());
data.root = $('#node-root-checkbox').prop('checked');
clearNodePopUp();
callback(data);
}
function findRootNode(path) {
for (var i = 0; i < path.length; i++) {
if (path[i].root) {
return path[i];
}
}
}
function deepCopyPath(path) {
var returnArray = [];
for (var i = 0; i < path.length; i++) {
var node = new Node();
node.label = path[i].label;
node.adjacencyList = [];
for (var j = 0; j < path[i].adjacencyList.length; j++) {
var nodeTemp = new Node();
nodeTemp.label = path[i].adjacencyList[j].label;
nodeTemp.visited = path[i].adjacencyList[j].visited;
nodeTemp.color = path[i].adjacencyList[j].color;
nodeTemp.root = path[i].adjacencyList[j].root;
nodeTemp.font = path[i].adjacencyList[j].font;
node.adjacencyList.push(nodeTemp);
}
node.visited = false;
node.root = path[i].root;
node.color = path[i].color;
node.font = path[i].font;
returnArray.push(node);
}
return returnArray;
}
| js/bfs.js | var Vis = require('vis');
var remote = require('remote');
var dialog = remote.require('dialog');
var fs = require('fs');
var network;
var inc = 0;
$(document).ready(function () {
$('#submit-btn').click(function () {
if (network.body.data.nodes.get().length == 0) {
createAlert("You have not added any nodes to the graph.");
return;
}
if (network.body.data.edges.get().length == 0) {
createAlert("You have not added any edges to the graph.");
return;
}
var rootNode = findRootNode(network.body.data.nodes.get());
if (!rootNode) {
rootNode = network.body.data.nodes.get()[0];
rootNode.root = true;
$("#algo-panel").prepend(alertUserThatNoRoot());
}
var obj = getBFSPath(rootNode);
obj.path = markAllNodesAsUnvisited(obj.path);
var pathClone = deepCopyPath(obj.path);
bfsRootAnimation(obj.path);
rootCodeLineAnimation();
setTimeout(function () {
bfsNodesAnimation(obj.path, obj.iter);
}, 3000);
});
});
// create a network
var container = $('#tree-simple')[0];
var options = {
autoResize: true,
manipulation: {
enabled: true,
initiallyActive: true,
addNode: function (nodeData, callback) {
if (network.body.nodes === {}) {
inc = 1;
}
else {
inc++;
}
nodeData.root = false;
nodeData.label = inc;
nodeData.color = '#009688';
nodeData.font = {
color: '#fff'
};
nodeData.visited = false;
nodeData.adjacencyList = [];
nodeData.predecessor = null;
callback(nodeData);
},
editNode: function (nodeData, callback) {
editNode(nodeData, callback);
},
addEdge: function (edgeData, callback) {
var fromNode = network.body.data.nodes.get().filter(function (x) {
return x.id === edgeData.from;
}
);
var toNode = network.body.data.nodes.get().filter(function (x) {
return x.id === edgeData.to;
}
);
fromNode[0].adjacencyList.push(toNode[0]);
if ($('#directed-chechbox').prop('checked')){
edgeData.arrows = {};
edgeData.arrows.to = true;
}
if (edgeData.from === edgeData.to) {
var r = confirm('Do you want to connect the node to itself?');
if (r === true) {
callback(edgeData);
}
}
else {
callback(edgeData);
}
},
editEdge: {
editWithoutDrag: function (data, callback) {
editEdgeWithoutDrag(data, callback);
}
}
},
interaction: {
navigationButtons: true
},
physics: {
enabled: false
}
};
network = new Vis.Network(container, [], options);
function bfsRootAnimation(path) {
var root = findRootNode(path);
for (var index = 1; index < 3; index++) {
(function (ind) {
setTimeout(function () {
if (ind === 1) {
root.visited = true;
root.color = '#3f51b5';
network = rebuildNetwork(path);
}
else {
appendToQueue(root.label);
}
}, (1000 * ind));
})(index);
}
}
// TODO: add code for line animation here instead of keeping 2 different functions
function bfsNodesAnimation(path, iter) {
var queue = [path[0]];
highlightCodeLine(3);
for (var index = 0; index < iter; index++) {
(function (ind) {
setTimeout(function () {
var u = queue.shift();
highlightCodeLine(4);
removeFromQueue();
if (u && u.adjacencyList && u.adjacencyList.length > 0) {
var adjacencyList = u.adjacencyList;
for (var index1 = 0; index1 < adjacencyList.length; index1++) {
(function (ind1) {
setTimeout(function () {
unHighlightCodeLine(4);
unHighlightCodeLine(9);
highlightCodeLine(5);
if (!adjacencyList[ind1].visited) {
for (var index2 = 0; index2 < 3; index2++) {
(function (ind2) {
setTimeout(function() {
highlightCodeLine(6);
if (ind2 == 0) {
adjacencyList[ind1].predecessor = u;
highlightCodeLine(7);
}
else if (ind2 == 1) {
adjacencyList[ind1].visited = true;
adjacencyList[ind1].color = '#3f51b5';
network = rebuildNetwork(path);
unHighlightCodeLine(7);
highlightCodeLine(8)
}
else {
queue.push(adjacencyList[ind1]);
appendToQueue(adjacencyList[ind1].label);
unHighlightCodeLine(8);
highlightCodeLine(9);
}
}, 8000 * ind + ind1 * (parseFloat(7800) * adjacencyList.length) + ind2 * (parseFloat(7800) / adjacencyList.length) / 3);
})(index2);
}
}
}, (8000 * ind + ind1 * (parseFloat(7800) / adjacencyList.length)));
})(index1);
}
}
}, ((8000 * ind)));
})(index);
}
}
function rootCodeLineAnimation() {
for (var index1 = 0; index1 < 3; index1++) {
(function (ind1) {
setTimeout(function () {
unHighlightCodeLine(ind1 - 1);
highlightCodeLine(ind1);
}, (1000 * ind1));
})(index1);
}
}
// function bfsNodesCodeLineAnimation(clonePath, iter) {
// clonePath[0].visited = true;
// var queue1 = [];
// queue1.push(clonePath[0]);
// for (var indexCode = 0; indexCode < iter; indexCode++) {
// (function (indCode) {
// setTimeout(function () {
// console.log("hit");
// var u1 = queue1.shift();
// unHighlightAllCodeLines();
// highlightMultipleCodeLines([3, 4]);
// if (u1 && u1.adjacencyList && u1.adjacencyList.length > 0) {
// var adjacencyList1 = u1.adjacencyList;
// for (var indexCode1 = 0; indexCode1 < adjacencyList1.length; indexCode1++) {
// (function (indCode1) {
// set
// unHighlightAllCodeLines();
// highlightMultipleCodeLines([3, 5]);
// if (adjacencyList1[indCode1].visited === false) {
// for (var indexCode2 = 0; indexCode2 < 3; indexCode2++) {
// (function (indCode2) {
// setTimeout(function () {
// unHighlightAllCodeLines();
// highlightMultipleCodeLines([3, 5, 6]);
// var d = new Date();
// console.log(d.getTime());
// if (indCode2 == 0) {
// unHighlightAllCodeLines();
// highlightMultipleCodeLines([3, 5, 6, 7]);
// adjacencyList1[indCode1].visited = true;
// adjacencyList1[indCode1].color = '#3f51b5';
// }
// else if (indCode2 == 1) {
// adjacencyList1[indCode1].predecessor = u1;
// unHighlightAllCodeLines();
// highlightMultipleCodeLines([3, 5, 6,8]);
// }
// else if (indCode2 == 2) {
// unHighlightAllCodeLines();
// highlightMultipleCodeLines([3, 5, 6, 9]);
// queue1.push(adjacencyList1[indCode1]);
// }
// }, (8000 * indCode + indCode1 * (parseFloat(7900) / adjacencyList1.length) + indCode2 * (parseFloat(7800) / adjacencyList1.length / 3)));
// })(indexCode2);
// }
// }
// }, (8000 * indCode + indCode1 * (parseFloat(7900) / adjacencyList1.length)));
// })(indexCode1);
// }
// }
// }, 8000 * indCode);
// })(indexCode);
// }
// }
function getBFSPath(root) {
var queue = [root];
var numberOfQueueIterations = 0;
var path = [root];
queue.push(root);
while (queue.length > 0) {
var u = queue.shift();
var adjacencyList = u.adjacencyList;
for (var i = 0; i < adjacencyList.length; i++) {
if (!adjacencyList[i].visited) {
adjacencyList[i].visited = true;
adjacencyList[i].predecessor = u;
queue.push(adjacencyList[i]);
path.push(adjacencyList[i]);
}
}
numberOfQueueIterations++;
}
return {path: path, iter: numberOfQueueIterations};
}
function highlightCodeLine(number) {
$('#line-' + number).css('color', 'red');
}
function unHighlightCodeLine(number) {
$('#line-' + number).css('color', '#3f51b5');
}
function unHighlightAllCodeLines() {
for (var i = 0; i < 10; i++) {
unHighlightCodeLine(i);
}
}
function highlightMultipleCodeLines(array) {
for (var i = 0; i < array.length; i++) {
highlightCodeLine(array[i]);
}
}
function appendToQueue(text) {
var th = '<th>' + text + '</th>';
$('#queue-row').append(th);
}
function removeFromQueue() {
$('#queue-row').find('th:first').remove();
}
function markAllNodesAsUnvisited(path) {
for (var i = 0; i < path.length; i++) {
path[i].visited = false;
}
return path;
}
function createAlert(alertText) {
var alert = "<div id='customAlert' class='alert alert-dismissible alert-danger'> <button type='button' class='close' data-dismiss='alert'> x </button> <strong>Oh snap!</strong> " + alertText + ' </div>';
$('#algo-panel').prepend(alert);
}
function alertUserThatNoRoot() {
var alert = "<div class='alert alert-dismissible alert-info'> \
<button type='button' class='close' data-dismiss='alert'>x</button> \
<strong>Heads up!</strong> You have not selected any \
root node, so the first node will be automatically set as root. \
</div>";
return alert;
}
function rebuildNetwork(nodes) {
var data = {
nodes: nodes,
edges: network.body.data.edges
};
network.destroy();
network = new Vis.Network(container, data, options);
return network;
}
function editEdgeWithoutDrag(data, callback) {
$('#edge-label-text').removeClass('is-empty');
$('#edge-label').val(data.label);
$('#edge-saveButton').click(saveEdgeData.bind(this, data, callback));
$('#edge-cancelButton').click(cancelEdgeEdit.bind(this,callback));
$('#close-x').click(cancelEdgeEdit.bind(this,callback));
$('#edge-popUp').css('display', 'block');
}
function clearEdgePopUp() {
$('#edge-saveButton').click(null);
$('#edge-cancelButton').click(null);
$('#close-x').click(null);
$('#edge-popUp').css('display', 'none');
}
function cancelEdgeEdit(callback) {
clearEdgePopUp();
callback(null);
}
function saveEdgeData(data, callback) {
if (typeof data.to === 'object')
data.to = data.to.id;
if (typeof data.from === 'object')
data.from = data.from.id;
data.label = $('#edge-label').val();
clearEdgePopUp();
callback(data);
}
function editNode(data, callback) {
var nodeInData = network.body.data.nodes.get().filter(function (x) {
return x.id === data.id;
});
data.adjacencyList = nodeInData[0].adjacencyList;
if (data.root) {
$('#node-root-checkbox').prop('checked', true);
}
else {
$('#node-root-checkbox').prop('checked', false);
}
$('#node-label-text').removeClass('is-empty');
$('#node-label').val(data.label);
$('#node-saveButton').click(saveNodeData.bind(this, data, callback));
$('#node-cancelButton').click(cancelNodeEdit.bind(this, callback));
$('#close-x1').click(cancelNodeEdit.bind(this, callback));
$('#node-popUp').css('display', 'block');
}
function clearNodePopUp() {
$('#node-saveButton').click(null);
$('#node-cancelButton').click(null);
$('#close-x1').click(null);
$('#node-popUp').css('display', 'none');
}
function cancelNodeEdit(callback) {
clearNodePopUp();
callback(null);
}
function saveNodeData(data, callback) {
data.label = parseInt($('#node-label').val());
data.root = $('#node-root-checkbox').prop('checked');
clearNodePopUp();
callback(data);
}
function findRootNode(path) {
for (var i = 0; i < path.length; i++) {
if (path[i].root) {
return path[i];
}
}
}
function deepCopyPath(path) {
var returnArray = [];
for (var i = 0; i < path.length; i++) {
var node = new Node();
node.label = path[i].label;
node.adjacencyList = [];
for (var j = 0; j < path[i].adjacencyList.length; j++) {
var nodeTemp = new Node();
nodeTemp.label = path[i].adjacencyList[j].label;
nodeTemp.visited = path[i].adjacencyList[j].visited;
nodeTemp.color = path[i].adjacencyList[j].color;
nodeTemp.root = path[i].adjacencyList[j].root;
nodeTemp.font = path[i].adjacencyList[j].font;
node.adjacencyList.push(nodeTemp);
}
node.visited = false;
node.root = path[i].root;
node.color = path[i].color;
node.font = path[i].font;
returnArray.push(node);
}
return returnArray;
}
| timing almost close to perfect
| js/bfs.js | timing almost close to perfect | <ide><path>s/bfs.js
<ide> }
<ide> var obj = getBFSPath(rootNode);
<ide> obj.path = markAllNodesAsUnvisited(obj.path);
<del> var pathClone = deepCopyPath(obj.path);
<ide> bfsRootAnimation(obj.path);
<ide> rootCodeLineAnimation();
<ide> setTimeout(function () {
<del> bfsNodesAnimation(obj.path, obj.iter);
<add> bfsNodesAnimation(obj.path, obj.iter - 1);
<ide> }, 3000);
<ide> });
<ide> });
<ide> function bfsNodesAnimation(path, iter) {
<ide> var queue = [path[0]];
<ide> highlightCodeLine(3);
<add> console.log("iter: " + iter);
<ide> for (var index = 0; index < iter; index++) {
<ide> (function (ind) {
<ide> setTimeout(function () {
<ide> var u = queue.shift();
<add> unHighlightAllCodeLines();
<ide> highlightCodeLine(4);
<add> highlightCodeLine(3);
<ide> removeFromQueue();
<ide> if (u && u.adjacencyList && u.adjacencyList.length > 0) {
<ide> var adjacencyList = u.adjacencyList;
<ide> highlightCodeLine(6);
<ide> if (ind2 == 0) {
<ide> adjacencyList[ind1].predecessor = u;
<add> adjacencyList[ind1].visited = true;
<add> adjacencyList[ind1].color = '#3f51b5';
<add> network = rebuildNetwork(path);
<ide> highlightCodeLine(7);
<ide> }
<ide> else if (ind2 == 1) {
<del> adjacencyList[ind1].visited = true;
<del> adjacencyList[ind1].color = '#3f51b5';
<del> network = rebuildNetwork(path);
<ide> unHighlightCodeLine(7);
<ide> highlightCodeLine(8)
<ide> }
<ide> unHighlightCodeLine(8);
<ide> highlightCodeLine(9);
<ide> }
<del> }, 8000 * ind + ind1 * (parseFloat(7800) * adjacencyList.length) + ind2 * (parseFloat(7800) / adjacencyList.length) / 3);
<add> }, 8000 * ind + ind1 * (1.0 * 7800 / adjacencyList.length) + ind2 * (1.0 * 7800 / adjacencyList.length / 3));
<ide> })(index2);
<ide> }
<ide> }
<del> }, (8000 * ind + ind1 * (parseFloat(7800) / adjacencyList.length)));
<add> }, (1000 + 7000 * ind + ind1 * (1.0 * 7800 / adjacencyList.length)));
<ide> })(index1);
<ide> }
<ide> }
<del> }, ((8000 * ind)));
<add> console.log((new Date()).getTime());
<add> }, 8000 * ind);
<ide> })(index);
<ide> }
<ide> } |
|
Java | apache-2.0 | ac9922c90b96ce910fa3e37e3bd48963c859adea | 0 | wschaeferB/autopsy,rcordovano/autopsy,mhmdfy/autopsy,wschaeferB/autopsy,sidheshenator/autopsy,millmanorama/autopsy,APriestman/autopsy,esaunders/autopsy,karlmortensen/autopsy,raman-bt/autopsy,esaunders/autopsy,sidheshenator/autopsy,raman-bt/autopsy,dgrove727/autopsy,raman-bt/autopsy,millmanorama/autopsy,millmanorama/autopsy,APriestman/autopsy,sidheshenator/autopsy,raman-bt/autopsy,APriestman/autopsy,karlmortensen/autopsy,karlmortensen/autopsy,maxrp/autopsy,mhmdfy/autopsy,narfindustries/autopsy,maxrp/autopsy,eXcomm/autopsy,narfindustries/autopsy,raman-bt/autopsy,eXcomm/autopsy,rcordovano/autopsy,raman-bt/autopsy,rcordovano/autopsy,sidheshenator/autopsy,raman-bt/autopsy,rcordovano/autopsy,esaunders/autopsy,mhmdfy/autopsy,APriestman/autopsy,dgrove727/autopsy,wschaeferB/autopsy,maxrp/autopsy,APriestman/autopsy,maxrp/autopsy,esaunders/autopsy,karlmortensen/autopsy,millmanorama/autopsy,rcordovano/autopsy,mhmdfy/autopsy,esaunders/autopsy,rcordovano/autopsy,APriestman/autopsy,dgrove727/autopsy,eXcomm/autopsy,narfindustries/autopsy,APriestman/autopsy,wschaeferB/autopsy,wschaeferB/autopsy,eXcomm/autopsy | /*
* Autopsy Forensic Browser
*
* Copyright 2012 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sleuthkit.autopsy.corecomponents;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import org.sleuthkit.autopsy.coreutils.Logger;
import javax.swing.ListSelectionModel;
import javax.swing.SwingWorker;
import org.netbeans.api.progress.ProgressHandle;
import org.netbeans.api.progress.ProgressHandleFactory;
import org.openide.explorer.ExplorerManager;
import org.openide.explorer.view.IconView;
import org.openide.nodes.AbstractNode;
import org.openide.nodes.Children;
import org.openide.nodes.Node;
import org.openide.nodes.NodeEvent;
import org.openide.nodes.NodeListener;
import org.openide.nodes.NodeMemberEvent;
import org.openide.nodes.NodeReorderEvent;
import org.openide.util.lookup.ServiceProvider;
import org.sleuthkit.autopsy.corecomponentinterfaces.DataResultViewer;
/**
* Thumbnail view of images in data result with paging support.
*
* Paging is added to reduce memory footprint and load only up to (currently)
* 1000 images at a time. This works whether or not the underlying content nodes
* are being lazy loaded or not.
*
*/
@ServiceProvider(service = DataResultViewer.class)
public final class DataResultViewerThumbnail extends AbstractDataResultViewer {
private static final Logger logger = Logger.getLogger(DataResultViewerThumbnail.class.getName());
//flag to keep track if images are being loaded
private int curPage;
private int totalPages;
private final PageUpdater pageUpdater = new PageUpdater();
/**
* Creates new form DataResultViewerThumbnail
*/
public DataResultViewerThumbnail() {
super();
initComponents();
// only allow one item to be selected at a time
((IconView) thumbnailScrollPanel).setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
curPage = -1;
totalPages = 0;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
thumbnailScrollPanel = new IconView();
pageLabel = new javax.swing.JLabel();
curPageLabel = new javax.swing.JLabel();
ofLabel = new javax.swing.JLabel();
totalPagesLabel = new javax.swing.JLabel();
pagesLabel = new javax.swing.JLabel();
pagePrevButton = new javax.swing.JButton();
pageNextButton = new javax.swing.JButton();
thumbnailScrollPanel.setPreferredSize(null);
pageLabel.setText(org.openide.util.NbBundle.getMessage(DataResultViewerThumbnail.class, "DataResultViewerThumbnail.pageLabel.text")); // NOI18N
curPageLabel.setText(org.openide.util.NbBundle.getMessage(DataResultViewerThumbnail.class, "DataResultViewerThumbnail.curPageLabel.text")); // NOI18N
ofLabel.setText(org.openide.util.NbBundle.getMessage(DataResultViewerThumbnail.class, "DataResultViewerThumbnail.ofLabel.text")); // NOI18N
totalPagesLabel.setText(org.openide.util.NbBundle.getMessage(DataResultViewerThumbnail.class, "DataResultViewerThumbnail.totalPagesLabel.text")); // NOI18N
pagesLabel.setText(org.openide.util.NbBundle.getMessage(DataResultViewerThumbnail.class, "DataResultViewerThumbnail.pagesLabel.text")); // NOI18N
pagePrevButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/corecomponents/btn_step_back.png"))); // NOI18N
pagePrevButton.setText(org.openide.util.NbBundle.getMessage(DataResultViewerThumbnail.class, "DataResultViewerThumbnail.pagePrevButton.text")); // NOI18N
pagePrevButton.setDisabledIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/corecomponents/btn_step_back_disabled.png"))); // NOI18N
pagePrevButton.setMargin(new java.awt.Insets(2, 0, 2, 0));
pagePrevButton.setMaximumSize(new java.awt.Dimension(27, 31));
pagePrevButton.setMinimumSize(new java.awt.Dimension(27, 31));
pagePrevButton.setPreferredSize(new java.awt.Dimension(55, 23));
pagePrevButton.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/corecomponents/btn_step_back_hover.png"))); // NOI18N
pagePrevButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
pagePrevButtonActionPerformed(evt);
}
});
pageNextButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/corecomponents/btn_step_forward.png"))); // NOI18N
pageNextButton.setText(org.openide.util.NbBundle.getMessage(DataResultViewerThumbnail.class, "DataResultViewerThumbnail.pageNextButton.text")); // NOI18N
pageNextButton.setDisabledIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/corecomponents/btn_step_forward_disabled.png"))); // NOI18N
pageNextButton.setMargin(new java.awt.Insets(2, 0, 2, 0));
pageNextButton.setMaximumSize(new java.awt.Dimension(27, 23));
pageNextButton.setMinimumSize(new java.awt.Dimension(27, 23));
pageNextButton.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/corecomponents/btn_step_forward_hover.png"))); // NOI18N
pageNextButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
pageNextButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(thumbnailScrollPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 675, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(pageLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(curPageLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(ofLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(totalPagesLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(61, 61, 61)
.addComponent(pagesLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(pagePrevButton, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(pageNextButton, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(pageLabel)
.addComponent(curPageLabel)
.addComponent(ofLabel)
.addComponent(totalPagesLabel)
.addComponent(pagesLabel)
.addComponent(pagePrevButton, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(pageNextButton, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)))
.addComponent(thumbnailScrollPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 325, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
private void pagePrevButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pagePrevButtonActionPerformed
previousPage();
}//GEN-LAST:event_pagePrevButtonActionPerformed
private void pageNextButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pageNextButtonActionPerformed
nextPage();
}//GEN-LAST:event_pageNextButtonActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel curPageLabel;
private javax.swing.JLabel ofLabel;
private javax.swing.JLabel pageLabel;
private javax.swing.JButton pageNextButton;
private javax.swing.JButton pagePrevButton;
private javax.swing.JLabel pagesLabel;
private javax.swing.JScrollPane thumbnailScrollPanel;
private javax.swing.JLabel totalPagesLabel;
// End of variables declaration//GEN-END:variables
@Override
public boolean isSupported(Node selectedNode) {
if (selectedNode == null) {
return false;
}
//TODO quering children will need to change after lazy loading of original nodes works.
//we will need to query children of the datamodel object instead,
//or force children creation, breaking the lazy loading.
Children ch = selectedNode.getChildren();
for (Node n : ch.getNodes()) {
if (ThumbnailViewChildren.isSupported(n)) {
return true;
}
}
return false;
}
@Override
public void setNode(Node givenNode) {
// change the cursor to "waiting cursor" for this operation
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
try {
if (givenNode != null) {
ThumbnailViewChildren childNode = new ThumbnailViewChildren(givenNode);
final Node root = new AbstractNode(childNode);
pageUpdater.setRoot(root);
root.addNodeListener(pageUpdater);
em.setRootContext(root);
} else {
Node emptyNode = new AbstractNode(Children.LEAF);
em.setRootContext(emptyNode); // make empty node
IconView iv = ((IconView) this.thumbnailScrollPanel);
iv.setBackground(Color.BLACK);
}
} finally {
this.setCursor(null);
}
}
@Override
public String getTitle() {
return "Thumbnail View";
}
@Override
public DataResultViewer getInstance() {
return new DataResultViewerThumbnail();
}
@Override
public void clearComponent() {
this.thumbnailScrollPanel.removeAll();
this.thumbnailScrollPanel = null;
//this destroyes em
super.clearComponent();
}
private void nextPage() {
if (curPage < totalPages) {
curPage++;
switchPage();
}
}
private void previousPage() {
if (curPage > 1) {
curPage--;
switchPage();
}
}
private void switchPage() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
}
});
//Note the nodes factories are likely creating nodes in EDT anyway, but worker still helps
new SwingWorker<Object, Void>() {
private ProgressHandle progress;
@Override
protected Object doInBackground() throws Exception {
pagePrevButton.setEnabled(false);
pageNextButton.setEnabled(false);
progress = ProgressHandleFactory.createHandle("Generating Thumbnails...");
progress.start();
progress.switchToIndeterminate();
Node root = em.getRootContext();
Node pageNode = root.getChildren().getNodeAt(curPage - 1);
em.setExploredContext(pageNode);
return null;
}
@Override
protected void done() {
progress.finish();
setCursor(null);
updateControls();
}
}.execute();
}
private void updateControls() {
if (totalPages == 0) {
pagePrevButton.setEnabled(false);
pageNextButton.setEnabled(false);
curPageLabel.setText("");
totalPagesLabel.setText("");
} else {
curPageLabel.setText(Integer.toString(curPage));
totalPagesLabel.setText(Integer.toString(totalPages));
pageNextButton.setEnabled(!(curPage == totalPages));
pagePrevButton.setEnabled(!(curPage == 1));
}
}
/**
* Listens for root change updates and updates the paging controls
*/
private class PageUpdater implements NodeListener {
private Node root;
void setRoot(Node root) {
this.root = root;
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
}
@Override
public void childrenAdded(NodeMemberEvent nme) {
totalPages = root.getChildren().getNodesCount();
if (curPage == -1) {
curPage = 1;
}
updateControls();
//force load the curPage node
final Node pageNode = root.getChildren().getNodeAt(curPage - 1);
//em.setSelectedNodes(new Node[]{pageNode});
if (pageNode != null) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
em.setExploredContext(pageNode);
}
});
}
}
@Override
public void childrenRemoved(NodeMemberEvent nme) {
totalPages = 0;
curPage = -1;
updateControls();
}
@Override
public void childrenReordered(NodeReorderEvent nre) {
}
@Override
public void nodeDestroyed(NodeEvent ne) {
}
}
}
| Core/src/org/sleuthkit/autopsy/corecomponents/DataResultViewerThumbnail.java | /*
* Autopsy Forensic Browser
*
* Copyright 2012 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sleuthkit.autopsy.corecomponents;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import org.sleuthkit.autopsy.coreutils.Logger;
import javax.swing.ListSelectionModel;
import javax.swing.SwingWorker;
import org.netbeans.api.progress.ProgressHandle;
import org.netbeans.api.progress.ProgressHandleFactory;
import org.openide.explorer.ExplorerManager;
import org.openide.explorer.view.IconView;
import org.openide.nodes.AbstractNode;
import org.openide.nodes.Children;
import org.openide.nodes.Node;
import org.openide.nodes.NodeEvent;
import org.openide.nodes.NodeListener;
import org.openide.nodes.NodeMemberEvent;
import org.openide.nodes.NodeReorderEvent;
import org.openide.util.lookup.ServiceProvider;
import org.sleuthkit.autopsy.corecomponentinterfaces.DataResultViewer;
/**
* Thumbnail view of images in data result with paging support.
*
* Paging is added to reduce memory footprint and load only up to (currently)
* 1000 images at a time. This works whether or not the underlying content nodes
* are being lazy loaded or not.
*
*/
@ServiceProvider(service = DataResultViewer.class)
public final class DataResultViewerThumbnail extends AbstractDataResultViewer {
private static final Logger logger = Logger.getLogger(DataResultViewerThumbnail.class.getName());
//flag to keep track if images are being loaded
private int curPage;
private int totalPages;
private final PageUpdater pageUpdater = new PageUpdater();
/**
* Creates new form DataResultViewerThumbnail
*/
public DataResultViewerThumbnail() {
super();
initComponents();
// only allow one item to be selected at a time
((IconView) thumbnailScrollPanel).setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
curPage = -1;
totalPages = 0;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
thumbnailScrollPanel = new IconView();
pageLabel = new javax.swing.JLabel();
curPageLabel = new javax.swing.JLabel();
ofLabel = new javax.swing.JLabel();
totalPagesLabel = new javax.swing.JLabel();
pagesLabel = new javax.swing.JLabel();
pagePrevButton = new javax.swing.JButton();
pageNextButton = new javax.swing.JButton();
thumbnailScrollPanel.setPreferredSize(null);
pageLabel.setText(org.openide.util.NbBundle.getMessage(DataResultViewerThumbnail.class, "DataResultViewerThumbnail.pageLabel.text")); // NOI18N
curPageLabel.setText(org.openide.util.NbBundle.getMessage(DataResultViewerThumbnail.class, "DataResultViewerThumbnail.curPageLabel.text")); // NOI18N
ofLabel.setText(org.openide.util.NbBundle.getMessage(DataResultViewerThumbnail.class, "DataResultViewerThumbnail.ofLabel.text")); // NOI18N
totalPagesLabel.setText(org.openide.util.NbBundle.getMessage(DataResultViewerThumbnail.class, "DataResultViewerThumbnail.totalPagesLabel.text")); // NOI18N
pagesLabel.setText(org.openide.util.NbBundle.getMessage(DataResultViewerThumbnail.class, "DataResultViewerThumbnail.pagesLabel.text")); // NOI18N
pagePrevButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/corecomponents/btn_step_back.png"))); // NOI18N
pagePrevButton.setText(org.openide.util.NbBundle.getMessage(DataResultViewerThumbnail.class, "DataResultViewerThumbnail.pagePrevButton.text")); // NOI18N
pagePrevButton.setDisabledIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/corecomponents/btn_step_back_disabled.png"))); // NOI18N
pagePrevButton.setMargin(new java.awt.Insets(2, 0, 2, 0));
pagePrevButton.setMaximumSize(new java.awt.Dimension(27, 31));
pagePrevButton.setMinimumSize(new java.awt.Dimension(27, 31));
pagePrevButton.setPreferredSize(new java.awt.Dimension(55, 23));
pagePrevButton.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/corecomponents/btn_step_back_hover.png"))); // NOI18N
pagePrevButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
pagePrevButtonActionPerformed(evt);
}
});
pageNextButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/corecomponents/btn_step_forward.png"))); // NOI18N
pageNextButton.setText(org.openide.util.NbBundle.getMessage(DataResultViewerThumbnail.class, "DataResultViewerThumbnail.pageNextButton.text")); // NOI18N
pageNextButton.setDisabledIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/corecomponents/btn_step_forward_disabled.png"))); // NOI18N
pageNextButton.setMargin(new java.awt.Insets(2, 0, 2, 0));
pageNextButton.setMaximumSize(new java.awt.Dimension(27, 23));
pageNextButton.setMinimumSize(new java.awt.Dimension(27, 23));
pageNextButton.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/org/sleuthkit/autopsy/corecomponents/btn_step_forward_hover.png"))); // NOI18N
pageNextButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
pageNextButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(thumbnailScrollPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 675, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(pageLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(curPageLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(ofLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(totalPagesLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(61, 61, 61)
.addComponent(pagesLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(pagePrevButton, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(pageNextButton, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(pageLabel)
.addComponent(curPageLabel)
.addComponent(ofLabel)
.addComponent(totalPagesLabel)
.addComponent(pagesLabel)
.addComponent(pagePrevButton, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(pageNextButton, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)))
.addComponent(thumbnailScrollPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 325, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
private void pagePrevButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pagePrevButtonActionPerformed
previousPage();
}//GEN-LAST:event_pagePrevButtonActionPerformed
private void pageNextButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pageNextButtonActionPerformed
nextPage();
}//GEN-LAST:event_pageNextButtonActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel curPageLabel;
private javax.swing.JLabel ofLabel;
private javax.swing.JLabel pageLabel;
private javax.swing.JButton pageNextButton;
private javax.swing.JButton pagePrevButton;
private javax.swing.JLabel pagesLabel;
private javax.swing.JScrollPane thumbnailScrollPanel;
private javax.swing.JLabel totalPagesLabel;
// End of variables declaration//GEN-END:variables
@Override
public boolean isSupported(Node selectedNode) {
if (selectedNode == null) {
return false;
}
//TODO quering children will need to change after lazy loading of original nodes works.
//we will need to query children of the datamodel object instead,
//or force children creation, breaking the lazy loading.
Children ch = selectedNode.getChildren();
for (Node n : ch.getNodes()) {
if (ThumbnailViewChildren.isSupported(n)) {
return true;
}
}
return false;
}
@Override
public void setNode(Node givenNode) {
// change the cursor to "waiting cursor" for this operation
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
try {
if (givenNode != null) {
ThumbnailViewChildren childNode = new ThumbnailViewChildren(givenNode);
final Node root = new AbstractNode(childNode);
pageUpdater.setRoot(root);
root.addNodeListener(pageUpdater);
em.setRootContext(root);
} else {
Node emptyNode = new AbstractNode(Children.LEAF);
em.setRootContext(emptyNode); // make empty node
IconView iv = ((IconView) this.thumbnailScrollPanel);
iv.setBackground(Color.BLACK);
}
} finally {
this.setCursor(null);
}
}
@Override
public String getTitle() {
return "Thumbnail View";
}
@Override
public DataResultViewer getInstance() {
return new DataResultViewerThumbnail();
}
@Override
public void clearComponent() {
this.thumbnailScrollPanel.removeAll();
this.thumbnailScrollPanel = null;
//this destroyes em
super.clearComponent();
}
private void nextPage() {
if (curPage < totalPages) {
curPage++;
switchPage();
}
}
private void previousPage() {
if (curPage > 1) {
curPage--;
switchPage();
}
}
private void switchPage() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
}
});
//Note the nodes factories are likely creating nodes in EDT anyway, but worker still helps
new SwingWorker<Object,Void>() {
private ProgressHandle progress;
@Override
protected Object doInBackground() throws Exception {
pagePrevButton.setEnabled(false);
pageNextButton.setEnabled(false);
progress = ProgressHandleFactory.createHandle("Generating Thumbnails...");
progress.start();
progress.switchToIndeterminate();
Node root = em.getRootContext();
Node pageNode = root.getChildren().getNodeAt(curPage - 1);
em.setExploredContext(pageNode);
return null;
}
@Override
protected void done() {
progress.finish();
setCursor(null);
updateControls();
}
}.execute();
}
private void updateControls() {
if (totalPages == 0) {
pagePrevButton.setEnabled(false);
pageNextButton.setEnabled(false);
curPageLabel.setText("");
totalPagesLabel.setText("");
} else {
curPageLabel.setText(Integer.toString(curPage));
totalPagesLabel.setText(Integer.toString(totalPages));
pageNextButton.setEnabled(!(curPage == totalPages));
pagePrevButton.setEnabled(!(curPage == 1));
}
}
/**
* Listens for root change updates and updates the paging controls
*/
private class PageUpdater implements NodeListener {
private Node root;
void setRoot(Node root) {
this.root = root;
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
}
@Override
public void childrenAdded(NodeMemberEvent nme) {
totalPages = root.getChildren().getNodesCount();
if (curPage == -1) {
curPage = 1;
}
updateControls();
//force load the curPage node
Node pageNode = root.getChildren().getNodeAt(curPage - 1);
//em.setSelectedNodes(new Node[]{pageNode});
em.setExploredContext(pageNode);
}
@Override
public void childrenRemoved(NodeMemberEvent nme) {
totalPages = 0;
curPage = -1;
updateControls();
}
@Override
public void childrenReordered(NodeReorderEvent nre) {
}
@Override
public void nodeDestroyed(NodeEvent ne) {
}
}
}
| fix initial load in some cases
| Core/src/org/sleuthkit/autopsy/corecomponents/DataResultViewerThumbnail.java | fix initial load in some cases | <ide><path>ore/src/org/sleuthkit/autopsy/corecomponents/DataResultViewerThumbnail.java
<ide> });
<ide>
<ide> //Note the nodes factories are likely creating nodes in EDT anyway, but worker still helps
<del> new SwingWorker<Object,Void>() {
<add> new SwingWorker<Object, Void>() {
<ide> private ProgressHandle progress;
<ide>
<ide> @Override
<ide>
<ide>
<ide> //force load the curPage node
<del> Node pageNode = root.getChildren().getNodeAt(curPage - 1);
<add> final Node pageNode = root.getChildren().getNodeAt(curPage - 1);
<ide>
<ide> //em.setSelectedNodes(new Node[]{pageNode});
<del> em.setExploredContext(pageNode);
<add> if (pageNode != null) {
<add> EventQueue.invokeLater(new Runnable() {
<add> @Override
<add> public void run() {
<add> em.setExploredContext(pageNode);
<add> }
<add> });
<add> }
<add>
<ide> }
<ide>
<ide> @Override |
|
Java | apache-2.0 | f49c14573cff01f4db12a70f905f137eb364598e | 0 | thesmartenergy/sparql-generate-jena,thesmartenergy/sparql-generate-jena,thesmartenergy/sparql-generate,thesmartenergy/sparql-generate,thesmartenergy/sparql-generate,thesmartenergy/sparql-generate | /*
* Copyright 2019 École des Mines de Saint-Étienne.
*
* 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 fr.emse.ci.sparqlext.function;
import fr.emse.ci.sparqlext.SPARQLExt;
import fr.emse.ci.sparqlext.iterator.IteratorFunction;
import fr.emse.ci.sparqlext.iterator.IteratorFunctionFactory;
import fr.emse.ci.sparqlext.query.SPARQLExtQuery;
import fr.emse.ci.sparqlext.stream.LookUpRequest;
import fr.emse.ci.sparqlext.stream.SPARQLExtStreamManager;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import org.apache.commons.io.IOUtils;
import org.apache.jena.atlas.logging.Log;
import org.apache.jena.atlas.web.TypedInputStream;
import org.apache.jena.query.QueryBuildException;
import org.apache.jena.query.QueryFactory;
import org.apache.jena.riot.SysRIOT;
import org.apache.jena.sparql.function.Function;
import org.apache.jena.sparql.function.FunctionFactory;
import org.apache.jena.sparql.function.FunctionRegistry;
import org.apache.jena.sparql.util.Context;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author maxime.lefrancois
*/
public class SPARQLExtFunctionRegistry extends FunctionRegistry {
private static final Logger LOG = LoggerFactory.getLogger(SPARQLExtFunctionRegistry.class);
private final Context context;
private final Map<String, FunctionFactory> registry = new HashMap<>();
private final Set<String> attemptedLoads = new HashSet<>();
public SPARQLExtFunctionRegistry(FunctionRegistry parent, Context context) {
Iterator<String> uris = parent.keys();
while (uris.hasNext()) {
String uri = uris.next();
registry.put(uri, parent.get(uri));
}
this.context = context;
}
/**
* Insert a class that is the function implementation
*
* @param uri String URI
* @param funcClass Class for the function (new instance called).
*/
@Override
public void put(String uri, Class<?> funcClass) {
if (!Function.class.isAssignableFrom(funcClass)) {
Log.warn(this, "Class " + funcClass.getName() + " is not a Function");
return;
}
put(uri, new FunctionFactoryAuto(funcClass));
}
/**
* Insert a function. Re-inserting with the same URI overwrites the old
* entry.
*
* @param uri
* @param f
*/
@Override
public void put(String uri, FunctionFactory f) {
registry.put(uri, f);
}
@Override
public boolean isRegistered(String uri) {
return registry.containsKey(uri);
}
/**
* Remove by URI
*
* @param uri
* @return
*/
@Override
public FunctionFactory remove(String uri) {
return registry.remove(uri);
}
/**
* Lookup by URI
*
* @return the function, or null
*/
@Override
public FunctionFactory get(String uri) {
if (registry.get(uri) != null) {
return registry.get(uri);
}
if (attemptedLoads.contains(uri)) {
return null;
}
final LookUpRequest req = new LookUpRequest(uri, "application/vnd.sparql-generate");
final SPARQLExtStreamManager sm = (SPARQLExtStreamManager) context.get(SysRIOT.sysStreamManager);
Objects.requireNonNull(sm);
TypedInputStream tin = sm.open(req);
if (tin == null) {
LOG.warn(String.format("Could not look up function %s", uri));
attemptedLoads.add(uri);
return null;
}
String functionString;
try {
functionString = IOUtils.toString(tin.getInputStream(), StandardCharsets.UTF_8);
} catch (IOException ex) {
LOG.warn(String.format("Could not read function %s as UTF-8 string", uri));
attemptedLoads.add(uri);
return null;
}
SPARQLExtQuery functionQuery;
try {
functionQuery = (SPARQLExtQuery) QueryFactory.create(functionString, SPARQLExt.SYNTAX);
} catch (Exception ex) {
LOG.warn(String.format("Could not parse function %s", uri), ex);
attemptedLoads.add(uri);
return null;
}
if (!functionQuery.isFunctionType()) {
LOG.warn(String.format("The query is not a function: %s", uri));
attemptedLoads.add(uri);
return null;
}
final SPARQLExtFunctionFactory function = new SPARQLExtFunctionFactory(functionQuery);
put(uri, function);
attemptedLoads.add(uri);
return function;
}
class FunctionFactoryAuto implements FunctionFactory {
Class<?> extClass;
FunctionFactoryAuto(Class<?> xClass) {
extClass = xClass;
}
@Override
public Function create(String uri) {
try {
return (Function) extClass.newInstance();
} catch (Exception e) {
LOG.debug("Can't instantiate function"
+ " for " + uri, e);
throw new QueryBuildException("Can't instantiate function"
+ " for " + uri, e);
}
}
}
class SPARQLExtFunctionFactory implements FunctionFactory {
final SPARQLExtQuery functionQuery;
public SPARQLExtFunctionFactory(final SPARQLExtQuery functionQuery) {
this.functionQuery = functionQuery;
}
@Override
public Function create(String uri) {
return new SPARQLExtFunction(functionQuery);
}
}
}
| sparql-generate/src/main/java/fr/emse/ci/sparqlext/function/SPARQLExtFunctionRegistry.java | /*
* Copyright 2019 École des Mines de Saint-Étienne.
*
* 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 fr.emse.ci.sparqlext.function;
import fr.emse.ci.sparqlext.SPARQLExt;
import fr.emse.ci.sparqlext.query.SPARQLExtQuery;
import fr.emse.ci.sparqlext.stream.LookUpRequest;
import fr.emse.ci.sparqlext.stream.SPARQLExtStreamManager;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import org.apache.commons.io.IOUtils;
import org.apache.jena.atlas.logging.Log;
import org.apache.jena.atlas.web.TypedInputStream;
import org.apache.jena.query.QueryFactory;
import org.apache.jena.riot.SysRIOT;
import org.apache.jena.sparql.function.Function;
import org.apache.jena.sparql.function.FunctionFactory;
import org.apache.jena.sparql.function.FunctionRegistry;
import org.apache.jena.sparql.util.Context;
import org.apache.jena.sparql.util.MappedLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author maxime.lefrancois
*/
public class SPARQLExtFunctionRegistry extends FunctionRegistry {
private static final Logger LOG = LoggerFactory.getLogger(SPARQLExtFunctionRegistry.class);
private final Context context;
Map<String, FunctionFactory> registry = new HashMap<>();
private final Set<String> attemptedLoads = new HashSet<>();
public SPARQLExtFunctionRegistry(FunctionRegistry parent, Context context) {
Iterator<String> uris = parent.keys();
while (uris.hasNext()) {
String uri = uris.next();
registry.put(uri, parent.get(uri));
}
this.context = context;
}
/**
* Insert a class that is the function implementation
*
* @param uri String URI
* @param funcClass Class for the function (new instance called).
*/
@Override
public void put(String uri, Class<?> funcClass) {
throw new UnsupportedOperationException("Should not reach this point");
}
/**
* Insert a function. Re-inserting with the same URI overwrites the old
* entry.
*
* @param uri
* @param f
*/
@Override
public void put(String uri, FunctionFactory f) {
registry.put(uri, f);
}
@Override
public boolean isRegistered(String uri) {
return registry.containsKey(uri);
}
/**
* Remove by URI
* @param uri
* @return
*/
@Override
public FunctionFactory remove(String uri) {
return registry.remove(uri);
}
/**
* Lookup by URI
*
* @return the function, or null
*/
@Override
public FunctionFactory get(String uri) {
if (registry.get(uri) != null) {
return registry.get(uri);
}
if (attemptedLoads.contains(uri)) {
return null;
}
final LookUpRequest req = new LookUpRequest(uri, "application/vnd.sparql-generate");
final SPARQLExtStreamManager sm = (SPARQLExtStreamManager) context.get(SysRIOT.sysStreamManager);
Objects.requireNonNull(sm);
TypedInputStream tin = sm.open(req);
if (tin == null) {
LOG.warn(String.format("Could not look up function %s", uri));
attemptedLoads.add(uri);
return null;
}
String functionString;
try {
functionString = IOUtils.toString(tin.getInputStream(), StandardCharsets.UTF_8);
} catch (IOException ex) {
LOG.warn(String.format("Could not read function %s as UTF-8 string", uri));
attemptedLoads.add(uri);
return null;
}
SPARQLExtQuery functionQuery;
try {
functionQuery = (SPARQLExtQuery) QueryFactory.create(functionString, SPARQLExt.SYNTAX);
} catch (Exception ex) {
LOG.warn(String.format("Could not parse function %s", uri), ex);
attemptedLoads.add(uri);
return null;
}
if (!functionQuery.isFunctionType()) {
LOG.warn(String.format("The query is not a function: %s", uri));
attemptedLoads.add(uri);
return null;
}
final SPARQLExtFunctionFactory function = new SPARQLExtFunctionFactory(functionQuery);
put(uri, function);
attemptedLoads.add(uri);
return function;
}
class SPARQLExtFunctionFactory implements FunctionFactory {
final SPARQLExtQuery functionQuery;
public SPARQLExtFunctionFactory(final SPARQLExtQuery functionQuery) {
this.functionQuery = functionQuery;
}
@Override
public Function create(String uri) {
return new SPARQLExtFunction(functionQuery);
}
}
}
| now able to bind function classes after initialization of SPARQL-Gnerate
| sparql-generate/src/main/java/fr/emse/ci/sparqlext/function/SPARQLExtFunctionRegistry.java | now able to bind function classes after initialization of SPARQL-Gnerate | <ide><path>parql-generate/src/main/java/fr/emse/ci/sparqlext/function/SPARQLExtFunctionRegistry.java
<ide> package fr.emse.ci.sparqlext.function;
<ide>
<ide> import fr.emse.ci.sparqlext.SPARQLExt;
<add>import fr.emse.ci.sparqlext.iterator.IteratorFunction;
<add>import fr.emse.ci.sparqlext.iterator.IteratorFunctionFactory;
<ide> import fr.emse.ci.sparqlext.query.SPARQLExtQuery;
<ide> import fr.emse.ci.sparqlext.stream.LookUpRequest;
<ide> import fr.emse.ci.sparqlext.stream.SPARQLExtStreamManager;
<ide> import org.apache.jena.atlas.logging.Log;
<ide>
<ide> import org.apache.jena.atlas.web.TypedInputStream;
<add>import org.apache.jena.query.QueryBuildException;
<ide> import org.apache.jena.query.QueryFactory;
<ide> import org.apache.jena.riot.SysRIOT;
<ide> import org.apache.jena.sparql.function.Function;
<ide> import org.apache.jena.sparql.function.FunctionFactory;
<ide> import org.apache.jena.sparql.function.FunctionRegistry;
<ide> import org.apache.jena.sparql.util.Context;
<del>import org.apache.jena.sparql.util.MappedLoader;
<ide> import org.slf4j.Logger;
<ide> import org.slf4j.LoggerFactory;
<ide>
<ide> private static final Logger LOG = LoggerFactory.getLogger(SPARQLExtFunctionRegistry.class);
<ide>
<ide> private final Context context;
<del> Map<String, FunctionFactory> registry = new HashMap<>();
<add> private final Map<String, FunctionFactory> registry = new HashMap<>();
<ide> private final Set<String> attemptedLoads = new HashSet<>();
<ide>
<ide> public SPARQLExtFunctionRegistry(FunctionRegistry parent, Context context) {
<ide> */
<ide> @Override
<ide> public void put(String uri, Class<?> funcClass) {
<del> throw new UnsupportedOperationException("Should not reach this point");
<add> if (!Function.class.isAssignableFrom(funcClass)) {
<add> Log.warn(this, "Class " + funcClass.getName() + " is not a Function");
<add> return;
<add> }
<add> put(uri, new FunctionFactoryAuto(funcClass));
<ide> }
<ide>
<ide> /**
<ide>
<ide> /**
<ide> * Remove by URI
<add> *
<ide> * @param uri
<del> * @return
<add> * @return
<ide> */
<ide> @Override
<ide> public FunctionFactory remove(String uri) {
<ide> return function;
<ide> }
<ide>
<add> class FunctionFactoryAuto implements FunctionFactory {
<add>
<add> Class<?> extClass;
<add>
<add> FunctionFactoryAuto(Class<?> xClass) {
<add> extClass = xClass;
<add> }
<add>
<add> @Override
<add> public Function create(String uri) {
<add> try {
<add> return (Function) extClass.newInstance();
<add> } catch (Exception e) {
<add> LOG.debug("Can't instantiate function"
<add> + " for " + uri, e);
<add> throw new QueryBuildException("Can't instantiate function"
<add> + " for " + uri, e);
<add> }
<add> }
<add> }
<add>
<ide> class SPARQLExtFunctionFactory implements FunctionFactory {
<ide>
<ide> final SPARQLExtQuery functionQuery; |
|
Java | apache-2.0 | 19c04959b3f35e20f0ea92bba7d457b474e57009 | 0 | thomasmaurel/ensj-healthcheck,Ensembl/ensj-healthcheck,Ensembl/ensj-healthcheck,Ensembl/ensj-healthcheck,Ensembl/ensj-healthcheck,thomasmaurel/ensj-healthcheck,thomasmaurel/ensj-healthcheck,thomasmaurel/ensj-healthcheck | /*
* Copyright (C) 2003 EBI, GRL
*
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.ensembl.healthcheck.testcase.generic;
import java.sql.Connection;
import org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.DatabaseType;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.Team;
import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase;
import org.ensembl.healthcheck.util.DBUtils;
import org.ensembl.healthcheck.util.SqlTemplate;
/**
* Check that the number of KNOWN & NOVEL genes is within 20% in the new and
* previous databases. Also check for unset statuses in genes & transcripts.
* Also check that all KNOWN and KNOWN_BY_PROJECTION genes have display_srefs
* set
*/
public class GeneStatus extends SingleDatabaseTestCase {
// fraction of KNOWN & NOVEL genes that are allowed to be different
private static double THRESHOLD = 0.2;
/**
* Create a new GeneStatus testcase.
*/
public GeneStatus() {
addToGroup("release");
addToGroup("core_xrefs");
addToGroup("post-compara-handover");
setDescription("Check that the number of KNOWN genes & transcripts is within 20% in the new and previous databases. Also check for unset status.");
setTeamResponsible(Team.CORE);
setSecondTeamResponsible(Team.GENEBUILD);
}
/**
* Don't try to run on Vega databases.
*/
public void types() {
removeAppliesToType(DatabaseType.CDNA);
removeAppliesToType(DatabaseType.VEGA);
removeAppliesToType(DatabaseType.SANGER_VEGA);
}
/**
* Run the test.
*
* @param dbre
* The database to use.
* @return true if the test passed.
*
*/
public boolean run(DatabaseRegistryEntry dbre) {
boolean result = true;
if (dbre.getType() != DatabaseType.OTHERFEATURES
&& dbre.getType() != DatabaseType.RNASEQ) {
checkPrevious(dbre);
}
result &= checkNull(dbre);
return result;
} // run
// ----------------------------------------------------------------------
private boolean checkPrevious(DatabaseRegistryEntry dbre) {
boolean result = true;
if (System.getProperty("ignore.previous.checks") != null) {
logger.finest("ignore.previous.checks is set in database.properties, skipping this test");
return true;
}
Connection con = dbre.getConnection();
DatabaseRegistryEntry sec = getEquivalentFromSecondaryServer(dbre);
if (sec == null) {
logger.warning("Can't get equivalent database for "
+ dbre.getName());
return true;
}
logger.finest("Equivalent database on secondary server is "
+ sec.getName());
String[] types = { "gene", "transcript" };
for (int t = 0; t < types.length; t++) {
String type = types[t];
String[] stats = { "KNOWN" };
for (int i = 0; i < stats.length; i++) {
String status = stats[i];
String sql = "SELECT COUNT(*) FROM " + type + " WHERE status='"
+ status + "'";
int current = DBUtils.getRowCount(dbre.getConnection(), sql);
int previous = DBUtils.getRowCount(sec.getConnection(), sql);
// if there are no KNOWN genes at all, fail
if (status.equals("KNOWN") && current == 0) {
ReportManager.problem(this, con, "No " + type
+ "s have status " + status);
return false;
}
// otherwise check ratios
if (previous == 0) { // avoid division by zero
ReportManager.warning(this, con, "Previous count of "
+ status + " " + type + "s is 0, skipping");
return false;
}
double difference = (double) (previous - current)
/ (double) previous;
logger.finest(type + ": previous " + previous + " current "
+ current + " difference ratio " + difference);
if (difference > THRESHOLD && previous > 100) {
ReportManager.problem(this, con, "Only " + current + " "
+ type + "s have " + status
+ " status in the current database, compared with "
+ previous + " in the previous database");
result = false;
} else {
ReportManager
.correct(
this,
con,
"Current database has "
+ current
+ " "
+ type
+ "s of status "
+ status
+ " compared to "
+ previous
+ " in the previous database, which is within the allowed tollerance.");
}
}
}
return result;
}
private boolean checkNull(DatabaseRegistryEntry dbre) {
boolean result = true;
for (String type : new String[] { "gene", "transcript" }) {
result &= checkNoNulls(dbre.getConnection(), type, "status");
}
return result;
}
}
| src/org/ensembl/healthcheck/testcase/generic/GeneStatus.java | /*
* Copyright (C) 2003 EBI, GRL
*
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.ensembl.healthcheck.testcase.generic;
import java.sql.Connection;
import org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.DatabaseType;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.Team;
import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase;
import org.ensembl.healthcheck.util.DBUtils;
import org.ensembl.healthcheck.util.SqlTemplate;
/**
* Check that the number of KNOWN & NOVEL genes is within 20% in the new and
* previous databases. Also check for unset statuses in genes & transcripts.
* Also check that all KNOWN and KNOWN_BY_PROJECTION genes have display_srefs
* set
*/
public class GeneStatus extends SingleDatabaseTestCase {
// fraction of KNOWN & NOVEL genes that are allowed to be different
private static double THRESHOLD = 0.2;
/**
* Create a new GeneStatus testcase.
*/
public GeneStatus() {
addToGroup("release");
addToGroup("core_xrefs");
addToGroup("post-compara-handover");
setDescription("Check that the number of KNOWN genes & transcripts is within 20% in the new and previous databases. Also check for unset status.");
setTeamResponsible(Team.CORE);
setSecondTeamResponsible(Team.GENEBUILD);
}
/**
* Don't try to run on Vega databases.
*/
public void types() {
removeAppliesToType(DatabaseType.CDNA);
removeAppliesToType(DatabaseType.VEGA);
removeAppliesToType(DatabaseType.SANGER_VEGA);
}
/**
* Run the test.
*
* @param dbre
* The database to use.
* @return true if the test passed.
*
*/
public boolean run(DatabaseRegistryEntry dbre) {
boolean result = true;
if (dbre.getType() != DatabaseType.OTHERFEATURES
&& dbre.getType() != DatabaseType.RNASEQ) {
checkPrevious(dbre);
}
result &= checkNull(dbre);
return result;
} // run
// ----------------------------------------------------------------------
private boolean checkPrevious(DatabaseRegistryEntry dbre) {
boolean result = true;
if (System.getProperty("ignore.previous.checks") != null) {
logger.finest("ignore.previous.checks is set in database.properties, skipping this test");
return true;
}
Connection con = dbre.getConnection();
DatabaseRegistryEntry sec = getEquivalentFromSecondaryServer(dbre);
if (sec == null) {
logger.warning("Can't get equivalent database for "
+ dbre.getName());
return true;
}
logger.finest("Equivalent database on secondary server is "
+ sec.getName());
String[] types = { "gene", "transcript" };
for (int t = 0; t < types.length; t++) {
String type = types[t];
String[] stats = { "KNOWN" };
for (int i = 0; i < stats.length; i++) {
String status = stats[i];
String sql = "SELECT COUNT(*) FROM " + type + " WHERE status='"
+ status + "'";
int current = DBUtils.getRowCount(dbre.getConnection(), sql);
int previous = DBUtils.getRowCount(sec.getConnection(), sql);
// if there are no KNOWN genes at all, fail
if (status.equals("KNOWN") && current == 0) {
ReportManager.problem(this, con, "No " + type
+ "s have status " + status);
return false;
}
// otherwise check ratios
if (previous == 0) { // avoid division by zero
ReportManager.warning(this, con, "Previous count of "
+ status + " " + type + "s is 0, skipping");
return false;
}
double difference = (double) (previous - current)
/ (double) previous;
logger.finest(type + ": previous " + previous + " current "
+ current + " difference ratio " + difference);
if (difference > THRESHOLD) {
ReportManager.problem(this, con, "Only " + current + " "
+ type + "s have " + status
+ " status in the current database, compared with "
+ previous + " in the previous database");
result = false;
} else {
ReportManager
.correct(
this,
con,
"Current database has "
+ current
+ " "
+ type
+ "s of status "
+ status
+ " compared to "
+ previous
+ " in the previous database, which is within the allowed tollerance.");
}
}
}
return result;
}
private boolean checkNull(DatabaseRegistryEntry dbre) {
boolean result = true;
for (String type : new String[] { "gene", "transcript" }) {
result &= checkNoNulls(dbre.getConnection(), type, "status");
}
return result;
}
}
| do not complain about change if there were hardly any to start with
| src/org/ensembl/healthcheck/testcase/generic/GeneStatus.java | do not complain about change if there were hardly any to start with | <ide><path>rc/org/ensembl/healthcheck/testcase/generic/GeneStatus.java
<ide> logger.finest(type + ": previous " + previous + " current "
<ide> + current + " difference ratio " + difference);
<ide>
<del> if (difference > THRESHOLD) {
<add> if (difference > THRESHOLD && previous > 100) {
<ide>
<ide> ReportManager.problem(this, con, "Only " + current + " "
<ide> + type + "s have " + status |
|
Java | apache-2.0 | 0a1d3f83c68b5d5e824ce5d5d865cc23410c588e | 0 | CS-SI/Orekit,petrushy/Orekit,CS-SI/Orekit,petrushy/Orekit | /* Copyright 2002-2016 CS Systèmes d'Information
* Licensed to CS Systèmes d'Information (CS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* CS 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.orekit.propagation.semianalytical.dsst.forces;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import org.apache.commons.math3.analysis.differentiation.DerivativeStructure;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import org.apache.commons.math3.util.FastMath;
import org.apache.commons.math3.util.MathUtils;
import org.orekit.attitudes.AttitudeProvider;
import org.orekit.errors.OrekitException;
import org.orekit.forces.gravity.potential.UnnormalizedSphericalHarmonicsProvider;
import org.orekit.forces.gravity.potential.UnnormalizedSphericalHarmonicsProvider.UnnormalizedSphericalHarmonics;
import org.orekit.frames.Frame;
import org.orekit.frames.Transform;
import org.orekit.orbits.Orbit;
import org.orekit.propagation.SpacecraftState;
import org.orekit.propagation.events.EventDetector;
import org.orekit.propagation.semianalytical.dsst.utilities.AuxiliaryElements;
import org.orekit.propagation.semianalytical.dsst.utilities.CoefficientsFactory;
import org.orekit.propagation.semianalytical.dsst.utilities.GHmsjPolynomials;
import org.orekit.propagation.semianalytical.dsst.utilities.GammaMnsFunction;
import org.orekit.propagation.semianalytical.dsst.utilities.JacobiPolynomials;
import org.orekit.propagation.semianalytical.dsst.utilities.ShortPeriodicsInterpolatedCoefficient;
import org.orekit.propagation.semianalytical.dsst.utilities.hansen.HansenTesseralLinear;
import org.orekit.time.AbsoluteDate;
import org.orekit.utils.TimeSpanMap;
/** Tesseral contribution to the {@link DSSTCentralBody central body gravitational
* perturbation}.
* <p>
* Only resonant tesserals are considered.
* </p>
*
* @author Romain Di Costanzo
* @author Pascal Parraud
*/
class TesseralContribution implements DSSTForceModel {
/** Minimum period for analytically averaged high-order resonant
* central body spherical harmonics in seconds.
*/
private static final double MIN_PERIOD_IN_SECONDS = 864000.;
/** Minimum period for analytically averaged high-order resonant
* central body spherical harmonics in satellite revolutions.
*/
private static final double MIN_PERIOD_IN_SAT_REV = 10.;
/** Number of points for interpolation. */
private static final int INTERPOLATION_POINTS = 3;
/** Maximum possible (absolute) value for j index. */
private static final int MAXJ = 12;
/** The maximum degree used for tesseral short periodics (without m-daily). */
private static final int MAX_DEGREE_TESSERAL_SP = 8;
/** The maximum degree used for m-daily tesseral short periodics. */
private static final int MAX_DEGREE_MDAILY_TESSERAL_SP = 12;
/** The maximum order used for tesseral short periodics (without m-daily). */
private static final int MAX_ORDER_TESSERAL_SP = 8;
/** The maximum order used for m-daily tesseral short periodics. */
private static final int MAX_ORDER_MDAILY_TESSERAL_SP = 12;
/** The maximum value for eccentricity power. */
private static final int MAX_ECCPOWER_SP = 4;
/** Retrograde factor I.
* <p>
* DSST model needs equinoctial orbit as internal representation.
* Classical equinoctial elements have discontinuities when inclination
* is close to zero. In this representation, I = +1. <br>
* To avoid this discontinuity, another representation exists and equinoctial
* elements can be expressed in a different way, called "retrograde" orbit.
* This implies I = -1. <br>
* As Orekit doesn't implement the retrograde orbit, I is always set to +1.
* But for the sake of consistency with the theory, the retrograde factor
* has been kept in the formulas.
* </p>
*/
private static final int I = 1;
/** Provider for spherical harmonics. */
private final UnnormalizedSphericalHarmonicsProvider provider;
/** Central body rotating frame. */
private final Frame bodyFrame;
/** Central body rotation rate (rad/s). */
private final double centralBodyRotationRate;
/** Central body rotation period (seconds). */
private final double bodyPeriod;
/** Maximal degree to consider for harmonics potential. */
private final int maxDegree;
/** Maximal degree to consider for short periodics tesseral harmonics potential (without m-daily). */
private final int maxDegreeTesseralSP;
/** Maximal degree to consider for short periodics m-daily tesseral harmonics potential . */
private final int maxDegreeMdailyTesseralSP;
/** Maximal order to consider for harmonics potential. */
private final int maxOrder;
/** Maximal order to consider for short periodics tesseral harmonics potential (without m-daily). */
private final int maxOrderTesseralSP;
/** Maximal order to consider for short periodics m-daily tesseral harmonics potential . */
private final int maxOrderMdailyTesseralSP;
/** List of resonant orders. */
private final List<Integer> resOrders;
/** Factorial. */
private final double[] fact;
/** Maximum power of the eccentricity to use in summation over s. */
private int maxEccPow;
/** Maximum power of the eccentricity to use in summation over s for
* short periodic tesseral harmonics (without m-daily). */
private int maxEccPowTesseralSP;
/** Maximum power of the eccentricity to use in summation over s for
* m-daily tesseral harmonics. */
private int maxEccPowMdailyTesseralSP;
/** Maximum power of the eccentricity to use in Hansen coefficient Kernel expansion. */
private int maxHansen;
/** Keplerian period. */
private double orbitPeriod;
/** Ratio of satellite period to central body rotation period. */
private double ratio;
// Equinoctial elements (according to DSST notation)
/** a. */
private double a;
/** ex. */
private double k;
/** ey. */
private double h;
/** hx. */
private double q;
/** hy. */
private double p;
/** lm. */
private double lm;
/** Eccentricity. */
private double ecc;
// Common factors for potential computation
/** Χ = 1 / sqrt(1 - e²) = 1 / B. */
private double chi;
/** Χ². */
private double chi2;
// Equinoctial reference frame vectors (according to DSST notation)
/** Equinoctial frame f vector. */
private Vector3D f;
/** Equinoctial frame g vector. */
private Vector3D g;
/** Central body rotation angle θ. */
private double theta;
/** Direction cosine α. */
private double alpha;
/** Direction cosine β. */
private double beta;
/** Direction cosine γ. */
private double gamma;
// Common factors from equinoctial coefficients
/** 2 * a / A .*/
private double ax2oA;
/** 1 / (A * B) .*/
private double ooAB;
/** B / A .*/
private double BoA;
/** B / (A * (1 + B)) .*/
private double BoABpo;
/** C / (2 * A * B) .*/
private double Co2AB;
/** μ / a .*/
private double moa;
/** R / a .*/
private double roa;
/** ecc². */
private double e2;
/** The satellite mean motion. */
private double meanMotion;
/** Flag to take into account only M-dailies harmonic tesserals for short periodic perturbations. */
private final boolean mDailiesOnly;
/** Maximum value for j.
* <p>
* jmax = maxDegreeTesseralSP + maxEccPowTesseralSP, no more than 12
* </p>
* */
private int jMax;
/** List of non resonant orders with j != 0. */
private final SortedMap<Integer, List<Integer> > nonResOrders;
/** A two dimensional array that contains the objects needed to build the Hansen coefficients. <br/>
* The indexes are s + maxDegree and j */
private HansenTesseralLinear[][] hansenObjects;
/** Fourier coefficients. */
private FourierCjSjCoefficients cjsjFourier;
/** Short period terms. */
private TesseralShortPeriodicCoefficients shortPeriodTerms;
/** Single constructor.
* @param centralBodyFrame rotating body frame
* @param centralBodyRotationRate central body rotation rate (rad/s)
* @param provider provider for spherical harmonics
* @param mDailiesOnly if true only M-dailies tesseral harmonics are taken into account for short periodics
*/
TesseralContribution(final Frame centralBodyFrame,
final double centralBodyRotationRate,
final UnnormalizedSphericalHarmonicsProvider provider,
final boolean mDailiesOnly) {
// Central body rotating frame
this.bodyFrame = centralBodyFrame;
//Save the rotation rate
this.centralBodyRotationRate = centralBodyRotationRate;
// Central body rotation period in seconds
this.bodyPeriod = MathUtils.TWO_PI / centralBodyRotationRate;
// Provider for spherical harmonics
this.provider = provider;
this.maxDegree = provider.getMaxDegree();
this.maxOrder = provider.getMaxOrder();
//set the maximum degree order for short periodics
this.maxDegreeTesseralSP = FastMath.min(maxDegree, MAX_DEGREE_TESSERAL_SP);
this.maxDegreeMdailyTesseralSP = FastMath.min(maxDegree, MAX_DEGREE_MDAILY_TESSERAL_SP);
this.maxOrderTesseralSP = FastMath.min(maxOrder, MAX_ORDER_TESSERAL_SP);
this.maxOrderMdailyTesseralSP = FastMath.min(maxOrder, MAX_ORDER_MDAILY_TESSERAL_SP);
// set the maximum value for eccentricity power
this.maxEccPowTesseralSP = MAX_ECCPOWER_SP;
this.maxEccPowMdailyTesseralSP = FastMath.min(maxDegreeMdailyTesseralSP - 2, MAX_ECCPOWER_SP);
this.jMax = FastMath.min(MAXJ, maxDegreeTesseralSP + maxEccPowTesseralSP);
// m-daylies only
this.mDailiesOnly = mDailiesOnly;
// Initialize default values
this.resOrders = new ArrayList<Integer>();
this.nonResOrders = new TreeMap<Integer, List <Integer> >();
this.maxEccPow = 0;
this.maxHansen = 0;
// Factorials computation
final int maxFact = 2 * maxDegree + 1;
this.fact = new double[maxFact];
fact[0] = 1;
for (int i = 1; i < maxFact; i++) {
fact[i] = i * fact[i - 1];
}
}
/** {@inheritDoc} */
@Override
public List<ShortPeriodTerms> initialize(final AuxiliaryElements aux, final boolean meanOnly)
throws OrekitException {
// Keplerian period
orbitPeriod = aux.getKeplerianPeriod();
// Set the highest power of the eccentricity in the analytical power
// series expansion for the averaged high order resonant central body
// spherical harmonic perturbation
final double e = aux.getEcc();
if (e <= 0.005) {
maxEccPow = 3;
} else if (e <= 0.02) {
maxEccPow = 4;
} else if (e <= 0.1) {
maxEccPow = 7;
} else if (e <= 0.2) {
maxEccPow = 10;
} else if (e <= 0.3) {
maxEccPow = 12;
} else if (e <= 0.4) {
maxEccPow = 15;
} else {
maxEccPow = 20;
}
// Set the maximum power of the eccentricity to use in Hansen coefficient Kernel expansion.
maxHansen = maxEccPow / 2;
jMax = FastMath.min(MAXJ, maxDegree + maxEccPow);
// Ratio of satellite to central body periods to define resonant terms
ratio = orbitPeriod / bodyPeriod;
// Compute the resonant tesseral harmonic terms if not set by the user
getResonantAndNonResonantTerms(meanOnly);
//initialize the HansenTesseralLinear objects needed
createHansenObjects(meanOnly);
final int mMax = FastMath.max(maxOrderTesseralSP, maxOrderMdailyTesseralSP);
cjsjFourier = new FourierCjSjCoefficients(jMax, mMax);
shortPeriodTerms = new TesseralShortPeriodicCoefficients(bodyFrame, maxOrderMdailyTesseralSP,
mDailiesOnly, nonResOrders,
mMax, jMax, INTERPOLATION_POINTS);
final List<ShortPeriodTerms> list = new ArrayList<ShortPeriodTerms>();
list.add(shortPeriodTerms);
return list;
}
/** Create the objects needed for linear transformation.
*
* <p>
* Each {@link org.orekit.propagation.semianalytical.dsst.utilities.hansenHansenTesseralLinear HansenTesseralLinear} uses
* a fixed value for s and j. Since j varies from -maxJ to +maxJ and s varies from -maxDegree to +maxDegree,
* a 2 * maxDegree + 1 x 2 * maxJ + 1 matrix of objects should be created. The size of this matrix can be reduced
* by taking into account the expression (2.7.3-2). This means that is enough to create the objects for positive
* values of j and all values of s.
* </p>
*
* @param meanOnly create only the objects required for the mean contribution
*/
private void createHansenObjects(final boolean meanOnly) {
//Allocate the two dimensional array
final int rows = 2 * maxDegree + 1;
final int columns = jMax + 1;
this.hansenObjects = new HansenTesseralLinear[rows][columns];
if (meanOnly) {
// loop through the resonant orders
for (int m : resOrders) {
//Compute the corresponding j term
final int j = FastMath.max(1, (int) FastMath.round(ratio * m));
//Compute the sMin and sMax values
final int sMin = FastMath.min(maxEccPow - j, maxDegree);
final int sMax = FastMath.min(maxEccPow + j, maxDegree);
//loop through the s values
for (int s = 0; s <= sMax; s++) {
//Compute the n0 value
final int n0 = FastMath.max(FastMath.max(2, m), s);
//Create the object for the pair j,s
this.hansenObjects[s + maxDegree][j] = new HansenTesseralLinear(maxDegree, s, j, n0, maxHansen);
if (s > 0 && s <= sMin) {
//Also create the object for the pair j, -s
this.hansenObjects[maxDegree - s][j] = new HansenTesseralLinear(maxDegree, -s, j, n0, maxHansen);
}
}
}
} else {
// create all objects
for (int j = 0; j <= jMax; j++) {
for (int s = -maxDegree; s <= maxDegree; s++) {
//Compute the n0 value
final int n0 = FastMath.max(2, FastMath.abs(s));
this.hansenObjects[s + maxDegree][j] = new HansenTesseralLinear(maxDegree, s, j, n0, maxHansen);
}
}
}
}
/** {@inheritDoc} */
@Override
public void initializeStep(final AuxiliaryElements aux) throws OrekitException {
// Equinoctial elements
a = aux.getSma();
k = aux.getK();
h = aux.getH();
q = aux.getQ();
p = aux.getP();
lm = aux.getLM();
// Eccentricity
ecc = aux.getEcc();
e2 = ecc * ecc;
// Equinoctial frame vectors
f = aux.getVectorF();
g = aux.getVectorG();
// Central body rotation angle from equation 2.7.1-(3)(4).
final Transform t = bodyFrame.getTransformTo(aux.getFrame(), aux.getDate());
final Vector3D xB = t.transformVector(Vector3D.PLUS_I);
final Vector3D yB = t.transformVector(Vector3D.PLUS_J);
theta = FastMath.atan2(-f.dotProduct(yB) + I * g.dotProduct(xB),
f.dotProduct(xB) + I * g.dotProduct(yB));
// Direction cosines
alpha = aux.getAlpha();
beta = aux.getBeta();
gamma = aux.getGamma();
// Equinoctial coefficients
// A = sqrt(μ * a)
final double A = aux.getA();
// B = sqrt(1 - h² - k²)
final double B = aux.getB();
// C = 1 + p² + q²
final double C = aux.getC();
// Common factors from equinoctial coefficients
// 2 * a / A
ax2oA = 2. * a / A;
// B / A
BoA = B / A;
// 1 / AB
ooAB = 1. / (A * B);
// C / 2AB
Co2AB = C * ooAB / 2.;
// B / (A * (1 + B))
BoABpo = BoA / (1. + B);
// &mu / a
moa = provider.getMu() / a;
// R / a
roa = provider.getAe() / a;
// Χ = 1 / B
chi = 1. / B;
chi2 = chi * chi;
//mean motion n
meanMotion = aux.getMeanMotion();
}
/** {@inheritDoc} */
@Override
public double[] getMeanElementRate(final SpacecraftState spacecraftState) throws OrekitException {
// Compute potential derivatives
final double[] dU = computeUDerivatives(spacecraftState.getDate());
final double dUda = dU[0];
final double dUdh = dU[1];
final double dUdk = dU[2];
final double dUdl = dU[3];
final double dUdAl = dU[4];
final double dUdBe = dU[5];
final double dUdGa = dU[6];
// Compute the cross derivative operator :
final double UAlphaGamma = alpha * dUdGa - gamma * dUdAl;
final double UAlphaBeta = alpha * dUdBe - beta * dUdAl;
final double UBetaGamma = beta * dUdGa - gamma * dUdBe;
final double Uhk = h * dUdk - k * dUdh;
final double pUagmIqUbgoAB = (p * UAlphaGamma - I * q * UBetaGamma) * ooAB;
final double UhkmUabmdUdl = Uhk - UAlphaBeta - dUdl;
final double da = ax2oA * dUdl;
final double dh = BoA * dUdk + k * pUagmIqUbgoAB - h * BoABpo * dUdl;
final double dk = -(BoA * dUdh + h * pUagmIqUbgoAB + k * BoABpo * dUdl);
final double dp = Co2AB * (p * UhkmUabmdUdl - UBetaGamma);
final double dq = Co2AB * (q * UhkmUabmdUdl - I * UAlphaGamma);
final double dM = -ax2oA * dUda + BoABpo * (h * dUdh + k * dUdk) + pUagmIqUbgoAB;
return new double[] {da, dk, dh, dq, dp, dM};
}
/** {@inheritDoc} */
@Override
public void updateShortPeriodTerms(final SpacecraftState ... meanStates)
throws OrekitException {
final Slot slot = shortPeriodTerms.createSlot(meanStates);
for (final SpacecraftState meanState : meanStates) {
initializeStep(new AuxiliaryElements(meanState.getOrbit(), I));
// Initialise the Hansen coefficients
for (int s = -maxDegree; s <= maxDegree; s++) {
// coefficients with j == 0 are always needed
this.hansenObjects[s + maxDegree][0].computeInitValues(e2, chi, chi2);
if (!mDailiesOnly) {
// initialize other objects only if required
for (int j = 1; j <= jMax; j++) {
this.hansenObjects[s + maxDegree][j].computeInitValues(e2, chi, chi2);
}
}
}
// Compute coefficients
// Compute only if there is at least one non-resonant tesseral
if (!nonResOrders.isEmpty() || mDailiesOnly) {
// Generate the fourrier coefficients
cjsjFourier.generateCoefficients(meanState.getDate());
// the coefficient 3n / 2a
final double tnota = 1.5 * meanMotion / a;
// build the mDaily coefficients
for (int m = 1; m <= maxOrderMdailyTesseralSP; m++) {
// build the coefficients
buildCoefficients(meanState.getDate(), slot, m, 0, tnota);
}
if (!mDailiesOnly) {
// generate the other coefficients, if required
for (final Map.Entry<Integer, List<Integer>> entry : nonResOrders.entrySet()) {
for (int j : entry.getValue()) {
// build the coefficients
buildCoefficients(meanState.getDate(), slot, entry.getKey(), j, tnota);
}
}
}
}
}
}
/** Build a set of coefficients.
*
* @param date the current date
* @param slot slot to which the coefficients belong
* @param m m index
* @param j j index
* @param tnota 3n/2a
*/
private void buildCoefficients(final AbsoluteDate date, final Slot slot,
final int m, final int j, final double tnota) {
// Create local arrays
final double[] currentCijm = new double[] {0., 0., 0., 0., 0., 0.};
final double[] currentSijm = new double[] {0., 0., 0., 0., 0., 0.};
// compute the term 1 / (jn - mθ<sup>.</sup>)
final double oojnmt = 1. / (j * meanMotion - m * centralBodyRotationRate);
// initialise the coeficients
for (int i = 0; i < 6; i++) {
currentCijm[i] = -cjsjFourier.getSijm(i, j, m);
currentSijm[i] = cjsjFourier.getCijm(i, j, m);
}
// Add the separate part for δ<sub>6i</sub>
currentCijm[5] += tnota * oojnmt * cjsjFourier.getCijm(0, j, m);
currentSijm[5] += tnota * oojnmt * cjsjFourier.getSijm(0, j, m);
//Multiply by 1 / (jn - mθ<sup>.</sup>)
for (int i = 0; i < 6; i++) {
currentCijm[i] *= oojnmt;
currentSijm[i] *= oojnmt;
}
// Add the coefficients to the interpolation grid
slot.cijm[m][j + jMax].addGridPoint(date, currentCijm);
slot.sijm[m][j + jMax].addGridPoint(date, currentSijm);
}
/** {@inheritDoc} */
@Override
public EventDetector[] getEventsDetectors() {
return null;
}
/**
* Get the resonant and non-resonant tesseral terms in the central body spherical harmonic field.
*
* @param resonantOnly extract only resonant terms
*/
private void getResonantAndNonResonantTerms(final boolean resonantOnly) {
// Compute natural resonant terms
final double tolerance = 1. / FastMath.max(MIN_PERIOD_IN_SAT_REV,
MIN_PERIOD_IN_SECONDS / orbitPeriod);
// Search the resonant orders in the tesseral harmonic field
resOrders.clear();
nonResOrders.clear();
for (int m = 1; m <= maxOrder; m++) {
final double resonance = ratio * m;
int jRes = 0;
final int jComputedRes = (int) FastMath.round(resonance);
if (jComputedRes > 0 && jComputedRes <= jMax && FastMath.abs(resonance - jComputedRes) <= tolerance) {
// Store each resonant index and order
resOrders.add(m);
jRes = jComputedRes;
}
if (!resonantOnly && !mDailiesOnly && m <= maxOrderTesseralSP) {
//compute non resonant orders in the tesseral harmonic field
final List<Integer> listJofM = new ArrayList<Integer>();
//for the moment we take only the pairs (j,m) with |j| <= maxDegree + maxEccPow (from |s-j| <= maxEccPow and |s| <= maxDegree)
for (int j = -jMax; j <= jMax; j++) {
if (j != 0 && j != jRes) {
listJofM.add(j);
}
}
nonResOrders.put(m, listJofM);
}
}
}
/** Computes the potential U derivatives.
* <p>The following elements are computed from expression 3.3 - (4).
* <pre>
* dU / da
* dU / dh
* dU / dk
* dU / dλ
* dU / dα
* dU / dβ
* dU / dγ
* </pre>
* </p>
*
* @param date current date
* @return potential derivatives
* @throws OrekitException if an error occurs
*/
private double[] computeUDerivatives(final AbsoluteDate date) throws OrekitException {
// Potential derivatives
double dUda = 0.;
double dUdh = 0.;
double dUdk = 0.;
double dUdl = 0.;
double dUdAl = 0.;
double dUdBe = 0.;
double dUdGa = 0.;
// Compute only if there is at least one resonant tesseral
if (!resOrders.isEmpty()) {
// Gmsj and Hmsj polynomials
final GHmsjPolynomials ghMSJ = new GHmsjPolynomials(k, h, alpha, beta, I);
// GAMMAmns function
final GammaMnsFunction gammaMNS = new GammaMnsFunction(fact, gamma, I);
// R / a up to power degree
final double[] roaPow = new double[maxDegree + 1];
roaPow[0] = 1.;
for (int i = 1; i <= maxDegree; i++) {
roaPow[i] = roa * roaPow[i - 1];
}
// SUM over resonant terms {j,m}
for (int m : resOrders) {
// Resonant index for the current resonant order
final int j = FastMath.max(1, (int) FastMath.round(ratio * m));
// Phase angle
final double jlMmt = j * lm - m * theta;
final double sinPhi = FastMath.sin(jlMmt);
final double cosPhi = FastMath.cos(jlMmt);
// Potential derivatives components for a given resonant pair {j,m}
double dUdaCos = 0.;
double dUdaSin = 0.;
double dUdhCos = 0.;
double dUdhSin = 0.;
double dUdkCos = 0.;
double dUdkSin = 0.;
double dUdlCos = 0.;
double dUdlSin = 0.;
double dUdAlCos = 0.;
double dUdAlSin = 0.;
double dUdBeCos = 0.;
double dUdBeSin = 0.;
double dUdGaCos = 0.;
double dUdGaSin = 0.;
// s-SUM from -sMin to sMax
final int sMin = FastMath.min(maxEccPow - j, maxDegree);
final int sMax = FastMath.min(maxEccPow + j, maxDegree);
for (int s = 0; s <= sMax; s++) {
//Compute the initial values for Hansen coefficients using newComb operators
this.hansenObjects[s + maxDegree][j].computeInitValues(e2, chi, chi2);
// n-SUM for s positive
final double[][] nSumSpos = computeNSum(date, j, m, s, maxDegree,
roaPow, ghMSJ, gammaMNS);
dUdaCos += nSumSpos[0][0];
dUdaSin += nSumSpos[0][1];
dUdhCos += nSumSpos[1][0];
dUdhSin += nSumSpos[1][1];
dUdkCos += nSumSpos[2][0];
dUdkSin += nSumSpos[2][1];
dUdlCos += nSumSpos[3][0];
dUdlSin += nSumSpos[3][1];
dUdAlCos += nSumSpos[4][0];
dUdAlSin += nSumSpos[4][1];
dUdBeCos += nSumSpos[5][0];
dUdBeSin += nSumSpos[5][1];
dUdGaCos += nSumSpos[6][0];
dUdGaSin += nSumSpos[6][1];
// n-SUM for s negative
if (s > 0 && s <= sMin) {
//Compute the initial values for Hansen coefficients using newComb operators
this.hansenObjects[maxDegree - s][j].computeInitValues(e2, chi, chi2);
final double[][] nSumSneg = computeNSum(date, j, m, -s, maxDegree,
roaPow, ghMSJ, gammaMNS);
dUdaCos += nSumSneg[0][0];
dUdaSin += nSumSneg[0][1];
dUdhCos += nSumSneg[1][0];
dUdhSin += nSumSneg[1][1];
dUdkCos += nSumSneg[2][0];
dUdkSin += nSumSneg[2][1];
dUdlCos += nSumSneg[3][0];
dUdlSin += nSumSneg[3][1];
dUdAlCos += nSumSneg[4][0];
dUdAlSin += nSumSneg[4][1];
dUdBeCos += nSumSneg[5][0];
dUdBeSin += nSumSneg[5][1];
dUdGaCos += nSumSneg[6][0];
dUdGaSin += nSumSneg[6][1];
}
}
// Assembly of potential derivatives componants
dUda += cosPhi * dUdaCos + sinPhi * dUdaSin;
dUdh += cosPhi * dUdhCos + sinPhi * dUdhSin;
dUdk += cosPhi * dUdkCos + sinPhi * dUdkSin;
dUdl += cosPhi * dUdlCos + sinPhi * dUdlSin;
dUdAl += cosPhi * dUdAlCos + sinPhi * dUdAlSin;
dUdBe += cosPhi * dUdBeCos + sinPhi * dUdBeSin;
dUdGa += cosPhi * dUdGaCos + sinPhi * dUdGaSin;
}
dUda *= -moa / a;
dUdh *= moa;
dUdk *= moa;
dUdl *= moa;
dUdAl *= moa;
dUdBe *= moa;
dUdGa *= moa;
}
return new double[] {dUda, dUdh, dUdk, dUdl, dUdAl, dUdBe, dUdGa};
}
/** Compute the n-SUM for potential derivatives components.
* @param date current date
* @param j resonant index <i>j</i>
* @param m resonant order <i>m</i>
* @param s d'Alembert characteristic <i>s</i>
* @param maxN maximum possible value for <i>n</i> index
* @param roaPow powers of R/a up to degree <i>n</i>
* @param ghMSJ G<sup>j</sup><sub>m,s</sub> and H<sup>j</sup><sub>m,s</sub> polynomials
* @param gammaMNS Γ<sup>m</sup><sub>n,s</sub>(γ) function
* @return Components of U<sub>n</sub> derivatives for fixed j, m, s
* @throws OrekitException if some error occurred
*/
private double[][] computeNSum(final AbsoluteDate date,
final int j, final int m, final int s, final int maxN, final double[] roaPow,
final GHmsjPolynomials ghMSJ, final GammaMnsFunction gammaMNS)
throws OrekitException {
//spherical harmonics
final UnnormalizedSphericalHarmonics harmonics = provider.onDate(date);
// Potential derivatives components
double dUdaCos = 0.;
double dUdaSin = 0.;
double dUdhCos = 0.;
double dUdhSin = 0.;
double dUdkCos = 0.;
double dUdkSin = 0.;
double dUdlCos = 0.;
double dUdlSin = 0.;
double dUdAlCos = 0.;
double dUdAlSin = 0.;
double dUdBeCos = 0.;
double dUdBeSin = 0.;
double dUdGaCos = 0.;
double dUdGaSin = 0.;
// I^m
@SuppressWarnings("unused")
final int Im = I > 0 ? 1 : (m % 2 == 0 ? 1 : -1);
// jacobi v, w, indices from 2.7.1-(15)
final int v = FastMath.abs(m - s);
final int w = FastMath.abs(m + s);
// Initialise lower degree nmin = (Max(2, m, |s|)) for summation over n
final int nmin = FastMath.max(FastMath.max(2, m), FastMath.abs(s));
//Get the corresponding Hansen object
final int sIndex = maxDegree + (j < 0 ? -s : s);
final int jIndex = FastMath.abs(j);
final HansenTesseralLinear hans = this.hansenObjects[sIndex][jIndex];
// n-SUM from nmin to N
for (int n = nmin; n <= maxN; n++) {
// If (n - s) is odd, the contribution is null because of Vmns
if ((n - s) % 2 == 0) {
// Vmns coefficient
final double fns = fact[n + FastMath.abs(s)];
final double vMNS = CoefficientsFactory.getVmns(m, n, s, fns, fact[n - m]);
// Inclination function Gamma and derivative
final double gaMNS = gammaMNS.getValue(m, n, s);
final double dGaMNS = gammaMNS.getDerivative(m, n, s);
// Hansen kernel value and derivative
final double kJNS = hans.getValue(-n - 1, chi);
final double dkJNS = hans.getDerivative(-n - 1, chi);
// Gjms, Hjms polynomials and derivatives
final double gMSJ = ghMSJ.getGmsj(m, s, j);
final double hMSJ = ghMSJ.getHmsj(m, s, j);
final double dGdh = ghMSJ.getdGmsdh(m, s, j);
final double dGdk = ghMSJ.getdGmsdk(m, s, j);
final double dGdA = ghMSJ.getdGmsdAlpha(m, s, j);
final double dGdB = ghMSJ.getdGmsdBeta(m, s, j);
final double dHdh = ghMSJ.getdHmsdh(m, s, j);
final double dHdk = ghMSJ.getdHmsdk(m, s, j);
final double dHdA = ghMSJ.getdHmsdAlpha(m, s, j);
final double dHdB = ghMSJ.getdHmsdBeta(m, s, j);
// Jacobi l-index from 2.7.1-(15)
final int l = FastMath.min(n - m, n - FastMath.abs(s));
// Jacobi polynomial and derivative
final DerivativeStructure jacobi =
JacobiPolynomials.getValue(l, v, w, new DerivativeStructure(1, 1, 0, gamma));
// Geopotential coefficients
final double cnm = harmonics.getUnnormalizedCnm(n, m);
final double snm = harmonics.getUnnormalizedSnm(n, m);
// Common factors from expansion of equations 3.3-4
final double cf_0 = roaPow[n] * Im * vMNS;
final double cf_1 = cf_0 * gaMNS * jacobi.getValue();
final double cf_2 = cf_1 * kJNS;
final double gcPhs = gMSJ * cnm + hMSJ * snm;
final double gsMhc = gMSJ * snm - hMSJ * cnm;
final double dKgcPhsx2 = 2. * dkJNS * gcPhs;
final double dKgsMhcx2 = 2. * dkJNS * gsMhc;
final double dUdaCoef = (n + 1) * cf_2;
final double dUdlCoef = j * cf_2;
final double dUdGaCoef = cf_0 * kJNS * (jacobi.getValue() * dGaMNS + gaMNS * jacobi.getPartialDerivative(1));
// dU / da components
dUdaCos += dUdaCoef * gcPhs;
dUdaSin += dUdaCoef * gsMhc;
// dU / dh components
dUdhCos += cf_1 * (kJNS * (cnm * dGdh + snm * dHdh) + h * dKgcPhsx2);
dUdhSin += cf_1 * (kJNS * (snm * dGdh - cnm * dHdh) + h * dKgsMhcx2);
// dU / dk components
dUdkCos += cf_1 * (kJNS * (cnm * dGdk + snm * dHdk) + k * dKgcPhsx2);
dUdkSin += cf_1 * (kJNS * (snm * dGdk - cnm * dHdk) + k * dKgsMhcx2);
// dU / dLambda components
dUdlCos += dUdlCoef * gsMhc;
dUdlSin += -dUdlCoef * gcPhs;
// dU / alpha components
dUdAlCos += cf_2 * (dGdA * cnm + dHdA * snm);
dUdAlSin += cf_2 * (dGdA * snm - dHdA * cnm);
// dU / dBeta components
dUdBeCos += cf_2 * (dGdB * cnm + dHdB * snm);
dUdBeSin += cf_2 * (dGdB * snm - dHdB * cnm);
// dU / dGamma components
dUdGaCos += dUdGaCoef * gcPhs;
dUdGaSin += dUdGaCoef * gsMhc;
}
}
return new double[][] {{dUdaCos, dUdaSin},
{dUdhCos, dUdhSin},
{dUdkCos, dUdkSin},
{dUdlCos, dUdlSin},
{dUdAlCos, dUdAlSin},
{dUdBeCos, dUdBeSin},
{dUdGaCos, dUdGaSin}};
}
/** {@inheritDoc} */
@Override
public void registerAttitudeProvider(final AttitudeProvider attitudeProvider) {
//nothing is done since this contribution is not sensitive to attitude
}
/** Compute the C<sup>j</sup> and the S<sup>j</sup> coefficients.
* <p>
* Those coefficients are given in Danielson paper by substituting the
* disturbing function (2.7.1-16) with m != 0 into (2.2-10)
* </p>
*/
private class FourierCjSjCoefficients {
/** Absolute limit for j ( -jMax <= j <= jMax ). */
private final int jMax;
/** The C<sub>i</sub><sup>jm</sup> coefficients.
* <p>
* The index order is [m][j][i] <br/>
* The i index corresponds to the C<sub>i</sub><sup>jm</sup> coefficients used to
* compute the following: <br/>
* - da/dt <br/>
* - dk/dt <br/>
* - dh/dt / dk <br/>
* - dq/dt <br/>
* - dp/dt / dα <br/>
* - dλ/dt / dβ <br/>
* </p>
*/
private final double[][][] cCoef;
/** The S<sub>i</sub><sup>jm</sup> coefficients.
* <p>
* The index order is [m][j][i] <br/>
* The i index corresponds to the C<sub>i</sub><sup>jm</sup> coefficients used to
* compute the following: <br/>
* - da/dt <br/>
* - dk/dt <br/>
* - dh/dt / dk <br/>
* - dq/dt <br/>
* - dp/dt / dα <br/>
* - dλ/dt / dβ <br/>
* </p>
*/
private final double[][][] sCoef;
/** G<sub>ms</sub><sup>j</sup> and H<sub>ms</sub><sup>j</sup> polynomials. */
private GHmsjPolynomials ghMSJ;
/** Γ<sub>ns</sub><sup>m</sup> function. */
private GammaMnsFunction gammaMNS;
/** R / a up to power degree. */
private final double[] roaPow;
/** Create a set of C<sub>i</sub><sup>jm</sup> and S<sub>i</sub><sup>jm</sup> coefficients.
* @param jMax absolute limit for j ( -jMax <= j <= jMax )
* @param mMax maximum value for m
*/
FourierCjSjCoefficients(final int jMax, final int mMax) {
// initialise fields
final int rows = mMax + 1;
final int columns = 2 * jMax + 1;
this.jMax = jMax;
this.cCoef = new double[rows][columns][6];
this.sCoef = new double[rows][columns][6];
this.roaPow = new double[maxDegree + 1];
roaPow[0] = 1.;
}
/**
* Generate the coefficients.
* @param date the current date
* @throws OrekitException if an error occurs while generating the coefficients
*/
public void generateCoefficients(final AbsoluteDate date) throws OrekitException {
// Compute only if there is at least one non-resonant tesseral
if (!nonResOrders.isEmpty() || mDailiesOnly) {
// Gmsj and Hmsj polynomials
ghMSJ = new GHmsjPolynomials(k, h, alpha, beta, I);
// GAMMAmns function
gammaMNS = new GammaMnsFunction(fact, gamma, I);
final int maxRoaPower = FastMath.max(maxDegreeTesseralSP, maxDegreeMdailyTesseralSP);
// R / a up to power degree
for (int i = 1; i <= maxRoaPower; i++) {
roaPow[i] = roa * roaPow[i - 1];
}
//generate the m-daily coefficients
for (int m = 1; m <= maxOrderMdailyTesseralSP; m++) {
buildFourierCoefficients(date, m, 0, maxDegreeMdailyTesseralSP);
}
// generate the other coefficients only if required
if (!mDailiesOnly) {
for (int m: nonResOrders.keySet()) {
final List<Integer> listJ = nonResOrders.get(m);
for (int j: listJ) {
buildFourierCoefficients(date, m, j, maxDegreeTesseralSP);
}
}
}
}
}
/** Build a set of fourier coefficients for a given m and j.
*
* @param date the date of the coefficients
* @param m m index
* @param j j index
* @param maxN maximum value for n index
* @throws OrekitException in case of Hansen kernel generation error
*/
private void buildFourierCoefficients(final AbsoluteDate date,
final int m, final int j, final int maxN) throws OrekitException {
// Potential derivatives components for a given non-resonant pair {j,m}
double dRdaCos = 0.;
double dRdaSin = 0.;
double dRdhCos = 0.;
double dRdhSin = 0.;
double dRdkCos = 0.;
double dRdkSin = 0.;
double dRdlCos = 0.;
double dRdlSin = 0.;
double dRdAlCos = 0.;
double dRdAlSin = 0.;
double dRdBeCos = 0.;
double dRdBeSin = 0.;
double dRdGaCos = 0.;
double dRdGaSin = 0.;
// s-SUM from -sMin to sMax
final int sMin = j == 0 ? maxEccPowMdailyTesseralSP : maxEccPowTesseralSP;
final int sMax = j == 0 ? maxEccPowMdailyTesseralSP : maxEccPowTesseralSP;
for (int s = 0; s <= sMax; s++) {
// n-SUM for s positive
final double[][] nSumSpos = computeNSum(date, j, m, s, maxN,
roaPow, ghMSJ, gammaMNS);
dRdaCos += nSumSpos[0][0];
dRdaSin += nSumSpos[0][1];
dRdhCos += nSumSpos[1][0];
dRdhSin += nSumSpos[1][1];
dRdkCos += nSumSpos[2][0];
dRdkSin += nSumSpos[2][1];
dRdlCos += nSumSpos[3][0];
dRdlSin += nSumSpos[3][1];
dRdAlCos += nSumSpos[4][0];
dRdAlSin += nSumSpos[4][1];
dRdBeCos += nSumSpos[5][0];
dRdBeSin += nSumSpos[5][1];
dRdGaCos += nSumSpos[6][0];
dRdGaSin += nSumSpos[6][1];
// n-SUM for s negative
if (s > 0 && s <= sMin) {
final double[][] nSumSneg = computeNSum(date, j, m, -s, maxN,
roaPow, ghMSJ, gammaMNS);
dRdaCos += nSumSneg[0][0];
dRdaSin += nSumSneg[0][1];
dRdhCos += nSumSneg[1][0];
dRdhSin += nSumSneg[1][1];
dRdkCos += nSumSneg[2][0];
dRdkSin += nSumSneg[2][1];
dRdlCos += nSumSneg[3][0];
dRdlSin += nSumSneg[3][1];
dRdAlCos += nSumSneg[4][0];
dRdAlSin += nSumSneg[4][1];
dRdBeCos += nSumSneg[5][0];
dRdBeSin += nSumSneg[5][1];
dRdGaCos += nSumSneg[6][0];
dRdGaSin += nSumSneg[6][1];
}
}
dRdaCos *= -moa / a;
dRdaSin *= -moa / a;
dRdhCos *= moa;
dRdhSin *= moa;
dRdkCos *= moa;
dRdkSin *= moa;
dRdlCos *= moa;
dRdlSin *= moa;
dRdAlCos *= moa;
dRdAlSin *= moa;
dRdBeCos *= moa;
dRdBeSin *= moa;
dRdGaCos *= moa;
dRdGaSin *= moa;
// Compute the cross derivative operator :
final double RAlphaGammaCos = alpha * dRdGaCos - gamma * dRdAlCos;
final double RAlphaGammaSin = alpha * dRdGaSin - gamma * dRdAlSin;
final double RAlphaBetaCos = alpha * dRdBeCos - beta * dRdAlCos;
final double RAlphaBetaSin = alpha * dRdBeSin - beta * dRdAlSin;
final double RBetaGammaCos = beta * dRdGaCos - gamma * dRdBeCos;
final double RBetaGammaSin = beta * dRdGaSin - gamma * dRdBeSin;
final double RhkCos = h * dRdkCos - k * dRdhCos;
final double RhkSin = h * dRdkSin - k * dRdhSin;
final double pRagmIqRbgoABCos = (p * RAlphaGammaCos - I * q * RBetaGammaCos) * ooAB;
final double pRagmIqRbgoABSin = (p * RAlphaGammaSin - I * q * RBetaGammaSin) * ooAB;
final double RhkmRabmdRdlCos = RhkCos - RAlphaBetaCos - dRdlCos;
final double RhkmRabmdRdlSin = RhkSin - RAlphaBetaSin - dRdlSin;
// da/dt
cCoef[m][j + jMax][0] = ax2oA * dRdlCos;
sCoef[m][j + jMax][0] = ax2oA * dRdlSin;
// dk/dt
cCoef[m][j + jMax][1] = -(BoA * dRdhCos + h * pRagmIqRbgoABCos + k * BoABpo * dRdlCos);
sCoef[m][j + jMax][1] = -(BoA * dRdhSin + h * pRagmIqRbgoABSin + k * BoABpo * dRdlSin);
// dh/dt
cCoef[m][j + jMax][2] = BoA * dRdkCos + k * pRagmIqRbgoABCos - h * BoABpo * dRdlCos;
sCoef[m][j + jMax][2] = BoA * dRdkSin + k * pRagmIqRbgoABSin - h * BoABpo * dRdlSin;
// dq/dt
cCoef[m][j + jMax][3] = Co2AB * (q * RhkmRabmdRdlCos - I * RAlphaGammaCos);
sCoef[m][j + jMax][3] = Co2AB * (q * RhkmRabmdRdlSin - I * RAlphaGammaSin);
// dp/dt
cCoef[m][j + jMax][4] = Co2AB * (p * RhkmRabmdRdlCos - RBetaGammaCos);
sCoef[m][j + jMax][4] = Co2AB * (p * RhkmRabmdRdlSin - RBetaGammaSin);
// dλ/dt
cCoef[m][j + jMax][5] = -ax2oA * dRdaCos + BoABpo * (h * dRdhCos + k * dRdkCos) + pRagmIqRbgoABCos;
sCoef[m][j + jMax][5] = -ax2oA * dRdaSin + BoABpo * (h * dRdhSin + k * dRdkSin) + pRagmIqRbgoABSin;
}
/** Get the coefficient C<sub>i</sub><sup>jm</sup>.
* @param i i index - corresponds to the required variation
* @param j j index
* @param m m index
* @return the coefficient C<sub>i</sub><sup>jm</sup>
*/
public double getCijm(final int i, final int j, final int m) {
return cCoef[m][j + jMax][i];
}
/** Get the coefficient S<sub>i</sub><sup>jm</sup>.
* @param i i index - corresponds to the required variation
* @param j j index
* @param m m index
* @return the coefficient S<sub>i</sub><sup>jm</sup>
*/
public double getSijm(final int i, final int j, final int m) {
return sCoef[m][j + jMax][i];
}
}
/** The C<sup>i</sup><sub>m</sub><sub>t</sub> and S<sup>i</sup><sub>m</sub><sub>t</sub> coefficients used to compute
* the short-periodic zonal contribution.
* <p>
* Those coefficients are given by expression 2.5.4-5 from the Danielson paper.
* </p>
*
* @author Sorin Scortan
*
*/
private static class TesseralShortPeriodicCoefficients implements ShortPeriodTerms {
/** Serializable UID. */
private static final long serialVersionUID = 20151119L;
/** Retrograde factor I.
* <p>
* DSST model needs equinoctial orbit as internal representation.
* Classical equinoctial elements have discontinuities when inclination
* is close to zero. In this representation, I = +1. <br>
* To avoid this discontinuity, another representation exists and equinoctial
* elements can be expressed in a different way, called "retrograde" orbit.
* This implies I = -1. <br>
* As Orekit doesn't implement the retrograde orbit, I is always set to +1.
* But for the sake of consistency with the theory, the retrograde factor
* has been kept in the formulas.
* </p>
*/
private static final int I = 1;
/** Central body rotating frame. */
private final Frame bodyFrame;
/** Maximal order to consider for short periodics m-daily tesseral harmonics potential. */
private final int maxOrderMdailyTesseralSP;
/** Flag to take into account only M-dailies harmonic tesserals for short periodic perturbations. */
private final boolean mDailiesOnly;
/** List of non resonant orders with j != 0. */
private final SortedMap<Integer, List<Integer> > nonResOrders;
/** Maximum value for m index. */
private final int mMax;
/** Maximum value for j index. */
private final int jMax;
/** Number of points used in the interpolation process. */
private final int interpolationPoints;
/** All coefficients slots. */
private final TimeSpanMap<Slot> slots;
/** Constructor.
* @param bodyFrame central body rotating frame
* @param maxOrderMdailyTesseralSP maximal order to consider for short periodics m-daily tesseral harmonics potential
* @param mDailiesOnly flag to take into account only M-dailies harmonic tesserals for short periodic perturbations
* @param nonResOrders lst of non resonant orders with j != 0
* @param mMax maximum value for m index
* @param jMax maximum value for j index
* @param interpolationPoints number of points used in the interpolation process
*/
TesseralShortPeriodicCoefficients(final Frame bodyFrame, final int maxOrderMdailyTesseralSP,
final boolean mDailiesOnly, final SortedMap<Integer, List<Integer> > nonResOrders,
final int mMax, final int jMax, final int interpolationPoints) {
this.bodyFrame = bodyFrame;
this.maxOrderMdailyTesseralSP = maxOrderMdailyTesseralSP;
this.mDailiesOnly = mDailiesOnly;
this.nonResOrders = nonResOrders;
this.mMax = mMax;
this.jMax = jMax;
this.interpolationPoints = interpolationPoints;
this.slots = new TimeSpanMap<Slot>(new Slot(mMax, jMax, interpolationPoints));
}
/** Get the slot valid for some date.
* @param meanStates mean states defining the slot
* @return slot valid at the specified date
*/
public Slot createSlot(final SpacecraftState ... meanStates) {
final Slot slot = new Slot(mMax, jMax, interpolationPoints);
final AbsoluteDate first = meanStates[0].getDate();
final AbsoluteDate last = meanStates[meanStates.length - 1].getDate();
if (first.compareTo(last) <= 0) {
slots.addValidAfter(slot, first);
} else {
slots.addValidBefore(slot, first);
}
return slot;
}
/** {@inheritDoc} */
@Override
public double[] value(final Orbit meanOrbit) throws OrekitException {
// select the coefficients slot
final Slot slot = slots.get(meanOrbit.getDate());
// Initialise the short periodic variations
final double[] shortPeriodicVariation = new double[6];
// Compute only if there is at least one non-resonant tesseral or
// only the m-daily tesseral should be taken into account
if (!nonResOrders.isEmpty() || mDailiesOnly) {
//Build an auxiliary object
final AuxiliaryElements aux = new AuxiliaryElements(meanOrbit, I);
// Central body rotation angle from equation 2.7.1-(3)(4).
final Transform t = bodyFrame.getTransformTo(aux.getFrame(), aux.getDate());
final Vector3D xB = t.transformVector(Vector3D.PLUS_I);
final Vector3D yB = t.transformVector(Vector3D.PLUS_J);
final Vector3D f = aux.getVectorF();
final Vector3D g = aux.getVectorG();
final double currentTheta = FastMath.atan2(-f.dotProduct(yB) + I * g.dotProduct(xB),
f.dotProduct(xB) + I * g.dotProduct(yB));
//Add the m-daily contribution
for (int m = 1; m <= maxOrderMdailyTesseralSP; m++) {
// Phase angle
final double jlMmt = -m * currentTheta;
final double sinPhi = FastMath.sin(jlMmt);
final double cosPhi = FastMath.cos(jlMmt);
// compute contribution for each element
final double[] c = slot.getCijm(0, m, meanOrbit.getDate());
final double[] s = slot.getSijm(0, m, meanOrbit.getDate());
for (int i = 0; i < 6; i++) {
shortPeriodicVariation[i] += c[i] * cosPhi + s[i] * sinPhi;
}
}
// loop through all non-resonant (j,m) pairs
for (final Map.Entry<Integer, List<Integer>> entry : nonResOrders.entrySet()) {
final int m = entry.getKey();
final List<Integer> listJ = entry.getValue();
for (int j : listJ) {
// Phase angle
final double jlMmt = j * meanOrbit.getLM() - m * currentTheta;
final double sinPhi = FastMath.sin(jlMmt);
final double cosPhi = FastMath.cos(jlMmt);
// compute contribution for each element
final double[] c = slot.getCijm(j, m, meanOrbit.getDate());
final double[] s = slot.getSijm(j, m, meanOrbit.getDate());
for (int i = 0; i < 6; i++) {
shortPeriodicVariation[i] += c[i] * cosPhi + s[i] * sinPhi;
}
}
}
}
return shortPeriodicVariation;
}
/** {@inheritDoc} */
@Override
public String getCoefficientsKeyPrefix() {
return "DSST-central-body-tesseral-";
}
/** {@inheritDoc}
* <p>
* For tesseral terms contributions,there are maxOrderMdailyTesseralSP
* m-daily cMm coefficients, maxOrderMdailyTesseralSP m-daily sMm
* coefficients, nbNonResonant cjm coefficients and nbNonResonant
* sjm coefficients, where maxOrderMdailyTesseralSP and nbNonResonant both
* depend on the orbit. The j index is the integer multiplier for the true
* longitude argument and the m index is the integer multiplier for m-dailies.
* </p>
*/
@Override
public Map<String, double[]> getCoefficients(final AbsoluteDate date, final Set<String> selected)
throws OrekitException {
// select the coefficients slot
final Slot slot = slots.get(date);
if (!nonResOrders.isEmpty() || mDailiesOnly) {
final Map<String, double[]> coefficients =
new HashMap<String, double[]>(12 * maxOrderMdailyTesseralSP +
12 * nonResOrders.size());
for (int m = 1; m <= maxOrderMdailyTesseralSP; m++) {
storeIfSelected(coefficients, selected, slot.getCijm(0, m, date), "cM", m);
storeIfSelected(coefficients, selected, slot.getSijm(0, m, date), "sM", m);
}
for (final Map.Entry<Integer, List<Integer>> entry : nonResOrders.entrySet()) {
final int m = entry.getKey();
final List<Integer> listJ = entry.getValue();
for (int j : listJ) {
for (int i = 0; i < 6; ++i) {
storeIfSelected(coefficients, selected, slot.getCijm(j, m, date), "c", j, m);
storeIfSelected(coefficients, selected, slot.getSijm(j, m, date), "s", j, m);
}
}
}
return coefficients;
} else {
return Collections.emptyMap();
}
}
/** Put a coefficient in a map if selected.
* @param map map to populate
* @param selected set of coefficients that should be put in the map
* (empty set means all coefficients are selected)
* @param value coefficient value
* @param id coefficient identifier
* @param indices list of coefficient indices
*/
private void storeIfSelected(final Map<String, double[]> map, final Set<String> selected,
final double[] value, final String id, final int ... indices) {
final StringBuilder keyBuilder = new StringBuilder(getCoefficientsKeyPrefix());
keyBuilder.append(id);
for (int index : indices) {
keyBuilder.append('[').append(index).append(']');
}
final String key = keyBuilder.toString();
if (selected.isEmpty() || selected.contains(key)) {
map.put(key, value);
}
}
}
/** Coefficients valid for one time slot. */
private static class Slot {
/** The coefficients C<sub>i</sub><sup>j</sup><sup>m</sup>.
* <p>
* The index order is cijm[m][j][i] <br/>
* i corresponds to the equinoctial element, as follows: <br/>
* - i=0 for a <br/>
* - i=1 for k <br/>
* - i=2 for h <br/>
* - i=3 for q <br/>
* - i=4 for p <br/>
* - i=5 for λ <br/>
* </p>
*/
private final ShortPeriodicsInterpolatedCoefficient[][] cijm;
/** The coefficients S<sub>i</sub><sup>j</sup><sup>m</sup>.
* <p>
* The index order is sijm[m][j][i] <br/>
* i corresponds to the equinoctial element, as follows: <br/>
* - i=0 for a <br/>
* - i=1 for k <br/>
* - i=2 for h <br/>
* - i=3 for q <br/>
* - i=4 for p <br/>
* - i=5 for λ <br/>
* </p>
*/
private final ShortPeriodicsInterpolatedCoefficient[][] sijm;
/** Simple constructor.
* @param mMax maximum value for m index
* @param jMax maximum value for j index
* @param interpolationPoints number of points used in the interpolation process
*/
Slot(final int mMax, final int jMax, final int interpolationPoints) {
final int rows = mMax + 1;
final int columns = 2 * jMax + 1;
cijm = new ShortPeriodicsInterpolatedCoefficient[rows][columns];
sijm = new ShortPeriodicsInterpolatedCoefficient[rows][columns];
for (int m = 1; m <= mMax; m++) {
for (int j = -jMax; j <= jMax; j++) {
cijm[m][j + jMax] = new ShortPeriodicsInterpolatedCoefficient(interpolationPoints);
sijm[m][j + jMax] = new ShortPeriodicsInterpolatedCoefficient(interpolationPoints);
}
}
}
/** Get C<sub>i</sub><sup>j</sup><sup>m</sup>.
*
* @param j j index
* @param m m index
* @param date the date
* @return C<sub>i</sub><sup>j</sup><sup>m</sup>
*/
double[] getCijm(final int j, final int m, final AbsoluteDate date) {
final int jMax = (cijm[m].length - 1) / 2;
return cijm[m][j + jMax].value(date);
}
/** Get S<sub>i</sub><sup>j</sup><sup>m</sup>.
*
* @param j j index
* @param m m index
* @param date the date
* @return S<sub>i</sub><sup>j</sup><sup>m</sup>
*/
double[] getSijm(final int j, final int m, final AbsoluteDate date) {
final int jMax = (cijm[m].length - 1) / 2;
return sijm[m][j + jMax].value(date);
}
}
}
| src/main/java/org/orekit/propagation/semianalytical/dsst/forces/TesseralContribution.java | /* Copyright 2002-2016 CS Systèmes d'Information
* Licensed to CS Systèmes d'Information (CS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* CS 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.orekit.propagation.semianalytical.dsst.forces;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import org.apache.commons.math3.analysis.differentiation.DerivativeStructure;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import org.apache.commons.math3.util.FastMath;
import org.apache.commons.math3.util.MathUtils;
import org.orekit.attitudes.AttitudeProvider;
import org.orekit.errors.OrekitException;
import org.orekit.forces.gravity.potential.UnnormalizedSphericalHarmonicsProvider;
import org.orekit.forces.gravity.potential.UnnormalizedSphericalHarmonicsProvider.UnnormalizedSphericalHarmonics;
import org.orekit.frames.Frame;
import org.orekit.frames.Transform;
import org.orekit.orbits.Orbit;
import org.orekit.propagation.SpacecraftState;
import org.orekit.propagation.events.EventDetector;
import org.orekit.propagation.semianalytical.dsst.utilities.AuxiliaryElements;
import org.orekit.propagation.semianalytical.dsst.utilities.CoefficientsFactory;
import org.orekit.propagation.semianalytical.dsst.utilities.GHmsjPolynomials;
import org.orekit.propagation.semianalytical.dsst.utilities.GammaMnsFunction;
import org.orekit.propagation.semianalytical.dsst.utilities.JacobiPolynomials;
import org.orekit.propagation.semianalytical.dsst.utilities.ShortPeriodicsInterpolatedCoefficient;
import org.orekit.propagation.semianalytical.dsst.utilities.hansen.HansenTesseralLinear;
import org.orekit.time.AbsoluteDate;
import org.orekit.utils.TimeSpanMap;
/** Tesseral contribution to the {@link DSSTCentralBody central body gravitational
* perturbation}.
* <p>
* Only resonant tesserals are considered.
* </p>
*
* @author Romain Di Costanzo
* @author Pascal Parraud
*/
class TesseralContribution implements DSSTForceModel {
/** Minimum period for analytically averaged high-order resonant
* central body spherical harmonics in seconds.
*/
private static final double MIN_PERIOD_IN_SECONDS = 864000.;
/** Minimum period for analytically averaged high-order resonant
* central body spherical harmonics in satellite revolutions.
*/
private static final double MIN_PERIOD_IN_SAT_REV = 10.;
/** Number of points for interpolation. */
private static final int INTERPOLATION_POINTS = 3;
/** Maximum possible (absolute) value for j index. */
private static final int MAXJ = 12;
/** The maximum degree used for tesseral short periodics (without m-daily). */
private static final int MAX_DEGREE_TESSERAL_SP = 8;
/** The maximum degree used for m-daily tesseral short periodics. */
private static final int MAX_DEGREE_MDAILY_TESSERAL_SP = 12;
/** The maximum order used for tesseral short periodics (without m-daily). */
private static final int MAX_ORDER_TESSERAL_SP = 8;
/** The maximum order used for m-daily tesseral short periodics. */
private static final int MAX_ORDER_MDAILY_TESSERAL_SP = 12;
/** The maximum value for eccentricity power. */
private static final int MAX_ECCPOWER_SP = 4;
/** Retrograde factor I.
* <p>
* DSST model needs equinoctial orbit as internal representation.
* Classical equinoctial elements have discontinuities when inclination
* is close to zero. In this representation, I = +1. <br>
* To avoid this discontinuity, another representation exists and equinoctial
* elements can be expressed in a different way, called "retrograde" orbit.
* This implies I = -1. <br>
* As Orekit doesn't implement the retrograde orbit, I is always set to +1.
* But for the sake of consistency with the theory, the retrograde factor
* has been kept in the formulas.
* </p>
*/
private static final int I = 1;
/** Provider for spherical harmonics. */
private final UnnormalizedSphericalHarmonicsProvider provider;
/** Central body rotating frame. */
private final Frame bodyFrame;
/** Central body rotation rate (rad/s). */
private final double centralBodyRotationRate;
/** Central body rotation period (seconds). */
private final double bodyPeriod;
/** Maximal degree to consider for harmonics potential. */
private final int maxDegree;
/** Maximal degree to consider for short periodics tesseral harmonics potential (without m-daily). */
private final int maxDegreeTesseralSP;
/** Maximal degree to consider for short periodics m-daily tesseral harmonics potential . */
private final int maxDegreeMdailyTesseralSP;
/** Maximal order to consider for harmonics potential. */
private final int maxOrder;
/** Maximal order to consider for short periodics tesseral harmonics potential (without m-daily). */
private final int maxOrderTesseralSP;
/** Maximal order to consider for short periodics m-daily tesseral harmonics potential . */
private final int maxOrderMdailyTesseralSP;
/** List of resonant orders. */
private final List<Integer> resOrders;
/** Factorial. */
private final double[] fact;
/** Maximum power of the eccentricity to use in summation over s. */
private int maxEccPow;
/** Maximum power of the eccentricity to use in summation over s for
* short periodic tesseral harmonics (without m-daily). */
private int maxEccPowTesseralSP;
/** Maximum power of the eccentricity to use in summation over s for
* m-daily tesseral harmonics. */
private int maxEccPowMdailyTesseralSP;
/** Maximum power of the eccentricity to use in Hansen coefficient Kernel expansion. */
private int maxHansen;
/** Keplerian period. */
private double orbitPeriod;
/** Ratio of satellite period to central body rotation period. */
private double ratio;
// Equinoctial elements (according to DSST notation)
/** a. */
private double a;
/** ex. */
private double k;
/** ey. */
private double h;
/** hx. */
private double q;
/** hy. */
private double p;
/** lm. */
private double lm;
/** Eccentricity. */
private double ecc;
// Common factors for potential computation
/** Χ = 1 / sqrt(1 - e²) = 1 / B. */
private double chi;
/** Χ². */
private double chi2;
// Equinoctial reference frame vectors (according to DSST notation)
/** Equinoctial frame f vector. */
private Vector3D f;
/** Equinoctial frame g vector. */
private Vector3D g;
/** Central body rotation angle θ. */
private double theta;
/** Direction cosine α. */
private double alpha;
/** Direction cosine β. */
private double beta;
/** Direction cosine γ. */
private double gamma;
// Common factors from equinoctial coefficients
/** 2 * a / A .*/
private double ax2oA;
/** 1 / (A * B) .*/
private double ooAB;
/** B / A .*/
private double BoA;
/** B / (A * (1 + B)) .*/
private double BoABpo;
/** C / (2 * A * B) .*/
private double Co2AB;
/** μ / a .*/
private double moa;
/** R / a .*/
private double roa;
/** ecc². */
private double e2;
/** The satellite mean motion. */
private double meanMotion;
/** Flag to take into account only M-dailies harmonic tesserals for short periodic perturbations. */
private final boolean mDailiesOnly;
/** Maximum value for j.
* <p>
* jmax = maxDegreeTesseralSP + maxEccPowTesseralSP, no more than 12
* </p>
* */
private int jMax;
/** List of non resonant orders with j != 0. */
private final SortedMap<Integer, List<Integer> > nonResOrders;
/** A two dimensional array that contains the objects needed to build the Hansen coefficients. <br/>
* The indexes are s + maxDegree and j */
private HansenTesseralLinear[][] hansenObjects;
/** Fourier coefficients. */
private FourierCjSjCoefficients cjsjFourier;
/** Short period terms. */
private TesseralShortPeriodicCoefficients shortPeriodTerms;
/** Single constructor.
* @param centralBodyFrame rotating body frame
* @param centralBodyRotationRate central body rotation rate (rad/s)
* @param provider provider for spherical harmonics
* @param mDailiesOnly if true only M-dailies tesseral harmonics are taken into account for short periodics
*/
TesseralContribution(final Frame centralBodyFrame,
final double centralBodyRotationRate,
final UnnormalizedSphericalHarmonicsProvider provider,
final boolean mDailiesOnly) {
// Central body rotating frame
this.bodyFrame = centralBodyFrame;
//Save the rotation rate
this.centralBodyRotationRate = centralBodyRotationRate;
// Central body rotation period in seconds
this.bodyPeriod = MathUtils.TWO_PI / centralBodyRotationRate;
// Provider for spherical harmonics
this.provider = provider;
this.maxDegree = provider.getMaxDegree();
this.maxOrder = provider.getMaxOrder();
//set the maximum degree order for short periodics
this.maxDegreeTesseralSP = FastMath.min(maxDegree, MAX_DEGREE_TESSERAL_SP);
this.maxDegreeMdailyTesseralSP = FastMath.min(maxDegree, MAX_DEGREE_MDAILY_TESSERAL_SP);
this.maxOrderTesseralSP = FastMath.min(maxOrder, MAX_ORDER_TESSERAL_SP);
this.maxOrderMdailyTesseralSP = FastMath.min(maxOrder, MAX_ORDER_MDAILY_TESSERAL_SP);
// set the maximum value for eccentricity power
this.maxEccPowTesseralSP = MAX_ECCPOWER_SP;
this.maxEccPowMdailyTesseralSP = FastMath.min(maxDegreeMdailyTesseralSP - 2, MAX_ECCPOWER_SP);
this.jMax = FastMath.min(MAXJ, maxDegreeTesseralSP + maxEccPowTesseralSP);
// m-daylies only
this.mDailiesOnly = mDailiesOnly;
// Initialize default values
this.resOrders = new ArrayList<Integer>();
this.nonResOrders = new TreeMap<Integer, List <Integer> >();
this.maxEccPow = 0;
this.maxHansen = 0;
// Factorials computation
final int maxFact = 2 * maxDegree + 1;
this.fact = new double[maxFact];
fact[0] = 1;
for (int i = 1; i < maxFact; i++) {
fact[i] = i * fact[i - 1];
}
}
/** {@inheritDoc} */
@Override
public List<ShortPeriodTerms> initialize(final AuxiliaryElements aux, final boolean meanOnly)
throws OrekitException {
// Keplerian period
orbitPeriod = aux.getKeplerianPeriod();
// Set the highest power of the eccentricity in the analytical power
// series expansion for the averaged high order resonant central body
// spherical harmonic perturbation
final double e = aux.getEcc();
if (e <= 0.005) {
maxEccPow = 3;
} else if (e <= 0.02) {
maxEccPow = 4;
} else if (e <= 0.1) {
maxEccPow = 7;
} else if (e <= 0.2) {
maxEccPow = 10;
} else if (e <= 0.3) {
maxEccPow = 12;
} else if (e <= 0.4) {
maxEccPow = 15;
} else {
maxEccPow = 20;
}
// Set the maximum power of the eccentricity to use in Hansen coefficient Kernel expansion.
maxHansen = maxEccPow / 2;
jMax = FastMath.min(MAXJ, maxDegree + maxEccPow);
// Ratio of satellite to central body periods to define resonant terms
ratio = orbitPeriod / bodyPeriod;
// Compute the resonant tesseral harmonic terms if not set by the user
getResonantAndNonResonantTerms(meanOnly);
//initialize the HansenTesseralLinear objects needed
createHansenObjects(meanOnly);
final int mMax = FastMath.max(maxOrderTesseralSP, maxOrderMdailyTesseralSP);
cjsjFourier = new FourierCjSjCoefficients(jMax, mMax);
shortPeriodTerms = new TesseralShortPeriodicCoefficients(bodyFrame, maxOrderMdailyTesseralSP,
mDailiesOnly, nonResOrders,
mMax, jMax, INTERPOLATION_POINTS);
final List<ShortPeriodTerms> list = new ArrayList<ShortPeriodTerms>();
list.add(shortPeriodTerms);
return list;
}
/** Create the objects needed for linear transformation.
*
* <p>
* Each {@link org.orekit.propagation.semianalytical.dsst.utilities.hansenHansenTesseralLinear HansenTesseralLinear} uses
* a fixed value for s and j. Since j varies from -maxJ to +maxJ and s varies from -maxDegree to +maxDegree,
* a 2 * maxDegree + 1 x 2 * maxJ + 1 matrix of objects should be created. The size of this matrix can be reduced
* by taking into account the expression (2.7.3-2). This means that is enough to create the objects for positive
* values of j and all values of s.
* </p>
*
* @param meanOnly create only the objects required for the mean contribution
*/
private void createHansenObjects(final boolean meanOnly) {
//Allocate the two dimensional array
final int rows = 2 * maxDegree + 1;
final int columns = jMax + 1;
this.hansenObjects = new HansenTesseralLinear[rows][columns];
if (meanOnly) {
// loop through the resonant orders
for (int m : resOrders) {
//Compute the corresponding j term
final int j = FastMath.max(1, (int) FastMath.round(ratio * m));
//Compute the sMin and sMax values
final int sMin = FastMath.min(maxEccPow - j, maxDegree);
final int sMax = FastMath.min(maxEccPow + j, maxDegree);
//loop through the s values
for (int s = 0; s <= sMax; s++) {
//Compute the n0 value
final int n0 = FastMath.max(FastMath.max(2, m), s);
//Create the object for the pair j,s
this.hansenObjects[s + maxDegree][j] = new HansenTesseralLinear(maxDegree, s, j, n0, maxHansen);
if (s > 0 && s <= sMin) {
//Also create the object for the pair j, -s
this.hansenObjects[maxDegree - s][j] = new HansenTesseralLinear(maxDegree, -s, j, n0, maxHansen);
}
}
}
} else {
// create all objects
for (int j = 0; j <= jMax; j++) {
for (int s = -maxDegree; s <= maxDegree; s++) {
//Compute the n0 value
final int n0 = FastMath.max(2, FastMath.abs(s));
this.hansenObjects[s + maxDegree][j] = new HansenTesseralLinear(maxDegree, s, j, n0, maxHansen);
}
}
}
}
/** {@inheritDoc} */
@Override
public void initializeStep(final AuxiliaryElements aux) throws OrekitException {
// Equinoctial elements
a = aux.getSma();
k = aux.getK();
h = aux.getH();
q = aux.getQ();
p = aux.getP();
lm = aux.getLM();
// Eccentricity
ecc = aux.getEcc();
e2 = ecc * ecc;
// Equinoctial frame vectors
f = aux.getVectorF();
g = aux.getVectorG();
// Central body rotation angle from equation 2.7.1-(3)(4).
final Transform t = bodyFrame.getTransformTo(aux.getFrame(), aux.getDate());
final Vector3D xB = t.transformVector(Vector3D.PLUS_I);
final Vector3D yB = t.transformVector(Vector3D.PLUS_J);
theta = FastMath.atan2(-f.dotProduct(yB) + I * g.dotProduct(xB),
f.dotProduct(xB) + I * g.dotProduct(yB));
// Direction cosines
alpha = aux.getAlpha();
beta = aux.getBeta();
gamma = aux.getGamma();
// Equinoctial coefficients
// A = sqrt(μ * a)
final double A = aux.getA();
// B = sqrt(1 - h² - k²)
final double B = aux.getB();
// C = 1 + p² + q²
final double C = aux.getC();
// Common factors from equinoctial coefficients
// 2 * a / A
ax2oA = 2. * a / A;
// B / A
BoA = B / A;
// 1 / AB
ooAB = 1. / (A * B);
// C / 2AB
Co2AB = C * ooAB / 2.;
// B / (A * (1 + B))
BoABpo = BoA / (1. + B);
// &mu / a
moa = provider.getMu() / a;
// R / a
roa = provider.getAe() / a;
// Χ = 1 / B
chi = 1. / B;
chi2 = chi * chi;
//mean motion n
meanMotion = aux.getMeanMotion();
}
/** {@inheritDoc} */
@Override
public double[] getMeanElementRate(final SpacecraftState spacecraftState) throws OrekitException {
// Compute potential derivatives
final double[] dU = computeUDerivatives(spacecraftState.getDate());
final double dUda = dU[0];
final double dUdh = dU[1];
final double dUdk = dU[2];
final double dUdl = dU[3];
final double dUdAl = dU[4];
final double dUdBe = dU[5];
final double dUdGa = dU[6];
// Compute the cross derivative operator :
final double UAlphaGamma = alpha * dUdGa - gamma * dUdAl;
final double UAlphaBeta = alpha * dUdBe - beta * dUdAl;
final double UBetaGamma = beta * dUdGa - gamma * dUdBe;
final double Uhk = h * dUdk - k * dUdh;
final double pUagmIqUbgoAB = (p * UAlphaGamma - I * q * UBetaGamma) * ooAB;
final double UhkmUabmdUdl = Uhk - UAlphaBeta - dUdl;
final double da = ax2oA * dUdl;
final double dh = BoA * dUdk + k * pUagmIqUbgoAB - h * BoABpo * dUdl;
final double dk = -(BoA * dUdh + h * pUagmIqUbgoAB + k * BoABpo * dUdl);
final double dp = Co2AB * (p * UhkmUabmdUdl - UBetaGamma);
final double dq = Co2AB * (q * UhkmUabmdUdl - I * UAlphaGamma);
final double dM = -ax2oA * dUda + BoABpo * (h * dUdh + k * dUdk) + pUagmIqUbgoAB;
return new double[] {da, dk, dh, dq, dp, dM};
}
/** {@inheritDoc} */
@Override
public void updateShortPeriodTerms(final SpacecraftState ... meanStates)
throws OrekitException {
final Slot slot = shortPeriodTerms.createSlot(meanStates);
for (final SpacecraftState meanState : meanStates) {
initializeStep(new AuxiliaryElements(meanState.getOrbit(), I));
// Initialise the Hansen coefficients
for (int s = -maxDegree; s <= maxDegree; s++) {
// coefficients with j == 0 are always needed
this.hansenObjects[s + maxDegree][0].computeInitValues(e2, chi, chi2);
if (!mDailiesOnly) {
// initialize other objects only if required
for (int j = 1; j <= jMax; j++) {
this.hansenObjects[s + maxDegree][j].computeInitValues(e2, chi, chi2);
}
}
}
// Compute coefficients
// Compute only if there is at least one non-resonant tesseral
if (!nonResOrders.isEmpty() || mDailiesOnly) {
// Generate the fourrier coefficients
cjsjFourier.generateCoefficients(meanState.getDate());
// the coefficient 3n / 2a
final double tnota = 1.5 * meanMotion / a;
// build the mDaily coefficients
for (int m = 1; m <= maxOrderMdailyTesseralSP; m++) {
// build the coefficients
buildCoefficients(meanState.getDate(), slot, m, 0, tnota);
}
if (!mDailiesOnly) {
// generate the other coefficients, if required
for (int m: nonResOrders.keySet()) {
final List<Integer> listJ = nonResOrders.get(m);
for (int j: listJ) {
// build the coefficients
buildCoefficients(meanState.getDate(), slot, m, j, tnota);
}
}
}
}
}
}
/** Build a set of coefficients.
*
* @param date the current date
* @param slot slot to which the coefficients belong
* @param m m index
* @param j j index
* @param tnota 3n/2a
*/
private void buildCoefficients(final AbsoluteDate date, final Slot slot,
final int m, final int j, final double tnota) {
// Create local arrays
final double[] currentCijm = new double[] {0., 0., 0., 0., 0., 0.};
final double[] currentSijm = new double[] {0., 0., 0., 0., 0., 0.};
// compute the term 1 / (jn - mθ<sup>.</sup>)
final double oojnmt = 1. / (j * meanMotion - m * centralBodyRotationRate);
// initialise the coeficients
for (int i = 0; i < 6; i++) {
currentCijm[i] = -cjsjFourier.getSijm(i, j, m);
currentSijm[i] = cjsjFourier.getCijm(i, j, m);
}
// Add the separate part for δ<sub>6i</sub>
currentCijm[5] += tnota * oojnmt * cjsjFourier.getCijm(0, j, m);
currentSijm[5] += tnota * oojnmt * cjsjFourier.getSijm(0, j, m);
//Multiply by 1 / (jn - mθ<sup>.</sup>)
for (int i = 0; i < 6; i++) {
currentCijm[i] *= oojnmt;
currentSijm[i] *= oojnmt;
}
// Add the coefficients to the interpolation grid
slot.cijm[m][j + jMax].addGridPoint(date, currentCijm);
slot.sijm[m][j + jMax].addGridPoint(date, currentSijm);
}
/** {@inheritDoc} */
@Override
public EventDetector[] getEventsDetectors() {
return null;
}
/**
* Get the resonant and non-resonant tesseral terms in the central body spherical harmonic field.
*
* @param resonantOnly extract only resonant terms
*/
private void getResonantAndNonResonantTerms(final boolean resonantOnly) {
// Compute natural resonant terms
final double tolerance = 1. / FastMath.max(MIN_PERIOD_IN_SAT_REV,
MIN_PERIOD_IN_SECONDS / orbitPeriod);
// Search the resonant orders in the tesseral harmonic field
resOrders.clear();
nonResOrders.clear();
for (int m = 1; m <= maxOrder; m++) {
final double resonance = ratio * m;
int jRes = 0;
final int jComputedRes = (int) FastMath.round(resonance);
if (jComputedRes > 0 && jComputedRes <= jMax && FastMath.abs(resonance - jComputedRes) <= tolerance) {
// Store each resonant index and order
resOrders.add(m);
jRes = jComputedRes;
}
if (!resonantOnly && !mDailiesOnly && m <= maxOrderTesseralSP) {
//compute non resonant orders in the tesseral harmonic field
final List<Integer> listJofM = new ArrayList<Integer>();
//for the moment we take only the pairs (j,m) with |j| <= maxDegree + maxEccPow (from |s-j| <= maxEccPow and |s| <= maxDegree)
for (int j = -jMax; j <= jMax; j++) {
if (j != 0 && j != jRes) {
listJofM.add(j);
}
}
nonResOrders.put(m, listJofM);
}
}
}
/** Computes the potential U derivatives.
* <p>The following elements are computed from expression 3.3 - (4).
* <pre>
* dU / da
* dU / dh
* dU / dk
* dU / dλ
* dU / dα
* dU / dβ
* dU / dγ
* </pre>
* </p>
*
* @param date current date
* @return potential derivatives
* @throws OrekitException if an error occurs
*/
private double[] computeUDerivatives(final AbsoluteDate date) throws OrekitException {
// Potential derivatives
double dUda = 0.;
double dUdh = 0.;
double dUdk = 0.;
double dUdl = 0.;
double dUdAl = 0.;
double dUdBe = 0.;
double dUdGa = 0.;
// Compute only if there is at least one resonant tesseral
if (!resOrders.isEmpty()) {
// Gmsj and Hmsj polynomials
final GHmsjPolynomials ghMSJ = new GHmsjPolynomials(k, h, alpha, beta, I);
// GAMMAmns function
final GammaMnsFunction gammaMNS = new GammaMnsFunction(fact, gamma, I);
// R / a up to power degree
final double[] roaPow = new double[maxDegree + 1];
roaPow[0] = 1.;
for (int i = 1; i <= maxDegree; i++) {
roaPow[i] = roa * roaPow[i - 1];
}
// SUM over resonant terms {j,m}
for (int m : resOrders) {
// Resonant index for the current resonant order
final int j = FastMath.max(1, (int) FastMath.round(ratio * m));
// Phase angle
final double jlMmt = j * lm - m * theta;
final double sinPhi = FastMath.sin(jlMmt);
final double cosPhi = FastMath.cos(jlMmt);
// Potential derivatives components for a given resonant pair {j,m}
double dUdaCos = 0.;
double dUdaSin = 0.;
double dUdhCos = 0.;
double dUdhSin = 0.;
double dUdkCos = 0.;
double dUdkSin = 0.;
double dUdlCos = 0.;
double dUdlSin = 0.;
double dUdAlCos = 0.;
double dUdAlSin = 0.;
double dUdBeCos = 0.;
double dUdBeSin = 0.;
double dUdGaCos = 0.;
double dUdGaSin = 0.;
// s-SUM from -sMin to sMax
final int sMin = FastMath.min(maxEccPow - j, maxDegree);
final int sMax = FastMath.min(maxEccPow + j, maxDegree);
for (int s = 0; s <= sMax; s++) {
//Compute the initial values for Hansen coefficients using newComb operators
this.hansenObjects[s + maxDegree][j].computeInitValues(e2, chi, chi2);
// n-SUM for s positive
final double[][] nSumSpos = computeNSum(date, j, m, s, maxDegree,
roaPow, ghMSJ, gammaMNS);
dUdaCos += nSumSpos[0][0];
dUdaSin += nSumSpos[0][1];
dUdhCos += nSumSpos[1][0];
dUdhSin += nSumSpos[1][1];
dUdkCos += nSumSpos[2][0];
dUdkSin += nSumSpos[2][1];
dUdlCos += nSumSpos[3][0];
dUdlSin += nSumSpos[3][1];
dUdAlCos += nSumSpos[4][0];
dUdAlSin += nSumSpos[4][1];
dUdBeCos += nSumSpos[5][0];
dUdBeSin += nSumSpos[5][1];
dUdGaCos += nSumSpos[6][0];
dUdGaSin += nSumSpos[6][1];
// n-SUM for s negative
if (s > 0 && s <= sMin) {
//Compute the initial values for Hansen coefficients using newComb operators
this.hansenObjects[maxDegree - s][j].computeInitValues(e2, chi, chi2);
final double[][] nSumSneg = computeNSum(date, j, m, -s, maxDegree,
roaPow, ghMSJ, gammaMNS);
dUdaCos += nSumSneg[0][0];
dUdaSin += nSumSneg[0][1];
dUdhCos += nSumSneg[1][0];
dUdhSin += nSumSneg[1][1];
dUdkCos += nSumSneg[2][0];
dUdkSin += nSumSneg[2][1];
dUdlCos += nSumSneg[3][0];
dUdlSin += nSumSneg[3][1];
dUdAlCos += nSumSneg[4][0];
dUdAlSin += nSumSneg[4][1];
dUdBeCos += nSumSneg[5][0];
dUdBeSin += nSumSneg[5][1];
dUdGaCos += nSumSneg[6][0];
dUdGaSin += nSumSneg[6][1];
}
}
// Assembly of potential derivatives componants
dUda += cosPhi * dUdaCos + sinPhi * dUdaSin;
dUdh += cosPhi * dUdhCos + sinPhi * dUdhSin;
dUdk += cosPhi * dUdkCos + sinPhi * dUdkSin;
dUdl += cosPhi * dUdlCos + sinPhi * dUdlSin;
dUdAl += cosPhi * dUdAlCos + sinPhi * dUdAlSin;
dUdBe += cosPhi * dUdBeCos + sinPhi * dUdBeSin;
dUdGa += cosPhi * dUdGaCos + sinPhi * dUdGaSin;
}
dUda *= -moa / a;
dUdh *= moa;
dUdk *= moa;
dUdl *= moa;
dUdAl *= moa;
dUdBe *= moa;
dUdGa *= moa;
}
return new double[] {dUda, dUdh, dUdk, dUdl, dUdAl, dUdBe, dUdGa};
}
/** Compute the n-SUM for potential derivatives components.
* @param date current date
* @param j resonant index <i>j</i>
* @param m resonant order <i>m</i>
* @param s d'Alembert characteristic <i>s</i>
* @param maxN maximum possible value for <i>n</i> index
* @param roaPow powers of R/a up to degree <i>n</i>
* @param ghMSJ G<sup>j</sup><sub>m,s</sub> and H<sup>j</sup><sub>m,s</sub> polynomials
* @param gammaMNS Γ<sup>m</sup><sub>n,s</sub>(γ) function
* @return Components of U<sub>n</sub> derivatives for fixed j, m, s
* @throws OrekitException if some error occurred
*/
private double[][] computeNSum(final AbsoluteDate date,
final int j, final int m, final int s, final int maxN, final double[] roaPow,
final GHmsjPolynomials ghMSJ, final GammaMnsFunction gammaMNS)
throws OrekitException {
//spherical harmonics
final UnnormalizedSphericalHarmonics harmonics = provider.onDate(date);
// Potential derivatives components
double dUdaCos = 0.;
double dUdaSin = 0.;
double dUdhCos = 0.;
double dUdhSin = 0.;
double dUdkCos = 0.;
double dUdkSin = 0.;
double dUdlCos = 0.;
double dUdlSin = 0.;
double dUdAlCos = 0.;
double dUdAlSin = 0.;
double dUdBeCos = 0.;
double dUdBeSin = 0.;
double dUdGaCos = 0.;
double dUdGaSin = 0.;
// I^m
@SuppressWarnings("unused")
final int Im = I > 0 ? 1 : (m % 2 == 0 ? 1 : -1);
// jacobi v, w, indices from 2.7.1-(15)
final int v = FastMath.abs(m - s);
final int w = FastMath.abs(m + s);
// Initialise lower degree nmin = (Max(2, m, |s|)) for summation over n
final int nmin = FastMath.max(FastMath.max(2, m), FastMath.abs(s));
//Get the corresponding Hansen object
final int sIndex = maxDegree + (j < 0 ? -s : s);
final int jIndex = FastMath.abs(j);
final HansenTesseralLinear hans = this.hansenObjects[sIndex][jIndex];
// n-SUM from nmin to N
for (int n = nmin; n <= maxN; n++) {
// If (n - s) is odd, the contribution is null because of Vmns
if ((n - s) % 2 == 0) {
// Vmns coefficient
final double fns = fact[n + FastMath.abs(s)];
final double vMNS = CoefficientsFactory.getVmns(m, n, s, fns, fact[n - m]);
// Inclination function Gamma and derivative
final double gaMNS = gammaMNS.getValue(m, n, s);
final double dGaMNS = gammaMNS.getDerivative(m, n, s);
// Hansen kernel value and derivative
final double kJNS = hans.getValue(-n - 1, chi);
final double dkJNS = hans.getDerivative(-n - 1, chi);
// Gjms, Hjms polynomials and derivatives
final double gMSJ = ghMSJ.getGmsj(m, s, j);
final double hMSJ = ghMSJ.getHmsj(m, s, j);
final double dGdh = ghMSJ.getdGmsdh(m, s, j);
final double dGdk = ghMSJ.getdGmsdk(m, s, j);
final double dGdA = ghMSJ.getdGmsdAlpha(m, s, j);
final double dGdB = ghMSJ.getdGmsdBeta(m, s, j);
final double dHdh = ghMSJ.getdHmsdh(m, s, j);
final double dHdk = ghMSJ.getdHmsdk(m, s, j);
final double dHdA = ghMSJ.getdHmsdAlpha(m, s, j);
final double dHdB = ghMSJ.getdHmsdBeta(m, s, j);
// Jacobi l-index from 2.7.1-(15)
final int l = FastMath.min(n - m, n - FastMath.abs(s));
// Jacobi polynomial and derivative
final DerivativeStructure jacobi =
JacobiPolynomials.getValue(l, v, w, new DerivativeStructure(1, 1, 0, gamma));
// Geopotential coefficients
final double cnm = harmonics.getUnnormalizedCnm(n, m);
final double snm = harmonics.getUnnormalizedSnm(n, m);
// Common factors from expansion of equations 3.3-4
final double cf_0 = roaPow[n] * Im * vMNS;
final double cf_1 = cf_0 * gaMNS * jacobi.getValue();
final double cf_2 = cf_1 * kJNS;
final double gcPhs = gMSJ * cnm + hMSJ * snm;
final double gsMhc = gMSJ * snm - hMSJ * cnm;
final double dKgcPhsx2 = 2. * dkJNS * gcPhs;
final double dKgsMhcx2 = 2. * dkJNS * gsMhc;
final double dUdaCoef = (n + 1) * cf_2;
final double dUdlCoef = j * cf_2;
final double dUdGaCoef = cf_0 * kJNS * (jacobi.getValue() * dGaMNS + gaMNS * jacobi.getPartialDerivative(1));
// dU / da components
dUdaCos += dUdaCoef * gcPhs;
dUdaSin += dUdaCoef * gsMhc;
// dU / dh components
dUdhCos += cf_1 * (kJNS * (cnm * dGdh + snm * dHdh) + h * dKgcPhsx2);
dUdhSin += cf_1 * (kJNS * (snm * dGdh - cnm * dHdh) + h * dKgsMhcx2);
// dU / dk components
dUdkCos += cf_1 * (kJNS * (cnm * dGdk + snm * dHdk) + k * dKgcPhsx2);
dUdkSin += cf_1 * (kJNS * (snm * dGdk - cnm * dHdk) + k * dKgsMhcx2);
// dU / dLambda components
dUdlCos += dUdlCoef * gsMhc;
dUdlSin += -dUdlCoef * gcPhs;
// dU / alpha components
dUdAlCos += cf_2 * (dGdA * cnm + dHdA * snm);
dUdAlSin += cf_2 * (dGdA * snm - dHdA * cnm);
// dU / dBeta components
dUdBeCos += cf_2 * (dGdB * cnm + dHdB * snm);
dUdBeSin += cf_2 * (dGdB * snm - dHdB * cnm);
// dU / dGamma components
dUdGaCos += dUdGaCoef * gcPhs;
dUdGaSin += dUdGaCoef * gsMhc;
}
}
return new double[][] {{dUdaCos, dUdaSin},
{dUdhCos, dUdhSin},
{dUdkCos, dUdkSin},
{dUdlCos, dUdlSin},
{dUdAlCos, dUdAlSin},
{dUdBeCos, dUdBeSin},
{dUdGaCos, dUdGaSin}};
}
/** {@inheritDoc} */
@Override
public void registerAttitudeProvider(final AttitudeProvider attitudeProvider) {
//nothing is done since this contribution is not sensitive to attitude
}
/** Compute the C<sup>j</sup> and the S<sup>j</sup> coefficients.
* <p>
* Those coefficients are given in Danielson paper by substituting the
* disturbing function (2.7.1-16) with m != 0 into (2.2-10)
* </p>
*/
private class FourierCjSjCoefficients {
/** Absolute limit for j ( -jMax <= j <= jMax ). */
private final int jMax;
/** The C<sub>i</sub><sup>jm</sup> coefficients.
* <p>
* The index order is [m][j][i] <br/>
* The i index corresponds to the C<sub>i</sub><sup>jm</sup> coefficients used to
* compute the following: <br/>
* - da/dt <br/>
* - dk/dt <br/>
* - dh/dt / dk <br/>
* - dq/dt <br/>
* - dp/dt / dα <br/>
* - dλ/dt / dβ <br/>
* </p>
*/
private final double[][][] cCoef;
/** The S<sub>i</sub><sup>jm</sup> coefficients.
* <p>
* The index order is [m][j][i] <br/>
* The i index corresponds to the C<sub>i</sub><sup>jm</sup> coefficients used to
* compute the following: <br/>
* - da/dt <br/>
* - dk/dt <br/>
* - dh/dt / dk <br/>
* - dq/dt <br/>
* - dp/dt / dα <br/>
* - dλ/dt / dβ <br/>
* </p>
*/
private final double[][][] sCoef;
/** G<sub>ms</sub><sup>j</sup> and H<sub>ms</sub><sup>j</sup> polynomials. */
private GHmsjPolynomials ghMSJ;
/** Γ<sub>ns</sub><sup>m</sup> function. */
private GammaMnsFunction gammaMNS;
/** R / a up to power degree. */
private final double[] roaPow;
/** Create a set of C<sub>i</sub><sup>jm</sup> and S<sub>i</sub><sup>jm</sup> coefficients.
* @param jMax absolute limit for j ( -jMax <= j <= jMax )
* @param mMax maximum value for m
*/
FourierCjSjCoefficients(final int jMax, final int mMax) {
// initialise fields
final int rows = mMax + 1;
final int columns = 2 * jMax + 1;
this.jMax = jMax;
this.cCoef = new double[rows][columns][6];
this.sCoef = new double[rows][columns][6];
this.roaPow = new double[maxDegree + 1];
roaPow[0] = 1.;
}
/**
* Generate the coefficients.
* @param date the current date
* @throws OrekitException if an error occurs while generating the coefficients
*/
public void generateCoefficients(final AbsoluteDate date) throws OrekitException {
// Compute only if there is at least one non-resonant tesseral
if (!nonResOrders.isEmpty() || mDailiesOnly) {
// Gmsj and Hmsj polynomials
ghMSJ = new GHmsjPolynomials(k, h, alpha, beta, I);
// GAMMAmns function
gammaMNS = new GammaMnsFunction(fact, gamma, I);
final int maxRoaPower = FastMath.max(maxDegreeTesseralSP, maxDegreeMdailyTesseralSP);
// R / a up to power degree
for (int i = 1; i <= maxRoaPower; i++) {
roaPow[i] = roa * roaPow[i - 1];
}
//generate the m-daily coefficients
for (int m = 1; m <= maxOrderMdailyTesseralSP; m++) {
buildFourierCoefficients(date, m, 0, maxDegreeMdailyTesseralSP);
}
// generate the other coefficients only if required
if (!mDailiesOnly) {
for (int m: nonResOrders.keySet()) {
final List<Integer> listJ = nonResOrders.get(m);
for (int j: listJ) {
buildFourierCoefficients(date, m, j, maxDegreeTesseralSP);
}
}
}
}
}
/** Build a set of fourier coefficients for a given m and j.
*
* @param date the date of the coefficients
* @param m m index
* @param j j index
* @param maxN maximum value for n index
* @throws OrekitException in case of Hansen kernel generation error
*/
private void buildFourierCoefficients(final AbsoluteDate date,
final int m, final int j, final int maxN) throws OrekitException {
// Potential derivatives components for a given non-resonant pair {j,m}
double dRdaCos = 0.;
double dRdaSin = 0.;
double dRdhCos = 0.;
double dRdhSin = 0.;
double dRdkCos = 0.;
double dRdkSin = 0.;
double dRdlCos = 0.;
double dRdlSin = 0.;
double dRdAlCos = 0.;
double dRdAlSin = 0.;
double dRdBeCos = 0.;
double dRdBeSin = 0.;
double dRdGaCos = 0.;
double dRdGaSin = 0.;
// s-SUM from -sMin to sMax
final int sMin = j == 0 ? maxEccPowMdailyTesseralSP : maxEccPowTesseralSP;
final int sMax = j == 0 ? maxEccPowMdailyTesseralSP : maxEccPowTesseralSP;
for (int s = 0; s <= sMax; s++) {
// n-SUM for s positive
final double[][] nSumSpos = computeNSum(date, j, m, s, maxN,
roaPow, ghMSJ, gammaMNS);
dRdaCos += nSumSpos[0][0];
dRdaSin += nSumSpos[0][1];
dRdhCos += nSumSpos[1][0];
dRdhSin += nSumSpos[1][1];
dRdkCos += nSumSpos[2][0];
dRdkSin += nSumSpos[2][1];
dRdlCos += nSumSpos[3][0];
dRdlSin += nSumSpos[3][1];
dRdAlCos += nSumSpos[4][0];
dRdAlSin += nSumSpos[4][1];
dRdBeCos += nSumSpos[5][0];
dRdBeSin += nSumSpos[5][1];
dRdGaCos += nSumSpos[6][0];
dRdGaSin += nSumSpos[6][1];
// n-SUM for s negative
if (s > 0 && s <= sMin) {
final double[][] nSumSneg = computeNSum(date, j, m, -s, maxN,
roaPow, ghMSJ, gammaMNS);
dRdaCos += nSumSneg[0][0];
dRdaSin += nSumSneg[0][1];
dRdhCos += nSumSneg[1][0];
dRdhSin += nSumSneg[1][1];
dRdkCos += nSumSneg[2][0];
dRdkSin += nSumSneg[2][1];
dRdlCos += nSumSneg[3][0];
dRdlSin += nSumSneg[3][1];
dRdAlCos += nSumSneg[4][0];
dRdAlSin += nSumSneg[4][1];
dRdBeCos += nSumSneg[5][0];
dRdBeSin += nSumSneg[5][1];
dRdGaCos += nSumSneg[6][0];
dRdGaSin += nSumSneg[6][1];
}
}
dRdaCos *= -moa / a;
dRdaSin *= -moa / a;
dRdhCos *= moa;
dRdhSin *= moa;
dRdkCos *= moa;
dRdkSin *= moa;
dRdlCos *= moa;
dRdlSin *= moa;
dRdAlCos *= moa;
dRdAlSin *= moa;
dRdBeCos *= moa;
dRdBeSin *= moa;
dRdGaCos *= moa;
dRdGaSin *= moa;
// Compute the cross derivative operator :
final double RAlphaGammaCos = alpha * dRdGaCos - gamma * dRdAlCos;
final double RAlphaGammaSin = alpha * dRdGaSin - gamma * dRdAlSin;
final double RAlphaBetaCos = alpha * dRdBeCos - beta * dRdAlCos;
final double RAlphaBetaSin = alpha * dRdBeSin - beta * dRdAlSin;
final double RBetaGammaCos = beta * dRdGaCos - gamma * dRdBeCos;
final double RBetaGammaSin = beta * dRdGaSin - gamma * dRdBeSin;
final double RhkCos = h * dRdkCos - k * dRdhCos;
final double RhkSin = h * dRdkSin - k * dRdhSin;
final double pRagmIqRbgoABCos = (p * RAlphaGammaCos - I * q * RBetaGammaCos) * ooAB;
final double pRagmIqRbgoABSin = (p * RAlphaGammaSin - I * q * RBetaGammaSin) * ooAB;
final double RhkmRabmdRdlCos = RhkCos - RAlphaBetaCos - dRdlCos;
final double RhkmRabmdRdlSin = RhkSin - RAlphaBetaSin - dRdlSin;
// da/dt
cCoef[m][j + jMax][0] = ax2oA * dRdlCos;
sCoef[m][j + jMax][0] = ax2oA * dRdlSin;
// dk/dt
cCoef[m][j + jMax][1] = -(BoA * dRdhCos + h * pRagmIqRbgoABCos + k * BoABpo * dRdlCos);
sCoef[m][j + jMax][1] = -(BoA * dRdhSin + h * pRagmIqRbgoABSin + k * BoABpo * dRdlSin);
// dh/dt
cCoef[m][j + jMax][2] = BoA * dRdkCos + k * pRagmIqRbgoABCos - h * BoABpo * dRdlCos;
sCoef[m][j + jMax][2] = BoA * dRdkSin + k * pRagmIqRbgoABSin - h * BoABpo * dRdlSin;
// dq/dt
cCoef[m][j + jMax][3] = Co2AB * (q * RhkmRabmdRdlCos - I * RAlphaGammaCos);
sCoef[m][j + jMax][3] = Co2AB * (q * RhkmRabmdRdlSin - I * RAlphaGammaSin);
// dp/dt
cCoef[m][j + jMax][4] = Co2AB * (p * RhkmRabmdRdlCos - RBetaGammaCos);
sCoef[m][j + jMax][4] = Co2AB * (p * RhkmRabmdRdlSin - RBetaGammaSin);
// dλ/dt
cCoef[m][j + jMax][5] = -ax2oA * dRdaCos + BoABpo * (h * dRdhCos + k * dRdkCos) + pRagmIqRbgoABCos;
sCoef[m][j + jMax][5] = -ax2oA * dRdaSin + BoABpo * (h * dRdhSin + k * dRdkSin) + pRagmIqRbgoABSin;
}
/** Get the coefficient C<sub>i</sub><sup>jm</sup>.
* @param i i index - corresponds to the required variation
* @param j j index
* @param m m index
* @return the coefficient C<sub>i</sub><sup>jm</sup>
*/
public double getCijm(final int i, final int j, final int m) {
return cCoef[m][j + jMax][i];
}
/** Get the coefficient S<sub>i</sub><sup>jm</sup>.
* @param i i index - corresponds to the required variation
* @param j j index
* @param m m index
* @return the coefficient S<sub>i</sub><sup>jm</sup>
*/
public double getSijm(final int i, final int j, final int m) {
return sCoef[m][j + jMax][i];
}
}
/** The C<sup>i</sup><sub>m</sub><sub>t</sub> and S<sup>i</sup><sub>m</sub><sub>t</sub> coefficients used to compute
* the short-periodic zonal contribution.
* <p>
* Those coefficients are given by expression 2.5.4-5 from the Danielson paper.
* </p>
*
* @author Sorin Scortan
*
*/
private static class TesseralShortPeriodicCoefficients implements ShortPeriodTerms {
/** Serializable UID. */
private static final long serialVersionUID = 20151119L;
/** Retrograde factor I.
* <p>
* DSST model needs equinoctial orbit as internal representation.
* Classical equinoctial elements have discontinuities when inclination
* is close to zero. In this representation, I = +1. <br>
* To avoid this discontinuity, another representation exists and equinoctial
* elements can be expressed in a different way, called "retrograde" orbit.
* This implies I = -1. <br>
* As Orekit doesn't implement the retrograde orbit, I is always set to +1.
* But for the sake of consistency with the theory, the retrograde factor
* has been kept in the formulas.
* </p>
*/
private static final int I = 1;
/** Central body rotating frame. */
private final Frame bodyFrame;
/** Maximal order to consider for short periodics m-daily tesseral harmonics potential. */
private final int maxOrderMdailyTesseralSP;
/** Flag to take into account only M-dailies harmonic tesserals for short periodic perturbations. */
private final boolean mDailiesOnly;
/** List of non resonant orders with j != 0. */
private final SortedMap<Integer, List<Integer> > nonResOrders;
/** Maximum value for m index. */
private final int mMax;
/** Maximum value for j index. */
private final int jMax;
/** Number of points used in the interpolation process. */
private final int interpolationPoints;
/** All coefficients slots. */
private final TimeSpanMap<Slot> slots;
/** Constructor.
* @param bodyFrame central body rotating frame
* @param maxOrderMdailyTesseralSP maximal order to consider for short periodics m-daily tesseral harmonics potential
* @param mDailiesOnly flag to take into account only M-dailies harmonic tesserals for short periodic perturbations
* @param nonResOrders lst of non resonant orders with j != 0
* @param mMax maximum value for m index
* @param jMax maximum value for j index
* @param interpolationPoints number of points used in the interpolation process
*/
TesseralShortPeriodicCoefficients(final Frame bodyFrame, final int maxOrderMdailyTesseralSP,
final boolean mDailiesOnly, final SortedMap<Integer, List<Integer> > nonResOrders,
final int mMax, final int jMax, final int interpolationPoints) {
this.bodyFrame = bodyFrame;
this.maxOrderMdailyTesseralSP = maxOrderMdailyTesseralSP;
this.mDailiesOnly = mDailiesOnly;
this.nonResOrders = nonResOrders;
this.mMax = mMax;
this.jMax = jMax;
this.interpolationPoints = interpolationPoints;
this.slots = new TimeSpanMap<Slot>(new Slot(mMax, jMax, interpolationPoints));
}
/** Get the slot valid for some date.
* @param meanStates mean states defining the slot
* @return slot valid at the specified date
*/
public Slot createSlot(final SpacecraftState ... meanStates) {
final Slot slot = new Slot(mMax, jMax, interpolationPoints);
final AbsoluteDate first = meanStates[0].getDate();
final AbsoluteDate last = meanStates[meanStates.length - 1].getDate();
if (first.compareTo(last) <= 0) {
slots.addValidAfter(slot, first);
} else {
slots.addValidBefore(slot, first);
}
return slot;
}
/** {@inheritDoc} */
@Override
public double[] value(final Orbit meanOrbit) throws OrekitException {
// select the coefficients slot
final Slot slot = slots.get(meanOrbit.getDate());
// Initialise the short periodic variations
final double[] shortPeriodicVariation = new double[6];
// Compute only if there is at least one non-resonant tesseral or
// only the m-daily tesseral should be taken into account
if (!nonResOrders.isEmpty() || mDailiesOnly) {
//Build an auxiliary object
final AuxiliaryElements aux = new AuxiliaryElements(meanOrbit, I);
// Central body rotation angle from equation 2.7.1-(3)(4).
final Transform t = bodyFrame.getTransformTo(aux.getFrame(), aux.getDate());
final Vector3D xB = t.transformVector(Vector3D.PLUS_I);
final Vector3D yB = t.transformVector(Vector3D.PLUS_J);
final Vector3D f = aux.getVectorF();
final Vector3D g = aux.getVectorG();
final double currentTheta = FastMath.atan2(-f.dotProduct(yB) + I * g.dotProduct(xB),
f.dotProduct(xB) + I * g.dotProduct(yB));
//Add the m-daily contribution
for (int m = 1; m <= maxOrderMdailyTesseralSP; m++) {
// Phase angle
final double jlMmt = -m * currentTheta;
final double sinPhi = FastMath.sin(jlMmt);
final double cosPhi = FastMath.cos(jlMmt);
// compute contribution for each element
final double[] c = slot.getCijm(0, m, meanOrbit.getDate());
final double[] s = slot.getSijm(0, m, meanOrbit.getDate());
for (int i = 0; i < 6; i++) {
shortPeriodicVariation[i] += c[i] * cosPhi + s[i] * sinPhi;
}
}
// loop through all non-resonant (j,m) pairs
for (final Map.Entry<Integer, List<Integer>> entry : nonResOrders.entrySet()) {
final int m = entry.getKey();
final List<Integer> listJ = entry.getValue();
for (int j : listJ) {
// Phase angle
final double jlMmt = j * meanOrbit.getLM() - m * currentTheta;
final double sinPhi = FastMath.sin(jlMmt);
final double cosPhi = FastMath.cos(jlMmt);
// compute contribution for each element
final double[] c = slot.getCijm(j, m, meanOrbit.getDate());
final double[] s = slot.getSijm(j, m, meanOrbit.getDate());
for (int i = 0; i < 6; i++) {
shortPeriodicVariation[i] += c[i] * cosPhi + s[i] * sinPhi;
}
}
}
}
return shortPeriodicVariation;
}
/** {@inheritDoc} */
@Override
public String getCoefficientsKeyPrefix() {
return "DSST-central-body-tesseral-";
}
/** {@inheritDoc}
* <p>
* For tesseral terms contributions,there are maxOrderMdailyTesseralSP
* m-daily cMm coefficients, maxOrderMdailyTesseralSP m-daily sMm
* coefficients, nbNonResonant cjm coefficients and nbNonResonant
* sjm coefficients, where maxOrderMdailyTesseralSP and nbNonResonant both
* depend on the orbit. The j index is the integer multiplier for the true
* longitude argument and the m index is the integer multiplier for m-dailies.
* </p>
*/
@Override
public Map<String, double[]> getCoefficients(final AbsoluteDate date, final Set<String> selected)
throws OrekitException {
// select the coefficients slot
final Slot slot = slots.get(date);
if (!nonResOrders.isEmpty() || mDailiesOnly) {
final Map<String, double[]> coefficients =
new HashMap<String, double[]>(12 * maxOrderMdailyTesseralSP +
12 * nonResOrders.size());
for (int m = 1; m <= maxOrderMdailyTesseralSP; m++) {
storeIfSelected(coefficients, selected, slot.getCijm(0, m, date), "cM", m);
storeIfSelected(coefficients, selected, slot.getSijm(0, m, date), "sM", m);
}
for (final Map.Entry<Integer, List<Integer>> entry : nonResOrders.entrySet()) {
final int m = entry.getKey();
final List<Integer> listJ = entry.getValue();
for (int j : listJ) {
for (int i = 0; i < 6; ++i) {
storeIfSelected(coefficients, selected, slot.getCijm(j, m, date), "c", j, m);
storeIfSelected(coefficients, selected, slot.getSijm(j, m, date), "s", j, m);
}
}
}
return coefficients;
} else {
return Collections.emptyMap();
}
}
/** Put a coefficient in a map if selected.
* @param map map to populate
* @param selected set of coefficients that should be put in the map
* (empty set means all coefficients are selected)
* @param value coefficient value
* @param id coefficient identifier
* @param indices list of coefficient indices
*/
private void storeIfSelected(final Map<String, double[]> map, final Set<String> selected,
final double[] value, final String id, final int ... indices) {
final StringBuilder keyBuilder = new StringBuilder(getCoefficientsKeyPrefix());
keyBuilder.append(id);
for (int index : indices) {
keyBuilder.append('[').append(index).append(']');
}
final String key = keyBuilder.toString();
if (selected.isEmpty() || selected.contains(key)) {
map.put(key, value);
}
}
}
/** Coefficients valid for one time slot. */
private static class Slot {
/** The coefficients C<sub>i</sub><sup>j</sup><sup>m</sup>.
* <p>
* The index order is cijm[m][j][i] <br/>
* i corresponds to the equinoctial element, as follows: <br/>
* - i=0 for a <br/>
* - i=1 for k <br/>
* - i=2 for h <br/>
* - i=3 for q <br/>
* - i=4 for p <br/>
* - i=5 for λ <br/>
* </p>
*/
private final ShortPeriodicsInterpolatedCoefficient[][] cijm;
/** The coefficients S<sub>i</sub><sup>j</sup><sup>m</sup>.
* <p>
* The index order is sijm[m][j][i] <br/>
* i corresponds to the equinoctial element, as follows: <br/>
* - i=0 for a <br/>
* - i=1 for k <br/>
* - i=2 for h <br/>
* - i=3 for q <br/>
* - i=4 for p <br/>
* - i=5 for λ <br/>
* </p>
*/
private final ShortPeriodicsInterpolatedCoefficient[][] sijm;
/** Simple constructor.
* @param mMax maximum value for m index
* @param jMax maximum value for j index
* @param interpolationPoints number of points used in the interpolation process
*/
Slot(final int mMax, final int jMax, final int interpolationPoints) {
final int rows = mMax + 1;
final int columns = 2 * jMax + 1;
cijm = new ShortPeriodicsInterpolatedCoefficient[rows][columns];
sijm = new ShortPeriodicsInterpolatedCoefficient[rows][columns];
for (int m = 1; m <= mMax; m++) {
for (int j = -jMax; j <= jMax; j++) {
cijm[m][j + jMax] = new ShortPeriodicsInterpolatedCoefficient(interpolationPoints);
sijm[m][j + jMax] = new ShortPeriodicsInterpolatedCoefficient(interpolationPoints);
}
}
}
/** Get C<sub>i</sub><sup>j</sup><sup>m</sup>.
*
* @param j j index
* @param m m index
* @param date the date
* @return C<sub>i</sub><sup>j</sup><sup>m</sup>
*/
double[] getCijm(final int j, final int m, final AbsoluteDate date) {
final int jMax = (cijm[m].length - 1) / 2;
return cijm[m][j + jMax].value(date);
}
/** Get S<sub>i</sub><sup>j</sup><sup>m</sup>.
*
* @param j j index
* @param m m index
* @param date the date
* @return S<sub>i</sub><sup>j</sup><sup>m</sup>
*/
double[] getSijm(final int j, final int m, final AbsoluteDate date) {
final int jMax = (cijm[m].length - 1) / 2;
return sijm[m][j + jMax].value(date);
}
}
}
| Fixed inefficient iterator. | src/main/java/org/orekit/propagation/semianalytical/dsst/forces/TesseralContribution.java | Fixed inefficient iterator. | <ide><path>rc/main/java/org/orekit/propagation/semianalytical/dsst/forces/TesseralContribution.java
<ide>
<ide> if (!mDailiesOnly) {
<ide> // generate the other coefficients, if required
<del> for (int m: nonResOrders.keySet()) {
<del> final List<Integer> listJ = nonResOrders.get(m);
<del>
<del> for (int j: listJ) {
<add> for (final Map.Entry<Integer, List<Integer>> entry : nonResOrders.entrySet()) {
<add>
<add> for (int j : entry.getValue()) {
<ide> // build the coefficients
<del> buildCoefficients(meanState.getDate(), slot, m, j, tnota);
<add> buildCoefficients(meanState.getDate(), slot, entry.getKey(), j, tnota);
<ide> }
<ide> }
<ide> } |
|
Java | apache-2.0 | 4466defb3168739bfc31229a91f6e2380104ceea | 0 | CMPUT301W15T06/Project,CMPUT301W15T06/Project | /*
UA CMPUT 301 Project Group: CMPUT301W15T06
Copyright {2015} {Jingjiao Ni
Tianqi Xiao
Jiafeng Wu
Xinyi Pan
Xinyi Wu
Han Wang}
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>ClaimantClaimDetailActivity</code> class is an extended class
* of <code>Activity</code> class. This class will control the interface
* of <code>Claim</code> detail for claimant. This view displays
* <code>Claim</code> details, and creates an option menu, including claimant's
* name, travel begin and end date, destination. It will be used when the claimant
* asks to access to the <code>Claim</code> detail. The associated class including
* <code>Claim</code> and <code>Destination</code>.
*
* @author CMPUT301W15T06
* @version 03/16/2015
* @see java.util.ArrayList
* @see android.os.Bundle
* @see android.app.Activity
* @see android.content.Intent
* @see android.view.Menu
* @see android.view.View
* @see android.widget.ArrayAdapter
* @see android.widget.EditText
* @see android.widget.ListView
* @see android.widget.TextView
*/
package ca.ualberta.CMPUT301W15T06;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
public class ClaimantClaimDetailActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_claimant_add_destination);
TextView nameView= (TextView) findViewById(R.id.nameValueClaimantClaimDetailTextView);
TextView beginView=(TextView) findViewById(R.id.startDateValueClaimantClaimDetailTextView);
TextView endView=(TextView) findViewById(R.id.endingDateValueClaimantClaimDetailTextView);
nameView.setText(AppSingleton.getInstance().getCurrentClaim().getName());
beginView.setText(AppSingleton.formatDate(AppSingleton.getInstance().getCurrentClaim().getBeginDate()));
endView.setText(AppSingleton.formatDate(AppSingleton.getInstance().getCurrentClaim().getEndDate()));
ListView listView = (ListView) findViewById(R.id.claimantDetailListView);
ArrayList<Destination> list =AppSingleton.getInstance().getCurrentClaim().getDestinationList();
final ArrayAdapter<Destination> adapter=new ArrayAdapter<Destination>(this, android.R.layout.simple_list_item_1,list);
listView.setAdapter(adapter);
Listener l=new Listener() {
@Override
public void update() {
adapter.notifyDataSetChanged();
}
};
AppSingleton.getInstance().getCurrentClaim().addListener(l);
for (Destination dest:AppSingleton.getInstance().getCurrentClaim().getDestinationList()){
dest.addListener(l);
};
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.claimant_add_destination, menu);
return true;
}
/**
* Set up a addDestination view. This method will be called when the
* claimant wants to add a new <code>Destination</code> to a current
* <code>Claim</code>.
*
* @param v a View object
* @see android.view.View
* @see android.content.Intent
*/
public void addDestination(View v){
Intent intent =new Intent(ClaimantClaimDetailActivity.this,ClaimantAddDestinationActivity.class);
startActivity(intent);
}
}
| App/src/ca/ualberta/CMPUT301W15T06/ClaimantClaimDetailActivity.java | /*
UA CMPUT 301 Project Group: CMPUT301W15T06
Copyright {2015} {Jingjiao Ni
Tianqi Xiao
Jiafeng Wu
Xinyi Pan
Xinyi Wu
Han Wang}
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 ca.ualberta.CMPUT301W15T06;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
public class ClaimantClaimDetailActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_claimant_add_destination);
TextView nameView= (TextView) findViewById(R.id.nameValueClaimantClaimDetailTextView);
TextView beginView=(TextView) findViewById(R.id.startDateValueClaimantClaimDetailTextView);
TextView endView=(TextView) findViewById(R.id.endingDateValueClaimantClaimDetailTextView);
nameView.setText(AppSingleton.getInstance().getCurrentClaim().getName());
beginView.setText(AppSingleton.formatDate(AppSingleton.getInstance().getCurrentClaim().getBeginDate()));
endView.setText(AppSingleton.formatDate(AppSingleton.getInstance().getCurrentClaim().getEndDate()));
ListView listView = (ListView) findViewById(R.id.claimantDetailListView);
ArrayList<Destination> list =AppSingleton.getInstance().getCurrentClaim().getDestinationList();
final ArrayAdapter<Destination> adapter=new ArrayAdapter<Destination>(this, android.R.layout.simple_list_item_1,list);
listView.setAdapter(adapter);
Listener l=new Listener() {
@Override
public void update() {
adapter.notifyDataSetChanged();
}
};
AppSingleton.getInstance().getCurrentClaim().addListener(l);
for (Destination dest:AppSingleton.getInstance().getCurrentClaim().getDestinationList()){
dest.addListener(l);
};
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.claimant_add_destination, menu);
return true;
}
public void addDestination(View v){
Intent intent =new Intent(ClaimantClaimDetailActivity.this,ClaimantAddDestinationActivity.class);
startActivity(intent);
}
}
| Update ClaimantClaimDetailActivity.java | App/src/ca/ualberta/CMPUT301W15T06/ClaimantClaimDetailActivity.java | Update ClaimantClaimDetailActivity.java | <ide><path>pp/src/ca/ualberta/CMPUT301W15T06/ClaimantClaimDetailActivity.java
<ide> ANY KIND, either express or implied. See the License for the specific language
<ide> governing permissions and limitations under the License.
<ide>
<add> */
<add>
<add> /**
<add> * This <code>ClaimantClaimDetailActivity</code> class is an extended class
<add> * of <code>Activity</code> class. This class will control the interface
<add> * of <code>Claim</code> detail for claimant. This view displays
<add> * <code>Claim</code> details, and creates an option menu, including claimant's
<add> * name, travel begin and end date, destination. It will be used when the claimant
<add> * asks to access to the <code>Claim</code> detail. The associated class including
<add> * <code>Claim</code> and <code>Destination</code>.
<add> *
<add> * @author CMPUT301W15T06
<add> * @version 03/16/2015
<add> * @see java.util.ArrayList
<add> * @see android.os.Bundle
<add> * @see android.app.Activity
<add> * @see android.content.Intent
<add> * @see android.view.Menu
<add> * @see android.view.View
<add> * @see android.widget.ArrayAdapter
<add> * @see android.widget.EditText
<add> * @see android.widget.ListView
<add> * @see android.widget.TextView
<ide> */
<ide> package ca.ualberta.CMPUT301W15T06;
<ide>
<ide> return true;
<ide> }
<ide>
<del>
<del>
<add> /**
<add> * Set up a addDestination view. This method will be called when the
<add> * claimant wants to add a new <code>Destination</code> to a current
<add> * <code>Claim</code>.
<add> *
<add> * @param v a View object
<add> * @see android.view.View
<add> * @see android.content.Intent
<add> */
<ide> public void addDestination(View v){
<ide> Intent intent =new Intent(ClaimantClaimDetailActivity.this,ClaimantAddDestinationActivity.class);
<ide> startActivity(intent); |
|
Java | agpl-3.0 | f3197e7ce910abbda5abb7de347d7554e5d04382 | 0 | duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test | 0a99d5b0-2e61-11e5-9284-b827eb9e62be | hello.java | 0a946828-2e61-11e5-9284-b827eb9e62be | 0a99d5b0-2e61-11e5-9284-b827eb9e62be | hello.java | 0a99d5b0-2e61-11e5-9284-b827eb9e62be | <ide><path>ello.java
<del>0a946828-2e61-11e5-9284-b827eb9e62be
<add>0a99d5b0-2e61-11e5-9284-b827eb9e62be |
|
JavaScript | mit | 4844c74e09d17e190d5a282bc9d38188dec513aa | 0 | lyrictenor/electron-triage-for-github,lyrictenor/electron-triage-for-github | #!/usr/bin/env node
/* eslint-disable no-console */
import yargs from 'yargs';
import spawn from 'buffered-spawn';
import path from 'path';
import rimraf from 'rimraf';
import packager from 'electron-packager';
import { productName, electronVersion } from '../package.json';
const outputPath = path.join(process.cwd(), 'output');
const packagerOptions = {
dir: path.join(process.cwd(), 'dist'),
name: productName,
version: electronVersion,
out: outputPath,
platform: 'all',
arch: 'all',
asar: true,
};
const argv = yargs.default(packagerOptions).argv;
const env = Object.assign({}, process.env, { NODE_ENV: 'production' });
console.log(`Pack electron ${electronVersion}`);
spawn('npm', ['run', 'build:dist'], { stdio: 'inherit', env: env })
.then(() => {
return new Promise((resolve, reject) => {
rimraf(outputPath, (error) => {
if (error) {
reject(error);
return;
}
resolve();
});
});
}).then(() => {
return new Promise((resolve, reject) => {
packager({
dir: argv.dir,
name: argv.name,
version: argv.version,
out: argv.out,
platform: argv.platform,
arch: argv.arch,
asar: argv.asar,
}, (err, appPath) => {
if (err) {
reject(err);
return;
}
resolve(appPath);
});
});
}).catch((error) => {
console.error(error);
process.exit(1);
});
| bin/electron-build.js | #!/usr/bin/env node
/* eslint-disable no-console */
import yargs from 'yargs';
import spawn from 'buffered-spawn';
import path from 'path';
import rimraf from 'rimraf';
import packager from 'electron-packager';
import { productName, electronVersion } from '../package.json';
const outputPath = path.join(process.cwd(), 'output');
const packagerOptions = {
dir: path.join(process.cwd(), 'dist'),
name: productName,
version: electronVersion,
out: outputPath,
platform: 'all',
arch: 'all',
};
const argv = yargs.default(packagerOptions).argv;
const env = Object.assign({}, process.env, { NODE_ENV: 'production' });
console.log(`Pack electron ${electronVersion}`);
spawn('npm', ['run', 'build:dist'], { stdio: 'inherit', env: env })
.then(() => {
return new Promise((resolve, reject) => {
rimraf(outputPath, (error) => {
if (error) {
reject(error);
return;
}
resolve();
});
});
}).then(() => {
return new Promise((resolve, reject) => {
packager({
dir: argv.dir,
name: argv.name,
version: argv.version,
out: argv.out,
platform: argv.platform,
arch: argv.arch,
}, (err, appPath) => {
if (err) {
reject(err);
return;
}
resolve(appPath);
});
});
}).catch((error) => {
console.error(error);
process.exit(1);
});
| chore(build): add asar
| bin/electron-build.js | chore(build): add asar | <ide><path>in/electron-build.js
<ide> out: outputPath,
<ide> platform: 'all',
<ide> arch: 'all',
<add> asar: true,
<ide> };
<ide> const argv = yargs.default(packagerOptions).argv;
<ide> const env = Object.assign({}, process.env, { NODE_ENV: 'production' });
<ide> out: argv.out,
<ide> platform: argv.platform,
<ide> arch: argv.arch,
<add> asar: argv.asar,
<ide> }, (err, appPath) => {
<ide> if (err) {
<ide> reject(err); |
|
Java | apache-2.0 | 8bd500f085ca6240f50c418acdbff9b843ce7eaf | 0 | ngageoint/mage-android,ngageoint/mage-android | package mil.nga.giat.mage.map.marker;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import mil.nga.giat.mage.sdk.R;
import mil.nga.giat.mage.sdk.connectivity.ConnectivityUtility;
import mil.nga.giat.mage.sdk.datastore.location.Location;
import mil.nga.giat.mage.sdk.datastore.user.User;
import mil.nga.giat.mage.sdk.datastore.user.UserHelper;
import mil.nga.giat.mage.sdk.preferences.PreferenceHelper;
import mil.nga.giat.mage.sdk.utils.MediaUtility;
import org.apache.commons.lang3.StringUtils;
import android.animation.ArgbEvaluator;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.LightingColorFilter;
import android.graphics.Paint;
import android.os.AsyncTask;
import android.os.Build;
import android.util.Log;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.Marker;
public class LocationBitmapFactory {
private static Long upperBoundTimeInSeconds = 1800L;
// TODO : SCOTT UFM
private static final Integer[] colorGradient = { 0xff0000ff, 0xffffff00 ,0xffffa500 };
// blue, yellow, orange
/*private static final Integer[] colorGradient = { 0xff0000ff, 0xff0000ff, 0xff0000ff, 0xff0807f8, 0xff0f10ef, 0xff1817e7, 0xff1f1fdf, 0xff2728d7, 0xff3030d0, 0xff3737c8, 0xff3f40bf, 0xff4847b7, 0xff4f4fb0, 0xff5757a7, 0xff5f5fa0, 0xff676797, 0xff706f8f, 0xff777787, 0xff7f7f7f, 0xff878878,
0xff8f9070, 0xff989767, 0xff9f9f60, 0xffa7a758, 0xffafb050, 0xffb8b848, 0xffbfbf40, 0xffc7c738, 0xffcfcf30, 0xffd8d828, 0xffdfe020, 0xffe7e718, 0xffefef10, 0xfff7f708, 0xffffff00, 0xffffff00, 0xfffffc00, 0xfffffa00, 0xfffff600, 0xfffff400, 0xfffff100, 0xffffee00, 0xffffeb00, 0xffffe800,
0xffffe600, 0xffffe300, 0xffffe100, 0xffffdd00, 0xffffdb00, 0xffffd700, 0xffffd500, 0xffffd200, 0xffffcf00, 0xffffcd00, 0xffffca00, 0xffffc700, 0xffffc400, 0xffffc100, 0xffffbf00, 0xffffbc00, 0xffffb900, 0xffffb600, 0xffffb300, 0xffffb000, 0xffffad00, 0xffffaa00, 0xffffa500 };*/
// hsv spectrum
private static final Integer[] colorGradient1 = { 0xff0000ff, 0xff0a00ff, 0xff1500ff, 0xff1f00ff, 0xff2a00ff, 0xff3500ff, 0xff3f00ff, 0xff4a00ff, 0xff5400ff, 0xff5f00ff, 0xff6900ff, 0xff7400ff, 0xff7e00ff, 0xff8900ff, 0xff9300ff, 0xff9e00ff, 0xffa800ff, 0xffb300ff, 0xffbe00ff, 0xffc800ff,
0xffd300ff, 0xffdd00ff, 0xffe800ff, 0xfff200ff, 0xfffc00ff, 0xffff00f6, 0xffff00ec, 0xffff00e1, 0xffff00d7, 0xffff00cc, 0xffff00c2, 0xffff00b7, 0xffff00ad, 0xffff00a2, 0xffff0098, 0xffff008d, 0xffff0083, 0xffff0078, 0xffff006d, 0xffff0063, 0xffff0058, 0xffff004e, 0xffff0044, 0xffff0039,
0xffff002e, 0xffff0023, 0xffff0019, 0xffff000e, 0xffff0004, 0xffff0700, 0xffff1100, 0xffff1b00, 0xffff2700, 0xffff3100, 0xffff3c00, 0xffff4600, 0xffff5100, 0xffff5b00, 0xffff6600, 0xffff7000, 0xffff7b00, 0xffff8500, 0xffff9000, 0xffff9a00, 0xffffa500 };
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static Bitmap bitmap(Context context, Location location, User user, Marker m) {
Bitmap finalBitmap = null;
Bitmap dotBitmap = createDot(context, location, user);
if (user.getLocalIconPath() != null) {
File f = new File(user.getLocalIconPath());
Bitmap combined = combineIconAndDot(dotBitmap.copy(Bitmap.Config.ARGB_8888, true), BitmapFactory.decodeFile(user.getLocalIconPath()));
m.setIcon(BitmapDescriptorFactory.fromBitmap(combined));
} else if (user.getIconUrl() != null) {
// if there is supposed to be an icon but we don't have it, go get it
if (ConnectivityUtility.isOnline(context)) {
String token = PreferenceHelper.getInstance(context).getValue(R.string.tokenKey);
new DownloadImageTask(dotBitmap.copy(Bitmap.Config.ARGB_8888, true), m, user, context).execute(user.getIconUrl() + "?access_token=" + token);
}
} else {
finalBitmap = dotBitmap;
m.setIcon(BitmapDescriptorFactory.fromBitmap(finalBitmap));
}
return finalBitmap;
}
private static Bitmap combineIconAndDot(Bitmap dot, Bitmap icon) {
Bitmap combined = Bitmap.createBitmap(96, 127, Config.ARGB_8888);
Canvas c = new Canvas(combined);
c.drawBitmap(dot, (96-dot.getWidth())/2, 95, null);
Bitmap roundedProfile = MediaUtility.resizeAndRoundCorners(icon, 96);
c.drawBitmap(roundedProfile, (96-roundedProfile.getWidth())/2, 0, null);
return combined;
}
private static class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
Marker marker;
Bitmap dotBitmap;
User user;
Context context;
public DownloadImageTask(Bitmap dotBitmap, Marker m, User user, Context context) {
this.marker = m;
this.dotBitmap = dotBitmap;
this.user = user;
this.context = context;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap icon = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
icon = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return icon;
}
protected void onPostExecute(Bitmap icon) {
FileOutputStream out = null;
try {
String localPath = MediaUtility.getUserIconDirectory() + "/" + user.getId();
out = new FileOutputStream(localPath);
icon.compress(Bitmap.CompressFormat.PNG, 90, out);
user.setLocalIconPath(localPath);
UserHelper.getInstance(context).update(user);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Bitmap combined = combineIconAndDot(dotBitmap.copy(Bitmap.Config.ARGB_8888, true), icon.copy(Bitmap.Config.ARGB_8888, true));;
if (marker != null) {
marker.setIcon(BitmapDescriptorFactory.fromBitmap(combined));
}
}
}
public static BitmapDescriptor bitmapDescriptor(Context context, Location location, User user, Marker m) {
Bitmap bitmap = bitmap(context, location, user, m);
return BitmapDescriptorFactory.fromBitmap(bitmap);
}
public static BitmapDescriptor dotBitmapDescriptor(Context context, Location location, User user) {
Bitmap bitmap = createDot(context, location, user);
return BitmapDescriptorFactory.fromBitmap(bitmap);
}
public static Bitmap createDot(Context context, Location location, User user) {
Bitmap dotBitmap = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inDensity = 480;
options.inTargetDensity = context.getResources().getDisplayMetrics().densityDpi;
try {
Long interval = (System.currentTimeMillis() - location.getTimestamp().getTime()) / 1000l;
// max out at 30 minutes
interval = Math.min(interval, upperBoundTimeInSeconds);
// upper bound in minutes
Double u = upperBoundTimeInSeconds.doubleValue() / 60.0;
// non-linear lookup
// 0 mins = blue
// 10 mins = yellow
// 30 mins = orange
Double gradientIndexDecimalNormalized = -0.25 + Math.sqrt((u * u) + (u * 24 * (interval.doubleValue() / 60.0))) / (4 * u);
// between 0 and 1
gradientIndexDecimalNormalized = Math.min(Math.max(0.0, gradientIndexDecimalNormalized), 1.0);
// find the index into the gradient
int gradientIndex = (int) (gradientIndexDecimalNormalized * (double) (colorGradient.length - 1));
// linearly interpolate between the gradient index
Integer COLOR1 = colorGradient[gradientIndex];
Integer COLOR2 = colorGradient[Math.min(gradientIndex + 1, colorGradient.length - 1)];
// TODO : SCOTT UFM
int color = (Integer) new ArgbEvaluator().evaluate(gradientIndexDecimalNormalized.floatValue(), COLOR1, COLOR1);
// use a invert filter to swap black and white colors in the bitmap. This will preserve the original black
float[] colorMatrix_Negative = { -1.0f, 0, 0, 0, 255, 0, -1.0f, 0, 0, 255, 0, 0, -1.0f, 0, 255, 0, 0, 0, 1.0f, 0 };
// make a mutable copy of the bitmap
Bitmap bitmapFile = BitmapFactory.decodeStream(context.getAssets().open("dots/black_dot.png"), null, options);
dotBitmap = bitmapFile.copy(Bitmap.Config.ARGB_8888, true);
Canvas myCanvas = new Canvas(dotBitmap);
// invert the gradient first
Paint gradientPaint = new Paint();
gradientPaint.setColorFilter(new LightingColorFilter(Color.WHITE, 0xFFFFFFFF - color));
myCanvas.drawBitmap(dotBitmap, 0, 0, gradientPaint);
// invert the entire image second
Paint negativePaint = new Paint();
negativePaint.setColorFilter(new ColorMatrixColorFilter(new ColorMatrix(colorMatrix_Negative)));
myCanvas.drawBitmap(dotBitmap, 0, 0, negativePaint);
} catch (IOException e1) {
try {
dotBitmap = BitmapFactory.decodeStream(context.getAssets().open("dots/maps_dav_bw_dot.png"), null, options);
} catch (IOException e2) {
}
}
return dotBitmap;
}
/**
* @deprecated No long using hard coded assets.
*
* @param location
* @return
*/
private static String getAsset(Location location) {
if (location == null) {
return null;
}
Collection<String> paths = new ArrayList<String>();
paths.add("people");
Long interval = System.currentTimeMillis() - location.getTimestamp().getTime();
if (interval < 600000) { // 10 minutes
paths.add("low");
} else if (interval < 1800000) { // 30 minutes
paths.add("medium");
} else {
paths.add("high");
}
paths.add("person");
return StringUtils.join(paths, "/") + ".png";
}
} | src/mil/nga/giat/mage/map/marker/LocationBitmapFactory.java | package mil.nga.giat.mage.map.marker;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import mil.nga.giat.mage.sdk.R;
import mil.nga.giat.mage.sdk.connectivity.ConnectivityUtility;
import mil.nga.giat.mage.sdk.datastore.location.Location;
import mil.nga.giat.mage.sdk.datastore.user.User;
import mil.nga.giat.mage.sdk.datastore.user.UserHelper;
import mil.nga.giat.mage.sdk.preferences.PreferenceHelper;
import mil.nga.giat.mage.sdk.utils.MediaUtility;
import org.apache.commons.lang3.StringUtils;
import android.animation.ArgbEvaluator;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.LightingColorFilter;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.AsyncTask;
import android.os.Build;
import android.util.Log;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.Marker;
public class LocationBitmapFactory {
private static Long upperBoundTimeInSeconds = 1800L;
// TODO : SCOTT UFM
private static final Integer[] colorGradient = { 0xff0000ff, 0xffffff00 ,0xffffa500 };
// blue, yellow, orange
/*private static final Integer[] colorGradient = { 0xff0000ff, 0xff0000ff, 0xff0000ff, 0xff0807f8, 0xff0f10ef, 0xff1817e7, 0xff1f1fdf, 0xff2728d7, 0xff3030d0, 0xff3737c8, 0xff3f40bf, 0xff4847b7, 0xff4f4fb0, 0xff5757a7, 0xff5f5fa0, 0xff676797, 0xff706f8f, 0xff777787, 0xff7f7f7f, 0xff878878,
0xff8f9070, 0xff989767, 0xff9f9f60, 0xffa7a758, 0xffafb050, 0xffb8b848, 0xffbfbf40, 0xffc7c738, 0xffcfcf30, 0xffd8d828, 0xffdfe020, 0xffe7e718, 0xffefef10, 0xfff7f708, 0xffffff00, 0xffffff00, 0xfffffc00, 0xfffffa00, 0xfffff600, 0xfffff400, 0xfffff100, 0xffffee00, 0xffffeb00, 0xffffe800,
0xffffe600, 0xffffe300, 0xffffe100, 0xffffdd00, 0xffffdb00, 0xffffd700, 0xffffd500, 0xffffd200, 0xffffcf00, 0xffffcd00, 0xffffca00, 0xffffc700, 0xffffc400, 0xffffc100, 0xffffbf00, 0xffffbc00, 0xffffb900, 0xffffb600, 0xffffb300, 0xffffb000, 0xffffad00, 0xffffaa00, 0xffffa500 };*/
// hsv spectrum
private static final Integer[] colorGradient1 = { 0xff0000ff, 0xff0a00ff, 0xff1500ff, 0xff1f00ff, 0xff2a00ff, 0xff3500ff, 0xff3f00ff, 0xff4a00ff, 0xff5400ff, 0xff5f00ff, 0xff6900ff, 0xff7400ff, 0xff7e00ff, 0xff8900ff, 0xff9300ff, 0xff9e00ff, 0xffa800ff, 0xffb300ff, 0xffbe00ff, 0xffc800ff,
0xffd300ff, 0xffdd00ff, 0xffe800ff, 0xfff200ff, 0xfffc00ff, 0xffff00f6, 0xffff00ec, 0xffff00e1, 0xffff00d7, 0xffff00cc, 0xffff00c2, 0xffff00b7, 0xffff00ad, 0xffff00a2, 0xffff0098, 0xffff008d, 0xffff0083, 0xffff0078, 0xffff006d, 0xffff0063, 0xffff0058, 0xffff004e, 0xffff0044, 0xffff0039,
0xffff002e, 0xffff0023, 0xffff0019, 0xffff000e, 0xffff0004, 0xffff0700, 0xffff1100, 0xffff1b00, 0xffff2700, 0xffff3100, 0xffff3c00, 0xffff4600, 0xffff5100, 0xffff5b00, 0xffff6600, 0xffff7000, 0xffff7b00, 0xffff8500, 0xffff9000, 0xffff9a00, 0xffffa500 };
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static Bitmap bitmap(Context context, Location location, User user, Marker m) {
Bitmap finalBitmap = null;
Bitmap dotBitmap = createDot(context, location, user);
if (user.getLocalIconPath() != null) {
Log.d("LocationBitmapFactory", "Using the locally stored icon file " + user.getLocalIconPath());
File f = new File(user.getLocalIconPath());
Bitmap combined = combineIconAndDot(dotBitmap.copy(Bitmap.Config.ARGB_8888, true), BitmapFactory.decodeFile(user.getLocalIconPath()));
m.setIcon(BitmapDescriptorFactory.fromBitmap(combined));
} else if (user.getIconUrl() != null) {
// if there is supposed to be an icon but we don't have it, go get it
if (ConnectivityUtility.isOnline(context)) {
String token = PreferenceHelper.getInstance(context).getValue(R.string.tokenKey);
new DownloadImageTask(dotBitmap.copy(Bitmap.Config.ARGB_8888, true), m, user, context).execute(user.getIconUrl() + "?access_token=" + token);
}
} else {
Log.d("LocationBitmapFactory", "icon for user " + user.getUsername() + " is null");
finalBitmap = dotBitmap;
m.setIcon(BitmapDescriptorFactory.fromBitmap(finalBitmap));
}
return finalBitmap;
}
private static Bitmap combineIconAndDot(Bitmap dot, Bitmap icon) {
Bitmap combined = Bitmap.createBitmap(96, 127, Config.ARGB_8888);
Canvas c = new Canvas(combined);
c.drawBitmap(dot, (96-dot.getWidth())/2, 95, null);
Bitmap roundedProfile = MediaUtility.resizeAndRoundCorners(icon, 96);
c.drawBitmap(roundedProfile, (96-roundedProfile.getWidth())/2, 0, null);
return combined;
}
private static class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
Marker marker;
Bitmap dotBitmap;
User user;
Context context;
public DownloadImageTask(Bitmap dotBitmap, Marker m, User user, Context context) {
this.marker = m;
this.dotBitmap = dotBitmap;
this.user = user;
this.context = context;
}
protected Bitmap doInBackground(String... urls) {
Log.d("downloader", "Downloading " + urls[0]);
String urldisplay = urls[0];
Bitmap icon = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
icon = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return icon;
}
protected void onPostExecute(Bitmap icon) {
FileOutputStream out = null;
try {
String localPath = MediaUtility.getUserIconDirectory() + "/" + user.getId();
out = new FileOutputStream(localPath);
icon.compress(Bitmap.CompressFormat.PNG, 90, out);
user.setLocalIconPath(localPath);
UserHelper.getInstance(context).update(user);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Bitmap combined = combineIconAndDot(dotBitmap.copy(Bitmap.Config.ARGB_8888, true), icon.copy(Bitmap.Config.ARGB_8888, true));;
if (marker != null) {
marker.setIcon(BitmapDescriptorFactory.fromBitmap(combined));
}
}
}
public static BitmapDescriptor bitmapDescriptor(Context context, Location location, User user, Marker m) {
Bitmap bitmap = bitmap(context, location, user, m);
return BitmapDescriptorFactory.fromBitmap(bitmap);
}
public static BitmapDescriptor dotBitmapDescriptor(Context context, Location location, User user) {
Bitmap bitmap = createDot(context, location, user);
return BitmapDescriptorFactory.fromBitmap(bitmap);
}
public static Bitmap createDot(Context context, Location location, User user) {
Bitmap dotBitmap = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inDensity = 480;
options.inTargetDensity = context.getResources().getDisplayMetrics().densityDpi;
try {
Long interval = (System.currentTimeMillis() - location.getTimestamp().getTime()) / 1000l;
// max out at 30 minutes
interval = Math.min(interval, upperBoundTimeInSeconds);
// upper bound in minutes
Double u = upperBoundTimeInSeconds.doubleValue() / 60.0;
// non-linear lookup
// 0 mins = blue
// 10 mins = yellow
// 30 mins = orange
Double gradientIndexDecimalNormalized = -0.25 + Math.sqrt((u * u) + (u * 24 * (interval.doubleValue() / 60.0))) / (4 * u);
// between 0 and 1
gradientIndexDecimalNormalized = Math.min(Math.max(0.0, gradientIndexDecimalNormalized), 1.0);
// find the index into the gradient
int gradientIndex = (int) (gradientIndexDecimalNormalized * (double) (colorGradient.length - 1));
// linearly interpolate between the gradient index
Integer COLOR1 = colorGradient[gradientIndex];
Integer COLOR2 = colorGradient[Math.min(gradientIndex + 1, colorGradient.length - 1)];
// TODO : SCOTT UFM
int color = (Integer) new ArgbEvaluator().evaluate(gradientIndexDecimalNormalized.floatValue(), COLOR1, COLOR1);
// use a invert filter to swap black and white colors in the bitmap. This will preserve the original black
float[] colorMatrix_Negative = { -1.0f, 0, 0, 0, 255, 0, -1.0f, 0, 0, 255, 0, 0, -1.0f, 0, 255, 0, 0, 0, 1.0f, 0 };
// make a mutable copy of the bitmap
Bitmap bitmapFile = BitmapFactory.decodeStream(context.getAssets().open("dots/black_dot.png"), null, options);
dotBitmap = bitmapFile.copy(Bitmap.Config.ARGB_8888, true);
Canvas myCanvas = new Canvas(dotBitmap);
// invert the gradient first
Paint gradientPaint = new Paint();
gradientPaint.setColorFilter(new LightingColorFilter(Color.WHITE, 0xFFFFFFFF - color));
myCanvas.drawBitmap(dotBitmap, 0, 0, gradientPaint);
// invert the entire image second
Paint negativePaint = new Paint();
negativePaint.setColorFilter(new ColorMatrixColorFilter(new ColorMatrix(colorMatrix_Negative)));
myCanvas.drawBitmap(dotBitmap, 0, 0, negativePaint);
} catch (IOException e1) {
try {
dotBitmap = BitmapFactory.decodeStream(context.getAssets().open("dots/maps_dav_bw_dot.png"), null, options);
} catch (IOException e2) {
}
}
return dotBitmap;
}
/**
* @deprecated No long using hard coded assets.
*
* @param location
* @return
*/
private static String getAsset(Location location) {
if (location == null) {
return null;
}
Collection<String> paths = new ArrayList<String>();
paths.add("people");
Long interval = System.currentTimeMillis() - location.getTimestamp().getTime();
if (interval < 600000) { // 10 minutes
paths.add("low");
} else if (interval < 1800000) { // 30 minutes
paths.add("medium");
} else {
paths.add("high");
}
paths.add("person");
return StringUtils.join(paths, "/") + ".png";
}
} | removed logging
| src/mil/nga/giat/mage/map/marker/LocationBitmapFactory.java | removed logging | <ide><path>rc/mil/nga/giat/mage/map/marker/LocationBitmapFactory.java
<ide> import android.graphics.ColorMatrixColorFilter;
<ide> import android.graphics.LightingColorFilter;
<ide> import android.graphics.Paint;
<del>import android.graphics.PorterDuff.Mode;
<del>import android.graphics.PorterDuffXfermode;
<del>import android.graphics.Rect;
<del>import android.graphics.RectF;
<ide> import android.os.AsyncTask;
<ide> import android.os.Build;
<ide> import android.util.Log;
<ide> Bitmap dotBitmap = createDot(context, location, user);
<ide>
<ide> if (user.getLocalIconPath() != null) {
<del> Log.d("LocationBitmapFactory", "Using the locally stored icon file " + user.getLocalIconPath());
<ide> File f = new File(user.getLocalIconPath());
<ide> Bitmap combined = combineIconAndDot(dotBitmap.copy(Bitmap.Config.ARGB_8888, true), BitmapFactory.decodeFile(user.getLocalIconPath()));
<ide> m.setIcon(BitmapDescriptorFactory.fromBitmap(combined));
<ide> new DownloadImageTask(dotBitmap.copy(Bitmap.Config.ARGB_8888, true), m, user, context).execute(user.getIconUrl() + "?access_token=" + token);
<ide> }
<ide> } else {
<del> Log.d("LocationBitmapFactory", "icon for user " + user.getUsername() + " is null");
<ide> finalBitmap = dotBitmap;
<ide> m.setIcon(BitmapDescriptorFactory.fromBitmap(finalBitmap));
<ide> }
<ide> }
<ide>
<ide> protected Bitmap doInBackground(String... urls) {
<del> Log.d("downloader", "Downloading " + urls[0]);
<ide> String urldisplay = urls[0];
<ide> Bitmap icon = null;
<ide> try { |
|
Java | lgpl-2.1 | 9d6f6f379fb282df0339fd584c6a40a151dd26ba | 0 | deegree/deegree3,deegree/deegree3,deegree/deegree3,deegree/deegree3,deegree/deegree3 | //$HeadURL$
/*----------------------------------------------------------------------------
This file is part of deegree, http://deegree.org/
Copyright (C) 2001-2009 by:
- Department of Geography, University of Bonn -
and
- lat/lon GmbH -
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free
Software Foundation; either version 2.1 of the License, or (at your option)
any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact information:
lat/lon GmbH
Aennchenstr. 19, 53177 Bonn
Germany
http://lat-lon.de/
Department of Geography, University of Bonn
Prof. Dr. Klaus Greve
Postfach 1147, 53001 Bonn
Germany
http://www.geographie.uni-bonn.de/deegree/
e-mail: [email protected]
----------------------------------------------------------------------------*/
package org.deegree.metadata.persistence.iso.parsing.inspectation;
import static org.slf4j.LoggerFactory.getLogger;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import javax.xml.namespace.QName;
import org.apache.axiom.om.OMElement;
import org.deegree.commons.xml.NamespaceBindings;
import org.deegree.commons.xml.XMLAdapter;
import org.deegree.commons.xml.XPath;
import org.deegree.metadata.i18n.Messages;
import org.deegree.metadata.persistence.MetadataInspectorException;
import org.deegree.metadata.persistence.iso.generating.generatingelements.GenerateOMElement;
import org.deegree.metadata.persistence.iso.parsing.IdUtils;
import org.deegree.metadata.persistence.iso19115.jaxb.FileIdentifierInspector;
import org.slf4j.Logger;
/**
* Inspects whether the fileIdentifier should be set when inserting a metadata or not and what consequences should
* occur.
*
* @author <a href="mailto:[email protected]">Steffen Thomas</a>
* @author last edited by: $Author$
*
* @version $Revision$, $Date$
*/
public class FIInspector implements RecordInspector {
private static final Logger LOG = getLogger( FIInspector.class );
private Connection conn;
private final XMLAdapter a;
private final FileIdentifierInspector config;
public FIInspector( FileIdentifierInspector inspector ) {
this.config = inspector;
this.a = new XMLAdapter();
}
/**
*
* @param fi
* the fileIdentifier that should be determined for one metadata, can be <Code>null</Code>.
* @param rsList
* the list of resourceIdentifier, not <Code>null</Code>.
* @param id
* the id-attribute, can be <Code>null<Code>.
* @param uuid
* the uuid-attribure, can be <Code>null</Code>.
* @return the new fileIdentifier.
*/
private List<String> determineFileIdentifier( String[] fi, List<String> rsList, String id, String uuid )
throws MetadataInspectorException {
List<String> idList = new ArrayList<String>();
if ( fi.length != 0 ) {
for ( String f : fi ) {
LOG.info( Messages.getMessage( "INFO_FI_AVAILABLE", f.trim() ) );
idList.add( f.trim() );
}
return idList;
}
if ( config != null && !config.isRejectEmpty() ) {
if ( rsList.size() == 0 && id == null && uuid == null ) {
LOG.debug( Messages.getMessage( "INFO_FI_GENERATE_NEW" ) );
idList.add( IdUtils.newInstance( conn ).generateUUID() );
LOG.debug( Messages.getMessage( "INFO_FI_NEW", idList ) );
} else {
if ( rsList.size() == 0 && id != null ) {
LOG.debug( Messages.getMessage( "INFO_FI_DEFAULT_ID", id ) );
idList.add( id );
} else if ( rsList.size() == 0 && uuid != null ) {
LOG.debug( Messages.getMessage( "INFO_FI_DEFAULT_UUID", uuid ) );
idList.add( uuid );
} else {
LOG.debug( Messages.getMessage( "INFO_FI_DEFAULT_RSID", rsList.get( 0 ) ) );
idList.add( rsList.get( 0 ) );
}
}
return idList;
}
if ( rsList.size() == 0 ) {
String msg = Messages.getMessage( "ERROR_REJECT_FI" );
LOG.debug( msg );
throw new MetadataInspectorException( msg );
}
LOG.debug( Messages.getMessage( "INFO_FI_DEFAULT_RSID", rsList.get( 0 ) ) );
idList.add( rsList.get( 0 ) );
return idList;
}
@Override
public OMElement inspect( OMElement record, Connection conn )
throws MetadataInspectorException {
this.conn = conn;
a.setRootElement( record );
NamespaceBindings nsContext = a.getNamespaceContext( record );
// NamespaceContext newNSC = generateNSC(nsContext);
nsContext.addNamespace( "srv", "http://www.isotc211.org/2005/srv" );
nsContext.addNamespace( "gmd", "http://www.isotc211.org/2005/gmd" );
nsContext.addNamespace( "gco", "http://www.isotc211.org/2005/gco" );
// String GMD_PRE = "gmd";
String[] fileIdentifierString = a.getNodesAsStrings( record,
new XPath( "./gmd:fileIdentifier/gco:CharacterString",
nsContext ) );
OMElement sv_service_OR_md_dataIdentification = a.getElement(
record,
new XPath(
"./gmd:identificationInfo/srv:SV_ServiceIdentification | ./gmd:identificationInfo/gmd:MD_DataIdentification",
nsContext ) );
String dataIdentificationId = sv_service_OR_md_dataIdentification.getAttributeValue( new QName( "id" ) );
String dataIdentificationUuId = sv_service_OR_md_dataIdentification.getAttributeValue( new QName( "uuid" ) );
List<OMElement> identifier = a.getElements( sv_service_OR_md_dataIdentification,
new XPath( "./gmd:citation/gmd:CI_Citation/gmd:identifier",
nsContext ) );
List<String> resourceIdentifierList = new ArrayList<String>();
for ( OMElement resourceElement : identifier ) {
String resourceIdentifier = a.getNodeAsString(
resourceElement,
new XPath(
"./gmd:MD_Identifier/gmd:code/gco:CharacterString | ./gmd:RS_Identifier/gmd:code/gco:CharacterString",
nsContext ), null );
LOG.debug( "resourceIdentifier: '" + resourceIdentifier + "' " );
resourceIdentifierList.add( resourceIdentifier );
}
List<String> idList = determineFileIdentifier( fileIdentifierString, resourceIdentifierList,
dataIdentificationId, dataIdentificationUuId );
// if ( idList.isEmpty() ) {
// return null;
// }
if ( !idList.isEmpty() && fileIdentifierString.length == 0 ) {
for ( String id : idList ) {
OMElement firstElement = record.getFirstElement();
firstElement.insertSiblingBefore( GenerateOMElement.newInstance().createFileIdentifierElement( id ) );
}
}
return record;
}
}
| deegree-core/deegree-core-metadata/src/main/java/org/deegree/metadata/persistence/iso/parsing/inspectation/FIInspector.java | //$HeadURL$
/*----------------------------------------------------------------------------
This file is part of deegree, http://deegree.org/
Copyright (C) 2001-2009 by:
- Department of Geography, University of Bonn -
and
- lat/lon GmbH -
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free
Software Foundation; either version 2.1 of the License, or (at your option)
any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact information:
lat/lon GmbH
Aennchenstr. 19, 53177 Bonn
Germany
http://lat-lon.de/
Department of Geography, University of Bonn
Prof. Dr. Klaus Greve
Postfach 1147, 53001 Bonn
Germany
http://www.geographie.uni-bonn.de/deegree/
e-mail: [email protected]
----------------------------------------------------------------------------*/
package org.deegree.metadata.persistence.iso.parsing.inspectation;
import static org.slf4j.LoggerFactory.getLogger;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import javax.xml.namespace.QName;
import org.apache.axiom.om.OMElement;
import org.deegree.commons.xml.NamespaceBindings;
import org.deegree.commons.xml.XMLAdapter;
import org.deegree.commons.xml.XPath;
import org.deegree.metadata.i18n.Messages;
import org.deegree.metadata.persistence.MetadataInspectorException;
import org.deegree.metadata.persistence.iso.generating.generatingelements.GenerateOMElement;
import org.deegree.metadata.persistence.iso.parsing.IdUtils;
import org.deegree.metadata.persistence.iso19115.jaxb.FileIdentifierInspector;
import org.deegree.protocol.csw.MetadataStoreException;
import org.slf4j.Logger;
/**
* Inspects whether the fileIdentifier should be set when inserting a metadata or not and what consequences should
* occur.
*
* @author <a href="mailto:[email protected]">Steffen Thomas</a>
* @author last edited by: $Author$
*
* @version $Revision$, $Date$
*/
public class FIInspector implements RecordInspector {
private static final Logger LOG = getLogger( FIInspector.class );
private Connection conn;
private final XMLAdapter a;
private final FileIdentifierInspector config;
public FIInspector( FileIdentifierInspector inspector ) {
this.config = inspector;
this.a = new XMLAdapter();
}
/**
*
* @param fi
* the fileIdentifier that should be determined for one metadata, can be <Code>null</Code>.
* @param rsList
* the list of resourceIdentifier, not <Code>null</Code>.
* @param id
* the id-attribute, can be <Code>null<Code>.
* @param uuid
* the uuid-attribure, can be <Code>null</Code>.
* @param isFileIdentifierExistenceDesired
* true, if the existence of the fileIdentifier is desired in backend.
* @return the new fileIdentifier.
* @throws MetadataStoreException
*/
private List<String> determineFileIdentifier( String[] fi, List<String> rsList, String id, String uuid )
throws MetadataInspectorException {
List<String> idList = new ArrayList<String>();
if ( fi.length != 0 ) {
for ( String f : fi ) {
LOG.info( Messages.getMessage( "INFO_FI_AVAILABLE", f ) );
idList.add( f );
}
return idList;
} else {
if ( config != null && !config.isRejectEmpty() ) {
if ( rsList.size() == 0 && id == null && uuid == null ) {
LOG.debug( Messages.getMessage( "INFO_FI_GENERATE_NEW" ) );
idList.add( IdUtils.newInstance( conn ).generateUUID() );
LOG.debug( Messages.getMessage( "INFO_FI_NEW", idList ) );
} else {
if ( rsList.size() == 0 && id != null ) {
LOG.debug( Messages.getMessage( "INFO_FI_DEFAULT_ID", id ) );
idList.add( id );
} else if ( rsList.size() == 0 && uuid != null ) {
LOG.debug( Messages.getMessage( "INFO_FI_DEFAULT_UUID", uuid ) );
idList.add( uuid );
} else {
LOG.debug( Messages.getMessage( "INFO_FI_DEFAULT_RSID", rsList.get( 0 ) ) );
idList.add( rsList.get( 0 ) );
}
}
return idList;
} else {
if ( rsList.size() == 0 ) {
String msg = Messages.getMessage( "ERROR_REJECT_FI" );
LOG.debug( msg );
throw new MetadataInspectorException( msg );
} else {
LOG.debug( Messages.getMessage( "INFO_FI_DEFAULT_RSID", rsList.get( 0 ) ) );
idList.add( rsList.get( 0 ) );
return idList;
}
}
}
}
@Override
public OMElement inspect( OMElement record, Connection conn )
throws MetadataInspectorException {
this.conn = conn;
a.setRootElement( record );
NamespaceBindings nsContext = a.getNamespaceContext( record );
// NamespaceContext newNSC = generateNSC(nsContext);
nsContext.addNamespace( "srv", "http://www.isotc211.org/2005/srv" );
nsContext.addNamespace( "gmd", "http://www.isotc211.org/2005/gmd" );
nsContext.addNamespace( "gco", "http://www.isotc211.org/2005/gco" );
// String GMD_PRE = "gmd";
String[] fileIdentifierString = a.getNodesAsStrings( record,
new XPath( "./gmd:fileIdentifier/gco:CharacterString",
nsContext ) );
OMElement sv_service_OR_md_dataIdentification = a.getElement( record,
new XPath(
"./gmd:identificationInfo/srv:SV_ServiceIdentification | ./gmd:identificationInfo/gmd:MD_DataIdentification",
nsContext ) );
String dataIdentificationId = sv_service_OR_md_dataIdentification.getAttributeValue( new QName( "id" ) );
String dataIdentificationUuId = sv_service_OR_md_dataIdentification.getAttributeValue( new QName( "uuid" ) );
List<OMElement> identifier = a.getElements( sv_service_OR_md_dataIdentification,
new XPath( "./gmd:citation/gmd:CI_Citation/gmd:identifier",
nsContext ) );
List<String> resourceIdentifierList = new ArrayList<String>();
for ( OMElement resourceElement : identifier ) {
String resourceIdentifier = a.getNodeAsString( resourceElement,
new XPath(
"./gmd:MD_Identifier/gmd:code/gco:CharacterString | ./gmd:RS_Identifier/gmd:code/gco:CharacterString",
nsContext ), null );
LOG.debug( "resourceIdentifier: '" + resourceIdentifier + "' " );
resourceIdentifierList.add( resourceIdentifier );
}
List<String> idList = determineFileIdentifier( fileIdentifierString, resourceIdentifierList,
dataIdentificationId, dataIdentificationUuId );
// if ( idList.isEmpty() ) {
// return null;
// }
if ( !idList.isEmpty() && fileIdentifierString.length == 0 ) {
for ( String id : idList ) {
OMElement firstElement = record.getFirstElement();
firstElement.insertSiblingBefore( GenerateOMElement.newInstance().createFileIdentifierElement( id ) );
}
}
return record;
}
}
| cleanup, trim file identifiers
| deegree-core/deegree-core-metadata/src/main/java/org/deegree/metadata/persistence/iso/parsing/inspectation/FIInspector.java | cleanup, trim file identifiers | <ide><path>eegree-core/deegree-core-metadata/src/main/java/org/deegree/metadata/persistence/iso/parsing/inspectation/FIInspector.java
<ide> import org.deegree.metadata.persistence.iso.generating.generatingelements.GenerateOMElement;
<ide> import org.deegree.metadata.persistence.iso.parsing.IdUtils;
<ide> import org.deegree.metadata.persistence.iso19115.jaxb.FileIdentifierInspector;
<del>import org.deegree.protocol.csw.MetadataStoreException;
<ide> import org.slf4j.Logger;
<ide>
<ide> /**
<ide> * the id-attribute, can be <Code>null<Code>.
<ide> * @param uuid
<ide> * the uuid-attribure, can be <Code>null</Code>.
<del> * @param isFileIdentifierExistenceDesired
<del> * true, if the existence of the fileIdentifier is desired in backend.
<ide> * @return the new fileIdentifier.
<del> * @throws MetadataStoreException
<ide> */
<ide> private List<String> determineFileIdentifier( String[] fi, List<String> rsList, String id, String uuid )
<ide> throws MetadataInspectorException {
<ide> List<String> idList = new ArrayList<String>();
<ide> if ( fi.length != 0 ) {
<ide> for ( String f : fi ) {
<del> LOG.info( Messages.getMessage( "INFO_FI_AVAILABLE", f ) );
<del> idList.add( f );
<add> LOG.info( Messages.getMessage( "INFO_FI_AVAILABLE", f.trim() ) );
<add> idList.add( f.trim() );
<ide> }
<ide> return idList;
<del> } else {
<del> if ( config != null && !config.isRejectEmpty() ) {
<del> if ( rsList.size() == 0 && id == null && uuid == null ) {
<add> }
<add> if ( config != null && !config.isRejectEmpty() ) {
<add> if ( rsList.size() == 0 && id == null && uuid == null ) {
<ide>
<del> LOG.debug( Messages.getMessage( "INFO_FI_GENERATE_NEW" ) );
<del> idList.add( IdUtils.newInstance( conn ).generateUUID() );
<del> LOG.debug( Messages.getMessage( "INFO_FI_NEW", idList ) );
<del> } else {
<del> if ( rsList.size() == 0 && id != null ) {
<del> LOG.debug( Messages.getMessage( "INFO_FI_DEFAULT_ID", id ) );
<del> idList.add( id );
<del> } else if ( rsList.size() == 0 && uuid != null ) {
<del> LOG.debug( Messages.getMessage( "INFO_FI_DEFAULT_UUID", uuid ) );
<del> idList.add( uuid );
<del> } else {
<del> LOG.debug( Messages.getMessage( "INFO_FI_DEFAULT_RSID", rsList.get( 0 ) ) );
<del> idList.add( rsList.get( 0 ) );
<del> }
<del> }
<del> return idList;
<add> LOG.debug( Messages.getMessage( "INFO_FI_GENERATE_NEW" ) );
<add> idList.add( IdUtils.newInstance( conn ).generateUUID() );
<add> LOG.debug( Messages.getMessage( "INFO_FI_NEW", idList ) );
<ide> } else {
<del> if ( rsList.size() == 0 ) {
<del> String msg = Messages.getMessage( "ERROR_REJECT_FI" );
<del> LOG.debug( msg );
<del> throw new MetadataInspectorException( msg );
<add> if ( rsList.size() == 0 && id != null ) {
<add> LOG.debug( Messages.getMessage( "INFO_FI_DEFAULT_ID", id ) );
<add> idList.add( id );
<add> } else if ( rsList.size() == 0 && uuid != null ) {
<add> LOG.debug( Messages.getMessage( "INFO_FI_DEFAULT_UUID", uuid ) );
<add> idList.add( uuid );
<ide> } else {
<ide> LOG.debug( Messages.getMessage( "INFO_FI_DEFAULT_RSID", rsList.get( 0 ) ) );
<ide> idList.add( rsList.get( 0 ) );
<del> return idList;
<ide> }
<ide> }
<del>
<add> return idList;
<ide> }
<add> if ( rsList.size() == 0 ) {
<add> String msg = Messages.getMessage( "ERROR_REJECT_FI" );
<add> LOG.debug( msg );
<add> throw new MetadataInspectorException( msg );
<add> }
<add> LOG.debug( Messages.getMessage( "INFO_FI_DEFAULT_RSID", rsList.get( 0 ) ) );
<add> idList.add( rsList.get( 0 ) );
<add> return idList;
<ide>
<ide> }
<ide>
<ide> new XPath( "./gmd:fileIdentifier/gco:CharacterString",
<ide> nsContext ) );
<ide>
<del> OMElement sv_service_OR_md_dataIdentification = a.getElement( record,
<add> OMElement sv_service_OR_md_dataIdentification = a.getElement(
<add> record,
<ide> new XPath(
<ide> "./gmd:identificationInfo/srv:SV_ServiceIdentification | ./gmd:identificationInfo/gmd:MD_DataIdentification",
<ide> nsContext ) );
<ide> nsContext ) );
<ide> List<String> resourceIdentifierList = new ArrayList<String>();
<ide> for ( OMElement resourceElement : identifier ) {
<del> String resourceIdentifier = a.getNodeAsString( resourceElement,
<add> String resourceIdentifier = a.getNodeAsString(
<add> resourceElement,
<ide> new XPath(
<ide> "./gmd:MD_Identifier/gmd:code/gco:CharacterString | ./gmd:RS_Identifier/gmd:code/gco:CharacterString",
<ide> nsContext ), null ); |
|
Java | mpl-2.0 | 8369cadda6ee6372939aa633ca92a6c2bbc6836f | 0 | deanhiller/databus,deanhiller/databus,deanhiller/databus,deanhiller/databus,deanhiller/databus,deanhiller/databus,deanhiller/databus | package controllers.modules2;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import controllers.modules2.framework.ReadResult;
import controllers.modules2.framework.TSRelational;
import controllers.modules2.framework.VisitorInfo;
import controllers.modules2.framework.procs.ProcessorSetup;
import controllers.modules2.framework.procs.StreamsProcessor;
public class AggregationProcessor extends StreamsProcessor {
//map of url to it's mapped column name:
private LinkedHashMap<String, String> entryNames = new LinkedHashMap<String, String>();
private boolean dropIncomplete = true;
private int lookaheadSize = 10;
private boolean lookaheadSatisfied = false;
private int largestRowWidth = -1;
private List<ReadResult> lookaheadBuffer;
@Override
public String init(String path, ProcessorSetup nextInChain,
VisitorInfo visitor, HashMap<String, String> options) {
String res = super.init(path, nextInChain, visitor, options);
for (String url:urls) {
String entryName = getRawDataSource(url);
if (entryNames.containsValue(entryName)) {
Set<Entry<String, String>> entries = entryNames.entrySet();
for (Entry<String, String> entry:entries) {
if (entry.getValue() != null && entry.getValue().equals(entryName)) {
String origEntry = entry.getKey();
entryNames.remove(origEntry);
entryNames.put(origEntry, origEntry);
entryNames.put(url, url);
break;
}
}
}
else
entryNames.put(url, entryName);
}
String dropIncompleteStr = options.get("dropIncomplete");
if (StringUtils.isNotBlank(dropIncompleteStr))
dropIncomplete = Boolean.parseBoolean(dropIncompleteStr);
String lookaheadSizeStr = options.get("lookaheadSize");
if (StringUtils.isNotBlank(lookaheadSizeStr))
lookaheadSize = Integer.parseInt(lookaheadSizeStr);
return res;
}
@Override
protected ReadResult process(List<TSRelational> rows) {
Long timeCompare = null;
BigDecimal total = BigDecimal.ZERO;
TSRelational ts = new TSRelational();
int index = 0;
for(TSRelational row : rows) {
if(row == null)
continue;
Long time = getTime(row);
if(timeCompare == null) {
timeCompare = time;
} else if(!timeCompare.equals(time)) {
throw new IllegalStateException("It appears you did not run spline before summing the streams as times are not lining up. t1="+time+" t2="+timeCompare);
}
BigDecimal val = getValueEvenIfNull(row);
if(val != null) {
total = total.add(val);
}
ts.put(entryNames.get(urls.get(index++)), val);
}
if(timeCompare == null) {
return new ReadResult();
}
setTime(ts, timeCompare);
setValue(ts, total);
ReadResult res = new ReadResult(null, ts);
return res;
}
private int getLargestRowWidth(List<ReadResult> rows) {
int result = 0;
for (ReadResult r : rows)
result = Math.max(result, r.getRow().size());
return result;
}
@Override
public ReadResult read() {
if (!dropIncomplete)
return super.read();
else {
if (!lookaheadSatisfied) {
lookaheadBuffer = new ArrayList<ReadResult>();
ReadResult r = super.read();
while (lookaheadBuffer.size() <= lookaheadSize && r != null && !r.isEndOfStream()) {
lookaheadBuffer.add(r);
r = super.read();
}
lookaheadBuffer.add(r);
lookaheadSatisfied = true;
}
if (largestRowWidth < 0)
largestRowWidth = getLargestRowWidth(lookaheadBuffer);
while (CollectionUtils.size(lookaheadBuffer)!=0) {
ReadResult RRreturn = lookaheadBuffer.get(0);
lookaheadBuffer.remove(0);
if (RRreturn != null && RRreturn.getRow() != null && RRreturn.isEndOfStream() && RRreturn.getRow().size() >=largestRowWidth)
return RRreturn;
}
ReadResult r = super.read();
while (r != null && r.getRow() != null && !r.isEndOfStream() && r.getRow().size() <largestRowWidth)
r=super.read();
return r;
}
}
private String getRawDataSource(String url) {
String apparentRawdata = StringUtils.substring(url, StringUtils.lastIndexOf(url, "/")+1);
if (!StringUtils.isEmpty(apparentRawdata) && !StringUtils.contains(apparentRawdata, "/"))
return apparentRawdata;
return url;
}
}
| webapp/app/controllers/modules2/AggregationProcessor.java | package controllers.modules2;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import controllers.modules2.framework.ReadResult;
import controllers.modules2.framework.TSRelational;
import controllers.modules2.framework.VisitorInfo;
import controllers.modules2.framework.procs.ProcessorSetup;
import controllers.modules2.framework.procs.StreamsProcessor;
public class AggregationProcessor extends StreamsProcessor {
//map of url to it's mapped column name:
private LinkedHashMap<String, String> entryNames = new LinkedHashMap<String, String>();
private boolean dropIncomplete = true;
private int lookaheadSize = 10;
private boolean lookaheadSatisfied = false;
private int largestRowWidth = -1;
private List<ReadResult> lookaheadBuffer;
@Override
public String init(String path, ProcessorSetup nextInChain,
VisitorInfo visitor, HashMap<String, String> options) {
String res = super.init(path, nextInChain, visitor, options);
for (String url:urls) {
String entryName = getRawDataSource(url);
if (entryNames.containsValue(entryName)) {
Set<Entry<String, String>> entries = entryNames.entrySet();
for (Entry<String, String> entry:entries) {
if (entry.getValue() != null && entry.getValue().equals(entryName)) {
String origEntry = entry.getKey();
entryNames.remove(origEntry);
entryNames.put(origEntry, origEntry);
entryNames.put(url, url);
break;
}
}
}
else
entryNames.put(url, entryName);
}
String dropIncompleteStr = options.get("dropIncomplete");
if (StringUtils.isNotBlank(dropIncompleteStr))
dropIncomplete = Boolean.parseBoolean(dropIncompleteStr);
String lookaheadSizeStr = options.get("lookaheadSize");
if (StringUtils.isNotBlank(lookaheadSizeStr))
lookaheadSize = Integer.parseInt(lookaheadSizeStr);
return res;
}
@Override
protected ReadResult process(List<TSRelational> rows) {
Long timeCompare = null;
BigDecimal total = BigDecimal.ZERO;
TSRelational ts = new TSRelational();
int index = 0;
for(TSRelational row : rows) {
if(row == null)
continue;
Long time = getTime(row);
if(timeCompare == null) {
timeCompare = time;
} else if(!timeCompare.equals(time)) {
throw new IllegalStateException("It appears you did not run spline before summing the streams as times are not lining up. t1="+time+" t2="+timeCompare);
}
BigDecimal val = getValueEvenIfNull(row);
if(val != null) {
total = total.add(val);
}
ts.put(entryNames.get(urls.get(index++)), val);
}
if(timeCompare == null) {
return new ReadResult();
}
setTime(ts, timeCompare);
setValue(ts, total);
ReadResult res = new ReadResult(null, ts);
return res;
}
private int getLargestRowWidth(List<ReadResult> rows) {
int result = 0;
for (ReadResult r : rows)
result = Math.max(result, r.getRow().size());
return result;
}
@Override
public ReadResult read() {
if (!dropIncomplete)
return super.read();
else {
if (!lookaheadSatisfied) {
lookaheadBuffer = new ArrayList<ReadResult>();
ReadResult r = super.read();
while (lookaheadBuffer.size() <= lookaheadSize && r != null && !r.isEndOfStream()) {
lookaheadBuffer.add(r);
r = super.read();
}
lookaheadBuffer.add(r);
lookaheadSatisfied = true;
}
if (largestRowWidth < 0)
largestRowWidth = getLargestRowWidth(lookaheadBuffer);
while (CollectionUtils.size(lookaheadBuffer)!=0) {
ReadResult RRreturn = lookaheadBuffer.get(0);
lookaheadBuffer.remove(0);
if (RRreturn != null && RRreturn.getRow() != null && RRreturn.isEndOfStream() && RRreturn.getRow().size() >=largestRowWidth)
return RRreturn;
}
ReadResult r = super.read();
while (r != null && r.getRow() != null && r.isEndOfStream() && r.getRow().size() >=largestRowWidth)
r=super.read();
return r;
}
}
private String getRawDataSource(String url) {
String apparentRawdata = StringUtils.substring(url, StringUtils.lastIndexOf(url, "/")+1);
if (!StringUtils.isEmpty(apparentRawdata) && !StringUtils.contains(apparentRawdata, "/"))
return apparentRawdata;
return url;
}
}
| fix for end of window on triggers... this isn't a long term fix, if a trigger runs too soon the after window is meaningless...
| webapp/app/controllers/modules2/AggregationProcessor.java | fix for end of window on triggers... this isn't a long term fix, if a trigger runs too soon the after window is meaningless... | <ide><path>ebapp/app/controllers/modules2/AggregationProcessor.java
<ide> return RRreturn;
<ide> }
<ide> ReadResult r = super.read();
<del> while (r != null && r.getRow() != null && r.isEndOfStream() && r.getRow().size() >=largestRowWidth)
<add> while (r != null && r.getRow() != null && !r.isEndOfStream() && r.getRow().size() <largestRowWidth)
<ide> r=super.read();
<ide> return r;
<ide> } |
|
Java | lgpl-2.1 | c8b652651bb032d1e3c7989c683dbc35134d5e41 | 0 | julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine | package org.intermine.api.profile;
/*
* Copyright (C) 2002-2011 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.functors.ConstantTransformer;
import org.apache.log4j.Logger;
import org.intermine.api.bag.IncompatibleTypesException;
import org.intermine.api.bag.UnknownBagTypeException;
import org.intermine.api.search.WebSearchable;
import org.intermine.metadata.ClassDescriptor;
import org.intermine.metadata.Model;
import org.intermine.model.userprofile.SavedBag;
import org.intermine.model.userprofile.UserProfile;
import org.intermine.objectstore.ObjectStore;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.objectstore.ObjectStoreWriter;
import org.intermine.objectstore.intermine.ObjectStoreInterMineImpl;
import org.intermine.objectstore.intermine.ObjectStoreWriterInterMineImpl;
import org.intermine.objectstore.proxy.ProxyReference;
import org.intermine.objectstore.query.BagConstraint;
import org.intermine.objectstore.query.ConstraintOp;
import org.intermine.objectstore.query.ObjectStoreBag;
import org.intermine.objectstore.query.Query;
import org.intermine.objectstore.query.QueryClass;
import org.intermine.objectstore.query.QueryField;
import org.intermine.objectstore.query.Results;
import org.intermine.objectstore.query.ResultsRow;
import org.intermine.objectstore.query.SingletonResults;
import org.intermine.sql.DatabaseUtil;
import org.intermine.sql.writebatch.Batch;
import org.intermine.sql.writebatch.BatchWriterPostgresCopyImpl;
import org.intermine.util.TypeUtil;
/**
* An object that represents a bag of objects in our database for the webapp. It is backed by an
* ObjectStoreBag object, but contains extra data such as name and description.
*
* @author Kim Rutherford
* @author Matthew Wakeling
*/
public class InterMineBag implements WebSearchable, Cloneable
{
protected static final Logger LOG = Logger.getLogger(InterMineBag.class);
public static final String BAG_VALUES = "bagvalues";
private Integer profileId;
private Integer savedBagId;
private String name;
protected final String type;
private String description;
private Date dateCreated;
private List<String> keyFieldNames = new ArrayList<String>();
private boolean isCurrent;
private ObjectStoreBag osb;
private ObjectStore os;
private ObjectStoreWriter uosw;
private Set<ClassDescriptor> classDescriptors;
/**
* Constructs a new InterMineIdBag, and saves it in the UserProfile database.
*
* @param name the name of the bag
* @param type the class of objects stored in the bag
* @param description the description of the bag
* @param dateCreated the Date when this bag was created
* @param isCurrent the status of this bag
* @param os the production ObjectStore
* @param profileId the ID of the user in the userprofile database
* @param uosw the ObjectStoreWriter of the userprofile database
* @throws ObjectStoreException if an error occurs
*/
public InterMineBag(String name, String type, String description, Date dateCreated,
boolean isCurrent, ObjectStore os, Integer profileId, ObjectStoreWriter uosw)
throws ObjectStoreException {
this.type = type;
init(name, description, dateCreated, isCurrent, os, profileId, uosw);
}
/**
* Constructs a new InterMineIdBag, and saves it in the UserProfile database.
*
* @param name the name of the bag
* @param type the class of objects stored in the bag
* @param description the description of the bag
* @param dateCreated the Date when this bag was created
* @param isCurrent the current state of the bag
* @param os the production ObjectStore
* @param profileId the ID of the user in the userprofile database
* @param uosw the ObjectStoreWriter of the userprofile database
* @param keyFieldNames the list of identifiers defined for this bag
* @throws ObjectStoreException if an error occurs
*/
public InterMineBag(String name, String type, String description, Date dateCreated,
boolean isCurrent, ObjectStore os, Integer profileId, ObjectStoreWriter uosw,
List<String> keyFieldNames) throws ObjectStoreException {
this.type = type;
init(name, description, dateCreated, isCurrent, os, profileId, uosw);
this.keyFieldNames = keyFieldNames;
}
private void init(String name, String description, Date dateCreated, boolean isCurrent,
ObjectStore os, Integer profileId, ObjectStoreWriter uosw) throws ObjectStoreException {
checkAndSetName(name);
this.description = description;
this.dateCreated = dateCreated;
this.isCurrent = isCurrent;
this.os = os;
this.profileId = profileId;
this.osb = os.createObjectStoreBag();
this.uosw = uosw;
this.savedBagId = null;
SavedBag savedBag = store();
this.savedBagId = savedBag.getId();
setClassDescriptors();
}
/**
* Loads an InterMineBag from the UserProfile database.
*
* @param os the production ObjectStore
* @param savedBagId the ID of the bag in the userprofile database
* @param uosw the ObjectStoreWriter of the userprofile database
* @throws ObjectStoreException if something goes wrong
*/
public InterMineBag(ObjectStore os, Integer savedBagId, ObjectStoreWriter uosw)
throws ObjectStoreException {
this.os = os;
this.uosw = uosw;
this.savedBagId = savedBagId;
ObjectStore uos = uosw.getObjectStore();
SavedBag savedBag = (SavedBag) uos.getObjectById(savedBagId, SavedBag.class);
checkAndSetName(savedBag.getName());
this.type = savedBag.getType();
this.description = savedBag.getDescription();
this.dateCreated = savedBag.getDateCreated();
this.profileId = savedBag.proxGetUserProfile().getId();
this.isCurrent = savedBag.getCurrent();
this.osb = new ObjectStoreBag(savedBag.getOsbId());
setClassDescriptors();
}
private void setClassDescriptors() {
try {
Class<?> cls = Class.forName(getQualifiedType());
classDescriptors = os.getModel().getClassDescriptorsForClass(cls);
} catch (ClassNotFoundException e) {
throw new UnknownBagTypeException("bag type " + getQualifiedType() + " not known", e);
}
}
private SavedBag store() throws ObjectStoreException {
SavedBag savedBag = new SavedBag();
savedBag.setId(savedBagId);
if (profileId != null) {
savedBag.setName(name);
savedBag.setType(type);
savedBag.setDescription(description);
savedBag.setDateCreated(dateCreated);
savedBag.proxyUserProfile(new ProxyReference(null, profileId, UserProfile.class));
savedBag.setOsbId(osb.getBagId());
savedBag.setCurrent(isCurrent);
uosw.store(savedBag);
}
return savedBag;
}
/**
* Delete this bag from the userprofile database, bag should not be used after this method has
* been called. Delete the ids from the production database too.
* @throws ObjectStoreException if problem deleting bag
*/
protected void delete() throws ObjectStoreException {
if (profileId != null) {
SavedBag savedBag = (SavedBag) uosw.getObjectStore().getObjectById(savedBagId,
SavedBag.class);
uosw.delete(savedBag);
removeIdsFromBag(getContentsAsIds(), false);
deleteAllBagValues();
this.profileId = null;
this.savedBagId = null;
}
}
/**
* Returns a List which contains the contents of this bag as Integer IDs.
*
* @return a List of Integers
*/
public List<Integer> getContentsAsIds() {
Query q = new Query();
q.addToSelect(osb);
q.setDistinct(false);
SingletonResults res = os.executeSingleton(q, 1000, false, true, true);
return ((List) res);
}
/**
* Returns a List of key field values of the objects contained by this bag.
* Removed any duplicates
* @return the list of key field values
*/
public List<String> getContentsASKeyFieldValues() {
List<String> keyFieldValueList = new ArrayList<String>();
if (isCurrent) {
Query q = new Query();
q.setDistinct(false);
try {
QueryClass qc = new QueryClass(Class.forName(getQualifiedType()));
q.addFrom(qc);
if (keyFieldNames.isEmpty()) {
throw new RuntimeException("set the keyFieldNames before calling "
+ "getContentsASKeyFieldValues method");
}
for (String keyFieldName : keyFieldNames) {
q.addToSelect(new QueryField(qc, keyFieldName));
}
QueryField idField = new QueryField(qc, "id");
BagConstraint c = new BagConstraint(idField, ConstraintOp.IN, osb);
q.setConstraint(c);
Results res = os.execute(q);
for (Object rowObj : res) {
ResultsRow<?> row = (ResultsRow<?>) rowObj;
String value;
for (int index = 0; index < keyFieldNames.size(); index++) {
value = (String) row.get(index);
if (value != null && !"".equals(value)) {
if (! keyFieldValueList.contains(value)) {
keyFieldValueList.add(value);
}
break;
}
}
}
return keyFieldValueList;
} catch (ClassNotFoundException cne) {
return new ArrayList<String>();
}
} else {
//we are upgrading bags, the osbag_int is empty, we need to use bagvalues table
Connection conn = null;
Statement stm = null;
ResultSet rs = null;
List<String> primaryIdentifiersList = new ArrayList<String>();
ObjectStoreInterMineImpl uos = null;
try {
uos = (ObjectStoreInterMineImpl) uosw.getObjectStore();
conn = uos.getConnection();
stm = conn.createStatement();
String sql = "SELECT value FROM " + BAG_VALUES + " WHERE savedbagid = "
+ savedBagId;
rs = stm.executeQuery(sql);
while (rs.next()) {
primaryIdentifiersList.add(rs.getString(1));
}
} catch (SQLException sqe) {
LOG.error("Connection problems during loadings primary identifiers fields for"
+ "the bag " + name, sqe);
} finally {
if (rs != null) {
try {
rs.close();
if (stm != null) {
stm.close();
}
} catch (SQLException sqle) {
LOG.error("Problems closing resources in the method "
+ "getContentsASPrimaryIdentifierValues for the bag " + name, sqle);
}
}
uos.releaseConnection(conn);
}
return primaryIdentifiersList;
}
}
/**
* Returns the values of the key field objects with id specified in input and contained in
* the bag. Removed any duplicates
* @param ids the collection of id
* @return the list of values
*/
@SuppressWarnings("unchecked")
public List<String> getKeyFieldValues(Collection<Integer> ids) {
List<String> keyFieldValueList = new ArrayList<String>();
Query q = new Query();
q.setDistinct(false);
if (keyFieldNames.isEmpty()) {
return Collections.EMPTY_LIST;
}
try {
QueryClass qc = new QueryClass(Class.forName(getQualifiedType()));
q.addFrom(qc);
for (String keyFieldName : keyFieldNames) {
q.addToSelect(new QueryField(qc, keyFieldName));
}
QueryField idField = new QueryField(qc, "id");
BagConstraint idsConstraints = new BagConstraint(idField, ConstraintOp.IN, ids);
q.setConstraint(idsConstraints);
Results res = os.execute(q, 1000, false, true, true);
for (Object rowObj : res) {
ResultsRow<?> row = (ResultsRow<?>) rowObj;
String value;
for (int index = 0; index < keyFieldNames.size(); index++) {
value = (String) row.get(index);
if (value != null && !"".equals(value)) {
if (! keyFieldValueList.contains(value)) {
keyFieldValueList.add(value);
}
break;
}
}
}
return keyFieldValueList;
} catch (ClassNotFoundException cne) {
return new ArrayList<String>();
}
}
/**
* Upgrades the ObjectStoreBag with a new ObjectStoreBag containing the collection of elements
* given in input
* @param values the collection of elements to add
* @param updateBagValues id true if we upgrade the bagvalues table
* @throws ObjectStoreException if an error occurs fetching a new ID
*/
public void upgradeOsb(Collection<Integer> values, boolean updateBagValues) throws ObjectStoreException {
ObjectStoreWriter oswProduction = null;
SavedBag savedBag = (SavedBag) uosw.getObjectById(savedBagId, SavedBag.class);
try {
oswProduction = os.getNewWriter();
osb = oswProduction.createObjectStoreBag();
oswProduction.addAllToBag(osb, values);
savedBag.setOsbId(osb.getBagId());
savedBag.setCurrent(true);
isCurrent = true;
uosw.store(savedBag);
if (updateBagValues) {
deleteAllBagValues();
addBagValues();
}
} finally {
if (oswProduction != null) {
oswProduction.close();
}
}
}
/**
* Returns the size of the bag.
*
* @return the number of elements in the bag
* @throws ObjectStoreException if something goes wrong
*/
public int size() throws ObjectStoreException {
Query q = new Query();
q.addToSelect(osb);
q.setDistinct(false);
return os.count(q, ObjectStore.SEQUENCE_IGNORE);
}
/**
* Getter for size, just to make JSP happy.
*
* @return the number of elements in the bag
* @throws ObjectStoreException if something goes wrong
*/
public int getSize() throws ObjectStoreException {
return size();
}
/**
* Returns the ObjectStoreBag, so that elements can be added and removed.
*
* @return the ObjectStoreBag
*/
public ObjectStoreBag getOsb() {
return osb;
}
/**
* Sets the ObjectStoreBag.
*
* @param osb the ObjectStoreBag
*/
public void setOsb(ObjectStoreBag osb) {
this.osb = osb;
}
/**
* Sets the profileId - moves this bag from one profile to another.
*
* @param profileId the ID of the new userprofile
* @throws ObjectStoreException if something goes wrong
*/
public void setProfileId(Integer profileId)
throws ObjectStoreException {
this.profileId = profileId;
SavedBag savedBag = store();
this.savedBagId = savedBag.getId();
isCurrent = savedBag.getCurrent();
addBagValues();
}
/**
* Save the bag into the userprofile database
*
* @param profileId the ID of the userprofile
* @param bagValues the list of the key field values of the objects contained by the bag
* @throws ObjectStoreException if something goes wrong
*/
public void saveWithBagValues(Integer profileId, Collection<String> bagValues)
throws ObjectStoreException {
this.profileId = profileId;
SavedBag savedBag = store();
this.savedBagId = savedBag.getId();
isCurrent = savedBag.getCurrent();
addBagValues(bagValues);
}
/**
* Returns the value of name
* @return the name of the bag
*/
@Override
public String getName() {
return name;
}
/**
* Set the value of name
* @param name the bag name
* @throws ObjectStoreException if something goes wrong
*/
public void setName(String name) throws ObjectStoreException {
checkAndSetName(name);
store();
}
// Always set the name via this method to avoid saving bags with blank names
private void checkAndSetName(String name) {
if (StringUtils.isBlank(name)) {
throw new RuntimeException("Attempt to create a list with a blank name.");
}
this.name = name;
}
/**
* Return the description of this bag.
* @return the description
*/
@Override
public String getDescription() {
return description;
}
/**
* Return the creation date that was passed to the constructor.
* @return the creation date
*/
public Date getDateCreated() {
return dateCreated;
}
/**
* @param description the description to set
* @throws ObjectStoreException if something goes wrong
*/
public void setDescription(String description)
throws ObjectStoreException {
this.description = description;
store();
}
/**
* Get the type of this bag (a class from InterMine model)
* @return the type of objects in this bag
*/
public String getType() {
return type;
}
/**
* Get the fully qualified type of this bag
* @return the type of objects in this bag
*/
public String getQualifiedType() {
return os.getModel().getPackageName() + "." + type;
}
/**
* Return the class descriptors for the type of this bag.
* @return the set of class descriptors
*/
public Set<ClassDescriptor> getClassDescriptors() {
return classDescriptors;
}
/**
* {@inheritDoc}
*/
@Override
public String getTitle() {
return getName();
}
/**
* Return the savedbagId of this bag
* @return savedbagId
*/
public Integer getSavedBagId() {
return savedBagId;
}
/**
* Set the keyFieldNames
* @param keyFieldNames the list of keyField names
*/
public void setKeyFieldNames(List<String> keyFieldNames) {
this.keyFieldNames = keyFieldNames;
}
/**
* Return a list containing the keyFieldNames for the bag
* @return keyFieldNames
*/
public List<String> getKeyFieldNames() {
return keyFieldNames;
}
/**
* Return true if the bag isCurrent
* @return isCurrent
*/
public boolean isCurrent() {
return isCurrent;
}
/**
* Set if the bag is current
* @param isCurrent the value to set
*/
public void setCurrent(boolean isCurrent) {
this.isCurrent = isCurrent;
}
/**
* Create copy of bag. Bag is saved to objectstore.
* @return create bag
*/
@Override
public Object clone() {
InterMineBag ret = cloneShallowIntermineBag();
cloneInternalObjectStoreBag(ret);
return ret;
}
private void cloneInternalObjectStoreBag(InterMineBag bag) {
ObjectStoreWriter osw = null;
try {
osw = os.getNewWriter();
ObjectStoreBag newBag = osw.createObjectStoreBag();
Query q = new Query();
q.addToSelect(this.osb);
osw.addToBagFromQuery(newBag, q);
bag.osb = newBag;
} catch (ObjectStoreException e) {
LOG.error("Clone failed.", e);
throw new RuntimeException("Clone failed.", e);
} finally {
try {
if (osw != null) {
osw.close();
}
} catch (ObjectStoreException e) {
LOG.error("Closing object store failed.", e);
}
}
}
private InterMineBag cloneShallowIntermineBag() {
// doesn't clone class descriptions and object store because they shouldn't change
// -> cloned instance shares it with the original instance
InterMineBag copy;
try {
copy = (InterMineBag) super.clone();
copy.savedBagId = null;
SavedBag savedBag = copy.store();
copy.savedBagId = savedBag.getId();
copy.keyFieldNames = keyFieldNames;
} catch (ObjectStoreException ex) {
throw new RuntimeException("Clone failed.", ex);
} catch (CloneNotSupportedException ex) {
throw new RuntimeException("Clone failed.", ex);
}
return copy;
}
/**
* Sets date when bag was created.
* @param date new date
*/
public void setDate(Date date) {
this.dateCreated = date;
}
/**
* Add the given id to the bag, this updates the bag contents in the database. he type can
* be a qualified or un-qualified class name.
* @param id the id to add
* @param type the type of ids being added
* @throws ObjectStoreException if problem storing
*/
public void addIdToBag(Integer id, String type) throws ObjectStoreException {
addIdsToBag(Collections.singleton(id), type);
}
/**
* Add the given ids to the bag, this updates the bag contents in the database. The type can
* be a qualified or un-qualified class name.
* @param ids the ids to add
* @param type the type of ids being added
* @throws ObjectStoreException
* if problem storing
*/
public void addIdsToBag(Collection<Integer> ids, String type)
throws ObjectStoreException {
if (!isOfType(type)) {
throw new IncompatibleTypesException("Cannot add type " + type
+ " to bag of type " + getType() + ".");
}
ObjectStoreWriter oswProduction = null;
try {
oswProduction = os.getNewWriter();
oswProduction.addAllToBag(osb, ids);
} finally {
if (oswProduction != null) {
oswProduction.close();
}
}
if (profileId != null) {
addBagValuesFromIds(ids);
}
}
/**
* Test whether the given type can be added to this bag, type can be a
* qualified or un-qualified string.
* @param testType type to check
* @return true if type can be added to the bag
*/
public boolean isOfType(String testType) {
Model model = os.getModel();
// this method works with qualified and unqualified class names
ClassDescriptor testCld = model.getClassDescriptorByName(testType);
if (testCld == null) {
throw new IllegalArgumentException("Class not found in model: " + testType);
}
Set<ClassDescriptor> clds = model.getClassDescriptorsForClass(testCld
.getType());
for (ClassDescriptor cld : clds) {
String className = cld.getName();
if (TypeUtil.unqualifiedName(className).equals(getType())) {
return true;
}
}
return false;
}
/**
* Add elements to the bag from a query, this is able to operate entirely in the database
* without needing to read objects into memory. The query should have a single column on the
* select list returning an object id.
* @param query to select object ids
* @throws ObjectStoreException if problem storing
*/
public void addToBagFromQuery(Query query) throws ObjectStoreException {
// query is checked in ObjectStoreWriter method
ObjectStoreWriter oswProduction = null;
try {
oswProduction = os.getNewWriter();
oswProduction.addToBagFromQuery(osb, query);
} finally {
if (oswProduction != null) {
oswProduction.close();
}
}
if (profileId != null) {
addBagValues();
}
}
/**
* Remove the given id from the bag, this updates the bag contents in the database
* @param id the id to remove
* @throws ObjectStoreException if problem storing
*/
public void removeIdFromBag(Integer id) throws ObjectStoreException {
removeIdsFromBag(Collections.singleton(id), true);
}
/**
* Remove the given ids from the bag, this updates the bag contents in the database
* @param ids the ids to remove
* @throws ObjectStoreException if problem storing
*/
public void removeIdsFromBag(Collection<Integer> ids, boolean updateBagValues) throws ObjectStoreException {
ObjectStoreWriter oswProduction = null;
try {
oswProduction = os.getNewWriter();
oswProduction.removeAllFromBag(osb, ids);
} finally {
if (oswProduction != null) {
oswProduction.close();
}
}
if (profileId != null && updateBagValues) {
deleteBagValues(ids);
}
}
/**
* Save the key field values associated to the bag into bagvalues table
*/
public void addBagValues() {
if (profileId != null) {
List<String> values = getContentsASKeyFieldValues();
addBagValues(values);
}
}
/**
* Save the key field values identified by the ids given in input into bagvalues table
*/
private void addBagValuesFromIds(Collection<Integer> ids) {
if (profileId != null) {
List<String> values = getKeyFieldValues(ids);
addBagValues(values);
}
}
/**
* Save the values given in input into bagvalues table
* @param bagValues the values to save
*/
public void addBagValues(Collection<String> bagValues) {
Connection conn = null;
Batch batch = null;
try {
conn = ((ObjectStoreWriterInterMineImpl) uosw).getConnection();
if (!DatabaseUtil.tableExists(conn, BAG_VALUES)) {
DatabaseUtil.createBagValuesTables(conn);
}
if (conn.getAutoCommit()) {
conn.setAutoCommit(false);
batch = new Batch(new BatchWriterPostgresCopyImpl());
String[] colNames = new String[] {"savedbagid", "value"};
for (String value : bagValues) {
batch.addRow(conn, BAG_VALUES, null, colNames,
new Object[] {savedBagId, value});
}
batch.flush(conn);
conn.commit();
conn.setAutoCommit(true);
}
} catch (SQLException sqle) {
System.out.println("Exception committing bagValues for bag: " + savedBagId);
sqle.printStackTrace();
LOG.error("Exception committing bagValues for bag: " + savedBagId, sqle);
try {
conn.rollback();
conn.setAutoCommit(true);
} catch (SQLException sqlex) {
throw new RuntimeException("Error aborting transaction", sqlex);
}
} finally {
try {
batch.close(conn);
} catch (Exception e) {
LOG.error("Exception caught when closing Batch while addbagValues", e);
}
((ObjectStoreWriterInterMineImpl) uosw).releaseConnection(conn);
}
}
private void deleteBagValues(Collection<Integer> ids) {
List<String> values = getKeyFieldValues(ids);
if (values.size() > 0) {
deleteBagValues(values);
}
}
public void deleteBagValues(List<String> values) {
Connection conn = null;
PreparedStatement stm = null;
try {
conn = ((ObjectStoreWriterInterMineImpl) uosw).getConnection();
Collection<String> placeHolders = CollectionUtils.collect(values,
new ConstantTransformer("?"));
String valuesList = StringUtils.join(placeHolders, ", ");
String sql = "DELETE FROM " + BAG_VALUES + " WHERE savedBagId = ? "
+ " AND value IN (" + valuesList + " )";
stm = conn.prepareStatement(sql);
stm.setInt(1, savedBagId);
for (int i = 0; i < values.size(); i++) {
stm.setString(i + 2, values.get(i));
}
stm.executeUpdate();
} catch (SQLException sqle) {
throw new RuntimeException("Error deleting the " + values.size() + " bagvalues of bag : " + savedBagId, sqle);
} finally {
if (stm != null) {
try {
stm.close();
} catch (SQLException e) {
throw new RuntimeException("Problem closing resources in"
+ " deleteBagValuesByValue()", e);
}
}
((ObjectStoreWriterInterMineImpl) uosw).releaseConnection(conn);
}
}
public void deleteAllBagValues() {
Connection conn = null;
PreparedStatement stm = null;
try {
conn = ((ObjectStoreWriterInterMineImpl) uosw).getConnection();
String sql = "DELETE FROM " + BAG_VALUES + " WHERE savedBagId = ? ";
stm = conn.prepareStatement(sql);
stm.setInt(1, savedBagId);
stm.executeUpdate();
} catch (SQLException sqle) {
throw new RuntimeException("Error deleting the bagvalues of bag : " + savedBagId, sqle);
} finally {
if (stm != null) {
try {
stm.close();
} catch (SQLException e) {
throw new RuntimeException("Problem closing resources in"
+ " deleteAllBagValues()", e);
}
}
((ObjectStoreWriterInterMineImpl) uosw).releaseConnection(conn);
}
}
}
| intermine/api/main/src/org/intermine/api/profile/InterMineBag.java | package org.intermine.api.profile;
/*
* Copyright (C) 2002-2011 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.functors.ConstantTransformer;
import org.apache.log4j.Logger;
import org.intermine.api.bag.IncompatibleTypesException;
import org.intermine.api.bag.UnknownBagTypeException;
import org.intermine.api.search.WebSearchable;
import org.intermine.metadata.ClassDescriptor;
import org.intermine.metadata.Model;
import org.intermine.model.userprofile.SavedBag;
import org.intermine.model.userprofile.UserProfile;
import org.intermine.objectstore.ObjectStore;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.objectstore.ObjectStoreWriter;
import org.intermine.objectstore.intermine.ObjectStoreInterMineImpl;
import org.intermine.objectstore.intermine.ObjectStoreWriterInterMineImpl;
import org.intermine.objectstore.proxy.ProxyReference;
import org.intermine.objectstore.query.BagConstraint;
import org.intermine.objectstore.query.ConstraintOp;
import org.intermine.objectstore.query.ObjectStoreBag;
import org.intermine.objectstore.query.Query;
import org.intermine.objectstore.query.QueryClass;
import org.intermine.objectstore.query.QueryField;
import org.intermine.objectstore.query.Results;
import org.intermine.objectstore.query.ResultsRow;
import org.intermine.objectstore.query.SingletonResults;
import org.intermine.sql.DatabaseUtil;
import org.intermine.sql.writebatch.Batch;
import org.intermine.sql.writebatch.BatchWriterPostgresCopyImpl;
import org.intermine.util.TypeUtil;
/**
* An object that represents a bag of objects in our database for the webapp. It is backed by an
* ObjectStoreBag object, but contains extra data such as name and description.
*
* @author Kim Rutherford
* @author Matthew Wakeling
*/
public class InterMineBag implements WebSearchable, Cloneable
{
protected static final Logger LOG = Logger.getLogger(InterMineBag.class);
public static final String BAG_VALUES = "bagvalues";
private Integer profileId;
private Integer savedBagId;
private String name;
protected final String type;
private String description;
private Date dateCreated;
private List<String> keyFieldNames = new ArrayList<String>();
private boolean isCurrent;
private ObjectStoreBag osb;
private ObjectStore os;
private ObjectStoreWriter uosw;
private Set<ClassDescriptor> classDescriptors;
/**
* Constructs a new InterMineIdBag, and saves it in the UserProfile database.
*
* @param name the name of the bag
* @param type the class of objects stored in the bag
* @param description the description of the bag
* @param dateCreated the Date when this bag was created
* @param isCurrent the status of this bag
* @param os the production ObjectStore
* @param profileId the ID of the user in the userprofile database
* @param uosw the ObjectStoreWriter of the userprofile database
* @throws ObjectStoreException if an error occurs
*/
public InterMineBag(String name, String type, String description, Date dateCreated,
boolean isCurrent, ObjectStore os, Integer profileId, ObjectStoreWriter uosw)
throws ObjectStoreException {
this.type = type;
init(name, description, dateCreated, isCurrent, os, profileId, uosw);
}
/**
* Constructs a new InterMineIdBag, and saves it in the UserProfile database.
*
* @param name the name of the bag
* @param type the class of objects stored in the bag
* @param description the description of the bag
* @param dateCreated the Date when this bag was created
* @param isCurrent the current state of the bag
* @param os the production ObjectStore
* @param profileId the ID of the user in the userprofile database
* @param uosw the ObjectStoreWriter of the userprofile database
* @param keyFieldNames the list of identifiers defined for this bag
* @throws ObjectStoreException if an error occurs
*/
public InterMineBag(String name, String type, String description, Date dateCreated,
boolean isCurrent, ObjectStore os, Integer profileId, ObjectStoreWriter uosw,
List<String> keyFieldNames) throws ObjectStoreException {
this.type = type;
init(name, description, dateCreated, isCurrent, os, profileId, uosw);
this.keyFieldNames = keyFieldNames;
}
private void init(String name, String description, Date dateCreated, boolean isCurrent,
ObjectStore os, Integer profileId, ObjectStoreWriter uosw) throws ObjectStoreException {
checkAndSetName(name);
this.description = description;
this.dateCreated = dateCreated;
this.isCurrent = isCurrent;
this.os = os;
this.profileId = profileId;
this.osb = os.createObjectStoreBag();
this.uosw = uosw;
this.savedBagId = null;
SavedBag savedBag = store();
this.savedBagId = savedBag.getId();
setClassDescriptors();
}
/**
* Loads an InterMineBag from the UserProfile database.
*
* @param os the production ObjectStore
* @param savedBagId the ID of the bag in the userprofile database
* @param uosw the ObjectStoreWriter of the userprofile database
* @throws ObjectStoreException if something goes wrong
*/
public InterMineBag(ObjectStore os, Integer savedBagId, ObjectStoreWriter uosw)
throws ObjectStoreException {
this.os = os;
this.uosw = uosw;
this.savedBagId = savedBagId;
ObjectStore uos = uosw.getObjectStore();
SavedBag savedBag = (SavedBag) uos.getObjectById(savedBagId, SavedBag.class);
checkAndSetName(savedBag.getName());
this.type = savedBag.getType();
this.description = savedBag.getDescription();
this.dateCreated = savedBag.getDateCreated();
this.profileId = savedBag.proxGetUserProfile().getId();
this.isCurrent = savedBag.getCurrent();
this.osb = new ObjectStoreBag(savedBag.getOsbId());
setClassDescriptors();
}
private void setClassDescriptors() {
try {
Class<?> cls = Class.forName(getQualifiedType());
classDescriptors = os.getModel().getClassDescriptorsForClass(cls);
} catch (ClassNotFoundException e) {
throw new UnknownBagTypeException("bag type " + getQualifiedType() + " not known", e);
}
}
private SavedBag store() throws ObjectStoreException {
SavedBag savedBag = new SavedBag();
savedBag.setId(savedBagId);
if (profileId != null) {
savedBag.setName(name);
savedBag.setType(type);
savedBag.setDescription(description);
savedBag.setDateCreated(dateCreated);
savedBag.proxyUserProfile(new ProxyReference(null, profileId, UserProfile.class));
savedBag.setOsbId(osb.getBagId());
savedBag.setCurrent(isCurrent);
uosw.store(savedBag);
}
return savedBag;
}
/**
* Delete this bag from the userprofile database, bag should not be used after this method has
* been called. Delete the ids from the production database too.
* @throws ObjectStoreException if problem deleting bag
*/
protected void delete() throws ObjectStoreException {
if (profileId != null) {
SavedBag savedBag = (SavedBag) uosw.getObjectStore().getObjectById(savedBagId,
SavedBag.class);
uosw.delete(savedBag);
removeIdsFromBag(getContentsAsIds(), false);
deleteAllBagValues();
this.profileId = null;
this.savedBagId = null;
}
}
/**
* Returns a List which contains the contents of this bag as Integer IDs.
*
* @return a List of Integers
*/
public List<Integer> getContentsAsIds() {
Query q = new Query();
q.addToSelect(osb);
q.setDistinct(false);
SingletonResults res = os.executeSingleton(q, 1000, false, true, true);
return ((List) res);
}
/**
* Returns a List of key field values of the objects contained by this bag.
* @return the list of key field values
*/
public List<String> getContentsASKeyFieldValues() {
List<String> keyFieldValueList = new ArrayList<String>();
if (isCurrent) {
Query q = new Query();
q.setDistinct(false);
try {
QueryClass qc = new QueryClass(Class.forName(getQualifiedType()));
q.addFrom(qc);
if (keyFieldNames.isEmpty()) {
throw new RuntimeException("set the keyFieldNames before calling "
+ "getContentsASKeyFieldValues method");
}
for (String keyFieldName : keyFieldNames) {
q.addToSelect(new QueryField(qc, keyFieldName));
}
QueryField idField = new QueryField(qc, "id");
BagConstraint c = new BagConstraint(idField, ConstraintOp.IN, osb);
q.setConstraint(c);
Results res = os.execute(q);
for (Object rowObj : res) {
ResultsRow<?> row = (ResultsRow<?>) rowObj;
String value;
for (int index = 0; index < keyFieldNames.size(); index++) {
value = (String) row.get(index);
if (value != null && !"".equals(value)) {
if (! keyFieldValueList.contains(value)) {
keyFieldValueList.add(value);
}
break;
}
}
}
return keyFieldValueList;
} catch (ClassNotFoundException cne) {
return new ArrayList<String>();
}
} else {
//we are upgrading bags, the osbag_int is empty, we need to use bagvalues table
Connection conn = null;
Statement stm = null;
ResultSet rs = null;
List<String> primaryIdentifiersList = new ArrayList<String>();
ObjectStoreInterMineImpl uos = null;
try {
uos = (ObjectStoreInterMineImpl) uosw.getObjectStore();
conn = uos.getConnection();
stm = conn.createStatement();
String sql = "SELECT value FROM " + BAG_VALUES + " WHERE savedbagid = "
+ savedBagId;
rs = stm.executeQuery(sql);
while (rs.next()) {
primaryIdentifiersList.add(rs.getString(1));
}
} catch (SQLException sqe) {
LOG.error("Connection problems during loadings primary identifiers fields for"
+ "the bag " + name, sqe);
} finally {
if (rs != null) {
try {
rs.close();
if (stm != null) {
stm.close();
}
} catch (SQLException sqle) {
LOG.error("Problems closing resources in the method "
+ "getContentsASPrimaryIdentifierValues for the bag " + name, sqle);
}
}
uos.releaseConnection(conn);
}
return primaryIdentifiersList;
}
}
/**
* Returns the values of the key field objects with id specified in input and contained in
* the bag
* @param ids the collection of id
* @return the list of values
*/
@SuppressWarnings("unchecked")
public List<String> getKeyFieldValues(Collection<Integer> ids) {
List<String> keyFieldValueList = new ArrayList<String>();
Query q = new Query();
q.setDistinct(false);
if (keyFieldNames.isEmpty()) {
return Collections.EMPTY_LIST;
}
try {
QueryClass qc = new QueryClass(Class.forName(getQualifiedType()));
q.addFrom(qc);
for (String keyFieldName : keyFieldNames) {
q.addToSelect(new QueryField(qc, keyFieldName));
}
QueryField idField = new QueryField(qc, "id");
BagConstraint idsConstraints = new BagConstraint(idField, ConstraintOp.IN, ids);
q.setConstraint(idsConstraints);
Results res = os.execute(q, 1000, false, true, true);
for (Object rowObj : res) {
ResultsRow<?> row = (ResultsRow<?>) rowObj;
String value;
for (int index = 0; index < keyFieldNames.size(); index++) {
value = (String) row.get(index);
if (value != null && !"".equals(value)) {
keyFieldValueList.add(value);
break;
}
}
}
return keyFieldValueList;
} catch (ClassNotFoundException cne) {
return new ArrayList<String>();
}
}
/**
* Upgrades the ObjectStoreBag with a new ObjectStoreBag containing the collection of elements
* given in input
* @param values the collection of elements to add
* @param updateBagValues id true if we upgrade the bagvalues table
* @throws ObjectStoreException if an error occurs fetching a new ID
*/
public void upgradeOsb(Collection<Integer> values, boolean updateBagValues) throws ObjectStoreException {
ObjectStoreWriter oswProduction = null;
SavedBag savedBag = (SavedBag) uosw.getObjectById(savedBagId, SavedBag.class);
try {
oswProduction = os.getNewWriter();
osb = oswProduction.createObjectStoreBag();
oswProduction.addAllToBag(osb, values);
savedBag.setOsbId(osb.getBagId());
savedBag.setCurrent(true);
isCurrent = true;
uosw.store(savedBag);
if (updateBagValues) {
deleteAllBagValues();
addBagValues();
}
} finally {
if (oswProduction != null) {
oswProduction.close();
}
}
}
/**
* Returns the size of the bag.
*
* @return the number of elements in the bag
* @throws ObjectStoreException if something goes wrong
*/
public int size() throws ObjectStoreException {
Query q = new Query();
q.addToSelect(osb);
q.setDistinct(false);
return os.count(q, ObjectStore.SEQUENCE_IGNORE);
}
/**
* Getter for size, just to make JSP happy.
*
* @return the number of elements in the bag
* @throws ObjectStoreException if something goes wrong
*/
public int getSize() throws ObjectStoreException {
return size();
}
/**
* Returns the ObjectStoreBag, so that elements can be added and removed.
*
* @return the ObjectStoreBag
*/
public ObjectStoreBag getOsb() {
return osb;
}
/**
* Sets the ObjectStoreBag.
*
* @param osb the ObjectStoreBag
*/
public void setOsb(ObjectStoreBag osb) {
this.osb = osb;
}
/**
* Sets the profileId - moves this bag from one profile to another.
*
* @param profileId the ID of the new userprofile
* @throws ObjectStoreException if something goes wrong
*/
public void setProfileId(Integer profileId)
throws ObjectStoreException {
this.profileId = profileId;
SavedBag savedBag = store();
this.savedBagId = savedBag.getId();
isCurrent = savedBag.getCurrent();
addBagValues();
}
/**
* Save the bag into the userprofile database
*
* @param profileId the ID of the userprofile
* @param bagValues the list of the key field values of the objects contained by the bag
* @throws ObjectStoreException if something goes wrong
*/
public void saveWithBagValues(Integer profileId, Collection<String> bagValues)
throws ObjectStoreException {
this.profileId = profileId;
SavedBag savedBag = store();
this.savedBagId = savedBag.getId();
isCurrent = savedBag.getCurrent();
addBagValues(bagValues);
}
/**
* Returns the value of name
* @return the name of the bag
*/
@Override
public String getName() {
return name;
}
/**
* Set the value of name
* @param name the bag name
* @throws ObjectStoreException if something goes wrong
*/
public void setName(String name) throws ObjectStoreException {
checkAndSetName(name);
store();
}
// Always set the name via this method to avoid saving bags with blank names
private void checkAndSetName(String name) {
if (StringUtils.isBlank(name)) {
throw new RuntimeException("Attempt to create a list with a blank name.");
}
this.name = name;
}
/**
* Return the description of this bag.
* @return the description
*/
@Override
public String getDescription() {
return description;
}
/**
* Return the creation date that was passed to the constructor.
* @return the creation date
*/
public Date getDateCreated() {
return dateCreated;
}
/**
* @param description the description to set
* @throws ObjectStoreException if something goes wrong
*/
public void setDescription(String description)
throws ObjectStoreException {
this.description = description;
store();
}
/**
* Get the type of this bag (a class from InterMine model)
* @return the type of objects in this bag
*/
public String getType() {
return type;
}
/**
* Get the fully qualified type of this bag
* @return the type of objects in this bag
*/
public String getQualifiedType() {
return os.getModel().getPackageName() + "." + type;
}
/**
* Return the class descriptors for the type of this bag.
* @return the set of class descriptors
*/
public Set<ClassDescriptor> getClassDescriptors() {
return classDescriptors;
}
/**
* {@inheritDoc}
*/
@Override
public String getTitle() {
return getName();
}
/**
* Return the savedbagId of this bag
* @return savedbagId
*/
public Integer getSavedBagId() {
return savedBagId;
}
/**
* Set the keyFieldNames
* @param keyFieldNames the list of keyField names
*/
public void setKeyFieldNames(List<String> keyFieldNames) {
this.keyFieldNames = keyFieldNames;
}
/**
* Return a list containing the keyFieldNames for the bag
* @return keyFieldNames
*/
public List<String> getKeyFieldNames() {
return keyFieldNames;
}
/**
* Return true if the bag isCurrent
* @return isCurrent
*/
public boolean isCurrent() {
return isCurrent;
}
/**
* Set if the bag is current
* @param isCurrent the value to set
*/
public void setCurrent(boolean isCurrent) {
this.isCurrent = isCurrent;
}
/**
* Create copy of bag. Bag is saved to objectstore.
* @return create bag
*/
@Override
public Object clone() {
InterMineBag ret = cloneShallowIntermineBag();
cloneInternalObjectStoreBag(ret);
return ret;
}
private void cloneInternalObjectStoreBag(InterMineBag bag) {
ObjectStoreWriter osw = null;
try {
osw = os.getNewWriter();
ObjectStoreBag newBag = osw.createObjectStoreBag();
Query q = new Query();
q.addToSelect(this.osb);
osw.addToBagFromQuery(newBag, q);
bag.osb = newBag;
} catch (ObjectStoreException e) {
LOG.error("Clone failed.", e);
throw new RuntimeException("Clone failed.", e);
} finally {
try {
if (osw != null) {
osw.close();
}
} catch (ObjectStoreException e) {
LOG.error("Closing object store failed.", e);
}
}
}
private InterMineBag cloneShallowIntermineBag() {
// doesn't clone class descriptions and object store because they shouldn't change
// -> cloned instance shares it with the original instance
InterMineBag copy;
try {
copy = (InterMineBag) super.clone();
copy.savedBagId = null;
SavedBag savedBag = copy.store();
copy.savedBagId = savedBag.getId();
copy.keyFieldNames = keyFieldNames;
} catch (ObjectStoreException ex) {
throw new RuntimeException("Clone failed.", ex);
} catch (CloneNotSupportedException ex) {
throw new RuntimeException("Clone failed.", ex);
}
return copy;
}
/**
* Sets date when bag was created.
* @param date new date
*/
public void setDate(Date date) {
this.dateCreated = date;
}
/**
* Add the given id to the bag, this updates the bag contents in the database. he type can
* be a qualified or un-qualified class name.
* @param id the id to add
* @param type the type of ids being added
* @throws ObjectStoreException if problem storing
*/
public void addIdToBag(Integer id, String type) throws ObjectStoreException {
addIdsToBag(Collections.singleton(id), type);
}
/**
* Add the given ids to the bag, this updates the bag contents in the database. The type can
* be a qualified or un-qualified class name.
* @param ids the ids to add
* @param type the type of ids being added
* @throws ObjectStoreException
* if problem storing
*/
public void addIdsToBag(Collection<Integer> ids, String type)
throws ObjectStoreException {
if (!isOfType(type)) {
throw new IncompatibleTypesException("Cannot add type " + type
+ " to bag of type " + getType() + ".");
}
ObjectStoreWriter oswProduction = null;
try {
oswProduction = os.getNewWriter();
oswProduction.addAllToBag(osb, ids);
} finally {
if (oswProduction != null) {
oswProduction.close();
}
}
if (profileId != null) {
addBagValuesFromIds(ids);
}
}
/**
* Test whether the given type can be added to this bag, type can be a
* qualified or un-qualified string.
* @param testType type to check
* @return true if type can be added to the bag
*/
public boolean isOfType(String testType) {
Model model = os.getModel();
// this method works with qualified and unqualified class names
ClassDescriptor testCld = model.getClassDescriptorByName(testType);
if (testCld == null) {
throw new IllegalArgumentException("Class not found in model: " + testType);
}
Set<ClassDescriptor> clds = model.getClassDescriptorsForClass(testCld
.getType());
for (ClassDescriptor cld : clds) {
String className = cld.getName();
if (TypeUtil.unqualifiedName(className).equals(getType())) {
return true;
}
}
return false;
}
/**
* Add elements to the bag from a query, this is able to operate entirely in the database
* without needing to read objects into memory. The query should have a single column on the
* select list returning an object id.
* @param query to select object ids
* @throws ObjectStoreException if problem storing
*/
public void addToBagFromQuery(Query query) throws ObjectStoreException {
// query is checked in ObjectStoreWriter method
ObjectStoreWriter oswProduction = null;
try {
oswProduction = os.getNewWriter();
oswProduction.addToBagFromQuery(osb, query);
} finally {
if (oswProduction != null) {
oswProduction.close();
}
}
if (profileId != null) {
addBagValues();
}
}
/**
* Remove the given id from the bag, this updates the bag contents in the database
* @param id the id to remove
* @throws ObjectStoreException if problem storing
*/
public void removeIdFromBag(Integer id) throws ObjectStoreException {
removeIdsFromBag(Collections.singleton(id), true);
}
/**
* Remove the given ids from the bag, this updates the bag contents in the database
* @param ids the ids to remove
* @throws ObjectStoreException if problem storing
*/
public void removeIdsFromBag(Collection<Integer> ids, boolean updateBagValues) throws ObjectStoreException {
ObjectStoreWriter oswProduction = null;
try {
oswProduction = os.getNewWriter();
oswProduction.removeAllFromBag(osb, ids);
} finally {
if (oswProduction != null) {
oswProduction.close();
}
}
if (profileId != null && updateBagValues) {
deleteBagValues(ids);
}
}
/**
* Save the key field values associated to the bag into bagvalues table
*/
public void addBagValues() {
if (profileId != null) {
List<String> values = getContentsASKeyFieldValues();
addBagValues(values);
}
}
/**
* Save the key field values identified by the ids given in input into bagvalues table
*/
private void addBagValuesFromIds(Collection<Integer> ids) {
if (profileId != null) {
List<String> values = getKeyFieldValues(ids);
addBagValues(values);
}
}
/**
* Save the values given in input into bagvalues table
* @param bagValues the values to save
*/
public void addBagValues(Collection<String> bagValues) {
Connection conn = null;
Batch batch = null;
try {
conn = ((ObjectStoreWriterInterMineImpl) uosw).getConnection();
if (!DatabaseUtil.tableExists(conn, BAG_VALUES)) {
DatabaseUtil.createBagValuesTables(conn);
}
if (conn.getAutoCommit()) {
conn.setAutoCommit(false);
batch = new Batch(new BatchWriterPostgresCopyImpl());
String[] colNames = new String[] {"savedbagid", "value"};
for (String value : bagValues) {
batch.addRow(conn, BAG_VALUES, null, colNames,
new Object[] {savedBagId, value});
}
batch.flush(conn);
conn.commit();
conn.setAutoCommit(true);
}
} catch (SQLException sqle) {
System.out.println("Exception committing bagValues for bag: " + savedBagId);
sqle.printStackTrace();
LOG.error("Exception committing bagValues for bag: " + savedBagId, sqle);
try {
conn.rollback();
conn.setAutoCommit(true);
} catch (SQLException sqlex) {
throw new RuntimeException("Error aborting transaction", sqlex);
}
} finally {
try {
batch.close(conn);
} catch (Exception e) {
LOG.error("Exception caught when closing Batch while addbagValues", e);
}
((ObjectStoreWriterInterMineImpl) uosw).releaseConnection(conn);
}
}
private void deleteBagValues(Collection<Integer> ids) {
List<String> values = getKeyFieldValues(ids);
if (values.size() > 0) {
deleteBagValues(values);
}
}
public void deleteBagValues(List<String> values) {
Connection conn = null;
PreparedStatement stm = null;
try {
conn = ((ObjectStoreWriterInterMineImpl) uosw).getConnection();
Collection<String> placeHolders = CollectionUtils.collect(values,
new ConstantTransformer("?"));
String valuesList = StringUtils.join(placeHolders, ", ");
String sql = "DELETE FROM " + BAG_VALUES + " WHERE savedBagId = ? "
+ " AND value IN (" + valuesList + " )";
stm = conn.prepareStatement(sql);
stm.setInt(1, savedBagId);
for (int i = 0; i < values.size(); i++) {
stm.setString(i + 2, values.get(i));
}
stm.executeUpdate();
} catch (SQLException sqle) {
throw new RuntimeException("Error deleting the " + values.size() + " bagvalues of bag : " + savedBagId, sqle);
} finally {
if (stm != null) {
try {
stm.close();
} catch (SQLException e) {
throw new RuntimeException("Problem closing resources in"
+ " deleteBagValuesByValue()", e);
}
}
((ObjectStoreWriterInterMineImpl) uosw).releaseConnection(conn);
}
}
public void deleteAllBagValues() {
Connection conn = null;
PreparedStatement stm = null;
try {
conn = ((ObjectStoreWriterInterMineImpl) uosw).getConnection();
String sql = "DELETE FROM " + BAG_VALUES + " WHERE savedBagId = ? ";
stm = conn.prepareStatement(sql);
stm.setInt(1, savedBagId);
stm.executeUpdate();
} catch (SQLException sqle) {
throw new RuntimeException("Error deleting the bagvalues of bag : " + savedBagId, sqle);
} finally {
if (stm != null) {
try {
stm.close();
} catch (SQLException e) {
throw new RuntimeException("Problem closing resources in"
+ " deleteAllBagValues()", e);
}
}
((ObjectStoreWriterInterMineImpl) uosw).releaseConnection(conn);
}
}
}
| Before save into bagvalues table, check if there are some duplicates
Former-commit-id: cee202613d9bd160d85433519b74b45144b990eb | intermine/api/main/src/org/intermine/api/profile/InterMineBag.java | Before save into bagvalues table, check if there are some duplicates | <ide><path>ntermine/api/main/src/org/intermine/api/profile/InterMineBag.java
<ide>
<ide> /**
<ide> * Returns a List of key field values of the objects contained by this bag.
<add> * Removed any duplicates
<ide> * @return the list of key field values
<ide> */
<ide> public List<String> getContentsASKeyFieldValues() {
<ide>
<ide> /**
<ide> * Returns the values of the key field objects with id specified in input and contained in
<del> * the bag
<add> * the bag. Removed any duplicates
<ide> * @param ids the collection of id
<ide> * @return the list of values
<ide> */
<ide> for (int index = 0; index < keyFieldNames.size(); index++) {
<ide> value = (String) row.get(index);
<ide> if (value != null && !"".equals(value)) {
<del> keyFieldValueList.add(value);
<add> if (! keyFieldValueList.contains(value)) {
<add> keyFieldValueList.add(value);
<add> }
<ide> break;
<ide> }
<ide> } |
|
Java | mit | e954525e02eb6cf46d64e306314b3e0e2743cad1 | 0 | vortexwolf/2ch-Browser | package com.vortexwolf.chan.activities;
import com.vortexwolf.chan.common.library.MyLog;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class NewRecaptchaActivity extends Activity {
private final static String data =
"<script src=\"https://www.google.com/recaptcha/api.js\" async defer></script>"+
"<form action=\"_intercept\" method=\"GET\">"+
" <div class=\"g-recaptcha\" data-sitekey=\"6LcM2P4SAAAAAD97nF449oigatS5hPCIgt8AQanz\"></div>"+
" <input type=\"submit\" value=\"Submit\">"+
"</form>";
private final static String hashfilter = "g-recaptcha-response=";
public final static int OK = 1;
public final static int FAIL = 2;
@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("Recaptcha 2.0");
WebView webView = new WebView(this);
webView.setWebViewClient(new WebViewClient() {
@SuppressWarnings("deprecation")
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
if (url.contains("_intercept")) {
if (url.indexOf(hashfilter) != -1) {
String hash = url.substring(url.indexOf(hashfilter) + hashfilter.length());
MyLog.d("INTERCEPTOR", "hash: "+hash);
Intent resultIntent = new Intent();
resultIntent.putExtra("hash", hash);
setResult(OK, resultIntent);
} else {
setResult(FAIL);
}
finish();
}
return super.shouldInterceptRequest(view, url);
}
});
webView.getSettings().setJavaScriptEnabled(true);
setContentView(webView);
webView.loadDataWithBaseURL("https://127.0.0.1/", data, "text/html", "UTF-8", null);
}
}
| src/com/vortexwolf/chan/activities/NewRecaptchaActivity.java | package com.vortexwolf.chan.activities;
import com.vortexwolf.chan.common.library.MyLog;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class NewRecaptchaActivity extends Activity {
private final static String data =
"<script src=\"https://www.google.com/recaptcha/api.js\" async defer></script>"+
"<form action=\"_intercept\" method=\"GET\">"+
" <div class=\"g-recaptcha\" data-sitekey=\"6LcM2P4SAAAAAD97nF449oigatS5hPCIgt8AQanz\"></div>"+
" <input type=\"submit\" value=\"Submit\">"+
"</form>";
private final static String hashfilter = "g-recaptcha-response=";
public final static int OK = 0;
public final static int FAIL = 1;
@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("Recaptcha 2.0");
WebView webView = new WebView(this);
webView.setWebViewClient(new WebViewClient() {
@SuppressWarnings("deprecation")
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
if (url.contains("_intercept")) {
if (url.indexOf(hashfilter) != -1) {
String hash = url.substring(url.indexOf(hashfilter) + hashfilter.length());
MyLog.d("INTERCEPTOR", "hash: "+hash);
Intent resultIntent = new Intent();
resultIntent.putExtra("hash", hash);
setResult(OK, resultIntent);
} else {
setResult(FAIL);
}
finish();
}
return super.shouldInterceptRequest(view, url);
}
});
webView.getSettings().setJavaScriptEnabled(true);
setContentView(webView);
webView.loadDataWithBaseURL("https://127.0.0.1/", data, "text/html", "UTF-8", null);
}
}
| Captcha 2 Fix
| src/com/vortexwolf/chan/activities/NewRecaptchaActivity.java | Captcha 2 Fix | <ide><path>rc/com/vortexwolf/chan/activities/NewRecaptchaActivity.java
<ide> "</form>";
<ide> private final static String hashfilter = "g-recaptcha-response=";
<ide>
<del> public final static int OK = 0;
<del> public final static int FAIL = 1;
<add> public final static int OK = 1;
<add> public final static int FAIL = 2;
<ide>
<ide> @SuppressLint("SetJavaScriptEnabled")
<ide> @Override |
|
Java | epl-1.0 | 029e6b8536ec602a4ef9f11fb2464c1e194a0e8a | 0 | tylerjemarshall/ChatServer | package client;
import game.TicTacToe;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.io.IOException;
//import java.util.Scanner;
/**
* @author marshall0530
*/
/**
* @author Tyler M
*
*/
public class GUIConsole extends JFrame implements ChatIF {
final public static int DEFAULT_PORT = 5555;
private static final long serialVersionUID = 1L;
private JButton sendB = new JButton("Send");
private JButton quitB = new JButton("Quit");
private JTextField messageTxF = new JTextField("");
private JTextArea messageList = new JTextArea();
private ChatClient client;
private Profile profile = new Profile();
private String[] args;
private String[] roomArray;
private JButton refresh = new JButton("Refresh Rooms");
private JComboBox roomList = new JComboBox();
//Makes the client accessible from LoginDialog
public void setRoomList(JComboBox arg)
{
this.roomList = arg;
}
public JComboBox getRoomList()
{
return this.roomList;
}
public ChatClient getChatClient()
{
return this.client;
}
public void setChatClient(ChatClient chatClient)
{
this.client = chatClient;
}
public String[] getRoomArray() {
return roomArray;
}
public void setRoomArray(String[] roomArray) {
this.roomArray = roomArray;
}
public String[] getArgs()
{
return this.args;
}
public GUIConsole ( String[] args)
{
super("Simple Chat GUI");
this.args = args;
setSize(300, 400);
messageList.setWrapStyleWord(true);
messageList.setSize(300, 1000);
profile.setFont("Tahoma",Font.PLAIN,12);
messageList.setFont(profile.getFont());
// roomList.
final Panel roomBox = new Panel();
setLayout( new BorderLayout(0,0));
final Panel southBox = new Panel();
final Panel southInput = new Panel();
final Panel southButtons = new Panel();
add( "North" , roomBox);
roomBox.setLayout(new GridLayout(1, 2, 5, 5));
roomBox.add(roomList);
roomBox.add(refresh);
add( "Center", messageList );
add( "South" , southBox);
southBox.setLayout( new GridLayout(2,1,5,5));
southBox.add(southInput);
southInput.setLayout(new GridLayout(1, 1, 5, 5));
southInput.add(messageTxF);
southBox.add(southButtons);
southButtons.setLayout(new GridLayout(1, 2, 5, 5));
southButtons.add(quitB); southButtons.add(sendB);
messageList.setLineWrap(true);
messageList.setEditable(false);
JScrollPane scroll = new JScrollPane (messageList);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
add(scroll);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation(dim.width/2-this.getSize().width/2, dim.height/2-this.getSize().height/2);
refresh.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setRoomList(new javax.swing.JComboBox());
getRoomList().setModel(new javax.swing.DefaultComboBoxModel(client.getRoomList()));
getRoomList().setName("roomList");
}
});
//This creates the Login Dialog which will establish the connection and welcomes the user.
LoginDialog loginDlg = new LoginDialog(args, this);
loginDlg.setVisible(true);
// Handles Combo Box
roomList.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// JComboBox<String[]> roomList = (JComboBox<String[]>) e.getSource();
// roomList.removeAll();
// ((JComboBox) e.getSource()).addItem(client.getRoomList());
// ((JComboBox) e.getSource()).setModel(new DefaultComboBoxModel(client.getRoomList()));
}
});
//This handles closing the client with the X Button
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent windowEvent) {
if (JOptionPane.showConfirmDialog(southBox,
"Are you sure to close this window?", "Really Closing?",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION){
client.handleMessageFromClientUI("Good Bye!");
try
{
client.closeConnection();
}
catch (IOException e)
{
display("Unable to close connection, terminating client");
}
finally
{
System.exit(0);
}
}
}});
// This handles the Enter Key being pressed when sending message
messageTxF.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleGUIMessage();
}
});
// This handles the Send Button being pressed, same as above
sendB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleGUIMessage();
}
});
//This handles when the Quit button is pressed
quitB.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (JOptionPane.showConfirmDialog(southBox,
"Are you sure to close this window?",
"Really Closing?", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
client.handleMessageFromClientUI("Good Bye!");
try {
client.sendToServer("#logout");
} catch (IOException ioe) {
display("Unable to close connection, terminating client");
} finally {
System.exit(0);
}
}
}
});
setVisible(true);
}
/**
* Method handles when the GUI tries to send a message.
*/
private void handleGUIMessage() {
if (!messageTxF.getText().isEmpty()) {
String msg = messageTxF.getText();
System.out.println("msg: " + msg);
if(msg.indexOf("#") == 0)
handleGUIClientCommand(msg);
else
send();
}
}
/**
* Handles commands from within the GUI that pertains to only the GUI.
*
* @param msg The command being sent for GUIConsole to handle.
*/
private void handleGUIClientCommand(String msg) {
//makes command case insensitive
msg = msg.toLowerCase().trim();
//declarations
String cmd = "";
cmd = (msg.indexOf(" ") == -1) ? msg : msg.substring(0, msg.indexOf(" "));
int end = msg.length();
int space = (msg.indexOf(" ") == -1) ? end : msg.indexOf(" ");
String truncMsg = msg.substring(space, end).trim();
switch (cmd)
{
case "#game":
client.setGame(new TicTacToe(this));
client.getGame().setOnline(true);
try {
client.tryToSendToServer(msg);
} catch (Exception e) {
e.printStackTrace();
display("Failed to send command to server.");
}
break;
case "#fontsize":
profile.setFontSize(Integer.parseInt(truncMsg));
messageList.setFont(profile.getFont());
break;
case "#fontstyle":
profile.setFontStyle(truncMsg);
messageList.setFont(profile.getFont());
break;
case "#fontname":
profile.setFontName((truncMsg));
messageList.setFont(profile.getFont());
break;
default:
send();
}
messageTxF.setText("");
}
/**
* Displays message in GUIConsole's Message List.
*/
@Override
public void display(String message) {
messageList.insert("> " + message + "\n", 0);
}
/**
* Displays message in GUIConsole's Message List with a UserName before the message.
*/
@Override
public void display(String message, String user)
{
messageList.insert(user + "> " + message + "\n", 0);
}
/**
* Method to send message to the Server. If client is not connected, will create LoginDialog
*/
public void send() {
if(!client.isConnected())
{
LoginDialog loginDlg = new LoginDialog(args, this);
loginDlg.setVisible(true);
}
client.handleMessageFromClientUI(messageTxF.getText());
messageTxF.setText("");
}
/**
* Main method, creates the JFrame for GUIConsole.
* @param args
* @param args[0] = host (Default: localhost)
* @param args[1] = port (Default: 5555)
* @param args[2] = userName (Default: User)
*/
@SuppressWarnings("unused")
public static void main(String[] args) {
String userName = "", host = "";
int port = 0;
try {
host = args[0];
} catch (ArrayIndexOutOfBoundsException e) {
args[0] = "localhost";
}
try {
port = Integer.parseInt(args[1]);
} catch (Throwable t) {
args[1] = DEFAULT_PORT + "";
}
try {
userName = args[2];
} catch (Throwable t) {
args[2] = "User";
}
GUIConsole clientConsole = new GUIConsole(args);
}
}
| src/client/GUIConsole.java | package client;
import game.TicTacToe;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.io.IOException;
//import java.util.Scanner;
/**
* @author marshall0530
*/
/**
* @author Tyler M
*
*/
public class GUIConsole extends JFrame implements ChatIF {
final public static int DEFAULT_PORT = 5555;
private static final long serialVersionUID = 1L;
private JButton sendB = new JButton("Send");
private JButton quitB = new JButton("Quit");
private JTextField messageTxF = new JTextField("");
private JTextArea messageList = new JTextArea();
private ChatClient client;
private Profile profile = new Profile();
private String[] args;
private String[] roomList;
//Makes the client accessible from LoginDialog
public ChatClient getChatClient()
{
return this.client;
}
public void setChatClient(ChatClient chatClient)
{
this.client = chatClient;
}
public String[] getRoomList() {
return roomList;
}
public void setRoomList(String[] roomList) {
this.roomList = roomList;
}
public String[] getArgs()
{
return this.args;
}
public GUIConsole ( String[] args)
{
super("Simple Chat GUI");
this.args = args;
setSize(300, 400);
messageList.setWrapStyleWord(true);
messageList.setSize(300, 1000);
profile.setFont("Tahoma",Font.PLAIN,12);
messageList.setFont(profile.getFont());
JComboBox roomList = new JComboBox();
setLayout( new BorderLayout(5,5));
final Panel southBox = new Panel();
final Panel southInput = new Panel();
final Panel southButtons = new Panel();
add( "Center", messageList );
add( "South" , southBox);
southBox.setLayout( new GridLayout(3,1,5,5));
southBox.add(southInput);
southInput.setLayout(new GridLayout(1, 1, 5, 5));
southInput.add(messageTxF);
southBox.add(southButtons);
southButtons.setLayout(new GridLayout(1, 2, 5, 5));
southButtons.add(quitB); southButtons.add(sendB);
southBox.add(roomList);
messageList.setLineWrap(true);
messageList.setEditable(false);
JScrollPane scroll = new JScrollPane (messageList);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
add(scroll);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation(dim.width/2-this.getSize().width/2, dim.height/2-this.getSize().height/2);
// String[] petStrings = { "Bird", "Cat", "Dog", "Rabbit", "Pig" };
//Create the combo box, select item at index 4.
//Indices start at 0, so 4 specifies the pig.
// roomList.addActionListener(this);
//This creates the Login Dialog which will establish the connection and welcomes the user.
LoginDialog loginDlg = new LoginDialog(args, this);
loginDlg.setVisible(true);
// Handles dropdown box
roomList.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JComboBox<String[]> roomList = (JComboBox<String[]>) e.getSource();
roomList.removeAll();
roomList.addItem(getRoomList());
}
});
//This handles closing the client with the X Button
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent windowEvent) {
if (JOptionPane.showConfirmDialog(southBox,
"Are you sure to close this window?", "Really Closing?",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION){
client.handleMessageFromClientUI("Good Bye!");
try
{
client.closeConnection();
}
catch (IOException e)
{
display("Unable to close connection, terminating client");
}
finally
{
System.exit(0);
}
}
}});
// This handles the Enter Key being pressed when sending message
messageTxF.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleGUIMessage();
}
});
// This handles the Send Button being pressed, same as above
sendB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
handleGUIMessage();
}
});
//This handles when the Quit button is pressed
quitB.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (JOptionPane.showConfirmDialog(southBox,
"Are you sure to close this window?",
"Really Closing?", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
client.handleMessageFromClientUI("Good Bye!");
try {
client.sendToServer("#logout");
} catch (IOException ioe) {
display("Unable to close connection, terminating client");
} finally {
System.exit(0);
}
}
}
});
setVisible(true);
}
/**
* Method handles when the GUI tries to send a message.
*/
private void handleGUIMessage() {
if (!messageTxF.getText().isEmpty()) {
String msg = messageTxF.getText();
System.out.println("msg: " + msg);
if(msg.indexOf("#") == 0)
handleGUIClientCommand(msg);
else
send();
}
}
/**
* Handles commands from within the GUI that pertains to only the GUI.
*
* @param msg The command being sent for GUIConsole to handle.
*/
private void handleGUIClientCommand(String msg) {
//makes command case insensitive
msg = msg.toLowerCase().trim();
//declarations
String cmd = "";
cmd = (msg.indexOf(" ") == -1) ? msg : msg.substring(0, msg.indexOf(" "));
int end = msg.length();
int space = (msg.indexOf(" ") == -1) ? end : msg.indexOf(" ");
String truncMsg = msg.substring(space, end).trim();
switch (cmd)
{
case "#game":
client.setGame(new TicTacToe(this));
client.getGame().setOnline(true);
try {
client.tryToSendToServer(msg);
} catch (Exception e) {
e.printStackTrace();
display("Failed to send command to server.");
}
break;
case "#fontsize":
profile.setFontSize(Integer.parseInt(truncMsg));
messageList.setFont(profile.getFont());
break;
case "#fontstyle":
profile.setFontStyle(truncMsg);
messageList.setFont(profile.getFont());
break;
case "#fontname":
profile.setFontName((truncMsg));
messageList.setFont(profile.getFont());
break;
default:
send();
}
messageTxF.setText("");
}
/**
* Displays message in GUIConsole's Message List.
*/
@Override
public void display(String message) {
messageList.insert("> " + message + "\n", 0);
}
/**
* Displays message in GUIConsole's Message List with a UserName before the message.
*/
@Override
public void display(String message, String user)
{
messageList.insert(user + "> " + message + "\n", 0);
}
/**
* Method to send message to the Server. If client is not connected, will create LoginDialog
*/
public void send() {
if(!client.isConnected())
{
LoginDialog loginDlg = new LoginDialog(args, this);
loginDlg.setVisible(true);
}
client.handleMessageFromClientUI(messageTxF.getText());
messageTxF.setText("");
}
/**
* Main method, creates the JFrame for GUIConsole.
* @param args
* @param args[0] = host (Default: localhost)
* @param args[1] = port (Default: 5555)
* @param args[2] = userName (Default: User)
*/
@SuppressWarnings("unused")
public static void main(String[] args) {
String userName = "", host = "";
int port = 0;
try {
host = args[0];
} catch (ArrayIndexOutOfBoundsException e) {
args[0] = "localhost";
}
try {
port = Integer.parseInt(args[1]);
} catch (Throwable t) {
args[1] = DEFAULT_PORT + "";
}
try {
userName = args[2];
} catch (Throwable t) {
args[2] = "User";
}
GUIConsole clientConsole = new GUIConsole(args);
}
}
| Attempted to make a ComboBox of roomList
not working yet.
| src/client/GUIConsole.java | Attempted to make a ComboBox of roomList | <ide><path>rc/client/GUIConsole.java
<ide> private ChatClient client;
<ide> private Profile profile = new Profile();
<ide> private String[] args;
<del> private String[] roomList;
<del>
<add>
<add>
<add> private String[] roomArray;
<add> private JButton refresh = new JButton("Refresh Rooms");
<add> private JComboBox roomList = new JComboBox();
<ide>
<ide>
<ide> //Makes the client accessible from LoginDialog
<add> public void setRoomList(JComboBox arg)
<add> {
<add> this.roomList = arg;
<add> }
<add>
<add> public JComboBox getRoomList()
<add> {
<add> return this.roomList;
<add> }
<add>
<ide> public ChatClient getChatClient()
<ide> {
<ide> return this.client;
<ide> this.client = chatClient;
<ide> }
<ide>
<del> public String[] getRoomList() {
<del> return roomList;
<del> }
<del>
<del> public void setRoomList(String[] roomList) {
<del> this.roomList = roomList;
<add> public String[] getRoomArray() {
<add> return roomArray;
<add> }
<add>
<add> public void setRoomArray(String[] roomArray) {
<add> this.roomArray = roomArray;
<ide> }
<ide>
<ide> public String[] getArgs()
<ide> profile.setFont("Tahoma",Font.PLAIN,12);
<ide> messageList.setFont(profile.getFont());
<ide>
<del> JComboBox roomList = new JComboBox();
<del>
<del>
<del>
<del> setLayout( new BorderLayout(5,5));
<add>
<add>// roomList.
<add> final Panel roomBox = new Panel();
<add>
<add>
<add> setLayout( new BorderLayout(0,0));
<ide> final Panel southBox = new Panel();
<ide> final Panel southInput = new Panel();
<ide> final Panel southButtons = new Panel();
<add> add( "North" , roomBox);
<add> roomBox.setLayout(new GridLayout(1, 2, 5, 5));
<add> roomBox.add(roomList);
<add> roomBox.add(refresh);
<ide> add( "Center", messageList );
<del>
<ide> add( "South" , southBox);
<del> southBox.setLayout( new GridLayout(3,1,5,5));
<del> southBox.add(southInput);
<del> southInput.setLayout(new GridLayout(1, 1, 5, 5));
<del> southInput.add(messageTxF);
<del> southBox.add(southButtons);
<del> southButtons.setLayout(new GridLayout(1, 2, 5, 5));
<del> southButtons.add(quitB); southButtons.add(sendB);
<del> southBox.add(roomList);
<add> southBox.setLayout( new GridLayout(2,1,5,5));
<add> southBox.add(southInput);
<add> southInput.setLayout(new GridLayout(1, 1, 5, 5));
<add> southInput.add(messageTxF);
<add> southBox.add(southButtons);
<add> southButtons.setLayout(new GridLayout(1, 2, 5, 5));
<add> southButtons.add(quitB); southButtons.add(sendB);
<add>
<ide>
<ide>
<ide>
<ide> Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
<ide> this.setLocation(dim.width/2-this.getSize().width/2, dim.height/2-this.getSize().height/2);
<ide>
<add>
<add> refresh.addActionListener(new ActionListener() {
<add> public void actionPerformed(ActionEvent e) {
<add> setRoomList(new javax.swing.JComboBox());
<add> getRoomList().setModel(new javax.swing.DefaultComboBoxModel(client.getRoomList()));
<add> getRoomList().setName("roomList");
<add> }
<add> });
<ide>
<del>// String[] petStrings = { "Bird", "Cat", "Dog", "Rabbit", "Pig" };
<del>
<del> //Create the combo box, select item at index 4.
<del> //Indices start at 0, so 4 specifies the pig.
<del>
<del>// roomList.addActionListener(this);
<ide>
<ide> //This creates the Login Dialog which will establish the connection and welcomes the user.
<ide> LoginDialog loginDlg = new LoginDialog(args, this);
<ide> loginDlg.setVisible(true);
<ide>
<ide>
<del> // Handles dropdown box
<add> // Handles Combo Box
<ide> roomList.addActionListener(new ActionListener() {
<ide> public void actionPerformed(ActionEvent e) {
<del> JComboBox<String[]> roomList = (JComboBox<String[]>) e.getSource();
<del> roomList.removeAll();
<del> roomList.addItem(getRoomList());
<add>// JComboBox<String[]> roomList = (JComboBox<String[]>) e.getSource();
<add>// roomList.removeAll();
<add>// ((JComboBox) e.getSource()).addItem(client.getRoomList());
<add>// ((JComboBox) e.getSource()).setModel(new DefaultComboBoxModel(client.getRoomList()));
<ide> }
<ide> });
<ide> |
|
Java | apache-2.0 | 97c7ec7c4e8f9679ebdc85ede96be60ae450b68f | 0 | jerome79/OG-Platform,jerome79/OG-Platform,codeaudit/OG-Platform,codeaudit/OG-Platform,nssales/OG-Platform,jeorme/OG-Platform,DevStreet/FinanceAnalytics,jerome79/OG-Platform,McLeodMoores/starling,jeorme/OG-Platform,ChinaQuants/OG-Platform,ChinaQuants/OG-Platform,DevStreet/FinanceAnalytics,ChinaQuants/OG-Platform,ChinaQuants/OG-Platform,McLeodMoores/starling,nssales/OG-Platform,jerome79/OG-Platform,codeaudit/OG-Platform,McLeodMoores/starling,jeorme/OG-Platform,DevStreet/FinanceAnalytics,jeorme/OG-Platform,McLeodMoores/starling,DevStreet/FinanceAnalytics,nssales/OG-Platform,codeaudit/OG-Platform,nssales/OG-Platform | /**
* Copyright (C) 2009 - 2009 by OpenGamma Inc.
*
* Please see distribution for license.
*/
package com.opengamma.util;
/**
* Utility methods for working with threads.
*
* @author kirk
*/
public final class ThreadUtil {
private ThreadUtil() {
}
/**
* Attempt to join the thread specified safely.
*
* @param t The thread to join.
* @return {@code true} if the join succeeded, or {@code false} if
* we went past the timeout.
*/
public static boolean safeJoin(Thread t, long msTimeout) {
if(!t.isAlive()) {
return true;
}
try {
t.join(msTimeout);
} catch (InterruptedException e) {
// Clear the interrupted state.
Thread.interrupted();
}
return !t.isAlive();
}
}
| src/com/opengamma/util/ThreadUtil.java | /**
* Copyright (C) 2009 - 2009 by OpenGamma Inc.
*
* Please see distribution for license.
*/
package com.opengamma.util;
/**
* Utility methods for working with threads.
*
* @author kirk
*/
public final class ThreadUtil {
private ThreadUtil() {
}
/**
* Attempt to join the thread specified safely.
*
* @param t The thread to join.
* @return {@code true} if the join succeeded, or {@code false} if
* we went past the timeout.
*/
public static boolean safeJoin(Thread t, long msTimeout) {
try {
t.join(msTimeout);
} catch (InterruptedException e) {
// Clear the interrupted state.
Thread.interrupted();
}
return !t.isAlive();
}
}
| Have safeJoin() check for already being terminated before attempting to join.
| src/com/opengamma/util/ThreadUtil.java | Have safeJoin() check for already being terminated before attempting to join. | <ide><path>rc/com/opengamma/util/ThreadUtil.java
<ide> * we went past the timeout.
<ide> */
<ide> public static boolean safeJoin(Thread t, long msTimeout) {
<add> if(!t.isAlive()) {
<add> return true;
<add> }
<ide> try {
<ide> t.join(msTimeout);
<ide> } catch (InterruptedException e) { |
Subsets and Splits