answer
stringlengths 17
10.2M
|
|---|
package com.example;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class TablonController {
//la URL JDBC con el valor jdbc:h2:mem:testdb se puede acceder a la
@Autowired
private AccesoRepository repository;
@PostConstruct
public void init() {
repository.save(new Acceso("Pepe", "1234567"));
repository.save(new Acceso("Juan", "hola123"));
}
@RequestMapping("/")
public String presentacion(Model model, Pageable page) {
model.addAttribute("acceso", repository.findAll(page));
return "presentacion";
}
}
|
package org.bimserver.cache;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.bimserver.longaction.DownloadParameters;
import org.bimserver.plugins.serializers.RemovableFileOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DiskCacheOutputStream extends RemovableFileOutputStream {
private static final Logger LOGGER = LoggerFactory.getLogger(DiskCacheOutputStream.class);
private DiskCacheManager diskCacheManager;
private Path file;
private Path tempFile;
private final CountDownLatch latch = new CountDownLatch(1);
private final DownloadParameters downloadParameters;
public DiskCacheOutputStream(DiskCacheManager diskCacheManager, Path file, DownloadParameters downloadParameters) throws FileNotFoundException {
super(file.getParent().resolve(file.getFileName().toString() + ".__tmp"));
this.tempFile = file.getParent().resolve(file.getFileName().toString() + ".__tmp");
this.diskCacheManager = diskCacheManager;
this.file = file;
this.downloadParameters = downloadParameters;
}
public DownloadParameters getDownloadParameters() {
return downloadParameters;
}
public void waitForFinish() throws InterruptedException {
latch.await(30, TimeUnit.MINUTES);
}
@Override
public void close() throws IOException {
super.close();
LOGGER.info("Renaming temp file " + tempFile.getFileName().toString() + " to " + file.getFileName().toString());
Files.move(tempFile, file);
diskCacheManager.doneGenerating(this);
latch.countDown();
}
@Override
public void remove() throws IOException {
super.remove();
Files.delete(this.tempFile);
diskCacheManager.remove(this);
latch.countDown();
}
public String getName() {
return file.getFileName().toString();
}
}
|
package org.bimserver.schemaconverter;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EAnnotation;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EClassifier;
import org.eclipse.emf.ecore.EDataType;
import org.eclipse.emf.ecore.EEnum;
import org.eclipse.emf.ecore.EEnumLiteral;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.ecore.EcoreFactory;
import org.eclipse.emf.ecore.EcorePackage;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.xmi.impl.XMLResourceFactoryImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import nl.tue.buildingsmart.emf.DerivedReader;
import nl.tue.buildingsmart.express.parser.SchemaLoader;
import nl.tue.buildingsmart.schema.AggregationType;
import nl.tue.buildingsmart.schema.ArrayType;
import nl.tue.buildingsmart.schema.Attribute;
import nl.tue.buildingsmart.schema.BaseType;
import nl.tue.buildingsmart.schema.BinaryType;
import nl.tue.buildingsmart.schema.BooleanType;
import nl.tue.buildingsmart.schema.DefinedType;
import nl.tue.buildingsmart.schema.DerivedAttribute2;
import nl.tue.buildingsmart.schema.EntityDefinition;
import nl.tue.buildingsmart.schema.EnumerationType;
import nl.tue.buildingsmart.schema.ExplicitAttribute;
import nl.tue.buildingsmart.schema.IntegerBound;
import nl.tue.buildingsmart.schema.IntegerType;
import nl.tue.buildingsmart.schema.InverseAttribute;
import nl.tue.buildingsmart.schema.LogicalType;
import nl.tue.buildingsmart.schema.NamedType;
import nl.tue.buildingsmart.schema.NumberType;
import nl.tue.buildingsmart.schema.RealType;
import nl.tue.buildingsmart.schema.SchemaDefinition;
import nl.tue.buildingsmart.schema.SelectType;
import nl.tue.buildingsmart.schema.SimpleType;
import nl.tue.buildingsmart.schema.StringType;
import nl.tue.buildingsmart.schema.UnderlyingType;
public class Express2EMF {
private static final Logger LOGGER = LoggerFactory.getLogger(Express2EMF.class);
private final SchemaDefinition schema;
private final EcoreFactory eFactory;
private final EcorePackage ePackage;
private final EPackage schemaPack;
private final Map<EClass, Set<EClass>> directSubTypes = new HashMap<EClass, Set<EClass>>();
private final Map<String, EDataType> simpleTypeReplacementMap = new HashMap<String, EDataType>();
private EEnum tristate;
public Express2EMF(File schemaFileName, String modelName, String nsUri) {
schema = new SchemaLoader(schemaFileName.getAbsolutePath()).getSchema();
eFactory = EcoreFactory.eINSTANCE;
ePackage = EcorePackage.eINSTANCE;
schemaPack = eFactory.createEPackage();
try {
new DerivedReader(schemaFileName, schema);
} catch (FileNotFoundException e) {
LOGGER.error("", e);
}
schemaPack.setName(modelName);
schemaPack.setNsPrefix("iai");
schemaPack.setNsURI(nsUri);
createTristate();
addClasses();
addSupertypes();
addSimpleTypes();
addDerivedTypes();
addEnumerations();
addHackedTypes();
addSelects();
addAttributes();
addInverses();
EClass ifcBooleanClass = (EClass) schemaPack.getEClassifier("IfcBoolean");
ifcBooleanClass.getESuperTypes().add((EClass) schemaPack.getEClassifier("IfcValue"));
doRealDerivedAttributes();
clean();
}
private void addHackedTypes() {
Iterator<DefinedType> typeIter = schema.getTypes().iterator();
while (typeIter.hasNext()) {
DefinedType type = typeIter.next();
if (type.getName().equals("IfcCompoundPlaneAngleMeasure")) {
// We model this by using a wrapper class
// EClass ifcCompoundPlaneAngleMeasure = getOrCreateEClass(type.getName());
// DefinedType integerType = new DefinedType("Integer");
// integerType.setDomain(new IntegerType());
// EAttribute attribute = modifySimpleType(integerType, ifcCompoundPlaneAngleMeasure);
// attribute.setUpperBound(4);
// ifcCompoundPlaneAngleMeasure.getEAnnotations().add(createWrappedAnnotation());
} else if (type.getName().equals("IfcComplexNumber")) {
// We model this by using a wrapper class
EClass ifcComplexNumber = getOrCreateEClass(type.getName());
DefinedType realType = new DefinedType("Real");
realType.setDomain(new RealType());
EAttribute attribute = modifySimpleType(realType, ifcComplexNumber);
ifcComplexNumber.getEStructuralFeature("wrappedValueAsString").setUpperBound(2);
attribute.setUpperBound(2);
ifcComplexNumber.getEAnnotations().add(createWrappedAnnotation());
} else if (type.getName().equals("IfcNullStyle")) {
// We cannot simply make this an enum because it is defined as a subtype(select) of IfcPresentationStyleSelect, so we use a wrapper here, both the wrapper and
EClassifier ifcNullStyleEnum = schemaPack.getEClassifier("IfcNullStyle");
ifcNullStyleEnum.setName("IfcNullStyleEnum");
EClass ifcNullStyleWrapper = getOrCreateEClass(type.getName());
EAttribute wrappedValue = eFactory.createEAttribute();
wrappedValue.setName("wrappedValue");
wrappedValue.setEType(ifcNullStyleEnum);
ifcNullStyleWrapper.getEAnnotations().add(createWrappedAnnotation());
ifcNullStyleWrapper.getEStructuralFeatures().add(wrappedValue);
} else if (type.getName().equals("IfcLineIndex")) {
EClass ifcLineIndex = getOrCreateEClass(type.getName());
DefinedType realType = new DefinedType("IfcPositiveInteger");
realType.setDomain(new IntegerType());
EAttribute attribute = modifySimpleType(realType, ifcLineIndex);
attribute.setLowerBound(2);
attribute.setUpperBound(-1);
ifcLineIndex.getEAnnotations().add(createWrappedAnnotation());
} else if (type.getName().equals("IfcArcIndex")) {
EClass ifcArcIndex = getOrCreateEClass(type.getName());
DefinedType realType = new DefinedType("IfcPositiveInteger");
realType.setDomain(new IntegerType());
EAttribute attribute = modifySimpleType(realType, ifcArcIndex);
attribute.setUpperBound(3);
attribute.setLowerBound(3);
ifcArcIndex.getEAnnotations().add(createWrappedAnnotation());
}
}
}
private EAnnotation createWrappedAnnotation() {
EAnnotation wrappedAnnotation = eFactory.createEAnnotation();
wrappedAnnotation.setSource("wrapped");
return wrappedAnnotation;
}
private void clean() {
Iterator<EClassifier> iterator = schemaPack.getEClassifiers().iterator();
while (iterator.hasNext()) {
EClassifier eClassifier = iterator.next();
if (eClassifier instanceof EClass) {
EClass eClass = (EClass) eClassifier;
if (eClass.getEAnnotation("wrapped") != null) {
if (eClass.getESuperTypes().size() == 1) {
// iterator.remove();
}
}
}
}
}
private void doRealDerivedAttributes() {
for (EntityDefinition entityDefinition : schema.getEntities()) {
for (DerivedAttribute2 attributeName : entityDefinition.getDerivedAttributes().values()) {
EClass eClass = (EClass) schemaPack.getEClassifier(entityDefinition.getName());
// EStructuralFeature derivedAttribute =
// eFactory.createEReference();
if (attributeName.getType() != null && !attributeName.hasSuper()) {
// if (attributeName.getType() instanceof EntityDefinition)
// derivedAttribute.setEType(schemaPack.getEClassifier(((EntityDefinition)
// attributeName.getType()).getName()));
// } else if (attributeName.getType() instanceof
// IntegerType) {
// derivedAttribute.setEType(schemaPack.getEClassifier("IfcInteger"));
// } else if (attributeName.getType() instanceof RealType) {
// derivedAttribute.setEType(schemaPack.getEClassifier("IfcReal"));
// } else if (attributeName.getType() instanceof
// LogicalType) {
// derivedAttribute.setEType(schemaPack.getEClassifier("IfcLogical"));
if (attributeName.getType() instanceof DefinedType) {
EClassifier eType = schemaPack.getEClassifier(((DefinedType) attributeName.getType()).getName());
boolean found = false;
for (EClass eSuperType : eClass.getEAllSuperTypes()) {
if (eSuperType.getEStructuralFeature(attributeName.getName()) != null) {
found = true;
break;
}
}
if (eType.getEAnnotation("wrapped") != null) {
if (!found) {
EAttribute eAttribute = eFactory.createEAttribute();
eAttribute.setDerived(true);
eAttribute.setName(attributeName.getName());
if (eAttribute.getName().equals("RefLatitude") || eAttribute.getName().equals("RefLongitude")) {
eAttribute.setUpperBound(3);
eAttribute.setUnique(false);
}
EClassifier type = ((EClass) eType).getEStructuralFeature("wrappedValue").getEType();
eAttribute.setEType(type);
eAttribute.setUnsettable(true); // TODO find out
// if its
// optional
eClass.getEStructuralFeatures().add(eAttribute);
if (type == EcorePackage.eINSTANCE.getEDouble()) {
EAttribute doubleStringAttribute = eFactory.createEAttribute();
doubleStringAttribute.setName(attributeName.getName() + "AsString");
doubleStringAttribute.getEAnnotations().add(createAsStringAnnotation());
doubleStringAttribute.getEAnnotations().add(createHiddenAnnotation());
doubleStringAttribute.setUnsettable(true); // TODO
// find
// out
// its
// optional
doubleStringAttribute.setEType(EcorePackage.eINSTANCE.getEString());
eClass.getEStructuralFeatures().add(doubleStringAttribute);
}
}
} else {
if (!found) {
EReference eReference = eFactory.createEReference();
eReference.setName(attributeName.getName());
eReference.setDerived(true);
eReference.setUnsettable(true);
eReference.setEType(eType);
eClass.getEStructuralFeatures().add(eReference);
}
}
// derivedAttribute.setEType(eType);
}
}
// derivedAttribute.setName(attributeName.getName());
// derivedAttribute.setDerived(true);
// derivedAttribute.setTransient(true);
// derivedAttribute.setVolatile(true);
// if (attributeName.isCollection()) {
// derivedAttribute.setUpperBound(-1);
// EAnnotation annotation = eFactory.createEAnnotation();
// annotation.getDetails().put("code",
// attributeName.getExpressCode());
// derivedAttribute.getEAnnotations().add(annotation);
// if (eClass.getEStructuralFeature(derivedAttribute.getName())
// == null) {
// eClass.getEStructuralFeatures().add(derivedAttribute);
}
}
}
private EAnnotation createHiddenAnnotation() {
EAnnotation hiddenAnnotation = EcoreFactory.eINSTANCE.createEAnnotation();
hiddenAnnotation.setSource("hidden");
return hiddenAnnotation;
}
private EAnnotation createAsStringAnnotation() {
EAnnotation asStringAnnotation = eFactory.createEAnnotation();
asStringAnnotation.setSource("asstring");
return asStringAnnotation;
}
private void createTristate() {
tristate = eFactory.createEEnum();
tristate.setName("Tristate");
EEnumLiteral trueLiteral = eFactory.createEEnumLiteral();
trueLiteral.setName("TRUE");
trueLiteral.setValue(0);
EEnumLiteral falseLiteral = eFactory.createEEnumLiteral();
falseLiteral.setName("FALSE");
falseLiteral.setValue(1);
EEnumLiteral undefinedLiteral = eFactory.createEEnumLiteral();
undefinedLiteral.setName("UNDEFINED");
undefinedLiteral.setValue(2);
tristate.getELiterals().add(trueLiteral);
tristate.getELiterals().add(falseLiteral);
tristate.getELiterals().add(undefinedLiteral);
schemaPack.getEClassifiers().add(tristate);
}
private void addInverses() {
Iterator<EntityDefinition> entIter = schema.getEntities().iterator();
while (entIter.hasNext()) {
EntityDefinition ent = (EntityDefinition) entIter.next();
Iterator<Attribute> attribIter = ent.getAttributes(false).iterator();
EClass cls = (EClass) schemaPack.getEClassifier(ent.getName());
// if (ent.getName().equals("IfcRepresentation")) {
// InverseAttribute attrib = new
// InverseAttribute("LayerAssignments", ent);
// EntityDefinition entityBN =
// schema.getEntityBN("IfcPresentationLayerAssignment");
// attrib.setDomain(entityBN);
// attrib.setInverted_attr((ExplicitAttribute)entityBN.getAttributeBN
// ("AssignedItems"));
// addInverseAttribute(attrib, cls);
// EClass ifcLayeredItem =
// (EClass)schemaPack.getEClassifier("IfcLayeredItem");
// EReference createEReference = eFactory.createEReference();
// createEReference.setName("LayerAssignments");
// EClassifier classifier =
// schemaPack.getEClassifier("IfcPresentationLayerAssignment");
// createEReference.setEType(classifier);
// EReference structuralFeature =
// (EReference)((EClass)classifier).getEStructuralFeature
// ("AssignedItems");
// createEReference.setEOpposite(structuralFeature);
// structuralFeature.setEOpposite(createEReference);
// ifcLayeredItem.getEStructuralFeatures().add(createEReference);
while (attribIter.hasNext()) {
Attribute attrib = (Attribute) attribIter.next();
// if (ent.getName().equals("IfcRepresentationItem") &&
// attrib.getName().equals("LayerAssignments")) {
// } else {
if (attrib instanceof InverseAttribute) {
addInverseAttribute(attrib, cls);
}
}
}
}
private void addInverseAttribute(Attribute attrib, EClass cls) {
InverseAttribute inverseAttribute = (InverseAttribute) attrib;
EReference eRef = eFactory.createEReference();
eRef.setUnsettable(true); // Inverses are always optional?
eRef.getEAnnotations().add(createInverseAnnotation());
eRef.setName(attrib.getName());
if (inverseAttribute.getMax_cardinality() != null) {
IntegerBound max_cardinality = (IntegerBound) inverseAttribute.getMax_cardinality();
if (max_cardinality.getBound_value() == -1) {
eRef.setUpperBound(max_cardinality.getBound_value());
} else {
eRef.setUpperBound(max_cardinality.getBound_value() + 1);
}
}
String type = (inverseAttribute).getDomain().getName();
EClass classifier = (EClass) schemaPack.getEClassifier(type);
eRef.setEType(classifier);
String reverseName = inverseAttribute.getInverted_attr().getName();
EReference reference = (EReference) classifier.getEStructuralFeature(reverseName);
reference.getEAnnotations().add(createInverseAnnotation());
if (eRef.getEType() == classifier && reference.getEType() == cls) {
if (eRef.isMany()) {
eRef.setUnique(true);
}
if (reference.isMany()) {
reference.setUnique(true);
}
reference.setEOpposite(eRef);
eRef.setEOpposite(reference);
} else {
System.out.println("Inverse mismatch");
System.out.println(classifier.getName() + "." + reference.getName() + " => " + cls.getName() + "." + eRef.getName());
}
cls.getEStructuralFeatures().add(eRef);
}
private EAnnotation createInverseAnnotation() {
EAnnotation eAnnotation = EcoreFactory.eINSTANCE.createEAnnotation();
eAnnotation.setSource("inverse");
return eAnnotation;
}
private void addAttributes() {
Iterator<EntityDefinition> entIter = schema.getEntities().iterator();
while (entIter.hasNext()) {
EntityDefinition ent = (EntityDefinition) entIter.next();
Iterator<Attribute> attribIter = ent.getAttributes(false).iterator();
while (attribIter.hasNext()) {
Attribute attrib = (Attribute) attribIter.next();
if (attrib instanceof ExplicitAttribute) {
processAttribute(ent, attrib);
}
}
}
}
private void processAttribute(EntityDefinition ent, Attribute attrib) {
if (attrib.getName().equals("RasterCode")) {
System.out.println();
}
ExplicitAttribute expAttrib = (ExplicitAttribute) attrib;
BaseType domain = expAttrib.getDomain();
if (ent.getName().equals("IfcRelConnectsPathElements") && (attrib.getName().equals("RelatingPriorities") || attrib.getName().equals("RelatedPriorities"))) {
// HACK, express parser does not recognize LIST [0:?] OF NUMBER
EClass cls = (EClass) schemaPack.getEClassifier(ent.getName());
EAttribute eAttribute = eFactory.createEAttribute();
eAttribute.setName(attrib.getName());
eAttribute.setUpperBound(-1);
eAttribute.setUnique(false);
eAttribute.setEType(EcorePackage.eINSTANCE.getELong());
eAttribute.setUnsettable(expAttrib.isOptional());
cls.getEStructuralFeatures().add(eAttribute);
return;
}
if (domain instanceof NamedType) {
NamedType nt = (NamedType) domain;
if (nt instanceof EnumerationType) {
EAttribute enumAttrib = eFactory.createEAttribute();
enumAttrib.setUnsettable(expAttrib.isOptional());
enumAttrib.setName(attrib.getName());
EClassifier eType = schemaPack.getEClassifier(nt.getName());
enumAttrib.setEType(eType);
EClass cls = (EClass) schemaPack.getEClassifier(ent.getName());
cls.getEStructuralFeatures().add(enumAttrib);
} else {
EClass eType = (EClass) schemaPack.getEClassifier(nt.getName());
EClass cls = (EClass) schemaPack.getEClassifier(ent.getName());
// If the DEFINED type is already a wrapped value, we prefer not to use wrappedValue indirection
boolean wrapped = superTypeIsWrapped(eType);
if (wrapped) {
EAttribute eAttribute = eFactory.createEAttribute();
eAttribute.setUnsettable(expAttrib.isOptional());
eAttribute.setName(attrib.getName());
if (eAttribute.getName().equals("RefLatitude") || eAttribute.getName().equals("RefLongitude")) {
eAttribute.setUpperBound(3);
eAttribute.setUnique(false);
}
EClassifier type = ((EClass) eType).getEStructuralFeature("wrappedValue").getEType();
eAttribute.setEType(type);
cls.getEStructuralFeatures().add(eAttribute);
if (type == EcorePackage.eINSTANCE.getEDouble()) {
EAttribute doubleStringAttribute = eFactory.createEAttribute();
doubleStringAttribute.setName(attrib.getName() + "AsString");
doubleStringAttribute.getEAnnotations().add(createAsStringAnnotation());
doubleStringAttribute.getEAnnotations().add(createHiddenAnnotation());
doubleStringAttribute.setEType(EcorePackage.eINSTANCE.getEString());
doubleStringAttribute.setUnsettable(expAttrib.isOptional());
cls.getEStructuralFeatures().add(doubleStringAttribute);
}
} else {
EReference eRef = eFactory.createEReference();
eRef.setName(attrib.getName());
// Hardcoded hack to fix multiplicity for
// IfcSpatialStructureElement which references
// RefLatitude and RefLongitude
eRef.setUnsettable(expAttrib.isOptional());
eRef.setEType(eType);
cls.getEStructuralFeatures().add(eRef);
}
}
} else if (domain instanceof AggregationType) {
BaseType bt = ((AggregationType) domain).getElement_type();
EClass cls = (EClass) schemaPack.getEClassifier(ent.getName());
if (bt instanceof NamedType) {
NamedType nt = (NamedType) bt;
EClassifier eType = schemaPack.getEClassifier(nt.getName());
if (superTypeIsWrapped((EClass) eType)) {
EAttribute eAttribute = eFactory.createEAttribute();
eAttribute.setName(attrib.getName());
if (eAttribute.getName().equals("RefLatitude") || eAttribute.getName().equals("RefLongitude")) {
eAttribute.setUpperBound(3);
} else {
eAttribute.setUpperBound(-1);
}
EClassifier type = ((EClass) eType).getEStructuralFeature("wrappedValue").getEType();
eAttribute.setEType(type);
eAttribute.setUnsettable(expAttrib.isOptional());
eAttribute.setUnique(false);
cls.getEStructuralFeatures().add(eAttribute);
if (type == EcorePackage.eINSTANCE.getEDouble()) {
EAttribute doubleStringAttribute = eFactory.createEAttribute();
doubleStringAttribute.setName(attrib.getName() + "AsString");
doubleStringAttribute.getEAnnotations().add(createAsStringAnnotation());
doubleStringAttribute.getEAnnotations().add(createHiddenAnnotation());
doubleStringAttribute.setEType(EcorePackage.eINSTANCE.getEString());
doubleStringAttribute.setUpperBound(-1);
doubleStringAttribute.setUnsettable(expAttrib.isOptional());
doubleStringAttribute.setUpperBound(eAttribute.getUpperBound());
doubleStringAttribute.setUnique(false);
cls.getEStructuralFeatures().add(doubleStringAttribute);
}
} else if (eType == EcorePackage.eINSTANCE.getEDouble()) {
EAttribute eAttribute = eFactory.createEAttribute();
eAttribute.setName(attrib.getName());
eAttribute.setUnsettable(expAttrib.isOptional());
eAttribute.setUnique(false);
eAttribute.setEType(EcorePackage.eINSTANCE.getEAttribute());
cls.getEStructuralFeatures().add(eAttribute);
EAttribute doubleStringAttribute = eFactory.createEAttribute();
doubleStringAttribute.getEAnnotations().add(createHiddenAnnotation());
doubleStringAttribute.getEAnnotations().add(createAsStringAnnotation());
doubleStringAttribute.setName(attrib.getName() + "AsString");
doubleStringAttribute.setUpperBound(-1);
doubleStringAttribute.setEType(EcorePackage.eINSTANCE.getEString());
doubleStringAttribute.setUnsettable(expAttrib.isOptional());
doubleStringAttribute.setUpperBound(eAttribute.getUpperBound());
doubleStringAttribute.setUnique(false);
cls.getEStructuralFeatures().add(doubleStringAttribute);
} else {
EReference eRef = eFactory.createEReference();
eRef.setUpperBound(-1);
eRef.setName(attrib.getName());
// Hardcoded hack to fix multiplicity for
// IfcSpatialStructureElement which references
// RefLatitude and RefLongitude
eRef.setUnsettable(expAttrib.isOptional());
eRef.setEType(eType);
eRef.setUnique(false);
// EClass cls = (EClass)
// schemaPack.getEClassifier(ent.getName());
cls.getEStructuralFeatures().add(eRef);
}
// EClassifier eType = schemaPack.getEClassifier(nt.getName());
// eRef.setEType(eType);
// cls.getEStructuralFeatures().add(eRef);
} else if (bt instanceof RealType) {
EAttribute eAttribute = eFactory.createEAttribute();
eAttribute.setUnsettable(expAttrib.isOptional());
eAttribute.setName(attrib.getName());
eAttribute.setUpperBound(-1);
eAttribute.setUnique(false);
eAttribute.setEType(EcorePackage.eINSTANCE.getEDouble());
cls.getEStructuralFeatures().add(eAttribute);
EAttribute doubleStringAttribute = eFactory.createEAttribute();
doubleStringAttribute.getEAnnotations().add(createHiddenAnnotation());
doubleStringAttribute.getEAnnotations().add(createAsStringAnnotation());
doubleStringAttribute.setName(attrib.getName() + "AsString");
doubleStringAttribute.setUpperBound(-1);
doubleStringAttribute.setEType(EcorePackage.eINSTANCE.getEString());
doubleStringAttribute.setUnsettable(expAttrib.isOptional());
doubleStringAttribute.setUpperBound(eAttribute.getUpperBound());
doubleStringAttribute.setUnique(false);
cls.getEStructuralFeatures().add(doubleStringAttribute);
} else if (bt instanceof IntegerType) {
EAttribute eAttribute = eFactory.createEAttribute();
eAttribute.setName(attrib.getName());
eAttribute.setUpperBound(-1);
eAttribute.setUnique(false);
eAttribute.setEType(EcorePackage.eINSTANCE.getELong());
eAttribute.setUnsettable(expAttrib.isOptional());
cls.getEStructuralFeatures().add(eAttribute);
} else if (bt instanceof NumberType) {
EAttribute eAttribute = eFactory.createEAttribute();
eAttribute.setName(attrib.getName());
eAttribute.setUpperBound(-1);
eAttribute.setUnique(false);
eAttribute.setEType(EcorePackage.eINSTANCE.getELong());
eAttribute.setUnsettable(expAttrib.isOptional());
cls.getEStructuralFeatures().add(eAttribute);
} else if (bt instanceof LogicalType) {
EAttribute eAttribute = eFactory.createEAttribute();
eAttribute.setName(attrib.getName());
eAttribute.setUpperBound(-1);
eAttribute.setUnique(false);
eAttribute.setEType(EcorePackage.eINSTANCE.getEBoolean());
eAttribute.setUnsettable(expAttrib.isOptional());
cls.getEStructuralFeatures().add(eAttribute);
} else if (bt instanceof BinaryType) {
EAttribute eAttribute = eFactory.createEAttribute();
eAttribute.setUnsettable(expAttrib.isOptional());
eAttribute.setUpperBound(-1);
eAttribute.setName(attrib.getName());
eAttribute.setUnique(false);
eAttribute.setEType(EcorePackage.eINSTANCE.getEByteArray());
cls.getEStructuralFeatures().add(eAttribute);
} else if (bt == null) {
// These are the new 2-dimensional arrays in IFC4, there are 10 of them (more in add2)
addTwoDimensionalArray(ent.getName(), attrib.getName());
}
if (domain instanceof ArrayType) {
// TODO this is not yet implmented in simpelSDAI
// eAttrib.setLowerBound(((nl.tue.buildingsmart.express.dictionary
// .ArrayType)domain).getLower_index());
// One fix for this has been implemented in addHackedTypes
}
} else {
EClass cls = (EClass) schemaPack.getEClassifier(ent.getName());
if (domain == null) {
EAttribute eAttribute = eFactory.createEAttribute();
eAttribute.setUnsettable(expAttrib.isOptional());
eAttribute.setName(attrib.getName());
eAttribute.setEType(tristate);
cls.getEStructuralFeatures().add(eAttribute);
} else if (domain instanceof IntegerType) {
EAttribute eAttribute = eFactory.createEAttribute();
eAttribute.setUnsettable(expAttrib.isOptional());
eAttribute.setName(attrib.getName());
eAttribute.setEType(EcorePackage.eINSTANCE.getELong());
cls.getEStructuralFeatures().add(eAttribute);
} else if (domain instanceof LogicalType) {
EAttribute eAttribute = eFactory.createEAttribute();
eAttribute.setUnsettable(expAttrib.isOptional());
eAttribute.setName(attrib.getName());
eAttribute.setEType(EcorePackage.eINSTANCE.getEBoolean());
cls.getEStructuralFeatures().add(eAttribute);
} else if (domain instanceof RealType) {
EAttribute eAttribute = eFactory.createEAttribute();
eAttribute.setUnsettable(expAttrib.isOptional());
eAttribute.setName(attrib.getName());
eAttribute.setEType(EcorePackage.eINSTANCE.getEDouble());
cls.getEStructuralFeatures().add(eAttribute);
EAttribute eAttributeAsString = eFactory.createEAttribute();
eAttributeAsString.getEAnnotations().add(createAsStringAnnotation());
eAttributeAsString.getEAnnotations().add(createHiddenAnnotation());
eAttributeAsString.setUnsettable(expAttrib.isOptional());
eAttributeAsString.setName(attrib.getName() + "AsString");
eAttributeAsString.setEType(EcorePackage.eINSTANCE.getEString());
cls.getEStructuralFeatures().add(eAttributeAsString);
} else if (domain instanceof StringType) {
EAttribute eAttribute = eFactory.createEAttribute();
eAttribute.setUnsettable(expAttrib.isOptional());
eAttribute.setName(attrib.getName());
eAttribute.setEType(EcorePackage.eINSTANCE.getEString());
cls.getEStructuralFeatures().add(eAttribute);
} else if (domain instanceof BinaryType) {
EAttribute eAttribute = eFactory.createEAttribute();
eAttribute.setUnsettable(expAttrib.isOptional());
eAttribute.setName(attrib.getName());
eAttribute.setEType(EcorePackage.eINSTANCE.getEByteArray());
cls.getEStructuralFeatures().add(eAttribute);
} else {
throw new RuntimeException("Unknown type: " + domain);
}
}
}
private void addTwoDimensionalArray(String entityName, String attribName) {
EClassifier finalType = null;
if (entityName.equals("IfcBSplineSurface") && attribName.equals("ControlPointsList")) {
finalType = schemaPack.getEClassifier("IfcCartesianPoint");
} else if (entityName.equals("IfcCartesianPointList3D") && attribName.equals("CoordList")) {
finalType = schemaPack.getEClassifier("IfcLengthMeasure");
} else if (entityName.equals("IfcColourRgbList") && attribName.equals("ColourList")) {
finalType = schemaPack.getEClassifier("IfcNormalisedRatioMeasure");
} else if (entityName.equals("IfcIndexedTriangleTextureMap") && attribName.equals("TexCoordIndex")) {
finalType = EcorePackage.eINSTANCE.getELong();
} else if (entityName.equals("IfcRationalBSplineSurfaceWithKnots") && attribName.equals("WeightsData")) {
finalType = EcorePackage.eINSTANCE.getEDouble();
} else if (entityName.equals("IfcStructuralLoadConfiguration") && attribName.equals("Locations")) {
finalType = schemaPack.getEClassifier("IfcLengthMeasure");
} else if (entityName.equals("IfcTessellatedFaceSet") && attribName.equals("Normals")) {
finalType = schemaPack.getEClassifier("IfcParameterValue");
} else if (entityName.equals("IfcTextureVertexList") && attribName.equals("TexCoordsList")) {
finalType = schemaPack.getEClassifier("IfcParameterValue");
} else if (entityName.equals("IfcTriangulatedFaceSet") && attribName.equals("CoordIndex")) {
finalType = EcorePackage.eINSTANCE.getELong();
} else if (entityName.equals("IfcCartesianPointList2D") && attribName.equals("CoordList")) {
finalType = schemaPack.getEClassifier("IfcLengthMeasure");
} else if (entityName.equals("IfcIndexedPolygonalFaceWithVoids") && attribName.equals("InnerCoordIndices")) {
finalType = EcorePackage.eINSTANCE.getELong();
} else if (entityName.equals("IfcTriangulatedFaceSet") && attribName.equals("Normals")) {
finalType = schemaPack.getEClassifier("IfcParameterValue");
} else if (entityName.equals("IfcTriangulatedFaceSet") && attribName.equals("NormalIndex")) {
finalType = EcorePackage.eINSTANCE.getELong();
} else {
throw new RuntimeException("Unimplemented " + entityName + "." + attribName);
}
EClass containerClass = (EClass) schemaPack.getEClassifier("ListOf" + finalType.getName());
if (containerClass == null) {
containerClass = EcoreFactory.eINSTANCE.createEClass();
containerClass.setName("ListOf" + finalType.getName());
if (finalType.getEPackage() == EcorePackage.eINSTANCE) {
EAttribute finalAttribute = EcoreFactory.eINSTANCE.createEAttribute();
finalAttribute.setName("List");
finalAttribute.setEType(finalType);
finalAttribute.setUpperBound(-1);
containerClass.getEAttributes().add(finalAttribute);
if (finalType == EcorePackage.eINSTANCE.getEDouble()) {
EAttribute stringAttribute = EcoreFactory.eINSTANCE.createEAttribute();
stringAttribute.setName("ListAsString");
stringAttribute.setEType(EcorePackage.eINSTANCE.getEString());
stringAttribute.setUpperBound(-1);
containerClass.getEAttributes().add(stringAttribute);
}
} else {
EReference finalReference = EcoreFactory.eINSTANCE.createEReference();
finalReference.setName("List");
finalReference.setEType(finalType);
finalReference.setUpperBound(-1);
containerClass.getEReferences().add(finalReference);
}
schemaPack.getEClassifiers().add(containerClass);
}
EReference eReference = EcoreFactory.eINSTANCE.createEReference();
eReference.getEAnnotations().add(createTwoDimensionalArrayAnnotation());
eReference.setName(attribName);
eReference.setUpperBound(-1);
eReference.setEType(containerClass);
EClass cls = (EClass) schemaPack.getEClassifier(entityName);
cls.getEStructuralFeatures().add(eReference);
}
private EAnnotation createTwoDimensionalArrayAnnotation() {
EAnnotation asStringAnnotation = eFactory.createEAnnotation();
asStringAnnotation.setSource("twodimensionalarray");
return asStringAnnotation;
}
private boolean superTypeIsWrapped(EClass eType) {
if (eType.getEAnnotation("wrapped") != null) {
return true;
}
for (EClass superClass : eType.getESuperTypes()) {
if (superTypeIsWrapped(superClass)) {
return true;
}
}
return false;
}
private void addClasses() {
Iterator<EntityDefinition> entIter = schema.getEntities().iterator();
while (entIter.hasNext()) {
getOrCreateEClass(entIter.next().getName());
}
}
private void addSupertypes() {
Iterator<EntityDefinition> entIter = schema.getEntities().iterator();
while (entIter.hasNext()) {
EntityDefinition ent = entIter.next();
if (ent.getSupertypes().size() > 0) {
EClass cls = getOrCreateEClass(ent.getName());
if (ent.getSupertypes().size() > 0) {
EClass parent = getOrCreateEClass(ent.getSupertypes().get(0).getName());
if (!directSubTypes.containsKey(parent)) {
directSubTypes.put(parent, new HashSet<EClass>());
}
directSubTypes.get(parent).add(cls);
cls.getESuperTypes().add(parent);
}
}
}
}
private void addSelects() {
Iterator<DefinedType> typeIter = schema.getTypes().iterator();
while (typeIter.hasNext()) {
DefinedType type = typeIter.next();
if (type instanceof SelectType) {
EClass selectType = getOrCreateEClass(type.getName());
selectType.setInterface(true);
selectType.setAbstract(true);
Iterator<NamedType> entIter = ((SelectType) type).getSelections().iterator();
while (entIter.hasNext()) {
NamedType nt = entIter.next();
if (nt instanceof EntityDefinition) {
EClass choice = getOrCreateEClass(nt.getName());
choice.getESuperTypes().add(selectType);
} else if (nt instanceof DefinedType) {
UnderlyingType domain = ((DefinedType) nt).getDomain();
if (domain instanceof RealType || domain instanceof StringType || domain instanceof IntegerType || domain instanceof NumberType
|| domain instanceof LogicalType) {
EClass choice = getOrCreateEClass(nt.getName());
choice.getESuperTypes().add(selectType);
} else if (domain instanceof DefinedType) {
DefinedType dt2 = (DefinedType) (domain);
if (dt2.getDomain() instanceof RealType) {
EClass choice = getOrCreateEClass(nt.getName());
choice.getESuperTypes().add(selectType);
}
} else if (nt instanceof SelectType) {
} else {
if (nt.getName().equals("IfcComplexNumber") || nt.getName().equals("IfcCompoundPlaneAngleMeasure") || nt.getName().equals("IfcBoolean") || nt.getName().equals("IfcNullStyle")) {
EClass choice = getOrCreateEClass(nt.getName());
choice.getESuperTypes().add(selectType);
} else {
System.out.println("The domain is null for " + selectType.getName() + " " + nt.getName());
}
}
}
}
}
}
typeIter = schema.getTypes().iterator();
while (typeIter.hasNext()) {
DefinedType type = typeIter.next();
if (type instanceof SelectType) {
EClass selectType = (EClass) schemaPack.getEClassifier(type.getName());
Iterator<NamedType> entIter = ((SelectType) type).getSelections().iterator();
while (entIter.hasNext()) {
NamedType nt = entIter.next();
if (nt instanceof SelectType) {
EClass choice = getOrCreateEClass(nt.getName());
choice.getESuperTypes().add(selectType);
}
}
}
}
}
private EAttribute modifySimpleType(DefinedType type, EClass testType) {
if (directSubTypes.containsKey(testType)) {
for (EClass subType : directSubTypes.get(testType)) {
x(type, subType);
}
}
EAttribute wrapperAttrib = x(type, testType);
return wrapperAttrib;
}
private EAttribute x(DefinedType type, EClass testType) {
EAttribute wrapperAttrib = eFactory.createEAttribute();
wrapperAttrib.setName("wrappedValue");
if (type.getDomain() instanceof IntegerType) {
wrapperAttrib.setEType(ePackage.getELong());
} else if (type.getDomain() instanceof RealType) {
wrapperAttrib.setEType(ePackage.getEDouble());
} else if (type.getDomain() instanceof StringType) {
wrapperAttrib.setEType(ePackage.getEString());
} else if (type.getDomain() instanceof BooleanType) {
wrapperAttrib.setEType(schemaPack.getEClassifier("Tristate"));
} else if (type.getDomain() instanceof NumberType) {
wrapperAttrib.setEType(ePackage.getEDouble());
} else if (type.getDomain() instanceof BinaryType) {
wrapperAttrib.setEType(ePackage.getEByteArray());
} else if (type.getDomain() instanceof LogicalType) {
wrapperAttrib.setEType(schemaPack.getEClassifier("Tristate"));
}
wrapperAttrib.setUnsettable(true);
testType.getEStructuralFeatures().add(wrapperAttrib);
if (wrapperAttrib.getEType() == ePackage.getEDouble()) {
EAttribute doubleStringAttribute = eFactory.createEAttribute();
doubleStringAttribute.setEType(ePackage.getEString());
doubleStringAttribute.setName("wrappedValueAsString");
doubleStringAttribute.getEAnnotations().add(createAsStringAnnotation());
doubleStringAttribute.getEAnnotations().add(createHiddenAnnotation());
doubleStringAttribute.setUnsettable(true);
testType.getEStructuralFeatures().add(doubleStringAttribute);
}
return wrapperAttrib;
}
private void addSimpleTypes() {
Iterator<DefinedType> typeIter = schema.getTypes().iterator();
while (typeIter.hasNext()) {
DefinedType type = typeIter.next();
if (type.getDomain() instanceof SimpleType) {
EClass testType = getOrCreateEClass(type.getName());
testType.getEAnnotations().add(createWrappedAnnotation());
modifySimpleType(type, testType);
}
}
}
private EClass getOrCreateEClass(String name) {
EClassifier eClassifier = schemaPack.getEClassifier(name);
if (eClassifier == null) {
eClassifier = eFactory.createEClass();
eClassifier.setName(name);
schemaPack.getEClassifiers().add(eClassifier);
}
return (EClass) eClassifier;
}
/**
* constructs the EXPRESS TYPEs like IfcPositiveLength measure that are not
* simple types but derived types: <code>
* TYPE IfcPositiveLengthMeasure = IfcLengthMeasure;
* WHERE
* WR1 : SELF > 0.;
* END_TYPE;
* </code>
*/
private void addDerivedTypes() {
Iterator<DefinedType> typeIter = schema.getTypes().iterator();
while (typeIter.hasNext()) {
DefinedType type = typeIter.next();
// debug (type.getName()+":"+type.getDomain(true).toString());
// if ((type.getDomain() instanceof SimpleType)==false &&
// (type instanceof EnumerationType)==false &&
// (type instanceof SelectType)==false){
/*
* one of the hard things TODO : TYPE IfcCompoundPlaneAngleMeasure =
* LIST [3:3] OF INTEGER; WHERE WR1 : { -360 <= SELF[1] < 360 }; WR2
* : { -60 <= SELF[2] < 60 }; WR3 : { -60 <= SELF[3] < 60 }; WR4 :
* ((SELF[1] >= 0) AND (SELF[2] >= 0) AND (SELF[3] >= 0)) OR
* ((SELF[1] <= 0) AND (SELF[2] <= 0) AND (SELF[3] <= 0)); END_TYPE;
*
* I am skipping this for now, it only occurs once in the model
* future versions should definitely find an answer to this
*
* A fix for this has been implemented in addHackedTypes
*/
if (type.getName().equalsIgnoreCase("IfcCompoundPlaneAngleMeasure")) {
EClass testType = getOrCreateEClass(type.getName());
DefinedType type2 = new DefinedType("Integer");
type2.setDomain(new IntegerType());
modifySimpleType(type2, testType);
testType.getEAnnotations().add(createWrappedAnnotation());
} else if (type.getDomain() instanceof DefinedType) {
if (schemaPack.getEClassifier(type.getName()) != null) {
EClass testType = (EClass) schemaPack.getEClassifier(type.getName());
DefinedType domain = (DefinedType) type.getDomain();
EClassifier classifier = schemaPack.getEClassifier(domain.getName());
testType.getESuperTypes().add((EClass) classifier);
testType.setInstanceClass(classifier.getInstanceClass());
} else {
EClass testType = getOrCreateEClass(type.getName());
DefinedType domain = (DefinedType) type.getDomain();
if (simpleTypeReplacementMap.containsKey(domain.getName())) {
// We can't subclass because it's a 'primitive' type
simpleTypeReplacementMap.put(type.getName(), simpleTypeReplacementMap.get(domain.getName()));
} else {
EClass classifier = getOrCreateEClass(domain.getName());
testType.getESuperTypes().add((EClass) classifier);
if (classifier.getEAnnotation("wrapped") != null) {
testType.getEAnnotations().add(createWrappedAnnotation());
}
testType.setInstanceClass(classifier.getInstanceClass());
}
}
}
}
}
private void addEnumerations() {
Iterator<DefinedType> typeIter = schema.getTypes().iterator();
while (typeIter.hasNext()) {
DefinedType type = typeIter.next();
if (type instanceof EnumerationType) {
EEnum enumeration = eFactory.createEEnum();
enumeration.setName(type.getName());
EEnumLiteral nullValue = eFactory.createEEnumLiteral();
nullValue.setName("NULL");
nullValue.setLiteral("NULL");
nullValue.setValue(0);
enumeration.getELiterals().add(nullValue);
int counter = 1;
Iterator<String> values = ((EnumerationType) type).getElements().iterator();
while (values.hasNext()) {
String stringVal = values.next();
if (!stringVal.equals("NULL")) {
EEnumLiteral value = eFactory.createEEnumLiteral();
value.setName(stringVal);
value.setLiteral(stringVal);
value.setValue(counter);
counter++;
enumeration.getELiterals().add(value);
}
}
schemaPack.getEClassifiers().add(enumeration);
}
}
}
public void writeEMF(String fileName) {
ResourceSet metaResourceSet = new ResourceSetImpl();
metaResourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("ecore", new XMLResourceFactoryImpl());
URI resUri = URI.createURI(fileName);
Resource metaResource = metaResourceSet.createResource(resUri);
metaResource.getContents().add(schemaPack);
try {
metaResource.save(null);
} catch (Exception e) {
LOGGER.error("", e);
}
}
}
|
package org.bimserver;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import org.bimserver.database.DatabaseRestartRequiredException;
import org.bimserver.database.berkeley.DatabaseInitException;
import org.bimserver.models.log.AccessMethod;
import org.bimserver.models.store.ServerState;
import org.bimserver.plugins.OptionsParser;
import org.bimserver.shared.LocalDevelopmentResourceFetcher;
import org.bimserver.shared.exceptions.PluginException;
import org.bimserver.shared.exceptions.ServiceException;
import org.bimserver.shared.interfaces.AdminInterface;
import org.bimserver.shared.interfaces.SettingsInterface;
import org.bimserver.webservices.authorization.SystemAuthorization;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.FileAppender;
import ch.qos.logback.core.util.StatusPrinter;
public class LocalDevBimServerStarter {
private BimServer bimServer;
public static void main(String[] args) {
new LocalDevBimServerStarter().start(-1, "localhost", 8080, 8085, new OptionsParser(args).getPluginDirectories());
}
public void start(int id, String address, int port, int pbport, Path[] pluginDirectories) {
BimServerConfig config = new BimServerConfig();
config.setHomeDir(Paths.get("home" + (id == -1 ? "" : id)));
config.setResourceFetcher(new LocalDevelopmentResourceFetcher(Paths.get("../")));
config.setStartEmbeddedWebServer(true);
config.setClassPath(System.getProperty("java.class.path"));
config.setLocalDev(true);
config.setEnvironment(Environment.LOCAL_DEV);
config.setPort(port);
config.setStartCommandLine(true);
config.setDevelopmentBaseDir(Paths.get("../BimServer"));
try {
fixLogging(config);
} catch (IOException e1) {
e1.printStackTrace();
}
bimServer = new BimServer(config);
bimServer.getVersionChecker().getLocalVersion().setDate(new Date());
bimServer.setEmbeddedWebServer(new EmbeddedWebServer(bimServer, config.getDevelopmentBaseDir(), config.isLocalDev()));
Logger LOGGER = LoggerFactory.getLogger(LocalDevBimServerStarter.class);
try {
bimServer.start();
if (bimServer.getServerInfo().getServerState() != ServerState.MIGRATION_REQUIRED) {
LocalDevPluginLoader.loadPlugins(bimServer.getPluginManager(), pluginDirectories);
try {
AdminInterface adminInterface = bimServer.getServiceFactory().get(new SystemAuthorization(1, TimeUnit.HOURS), AccessMethod.INTERNAL).get(AdminInterface.class);
adminInterface.setup("http:
SettingsInterface settingsInterface = bimServer.getServiceFactory().get(new SystemAuthorization(1, TimeUnit.HOURS), AccessMethod.INTERNAL).get(SettingsInterface.class);
settingsInterface.setCacheOutputFiles(false);
settingsInterface.setPluginStrictVersionChecking(false);
} catch (Exception e) {
// Ignore
}
bimServer.activateServices();
} else {
bimServer.getServerInfoManager().registerStateChangeListener(new StateChangeListener() {
@Override
public void stateChanged(ServerState oldState, ServerState newState) {
if (oldState == ServerState.MIGRATION_REQUIRED && newState == ServerState.RUNNING) {
try {
LocalDevPluginLoader.loadPlugins(bimServer.getPluginManager(), pluginDirectories);
} catch (PluginException e) {
LOGGER.error("", e);
}
}
}
});
}
} catch (PluginException e) {
LOGGER.error("", e);
} catch (ServiceException e) {
LOGGER.error("", e);
} catch (DatabaseInitException e) {
LOGGER.error("", e);
} catch (BimserverDatabaseException e) {
LOGGER.error("", e);
} catch (DatabaseRestartRequiredException e) {
LOGGER.error("", e);
}
}
/**
* Add a file appender to every logger we can find (the loggers should already have been configured via logback.xml)
*
* @throws IOException
*/
private void fixLogging(BimServerConfig config) throws IOException {
Path logFolder = config.getHomeDir().resolve("logs");
if (!Files.isDirectory(logFolder)) {
Files.createDirectories(logFolder);
}
Path file = logFolder.resolve("bimserver.log");
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
PatternLayoutEncoder ple = new PatternLayoutEncoder();
ple.setPattern("%date %level [%thread] %logger{10} [%file:%line] %msg%n");
ple.setContext(lc);
ple.start();
FileAppender<ILoggingEvent> fileAppender = new FileAppender<ILoggingEvent>();
String filename = file.toAbsolutePath().toString();
if (lc instanceof LoggerContext) {
if (!lc.isStarted()) {
lc.start();
}
}
System.out.println("Logging to " + filename);
fileAppender.setFile(filename);
fileAppender.setEncoder(ple);
fileAppender.setContext(lc);
fileAppender.start();
for (ch.qos.logback.classic.Logger log : lc.getLoggerList()) {
if (log.getLevel() != null) {
log.addAppender(fileAppender);
}
}
}
public BimServer getBimServer() {
return bimServer;
}
}
|
package ch.openech.mj.edit.form;
import java.awt.event.KeyListener;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.logging.Logger;
import javax.swing.Action;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.joda.time.LocalDate;
import ch.openech.mj.autofill.DemoEnabled;
import ch.openech.mj.db.model.Constants;
import ch.openech.mj.db.model.PropertyInterface;
import ch.openech.mj.edit.ChangeableValue;
import ch.openech.mj.edit.fields.BigDecimalEditField;
import ch.openech.mj.edit.fields.CheckBoxStringField;
import ch.openech.mj.edit.fields.CodeEditField;
import ch.openech.mj.edit.fields.CodeFormField;
import ch.openech.mj.edit.fields.DateField;
import ch.openech.mj.edit.fields.EditField;
import ch.openech.mj.edit.fields.FormField;
import ch.openech.mj.edit.fields.IntegerEditField;
import ch.openech.mj.edit.fields.TextEditField;
import ch.openech.mj.edit.fields.TextFormField;
import ch.openech.mj.model.annotation.AnnotationUtil;
import ch.openech.mj.model.annotation.PartialDate;
import ch.openech.mj.resources.Resources;
import ch.openech.mj.toolkit.Caption;
import ch.openech.mj.toolkit.ClientToolkit;
import ch.openech.mj.toolkit.GridFormLayout;
import ch.openech.mj.toolkit.IComponent;
public class Form<T> implements IForm<T>, DemoEnabled {
private static Logger logger = Logger.getLogger(Form.class.getName());
protected final boolean editable;
private final ResourceBundle resourceBundle;
private final int columns;
private final GridFormLayout layout;
private final LinkedHashMap<PropertyInterface, FormField<?>> fields = new LinkedHashMap<PropertyInterface, FormField<?>>();
private final Map<PropertyInterface, Caption> indicators = new HashMap<PropertyInterface, Caption>();
private KeyListener keyListener;
private final FormPanelChangeListener formPanelChangeListener = new FormPanelChangeListener();
private ChangeListener changeListener;
private Action saveAction;
private boolean resizable = false;
protected Form() {
this(true);
}
protected Form(boolean editable) {
this(editable, 1);
}
protected Form(boolean editable, int columns) {
this(null, null, editable, columns);
}
public Form(Class<T> objectClass, ResourceBundle resourceBundle, boolean editable) {
this(objectClass, resourceBundle, editable, 1);
}
public Form(Class<T> objectClass, ResourceBundle resourceBundle, boolean editable, int columns) {
this.resourceBundle = resourceBundle != null ? resourceBundle : Resources.getResourceBundle();
this.editable = editable;
this.columns = columns;
this.layout = ClientToolkit.getToolkit().createGridLayout(columns, getColumnWidthPercentage());
}
protected int getColumnWidthPercentage() {
return 100;
}
protected int getAreaHeightPercentage() {
return 100;
}
// Methods to create the form
@Override
public IComponent getComponent() {
return layout;
}
@Override
public void setSaveAction(Action saveAction) {
this.saveAction = saveAction;
}
public FormField<?> createField(Object key) {
FormField<?> field;
if (key == null) {
throw new NullPointerException("Key must not be null");
} else if (key instanceof FormField) {
field = (FormField<?>) key;
if (field.getProperty() == null) {
throw new IllegalArgumentException(IComponent.class.getSimpleName() + " has no key");
}
} else {
PropertyInterface property = Constants.getProperty(key);
field = createField(property);
}
return field;
}
protected FormField<?> createField(PropertyInterface property) {
Class<?> fieldClass = property.getFieldClazz();
if (fieldClass == String.class) {
if (editable) {
int size = AnnotationUtil.getSize(property);
return new TextEditField(property, size);
} else {
return new TextFormField(property);
}
} else if (fieldClass == LocalDate.class) {
boolean partialAllowed = property.getAnnotation(PartialDate.class) != null;
return new DateField(property, partialAllowed, editable);
} else if (Enum.class.isAssignableFrom(fieldClass)) {
return editable ? new CodeEditField(property) : new CodeFormField(property);
} else if (fieldClass == Boolean.class) {
String checkBoxText = Resources.getObjectFieldName(resourceBundle, property, ".checkBoxText");
CheckBoxStringField field = new CheckBoxStringField(property, checkBoxText, editable);
return field;
} else if (fieldClass == Integer.class) {
int size = AnnotationUtil.getSize(property);
boolean negative = AnnotationUtil.isNegative(property);
return new IntegerEditField(property, size, negative);
} else if (fieldClass == BigDecimal.class) {
int size = AnnotationUtil.getSize(property);
int decimal = AnnotationUtil.getDecimal(property);
boolean negative = AnnotationUtil.isNegative(property);
return new BigDecimalEditField(property, size, negative);
}
throw new IllegalArgumentException("Unknown Field: " + property.getFieldName());
}
public void line(Object key) {
FormField<?> visual = createField(key);
add(key, visual, columns);
}
// with this it would be possible to split cells
// public void line(Object... keys) {
// int span = columns / keys.length;
// int rest = columns;
// for (int i = 0; i<keys.length; i++) {
// Object key = keys[i];
// if (key instanceof Object[]) {
// Object[] split = (Object[]) key;
// IComponent[] components = new IComponent[split.length];
// int index = 0;
// for (Object o : split) {
// FormField<?> visual = createField(o);
// registerNamedField(visual);
// components[index++] = decorateWithCaption(visual);
// HorizontalLayout horizontalLayout = ClientToolkit.getToolkit().createHorizontalLayout(components);
// layout.add(horizontalLayout, i < keys.length - 1 ? span : rest);
// } else {
// FormField<?> visual = createField(key);
// add(visual, i < keys.length - 1 ? span : rest);
// rest = rest - span;
public void line(Object... keys) {
int span = columns / keys.length;
int rest = columns;
for (int i = 0; i<keys.length; i++) {
Object key = keys[i];
FormField<?> visual = createField(key);
add(key, visual, i < keys.length - 1 ? span : rest);
rest = rest - span;
}
}
private void add(Object key, FormField<?> c, int span) {
layout.add(decorateWithCaption(c), span);
registerNamedField(c);
}
public void area(Object... keys) {
int span = columns / keys.length;
int rest = columns;
for (int i = 0; i<keys.length; i++) {
Object key = keys[i];
FormField<?> visual = createField(key);
area(key, visual, i < keys.length - 1 ? span : rest);
rest = rest - span;
}
}
private void area(Object key, FormField<?> visual, int span) {
layout.addArea(decorateWithCaption(visual), span);
registerNamedField(visual);
resizable = true;
}
private IComponent decorateWithCaption(FormField<?> visual) {
String captionText = caption(visual);
Caption captioned = ClientToolkit.getToolkit().decorateWithCaption(visual.getComponent(), captionText);
indicators.put(visual.getProperty(), captioned);
return captioned;
}
public void text(String text) {
text(text, columns);
}
public void text(String text, int span) {
IComponent label = ClientToolkit.getToolkit().createLabel(text);
layout.add(label, span);
}
public void addTitle(String text) {
IComponent label = ClientToolkit.getToolkit().createTitle(text);
layout.add(label, columns);
}
protected FormField<?> getField(Object key) {
return fields.get(Constants.getProperty(key));
}
protected void registerNamedField(FormField<?> field) {
fields.put(field.getProperty(), field);
if (field instanceof ChangeableValue<?>) {
ChangeableValue<?> changeable = (ChangeableValue<?>) field;
changeable.setChangeListener(formPanelChangeListener);
}
// addListeners(field);
}
@Override
public void fillWithDemoData() {
for (FormField<?> field : fields.values()) {
if (field instanceof DemoEnabled) {
DemoEnabled demoEnabledField = (DemoEnabled) field;
demoEnabledField.fillWithDemoData();
}
}
}
protected String caption(FormField<?> field) {
return Resources.getObjectFieldName(resourceBundle, field.getProperty());
}
/**
*
* @return Collection provided by a LinkedHashMap so it will be a ordered set
*/
public Collection<PropertyInterface> getProperties() {
return fields.keySet();
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public void set(PropertyInterface property, Object value) {
FormField formField = fields.get(property);
formField.setObject(value);
}
public void setValidationMessage(PropertyInterface property, List<String> validationMessages) {
indicators.get(property).setValidationMessages(validationMessages);
}
@Override
public void setObject(Object object) {
for (PropertyInterface property : getProperties()) {
Object propertyValue = property.getValue(object);
set(property, propertyValue);
}
}
@Override
public boolean isResizable() {
return resizable;
}
private String getName(FormField<?> field) {
PropertyInterface property = field.getProperty();
return property.getFieldName();
}
// Changeable
@Override
public void setChangeListener(ChangeListener changeListener) {
this.changeListener = changeListener;
}
private class FormPanelChangeListener implements ChangeListener {
private boolean adjusting = false;
public void setAdjusting(boolean adjusting) {
this.adjusting = adjusting;
}
@Override
public void stateChanged(ChangeEvent event) {
if (adjusting) return;
EditField<?> changedField = (EditField<?>) event.getSource();
logger.fine("ChangeEvent from " + getName(changedField));
PropertyInterface property = changedField.getProperty();
Object value = changedField.getObject();
forwardToDependingFields(changedField);
if (changeListener != null) {
FormChangeEvent formChangeEvent = new FormChangeEvent(this, property, value);
changeListener.stateChanged(formChangeEvent);
}
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private void forwardToDependingFields(EditField<?> changedField) {
PropertyInterface propertyChangedField = null;
for (Map.Entry<PropertyInterface, FormField<?>> entry : fields.entrySet()) {
FormField field = entry.getValue();
if (field == changedField) {
propertyChangedField = entry.getKey();
continue;
}
if (propertyChangedField == null) {
// only fields below the changed field can be depending.
// know what you do before remove this line!
continue;
}
if (field instanceof DependingOnFieldAbove) {
DependingOnFieldAbove dependingOnFieldAbove = (DependingOnFieldAbove) field;
if (propertyChangedField.equals(Constants.getProperty(dependingOnFieldAbove.getKeyOfDependedField()))) {
try {
dependingOnFieldAbove.valueChanged(changedField.getObject());
} catch (Exception x) {
logger.severe("Could not forward value from " + getName(changedField) + " to " + getName(field) + " (" + x.getLocalizedMessage() + ")");
}
}
}
}
}
public static class FormChangeEvent extends ChangeEvent {
private final PropertyInterface property;
private final Object value;
public FormChangeEvent(Object source, PropertyInterface property, Object value) {
super(source);
this.property = property;
this.value = value;
}
public PropertyInterface getProperty() {
return property;
}
public Object getValue() {
return value;
}
}
}
|
package HelperClasses;
import java.util.TreeMap;
import javax.swing.JTextField;
public class Units
{
public static final int ENTERFIELD_AMOUNT_COLUMNS = 6;
public static final int ENTERFIELD_AMOUNT_WIDTH = ((System.getProperty("os.name").contains("Mac")) ? -6 : 0) +
(int)(new JTextField(ENTERFIELD_AMOUNT_COLUMNS).getPreferredSize().getWidth());
public static final double R = .0821, STANDARD_PRESSURE = 1, STANDARD_TEMPERATURE = 273.15, C = 3E8, h = 6.626E-34;
public static final int UNKNOWN_VALUE = -500, ERROR_VALUE = -501;
public static final String[] PREFIXES = {"p", "n", "\u00B5", "m", "c", "d", "", "da", "h", "k", "M", "T", "G"};
public static final int[] POWERS = {-12, -9, -6, -3, -2, -1, 0, 1, 2, 3, 6, 9, 12};
private static final TreeMap<String, String[]> UNITS = generateMap();
private static TreeMap<String, String[]> generateMap()
{
TreeMap<String, String[]> units = new TreeMap<String, String[]>();
units.put("Pressure", new String[]{"atm", "torr", "kPa"});
units.put("Temperature", new String[]{"K", "\u2103", "\u2109"});
units.put("Amount", new String[]{"mol"});
units.put("Volume", createGroup("L"));
units.put("Length", createGroup("m"));
units.put("Mass", createGroup("g"));
units.put("Frequency", new String[]{"1/s"});
units.put("Energy", new String[]{"J"});
units.put("Velocity", new String[] {"m/s"});
units.put("Planck", new String[]{"J\u00B7s"});
units.put("Time", new String[]{"s", "hr", "day"});
units.put("Mass*Temp", new String[]{"g\u00B7K", "g\u00B7\u2103"});
return units;
}
private static String[] createGroup(String base)
{
String[] group = new String[PREFIXES.length];
for(int index = 0; index < PREFIXES.length; index++)
{
group[index] = PREFIXES[index] + base;
}
return group;
}
public static String[] getUnits(String type)
{
if(type.equals("Moles")) type = "Amount";
return UNITS.get(type);
}
public static String[][] getUnits(String[] types)
{
String[][] units = new String[types.length][];
for(int index = 0; index < types.length; index++)
{
units[index] = getUnits(types[index]);
}
return units;
}
public static double fahrenheitToKelvin(double fahrenheit)
{
return (fahrenheit + 459.67) * 5 / 9;
}
public static double kelvinToFahrenheit(double kelvin)
{
return (kelvin * 9 / 5) - 459.67;
}
public static double celsiusToKelvin(double celsius)
{
return celsius + 273.15;
}
public static double kelvinToCelsius(double kelvin)
{
return kelvin - 273.15;
}
public static double torrToatm(double torr)
{
return torr * 0.00131579;
}
public static double atmTotorr(double atm)
{
return atm / 0.00131579;
}
public static double kPaToatm(double kPa)
{
return kPa * 0.00986923;
}
public static double atmTokPa(double atm)
{
return atm / 0.00986923;
}
public static double toBaseUnit(double amount, int unit)
{
if(amount == Units.UNKNOWN_VALUE) return amount;
else if(amount == Units.ERROR_VALUE) return amount;
else return amount * Math.pow(10, POWERS[unit]);
}
public static double fromBaseUnit(double amount, int unit)
{
if(amount == Units.UNKNOWN_VALUE) return amount;
else if(amount == Units.ERROR_VALUE) return amount;
else return amount / Math.pow(10, POWERS[unit]);
}
public static double betweenUnits(double amount, int from, int to)
{
return amount * Math.pow(10, POWERS[from - to]);
}
public static double toKelvin(double amount, int unit) {
if(amount == UNKNOWN_VALUE) return amount;
else if(amount == ERROR_VALUE) return amount;
else if(unit == 0) return amount; //if kelvin
else if(unit == 1) return Units.celsiusToKelvin(amount); //if celcius
else return Units.fahrenheitToKelvin(amount); //if fahrenheit
}
public static double toOriginalTemp(double amount, int unit) {
if(unit == 0) return amount; //if kelvin
else if(unit == 1) return Units.kelvinToCelsius(amount);//if celcius
else return Units.kelvinToFahrenheit(amount); //if fahrenheit
}
public static double toSeconds(double amount, int unit) {
if(unit == 0) return amount; //if seconds
else if(unit == 1) return amount * 3600; //if hours
else return amount * 86400; //if days
}
public static double toOriginalTime(double amount, int unit) {
if(unit == 0) return amount; //if seconds
else if(unit == 1) return amount / 3600; //if hours
else return amount / 86400; //if days
}
public static double toAtm(double amount, int unit)
{
if(amount == UNKNOWN_VALUE || amount == ERROR_VALUE || unit == 0) return amount;
if(unit == 1) return torrToatm(amount);
return kPaToatm(amount);
}
public static double fromAtm(double amount, int unit)
{
if(amount == UNKNOWN_VALUE || amount == ERROR_VALUE || unit == 0) return amount;
if(unit == 1) return atmTotorr(amount);
return atmTokPa(amount);
}
public static double toStandard(double amount, int unit, String type)
{
if(amount == UNKNOWN_VALUE || amount == ERROR_VALUE) return amount;
if(type.equals("Temperature")) return toKelvin(amount, unit);
else if(type.equals("Pressure")) return toAtm(amount, unit);
else if(type.equals("Time")) return toSeconds(amount, unit);
else if(UNITS.get(type).length == PREFIXES.length) return toBaseUnit(amount, unit);
else return amount;
}
public static double fromStandard(double amount, int unit, String type)
{
if(amount == UNKNOWN_VALUE || amount == ERROR_VALUE) return amount;
if(type.equals("Temperature")) return toOriginalTemp(amount, unit);
else if(type.equals("Pressure")) return fromAtm(amount, unit);
else if(type.equals("Time")) return toOriginalTime(amount, unit);
else if(UNITS.get(type).length == PREFIXES.length) return fromBaseUnit(amount, unit);
else return amount;
}
}
|
package interrogation;
import java.util.HashMap;
import indexation.Index;
public class VectorielCartesien extends ModelIR {
private Weighter w;
public VectorielCartesien(Index index, Weighter w){
super(index);
this.w = w;
}
public double freqQuery(String word, HashMap<String, Integer> queryProcessed){
double freq;
double nbWord = 0;
double occ = queryProcessed.get(word);
for (HashMap.Entry<String, Integer> entry : queryProcessed.entrySet()){
nbWord += queryProcessed.get(entry.getKey());
}
freq = occ/nbWord;
System.out.println("occ "+occ+"nb WOrd "+nbWord+"Frequence query ok ! "+freq);
return freq;
}
public HashMap<String, Double> getDocScores (HashMap<String, Integer> queryProcessed){
HashMap<String, Double> ret = new HashMap<>();
HashMap<String, String> docs = index.getDocs();
double freqdoc;
double freqQuery ;
double somme = 0;
for(HashMap.Entry<String, String> entry2 : docs.entrySet()){ //Parcours de tout les docs
for (HashMap.Entry<String,Integer> entry : queryProcessed.entrySet()){ // parcours des mot de query
freqQuery = this.freqQuery(entry.getKey(),queryProcessed); //Frequence qi
freqdoc = w.frequence(entry2.getKey(), entry.getKey());//Frequence di
somme += freqQuery*freqdoc;
}
ret.put(entry2.getKey(), somme); // on ajoute la frequence dans la HashMap ret + on remet somme a 0 car on passe au doc suivant
somme = 0;
}
return ret;
}
}
|
import Item.*;
import java.util.*;
public class ItemTester
{
public static void main(String[] args)
{
ArrayList myList = new ArrayList<Storable>();
myList.add(new Bow(1));
myList.add(new Chainmail(2));
myList.add(new Dagger(3));
myList.add(new Bow(3));
myList.add(new Bow(1));
myList.add(new Hammer(3));
myList.add(new Dagger(1));
//myList.add(new Potion(2));
myList.add(new Staff(1));
myList.add(new Sword(2));
for(int x = 0; x < myList.size(); x++)
{
System.out.println(myList.get(x) + " " + ((Storable)myList.get(x)).getPower());
}
System.out.println("\n\n\n\n\n");
Collections.sort(myList, new CompareStorables());
for(int x = 0; x < myList.size(); x++)
{
System.out.println(myList.get(x) + " " + ((Storable)myList.get(x)).getPower());
}
}
}
|
/**
* @author kos
*/
package compiler.phases.finalphase;
import java.io.IOException;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.io.File;
import java.util.Vector;
import compiler.Main;
import compiler.common.report.Report;
import compiler.data.asmcode.AsmInstr;
import compiler.data.asmcode.AsmLABEL;
import compiler.data.asmcode.AsmOPER;
import compiler.data.asmcode.Code;
import compiler.data.chunk.DataChunk;
import compiler.data.layout.Frame;
import compiler.data.layout.Label;
import compiler.data.layout.Temp;
import compiler.phases.*;
import compiler.phases.asmcode.AsmGen;
import compiler.phases.chunks.Chunks;
public class FinalPhase extends Phase {
private final String kJump = "JMP ";
private final String kSetConstPrePendix = "SET $0,";
private final String kINCLow = "INCML $0,";
private final String kINCMidHigh = "INCMH $0,";
private final String kINCHigh = "INCH $0,";
private final String kFP = "FP";// "$253";
private final String kSP = "SP";// "$254";
public FinalPhase() {
super("final");
}
private Vector<String> AsmInstructionToString(Vector<AsmInstr> instructions) {
Vector<String> strings = new Vector<>();
for (AsmInstr instr : instructions) {
if (instr instanceof AsmLABEL) {
strings.add(instr.toAsemblerCode(null));
} else {
strings.add(instr.toAsemblerCode(null) + '\n');
}
}
return strings;
}
private Vector<String> CreatePutChar() {
Vector<String> putCharCode = new Vector<>();
Label putCharLabel = new Label("putChar");
Label entryLabel = new Label();
Label exitLabel = new Label();
Code code = new Code(new Frame(putCharLabel, 0, 0, 8), entryLabel, exitLabel, new Vector<>(), null, 0);
putCharCode.add("% Code for function: _putChar\n");
putCharCode.addAll(AsmInstructionToString(CreateProlog(code)));
putCharCode.add(entryLabel.name + "\tSET\t$0,14\n");
putCharCode.add("\tADD\t$0,FP,$0\n");
putCharCode.add("\t%Putting char one position in front\n");
putCharCode.add("\t%so that we put end char at the end\n");
putCharCode.add("\tLDB\t$1,$0,1\n");
putCharCode.add("\tSTB\t$1,$0,0\n");
putCharCode.add("\tSET\t$1,0\n");
putCharCode.add("\tSTB\t$1,$0,1\n");
putCharCode.add("\tSET\t$255,$0\n");
putCharCode.add("\tTRAP\t0,Fputs,StdOut\n");
putCharCode.addAll(AsmInstructionToString(CreateEpilogue(code)));
return putCharCode;
}
private Vector<String> CreatePutString() {
Vector<String> putStringCode = new Vector<>();
Label putStringLabel = new Label("putString");
Label entryLabel = new Label();
Label exitLabel = new Label();
Code code = new Code(new Frame(putStringLabel, 0, 0, 8), entryLabel, exitLabel, new Vector<>(), null, 0);
putStringCode.add("% Code for function: _putString\n");
putStringCode.addAll(AsmInstructionToString(CreateProlog(code)));
putStringCode.add(entryLabel.name + "\tSET\t$0,8\n");
putStringCode.add("\tADD\t$0,FP,$0\n");
putStringCode.add("\tLDO\t$1,$0,0\n");
putStringCode.add("\tSET\t$255,$1\n");
putStringCode.add("\tTRAP\t0,Fputs,StdOut\n");
putStringCode.addAll(AsmInstructionToString(CreateEpilogue(code)));
return putStringCode;
}
private Vector<String> CreatePutInt() {
Vector<String> putIntCode = new Vector<>();
Label putIntLabel = new Label("putInt");
Label entryLabel = new Label();
Label exitLabel = new Label();
Code code = new Code(new Frame(putIntLabel, 1, 16, 16), entryLabel, exitLabel, new Vector<>(), null, 0);
putIntCode.add("% Code for function: _putInt\n");
putIntCode.addAll(AsmInstructionToString(CreateProlog(code)));
putIntCode.add("% Storing inverse number\n");
putIntCode.add(entryLabel.name + "\tSET\t$0,FP\n");
putIntCode.add("\tSET\t$1,16\n");
putIntCode.add("\tNEG\t$1,0,$1\n");
putIntCode.add("\tADD\t$0,$0,$1\n");
putIntCode.add("\tSET\t$1,0\n");
putIntCode.add("\tSTO\t$1,$0,0\n");
putIntCode.add("% While condition\n");
putIntCode.add("_putInt_Inverse_Loop_\tSET\t$0,FP\n");
putIntCode.add("\tSET\t$1,8\n");
putIntCode.add("\tADD\t$0,$0,$1\n");
putIntCode.add("\tLDO\t$0,$0,0\n");
putIntCode.add("\tSET\t$1,0\n");
putIntCode.add("\tCMP\t$0,$0,$1\n");
putIntCode.add("\tZSP\t$0,$0,1\n");
putIntCode.add("\tBZ\t$0,_putInt_Inverse_End_\n");
putIntCode.addAll(AsmInstructionToString(CreateEpilogue(code)));
return putIntCode;
}
private Vector<AsmInstr> SetConstant(long value) {
Vector<AsmInstr> instructions = new Vector<>();
int bits = ((short) value & 0xffff);
instructions.add(new AsmOPER(kSetConstPrePendix + bits, null, null, null));
value >>= 16;
if (value > 0) {
bits = ((short) value & 0xffff);
instructions.add(new AsmOPER(kINCLow + bits, null, null, null));
value >>= 16;
}
if (value > 0) {
bits = ((short) value & 0xffff);
instructions.add(new AsmOPER(kINCMidHigh + bits, null, null, null));
value >>= 16;
}
if (value > 0) {
bits = ((short) value & 0xffff);
instructions.add(new AsmOPER(kINCHigh + bits, null, null, null));
value >>= 16;
}
return instructions;
}
private boolean IsMain(Code code) {
return code.frame.label.name.equals("_main");
}
private Vector<AsmInstr> CreateProlog(Code code) {
Vector<AsmInstr> instr = new Vector<>();
instr.add(new AsmOPER("%
instr.add(new AsmLABEL(code.frame.label));
// Storing FP
instr.addAll(SetConstant(code.frame.locsSize + 2 * 8));
instr.add(new AsmOPER("% Storing FP ", null, null, null));
instr.add(new AsmOPER("SUB $0," + kSP + ",$0", null, null, null));
instr.add(new AsmOPER("STO " + kFP + ",$0,0", null, null, null));
// STORING RA
instr.add(new AsmOPER("% STORING RA ", null, null, null));
instr.add(new AsmOPER("GET $1,rJ", null, null, null));
instr.add(new AsmOPER("STO $1,$0,8", null, null, null));
instr.add(new AsmOPER("% Lowering FP ", null, null, null));
instr.add(new AsmOPER("SET " + kFP + "," + kSP, null, null, null));
instr.add(new AsmOPER("% Lowering SP ", null, null, null));
instr.addAll(SetConstant(code.frame.size + code.tempSize));
instr.add(new AsmOPER("SUB " + kSP + "," + kSP + ",$0", null, null, null));
Vector<Label> jumps = new Vector<>();
jumps.add(code.entryLabel);
instr.add(new AsmOPER(kJump + code.entryLabel.name, null, null, jumps));
return instr;
}
private Vector<AsmInstr> CreateEpilogue(Code code) {
Vector<AsmInstr> instr = new Vector<>();
instr.add(new AsmOPER("%
instr.add(new AsmLABEL(code.exitLabel));
// Save return value
instr.add(new AsmOPER("STO $0," + kFP + ",0 % Save return value ", null, null, null));
// Highering Stack pointer
instr.add(new AsmOPER("% Highering Stack pointer ", null, null, null));
instr.add(new AsmOPER("SET " + kSP + "," + kFP, null, null, null));
// instr.addAll(SetConstant(code.frame.size + code.tempSize));
// instr.add(new AsmOPER("ADD " + kSP + "," + kSP + ",$0", null, null, null));
instr.add(new AsmOPER("% Getting RA ", null, null, null));
instr.addAll(SetConstant(code.frame.locsSize + 2 * 8));
instr.add(new AsmOPER("SUB $0," + kSP + ",$0", null, null, null));
instr.add(new AsmOPER("LDO $1,$0,8", null, null, null));
instr.add(new AsmOPER("PUT rJ,$1", null, null, null));
instr.add(new AsmOPER("% Getting old FP ", null, null, null));
instr.add(new AsmOPER("LDO " + kFP + ",$0,0", null, null, null));
instr.add(new AsmOPER("POP " + Main.numOfRegs + ",0", null, null, null));
return instr;
}
public void Finish() {
for (Code code : AsmGen.codes) {
code.instrs.addAll(0, CreateProlog(code));
code.instrs.addAll(CreateEpilogue(code));
}
Vector<String> bootstrapCode = new Vector<>();
bootstrapCode.add("% Code generated by PREV compiler");
bootstrapCode.add("SP\tGREG\tStack_Segment");
bootstrapCode.add("FP\tGREG\t#6100000000000000");
bootstrapCode.add("HP\tGREG\tData_Segment");
bootstrapCode.add("\tLOC\tData_Segment");
for (DataChunk data : Chunks.dataChunks) {
String string_data = data.init != null ? data.init + ",0" : "0";
bootstrapCode.add(data.label.name + "\tBYTE\t" + string_data);
}
bootstrapCode.add("% Code Segment");
bootstrapCode.add("\tLOC\t#500");
bootstrapCode.add("Main\tPUSHJ\t$" + Main.numOfRegs + ",_main");
bootstrapCode.add("% STOPPING PROGRAM");
bootstrapCode.add("\tTRAP\t0,Halt,0");
try {
OutputStream os = new FileOutputStream(new File(Main.cmdLineArgValue("--dst-file-name")));
for (String line : bootstrapCode) {
os.write((line + "\n").getBytes());
}
boolean previousLabel = false;
for (Code code : AsmGen.codes) {
os.write(("% Code for function: " + code.frame.label.name + "\n").getBytes());
for (AsmInstr instr : code.instrs) {
if (instr instanceof AsmLABEL) {
if (previousLabel) {
os.write(("\tSWYM\t0,4,2 %Two labels one after another\n").getBytes());
os.write((instr.toAsemblerCode(code.regs)).getBytes());
} else {
os.write((instr.toAsemblerCode(code.regs)).getBytes());
}
previousLabel = true;
} else {
os.write((instr.toAsemblerCode(code.regs) + "\n").getBytes());
previousLabel = false;
}
}
}
for (String putCharInstruction : CreatePutChar()) {
os.write(putCharInstruction.getBytes());
}
for (String putCharInstruction : CreatePutString()) {
os.write(putCharInstruction.getBytes());
}
for (String putCharInstruction : CreatePutInt()) {
os.write(putCharInstruction.getBytes());
}
os.close();
} catch (IOException e) {
throw new Report.Error(e.toString());
}
}
public void log() {
if (logger == null)
return;
for (Code code : AsmGen.codes) {
logger.begElement("code");
logger.addAttribute("entrylabel", code.entryLabel.name);
logger.addAttribute("exitlabel", code.exitLabel.name);
logger.addAttribute("tempsize", Long.toString(code.tempSize));
code.frame.log(logger);
logger.begElement("instructions");
for (AsmInstr instr : code.instrs) {
logger.begElement("instruction");
logger.addAttribute("code", instr.toString(code.regs));
logger.endElement();
}
logger.endElement();
logger.endElement();
}
}
}
|
package ru.pinkponies.app;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.net.InetSocketAddress;
import java.nio.BufferOverflowException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.security.InvalidParameterException;
import java.util.Iterator;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import ru.pinkponies.protocol.AppleUpdatePacket;
import ru.pinkponies.protocol.LocationUpdatePacket;
import ru.pinkponies.protocol.LoginPacket;
import ru.pinkponies.protocol.Packet;
import ru.pinkponies.protocol.Protocol;
import ru.pinkponies.protocol.SayPacket;
/**
* The networking thread which provides asynchronous network IO for the main activity.
*/
public class NetworkingThread extends Thread {
/**
* The class wide logger.
*/
private static final Logger LOGGER = Logger.getLogger(NetworkingThread.class.getName());
/**
* The default server ip.
*/
private static final String SERVER_IP = "192.168.0.199";
/**
* The default server port.
*/
private static final int SERVER_PORT = 4264;
/**
* A message handler class for the networking thread.
*/
private static final class MessageHandler extends Handler {
/**
* The weak reference to the networking thread.
*/
private final WeakReference<NetworkingThread> thread;
/**
* Creates a new message handler which handles messages sent to the networking thread.
*
* @param networkingThread
* The networking thread.
*/
MessageHandler(final NetworkingThread networkingThread) {
this.thread = new WeakReference<NetworkingThread>(networkingThread);
}
/**
* Handles incoming messages and sends them to the networking thread.
*
* @param msg
* The incoming message.
*/
@Override
public void handleMessage(final Message msg) {
this.thread.get().onMessageFromUIThread(msg.obj);
}
};
/**
* The message handler which receives messages for this networking thread.
*/
private MessageHandler messageHandler = new MessageHandler(this);
/**
* Returns the message handler associated with this networking thread.
*
* @return The message handler.
*/
public final Handler getMessageHandler() {
return this.messageHandler;
}
/**
* The default incoming/outgoing buffer size.
*/
private static final int BUFFER_SIZE = 8192;
/**
* The protocol helper. Provides methods for serialization and deserialization of packets.
*/
private final Protocol protocol;
/**
* The weak reference to the main activity.
*/
private final WeakReference<MainActivity> mainActivity;
/**
* The socket channel.
*/
private SocketChannel socket;
/**
* The selector.
*/
private Selector selector;
/**
* The incoming data buffer.
*/
private final ByteBuffer incomingData = ByteBuffer.allocate(BUFFER_SIZE);
/**
* The outgoing data buffer.
*/
private final ByteBuffer outgoingData = ByteBuffer.allocate(BUFFER_SIZE);
/**
* Creates a new networking thread which will communicate and send updates to the given
* activity.
*
* @param activity
* The activity to which updates will be sent.
*/
NetworkingThread(final MainActivity activity) {
this.mainActivity = new WeakReference<MainActivity>(activity);
this.protocol = new Protocol();
}
/**
* Starts the networking thread.
*/
@Override
public final void run() {
try {
Looper.prepare();
this.messageHandler = new MessageHandler(this);
this.sendMessageToUIThread("initialized");
Looper.loop();
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Exception", e);
}
}
/**
* Initiates connection to the server.
*
* @throws IOException
* If connection could not be initiated.
*/
private void connect() throws IOException {
LOGGER.info("Connecting to " + NetworkingThread.SERVER_IP + ":" + NetworkingThread.SERVER_PORT + "...");
this.socket = SocketChannel.open();
this.socket.configureBlocking(false);
this.socket.connect(new InetSocketAddress(NetworkingThread.SERVER_IP, NetworkingThread.SERVER_PORT));
this.selector = Selector.open();
this.socket.register(this.selector, SelectionKey.OP_CONNECT);
LOGGER.info("Connection initiated, waiting for finishing...");
}
/**
* Pumps all available IO events.
*
* @throws IOException
* If there was any sort of IO error.
*/
private void service() throws IOException {
this.selector.select();
Set<SelectionKey> keys = this.selector.selectedKeys();
Iterator<SelectionKey> iterator = keys.iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
iterator.remove();
if (!key.isValid()) {
continue;
}
if (key.isConnectable()) {
this.finishConnection(key);
} else if (key.isReadable()) {
this.read(key);
} else if (key.isWritable()) {
this.write(key);
}
}
}
/**
* Finishes the connection.
*
* @param key
* The selection key.
* @throws IOException
* If there was a problem finishing the connection.
*/
private void finishConnection(final SelectionKey key) throws IOException {
if (this.socket.isConnectionPending()) {
this.socket.finishConnect();
this.socket.register(this.selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
this.sendMessageToUIThread("connected");
}
}
/**
* Closes the connection and selection key.
*
* @param key
* The selection key.
* @throws IOException
* If there was a problem closing the connection or selection key.
*/
private void close(final SelectionKey key) throws IOException {
this.socket.close();
key.cancel();
}
/**
* Reads data available on the socket channel.
*
* @param key
* The selection key.
* @throws IOException
* If there was a problem reading data.
*/
private void read(final SelectionKey key) throws IOException {
SocketChannel channel = (SocketChannel) key.channel();
this.incomingData.limit(this.incomingData.capacity());
int numRead;
try {
numRead = channel.read(this.incomingData);
} catch (IOException e) {
this.close(key);
throw e;
}
if (numRead == -1) {
this.close(key);
throw new IOException("Read failed.");
}
Packet packet = null;
this.incomingData.flip();
while (this.incomingData.remaining() > 0) {
try {
packet = this.protocol.unpack(this.incomingData);
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Exception", e);
}
if (packet == null) {
break;
}
this.onPacket(packet);
this.incomingData.compact();
this.incomingData.flip();
}
this.incomingData.compact();
}
/**
* Writes all buffered outgoing data to the socket channel.
*
* @param key
* The selection key.
* @throws IOException
* If there was a problem writing data.
*/
private void write(final SelectionKey key) throws IOException {
SocketChannel channel = (SocketChannel) key.channel();
this.outgoingData.flip();
channel.write(this.outgoingData);
this.outgoingData.compact();
}
/**
* Parses a packet.
*
* @param packet
* The packet to be parsed.
*/
private void onPacket(final Packet packet) {
if (packet instanceof SayPacket) {
SayPacket sayPacket = (SayPacket) packet;
LOGGER.info("Server: " + sayPacket.toString());
} else if (packet instanceof LocationUpdatePacket) {
this.sendMessageToUIThread(packet);
} else if (packet instanceof AppleUpdatePacket) {
this.sendMessageToUIThread(packet);
}
}
/**
* Writes a packet into the channel's output buffer.
*
* @param packet
* The packet which should be written.
* @throws IOException
* If there was a error writing to the output buffer (e.g not enough space).
*/
private void sendPacket(final Packet packet) throws IOException {
try {
this.outgoingData.put(this.protocol.pack(packet));
} catch (BufferOverflowException e) {
LOGGER.log(Level.SEVERE, "Exception", e);
}
}
/**
* Writes a login packet to the output buffer.
*
* @throws IOException
* If there was a error writing to the output buffer (e.g not enough space).
*/
private void login() throws IOException {
LoginPacket packet = new LoginPacket(Build.DISPLAY);
this.sendPacket(packet);
}
/**
* Writes a say packet to the output buffer.
*
* @param message
* The message.
* @throws IOException
* If there was a error writing to the output buffer (e.g not enough space).
*/
private void say(final String message) throws IOException {
SayPacket packet = new SayPacket(message);
this.sendPacket(packet);
}
/**
* Called when a new message was received from the activity.
*
* @param message
* The message.
*/
private void onMessageFromUIThread(final Object message) {
try {
// LOGGER.info("MA: " + message.toString());
if (message.equals("connect")) {
this.connect();
} else if (message.equals("service")) {
this.service();
} else if (message.equals("login")) {
this.login();
} else if (message instanceof Packet) {
this.sendPacket((Packet) message);
} else if (message instanceof String) {
this.say((String) message);
} else {
throw new InvalidParameterException("Unknown message type.");
}
} catch (Exception e) {
this.sendMessageToUIThread("failed");
LOGGER.log(Level.SEVERE, "Exception", e);
}
}
/**
* Sends message to the activity.
*
* @param message
* The message.
*/
private void sendMessageToUIThread(final Object message) {
try {
Message msg = this.mainActivity.get().getMessageHandler().obtainMessage();
msg.obj = message;
this.mainActivity.get().getMessageHandler().sendMessage(msg);
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Exception", e);
}
}
}
|
package com.wenchao.cardstack;
import android.content.res.TypedArray;
import java.util.ArrayList;
import java.util.Queue;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.database.DataSetObserver;
public class CardStack extends RelativeLayout {
public static final int DEFAULT_STACK_MARGIN = 20;
private int mStackMargin = DEFAULT_STACK_MARGIN;
private int mColor = -1;
private int mIndex = 0;
private int mNumVisible = 4;
private boolean canSwipe = true;
private ArrayAdapter<?> mAdapter;
private OnTouchListener mOnTouchListener;
private CardAnimator mCardAnimator;
private CardEventListener mEventListener = new DefaultStackEventListener(300);
private int mContentResource = 0;
public interface CardEventListener{
//section
// 0 | 1
// 2 | 3
// swipe distance, most likely be used with height and width of a view ;
boolean swipeEnd(int section,float distance);
boolean swipeStart(int section,float distance);
boolean swipeContinue(int section, float distanceX,float distanceY );
void discarded(int mIndex, int direction);
void topCardTapped();
}
public void discardTop(final int direction){
mCardAnimator.discard(direction, new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator arg0) {
mCardAnimator.initLayout();
mIndex++;
loadLast();
viewCollection.get(0).setOnTouchListener(null);
viewCollection.get(viewCollection.size() - 1).setOnTouchListener(mOnTouchListener);
mEventListener.discarded(mIndex - 1, direction);
}
});
}
public int getCurrIndex(){
//sync?
return mIndex;
}
//only necessary when I need the attrs from xml, this will be used when inflating layout
public CardStack(Context context, AttributeSet attrs) {
super(context, attrs);
if (attrs != null) {
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.CardStack);
mColor = array.getColor(R.styleable.CardStack_backgroundColor, mColor);
mStackMargin = array.getInteger(R.styleable.CardStack_stackMargin, mStackMargin);
array.recycle();
}
//get attrs assign minVisiableNum
for(int i = 0; i<mNumVisible; i++){
addContainerViews();
}
setupAnimation();
}
private void addContainerViews(){
FrameLayout v = new FrameLayout(getContext());
viewCollection.add(v);
addView(v);
}
public void setStackMargin(int margin){
mStackMargin = margin;
mCardAnimator.setStackMargin(mStackMargin);
mCardAnimator.initLayout();
}
public void setContentResource(int res){
mContentResource = res;
}
public void setCanSwipe(boolean can) {
this.canSwipe = can;
}
public void reset(boolean resetIndex){
if(resetIndex) mIndex = 0;
removeAllViews();
viewCollection.clear();
for(int i = 0; i<mNumVisible; i++){
addContainerViews();
}
setupAnimation();
loadData();
}
public void setVisibleCardNum(int visiableNum){
mNumVisible = visiableNum;
reset(false);
}
public void setThreshold(int t){
mEventListener = new DefaultStackEventListener(t);
}
public void setListener(CardEventListener cel){
mEventListener = cel;
}
private void setupAnimation(){
final View cardView = viewCollection.get(viewCollection.size()-1);
mCardAnimator = new CardAnimator(viewCollection, mColor, mStackMargin);
mCardAnimator.initLayout();
final DragGestureDetector dd = new DragGestureDetector(CardStack.this.getContext(),new DragGestureDetector.DragListener(){
@Override
public boolean onDragStart(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
if (canSwipe) {
mCardAnimator.drag(e1, e2, distanceX, distanceY);
}
float x1 = e1.getRawX();
float y1 = e1.getRawY();
float x2 = e2.getRawX();
float y2 = e2.getRawY();
final int direction = CardUtils.direction(x1, y1, x2, y2);
float distance = CardUtils.distance(x1, y1, x2, y2);
mEventListener.swipeStart(direction, distance);
return true;
}
@Override
public boolean onDragContinue(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
float x1 = e1.getRawX();
float y1 = e1.getRawY();
float x2 = e2.getRawX();
float y2 = e2.getRawY();
final int direction = CardUtils.direction(x1,y1,x2,y2);
if (canSwipe) {
mCardAnimator.drag(e1, e2, distanceX, distanceY);
}
mEventListener.swipeContinue(direction, Math.abs(x2-x1), Math.abs(y2-y1));
return true;
}
@Override
public boolean onDragEnd(MotionEvent e1, MotionEvent e2) {
//reverse(e1,e2);
float x1 = e1.getRawX();
float y1 = e1.getRawY();
float x2 = e2.getRawX();
float y2 = e2.getRawY();
float distance = CardUtils.distance(x1,y1,x2,y2);
final int direction = CardUtils.direction(x1,y1,x2,y2);
boolean discard = mEventListener.swipeEnd(direction, distance);
if(discard){
if (canSwipe) {
mCardAnimator.discard(direction, new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator arg0) {
mCardAnimator.initLayout();
mIndex++;
mEventListener.discarded(mIndex, direction);
//mIndex = mIndex%mAdapter.getCount();
loadLast();
viewCollection.get(0).setOnTouchListener(null);
viewCollection.get(viewCollection.size() - 1)
.setOnTouchListener(mOnTouchListener);
}
});
}
}else{
if (canSwipe) {
mCardAnimator.reverse(e1, e2);
}
}
return true;
}
@Override
public boolean onTapUp() {
mEventListener.topCardTapped();
return true;
}
}
);
mOnTouchListener = new OnTouchListener() {
private static final String DEBUG_TAG = "MotionEvents";
@Override
public boolean onTouch(View arg0, MotionEvent event) {
dd.onTouchEvent(event);
return true;
}
};
cardView.setOnTouchListener(mOnTouchListener);
}
private DataSetObserver mOb = new DataSetObserver(){
@Override
public void onChanged(){
reset(false);
}
};
//ArrayList
ArrayList<View> viewCollection = new ArrayList<View>();
public CardStack(Context context) {
super(context);
}
public void setAdapter(final ArrayAdapter<?> adapter){
if(mAdapter != null){
mAdapter.unregisterDataSetObserver(mOb);
}
mAdapter = adapter;
adapter.registerDataSetObserver(mOb);
loadData();
}
public ArrayAdapter getAdapter() {
return mAdapter;
}
public View getTopView() {
return ((ViewGroup) viewCollection.get(viewCollection.size() - 1)).getChildAt(0);
}
private void loadData(){
for(int i=mNumVisible-1 ; i>=0 ; i
ViewGroup parent = (ViewGroup) viewCollection.get(i);
int index = (mIndex + mNumVisible - 1) - i;
if (index > mAdapter.getCount() - 1) {
parent.setVisibility(View.GONE);
}else{
View child = mAdapter.getView(index, getContentView(), this);
parent.addView(child);
parent.setVisibility(View.VISIBLE);
}
}
}
private View getContentView(){
View contentView = null;
if(mContentResource != 0) {
LayoutInflater lf = LayoutInflater.from(getContext());
contentView = lf.inflate(mContentResource,null);
}
return contentView;
}
private void loadLast(){
ViewGroup parent = (ViewGroup)viewCollection.get(0);
int lastIndex = (mNumVisible - 1)+ mIndex;
if(lastIndex > mAdapter.getCount() -1 ){
parent.setVisibility(View.GONE);
return;
}
View child = mAdapter.getView(lastIndex, getContentView(), parent);
parent.removeAllViews();
parent.addView(child);
}
public int getStackSize() {
return mNumVisible;
}
}
|
package sunmi.com.sunmiauto;
import android.app.Instrumentation;
import android.os.Build;
import android.os.Environment;
import android.os.RemoteException;
import android.support.test.InstrumentationRegistry;
import android.support.test.uiautomator.By;
import android.support.test.uiautomator.UiDevice;
import android.support.test.uiautomator.UiObject2;
import android.support.test.uiautomator.UiObjectNotFoundException;
import android.support.test.uiautomator.UiScrollable;
import android.support.test.uiautomator.UiSelector;
import android.support.test.uiautomator.Until;
import android.util.Log;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.mail.MessagingException;
public class UiAuto {
static Instrumentation instrumentation =InstrumentationRegistry.getInstrumentation();
static UiDevice device = UiDevice.getInstance(instrumentation);
@Before
public void setup() throws RemoteException, UiObjectNotFoundException, IOException {
device.executeShellCommand("am start -n woyou.market/store.ui.activity.HomeActivity");
device.findObject(By.text("")).click();
}
@After
public void teardown() throws RemoteException {
sleep(1000);
device.pressHome();
}
@BeforeClass
public static void initLiza() throws RemoteException {
File dir=new File(Environment.getExternalStorageDirectory()+File.separator+"app_spoon-screenshots");
class Inner {
private void deleteFile(File file) {
if (file.exists()) {
if (file.isFile()) {
file.delete();
} else if (file.isDirectory()) {
File[] files = file.listFiles();// files[];
for (int i = 0;i < files.length;i ++) {
this.deleteFile(files[i]);
}
file.delete();
}
} else {
System.out.println("");
}
}
}
new Inner().deleteFile(dir);
dir.mkdir();
}
@AfterClass
public static void clearDown() throws MessagingException, RemoteException {
// imageGenerator.saveAsHtmlWithMap("hello-world.html", "hello-world.png");
// new SendMail().sendEmail("hello,this is Alan");
// MailInfo mailInfo = new MailInfo();
// mailInfo.setMailServerHost("smtp.exmail.qq.com");
// mailInfo.setMailServerPort("25");
// mailInfo.setValidate(true);
// mailInfo.setUsername("zhangjiyang@sunmi.com");
// mailInfo.setPassword("Sunmi2017");//
// mailInfo.setFromAddress("zhangjiyang@sunmi.com");
// mailInfo.setToAddress("zhangjiyang@sunmi.com");
// mailInfo.setSubject("SUNMIAUTODEMO_TESTRESULT"+Calendar.getInstance().getTime());
// String[] attachFileNames={"sdcard//Download//Sunset.jpg"};
// mailInfo.setAttachFileNames(attachFileNames);
//mailInfo.setContent("");
//SimpleMail.sendTextMail(mailInfo);//
// StringBuffer demo = new StringBuffer();
// .append("<html>")
// .append("<head>")
// .append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">")
// .append("<title></title>")
// .append("<style type=\"text/css\">")
// .append(".test{font-family:\"Microsoft Yahei\";font-size: 18px;color: red;}")
// .append("</style>")
// .append("</head>")
// .append("<body>")
// .append("</body>")
// .append("</html>");
// mailInfo.setContent(demo.toString());
// Boolean b = SimpleMail.sendHtmlMail(mailInfo);// html
// Log.v("aftersend",b+""+"66666666666");
}
// @Test
// public void testWiFi(){
// device.swipe(5,device.getDisplayHeight()/2,device.getDisplayWidth()-5,device.getDisplayHeight()/2,20);
// sleep(2000);
// UiObject2 settingObj = device.findObject(By.text("Settings"));
// settingObj.clickAndWait(Until.newWindow(),5000);
// screenshotCap("setting_interface");
// wifiops.clickAndWait(Until.newWindow(),5000);
// screenshotCap("wifi_interface");
// UiObject2 wifiButton = device.findObject(By.res("com.android.settings:id/switch_widget"));
// Assert.assertEquals("Wifi",true,wifiButton.isChecked());
// @Test
// public void testEthernet(){
// UiObject2 settingObj = device.findObject(By.text("Settings"));
// settingObj.clickAndWait(Until.newWindow(),5000);
// screenshotCap("setting_interface");
// UiObject2 ethOps = device.findObject(By.text("Ethernet"));
// ethOps.clickAndWait(Until.newWindow(),5000);
// screenshotCap("eth_interface");
// UiObject2 ethButton = device.findObject(By.res("com.android.settings:id/switch_widget"));
// Assert.assertEquals("",true,ethButton.isChecked());
// @Test
// public void testDataUsage(){
// UiObject2 settingObj = device.findObject(By.text("Settings"));
// settingObj.clickAndWait(Until.newWindow(),5000);
// screenshotCap("setting_interface");
// UiObject2 ethOps = device.findObject(By.text("Data usage"));
// ethOps.clickAndWait(Until.newWindow(),5000);
// screenshotCap("dataUsage_interface");
// UiObject2 dataUsageObj = device.findObject(By.text("Data usage").clazz("android.widget.TextView"));
// Assert.assertNotNull("Data usage",dataUsageObj);
// @Test
// public void testUserCenter() {
// sleep(3000);
// screenshotCap("before_enter");
// UiObject2 settingObj = device.findObject(By.text(""));
// settingObj.click();
// sleep(2000);
// screenshotCap("after_enter");
// UiObject2 regObj = device.findObject(By.res("com.sunmi.usercenter:id/edit_login_username"));
// regObj.setText("zhangjiyang@sunmi.com");
// sleep(2000);
// screenshotCap("after_click");
// sleep(2000);
// @Test
// public void testOpenWiFi() {
// screenshotCap("berfore_enter");
// UiObject2 settingObj = device.findObject(By.text(""));
// settingObj.clickAndWait(Until.newWindow(), 1000);
// sleep(2000);
// screenshotCap("after_enter");
// UiObject2 WlanObj = device.findObject(By.text("WLAN"));
// WlanObj.click();
// sleep(2000);
// screenshotCap("after_click");
// sleep(2000);
// @Test
// public void testOpenBT() {
// screenshotCap("berfore_enter");
// sleep(2000);
// UiObject2 settingObj = device.findObject(By.text(""));
// settingObj.clickAndWait(Until.newWindow(), 1000);
// sleep(2000);
// screenshotCap("after_enter");
// UiObject2 WlanObj = device.findObject(By.text(""));
// WlanObj.click();
// sleep(2000);
// screenshotCap("after_click");
// sleep(2000);
public void screenshotCap(String tag){
StackTraceElement testClass = findTestClassTraceElement(Thread.currentThread().getStackTrace());
String className = testClass.getClassName().replaceAll("[^A-Za-z0-9._-]", "_");
String methodName = testClass.getMethodName();
Log.v("Extenrnal",Environment.getExternalStorageState());
File dir=new File(Environment.getExternalStorageDirectory()
+File.separator+"app_spoon-screenshots"+File.separator
+className+File.separator+methodName);
Log.v("TEST", dir.getAbsolutePath());
if(!dir.exists()){
dir.mkdirs();
}
String screenshotName = System.currentTimeMillis() + "_" + tag + ".png";
File screenshotFile = new File(dir, screenshotName);
device.takeScreenshot(screenshotFile,0.2F,50);
sleep(2000);
}
StackTraceElement findTestClassTraceElement(StackTraceElement[] trace) {
for(int i = trace.length - 1; i >= 0; --i) {
StackTraceElement element = trace[i];
if("android.test.InstrumentationTestCase".equals(element.getClassName()) && "runMethod".equals(element.getMethodName())) {
return trace[i - 3];
}
if("org.junit.runners.model.FrameworkMethod$1".equals(element.getClassName()) && "runReflectiveCall".equals(element.getMethodName())) {
return trace[i - 3];
}
}
throw new IllegalArgumentException("Could not find test class!");
}
public static void sleep(int sleep) {
try {
Thread.sleep(sleep);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Test
public void testOpenAppStore(){
// screenshotCap("beforeEnter");
// device.findObject(By.text("")).clickAndWait(Until.newWindow(),5000);
// device.waitForIdle(10000);
screenshotCap("afterEnter");
UiObject2 suggObj = device.findObject(By.res("woyou.market:id/fab_me"));
Assert.assertNotNull("",suggObj);
}
@Test
public void testCheckNewArrive(){
// screenshotCap("beforeEnter");
// device.findObject(By.text("")).clickAndWait(Until.newWindow(),10000);
screenshotCap("afterEnter");
device.findObject(By.res("woyou.market:id/tv_newest_all").text("")).clickAndWait(Until.newWindow(),10000);
screenshotCap("afterClickNewestAll");
UiObject2 newestAllObj = device.findObject(By.res("woyou.market:id/list_view"));
Assert.assertNotNull("",newestAllObj);
}
@Test
public void testNewScroll() throws UiObjectNotFoundException {
// screenshotCap("beforeEnter");
// device.findObject(By.text("")).clickAndWait(Until.newWindow(),10000);
screenshotCap("afterEnter");
UiScrollable newAllScroll = new UiScrollable(new UiSelector().resourceId("woyou.market:id/recycler_view_newest"));
newAllScroll.setAsHorizontalList();
newAllScroll.scrollToEnd(20,10);
newAllScroll.scrollToBeginning(20,10);
}
@Test
public void testCheckHotApps(){
// screenshotCap("beforeEnter");
// device.findObject(By.text("")).clickAndWait(Until.newWindow(),10000);
screenshotCap("afterEnter");
device.findObject(By.res("woyou.market:id/tv_hot_all").text("")).clickAndWait(Until.newWindow(),10000);
screenshotCap("afterClickHotAll");
UiObject2 hotAllObj = device.findObject(By.res("woyou.market:id/list_view"));
Assert.assertNotNull("reswoyou.market:id/list_view",hotAllObj);
}
@Test
public void testHotScroll() throws UiObjectNotFoundException {
// screenshotCap("beforeEnter");
// device.findObject(By.text("")).clickAndWait(Until.newWindow(),10000);
screenshotCap("afterEnter");
UiScrollable hotAllScroll = new UiScrollable(new UiSelector().resourceId("woyou.market:id/linear_hot_view"));
hotAllScroll.scrollToEnd(20,10);
hotAllScroll.scrollToBeginning(20,10);
}
@Test
public void testCheckCategory() throws UiObjectNotFoundException {
// screenshotCap("beforeEnter");
// device.findObject(By.text("")).clickAndWait(Until.newWindow(),10000);
screenshotCap("afterEnter");
device.findObject(By.text("")).clickAndWait(Until.newWindow(),10000);
screenshotCap("enterCategory");
UiScrollable cateScroll = new UiScrollable(new UiSelector().resourceId("woyou.market:id/recycler_view"));
ArrayList<String> appCategory = new ArrayList<>();
switch (Build.DEVICE){
case "V1-B18":
Log.v("enterV1-B18","V1-B18");
appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("EET");
break;
case "V1s-G":
Log.v("enterV1s-G","V1s-G");
appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("EET");
break;
default:
Log.v("enterDefault","default");
appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("EET");
}
for (String s:appCategory
) {
boolean b = cateScroll.scrollTextIntoView(s);
Assert.assertTrue(s+"
}
}
@Test
public void testEnterCategory() throws UiObjectNotFoundException {
// screenshotCap("beforeEnter");
// device.findObject(By.text("")).clickAndWait(Until.newWindow(),10000);
screenshotCap("afterEnter");
device.findObject(By.text("")).clickAndWait(Until.newWindow(),10000);
screenshotCap("enterCategory");
UiScrollable cateScroll = new UiScrollable(new UiSelector().resourceId("woyou.market:id/recycler_view"));
ArrayList<String> appCategory = new ArrayList<>();
switch (Build.DEVICE){
case "V1-B18":
Log.v("enterV1-B18","V1-B18");
appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("EET");
break;
case "V1s-G":
Log.v("enterV1s-G","V1s-G");
appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("EET");
break;
default:
Log.v("enterDefault","default");
appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("");appCategory.add("EET");
}
for (String s:appCategory
) {
boolean b = cateScroll.scrollTextIntoView(s);
Assert.assertTrue(s+"
UiObject2 sCategoryObj = device.findObject(By.text(s));
sCategoryObj.clickAndWait(Until.newWindow(),10000);
UiObject2 cateNmaeObj = device.findObject(By.res("woyou.market:id/tv_title"));
String cateName = cateNmaeObj.getText();
Assert.assertEquals(""+s+","+cateName,s,cateName);
device.pressBack();
}
}
@Test
public void testEnterMine(){
// screenshotCap("beforeEnter");
// device.findObject(By.text("")).clickAndWait(Until.newWindow(),10000);
screenshotCap("afterEnter");
device.findObject(By.res("woyou.market:id/fab_me")).clickAndWait(Until.newWindow(),10000);
UiObject2 mineObj = device.findObject(By.res("woyou.market:id/tv_title").text(""));
Assert.assertNotNull("\"\"",mineObj);
}
@Test
public void testEnterLoginPageFromAppStore(){
// screenshotCap("beforeEnter");
// device.findObject(By.text("")).clickAndWait(Until.newWindow(),10000);
screenshotCap("afterEnter");
device.findObject(By.res("woyou.market:id/fab_me")).clickAndWait(Until.newWindow(),10000);
device.findObject(By.res("woyou.market:id/item_user_info")).clickAndWait(Until.newWindow(),10000);
screenshotCap("enterUserLoginCenter");
String actulPkg = device.getCurrentPackageName();
Assert.assertEquals("com.sunmi.usercenter"+actulPkg,"com.sunmi.usercenter",actulPkg);
}
@Test
public void testInstallAppFromHot() throws UiObjectNotFoundException {
// screenshotCap("beforeEnter");
// device.findObject(By.text("")).clickAndWait(Until.newWindow(),10000);
screenshotCap("afterEnter");
device.findObject(By.res("woyou.market:id/tv_hot_all").text("")).clickAndWait(Until.newWindow(),10000);
screenshotCap("afterClickHotAll");
UiScrollable hotAllScroll = new UiScrollable(new UiSelector().resourceId("woyou.market:id/list_view"));
hotAllScroll.scrollTextIntoView("");
device.findObject(By.text("")).click();
}
}
|
package com.comp.ninti.database;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.comp.ninti.general.RuleType;
import com.comp.ninti.general.core.Customer;
import com.comp.ninti.general.core.Discipline;
import com.comp.ninti.general.core.Event;
import com.comp.ninti.general.core.Rule;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.LinkedList;
import java.util.List;
public class DbHandler extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "sportsmanager.db";
private static final int DATABASE_VERSION = 15;
public DbHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
System.out.println("creating customers table");
db.execSQL(CustomerContract.CREATE_TABLE);
System.out.println("creating rules table");
db.execSQL(RuleContract.CREATE_TABLE_RULE);
System.out.println("creating disciplines table");
db.execSQL(EventContract.CREATE_TABLE);
System.out.println("creating events table");
db.execSQL(DisciplineContract.CREATE_TABLE);
System.out.println("creating eventcustomer table");
db.execSQL(EventCustomerContract.CREATE_TABLE);
createDefaultValues(db);
System.out.println("creating default values");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(CustomerContract.DROP_TABLE);
db.execSQL(DisciplineContract.DROP_TABLE);
db.execSQL(RuleContract.DROP_TABLE_RULE);
db.execSQL(EventContract.DROP_TABLE);
db.execSQL(EventCustomerContract.DROP_TABLE);
onCreate(db);
}
public Cursor getAllCustomers() {
return this.getReadableDatabase().rawQuery("select * from " + CustomerContract.CUSTOMER.TABLE_NAME, null);
}
public Cursor getAllRules() {
return this.getReadableDatabase().rawQuery("select * from " + RuleContract.RULE.TABLE_NAME, null);
}
public Cursor getAllDisciplines() {
return this.getReadableDatabase().rawQuery("select * from " + DisciplineContract.DISCIPLINE.TABLE_NAME, null);
}
public Cursor getAllEvents() {
return this.getReadableDatabase().rawQuery("select * from " + EventContract.EVENT.TABLE_NAME, null);
}
public Cursor getDisciplinesById(List<Long> ids) {
final StringBuilder query = new StringBuilder("select * from " + DisciplineContract.DISCIPLINE.TABLE_NAME);
final String discEq = DisciplineContract.DISCIPLINE._ID + " = ";
final String separator = " or ";
query.append(" where ");
for (Long id : ids) {
query.append(discEq);
query.append(id);
query.append(separator);
}
query.delete(query.length() - separator.length(), query.length());
return this.getReadableDatabase().rawQuery(query.toString(), null);
}
public Cursor getCustomerById(long id) {
final String query = "select * from " + CustomerContract.CUSTOMER.TABLE_NAME + " where " + CustomerContract.CUSTOMER._ID + " = " + id;
return this.getReadableDatabase().rawQuery(query, null);
}
public Cursor getCustomersById(List<Long> ids) {
final StringBuilder query = new StringBuilder("select * from " + CustomerContract.CUSTOMER.TABLE_NAME);
final String discEq = CustomerContract.CUSTOMER._ID + " = ";
final String separator = " or ";
query.append(" where ");
for (Long id : ids) {
query.append(discEq);
query.append(id);
query.append(separator);
}
query.delete(query.length() - separator.length(), query.length());
return this.getReadableDatabase().rawQuery(query.toString(), null);
}
/**
* Returns the Rule with the given ruleName
*
* @param ruleName the name of the rule you want to get
* @return the Rule with the given ruleName or null if none was found
*/
public Rule getSpecificRule(String ruleName) {
String select = "select * from " + RuleContract.RULE.TABLE_NAME + " where " + RuleContract.RULE.COLUMN_NAME + " = \"" + ruleName + "\"";
Cursor cursor = this.getReadableDatabase().rawQuery(select, null);
cursor.moveToFirst();
return RuleContract.createRule(cursor);
}
public Cursor getEventCustomerEntries(long discId, long evId) {
String select = "select * from " + EventCustomerContract.EVENTCUSTOMER.TABLE_NAME
+ " where " + EventCustomerContract.EVENTCUSTOMER.COLUMN_DI_ID + " = " + discId
+ " AND " + EventCustomerContract.EVENTCUSTOMER.COLUMN_EV_ID + " = " + evId;
return this.getReadableDatabase().rawQuery(select, null);
}
/**
* Returns the Rule with the given id
*
* @param ruleId the id of the rule you want to get
* @return the Rule with the given ruleId or null if none was found
*/
public Rule getSpecificRuleById(long ruleId) {
String select = "select * from " + RuleContract.RULE.TABLE_NAME + " where " + RuleContract.RULE._ID + " = " + ruleId + "";
Cursor cursor = this.getReadableDatabase().rawQuery(select, null);
cursor.moveToFirst();
return RuleContract.createRule(cursor);
}
public boolean isEventIn(long eventId) {
String query = "SELECT EXISTS(SELECT 1 FROM " + EventCustomerContract.EVENTCUSTOMER.TABLE_NAME + " WHERE "
+ EventCustomerContract.EVENTCUSTOMER.COLUMN_EV_ID + " = " + eventId + " LIMIT 1);";
Cursor cursor = this.getReadableDatabase().rawQuery(query, null);
cursor.moveToFirst();
if (cursor.getInt(0) == 1) {
cursor.close();
return true;
}
cursor.close();
return false;
}
private JSONArray getResults(SQLiteDatabase myDataBase, String searchQuery) {
Cursor cursor = myDataBase.rawQuery(searchQuery, null);
JSONArray resultSet = new JSONArray();
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
int totalColumn = cursor.getColumnCount();
JSONObject rowObject = new JSONObject();
for (int i = 0; i < totalColumn; i++) {
if (cursor.getColumnName(i) != null) {
try {
if (cursor.getString(i) != null) {
Log.d("TAG_NAME", cursor.getString(i));
rowObject.put(cursor.getColumnName(i), cursor.getString(i));
} else {
rowObject.put(cursor.getColumnName(i), "");
}
} catch (Exception e) {
Log.d("TAG_NAME", e.getMessage());
}
}
}
resultSet.put(rowObject);
cursor.moveToNext();
}
cursor.close();
Log.d("TAG_NAME", resultSet.toString());
return resultSet;
}
public static Customer populateCustomer(Cursor c) {
return new Customer(c.getString(c.getColumnIndex(CustomerContract.CUSTOMER.COLUMN_NAME)),
c.getInt(c.getColumnIndex(CustomerContract.CUSTOMER.COLUMN_AGE)), c.getString(c.getColumnIndex(CustomerContract.CUSTOMER.COLUMN_EMAIL)),
c.getString(c.getColumnIndex(CustomerContract.CUSTOMER.COLUMN_PHONE)), c.getLong(c.getColumnIndex(CustomerContract.CUSTOMER._ID)));
}
public static Discipline populateDiscipline(Cursor c) {
return new Discipline(c.getString(c.getColumnIndex(DisciplineContract.DISCIPLINE.COLUMN_NAME)),
c.getLong(c.getColumnIndex(DisciplineContract.DISCIPLINE.COLUMN_RULE_ID)), c.getInt(c.getColumnIndex(DisciplineContract.DISCIPLINE.COLUMN_ATTEMPTS)),
c.getLong(c.getColumnIndex(DisciplineContract.DISCIPLINE._ID)));
}
private void createDefaultValues(SQLiteDatabase db) {
Customer customer = new Customer("Jonas Huber", 23, "Jonas.Huber@rocketmail.com", "01718650307");
Customer customer1 = new Customer("Sepp Huber", 23, "Jonas.Huber@rocketmail.com", "01718650307");
Customer customer2 = new Customer("Woife Huber", 23, "Jonas.Huber@rocketmail.com", "01718650307");
db.insert(CustomerContract.CUSTOMER.TABLE_NAME, null, CustomerContract.getInsert(customer));
db.insert(CustomerContract.CUSTOMER.TABLE_NAME, null, CustomerContract.getInsert(customer1));
db.insert(CustomerContract.CUSTOMER.TABLE_NAME, null, CustomerContract.getInsert(customer2));
Rule rule = new Rule("Default1", RuleType.Default, 1L);
Rule rule1 = new Rule("Default2", RuleType.Default, 2L);
Rule rule2 = new Rule("Default3", RuleType.Default, 3L);
Rule rule3 = new Rule("Time1", RuleType.Time, 20D, 40, 40D, 20, 4L);
db.insert(RuleContract.RULE.TABLE_NAME, null, RuleContract.getInsert(rule));
db.insert(RuleContract.RULE.TABLE_NAME, null, RuleContract.getInsert(rule1));
db.insert(RuleContract.RULE.TABLE_NAME, null, RuleContract.getInsert(rule2));
db.insert(RuleContract.RULE.TABLE_NAME, null, RuleContract.getInsert(rule3));
Discipline discipline = new Discipline("Weitschussexperte", rule, 2);
Discipline discipline1 = new Discipline("Sprintmeister", rule, 2);
Discipline discipline2 = new Discipline("WasErAuchSonstMacht", rule, 2);
Discipline discipline3 = new Discipline("TIMEBased", rule3, 2);
db.insert(DisciplineContract.DISCIPLINE.TABLE_NAME, null, DisciplineContract.getInsert(discipline));
db.insert(DisciplineContract.DISCIPLINE.TABLE_NAME, null, DisciplineContract.getInsert(discipline1));
db.insert(DisciplineContract.DISCIPLINE.TABLE_NAME, null, DisciplineContract.getInsert(discipline2));
db.insert(DisciplineContract.DISCIPLINE.TABLE_NAME, null, DisciplineContract.getInsert(discipline3));
LinkedList<Long> disciplines = new LinkedList<>();
disciplines.add(1L);
disciplines.add(2L);
disciplines.add(3L);
disciplines.add(4L);
LinkedList<Long> customers = new LinkedList<>();
customers.add(1L);
customers.add(2L);
customers.add(3L);
Event event = new Event("Fussballcamp", disciplines, customers, "2017-08-21 18:30");
db.insert(EventContract.EVENT.TABLE_NAME, null, EventContract.getInsert(event));
}
}
|
package com.example.rover;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
import io.rover.ExperienceActivity;
import io.rover.RemoteScreenActivity;
import io.rover.model.Message;
import io.rover.Rover;
public class MessageFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener, MyMessageRecyclerViewAdapter.OnClickListener, MyMessageRecyclerViewAdapter.OnDeleteListener {
// TODO: Customize parameter argument names
private static final String ARG_COLUMN_COUNT = "column-count";
// TODO: Customize parameters
private int mColumnCount = 1;
private SwipeRefreshLayout mSwipeLayout;
private MyMessageRecyclerViewAdapter mAdapter;
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public MessageFragment() {
}
// TODO: Customize parameter initialization
@SuppressWarnings("unused")
public static MessageFragment newInstance(int columnCount) {
MessageFragment fragment = new MessageFragment();
Bundle args = new Bundle();
args.putInt(ARG_COLUMN_COUNT, columnCount);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_message_list, container, false);
if (view instanceof SwipeRefreshLayout) {
Context context = view.getContext();
mSwipeLayout = (SwipeRefreshLayout)view;
mSwipeLayout.setOnRefreshListener(this);
mSwipeLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
// Set the adapter
RecyclerView recyclerView = (RecyclerView)view.findViewById(R.id.list);
if (mColumnCount <= 1) {
recyclerView.setLayoutManager(new LinearLayoutManager(context));
} else {
recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
}
mAdapter = new MyMessageRecyclerViewAdapter(new ArrayList<Message>());
mAdapter.setOnClickListener(this);
mAdapter.setOnDeleteMessageListener(this);
recyclerView.setAdapter(mAdapter);
}
return view;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
onRefresh();
}
@Override
public void onRefresh() {
Rover.reloadInbox(new Rover.OnInboxReloadListener() {
public void onSuccess(List<Message> messages) {
mAdapter.clear();
mAdapter.addAll(messages);
mSwipeLayout.setRefreshing(false);
}
public void onFailure() {
mSwipeLayout.setRefreshing(false);
}
});
}
@Override
public void onDetach() {
super.onDetach();
}
@Override
public void onClick(final Message message) {
if (!message.isRead()) {
message.setRead(true);
Rover.patchMessage(message, new Rover.OnPatchMessageListener() {
@Override
public void onSuccess() {
if (mAdapter != null) {
mAdapter.messageUpdated(message);
}
}
@Override
public void onFailure() {
Log.e("RoverApp", "Failed to update message");
}
});
}
Intent intent = null;
switch (message.getAction()) {
case Website: {
intent = new Intent(Intent.ACTION_VIEW, Uri.parse(message.getURI().toString()));
break;
}
case LandingPage: {
intent = new Intent(getContext(), RemoteScreenActivity.class);
if (message.getLandingPage() != null) {
intent.putExtra(RemoteScreenActivity.INTENT_EXTRA_SCREEN, message.getLandingPage());
} else {
Uri uri = new Uri.Builder().scheme("rover")
.authority("message")
.appendPath(message.getId()).build();
intent.setData(uri);
}
break;
}
case DeepLink: {
intent = new Intent(Intent.ACTION_VIEW, Uri.parse(message.getURI().toString()));
break;
}
case Experience: {
intent = new Intent(getContext(), MyCustomExperience.class);
intent.setData(message.getExperienceUri());
break;
}
}
if (intent != null) {
Rover.didOpenMessage(message);
startActivity(intent);
}
}
@Override
public void onDelete(final Message message) {
Rover.deleteMessage(message, new Rover.OnDeleteMessageListener() {
@Override
public void onSuccess() {
mAdapter.remove(message);
}
@Override
public void onFailure() {
Log.w("Rover", "Failed to delete message");
}
});
}
}
|
package com.expidev.gcmapp.db;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.expidev.gcmapp.model.Training;
import com.expidev.gcmapp.sql.TableNames;
import com.expidev.gcmapp.utils.DatabaseOpenHelper;
import org.ccci.gto.android.common.db.AbstractDao;
import org.json.JSONArray;
import org.json.JSONObject;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class TrainingDao extends AbstractDao
{
private final String TAG = getClass().getSimpleName();
private final SQLiteOpenHelper databaseHelper;
private static final Object instanceLock = new Object();
private static TrainingDao instance;
private TrainingDao(final Context context)
{
super(DatabaseOpenHelper.getInstance(context));
this.databaseHelper = this.dbHelper;
}
public static TrainingDao getInstance(Context context)
{
if (instance == null)
{
synchronized (instanceLock)
{
instance = new TrainingDao(context.getApplicationContext());
}
}
return instance;
}
public Cursor retrieveTrainingCursor(String tableName)
{
final SQLiteDatabase database = databaseHelper.getReadableDatabase();
try
{
return database.query(tableName, null, null, null, null, null, null);
}
catch (Exception e)
{
Log.e(TAG, "Failed to retrieve training: " + e.getMessage(), e);
}
return null;
}
public Cursor retrieveCompletedTrainingCursor(String tableName)
{
final SQLiteDatabase database = databaseHelper.getReadableDatabase();
try
{
return database.query(tableName, null, null, null, null, null, null);
}
catch (Exception e)
{
Log.e(TAG, e.getMessage(), e);
}
return null;
}
public Cursor retrieveTrainingCursorById(int id)
{
final SQLiteDatabase database = databaseHelper.getReadableDatabase();
String whereCondition = "id = ?";
String[] whereArgs = {String.valueOf(id)};
try
{
return database.query(TableNames.TRAINING.getTableName(), null, whereCondition, whereArgs, null, null, null);
}
catch (Exception e)
{
Log.e(TAG, e.getMessage(), e);
}
return null;
}
public Cursor retrieveTrainingCursorByMinistry(String ministryId)
{
final SQLiteDatabase database = databaseHelper.getReadableDatabase();
String where = "ministry_id = ?";
String[] whereArgs = {ministryId};
try
{
return database.query(TableNames.TRAINING.getTableName(), null, where, whereArgs, null, null, null);
}
catch (Exception e)
{
Log.e(TAG, e.getMessage(), e);
}
return null;
}
public Cursor retrieveCompletedTrainingCursor(int trainingId)
{
final SQLiteDatabase database = databaseHelper.getReadableDatabase();
String whereCondition = "training_id = ?";
String[] whereArgs = {String.valueOf(trainingId)};
try
{
return database.query(TableNames.TRAINING_COMPLETIONS.getTableName(), null, whereCondition, whereArgs, null, null, null);
}
catch (Exception e)
{
Log.e(TAG, e.getMessage(), e);
}
return null;
}
public Training retrieveTrainingById(int id)
{
// first see if there is any completed training for this training
List<Training.GCMTrainingCompletions> complete = getCompletedTrainingByTrainingId(id);
Cursor cursor = null;
try
{
cursor = retrieveTrainingCursorById(id);
if (cursor != null && cursor.getCount() == 1)
{
cursor.moveToFirst();
return setTrainingFromCursor(cursor, complete);
}
}
catch (Exception e)
{
Log.e(TAG, e.getMessage(), e);
}
finally
{
if (cursor != null) cursor.close();
}
return null;
}
public List<Training> getAllMinistryTraining(String ministry_id)
{
Log.i(TAG, "Getting all training for ministry: " + ministry_id);
Cursor cursor = null;
List<Training> allTraining = new ArrayList<>();
try
{
cursor = retrieveTrainingCursorByMinistry(ministry_id);
if (cursor != null && cursor.getCount() > 0)
{
cursor.moveToFirst();
for (int i = 0; i < cursor.getCount(); i++)
{
int id = cursor.getInt(cursor.getColumnIndex("id"));
List<Training.GCMTrainingCompletions> completed = getCompletedTrainingByTrainingId(id);
Training training = setTrainingFromCursor(cursor, completed);
// if size is 0 go ahead an add
if (allTraining.size() > 0)
{
boolean exists = false;
for (Training trainingAlreadyAdded : allTraining)
{
if (Training.equals(trainingAlreadyAdded, training)) exists = true;
}
if (!exists) allTraining.add(training);
}
else
{
allTraining.add(training);
}
cursor.moveToNext();
}
}
Log.i(TAG, "Trainings returned: " + allTraining.size());
return allTraining;
}
catch (Exception e)
{
Log.e(TAG, e.getMessage(), e);
}
finally
{
if (cursor != null) cursor.close();
}
return null;
}
public List<Training.GCMTrainingCompletions> getCompletedTrainingByTrainingId(int id)
{
Cursor cursor = null;
List<Training.GCMTrainingCompletions> completed = new ArrayList<>();
try
{
cursor = retrieveCompletedTrainingCursor(id);
if (cursor != null && cursor.getCount() > 0)
{
cursor.moveToFirst();
for (int i = 0; i < cursor.getCount(); i++)
{
Training.GCMTrainingCompletions completedTraining = setCompletedTrainingFromCursor(cursor);
// if size is 0, go ahead and add
if (completed.size() > 0)
{
boolean exists = false;
for (Training.GCMTrainingCompletions trainingAlreadyAdded : completed)
{
if (Training.GCMTrainingCompletions.equals(trainingAlreadyAdded, completedTraining)) exists = true;
}
if (!exists) completed.add(completedTraining);
}
else
{
completed.add(completedTraining);
}
cursor.moveToNext();
}
}
return completed;
}
catch (Exception e)
{
Log.e(TAG, e.getMessage(), e);
}
finally
{
if (cursor != null) cursor.close();
}
return null;
}
public void saveTrainingFromAPI(JSONArray jsonArray)
{
final SQLiteDatabase database = databaseHelper.getWritableDatabase();
try
{
database.beginTransaction();
String trainingTable = TableNames.TRAINING.getTableName();
String trainingCompleteTable = TableNames.TRAINING_COMPLETIONS.getTableName();
Cursor existingTraining = retrieveTrainingCursor(trainingTable);
Cursor existingCompletedTraining = retrieveTrainingCursor(trainingCompleteTable);
Log.i(TAG, "API returned: " + jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject training = jsonArray.getJSONObject(i);
int id = training.getInt("id");
Log.i(TAG, "Saving id: " + id);
ContentValues trainingToInsert = new ContentValues();
trainingToInsert.put("id", id);
trainingToInsert.put("ministry_id", training.getString("ministry_id"));
trainingToInsert.put("name", training.getString("name"));
trainingToInsert.put("date", training.getString("date"));
trainingToInsert.put("type", training.getString("type"));
trainingToInsert.put("mcc", training.getString("mcc"));
trainingToInsert.put("latitude", training.getDouble("latitude"));
trainingToInsert.put("longitude", training.getDouble("longitude"));
trainingToInsert.put("synced", new Timestamp(new Date().getTime()).toString());
JSONArray trainingCompletedArray = training.getJSONArray("gcm_training_completions");
for (int j = 0; j < trainingCompletedArray.length(); j++)
{
JSONObject completedTraining = trainingCompletedArray.getJSONObject(j);
int completedId = completedTraining.getInt("id");
ContentValues completedTrainingToInsert = new ContentValues();
completedTrainingToInsert.put("id", completedId);
completedTrainingToInsert.put("phase", completedTraining.getInt("phase"));
completedTrainingToInsert.put("number_completed", completedTraining.getInt("number_completed"));
completedTrainingToInsert.put("date", completedTraining.getString("date"));
completedTrainingToInsert.put("training_id", completedTraining.getInt("training_id"));
completedTrainingToInsert.put("synced", new Timestamp(new Date().getTime()).toString());
if (!trainingExistsInDatabase(completedId, existingCompletedTraining))
{
database.insert(trainingCompleteTable, null, completedTrainingToInsert);
}
else
{
database.update(trainingCompleteTable, completedTrainingToInsert, null, null);
}
Log.i(TAG, "Inserted/Updated completed training: " + completedId);
}
if (!trainingExistsInDatabase(id, existingTraining))
{
database.insert(trainingTable, null, trainingToInsert);
Log.i(TAG, "Inserted training: " + trainingToInsert.getAsString("id"));
}
else
{
String where = "id = ?";
String[] args = {trainingToInsert.getAsString("id")};
database.update(trainingTable, trainingToInsert, where, args);
Log.i(TAG, "Updated training: " + trainingToInsert.getAsString("id"));
}
}
database.setTransactionSuccessful();
}
catch (Exception e)
{
Log.e(TAG, e.getMessage(), e);
}
finally
{
database.endTransaction();
if (database.isDbLockedByCurrentThread()) Log.w(TAG, "Database Locked by thread (saveTrainingFromAPI)");
}
}
public void saveTraining(Training training)
{
final SQLiteDatabase database = databaseHelper.getWritableDatabase();
try
{
database.beginTransaction();
String trainingTable = TableNames.TRAINING.getTableName();
String completedTrainingTable = TableNames.TRAINING_COMPLETIONS.getTableName();
Cursor existingTraining = retrieveTrainingCursor(trainingTable);
Cursor existingCompletedTraining = retrieveCompletedTrainingCursor(completedTrainingTable);
ContentValues trainingToInsert = new ContentValues();
trainingToInsert.put("id", training.getId());
trainingToInsert.put("ministry_id", training.getMinistryId().toString());
trainingToInsert.put("name", training.getName());
trainingToInsert.put("date", dateToString(training.getDate()));
trainingToInsert.put("type", training.getType());
trainingToInsert.put("mcc", training.getMcc());
trainingToInsert.put("latitude", training.getLatitude());
trainingToInsert.put("longitude", training.getLongitude());
trainingToInsert.put("synced", training.getSynced().toString());
if (training.getCompletions() != null && training.getCompletions().size() > 0)
{
for (Training.GCMTrainingCompletions completion : training.getCompletions())
{
ContentValues completedTrainingToInsert = new ContentValues();
completedTrainingToInsert.put("id", completion.getId());
completedTrainingToInsert.put("phase", completion.getPhase());
completedTrainingToInsert.put("number_completed", completion.getNumberCompleted());
completedTrainingToInsert.put("training_id", completion.getTrainingId());
completedTrainingToInsert.put("synced", completion.getSynced().toString());
if (!trainingExistsInDatabase(completion.getId(), existingCompletedTraining))
{
database.insert(completedTrainingTable, null, completedTrainingToInsert);
}
else
{
database.update(completedTrainingTable, completedTrainingToInsert, null, null);
}
Log.i(TAG, "Inserted/Updated completed training: " + completion.getId());
}
}
if (!trainingExistsInDatabase(training.getId(), existingTraining))
{
database.insert(trainingTable, null, trainingToInsert);
Log.i(TAG, "Inserted training: " + training.getId());
}
else
{
database.update(trainingTable, trainingToInsert, null, null);
Log.i(TAG, "Updated training: " + training.getId());
}
database.setTransactionSuccessful();
}
catch (Exception e)
{
Log.e(TAG, e.getMessage(), e);
}
finally
{
database.endTransaction();
if (database.isDbLockedByCurrentThread()) Log.w(TAG, "Database Locked by thread (saveTraining)");
}
}
void deleteAllData()
{
final SQLiteDatabase database = databaseHelper.getWritableDatabase();
database.beginTransaction();
try
{
database.delete(TableNames.TRAINING.getTableName(), null, null);
database.setTransactionSuccessful();
} catch (Exception e)
{
Log.e(TAG, e.getMessage());
} finally
{
database.endTransaction();
if (database.isDbLockedByCurrentThread()) Log.w(TAG, "Database Locked by thread (deleteAllData)");
}
}
private boolean trainingExistsInDatabase(int id, Cursor existingTraining)
{
existingTraining.moveToFirst();
for (int i = 0; i < existingTraining.getCount(); i++)
{
int existingId = existingTraining.getInt(existingTraining.getColumnIndex("id"));
if (existingId == id) return true;
existingTraining.moveToNext();
}
return false;
}
private Date stringToDate(String string) throws ParseException
{
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
return format.parse(string);
}
private String dateToString(Date date)
{
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
return dateFormat.format(date);
}
private Training setTrainingFromCursor(Cursor cursor, List<Training.GCMTrainingCompletions> completed) throws ParseException
{
Log.i(TAG, "Building training");
Training training = new Training();
training.setId(cursor.getInt(cursor.getColumnIndex("id")));
training.setMinistryId(cursor.getString(cursor.getColumnIndex("ministry_id")));
training.setName(cursor.getString(cursor.getColumnIndex("name")));
training.setDate(stringToDate(cursor.getString(cursor.getColumnIndex("date"))));
training.setType(cursor.getString(cursor.getColumnIndex("type")));
training.setMcc(cursor.getString(cursor.getColumnIndex("mcc")));
training.setLatitude(cursor.getDouble(cursor.getColumnIndex("latitude")));
training.setLongitude(cursor.getDouble(cursor.getColumnIndex("longitude")));
if (completed != null && completed.size() > 0)
{
training.setCompletions(completed);
}
if (!cursor.getString(cursor.getColumnIndex("synced")).isEmpty())
{
try
{
training.setSynced(Timestamp.valueOf(cursor.getString(cursor.getColumnIndex("synced"))));
}
catch (Exception e)
{
Log.i(TAG, "Could not parse Timestamp");
}
}
Log.i(TAG, "Returning new training: " + training.getId());
return training;
}
private Training.GCMTrainingCompletions setCompletedTrainingFromCursor(Cursor cursor) throws ParseException
{
Training.GCMTrainingCompletions trainingCompletions = new Training.GCMTrainingCompletions();
trainingCompletions.setId(cursor.getInt(cursor.getColumnIndex("id")));
trainingCompletions.setPhase(cursor.getInt(cursor.getColumnIndex("phase")));
trainingCompletions.setNumberCompleted(cursor.getInt(cursor.getColumnIndex("number_completed")));
trainingCompletions.setTrainingId(cursor.getInt(cursor.getColumnIndex("training_id")));
trainingCompletions.setDate(stringToDate(cursor.getString(cursor.getColumnIndex("date"))));
if (!cursor.getString(cursor.getColumnIndex("synced")).isEmpty())
{
try
{
trainingCompletions.setSynced(Timestamp.valueOf(cursor.getString(cursor.getColumnIndex("synced"))));
}
catch (Exception e)
{
Log.i(TAG, "Could not parse Timestamp");
}
}
return trainingCompletions;
}
}
|
package com.k3nx.signupform;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class LoginActivity extends ActionBarActivity {
private static final String TAG = "LoginActivity";
private Button mSubmitButton;
private EditText mUsernameInput;
private EditText mPasswordInput;
private EditText mConfirmInput;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mSubmitButton = (Button)findViewById(R.id.submit_button);
mUsernameInput = (EditText)findViewById(R.id.username_input);
mPasswordInput = (EditText)findViewById(R.id.password_input);
mConfirmInput = (EditText)findViewById(R.id.confirm_input);
mSubmitButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String username = mUsernameInput.getText().toString();
String password = mPasswordInput.getText().toString();
String confirmation = mConfirmInput.getText().toString();
if (password.equals(confirmation)) {
Log.d(TAG, String.format("Password Success for %1$s!!!", username));
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_login, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
package com.njlabs.showjava.ui;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.crashlytics.android.Crashlytics;
import com.njlabs.showjava.R;
import com.njlabs.showjava.utils.Utils;
import com.njlabs.showjava.utils.logging.Ln;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class AppListing extends BaseActivity {
private ProgressDialog packageLoadDialog;
private ListView listView = null;
private boolean isDestroyed;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupLayout(R.layout.activity_app_listing, "Show Java"+(isPro()?" Pro":""));
listView = (ListView) findViewById(R.id.list);
ApplicationLoader runner = new ApplicationLoader();
runner.execute();
}
private void showProgressDialog() {
if (packageLoadDialog == null) {
packageLoadDialog = new ProgressDialog(this);
packageLoadDialog.setIndeterminate(false);
packageLoadDialog.setCancelable(false);
packageLoadDialog.setInverseBackgroundForced(false);
packageLoadDialog.setCanceledOnTouchOutside(false);
packageLoadDialog.setMessage("Loading installed applications...");
}
packageLoadDialog.show();
}
private void dismissProgressDialog() {
if (packageLoadDialog != null && packageLoadDialog.isShowing()) {
packageLoadDialog.dismiss();
}
}
private void setupList(ArrayList<PackageInfoHolder> AllPackages) {
ArrayAdapter<PackageInfoHolder> aa = new ArrayAdapter<PackageInfoHolder>(getBaseContext(), R.layout.package_list_item, AllPackages) {
@SuppressLint("InflateParams")
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = getLayoutInflater().inflate(R.layout.package_list_item, null);
}
PackageInfoHolder pkg = getItem(position);
ViewHolder holder = new ViewHolder();
holder.packageLabel = (TextView) convertView.findViewById(R.id.pkg_name);
holder.packageName = (TextView) convertView.findViewById(R.id.pkg_id);
holder.packageVersion = (TextView) convertView.findViewById(R.id.pkg_version);
holder.packageFilePath = (TextView) convertView.findViewById(R.id.pkg_dir);
holder.packageIcon = (ImageView) convertView.findViewById(R.id.pkg_img);
holder.position = position;
convertView.setTag(holder);
holder.packageLabel.setText(pkg.packageLabel);
holder.packageName.setText(pkg.packageName);
holder.packageVersion.setText("version " + pkg.packageVersion);
holder.packageFilePath.setText(pkg.packageFilePath);
holder.packageIcon.setImageDrawable(pkg.packageIcon);
return convertView;
}
};
listView.setAdapter(aa);
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final ViewHolder holder = (ViewHolder) view.getTag();
String myApp = "com.njlabs.tester";
if (holder.packageName.getText().toString().toLowerCase().contains(myApp.toLowerCase())) {
Toast.makeText(getApplicationContext(), "The application " + holder.packageName.getText().toString() + " cannot be decompiled !", Toast.LENGTH_SHORT).show();
} else {
final File sourceDir = new File(Environment.getExternalStorageDirectory() + "/ShowJava/sources/" + holder.packageName.getText().toString() + "");
if (Utils.sourceExists(sourceDir)) {
showAlreadyExistsDialog(holder, sourceDir);
} else {
showDecompilerSelection(holder);
}
}
}
});
}
private ArrayList<PackageInfoHolder> getInstalledApps(ApplicationLoader task) {
ArrayList<PackageInfoHolder> res = new ArrayList<>();
List<PackageInfo> packages = getPackageManager().getInstalledPackages(0);
int totalPackages = packages.size();
for (int i = 0; i < totalPackages; i++) {
PackageInfo p = packages.get(i);
if (!isSystemPackage(p)) {
ApplicationInfo appInfo = null;
try {
appInfo = getPackageManager().getApplicationInfo(p.packageName, 0);
} catch (PackageManager.NameNotFoundException e) {
Ln.e(e);
}
int count = i + 1;
final PackageInfoHolder newInfo = new PackageInfoHolder();
newInfo.packageLabel = p.applicationInfo.loadLabel(getPackageManager()).toString();
task.doProgress("Loading application " + count + " of " + totalPackages + " (" + newInfo.packageLabel + ")");
newInfo.packageName = p.packageName;
newInfo.packageVersion = p.versionName;
if (appInfo != null) {
newInfo.packageFilePath = appInfo.publicSourceDir;
}
newInfo.packageIcon = p.applicationInfo.loadIcon(getPackageManager());
res.add(newInfo);
}
}
Comparator<PackageInfoHolder> AppNameComparator = new Comparator<PackageInfoHolder>() {
public int compare(PackageInfoHolder o1, PackageInfoHolder o2) {
return o1.getPackageLabel().toLowerCase().compareTo(o2.getPackageLabel().toLowerCase());
}
};
Collections.sort(res, AppNameComparator);
return res;
}
private boolean isSystemPackage(PackageInfo pkgInfo) {
return ((pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
}
@Override
protected void onDestroy() {
isDestroyed = true;
dismissProgressDialog();
super.onDestroy();
}
private static class ViewHolder {
TextView packageLabel;
TextView packageName;
TextView packageVersion;
TextView packageFilePath;
ImageView packageIcon;
int position;
}
private class ApplicationLoader extends AsyncTask<String, String, ArrayList<PackageInfoHolder>> {
@Override
protected ArrayList<PackageInfoHolder> doInBackground(String... params) {
publishProgress("Retrieving installed application");
return getInstalledApps(this);
}
@Override
protected void onPostExecute(ArrayList<PackageInfoHolder> AllPackages) {
setupList(AllPackages);
if (!isDestroyed) {
dismissProgressDialog();
}
}
public void doProgress(String value) {
publishProgress(value);
}
@Override
protected void onPreExecute() {
showProgressDialog();
}
@Override
protected void onProgressUpdate(String... text) {
packageLoadDialog.setMessage(text[0]);
}
}
class PackageInfoHolder {
private String packageLabel = "";
private String packageName = "";
private String packageVersion = "";
private String packageFilePath = "";
private Drawable packageIcon;
public String getPackageLabel() {
return packageLabel;
}
}
private void showAlreadyExistsDialog(final ViewHolder holder, final File sourceDir){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(AppListing.this, R.style.AlertDialog);
alertDialog.setTitle("This Package has already been decompiled");
alertDialog.setMessage("This application has already been decompiled once and the source exists on your sdcard. What would you like to do ?");
alertDialog.setPositiveButton("View Source", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(getApplicationContext(), JavaExplorer.class);
i.putExtra("java_source_dir", sourceDir + "/");
i.putExtra("package_id", holder.packageName.getText().toString());
startActivity(i);
}
});
alertDialog.setNegativeButton("Decompile", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
try {
FileUtils.deleteDirectory(sourceDir);
} catch (IOException e) {
Crashlytics.logException(e);
}
showDecompilerSelection(holder);
}
});
alertDialog.show();
}
private void openProcessActivity(ViewHolder holder, String decompiler){
Intent i = new Intent(getApplicationContext(), AppProcessActivity.class);
i.putExtra("package_label", holder.packageLabel.getText().toString());
i.putExtra("package_file_path", holder.packageFilePath.getText().toString());
i.putExtra("decompiler", decompiler);
startActivity(i);
}
private void showDecompilerSelection(final ViewHolder holder){
if(!prefs.getBoolean("hide_decompiler_select", false)){
final CharSequence[] items = getResources().getTextArray(R.array.decompilers);
final CharSequence[] itemsVals = getResources().getTextArray(R.array.decompilers_values);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick a decompiler");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
openProcessActivity(holder, itemsVals[item].toString());
}
});
AlertDialog alert = builder.create();
alert.show();
} else {
openProcessActivity(holder, prefs.getString("decompiler","cfr"));
}
}
}
|
package com.shinewave.sopviewer;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
public class DBManager {
private static final String TAG = "DBManager";
private static DataBaseHelper sopDBAccess;
public static void initDBHelp(DataBaseHelper dbAccess) {
sopDBAccess = dbAccess; //keep dbhelper instance
}
public static List<FileInfo> getFileInfo() {
SQLiteDatabase db = sopDBAccess.getReadableDatabase();
List<FileInfo> list = new ArrayList<>();
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Cursor cr = null;
try {
cr = db.rawQuery("SELECT * FROM SOPViewer_FileInfo", null);
} catch (Exception e) {
Log.d("TAG", e.getMessage());
}
if (cr != null) {
cr.moveToFirst();
for (int i = 0; i < cr.getCount(); i++) {
try {
FileInfo info = new FileInfo();
info.localFullFilePath = cr.getString(0);
info.remoteFullFilePath = cr.getString(1);
info.connectionName = cr.getString(2);
info.updateTime = format.parse(cr.getString(3));
info.size = cr.getInt(4);
info.remoteTimeStamp = format.parse(cr.getString(5));
list.add(info);
cr.moveToNext();
} catch (ParseException e) {
Log.d("TAG", e.getMessage());
}
}
cr.close();
}
db.close();
return list;
}
public static boolean insertFileInfo(FileInfo info) {
boolean res = false;
SQLiteDatabase db = sopDBAccess.getReadableDatabase();
ContentValues ctv = new ContentValues();
ctv.put("localFullFilePath", info.localFullFilePath);
ctv.put("remoteFullFilePath", info.remoteFullFilePath);
ctv.put("connectionName", info.connectionName);
ctv.put("size", info.size);
ctv.put("remoteTimeStamp", info.remoteTimeStamp.toString());
ctv.put("updateTime", info.updateTime.toString());
try {
long resLong = db.insert("SOPViewer_FileInfo", "", ctv);
if (resLong >= 0)
res = true;
} catch (Exception e) {
Log.d("TAG", e.getMessage());
}
db.close();
return res;
}
public static boolean deleteFileInfo(String localFullFilePath) {
boolean res = false;
SQLiteDatabase db = sopDBAccess.getReadableDatabase();
try {
long resLong = db.delete("SOPViewer_FileInfo", "localFullFilePath=?", new String[]{localFullFilePath});
if (resLong >= 0)
res = true;
} catch (Exception e) {
Log.d("TAG", e.getMessage());
}
db.close();
return res;
}
public static boolean updateFileInfo(FileInfo info) {
boolean res = false;
SQLiteDatabase db = sopDBAccess.getWritableDatabase();
String name = info.localFullFilePath;
ContentValues ctv = new ContentValues();
ctv.put("remoteFullFilePath", info.remoteFullFilePath);
ctv.put("connectionName", info.connectionName);
ctv.put("size", info.size);
ctv.put("remoteTimeStamp", info.remoteTimeStamp.toString());
ctv.put("updateTime", info.updateTime.toString());
try {
long resLong = db.update("SOPViewer_FileInfo", ctv, "localFullFilePath=?", new String[]{name});
if (resLong >= 0)
res = true;
} catch (Exception e) {
Log.d("TAG", e.getMessage());
}
db.close();
return res;
}
public static FileInfo getSingleFileInfo(String fullPath) {
SQLiteDatabase db = sopDBAccess.getReadableDatabase();
FileInfo info = new FileInfo();
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Cursor cr = null;
try {
cr = db.rawQuery("SELECT * FROM SOPViewer_FileInfo WHERE localFullFilePath=?", new String[]{fullPath});
} catch (Exception e) {
Log.d("TAG", e.getMessage());
}
if (cr != null) {
cr.moveToFirst();
for (int i = 0; i < cr.getCount(); i++) {
try {
info.localFullFilePath = cr.getString(0);
info.remoteFullFilePath = cr.getString(1);
info.connectionName = cr.getString(2);
info.updateTime = format.parse(cr.getString(3));
info.size = cr.getInt(4);
info.remoteTimeStamp = format.parse(cr.getString(5));
cr.moveToNext();
} catch (ParseException e) {
Log.d("TAG", e.getMessage());
}
}
cr.close();
}
db.close();
return info;
}
public static ConnectionInfo getConnection(String connName) {
SQLiteDatabase db = sopDBAccess.getReadableDatabase();
ConnectionInfo info = null;
Cursor cr = null;
try {
cr = db.rawQuery("SELECT * FROM SOPViewer_ConnectionInfo where connectionName=" + connName, null);
} catch (Exception e) {
Log.d("TAG", e.getMessage());
}
if (cr != null) {
cr.moveToFirst();
info = new ConnectionInfo();
info.connectionName = cr.getString(0);
info.protocol = cr.getInt(1);
info.protocolType = ConnectionInfo.ProtocolType.values()[cr.getInt(1)].toString();
info.url = cr.getString(2);
info.id = cr.getString(3);
info.password = cr.getString(4);
cr.close();
}
db.close();
return info;
}
public static List<ConnectionInfo> getConnectionList() {
SQLiteDatabase db = sopDBAccess.getReadableDatabase();
List<ConnectionInfo> list = new ArrayList<>();
Cursor cr = null;
try {
cr = db.rawQuery("SELECT * FROM SOPViewer_ConnectionInfo", null);
} catch (Exception e) {
Log.d("TAG", e.getMessage());
}
if (cr != null) {
cr.moveToFirst();
for (int i = 0; i < cr.getCount(); i++) {
ConnectionInfo info = new ConnectionInfo();
info.connectionName = cr.getString(0);
info.protocol = cr.getInt(1);
info.protocolType = ConnectionInfo.ProtocolType.values()[cr.getInt(1)].toString();
info.url = cr.getString(2);
info.id = cr.getString(3);
info.password = cr.getString(4);
list.add(info);
cr.moveToNext();
}
cr.close();
}
db.close();
return list;
}
public static boolean insertConnection(ConnectionInfo conn) {
boolean res = false;
SQLiteDatabase db = sopDBAccess.getReadableDatabase();
ContentValues ctv = new ContentValues();
ctv.put("connectionName", conn.connectionName);
ctv.put("protocol", conn.protocol);
ctv.put("url", conn.url);
ctv.put("id", conn.id);
ctv.put("password", conn.password);
try {
long resLong = db.insert("SOPViewer_ConnectionInfo", "", ctv);
if (resLong >= 0)
res = true;
} catch (Exception e) {
Log.d("TAG", e.getMessage());
}
db.close();
return res;
}
public static boolean deleteConnection(String connName) {
boolean res = false;
SQLiteDatabase db = sopDBAccess.getReadableDatabase();
try {
long resLong = db.delete("SOPViewer_ConnectionInfo", "connectionName=?", new String[]{connName});
if (resLong >= 0)
res = true;
} catch (Exception e) {
Log.d("TAG", e.getMessage());
}
db.close();
return res;
}
public static boolean updateConnection(ConnectionInfo conn) {
boolean res = false;
SQLiteDatabase db = sopDBAccess.getWritableDatabase();
String name = conn.connectionName;
ContentValues ctv = new ContentValues();
ctv.put("protocol", conn.protocol);
ctv.put("url", conn.url);
ctv.put("id", conn.id);
ctv.put("password", conn.password);
try {
long resLong = db.update("SOPViewer_ConnectionInfo", ctv, "connectionName=?", new String[]{name});
if (resLong >= 0)
res = true;
} catch (Exception e) {
}
db.close();
return res;
}
public static List<PlayList> getPlayList() {
SQLiteDatabase db = sopDBAccess.getReadableDatabase();
List<PlayList> list = new ArrayList<>();
PlayList info = new PlayList();
PlayListItem item = new PlayListItem();
Cursor cr = null;
try {
cr = db.rawQuery("SELECT * FROM SOPViewer_PlayList ORDER BY playListName", null);
} catch (Exception e) {
}
if (cr != null) {
cr.moveToFirst();
String tmpName = "";
int guard = 0;
for (int i = 0; i < cr.getCount(); i++) {
try {
guard++;
if (!tmpName.equals(cr.getString(0))) {
if (guard > 1)
list.add(info);
info = new PlayList();
info.playListName = cr.getString(0);
info.loop = cr.getInt(1);
item.seq = cr.getInt(2);
item.localFullFilePath = cr.getString(3);
item.strPages = cr.getString(4);
item.sec = cr.getInt(5);
info.playListItem.add(item);
tmpName = info.playListName;
} else {
item.seq = cr.getInt(2);
item.localFullFilePath = cr.getString(3);
item.strPages = cr.getString(4);
item.sec = cr.getInt(5);
info.playListItem.add(item);
}
cr.moveToNext();
} catch (Exception e) {
}
}
cr.close();
}
db.close();
return list;
}
public static boolean insertPlayList(PlayList pList) {
boolean res = false;
SQLiteDatabase db = sopDBAccess.getReadableDatabase();
ContentValues ctv = new ContentValues();
for (PlayListItem item : pList.playListItem) {
ctv.put("playListName", pList.playListName);
ctv.put("loop", pList.loop);
ctv.put("seq", item.seq);
ctv.put("localFullFilePath", item.localFullFilePath);
ctv.put("strPages", item.strPages);
ctv.put("sec", item.sec);
try {
long resLong = db.insert("SOPViewer_PlayList", "", ctv);
if (resLong >= 0)
res = true;
} catch (Exception e) {
}
}
db.close();
return res;
}
public static boolean deletePlayList(String pListName) {
boolean res = false;
SQLiteDatabase db = sopDBAccess.getReadableDatabase();
try {
long resLong = db.delete("SOPViewer_PlayList", "playListName=?", new String[]{pListName});
if (resLong >= 0)
res = true;
} catch (Exception e) {
}
db.close();
return res;
}
public static boolean updatePlayList(PlayList pList) {
//updatedeleteinsert
boolean res = false;
SQLiteDatabase db = sopDBAccess.getWritableDatabase();
String name = "";
ContentValues ctv = new ContentValues();
try {
long resLong = db.update("SOPViewer_PlayList", ctv, "playListName=?", new String[]{name});
if (resLong >= 0)
res = true;
} catch (Exception e) {
}
db.close();
return res;
}
}
|
package com.tpb.projects.flow;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Parcelable;
import com.tpb.projects.R;
import com.tpb.projects.issues.IssueActivity;
import com.tpb.projects.milestones.MilestoneActivity;
import com.tpb.projects.milestones.MilestonesActivity;
import com.tpb.projects.project.ProjectActivity;
import com.tpb.projects.repo.RepoActivity;
import com.tpb.projects.repo.content.ContentActivity;
import com.tpb.projects.repo.content.FileActivity;
import com.tpb.projects.user.UserActivity;
import com.tpb.projects.util.Logger;
import java.util.ArrayList;
import java.util.List;
public class Interceptor extends Activity {
private static final String TAG = Interceptor.class.getSimpleName();
private Intent failIntent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
createFailIntent();
if(getIntent().getAction().equals(Intent.ACTION_VIEW) &&
getIntent().getData() != null &&
"github.com".equals(getIntent().getData().getHost())) {
final List<String> segments = getIntent().getData().getPathSegments();
Logger.i(TAG, "onCreate: Path: " + segments.toString());
if(segments.size() == 1) {
final Intent u = new Intent(Interceptor.this, UserActivity.class);
u.putExtra(getString(R.string.intent_username), segments.get(0));
startActivity(u);
overridePendingTransition(R.anim.slide_up, R.anim.none);
finish();
} else {
final Intent i = new Intent();
putRepo(i, segments);
switch(segments.size()) {
case 2: //Repo
i.setClass(Interceptor.this, RepoActivity.class);
break;
case 3:
if("projects".equals(segments.get(2))) {
i.setClass(Interceptor.this, RepoActivity.class);
i.putExtra(getString(R.string.intent_pager_page),
RepoActivity.PAGE_PROJECTS
);
} else if("issues".equals(segments.get(2))) {
i.setClass(Interceptor.this, RepoActivity.class);
i.putExtra(getString(R.string.intent_pager_page),
RepoActivity.PAGE_ISSUES
);
} else if("milestones".equals(segments.get(2))) {
i.setClass(Interceptor.this, MilestonesActivity.class);
} else if("commits".equals(segments.get(2))) {
i.setClass(Interceptor.this, RepoActivity.class);
i.putExtra(getString(R.string.intent_pager_page),
RepoActivity.PAGE_COMMITS
);
}
break;
case 4: //Project
if("projects".equals(segments.get(2))) {
i.setClass(Interceptor.this, ProjectActivity.class);
i.putExtra(getString(R.string.intent_project_number),
safelyExtractInt(segments.get(3))
);
final String path = getIntent().getDataString();
final StringBuilder id = new StringBuilder();
for(int j = path
.indexOf('#', path.indexOf(segments.get(3))) + 6; j < path
.length(); j++) {
if(path.charAt(j) >= '0' && path.charAt(j) <= '9')
id.append(path.charAt(j));
}
try {
i.putExtra(getString(R.string.intent_card_id),
safelyExtractInt(id.toString())
);
} catch(Exception ignored) {
}
} else if("issues".equals(segments.get(2))) {
i.setClass(Interceptor.this, IssueActivity.class);
i.putExtra(getString(R.string.intent_issue_number),
safelyExtractInt(segments.get(3))
);
} else if("milestone".equals(segments.get(2))) {
i.setClass(Interceptor.this, MilestonesActivity.class);
i.putExtra(getString(R.string.intent_milestone_number),
safelyExtractInt(segments.get(3))
);
}
break;
default:
if("tree".equals(segments.get(2))) {
i.setClass(Interceptor.this, ContentActivity.class);
final StringBuilder path = new StringBuilder();
for(int j = 3; j < segments.size(); j++) {
path.append(segments.get(j));
path.append('/');
}
i.putExtra(getString(R.string.intent_path), path.toString());
} else if("blob".equals(segments.get(2))) {
i.setClass(Interceptor.this, FileActivity.class);
final StringBuilder path = new StringBuilder();
for(int j = 2; j < segments.size(); j++) {
path.append('/');
path.append(segments.get(j));
}
i.putExtra(getString(R.string.intent_blob_path), path.toString());
} else if("milestone".equals(segments.get(2))) {
//TODO Deal with number and edit suffix
i.setClass(Interceptor.this, MilestoneActivity.class);
i.putExtra(getString(R.string.intent_milestone_number),
safelyExtractInt(segments.get(3))
);
} else if("releases".equals(segments.get(2))) {
i.setClass(Interceptor.this, RepoActivity.class);
}
}
if(i.getComponent() != null && i.getComponent().getClassName() != null) {
startActivity(i);
overridePendingTransition(R.anim.slide_up, R.anim.none);
finish();
} else {
fail();
}
}
} else {
fail();
}
}
private static int safelyExtractInt(String possibleInt) {
try {
return Integer.parseInt(possibleInt.replace("\\s+", ""));
} catch(NumberFormatException nfe) {
return -1;
}
}
private void putRepo(Intent i, List<String> segments) {
i.putExtra(getString(R.string.intent_repo), segments.get(0) + "/" + segments.get(1));
}
private void fail() {
Logger.e(TAG, "fail: ");
try {
if(failIntent != null) {
startActivity(failIntent);
finish();
} else {
startActivity(onFail());
finish();
}
} catch(Exception e) {
e.printStackTrace();
finish();
}
}
private void createFailIntent() {
new AsyncTask<Void, Void, Intent>() {
@Override
protected Intent doInBackground(Void... params) {
return onFail();
}
@Override
protected void onPostExecute(Intent intent) {
super.onPostExecute(intent);
Interceptor.this.failIntent = intent;
}
}.execute();
}
private Intent onFail() {
if(failIntent == null && getIntent() != null) {
return generateFailIntentWithoutApp();
} else {
return failIntent;
}
}
private Intent generateFailIntentWithoutApp() {
try {
final Intent intent = new Intent(getIntent().getAction());
intent.setData(getIntent().getData());
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.addCategory(Intent.CATEGORY_DEFAULT);
final List<ResolveInfo> resolvedInfo = getPackageManager()
.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
if(!resolvedInfo.isEmpty()) {
final List<Intent> targetedShareIntents = new ArrayList<>();
for(ResolveInfo resolveInfo : resolvedInfo) {
final String packageName = resolveInfo.activityInfo.packageName;
if(!packageName.equals(getPackageName())) {
final Intent targetedShareIntent = new Intent(getIntent().getAction());
targetedShareIntent.setData(getIntent().getData());
targetedShareIntent.setPackage(packageName);
targetedShareIntents.add(targetedShareIntent);
}
}
final Intent chooserIntent = Intent.createChooser(targetedShareIntents.remove(0),
getString(R.string.text_interceptor_open_with)
);
if(targetedShareIntents.size() > 0) {
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetedShareIntents
.toArray(new Parcelable[targetedShareIntents.size()]));
}
return chooserIntent;
}
} catch(Exception ignored) {
}
return failIntent;
}
}
|
package com.turlir.abakgists;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.TimeInterpolator;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.util.Pair;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import com.turlir.abakgists.allgists.view.AllGistsActivity;
import com.turlir.abakgists.notes.view.NotesActivity;
import com.turlir.abakgists.widgets.anim.base.Factory;
import com.turlir.abakgists.widgets.anim.creator.Timing;
import com.turlir.abakgists.widgets.anim.factor.ButtonAnimFactory;
import com.turlir.abakgists.widgets.anim.factor.Params;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class MainActivity extends AppCompatActivity {
private static final Timing COMMON = new Timing(0, 750);
@BindView(R.id.btn_all_gists)
View btnAllGists;
@BindView(R.id.btn_notes)
View btnNotes;
@BindView(R.id.btn_all_in_one)
View btnAll;
private AnimatorSet animation;
@Override
protected void onCreate(@Nullable Bundle state) {
super.onCreate(state);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
}
@Override
protected void onResume() {
super.onResume();
if (animation != null) {
compatReverse(animation);
}
}
@Override
protected void onPause() {
super.onPause();
if (animation != null) {
animation.removeAllListeners();
if (animation.isStarted()) {
animation.end();
}
}
}
@OnClick(R.id.btn_all_gists)
public void onClickAllGists(View v) {
buttonClick(btnAllGists, AllGistsActivity.class);
}
@OnClick(R.id.btn_notes)
public void onClickNotes() {
buttonClick(btnNotes, NotesActivity.class);
}
@OnClick(R.id.btn_all_in_one)
public void clickAllInOne() {
buttonClick(btnAll, AllInOneActivity.class);
}
private void buttonClick(View clicked, final Class clazz) {
Pair<Params, Params> animateParams = new Params.TwoWayBuilder(clicked)
.up(btnAllGists)
.center(btnNotes)
.down(btnAll)
.compute();
animation = animateButton(animateParams.first);
animation.start();
animation.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
Intent i = new Intent(getApplicationContext(), clazz);
startActivity(i);
}
});
}
private AnimatorSet animateButton(final Params params) {
Factory factory = new ButtonAnimFactory(params, COMMON);
return factory.animate(btnAllGists, btnNotes, btnAll);
}
private void compatReverse(AnimatorSet directAnim) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
oreoReverse(directAnim);
} else {
oldReverse(directAnim);
}
}
@TargetApi(Build.VERSION_CODES.O)
private void oreoReverse(AnimatorSet directAnim) {
if (directAnim.getTotalDuration() != Animator.DURATION_INFINITE) {
directAnim.reverse();
}
}
private void oldReverse(AnimatorSet directAnim) {
class ReverseInterpolator implements Interpolator {
private final TimeInterpolator delegate;
private ReverseInterpolator(TimeInterpolator delegate){
this.delegate = delegate;
}
private ReverseInterpolator(){
this(new LinearInterpolator());
}
@Override
public float getInterpolation(float input) {
return 1 - delegate.getInterpolation(input);
}
}
AnimatorSet back = new AnimatorSet();
back.play(directAnim);
back.setInterpolator(new ReverseInterpolator());
back.start();
}
}
|
package io.rong.app.activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import java.util.List;
import java.util.Locale;
import io.rong.app.DemoContext;
import io.rong.app.R;
import io.rong.app.fragment.FriendMultiChoiceFragment;
import io.rong.app.ui.LoadingDialog;
import io.rong.app.ui.WinToast;
import io.rong.imkit.RongIM;
import io.rong.imkit.common.RongConst;
import io.rong.imkit.fragment.ConversationFragment;
import io.rong.imkit.fragment.ConversationListFragment;
import io.rong.imkit.fragment.SubConversationListFragment;
import io.rong.imkit.fragment.UriFragment;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Discussion;
public class DemoActivity extends BaseActivity implements Handler.Callback {
private static final String TAG = DemoActivity.class.getSimpleName();
private String targetId;
/**
* targetIds
*/
private String targetIds;
private String mDiscussionId;
private Conversation.ConversationType mConversationType;
private LoadingDialog mDialog;
private Handler mHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.de_activity);
initView();
initData();
}
protected void initView() {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.de_actionbar_back);
mHandler = new Handler(this);
Intent intent = getIntent();
//push
if (intent != null && intent.getData() != null && intent.getData().getScheme().equals("rong") && intent.getData().getQueryParameter("push") != null) {
//intent.getData().getQueryParameter("push") truepush
if (DemoContext.getInstance() != null && intent.getData().getQueryParameter("push").equals("true")) {
Log.e(TAG,"0518---test-push --"+intent.getData());
// Intent in = new Intent(DemoActivity.this,LoginActivity.class);
// in.putExtra("PUSH_CONTEXT","push");
// startActivity(in);
if (DemoContext.getInstance() != null) {
String token = DemoContext.getInstance().getSharedPreferences().getString("DEMO_TOKEN", "defult");
reconnect(token);
}
} else {
enterFragment(intent);
}
} else if (intent != null) {
Log.e(TAG,"0518---test-activity--"+intent.getData());
enterFragment(intent);
}
}
/**
* push
*
* @param token
*/
private void reconnect(String token) {
mDialog = new LoadingDialog(this);
mDialog.setCancelable(false);
mDialog.setText("connect_auto_reconnect");
mDialog.show();
try {
RongIM.connect(token, new RongIMClient.ConnectCallback() {
@Override
public void onTokenIncorrect() {
}
@Override
public void onSuccess(String userId) {
mHandler.post(new Runnable() {
@Override
public void run() {
mDialog.dismiss();
Intent intent = getIntent();
if (intent != null) {
enterFragment(intent);
}
}
});
}
@Override
public void onError(RongIMClient.ErrorCode e) {
mHandler.post(new Runnable() {
@Override
public void run() {
mDialog.dismiss();
}
});
}
});
} catch (Exception e) {
mHandler.post(new Runnable() {
@Override
public void run() {
mDialog.dismiss();
}
});
e.printStackTrace();
}
}
/**
* fragment
*
* @param intent
*/
private void enterFragment(Intent intent) {
String tag = null;
if (intent != null) {
Fragment fragment = null;
if (intent.getExtras() != null && intent.getExtras().containsKey(RongConst.EXTRA.CONTENT)) {
String fragmentName = intent.getExtras().getString(RongConst.EXTRA.CONTENT);
fragment = Fragment.instantiate(this, fragmentName);
} else if (intent.getData() != null) {
if (intent.getData().getPathSegments().get(0).equals("conversation")) {
tag = "conversation";
if (intent.getData().getLastPathSegment().equals("system")) {
// String fragmentName = MessageListFragment.class.getCanonicalName();
// fragment = Fragment.instantiate(this, fragmentName);
startActivity(new Intent(DemoActivity.this, NewFriendListActivity.class));
finish();
List<Conversation> conversations = RongIM.getInstance().getRongIMClient().getConversationList(Conversation.ConversationType.SYSTEM);
for (int i = 0; i < conversations.size(); i++) {
RongIM.getInstance().getRongIMClient().clearMessagesUnreadStatus(Conversation.ConversationType.SYSTEM, conversations.get(i).getSenderUserId());
}
} else {
String fragmentName = ConversationFragment.class.getCanonicalName();
fragment = Fragment.instantiate(this, fragmentName);
}
} else if (intent.getData().getLastPathSegment().equals("conversationlist")) {
tag = "conversationlist";
String fragmentName = ConversationListFragment.class.getCanonicalName();
fragment = Fragment.instantiate(this, fragmentName);
} else if (intent.getData().getLastPathSegment().equals("subconversationlist")) {
tag = "subconversationlist";
String fragmentName = SubConversationListFragment.class.getCanonicalName();
fragment = Fragment.instantiate(this, fragmentName);
} else if (intent.getData().getPathSegments().get(0).equals("friend")) {
tag = "friend";
String fragmentName = FriendMultiChoiceFragment.class.getCanonicalName();
fragment = Fragment.instantiate(this, fragmentName);
ActionBar actionBar = getSupportActionBar();
actionBar.hide();//ActionBar
}
targetId = intent.getData().getQueryParameter("targetId");
targetIds = intent.getData().getQueryParameter("targetIds");
mDiscussionId = intent.getData().getQueryParameter("discussionId");
if (targetId != null) {
mConversationType = Conversation.ConversationType.valueOf(intent.getData().getLastPathSegment().toUpperCase(Locale.getDefault()));
} else if (targetIds != null)
mConversationType = Conversation.ConversationType.valueOf(intent.getData().getLastPathSegment().toUpperCase(Locale.getDefault()));
}
if (fragment != null) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.de_content, fragment, tag);
transaction.addToBackStack(null).commitAllowingStateLoss();
}
}
}
protected void initData() {
if (mConversationType != null) {
if (mConversationType.toString().equals("PRIVATE")) {
if (DemoContext.getInstance() != null)
getSupportActionBar().setTitle(DemoContext.getInstance().getUserNameByUserId(targetId));
} else if (mConversationType.toString().equals("GROUP")) {
if (DemoContext.getInstance() != null) {
getSupportActionBar().setTitle(DemoContext.getInstance().getGroupNameById(targetId));
}
} else if (mConversationType.toString().equals("DISCUSSION")) {
if (targetId != null) {
RongIM.getInstance().getRongIMClient().getDiscussion(targetId, new RongIMClient.ResultCallback<Discussion>() {
@Override
public void onSuccess(Discussion discussion) {
getSupportActionBar().setTitle(discussion.getName());
}
@Override
public void onError(RongIMClient.ErrorCode e) {
}
});
} else if (targetIds != null) {
setDiscussionName(targetIds);
} else {
getSupportActionBar().setTitle("");
}
} else if (mConversationType.toString().equals("SYSTEM")) {
getSupportActionBar().setTitle("");
} else if (mConversationType.toString().equals("CHATROOM")) {
getSupportActionBar().setTitle("");
} else if (mConversationType.toString().equals("CUSTOMER_SERVICE")) {
getSupportActionBar().setTitle("");
}else if(mConversationType.toString().equals("PUBLIC_APP_SERVICE")){
getSupportActionBar().setTitle("PUBLIC_APP_SERVICE");
}else if(mConversationType.toString().equals("PUBLIC_SERVICE")){
getSupportActionBar().setTitle("PUBLIC_SERVICE");
}
}
}
/**
* set discussion name
*
* @param targetIds
*/
private void setDiscussionName(String targetIds) {
StringBuilder sb = new StringBuilder();
getSupportActionBar().setTitle(targetIds);
String[] ids = targetIds.split(",");
if (DemoContext.getInstance() != null) {
for (int i = 0; i < ids.length; i++) {
DemoContext.getInstance().getUserNameByUserId(ids[i]);
sb.append(DemoContext.getInstance().getUserNameByUserId(ids[i]));
sb.append(",");
}
sb.append(DemoContext.getInstance().getSharedPreferences().getString("DEMO_USER_NAME", "0.0"));
}
getSupportActionBar().setTitle(sb);
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
String tag = null;
Fragment fragment = null;
if (intent.getExtras() != null && intent.getExtras().containsKey(RongConst.EXTRA.CONTENT)) {
String fragmentName = intent.getExtras().getString(RongConst.EXTRA.CONTENT);
fragment = Fragment.instantiate(this, fragmentName);
} else if (intent.getData() != null) {
if (intent.getData().getPathSegments().get(0).equals("conversation")) {
tag = "conversation";
fragment = getSupportFragmentManager().findFragmentByTag(tag);
if (fragment != null)
return;
String fragmentName = ConversationFragment.class.getCanonicalName();
fragment = Fragment.instantiate(this, fragmentName);
} else if (intent.getData().getLastPathSegment().equals("conversationlist")) {
tag = "conversationlist";
String fragmentName = ConversationListFragment.class.getCanonicalName();
fragment = Fragment.instantiate(this, fragmentName);
} else if (intent.getData().getLastPathSegment().equals("subconversationlist")) {
tag = "subconversationlist";
String fragmentName = SubConversationListFragment.class.getCanonicalName();
fragment = Fragment.instantiate(this, fragmentName);
}
}
if (fragment != null) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.de_content, fragment, tag);
transaction.addToBackStack(null).commitAllowingStateLoss();
}
}
@Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() == 1) {
super.onBackPressed();
this.finish();
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.de_conversation_menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.icon:
if (mConversationType == null) {
return false;
}
if (mConversationType == Conversation.ConversationType.PUBLIC_SERVICE || mConversationType == Conversation.ConversationType.APP_PUBLIC_SERVICE) {
RongIM.getInstance().startPublicServiceProfile(this, mConversationType, targetId);
} else {
//targetId
if (!TextUtils.isEmpty(targetId)) {
Uri uri = Uri.parse("demo://" + getApplicationInfo().packageName).buildUpon().appendPath("conversationSetting")
.appendPath(mConversationType.getName()).appendQueryParameter("targetId", targetId).build();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(uri);
startActivity(intent);
// targetIds
} else if (!TextUtils.isEmpty(targetIds)) {
UriFragment fragment = (UriFragment) getSupportFragmentManager().getFragments().get(0);
fragment.getUri();
// targetId
targetId = fragment.getUri().getQueryParameter("targetId");
if (!TextUtils.isEmpty(targetId)) {
Uri uri = Uri.parse("demo://" + getApplicationInfo().packageName).buildUpon().appendPath("conversationSetting")
.appendPath(mConversationType.getName()).appendQueryParameter("targetId", targetId).build();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(uri);
startActivity(intent);
} else {
WinToast.toast(DemoActivity.this, "");
}
}
}
break;
case android.R.id.home:
finish();
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean handleMessage(Message msg) {
return false;
}
}
|
package shivamdh.com.fitness60;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;
import java.util.Timer;
import static shivamdh.com.fitness60.Options.timerC;
/*
This class is used to by the user when creating a new workout. This class serves to handle all the renderings and
database manipulations. This class keeps all the individual activities within a workout in a list and keeps track of all their
data and properly packages it into the database. The class also handles activity deletion and addition through multiple on click listeners
and access to constructing the proper activity classes on the user's discretion.
*/
public class NewWorkout extends Fragment implements View.OnClickListener {
DatabaseHelper db;
private ArrayList<Activities> workoutActivities = new ArrayList<>();
private LayoutInflater currInflate;
private ViewGroup currContainer;
private View theView;
LinearLayout workoutTab;
Context appContext;
static WorkoutActivityDatabase myData;
public static boolean done = false; //default booleans
public static boolean Save = false;
public NewWorkout() {
// Required empty public constructor
done = true; //test the true boolean
}
public void setTheContext (Context aContext) {
appContext = aContext;
// db = new DatabaseHelper(appContext, 0);
}
//class within the class to help with the Dialog Fragment that gets called on when the app exit the fragment
public static class MyDialogFragment extends DialogFragment implements DialogInterface.OnClickListener {
public MyDialogFragment() {
super();
}
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new AlertDialog.Builder(getActivity()) //send out the appropriate dialog fragment to user for workout save feature
.setMessage("Workout closed. Would you like to save it?").setPositiveButton("Yes", this)
.setNegativeButton("No", this).create();
}
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) { //database actions depend on what the user selects
case DialogInterface.BUTTON_POSITIVE:
Save = true;
break;
case DialogInterface.BUTTON_NEGATIVE:
Save = false;
break;
default:
break;
}
}
}
@Override
public void onPause() {
super.onPause();
//Code below can be used to insert data into the database and allow the database to grow, still incomplete because
//the code only takes information of the first activity from the workout (which works well, just need to expand to all activites)
//in the workout
//THIS IS ONLY TAKING THE DATA FROM THE FIRST WORKOUT ACTIVITY, NEED IT TO DO ALL ACTIVITIES
// Cursor previousData;
// String buffer;
// if (myData != null) {
// previousData = myData.getAllData();
// previousData.moveToFirst();
// if (!previousData.isAfterLast()) {
// buffer = previousData.getString(0);
// } else {
// buffer = "";
// } else {
// buffer = "";
// int previousSets;
// try {
// previousSets = Integer.parseInt(buffer);
// } catch (NumberFormatException e) {
// previousSets = 0;
if (workoutActivities.get(0).getClass() == DistanceActivity.class) { //distance activity
myData = new WorkoutActivityDatabase(appContext, false, workoutActivities.get(0).table); //create normal database
} else { //normal activity
myData = new WorkoutActivityDatabase(appContext, true, workoutActivities.get(0).table); //create normal database
}
myData.addData();
}
@Override
public void onDestroyView() {
super.onDestroyView();
}
@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
//create local variables with inserted paramters
currContainer = container;
currInflate = inflater;
theView = currInflate.inflate(R.layout.new_workout, currContainer, false);
//used to display the time that the workout starts at
SimpleDateFormat time = new SimpleDateFormat(getString(R.string.dateFormat), Locale.CANADA);
Calendar theTime = Calendar.getInstance();
String displayTime = time.format(theTime.getTime());
String finalTime = getString(R.string.starting_workout) + " " + displayTime;
TextView toStartWorkout = (TextView) theView.findViewById(R.id.time_start);
toStartWorkout.setText(finalTime);
//test with one activity inserted as a default
workoutActivities.add(new Activities(container, theView, inflater, getContext(), workoutActivities.size()+1, getActivity(), true));
//set the button on click listeners for various tasks
Button addActivities = (Button) theView.findViewById(R.id.new_activity);
addActivities.setOnClickListener(this);
Button removeActivities = (Button) theView.findViewById(R.id.remove_last_activity);
removeActivities.setOnClickListener(this);
Button distanceActivity = (Button) theView.findViewById(R.id.distance_activity);
distanceActivity.setOnClickListener(this);
Button bodyweight = (Button) theView.findViewById(R.id.bodyweight_exercise);
bodyweight.setOnClickListener(this);
workoutTab = (LinearLayout) theView.findViewById(R.id.layout);
return theView;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.new_activity: //user asks for a new basic activity
if (timerC && workoutActivities.size() > 0) {
workoutActivities.get(workoutActivities.size()-1).setTimer.cancel();
}
workoutActivities.add(new Activities(currContainer, theView, currInflate, getContext(), workoutActivities.size()+1, getActivity(), true));
break;
case R.id.bodyweight_exercise: //user asks for a new bodyweight exercise activity
if (timerC && workoutActivities.size() > 0) {
workoutActivities.get(workoutActivities.size()-1).setTimer.cancel();
}
workoutActivities.add(new Activities(currContainer, theView, currInflate, getContext(), workoutActivities.size()+1, getActivity(), false));
break;
case R.id.remove_last_activity: //user wishes to remove the last activity in the workout
if (workoutActivities.size() > 0) {
if (timerC && workoutActivities.size() > 1) {
Activities nowLastActivity = workoutActivities.get(workoutActivities.size() - 2); // about to become the last activity now
if (workoutActivities.size() > 1 && nowLastActivity.setNumber > 0) { //start previous activities timer now, only if there was a timer left
TableLayout getTable = nowLastActivity.table;
TableRow wantedRow = (TableRow) getTable.getChildAt(nowLastActivity.getSetNumber());
TextView resumedTimer = (TextView) wantedRow.getChildAt(wantedRow.getChildCount()-1); //get the desired timer textview
int previousM = nowLastActivity.getPreviousMins(resumedTimer.getText()); //get the previous minutes on timer
int previousS = nowLastActivity.getPreviousSecs(resumedTimer.getText()); //get the previous seconds form the timer
nowLastActivity.setTime(resumedTimer); //set the class's timer to the timer last left off
Activities.start = System.currentTimeMillis() - ((previousM * 60) + previousS) * 1000; //set the time of the 'start' var according to previous timer's time
nowLastActivity.setTimer = new Timer(); //have to create a brand new time since last timer was canceled and deleted
nowLastActivity.setTimer.schedule(new Activities.runTimer(getActivity()), 1000, 1000);
}
}
workoutTab.removeViewAt(workoutActivities.size()); //safely remove the lass activity
workoutActivities.remove(workoutActivities.size() - 1); //take out the activity from the linkedlist
}
break;
case R.id.distance_activity: //user opts to start a distance activity
if (timerC && workoutActivities.size() > 0) {
workoutActivities.get(workoutActivities.size()-1).setTimer.cancel();
}
workoutActivities.add(new DistanceActivity(currContainer, theView, currInflate, getContext(), workoutActivities.size()+1, getActivity()));
break;
default:
break;
}
}
}
|
package jlibs.xml.sax.sniff.model.expr.nodeset;
import jlibs.xml.sax.sniff.engine.context.Context;
import jlibs.xml.sax.sniff.events.Event;
import jlibs.xml.sax.sniff.model.Datatype;
import jlibs.xml.sax.sniff.model.Node;
import jlibs.xml.sax.sniff.model.Notifier;
import jlibs.xml.sax.sniff.model.expr.Expression;
import java.util.Map;
import java.util.TreeMap;
/**
* @author Santhosh Kumar T
*/
public class Count extends ValidatedExpression{
public Count(Node contextNode, Notifier member, Expression predicate){
super(Datatype.NUMBER, contextNode, member, predicate);
}
class MyEvaluation extends DelayedEvaluation{
private TreeMap<Long, Double> map = new TreeMap<Long, Double>();
@Override
protected Object getCachedResult(){
if(storeDocumentOrder || listeners.get(0) instanceof Count)
return map;
else
return (double)map.size();
}
@Override
@SuppressWarnings({"unchecked"})
protected void consumeMemberResult(Object result){
if(result instanceof Event)
map.put(((Event)result).order(), 1d);
else if(result instanceof TreeMap)
map.putAll((Map<Long, Double>)result);
}
}
@Override
protected Evaluation createEvaluation(){
return new MyEvaluation();
}
@Override
public void onNotification(Notifier source, Context context, Object result){
onNotification2(source, context, result);
}
}
|
// OLEParser.java
package loci.formats.in;
import java.io.*;
import java.util.*;
import loci.formats.*;
public class OLEParser {
// -- Constants --
/** OLE compound magic number. */
private static final byte[] MAGIC_NUMBER = new byte[] {
(byte) 0xd0, (byte) 0xcf, 0x11, (byte) 0xe0,
(byte) 0xa1, (byte) 0xb1, 0x1a, (byte) 0xe1
};
// -- Fields --
/** Current file name. */
private String filename;
/** Current file input stream. */
private RandomAccessStream in;
/** Block allocation table. */
private int[] bat;
/** Small block allocation table. */
private int[] sbat;
/** Small block array. */
private byte[] smallBlockArray;
/** Big block size. */
private int bigBlock;
/** Small block size. */
private int smallBlock;
/** Byte array containing the entire array of property tables. */
private byte[] propertyArray;
/** Array of property table indices that we've already visited. */
private Vector indices;
/** Vector of parent nodes. */
private Vector parents;
/** Red-black tree representing the filesystem structure. */
private RedBlackTree fileSystem;
/** Blocks we've already read. */
private HashSet read;
/** Last property array index parsed. */
private int last;
/** Whether or not we've parsed all of the property array entries. */
private boolean parsedAll = false;
/** Ordered list of item names. */
private Vector itemNames;
// -- Variables for a weird special case --
/** Cut point for data shuffling. */
private int cutPoint;
/** Actual number of bytes read in the "main" file. */
private int realNumRead;
// -- Constructor --
public OLEParser(String filename) {
this.filename = filename;
}
// -- Internal API methods --
/** Check if this file is actually an OLE file. */
public static boolean isOLE(byte[] block) {
if (block == null) return false;
int len = block.length < MAGIC_NUMBER.length ? block.length :
MAGIC_NUMBER.length;
for (int i=0; i<len; i++) if (block[i] != MAGIC_NUMBER[i]) return false;
return true;
}
/** Parse blocks at the given depth within the file. */
public void parse(int depth) throws IOException {
in = new RandomAccessStream(filename);
parents = new Vector();
fileSystem = new RedBlackTree();
indices = new Vector();
read = new HashSet();
itemNames = new Vector();
long check = DataTools.read8SignedBytes(in, true);
if (check != DataTools.bytesToLong(MAGIC_NUMBER, true)) {
throw new IOException("File is not an OLE variant");
}
in.skipBytes(16);
short revision = DataTools.read2SignedBytes(in, true);
short version = DataTools.read2SignedBytes(in, true);
in.skipBytes(2);
bigBlock = (int) Math.pow(2, DataTools.read2SignedBytes(in, true));
smallBlock = (int) Math.pow(2, DataTools.read4SignedBytes(in, true));
in.skipBytes(8);
int batCount = DataTools.read4SignedBytes(in, true);
int propertyTableIndex = DataTools.read4SignedBytes(in, true);
in.skipBytes(8);
int sbatIndex = DataTools.read4SignedBytes(in, true);
int numSbatBlocks = DataTools.read4SignedBytes(in, true);
int xbatIndex = DataTools.read4SignedBytes(in, true);
int numXbatBlocks = DataTools.read4SignedBytes(in, true);
bat = new int[batCount + numXbatBlocks];
// read the BAT
for (int i=0; i<batCount; i++) {
bat[i] = DataTools.read4SignedBytes(in, true);
}
// TODO: read the XBAT if necessary (just add to the BAT for simplicity)
for (int i=batCount; i<bat.length; i++) {
// read the XBAT here
}
// read the SBAT
sbat = new int[numSbatBlocks * (bigBlock / 4)];
in.seek((sbatIndex+1) * bigBlock);
read.add(new Integer(sbatIndex + 1));
for (int i=0; i<sbat.length; i++) {
sbat[i] = DataTools.read4SignedBytes(in, true);
}
getPropertyArray(propertyTableIndex);
// recursively parse each directory entry
parseDir(0, 0);
}
/** Find and link together the blocks comprising the property table. */
private void getPropertyArray(int firstBlock) throws IOException {
// this is kind of inefficient for large files with small big block sizes
int pa = firstBlock + 1;
propertyArray = new byte[0];
Vector v = new Vector();
// really naive strategy:
// Read 524288 bytes at a time, and check each block in the buffer to see
// if it looks like a property array block. To check, look at bytes 66
// and 67; byte 66 should be 1, 2, or 5 and byte 67 should be 0 or 1.
// TODO : make this more efficient
byte[] buf = new byte[524288];
int baseBlock = 2;
while (in.getFilePointer() < in.length()) {
in.seek(baseBlock * bigBlock);
in.read(buf);
for (int i=0; i<(buf.length / bigBlock); i++) {
int offset = i * bigBlock;
byte check1 = buf[offset + 66];
byte check2 = buf[offset + 67];
short check3 = DataTools.bytesToShort(buf, offset + 64, 2, true);
if ((check1 == 1) || (check1 == 2) || (check1 == 5)) {
if (check2 == 0 || check2 == 1) {
if (check3 <= 32 && check3 >= 0) {
byte[] check4 = new byte[32 - check3];
System.arraycopy(buf, offset + (64 - check3),
check4, 0, check4.length);
boolean isZero = true;
for (int j=0; j<check4.length; j++) {
if (check4[j] != 0) isZero = false;
}
if (isZero) {
if (DataTools.bytesToInt(buf, offset + 116, 4, true) <
(in.length() / bigBlock)) {
v.add(new Integer(baseBlock + i + 2));
}
}
}
}
}
}
baseBlock += (buf.length / bigBlock);
}
int[] array = new int[v.size()];
for (int i=0; i<array.length; i++) {
array[i] = ((Integer) v.get(i)).intValue() - 2;
}
int next = 0;
while ((pa > 0) && (pa*bigBlock < in.length()) && (next <= array.length)) {
in.seek(pa * bigBlock);
read.add(new Integer(pa));
// allocate more space in the property array
byte[] tmp = propertyArray;
propertyArray = new byte[tmp.length + bigBlock];
System.arraycopy(tmp, 0, propertyArray, 0, tmp.length);
in.read(propertyArray, tmp.length, bigBlock);
if (next < array.length) pa = array[next];
next++;
}
}
/** Find and link together the blocks comprising the small block array. */
private void buildSmallBlockArray(int fileSize, int firstBlock)
throws IOException
{
int numBigBlocks = ((fileSize / 64) / bigBlock) + 1;
ByteVector sba = new ByteVector(3*bigBlock);
int blocksRead = 0;
while ((numBigBlocks > 0) && (firstBlock > 0)) {
in.seek(firstBlock * bigBlock);
read.add(new Integer(firstBlock));
byte[] block = new byte[bigBlock];
in.read(block);
for (int i=0; i<block.length; i+=4) {
if ((blocksRead*bigBlock + (i / 4)) < (fileSize / 64)) {
int blockNumber = DataTools.bytesToInt(block, i, 4, true);
if ((blockNumber*bigBlock) > 0) {
in.seek(blockNumber * bigBlock);
read.add(new Integer(blockNumber));
byte[] buf = new byte[bigBlock];
in.read(buf);
sba.add(buf);
}
}
}
smallBlockArray = sba.toByteArray();
firstBlock = sbat[firstBlock];
blocksRead++;
numBigBlocks
}
}
/**
* Parse a directory entry at the given depth, with the
* specified number of available bytes.
*/
private void parseDir(int depth, int ndx) throws IOException {
Vector toParse = new Vector();
toParse.add(new Integer(ndx));
int q = 0;
while (!parsedAll) {
while (q < toParse.size()) {
ndx = ((Integer) toParse.get(q)).intValue();
q++;
byte[] table = new byte[128];
System.arraycopy(propertyArray, ndx*128, table, 0, table.length);
last = ndx;
indices.add(new Integer(ndx));
// extract some information from the property table
byte[] b = new byte[64];
System.arraycopy(table, 0, b, 0, b.length);
StringBuffer sb = new StringBuffer();
for (int i=0; i<b.length; i++) {
sb = sb.append((char) b[i]);
}
String name = sb.toString();
if (name.trim().equals("")) return;
if (name.indexOf("(") != -1 && name.indexOf(")") != -1) {
itemNames.add(
name.substring(name.indexOf("(") + 1, name.indexOf(")")).trim());
}
short numNameChars = DataTools.bytesToShort(table, 64, 2, true);
byte propType = table[66]; // 1 = dir, 2 = file, 5 = root
byte nodeColor = table[67]; // 0 = red, 1 = black
int previousIndex = DataTools.bytesToInt(table, 68, 4, true);
int nextIndex = DataTools.bytesToInt(table, 72, 4, true);
int firstChildIndex = DataTools.bytesToInt(table, 76, 4, true);
int createdSeconds = DataTools.bytesToInt(table, 100, 4, true);
int createdDays = DataTools.bytesToInt(table, 104, 4, true);
int modifiedSeconds = DataTools.bytesToInt(table, 108, 4, true);
int modifiedDays = DataTools.bytesToInt(table, 112, 4, true);
int firstBlock = DataTools.bytesToInt(table, 116, 4, true);
int fileSize = DataTools.bytesToInt(table, 120, 4, true);
if (propType != 5) {
fileSystem.add(nodeColor, propType, ndx, nextIndex,
((Integer) parents.get(parents.size() - 1)).intValue(),
name, firstBlock, fileSize);
}
else if (fileSystem.nullRoot()) {
buildSmallBlockArray(fileSize, firstBlock);
fileSystem.add(nodeColor, propType, 0, nextIndex, -1, name,
firstBlock, fileSize);
parents.add(new Integer(0));
}
// add the child
if ((firstChildIndex != -1) &&
!indices.contains(new Integer(firstChildIndex)) &&
(firstChildIndex < (propertyArray.length / 128)))
{
if ((propType == 5) && fileSystem.nullRoot()) {
parents.add(new Integer(0));
}
else parents.add(new Integer(ndx));
depth++;
toParse.add(q, new Integer(firstChildIndex));
}
// add the previous node
if ((previousIndex != -1) &&
!indices.contains(new Integer(previousIndex)) &&
(previousIndex < (propertyArray.length / 128)))
{
toParse.add(q, new Integer(previousIndex));
}
// add the next node
if ((nextIndex != -1) && !indices.contains(new Integer(nextIndex)) &&
(nextIndex < (propertyArray.length / 128)))
{
toParse.add(q, new Integer(nextIndex));
}
}
toParse = new Vector();
q = 0;
for (int i=0; i<(propertyArray.length / 128); i++) {
if (!indices.contains(new Integer(i))) {
toParse.add(new Integer(i));
}
}
parsedAll = toParse.size() == 0;
}
}
/**
* Get the names of data items in the order they were parsed.
*/
public Vector getNames() {
return itemNames;
}
/**
* Build the files; that is, for each file, construct a byte array given
* the BAT and the starting block. The resulting pair of Vectors can be used
* by file format readers
*/
public Vector[] getFiles() throws IOException {
Vector leaves = fileSystem.getLeaf();
Vector names = new Vector(); // should be the full path through the tree
Vector files = new Vector();
for (int i=0; i<leaves.size(); i++) {
RedBlackTreeNode node = (RedBlackTreeNode) leaves.get(i);
names.add(node.getName());
int start = node.getFirstBlock();
int size = node.getSize() + bigBlock;
byte[] file = new byte[size];
int numRead = 0;
// if the size of the file is less than 4096, use the SBAT
// otherwise, use the BAT
Vector sread = new Vector();
if (size < 4096) {
//if (size < 8*bigBlock) {
int ndx = 2 * (start + 1);
if ((ndx + 1)*smallBlock >= smallBlockArray.length) {
ndx = start;
}
while ((numRead < size) && (ndx >= 0) &&
((ndx + 1) < smallBlockArray.length / smallBlock))
{
int toCopy = smallBlock;
if ((size - numRead) < smallBlock) {
toCopy = size - numRead;
}
sread.add(new Integer(ndx));
System.arraycopy(smallBlockArray, ndx*smallBlock, file,
numRead, toCopy);
numRead += toCopy;
if (ndx < sbat.length && sbat[ndx] >= 0) ndx = sbat[ndx];
else {
ndx++;
while (inSbat(ndx - 1) && !sread.contains(new Integer(ndx))) {
ndx++;
}
}
}
}
else {
start++;
int numBlocksInFile = 0;
HashSet v = new HashSet();
while ((numRead < size) && (start < (in.length() / bigBlock))) {
in.seek(bigBlock * start);
v.add(new Integer(start));
numBlocksInFile++;
int toCopy = bigBlock;
if ((size - numRead) < bigBlock) {
toCopy = size - numRead;
}
numRead += toCopy;
if (start < bat.length) {
start = bat[start];
}
else {
start++;
while (inBat(start - 1) && !read.contains(new Integer(start))) {
start++;
}
}
}
boolean reallyWeirdSpecialCase = false;
int ndx = 0;
if (numBlocksInFile < (size / bigBlock)) {
// In this case, we haven't found enough blocks to make up the file.
// This probably reflects a flaw in the parser logic, but since only
// one of our files demonstrates this behavior, it is reasonable to
// assume that this is just another brain-damaged aspect of the OLE
// file format.
// basically, we want to loop through each block in the file, check
// if it has already been read; if not, we will try to add it to
// the beginning of the block list for this file
ndx = v.size();
for (int j=0; j<(in.length() / bigBlock); j++) {
Integer ij = new Integer(j);
if (!read.contains(ij) && !inBat(j - 1) && !v.contains(ij)) {
v.add(ij);
}
}
if (v.size() > ndx) reallyWeirdSpecialCase = true;
}
// now read all of the blocks into the file
numRead = 0;
Iterator iter = v.iterator();
int j = 0;
while (iter.hasNext()) {
Integer ij = (Integer) iter.next();
in.seek(ij.intValue() * bigBlock);
read.add(ij);
int toCopy = bigBlock;
if ((size - numRead) < bigBlock) toCopy = size - numRead;
in.read(file, numRead, toCopy);
numRead += toCopy;
if ((j++ < ndx) && reallyWeirdSpecialCase) cutPoint += toCopy;
}
if (reallyWeirdSpecialCase) realNumRead = numRead;
}
files.add(file);
}
return new Vector[] {names, files};
}
public int shuffle() {
return cutPoint;
}
public int length() { return realNumRead; }
private boolean inSbat(int b) {
for (int i=0; i<sbat.length; i++) if (b == sbat[i]) return true;
return false;
}
private boolean inBat(int b) {
for (int i=0; i<bat.length; i++) if (b == bat[i]) return true;
return false;
}
}
|
// SDTReader.java
package loci.formats.in;
import java.io.*;
import loci.formats.*;
import loci.formats.meta.FilterMetadata;
import loci.formats.meta.MetadataStore;
public class SDTReader extends FormatReader {
// -- Fields --
/** Object containing SDT header information. */
protected SDTInfo info;
/** Offset to binary data. */
protected int off;
/** Number of time bins in lifetime histogram. */
protected int timeBins;
/** Number of spectral channels. */
protected int channels;
/** Whether to combine lifetime bins into single intensity image planes. */
protected boolean intensity = false;
// -- Constructor --
/** Constructs a new SDT reader. */
public SDTReader() {
super("SPCImage Data", "sdt");
}
// -- SDTReader API methods --
/**
* Toggles whether the reader should return intensity
* data only (the sum of each lifetime histogram).
*/
public void setIntensity(boolean intensity) {
FormatTools.assertId(currentId, false, 1);
this.intensity = intensity;
}
/**
* Gets whether the reader is combining each lifetime
* histogram into a summed intensity image plane.
*/
public boolean isIntensity() { return intensity; }
/** Gets the number of bins in the lifetime histogram. */
public int getTimeBinCount() {
return timeBins;
}
/** Gets the number of spectral channels. */
public int getChannelCount() {
return channels;
}
/** Gets object containing SDT header information. */
public SDTInfo getInfo() {
return info;
}
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#isThisType(byte[]) */
public boolean isThisType(byte[] block) { return false; }
/* @see loci.formats.IFormatReader#getChannelDimLengths() */
public int[] getChannelDimLengths() {
FormatTools.assertId(currentId, true, 1);
return intensity ? new int[] {channels} : new int[] {timeBins, channels};
}
/* @see loci.formats.IFormatReader#getChannelDimTypes() */
public String[] getChannelDimTypes() {
FormatTools.assertId(currentId, true, 1);
return intensity ? new String[] {FormatTools.SPECTRA} :
new String[] {FormatTools.LIFETIME, FormatTools.SPECTRA};
}
/* @see loci.formats.IFormatReader#isInterleaved(int) */
public boolean isInterleaved(int subC) {
FormatTools.assertId(currentId, true, 1);
return !intensity && subC == 0;
}
/**
* @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int)
*/
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h)
throws FormatException, IOException
{
FormatTools.assertId(currentId, true, 1);
FormatTools.checkPlaneNumber(this, no);
FormatTools.checkBufferSize(this, buf.length, w, h);
int sizeX = core.sizeX[series];
int sizeY = core.sizeY[series];
int bpp = FormatTools.getBytesPerPixel(core.pixelType[series]);
boolean little = core.littleEndian[series];
boolean direct = !intensity && x == 0 && y == 0 && w == sizeX && h == sizeY;
byte[] b = direct ? buf : new byte[sizeY * sizeX * timeBins * bpp];
in.seek(off + no * b.length);
in.readFully(b);
if (direct) return buf; // no cropping required
int scan = intensity ? bpp : timeBins * bpp;
for (int row=0; row<h; row++) {
int yi = (y + row) * sizeX * timeBins * bpp;
int ri = row * w * scan;
for (int col=0; col<w; col++) {
int xi = yi + (x + col) * timeBins * bpp;
int ci = ri + col * scan;
if (intensity) {
// combine all lifetime bins into single intensity value
short sum = 0;
for (int t=0; t<timeBins; t++) {
sum += DataTools.bytesToShort(b, xi + t * bpp, little);
}
DataTools.unpackShort(sum, buf, ci, little);
}
else {
// each lifetime bin is a separate interleaved "channel"
System.arraycopy(b, xi, buf, ci, scan);
}
}
}
return buf;
}
// -- IFormatHandler API methods --
/* @see loci.formats.IFormatHandler#close() */
public void close() throws IOException {
super.close();
off = timeBins = channels = 0;
info = null;
}
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
protected void initFile(String id) throws FormatException, IOException {
if (debug) debug("SDTReader.initFile(" + id + ")");
super.initFile(id);
in = new RandomAccessStream(id);
in.order(true);
status("Reading header");
// read file header information
info = new SDTInfo(in, metadata);
off = info.dataBlockOffs + 22;
timeBins = info.timeBins;
channels = info.channels;
addMeta("time bins", new Integer(timeBins));
addMeta("channels", new Integer(channels));
status("Populating metadata");
core.sizeX[0] = info.width;
core.sizeY[0] = info.height;
core.sizeZ[0] = 1;
core.sizeC[0] = intensity ? channels : timeBins * channels;
core.sizeT[0] = 1;
core.currentOrder[0] = "XYZTC";
core.pixelType[0] = FormatTools.UINT16;
core.rgb[0] = !intensity;
core.littleEndian[0] = true;
core.imageCount[0] = channels;
core.indexed[0] = false;
core.falseColor[0] = false;
core.metadataComplete[0] = true;
MetadataStore store =
new FilterMetadata(getMetadataStore(), isMetadataFiltered());
store.setImageName("", 0);
store.setImageCreationDate(
DataTools.convertDate(System.currentTimeMillis(), DataTools.UNIX), 0);
MetadataTools.populatePixels(store, this);
// CTR CHECK
// for (int i=0; i<core.sizeC[0]; i++) {
// store.setLogicalChannel(i, null, null, null, null, null, null, null,
// null, null, null, null, null, null, null, null, null, null, null, null,
// null, null, null, null, null);
}
}
|
package nars;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import nars.core.Memory;
import nars.core.Parameters;
import nars.entity.Task;
import nars.io.Symbols;
import nars.io.Texts;
import nars.language.Inheritance;
import nars.language.Product;
import nars.language.Term;
import nars.language.Variable;
import nars.operator.Operation;
import nars.operator.Operator;
import nars.prolog.Int;
import nars.prolog.NoSolutionException;
import nars.prolog.Parser;
import nars.prolog.Prolog;
import nars.prolog.SolveInfo;
import nars.prolog.Struct;
import nars.prolog.Theory;
import nars.prolog.Var;
/**
*
*
* Usage:
* (^prologQuery, "database(Query,0).", prolog0, "Query", #0)
*
* @author me
*/
public class PrologQueryOperator extends Operator {
private final PrologContext context;
private static class VariableInfo {
public nars.prolog.Term boundValue;
public String variableName; // only valid if it is not bound
// is the variable bound to a value? if false then it is a asked value which the operator should fill in
public boolean isBound() {
return boundValue != null;
}
}
public PrologQueryOperator(PrologContext context) {
super("^prologQuery");
this.context = context;
}
@Override
protected List<Task> execute(Operation operation, Term[] args, Memory memory) {
if (args.length < 2) {
// TODO< error report >
return null;
}
if (((args.length - 2) % 2) != 0) {
// TODO< error report >
return null;
}
// check if 1st parameter is a string
if (!(args[0] instanceof Term)) {
// TODO< report error >
return null;
}
// check if 2nd parameter is a string
if (!(args[1] instanceof Term)) {
// TODO< report error >
return null;
}
// try to retrive the prolog interpreter instance by the name of it
if (!context.prologInterpreters.containsKey(args[1])) {
// TODO< report error >
return null;
}
Prolog prologInterpreter = context.prologInterpreters.get(args[1]);
Term queryTerm = (Term)args[0];
String query = getStringOfTerm(queryTerm);
// get all variablenames
// prolog must resolve the variables and assign values to them
VariableInfo[] variableInfos = translateNarsArgumentsToQueryVariableInfos(args);
// execute
prologParseAndExecuteAndDereferenceInput(prologInterpreter, query, variableInfos);
// TODO< convert the result from the prolog to strings >
memory.output(Prolog.class, query + " | TODO");
//memory.output(Prolog.class, query + " | " + result);
// set result values
Term[] resultTerms = getResultVariablesFromPrologVariables(variableInfos, memory);
// create evaluation result
int i;
Term[] resultInnerProductTerms = new Term[2 + resultTerms.length*2];
resultInnerProductTerms[0] = args[0];
resultInnerProductTerms[1] = args[1];
for (i = 0; i < resultTerms.length; i++ ) {
resultInnerProductTerms[2+i*2+0] = args[2+i*2];
resultInnerProductTerms[2+i*2+1] = resultTerms[i];
}
Inheritance operatorInheritance = Operation.make(
Product.make(resultInnerProductTerms, memory),
this,
memory
);
// create the nars result and return it
Inheritance resultInheritance = Inheritance.make(
operatorInheritance,
new Term("prolog_evaluation"),
memory
);
memory.output(Task.class, resultInheritance);
ArrayList<Task> results = new ArrayList<>(1);
results.add(memory.newTask(resultInheritance, Symbols.JUDGMENT_MARK, 1f, 0.99f, Parameters.DEFAULT_JUDGMENT_PRIORITY, Parameters.DEFAULT_JUDGMENT_DURABILITY));
return results;
}
static private String[] getVariableNamesOfArgs(Term[] args) {
int numberOfVariables = (args.length - 2) / 2;
int variableI;
String[] variableNames = new String[numberOfVariables];
for( variableI = 0; variableI < numberOfVariables; variableI++ ) {
Term termWithVariableName = args[2+2*variableI];
if( !(termWithVariableName instanceof Term) ) {
throw new RuntimeException("Result Variable Name is not an term!");
}
variableNames[variableI] = getStringOfTerm(termWithVariableName);
}
return variableNames;
}
static private VariableInfo[] translateNarsArgumentsToQueryVariableInfos(Term[] args) {
int numberOfVariables = (args.length - 2) / 2;
int variableI;
VariableInfo[] resultVariableInfos = new VariableInfo[numberOfVariables];
for( variableI = 0; variableI < numberOfVariables; variableI++ ) {
resultVariableInfos[variableI] = new VariableInfo();
}
for( variableI = 0; variableI < numberOfVariables; variableI++ ) {
Term currentTerm = args[2+2*variableI];
Term valueOrVariableNarsTerm = args[2+2*variableI+1];
if( !(currentTerm instanceof Term) ) {
throw new RuntimeException("Result or Query Variable Name is not an term!");
}
resultVariableInfos[variableI].variableName = getStringOfTerm(currentTerm);
// following term can be a variable(if it is requested) or a term[with a constant](if it is given)
// we only branch for the constant case, because
// in the variable case it then not bound, which means that its a variable
if( !(valueOrVariableNarsTerm instanceof Variable) ) {
resultVariableInfos[variableI].boundValue = convertConstantNarsTermToPrologTerm(valueOrVariableNarsTerm);
}
}
return resultVariableInfos;
}
static private nars.prolog.Term convertConstantNarsTermToPrologTerm(Term term) {
String termAsString = term.name().toString();
if (termAsString.length() == 0) {
throw new RuntimeException("term length was zero!");
}
if (termAsString.charAt(0) == '"') {
// it is a string
String stringOfNarsTerm = getStringOfTerm(term);
// now we translate the string into a prolog string
return new nars.prolog.Struct(stringOfNarsTerm);
}
// if we are here it must be a number, either a double or a integer
if (containsDot(termAsString)) {
double doubleValue = Double.parseDouble(termAsString);
return new nars.prolog.Double(doubleValue);
}
else {
int intValue = Integer.parseInt(termAsString);
return new nars.prolog.Int(intValue);
}
}
// tries to convert the Term (which must be a string) to a string with the content
static public String getStringOfTerm(Term term) {
// escape sign codes
String string = term.name().toString();
string = Texts.unescape(string).toString();
if (string.charAt(0) != '"') {
throw new RuntimeException("term is not a string as expected!");
}
string = string.substring(1, string.length()-1);
// because the text can contain quoted text
string = unescape(string);
return string;
}
static private Term[] getResultVariablesFromPrologVariables(VariableInfo[] variableInfos, Memory memory) {
int variableI;
Term[] resultTerms = new Term[variableInfos.length];
for( variableI = 0; variableI < variableInfos.length; variableI++ ) {
resultTerms[variableI] = convertPrologTermToNarsTermRecursive(variableInfos[variableI].boundValue, memory);
}
return resultTerms;
}
// TODO< return status/ error/sucess >
private void prologParseAndExecuteAndDereferenceInput(Prolog prolog, String goal, VariableInfo[] variableInfos) {
SolveInfo solution;
// parse, fill in known variables
nars.prolog.Parser parser = new nars.prolog.Parser(prolog.getOperatorManager(), goal);
nars.prolog.Term queryTerm = parser.nextTerm(true);
queryTerm = replaceBoundVariablesOfPrologTermRecursive(queryTerm, variableInfos);
solution = prolog.solve(queryTerm);
if (solution == null ) {
return; // TODO error
}
if (!solution.isSuccess()) {
throw new RuntimeException("Query was not successful");
}
nars.prolog.Term solutionTerm;
try {
solutionTerm = solution.getSolution();
}
catch (NoSolutionException exception) {
throw new RuntimeException("Query had no solution");
}
int variableI;
for( variableI = 0; variableI < variableInfos.length; variableI++ ) {
// we don't to lookup a allready bound variable
if (variableInfos[variableI].isBound()) {
continue;
}
// get variable and dereference
// get the variable which has the name
Var variableTerm = getVariableByNameRecursive(solutionTerm, variableInfos[variableI].variableName);
if( variableTerm == null )
{
return; // error
}
variableTerm.resolveTerm();
nars.prolog.Term dereferencedTerm = variableTerm.getTerm();
variableInfos[variableI].boundValue = dereferencedTerm;
}
}
// sets unbound variables inside the term
// so for example the term a(X,6,Y) with X=7 in VariablesInfos gets rewritten to
// a(7,6,Y)
static private nars.prolog.Term replaceBoundVariablesOfPrologTermRecursive(nars.prolog.Term term, VariableInfo[] variableInfos) {
if (term instanceof nars.prolog.Struct) {
nars.prolog.Struct termAsStruct = (nars.prolog.Struct)term;
nars.prolog.Term[] replacedArguments = new nars.prolog.Term[termAsStruct.getArity()];
int childrenI;
// iterate over childrens
for (childrenI = 0; childrenI < termAsStruct.getArity(); childrenI++) {
replacedArguments[childrenI] = replaceBoundVariablesOfPrologTermRecursive(termAsStruct.getTerm(childrenI), variableInfos);
}
return new nars.prolog.Struct(termAsStruct.getName(), replacedArguments);
}
else if (term instanceof nars.prolog.Var) {
nars.prolog.Var termAsVar = (nars.prolog.Var)term;
for(VariableInfo iterationVariableInfo: variableInfos) {
if (!iterationVariableInfo.isBound()) {
continue;
}
if (termAsVar.getName().equals(iterationVariableInfo.variableName)) {
return iterationVariableInfo.boundValue;
}
}
return term;
}
else if( term instanceof nars.prolog.Int ) {
return term;
}
else if( term instanceof nars.prolog.Double ) {
return term;
}
else if( term instanceof nars.prolog.Float ) {
return term;
}
throw new RuntimeException("Internal Error: Unknown prolog term!");
}
// tries to convert a prolog term to a nars term
// a chained Prolog Struct List will be converted to a Nars-Product (because it maps good to a list and nars can kinda understand it)
// throws a exception if the term type is not handable
static private Term convertPrologTermToNarsTermRecursive(nars.prolog.Term prologTerm, Memory memory) {
if( prologTerm instanceof Int ) {
Int prologIntegerTerm = (Int)prologTerm;
return new Term(String.valueOf(prologIntegerTerm.intValue()));
}
else if( prologTerm instanceof nars.prolog.Double ) {
nars.prolog.Double prologDoubleTerm = (nars.prolog.Double)prologTerm;
return new Term(String.valueOf(prologDoubleTerm.floatValue()));
}
else if( prologTerm instanceof nars.prolog.Float ) {
nars.prolog.Float prologFloatTerm = (nars.prolog.Float)prologTerm;
return new Term(String.valueOf(prologFloatTerm.floatValue()));
}
else if( prologTerm instanceof Struct ) {
Struct structTerm = (Struct)prologTerm;
// check if it is a string (has arity 0) or a list/struct (arity == 2 because lists are composed out of 2 tuples)
if (structTerm.getArity() == 0) {
String variableAsString = structTerm.getName();
return new Term("\"" + variableAsString + "\"");
}
else if (structTerm.getArity() == 2 && structTerm.getName().equals(".")) {
// convert the result array to a nars thingy
ArrayList<nars.prolog.Term> structAsList = convertChainedStructToList(structTerm);
// convert the list to a nars product wth the cconverted elements
Term[] innerProductTerms = new Term[structAsList.size()];
for (int i = 0; i < structAsList.size(); i++) {
innerProductTerms[i] = convertPrologTermToNarsTermRecursive(structAsList.get(i), memory);
}
// is wraped up in a inheritance because there can also exist operators
// and it is better understandable by nars or other operators
return Inheritance.make(
Product.make(innerProductTerms, memory),
new Term("prolog_list"),
memory
);
}
else {
// must be a operation
// so we convert the operation to a nars term
// in the form
// <(*, operationName, param0, param1) --> prolog_operation>
String operationName = structTerm.getName();
// convert the result array to a nars thingy
ArrayList<nars.prolog.Term> parametersAsList = convertChainedStructToList(structTerm);
// convert the list to a nars product wth the cconverted elements
Term[] innerProductTerms = new Term[1+parametersAsList.size()];
for (int i = 0; i < parametersAsList.size(); i++) {
innerProductTerms[i+1] = convertPrologTermToNarsTermRecursive(parametersAsList.get(i), memory);
}
innerProductTerms[0] = new Term(operationName);
// is wraped up in a inheritance because there can also exist operators
// and it is better understandable by nars or other operators
return Inheritance.make(
Product.make(innerProductTerms, memory),
new Term("prolog_operation"),
memory
);
}
// unreachable
}
throw new RuntimeException("Unhandled type of result variable");
}
// tries to get a variable from a term by name
// returns null if it wasn't found
static private nars.prolog.Var getVariableByNameRecursive(nars.prolog.Term term, String name) {
if( term instanceof Struct ) {
Struct s = (Struct)term;
for (int i = 0; i < s.getArity(); i++) {
nars.prolog.Term iterationTerm = s.getArg(i);
nars.prolog.Var result = getVariableByNameRecursive(iterationTerm, name);
if( result != null ) {
return result;
}
}
return null;
}
else if( term instanceof nars.prolog.Var ) {
nars.prolog.Var termAsVar = (nars.prolog.Var)term;
String nameOfVar = termAsVar.name().toString();
if( nameOfVar.equals(name) ) {
return termAsVar;
}
return null;
}
else if( term instanceof Int ) {
return null;
}
else if( term instanceof nars.prolog.Double ) {
return null;
}
throw new RuntimeException("Internal Error: Unknown prolog term!");
}
// converts a chained compound term (which contains oher compound terms) to a list
static private ArrayList<nars.prolog.Term> convertChainedStructToList(Struct structTerm) {
ArrayList<nars.prolog.Term> result = new ArrayList<>();
Struct currentCompundTerm = structTerm;
for(;;) {
if( currentCompundTerm.getArity() == 0 ) {
// end is reached
break;
}
else if( currentCompundTerm.getArity() != 2 ) {
throw new RuntimeException("Compound must have two or zero arguments!");
}
result.add(currentCompundTerm.getArg(0));
nars.prolog.Term arg2 = currentCompundTerm.getArg(1);
if (arg2.isAtom()) {
Struct atomTerm = (Struct)arg2;
if (atomTerm.getName().equals("[]")) {
// this is the last element of the list, we are done
break;
}
else {
// we are here if we converted a parameterlist of a function to a list, append the last argument which is this
// and return
result.add(atomTerm);
break;
}
}
if (!(arg2 instanceof Struct)) {
throw new RuntimeException("Second argument of Struct term is expected to be a Struct term!");
}
currentCompundTerm = (Struct)(arg2);
}
return result;
}
// tries to convert a list with integer terms to an string
// checks also if the signs are correct
// throws an ConversionFailedException if the conversion is not possible
static private String tryToConvertPrologListToString(ArrayList<nars.prolog.Term> array) {
String result = "";
for( nars.prolog.Term iterationTerm : array ) {
if( !(iterationTerm instanceof Int) ) {
throw new PrologTheoryStringOperator.ConversionFailedException();
}
Int integerTerm = (Int)iterationTerm;
int integer = integerTerm.intValue();
if( integer > 127 || integer < 0 ) {
throw new PrologTheoryStringOperator.ConversionFailedException();
}
result += Character.toString((char)integer);
}
return result;
}
// TODO< move into prolog utils >
private static String unescape(String text) {
return text.replace("\\\"", "\"");
}
static private boolean containsDot(String string) {
return string.contains(".");
}
}
|
package org.jasig.portal.container.om.common;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.portlet.PreferencesValidator;
import org.apache.pluto.om.common.Preference;
import org.apache.pluto.om.common.PreferenceSet;
import org.apache.pluto.om.common.PreferenceSetCtrl;
/**
* Implementation of Apache Pluto object model.
* @author Ken Weiner, kweiner@unicon.net
* @version $Revision$
*/
public class PreferenceSetImpl implements PreferenceSet, PreferenceSetCtrl, Serializable {
Map preferences = null; // Preference name --> Preference
PreferencesValidator validator = null;
String validatorClassName = null;
ClassLoader classLoader = null;
public PreferenceSetImpl() {
preferences = new HashMap();
}
// PreferenceSet methods
public Iterator iterator() {
return preferences.values().iterator();
}
public Preference get(String name) {
return (Preference)preferences.get(name);
}
public PreferencesValidator getPreferencesValidator() {
if (validator == null) {
if (this.classLoader == null) {
throw new IllegalStateException("Portlet class loader is not yet available to load preferences validator.");
}
try {
if (validatorClassName != null) {
Object o = classLoader.loadClass(validatorClassName).newInstance();
if (o instanceof PreferencesValidator) {
validator = (PreferencesValidator)o;
}
}
} catch (Exception e) {
// Do nothing
e.printStackTrace();
}
}
return validator;
}
// PreferenceSetCtrl methods
public Preference add(String name, List values) {
return add(name, values, false);
}
public Preference remove(String name) {
return (Preference)preferences.remove(name);
}
public void remove(Preference preference) {
preferences.remove(preference.getName());
}
// Additional methods
public void setClassLoader(ClassLoader classLoader) {
this.classLoader = classLoader;
}
public void setPreferencesValidator(PreferencesValidator validator) {
this.validator = validator;
}
public void setPreferencesValidator(String validatorClassName) {
this.validatorClassName = validatorClassName;
}
public void clear() {
preferences.clear();
}
public Preference add(String name, List values, boolean readOnly) {
PreferenceImpl preference = new PreferenceImpl();
preference.setName(name);
preference.setValues(values);
preference.setReadOnly(readOnly);
preferences.put(name, preference);
return preference;
}
public void addAll(PreferenceSet preferences) {
Iterator iter = preferences.iterator();
while (iter.hasNext()) {
Preference preference = (Preference)iter.next();
this.preferences.put(preference.getName(), preference);
}
}
public int size() {
return preferences.size();
}
}
|
package org.pentaho.di.ui.spoon.delegates;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.MessageBox;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.NotePadMeta;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleStepException;
import org.pentaho.di.ui.core.gui.GUIResource;
import org.pentaho.di.core.gui.Point;
import org.pentaho.di.core.undo.TransAction;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.job.JobEntryLoader;
import org.pentaho.di.job.JobEntryType;
import org.pentaho.di.job.JobHopMeta;
import org.pentaho.di.job.JobMeta;
import org.pentaho.di.job.JobPlugin;
import org.pentaho.di.job.entries.special.JobEntrySpecial;
import org.pentaho.di.job.entries.sql.JobEntrySQL;
import org.pentaho.di.job.entries.trans.JobEntryTrans;
import org.pentaho.di.job.entry.JobEntryCopy;
import org.pentaho.di.job.entry.JobEntryDialogInterface;
import org.pentaho.di.job.entry.JobEntryInterface;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.repository.RepositoryDirectory;
import org.pentaho.di.ui.spoon.delegates.SpoonDelegate;
import org.pentaho.di.ui.spoon.job.JobGraph;
import org.pentaho.di.ui.spoon.job.JobHistory;
import org.pentaho.di.ui.spoon.job.JobHistoryRefresher;
import org.pentaho.di.ui.spoon.job.JobLog;
import org.pentaho.di.ui.spoon.wizards.RipDatabaseWizardPage1;
import org.pentaho.di.ui.spoon.wizards.RipDatabaseWizardPage2;
import org.pentaho.di.ui.spoon.wizards.RipDatabaseWizardPage3;
import org.pentaho.di.trans.StepLoader;
import org.pentaho.di.trans.TransHopMeta;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.StepDialogInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInterface;
import org.pentaho.di.trans.steps.tableinput.TableInputMeta;
import org.pentaho.di.trans.steps.tableoutput.TableOutputMeta;
import org.pentaho.di.ui.core.dialog.ErrorDialog;
import org.pentaho.di.ui.core.dialog.ShowMessageDialog;
import org.pentaho.di.ui.spoon.Messages;
import org.pentaho.di.ui.spoon.Spoon;
import org.pentaho.di.ui.spoon.TabMapEntry;
import org.pentaho.xul.swt.tab.TabItem;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
public class SpoonJobDelegate extends SpoonDelegate
{
/**
* This contains a map between the name of a transformation and the
* TransMeta object. If the transformation has no name it will be mapped
* under a number [1], [2] etc.
*/
private Map<String, JobMeta> jobMap;
public SpoonJobDelegate(Spoon spoon)
{
super(spoon);
jobMap = new Hashtable<String, JobMeta>();
}
public JobEntryCopy newJobEntry(JobMeta jobMeta, String type_desc, boolean openit)
{
JobEntryLoader jobLoader = JobEntryLoader.getInstance();
JobPlugin jobPlugin = null;
try
{
jobPlugin = jobLoader.findJobEntriesWithDescription(type_desc);
if (jobPlugin == null)
{
// Check if it's not START or DUMMY
if (JobMeta.STRING_SPECIAL_START.equals(type_desc)
|| JobMeta.STRING_SPECIAL_DUMMY.equals(type_desc))
{
jobPlugin = jobLoader.findJobEntriesWithID(JobMeta.STRING_SPECIAL);
}
}
if (jobPlugin != null)
{
// Determine name & number for this entry.
String basename = type_desc;
int nr = jobMeta.generateJobEntryNameNr(basename);
String entry_name = basename + " " + nr; //$NON-NLS-1$
// Generate the appropriate class...
JobEntryInterface jei = jobLoader.getJobEntryClass(jobPlugin);
jei.setName(entry_name);
if (jei.isSpecial())
{
if (JobMeta.STRING_SPECIAL_START.equals(type_desc))
{
// Check if start is already on the canvas...
if (jobMeta.findStart() != null)
{
JobGraph.showOnlyStartOnceMessage(spoon.getShell());
return null;
}
((JobEntrySpecial) jei).setStart(true);
jei.setName(JobMeta.STRING_SPECIAL_START);
}
if (JobMeta.STRING_SPECIAL_DUMMY.equals(type_desc))
{
((JobEntrySpecial) jei).setDummy(true);
// jei.setName(JobMeta.STRING_SPECIAL_DUMMY); // Don't overwrite the name
}
}
if (openit)
{
JobEntryDialogInterface d = getJobEntryDialog(jei, jobMeta);
if (d != null && d.open() != null)
{
JobEntryCopy jge = new JobEntryCopy();
jge.setEntry(jei);
jge.setLocation(50, 50);
jge.setNr(0);
jobMeta.addJobEntry(jge);
spoon.addUndoNew(jobMeta, new JobEntryCopy[] { jge }, new int[] { jobMeta
.indexOfJobEntry(jge) });
spoon.refreshGraph();
spoon.refreshTree();
return jge;
} else
{
return null;
}
} else
{
JobEntryCopy jge = new JobEntryCopy();
jge.setEntry(jei);
jge.setLocation(50, 50);
jge.setNr(0);
jobMeta.addJobEntry(jge);
spoon.addUndoNew(jobMeta, new JobEntryCopy[] { jge }, new int[] { jobMeta
.indexOfJobEntry(jge) });
spoon.refreshGraph();
spoon.refreshTree();
return jge;
}
} else
{
return null;
}
} catch (Throwable e)
{
new ErrorDialog(
spoon.getShell(),
Messages
.getString("Spoon.ErrorDiaspoon.getLog().UnexpectedErrorCreatingNewJobGraphEntry.Title"), Messages.getString("Spoon.ErrorDiaspoon.getLog().UnexpectedErrorCreatingNewJobGraphEntry.Message"), new Exception(e)); //$NON-NLS-1$ //$NON-NLS-2$
return null;
}
}
public JobEntryDialogInterface getJobEntryDialog(JobEntryInterface jei, JobMeta jobMeta)
{
String dialogClassName = jei.getDialogClassName();
try
{
Class<?> dialogClass;
Class<?>[] paramClasses = new Class[] { spoon.getShell().getClass(), JobEntryInterface.class,
Repository.class, JobMeta.class };
Object[] paramArgs = new Object[] { spoon.getShell(), jei, spoon.getRepository(), jobMeta };
Constructor<?> dialogConstructor;
dialogClass = jei.getPluginID()!=null?
JobEntryLoader.getInstance().loadClassByID(jei.getPluginID(),dialogClassName):
JobEntryLoader.getInstance().loadClass(jei.getJobEntryType().getDescription(), dialogClassName);
dialogConstructor = dialogClass.getConstructor(paramClasses);
return (JobEntryDialogInterface) dialogConstructor.newInstance(paramArgs);
} catch (Throwable t)
{
t.printStackTrace();
spoon.getLog().logError("Could not create dialog for " + dialogClassName, t.getMessage());
}
return null;
}
public StepDialogInterface getStepEntryDialog(StepMetaInterface stepMeta, TransMeta transMeta,
String stepName)
{
String dialogClassName = stepMeta.getDialogClassName();
try
{
Class<?> dialogClass;
Class<?>[] paramClasses = new Class[] { spoon.getShell().getClass(), Object.class,
TransMeta.class, String.class };
Object[] paramArgs = new Object[] { spoon.getShell(), stepMeta, transMeta, stepName };
Constructor<?> dialogConstructor;
dialogClass = stepMeta.getClass().getClassLoader().loadClass(dialogClassName);
dialogConstructor = dialogClass.getConstructor(paramClasses);
return (StepDialogInterface) dialogConstructor.newInstance(paramArgs);
} catch (Throwable t)
{
spoon.getLog().logError("Could not create dialog for " + dialogClassName, t.getMessage());
}
return null;
}
public void editJobEntry(JobMeta jobMeta, JobEntryCopy je)
{
try
{
spoon.getLog().logBasic(toString(), "edit job graph entry: " + je.getName()); //$NON-NLS-1$
JobEntryCopy before = (JobEntryCopy) je.clone_deep();
boolean entry_changed = false;
JobEntryInterface jei = je.getEntry();
if (jei.isSpecial())
{
JobEntrySpecial special = (JobEntrySpecial) jei;
if (special.isDummy())
return;
}
JobEntryDialogInterface d = getJobEntryDialog(jei, jobMeta);
if (d != null)
{
if (d.open() != null)
{
entry_changed = true;
}
if (entry_changed)
{
JobEntryCopy after = (JobEntryCopy) je.clone();
spoon.addUndoChange(jobMeta, new JobEntryCopy[] { before }, new JobEntryCopy[] { after },
new int[] { jobMeta.indexOfJobEntry(je) });
spoon.refreshGraph();
spoon.refreshTree();
}
} else
{
MessageBox mb = new MessageBox(spoon.getShell(), SWT.OK | SWT.ICON_INFORMATION);
mb.setMessage(Messages.getString("Spoon.Dialog.JobEntryCanNotBeChanged.Message")); //$NON-NLS-1$
mb.setText(Messages.getString("Spoon.Dialog.JobEntryCanNotBeChanged.Title")); //$NON-NLS-1$
mb.open();
}
} catch (Exception e)
{
if (!spoon.getShell().isDisposed())
new ErrorDialog(
spoon.getShell(),
Messages.getString("Spoon.ErrorDiaLog.ErrorEditingJobEntry.Title"), Messages.getString("Spoon.ErrorDiaspoon.getLog().ErrorEditingJobEntry.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$
}
}
public JobEntryTrans newJobEntry(JobMeta jobMeta, JobEntryType type)
{
JobEntryTrans je = new JobEntryTrans();
je.setJobEntryType(type);
String basename = type.getDescription();
int nr = jobMeta.generateJobEntryNameNr(basename);
je.setName(basename + " " + nr); //$NON-NLS-1$
spoon.setShellText();
return je;
}
public void deleteJobEntryCopies(JobMeta jobMeta, JobEntryCopy jobEntry)
{
String name = jobEntry.getName();
// TODO Show warning "Are you sure? This operation can't be undone." +
// clear undo buffer.
// First delete all the hops using entry with name:
JobHopMeta hi[] = jobMeta.getAllJobHopsUsing(name);
if (hi.length > 0)
{
int hix[] = new int[hi.length];
for (int i = 0; i < hi.length; i++)
hix[i] = jobMeta.indexOfJobHop(hi[i]);
spoon.addUndoDelete(jobMeta, hi, hix);
for (int i = hix.length - 1; i >= 0; i
jobMeta.removeJobHop(hix[i]);
}
// Then delete all the entries with name:
JobEntryCopy je[] = jobMeta.getAllJobGraphEntries(name);
int jex[] = new int[je.length];
for (int i = 0; i < je.length; i++)
jex[i] = jobMeta.indexOfJobEntry(je[i]);
if (je.length > 0)
spoon.addUndoDelete(jobMeta, je, jex);
for (int i = jex.length - 1; i >= 0; i
jobMeta.removeJobEntry(jex[i]);
jobMeta.clearUndo();
spoon.setUndoMenu(jobMeta);
spoon.refreshGraph();
spoon.refreshTree();
}
public void dupeJobEntry(JobMeta jobMeta, JobEntryCopy jobEntry)
{
if (jobEntry != null && !jobEntry.isStart())
{
JobEntryCopy dupejge = (JobEntryCopy) jobEntry.clone();
dupejge.setNr(jobMeta.findUnusedNr(dupejge.getName()));
if (dupejge.isDrawn())
{
Point p = jobEntry.getLocation();
dupejge.setLocation(p.x + 10, p.y + 10);
}
jobMeta.addJobEntry(dupejge);
spoon.refreshGraph();
spoon.refreshTree();
spoon.setShellText();
}
}
public void copyJobEntries(JobMeta jobMeta, JobEntryCopy jec[])
{
if (jec == null || jec.length == 0)
return;
String xml = XMLHandler.getXMLHeader();
xml += "<jobentries>" + Const.CR; //$NON-NLS-1$
for (int i = 0; i < jec.length; i++)
{
xml += jec[i].getXML();
}
xml += " </jobentries>" + Const.CR; //$NON-NLS-1$
spoon.toClipboard(xml);
}
public void pasteXML(JobMeta jobMeta, String clipcontent, Point loc)
{
try
{
Document doc = XMLHandler.loadXMLString(clipcontent);
// De-select all, re-select pasted steps...
jobMeta.unselectAll();
Node entriesnode = XMLHandler.getSubNode(doc, "jobentries"); //$NON-NLS-1$
int nr = XMLHandler.countNodes(entriesnode, "entry"); //$NON-NLS-1$
spoon.getLog()
.logDebug(toString(), "I found " + nr + " job entries to paste on location: " + loc); //$NON-NLS-1$ //$NON-NLS-2$
JobEntryCopy entries[] = new JobEntryCopy[nr];
// Point min = new Point(loc.x, loc.y);
Point min = new Point(99999999, 99999999);
for (int i = 0; i < nr; i++)
{
Node entrynode = XMLHandler.getSubNodeByNr(entriesnode, "entry", i); //$NON-NLS-1$
entries[i] = new JobEntryCopy(entrynode, jobMeta.getDatabases(), spoon.getRepository());
String name = jobMeta.getAlternativeJobentryName(entries[i].getName());
entries[i].setName(name);
if (loc != null)
{
Point p = entries[i].getLocation();
if (min.x > p.x)
min.x = p.x;
if (min.y > p.y)
min.y = p.y;
}
}
// What's the difference between loc and min?
// This is the offset:
Point offset = new Point(loc.x - min.x, loc.y - min.y);
// Undo/redo object positions...
int position[] = new int[entries.length];
for (int i = 0; i < entries.length; i++)
{
Point p = entries[i].getLocation();
String name = entries[i].getName();
entries[i].setLocation(p.x + offset.x, p.y + offset.y);
// Check the name, find alternative...
entries[i].setName(jobMeta.getAlternativeJobentryName(name));
jobMeta.addJobEntry(entries[i]);
position[i] = jobMeta.indexOfJobEntry(entries[i]);
}
// Save undo information too...
spoon.addUndoNew(jobMeta, entries, position);
if (jobMeta.hasChanged())
{
spoon.refreshTree();
spoon.refreshGraph();
}
} catch (KettleException e)
{
new ErrorDialog(
spoon.getShell(),
Messages.getString("Spoon.ErrorDiaspoon.getLog().ErrorPasingJobEntries.Title"), Messages.getString("Spoon.ErrorDiaspoon.getLog().ErrorPasingJobEntries.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$
}
}
public void newJobHop(JobMeta jobMeta, JobEntryCopy fr, JobEntryCopy to)
{
JobHopMeta hi = new JobHopMeta(fr, to);
jobMeta.addJobHop(hi);
spoon.addUndoNew(jobMeta, new JobHopMeta[] { hi }, new int[] { jobMeta.indexOfJobHop(hi) });
spoon.refreshGraph();
spoon.refreshTree();
}
/**
* Create a job that extracts tables & data from a database.
* <p>
* <p>
*
* 0) Select the database to rip
* <p>
* 1) Select the tables in the database to rip
* <p>
* 2) Select the database to dump to
* <p>
* 3) Select the repository directory in which it will end up
* <p>
* 4) Select a name for the new job
* <p>
* 5) Create an empty job with the selected name.
* <p>
* 6) Create 1 transformation for every selected table
* <p>
* 7) add every created transformation to the job & evaluate
* <p>
*
*/
public void ripDBWizard()
{
final List<DatabaseMeta> databases = spoon.getActiveDatabases();
if (databases.size() == 0)
return; // Nothing to do here
final RipDatabaseWizardPage1 page1 = new RipDatabaseWizardPage1("1", databases); //$NON-NLS-1$
page1.createControl(spoon.getShell());
final RipDatabaseWizardPage2 page2 = new RipDatabaseWizardPage2("2"); //$NON-NLS-1$
page2.createControl(spoon.getShell());
final RipDatabaseWizardPage3 page3 = new RipDatabaseWizardPage3("3", spoon.getRepository()); //$NON-NLS-1$
page3.createControl(spoon.getShell());
Wizard wizard = new Wizard()
{
public boolean performFinish()
{
JobMeta jobMeta = ripDB(databases, page3.getJobname(), page3.getRepositoryDirectory(), page3
.getDirectory(), page1.getSourceDatabase(), page1.getTargetDatabase(), page2
.getSelection());
if (jobMeta == null)
return false;
if (page3.getRepositoryDirectory() != null)
{
spoon.saveToRepository(jobMeta);
} else
{
spoon.saveToFile(jobMeta);
}
addJobGraph(jobMeta);
return true;
}
/**
* @see org.eclipse.jface.wizard.Wizard#canFinish()
*/
public boolean canFinish()
{
return page3.canFinish();
}
};
wizard.addPage(page1);
wizard.addPage(page2);
wizard.addPage(page3);
WizardDialog wd = new WizardDialog(spoon.getShell(), wizard);
wd.setMinimumPageSize(700, 400);
wd.updateSize();
wd.open();
}
public JobMeta ripDB(final List<DatabaseMeta> databases, final String jobname,
final RepositoryDirectory repdir, final String directory, final DatabaseMeta sourceDbInfo,
final DatabaseMeta targetDbInfo, final String[] tables)
{
// Create a new job...
final JobMeta jobMeta = new JobMeta(spoon.getLog());
jobMeta.setDatabases(databases);
jobMeta.setFilename(null);
jobMeta.setName(jobname);
if (spoon.getRepository() != null)
{
jobMeta.setDirectory(repdir);
} else
{
jobMeta.setFilename(Const.createFilename(directory, jobname, Const.STRING_JOB_DEFAULT_EXT));
}
spoon.refreshTree();
spoon.refreshGraph();
final Point location = new Point(50, 50);
// The start entry...
final JobEntryCopy start = JobMeta.createStartEntry();
start.setLocation(new Point(location.x, location.y));
start.setDrawn();
jobMeta.addJobEntry(start);
// final Thread parentThread = Thread.currentThread();
// Create a dialog with a progress indicator!
IRunnableWithProgress op = new IRunnableWithProgress()
{
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException
{
// This is running in a new process: copy some KettleVariables
// info
// LocalVariables.getInstance().createKettleVariables(Thread.currentThread().getName(),
// parentThread.getName(), true);
monitor.beginTask(Messages.getString("Spoon.RipDB.Monitor.BuildingNewJob"), tables.length); //$NON-NLS-1$
monitor.worked(0);
JobEntryCopy previous = start;
// Loop over the table-names...
for (int i = 0; i < tables.length && !monitor.isCanceled(); i++)
{
monitor
.setTaskName(Messages.getString("Spoon.RipDB.Monitor.ProcessingTable") + tables[i] + "]..."); //$NON-NLS-1$ //$NON-NLS-2$
// Create the new transformation...
String transname = Messages.getString("Spoon.RipDB.Monitor.Transname1") + sourceDbInfo + "].[" + tables[i] + Messages.getString("Spoon.RipDB.Monitor.Transname2") + targetDbInfo + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
TransMeta transMeta = new TransMeta((String) null, transname, null);
if (repdir != null)
{
transMeta.setDirectory(repdir);
} else
{
transMeta.setFilename(Const.createFilename(directory, transname,
Const.STRING_TRANS_DEFAULT_EXT));
}
// Add the source & target db
transMeta.addDatabase(sourceDbInfo);
transMeta.addDatabase(targetDbInfo);
// Add a note
String note = Messages.getString("Spoon.RipDB.Monitor.Note1") + tables[i] + Messages.getString("Spoon.RipDB.Monitor.Note2") + sourceDbInfo + "]" + Const.CR; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
note += Messages.getString("Spoon.RipDB.Monitor.Note3") + tables[i] + Messages.getString("Spoon.RipDB.Monitor.Note4") + targetDbInfo + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
NotePadMeta ni = new NotePadMeta(note, 150, 10, -1, -1);
transMeta.addNote(ni);
// Add the TableInputMeta step...
String fromstepname = Messages.getString("Spoon.RipDB.Monitor.FromStep.Name") + tables[i] + "]"; //$NON-NLS-1$ //$NON-NLS-2$
TableInputMeta tii = new TableInputMeta();
tii.setDatabaseMeta(sourceDbInfo);
tii.setSQL("SELECT * FROM " + sourceDbInfo.quoteField(tables[i])); //$NON-NLS-1$
String fromstepid = StepLoader.getInstance().getStepPluginID(tii);
StepMeta fromstep = new StepMeta(fromstepid, fromstepname, tii);
fromstep.setLocation(150, 100);
fromstep.setDraw(true);
fromstep
.setDescription(Messages.getString("Spoon.RipDB.Monitor.FromStep.Description") + tables[i] + Messages.getString("Spoon.RipDB.Monitor.FromStep.Description2") + sourceDbInfo + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
transMeta.addStep(fromstep);
// Add the TableOutputMeta step...
String tostepname = Messages.getString("Spoon.RipDB.Monitor.ToStep.Name") + tables[i] + "]"; //$NON-NLS-1$ //$NON-NLS-2$
TableOutputMeta toi = new TableOutputMeta();
toi.setDatabaseMeta(targetDbInfo);
toi.setTablename(tables[i]);
toi.setCommitSize(100);
toi.setTruncateTable(true);
String tostepid = StepLoader.getInstance().getStepPluginID(toi);
StepMeta tostep = new StepMeta(tostepid, tostepname, toi);
tostep.setLocation(500, 100);
tostep.setDraw(true);
tostep
.setDescription(Messages.getString("Spoon.RipDB.Monitor.ToStep.Description1") + tables[i] + Messages.getString("Spoon.RipDB.Monitor.ToStep.Description2") + targetDbInfo + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
transMeta.addStep(tostep);
// Add a hop between the two steps...
TransHopMeta hi = new TransHopMeta(fromstep, tostep);
transMeta.addTransHop(hi);
// Now we generate the SQL needed to run for this
// transformation.
// First set the limit to 1 to speed things up!
String tmpSql = tii.getSQL();
tii.setSQL(tii.getSQL() + sourceDbInfo.getLimitClause(1));
String sql = ""; //$NON-NLS-1$
try
{
sql = transMeta.getSQLStatementsString();
} catch (KettleStepException kse)
{
throw new InvocationTargetException(
kse,
Messages.getString("Spoon.RipDB.Exception.ErrorGettingSQLFromTransformation") + transMeta + "] : " + kse.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
}
// remove the limit
tii.setSQL(tmpSql);
// Now, save the transformation...
boolean ok;
if (spoon.getRepository() != null)
{
ok = spoon.saveToRepository(transMeta);
} else
{
ok = spoon.saveToFile(transMeta);
}
if (!ok)
{
throw new InvocationTargetException(
new Exception(
Messages
.getString("Spoon.RipDB.Exception.UnableToSaveTransformationToRepository")), Messages.getString("Spoon.RipDB.Exception.UnableToSaveTransformationToRepository")); //$NON-NLS-1$
}
// We can now continue with the population of the job...
location.x = 250;
if (i > 0)
location.y += 100;
// We can continue defining the job.
// First the SQL, but only if needed!
// If the table exists & has the correct format, nothing is
// done
if (!Const.isEmpty(sql))
{
String jesqlname = Messages.getString("Spoon.RipDB.JobEntrySQL.Name") + tables[i] + "]"; //$NON-NLS-1$ //$NON-NLS-2$
JobEntrySQL jesql = new JobEntrySQL(jesqlname);
jesql.setDatabase(targetDbInfo);
jesql.setSQL(sql);
jesql
.setDescription(Messages.getString("Spoon.RipDB.JobEntrySQL.Description") + targetDbInfo + "].[" + tables[i] + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
JobEntryCopy jecsql = new JobEntryCopy();
jecsql.setEntry(jesql);
jecsql.setLocation(new Point(location.x, location.y));
jecsql.setDrawn();
jobMeta.addJobEntry(jecsql);
// Add the hop too...
JobHopMeta jhi = new JobHopMeta(previous, jecsql);
jobMeta.addJobHop(jhi);
previous = jecsql;
}
// Add the jobentry for the transformation too...
String jetransname = Messages.getString("Spoon.RipDB.JobEntryTrans.Name") + tables[i] + "]"; //$NON-NLS-1$ //$NON-NLS-2$
JobEntryTrans jetrans = new JobEntryTrans(jetransname);
jetrans.setTransname(transMeta.getName());
if (spoon.getRepository() != null)
{
jetrans.setDirectory(transMeta.getDirectory());
} else
{
jetrans.setFileName(Const.createFilename("${"
+ Const.INTERNAL_VARIABLE_JOB_FILENAME_DIRECTORY + "}", transMeta.getName(),
Const.STRING_TRANS_DEFAULT_EXT));
}
JobEntryCopy jectrans = new JobEntryCopy(spoon.getLog(), jetrans);
jectrans
.setDescription(Messages.getString("Spoon.RipDB.JobEntryTrans.Description1") + Const.CR + Messages.getString("Spoon.RipDB.JobEntryTrans.Description2") + sourceDbInfo + "].[" + tables[i] + "]" + Const.CR + Messages.getString("Spoon.RipDB.JobEntryTrans.Description3") + targetDbInfo + "].[" + tables[i] + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
jectrans.setDrawn();
location.x += 400;
jectrans.setLocation(new Point(location.x, location.y));
jobMeta.addJobEntry(jectrans);
// Add a hop between the last 2 job entries.
JobHopMeta jhi2 = new JobHopMeta(previous, jectrans);
jobMeta.addJobHop(jhi2);
previous = jectrans;
monitor.worked(1);
}
monitor.worked(100);
monitor.done();
}
};
try
{
ProgressMonitorDialog pmd = new ProgressMonitorDialog(spoon.getShell());
pmd.run(false, true, op);
} catch (InvocationTargetException e)
{
new ErrorDialog(
spoon.getShell(),
Messages.getString("Spoon.ErrorDiaspoon.getLog().RipDB.ErrorRippingTheDatabase.Title"), Messages.getString("Spoon.ErrorDiaspoon.getLog().RipDB.ErrorRippingTheDatabase.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$
return null;
} catch (InterruptedException e)
{
new ErrorDialog(
spoon.getShell(),
Messages.getString("Spoon.ErrorDiaspoon.getLog().RipDB.ErrorRippingTheDatabase.Title"), Messages.getString("Spoon.ErrorDiaspoon.getLog().RipDB.ErrorRippingTheDatabase.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$
return null;
} finally
{
spoon.refreshGraph();
spoon.refreshTree();
}
return jobMeta;
}
public void addJobHistory(JobMeta jobMeta, boolean select)
{
// See if there already is a tab for this history view
// If no, add it
// If yes, select that tab
String tabName = spoon.delegates.tabs.makeJobHistoryTabName(jobMeta);
TabItem tabItem = spoon.delegates.tabs.findTabItem(tabName, TabMapEntry.OBJECT_TYPE_JOB_HISTORY);
if (tabItem == null)
{
JobHistory jobHistory = new JobHistory(spoon.tabfolder.getSwtTabset(), spoon, jobMeta);
tabItem = new TabItem(spoon.tabfolder, tabName, tabName);
tabItem.setToolTipText(Messages.getString("Spoon.Title.ExecHistoryJobView.Tooltip", spoon.delegates.tabs
.makeJobGraphTabName(jobMeta)));
tabItem.setControl(jobHistory);
// If there is an associated log window that's open, find it and add
// a refresher
JobLog jobLog = findJobLogOfJob(jobMeta);
if (jobLog != null)
{
JobHistoryRefresher jobHistoryRefresher = new JobHistoryRefresher(tabItem, jobHistory);
spoon.tabfolder.addListener(jobHistoryRefresher);
jobLog.setJobHistoryRefresher(jobHistoryRefresher);
}
jobHistory.markRefreshNeeded(); // will refresh when first selected
spoon.delegates.tabs.addTab(tabName, new TabMapEntry(tabItem, tabName, jobHistory,
TabMapEntry.OBJECT_TYPE_JOB_HISTORY));
}
if (select)
{
int idx = spoon.tabfolder.indexOf(tabItem);
spoon.tabfolder.setSelected(idx);
}
}
public boolean isDefaultJobName(String name)
{
if (!name.startsWith(Spoon.STRING_JOB))
return false;
// see if there are only digits behind the job...
// This will detect:
// "Job"
// "Job "
// "Job 1"
// "Job 2"
for (int i = Spoon.STRING_JOB.length() + 1; i < name.length(); i++)
{
if (!Character.isDigit(name.charAt(i)))
return false;
}
return true;
}
public JobGraph findJobGraphOfJob(JobMeta jobMeta)
{
// Now loop over the entries in the tab-map
for (TabMapEntry mapEntry : spoon.delegates.tabs.getTabs())
{
if (mapEntry.getObject() instanceof JobGraph)
{
JobGraph jobGraph = (JobGraph) mapEntry.getObject();
if (jobGraph.getMeta().equals(jobMeta))
return jobGraph;
}
}
return null;
}
public JobLog findJobLogOfJob(JobMeta jobMeta)
{
// Now loop over the entries in the tab-map
for (TabMapEntry mapEntry : spoon.delegates.tabs.getTabs())
{
if (mapEntry.getObject() instanceof JobLog)
{
JobLog jobLog = (JobLog) mapEntry.getObject();
if (jobLog.getMeta().equals(jobMeta))
return jobLog;
}
}
return null;
}
/**
* Add a job to the job map
*
* @param jobMeta
* the job to add to the map
* @return the key used to store the transformation in the map
*/
public String addJob(JobMeta jobMeta)
{
String key = spoon.delegates.tabs.makeJobGraphTabName(jobMeta);
JobMeta xjob = jobMap.get(key);
if (xjob == null)
{
jobMap.put(key, jobMeta);
} else
{
// found a transformation tab that has the same name, is it the same
// as the one we want to load, if not warn the user of the duplicate name
boolean same = false;
if (jobMeta.isRepReference() && xjob.isRepReference())
{
// a repository value
same = jobMeta.getDirectory().getPath().equals(xjob.getDirectory().getPath());
}
else if (jobMeta.isFileReference() && xjob.isFileReference()){
// a file system entry
same = jobMeta.getFilename().equals(xjob.getFilename());
}
if (!same) {
ShowMessageDialog dialog = new ShowMessageDialog(spoon.getShell(), SWT.OK | SWT.ICON_INFORMATION,
Messages.getString("Spoon.Dialog.JobAlreadyLoaded.Title"), "'" + key + "'" + Const.CR
+ Const.CR + Messages.getString("Spoon.Dialog.JobAlreadyLoaded.Message"));
dialog.setTimeOut(6);
dialog.open();
}
}
return key;
}
/**
* @param transMeta
* the transformation to close, make sure it's ok to dispose of
* it BEFORE you call this.
*/
public void closeJob(JobMeta jobMeta)
{
String tabName = spoon.delegates.tabs.makeJobGraphTabName(jobMeta);
jobMap.remove(tabName);
// Close the associated tabs...
TabItem graphTab = spoon.delegates.tabs.findTabItem(tabName, TabMapEntry.OBJECT_TYPE_JOB_GRAPH);
if (graphTab != null)
{
spoon.delegates.tabs.removeTab(tabName);
graphTab.dispose();
}
// Logging
String logTabName = spoon.delegates.tabs.makeJobLogTabName(jobMeta);
TabItem logTab = spoon.delegates.tabs.findTabItem(logTabName, TabMapEntry.OBJECT_TYPE_JOB_LOG);
if (logTab != null)
{
logTab.dispose();
spoon.delegates.tabs.removeTab(logTabName);
}
// History
String historyTabName = spoon.delegates.tabs.makeJobHistoryTabName(jobMeta);
TabItem historyTab = spoon.delegates.tabs.findTabItem(historyTabName, TabMapEntry.OBJECT_TYPE_JOB_HISTORY);
if (historyTab != null)
{
historyTab.dispose();
spoon.delegates.tabs.removeTab(historyTabName);
}
spoon.refreshTree();
}
public void addJobGraph(JobMeta jobMeta)
{
String key = addJob(jobMeta);
if (key != null)
{
// See if there already is a tab for this graph
// If no, add it
// If yes, select that tab
String tabName = spoon.delegates.tabs.makeJobGraphTabName(jobMeta);
TabItem tabItem = spoon.delegates.tabs.findTabItem(tabName, TabMapEntry.OBJECT_TYPE_JOB_GRAPH);
if (tabItem == null)
{
JobGraph jobGraph = new JobGraph(spoon.tabfolder.getSwtTabset(), spoon, jobMeta);
tabItem = new TabItem(spoon.tabfolder, tabName, tabName);
tabItem.setToolTipText(Messages.getString("Spoon.TabJob.Tooltip", spoon.delegates.tabs
.makeJobGraphTabName(jobMeta)));
tabItem.setImage(GUIResource.getInstance().getImageJobGraph());
tabItem.setControl(jobGraph);
spoon.delegates.tabs.addTab(tabName, new TabMapEntry(tabItem, tabName, jobGraph,
TabMapEntry.OBJECT_TYPE_JOB_GRAPH));
}
int idx = spoon.tabfolder.indexOf(tabItem);
// OK, also see if we need to open a new history window.
if (jobMeta.getLogConnection() != null && !Const.isEmpty(jobMeta.getLogTable()))
{
addJobHistory(jobMeta, false);
}
// keep the focus on the graph
spoon.tabfolder.setSelected(idx);
spoon.setUndoMenu(jobMeta);
spoon.enableMenus();
}
}
public void addJobLog(JobMeta jobMeta)
{
// See if there already is a tab for this log
// If no, add it
// If yes, select that tab
String tabName = spoon.delegates.tabs.makeJobLogTabName(jobMeta);
TabItem tabItem = spoon.delegates.tabs.findTabItem(tabName, TabMapEntry.OBJECT_TYPE_JOB_LOG);
if (tabItem == null)
{
JobLog jobLog = new JobLog(spoon.tabfolder.getSwtTabset(), spoon, jobMeta);
tabItem = new TabItem(spoon.tabfolder, tabName, tabName);
tabItem.setText(tabName);
tabItem.setToolTipText(Messages.getString("Spoon.Title.ExecLogJobView.Tooltip", spoon.delegates.tabs
.makeJobGraphTabName(jobMeta)));
tabItem.setControl(jobLog);
// If there is an associated history window, we want to keep that
// one up-to-date as well.
JobHistory jobHistory = findJobHistoryOfJob(jobMeta);
TabItem historyItem = spoon.delegates.tabs.findTabItem(spoon.delegates.tabs.makeJobHistoryTabName(jobMeta),
TabMapEntry.OBJECT_TYPE_JOB_HISTORY);
if (jobHistory != null && historyItem != null)
{
JobHistoryRefresher jobHistoryRefresher = new JobHistoryRefresher(historyItem, jobHistory);
spoon.tabfolder.addListener(jobHistoryRefresher);
jobLog.setJobHistoryRefresher(jobHistoryRefresher);
}
spoon.delegates.tabs.addTab(tabName, new TabMapEntry(tabItem, tabName, jobLog,
TabMapEntry.OBJECT_TYPE_JOB_LOG));
}
int idx = spoon.tabfolder.indexOf(tabItem);
spoon.tabfolder.setSelected(idx);
}
public List<JobMeta> getJobList()
{
return new ArrayList<JobMeta>(jobMap.values());
}
public JobMeta getJob(String tabItemText)
{
return jobMap.get(tabItemText);
}
public JobMeta[] getLoadedJobs()
{
List<JobMeta> list = new ArrayList<JobMeta>(jobMap.values());
return list.toArray(new JobMeta[list.size()]);
}
public void addJob(String key, JobMeta entry)
{
jobMap.put(key, entry);
}
public void removeJob(String key)
{
jobMap.remove(key);
}
public JobHistory findJobHistoryOfJob(JobMeta jobMeta)
{
if (jobMeta == null)
return null;
// Now loop over the entries in the tab-map
for (TabMapEntry mapEntry : spoon.delegates.tabs.getTabs())
{
if (mapEntry.getObject() instanceof JobHistory)
{
JobHistory jobHistory = (JobHistory) mapEntry.getObject();
if (jobHistory.getMeta() != null && jobHistory.getMeta().equals(jobMeta))
return jobHistory;
}
}
return null;
}
public void redoJobAction(JobMeta jobMeta, TransAction transAction)
{
switch (transAction.getType())
{
// NEW
case TransAction.TYPE_ACTION_NEW_JOB_ENTRY:
// re-delete the entry at correct location:
{
JobEntryCopy si[] = (JobEntryCopy[]) transAction.getCurrent();
int idx[] = transAction.getCurrentIndex();
for (int i = 0; i < idx.length; i++)
jobMeta.addJobEntry(idx[i], si[i]);
spoon.refreshTree();
spoon.refreshGraph();
}
break;
case TransAction.TYPE_ACTION_NEW_NOTE:
// re-insert the note at correct location:
{
NotePadMeta ni[] = (NotePadMeta[]) transAction.getCurrent();
int idx[] = transAction.getCurrentIndex();
for (int i = 0; i < idx.length; i++)
jobMeta.addNote(idx[i], ni[i]);
spoon.refreshTree();
spoon.refreshGraph();
}
break;
case TransAction.TYPE_ACTION_NEW_JOB_HOP:
// re-insert the hop at correct location:
{
JobHopMeta hi[] = (JobHopMeta[]) transAction.getCurrent();
int idx[] = transAction.getCurrentIndex();
for (int i = 0; i < idx.length; i++)
jobMeta.addJobHop(idx[i], hi[i]);
spoon.refreshTree();
spoon.refreshGraph();
}
break;
// DELETE
case TransAction.TYPE_ACTION_DELETE_JOB_ENTRY:
// re-remove the entry at correct location:
{
int idx[] = transAction.getCurrentIndex();
for (int i = idx.length - 1; i >= 0; i
jobMeta.removeJobEntry(idx[i]);
spoon.refreshTree();
spoon.refreshGraph();
}
break;
case TransAction.TYPE_ACTION_DELETE_NOTE:
// re-remove the note at correct location:
{
int idx[] = transAction.getCurrentIndex();
for (int i = idx.length - 1; i >= 0; i
jobMeta.removeNote(idx[i]);
spoon.refreshTree();
spoon.refreshGraph();
}
break;
case TransAction.TYPE_ACTION_DELETE_JOB_HOP:
// re-remove the hop at correct location:
{
int idx[] = transAction.getCurrentIndex();
for (int i = idx.length - 1; i >= 0; i
jobMeta.removeJobHop(idx[i]);
spoon.refreshTree();
spoon.refreshGraph();
}
break;
// CHANGE
// We changed a step : undo this...
case TransAction.TYPE_ACTION_CHANGE_JOB_ENTRY:
// replace with "current" version.
{
for (int i = 0; i < transAction.getCurrent().length; i++)
{
JobEntryCopy copy = (JobEntryCopy) ((JobEntryCopy) (transAction.getCurrent()[i]))
.clone_deep();
jobMeta.getJobEntry(transAction.getCurrentIndex()[i]).replaceMeta(copy);
}
spoon.refreshTree();
spoon.refreshGraph();
}
break;
// We changed a note : undo this...
case TransAction.TYPE_ACTION_CHANGE_NOTE:
// Delete & re-insert
{
NotePadMeta ni[] = (NotePadMeta[]) transAction.getCurrent();
int idx[] = transAction.getCurrentIndex();
for (int i = 0; i < idx.length; i++)
{
jobMeta.removeNote(idx[i]);
jobMeta.addNote(idx[i], ni[i]);
}
spoon.refreshTree();
spoon.refreshGraph();
}
break;
// We changed a hop : undo this...
case TransAction.TYPE_ACTION_CHANGE_JOB_HOP:
// Delete & re-insert
{
JobHopMeta hi[] = (JobHopMeta[]) transAction.getCurrent();
int idx[] = transAction.getCurrentIndex();
for (int i = 0; i < idx.length; i++)
{
jobMeta.removeJobHop(idx[i]);
jobMeta.addJobHop(idx[i], hi[i]);
}
spoon.refreshTree();
spoon.refreshGraph();
}
break;
// CHANGE POSITION
case TransAction.TYPE_ACTION_POSITION_JOB_ENTRY:
{
// Find the location of the step:
int idx[] = transAction.getCurrentIndex();
Point p[] = transAction.getCurrentLocation();
for (int i = 0; i < p.length; i++)
{
JobEntryCopy entry = jobMeta.getJobEntry(idx[i]);
entry.setLocation(p[i]);
}
spoon.refreshGraph();
}
break;
case TransAction.TYPE_ACTION_POSITION_NOTE:
{
int idx[] = transAction.getCurrentIndex();
Point curr[] = transAction.getCurrentLocation();
for (int i = 0; i < idx.length; i++)
{
NotePadMeta npi = jobMeta.getNote(idx[i]);
npi.setLocation(curr[i]);
}
spoon.refreshGraph();
}
break;
default:
break;
}
}
public void undoJobAction(JobMeta jobMeta, TransAction transAction)
{
switch (transAction.getType())
{
// We created a new entry : undo this...
case TransAction.TYPE_ACTION_NEW_JOB_ENTRY:
// Delete the entry at correct location:
{
int idx[] = transAction.getCurrentIndex();
for (int i = idx.length - 1; i >= 0; i
jobMeta.removeJobEntry(idx[i]);
spoon.refreshTree();
spoon.refreshGraph();
}
break;
// We created a new note : undo this...
case TransAction.TYPE_ACTION_NEW_NOTE:
// Delete the note at correct location:
{
int idx[] = transAction.getCurrentIndex();
for (int i = idx.length - 1; i >= 0; i
jobMeta.removeNote(idx[i]);
spoon.refreshTree();
spoon.refreshGraph();
}
break;
// We created a new hop : undo this...
case TransAction.TYPE_ACTION_NEW_JOB_HOP:
// Delete the hop at correct location:
{
int idx[] = transAction.getCurrentIndex();
for (int i = idx.length - 1; i >= 0; i
jobMeta.removeJobHop(idx[i]);
spoon.refreshTree();
spoon.refreshGraph();
}
break;
// DELETE
// We delete an entry : undo this...
case TransAction.TYPE_ACTION_DELETE_STEP:
// un-Delete the entry at correct location: re-insert
{
JobEntryCopy ce[] = (JobEntryCopy[]) transAction.getCurrent();
int idx[] = transAction.getCurrentIndex();
for (int i = 0; i < ce.length; i++)
jobMeta.addJobEntry(idx[i], ce[i]);
spoon.refreshTree();
spoon.refreshGraph();
}
break;
// We delete new note : undo this...
case TransAction.TYPE_ACTION_DELETE_NOTE:
// re-insert the note at correct location:
{
NotePadMeta ni[] = (NotePadMeta[]) transAction.getCurrent();
int idx[] = transAction.getCurrentIndex();
for (int i = 0; i < idx.length; i++)
jobMeta.addNote(idx[i], ni[i]);
spoon.refreshTree();
spoon.refreshGraph();
}
break;
// We deleted a new hop : undo this...
case TransAction.TYPE_ACTION_DELETE_JOB_HOP:
// re-insert the hop at correct location:
{
JobHopMeta hi[] = (JobHopMeta[]) transAction.getCurrent();
int idx[] = transAction.getCurrentIndex();
for (int i = 0; i < hi.length; i++)
{
jobMeta.addJobHop(idx[i], hi[i]);
}
spoon.refreshTree();
spoon.refreshGraph();
}
break;
// CHANGE
// We changed a job entry: undo this...
case TransAction.TYPE_ACTION_CHANGE_JOB_ENTRY:
// Delete the current job entry, insert previous version.
{
for (int i = 0; i < transAction.getPrevious().length; i++)
{
JobEntryCopy copy = (JobEntryCopy) ((JobEntryCopy) transAction.getPrevious()[i]).clone();
jobMeta.getJobEntry(transAction.getCurrentIndex()[i]).replaceMeta(copy);
}
spoon.refreshTree();
spoon.refreshGraph();
}
break;
// We changed a note : undo this...
case TransAction.TYPE_ACTION_CHANGE_NOTE:
// Delete & re-insert
{
NotePadMeta prev[] = (NotePadMeta[]) transAction.getPrevious();
int idx[] = transAction.getCurrentIndex();
for (int i = 0; i < idx.length; i++)
{
jobMeta.removeNote(idx[i]);
jobMeta.addNote(idx[i], prev[i]);
}
spoon.refreshTree();
spoon.refreshGraph();
}
break;
// We changed a hop : undo this...
case TransAction.TYPE_ACTION_CHANGE_JOB_HOP:
// Delete & re-insert
{
JobHopMeta prev[] = (JobHopMeta[]) transAction.getPrevious();
int idx[] = transAction.getCurrentIndex();
for (int i = 0; i < idx.length; i++)
{
jobMeta.removeJobHop(idx[i]);
jobMeta.addJobHop(idx[i], prev[i]);
}
spoon.refreshTree();
spoon.refreshGraph();
}
break;
// POSITION
// The position of a step has changed: undo this...
case TransAction.TYPE_ACTION_POSITION_JOB_ENTRY:
// Find the location of the step:
{
int idx[] = transAction.getCurrentIndex();
Point p[] = transAction.getPreviousLocation();
for (int i = 0; i < p.length; i++)
{
JobEntryCopy entry = jobMeta.getJobEntry(idx[i]);
entry.setLocation(p[i]);
}
spoon.refreshGraph();
}
break;
// The position of a note has changed: undo this...
case TransAction.TYPE_ACTION_POSITION_NOTE:
int idx[] = transAction.getCurrentIndex();
Point prev[] = transAction.getPreviousLocation();
for (int i = 0; i < idx.length; i++)
{
NotePadMeta npi = jobMeta.getNote(idx[i]);
npi.setLocation(prev[i]);
}
spoon.refreshGraph();
break;
default:
break;
}
}
}
|
package imagej.data.types;
import java.math.BigDecimal;
import java.math.RoundingMode;
import net.imglib2.type.numeric.ComplexType;
/**
* A complex number that stores values in BigDecimal (arbitrary) precision. This
* class is useful for supporting DataType translations with minimal data loss.
*
* @author Barry DeZonia
*/
public class BigComplex implements ComplexType<BigComplex> {
// TODO - if we implement FloatingType interface then this class will be
// tricky to implement. acos, tanh, sin, atanh, etc.
private BigDecimal r, i;
public BigComplex() {
setZero();
}
public BigComplex(BigDecimal r, BigDecimal i) {
setReal(r);
setImag(i);
}
public BigComplex(double r, double i) {
setReal(BigDecimal.valueOf(r));
setImag(BigDecimal.valueOf(i));
}
public BigDecimal getReal() {
return r;
}
public BigDecimal getImag() {
return i;
}
public void setReal(BigDecimal r) {
this.r = r;
}
public void setImag(BigDecimal i) {
this.i = i;
}
@Override
public void add(BigComplex c) {
r = r.add(c.r);
i = i.add(c.i);
}
@Override
public void sub(BigComplex c) {
r = r.subtract(c.r);
i = i.subtract(c.i);
}
@Override
public void mul(BigComplex c) {
BigDecimal a = r.multiply(c.r);
BigDecimal b = i.multiply(c.i);
BigDecimal sum1 = a.subtract(b);
a = i.multiply(c.r);
a = r.multiply(c.i);
BigDecimal sum2 = a.add(b);
r = sum1;
i = sum2;
}
@Override
public void div(BigComplex c) {
BigDecimal a = c.r.multiply(c.r);
BigDecimal b = c.r.multiply(c.r);
BigDecimal denom = a.add(b);
a = r.multiply(c.r);
b = i.multiply(c.i);
BigDecimal sum1 = a.add(b);
a = i.multiply(c.r);
b = r.multiply(c.i);
BigDecimal sum2 = a.subtract(b);
r = sum1.divide(denom);
i = sum2.divide(denom);
}
@Override
public void setZero() {
r = BigDecimal.ZERO;
i = BigDecimal.ZERO;
}
@Override
public void setOne() {
r = BigDecimal.ONE;
i = BigDecimal.ZERO;
}
@Override
public void mul(float c) {
mul(new BigComplex(BigDecimal.valueOf(c), BigDecimal.ZERO));
}
@Override
public void mul(double c) {
mul(new BigComplex(BigDecimal.valueOf(c), BigDecimal.ZERO));
}
@Override
public BigComplex createVariable() {
return new BigComplex();
}
@Override
public BigComplex copy() {
return new BigComplex(r, i);
}
@Override
public void set(BigComplex c) {
this.r = c.r;
this.i = c.i;
}
@Override
public void complexConjugate() {
i = i.negate();
}
// -- narrowing methods --
@Override
public double getRealDouble() {
return r.doubleValue();
}
@Override
public float getRealFloat() {
return r.floatValue();
}
@Override
public double getImaginaryDouble() {
return i.doubleValue();
}
@Override
public float getImaginaryFloat() {
return i.floatValue();
}
@Override
public void setReal(float f) {
r = BigDecimal.valueOf(f);
}
@Override
public void setReal(double f) {
r = BigDecimal.valueOf(f);
}
@Override
public void setImaginary(float f) {
i = BigDecimal.valueOf(f);
}
@Override
public void setImaginary(double f) {
i = BigDecimal.valueOf(f);
}
@Override
public void setComplexNumber(float r, float i) {
setReal(r);
setImaginary(i);
}
@Override
public void setComplexNumber(double r, double i) {
setReal(r);
setImaginary(i);
}
@Override
public float getPowerFloat() {
return modulus().floatValue();
}
@Override
public double getPowerDouble() {
return modulus().doubleValue();
}
@Override
public float getPhaseFloat() {
return phase().floatValue();
}
@Override
public double getPhaseDouble() {
return phase().doubleValue();
}
// -- helpers --
private BigDecimal modulus() {
BigDecimal a = r.multiply(r);
BigDecimal b = i.multiply(i);
BigDecimal sum = a.add(b);
return bigSqrt(sum);
}
private BigDecimal phase() {
return atan2(i, r);
}
private static final BigDecimal TWO = new BigDecimal(2);
private static final int DIGITS = 50;
private static final BigDecimal SQRT_PRE = new BigDecimal(10).pow(DIGITS);
private static BigDecimal bigSqrt(BigDecimal c) {
return sqrtNewtonRaphson(c, BigDecimal.ONE, BigDecimal.ONE.divide(SQRT_PRE));
}
private static BigDecimal sqrtNewtonRaphson(BigDecimal c, BigDecimal xn,
BigDecimal precision)
{
BigDecimal fx = xn.pow(2).add(c.negate());
BigDecimal fpx = xn.multiply(TWO);
BigDecimal xn1 = fx.divide(fpx, 2 * DIGITS, RoundingMode.HALF_DOWN);
xn1 = xn.add(xn1.negate());
BigDecimal currentSquare = xn1.pow(2);
BigDecimal currentPrecision = currentSquare.subtract(c);
currentPrecision = currentPrecision.abs();
if (currentPrecision.compareTo(precision) < 0) {
return xn1;
}
return sqrtNewtonRaphson(c, xn1, precision);
}
// NB - PI limited to 50 decimal places of precision so narrowing possible
private static final BigDecimal PI = new BigDecimal(
"3.14159265358979323846264338327950288419716939937510");
private BigDecimal atan2(BigDecimal y, BigDecimal x) {
BigDecimal tx = x;
BigDecimal ty = y;
BigDecimal angle = BigDecimal.ZERO;
if (tx.compareTo(BigDecimal.ZERO) < 0) {
angle = PI;
tx = tx.negate();
ty = ty.negate();
}
else if (ty.compareTo(BigDecimal.ZERO) < 0)
angle = TWO.multiply(PI);
BigDecimal xNew, yNew;
for (int j = 0; j < ANGLES.length; j++) {
BigDecimal twoPowJ = POWERS_OF_TWO[j];
if (ty.compareTo(BigDecimal.ZERO) < 0) {
// Rotate counter-clockwise
xNew = tx.subtract(ty.divide(twoPowJ));
yNew = ty.add(tx.divide(twoPowJ));
angle = angle.subtract(ANGLES[j]);
}
else {
// Rotate clockwise
xNew = tx.add(ty.divide(twoPowJ));
yNew = ty.subtract(tx.divide(twoPowJ));
angle = angle.add(ANGLES[j]);
}
tx = xNew;
ty = yNew;
}
return angle;
}
// ATAN helpers
// To increase precision: keep adding angles from wolfram alpha. One can see
// precision by counting leading zeros of last entry in table below. More
// angles requires more processing time. It takes 3 or 4 angles to increase
// precision by one place.
private static final BigDecimal[] ANGLES =
new BigDecimal[] {
// taken from wolfram alpha: entry i = atan(2^(-(i))
new BigDecimal("0.7853981633974483096156608458198757210492923498437764"),
new BigDecimal("0.4636476090008061162142562314612144020285370542861202"),
new BigDecimal("0.2449786631268641541720824812112758109141440983811840"),
new BigDecimal("0.1243549945467614350313548491638710255731701917698040"),
new BigDecimal("0.0624188099959573484739791129855051136062738877974991"),
new BigDecimal("0.0312398334302682762537117448924909770324956637254000"),
new BigDecimal("0.0156237286204768308028015212565703189111141398009054"),
new BigDecimal("0.0078123410601011112964633918421992816212228117250147"),
new BigDecimal("0.0039062301319669718276286653114243871403574901152028"),
new BigDecimal("0.0019531225164788186851214826250767139316107467772335"),
new BigDecimal("0.0009765621895593194304034301997172908516341970158100"),
new BigDecimal("0.0004882812111948982754692396256448486661923611331350"),
new BigDecimal("0.0002441406201493617640167229432596599862124177909706"),
new BigDecimal("0.0001220703118936702042390586461179563009308294090157"),
new BigDecimal("0.0000610351561742087750216625691738291537851435368333"),
new BigDecimal("0.0000305175781155260968618259534385360197509496751194"),
new BigDecimal("0.0000152587890613157621072319358126978851374292381445"),
new BigDecimal("0.0000076293945311019702633884823401050905863507439184"),
new BigDecimal("0.0000038146972656064962829230756163729937228052573039"),
new BigDecimal("0.0000019073486328101870353653693059172441687143421654"),
new BigDecimal("0.00000095367431640596087942067068992311239001963412449"),
new BigDecimal("0.00000047683715820308885992758382144924707587049404378"),
new BigDecimal("0.00000023841857910155798249094797721893269783096898769"),
new BigDecimal("0.00000011920928955078068531136849713792211264596758766"),
new BigDecimal("0.000000059604644775390554413921062141788874250030195782"),
new BigDecimal("0.000000029802322387695303676740132767709503349043907067"),
new BigDecimal("0.000000014901161193847655147092516595963247108248930025"),
new BigDecimal(
"0.0000000074505805969238279871365645744953921132066925545"),
new BigDecimal(
"0.0000000037252902984619140452670705718119235836719483287"),
new BigDecimal(
"0.0000000018626451492309570290958838214764904345065282835"),
new BigDecimal(
"0.0000000009313225746154785153557354776845613038929264961"),
new BigDecimal(
"0.0000000004656612873077392577788419347105701629734786389"),
new BigDecimal(
"0.0000000002328306436538696289020427418388212703712742932"),
new BigDecimal(
"0.0000000001164153218269348144525990927298526587963964573"),
new BigDecimal(
"0.00000000005820766091346740722649676159123158234954915625"),
new BigDecimal(
"0.00000000002910383045673370361327303269890394779369363200"),
new BigDecimal(
"0.00000000001455191522836685180663959783736299347421170360"),
new BigDecimal(
"0.000000000007275957614183425903320184104670374184276462938"),
new BigDecimal(
"0.000000000003637978807091712951660140200583796773034557866"),
new BigDecimal(
"0.000000000001818989403545856475830076118822974596629319733"),
new BigDecimal(
"0.0000000000009094947017729282379150388117278718245786649666"),
new BigDecimal(
"0.0000000000004547473508864641189575194999034839780723331208"),
new BigDecimal(
"0.0000000000002273736754432320594787597617066854972590416401"),
new BigDecimal(
"0.0000000000001136868377216160297393798823227106871573802050"),
new BigDecimal(
"0.00000000000005684341886080801486968994134502633589467252562") };
private static BigDecimal[] POWERS_OF_TWO = powersOfTwo();
private static BigDecimal[] powersOfTwo() {
BigDecimal[] powers = new BigDecimal[ANGLES.length];
for (int i = 0; i < ANGLES.length; i++) {
powers[i] = TWO.pow(i);
}
return powers;
}
/* useful if we implement sine and cosine
private static final BigDecimal[] K_VALUES = new BigDecimal[MAX_ATAN_ITERS];
static {
// K(0) = (1 / sqrt(1 + (2^(-(2*0)))))
// K(1) = K(0) * (1 / sqrt(1 + (2^(-(2*1)))))
// K(2) = K(1) * (1 / sqrt(1 + (2^(-(2*2)))))
// etc.
BigDecimal prev = BigDecimal.ONE;
for (int i = 0; i < MAX_ATAN_ITERS; i++) {
int power = -2 * i;
BigDecimal factor = TWO.pow(power);
BigDecimal sum = BigDecimal.ONE.add(factor);
BigDecimal root =
sqrtNewtonRaphson(sum, BigDecimal.ONE, BigDecimal.ONE.divide(SQRT_PRE));
BigDecimal term = BigDecimal.ONE.divide(root);
K_VALUES[i] = term.multiply(prev);
prev = K_VALUES[i];
}
}
*/
}
|
package com.squareup.spoon;
import java.io.File;
import java.util.Iterator;
import java.util.Set;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.ArtifactResolutionRequest;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectHelper;
import org.apache.maven.repository.RepositorySystem;
import static com.squareup.spoon.Main.DEFAULT_TITLE;
import static com.squareup.spoon.Main.OUTPUT_DIRECTORY_NAME;
import static org.apache.maven.plugins.annotations.LifecyclePhase.INTEGRATION_TEST;
/**
* Goal which invokes Spoon. By default the output will be placed in a {@code spoon-output/} folder
* in your project's build directory.
*/
@SuppressWarnings("UnusedDeclaration") // Used reflectively by Maven.
@Mojo(name = "run", defaultPhase = INTEGRATION_TEST, threadSafe = false)
public class SpoonMojo extends AbstractMojo {
private static final String SPOON_GROUP_ID = "com.squareup.spoon";
private static final String SPOON_PLUGIN_ARTIFACT_ID = "spoon-maven-plugin";
private static final String SPOON_ARTIFACT_ID = "spoon";
private static final String ARTIFACT_TYPE = "zip";
private static final String ARTIFACT_CLASSIFIER = "spoon-output";
/** {@code -Dmaven.test.skip} is commonly used with Maven to skip tests. We honor it too. */
@Parameter(property = "maven.test.skip", defaultValue = "false", readonly = true)
private boolean mavenTestSkip;
/** {@code -DskipTests} is commonly used with Maven to skip tests. We honor it too. */
@Parameter(property = "skipTests", defaultValue = "false", readonly = true)
private boolean mavenSkipTests;
/** Configuration option to skip execution. */
@Parameter
private boolean skip;
/** Location of the output directory. */
@Parameter(defaultValue = "${project.build.directory}", required = true)
private File outputDirectory;
/** A title for the output website. */
@Parameter(defaultValue = DEFAULT_TITLE)
private String title;
/** The location of the Android SDK. */
@Parameter(defaultValue = "${env.ANDROID_HOME}", required = true)
private String androidSdk;
/** Attaches output artifact as zip when {@code true}. */
@Parameter
private boolean attachArtifact;
/** Whether debug execution debug logging is enabled. */
@Parameter
private boolean debug;
@Parameter(property = "project.build.directory", required = true, readonly = true)
private File buildDirectory;
@Parameter(property = "project", required = true, readonly = true)
private MavenProject project;
@Parameter(property = "localRepository", readonly = true, required = true)
private ArtifactRepository local;
@Component
private MavenProjectHelper projectHelper;
@Component
private RepositorySystem repositorySystem;
public void execute() throws MojoExecutionException {
Log log = getLog();
if (mavenTestSkip || mavenSkipTests || skip) {
log.debug("maven.test.skip = " + mavenTestSkip);
log.debug("skipTests = " + mavenSkipTests);
log.debug("skip = " + skip);
log.info("Skipping Spoon execution.");
return;
}
File sdkFile = new File(androidSdk);
if (!sdkFile.exists()) {
throw new MojoExecutionException(
"Could not find Android SDK. Ensure ANDROID_HOME environment variable is set.");
}
log.debug("Android SDK: " + sdkFile.getAbsolutePath());
File instrumentation = getInstrumentationApk();
log.debug("Instrumentation APK: " + instrumentation);
File app = getApplicationApk();
log.debug("Application APK: " + app.getAbsolutePath());
String classpath = getSpoonClasspath();
log.debug("Classpath: " + classpath);
File output = new File(outputDirectory, OUTPUT_DIRECTORY_NAME);
log.debug("Output directory: " + output.getAbsolutePath());
log.debug("Spoon title: " + title);
log.debug("Debug: " + Boolean.toString(debug));
new ExecutionSuite(title, androidSdk, app, instrumentation, output, debug, classpath).run();
if (attachArtifact) {
File outputZip = new File(buildDirectory, OUTPUT_DIRECTORY_NAME + ".zip");
ZipUtil.zip(outputZip, output);
projectHelper.attachArtifact(project, ARTIFACT_TYPE, ARTIFACT_CLASSIFIER, outputZip);
}
}
private File getInstrumentationApk() throws MojoExecutionException {
Artifact instrumentationArtifact = project.getArtifact();
if (!"apk".equals(instrumentationArtifact.getType())) {
throw new MojoExecutionException("Spoon can only be invoked on a module with type 'apk'.");
}
return instrumentationArtifact.getFile();
}
private File getApplicationApk() throws MojoExecutionException {
for (Artifact dependency : project.getDependencyArtifacts()) {
if ("apk".equals(dependency.getType())) {
return dependency.getFile();
}
}
throw new MojoExecutionException(
"Could not find application. Ensure 'apk' dependency on it exists.");
}
private String getSpoonClasspath() throws MojoExecutionException {
Artifact spoonPlugin = findArtifact(SPOON_GROUP_ID, SPOON_PLUGIN_ARTIFACT_ID,
project.getPluginArtifacts());
Set<Artifact> spoonPluginDeps = getDependenciesForArtifact(spoonPlugin);
Artifact spoon = findArtifact(SPOON_GROUP_ID, SPOON_ARTIFACT_ID, spoonPluginDeps);
Set<Artifact> spoonDeps = getDependenciesForArtifact(spoon);
return createClasspath(spoonDeps);
}
private static Artifact findArtifact(String groupId, String artifactId, Set<Artifact> artifacts)
throws MojoExecutionException {
for (Artifact artifact : artifacts) {
if (groupId.equals(artifact.getGroupId()) && artifactId.equals(artifact.getArtifactId())) {
return artifact;
}
}
throw new MojoExecutionException("Could not find " + groupId + ":" + artifactId + " artifact.");
}
private Set<Artifact> getDependenciesForArtifact(Artifact artifact) {
ArtifactResolutionRequest arr = new ArtifactResolutionRequest()
.setArtifact(artifact)
.setResolveTransitively(true)
.setLocalRepository(local);
return repositorySystem.resolve(arr).getArtifacts();
}
private String createClasspath(Set<Artifact> selfWithDeps) {
StringBuilder builder = new StringBuilder();
Iterator<Artifact> i = selfWithDeps.iterator();
if (i.hasNext()) {
builder.append(getLocalPathToArtifact(i.next()));
while (i.hasNext()) {
builder.append(File.pathSeparator).append(getLocalPathToArtifact(i.next()));
}
}
return builder.toString();
}
private String getLocalPathToArtifact(Artifact artifact) {
return new File(local.getBasedir(), local.pathOf(artifact)).getAbsolutePath();
}
}
|
package org.opencms.ade.contenteditor.client;
import com.alkacon.acacia.client.EditorBase;
import com.alkacon.acacia.client.I_EntityRenderer;
import com.alkacon.acacia.client.I_InlineFormParent;
import com.alkacon.acacia.client.UndoRedoHandler;
import com.alkacon.acacia.client.UndoRedoHandler.UndoRedoState;
import com.alkacon.acacia.client.ValidationContext;
import com.alkacon.acacia.client.ValueFocusHandler;
import com.alkacon.acacia.client.css.I_LayoutBundle;
import com.alkacon.acacia.shared.ContentDefinition;
import com.alkacon.acacia.shared.TabInfo;
import com.alkacon.acacia.shared.ValidationResult;
import com.alkacon.vie.client.Entity;
import com.alkacon.vie.client.Vie;
import com.alkacon.vie.shared.I_Entity;
import org.opencms.ade.contenteditor.client.css.I_CmsLayoutBundle;
import org.opencms.ade.contenteditor.shared.CmsComplexWidgetData;
import org.opencms.ade.contenteditor.shared.CmsContentDefinition;
import org.opencms.ade.contenteditor.shared.rpc.I_CmsContentService;
import org.opencms.ade.contenteditor.shared.rpc.I_CmsContentServiceAsync;
import org.opencms.ade.contenteditor.widgetregistry.client.WidgetRegistry;
import org.opencms.ade.publish.client.CmsPublishDialog;
import org.opencms.ade.publish.shared.CmsPublishOptions;
import org.opencms.gwt.client.CmsCoreProvider;
import org.opencms.gwt.client.rpc.CmsRpcAction;
import org.opencms.gwt.client.rpc.CmsRpcPrefetcher;
import org.opencms.gwt.client.ui.CmsConfirmDialog;
import org.opencms.gwt.client.ui.CmsErrorDialog;
import org.opencms.gwt.client.ui.CmsInfoHeader;
import org.opencms.gwt.client.ui.CmsModelSelectDialog;
import org.opencms.gwt.client.ui.CmsNotification;
import org.opencms.gwt.client.ui.CmsNotification.Type;
import org.opencms.gwt.client.ui.CmsPushButton;
import org.opencms.gwt.client.ui.CmsToggleButton;
import org.opencms.gwt.client.ui.CmsToolbar;
import org.opencms.gwt.client.ui.I_CmsButton;
import org.opencms.gwt.client.ui.I_CmsButton.ButtonStyle;
import org.opencms.gwt.client.ui.I_CmsButton.Size;
import org.opencms.gwt.client.ui.I_CmsConfirmDialogHandler;
import org.opencms.gwt.client.ui.I_CmsModelSelectHandler;
import org.opencms.gwt.client.ui.css.I_CmsToolbarButtonLayoutBundle;
import org.opencms.gwt.client.ui.input.CmsLabel;
import org.opencms.gwt.client.ui.input.CmsSelectBox;
import org.opencms.gwt.client.util.CmsDebugLog;
import org.opencms.gwt.client.util.I_CmsSimpleCallback;
import org.opencms.gwt.shared.CmsIconUtil;
import org.opencms.gwt.shared.rpc.I_CmsCoreServiceAsync;
import org.opencms.util.CmsStringUtil;
import org.opencms.util.CmsUUID;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.Style.Overflow;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.dom.client.Style.VerticalAlign;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.CloseEvent;
import com.google.gwt.event.logical.shared.CloseHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.Window.ClosingEvent;
import com.google.gwt.user.client.Window.ClosingHandler;
import com.google.gwt.user.client.rpc.SerializationException;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.SimplePanel;
/**
* The content editor.<p>
*/
public final class CmsContentEditor extends EditorBase {
/** The add change listener method name. */
private static final String ADD_CHANGE_LISTENER_METHOD = "cmsAddEntityChangeListener";
/** The get current entity method name. */
private static final String GET_CURRENT_ENTITY_METHOD = "cmsGetCurrentEntity";
/** The in-line editor instance. */
private static CmsContentEditor INSTANCE;
/** The on close call back. */
protected Command m_onClose;
/** The edit tool-bar. */
protected CmsToolbar m_toolbar;
/** Value of the auto-unlock option from the configuration. */
private boolean m_autoUnlock;
/** The available locales. */
private Map<String, String> m_availableLocales;
/** The form editing base panel. */
private FlowPanel m_basePanel;
/** The cancel button. */
private CmsPushButton m_cancelButton;
/** The id's of the changed entities. */
private Set<String> m_changedEntityIds;
/** The window closing handler registration. */
private HandlerRegistration m_closingHandlerRegistration;
/** The locales present within the edited content. */
private Set<String> m_contentLocales;
/** The editor context. */
private CmsEditorContext m_context;
/** The copy locale button. */
private CmsPushButton m_copyLocaleButton;
/** The core RPC service instance. */
private I_CmsCoreServiceAsync m_coreSvc;
/** The loaded content definitions by locale. */
private Map<String, CmsContentDefinition> m_definitions;
/** The entities to delete. */
private Set<String> m_deletedEntities;
/** The delete locale button. */
private CmsPushButton m_deleteLocaleButton;
/** Flag indicating the resource needs to removed on cancel. */
private boolean m_deleteOnCancel;
/** The entity observer instance. */
private CmsEntityObserver m_entityObserver;
/** The hide help bubbles button. */
private CmsToggleButton m_hideHelpBubblesButton;
/** Flag which indicate whether the directedit parameter was set to true when loading the editor. */
private boolean m_isDirectEdit;
/** Flag indicating the editor was opened as the stand alone version, not from within any other module. */
private boolean m_isStandAlone;
/** The current content locale. */
private String m_locale;
/** The locale select label. */
private CmsLabel m_localeLabel;
/** The locale select box. */
private CmsSelectBox m_localeSelect;
/** The open form button. */
private CmsPushButton m_openFormButton;
/** The publish button. */
private CmsPushButton m_publishButton;
/** The redo button. */
private CmsPushButton m_redoButton;
/** The registered entity id's. */
private Set<String> m_registeredEntities;
/** The resource type name. */
private String m_resourceTypeName;
/** The save button. */
private CmsPushButton m_saveButton;
/** The save and exit button. */
private CmsPushButton m_saveExitButton;
/** The content service. */
private I_CmsContentServiceAsync m_service;
/** The resource site path. */
private String m_sitePath;
/** The tab informations for this form. */
private List<TabInfo> m_tabInfos;
/** The resource title. */
private String m_title;
/** The undo button. */
private CmsPushButton m_undoButton;
/**
* Constructor.<p>
*/
private CmsContentEditor() {
super((I_CmsContentServiceAsync)GWT.create(I_CmsContentService.class), new CmsDefaultWidgetService());
m_service = (I_CmsContentServiceAsync)super.getService();
String serviceUrl = CmsCoreProvider.get().link("org.opencms.ade.contenteditor.CmsContentService.gwt");
((ServiceDefTarget)m_service).setServiceEntryPoint(serviceUrl);
getWidgetService().setWidgetFactories(WidgetRegistry.getInstance().getWidgetFactories());
for (I_EntityRenderer renderer : WidgetRegistry.getInstance().getRenderers()) {
getWidgetService().addRenderer(renderer);
}
// set the acacia editor message bundle
setDictionary(Messages.get().getDictionary());
I_CmsLayoutBundle.INSTANCE.editorCss().ensureInjected();
I_CmsLayoutBundle.INSTANCE.widgetCss().ensureInjected();
I_CmsLayoutBundle.INSTANCE.galleryWidgetsCss().ensureInjected();
m_changedEntityIds = new HashSet<String>();
m_registeredEntities = new HashSet<String>();
m_availableLocales = new HashMap<String, String>();
m_contentLocales = new HashSet<String>();
m_deletedEntities = new HashSet<String>();
m_definitions = new HashMap<String, CmsContentDefinition>();
addValidationChangeHandler(new ValueChangeHandler<ValidationContext>() {
public void onValueChange(ValueChangeEvent<ValidationContext> event) {
handleValidationChange(event.getValue());
}
});
}
/**
* Adds an entity change listener.<p>
*
* @param changeListener the change listener
* @param changeScope the change scope
*/
public static void addEntityChangeListener(I_CmsEntityChangeListener changeListener, String changeScope) {
CmsDebugLog.getInstance().printLine("trying to ad change listener for scope: " + changeScope);
if ((INSTANCE == null) || (INSTANCE.m_entityObserver == null)) {
CmsDebugLog.getInstance().printLine("handling external registration");
if (isObserverExported()) {
CmsDebugLog.getInstance().printLine("registration is available");
try {
addNativeListsner(changeListener, changeScope);
} catch (Exception e) {
CmsDebugLog.getInstance().printLine(
"Exception occured during listener registration" + e.getMessage());
}
} else {
throw new RuntimeException("Editor is not initialized yet.");
}
} else {
INSTANCE.m_entityObserver.addEntityChangeListener(changeListener, changeScope);
}
}
/**
* Returns the currently edited entity.<p>
*
* @return the currently edited entity
*/
public static Entity getEntity() {
if ((INSTANCE == null) || (INSTANCE.m_entityObserver == null)) {
CmsDebugLog.getInstance().printLine("handling external registration");
if (isObserverExported()) {
return nativeGetEntity();
} else {
throw new RuntimeException("Editor is not initialized yet.");
}
} else {
return INSTANCE.getCurrentEntity();
}
}
/**
* Returns the in-line editor instance.<p>
*
* @return the in-line editor instance
*/
public static CmsContentEditor getInstance() {
if (INSTANCE == null) {
INSTANCE = new CmsContentEditor();
}
return INSTANCE;
}
/**
* Returns if the given element or it's descendants are inline editable.<p>
*
* @param element the element
*
* @return <code>true</code> if the element has editable descendants
*/
public static boolean hasEditable(Element element) {
List<Element> children = Vie.getInstance().find("[property^=\"opencms://\"]", element);
return (children != null) && !children.isEmpty();
}
/**
* Replaces the id's within about attributes of the given element and all it's children.<p>
*
* @param element the element
* @param oldId the old id
* @param newId the new id
*/
public static void replaceResourceIds(Element element, String oldId, String newId) {
String about = element.getAttribute("about");
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(about)) {
about = about.replace(oldId, newId);
element.setAttribute("about", about);
}
Element child = element.getFirstChildElement();
while (child != null) {
replaceResourceIds(child, oldId, newId);
child = child.getNextSiblingElement();
}
}
/**
* Sets all annotated child elements editable.<p>
*
* @param element the element
* @param editable <code>true</code> to enable editing
*
* @return <code>true</code> if the element had editable elements
*/
public static boolean setEditable(Element element, boolean editable) {
I_CmsLayoutBundle.INSTANCE.editorCss().ensureInjected();
List<Element> children = Vie.getInstance().select("[property^=\"opencms://\"]", element);
if (children.size() > 0) {
for (Element child : children) {
if (editable) {
child.setAttribute("contentEditable", "true");
child.addClassName(I_CmsLayoutBundle.INSTANCE.editorCss().inlineEditable());
} else {
child.removeAttribute("contentEditable");
child.removeClassName(I_CmsLayoutBundle.INSTANCE.editorCss().inlineEditable());
}
}
return true;
}
return false;
}
/**
* Adds the change listener.<p>
*
* @param changeListener the change listener
* @param changeScope the change scope
*/
private static native void addNativeListsner(I_CmsEntityChangeListener changeListener, String changeScope)/*-{
var instance = changeListener;
var nat = {
onChange : function(entity) {
instance.@org.opencms.ade.contenteditor.client.I_CmsEntityChangeListener::onEntityChange(Lcom/alkacon/vie/client/Entity;)(entity);
}
}
var method = $wnd[@org.opencms.ade.contenteditor.client.CmsContentEditor::ADD_CHANGE_LISTENER_METHOD];
if (typeof method == 'function') {
method(nat, changeScope);
}
}-*/;
/**
* Checks whether the add entity change listener method has been exported.<p>
*
* @return <code>true</code> if the add entity change listener method has been exported
*/
private static native boolean isObserverExported()/*-{
var method = $wnd[@org.opencms.ade.contenteditor.client.CmsContentEditor::ADD_CHANGE_LISTENER_METHOD];
if (typeof method == 'function') {
return true;
} else {
return false;
}
}-*/;
/**
* Returns the current entity.<p>
*
* @return the current entity
*/
private static native Entity nativeGetEntity()/*-{
return $wnd[@org.opencms.ade.contenteditor.client.CmsContentEditor::GET_CURRENT_ENTITY_METHOD]
();
}-*/;
/**
* Closes the editor.<p>
* May be used from outside the editor module.<p>
*/
public void closeEditor() {
if (m_saveButton != null) {
if (m_saveButton.isEnabled()) {
CmsConfirmDialog dialog = new CmsConfirmDialog(org.opencms.gwt.client.Messages.get().key(
org.opencms.gwt.client.Messages.GUI_DIALOG_RESET_TITLE_0), Messages.get().key(
Messages.GUI_CONFIRM_LEAVING_EDITOR_0));
dialog.setHandler(new I_CmsConfirmDialogHandler() {
public void onClose() {
cancelEdit();
}
public void onOk() {
saveAndExit();
}
});
dialog.center();
} else {
cancelEdit();
}
}
}
/**
* @see com.alkacon.acacia.client.EditorBase#getService()
*/
@Override
public I_CmsContentServiceAsync getService() {
return m_service;
}
/**
* Loads the content definition for the given entity and executes the callback on success.<p>
*
* @param entityId the entity id
* @param callback the callback
*/
public void loadDefinition(final String entityId, final I_CmsSimpleCallback<CmsContentDefinition> callback) {
CmsRpcAction<CmsContentDefinition> action = new CmsRpcAction<CmsContentDefinition>() {
@Override
public void execute() {
start(0, true);
getService().loadDefinition(entityId, this);
}
@Override
protected void onResponse(final CmsContentDefinition result) {
registerContentDefinition(result);
WidgetRegistry.getInstance().registerExternalWidgets(
result.getExternalWidgetConfigurations(),
new Command() {
public void execute() {
stop(false);
callback.execute(result);
}
});
}
};
action.execute();
}
/**
* Loads the content definition for the given entity and executes the callback on success.<p>
*
* @param entityId the entity id
* @param newLink the new link
* @param modelFileId the model file id
* @param callback the callback
*/
public void loadDefinition(
final String entityId,
final String newLink,
final CmsUUID modelFileId,
final I_CmsSimpleCallback<CmsContentDefinition> callback) {
CmsRpcAction<CmsContentDefinition> action = new CmsRpcAction<CmsContentDefinition>() {
@Override
public void execute() {
start(0, true);
getService().loadDefinition(entityId, newLink, modelFileId, CmsCoreProvider.get().getUri(), this);
}
@Override
protected void onResponse(final CmsContentDefinition result) {
if (result.isModelInfo()) {
callback.execute(result);
} else {
registerContentDefinition(result);
WidgetRegistry.getInstance().registerExternalWidgets(
result.getExternalWidgetConfigurations(),
new Command() {
public void execute() {
stop(false);
callback.execute(result);
}
});
}
}
};
action.execute();
}
/**
* Loads the content definition for the given entity and executes the callback on success.<p>
*
* @param entityId the entity id
* @param callback the callback
*/
public void loadNewDefinition(final String entityId, final I_CmsSimpleCallback<CmsContentDefinition> callback) {
CmsRpcAction<CmsContentDefinition> action = new CmsRpcAction<CmsContentDefinition>() {
@Override
public void execute() {
getService().loadNewDefinition(entityId, this);
}
@Override
protected void onResponse(final CmsContentDefinition result) {
stop(false);
callback.execute(result);
}
};
action.execute();
}
/**
* Opens the content editor dialog.<p>
*
* @param context the editor context
* @param locale the content locale
* @param elementId the element id
* @param newLink the new link
* @param modelFileId the model file id
* @param onClose the command executed on dialog close
*/
public void openFormEditor(
final CmsEditorContext context,
String locale,
String elementId,
String newLink,
CmsUUID modelFileId,
Command onClose) {
m_onClose = onClose;
CmsUUID structureId = new CmsUUID(elementId);
// make sure the resource is locked, if we are not creating a new one
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(newLink) || CmsCoreProvider.get().lock(structureId)) {
loadDefinition(
CmsContentDefinition.uuidToEntityId(structureId, locale),
newLink,
modelFileId,
new I_CmsSimpleCallback<CmsContentDefinition>() {
public void execute(CmsContentDefinition contentDefinition) {
if (contentDefinition.isModelInfo()) {
openModelSelectDialog(context, contentDefinition);
} else {
initEditor(context, contentDefinition, null, false);
}
}
});
} else {
showLockedResourceMessage();
}
}
/**
* Renders the in-line editor for the given element.<p>
*
* @param context the editor context
* @param elementId the element id
* @param locale the content locale
* @param panel the element panel
* @param onClose the command to execute on close
*/
public void openInlineEditor(
final CmsEditorContext context, CmsUUID elementId, String locale, final I_InlineFormParent panel, Command onClose) {
String entityId = CmsContentDefinition.uuidToEntityId(elementId, locale);
m_locale = locale;
m_onClose = onClose;
if (CmsCoreProvider.get().lock(elementId)) {
loadDefinition(entityId, new I_CmsSimpleCallback<CmsContentDefinition>() {
public void execute(CmsContentDefinition contentDefinition) {
initEditor(context, contentDefinition, panel, true);
}
});
} else {
showLockedResourceMessage();
}
}
/**
* Opens the form based editor. Used within the stand alone contenteditor.jsp.<p>
*
* @param context the editor context
*/
public void openStandAloneFormEditor(final CmsEditorContext context) {
final CmsContentDefinition definition;
try {
definition = (CmsContentDefinition)CmsRpcPrefetcher.getSerializedObjectFromDictionary(
getService(),
I_CmsContentService.DICT_CONTENT_DEFINITION);
} catch (SerializationException e) {
RootPanel.get().add(new Label(e.getMessage()));
return;
}
m_isStandAlone = true;
if (definition.isModelInfo()) {
openModelSelectDialog(context, definition);
} else {
if (CmsCoreProvider.get().lock(CmsContentDefinition.entityIdToUuid(definition.getEntityId()))) {
registerContentDefinition(definition);
// register all external widgets
WidgetRegistry.getInstance().registerExternalWidgets(
definition.getExternalWidgetConfigurations(),
new Command() {
public void execute() {
initEditor(context, definition, null, false);
}
});
} else {
showLockedResourceMessage();
}
}
}
/**
* Registers a deep copy of the source entity with the given target entity id.<p>
*
* @param sourceEntityId the source entity id
* @param targetEntityId the target entity id
*/
public void registerClonedEntity(String sourceEntityId, String targetEntityId) {
Vie.getInstance().getEntity(sourceEntityId).createDeepCopy(targetEntityId);
}
/**
* @see com.alkacon.acacia.client.EditorBase#registerContentDefinition(com.alkacon.acacia.shared.ContentDefinition)
*/
@Override
public void registerContentDefinition(ContentDefinition definition) {
super.registerContentDefinition(definition);
CmsContentDefinition cmsDefinition = (CmsContentDefinition)definition;
for (Map.Entry<String, CmsComplexWidgetData> entry : cmsDefinition.getComplexWidgetData().entrySet()) {
String attrName = entry.getKey();
CmsComplexWidgetData widgetData = entry.getValue();
getWidgetService().registerComplexWidgetAttribute(
attrName,
widgetData.getRendererName(),
widgetData.getConfiguration());
}
}
/**
* Saves the given entities.<p>
*
* @param entities the entities to save
* @param deletedEntites the deleted entity id's
* @param clearOnSuccess <code>true</code> to clear the VIE instance on success
* @param callback the call back command
*/
public void saveAndDeleteEntities(
final List<com.alkacon.acacia.shared.Entity> entities,
final List<String> deletedEntites,
final boolean clearOnSuccess,
final Command callback) {
CmsRpcAction<ValidationResult> asyncCallback = new CmsRpcAction<ValidationResult>() {
@Override
public void execute() {
start(200, true);
getService().saveAndDeleteEntities(entities, deletedEntites, clearOnSuccess, this);
}
@Override
protected void onResponse(ValidationResult result) {
stop(false);
if ((result != null) && result.hasErrors()) {
showValidationErrorDialog(result);
} else {
callback.execute();
if (clearOnSuccess) {
destroyForm(true);
}
}
}
};
asyncCallback.execute();
}
/**
* Saves the given entities.<p>
*
* @param entities the entities to save
* @param deletedEntites the deleted entity id's
* @param clearOnSuccess <code>true</code> to clear the VIE instance on success
* @param callback the call back command
*/
public void saveAndDeleteEntities(
final Set<String> entities,
final Set<String> deletedEntites,
final boolean clearOnSuccess,
final Command callback) {
List<com.alkacon.acacia.shared.Entity> changedEntites = new ArrayList<com.alkacon.acacia.shared.Entity>();
for (String entityId : entities) {
I_Entity entity = m_vie.getEntity(entityId);
if (entity != null) {
changedEntites.add(com.alkacon.acacia.shared.Entity.serializeEntity(entity));
}
}
saveAndDeleteEntities(changedEntites, new ArrayList<String>(deletedEntites), clearOnSuccess, callback);
}
/**
* Sets the show editor help flag to the user session.<p>
*
* @param show the show editor help flag
*/
public void setShowEditorHelp(final boolean show) {
CmsRpcAction<Void> action = new CmsRpcAction<Void>() {
/**
* @see org.opencms.gwt.client.rpc.CmsRpcAction#execute()
*/
@Override
public void execute() {
getCoreService().setShowEditorHelp(show, this);
}
/**
* @see org.opencms.gwt.client.rpc.CmsRpcAction#onResponse(java.lang.Object)
*/
@Override
protected void onResponse(Void result) {
//nothing to do
}
};
action.execute();
}
/**
* Removes the given entity from the entity VIE store.<p>
*
* @param entityId the entity id
*/
public void unregistereEntity(String entityId) {
Vie.getInstance().removeEntity(entityId);
}
/**
* Closes the editor.<p>
*/
protected void clearEditor() {
m_context = null;
removeEditOverlays();
if (m_toolbar != null) {
m_toolbar.removeFromParent();
m_toolbar = null;
}
m_cancelButton = null;
m_localeSelect = null;
m_localeLabel = null;
m_deleteLocaleButton = null;
m_copyLocaleButton = null;
m_openFormButton = null;
m_saveButton = null;
m_entityId = null;
m_onClose = null;
m_locale = null;
if (m_basePanel != null) {
m_basePanel.removeFromParent();
m_basePanel = null;
}
if (m_entityObserver != null) {
m_entityObserver.clear();
m_entityObserver = null;
}
m_changedEntityIds.clear();
m_registeredEntities.clear();
m_availableLocales.clear();
m_contentLocales.clear();
m_deletedEntities.clear();
m_definitions.clear();
m_title = null;
m_sitePath = null;
m_resourceTypeName = null;
if (m_closingHandlerRegistration != null) {
m_closingHandlerRegistration.removeHandler();
m_closingHandlerRegistration = null;
}
if (m_isStandAlone) {
closeEditorWidow();
} else {
RootPanel.getBodyElement().getParentElement().getStyle().clearOverflow();
}
}
/**
* Gets the editor context.<p>
*
* @return the editor context
*/
protected CmsEditorContext getContext() {
return m_context;
}
/**
* @see com.alkacon.acacia.client.EditorBase#getContextUri()
*/
@Override
protected String getContextUri() {
return CmsCoreProvider.get().getUri();
}
/**
* Returns the core RPC service.<p>
*
* @return the core service
*/
protected I_CmsCoreServiceAsync getCoreService() {
if (m_coreSvc == null) {
m_coreSvc = CmsCoreProvider.getService();
}
return m_coreSvc;
}
/**
* Gets the entity id.<p>
*
* @return the entity id
*/
protected String getEntityId() {
return m_entityId;
}
/**
* @see com.alkacon.acacia.client.EditorBase#getHtmlContextInfo()
*/
@Override
protected String getHtmlContextInfo() {
return m_context.getHtmlContextInfo();
}
/**
* Adds a content definition to the internal store.<p>
*
* @param definition the definition to add
*/
void addContentDefinition(CmsContentDefinition definition) {
m_definitions.put(definition.getLocale(), definition);
m_contentLocales.add(definition.getLocale());
}
/**
* Cancels the editing process.<p>
*/
void cancelEdit() {
unlockResource();
if (m_onClose != null) {
m_onClose.execute();
}
destroyForm(true);
clearEditor();
}
/**
* Asks the user to confirm resetting all changes.<p>
*/
void confirmCancel() {
if (m_saveButton.isEnabled()) {
CmsConfirmDialog dialog = new CmsConfirmDialog(org.opencms.gwt.client.Messages.get().key(
org.opencms.gwt.client.Messages.GUI_DIALOG_RESET_TITLE_0), org.opencms.gwt.client.Messages.get().key(
org.opencms.gwt.client.Messages.GUI_DIALOG_RESET_TEXT_0));
dialog.setHandler(new I_CmsConfirmDialogHandler() {
public void onClose() {
// nothing to do
}
public void onOk() {
cancelEdit();
}
});
dialog.center();
} else {
cancelEdit();
}
}
/**
* Opens the confirm delete locale dialog.<p>
*/
void confirmDeleteLocale() {
CmsConfirmDialog dialog = new CmsConfirmDialog(
Messages.get().key(Messages.GUI_CONFIRM_DELETE_LOCALE_TITLE_0),
Messages.get().key(Messages.GUI_CONFIRM_DELETE_LOCALE_TEXT_0));
dialog.setHandler(new I_CmsConfirmDialogHandler() {
public void onClose() {
// nothing to do
}
public void onOk() {
deleteCurrentLocale();
}
});
dialog.center();
}
/**
* Copies the current entity values to the given locales.<p>
*
* @param targetLocales the target locales
*/
void copyLocales(Set<String> targetLocales) {
for (String targetLocale : targetLocales) {
String targetId = getIdForLocale(targetLocale);
if (!m_entityId.equals(targetId)) {
if (m_registeredEntities.contains(targetId)) {
unregistereEntity(targetId);
} else {
loadNewDefinition(targetId, new I_CmsSimpleCallback<CmsContentDefinition>() {
public void execute(CmsContentDefinition definition) {
addContentDefinition(definition);
}
});
}
registerClonedEntity(m_entityId, targetId);
m_registeredEntities.add(targetId);
m_changedEntityIds.add(targetId);
m_contentLocales.add(targetLocale);
m_deletedEntities.remove(targetId);
enableSave();
}
}
initLocaleSelect();
}
/**
* Deferrers the save action to the end of the browser event queue.<p>
*/
void deferSave() {
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
public void execute() {
save();
}
});
}
/**
* Deferrers the save and exit action to the end of the browser event queue.<p>
*/
void deferSaveAndExit() {
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
public void execute() {
saveAndExit();
}
});
}
/**
* Deletes the current locale.<p>
*/
void deleteCurrentLocale() {
// there has to remain at least one content locale
if (m_contentLocales.size() > 1) {
String deletedLocale = m_locale;
m_contentLocales.remove(deletedLocale);
m_registeredEntities.remove(m_entityId);
m_changedEntityIds.remove(m_entityId);
m_deletedEntities.add(m_entityId);
unregistereEntity(m_entityId);
enableSave();
String nextLocale = null;
if (m_registeredEntities.isEmpty()) {
nextLocale = m_contentLocales.iterator().next();
} else {
nextLocale = CmsContentDefinition.getLocaleFromId(m_registeredEntities.iterator().next());
}
switchLocale(nextLocale);
}
}
/**
* Disables the save buttons with the given message.<p>
*
* @param message the disabled message
*/
void disableSave(String message) {
m_saveButton.disable(message);
m_saveExitButton.disable(message);
}
/**
* Leaves the editor saving the content if necessary.<p>
*/
void exitWithSaving() {
if (m_saveExitButton.isEnabled()) {
saveAndExit();
} else {
cancelEdit();
}
}
/**
* Handles validation changes.<p>
*
* @param validationContext the changed validation context
*/
void handleValidationChange(ValidationContext validationContext) {
if (validationContext.hasValidationErrors()) {
String locales = "";
for (String id : validationContext.getInvalidEntityIds()) {
if (locales.length() > 0) {
locales += ", ";
}
String locale = CmsContentDefinition.getLocaleFromId(id);
if (m_availableLocales.containsKey(locale)) {
locales += m_availableLocales.get(locale);
}
}
disableSave(Messages.get().key(Messages.GUI_TOOLBAR_VALIDATION_ERRORS_1, locales));
} else if (!m_changedEntityIds.isEmpty()) {
enableSave();
}
}
/**
* Hides the editor help bubbles.<p>
*
* @param hide <code>true</code> to hide the help bubbles
*/
void hideHelpBubbles(boolean hide) {
setShowEditorHelp(!hide);
ValueFocusHandler.getInstance().hideHelpBubbles(RootPanel.get(), hide);
if (!hide) {
m_hideHelpBubblesButton.setTitle(Messages.get().key(Messages.GUI_TOOLBAR_HELP_BUBBLES_SHOWN_0));
} else {
m_hideHelpBubblesButton.setTitle(Messages.get().key(Messages.GUI_TOOLBAR_HELP_BUBBLES_HIDDEN_0));
}
}
/**
* Initializes the editor.<p>
*
* @param context the editor context
* @param contentDefinition the content definition
* @param formParent the inline form parent panel, used for inline editing only
* @param inline <code>true</code> to render the editor for inline editing
*/
void initEditor(
CmsEditorContext context,
CmsContentDefinition contentDefinition,
I_InlineFormParent formParent,
boolean inline) {
m_context = context;
m_locale = contentDefinition.getLocale();
m_entityId = contentDefinition.getEntityId();
m_deleteOnCancel = contentDefinition.isDeleteOnCancel();
m_autoUnlock = contentDefinition.isAutoUnlock();
m_isDirectEdit = contentDefinition.isDirectEdit();
initClosingHandler();
setContentDefinition(contentDefinition);
initToolbar();
if (inline && (formParent != null)) {
initEditOverlay(formParent.getElement());
addOverlayClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
exitWithSaving();
}
});
m_hideHelpBubblesButton.setVisible(false);
setNativeResourceInfo(m_sitePath, m_locale);
renderInlineEntity(m_entityId, formParent);
} else {
initFormPanel();
renderFormContent();
}
if (contentDefinition.isPerformedAutocorrection()) {
CmsNotification.get().send(Type.NORMAL, Messages.get().key(Messages.GUI_WARN_INVALID_XML_STRUCTURE_0));
setChanged();
}
}
/**
* Opens the form based editor.<p>
*/
void initFormPanel() {
removeEditOverlays();
m_openFormButton.setVisible(false);
m_saveButton.setVisible(true);
m_hideHelpBubblesButton.setVisible(true);
m_undoButton.setVisible(true);
m_redoButton.setVisible(true);
m_basePanel = new FlowPanel();
m_basePanel.addStyleName(I_CmsLayoutBundle.INSTANCE.editorCss().basePanel());
// insert base panel before the tool bar to keep the tool bar visible
RootPanel.get().add(m_basePanel);
if (m_isStandAlone) {
RootPanel.getBodyElement().addClassName(I_CmsLayoutBundle.INSTANCE.editorCss().standAloneEditor());
} else {
RootPanel.getBodyElement().getParentElement().getStyle().setOverflow(Overflow.HIDDEN);
}
}
/**
* Opens the copy locale dialog.<p>
*/
void openCopyLocaleDialog() {
CmsCopyLocaleDialog dialog = new CmsCopyLocaleDialog(m_availableLocales, m_contentLocales, m_locale, this);
dialog.center();
}
/**
* Opens the model file select dialog.<p>
*
* @param context the editor context
* @param definition the content definition
*/
void openModelSelectDialog(final CmsEditorContext context, final CmsContentDefinition definition) {
I_CmsModelSelectHandler handler = new I_CmsModelSelectHandler() {
public void onModelSelect(CmsUUID modelStructureId) {
if (modelStructureId == null) {
modelStructureId = CmsUUID.getNullUUID();
}
openFormEditor(
context,
definition.getLocale(),
definition.getReferenceResourceId().toString(),
definition.getNewLink(),
modelStructureId,
m_onClose);
}
};
String title = org.opencms.gwt.client.Messages.get().key(
org.opencms.gwt.client.Messages.GUI_MODEL_SELECT_TITLE_0);
String message = org.opencms.gwt.client.Messages.get().key(
org.opencms.gwt.client.Messages.GUI_MODEL_SELECT_MESSAGE_0);
CmsModelSelectDialog dialog = new CmsModelSelectDialog(handler, definition.getModelInfos(), title, message);
dialog.center();
}
/**
* Renders the form content.<p>
*/
void renderFormContent() {
initLocaleSelect();
setNativeResourceInfo(m_sitePath, m_locale);
CmsInfoHeader header = new CmsInfoHeader(
m_title,
null,
m_sitePath,
m_locale,
CmsIconUtil.getResourceIconClasses(m_resourceTypeName, m_sitePath, false));
m_basePanel.add(header);
SimplePanel content = new SimplePanel();
content.setStyleName(I_LayoutBundle.INSTANCE.form().formParent());
m_basePanel.add(content);
if (m_entityObserver != null) {
m_entityObserver.clear();
}
m_entityObserver = new CmsEntityObserver(getCurrentEntity());
exportObserver();
renderEntityForm(m_entityId, m_tabInfos, content, m_basePanel.getElement());
}
/**
* Saves the content and closes the editor.<p>
*/
void save() {
saveAndDeleteEntities(m_changedEntityIds, m_deletedEntities, false, new Command() {
public void execute() {
setSaved();
setUnchanged();
}
});
}
/**
* Saves the changed/deleted entities.<p>
* @param clearOnSuccess <code>true</code> to clear the VIE instance on success
* @param callback the call back command
*/
void saveAndDeleteEntities(boolean clearOnSuccess, Command callback) {
saveAndDeleteEntities(m_changedEntityIds, m_deletedEntities, clearOnSuccess, callback);
}
/**
* Saves the content and closes the editor.<p>
*/
void saveAndExit() {
boolean unlock = shouldUnlockAutomatically();
saveAndDeleteEntities(m_changedEntityIds, m_deletedEntities, unlock, new Command() {
public void execute() {
setSaved();
if (m_onClose != null) {
m_onClose.execute();
}
clearEditor();
}
});
}
/**
* Sets the has changed flag and enables the save button.<p>
*/
void setChanged() {
enableSave();
m_changedEntityIds.add(m_entityId);
m_deletedEntities.remove(m_entityId);
updateOverlayPosition();
}
/**
* Sets the content definition.<p>
*
* @param definition the content definition
*/
void setContentDefinition(CmsContentDefinition definition) {
if (m_availableLocales.isEmpty()) {
// only set the locales when initially setting the content definition
m_availableLocales.putAll(definition.getAvailableLocales());
m_contentLocales.addAll(definition.getContentLocales());
} else {
m_contentLocales.add(definition.getLocale());
}
m_title = definition.getTitle();
m_sitePath = definition.getSitePath();
m_resourceTypeName = definition.getResourceType();
m_registeredEntities.add(definition.getEntityId());
m_tabInfos = definition.getTabInfos();
addContentDefinition(definition);
getWidgetService().addConfigurations(definition.getConfigurations());
addEntityChangeHandler(definition.getEntityId(), new ValueChangeHandler<Entity>() {
public void onValueChange(ValueChangeEvent<Entity> event) {
setChanged();
}
});
}
/**
* Removes the delete on cancel flag for new resources.<p>
*/
void setSaved() {
m_deleteOnCancel = false;
}
/**
* Call after save.<p>
*/
void setUnchanged() {
m_changedEntityIds.clear();
m_deletedEntities.clear();
disableSave(Messages.get().key(Messages.GUI_TOOLBAR_NOTHING_CHANGED_0));
}
/**
* Enables and disabler the undo redo buttons according to the state.<p>
*
* @param state the undo redo state
*/
void setUndoRedoState(UndoRedoState state) {
if (state.hasUndo()) {
m_undoButton.enable();
} else {
m_undoButton.disable(Messages.get().key(Messages.GUI_TOOLBAR_UNDO_DISABLED_0));
}
if (state.hasRedo()) {
m_redoButton.enable();
} else {
m_redoButton.disable(Messages.get().key(Messages.GUI_TOOLBAR_REDO_DISABLED_0));
}
}
/**
* Returns true if the edited resource should be unlocked automatically after pressing Save/Exit.<p>
*
* @return true if the edited resource should be unlocked automatically
*/
boolean shouldUnlockAutomatically() {
if (m_isStandAlone) {
if (m_isDirectEdit) {
// Classic direct edit case - always unlock
return true;
} else {
// Workplace case - determined by configuration
return m_autoUnlock;
}
}
// Container page case - always unlock
return true;
}
/**
* Shows the validation error dialog.<p>
*
* @param validationResult the validation result
*/
void showValidationErrorDialog(ValidationResult validationResult) {
if (validationResult.getErrors().keySet().contains(m_entityId)) {
getValidationHandler().displayValidation(m_entityId, validationResult);
}
String errorLocales = "";
for (String entityId : validationResult.getErrors().keySet()) {
String locale = CmsContentDefinition.getLocaleFromId(entityId);
errorLocales += m_availableLocales.get(locale) + ", ";
}
// remove trailing ','
errorLocales = errorLocales.substring(0, errorLocales.length() - 2);
CmsErrorDialog dialog = new CmsErrorDialog(
Messages.get().key(Messages.GUI_VALIDATION_ERROR_1, errorLocales),
null);
dialog.center();
}
/**
* Switches to the selected locale. Will save changes first.<p>
*
* @param locale the locale to switch to
*/
void switchLocale(final String locale) {
if (locale.equals(m_locale)) {
return;
}
m_locale = locale;
m_basePanel.clear();
destroyForm(false);
m_entityId = getIdForLocale(locale);
// if the content does not contain the requested locale yet, a new node will be created
final boolean addedNewLocale = !m_contentLocales.contains(locale);
if (!m_registeredEntities.contains(m_entityId)) {
if (addedNewLocale) {
loadNewDefinition(m_entityId, new I_CmsSimpleCallback<CmsContentDefinition>() {
public void execute(final CmsContentDefinition contentDefinition) {
registerContentDefinition(contentDefinition);
CmsNotification.get().sendBlocking(
CmsNotification.Type.NORMAL,
org.opencms.gwt.client.Messages.get().key(org.opencms.gwt.client.Messages.GUI_LOADING_0));
WidgetRegistry.getInstance().registerExternalWidgets(
contentDefinition.getExternalWidgetConfigurations(),
new Command() {
public void execute() {
setContentDefinition(contentDefinition);
renderFormContent();
if (addedNewLocale) {
setChanged();
}
CmsNotification.get().hide();
}
});
}
});
} else {
loadDefinition(m_entityId, new I_CmsSimpleCallback<CmsContentDefinition>() {
public void execute(CmsContentDefinition contentDefinition) {
setContentDefinition(contentDefinition);
renderFormContent();
if (addedNewLocale) {
setChanged();
}
}
});
}
} else {
getWidgetService().addConfigurations(m_definitions.get(locale).getConfigurations());
renderFormContent();
}
}
/**
* Unlocks the edited resource.<p>
*/
void unlockResource() {
if (!shouldUnlockAutomatically()) {
return;
}
if (m_entityId != null) {
final CmsUUID structureId = CmsContentDefinition.entityIdToUuid(m_entityId);
if (m_deleteOnCancel) {
CmsRpcAction<Void> action = new CmsRpcAction<Void>() {
@Override
public void execute() {
CmsCoreProvider.getVfsService().syncDeleteResource(structureId, this);
}
@Override
protected void onResponse(Void result) {
// nothing to do
}
};
action.executeSync();
} else {
CmsCoreProvider.get().unlock(structureId);
}
}
}
/**
* Adds the change listener to the observer.<p>
*
* @param changeListener the change listener
* @param changeScope the change scope
*/
private void addChangeListener(JavaScriptObject changeListener, String changeScope) {
try {
m_entityObserver.addEntityChangeListener(new CmsEntityChangeListenerWrapper(changeListener), changeScope);
} catch (Exception e) {
CmsDebugLog.getInstance().printLine("Exception occured during listener registration" + e.getMessage());
}
}
/**
* Closes the editor.<p>
*/
private native void closeEditorWidow() /*-{
if ($wnd.top.cms_ade_closeEditorDialog) {
$wnd.top.cms_ade_closeEditorDialog();
} else {
var backlink = $wnd[@org.opencms.ade.contenteditor.shared.rpc.I_CmsContentService::PARAM_BACKLINK];
if (backlink) {
$wnd.top.location.href = backlink;
}
}
}-*/;
/**
* Creates a push button for the edit tool-bar.<p>
*
* @param title the button title
* @param imageClass the image class
*
* @return the button
*/
private CmsPushButton createButton(String title, String imageClass) {
CmsPushButton result = new CmsPushButton();
result.setTitle(title);
result.setImageClass(imageClass);
result.setButtonStyle(ButtonStyle.IMAGE, null);
result.setSize(Size.big);
return result;
}
/**
* Enables the save buttons.<p>
*/
private void enableSave() {
m_saveButton.enable();
m_saveExitButton.enable();
}
/**
* Exports the add entity change listener method.<p>
*/
private native void exportObserver()/*-{
var self = this;
$wnd[@org.opencms.ade.contenteditor.client.CmsContentEditor::ADD_CHANGE_LISTENER_METHOD] = function(
listener, scope) {
var wrapper = {
onChange : listener.onChange
}
self.@org.opencms.ade.contenteditor.client.CmsContentEditor::addChangeListener(Lcom/google/gwt/core/client/JavaScriptObject;Ljava/lang/String;)(wrapper, scope);
}
$wnd[@org.opencms.ade.contenteditor.client.CmsContentEditor::GET_CURRENT_ENTITY_METHOD] = function() {
return self.@org.opencms.ade.contenteditor.client.CmsContentEditor::getCurrentEntity()();
}
}-*/;
/**
* Returns the entity id for the given locale.<p>
*
* @param locale the locale
*
* @return the entity id
*/
private String getIdForLocale(String locale) {
return CmsContentDefinition.uuidToEntityId(CmsContentDefinition.entityIdToUuid(m_entityId), locale);
}
/**
* Initializes the window closing handler to ensure the resource will be unlocked when leaving the editor.<p>
*/
private void initClosingHandler() {
m_closingHandlerRegistration = Window.addWindowClosingHandler(new ClosingHandler() {
/**
* @see com.google.gwt.user.client.Window.ClosingHandler#onWindowClosing(com.google.gwt.user.client.Window.ClosingEvent)
*/
public void onWindowClosing(ClosingEvent event) {
unlockResource();
}
});
}
/**
* Initializes the locale selector.<p>
*/
private void initLocaleSelect() {
if (m_availableLocales.size() < 2) {
return;
}
if (m_localeLabel == null) {
m_localeLabel = new CmsLabel();
m_localeLabel.addStyleName(I_CmsLayoutBundle.INSTANCE.generalCss().inlineBlock());
m_localeLabel.addStyleName(I_CmsLayoutBundle.INSTANCE.generalCss().textBig());
m_localeLabel.setText(Messages.get().key(Messages.GUI_TOOLBAR_LANGUAGE_0));
m_toolbar.addLeft(m_localeLabel);
}
Map<String, String> selectOptions = new HashMap<String, String>();
for (Entry<String, String> localeEntry : m_availableLocales.entrySet()) {
if (m_contentLocales.contains(localeEntry.getKey())) {
selectOptions.put(localeEntry.getKey(), localeEntry.getValue());
} else {
selectOptions.put(localeEntry.getKey(), localeEntry.getValue() + " [-]");
}
}
if (m_localeSelect == null) {
m_localeSelect = new CmsSelectBox(selectOptions);
m_toolbar.addLeft(m_localeSelect);
m_localeSelect.addStyleName(I_CmsLayoutBundle.INSTANCE.generalCss().inlineBlock());
m_localeSelect.getElement().getStyle().setWidth(100, Unit.PX);
m_localeSelect.getElement().getStyle().setVerticalAlign(VerticalAlign.MIDDLE);
m_localeSelect.addValueChangeHandler(new ValueChangeHandler<String>() {
public void onValueChange(ValueChangeEvent<String> event) {
switchLocale(event.getValue());
}
});
} else {
m_localeSelect.setItems(selectOptions);
}
m_localeSelect.setFormValueAsString(m_locale);
if (m_deleteLocaleButton == null) {
m_deleteLocaleButton = createButton(
Messages.get().key(Messages.GUI_TOOLBAR_DELETE_LOCALE_0),
I_CmsToolbarButtonLayoutBundle.INSTANCE.toolbarButtonCss().toolbarDeleteLocale());
m_deleteLocaleButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
confirmDeleteLocale();
}
});
m_toolbar.addLeft(m_deleteLocaleButton);
}
if (m_contentLocales.size() > 1) {
m_deleteLocaleButton.enable();
} else {
m_deleteLocaleButton.disable(Messages.get().key(Messages.GUI_TOOLBAR_CANT_DELETE_LAST_LOCALE_0));
}
if (m_copyLocaleButton == null) {
m_copyLocaleButton = createButton(
I_CmsButton.ButtonData.COPY_LOCALE.getTitle(),
I_CmsButton.ButtonData.COPY_LOCALE.getIconClass());
m_copyLocaleButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
openCopyLocaleDialog();
}
});
m_toolbar.addLeft(m_copyLocaleButton);
}
}
/**
* Generates the button bar displayed beneath the editable fields.<p>
*/
private void initToolbar() {
m_toolbar = new CmsToolbar();
m_publishButton = createButton(
org.opencms.gwt.client.Messages.get().key(org.opencms.gwt.client.Messages.GUI_TOOLBAR_PUBLISH_0),
I_CmsToolbarButtonLayoutBundle.INSTANCE.toolbarButtonCss().toolbarPublish());
m_toolbar.addLeft(m_publishButton);
m_publishButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
boolean unlock = shouldUnlockAutomatically();
saveAndDeleteEntities(unlock, new Command() {
public void execute() {
setSaved();
HashMap<String, String> params = new HashMap<String, String>(
getContext().getPublishParameters());
CmsUUID structureId = CmsContentDefinition.entityIdToUuid(getEntityId());
params.put(CmsPublishOptions.PARAM_CONTENT, "" + structureId);
params.put(CmsPublishOptions.PARAM_START_WITH_CURRENT_PAGE, "");
CmsPublishDialog.showPublishDialog(params, new CloseHandler<PopupPanel>() {
public void onClose(CloseEvent<PopupPanel> closeEvent) {
if (m_onClose != null) {
m_onClose.execute();
}
clearEditor();
}
});
}
});
}
});
m_saveExitButton = createButton(
Messages.get().key(Messages.GUI_TOOLBAR_SAVE_AND_EXIT_0),
I_CmsToolbarButtonLayoutBundle.INSTANCE.toolbarButtonCss().toolbarSaveExit());
m_saveExitButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
deferSaveAndExit();
}
});
m_toolbar.addLeft(m_saveExitButton);
m_saveButton = createButton(
Messages.get().key(Messages.GUI_TOOLBAR_SAVE_0),
I_CmsButton.ButtonData.SAVE.getIconClass());
m_saveButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
deferSave();
}
});
m_saveButton.setVisible(false);
m_toolbar.addLeft(m_saveButton);
disableSave(Messages.get().key(Messages.GUI_TOOLBAR_NOTHING_CHANGED_0));
m_undoButton = createButton(
Messages.get().key(Messages.GUI_TOOLBAR_UNDO_0),
I_CmsToolbarButtonLayoutBundle.INSTANCE.toolbarButtonCss().toolbarUndo());
m_undoButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
if (UndoRedoHandler.getInstance().isIntitalized()) {
UndoRedoHandler.getInstance().undo();
}
}
});
m_undoButton.disable(Messages.get().key(Messages.GUI_TOOLBAR_UNDO_DISABLED_0));
m_undoButton.getElement().getStyle().setMarginLeft(10, Unit.PX);
m_undoButton.setVisible(false);
m_toolbar.addLeft(m_undoButton);
m_redoButton = createButton(
Messages.get().key(Messages.GUI_TOOLBAR_REDO_0),
I_CmsToolbarButtonLayoutBundle.INSTANCE.toolbarButtonCss().toolbarRedo());
m_redoButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
if (UndoRedoHandler.getInstance().isIntitalized()) {
UndoRedoHandler.getInstance().redo();
}
}
});
m_redoButton.disable(Messages.get().key(Messages.GUI_TOOLBAR_REDO_DISABLED_0));
m_redoButton.getElement().getStyle().setMarginRight(20, Unit.PX);
m_redoButton.setVisible(false);
m_toolbar.addLeft(m_redoButton);
UndoRedoHandler.getInstance().addValueChangeHandler(new ValueChangeHandler<UndoRedoHandler.UndoRedoState>() {
public void onValueChange(ValueChangeEvent<UndoRedoState> event) {
setUndoRedoState(event.getValue());
}
});
m_openFormButton = createButton(
Messages.get().key(Messages.GUI_TOOLBAR_OPEN_FORM_0),
I_CmsButton.ButtonData.EDIT.getIconClass());
m_openFormButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
initFormPanel();
renderFormContent();
}
});
m_toolbar.addLeft(m_openFormButton);
m_hideHelpBubblesButton = new CmsToggleButton();
m_hideHelpBubblesButton.setImageClass(I_CmsButton.ButtonData.TOGGLE_HELP.getIconClass());
m_hideHelpBubblesButton.setButtonStyle(ButtonStyle.IMAGE, null);
m_hideHelpBubblesButton.setSize(Size.big);
m_hideHelpBubblesButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
CmsToggleButton button = (CmsToggleButton)event.getSource();
hideHelpBubbles(!button.isDown());
}
});
m_hideHelpBubblesButton.setDown(CmsCoreProvider.get().isShowEditorHelp());
ValueFocusHandler.getInstance().hideHelpBubbles(RootPanel.get(), !CmsCoreProvider.get().isShowEditorHelp());
if (!CmsCoreProvider.get().isShowEditorHelp()) {
m_hideHelpBubblesButton.setTitle(Messages.get().key(Messages.GUI_TOOLBAR_HELP_BUBBLES_HIDDEN_0));
} else {
m_hideHelpBubblesButton.setTitle(Messages.get().key(Messages.GUI_TOOLBAR_HELP_BUBBLES_SHOWN_0));
}
m_toolbar.addRight(m_hideHelpBubblesButton);
m_cancelButton = createButton(
Messages.get().key(Messages.GUI_TOOLBAR_RESET_0),
I_CmsButton.ButtonData.RESET.getIconClass());
m_cancelButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
confirmCancel();
}
});
m_toolbar.addRight(m_cancelButton);
RootPanel.get().add(m_toolbar);
}
/**
* Sets the resource info to native window context variables.<p>
*
* @param sitePath the site path
* @param locale the content locale
*/
private native void setNativeResourceInfo(String sitePath, String locale)/*-{
$wnd._editResource = sitePath;
$wnd._editLanguage = locale;
}-*/;
/**
* Shows the locked resource error message.<p>
*/
private void showLockedResourceMessage() {
CmsErrorDialog dialog = new CmsErrorDialog(Messages.get().key(
Messages.ERR_RESOURCE_ALREADY_LOCKED_BY_OTHER_USER_0), null);
dialog.addCloseHandler(new CloseHandler<PopupPanel>() {
public void onClose(CloseEvent<PopupPanel> event) {
cancelEdit();
}
});
dialog.center();
}
}
|
package com.galvarez.ttw.model;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.artemis.Aspect;
import com.artemis.ComponentMapper;
import com.artemis.Entity;
import com.artemis.annotations.Wire;
import com.artemis.systems.EntityProcessingSystem;
import com.galvarez.ttw.model.components.AIControlled;
import com.galvarez.ttw.model.components.Army;
import com.galvarez.ttw.model.components.Destination;
import com.galvarez.ttw.model.map.GameMap;
import com.galvarez.ttw.model.map.MapPosition;
import com.galvarez.ttw.rendering.components.Description;
import com.galvarez.ttw.screens.overworld.OverworldScreen;
/**
* Send the army to the tile with smallest difference between ours and second
* influence.
*
* @author Guillaume Alvarez
*/
@Wire
public final class AIArmyMovementSystem extends EntityProcessingSystem {
private static final Logger log = LoggerFactory.getLogger(AIArmyMovementSystem.class);
private ComponentMapper<Destination> destinations;
private ComponentMapper<MapPosition> positions;
private ComponentMapper<Army> armies;
private ComponentMapper<AIControlled> intelligences;
private DestinationSystem destinationSystem;
private final OverworldScreen screen;
private final GameMap map;
@SuppressWarnings("unchecked")
public AIArmyMovementSystem(GameMap map, OverworldScreen screen) {
super(Aspect.getAspectForAll(AIControlled.class, Army.class));
this.map = map;
this.screen = screen;
}
@Override
protected boolean checkProcessing() {
return true;
}
@Override
protected void process(Entity e) {
Destination dest = destinations.getSafe(e);
if (dest == null)
return;
AIControlled ai = intelligences.get(e);
// no need to also check if destination is still influenced by army
// controller: worst case is it is recreated at capital
if (dest.target == null) {
setNewTarget(e, ai);
} else {
// check we are not stuck
MapPosition current = positions.get(e);
if (current.equals(ai.lastPosition)) {
// are we stuck for 3 turns?
if (screen.getTurnNumber() - ai.lastMove > 3)
setNewTarget(e, ai);
} else {
ai.lastMove = screen.getTurnNumber();
ai.lastPosition = current;
}
}
}
private void setNewTarget(Entity army, AIControlled ai) {
AIControlled empire = intelligences.get(armies.get(army).source);
for (int i = 0; i < empire.armiesTargets.size(); i++) {
MapPosition pos = empire.armiesTargets.get(i);
if (!pos.equals(positions.get(army)) && !map.hasEntity(pos)) {
List<MapPosition> path = destinationSystem.computePath(army, pos);
if (path != null) {
ai.lastMove = screen.getTurnNumber();
ai.lastPosition = positions.get(army);
empire.armiesTargets.remove(i);
return;
}
}
}
log.warn("Cannot find a destination for {}", army.getComponent(Description.class));
}
}
|
package org.opencms.workplace.administration;
import org.opencms.jsp.CmsJspActionElement;
import org.opencms.main.OpenCms;
import org.opencms.util.CmsIdentifiableObjectContainer;
import org.opencms.util.CmsStringUtil;
import org.opencms.util.I_CmsIdentifiableObjectContainer;
import org.opencms.workplace.CmsWorkplace;
import org.opencms.workplace.CmsWorkplaceSettings;
import org.opencms.workplace.tools.CmsTool;
import org.opencms.workplace.tools.CmsToolDialog;
import org.opencms.workplace.tools.CmsToolManager;
import java.util.Iterator;
import javax.servlet.http.HttpServletRequest;
/**
* Implementation of the administration view leftside's menu.<p>
*
* @author Michael Moossen
*
* @version $Revision: 1.10 $
*
* @since 6.0.0
*/
public class CmsAdminMenu extends CmsToolDialog {
/** Default link target constant. */
public static final String DEFAULT_TARGET = "admin_content";
/** Group container. */
private I_CmsIdentifiableObjectContainer m_groupContainer = new CmsIdentifiableObjectContainer(true, true);
/**
* Default Constructor.<p>
*
* @param jsp the jsp context
*/
public CmsAdminMenu(CmsJspActionElement jsp) {
super(jsp);
initAdminTool();
installMenu();
}
/**
* Adds a group.<p>
*
* @param group the group
*
* @see I_CmsIdentifiableObjectContainer#addIdentifiableObject(String, Object)
*/
public void addGroup(CmsAdminMenuGroup group) {
m_groupContainer.addIdentifiableObject(group.getName(), group);
}
/**
* Adds a menu item at the given position.<p>
*
* @param group the group
* @param position the position
*
* @see I_CmsIdentifiableObjectContainer#addIdentifiableObject(String, Object, float)
*/
public void addGroup(CmsAdminMenuGroup group, float position) {
m_groupContainer.addIdentifiableObject(group.getName(), group, position);
}
/**
* Adds a new item to the specified menu.<p>
*
* If the menu does not exist, it will be created.<p>
*
* @param groupName the name of the group
* @param name the name of the item
* @param icon the icon to display
* @param link the link to open when selected
* @param helpText the help text to display
* @param enabled if enabled or not
* @param position the relative position to install the item
* @param target the target frame to open the link into
*
* @return the new item
*/
public CmsAdminMenuItem addItem(
String groupName,
String name,
String icon,
String link,
String helpText,
boolean enabled,
float position,
String target) {
groupName = resolveMacros(groupName);
CmsAdminMenuGroup group = getGroup(groupName);
if (group == null) {
String gid = "group" + m_groupContainer.elementList().size();
group = new CmsAdminMenuGroup(gid, groupName);
addGroup(group, position);
}
String id = "item" + group.getId() + group.getMenuItems().size();
CmsAdminMenuItem item = new CmsAdminMenuItem(id, name, icon, link, helpText, enabled, target);
group.addMenuItem(item, position);
return item;
}
/**
* Returns the requested group.<p>
*
* @param name the name of the group
*
* @return the group
*
* @see I_CmsIdentifiableObjectContainer#getObject(String)
*/
public CmsAdminMenuGroup getGroup(String name) {
return (CmsAdminMenuGroup)m_groupContainer.getObject(name);
}
/**
* Returns the admin manager.<p>
*
* @return the admin manager
*/
public CmsToolManager getToolManager() {
return OpenCms.getWorkplaceManager().getToolManager();
}
/**
* Generates the necesary html code for the groups.<p>
*
* @param wp the page for which the code is generated
*
* @return html code
*/
public String groupHtml(CmsWorkplace wp) {
StringBuffer html = new StringBuffer(2048);
Iterator itHtml = m_groupContainer.elementList().iterator();
while (itHtml.hasNext()) {
CmsAdminMenuGroup group = (CmsAdminMenuGroup)itHtml.next();
html.append(group.groupHtml(wp));
}
return html.toString();
}
/**
* Creates the default menu as the root tool structure.<p>
*/
public void installMenu() {
// initialize the menu groups
m_groupContainer.clear();
// creates the context help menu
CmsAdminMenuGroup helpMenu = new CmsAdminMenuGroup("help", Messages.get().key(
getLocale(),
Messages.GUI_ADMIN_MENU_HELP_GROUP_0,
null));
helpMenu.addMenuItem(new CmsAdminContextHelpMenuItem());
addGroup(helpMenu);
Iterator itElems = getToolManager().getToolHandlers().iterator();
while (itElems.hasNext()) {
CmsTool tool = (CmsTool)itElems.next();
// check visibility
if (!getCms().existsResource(tool.getHandler().getLink()) || !tool.getHandler().isVisible(getCms())) {
continue;
}
String root = getToolManager().getRootToolPath(this);
// leave out everything above the root
if (!tool.getHandler().getPath().startsWith(root)) {
continue;
}
// cut out the root
String path = tool.getHandler().getPath().substring(getToolManager().getRootToolPath(this).length());
// special case of the root tool
if (CmsStringUtil.isEmpty(path)) {
continue;
}
// skip initial '/'
int pos = tool.getHandler().getPath().indexOf(CmsToolManager.C_TOOLPATH_SEPARATOR);
// only install if at first level
if (path.indexOf(CmsToolManager.C_TOOLPATH_SEPARATOR, pos + 1) < 0) {
addItem(
tool.getHandler().getGroup(),
tool.getHandler().getShortName(),
tool.getHandler().getSmallIconPath(),
CmsToolManager.linkForToolPath(getJsp(), tool.getHandler().getPath()),
tool.getHandler().isEnabled(getCms()) ? tool.getHandler().getHelpText()
: tool.getHandler().getDisabledHelpText(),
tool.getHandler().isEnabled(getCms()),
tool.getHandler().getPosition(),
CmsAdminMenu.DEFAULT_TARGET);
}
}
}
/**
* @see org.opencms.workplace.CmsWorkplace#initWorkplaceRequestValues(org.opencms.workplace.CmsWorkplaceSettings, javax.servlet.http.HttpServletRequest)
*/
protected void initWorkplaceRequestValues(CmsWorkplaceSettings settings, HttpServletRequest request) {
fillParamValues(request);
}
}
|
package liquibase.database.sql;
import liquibase.database.Database;
import java.util.*;
public class UpdateStatement implements SqlStatement {
private String schemaName;
private String tableName;
private Map<String, Object> newColumnValues = new HashMap<String, Object>();
private String whereClause;
private List<Object> whereParameters = new ArrayList<Object>();
public UpdateStatement(String schemaName, String tableName) {
this.schemaName = schemaName;
this.tableName = tableName;
}
public String getSchemaName() {
return schemaName;
}
public String getTableName() {
return tableName;
}
public UpdateStatement addNewColumnValue(String columnName, Object newValue) {
newColumnValues.put(columnName, newValue);
return this;
}
public String getWhereClause() {
return whereClause;
}
public UpdateStatement setWhereClause(String whereClause) {
this.whereClause = whereClause;
return this;
}
public void addWhereParameter(Object value) {
this.whereParameters.add(value);
}
public boolean supportsDatabase(Database database) {
return true;
}
public Map<String, Object> getNewColumnValues() {
return newColumnValues;
}
public String getSqlStatement(Database database) {
StringBuffer sql = new StringBuffer("UPDATE "+database.escapeTableName(getSchemaName(), getTableName())+" SET");
for (String column : newColumnValues.keySet()) {
sql.append(" ").append(database.escapeColumnName(getSchemaName(), getTableName(), column)).append(" = ");
sql.append(convertToString(newColumnValues.get(column), database));
sql.append(",");
}
sql.deleteCharAt(sql.lastIndexOf(","));
if (whereClause != null) {
String fixedWhereClause = "WHERE "+whereClause;
for (Object param : whereParameters) {
fixedWhereClause = fixedWhereClause.replaceFirst("\\?", convertToString(param, database));
}
sql.append(" ").append(fixedWhereClause);
}
return sql.toString();
}
private String convertToString(Object newValue, Database database) {
String sqlString;
if (newValue == null || newValue.toString().equalsIgnoreCase("NULL")) {
sqlString = "NULL";
} else if (newValue instanceof String && database.shouldQuoteValue(((String) newValue))) {
sqlString = "'" + database.escapeStringForDatabase(newValue.toString()) + "'";
} else if (newValue instanceof Date) {
sqlString = database.getDateLiteral(((Date) newValue));
} else if (newValue instanceof Boolean) {
if (((Boolean) newValue)) {
sqlString = database.getTrueBooleanValue();
} else {
sqlString = database.getFalseBooleanValue();
}
} else {
sqlString = newValue.toString();
}
return sqlString;
}
public String getEndDelimiter(Database database) {
return ";";
}
}
|
package net.tomp2p.message;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.channel.socket.DatagramChannel;
import io.netty.channel.socket.DatagramPacket;
import java.net.InetSocketAddress;
import net.tomp2p.connection.SignatureFactory;
import net.tomp2p.storage.AlternativeCompositeByteBuf;
import net.tomp2p.utils.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TomP2POutbound extends ChannelOutboundHandlerAdapter {
private static final Logger LOG = LoggerFactory.getLogger(TomP2POutbound.class);
private final boolean preferDirect;
private final Encoder encoder;
private final CompByteBufAllocator alloc;
public TomP2POutbound(boolean preferDirect, SignatureFactory signatureFactory) {
this(preferDirect, signatureFactory, new CompByteBufAllocator());
}
public TomP2POutbound(boolean preferDirect, SignatureFactory signatureFactory, CompByteBufAllocator alloc) {
this.preferDirect = preferDirect;
this.encoder = new Encoder(signatureFactory);
this.alloc = alloc;
}
@Override
public void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise)
throws Exception {
AlternativeCompositeByteBuf buf = null;
if (!(msg instanceof Message)) {
ctx.write(msg, promise);
return;
}
try {
boolean done = false;
if (preferDirect) {
buf = alloc.compDirectBuffer();
} else {
buf = alloc.compBuffer();
}
//null, means create signature
done = encoder.write(buf, (Message) msg, null);
final Message message = encoder.message();
if (buf.isReadable()) {
// this will release the buffer
if (ctx.channel() instanceof DatagramChannel) {
final InetSocketAddress recipientUnreflected;
final InetSocketAddress recipient;
final InetSocketAddress sender;
if (message.senderSocket() == null) {
//in case of a request
if(message.recipientRelay()!=null) {
//in case of sending to a relay (the relayed flag is already set)
recipientUnreflected = message.recipientRelay().createSocketUDP();
} else {
recipientUnreflected = message.recipient().createSocketUDP();
}
recipient = Utils.natReflection(recipientUnreflected, true, message.sender());
sender = message.sender().createSocketUDP(0);
} else {
//in case of a reply
recipient = message.senderSocket();
sender = message.recipientSocket();
}
DatagramPacket d = new DatagramPacket(buf, recipient, sender);
LOG.debug("Send UPD message {}, datagram: {}", message, d);
ctx.writeAndFlush(d, promise);
} else {
LOG.debug("Send TCP message {} to {}", message, message.senderSocket());
ctx.writeAndFlush(buf, promise);
}
if (done) {
message.setDone(true);
// we wrote the complete message, reset state
encoder.reset();
}
} else {
buf.release();
ctx.write(Unpooled.EMPTY_BUFFER, promise);
}
buf = null;
} catch (Throwable t) {
exceptionCaught(ctx, t);
}
finally {
if (buf != null) {
buf.release();
}
}
}
@Override
public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) throws Exception {
if (encoder.message() == null) {
LOG.error("exception in encoding, starting", cause);
cause.printStackTrace();
} else if (encoder.message() != null && !encoder.message().isDone()) {
LOG.error("exception in encoding, started", cause);
cause.printStackTrace();
}
}
}
|
import java.io.IOException;
import java.io.FileInputStream;
import java.io.BufferedInputStream;
import java.util.Date;
import java.util.Properties;
import java.util.Observable;
import java.util.Observer;
import java.util.Vector;
import ie.omk.smpp.SMPPException;
import ie.omk.smpp.SmppConnectionDropPacket;
import ie.omk.smpp.SmppReceiver;
import ie.omk.smpp.SmppEvent;
import ie.omk.smpp.net.TcpLink;
import ie.omk.smpp.message.SMPPPacket;
import ie.omk.smpp.message.DeliverSM;
import ie.omk.smpp.message.SmeAddress;
import ie.omk.smpp.message.Unbind;
import ie.omk.smpp.message.UnbindResp;
import ie.omk.smpp.util.GSMConstants;
/** Example class to submit a message to a SMSC.
* This class simply binds to the server, submits a message and then unbinds.
*/
public class AsyncReceiver
implements java.util.Observer
{
// Default properties file to read..
public static final String PROPS_FILE = "smpp.properties";
private static Properties props = null;
private static int msgCount = 0;
// Start time (once successfully bound).
private long start = 0;
// End time (either send an unbind or an unbind received).
private long end = 0;
// Set to true to display each message received.
private boolean showMsgs = false;
// This is called when the connection receives a packet from the SMSC.
public void update(Observable o, Object arg)
{
SmppReceiver trans = (SmppReceiver)o;
SmppEvent ev = (SmppEvent)arg;
SMPPPacket pak = ev.getPacket();
switch (pak.getCommandId()) {
// Bind transmitter response. Check it's status for success...
case SMPPPacket.ESME_BNDRCV_RESP:
if (pak.getCommandStatus() != 0) {
System.out.println("Error binding to the SMSC. Error = "
+ pak.getCommandStatus());
} else {
this.start = System.currentTimeMillis();
System.out.println("Successfully bound. Waiting for message"
+ " delivery..");
System.out.println("(Each dot printed is 500 deliver_sm's!)");
}
break;
// Submit message response...
case SMPPPacket.SMSC_DELIVER_SM:
if (pak.getCommandStatus() != 0) {
System.out.println("Deliver SM with an error! "
+ pak.getCommandStatus());
} else {
++msgCount;
if (showMsgs) {
System.out.println(Integer.toString(pak.getSequenceNum())
+ ": \"" + ((DeliverSM)pak).getMessageText()
+ "\"");
} else if ((msgCount % 500) == 0) {
System.out.print("."); // Give some feedback
}
}
break;
// Unbind request received from server..
case SMPPPacket.ESME_UBD:
this.end = System.currentTimeMillis();
System.out.println("\nSMSC has requested unbind! Responding..");
try {
UnbindResp ubr = new UnbindResp((Unbind)pak);
trans.sendResponse(ubr);
} catch (SMPPException x) {
x.printStackTrace(System.err);
} catch (IOException x) {
x.printStackTrace(System.err);
} finally {
endReport();
}
break;
// Unbind response..
case SMPPPacket.ESME_UBD_RESP:
this.end = System.currentTimeMillis();
System.out.println("\nUnbound.");
endReport();
break;
case SmppConnectionDropPacket.CONNECTION_DROP:
this.end = System.currentTimeMillis();
System.out.println("\nNetwork connection dropped!");
endReport();
break;
default:
System.out.println("\nUnexpected packet received! Id = "
+ Integer.toHexString(pak.getCommandId()));
}
}
// Print out a report
private void endReport()
{
System.out.println("deliver_sm's received: " + msgCount);
System.out.println("Start time: " + new Date(start).toString());
System.out.println("End time: " + new Date(end).toString());
System.out.println("Elapsed: " + (end - start) + " milliseconds.");
}
public static void main(String[] args)
{
try {
AsyncReceiver ex = new AsyncReceiver();
if (args.length > 0 && "-s".equals(args[0]))
ex.showMsgs = true;
FileInputStream in = new FileInputStream(PROPS_FILE);
ex.props = new Properties();
ex.props.load(new BufferedInputStream(in));
String server = props.getProperty("smsc.name", "localhost");
String p = props.getProperty("smsc.port", "5432");
int port = Integer.parseInt(p);
// Open a network link to the SMSC..
TcpLink link = new TcpLink(server, port);
// Create an SmppReceiver object (we won't bind just yet..)
SmppReceiver recv = new SmppReceiver(link, true);
// Need to add myself to the list of listeners for this connection
recv.addObserver(ex);
// Automatically respond to ENQUIRE_LINK requests from the SMSC
recv.autoAckLink(true);
recv.autoAckMessages(true);
// Set our authorisation information
String sysType = props.getProperty("esme.system_type");
String sysID = props.getProperty("esme.system_id");
String password = props.getProperty("esme.password");
SmeAddress source = new SmeAddress(
GSMConstants.GSM_TON_UNKNOWN,
GSMConstants.GSM_NPI_UNKNOWN,
props.getProperty("esme.destination"));
// Bind to the SMSC
recv.bind(sysID, password, sysType, source);
System.out.println("Hit a key to issue an unbind..");
System.in.read();
if (recv.getState() == recv.BOUND) {
System.out.println("Sending unbind request..");
recv.unbind();
}
} catch (IOException x) {
x.printStackTrace(System.err);
} catch (NumberFormatException x) {
System.err.println("Bad port number in properties file.");
x.printStackTrace(System.err);
} catch (SMPPException x) {
System.err.println("SMPP exception: " + x.getMessage());
x.printStackTrace(System.err);
}
}
}
|
package controllers;
import java.io.*;
import java.nio.charset.Charset;
import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.Expr;
import com.avaje.ebean.SqlRow;
import com.csvreader.CsvWriter;
import models.*;
import play.*;
import play.data.*;
import play.libs.Json;
import play.mvc.*;
import static controllers.Application.getConfiguration;
@With(DumpOnError.class)
@Secured.Auth(UserRole.ROLE_ALL_ACCESS)
public class Attendance extends Controller {
static Form<AttendanceCode> code_form;
static Form<AttendanceCode> getCodeForm() {
if (code_form == null) {
code_form = Form.form(AttendanceCode.class);
}
return code_form;
}
String renderIndexContent(Date start_date) {
Date end_date = new Date(start_date.getTime());
end_date.setYear(end_date.getYear() + 1);
Map<Person, AttendanceStats> person_to_stats = new HashMap<>();
Map<String, AttendanceCode> codes_map = getCodesMap(false);
List<AttendanceDay> days =
AttendanceDay.find.where()
.eq("person.organization", OrgConfig.get().org)
.ge("day", start_date)
.le("day", end_date)
.findList();
for (AttendanceDay day : days) {
if (!person_to_stats.containsKey(day.person)) {
person_to_stats.put(day.person, new AttendanceStats());
}
AttendanceStats stats = person_to_stats.get(day.person);
if (day.code != null && day.code.equals("_NS_")) {
// special no school day code, do nothing.
} else if (day.code != null || day.start_time == null || day.end_time == null) {
stats.incrementCodeCount(codes_map.get(day.code));
} else {
stats.incrementAttendance(day);
}
}
List<AttendanceWeek> weeks =
AttendanceWeek.find.where()
.eq("person.organization", OrgConfig.get().org)
.ge("monday", start_date)
.le("monday", end_date)
.findList();
for (AttendanceWeek week : weeks) {
if (!person_to_stats.containsKey(week.person)) {
person_to_stats.put(week.person, new AttendanceStats());
}
AttendanceStats stats = person_to_stats.get(week.person);
stats.total_hours += week.extra_hours;
}
List<Person> all_people = new ArrayList<>(person_to_stats.keySet());
Collections.sort(all_people, Person.SORT_FIRST_NAME);
List<String> all_codes = new ArrayList<>(codes_map.keySet());
Date prev_date = new Date(start_date.getTime());
prev_date.setYear(prev_date.getYear() - 1);
Date next_date = new Date(start_date.getTime());
next_date.setYear(next_date.getYear() + 1);
if (start_date.getYear() == Application.getStartOfYear().getYear()) {
next_date = null;
}
return views.html.attendance_index.render(
all_people, person_to_stats, all_codes, codes_map,
Application.attendancePeople(), start_date, prev_date, next_date).toString();
}
public Result index(String start_date) {
if (start_date.equals("")) {
return ok(views.html.cached_page.render(
new CachedPage(CachedPage.ATTENDANCE_INDEX,
"Attendance",
"attendance",
"attendance_home") {
@Override
String render() {
return renderIndexContent(Application.getStartOfYear());
}
}));
} else {
return ok(views.html.cached_page.render(
new CachedPage("",
"Attendance",
"attendance",
"attendance_home") {
@Override
public String getPage() {
return renderIndexContent(Utils.parseDateOrNow(start_date).getTime());
}
@Override
String render() {
throw new RuntimeException("This shouldn't be called");
}
}));
}
}
public Result viewOrEditWeek(String date, boolean do_view) {
Calendar start_date = Utils.parseDateOrNow(date);
Utils.adjustToPreviousDay(start_date, Calendar.MONDAY);
Calendar end_date = (Calendar)start_date.clone();
end_date.add(Calendar.DAY_OF_MONTH, 5);
List<AttendanceDay> days =
AttendanceDay.find.where()
.eq("person.organization", OrgConfig.get().org)
.ge("day", start_date.getTime())
.lt("day", end_date.getTime())
.order("day ASC")
.findList();
Map<Person, List<AttendanceDay>> person_to_days =
new HashMap<Person, List<AttendanceDay>>();
for (AttendanceDay day : days) {
List<AttendanceDay> list = person_to_days.containsKey(day.person)
? person_to_days.get(day.person)
: new ArrayList<AttendanceDay>();
list.add(day);
person_to_days.put(day.person, list);
}
List<AttendanceWeek> weeks =
AttendanceWeek.find.where()
.eq("person.organization", OrgConfig.get().org)
.eq("monday", start_date.getTime())
.findList();
Map<Person, AttendanceWeek> person_to_week =
new HashMap<Person, AttendanceWeek>();
for (AttendanceWeek week : weeks) {
person_to_week.put(week.person, week);
}
List<Person> all_people = new ArrayList<Person>(person_to_days.keySet());
for (Person p : person_to_week.keySet()) {
if (!all_people.contains(p)) {
all_people.add(p);
}
}
Collections.sort(all_people, Person.SORT_FIRST_NAME);
Map<String, AttendanceCode> codes = getCodesMap(do_view);
if (do_view) {
return ok(views.html.attendance_week.render(
start_date.getTime(),
codes,
all_people,
person_to_days,
person_to_week));
} else {
List<Person> additional_people = Application.attendancePeople();
additional_people.removeAll(all_people);
Collections.sort(additional_people, Person.SORT_DISPLAY_NAME);
response().setHeader("Cache-Control", "max-age=0, no-cache, no-store");
response().setHeader("Pragma", "no-cache");
return ok(views.html.edit_attendance_week.render(
start_date.getTime(),
codes,
all_people,
additional_people,
person_to_days,
person_to_week));
}
}
public Result jsonPeople(String term) {
List<Person> name_matches =
Person.find.where()
.add(Expr.or(Expr.ilike("last_name", "%" + term + "%"),
Expr.ilike("first_name", "%" + term + "%")))
.eq("organization", Organization.getByHost())
.eq("is_family", false)
.findList();
List<Person> selected_people = new ArrayList<>();
for (Person p : name_matches) {
if (!p.attendance_days.isEmpty()) {
selected_people.add(p);
}
}
selected_people.sort(Person.SORT_FIRST_NAME);
List<Map<String, String>> result = new ArrayList<>();
for (Person p : selected_people) {
HashMap<String, String> values = new HashMap<>();
String label = p.first_name;
if (p.last_name != null) {
label = label + " " + p.last_name;
}
values.put("label", label);
values.put("id", "" + p.person_id);
result.add(values);
}
return ok(Json.stringify(Json.toJson(result)));
}
public Result viewPersonReport(Integer person_id, String start_date_str, String end_date_str) {
Person p = Person.findById(person_id);
Date start_date = Application.getStartOfYear();
Date end_date = new Date();
if (!start_date_str.trim().isEmpty() || !end_date_str.trim().isEmpty()) {
try {
start_date = new SimpleDateFormat("yyyy-M-d").parse(start_date_str);
end_date = new SimpleDateFormat("yyyy-M-d").parse(end_date_str);
} catch (ParseException e) {
}
} else {
AttendanceDay last_day =
AttendanceDay.find.where()
.eq("person", p)
.order("day DESC")
.setMaxRows(1)
.findUnique();
if (last_day != null) {
end_date = last_day.day;
start_date = Application.getStartOfYear(end_date);
}
}
String sql = "select min(day) as min_date, max(day) as max_date from attendance_day where " +
"person_id=:person_id and " +
"((code is not null and code != '_NS_') or " +
"(start_time is not null and end_time is not null)) " +
"group by person_id";
SqlRow row = Ebean.createSqlQuery(sql)
.setParameter("person_id", p.person_id)
.findUnique();
List<AttendanceDay> days =
AttendanceDay.find.where()
.eq("person", p)
.ge("day", start_date)
.le("day", end_date)
.order("day ASC")
.findList();
List<AttendanceWeek> weeks =
AttendanceWeek.find.where()
.eq("person", p)
.ge("monday", start_date)
.le("monday", end_date)
.findList();
Map<String, AttendanceCode> codes_map = getCodesMap(true);
AttendanceStats stats = new AttendanceStats();
for (AttendanceDay day : days) {
if (day.code != null || day.start_time == null || day.end_time == null) {
stats.incrementCodeCount(codes_map.get(day.code));
} else {
stats.incrementAttendance(day);
}
}
for (AttendanceWeek week : weeks) {
stats.total_hours += week.extra_hours;
}
Map<Date, AttendanceWeek> day_to_week = new HashMap<Date, AttendanceWeek>();
for (AttendanceWeek w : weeks) {
day_to_week.put(w.monday, w);
}
return ok(views.html.attendance_person.render(
p,
days,
day_to_week,
new ArrayList<String>(codes_map.keySet()),
codes_map,
stats,
start_date,
end_date,
row == null ? null : row.getDate("min_date"),
row == null ? null : row.getDate("max_date")
));
}
public Result importFromCustodia() {
Map<String,String[]> data = request().body().asFormUrlEncoded();
Calendar start_date = Utils.parseDateOrNow(data.get("monday")[0]);
Calendar end_date = (Calendar) start_date.clone();
end_date.add(Calendar.DAY_OF_MONTH, 4);
List<AttendanceDay> days =
AttendanceDay.find.where()
.eq("person.organization", OrgConfig.get().org)
.ge("day", start_date.getTime())
.le("day", end_date.getTime())
.findList();
Set<Person> people = new HashSet<>();
for (AttendanceDay day : days) {
people.add(day.person);
}
List<Integer> person_ids = new ArrayList<>();
for (Person person : people) {
person_ids.add(person.person_id);
}
if (!person_ids.isEmpty()) {
String sql = "select dst_id, swipe_day, " +
"min(in_time) at time zone :time_zone as in_time, " +
"max(out_time) at time zone :time_zone as out_time " +
"from overseer.swipes sw join overseer.students stu on sw.student_id=stu._id " +
"where in_time is not null and out_time is not null " +
"and dst_id in (:person_ids) " +
"and swipe_day >= :first_date and swipe_day <= :last_date " +
"group by dst_id, swipe_day";
List<SqlRow> custodiaRows = Ebean.createSqlQuery(sql)
.setParameter("time_zone", OrgConfig.get().time_zone.getID())
.setParameter("person_ids", person_ids)
.setParameter("first_date", start_date.getTime())
.setParameter("last_date", end_date.getTime())
.findList();
Map<Integer, Map<Date, SqlRow>> person_day_custodia = new HashMap<>();
for (SqlRow row : custodiaRows) {
int person_id = row.getInteger("dst_id");
Date day = row.getDate("swipe_day");
if (!person_day_custodia.containsKey(person_id)) {
person_day_custodia.put(person_id, new HashMap<>());
}
person_day_custodia.get(person_id).put(day, row);
}
for (AttendanceDay day : days) {
if (day.code == null && day.start_time == null && day.end_time == null
&& person_day_custodia.containsKey(day.person.person_id)
&& person_day_custodia.get(day.person.person_id).containsKey(day.day)) {
SqlRow row = person_day_custodia.get(day.person.person_id).get(day.day);
day.start_time = new Time(row.getDate("in_time").getTime());
day.end_time = new Time(row.getDate("out_time").getTime());
day.save();
}
}
CachedPage.remove(CachedPage.ATTENDANCE_INDEX);
}
return redirect(routes.Attendance.editWeek(Application.forDateInput(start_date.getTime())));
}
public Result createPersonWeek() {
CachedPage.remove(CachedPage.ATTENDANCE_INDEX);
Map<String,String[]> data = request().body().asFormUrlEncoded();
Calendar start_date = Utils.parseDateOrNow(data.get("monday")[0]);
ArrayList<Object> result = new ArrayList<Object>();
String[] person_ids = data.get("person_id[]");
if (person_ids == null) {
return badRequest("No person_id[] found");
}
for (String person_id : person_ids) {
Calendar end_date = (Calendar)start_date.clone();
boolean alreadyExists = false;
Person p = Person.findById(Integer.parseInt(person_id));
try {
AttendanceWeek.create(start_date.getTime(), p);
} catch (javax.persistence.PersistenceException pe) {
Utils.eatIfUniqueViolation(pe);
alreadyExists = true;
}
Map<String, Object> one_result = new HashMap<String, Object>();
// look up our newly-created object so that we get the ID
one_result.put("week", AttendanceWeek.find.where()
.eq("person", p)
.eq("monday", start_date.getTime())
.findUnique());
for (int i = 0; i < 5; i++) {
try {
AttendanceDay.create(end_date.getTime(), p);
} catch (javax.persistence.PersistenceException pe) {
Utils.eatIfUniqueViolation(pe);
alreadyExists = true;
}
end_date.add(Calendar.DAY_OF_MONTH, 1);
}
one_result.put("days",
AttendanceDay.find.where()
.eq("person", p)
.ge("day", start_date.getTime())
.le("day", end_date.getTime())
.order("day ASC")
.setMaxRows(5)
.findList());
if (!alreadyExists) {
result.add(one_result);
}
}
return ok(Utils.toJson(result));
}
public Result deletePersonWeek(int person_id, String monday) {
CachedPage.remove(CachedPage.ATTENDANCE_INDEX);
Calendar start_date = Utils.parseDateOrNow(monday);
Calendar end_date = (Calendar)start_date.clone();
end_date.add(Calendar.DAY_OF_MONTH, 5);
Person p = Person.findById(person_id);
List<AttendanceDay> days = AttendanceDay.find.where()
.eq("person", p)
.ge("day", start_date.getTime())
.le("day", end_date.getTime())
.findList();
for (AttendanceDay day : days) {
day.delete();
}
List<AttendanceWeek> weeks = AttendanceWeek.find.where()
.eq("person", p)
.eq("monday", start_date.getTime())
.findList();
for (AttendanceWeek week : weeks) {
week.delete();
}
return ok();
}
public Result download(String start_date_str) throws IOException {
Date start_date = Application.getStartOfYear();
if (!start_date_str.equals("")) {
start_date = Utils.parseDateOrNow(start_date_str).getTime();
}
Date end_date = new Date(start_date.getTime());
end_date.setYear(end_date.getYear() + 1);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Charset charset = Charset.forName("UTF-8");
CsvWriter writer = new CsvWriter(baos, ',', charset);
writer.write("Name");
writer.write("Day");
writer.write("Absence code");
writer.write("Arrival time");
writer.write("Departure time");
writer.write("Extra hours");
writer.endRecord();
List<AttendanceDay> days =
AttendanceDay.find.where()
.eq("person.organization", OrgConfig.get().org)
.ge("day", start_date)
.le("day", end_date)
.findList();
for (AttendanceDay day : days) {
writer.write(day.person.first_name + " " + day.person.last_name);
writer.write(Application.yymmddDate(day.day));
if (day.code != null) {
writer.write(day.code);
writer.write(""); // empty start_time and end_time
writer.write("");
} else {
writer.write("");
writer.write(day.start_time != null ? day.start_time.toString() : "");
writer.write(day.end_time != null ? day.end_time.toString() : "");
}
writer.write(""); // no extra hours
writer.endRecord();
}
List<AttendanceWeek> weeks =
AttendanceWeek.find.where()
.eq("person.organization", OrgConfig.get().org)
.ge("monday", start_date)
.le("monday", end_date)
.findList();
for (AttendanceWeek week : weeks) {
writer.write(week.person.first_name + " " + week.person.last_name);
writer.write(Application.yymmddDate(week.monday));
for (int i = 0; i < 3; i++) {
writer.write("");
}
writer.write("" + week.extra_hours);
writer.endRecord();
}
writer.close();
response().setHeader("Content-Type", "application/zip");
response().setHeader("Content-Disposition",
"attachment; filename=attendance.zip");
ByteArrayOutputStream zipBytes = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(zipBytes);
zos.putNextEntry(new ZipEntry("attendance/all_data.csv"));
// Adding the BOM here causes Excel 2010 on Windows to realize
// that the file is Unicode-encoded.
zos.write("\ufeff".getBytes(charset));
zos.write(baos.toByteArray());
zos.closeEntry();
TreeSet<Date> allDates = new TreeSet<>();
TreeMap<String, HashMap<Date, AttendanceDay>> personDateAttendance = new TreeMap<>();
for (AttendanceDay day : days) {
allDates.add(day.day);
String name = day.person.first_name + " " + day.person.last_name;
if (!personDateAttendance.containsKey(name)) {
personDateAttendance.put(name, new HashMap<>());
}
personDateAttendance.get(name).put(day.day, day);
}
zos.putNextEntry(new ZipEntry("attendance/daily_hours.csv"));
// Adding the BOM here causes Excel 2010 on Windows to realize
// that the file is Unicode-encoded.
zos.write("\ufeff".getBytes(charset));
zos.write(getDailyHoursFile(allDates, personDateAttendance, charset));
zos.closeEntry();
zos.putNextEntry(new ZipEntry("attendance/daily_signins.csv"));
// Adding the BOM here causes Excel 2010 on Windows to realize
// that the file is Unicode-encoded.
zos.write("\ufeff".getBytes(charset));
zos.write(getDailySigninsFile(allDates, personDateAttendance, charset));
zos.closeEntry();
zos.close();
return ok(zipBytes.toByteArray());
}
private byte[] getDailyHoursFile(TreeSet<Date> allDates,
TreeMap<String, HashMap<Date, AttendanceDay>> personDateAttendance,
Charset charset) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
CsvWriter writer = new CsvWriter(baos, ',', charset);
writer.write("Name");
for (Date d : allDates) {
writer.write(Application.yymmddDate(d));
}
writer.endRecord();
for (String name : personDateAttendance.keySet()) {
writer.write(name);
for (Date date : allDates) {
AttendanceDay day = personDateAttendance.get(name).get(date);
if (day == null || day.start_time == null || day.end_time == null) {
writer.write(day == null || day.code == null ? "" : day.code);
} else {
writer.write(String.format("%.2f", day.getHours()));
}
}
writer.endRecord();
}
writer.close();
return baos.toByteArray();
}
private byte[] getDailySigninsFile(TreeSet<Date> allDates,
TreeMap<String, HashMap<Date, AttendanceDay>> personDateAttendance,
Charset charset) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
CsvWriter writer = new CsvWriter(baos, ',', charset);
writer.write("Name");
for (Date d : allDates) {
writer.write(Application.yymmddDate(d));
}
writer.endRecord();
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
for (String name : personDateAttendance.keySet()) {
for (int x = 0; x < 2; x++) {
writer.write(x == 0 ? name : "");
for (Date date : allDates) {
AttendanceDay day = personDateAttendance.get(name).get(date);
if (day == null || day.start_time == null || day.end_time == null) {
writer.write(day == null || day.code == null ? "" : day.code);
} else {
writer.write(dateFormat.format(x == 0 ? day.start_time : day.end_time));
}
}
writer.endRecord();
}
}
writer.close();
return baos.toByteArray();
}
public Result viewWeek(String date) {
return viewOrEditWeek(date, true);
}
public Result editWeek(String date) {
return viewOrEditWeek(date, false);
}
public Result saveWeek(Integer week_id, Double extra_hours) {
CachedPage.remove(CachedPage.ATTENDANCE_INDEX);
AttendanceWeek.find.byId(week_id).edit(extra_hours);
return ok();
}
public Result saveDay(Integer day_id, String code,
String start_time, String end_time) throws Exception {
CachedPage.remove(CachedPage.ATTENDANCE_INDEX);
AttendanceDay.find.byId(day_id).edit(code, start_time, end_time);
return ok();
}
public static Map<String, AttendanceCode> getCodesMap(boolean include_no_school) {
Map<String, AttendanceCode> codes = new HashMap<String, AttendanceCode>();
for (AttendanceCode code : AttendanceCode.all(OrgConfig.get().org)) {
codes.put(code.code, code);
}
if (include_no_school) {
AttendanceCode no_school = new AttendanceCode();
no_school.description = "No school";
no_school.color = "#cc9";
no_school.code = "_NS_";
codes.put("_NS_", no_school);
}
return codes;
}
public Result viewCustodiaAdmin() {
Map<String, Object> scopes = new HashMap<>();
Configuration conf = getConfiguration();
scopes.put("custodiaUrl", conf.getString("custodia_url"));
scopes.put("custodiaUsername", OrgConfig.get().org.short_name + "-admin");
scopes.put("custodiaPassword", conf.getString("custodia_password"));
Result result = ok(views.html.main_with_mustache.render(
"Sign in system",
"custodia",
"",
"custodia_admin.html",
scopes));
return result;
}
public Result assignPINs() {
List<Person> people = Application.attendancePeople();
Collections.sort(people, Person.SORT_DISPLAY_NAME);
return ok(views.html.attendance_pins.render(people));
}
public Result savePINs() {
List<Person> people = Application.attendancePeople();
Set<Map.Entry<String,String[]>> entries = request().queryString().entrySet();
for (Map.Entry<String, String[]> entry : entries) {
Integer person_id = Integer.parseInt(entry.getKey());
for (Person person : people) {
if (person.person_id == person_id) {
person.pin = entry.getValue()[0];
person.save();
break;
}
}
}
return redirect(routes.Attendance.assignPINs());
}
// TODO need to make this accessible without logging in
public Result checkin() {
return redirect("/assets/checkin/app.html");
}
public Result checkinData() {
List<CheckinPerson> people = Application.attendancePeople().stream()
.filter(p -> p.pin != null && !p.pin.isEmpty())
.map(p -> new CheckinPerson(p))
.collect(Collectors.toList());
return ok(Json.stringify(Json.toJson(people)));
}
public Result checkinMessage(long time, int person_id, boolean is_arriving) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date day = sdf.parse(sdf.format(new Date(time)));
// if the day is Saturday or Sunday, ignore the message
Calendar calendar = new GregorianCalendar();
calendar.setTime(day);
int dow = calendar.get(Calendar.DAY_OF_WEEK);
if (dow == Calendar.SATURDAY || dow == Calendar.SUNDAY) {
return ok();
}
// find or create AttendanceWeek and AttendanceDay objects
Person person = Person.findById(person_id);
AttendanceWeek.findOrCreate(day, person);
AttendanceDay attendance_day = AttendanceDay.find.where()
.eq("person", person)
.eq("day", day)
.findUnique();
// Messages from the app should never overwrite existing data.
// Check if the value exists and set it if it doesn't.
if (attendance_day.code == null || attendance_day.code.isEmpty()) {
if (is_arriving && attendance_day.start_time == null) {
attendance_day.start_time = new Time(time);
attendance_day.update();
}
else if (!is_arriving && attendance_day.end_time == null) {
attendance_day.end_time = new Time(time);
attendance_day.update();
}
}
return ok();
}
public Result viewCodes() {
return ok(views.html.attendance_codes.render(
AttendanceCode.all(OrgConfig.get().org),
getCodeForm()));
}
public Result newCode() {
AttendanceCode ac = AttendanceCode.create(OrgConfig.get().org);
Form<AttendanceCode> filled_form = getCodeForm().bindFromRequest();
ac.edit(filled_form);
CachedPage.remove(CachedPage.ATTENDANCE_INDEX);
return redirect(routes.Attendance.viewCodes());
}
public Result editCode(Integer code_id) {
AttendanceCode ac = AttendanceCode.findById(code_id);
Form<AttendanceCode> filled_form = getCodeForm().fill(ac);
return ok(views.html.edit_attendance_code.render(filled_form));
}
public Result saveCode() {
Form<AttendanceCode> filled_form = getCodeForm().bindFromRequest();
AttendanceCode ac = AttendanceCode.findById(
Integer.parseInt(filled_form.field("id").value()));
ac.edit(filled_form);
CachedPage.remove(CachedPage.ATTENDANCE_INDEX);
return redirect(routes.Attendance.viewCodes());
}
public static String formatTime(Time t) {
if (t != null) {
return new SimpleDateFormat("h:mm a").format(t);
} else {
return "
}
}
public static int getDaysPresent(List<AttendanceDay> days) {
int result = 0;
for (AttendanceDay day : days) {
if (day.code == null && day.start_time != null && day.end_time != null) {
result++;
}
}
return result;
}
public static double getTotalHours(List<AttendanceDay> days, AttendanceWeek week) {
double result = 0;
for (AttendanceDay day : days) {
if (day.code == null && day.start_time != null && day.end_time != null) {
result += day.getHours();
}
}
if (week != null) {
result += week.extra_hours;
}
return result;
}
public static double getAverageHours(List<AttendanceDay> days, AttendanceWeek week) {
int daysPresent = getDaysPresent(days);
if (daysPresent == 0) {
return 0;
}
return getTotalHours(days, week) / (double)daysPresent;
}
public static String format(double d) {
return String.format("%,.1f", d);
}
public static String formatAsPercent(double d) {
return String.format("%,.1f", d * 100) + "%";
}
}
|
package se.fnord.jamon;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
public class Node {
public static final int UNSET = -1;
private final List<Node> children = new ArrayList<Node>();
private final String value;
private Object attachment;
private int end;
private int start;
public Node(Object attachment) {
this.start = UNSET;
this.end = UNSET;
this.value = null;
this.attachment = attachment;
}
public Node() {
this.start = UNSET;
this.end = UNSET;
this.value = null;
}
public Node(String value, Object attachment) {
this.start = UNSET;
this.end = UNSET;
this.value = value;
this.attachment = attachment;
}
public Node(int start, int end, String value, Object attachment) {
this.start = start;
this.end = end;
this.value = value;
this.attachment = attachment;
}
public Node(int start, int end, Object attachment) {
this.start = start;
this.end = end;
this.value = null;
this.attachment = attachment;
}
public int start() {
return start;
}
void start(int start) {
this.start = start;
}
public int end() {
return end;
}
void end(int end) {
this.end = end;
}
void attachment(Object attachment) {
this.attachment = attachment;
}
Node addChildren(Node ... nodes) {
for (final Node node : nodes)
children.add(node);
return this;
}
Node addChildren(List<Node> nodes) {
children.addAll(nodes);
return this;
}
public List<Node> children() {
return Collections.unmodifiableList(children);
}
public Node firstChild() {
return children.get(0);
}
public String value() {
return value;
}
public Object attachment() {
return attachment;
}
@Override
public boolean equals(Object obj) {
return shallowEquals(obj) && Objects.equals(children, ((Node) obj).children);
}
public boolean shallowEquals(Object obj) {
if (!(obj instanceof Node))
return false;
final Node other = (Node) obj;
return (start == other.start) && (end == other.end) && Objects.equals(value, other.value) && Objects.equals(attachment, other.attachment);
}
@Override
public int hashCode() {
return (value == null ? 0 : value.hashCode()) + 31 * (attachment == null ? 0 : attachment.hashCode());
}
private static String toString(List<Node> nodes) {
if (nodes.isEmpty())
return "{}";
final StringBuilder sb = new StringBuilder();
final Iterator<Node> i = nodes.iterator();
final Node first = i.next();
sb.append("{").append(first.toString());
while (i.hasNext())
sb.append(", ").append(i.next().toString());
return sb.append("}").toString();
}
private static String toPrefixedString(String prefix, List<Node> nodes) {
if (nodes.isEmpty())
return "{}";
final StringBuilder sb = new StringBuilder();
final Iterator<Node> i = nodes.iterator();
final Node first = i.next();
sb.append("{\n").append(prefix).append(first.dump(prefix + " "));
while (i.hasNext())
sb.append(",\n").append(prefix).append(i.next().dump(prefix + " "));
return sb.append("}").toString();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder(String.format("N[(%d, %d)", start, end));
if (attachment != null)
sb.append(", attach=").append(attachment);
if (value != null)
sb.append(", val=\"").append(value).append("\"");
if (!children.isEmpty())
sb.append(", child=").append(toString(children));
return sb.append("]").toString();
}
private String dump(String prefix) {
StringBuilder sb = new StringBuilder("Node[");
if (attachment != null)
sb.append("attachment=").append(attachment);
if (attachment != null && value != null)
sb.append(", ");
if (value != null)
sb.append("value=\"").append(value).append("\"");
if ((value != null || attachment != null) && !children.isEmpty())
sb.append(", ");
if (!children.isEmpty())
sb.append("children=").append(toPrefixedString(prefix + " ", children));
return sb.append("]").toString();
}
public String dump() {
return dump("");
}
}
|
package net.codehobby;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.SocketTimeoutException;
import java.net.URL;
//import java.security.Security;
//import java.util.ArrayList;
import java.util.Arrays;
//import java.util.List;
import java.util.UUID;
//import java.util.logging.Level;
//import java.util.logging.Logger;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.HttpsURLConnection;
import java.security.MessageDigest;
public class PseudoRandomNumberGenerator
{
private byte[] initializationVector;
private BigInteger counter;
private byte[] key;
private byte[] cipherText;
private boolean iVSet, counterSet, encryptionKeySet;
private String keyFileName;
private String APIKey;
/**
* Default constructor. Sets the *Set boolean values to false so this object knows they haven't been set yet.
*/
public PseudoRandomNumberGenerator()
{
iVSet = false;
counterSet = false;
encryptionKeySet = false;
keyFileName = "APIKey.txt";
APIKey = "";
fetchAPIKeyFromFile();
getRandomDataFromWeb();
}
/**
* Constructor that sets the initial values.
* @param newInitializationVector The new InitializationVector.
* @param newCounter The new Counter.
* @param newKey The new Key.
*/
public PseudoRandomNumberGenerator( byte[] newInitializationVector, BigInteger newCounter, byte[] newKey )
{
iVSet = false;
counterSet = false;
encryptionKeySet = false;
keyFileName = "APIKey.txt";
APIKey = "";
setIV( newInitializationVector );
setCounter( newCounter.toByteArray() );
setEncryptionKey( newKey );
fetchAPIKeyFromFile();
}
/**
* Sets the Initialization Vector. The Initialization Vector will be used once at the beginning to
* help initialize the encryption process.
*
* @param newInitializationVector The value to assign to the Initialization Vector. The value should be 16 bytes (128 bits) long and ideally as random as possible.
*/
public void setIV( byte[] newInitializationVector )
{
if( newInitializationVector.length == 16 )
{//If the length is right, 16 bytes (128 bits), go ahead and save the value.
initializationVector = newInitializationVector;
iVSet = true;
}
else
{//If the lenght isn't right, throw an error.
throw new IllegalArgumentException( "The key argument needs to be 16 bytes (128 bits)." );
}
}
/**
* Sets the counter. The counter is incremented each time random info is generated and is
* xor-ed with either the Initialization Vector or the previous ciphertext to feed into the
* AES encryption process.
*
* @param newCounter The value to assign to the counter. The value should be 16 bytes (128 bits) long and ideally as random as possible.
*/
public void setCounter( byte[] newCounter )
{
if( newCounter.length == 16 )
{//If the length is right, 16 bytes (128 bits), go ahead and save the value.
counter = new BigInteger( newCounter );
counterSet = true;
}
else
{//If the lenght isn't right, throw an error.
throw new IllegalArgumentException( "The counter argument needs to be 16 bytes (128 bits)." );
}
}
/**
* Sets the encryption key for the AES encryption.
*
* @param newKey The value to assign to the key. The value should be 32 bytes (256 bits) long and ideally as random as possible.
*/
public void setEncryptionKey( byte[] newKey )
{
if( newKey.length == 32 )
{//If the length is right, 32 bytes (256 bits), go ahead and save the value.
key = newKey;
encryptionKeySet = true;
}
else
{//If the lenght isn't right, throw an error.
throw new IllegalArgumentException( "The key argument needs to be 32 bytes (256 bits)." );
}
}
/**
* Sets newKeyFileName to the filename the program will look to for the Random.org API key. The file should be a text file containing only the key.
* @param newKeyFileName The filename containing the key.
*/
public void setAPIKeyFileName( String newKeyFileName )
{
keyFileName = newKeyFileName;
}
/**
* Sets the Random.org API key to newKey.
* @param newKey The value of the Random.org API key.
*/
public void setAPIKey( String newKey )
{
APIKey = newKey;
}
public byte[] generate() throws Exception
{//Generate some pseudo-random bytes.
byte[] input;
if( !iVSet )
{//If iVSet is false, indicating the Initialization Vector isn't set, throw an exception.
throw new IllegalStateException( "The Initialization Vector isn't set." );
}
else if( !counterSet )
{//If counterSet is false, indicating the counter isn't set, throw an exception.
throw new IllegalStateException( "The counter isn't set." );
}
else if( !encryptionKeySet )
{//If encryptionKeySet false, indicating the key isn't set, throw an exception.
throw new IllegalStateException( "The key isn't set." );
}
if( cipherText == null )
{//If cipherText is empty, this is the first time the method has been run. Use the Initialization Vector.
input = counter.xor( new BigInteger(initializationVector) ).toByteArray();
}
else
{//cipherText isn't emtpy because this method has run before, so use cipherText.
input = counter.xor( new BigInteger(cipherText) ).toByteArray();
}
if( input.length%16 != 0 )
{//The block size needs to be a multpile of 16 bytes. If it's not, pad out input.
byte[] newInput = Arrays.copyOf( input, input.length + (16-input.length%16) );
input = newInput;
}
//Changing to a SHA hash instead of an AES encryption.
//MessageDigest md = MessageDigest.getInstance("SHA-256");
MessageDigest md = MessageDigest.getInstance("SHA-512");
md.update(input);
cipherText = md.digest();
/*
SecretKeySpec sKey = new SecretKeySpec( key, 0, 16, "AES" );
//Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, sKey);
//System.out.println( "Input length: " + input.length );
cipherText = cipher.doFinal(input, 0, input.length);
*/
//Set up for the next iteration
counter = counter.add( BigInteger.valueOf(1) );
return cipherText;
}
public BigInteger getPseudoRandomBigInteger() throws Exception
{
return new BigInteger( generate() );
}
public BigInteger getPseudoRandomBigIntegerRange( BigInteger low, BigInteger high ) throws Exception
{
return (new BigInteger(generate())).abs().mod(low).add(high);
}
public String getPseudoRandomHexString() throws Exception
{
return bytesToHex( generate() );
}
/**
* Returns a string representation of the value of the bites parameter in hex format.
*
* @param bites The binary data to format as a hex string.
* @return A string representation in hex format of the binary data in bites.
*/
public static String bytesToHex( byte[] bites )
{//Convert an array of bytes to a hex string for printing.
StringBuilder strBuilder = new StringBuilder();
for( byte bite : bites )
{//Go through each byte and append it to the string as a couple hex characters.
strBuilder.append( String.format("%02x", bite&0xff) );
}
return strBuilder.toString();
}
/**
* Interprets hexValue as a string of a hexadecimal number and returns an array of bytes equivalent to that number.
* @param hexValue A string with a hexadecimal number inside.
* @return An array of bytes corresponding to the value of the number in hexValue.
*/
public static byte[] hexToBytes( String hexValue )
{
//List<Byte> bites = new ArrayList<Byte>();
byte[] bites = new byte[hexValue.length()/2];
for( int i = 0; i < hexValue.length(); i+=2 )
{//Go through each 2 characters and add them as bytes to bites.
bites[i/2] = Byte.parseByte(hexValue.substring(i, i+1), 16);
}
return bites;
//return new BigInteger( hexValue, 16 ).toByteArray();
}
/**
* Gets some random data from the web and uses that data to set initializationVector, key and counter.
* Currently set to get data from Random.org's API.
*/
public void getRandomDataFromWeb()
{
//Get the API Key from the file APIKey.txt
int numBitsPerBlob = 128;//The number of bits to request per BLOB from Random.org.
int numBlobs = 4;//The number of BLOBs to request from Random.org.
//Uee the API key to get some random data from Random.org
//System.err.println( "The part to contact Random.org hasn't been finished yet.");
JsonObject jsonData = new JsonObject();
JsonObject jsonResponse = new JsonObject();
JsonObject params = new JsonObject();
//System.err.println( "Add a check to make sure it's not going over Random.org's request limit" );
//Create the JSON data to send to Random.org.
jsonData.addProperty( "jsonrpc", "2.0" );
jsonData.addProperty( "method", "generateBlobs" );
params.addProperty( "apiKey", APIKey );
params.addProperty( "n", numBlobs );
params.addProperty( "size", numBitsPerBlob );
params.addProperty( "format", "hex" );
jsonData.add( "params", params );
jsonData.addProperty( "id", UUID.randomUUID().toString() );
//System.out.println( jsonData.toString() );
try
{
if( fetchUsageFromWeb(numBitsPerBlob*numBlobs, APIKey) )
{//If the request is authorized by Random.org, go ahead and make it.
jsonResponse = fetchFromWeb( jsonData );
}
//Take the data from the response and put it in the initialization data.
//System.out.println( jsonResponse.toString() );
if( jsonResponse.has("error") )
{
System.err.println( "In getRandomDataFromWeb(), error number " + jsonResponse.getAsJsonObject("error").getAsJsonPrimitive("code").getAsString() + " was returned with message:" );
System.err.println( jsonResponse.getAsJsonObject("error").getAsJsonPrimitive("message").getAsString() );
}
else
{
JsonArray randomBlobs = jsonResponse.getAsJsonObject("result").getAsJsonObject("random").getAsJsonArray("data");
setIV( hexToBytes(randomBlobs.get(0).getAsString()) );//Assign the IV to the first blob.
setCounter( hexToBytes(randomBlobs.get(1).getAsString()) );//Assign the counter to the second blob.
setEncryptionKey( hexToBytes(randomBlobs.get(2).getAsString() + randomBlobs.get(3).getAsString()) );//Assign the key to the third and fourth blobs since it needs 256 bits.
/*
for( int i = 0; i < randomBlobs.size(); i++ )
{
System.out.println( randomBlobs.get(i).getAsString() );
}
*/
//System.err.println( "Add something to add the returned values to the initialization values.");
}
} catch( MalformedURLException ex ) {
System.err.println( "The URL was malformed." );
System.err.println( "Error Message: " + ex.getMessage() );
ex.printStackTrace();
setDefaultInitValues();
} catch( SocketTimeoutException e ) {
System.err.println( "The connection to Random.org timed out." );
System.err.println( "Error Message: " + e.getMessage() );
e.printStackTrace();
setDefaultInitValues();
} catch (ProtocolException ex) {
System.err.println( "The protocol (probably POST protocol) isn't supported." );
System.err.println( "Error Message: " + ex.getMessage() );
ex.printStackTrace();
setDefaultInitValues();
} catch (IOException ex) {
System.err.println( "Input/Output exception." );
System.err.println( "Error Message: " + ex.getMessage() );
ex.printStackTrace();
setDefaultInitValues();
} catch (Exception ex) {
System.err.println( "Exception: " + ex.getMessage() );
ex.printStackTrace();
setDefaultInitValues();
}
}
/**
* Gets the Random.org API key from the file pointed to by keyFileName.
*/
public void fetchAPIKeyFromFile()
{
fetchAPIKeyFromFile( keyFileName );
/*
try {
BufferedReader keyFileReader = new BufferedReader( new FileReader(keyFileName) );
APIKey = keyFileReader.readLine();
} catch (FileNotFoundException ex) {
System.err.println( keyFileName + " wasn't found." );
setDefaultInitValues();
} catch (IOException ex) {
System.err.println( "Error reading " + keyFileName );
setDefaultInitValues();
}
*/
}
/**
* Gets the Random.org API key from the file pointed to by tempKeyFileName. The file should be a text file with only the key in it.
* @param tempKeyFileName The filename of the file containing the Random.org API key.
*/
public void fetchAPIKeyFromFile( String tempKeyFileName )
{
BufferedReader keyFileReader = null;
try {
keyFileReader = new BufferedReader( new FileReader(tempKeyFileName) );
APIKey = keyFileReader.readLine();
} catch (FileNotFoundException ex) {
System.err.println( keyFileName + " wasn't found." );
setDefaultInitValues();
} catch (IOException ex) {
System.err.println( "Error reading " + keyFileName );
setDefaultInitValues();
}
finally
{
try {
keyFileReader.close();
} catch (IOException e)
{
System.err.println( "Error closing " + keyFileName );
e.printStackTrace();
} catch (Exception e)
{
System.err.println( "Error closing " + keyFileName );
e.printStackTrace();
}
}
}
/**
* Takes a request for Random.org as a JSON object, sends it to Random.org and returns the output as another JSON object.
* @param jsonRequest The request as a JSON object.
* @return The output from Random.org as a JSON object.
* @throws MalformedURLException
* @throws ProtocolException
* @throws IOException
* @throws Exception
*/
private JsonObject fetchFromWeb( JsonObject jsonRequest ) throws MalformedURLException, ProtocolException, IOException, Exception
{
String URLText = "https://api.random.org/json-rpc/1/invoke";
HttpsURLConnection connection = (HttpsURLConnection) new URL( URLText ).openConnection();//Open the connection.
connection.setConnectTimeout(5000);//Set the timeout to 5 seconds.
//Set the headers
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
//Send the request with the JSON and get the response
connection.setDoOutput( true );
DataOutputStream outputStream = new DataOutputStream( connection.getOutputStream() );
outputStream.writeBytes( jsonRequest.toString() );
outputStream.flush();
outputStream.close();
int responseCode = connection.getResponseCode();
if( responseCode == HttpsURLConnection.HTTP_OK )
{//If the response code is ok, get the json data returned by Random.org.
BufferedReader inputReader = new BufferedReader( new InputStreamReader(connection.getInputStream()) );//Establish the input reader.
String inputLine;
StringBuffer inputBuffer = new StringBuffer();
while( (inputLine = inputReader.readLine()) != null )
{//Take each line from the reader and append them to the buffer until there are no more lines from the reader.
inputBuffer.append( inputLine );
}
//Close the reader.
inputReader.close();
//Parse the buffer into a json object and return it.
return new JsonParser().parse( inputBuffer.toString() ).getAsJsonObject();
}
else
{
System.err.println( "Error " + responseCode + ": " + connection.getResponseMessage() );
throw new Exception( "Error " + responseCode + ": " + connection.getResponseMessage() );
}
}
/**
* Sets some default initialization values.
* Using this method isn't ideal since the values returned will be less random, but it's better than
* returning no pseudo-random values.
*/
private void setDefaultInitValues()
{
BigInteger newInitializationVector = new BigInteger( "1A024F91E8150033B974CD817BA67EB4", 16 );
BigInteger newCounter = new BigInteger( "7486667286DEEB44A3C7C89658C73B25", 16 );
BigInteger newKey = new BigInteger( "D373838825F7123B81E45C52EF8DA2BEB5582B44EC0231AD99EE598A894D08", 16 );
//BigInteger key = new BigInteger( "D373838825F7123B81E45C52EF8DA2BEB5582B44EC0231AD99EE598A894D0837", 16 );
setIV( newInitializationVector.toByteArray() );
setCounter( newCounter.toByteArray() );
setEncryptionKey( newKey.toByteArray() );
}
/**
* Checks the usage statistics from Random.org and returns whether it'll allow another request of initial values.
* @param numBits The number of bits that are planned to be requested from Random.org.
* @return True if Random.org should allow for the request, ,false if it shouldn't.
*/
private boolean fetchUsageFromWeb( int numBits, String APIKey ) throws IOException, ProtocolException, Exception
{
JsonObject jsonData = new JsonObject();
JsonObject jsonResponse = new JsonObject();
JsonObject params = new JsonObject();
//Create the JSON data to send to Random.org.
jsonData.addProperty( "jsonrpc", "2.0" );
jsonData.addProperty( "method", "getUsage" );
params.addProperty( "apiKey", APIKey );
jsonData.add( "params", params );
jsonData.addProperty( "id", UUID.randomUUID().toString() );
//System.out.println( jsonData.toString() );
jsonResponse = fetchFromWeb( jsonData );
//Take the data from the response and put it in the initialization data.
//System.out.println( jsonResponse.toString() );
if( jsonResponse.has("error") )
{
System.err.println( "In fetchUsageFromWeb(...), JSON Error number " + jsonResponse.getAsJsonObject("error").getAsJsonPrimitive("code").getAsString() + " was returned with message:" );
System.err.println( jsonResponse.getAsJsonObject("error").getAsJsonPrimitive("message").getAsString() );
throw new Exception( "JSON Error number " + jsonResponse.getAsJsonObject("error").getAsJsonPrimitive("code").getAsString() + " was returned with message:" + jsonResponse.getAsJsonObject("error").getAsJsonPrimitive("message").getAsString() );
}
else
{
String status = jsonResponse.getAsJsonObject("result").getAsJsonPrimitive("status").getAsString();
if( status.contentEquals("paused") )
{//If the API Key is paused by Random.org, return false.
System.err.println( "The API Key is paused." );
return false;
}
else
{
long requestsLeft = jsonResponse.getAsJsonObject("result").getAsJsonPrimitive("requestsLeft").getAsLong();
if( requestsLeft < 1 )
{//If there aren't any more requests left, return false.
System.err.println( "There are no requests left. The requestsLeft field returned by Random.org is " + requestsLeft );
return false;
}
else
{
long bitsLeft = jsonResponse.getAsJsonObject("result").getAsJsonPrimitive("requestsLeft").getAsLong();
if( bitsLeft < numBits )
{//If there aren't any more requests left, return false.
System.err.println( "There aren't enough bits left to request. Random.org says it'll only allow a request of up to " + bitsLeft + " bits.");
return false;
}
else
{//There is nothing blocking the request per Random.org. Return true.
return true;
}
}
}
}
}
/**
* Saves some pseudo-random data to a file either as hex or bytes.
* @param filename The filename of the file to save data to.
* @param numGroups The number of outputs of generate to save.
* @param asHex
* @throws Exception If an exception is generated during the generation of the pseudo-random data.
*/
public void savePseudoRandomDataToFile( String filename, long numGroups, boolean asHex ) throws Exception
{
DataOutputStream binaryOutput = null;
BufferedWriter textWriter = null;
try {
binaryOutput = new DataOutputStream( new FileOutputStream(filename, true) );//Create the file output stream. Will append to the file.
textWriter = new BufferedWriter( new FileWriter(filename, true) );
int i = 0;
while( i < numGroups )
{//Iterate until it gets to the number of groups as a parameter.
byte[] group = generate();//Generate the pseudo-random data
if( asHex )
{
textWriter.write( bytesToHex(group) + "\n" );//Write the random data as hex to the file.
}
else
{
//System.out.println( "Writing as binary." );
for( byte bite : group )
{
binaryOutput.writeByte(bite);
}
}
i++;
}
} catch (FileNotFoundException ex) {
System.err.println( "File not found error for file \"" + filename + "\": ");
System.err.println( ex.getMessage() );
ex.printStackTrace();
} catch (IOException ex) {
System.err.println( "IO Exception for file \"" + filename + "\": ");
System.err.println( ex.getMessage() );
ex.printStackTrace();
}
finally
{
//binaryOutput.close();//Close the file.
textWriter.close();//Close the file.
}
}
}
|
/**
* When a Bucket is created Simperium creates a Channel to sync changes between
* a Bucket and simperium.com.
*
* A Channel is provided with a Simperium App ID, a Bucket to operate on, a User
* who owns the bucket and a Channel.Listener that receives messages from the
* Channel.
*
* To get messages into a Channel, Channel.receiveMessage receives a Simperium
* websocket API message stripped of the channel ID prefix.
*
* TODO: instead of notifying the bucket about each individual item, there should be
* a single event for when there's a "re-index" or after performing all changes in a
* change operation.
*
*/
package com.simperium.client;
import com.simperium.util.JSONDiff;
import com.simperium.util.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EventObject;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Timer;
public class Channel implements Bucket.Channel {
public interface OnMessageListener {
void onMessage(MessageEvent event);
void onClose(Channel channel);
void onOpen(Channel channel);
}
public static final String TAG="Simperium.Channel";
// key names for init command json object
static public final String FIELD_CLIENT_ID = "clientid";
static public final String FIELD_API_VERSION = "api";
static public final String FIELD_AUTH_TOKEN = "token";
static public final String FIELD_APP_ID = "app_id";
static public final String FIELD_BUCKET_NAME = "name";
static public final String FIELD_COMMAND = "cmd";
static public final String FIELD_LIBRARY = "library";
static public final String FIELD_LIBRARY_VERSION = "version";
static public final String SIMPERIUM_API_VERSION = "1.1";
static public final String LIBRARY_NAME = "android";
static public final Integer LIBRARY_VERSION = 0;
// commands sent over the socket
public static final String COMMAND_INIT = "init"; // init:{INIT_PROPERTIES}
public static final String COMMAND_AUTH = "auth"; // received after an init: auth:expired or auth:email@example.com
public static final String COMMAND_INDEX = "i"; // i:1:MARK:?:LIMIT
public static final String COMMAND_CHANGE = "c";
public static final String COMMAND_VERSION = "cv";
public static final String COMMAND_ENTITY = "e";
static public final String COMMAND_INDEX_STATE = "index";
static final String RESPONSE_UNKNOWN = "?";
static final String EXPIRED_AUTH = "expired"; // after unsuccessful init:
static final String EXPIRED_AUTH_INDICATOR = "{";
static final String EXPIRED_AUTH_REASON_KEY = "msg";
static final String EXPIRED_AUTH_CODE_KEY = "code";
static final int EXPIRED_AUTH_INVALID_TOKEN_CODE = 401;
// Parameters for querying bucket
static final Integer INDEX_PAGE_SIZE = 50;
static final Integer INDEX_BATCH_SIZE = 10;
static final Integer INDEX_QUEUE_SIZE = 5;
// Constants for parsing command messages
static final Integer MESSAGE_PARTS = 2;
static final Integer COMMAND_PART = 0;
static final Integer PAYLOAD_PART = 1;
static final String COMMAND_FORMAT = "%s:%s";
// bucket determines which bucket we are using on this channel
private Bucket bucket;
// the object the receives the messages the channel emits
private OnMessageListener listener;
// track channel status
protected boolean started = false, connected = false, startOnConnect = false, idle = true;
private boolean haveIndex = false;
private CommandInvoker commands = new CommandInvoker();
private String appId, sessionId;
private Serializer serializer;
// for sending and receiving changes
final private ChangeProcessor changeProcessor;
private IndexProcessor indexProcessor;
public interface Serializer {
// public <T extends Syncable> void save(Bucket<T> bucket, SerializedQueue<T> data);
public SerializedQueue restore(Bucket bucket);
public void reset(Bucket bucket);
public void onQueueChange(Change change);
public void onDequeueChange(Change change);
public void onSendChange(Change change);
public void onAcknowledgeChange(Change change);
}
public static class SerializedQueue {
final public Map<String,Change> pending;
final public List<Change> queued;
public SerializedQueue(){
this(new HashMap<String, Change>(), new ArrayList<Change>());
}
public SerializedQueue(Map<String,Change> pendingChanges, List<Change> queuedChanges){
this.pending = pendingChanges;
this.queued = queuedChanges;
}
}
public Channel(String appId, String sessionId, final Bucket bucket, Serializer serializer, OnMessageListener listener){
this.serializer = serializer;
this.appId = appId;
this.sessionId = sessionId;
this.bucket = bucket;
this.listener = listener;
// Receive auth: command
command(COMMAND_AUTH, new Command(){
public void execute(String param){
User user = getUser();
// ignore auth:expired, implement new auth:{JSON} for failures
if(EXPIRED_AUTH.equals(param.trim())) return;
// if it starts with { let's see if it's error JSON
if (param.indexOf(EXPIRED_AUTH_INDICATOR) == 0) {
try {
JSONObject authResponse = new JSONObject(param);
int code = authResponse.getInt(EXPIRED_AUTH_CODE_KEY);
if (code == EXPIRED_AUTH_INVALID_TOKEN_CODE) {
user.setStatus(User.Status.NOT_AUTHORIZED);
stop();
return;
} else {
// TODO retry auth?
Logger.log(TAG, String.format("Unable to auth: %d", code));
return;
}
} catch (JSONException e) {
Logger.log(TAG, String.format("Unable to parse auth JSON, assume was email %s", param));
}
}
user.setEmail(param);
user.setStatus(User.Status.AUTHORIZED);
}
});
// Receive i: command
command(COMMAND_INDEX, new Command(){
@Override
public void execute(String param){
updateIndex(param);
}
});
// Receive c: command
command(COMMAND_CHANGE, new Command(){
@Override
public void execute(String param){
handleRemoteChanges(param);
}
});
// Receive e: command
command(COMMAND_ENTITY, new Command(){
@Override
public void execute(String param){
handleVersionResponse(param);
}
});
// Receive index command
command(COMMAND_INDEX_STATE, new Command() {
@Override
public void execute(String param){
sendIndexStatus();
}
});
// Receive cv:? command
command(COMMAND_VERSION, new Command() {
@Override
public void execute(String param) {
if (param.equals(RESPONSE_UNKNOWN)) {
Logger.log(TAG, "CV is out of date");
stopChangesAndRequestIndex();
}
}
});
changeProcessor = new ChangeProcessor();
}
public String toString(){
return String.format("%s<%s>", super.toString(), bucket.getName());
}
protected Ghost onAcknowledged(RemoteChange remoteChange, Change acknowledgedChange)
throws RemoteChangeInvalidException {
// if this isn't a removal, update the ghost for the relevant object
return bucket.acknowledgeChange(remoteChange, acknowledgedChange);
}
protected void onError(RemoteChange remoteChange, Change erroredChange){
Logger.log(TAG, String.format("Received error from service %s", remoteChange));
}
protected Ghost onRemote(RemoteChange remoteChange)
throws RemoteChangeInvalidException {
return bucket.applyRemoteChange(remoteChange);
}
@Override
public void reset(){
changeProcessor.reset();
}
private boolean hasChangeVersion(){
return bucket.hasChangeVersion();
}
private String getChangeVersion(){
return bucket.getChangeVersion();
}
private void getLatestVersions(){
// TODO: should local changes still be stored?
// abort any remote and local changes since we're getting new data
// and top the processor
changeProcessor.abort();
haveIndex = false;
// initialize the new query for new index data
IndexQuery query = new IndexQuery();
// send the i:::: messages
sendMessage(query.toString());
}
/**
* Diffs and object's local modifications and queues up the changes
*/
public Change queueLocalChange(Syncable object){
Change change = new Change(Change.OPERATION_MODIFY, object);
changeProcessor.addChange(change);
return change;
}
public Change queueLocalDeletion(Syncable object){
Change change = new Change(Change.OPERATION_REMOVE, object);
changeProcessor.addChange(change);
return change;
}
private static final String INDEX_CURRENT_VERSION_KEY = "current";
private static final String INDEX_VERSIONS_KEY = "index";
private static final String INDEX_MARK_KEY = "mark";
private void updateIndex(String indexJson){
// if we don't have an index processor, create a new one for the associated cv
// listen for when the index processor is done so we can start the changeprocessor again
// if we do have an index processor and the cv's match, add the page of items
// to the queue.
if (indexJson.equals(RESPONSE_UNKNOWN)) {
// noop, api 1.1 should not be sending ? here
return;
}
JSONObject index;
try {
index = new JSONObject(indexJson);
} catch (JSONException e) {
Logger.log(TAG, String.format("Index had invalid json: %s", indexJson));
return;
}
// if we don't have a processor or we are getting a different cv
if (indexProcessor == null || !indexProcessor.addIndexPage(index)) {
// make sure we're not processing changes and clear pending changes
// TODO: pause the change processor instead of clearing it :(
changeProcessor.reset();
// start a new index
String currentIndex;
try {
currentIndex = index.getString(INDEX_CURRENT_VERSION_KEY);
} catch(JSONException e){
// we have an empty index
currentIndex = "";
}
indexProcessor = new IndexProcessor(getBucket(), currentIndex, indexProcessorListener);
indexProcessor.start(index);
} else {
// received an index page for a different change version
// TODO: reconcile the out of band index cv
}
}
private IndexProcessorListener indexProcessorListener = new IndexProcessorListener(){
@Override
public void onComplete(String cv){
haveIndex = true;
}
};
private void handleRemoteChanges(String changesJson){
JSONArray changes;
if (changesJson.equals(RESPONSE_UNKNOWN)) {
// noop API 1.1 does not send "?" here
return;
}
try {
changes = new JSONArray(changesJson);
} catch (JSONException e){
Logger.log(TAG, "Failed to parse remote changes JSON", e);
return;
}
// Loop through each change? Convert changes to array list
changeProcessor.addChanges(changes);
}
private static final String ENTITY_DATA_KEY = "data";
private void handleVersionResponse(String versionData){
// versionData will be: key.version\n{"data":ENTITY}
// we need to parse out the key and version, parse the json payload and
// retrieve the data
if (indexProcessor == null || !indexProcessor.addObjectData(versionData)) {
Logger.log(TAG, String.format("Unkown Object for index: %s", versionData));
}
}
/**
* Stop sending changes and download a new index
*/
private void stopChangesAndRequestIndex() {
// top the change processor from listening for changes
changeProcessor.stop();
// get the latest index
getLatestVersions();
}
/**
* Send index status JSON
*/
private void sendIndexStatus() {
bucket.submit(new Runnable(){
@Override
public void run(){
int total = bucket.count();
JSONArray objectVersions = new JSONArray();
String idKey = "id";
String versionKey = "v";
Bucket.ObjectCursor objects = bucket.allObjects();
while(objects.moveToNext()) {
try {
JSONObject objectData = new JSONObject();
Syncable object = objects.getObject();
objectData.put(idKey, object.getSimperiumKey());
objectData.put(versionKey, object.getVersion());
objectVersions.put(objectData);
} catch (JSONException e) {
Logger.log(TAG, "Unable to add object version", e);
}
}
JSONObject index = new JSONObject();
try {
index.put("index", objectVersions);
index.put("current", getChangeVersion());
} catch (JSONException e) {
Logger.log(TAG, "Unable to build index response", e);
}
sendMessage(String.format("%s:%s", COMMAND_INDEX_STATE, index));
}
});
}
public Bucket getBucket(){
return bucket;
}
public User getUser(){
return bucket.getUser();
}
public String getSessionId(){
return sessionId;
}
public boolean isStarted(){
return started;
}
public boolean isConnected(){
return connected;
}
/**
* ChangeProcessor has no work to do
*/
public boolean isIdle(){
return idle;
}
/**
* Send Bucket's init message to start syncing changes.
*/
@Override
public void start(){
if (started) {
// we've already started
return;
}
// If socket isn't connected yet we have to wait until connection
// is up and try starting then
if (!connected) {
if (listener != null) listener.onOpen(this);
startOnConnect = true;
return;
}
if (!bucket.getUser().hasAccessToken()) {
// we won't connect unless we have an access token
return;
}
started = true;
Object initialCommand;
if (!hasChangeVersion()) {
// the bucket has never gotten an index
haveIndex = false;
initialCommand = new IndexQuery();
} else {
// retive changes since last cv
haveIndex = true;
initialCommand = String.format("%s:%s", COMMAND_VERSION, getChangeVersion());
}
// Build the required json object for initializing
HashMap<String,Object> init = new HashMap<String,Object>(6);
init.put(FIELD_API_VERSION, SIMPERIUM_API_VERSION);
init.put(FIELD_CLIENT_ID, sessionId);
init.put(FIELD_APP_ID, appId);
init.put(FIELD_AUTH_TOKEN, bucket.getUser().getAccessToken());
init.put(FIELD_BUCKET_NAME, bucket.getRemoteName());
init.put(FIELD_COMMAND, initialCommand.toString());
init.put(FIELD_LIBRARY_VERSION, LIBRARY_VERSION);
init.put(FIELD_LIBRARY, LIBRARY_NAME);
String initParams = new JSONObject(init).toString();
String message = String.format(COMMAND_FORMAT, COMMAND_INIT, initParams);
sendMessage(message);
}
/**
* Saves syncing state and tells listener to close
*/
@Override
public void stop(){
startOnConnect = false;
started = false;
changeProcessor.stop();
if (listener != null) {
listener.onClose(this);
}
}
// websocket
public void onConnect(){
connected = true;
Logger.log(TAG, String.format("onConnect autoStart? %b", startOnConnect));
if(startOnConnect) start();
}
public void onDisconnect(){
started = false;
connected = false;
changeProcessor.stop();
}
/**
* Receive a message from the WebSocketManager which already strips the channel
* prefix from the message.
*/
public void receiveMessage(String message){
// parse the message and react to it
String[] parts = message.split(":", MESSAGE_PARTS);
String command = parts[COMMAND_PART];
if (parts.length == 2) {
executeCommand(command, parts[1]);
} else if (parts.length == 1) {
executeCommand(command, "");
}
}
// send without the channel id, the socket manager should know which channel is writing
private void sendMessage(String message){
// send a message
if (listener != null) {
MessageEvent event = new MessageEvent(this, message);
listener.onMessage(event);
}
}
public static class MessageEvent extends EventObject {
public String message;
public MessageEvent(Channel source, String message){
super(source);
this.message = message;
}
public String getMessage(){
return message;
}
public String toString(){
return getMessage();
}
}
private void command(String name, Command command){
commands.add(name, command);
}
private void executeCommand(String name, String params){
commands.executeCommand(name, params);
}
/**
* Command and CommandInvoker provide a declaritive syntax for handling commands that come in
* from Channel.onMessage. Takes a message like "auth:user@example.com" and finds the correct
* command to run and stips the command from the message so the command can take care of
* processing the params.
*
* channel.command("auth", new Command(){
* public void onRun(String params){
* // params is now either an email address or "expired"
* }
* });
*/
private interface Command {
void execute(String params);
}
private class CommandInvoker {
private HashMap<String,Command> commands = new HashMap<String,Command>();
protected CommandInvoker add(String name, Command command){
commands.put(name, command);
return this;
}
protected void executeCommand(String name, String params){
if (commands.containsKey(name)) {
Command command = commands.get(name);
command.execute(params);
} else {
Logger.log(TAG, String.format("Unkown command received: %s", name));
}
}
}
static final String CURSOR_FORMAT = "%s::%s::%s";
static final String QUERY_DELIMITER = ":";
// static final Integer INDEX_MARK = 2;
// static final Integer INDEX_LIMIT = 5;
/**
* IndexQuery provides an interface for managing a query cursor and limit fields.
* TODO: add a way to build an IndexQuery from an index response
*/
private class IndexQuery {
private String mark = "";
private Integer limit = INDEX_PAGE_SIZE;
public IndexQuery(){};
public IndexQuery(String mark){
this(mark, INDEX_PAGE_SIZE);
}
public IndexQuery(Integer limit){
this.limit = limit;
}
public IndexQuery(String mark, Integer limit){
this.mark = mark;
this.limit = limit;
}
public String toString(){
String limitString = "";
if (limit > -1) {
limitString = limit.toString();
}
return String.format(CURSOR_FORMAT, COMMAND_INDEX, mark, limitString);
}
}
public static class ObjectVersion {
private String key;
private Integer version;
public ObjectVersion(String key, Integer version){
this.key = key;
this.version = version;
}
public String getKey(){
return key;
}
public Integer getVersion(){
return version;
}
public String toString(){
return String.format("%s.%d", key, version);
}
public static ObjectVersion parseString(String versionString)
throws java.text.ParseException {
int lastDot = versionString.lastIndexOf(".");
if (lastDot == -1) {
throw new java.text.ParseException(String.format("Missing version string: %s", versionString), versionString.length());
}
String key = versionString.substring(0, lastDot);
String version = versionString.substring(lastDot + 1);
return new ObjectVersion(key, Integer.parseInt(version));
}
}
private interface IndexProcessorListener {
void onComplete(String cv);
}
/**
* When index data is received it should queue up entities in the IndexProcessor.
* The IndexProcessor then receives the object data and on a seperate thread asks
* the StorageProvider to persist the object data. The storageProvider's operation
* should not block the websocket thread in any way.
*
* Build up a list of entities and versions we need for the index. Allow the
* channel to pass in the version data
*/
private class IndexProcessor {
public static final String INDEX_OBJECT_ID_KEY = "id";
public static final String INDEX_OBJECT_VERSION_KEY = "v";
final private String cv;
final private Bucket bucket;
private List<String> queue = Collections.synchronizedList(new ArrayList<String>());
private IndexQuery nextQuery;
private boolean complete = false;
final private IndexProcessorListener listener;
int indexedCount = 0;
public IndexProcessor(Bucket bucket, String cv, IndexProcessorListener listener){
this.bucket = bucket;
this.cv = cv;
this.listener = listener;
}
public Boolean addObjectData(String versionData){
String[] objectParts = versionData.split("\n");
String prefix = objectParts[0];
String payload = objectParts[1];
ObjectVersion objectVersion;
try {
objectVersion = ObjectVersion.parseString(prefix);
} catch (java.text.ParseException e) {
Logger.log(TAG, "Failed to add object data", e);
return false;
}
if (payload.equals(RESPONSE_UNKNOWN)) {
Logger.log(TAG, String.format("Object unkown to simperium: %s", objectVersion));
return false;
}
if (!queue.remove(objectVersion.toString())) {
return false;
}
JSONObject data = null;
try {
JSONObject payloadJSON = new JSONObject(payload);
data = payloadJSON.getJSONObject(ENTITY_DATA_KEY);
} catch (JSONException e) {
Logger.log(TAG, "Failed to parse object JSON", e);
return false;
}
// build the ghost and update
Ghost ghost = new Ghost(objectVersion.getKey(), objectVersion.getVersion(), data);
bucket.addObjectWithGhost(ghost);
indexedCount ++;
// for every 10 items, notify progress
if(indexedCount % 10 == 0) {
notifyProgress();
}
next();
return true;
}
public void start(JSONObject indexPage){
addIndexPage(indexPage);
}
public void next(){
// if queue isn't empty, pull it off the top and send request
if (!queue.isEmpty()) {
String versionString = queue.get(0);
ObjectVersion version;
try {
version = ObjectVersion.parseString(versionString);
} catch (java.text.ParseException e) {
Logger.log(TAG, "Failed to parse version string, skipping", e);
queue.remove(versionString);
next();
return;
}
if (!bucket.hasKeyVersion(version.getKey(), version.getVersion())) {
sendMessage(String.format("%s:%s", COMMAND_ENTITY, version.toString()));
} else {
Logger.log(TAG, String.format("Already have %s requesting next object", version));
queue.remove(versionString);
next();
return;
}
return;
}
// if index is empty and we have a next request, make the request
if (nextQuery != null){
sendMessage(nextQuery.toString());
return;
}
// no queue, no next query, all done!
complete = true;
notifyDone();
}
/**
* Add the page of data, but only if indexPage cv matches. Detects when it's the
* last page due to absence of cursor mark
*/
public Boolean addIndexPage(JSONObject indexPage){
String currentIndex;
try {
currentIndex = indexPage.getString(INDEX_CURRENT_VERSION_KEY);
} catch(JSONException e){
Logger.log(TAG, String.format("Index did not have current version %s", cv));
currentIndex = "";
}
if (!currentIndex.equals(cv)) {
return false;
}
JSONArray indexVersions;
try {
indexVersions = indexPage.getJSONArray(INDEX_VERSIONS_KEY);
} catch(JSONException e){
Logger.log(TAG, String.format("Index did not have entities: %s", indexPage));
return true;
}
if (indexVersions.length() > 0) {
// query for each item that we don't have locally in the bucket
for (int i=0; i<indexVersions.length(); i++) {
try {
JSONObject version = indexVersions.getJSONObject(i);
String key = version.getString(INDEX_OBJECT_ID_KEY);
Integer versionNumber = version.getInt(INDEX_OBJECT_VERSION_KEY);
ObjectVersion objectVersion = new ObjectVersion(key, versionNumber);
queue.add(objectVersion.toString());
// if (!bucket.hasKeyVersion(key, versionNumber)) {
// // we need to get the remote object
// index.add(objectVersion.toString());
// // sendMessage(String.format("%s:%s.%d", COMMAND_ENTITY, key, versionNumber));
} catch (JSONException e) {
Logger.log(TAG, String.format("Error processing index: %d", i), e);
}
}
}
String nextMark = null;
if (indexPage.has(INDEX_MARK_KEY)) {
try {
nextMark = indexPage.getString(INDEX_MARK_KEY);
} catch (JSONException e) {
nextMark = null;
}
}
if (nextMark != null && nextMark.length() > 0) {
nextQuery = new IndexQuery(nextMark);
// sendMessage(nextQuery.toString());
} else {
nextQuery = null;
}
next();
return true;
}
/**
* If the index is done processing
*/
public boolean isComplete(){
return complete;
}
private void notifyDone(){
bucket.indexComplete(cv);
listener.onComplete(cv);
}
private void notifyProgress(){
bucket.notifyOnNetworkChangeListeners(Bucket.ChangeType.INDEX);
}
}
public boolean haveCompleteIndex(){
return haveIndex;
}
/**
* ChangeProcessor should perform operations on a seperate thread as to not block the websocket
* ideally it will be a FIFO queue processor so as changes are brought in they can be appended.
* We also need a way to pause and clear the queue when we download a new index.
*/
private class ChangeProcessor implements Runnable, Change.OnRetryListener {
// public static final Integer CAPACITY = 200;
public static final long RETRY_DELAY_MS = 5000; // 5 seconds for retries?
private Thread thread;
private List<JSONObject> remoteQueue = Collections.synchronizedList(new ArrayList<JSONObject>(10));
private List<Change> localQueue = Collections.synchronizedList(new ArrayList<Change>());
private Map<String,Change> pendingChanges = Collections.synchronizedMap(new HashMap<String,Change>());
private Timer retryTimer;
private final Object lock = new Object();
public Object runLock = new Object();
public ChangeProcessor() {
restore();
}
/**
* If thread is running
*/
public boolean isRunning(){
return thread != null && thread.isAlive();
}
private void restore(){
synchronized(lock){
SerializedQueue serialized = serializer.restore(bucket);
localQueue.addAll(serialized.queued);
pendingChanges.putAll(serialized.pending);
resendPendingChanges();
}
}
public void addChanges(JSONArray changes) {
synchronized(lock){
int length = changes.length();
Logger.log(TAG, String.format("Add remote changes to processor %d", length));
for (int i = 0; i < length; i++) {
JSONObject change = changes.optJSONObject(i);
if (change != null) {
remoteQueue.add(change);
}
}
start();
}
}
public void addChange(JSONObject change) {
synchronized(lock){
remoteQueue.add(change);
}
start();
}
/**
* Local change to be queued
*/
public void addChange(Change change){
synchronized (lock){
// compress all changes for this same key
Iterator<Change> iterator = localQueue.iterator();
boolean isModify = change.isModifyOperation();
while(iterator.hasNext() && isModify){
Change queued = iterator.next();
if(queued.getKey().equals(change.getKey())){
serializer.onDequeueChange(queued);
iterator.remove();
}
}
serializer.onQueueChange(change);
localQueue.add(change);
}
start();
}
public void start(){
// channel must be started and have complete index
if (!started) {
return;
}
if (retryTimer == null) {
retryTimer = new Timer();
}
if (thread == null || thread.getState() == Thread.State.TERMINATED) {
thread = new Thread(this, String.format("simperium.processor.%s", getBucket().getName()));
thread.start();
} else {
// notify
synchronized(runLock){
runLock.notify();
}
}
}
public void stop(){
// interrupt the thread
if (this.thread != null) {
this.thread.interrupt();
synchronized(runLock){
runLock.notify();
}
}
}
protected void reset(){
pendingChanges.clear();
serializer.reset(bucket);
}
protected void abort(){
reset();
stop();
}
/**
* Check if we have changes we can send out
*/
protected boolean hasQueuedChanges(){
synchronized(lock){
Logger.log(TAG, String.format("Checking for queued changes %d", localQueue.size()));
// if we have have any remote changes to process we have work to do
if (!remoteQueue.isEmpty()) return true;
// if our local queue is empty we don't have work to do
if (localQueue.isEmpty()) return false;
// if we have queued changes, if there's no corresponding pending change then there's still work to do
Iterator<Change> changes = localQueue.iterator();
while(changes.hasNext()){
Change change = changes.next();
if (!pendingChanges.containsKey(change.getKey())) return true;
}
return false;
}
}
protected boolean hasPendingChanges(){
synchronized(lock){
return !pendingChanges.isEmpty() || !localQueue.isEmpty();
}
}
public void run(){
if(!haveCompleteIndex()) return;
idle = false;
Logger.log(TAG, String.format("%s - Starting change queue", Thread.currentThread().getName()));
while(true){
try {
processRemoteChanges();
processLocalChanges();
} catch (InterruptedException e) {
// shut down
break;
}
if(!hasQueuedChanges()){
// we've sent out every change that we can so far, if nothing is pending we can disconnect
if (pendingChanges.isEmpty()) {
idle = true;
}
synchronized(runLock){
try {
Logger.log(TAG, String.format("Waiting <%s> idle? %b", bucket.getName(), idle));
runLock.wait();
} catch (InterruptedException e) {
break;
}
Logger.log(TAG, "Waking change processor");
}
}
}
retryTimer.cancel();
retryTimer = null;
Logger.log(TAG, String.format("%s - Queue interrupted", Thread.currentThread().getName()));
}
private void processRemoteChanges()
throws InterruptedException {
synchronized(lock){
Logger.log(TAG, String.format("Processing remote changes %d", remoteQueue.size()));
// bail if thread is interrupted
while(remoteQueue.size() > 0){
if (Thread.interrupted()) {
throw new InterruptedException();
}
// take an item off the queue
RemoteChange remoteChange = null;
try {
remoteChange = RemoteChange.buildFromMap(remoteQueue.remove(0));
} catch (JSONException e) {
Logger.log(TAG, "Failed to build remote change", e);
continue;
}
Boolean acknowledged = false;
// synchronizing on pendingChanges since we're looking up and potentially
// removing an entry
Change change = null;
change = pendingChanges.get(remoteChange.getKey());
if (remoteChange.isAcknowledgedBy(change)) {
serializer.onAcknowledgeChange(change);
// change is no longer pending so remove it
pendingChanges.remove(change.getKey());
if (remoteChange.isError()) {
Logger.log(TAG, String.format("Change error response! %d %s", remoteChange.getErrorCode(), remoteChange.getKey()));
onError(remoteChange, change);
} else {
try {
Ghost ghost = onAcknowledged(remoteChange, change);
Change compressed = null;
Iterator<Change> queuedChanges = localQueue.iterator();
while(queuedChanges.hasNext()){
Change queuedChange = queuedChanges.next();
if (queuedChange.getKey().equals(change.getKey())) {
queuedChanges.remove();
if (!remoteChange.isRemoveOperation()) {
compressed = queuedChange.reapplyOrigin(ghost.getVersion(), ghost.getDiffableValue());
}
}
}
if (compressed != null) {
localQueue.add(compressed);
}
} catch (RemoteChangeInvalidException e){
Logger.log(TAG, "Remote change could not be acknowledged", e);
}
}
} else {
if (remoteChange.isError()){
Logger.log(TAG, String.format("Remote change %s was an error but not acknowledged", remoteChange));
} else {
try {
onRemote(remoteChange);
} catch (RemoteChangeInvalidException e) {
Logger.log(TAG, "Remote change could not be applied", e);
}
}
}
if (!remoteChange.isError() && remoteChange.isRemoveOperation()) {
Iterator<Change> iterator = localQueue.iterator();
while(iterator.hasNext()){
Change queuedChange = iterator.next();
if (queuedChange.getKey().equals(remoteChange.getKey())) {
iterator.remove();
}
}
}
}
}
}
public void processLocalChanges()
throws InterruptedException {
synchronized(lock){
if (localQueue.isEmpty()) {
return;
}
final List<Change> sendLater = new ArrayList<Change>();
// find the first local change whose key does not exist in the pendingChanges and there are no remote changes
while(!localQueue.isEmpty()){
if (Thread.interrupted()) {
localQueue.addAll(0, sendLater);
throw new InterruptedException();
}
// take the first change of the queue
Change localChange = localQueue.remove(0);
// check if there's a pending change with the same key
if (pendingChanges.containsKey(localChange.getKey())) {
// we have a change for this key that has not been acked
// so send it later
sendLater.add(localChange);
// let's get the next change
} else {
// send the change to simperium, if the change ends up being empty
// then we'll just skip it
if(sendChange(localChange)) {
// add the change to pending changes
pendingChanges.put(localChange.getKey(), localChange);
localChange.setOnRetryListener(this);
// starts up the timer
retryTimer.scheduleAtFixedRate(localChange.getRetryTimer(), RETRY_DELAY_MS, RETRY_DELAY_MS);
}
}
}
localQueue.addAll(0, sendLater);
}
}
private void resendPendingChanges(){
if (retryTimer == null) {
retryTimer = new Timer();
}
synchronized(lock){
// resend all pending changes
for (Map.Entry<String, Change> entry : pendingChanges.entrySet()) {
Change change = entry.getValue();
change.setOnRetryListener(this);
retryTimer.scheduleAtFixedRate(change.getRetryTimer(), RETRY_DELAY_MS, RETRY_DELAY_MS);
}
}
}
@Override
public void onRetry(Change change){
sendChange(change);
}
private Boolean sendChange(Change change) {
// send the change down the socket!
if (!connected) {
// channel is not initialized, send on reconnect
return true;
}
try {
JSONObject map = new JSONObject();
map.put(Change.ID_KEY, change.getKey());
map.put(Change.CHANGE_ID_KEY, change.getChangeId());
map.put(JSONDiff.DIFF_OPERATION_KEY, change.getOperation());
Integer version = change.getVersion();
if (version != null && version > 0) {
map.put(Change.SOURCE_VERSION_KEY, version);
}
if (change.requiresDiff()) {
JSONObject diff = change.getDiff(); // jsondiff.diff(change.getOrigin(), change.getTarget());
if (diff.length() == 0) {
Logger.log(TAG, String.format("Discarding empty change %s diff: %s", change.getChangeId(), diff));
change.setComplete();
return false;
}
map.put(JSONDiff.DIFF_VALUE_KEY, diff.get(JSONDiff.DIFF_VALUE_KEY));
}
// JSONObject changeJSON = Channel.serializeJSON(map);
sendMessage(String.format("c:%s", map.toString()));
serializer.onSendChange(change);
change.setSent();
return true;
} catch (JSONException e) {
android.util.Log.e(TAG, "Could not send change", e);
return false;
}
}
}
public static Map<String,Object> convertJSON(JSONObject json){
Map<String,Object> map = new HashMap<String,Object>(json.length());
Iterator keys = json.keys();
while(keys.hasNext()){
String key = (String)keys.next();
try {
Object val = json.get(key);
if (val.getClass().equals(JSONObject.class)) {
map.put(key, convertJSON((JSONObject) val));
} else if (val.getClass().equals(JSONArray.class)) {
map.put(key, convertJSON((JSONArray) val));
} else {
map.put(key, val);
}
} catch (JSONException e) {
Logger.log(TAG, String.format("Failed to convert JSON: %s", e.getMessage()), e);
}
}
return map;
}
public static List<Object> convertJSON(JSONArray json){
List<Object> list = new ArrayList<Object>(json.length());
for (int i=0; i<json.length(); i++) {
try {
Object val = json.get(i);
if (val.getClass().equals(JSONObject.class)) {
list.add(convertJSON((JSONObject) val));
} else if (val.getClass().equals(JSONArray.class)) {
list.add(convertJSON((JSONArray) val));
} else {
list.add(val);
}
} catch (JSONException e) {
Logger.log(TAG, String.format("Faile to convert JSON: %s", e.getMessage()), e);
}
}
return list;
}
public static JSONObject serializeJSON(Map<String,Object>map){
JSONObject json = new JSONObject();
Iterator<String> keys = map.keySet().iterator();
while(keys.hasNext()){
String key = keys.next();
Object val = map.get(key);
try {
if (val instanceof Map) {
json.put(key, serializeJSON((Map<String,Object>) val));
} else if(val instanceof List){
json.put(key, serializeJSON((List<Object>) val));
} else if(val instanceof Change){
json.put(key, serializeJSON(((Change) val).toJSONSerializable()));
} else {
json.put(key, val);
}
} catch(JSONException e){
Logger.log(TAG, String.format("Failed to serialize %s", val));
}
}
return json;
}
public static JSONArray serializeJSON(List<Object>list){
JSONArray json = new JSONArray();
Iterator<Object> vals = list.iterator();
while(vals.hasNext()){
Object val = vals.next();
if (val instanceof Map) {
json.put(serializeJSON((Map<String,Object>) val));
} else if(val instanceof List) {
json.put(serializeJSON((List<Object>) val));
} else if(val instanceof Change){
json.put(serializeJSON(((Change) val).toJSONSerializable()));
} else {
json.put(val);
}
}
return json;
}
}
|
package net.sf.taverna.t2.activities.dataflow.filemanager;
import java.util.Collection;
import net.sf.taverna.t2.activities.dataflow.DataflowActivity;
import net.sf.taverna.t2.workbench.file.FileManager;
import net.sf.taverna.t2.workflowmodel.Dataflow;
import net.sf.taverna.t2.workflowmodel.Processor;
import net.sf.taverna.t2.workflowmodel.utils.Tools;
/**
* A source description for a nested dataflow, opened from a
* {@link DataflowActivity} within an a {@link Processor} which is in the parent
* {@link Dataflow}.
*
* @author Stian Soiland-Reyes
*
*/
public class NestedDataflowSource {
private final DataflowActivity dataflowActivity;
private final Dataflow parentDataflow;
public NestedDataflowSource(Dataflow parentDataflow,
DataflowActivity dataflowActivity) {
this.parentDataflow = parentDataflow;
this.dataflowActivity = dataflowActivity;
}
public DataflowActivity getDataflowActivity() {
return dataflowActivity;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime
* result
+ ((dataflowActivity == null) ? 0 : dataflowActivity.hashCode());
result = prime * result
+ ((parentDataflow == null) ? 0 : parentDataflow.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final NestedDataflowSource other = (NestedDataflowSource) obj;
if (dataflowActivity == null) {
if (other.dataflowActivity != null)
return false;
} else if (!dataflowActivity.equals(other.dataflowActivity))
return false;
if (parentDataflow == null) {
if (other.parentDataflow != null)
return false;
} else if (!parentDataflow.equals(other.parentDataflow))
return false;
return true;
}
public Dataflow getParentDataflow() {
return parentDataflow;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
//sb.append("Nested workflow");
Collection<Processor> processors = Tools.getProcessorsWithActivity(getParentDataflow(),
getDataflowActivity());
if (! processors.isEmpty()) {
Processor processor = processors.iterator().next();
//sb.append(' ');
sb.append(processor.getLocalName());
sb.append(" in ");
// TODO: Is this safe? This might make a loop if a nested workflow has a parent
// in a nested workflow..
sb.append(FileManager.getInstance().getDataflowName(getParentDataflow()));
} else {
sb.append("Nested workflow");
}
return sb.toString();
}
}
|
package org.sitenv.service.ccda.smartscorecard.controller;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.io.IOUtils;
import org.jsoup.Jsoup;
import org.sitenv.ccdaparsing.model.CCDAXmlSnippet;
import org.sitenv.service.ccda.smartscorecard.cofiguration.ApplicationConfiguration;
import org.sitenv.service.ccda.smartscorecard.model.CCDAScoreCardRubrics;
import org.sitenv.service.ccda.smartscorecard.model.Category;
import org.sitenv.service.ccda.smartscorecard.model.ReferenceError;
import org.sitenv.service.ccda.smartscorecard.model.ReferenceResult;
import org.sitenv.service.ccda.smartscorecard.model.ReferenceTypes.ReferenceInstanceType;
import org.sitenv.service.ccda.smartscorecard.model.ResponseTO;
import org.sitenv.service.ccda.smartscorecard.model.Results;
import org.sitenv.service.ccda.smartscorecard.processor.ScorecardProcessor;
import org.sitenv.service.ccda.smartscorecard.util.ApplicationConstants;
import org.sitenv.service.ccda.smartscorecard.util.ApplicationUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.w3c.dom.Document;
import org.xhtmlrenderer.pdf.ITextRenderer;
import org.xml.sax.SAXException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lowagie.text.DocumentException;
@RestController
public class SaveReportController {
@Autowired
private ScorecardProcessor scorecardProcessor;
public static final String SAVE_REPORT_CHARSET_NAME = "UTF8";
private static final int CONFORMANCE_ERROR_INDEX = 0;
private static final int CERTIFICATION_FEEDBACK_INDEX = 1;
private static final boolean LOG_HTML = true;
/**
* Converts received JSON to a ResponseTO POJO (via method signature
* automagically), converts the ResponseTO to a cleaned (parsable) HTML
* report including relevant data, converts the HTML to a PDF report, and,
* finally, streams the data for consumption.
* This is intended to be called from a frontend which has already collected the JSON results.
*
* @param jsonReportData
* JSON which resembles ResponseTO
* @param response
* used to stream the PDF
*/
@RequestMapping(value = "/savescorecardservice", method = RequestMethod.POST)
public void savescorecardservice(@RequestBody ResponseTO jsonReportData,
HttpServletResponse response) {
convertHTMLToPDFAndStreamToOutput(
ensureLogicalParseTreeInHTML(convertReportToHTML(jsonReportData, SaveReportType.MATCH_UI)),
response);
}
/**
* A single service to handle a pure back-end implementation of the
* scorecard which streams back a PDF report.
* This does not require the completed JSON up-front, it creates it from the file sent.
*
* @param ccdaFile
* The C-CDA XML file intended to be scored
*/
@RequestMapping(value = "/savescorecardservicebackend", method = RequestMethod.POST)
public void savescorecardservicebackend(
@RequestParam("ccdaFile") MultipartFile ccdaFile,
HttpServletResponse response) {
handlePureBackendCall(ccdaFile, response, SaveReportType.MATCH_UI, scorecardProcessor);
}
/**
* A single service to handle a pure back-end implementation of the
* scorecard which streams back a PDF report.
* This does not require the completed JSON up-front, it creates it from the file sent.
* This differs from the savescorecardservicebackend in that it has its own specific format of the results
* (dynamic and static table with 'call outs', no filename, more overview type content, etc.)
* and is intended to be used when a Direct Message is received with a C-CDA document.
*
* @param ccdaFile
* The C-CDA XML file intended to be scored
* @param sender
* The email address of the sender to be logged in the report
*/
@RequestMapping(value = "/savescorecardservicebackendsummary", method = RequestMethod.POST)
public void savescorecardservicebackendsummary(
@RequestParam("ccdaFile") MultipartFile ccdaFile, @RequestParam("sender") String sender,
HttpServletResponse response) {
if(ApplicationUtil.isEmpty(sender)) {
sender = "Unknown Sender";
}
handlePureBackendCall(ccdaFile, response, SaveReportType.SUMMARY, scorecardProcessor, sender);
}
private static void handlePureBackendCall(MultipartFile ccdaFile, HttpServletResponse response, SaveReportType reportType,
ScorecardProcessor scorecardProcessor) {
handlePureBackendCall(ccdaFile, response, reportType, scorecardProcessor, null);
}
private static void handlePureBackendCall(MultipartFile ccdaFile, HttpServletResponse response, SaveReportType reportType,
ScorecardProcessor scorecardProcessor, String sender) {
// ResponseTO pojoResponse = callCcdascorecardserviceExternally(ccdaFile);
ResponseTO pojoResponse = callCcdascorecardserviceInternally(ccdaFile, scorecardProcessor);
if (pojoResponse == null) {
pojoResponse = new ResponseTO();
pojoResponse.setResults(null);
pojoResponse.setSuccess(false);
pojoResponse
.setErrorMessage(ApplicationConstants.ErrorMessages.NULL_RESULT_ON_SAVESCORECARDSERVICEBACKEND_CALL);
} else {
if (!ApplicationUtil.isEmpty(ccdaFile.getOriginalFilename())
&& ccdaFile.getOriginalFilename().contains(".")) {
pojoResponse.setFilename(ccdaFile.getOriginalFilename());
} else if (!ApplicationUtil.isEmpty(ccdaFile.getName())
&& ccdaFile.getName().contains(".")) {
pojoResponse.setFilename(ccdaFile.getName());
}
if(ApplicationUtil.isEmpty(pojoResponse.getFilename())) {
pojoResponse.setFilename("Unknown");
}
// otherwise it uses the name given by ccdascorecardservice
}
if(reportType == SaveReportType.SUMMARY) {
pojoResponse.setFilename(sender);
}
convertHTMLToPDFAndStreamToOutput(
ensureLogicalParseTreeInHTML(convertReportToHTML(pojoResponse, reportType)),
response);
};
protected static ResponseTO callCcdascorecardserviceInternally(MultipartFile ccdaFile,
ScorecardProcessor scorecardProcessor) {
return scorecardProcessor.processCCDAFile(ccdaFile, true);
}
public static ResponseTO callCcdascorecardserviceExternally(MultipartFile ccdaFile) {
String endpoint = ApplicationConfiguration.CCDASCORECARDSERVICE_URL;
return callServiceExternally(endpoint, ccdaFile, null);
}
public static ResponseTO callSavescorecardservicebackendExternally(MultipartFile ccdaFile) {
String endpoint = ApplicationConfiguration.SAVESCORECARDSERVICEBACKEND_URL;
return callServiceExternally(endpoint, ccdaFile, null);
}
public static ResponseTO callSavescorecardservicebackendsummaryExternally(MultipartFile ccdaFile, String senderValue) {
String endpoint = ApplicationConfiguration.SAVESCORECARDSERVICEBACKENDSUMMARY_URL;
return callServiceExternally(endpoint, ccdaFile, senderValue);
}
private static ResponseTO callServiceExternally(String endpoint, MultipartFile ccdaFile, String senderValue) {
ResponseTO pojoResponse = null;
LinkedMultiValueMap<String, Object> requestMap = new LinkedMultiValueMap<>();
FileOutputStream out = null;
File tempFile = null;
try {
final String tempCcdaFileName = "ccdaFile";
tempFile = File.createTempFile(tempCcdaFileName, "xml");
out = new FileOutputStream(tempFile);
IOUtils.copy(ccdaFile.getInputStream(), out);
requestMap.add(tempCcdaFileName, new FileSystemResource(tempFile));
if(senderValue != null) {
String senderKey = "sender";
requestMap.add(senderKey, senderValue);
}
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new HttpEntity<>(
requestMap, headers);
FormHttpMessageConverter formConverter = new FormHttpMessageConverter();
formConverter.setCharset(Charset.forName(SAVE_REPORT_CHARSET_NAME));
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(formConverter);
restTemplate.getMessageConverters().add(
new MappingJackson2HttpMessageConverter());
pojoResponse = restTemplate.postForObject(endpoint, requestEntity, ResponseTO.class);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.flush();
out.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
if (tempFile != null && tempFile.isFile()) {
tempFile.delete();
}
}
return pojoResponse;
}
/**
* Parses (POJO ResponseTO converted) JSON and builds the results into an
* HTML report
*
* @param report
* the ResponseTO report intended to be converted to HTML
* @return the converted HTML report as a String
*/
protected static String convertReportToHTML(ResponseTO report, SaveReportType reportType) {
StringBuffer sb = new StringBuffer();
appendOpeningHtml(sb);
if (report == null) {
report = new ResponseTO();
report.setResults(null);
report.setSuccess(false);
report.setErrorMessage(ApplicationConstants.ErrorMessages.GENERIC_WITH_CONTACT);
appendErrorMessageFromReport(sb, report,
ApplicationConstants.ErrorMessages.RESULTS_ARE_NULL);
} else {
// report != null
if (report.getResults() != null) {
if (report.isSuccess()) {
Results results = report.getResults();
List<Category> categories = results.getCategoryList();
List<ReferenceResult> referenceResults = report
.getReferenceResults();
appendHeader(sb, report, results, reportType);
appendHorizontalRuleWithBreaks(sb);
if(reportType == SaveReportType.SUMMARY) {
appendPreTopLevelResultsContent(sb);
}
appendTopLevelResults(sb, results, categories,
referenceResults, reportType, report.getCcdaDocumentType());
if(reportType == SaveReportType.MATCH_UI) {
appendHorizontalRuleWithBreaks(sb);
appendHeatmap(sb, results, categories,
referenceResults);
}
sb.append("<br />");
appendHorizontalRuleWithBreaks(sb);
if(reportType == SaveReportType.MATCH_UI) {
if(!ApplicationUtil.isEmpty(report.getReferenceResults()) || results.getNumberOfIssues() > 0) {
appendDetailedResults(sb, categories, referenceResults);
}
}
if(reportType == SaveReportType.SUMMARY) {
/*
appendPictorialGuide(sb, categories, referenceResults);
appendPictorialGuideKey(sb);
*/
}
}
} else {
// report.getResults() == null
if (!report.isSuccess()) {
appendErrorMessageFromReport(sb, report,
ApplicationConstants.ErrorMessages.IS_SUCCESS_FALSE);
} else {
appendErrorMessageFromReport(sb, report);
}
}
}
appendClosingHtml(sb);
return sb.toString();
}
private static void appendOpeningHtml(StringBuffer sb) {
sb.append("<!DOCTYPE html>");
sb.append("<html>");
sb.append("<head>");
sb.append("<title>SITE C-CDA Scorecard Report</title>");
appendStyleSheet(sb);
sb.append("</head>");
sb.append("<body style='font-family: \"Helvetica Neue\",Helvetica,Arial,sans-serif;'>");
}
private static void appendStyleSheet(StringBuffer sb) {
sb.append("<style>" +
" .site-header { background: url('https://sitenv.org/assets/images/site/bg-header-1920x170.png') repeat-x center top #1fdbfe; } " +
" .site-logo { text-decoration: none; } " +
" table { font-family: arial, sans-serif; border-collapse: separate; width: 100%; } " +
" td, th { border: 1px solid #dddddd; text-align: left; padding: 8px; } " +
" #dynamicTable tr:nth-child(even) { background-color: #dddddd; } " +
" #staticTable { font-size: 11px; } " +
" .popOuts { font-size: 11px; background-color: ghostwhite !important; } " +
" .removeBorder { border: none; background-color: white; } " +
" #notScoredRowPopOutLink { border-top: 6px double MAGENTA; border-bottom: none; border-left: none; border-right: none; } " +
" #perfectRowPopOutLink { border-top: 6px double MEDIUMPURPLE; border-bottom: none; border-left: none; border-right: none; } " +
" #gradePopOutLink { border-left: 6px solid MEDIUMSEAGREEN; border-right: none; border-bottom: none; border-top: none; } " +
" #issuePopOutLink { border-left: 6px double orange; border-right: none; border-bottom: none; border-top: none; } " +
" #errorPopOutLink { border-right: none; border-left: 6px solid red; border-bottom: none; border-top: none; } " +
" #feedbackPopOutLink { border-right: none; border-left: 6px double DEEPSKYBLUE; border-bottom: none; border-top: none; } " +
" #notScoredRowPopOut { border: 6px double MAGENTA; border-radius: 0px 25px 25px 25px; } " +
" #perfectRowPopOut { border: 6px double MEDIUMPURPLE; border-radius: 25px 0px 25px 25px; } " +
" #gradePopOut { border: 6px solid MEDIUMSEAGREEN; border-radius: 25px 25px 25px 25px; } " +
" #issuePopOut { border: 6px double orange; border-radius: 25px 25px 25px 0px; } " +
" #errorPopOut { border: 6px solid red; border-radius: 25px 25px 25px 0px; } " +
" #feedbackPopOut { border: 6px double DEEPSKYBLUE; border-radius: 25px 25px 25px 0px; } " +
" #perfectRowLeftHeader { border-left: 6px double MEDIUMPURPLE; border-top: 6px double MEDIUMPURPLE; border-bottom: 6px double MEDIUMPURPLE; } " +
" #perfectRowRightHeader { border-right: 6px double MEDIUMPURPLE; border-top: 6px double MEDIUMPURPLE; border-bottom: 6px double MEDIUMPURPLE; } " +
" .perfectRowMiddleHeader { border-top: 6px double MEDIUMPURPLE; border-bottom: 6px double MEDIUMPURPLE; } " +
" #notScoredRowLeftHeader { border-left: 6px double MAGENTA; border-top: 6px double MAGENTA; border-bottom: 6px double MAGENTA; } " +
" #notScoredRowRightHeader { border-right: 6px double MAGENTA; border-top: 6px double MAGENTA; border-bottom: 6px double MAGENTA; } " +
" .notScoredRowMiddleHeader { border-top: 6px double MAGENTA; border-bottom: 6px double MAGENTA; } " +
" #gradeHeader { border: 6px solid MEDIUMSEAGREEN; } " +
" #issueHeader { border: 6px double orange; } " +
" #errorHeader { border: 6px solid red; } " +
" #feedbackHeader { border: 6px double DEEPSKYBLUE; } " +
" #keyGradeHeader { color: MEDIUMSEAGREEN; font-weight: bold; } " +
" #keyIssueHeader { color: orange; font-weight: bold; } " +
" #keyErrorHeader { color: red; font-weight: bold; } " +
" #keyFeedbackHeader { color: DEEPSKYBLUE; font-weight: bold; } " +
" </style> ");
}
private static void appendHeader(StringBuffer sb, ResponseTO report,
Results results, SaveReportType reportType) {
sb.append("<header id='topOfScorecard'>");
sb.append("<center>");
sb.append("<div class=\"site-header\">")
.append(" <a class=\"site-logo\" href=\"https:
.append(" rel=\"external\" title=\"HealthIT.gov\"> <img alt=\"HealthIT.gov\"")
.append(" src=\"https://sitenv.org/assets/images/site/healthit.gov.logo.png\" width='40%'>")
.append(" </a>")
.append("</div>");
sb.append("<br />");
appendHorizontalRuleWithBreaks(sb);
sb.append("<h1>" + "C-CDA ");
if(reportType == SaveReportType.SUMMARY) {
sb.append("Scorecard For "
+ (report.getCcdaDocumentType() != null ? report
.getCcdaDocumentType() : "document") + "</h1>");
sb.append("<h5>");
sb.append("<span style='float: left'>" + "Submitted By: "
+ (!ApplicationUtil.isEmpty(report.getFilename()) ? report.getFilename() : "Unknown")
+ "</span>");
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
sb.append("<span style='float: right'>" + "Submission Time: " + dateFormat.format(new Date()) + "</span>");
sb.append("</h5>");
sb.append("<div style='clear: both'></div>");
appendBasicResults(sb, results);
} else {
sb.append(results.getDocType() + " "
+ (report.getCcdaDocumentType() != null ? report .getCcdaDocumentType() : "document")
+ " Scorecard For:" + "</h1>");
sb.append("<h2>" + report.getFilename() + "</h2>");
}
sb.append("</center>");
sb.append("</header>");
}
private static void appendPreTopLevelResultsContent(StringBuffer sb) {
sb.append("<p>If you are not satisfied with your results:</p>");
sb.append("<ul>");
sb.append("<li>");
sb.append("Please ask your vendor to de-identify your C-CDA document and submit it to the SITE C-CDA Scorecard tool "
+ "located at " + "<a href=\"https:
sb.append("</li>");
sb.append("<li>");
sb.append("Using the results provided by the online tool, "
+ "your vendor can update or provide insight on how to update your document to meet the latest HL7 best-practices");
sb.append("</li>");
sb.append("<li>");
sb.append("Once updated, "
+ "resubmitting your document to the ONC One Click Scorecard will produce a report with a higher score "
+ "and/or less or no conformance errors or less or no certification feedback results");
sb.append("</li>");
sb.append("</ul>");
sb.append("<p>")
.append("This page contains a summary of the C-CDA Scorecard results highlighting the overall document grade "
+ "which is derived from a quantitative score out of a maximum of 100. ")
.append("</p>");
sb.append("<p>")
.append("The second and final page identifies areas for improvement organized by clinical domains.")
.append("</p>");
}
private static void appendBasicResults(StringBuffer sb, Results results) {
sb.append("<center>");
sb.append("<h2>");
sb.append("<span style=\"margin-right: 40px\">Grade: " + results.getFinalGrade() + "</span>");
sb.append("<span style=\"margin-left: 40px\">Score: " + results.getFinalNumericalGrade() + "/100" + "</span>");
sb.append("</h2>");
sb.append("</center>");
}
private static void appendTopLevelResults(StringBuffer sb, Results results,
List<Category> categories, List<ReferenceResult> referenceResults, SaveReportType reportType, String ccdaDocumentType) {
boolean isReferenceResultsEmpty = ApplicationUtil.isEmpty(referenceResults);
int conformanceErrorCount = isReferenceResultsEmpty ? 0 : referenceResults.get(CONFORMANCE_ERROR_INDEX).getTotalErrorCount();
int certificationFeedbackCount = isReferenceResultsEmpty ? 0 : referenceResults.get(CERTIFICATION_FEEDBACK_INDEX).getTotalErrorCount();
if(reportType == SaveReportType.SUMMARY) {
//brief summary of overall document results (without scorecard issues count listed)
sb.append("<h3>Summary</h3>");
sb.append("<p>"
+ "Your " + ccdaDocumentType + " document received a grade of <b>" + results.getFinalGrade() + "</b>"
+ " compared to an industry average of " + "<b>" + results.getIndustryAverageGrade() + "</b>" + ". "
+ "The document scored " + "<b>" + results.getFinalNumericalGrade() + "/100" + "</b>"
+ " and is "
+ (conformanceErrorCount > 0 ? "non-compliant" : "compliant")
+ " with the HL7 C-CDA IG"
+ " and is "
+ (certificationFeedbackCount > 0 ? "non-compliant" : "compliant")
+ " with 2015 Edition Certification requirements. "
+ "The detailed results organized by clinical domains are provided in the table below:"
+ "</p>");
//dynamic table
appendHorizontalRuleWithBreaks(sb);
sb.append("<br /><br />");
sb.append("<h2>Scorecard Results by Clinical Domain</h2>");
appendDynamicTopLevelResultsTable(sb, results, categories, referenceResults);
} else {
sb.append("<h3>Scorecard Grade: " + results.getFinalGrade() + "</h3>");
sb.append("<ul><li>");
sb.append("<p>Your document scored a " + "<b>"
+ results.getFinalGrade() + "</b>"
+ " compared to an industry average of " + "<b>"
+ results.getIndustryAverageGrade() + "</b>" + ".</p>");
sb.append("</ul></li>");
sb.append("<h3>Scorecard Score: " + results.getFinalNumericalGrade()
+ "</h3>");
sb.append("<ul><li>");
sb.append("<p>Your document scored " + "<b>"
+ +results.getFinalNumericalGrade() + "</b>" + " out of "
+ "<b>" + " 100 " + "</b>" + " total possible points.</p>");
sb.append("</ul></li>");
boolean isSingular = results.getNumberOfIssues() == 1;
appendSummaryRow(sb, results.getNumberOfIssues(), "Scorecard Issues",
null, isSingular ? "Scorecard Issue" : "Scorecard Issues",
isSingular);
sb.append("</ul></li>");
String messageSuffix = null;
if (isReferenceResultsEmpty) {
for (ReferenceInstanceType refType : ReferenceInstanceType.values()) {
if (refType == ReferenceInstanceType.CERTIFICATION_2015) {
messageSuffix = "results";
}
appendSummaryRow(sb, 0, refType.getTypePrettyName(),
messageSuffix, refType.getTypePrettyName(), false, reportType);
sb.append("</ul></li>");
}
} else {
for (ReferenceResult refResult : referenceResults) {
int refErrorCount = refResult.getTotalErrorCount();
isSingular = refErrorCount == 1;
String refTypeName = refResult.getType().getTypePrettyName();
String messageSubject = "";
if (refResult.getType() == ReferenceInstanceType.IG_CONFORMANCE) {
messageSubject = isSingular ? refTypeName.substring(0,
refTypeName.length() - 1) : refTypeName;
} else if (refResult.getType() == ReferenceInstanceType.CERTIFICATION_2015) {
messageSuffix = isSingular ? "result" : "results";
messageSubject = refTypeName;
}
appendSummaryRow(sb, refErrorCount, refTypeName, messageSuffix,
messageSubject, isSingular, reportType);
sb.append("</ul></li>");
}
}
}
}
private static int getFailingSectionSpecificErrorCount(String categoryName,
ReferenceInstanceType refType, List<ReferenceResult> referenceResults) {
if (!ApplicationUtil.isEmpty(referenceResults)) {
if (refType == ReferenceInstanceType.IG_CONFORMANCE) {
List<ReferenceError> igErrors =
referenceResults.get(CONFORMANCE_ERROR_INDEX).getReferenceErrors();
if (!ApplicationUtil.isEmpty(igErrors)) {
return getFailingSectionSpecificErrorCountProcessor(categoryName, igErrors);
}
} else if (refType == ReferenceInstanceType.CERTIFICATION_2015) {
List<ReferenceError> certErrors =
referenceResults.get(CERTIFICATION_FEEDBACK_INDEX).getReferenceErrors();
if (!ApplicationUtil.isEmpty(certErrors)) {
return getFailingSectionSpecificErrorCountProcessor(categoryName, certErrors);
}
}
}
return 0;
}
private static int getFailingSectionSpecificErrorCountProcessor(
String categoryName, List<ReferenceError> errors) {
int count = 0;
for (int i = 0; i < errors.size(); i++) {
String currentSectionInReferenceErrors = errors.get(i).getSectionName();
if (!ApplicationUtil.isEmpty(currentSectionInReferenceErrors)) {
if (currentSectionInReferenceErrors.equalsIgnoreCase(categoryName)) {
count++;
}
}
}
return count;
}
private static void appendDynamicTopLevelResultsTable(StringBuffer sb, Results results,
List<Category> categories, List<ReferenceResult> referenceResults) {
sb.append("<table id='dynamicTable'>");
sb.append(" <tbody>");
sb.append(" <tr class=\"popOuts\">");
sb.append(" <td id=\"gradePopOut\" colspan=\"2\">");
sb.append(" The Scorecard grade is a quantitative assessment of the data quality of the submitted document. "
+ "A higher grade indicates that HL7 best practices for C-CDA implementation are being followed by the organization and "
+ "has higher probability of being interoperable with other organizations.");
sb.append(" </td>");
sb.append(" <td id=\"issuePopOut\">");
sb.append(" A Scorecard Issue identifies data within the document which can be represented in a better way using "
+ "HL7 best practices for C-CDA. This column should have numbers as close to zero as possible.");
sb.append(" </td>");
sb.append(" <td id=\"errorPopOut\">");
sb.append(" A Conformance Error implies that the document is non-compliant with the HL7 C-CDA IG requirements. "
+ "This column should have zeros ideally. Providers should work with their health IT vendor to rectify the errors.");
sb.append(" </td>");
sb.append(" <td id=\"feedbackPopOut\">");
sb.append(" A Certification Feedback result identifies areas where the generated documents are not compliant with "
+ "the requirements of 2015 Edition Certification. Ideally, this column should have all zeros.");
sb.append(" </td>");
sb.append(" </tr>");
sb.append(" <tr>");
sb.append(" <td class=\"removeBorder\"></td>");
sb.append(" <td class=\"removeBorder\" id=\"gradePopOutLink\"></td>");
sb.append(" <td class=\"removeBorder\" id=\"issuePopOutLink\"></td>");
sb.append(" <td class=\"removeBorder\" id=\"errorPopOutLink\"></td>");
sb.append(" <td class=\"removeBorder\" id=\"feedbackPopOutLink\"></td>");
sb.append(" </tr> ");
sb.append(" <tr style=\"background-color: ghostwhite\">");
sb.append(" <th>Clinical Domain</th> ");
sb.append(" <th id=\"gradeHeader\">Scorecard Grade</th> ");
sb.append(" <th id=\"issueHeader\">Scorecard Issues</th> ");
sb.append(" <th id=\"errorHeader\">Conformance Errors</th> ");
sb.append(" <th id=\"feedbackHeader\">Certification Feedback</th> ");
sb.append(" </tr> ");
for(Category category : getSortedCategories(categories)) {
// if(category.getNumberOfIssues() > 0 || referenceResults.get(ReferenceInstanceType.IG/CERT).getTotalErrorCount() > 0) {
// if(category.getNumberOfIssues() > 0 || category.isFailingConformance() || category.isCertificationFeedback()) {
sb.append(" <tr>")
.append(" <td>" + (category.getCategoryName() != null ? category.getCategoryName() : "Unknown") + "</td>")
.append(" <td>" + (category.getCategoryGrade() != null ? category.getCategoryGrade() : "N/A") + "</td>")
.append(" <td>" + (category.isFailingConformance() || category.isCertificationFeedback() || category.isNullFlavorNI()
? "N/A"
: category.getNumberOfIssues())
+ "</td>")
.append(" <td>"
+ (!ApplicationUtil.isEmpty(category.getCategoryName())
? getFailingSectionSpecificErrorCount(category.getCategoryName(), ReferenceInstanceType.IG_CONFORMANCE, referenceResults)
: "N/A")
+ "</td>")
.append(" <td>"
+ (!ApplicationUtil.isEmpty(category.getCategoryName())
? getFailingSectionSpecificErrorCount(category.getCategoryName(), ReferenceInstanceType.CERTIFICATION_2015, referenceResults)
: "N/A")
+ "</td>")
.append(" </tr>");
}
sb.append(" <tbody>");
sb.append("</table>");
}
/**
* Order from best to worst:<br/>
* 1. Numerical score high to low 2. Empty/null 3. Certification Feedback 4. Conformance Error
* @param categories - Category List to sort
* @return sorted categories
*/
private static List<Category> getSortedCategories(List<Category> categories) {
List<Category> sortedCategories = new ArrayList<Category>(categories);
//prepare for sort of non-scored items
for(Category category : sortedCategories) {
if(category.isFailingConformance()) {
category.setCategoryNumericalScore(-3);
} else if(category.isCertificationFeedback()) {
category.setCategoryNumericalScore(-2);
} else if(category.isNullFlavorNI()) {
category.setCategoryNumericalScore(-1);
}
}
//sorts by numerical score via Comparable implementation in Category
Collections.sort(sortedCategories, Collections.reverseOrder());
return sortedCategories;
}
private static void appendHeatmap(StringBuffer sb, Results results,
List<Category> categories, List<ReferenceResult> referenceResults) {
sb.append("<span id='heatMap'>" + "</span>");
for (Category curCategory : getSortedCategories(categories)) {
sb.append("<h3>"
+ (curCategory.getNumberOfIssues() > 0
? "<a href='#" + curCategory.getCategoryName() + "-category" + "'>" : "")
+ curCategory.getCategoryName()
+ (curCategory.getNumberOfIssues() > 0
? "</a>" : "")
+ "</h3>");
sb.append("<ul>");
if (curCategory.getCategoryGrade() != null) {
sb.append("<li>" + "Section Grade: " + "<b>"
+ curCategory.getCategoryGrade() + "</b>" + "</li>"
+ "<li>" + "Number of Issues: " + "<b>"
+ curCategory.getNumberOfIssues() + "</b>" + "</li>");
} else {
sb.append("<li>"
+ "This category was not scored as it ");
if(curCategory.isNullFlavorNI()) {
sb.append("is an <b>empty section</b>");
}
boolean failingConformance = curCategory.isFailingConformance();
boolean failingCertification = curCategory.isCertificationFeedback();
if(failingConformance || failingCertification) {
boolean isCategoryNameValid = !ApplicationUtil.isEmpty(curCategory.getCategoryName());
if(failingConformance && failingCertification || failingConformance && !failingCertification) {
//we default to IG if true for both since IG is considered a more serious issue (same with the heatmap label, so we match that)
//there could be a duplicate for two reasons, right now, there's always at least one duplicate since we derive ig from cert in the backend
//in the future this might not be the case, but, there could be multiple section fails in the same section, so we have a default for those too
int igErrorCount = isCategoryNameValid
? getFailingSectionSpecificErrorCount(curCategory.getCategoryName(), ReferenceInstanceType.IG_CONFORMANCE, referenceResults)
: -1;
sb.append("contains" + (isCategoryNameValid ? " <b>" + igErrorCount + "</b> " : "")
+ "<a href='#" + ReferenceInstanceType.IG_CONFORMANCE.getTypePrettyName()
+ "-category'" + ">" + "Conformance Error" + (igErrorCount != 1 ? "s" : "") + "</a>");
} else if(failingCertification && !failingConformance) {
int certFeedbackCount = isCategoryNameValid
? getFailingSectionSpecificErrorCount(curCategory.getCategoryName(), ReferenceInstanceType.CERTIFICATION_2015, referenceResults)
: -1;
sb.append("contains" + (isCategoryNameValid ? " <b>" + certFeedbackCount + "</b> " : "")
+ "<a href='#" + ReferenceInstanceType.CERTIFICATION_2015.getTypePrettyName()
+ "-category'" + ">" + "Certification Feedback" + "</a>" + " result" + (certFeedbackCount != 1 ? "s" : ""));
}
}
sb.append("</li>");
}
sb.append("</ul></li>");
}
}
private static void appendSummaryRow(StringBuffer sb, int result,
String header, String messageSuffix, String messageSubject,
boolean isSingular) {
appendSummaryRow(sb, result, header, messageSuffix, messageSubject, isSingular, null);
}
private static void appendSummaryRow(StringBuffer sb, int result,
String header, String messageSuffix, String messageSubject,
boolean isSingular, SaveReportType reportType) {
if(reportType == null) {
reportType = SaveReportType.MATCH_UI;
}
sb.append("<h3>"
+ header
+ ": "
+ ("Scorecard Issues".equals(header) || result < 1 || reportType == SaveReportType.SUMMARY ? result
: ("<a href=\"#" + header + "-category\">" + result + "</a>"))
+ "</h3>");
sb.append("<ul><li>");
sb.append("<p>There " + (isSingular ? "is" : "are") + " " + "<b>"
+ result + "</b>" + " " + messageSubject
+ (messageSuffix != null ? " " + messageSuffix : "")
+ " in your document.</p>");
}
private static void appendDetailedResults(StringBuffer sb,
List<Category> categories, List<ReferenceResult> referenceResults) {
sb.append("<h2>" + "Detailed Results" + "</h2>");
if (!ApplicationUtil.isEmpty(referenceResults)) {
for (ReferenceResult curRefInstance : referenceResults) {
ReferenceInstanceType refType = curRefInstance.getType();
if (curRefInstance.getTotalErrorCount() > 0) {
String refTypeName = refType.getTypePrettyName();
sb.append("<h3 id=\"" + refTypeName + "-category\">"
+ refTypeName + "</h3>");
sb.append("<ul>"); // START curRefInstance ul
sb.append("<li>"
+ "Number of "
+ (refType == ReferenceInstanceType.CERTIFICATION_2015 ? "Results:"
: "Errors:") + " "
+ curRefInstance.getTotalErrorCount() + "</li>");
sb.append("<ol>"); // START reference errors ol
for (ReferenceError curRefError : curRefInstance
.getReferenceErrors()) {
sb.append("<li>"
+ (refType == ReferenceInstanceType.CERTIFICATION_2015 ? "Feedback:"
: "Error:") + " "
+ curRefError.getDescription() + "</li>");
sb.append("<ul>"); // START ul within the curRefError
if (!ApplicationUtil.isEmpty(curRefError
.getSectionName())) {
sb.append("<li>" + "Related Section: "
+ curRefError.getSectionName() + "</li>");
}
sb.append("<li>"
+ "Document Line Number (approximate): "
+ curRefError.getDocumentLineNumber() + "</li>");
sb.append("<li>"
+ "xPath: "
+ "<xmp style='font-family: Consolas, monaco, monospace;'>"
+ curRefError.getxPath() + "</xmp>" + "</li>");
sb.append("</ul>"); // END ul within the curRefError
}
}
sb.append("</ol>"); // END reference errors ol
sb.append("</ul>"); // END curRefInstance ul
appendBackToTopWithBreaks(sb);
} //END for (ReferenceResult curRefInstance : referenceResults)
}
for (Category curCategory : getSortedCategories(categories)) {
if (curCategory.getNumberOfIssues() > 0) {
sb.append("<h3 id='" + curCategory.getCategoryName() + "-category"
+ "'>" + curCategory.getCategoryName() + "</h3>");
sb.append("<ul>"); // START curCategory ul
sb.append("<li>" + "Section Grade: "
+ curCategory.getCategoryGrade() + "</li>" + "<li>"
+ "Number of Issues: "
+ curCategory.getNumberOfIssues() + "</li>");
sb.append("<ol>"); // START rules ol
for (CCDAScoreCardRubrics curRubric : curCategory
.getCategoryRubrics()) {
if (curRubric.getNumberOfIssues() > 0) {
sb.append("<li>" + "Rule: " + curRubric.getRule()
+ "</li>");
if (curRubric.getDescription() != null) {
sb.append("<ul>" + "<li>" + "Description"
+ "</li>" + "<ul>" + "<li>"
+ curRubric.getDescription() + "</li>"
+ "</ul>" + "</ul>");
sb.append("<br />");
sb.append("<ol>"); // START snippets ol
for (CCDAXmlSnippet curSnippet : curRubric
.getIssuesList()) {
sb.append("<li>"
+ "XML at line number "
+ curSnippet.getLineNumber()
+ "</li>"
+ "<br /><xmp style='font-family: Consolas, monaco, monospace;'>"
+ curSnippet.getXmlString()
+ "</xmp><br /><br />");
}
sb.append("</ol>"); // END snippets ol
}
} else {
// don't display rules without occurrences
sb.append("</ol>");
}
}
sb.append("</ol>"); // END rules ol
sb.append("</ul>"); // END curCategory ul
appendBackToTopWithBreaks(sb);
} //END if (curCategory.getNumberOfIssues() > 0)
} //END for (Category curCategory : categories)
}
private static void appendPictorialGuide(StringBuffer sb,
List<Category> categories, List<ReferenceResult> referenceResults) {
//minimum breaks based on 11 categories
sb.append("<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />");
sb.append("<h2>" + "Guide to Interpret the Scorecard Results Table" + "</h2>");
sb.append("<p>" + "The following sample table identifies how to use the C-CDA Scorecard results "
+ "to improve the C-CDA documents generated by your organization. "
+ "Note: The table below is an example containing fictitious results "
+ "and does not reflect C-CDAs generated by your organization." + "</p>");
//static table
sb.append("<table id=\"staticTable\">")
.append(" <tbody>")
.append(" <tr>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td id=\"issuePopOut\" rowspan=\"2\">A Scorecard Issue identifies data within the document which can be represented in a better way using HL7 best practices for C-CDA. This column should have numbers as close to zero as possible.</td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" </tr>")
.append(" <tr>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td id=\"gradePopOut\" colspan=\"2\">The Scorecard grade is a quantitative assessment of the data quality of the submitted document. A higher grade indicates that HL7 best practices for C-CDA implementation are being followed by the organization and has higher probability of being interoperable")
.append(" with other organizations.</td>")
.append(" <td id=\"errorPopOut\" colspan=\"2\">A Conformance Error implies that the document is non-compliant with the HL7 C-CDA IG requirements. This column should have zeros ideally. Providers should work with their health IT vendor to rectify the errors.</td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" </tr>")
.append(" <tr>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td id=\"gradePopOutLink\"></td>")
.append(" <td id=\"issuePopOutLink\"></td>")
.append(" <td id=\"errorPopOutLink\"></td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" </tr>")
.append(" <tr>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <th>Clinical Domain</th>")
.append(" <th id=\"gradeHeader\">Scorecard Grade</th>")
.append(" <th id=\"issueHeader\">Scorecard Issues</th>")
.append(" <th id=\"errorHeader\">Conformance Errors</th>")
.append(" <th id=\"feedbackHeader\">Certification Feedback</th>")
.append(" <td id=\"feedbackPopOutLink\"></td>")
.append(" <td id=\"feedbackPopOut\" rowspan=\"5\">A Certification Feedback result identifies areas where the generated documents are not compliant with the requirements of 2015 Edition Certification. Ideally, this column should have all zeros.</td>")
.append(" </tr>")
.append(" <tr>")
.append(" <td id=\"perfectRowPopOut\" rowspan=\"4\">The Problems row in this example has an A+ grade and all zeros across the board. This is the most desirable outcome for a Clinical Domain result set.</td>")
.append(" <td id=\"perfectRowPopOutLink\"></td>")
.append(" <td id=\"perfectRowLeftHeader\">Problems</td>")
.append(" <td class=\"perfectRowMiddleHeader\">A+</td>")
.append(" <td class=\"perfectRowMiddleHeader\">0</td>")
.append(" <td class=\"perfectRowMiddleHeader\">0</td>")
.append(" <td id=\"perfectRowRightHeader\">0</td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" </tr>")
.append(" <tr>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td>Lab Results</td>")
.append(" <td>A-</td>")
.append(" <td>2</td>")
.append(" <td>0</td>")
.append(" <td>0</td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" </tr>")
.append(" <tr>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td>Vital Signs</td>")
.append(" <td>A-</td>")
.append(" <td>1</td>")
.append(" <td>0</td>")
.append(" <td>0</td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" </tr>")
.append(" <tr>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td>Encounters</td>")
.append(" <td>D</td>")
.append(" <td>12</td>")
.append(" <td>0</td>")
.append(" <td>0</td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" </tr>")
.append(" <tr>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td id=\"notScoredRowLeftHeader\">Medications</td>")
.append(" <td class=\"notScoredRowMiddleHeader\">N/A</td>")
.append(" <td class=\"notScoredRowMiddleHeader\">N/A</td>")
.append(" <td class=\"notScoredRowMiddleHeader\">2</td>")
.append(" <td id=\"notScoredRowRightHeader\">0</td>")
.append(" <td id=\"notScoredRowPopOutLink\"></td>")
.append(" <td id=\"notScoredRowPopOut\" rowspan=\"3\">This domain was not scored because the document did not have data pertaining to the clinical domain or there were conformance errors or certification results.</td>")
.append(" </tr>")
.append(" <tr>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td>Allergies</td>")
.append(" <td>N/A</td>")
.append(" <td>N/A</td>")
.append(" <td>0</td>")
.append(" <td>4</td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" </tr>")
.append(" <tr>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td>Immunizations</td>")
.append(" <td>N/A</td>")
.append(" <td>N/A</td>")
.append(" <td>0</td>")
.append(" <td>0</td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" <td class=\"removeBorder\"></td>")
.append(" </tr>")
.append(" </tbody>")
.append("</table>");
}
private static void appendPictorialGuideKey(StringBuffer sb) {
sb.append("<h3>Additional Guidance to Interpret the Scorecard Results and Achieve Higher Grades</h3>")
.append("<p>")
.append(" <span id=\"keyGradeHeader\">Scorecard Grade: </span>")
.append("The Scorecard grade is a quantitative assessment of the data quality of the submitted document. "
+ "A higher grade indicates that HL7 best practices for C-CDA implementation are being followed by the organization "
+ "and has higher probability of being interoperable with other organizations. "
+ "The grades are derived from the scores as follows: "
+ "A+ ( > 94), A- ( 90 to 94), B+ (85 to 89), B- (80 to 84), C (70 to 79) and D (< 70).")
.append("</p>")
.append("<p>")
.append(" <span id=\"keyIssueHeader\">Scorecard Issues: </span>")
.append("A Scorecard Issue identifies data within the document which can be represented in a better way using HL7 best practices for C-CDA. "
+ "This column should have numbers as close to zero as possible. "
+ "The issues are counted for each occurrence of unimplemented best practice. "
+ "For example, if a Vital Sign measurement is not using the appropriate UCUM units then each such occurrence would be flagged "
+ "as an issue. A provider should work with their health IT vendor to better understand the source for why a best practice "
+ "may not be implemented and then determine if it can be implemented in the future. Note: Scorecard Issues will be listed as "
+ "'N/A' for a clinical domain, when there is no data for the domain or if there are conformance or certification feedback results.")
.append("</p>")
.append("<p>")
.append(" <span id=\"keyErrorHeader\">Conformance Errors: </span>")
.append("A Conformance Error implies that the document is non-compliant with the HL7 C-CDA IG requirements. "
+ "This column should have zeros ideally. "
+ "Providers should work with their health IT vendor to rectify the errors.")
.append("</p>")
.append("<p>")
.append(" <span id=\"keyFeedbackHeader\">Certification Feedback: </span>")
.append("A Certification Feedback result identifies areas where the generated documents are not compliant with "
+ "the requirements of 2015 Edition Certification. Ideally, this column should have all zeros."
+ "Most of these results fall into incorrect use of vocabularies and terminologies. "
+ "Although not as severe as a Conformance Error, providers should work with their health IT vendor "
+ "to address feedback provided to improve interoperable use of structured data between systems.")
.append("</p>");
}
private static void appendClosingHtml(StringBuffer sb) {
sb.append("</body>");
sb.append("</html>");
}
private static void appendHorizontalRuleWithBreaks(StringBuffer sb) {
sb.append("<br />");
sb.append("<hr />");
sb.append("<br />");
}
private static void appendBackToTopWithBreaks(StringBuffer sb) {
// sb.append("<br />");
sb.append("<a href='#topOfScorecard'>Back to Top</a>");
// sb.append("<br />");
// A PDF conversion bug is not processing this valid HTML so commenting
// out until time to address
// sb.append("<a href='#heatMap'>Back to Section List</a>");
sb.append("<br />");
// sb.append("<br />");
}
private static void appendErrorMessage(StringBuffer sb, String errorMessage) {
sb.append("<h2 style='color:red; background-color: #ffe6e6'>");
sb.append(errorMessage);
sb.append("</h2>");
if(!errorMessage.contains("HL7 CDA Schema Errors")) {
sb.append("<p>" + ApplicationConstants.ErrorMessages.CONTACT + "</p>");
}
}
private static void appendGenericErrorMessage(StringBuffer sb) {
sb.append("<p>"
+ ApplicationConstants.ErrorMessages.JSON_TO_JAVA_JACKSON
+ "<br />" + ApplicationConstants.ErrorMessages.CONTACT
+ "</p>");
}
private static void appendErrorMessageFromReport(StringBuffer sb,
ResponseTO report) {
appendErrorMessageFromReport(sb, report, null);
}
private static void appendErrorMessageFromReport(StringBuffer sb,
ResponseTO report, String extraMessage) {
if (report.getErrorMessage() != null
&& !report.getErrorMessage().isEmpty()) {
appendErrorMessage(sb, report.getErrorMessage());
if(report.getSchemaErrorList() != null && !report.getSchemaErrorList().isEmpty()) {
sb.append("<h3>" + ApplicationConstants.ErrorMessages.SCHEMA_ERRORS_GENERIC_PART2 + "</h3>");
final String noData = "No data available";
sb.append("<ol style='color:red'>");
for(ReferenceError schemaError : report.getSchemaErrorList()) {
sb.append("<li>");
sb.append("<ul>");
sb.append("<li>Message: " + (schemaError.getDescription() != null ? schemaError.getDescription() : noData));
sb.append("</li>");
sb.append("<li>Path: " + (schemaError.getxPath() != null ? schemaError.getxPath() : noData));
sb.append("</li>");
sb.append("<li>Line Number (approximate): " +
(schemaError.getDocumentLineNumber() != null ? schemaError.getDocumentLineNumber() : noData));
sb.append("</li>");
sb.append("<li>xPath: "
+ "<xmp style='font-family: Consolas, monaco, monospace;'>"
+ (schemaError.getxPath() != null ? schemaError.getxPath() : noData) + "</xmp>");
sb.append("<p></p>");
sb.append("</li>");
sb.append("</ul>");
sb.append("</li>");
}
sb.append("</ol>");
}
} else {
appendGenericErrorMessage(sb);
}
if (extraMessage != null && !extraMessage.isEmpty()) {
sb.append("<p>" + extraMessage + "</p>");
}
}
protected static String ensureLogicalParseTreeInHTML(String htmlReport) {
org.jsoup.nodes.Document doc = Jsoup.parse(htmlReport);
String cleanHtmlReport = doc.toString();
return cleanHtmlReport;
}
private static void convertHTMLToPDF(String cleanHtmlReport) {
convertHTMLToPDF(cleanHtmlReport, null);
}
private static void convertHTMLToPDF(String cleanHtmlReport, HttpServletResponse response) {
OutputStream out = null;
try {
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
factory.setNamespaceAware(false);
factory.setValidating(false);
DocumentBuilder builder = factory.newDocumentBuilder();
Document refineddoc = builder.parse(new ByteArrayInputStream(
cleanHtmlReport.getBytes("UTF-8")));
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(refineddoc, null);
renderer.layout();
if(response != null) {
//Stream to Output
response.setContentType("application/pdf");
response.setHeader("Content-disposition", "attachment; filename="
+ "scorecardReport.pdf");
response.setHeader("max-age=3600", "must-revalidate");
response.addCookie(new Cookie("fileDownload=true", "path=/"));
out = response.getOutputStream();
} else {
//Save to local file system
out = new FileOutputStream(new File("testSaveReportImplementation.pdf"));
}
renderer.createPDF(out);
} catch (ParserConfigurationException pcE) {
pcE.printStackTrace();
} catch (SAXException saxE) {
saxE.printStackTrace();
} catch (DocumentException docE) {
docE.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(LOG_HTML) {
ApplicationUtil.debugLog("cleanHtmlReport", cleanHtmlReport);
}
}
}
protected static void convertHTMLToPDFAndStreamToOutput(
String cleanHtmlReport, HttpServletResponse response) {
convertHTMLToPDF(cleanHtmlReport, response);
}
private static void convertHTMLToPDFAndSaveToLocalFileSystem(String cleanHtmlReport) {
convertHTMLToPDF(cleanHtmlReport);
}
/**
* Converts JSON to ResponseTO Java Object using The Jackson API
*
* @param jsonReportData
* JSON which resembles ResponseTO
* @return converted ResponseTO POJO
*/
protected static ResponseTO convertJsonToPojo(String jsonReportData) {
ObjectMapper mapper = new ObjectMapper();
ResponseTO pojo = null;
try {
pojo = mapper.readValue(jsonReportData, ResponseTO.class);
} catch (IOException e) {
e.printStackTrace();
}
return pojo;
}
public enum SaveReportType {
MATCH_UI, SUMMARY;
}
private static void buildReportUsingJSONFromLocalFile(String filenameWithoutExtension,
SaveReportType reportType) throws URISyntaxException {
URI jsonFileURI = new File(
"src/main/webapp/resources/"
+ filenameWithoutExtension + ".json").toURI();
System.out.println("jsonFileURI");
System.out.println(jsonFileURI);
String jsonReportData = convertFileToString(jsonFileURI);
System.out.println("jsonReportData");
System.out.println(jsonReportData);
ResponseTO pojoResponse = convertJsonToPojo(jsonReportData);
System.out.println("response");
System.out.println(pojoResponse.getCcdaDocumentType());
convertHTMLToPDFAndSaveToLocalFileSystem(
ensureLogicalParseTreeInHTML(convertReportToHTML(pojoResponse, reportType)));
}
private static String convertFileToString(URI fileURI) {
StringBuilder sb = new StringBuilder();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(fileURI.getPath()));
String sCurrentLine = "";
while ((sCurrentLine = br.readLine()) != null) {
sb.append(sCurrentLine);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
public static void main(String[] args) {
String[] filenames = {"highScoringSample", "lowScoringSample", "sampleWithErrors",
"sampleWithSchemaErrors"};
final int HIGH_SCORING_SAMPLE = 0, LOW_SCORING_SAMPLE = 1, SAMPLE_WITH_ERRORS = 2,
SAMPLE_WITH_SCHEMA_ERRORS = 3;
try {
buildReportUsingJSONFromLocalFile(filenames[HIGH_SCORING_SAMPLE], SaveReportType.SUMMARY);
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}
|
package org.kie.uberfire.plugin.model;
import org.jboss.errai.common.client.api.annotations.Portable;
@Portable
public enum PluginType {
PERSPECTIVE, SCREEN, EDITOR, SPLASH, DYNAMIC_MENU
}
|
package com.vondear.vontools;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Hashtable;
public class VonUtils {
private static Context context;
/**
*
*
* @param context
*/
public static void init(Context context) {
VonUtils.context = context.getApplicationContext();
VonCrashUtils.getInstance(context).init();
}
public interface DelayListener {
void doSomething();
}
public static void delayToDo(final DelayListener delayListener,long delayTime) {
new Handler().postDelayed(new Runnable() {
public void run() {
//execute the task
delayListener.doSomething();
}
}, delayTime);
}
/**
* ApplicationContext
*
* @return ApplicationContext
*/
public static Context getContext() {
if (context != null) return context;
throw new NullPointerException("init()");
}
/**
*
*
* @param activity
* @param view
*/
public static void hideKeyboard(Activity activity, View view) {
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
/**
*
*
* @param textView
* @param waitTime
* @param interval
* @param hint
*/
public static void countDown(final TextView textView, long waitTime, long interval, final String hint) {
textView.setEnabled(false);
android.os.CountDownTimer timer = new android.os.CountDownTimer(waitTime, interval) {
@Override
public void onTick(long millisUntilFinished) {
textView.setText(" " + (millisUntilFinished / 1000) + " S");
}
@Override
public void onFinish() {
textView.setEnabled(true);
textView.setText(hint);
}
};
timer.start();
}
/**
* Toast :
*
* @param cxt
* @param str
* @param isLong
*/
public static void showToast(Context cxt, String str, boolean isLong) {
if (isLong) {
Toast.makeText(cxt, str, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(cxt, str, Toast.LENGTH_SHORT).show();
}
}
public static void showToastShort(String str) {
Toast.makeText(getContext(), str, Toast.LENGTH_SHORT).show();
}
public static void showToastShort(int resId) {
Toast.makeText(getContext(), context.getString(resId), Toast.LENGTH_SHORT).show();
}
public static void showToastLong(String str) {
Toast.makeText(getContext(), str, Toast.LENGTH_LONG).show();
}
public static void showToastLong(int resId) {
Toast.makeText(getContext(), context.getString(resId), Toast.LENGTH_LONG).show();
}
public static void showToast(String msg) {
if (mToast == null) {
mToast = Toast.makeText(getContext(), msg, Toast.LENGTH_LONG);
} else {
mToast.setText(msg);
}
mToast.show();
}
public static void showToast(int resId) {
context = getContext();
if (mToast == null) {
mToast = Toast.makeText(getContext(), context.getString(resId), Toast.LENGTH_LONG);
} else {
mToast.setText(context.getString(resId));
}
mToast.show();
}
/**
* Toast
*/
private static Toast mToast;
/**
* Toast
*
* @param context
* @param resId ID
* @param duration
*/
public static void showToast(Context context, int resId, int duration) {
showToast(context, context.getString(resId), duration);
}
/**
* Toast
*
* @param context
* @param msg
* @param duration
*/
public static void showToast(Context context, String msg, int duration) {
if (mToast == null) {
mToast = Toast.makeText(context, msg, duration);
} else {
mToast.setText(msg);
}
mToast.show();
}
/**
* listView
*
* @param listView
*/
public static void fixListViewHeight(ListView listView) {
// ListView
ListAdapter listAdapter = listView.getAdapter();
int totalHeight = 0;
if (listAdapter == null) {
return;
}
for (int index = 0, len = listAdapter.getCount(); index < len; index++) {
View listViewItem = listAdapter.getView(index, null, listView);
// View
listViewItem.measure(0, 0);
totalHeight += listViewItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
// listView.getDividerHeight()
// params.heightListView
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
/**
* @param url
* @param QR_WIDTH
* @param QR_HEIGHT
* @param iv_code
*/
public static void createQRImage(String url, int QR_WIDTH, int QR_HEIGHT,
ImageView iv_code) {
try {
// URL
if (url == null || "".equals(url) || url.length() < 1) {
return;
}
Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
BitMatrix bitMatrix = new QRCodeWriter().encode(url,
BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT, hints);
int[] pixels = new int[QR_WIDTH * QR_HEIGHT];
// for
for (int y = 0; y < QR_HEIGHT; y++) {
for (int x = 0; x < QR_WIDTH; x++) {
if (bitMatrix.get(x, y)) {
pixels[y * QR_WIDTH + x] = 0xff000000;
} else {
pixels[y * QR_WIDTH + x] = 0xffffffff;
}
}
}
// ARGB_8888
Bitmap bitmap = Bitmap.createBitmap(QR_WIDTH, QR_HEIGHT,
Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, QR_WIDTH, 0, 0, QR_WIDTH, QR_HEIGHT);
// ImageView
iv_code.setImageBitmap(bitmap);
} catch (WriterException e) {
e.printStackTrace();
}
}
/**
*
*
* @param context
* @param contents
* @param desiredWidth
* @param desiredHeight
* @return
*/
public static Bitmap drawLinecode(Context context, String contents,
int desiredWidth, int desiredHeight) {
Bitmap ruseltBitmap = null;
BarcodeFormat barcodeFormat = BarcodeFormat.CODE_128;
final int WHITE = 0xFFFFFFFF;
final int BLACK = 0xFF000000;
MultiFormatWriter writer = new MultiFormatWriter();
BitMatrix result = null;
try {
result = writer.encode(contents, barcodeFormat, desiredWidth,
desiredHeight, null);
} catch (WriterException e) {
e.printStackTrace();
}
int width = result.getWidth();
int height = result.getHeight();
int[] pixels = new int[width * height];
// All are 0, or black, by default
for (int y = 0; y < height; y++) {
int offset = y * width;
for (int x = 0; x < width; x++) {
pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
ruseltBitmap = bitmap;
return ruseltBitmap;
}
/**
* MD532
*
* @param MStr :
* @return
*/
public static String Md5(String MStr) {
try {
final MessageDigest mDigest = MessageDigest.getInstance("MD5");
mDigest.update(MStr.getBytes());
return bytesToHexString(mDigest.digest());
} catch (NoSuchAlgorithmException e) {
return String.valueOf(MStr.hashCode());
}
}
private static String bytesToHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(0xFF & bytes[i]);
if (hex.length() == 1) {
sb.append('0');
}
sb.append(hex);
}
return sb.toString();
}
}
|
package org.voovan.http.message;
import org.voovan.Global;
import org.voovan.http.message.packet.Cookie;
import org.voovan.http.message.packet.Part;
import org.voovan.http.server.context.WebContext;
import org.voovan.http.server.exception.HttpParserException;
import org.voovan.http.server.exception.RequestTooLarge;
import org.voovan.network.IoSession;
import org.voovan.tools.*;
import org.voovan.tools.buffer.ByteBufferChannel;
import org.voovan.tools.buffer.TByteBuffer;
import org.voovan.tools.hashwheeltimer.HashWheelTask;
import org.voovan.tools.log.Logger;
import org.voovan.tools.security.THash;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentSkipListMap;
public class HttpParser {
private static final String PL_METHOD = "1";
private static final String PL_PATH = "2";
private static final String PL_PROTOCOL = "3";
private static final String PL_VERSION = "4";
private static final String PL_STATUS = "5";
private static final String PL_STATUS_CODE = "6";
private static final String PL_QUERY_STRING = "7";
private static final String PL_HASH = "8";
private static final String USE_CACHE = "9";
private static final String BODY_PARTS = "10";
private static final String BODY_VALUE = "11";
private static final String BODY_FILE = "12";
public static final String MULTIPART_FORM_DATA = "multipart/form-data";
public static final String UPLOAD_PATH = TFile.assemblyPath(TFile.getTemporaryPath(),"voovan", "webserver", "upload");
public static final String propertyLineRegex = ": ";
public static final String equalMapRegex = "([^ ;,]+=[^;,]+)";
public static FastThreadLocal<Map<String, Object>> THREAD_PACKET_MAP = FastThreadLocal.withInitial(()->new HashMap<String, Object>());
public static FastThreadLocal<Request> THREAD_REQUEST = FastThreadLocal.withInitial(()->new Request());
public static FastThreadLocal<Response> THREAD_RESPONSE = FastThreadLocal.withInitial(()->new Response());
private static FastThreadLocal<byte[]> THREAD_STRING_BUILDER = FastThreadLocal.withInitial(()->new byte[1024]);
private static ConcurrentSkipListMap<Long, Map<String, Object>> PACKET_MAP_CACHE = new ConcurrentSkipListMap<Long, Map<String, Object>>();
public static final int PARSER_TYPE_REQUEST = 0;
public static final int PARSER_TYPE_RESPONSE = 1;
static {
Global.getHashWheelTimer().addTask(new HashWheelTask() {
@Override
public void run() {
PACKET_MAP_CACHE.clear();
}
}, 60);
}
private HttpParser(){
}
/**
* HTTP Header
* @param propertyLine
* Http
* @return
*/
private static Map<String,String> parsePropertyLine(String propertyLine){
Map<String,String> property = new HashMap<String, String>();
int index = propertyLine.indexOf(propertyLineRegex);
if(index > 0){
String propertyName = propertyLine.substring(0, index);
String properyValue = propertyLine.substring(index+2, propertyLine.length());
property.put(fixHeaderName(propertyName), properyValue.trim());
}
return property;
}
/**
* Http
* @param headerName http
* @return http
*/
public static String fixHeaderName(String headerName) {
if(headerName==null){
return null;
}
String[] headerNameSplits = headerName.split("-");
StringBuilder stringBuilder = new StringBuilder();
for(String headerNameSplit : headerNameSplits) {
if(Character.isLowerCase(headerNameSplit.codePointAt(0))){
stringBuilder.append((char)(headerNameSplit.codePointAt(0) - 32));
stringBuilder.append(TString.removePrefix(headerNameSplit));
} else {
stringBuilder.append(headerNameSplit);
}
stringBuilder.append("-");
}
return TString.removeSuffix(stringBuilder.toString());
}
/**
* Map
* @param str
*
* @return Map
*/
public static Map<String, String> getEqualMap(String str){
Map<String, String> equalMap = new HashMap<String, String>();
String[] searchedStrings = TString.searchByRegex(str, equalMapRegex);
for(String groupString : searchedStrings){
// split
String[] equalStrings = new String[2];
int equalCharIndex= groupString.indexOf(Global.STR_EQUAL);
equalStrings[0] = groupString.substring(0,equalCharIndex);
equalStrings[1] = groupString.substring(equalCharIndex+1,groupString.length());
if(equalStrings.length==2){
String key = equalStrings[0];
String value = equalStrings[1];
if(value.startsWith(Global.STR_QUOTE) && value.endsWith(Global.STR_QUOTE)){
value = value.substring(1,value.length()-1);
}
equalMap.put(key, value);
}
}
return equalMap;
}
/**
* HTTP
* Content-Type: multipart/form-data; boundary=ujjLiiJBznFt70fG1F4EUCkIupn7H4tzm
* boundary.
* :getPerprotyEqualValue(packetMap,"Content-Type","boundary")ujjLiiJBznFt70fG1F4EUCkIupn7H4tzm
* @param propertyName
* @param valueName
* @return
*/
private static String getPerprotyEqualValue(Map<String,Object> packetMap,String propertyName,String valueName){
Object propertyValueObj = packetMap.get(propertyName);
if(propertyValueObj == null){
return null;
}
String propertyValue = propertyValueObj.toString();
Map<String, String> equalMap = getEqualMap(propertyValue);
return equalMap.get(valueName);
}
/**
* Cookie
* @param packetMap MAp
* @param cookieName Http Cookie
* @param cookieValue Http Cookie
*/
@SuppressWarnings("unchecked")
private static void parseCookie(Map<String, Object> packetMap,String cookieName, String cookieValue){
if(!packetMap.containsKey(HttpStatic.COOKIE_STRING)){
packetMap.put(HttpStatic.COOKIE_STRING, new ArrayList<Map<String, String>>());
}
List<Map<String, String>> cookies = (List<Map<String, String>>) packetMap.get(HttpStatic.COOKIE_STRING);
// Cookie
Map<String, String>cookieMap = getEqualMap(cookieValue);
// response cookie cookie
if(HttpStatic.SET_COOKIE_STRING.equalsIgnoreCase(cookieName)){
// cookie
if(cookieValue.toLowerCase().contains(HttpStatic.HTTPONLY_STRING)){
cookieMap.put(HttpStatic.HTTPONLY_STRING, Global.EMPTY_STRING);
}
if(cookieValue.toLowerCase().contains(HttpStatic.SECURE_STRING)){
cookieMap.put(HttpStatic.SECURE_STRING, Global.EMPTY_STRING);
}
cookies.add(cookieMap);
}
// request cookie cookie
else if(HttpStatic.COOKIE_STRING.equalsIgnoreCase(cookieName)){
for(Entry<String,String> cookieMapEntry: cookieMap.entrySet()){
HashMap<String, String> cookieOneMap = new HashMap<String, String>();
cookieOneMap.put(cookieMapEntry.getKey(), cookieMapEntry.getValue());
cookies.add(cookieOneMap);
}
}
}
/**
* body
* GZIP ,,
* @param packetMap
* @param contentBytes
* @return
* @throws IOException
*/
private static byte[] dealBodyContent(Map<String, Object> packetMap,byte[] contentBytes) throws IOException{
byte[] bytesValue;
if(contentBytes.length == 0 ){
return contentBytes;
}
// GZip
boolean isGZip = packetMap.get(HttpStatic.CONTENT_ENCODING_STRING)==null ? false : packetMap.get(HttpStatic.CONTENT_ENCODING_STRING).toString().contains(HttpStatic.GZIP_STRING);
// GZip
if(isGZip && contentBytes.length>0){
bytesValue = TZip.decodeGZip(contentBytes);
} else {
bytesValue = contentBytes;
}
return TObject.nullDefault(bytesValue,new byte[0]);
}
/**
* HTTP
* @param packetMap
* @param type
* @param byteBuffer ByteBuffer
* @param contiuneRead
* @param timeout
*/
public static void parserProtocol(Map<String, Object> packetMap, int type, ByteBuffer byteBuffer, Runnable contiuneRead, int timeout) {
byte[] bytes = THREAD_STRING_BUILDER.get();
int position = 0;
int hashCode = 0;
boolean isCache = type==PARSER_TYPE_REQUEST ? WebContext.isCache() : false;
// Protocol
int segment = 0;
String segment_1 = "";
String segment_2 = "";
String segment_3 = "";
int questPositiion = -1;
byte prevByte = '\0';
byte currentByte = '\0';
long start = System.currentTimeMillis();
while (true) {
while(!byteBuffer.hasRemaining()) {
contiuneRead.run();
if(System.currentTimeMillis() - start > timeout) {
throw new HttpParserException("HttpParser read failed");
}
}
currentByte = byteBuffer.get();
if (currentByte == Global.BYTE_SPACE && segment < 2) {
if (segment == 0) {
HttpItem httpItem = HttpItem.getHttpItem(bytes, 0, position);
hashCode = hashCode + httpItem.getHashCode() << 1;
segment_1 = httpItem.getString();
} else if (segment == 1) {
HttpItem httpItem = HttpItem.getHttpItem(bytes, 0, position);
hashCode = hashCode + httpItem.getHashCode() << 2;
segment_2 =httpItem.getString();
}
position = 0;
segment++;
continue;
} else if (currentByte == Global.BYTE_QUESTION) {
if (segment == 1) {
questPositiion = byteBuffer.position();
continue;
}
} else if (prevByte == Global.BYTE_CR && currentByte == Global.BYTE_LF && segment == 2) {
HttpItem httpItem = HttpItem.getHttpItem(bytes, 0, position);
hashCode = hashCode + httpItem.getHashCode() << 3;
segment_3 =httpItem.getString();
position = 0;
break;
}
prevByte = currentByte;
if (currentByte == Global.BYTE_CR) {
continue;
}
bytes[position] = currentByte;
position++;
}
if (type == 0) {
packetMap.put(PL_METHOD, segment_1);
questPositiion = questPositiion - segment_1.length() - 1;
packetMap.put(PL_PATH, questPositiion > 0 ? segment_2.substring(0, questPositiion - 1) : segment_2);
if (questPositiion > 0) {
packetMap.put(PL_QUERY_STRING, segment_2.substring(questPositiion - 1));
}
if(segment_3.charAt(0)=='H' && segment_3.charAt(1)=='T' && segment_3.charAt(2)=='T' && segment_3.charAt(3)=='P') {
packetMap.put(PL_PROTOCOL, HttpStatic.HTTP.getString());
} else {
throw new HttpParserException("Not a http packet");
}
switch (segment_3.charAt(7)) {
case '1':
packetMap.put(PL_VERSION, HttpStatic.HTTP_11_STRING);
break;
case '0':
packetMap.put(PL_VERSION, HttpStatic.HTTP_10_STRING);
break;
case '9':
packetMap.put(PL_VERSION, HttpStatic.HTTP_09_STRING);
break;
default:
packetMap.put(PL_VERSION, HttpStatic.HTTP_11_STRING);
}
}
if (type == 1) {
if(segment_1.charAt(0)=='H' && segment_1.charAt(1)=='T' && segment_1.charAt(2)=='T' && segment_1.charAt(3)=='P') {
packetMap.put(PL_PROTOCOL, HttpStatic.HTTP.getString());
} else {
throw new HttpParserException("Not a http packet");
}
switch (segment_1.charAt(7)) {
case '1':
packetMap.put(PL_VERSION, HttpStatic.HTTP_11_STRING);
break;
case '0':
packetMap.put(PL_VERSION, HttpStatic.HTTP_10_STRING);
break;
case '9':
packetMap.put(PL_VERSION, HttpStatic.HTTP_09_STRING);
break;
default:
packetMap.put(PL_VERSION, HttpStatic.HTTP_11_STRING);
}
packetMap.put(PL_STATUS, segment_2);
packetMap.put(PL_STATUS_CODE, segment_3);
}
if(isCache) {
packetMap.put(PL_HASH, hashCode);
}
}
/**
* HTTP
* @param packetMap
* @param byteBuffer ByteBuffer
* @param contiuneRead
* @param timeout
* @return true: Header, false: Header
*/
public static boolean parseHeader(Map<String, Object> packetMap, ByteBuffer byteBuffer, Runnable contiuneRead, int timeout) {
byte[] bytes = THREAD_STRING_BUILDER.get();
int position = 0;
// Protocol
boolean onHeaderName = true;
byte prevByte = '\0';
byte currentByte = '\0';
String headerName = null;
String headerValue = null;
long start = System.currentTimeMillis();
while (true) {
while(!byteBuffer.hasRemaining()) {
contiuneRead.run();
if(System.currentTimeMillis() - start > timeout) {
throw new HttpParserException("HttpParser read failed");
}
}
currentByte = byteBuffer.get();
if (onHeaderName && prevByte == Global.BYTE_COLON && currentByte == Global.BYTE_SPACE) {
headerName = HttpItem.getHttpItem(bytes, 0, position).getString();
onHeaderName = false;
position = 0;
continue;
} else if (!onHeaderName && prevByte == Global.BYTE_CR && currentByte == Global.BYTE_LF) {
headerValue = HttpItem.getHttpItem(bytes, 0, position).getString();
break;
}
//http
if (onHeaderName && prevByte == Global.BYTE_CR && currentByte == Global.BYTE_LF) {
return true;
}
prevByte = currentByte;
if (onHeaderName && currentByte == Global.BYTE_COLON) {
continue;
} else if (!onHeaderName && currentByte == Global.BYTE_CR) {
continue;
}
bytes[position] = currentByte;
position++;
}
if(headerName!=null && headerValue!=null) {
packetMap.put(headerName, headerValue);
}
return false;
// packetMap.put(fixHeaderName(headerName), headerValue);
}
/**
* HTTP
* Map ,:
* 1.protocol key/value
* 2.header key/value
* 3.cookie List[Map[String,String]]
* 3.part List[Map[Stirng,Object]](, HTTP )
* 5.body key=BODY_VALUE Map
* @param session socket
* @param packetMap map
* @param type , 0: Request, 1: Response
* @param byteBufferChannel
* @param timeout
* @param requestMaxSize , : kb
* @return Map
* @throws IOException IO
*/
public static Map<String, Object> parser(IoSession session, Map<String, Object> packetMap, int type,
ByteBufferChannel byteBufferChannel, int timeout,
long requestMaxSize) throws IOException {
int totalLength = 0;
long mark = 0;
int headerMark = 0;
int protocolPosition = 0;
boolean isBodyConent = false;
boolean isCache = type==PARSER_TYPE_REQUEST ? WebContext.isCache() : false;
requestMaxSize = requestMaxSize < 0 ? Integer.MAX_VALUE : requestMaxSize;
// Socket
Runnable contiuneRead = ()->{
if(session==null || !session.isConnected()) {
throw new HttpParserException("Socket is disconnect");
}
session.getSocketSelector().eventChoose();
if(session.getReadByteBufferChannel().isReleased()) {
throw new HttpParserException("socket read buffer is released, may be Socket is disconnected");
}
};
//HTTP
while(byteBufferChannel.size() > 0){
ByteBuffer innerByteBuffer = byteBufferChannel.getByteBuffer();
try {
{
parserProtocol(packetMap, type, innerByteBuffer, contiuneRead, timeout);
protocolPosition = innerByteBuffer.position() - 1;
if (isCache) {
mark = ((Integer) packetMap.get(PL_HASH)).longValue();
for (Entry<Long, Map<String, Object>> packetMapCacheItem : PACKET_MAP_CACHE.entrySet()) {
long cachedMark = ((Long) packetMapCacheItem.getKey()).longValue();
long totalLengthInMark = (cachedMark << 32) >> 32;
if (totalLengthInMark > innerByteBuffer.limit()) {
continue;
}
headerMark = THash.HashFNV1(innerByteBuffer, protocolPosition, (int) (totalLengthInMark - protocolPosition));
if (mark + headerMark == cachedMark >> 32) {
if (byteBufferChannel.size() >= totalLengthInMark &&
byteBufferChannel.get((int) totalLengthInMark - 1) == 10 &&
byteBufferChannel.get((int) totalLengthInMark - 2) == 13) {
innerByteBuffer.position((int) totalLengthInMark);
return packetMapCacheItem.getValue();
}
}
}
}
if (!packetMap.containsKey(PL_PROTOCOL)) {
return null;
}
}
{
while (!parseHeader(packetMap, innerByteBuffer, contiuneRead, timeout)) {
if (!innerByteBuffer.hasRemaining() && session.isConnected()) {
return null;
}
}
}
// Cookie
{
String cookieName = null;
String cookieValue = null;
if (packetMap.containsKey(HttpStatic.SET_COOKIE_STRING)) {
cookieName = HttpStatic.SET_COOKIE_STRING;
cookieValue = packetMap.get(HttpStatic.SET_COOKIE_STRING).toString();
packetMap.remove(HttpStatic.SET_COOKIE_STRING);
} else if (packetMap.containsKey(HttpStatic.COOKIE_STRING)) {
cookieName = HttpStatic.COOKIE_STRING;
cookieValue = packetMap.get(HttpStatic.COOKIE_STRING).toString();
packetMap.remove(HttpStatic.COOKIE_STRING);
}
if (cookieName != null) {
parseCookie(packetMap, cookieName, cookieValue);
}
}
if(isCache && "GET".equals(packetMap.get(PL_METHOD)) || !packetMap.containsKey(HttpStatic.CONTENT_TYPE_STRING)) {
totalLength = innerByteBuffer.position();
headerMark = THash.HashFNV1(innerByteBuffer, protocolPosition, (int)(totalLength - protocolPosition));
mark = (mark + headerMark) << 32 | totalLength; // hash,
packetMap.put(PL_HASH, mark);
HashMap<String, Object> cachedPacketMap = new HashMap<String, Object>();
cachedPacketMap.putAll(packetMap);
cachedPacketMap.put(USE_CACHE, 1);
PACKET_MAP_CACHE.put(mark, cachedPacketMap);
break;
}
} finally {
byteBufferChannel.compact();
}
isBodyConent = true;
packetMap.put(PL_HASH, null);
// HTTP body
if(isBodyConent){
String contentType =packetMap.get(HttpStatic.CONTENT_TYPE_STRING)==null ? Global.EMPTY_STRING : packetMap.get(HttpStatic.CONTENT_TYPE_STRING).toString();
String transferEncoding = packetMap.get(HttpStatic.TRANSFER_ENCODING_STRING)==null ? "" : packetMap.get(HttpStatic.TRANSFER_ENCODING_STRING).toString();
//1. HTTP POST body part
if(contentType.contains(MULTIPART_FORM_DATA)){
// Part list
List<Map<String, Object>> bodyPartList = new ArrayList<Map<String, Object>>();
//boundary part
String boundary = TString.assembly("--", getPerprotyEqualValue(packetMap, HttpStatic.CONTENT_TYPE_STRING, HttpStatic.BOUNDARY_STRING));
ByteBuffer boundaryEnd = ByteBuffer.allocate(2);
while(true) {
if (!byteBufferChannel.waitData(boundary.getBytes(), timeout, contiuneRead)) {
throw new HttpParserException("Http Parser readFromChannel data error");
}
int boundaryIndex = byteBufferChannel.indexOf(boundary.getBytes(Global.CS_UTF_8));
// boundary
byteBufferChannel.shrink((boundaryIndex + boundary.length()));
// boundary
boundaryEnd.clear();
int readSize = byteBufferChannel.readHead(boundaryEnd);
totalLength = totalLength + readSize;
if(totalLength > requestMaxSize * 1024){
throw new RequestTooLarge("Request is too large: {max size: " + requestMaxSize*1024 + ", expect size: " + totalLength + "}");
}
// boundary , "--"
if (Arrays.equals(boundaryEnd.array(), "--".getBytes())) {
byteBufferChannel.shrink(2);
break;
}
byte[] boundaryMark = HttpStatic.BODY_MARK.getBytes();
if (!byteBufferChannel.waitData(boundaryMark, timeout, contiuneRead)) {
throw new HttpParserException("Http Parser readFromChannel data error");
}
int partHeadEndIndex = byteBufferChannel.indexOf(boundaryMark);
//Part
ByteBuffer partHeadBuffer = TByteBuffer.allocateDirect(partHeadEndIndex + 4);
byteBufferChannel.readHead(partHeadBuffer);
// Bytebufer
ByteBufferChannel partByteBufferChannel = new ByteBufferChannel(partHeadEndIndex + 4);
partByteBufferChannel.writeEnd(partHeadBuffer);
Map<String, Object> partMap = new HashMap<String, Object>();
ByteBuffer partByteBuffer = partByteBufferChannel.getByteBuffer();
try {
while (parseHeader(partMap, partByteBuffer, contiuneRead, timeout)) {
if (!partByteBuffer.hasRemaining() && session.isConnected()) {
return null;
}
}
} finally {
partByteBufferChannel.compact();
}
TByteBuffer.release(partHeadBuffer);
partByteBufferChannel.release();
TByteBuffer.release(partHeadBuffer);
String fileName = getPerprotyEqualValue(partMap, HttpStatic.CONTENT_DISPOSITION_STRING, "filename");
if(fileName!=null && fileName.isEmpty()){
break;
}
// Part
// index
boundaryIndex = -1;
if (fileName == null) {
if (!byteBufferChannel.waitData(boundary.getBytes(), timeout, contiuneRead)) {
throw new HttpParserException("Http Parser readFromChannel data error");
}
boundaryIndex = byteBufferChannel.indexOf(boundary.getBytes(Global.CS_UTF_8));
ByteBuffer bodyByteBuffer = ByteBuffer.allocate(boundaryIndex - 2);
byteBufferChannel.readHead(bodyByteBuffer);
partMap.put(BODY_VALUE, bodyByteBuffer.array());
}
else {
String fileExtName = TFile.getFileExtension(fileName);
fileExtName = fileExtName==null || fileExtName.equals(Global.EMPTY_STRING) ? "tmp" : fileExtName;
String localFileName =TString.assembly(UPLOAD_PATH, Global.NAME, System.currentTimeMillis(), ".", fileExtName);
boolean isFileRecvDone = false;
while (true){
int dataLength = byteBufferChannel.size();
if (byteBufferChannel.waitData(boundary.getBytes(), 0, contiuneRead)) {
isFileRecvDone = true;
}
if(!isFileRecvDone) {
if(dataLength!=0) {
byteBufferChannel.saveToFile(localFileName, dataLength);
totalLength = totalLength + dataLength;
}
continue;
} else {
boundaryIndex = byteBufferChannel.indexOf(boundary.getBytes(Global.CS_UTF_8));
int length = boundaryIndex == -1 ? byteBufferChannel.size() : (boundaryIndex - 2);
if (boundaryIndex > 0) {
byteBufferChannel.saveToFile(localFileName, length);
totalLength = totalLength + dataLength;
}
}
if(totalLength > requestMaxSize * 1024){
TFile.deleteFile(new File(localFileName));
throw new RequestTooLarge("Request is too large: {max size: " + requestMaxSize*1024 + ", expect size: " + totalLength + "}");
}
if(!isFileRecvDone){
TEnv.sleep(100);
} else {
break;
}
}
if(boundaryIndex == -1){
new File(localFileName).delete();
throw new HttpParserException("Http Parser not enough data with " + boundary);
}else{
partMap.remove(BODY_VALUE);
partMap.put(BODY_FILE, localFileName.getBytes());
}
}
//bodyPartList
bodyPartList.add(partMap);
}
// part list packetMap
packetMap.put(BODY_PARTS, bodyPartList);
}
//2. HTTP body chunked
else if(HttpStatic.CHUNKED_STRING.equals(transferEncoding)){
ByteBufferChannel chunkedByteBufferChannel = new ByteBufferChannel(3);
String chunkedLengthLine = "";
while(chunkedLengthLine!=null){
if(!byteBufferChannel.waitData("\r\n".getBytes(), timeout, contiuneRead)){
throw new HttpParserException("Http Parser readFromChannel data error");
}
chunkedLengthLine = byteBufferChannel.readLine().trim();
if("0".equals(chunkedLengthLine)){
break;
}
if(chunkedLengthLine.isEmpty()){
continue;
}
int chunkedLength = 0;
//chunked
try {
chunkedLength = Integer.parseInt(chunkedLengthLine, 16);
}catch(Exception e){
e.printStackTrace();
break;
}
if(!byteBufferChannel.waitData(chunkedLength, timeout, contiuneRead)){
throw new HttpParserException("Http Parser readFromChannel data error");
}
int readSize = 0;
if(chunkedLength > 0) {
//chunked
ByteBuffer byteBuffer = TByteBuffer.allocateDirect(chunkedLength);
readSize = byteBufferChannel.readHead(byteBuffer);
totalLength = totalLength + readSize;
if(readSize != chunkedLength){
throw new HttpParserException("Http Parser readFromChannel chunked data error");
}
chunkedByteBufferChannel.writeEnd(byteBuffer);
TByteBuffer.release(byteBuffer);
}
if(totalLength > requestMaxSize * 1024){
throw new RequestTooLarge("Request is too large: {max size: " + requestMaxSize*1024 + ", expect size: " + totalLength + "}");
}
byteBufferChannel.shrink(2);
}
byte[] value = dealBodyContent(packetMap, chunkedByteBufferChannel.array());
chunkedByteBufferChannel.release();
packetMap.put(BODY_VALUE, value);
byteBufferChannel.shrink(2);
}
//3. HTTP() Content-Length , body
else if(packetMap.containsKey(HttpStatic.CONTENT_LENGTH_STRING)){
int contentLength = Integer.parseInt(packetMap.get(HttpStatic.CONTENT_LENGTH_STRING).toString());
totalLength = totalLength + contentLength;
if(totalLength > requestMaxSize * 1024){
throw new HttpParserException("Request is too large: {max size: " + requestMaxSize*1024 + ", expect size: " + totalLength + "}");
}
if(!byteBufferChannel.waitData(contentLength, timeout, contiuneRead)){
throw new HttpParserException("Http Parser readFromChannel data error");
}
ByteBuffer byteBuffer = ByteBuffer.allocate(contentLength);
byteBufferChannel.readHead(byteBuffer);
byte[] contentBytes = byteBuffer.array();
byte[] value = dealBodyContent(packetMap, contentBytes);
packetMap.put(BODY_VALUE, value);
}
break;
}
}
return packetMap;
}
/**
* HttpRequest
* @param session socket
* @param byteBufferChannel
* @param timeOut
* @param requestMaxSize , : kb
* @return
* @throws IOException IO
*/
@SuppressWarnings("unchecked")
public static Request parseRequest(IoSession session, ByteBufferChannel byteBufferChannel, int timeOut, long requestMaxSize) throws IOException {
Request request = null;
Map<String, Object> packetMap = THREAD_PACKET_MAP.get();
packetMap = parser(session, packetMap, PARSER_TYPE_REQUEST, byteBufferChannel, timeOut, requestMaxSize);
//Map,
if(packetMap==null || packetMap.isEmpty() || byteBufferChannel.isReleased()){
return null;
}
request = THREAD_REQUEST.get();
request.clear();
Set<Entry<String, Object>> parsedItems= packetMap.entrySet();
for(Entry<String, Object> parsedPacketEntry: parsedItems) {
String key = parsedPacketEntry.getKey();
switch (key) {
case PL_METHOD:
request.protocol().setMethod(parsedPacketEntry.getValue().toString());
break;
case PL_PROTOCOL:
request.protocol().setProtocol(parsedPacketEntry.getValue().toString());
break;
case PL_QUERY_STRING:
request.protocol().setQueryString(parsedPacketEntry.getValue().toString());
break;
case PL_VERSION:
request.protocol().setVersion(parsedPacketEntry.getValue().toString());
break;
case PL_PATH:
request.protocol().setPath(parsedPacketEntry.getValue().toString());
break;
case PL_HASH:
request.setMark((Long)parsedPacketEntry.getValue());
break;
case HttpStatic.COOKIE_STRING:
List<Map<String, String>> cookieMap = (List<Map<String, String>>)packetMap.get(HttpStatic.COOKIE_STRING);
// Cookie, Cookie
for(Map<String,String> cookieMapItem : cookieMap){
Cookie cookie = Cookie.buildCookie(cookieMapItem);
request.cookies().add(cookie);
}
cookieMap.clear();
break;
case BODY_VALUE:
byte[] value = (byte[])(parsedPacketEntry.getValue());
request.body().write(value);
break;
case BODY_PARTS:
List<Map<String, Object>> parsedParts = (List<Map<String, Object>>)(parsedPacketEntry.getValue());
// part List, Part
for(Map<String, Object> parsedPartMap : parsedParts){
Part part = new Part();
// part Map, Part
for(Entry<String, Object> parsedPartMapItem : parsedPartMap.entrySet()){
// Value body
if(parsedPartMapItem.getKey().equals(BODY_VALUE)){
part.body().changeToBytes((byte[])parsedPartMapItem.getValue());
} if(parsedPartMapItem.getKey().equals(BODY_FILE)){
String filePath = new String((byte[])parsedPartMapItem.getValue());
part.body().changeToFile(new File(filePath));
} else {
// header
String partedHeaderKey = parsedPartMapItem.getKey();
String partedHeaderValue = parsedPartMapItem.getValue().toString();
part.header().put(partedHeaderKey, partedHeaderValue);
if(HttpStatic.CONTENT_DISPOSITION_STRING.equals(partedHeaderKey)){
//Content-Disposition"name=xxx",
Map<String, String> contentDispositionValue = HttpParser.getEqualMap(partedHeaderValue);
part.header().putAll(contentDispositionValue);
}
}
}
request.parts().add(part);
parsedPartMap.clear();
}
break;
default:
request.header().put(parsedPacketEntry.getKey(), parsedPacketEntry.getValue().toString());
break;
}
}
if(!packetMap.containsKey(USE_CACHE)) {
packetMap.clear();
}
return request;
}
/**
* HttpResponse
* @param session socket
* @param byteBufferChannel
* @param timeOut
* @return
* @throws IOException IO
*/
@SuppressWarnings("unchecked")
public static Response parseResponse(IoSession session, ByteBufferChannel byteBufferChannel, int timeOut) throws IOException {
Map<String, Object> packetMap = THREAD_PACKET_MAP.get();
packetMap = parser(session, packetMap, PARSER_TYPE_RESPONSE, byteBufferChannel, timeOut, -1);
packetMap.remove(PL_HASH);
//Map,
if(packetMap==null || packetMap.isEmpty() || byteBufferChannel.isReleased()){
return null;
}
Response response = THREAD_RESPONSE.get();
response.clear();
Set<Entry<String, Object>> parsedItems= packetMap.entrySet();
for(Entry<String, Object> parsedPacketEntry: parsedItems){
String key = parsedPacketEntry.getKey();
switch (key) {
case PL_PROTOCOL:
response.protocol().setProtocol(parsedPacketEntry.getValue().toString());
break;
case PL_VERSION:
response.protocol().setVersion(parsedPacketEntry.getValue().toString());
break;
case PL_STATUS:
response.protocol().setStatus(Integer.parseInt(parsedPacketEntry.getValue().toString()));
break;
case PL_STATUS_CODE:
response.protocol().setStatusCode(parsedPacketEntry.getValue().toString());
break;
case HttpStatic.COOKIE_STRING:
List<Map<String, String>> cookieMap = (List<Map<String, String>>)parsedPacketEntry.getValue();
// Cookie, Cookie
for(Map<String,String> cookieMapItem : cookieMap){
Cookie cookie = Cookie.buildCookie(cookieMapItem);
response.cookies().add(cookie);
}
break;
case BODY_VALUE:
response.body().write((byte[])parsedPacketEntry.getValue());
break;
default:
response.header().put(parsedPacketEntry.getKey(), parsedPacketEntry.getValue().toString());
break;
}
}
packetMap.clear();
return response;
}
public static void resetThreadLocal(){
THREAD_REQUEST.set(new Request());
THREAD_RESPONSE.set(new Response());
}
}
|
package edu.wpi.first.wpilibj.templates;
import edu.wpi.first.wpilibj.*;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
/**
*
* @author Roi and Simon
*/
public class RobotShoot {
private static boolean needsToBeWound;
private static boolean needsToBeUnwound;
private static boolean latched;
private static boolean windMax;
public static double speed;
public static double WIND_SPEED = .3;
public static final double UNWIND_SPEED = -.3;
private static Timer timerRelatch;
public static final int ENCODER_REVOLUTIONS = 5;
public static int revolutionsOfShooter;
private static double time;
private static final double rewindMaxRevolutions = 5000;
public static void initialize() {
time = 0;
}
/**
* It is a test method to test the shooter
*/
public static void testShooter() {
RobotShoot.automatedShoot();
}
/**
* This is an automated Shooter to be used
*/
public static void automatedShoot() {
//RobotShoot.releaseBall();
if (timerRelatch == null) {
timerRelatch = new Timer();
timerRelatch.start();
time = timerRelatch.get();
}
RobotShoot.unwindShooter();
}
/**
* This releases the ball if it is loaded, and if it is not, it displays
* that it is not.
*/
public static void releaseBall() {
if (RobotPickUp.ifLoaded() || true) { //TODO: Remove true||, and start the timer here
RobotActuators.latch.set(false);
System.out.println("Success: Ball has been shot");
} else {
SmartDashboard.putString("Error", "Ball not loaded");
//or blink a light
}
}
/**
* it gets the encoder value of the shooter wheel
*
* @returns the encoderValue
*/
private static int getEncoderValue() {
revolutionsOfShooter = RobotSensors.shooterWinchEncoder.get();
return revolutionsOfShooter;
}
/**
* This will unwind the shooter if .5 seconds have passed, and until the
* limit switch is reached or until it has exceeded the max number of
* revolutions.
*/
public static void unwindShooter() {
if (timerRelatch == null && !latched) {
needsToBeUnwound = true;
} else {
needsToBeUnwound = false;
}
}
/**
* It rewinds the shooter until the limit switch has been reached or again
* max number of revolutions
*/
public static void rewindShooter() {
if (!windMax) {
needsToBeWound = true;
} else {
needsToBeWound = false;
}
}
public static void stopShooter() {
RobotActuators.shooterWinch.set(0);
}
static int rc = 0;
/**
* This method will set the movement of the shooter winch based on two
* booleans which represent two buttons
*
* @param forward
* @param backward
*/
public static void manualWind(boolean forward, boolean backward) {
if (forward && !backward) {
speed = WIND_SPEED;
System.out.println("Wind Speed: " + WIND_SPEED);
} else if (!forward && backward) {
speed = UNWIND_SPEED;
System.out.println("Wind Speed: " + UNWIND_SPEED);
} else {
speed = 0;
}
RobotActuators.shooterWinch.set(speed);
}
/**
* This will get all of the new values that we need as well as setting the
* shooter speed
*/
public static void update() {
if (timerRelatch != null) {
double b = timerRelatch.get();
if (b - time > .5) {
timerRelatch = null;
RobotSensors.shooterWinchEncoder.reset();
unwindShooter();
}
}
if (RobotShoot.getEncoderValue() >= rewindMaxRevolutions) {
needsToBeUnwound = false;
}
if (RobotShoot.getEncoderValue() <= 0){
needsToBeWound = true;
}
if (needsToBeWound && latched) {
RobotActuators.shooterWinch.set(WIND_SPEED); //TODO: Change speed to constant value WIND_SPEED
}
if (needsToBeUnwound && !latched) {
RobotActuators.shooterWinch.set(UNWIND_SPEED); //TODO: Change speed to constant value UNWIND_SPEED
}
if (!needsToBeUnwound && latched) {
RobotShoot.rewindShooter();
}
windMax = RobotSensors.shooterLoadedLim.get(); //SHOOTER_LOADED_LIM
latched = RobotSensors.shooterAtBack.get(); //SHOOTER_LATCHED_LIM
if (latched && !windMax) {
RobotActuators.latch.set(true); //true means it goes in
}
//System.out.println("sneedsToBeUnwound: " + needsToBeUnwound);
//System.out.println("needsToBeWound: " + needsToBeWound);
//System.out.println("latched: " + latched + rc++);
//System.out.println("windMax: " + windMax + rc++);
System.out.println(RobotSensors.shooterWinchEncoder.get()); //FOR TESTING PURPOSES ONLY
}
}
//IF WE WANT A MANUAL SHOT YOU WILL NEED TO SET THE MOTOR IN TELEOP
|
package com.axelor.meta;
import static com.axelor.common.StringUtils.isBlank;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.CopyOption;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileAttribute;
import java.time.LocalDate;
import java.util.List;
import java.util.regex.Pattern;
import javax.activation.MimeType;
import javax.activation.MimeTypeParseException;
import javax.inject.Inject;
import javax.persistence.PersistenceException;
import org.apache.tika.Tika;
import com.axelor.app.AppSettings;
import com.axelor.common.StringUtils;
import com.axelor.db.EntityHelper;
import com.axelor.db.Model;
import com.axelor.db.tenants.TenantResolver;
import com.axelor.dms.db.DMSFile;
import com.axelor.dms.db.repo.DMSFileRepository;
import com.axelor.inject.Beans;
import com.axelor.meta.db.MetaAttachment;
import com.axelor.meta.db.MetaFile;
import com.axelor.meta.db.repo.MetaAttachmentRepository;
import com.axelor.meta.db.repo.MetaFileRepository;
import com.google.common.base.Preconditions;
import com.google.inject.persist.Transactional;
/**
* This class provides some helper methods to deal with files.
*
*/
public class MetaFiles {
private static final String DEFAULT_UPLOAD_PATH = "{java.io.tmpdir}/axelor/attachments";
private static final Path UPLOAD_PATH = Paths.get(AppSettings.get().get("file.upload.dir", DEFAULT_UPLOAD_PATH));
private static final String UPLOAD_NAME_PATTERN = AppSettings.get().get("file.upload.filename.pattern", "auto");
private static final String UPLOAD_NAME_PATTERN_AUTO = "auto";
private static final CopyOption[] COPY_OPTIONS = {
StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.COPY_ATTRIBUTES
};
private static final CopyOption[] MOVE_OPTIONS = {
StandardCopyOption.REPLACE_EXISTING
};
// temp clean up threshold 24 hours
private static final long TEMP_THRESHOLD = 24 * 3600 * 1000;
private static final Object lock = new Object();
private static final List<Pattern> WHITELIST_PATTERNS = AppSettings.get().getList("file.upload.whitelist.pattern", Pattern::compile);
private static final List<Pattern> BLACKLIST_PATTERNS = AppSettings.get().getList("file.upload.blacklist.pattern", Pattern::compile);
private static final List<MimeType> WHITELIST_TYPES = getMimeTypes("file.upload.whitelist.types");
private static final List<MimeType> BLACKLIST_TYPES = getMimeTypes("file.upload.blacklist.types");
private static final Tika TIKA = new Tika();
private MetaFileRepository filesRepo;
@Inject
public MetaFiles(MetaFileRepository filesRepo) {
this.filesRepo = filesRepo;
}
private static List<MimeType> getMimeTypes(String key) {
return AppSettings.get().getList(key, (s) -> {
try {
return new MimeType(s);
} catch (MimeTypeParseException e) {
throw new RuntimeException("Invalid file type: " + s + " for '" + key + "'");
}
});
}
private static Path getUploadPath() {
String tenantId = TenantResolver.currentTenantIdentifier();
if (StringUtils.isBlank(tenantId)) {
return UPLOAD_PATH;
}
return UPLOAD_PATH.resolve(tenantId);
}
private static Path getUploadPath(String fileName) {
final Path uploadPath = getUploadPath().normalize();
final Path targetPath = uploadPath.resolve(fileName).normalize();
if (targetPath.startsWith(uploadPath) && !targetPath.equals(uploadPath)) {
return targetPath;
}
throw new IllegalArgumentException("Invalid file name: " + fileName);
}
private static Path getTempPath() {
return getUploadPath("tmp");
}
private static Path getTempPath(String fileName) {
return getTempPath().resolve(fileName);
}
/**
* Get the actual storage path of the file represented by the give
* {@link MetaFile} instance.
*
* @param file
* the given {@link MetaFile} instance
* @return actual file path
*/
public static Path getPath(MetaFile file) {
Preconditions.checkNotNull(file, "file instance can't be null");
return getUploadPath(file.getFilePath());
}
/**
* Get the actual storage path of the given relative file path.
*
* @param filePath
* relative file path
* @return actual file path
*/
public static Path getPath(String filePath) {
Preconditions.checkNotNull(filePath, "file path can't be null");
return getUploadPath(filePath);
}
public static void checkPath(String filePath) {
Preconditions.checkNotNull(filePath, "file path can't be null");
boolean blocked = BLACKLIST_PATTERNS.isEmpty() ? false : BLACKLIST_PATTERNS.stream()
.map(p -> p.matcher(filePath))
.filter(m -> m.find())
.findFirst()
.isPresent();
if (blocked) {
throw new IllegalArgumentException("File name is not allowed: " + filePath);
}
boolean allowed = WHITELIST_PATTERNS.isEmpty() ? true : WHITELIST_PATTERNS.stream()
.map(p -> p.matcher(filePath))
.filter(m -> m.find())
.findFirst()
.isPresent();
if (!allowed) {
throw new IllegalArgumentException("File name is not allowed: " + filePath);
}
getUploadPath(filePath);
}
public static void checkType(String fileType) {
if (StringUtils.isBlank(fileType)) {
return;
}
final MimeType mimeType;
try {
mimeType = new MimeType(fileType);
} catch (MimeTypeParseException e) {
return;
}
boolean blocked = BLACKLIST_TYPES.isEmpty() ? false : BLACKLIST_TYPES.stream()
.filter(m -> m.match(mimeType))
.findFirst()
.isPresent();
if (blocked) {
throw new IllegalArgumentException("File type is not allowed: " + fileType);
}
boolean allowed = WHITELIST_TYPES.isEmpty() ? true : WHITELIST_TYPES.stream()
.filter(m -> m.match(mimeType))
.findFirst()
.isPresent();
if (!allowed) {
throw new IllegalArgumentException("File type is not allowed: " + fileType);
}
}
public static void checkType(File file) {
Preconditions.checkNotNull(file, "file can't be null");
String type = null;
try {
type = Files.probeContentType(file.toPath());
if (type == null) {
type = TIKA.detect(file);
}
} catch (IOException e1) {
throw new IllegalArgumentException("File is not accessible: " + file.getName());
}
checkType(type);
}
/**
* Create a temporary file under upload directory.
*
* @param prefix
* the file prefix to use
* @param suffix
* the file suffix to use
* @param attrs
* an optional list of file attributes
* @return the path to the newly created file
* @throws IOException
* if an I/O error occurs
* @see Files#createTempFile(String, String, FileAttribute...)
*/
public static Path createTempFile(String prefix, String suffix, FileAttribute<?>... attrs) throws IOException {
// make sure the upload directories exist
Path tmp = getTempPath();
Files.createDirectories(tmp);
return Files.createTempFile(tmp, prefix, suffix, attrs);
}
/**
* Find a temporary file by the given name created previously.
*
* @param name
* name of the temp file
* @return file path
*/
public static Path findTempFile(String name) {
return getTempPath(name);
}
private String getTargetName(String fileName) {
if (UPLOAD_NAME_PATTERN.equals(UPLOAD_NAME_PATTERN_AUTO)) {
return fileName;
}
LocalDate date = LocalDate.now();
String targetName = UPLOAD_NAME_PATTERN;
if (targetName.indexOf("{A}") > -1) {
targetName = targetName.replace("{A}", fileName.substring(0, 1).toUpperCase());
}
if (targetName.indexOf("{AA}") > -1) {
targetName = targetName.replace("{AA}", fileName.substring(0, Math.min(2, fileName.length())).toUpperCase());
}
if (targetName.indexOf("{AAA}") > -1) {
targetName = targetName.replace("{AAA}", fileName.substring(0, Math.min(3, fileName.length())).toUpperCase());
}
targetName = targetName.replace("{year}", "" + date.getYear());
targetName = targetName.replace("{month}", "" + date.getMonthValue());
targetName = targetName.replace("{day}", "" + date.getDayOfMonth());
targetName = targetName.replace("{name}", fileName);
return targetName;
}
private Path getNextPath(String fileName) {
synchronized (lock) {
int dotIndex = fileName.lastIndexOf('.');
int counter = 1;
String fileNameBase = fileName;
String fileNameExt = "";
if (dotIndex > -1) {
fileNameExt = fileName.substring(dotIndex);
fileNameBase = fileName.substring(0, dotIndex);
}
String targetName = getTargetName(fileName);
Path target = getUploadPath(targetName);
Path targetDir = target.getParent();
while (Files.exists(target)) {
targetName = fileNameBase + " (" + counter++ + ")" + fileNameExt;
target = targetDir.resolve(targetName);
}
return target;
}
}
/**
* Clean up obsolete temporary files from upload directory.
*
* @throws IOException
* if an I/O error occurs
*/
public void clean() throws IOException {
if (!Files.isDirectory(getTempPath())) {
return;
}
final long currentTime = System.currentTimeMillis();
Files.walkFileTree(getTempPath(), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file,
BasicFileAttributes attrs) throws IOException {
long diff = currentTime - Files.getLastModifiedTime(file).toMillis();
if (diff >= TEMP_THRESHOLD) {
Files.deleteIfExists(file);
}
return FileVisitResult.CONTINUE;
}
});
}
/**
* This method can be used to delete temporary file of an incomplete upload.
*
* @param fileId
* the upload file id
* @throws IOException
* if an I/O error occurs
*/
public void clean(String fileId) throws IOException {
Files.deleteIfExists(getTempPath(fileId));
}
/**
* Upload the given chunk of file data to a temporary file identified by the
* given file id.
*
* <p>
* Upload would restart if startOffset is 0 (zero), otherwise upload file
* size is checked against given startOffset. The startOffset must be less
* than expected fileSize.
*
* <p>
* Unlike the {@link #upload(File, MetaFile)} or {@link #upload(File)}
* methods, this method doesn't create {@link MetaFile} instance.
*
* <p>
* The temporary file generated should be manually uploaded again using
* {@link #upload(File, MetaFile)} or should be deleted using
* {@link #clean(String)} method if something went wrong.
*
* @param chunk
* the input stream
* @param startOffset
* the start offset byte position
* @param fileSize
* the actual file size
* @param fileId
* an unique upload file identifier
* @return a temporary file where upload is being saved
* @throws IOException
* if there is any error during io operations
*/
public File upload(InputStream chunk, long startOffset, long fileSize, String fileId) throws IOException {
final Path tmp = getTempPath(fileId);
if ((fileSize > -1 && startOffset > fileSize)
|| (Files.exists(tmp) && Files.size(tmp) != startOffset)
|| (!Files.exists(tmp) && startOffset > 0)) {
throw new IllegalArgumentException("Start offset is out of bound.");
}
// make sure the upload directories exist
Files.createDirectories(getTempPath());
// clean up obsolete temporary files
try {
clean();
} catch (Exception e) {
}
final File file = tmp.toFile();
final BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file, startOffset > 0));
try {
int read = 0;
long total = startOffset;
byte[] bytes = new byte[4096];
while ((read = chunk.read(bytes)) != -1) {
total += read;
if (fileSize > -1 && total > fileSize) {
throw new IllegalArgumentException("Invalid chunk, oversized upload.");
}
bos.write(bytes, 0, read);
}
bos.flush();
} finally {
bos.close();
}
return file;
}
/**
* Upload the given file to the file upload directory and create an instance
* of {@link MetaFile} for the given file.
*
* @param file
* the given file
* @return an instance of {@link MetaFile}
* @throws IOException
* if unable to read the file
* @throws PersistenceException
* if unable to save to a {@link MetaFile} instance
*/
@Transactional
public MetaFile upload(File file) throws IOException {
return upload(file, new MetaFile());
}
/**
* Upload the given {@link File} to the upload directory and link it to the
* to given {@link MetaFile}.
*
* <p>
* Any existing file linked to the given {@link MetaFile} will be removed
* from the upload directory.
* </p>
*
* @param file
* the file to upload
* @param metaFile
* the target {@link MetaFile} instance
* @return persisted {@link MetaFile} instance
* @throws IOException
* if unable to read the file
* @throws PersistenceException
* if unable to save to {@link MetaFile} instance
*/
@Transactional
public MetaFile upload(File file, MetaFile metaFile) throws IOException {
Preconditions.checkNotNull(metaFile);
Preconditions.checkNotNull(file);
final boolean update = !isBlank(metaFile.getFilePath());
final String fileName = isBlank(metaFile.getFileName()) ? file.getName() : metaFile.getFileName();
final String targetName = update ? metaFile.getFilePath() : fileName;
final Path path = getUploadPath(targetName);
final Path tmp = update ? createTempFile(null, null) : null;
if (update && Files.exists(path)) {
Files.move(path, tmp, MOVE_OPTIONS);
}
try {
final Path source = file.toPath();
final Path target = getNextPath(fileName);
// make sure the target dirs exist
Files.createDirectories(target.getParent());
// if source is in tmp directory, move it otherwise copy
if (getTempPath().equals(source.getParent())) {
Files.move(source, target, MOVE_OPTIONS);
} else {
Files.copy(source, target, COPY_OPTIONS);
}
// only update file name if not provides from meta file
if (isBlank(metaFile.getFileName())) {
metaFile.setFileName(file.getName());
}
if (isBlank(metaFile.getFileType())) {
metaFile.setFileType(Files.probeContentType(target));
}
metaFile.setFileSize(Files.size(target));
metaFile.setFilePath(getUploadPath().relativize(target).toString());
try {
return filesRepo.save(metaFile);
} catch (Exception e) {
// delete the uploaded file
Files.deleteIfExists(target);
// restore original file
if (tmp != null) {
Files.move(tmp, target, MOVE_OPTIONS);
}
throw new PersistenceException(e);
}
} finally {
if (tmp != null) {
Files.deleteIfExists(tmp);
}
}
}
/**
* Upload the given stream to the upload directory and link it to the to
* given {@link MetaFile}.
*
* <p>
* The given {@link MetaFile} instance must have fileName set to save the
* stream as file.
* </p>
*
* Upload the stream
*
* @param stream
* the stream to upload
* @param metaFile
* the {@link MetaFile} to link the uploaded file
* @return the given {@link MetaFile} instance
* @throws IOException
* if an I/O error occurs
*/
@Transactional
public MetaFile upload(InputStream stream, MetaFile metaFile) throws IOException {
Preconditions.checkNotNull(stream, "stream can't be null");
Preconditions.checkNotNull(metaFile, "meta file can't be null");
Preconditions.checkNotNull(metaFile.getFileName(), "meta file should have filename");
final Path tmp = createTempFile(null, null);
final File tmpFile = upload(stream, 0, -1, tmp.toFile().getName());
return upload(tmpFile, metaFile);
}
/**
* Upload the given stream to the upload directory.
*
* @param stream
* the stream to upload
* @param fileName
* the file name to use
* @return a new {@link MetaFile} instance
* @throws IOException
* if an I/O error occurs
*/
@Transactional
public MetaFile upload(InputStream stream, String fileName) throws IOException {
final MetaFile file = new MetaFile();
file.setFileName(fileName);
return upload(stream, file);
}
/**
* Upload the given file stream and attach it to the given record.
*
* <p>
* The attachment will be saved as {@link DMSFile} and will be visible in
* DMS user interface. Use {@link #upload(InputStream, String)} along with
* {@link #attach(MetaFile, Model)} if you don't want to show the attachment
* in DMS interface.
* </p>
*
* @param stream
* the stream to upload
* @param fileName
* the file name to use
* @param entity
* the record to attach to
* @return a {@link DMSFile} record created for the attachment
* @throws IOException
* if an I/O error occurs
*/
@Transactional
public DMSFile attach(InputStream stream, String fileName, Model entity) throws IOException {
final MetaFile metaFile = upload(stream, fileName);
return attach(metaFile, fileName, entity);
}
/**
* Attach the given file to the given record.
*
* @param metaFile
* the file to attach
* @param fileName
* alternative file name to use (optional, can be null)
* @param entity
* the record to attach to
* @return a {@link DMSFile} record created for the attachment
*/
@Transactional
public DMSFile attach(MetaFile metaFile, String fileName, Model entity) {
Preconditions.checkNotNull(metaFile);
Preconditions.checkNotNull(metaFile.getId());
Preconditions.checkNotNull(entity);
Preconditions.checkNotNull(entity.getId());
final String name = isBlank(fileName) ? metaFile.getFileName() : fileName;
final DMSFile dmsFile = new DMSFile();
final DMSFileRepository repository = Beans.get(DMSFileRepository.class);
dmsFile.setFileName(name);
dmsFile.setMetaFile(metaFile);
dmsFile.setRelatedId(entity.getId());
dmsFile.setRelatedModel(EntityHelper.getEntityClass(entity).getName());
repository.save(dmsFile);
return dmsFile;
}
/**
* Delete the given {@link DMSFile} and also delete linked file if not
* referenced by any other record.
*
* <p>
* It will attempt to clean up associated {@link MetaFile} and
* {@link MetaAttachment} records and also try to delete linked file from
* upload directory.
* </p>
*
* @param file
* the {@link DMSFile} to delete
*/
@Transactional
public void delete(DMSFile file) {
final DMSFileRepository repository = Beans.get(DMSFileRepository.class);
repository.remove(file);
}
/**
* Attach the given {@link MetaFile} to the given {@link Model} object and
* return an instance of a {@link MetaAttachment} that represents the
* attachment.
* <p>
* The {@link MetaAttachment} instance is not persisted.
* </p>
*
* @param file
* the given {@link MetaFile} instance
* @param entity
* the given {@link Model} instance
* @return a new instance of {@link MetaAttachment}
*/
public MetaAttachment attach(MetaFile file, Model entity) {
Preconditions.checkNotNull(file);
Preconditions.checkNotNull(entity);
Preconditions.checkNotNull(entity.getId());
MetaAttachment attachment = new MetaAttachment();
attachment.setMetaFile(file);
attachment.setObjectId(entity.getId());
attachment.setObjectName(EntityHelper.getEntityClass(entity).getName());
return attachment;
}
/**
* Delete the given attachment and related {@link MetaFile} instance along
* with the file content.
*
* @param attachment
* the attachment to delete
* @throws IOException
* if unable to delete file
*/
@Transactional
public void delete(MetaAttachment attachment) throws IOException {
Preconditions.checkNotNull(attachment);
Preconditions.checkNotNull(attachment.getMetaFile());
MetaAttachmentRepository attachments = Beans.get(MetaAttachmentRepository.class);
MetaFileRepository files = Beans.get(MetaFileRepository.class);
DMSFileRepository dms = Beans.get(DMSFileRepository.class);
attachments.remove(attachment);
MetaFile metaFile = attachment.getMetaFile();
long count = dms.all().filter("self.metaFile = ?", metaFile).count();
if (count == 0) {
count = attachments.all()
.filter("self.metaFile = ? and self.id != ?", metaFile, attachment.getId())
.count();
}
// only delete real file if not reference anywhere else
if (count > 0) {
return;
}
files.remove(metaFile);
Path target = getUploadPath(metaFile.getFilePath());
Files.deleteIfExists(target);
}
/**
* Delete the given {@link MetaFile} instance along with the file content.
*
* @param metaFile
* the file to delete
* @throws IOException
* if unable to delete file
*/
@Transactional
public void delete(MetaFile metaFile) throws IOException {
Preconditions.checkNotNull(metaFile);
MetaFileRepository files = Beans.get(MetaFileRepository.class);
Path target = getUploadPath(metaFile.getFilePath());
files.remove(metaFile);
Files.deleteIfExists(target);
}
public String fileTypeIcon(MetaFile file) {
String fileType = file.getFileType();
if (fileType == null) {
return "fa-file-o";
}
switch (fileType) {
case "application/msword":
case "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
case "application/vnd.oasis.opendocument.text":
return "fa-file-word-o";
case "application/vnd.ms-excel":
case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
case "application/vnd.oasis.opendocument.spreadsheet":
return "fa-file-excel-o";
case "application/vnd.ms-powerpoint":
case "application/vnd.openxmlformats-officedocument.presentationml.presentation":
case "application/vnd.oasis.opendocument.presentation":
return "fa-file-powerpoint-o";
case "application/pdf":
return "fa-file-pdf-o";
case "application/zip":
case "application/gzip":
return "fa-file-archive-o";
default:
if (fileType.startsWith("text")) return "fa-file-text-o";
if (fileType.startsWith("image")) return "fa-file-image-o";
if (fileType.startsWith("video")) return "fa-file-video-o";
}
return "fa-file-o";
}
}
|
package demo;
import org.biojava.bio.structure.Structure;
import org.biojava.bio.structure.align.util.AtomCache;
import org.biojava.bio.structure.io.FileParsingParameters;
/** Example of how to load PDB files using the AtomCache class.
*
* @author Andreas Prlic
*
*/
public class DemoAtomCache {
public static void main(String[] args){
boolean splitFileOrganisation = true;
AtomCache cache = new AtomCache("/tmp",splitFileOrganisation);
FileParsingParameters params = cache.getFileParsingParams();
params.setLoadChemCompInfo(false);
params.setAlignSeqRes(true);
params.setHeaderOnly(false);
params.setParseCAOnly(false);
params.setParseSecStruc(false);
String[] pdbIDs = new String[]{"4hhb", "1cdg","5pti","1gav", "WRONGID" };
for (String pdbID : pdbIDs){
try {
Structure s = cache.getStructure(pdbID);
if ( s == null) {
System.out.println("could not find structure " + pdbID);
continue;
}
// do something with the structure
System.out.println(s);
} catch (Exception e){
// something crazy happened...
System.err.println("Can't load structure " + pdbID + " reason: " + e.getMessage());
e.printStackTrace();
}
}
}
}
|
package runtime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map.Entry;
import java.util.Set;
import org.eclipse.jgit.api.CheckoutCommand;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.revwalk.RevCommit;
import org.hawk.core.IModelIndexer;
import org.hawk.core.VcsCommitItem;
import org.hawk.core.graph.IGraphChangeListener;
import org.hawk.core.graph.IGraphDatabase;
import org.hawk.core.graph.IGraphEdge;
import org.hawk.core.graph.IGraphNode;
import org.hawk.core.graph.IGraphTransaction;
import org.hawk.core.model.IHawkAttribute;
import org.hawk.core.model.IHawkClass;
import org.hawk.core.model.IHawkModelResource;
import org.hawk.core.model.IHawkObject;
import org.hawk.core.model.IHawkPackage;
import org.hawk.core.model.IHawkReference;
import org.hawk.core.runtime.ModelIndexerImpl;
import org.hawk.graph.internal.updater.GraphModelUpdater;
public class SyncChangeListener implements IGraphChangeListener {
private Git git;
private LinkedList<RevCommit> orderedCommits = new LinkedList<>();
ModelIndexerImpl hawk;
public SyncChangeListener(Git git,
LinkedHashMap<String, RevCommit> commits, IModelIndexer hawk) {
this.hawk = (ModelIndexerImpl) hawk;
this.git = git;
for (RevCommit c : commits.values())
orderedCommits.add(0, c);
}
@Override
public String getName() {
return null;
}
@Override
public void synchroniseStart() {
// System.out.println("a");
}
@Override
public void synchroniseEnd() {
validateChanges();
if (orderedCommits.size() > 0) {
RevCommit first = orderedCommits.getFirst();
orderedCommits.remove();
System.out.println("changing repo to commit with time: "
+ first.getCommitTime());
// update git to this revision
// Repository r = git.getRepository();
// git.
CheckoutCommand c = git.checkout();
c.setStartPoint(first);
c.setAllPaths(true);
try {
c.call();
} catch (Exception e) {
System.err.println(e.getMessage());
// e.printStackTrace();
}
} else {
System.out.println("done -- we are at latest marked commit");
}
}
@SuppressWarnings("unchecked")
private void validateChanges() {
System.err.println("validating changes...");
boolean allValid = true;
int totalResourceSizes = 0;
int totalGraphSize = 0;
// for all non-null resources
if (hawk.fileToResourceMap != null)
for (VcsCommitItem c : hawk.fileToResourceMap.keySet()) {
IHawkModelResource r = hawk.fileToResourceMap.get(c);
if (r == null) {
// file didnt get parsed so no changes are made -- any way
// verify this further?
}
else {
System.out.println("validating file " + c.getChangeType()
+ " for " + c.getPath());
totalResourceSizes += r.getAllContentsSet().size();
IGraphDatabase graph = hawk.getGraph();
try (IGraphTransaction t = graph.beginTransaction()) {
IGraphNode filenode = graph
.getFileIndex()
.get("id",
c.getCommit().getDelta()
.getRepository().getUrl()
+ GraphModelUpdater.FILEINDEX_REPO_SEPARATOR
+ c.getPath()).getSingle();
Iterable<IGraphEdge> instancesEdges = filenode
.getIncomingWithType("file");
// cache model elements in current resource
HashMap<String, IHawkObject> eobjectCache = new HashMap<>();
for (IHawkObject content : r.getAllContentsSet())
eobjectCache.put(content.getUriFragment(), content);
// go through all nodes in graph from the file the
// resource
// is in
for (IGraphEdge instanceEdge : instancesEdges) {
IGraphNode instance = instanceEdge.getStartNode();
totalGraphSize++;
IHawkObject eobject = eobjectCache.get(instance
.getProperty("id"));
// if a node cannot be found in the model cache
if (eobject == null) {
System.err
.println("error in validating: graph contains node with identifier:"
+ instance.getProperty("id")
+ " but resource does not!");
allValid = false;
} else {
eobjectCache.remove(instance.getProperty("id"));
// cache model element attributes and references
// name
HashMap<String, Object> attributeCache = new HashMap<>();
for (IHawkAttribute a : ((IHawkClass) eobject
.getType()).getAllAttributes())
if (eobject.isSet(a))
attributeCache.put(a.getName(),
eobject.get(a));
HashMap<String, Set<String>> modelreferences = new HashMap<>();
for (IHawkReference ref : ((IHawkClass) eobject
.getType()).getAllReferences()) {
if (eobject.isSet(ref)) {
Object refval = eobject.get(ref, false);
HashSet<String> vals = new HashSet<>();
if (refval instanceof Iterable<?>) {
for (Object val : ((Iterable<IHawkObject>) refval))
if (!((IHawkObject) val)
.isProxy())
vals.add(((IHawkObject) val)
.getUriFragment());
} else {
if (!((IHawkObject) refval)
.isProxy())
vals.add(((IHawkObject) refval)
.getUriFragment());
}
if (vals.size() > 0)
modelreferences.put(ref.getName(),
vals);
}
}
for (String propertykey : instance
.getPropertyKeys()) {
if (!propertykey.equals("hashCode")
&& !propertykey.equals("id")
&& !propertykey
.startsWith("_proxyRef")) {
Object dbattr = instance
.getProperty(propertykey);
Object attr = attributeCache
.get(propertykey);
if (!flattenedStringEquals(dbattr, attr)) {
allValid = false;
System.err
.println("error in validating, attribute: "
+ propertykey
+ " has values:");
String cla1 = dbattr != null ? dbattr
.getClass().toString()
: "null attr";
System.err
.println("database:\t"
+ (dbattr instanceof Object[] ? (Arrays
.asList((Object[]) dbattr))
: dbattr)
+ " JAVATYPE: "
+ cla1);
String cla2 = attr != null ? attr
.getClass().toString()
: "null attr";
System.err
.println("model:\t\t"
+ (attr instanceof Object[] ? (Arrays
.asList((Object[]) attr))
: attr)
+ " JAVATYPE: "
+ cla2);
} else
attributeCache.remove(propertykey);
}
}
if (attributeCache.size() > 0) {
System.err
.println("error in validating, the following attributes were not found in the graph node:");
System.err.println(attributeCache.keySet());
allValid = false;
}
HashMap<String, Set<String>> nodereferences = new HashMap<>();
for (IGraphEdge reference : instance
.getOutgoing()) {
if (reference.getType().equals("file")
|| reference.getType().equals(
"typeOf")
|| reference.getType().equals(
"kindOf")
|| reference.getPropertyKeys()
.contains("derived")) {
// ignore
} else {
HashSet<String> refvals = new HashSet<>();
if (nodereferences
.containsKey(reference
.getType())) {
refvals.addAll(nodereferences
.get(reference.getType()));
}
refvals.add(reference.getEndNode()
.getProperty("id").toString());
nodereferences.put(reference.getType(),
refvals);
}
}
// compare model and graph reference maps
Iterator<Entry<String, Set<String>>> rci = modelreferences
.entrySet().iterator();
while (rci.hasNext()) {
Entry<String, Set<String>> modelRef = rci
.next();
String modelRefName = modelRef.getKey();
if (!nodereferences
.containsKey(modelRefName)) {
System.err
.println("error in validating: reference "
+ modelRefName
+ " had targets in the model but none in the graph: ");
System.err.println(modelRef.getValue());
allValid = false;
} else {
Set<String> noderefvalues = new HashSet<>();
noderefvalues.addAll(nodereferences
.get(modelRefName));
Set<String> modelrefvalues = new HashSet<>();
modelrefvalues.addAll(modelreferences
.get(modelRefName));
Set<String> noderefvaluesclone = new HashSet<>();
noderefvaluesclone
.addAll(nodereferences
.get(modelRefName));
noderefvaluesclone
.removeAll(modelrefvalues);
Set<String> modelrefvaluesclone = new HashSet<>();
modelrefvaluesclone
.addAll(modelreferences
.get(modelRefName));
modelrefvaluesclone
.removeAll(noderefvalues);
if (noderefvaluesclone.size() > 0) {
System.err
.println("error in validating: reference "
+ modelRefName);
System.err
.println(noderefvaluesclone);
System.err
.println("the above ids were found in the graph but not the model");
allValid = false;
}
if (modelrefvaluesclone.size() > 0) {
System.err
.println("error in validating: reference "
+ modelRefName);
System.err
.println(modelrefvaluesclone);
System.err
.println("the above ids were found in the model but not the graph");
allValid = false;
}
nodereferences.remove(modelRefName);
// rci.remove();
}
}
if (nodereferences.size() > 0) {
System.err
.println("error in validating: references "
+ nodereferences.keySet()
+ " had targets in the graph but not in the model: ");
System.err.println(nodereferences);
allValid = false;
}
}
}
// if there are model elements not found in nodes
if (eobjectCache.size() > 0) {
System.err
.println("error in validating: the following objects were not found in the graph:");
System.err.println(eobjectCache.keySet());
allValid = false;
}
t.success();
} catch (Exception e) {
System.err
.println("syncChangeListener transaction error:");
e.printStackTrace();
}
}
}
else
System.err
.println("filetoresourcemap was empty -- maybe a metamodel addition happened?");
if (hawk.deleteditems != null)
for (@SuppressWarnings("unused")
VcsCommitItem c : hawk.deleteditems) {
// any other check needed other than totalsize match?
}
else
System.err
.println("deleteditems was empty -- maybe a metamodel addition happened?");
System.err.println("changed resource size: " + totalResourceSizes);
System.err.println("relevant graph size: " + totalGraphSize);
if (totalGraphSize != totalResourceSizes)
allValid = false;
System.err.println("validated changes..." + allValid);
}
private boolean flattenedStringEquals(Object dbattr, Object attr) {
String newdbattr = dbattr == null ? "null" : dbattr.toString();
if (dbattr instanceof int[])
newdbattr = Arrays.toString((int[]) dbattr);
else if (dbattr instanceof long[])
newdbattr = Arrays.toString((long[]) dbattr);
else if (dbattr instanceof String[])
newdbattr = Arrays.toString((String[]) dbattr);
else if (dbattr instanceof boolean[])
newdbattr = Arrays.toString((boolean[]) dbattr);
else if (dbattr instanceof Object[])
newdbattr = Arrays.toString((Object[]) dbattr);
String newattr = attr == null ? "null" : attr.toString();
if (attr instanceof int[])
newattr = Arrays.toString((int[]) attr);
else if (attr instanceof long[])
newattr = Arrays.toString((long[]) attr);
else if (attr instanceof String[])
newattr = Arrays.toString((String[]) attr);
else if (attr instanceof boolean[])
newattr = Arrays.toString((boolean[]) attr);
else if (attr instanceof Object[])
newattr = Arrays.toString((Object[]) attr);
return newdbattr.equals(newattr);
}
@Override
public void changeStart() {
}
@Override
public void changeSuccess() {
}
@Override
public void changeFailure() {
}
@Override
public void metamodelAddition(IHawkPackage pkg, IGraphNode pkgNode) {
}
@Override
public void classAddition(IHawkClass cls, IGraphNode clsNode) {
}
@Override
public void fileAddition(VcsCommitItem s, IGraphNode fileNode) {
}
@Override
public void fileRemoval(VcsCommitItem s, IGraphNode fileNode) {
}
@Override
public void modelElementAddition(VcsCommitItem s, IHawkObject element,
IGraphNode elementNode, boolean isTransient) {
}
@Override
public void modelElementRemoval(VcsCommitItem s, IGraphNode elementNode,
boolean isTransient) {
}
@Override
public void modelElementAttributeUpdate(VcsCommitItem s,
IHawkObject eObject, String attrName, Object oldValue,
Object newValue, IGraphNode elementNode, boolean isTransient) {
}
@Override
public void modelElementAttributeRemoval(VcsCommitItem s,
IHawkObject eObject, String attrName, IGraphNode elementNode,
boolean isTransient) {
}
@Override
public void referenceAddition(VcsCommitItem s, IGraphNode source,
IGraphNode destination, String edgelabel, boolean isTransient) {
}
@Override
public void referenceRemoval(VcsCommitItem s, IGraphNode source,
IGraphNode destination, String edgelabel, boolean isTransient) {
}
}
|
/*
* $Log: IbisLocalSender.java,v $
* Revision 1.3 2005-08-30 16:02:28 europe\L190409
* made parameterized version
*
* Revision 1.2 2005/08/24 15:53:28 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* improved error message for configuration exception
*
* Revision 1.1 2004/08/09 13:50:57 Gerrit van Brakel <gerrit.van.brakel@ibissource.org>
* first version
*
*/
package nl.nn.adapterframework.pipes;
import nl.nn.adapterframework.configuration.ConfigurationException;
import nl.nn.adapterframework.core.ListenerException;
import nl.nn.adapterframework.core.ParameterException;
import nl.nn.adapterframework.core.SenderException;
import nl.nn.adapterframework.core.SenderWithParametersBase;
import nl.nn.adapterframework.core.TimeOutException;
import nl.nn.adapterframework.parameters.ParameterResolutionContext;
import nl.nn.adapterframework.receivers.ServiceDispatcher;
import org.apache.commons.lang.StringUtils;
import java.util.HashMap;
/**
* Posts a message to another IBIS-adapter in the same JVM.
*
* <p><b>Configuration:</b>
* <table border="1">
* <tr><th>attributes</th><th>description</th><th>default</th></tr>
* <tr><td>classname</td><td>nl.nn.adapterframework.pipes.IbisLocalSender</td><td> </td></tr>
* <tr><td>{@link #setName(String) name}</td> <td>name of the sender</td><td> </td></tr>
* <tr><td>{@link #setServiceName(String) serviceName}</td><td>Name of the WebServiceListener or JavaListener that should be called</td><td> </td></tr>
* </table>
* </p>
* Any parameters are copied to the PipeLineSession of the service called.
*
* @author Gerrit van Brakel
* @since 4.2
*/
public class IbisLocalSender extends SenderWithParametersBase {
public static final String version="$RCSfile: IbisLocalSender.java,v $ $Revision: 1.3 $ $Date: 2005-08-30 16:02:28 $";
private String name;
private String serviceName;
public void configure() throws ConfigurationException {
if (StringUtils.isEmpty(getServiceName())) {
throw new ConfigurationException(getLogPrefix()+"has no serviceName specified");
}
}
public void open() {
}
public void close() {
}
public boolean isSynchronous() {
return true;
}
public String sendMessage(String correlationID, String message, ParameterResolutionContext prc) throws SenderException, TimeOutException {
HashMap context = null;
if (paramList!=null) {
try {
context = prc.getValueMap(paramList);
} catch (ParameterException e) {
throw new SenderException(getLogPrefix()+"exception evaluating parameters",e);
}
}
try {
return ServiceDispatcher.getInstance().dispatchRequestWithExceptions(getServiceName(), correlationID, message, context);
} catch (ListenerException e) {
throw new SenderException(getLogPrefix()+"exception calling service ["+getServiceName()+"]",e);
}
}
public void setName(String name) {
this.name=name;
}
public String getName() {
return name;
}
/**
* @param serviceName under which the JavaListener or WebServiceListener is registered
*/
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
public String getServiceName() {
return serviceName;
}
}
|
package org.unitime.timetable.model;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.Vector;
import org.hibernate.Query;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.unitime.commons.User;
import org.unitime.timetable.model.base.BaseTimetableManager;
import org.unitime.timetable.model.dao.TimetableManagerDAO;
import org.unitime.timetable.util.Constants;
public class TimetableManager extends BaseTimetableManager implements Comparable {
private static final long serialVersionUID = 1L;
/*[CONSTRUCTOR MARKER BEGIN]*/
public TimetableManager () {
super();
}
/**
* Constructor for primary key
*/
public TimetableManager (java.lang.Long uniqueId) {
super(uniqueId);
}
/*[CONSTRUCTOR MARKER END]*/
public static TimetableManager findByExternalId(String externalId){
if (externalId == null || externalId.length() == 0){
return(null);
}
TimetableManagerDAO tmDao = new TimetableManagerDAO();
List mgrs = tmDao.getSession().createCriteria(TimetableManager.class)
.add(Restrictions.eq("externalUniqueId", externalId))
.setCacheable(true).list();
if(mgrs != null && mgrs.size() == 1){
return((TimetableManager) mgrs.get(0));
} else
return (null);
}
public static TimetableManager getWithUniqueId(Long uniqueId){
TimetableManagerDAO tmDao = new TimetableManagerDAO();
return(tmDao.get(uniqueId));
}
public static TimetableManager getManager(User user){
if (user==null) return null;
String idString = (String)user.getAttribute(Constants.TMTBL_MGR_ID_ATTR_NAME);
if (idString != null && idString.length() > 0){
return(getWithUniqueId(new Long(idString)));
} else {
return(findByExternalId(user.getId()));
}
}
public static Set getSubjectAreas(User user) throws Exception {
Set saList = new TreeSet();
Session session = Session.getCurrentAcadSession(user);
if (user.isAdmin() || Roles.VIEW_ALL_ROLE.equals(user.getCurrentRole()) || Roles.EXAM_MGR_ROLE.equals(user.getCurrentRole())){
return(session.getSubjectAreas());
}
TimetableManager tm = TimetableManager.getManager(user);
if (tm != null && tm.getDepartments() != null){
Department d = null;
for (Iterator it = tm.departmentsForSession(session.getUniqueId()).iterator(); it.hasNext();){
d = (Department) it.next();
if (d.isExternalManager().booleanValue()){
return(session.getSubjectAreas());
} else {
saList.addAll(d.getSubjectAreas());
}
}
}
return saList;
}
public boolean isExternalManager(){
boolean isExternal = false;
Department d = null;
for(Iterator it = this.getDepartments().iterator(); it.hasNext(); ){
d = (Department) it.next();
if (d.isExternalManager().booleanValue()){
isExternal = true;
}
}
return(isExternal);
}
public Set departmentsForSession(Long sessionId){
HashSet l = new HashSet();
if (this.getDepartments() != null){
Department d = null;
for (Iterator it = this.getDepartments().iterator(); it.hasNext();){
d = (Department) it.next();
if (d.getSessionId().equals(sessionId)){
l.add(d);
}
}
}
return(l);
}
public Set sessionsCanManage(){
TreeSet sessions = new TreeSet();
Department dept = null;
for(Iterator it = getDepartments().iterator(); it.hasNext();){
dept = (Department) it.next();
sessions.add(dept.getSession());
}
return(sessions);
}
public String getName() {
return (getLastName()==null?"":getLastName()+", ")+
(getFirstName()==null?"":getFirstName())+
(getMiddleName()==null?"": " " + getMiddleName());
}
public boolean canAudit(Session session, User user) {
if (user.isAdmin()) return true;
if (user.getCurrentRole().equals(Roles.VIEW_ALL_ROLE)) return false;
if (user.getCurrentRole().equals(Roles.EXAM_MGR_ROLE)) return false;
for (Iterator i=getSolverGroups().iterator();i.hasNext();) {
SolverGroup solverGroup = (SolverGroup)i.next();
if (!solverGroup.getSession().equals(session)) continue;
if (solverGroup.canAudit()) return true;
}
return false;
}
public boolean canSeeTimetable(Session session, User user) {
if (user.isAdmin()) return true;
if (user.getCurrentRole().equals(Roles.VIEW_ALL_ROLE)) return true;
if (user.getCurrentRole().equals(Roles.EXAM_MGR_ROLE)) return true;
if (canDoTimetable(session, user)) return true;
for (Iterator i=getDepartments().iterator();i.hasNext();) {
Department department = (Department)i.next();
if (!department.getSession().equals(session)) continue;
if (department.getSolverGroup()!=null && !department.getSolverGroup().getSolutions().isEmpty()) return true;
}
for (Iterator i=Department.findAllExternal(session.getUniqueId()).iterator();i.hasNext();) {
Department department = (Department)i.next();
if (!department.getSession().equals(session)) continue;
if (department.getSolverGroup()!=null && department.getSolverGroup().getCommittedSolution()!=null) return true;
}
return false;
}
public boolean canDoTimetable(Session session, User user) {
if (user.isAdmin()) return true;
if (user.getCurrentRole().equals(Roles.VIEW_ALL_ROLE)) return false;
if (user.getCurrentRole().equals(Roles.EXAM_MGR_ROLE)) return false;
for (Iterator i=getSolverGroups().iterator();i.hasNext();) {
SolverGroup solverGroup = (SolverGroup)i.next();
if (!solverGroup.getSession().equals(session)) continue;
if (solverGroup.canTimetable()) return true;
}
return false;
}
public boolean canEditExams(Session session, User user) {
//admin
if (Roles.ADMIN_ROLE.equals(user.getCurrentRole()))
return true;
//timetable manager
if (Roles.DEPT_SCHED_MGR_ROLE.equals(user.getCurrentRole()))
return session.getStatusType().canExamEdit();
//exam manager
if (Roles.EXAM_MGR_ROLE.equals(user.getCurrentRole()))
return session.getStatusType().canExamTimetable();
return false;
}
public boolean canSeeCourses(Session session, User user) {
//admin or exam manager
if (Roles.ADMIN_ROLE.equals(user.getCurrentRole()) || Roles.VIEW_ALL_ROLE.equals(user.getCurrentRole()) || Roles.EXAM_MGR_ROLE.equals(user.getCurrentRole())) return true;
if (Roles.DEPT_SCHED_MGR_ROLE.equals(user.getCurrentRole())) {
for (Iterator i=getDepartments().iterator();i.hasNext();) {
Department d = (Department)i.next();
if (!d.getSession().equals(session)) continue;
if (d.isExternalManager() && d.effectiveStatusType().canManagerView()) return true;
if (!d.isExternalManager() && d.effectiveStatusType().canOwnerView()) return true;
}
}
return false;
}
public boolean canAddCourses(Session session, User user) {
if (Roles.ADMIN_ROLE.equals(user.getCurrentRole())) return true;
if (Roles.DEPT_SCHED_MGR_ROLE.equals(user.getCurrentRole())) {
for (Iterator i=getDepartments().iterator();i.hasNext();) {
Department d = (Department)i.next();
if (!d.getSession().equals(session)) continue;
if (d.isExternalManager() && d.effectiveStatusType().canManagerEdit()) return true;
if (!d.isExternalManager() && d.effectiveStatusType().canOwnerEdit()) return true;
}
}
return false;
}
public boolean canSeeExams(Session session, User user) {
//can edit -> can view
if (canEditExams(session, user)) return true;
//admin or exam manager
if (Roles.ADMIN_ROLE.equals(user.getCurrentRole()) || Roles.EXAM_MGR_ROLE.equals(user.getCurrentRole()))
return true;
//timetable manager or view all
if (Roles.DEPT_SCHED_MGR_ROLE.equals(user.getCurrentRole()) || Roles.VIEW_ALL_ROLE.equals(user.getCurrentRole()))
return session.getStatusType().canExamView();
return false;
}
public boolean canTimetableExams(Session session, User user) {
if (Roles.ADMIN_ROLE.equals(user.getCurrentRole()))
return true;
if (Roles.EXAM_MGR_ROLE.equals(user.getCurrentRole()))
return session.getStatusType().canExamTimetable();
return false;
}
public boolean canSectionStudents(Session session, User user) {
if (Roles.ADMIN_ROLE.equals(user.getCurrentRole()))
return true;
return false;
}
public boolean hasASolverGroup(Session session, User user) {
if (user.isAdmin() || user.getCurrentRole().equals(Roles.VIEW_ALL_ROLE) || user.getCurrentRole().equals(Roles.EXAM_MGR_ROLE)) {
return !SolverGroup.findBySessionId(session.getUniqueId()).isEmpty();
} else {
return !getSolverGroups(session).isEmpty();
}
}
//needs to be implemented
public static boolean canSeeEvents (User user) {
for (RoomType roomType : RoomType.findAll()) {
if (roomType.countManagableRooms()>0) return true;
}
return false;
}
public Collection getClasses(Session session) {
Vector classes = new Vector();
for (Iterator i=departmentsForSession(session.getUniqueId()).iterator();i.hasNext();) {
Department d = (Department)i.next();
classes.addAll(d.getClasses());
}
return classes;
}
public Collection getNotAssignedClasses(Solution solution) {
Vector classes = new Vector();
for (Iterator i=departmentsForSession(solution.getSession().getUniqueId()).iterator();i.hasNext();) {
Department d = (Department)i.next();
classes.addAll(d.getNotAssignedClasses(solution));
}
return classes;
}
public Set getDistributionPreferences(Session session) {
TreeSet prefs = new TreeSet();
for (Iterator i=departmentsForSession(session.getUniqueId()).iterator();i.hasNext();) {
Department d = (Department)i.next();
prefs.addAll(d.getDistributionPreferences());
}
return prefs;
}
public Set getSolverGroups(Session session) {
TreeSet groups = new TreeSet();
for (Iterator i=getSolverGroups().iterator();i.hasNext();) {
SolverGroup g = (SolverGroup)i.next();
if (session.equals(g.getSession())) groups.add(g);
}
return groups;
}
public String getShortName() {
StringBuffer sb = new StringBuffer();
if (getFirstName()!=null && getFirstName().length()>0) {
sb.append(getFirstName().substring(0,1).toUpperCase());
sb.append(". ");
}
if (getLastName()!=null && getLastName().length()>0) {
sb.append(getLastName().substring(0,1).toUpperCase());
sb.append(getLastName().substring(1,Math.min(10,getLastName().length())).toLowerCase().trim());
}
return sb.toString();
}
public int compareTo(Object o) {
if (o==null || !(o instanceof TimetableManager)) return -1;
TimetableManager m = (TimetableManager)o;
int cmp = getName().compareTo(m.getName());
if (cmp!=0) return cmp;
return getUniqueId().compareTo(m.getUniqueId());
}
public String toString() { return getName(); }
/** Request attribute name for manager list **/
public static String MGR_LIST_ATTR_NAME = "managerList";
/**
* Retrieves all consent types in the database
* ordered by column last name, first name
* @return Vector of TimetableManager objects
*/
public static synchronized Vector getManagerList() {
TimetableManagerDAO tdao = new TimetableManagerDAO();
List l = tdao.findAll(Order.asc("lastName"), Order.asc("firstName"));
if (l!=null)
return new Vector(l);
return null;
}
public Roles getPrimaryRole() {
for (Iterator i=getManagerRoles().iterator();i.hasNext();) {
ManagerRole role = (ManagerRole)i.next();
if (role.isPrimary()) return role.getRole();
}
if (getManagerRoles().size()==1) return ((ManagerRole)getManagerRoles().iterator().next()).getRole();
return null;
}
public Vector<RoomType> findDefaultEventManagerRoomTimesFor(String currentRole, Long acadSessionId){
Vector<RoomType> roomTypes = new Vector<RoomType>();
if (Roles.EVENT_MGR_ROLE.equals(currentRole)){
StringBuilder sb = new StringBuilder();
sb.append("select distinct rt from TimetableManager tm inner join tm.departments d")
.append(" inner join d.roomDepts rd inner join rd.room.roomType rt")
.append(" where tm.uniqueId = :managerId ")
.append(" and rd.control = true ")
.append(" and 1 = (select rto.status from RoomTypeOption rto where rto.session.uniqueId = :sessionId and rto.roomType.uniqueId = rt.uniqueId )");
Query query = TimetableManagerDAO.getInstance().getSession()
.createQuery(sb.toString())
.setLong("managerId", getUniqueId().longValue())
.setLong("sessionId", acadSessionId.longValue());
for(Iterator it = query.iterate(); it.hasNext();){
roomTypes.add((RoomType) it.next());
}
}
return(roomTypes);
}
}
|
package org.openecard.addon;
import org.openecard.common.util.ThreadManager;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.Collection;
import java.util.Set;
import javax.annotation.Nonnull;
import org.openecard.addon.bind.AppExtensionAction;
import org.openecard.addon.bind.AppExtensionActionProxy;
import org.openecard.addon.bind.AppExtensionException;
import org.openecard.addon.bind.AppPluginAction;
import org.openecard.addon.bind.AppPluginActionProxy;
import org.openecard.addon.ifd.IFDProtocol;
import org.openecard.addon.ifd.IFDProtocolProxy;
import org.openecard.addon.manifest.AddonSpecification;
import org.openecard.addon.manifest.AppExtensionSpecification;
import org.openecard.addon.manifest.AppPluginSpecification;
import org.openecard.addon.manifest.ProtocolPluginSpecification;
import org.openecard.addon.sal.SALProtocol;
import org.openecard.addon.sal.SALProtocolProxy;
import org.openecard.common.sal.state.CardStateMap;
import org.openecard.common.util.FacadeInvocationHandler;
import org.openecard.common.interfaces.Environment;
import org.openecard.gui.UserConsent;
import org.openecard.gui.definition.ViewController;
import org.openecard.ws.marshal.WSMarshallerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Implementation of a AddonManager.
*
* The AddonManager takes care for the management of the add-on. This covers the initialization startup, registering of
* new add-ons, unloading of add-ons on shut down and removal and the uninstalling of an add-on. Furthermore the
* AddonManager provides methods to retrieve specific parts of a add-on.
*
* @author Tobias Wich
* @author Dirk Petrautzki
* @author Hans-Martin Haase
*/
public class AddonManager {
private static final Logger LOG = LoggerFactory.getLogger(AddonManager.class);
private final CombiningRegistry registry;
private final AddonRegistry protectedRegistry;
private final Environment env;
private final UserConsent userConsent;
private final CardStateMap cardStates;
private final EventHandler eventHandler;
private final ViewController viewController;
private final ThreadManager<ActionBackgroundTaskKey> backgroundActionManager;
// TODO: rework cache to have borrow and return semantic
private final Cache cache = new Cache();
/**
* Creates a new AddonManager.
*
* @param env
* @param userConsent
* @param cardStates
* @param view
* @param registry
* @throws WSMarshallerException
*/
public AddonManager(Environment env, UserConsent userConsent, CardStateMap cardStates, ViewController view,
CombiningRegistry registry) throws WSMarshallerException {
if (registry == null) {
this.registry = new ClasspathAndFileRegistry(this);
} else {
this.registry = registry;
}
this.protectedRegistry = getProtectedRegistry(this.registry);
this.env = env;
this.userConsent = userConsent;
this.cardStates = cardStates;
this.eventHandler = new EventHandler();
this.env.getEventDispatcher().add(eventHandler);
this.viewController = view;
this.backgroundActionManager = new ThreadManager<>("BackgroundActions");
new Thread(() -> {
loadLoadOnStartAddons();
runAddonsBackgroundJobs();
}, "Init-Addons").start();
}
public AddonManager(Environment env, UserConsent userConsent, CardStateMap cardStates, ViewController view)
throws WSMarshallerException {
this(env, userConsent, cardStates, view, null);
}
/**
* Load all addons which contain an loadOnStart = true.
*
* @throws WSMarshallerException
*/
private void loadLoadOnStartAddons() {
// load plugins which have an loadOnStartup = true
Set<AddonSpecification> specs = protectedRegistry.listAddons();
for (AddonSpecification addonSpec : specs) {
loadLoadOnStartupActions(addonSpec);
}
}
private void runAddonsBackgroundJobs() {
Set<AddonSpecification> specs = protectedRegistry.listAddons();
for (AddonSpecification addonSpec : specs) {
runBackgroundJobsAction(addonSpec);
}
}
/**
* Load a single addon which contains a LoadOnStartup = true.
*
* @param addonSpec The {@link AddonSpecification} of the addon.
*/
protected void loadLoadOnStartupActions(AddonSpecification addonSpec) {
if (!addonSpec.getApplicationActions().isEmpty()) {
for (AppExtensionSpecification appExSpec : addonSpec.getApplicationActions()) {
if (appExSpec.isLoadOnStartup()) {
getAppExtensionAction(addonSpec, appExSpec.getId());
}
}
}
if (!addonSpec.getBindingActions().isEmpty()) {
for (AppPluginSpecification appPlugSpec : addonSpec.getBindingActions()) {
if (appPlugSpec.isLoadOnStartup()) {
getAppPluginAction(addonSpec, appPlugSpec.getResourceName());
}
}
}
if (!addonSpec.getIfdActions().isEmpty()) {
for (ProtocolPluginSpecification protPlugSpec : addonSpec.getIfdActions()) {
if (protPlugSpec.isLoadOnStartup()) {
getIFDProtocol(addonSpec, protPlugSpec.getUri());
}
}
}
if (!addonSpec.getSalActions().isEmpty()) {
for (ProtocolPluginSpecification protPlugSpec : addonSpec.getSalActions()) {
if (protPlugSpec.isLoadOnStartup()) {
getSALProtocol(addonSpec, protPlugSpec.getUri());
}
}
}
}
protected void runBackgroundJobsAction(AddonSpecification addonSpec) {
for (AppExtensionSpecification appExSpec : addonSpec.getApplicationActions()) {
if (appExSpec.isBackgroundJob()) {
ActionBackgroundTaskKey key = new ActionBackgroundTaskKey(addonSpec, appExSpec);
AppExtensionAction action = getAppExtensionAction(addonSpec, appExSpec.getId());
if (action != null) {
LOG.info("Starting action ({}) as background job.", key.toString());
backgroundActionManager.submit(key, new Runnable() {
@Override
public void run() {
boolean autoRestart = appExSpec.isAutoRestartBackgroundJob();
boolean runAgain = true;
while (runAgain) {
// set the flag, so we run again if autoRestart is set
runAgain = autoRestart;
try {
action.execute();
} catch (AppExtensionException ex) {
LOG.warn("Failed to execute action.", ex);
}
}
}
});
} else {
LOG.error("Failed to load action ({}) for background execution.", key.toString());
}
}
}
}
/**
* Unload all add-ons.
*/
private void unloadAllAddons() {
Set<AddonSpecification> addons = protectedRegistry.listInstalledAddons();
for (AddonSpecification addonSpec : addons) {
unloadAddon(addonSpec);
}
}
/**
* Unload all actions and protocols of a specific add-on.
*
* @param addonSpec The {@link AddonSpecification} of the add-on to unload.
*/
protected void unloadAddon(AddonSpecification addonSpec) {
// stop background jobs
for (AppExtensionSpecification appExSpec : addonSpec.getApplicationActions()) {
ActionBackgroundTaskKey key = new ActionBackgroundTaskKey(addonSpec, appExSpec);
try {
backgroundActionManager.stopThread(key);
} catch (InterruptedException ex) {
LOG.error(String.format("Failed to stop background action (%s).", key), ex);
}
}
Collection<? extends LifecycleTrait> actionsAndProtocols = cache.getAllAddonData(addonSpec);
for (LifecycleTrait obj : actionsAndProtocols) {
obj.destroy(true);
}
cache.removeCompleteAddonCache(addonSpec);
}
/**
* This method returns an instance of the given registry where only the interface methods are accessible.
*
* @param registry Unprotected registry instance.
* @return Protected registry instance.
*/
private static AddonRegistry getProtectedRegistry(AddonRegistry registry) {
if (registry != null) {
ClassLoader cl = AddonManager.class.getClassLoader();
Class<?>[] interfaces = new Class<?>[] { AddonRegistry.class };
InvocationHandler handler = new FacadeInvocationHandler(registry);
Object o = Proxy.newProxyInstance(cl, interfaces, handler);
return (AddonRegistry) o;
}
return null;
}
/**
* Get the CombiningRigistry.
*
* @return A {@link AddonRegistry} object which provides access just to the interface methods of the
* {@link ClasspathAndFileRegistry}.
*/
public AddonRegistry getRegistry() {
return protectedRegistry;
}
/**
* Get the ClasspathRegistry.
*
* @return A {@link AddonRegistry} object which provides access just to the interface methods of the
* {@link ClasspathRegistry}.
*/
public AddonRegistry getBuiltinRegistry() {
return getProtectedRegistry(registry.getClasspathRegistry());
}
/**
* Get the FileRegistry.
*
* @return A {@link AddonRegistry} object which provides access just to the interface methods of the
* {@link FileRegistry}.
*/
public AddonRegistry getExternalRegistry() {
return getProtectedRegistry(registry.getFileRegistry());
}
/**
* Register a new add-on which is located in the class path.
*
* @param desc {@link AddonSpecification} of the add-on which shall be registered.
*/
public void registerClasspathAddon(AddonSpecification desc) {
// TODO: protect this method from the sandbox
this.registry.getClasspathRegistry().register(desc);
}
/**
* Get a specific IFDProtocol.
*
* @param addonSpec {@link AddonSpecification} which contains the description of the {@link IFDProtocol}.
* @param uri The {@link ProtocolPluginSpecification#uri} to identify the requested IFDProtocol.
* @return The requested IFDProtocol object or NULL if no such object was found.
*/
public IFDProtocol getIFDProtocol(@Nonnull AddonSpecification addonSpec, @Nonnull String uri) {
IFDProtocol ifdProt = cache.getIFDProtocol(addonSpec, uri);
// TODO: find a better way to deal with the reuse of protocol plugins
// if (ifdProt != null) {
// // protocol cached so return it
// return ifdProt;
ProtocolPluginSpecification protoSpec = addonSpec.searchIFDActionByURI(uri);
if (protoSpec == null) {
LOG.error("Requested IFD Protocol {} does not exist in Add-on {}.", uri, addonSpec.getId());
} else {
String className = protoSpec.getClassName();
try {
ClassLoader cl = registry.downloadAddon(addonSpec);
IFDProtocolProxy protoFactory = new IFDProtocolProxy(className, cl);
Context aCtx = createContext(addonSpec);
protoFactory.init(aCtx);
cache.addIFDProtocol(addonSpec, uri, protoFactory);
return protoFactory;
} catch (ActionInitializationException e) {
LOG.error("Initialization of IFD Protocol failed", e);
} catch (AddonException ex) {
LOG.error("Failed to download Add-on.", ex);
}
}
return null;
}
public void returnIFDProtocol(IFDProtocol obj) {
obj.destroy(false);
}
/**
* Get a specific SALProtocol.
*
* @param addonSpec {@link AddonSpecification} which contains the description of the {@link SALProtocol}.
* @param uri The {@link ProtocolPluginSpecification#uri} to identify the requested SALProtocol.
* @return The requested SALProtocol object or NULL if no such object was found.
*/
public SALProtocol getSALProtocol(@Nonnull AddonSpecification addonSpec, @Nonnull String uri) {
SALProtocol salProt = cache.getSALProtocol(addonSpec, uri);
// TODO: find a better way to deal with the reuse of protocol plugins
// if (salProt != null) {
// // protocol cached so return it
// return salProt;
ProtocolPluginSpecification protoSpec = addonSpec.searchSALActionByURI(uri);
if (protoSpec == null) {
LOG.error("Requested SAL Protocol {} does not exist in Add-on {}.", uri, addonSpec.getId());
} else {
String className = protoSpec.getClassName();
try {
ClassLoader cl = registry.downloadAddon(addonSpec);
SALProtocolProxy protoFactory = new SALProtocolProxy(className, cl);
Context aCtx = createContext(addonSpec);
protoFactory.init(aCtx);
cache.addSALProtocol(addonSpec, uri, protoFactory);
return protoFactory;
} catch (ActionInitializationException e) {
LOG.error("Initialization of SAL Protocol failed", e);
} catch (AddonException ex) {
LOG.error("Failed to download Add-on.", ex);
}
}
return null;
}
public void returnSALProtocol(SALProtocol obj, boolean force) {
obj.destroy(force);
}
/**
* Get a specific AppExtensionAction.
*
* @param addonSpec {@link AddonSpecification} which contains the description of the {@link AppExtensionAction}.
* @param actionId The {@link AppExtensionSpecification#id} to identify the requested AppExtensionAction.
* @return The AppExtensionAction which corresponds the given {@code actionId} or NULL if no AppExtensionAction with
* the given {@code actionId} exists.
*/
public AppExtensionAction getAppExtensionAction(@Nonnull AddonSpecification addonSpec, @Nonnull String actionId) {
// get extension from cache
AppExtensionAction appExtAction = cache.getAppExtensionAction(addonSpec, actionId);
// TODO: find a better way to deal with the reuse of protocol plugins
// if (appExtAction != null) {
// // AppExtensionAction cached so return it
// return appExtAction;
AppExtensionSpecification protoSpec = addonSpec.searchByActionId(actionId);
if (protoSpec == null) {
LOG.error("Requested Extension {} does not exist in Add-on {}.", actionId, addonSpec.getId());
} else {
String className = protoSpec.getClassName();
try {
ClassLoader cl = registry.downloadAddon(addonSpec);
AppExtensionActionProxy protoFactory = new AppExtensionActionProxy(className, cl);
Context aCtx = createContext(addonSpec);
protoFactory.init(aCtx);
cache.addAppExtensionAction(addonSpec, actionId, protoFactory);
return protoFactory;
} catch (ActionInitializationException e) {
LOG.error("Initialization of AppExtensionAction failed", e);
} catch (AddonException ex) {
LOG.error("Failed to download Add-on.", ex);
}
}
return null;
}
public void returnAppExtensionAction(AppExtensionAction obj) {
obj.destroy(false);
}
/**
* Get a specific AppPluginAction.
*
* @param addonSpec {@link AddonSpecification} which contains the description of the {@link AppPluginAction}.
* @param resourceName The {@link AppPluginSpecification#resourceName} to identify the @{@link AppPluginAction} to
* return.
* @return A AppPluginAction which corresponds to the {@link AddonSpecification} and the {@code resourceName}. If no
* such AppPluginAction exists NULL is returned.
*/
public AppPluginAction getAppPluginAction(@Nonnull AddonSpecification addonSpec, @Nonnull String resourceName) {
AppPluginAction appPluginAction = cache.getAppPluginAction(addonSpec, resourceName);
// TODO: find a better way to deal with the reuse of protocol plugins
// if (appPluginAction != null) {
// // AppExtensionAction cached so return it
// return appPluginAction;
AppPluginSpecification protoSpec = addonSpec.searchByResourceName(resourceName);
if (protoSpec == null) {
LOG.error("Plugin for resource {} does not exist in Add-on {}.", resourceName, addonSpec.getId());
} else {
String className = protoSpec.getClassName();
try {
ClassLoader cl = registry.downloadAddon(addonSpec);
AppPluginActionProxy protoFactory = new AppPluginActionProxy(className, cl);
Context aCtx = createContext(addonSpec);
protoFactory.init(aCtx);
cache.addAppPluginAction(addonSpec, resourceName, protoFactory);
return protoFactory;
} catch (ActionInitializationException e) {
LOG.error("Initialization of AppPluginAction failed", e);
} catch (AddonException ex) {
LOG.error("Failed to download Add-on.", ex);
}
}
return null;
}
public void returnAppPluginAction(AppPluginAction obj) {
obj.destroy(false);
}
private Context createContext(@Nonnull AddonSpecification addonSpec) {
Context aCtx = new Context(this, env, addonSpec, viewController);
aCtx.setCardRecognition(env.getRecognition());
aCtx.setCardStateMap(cardStates);
aCtx.setEventHandle(eventHandler);
aCtx.setUserConsent(userConsent);
return aCtx;
}
/**
* Shut down the AddonManager.
* The method unloads all installed add-ons.
*/
public void shutdown() {
unloadAllAddons();
}
/**
* Uninstall an add-on.
* This is primarily a wrapper method for the {@link FileRegistry#uninstallAddon(AddonSpecification)}
*
* @param addonSpec The specification of the add-on to uninstall.
*/
public void uninstallAddon(@Nonnull AddonSpecification addonSpec) {
// unloading is done by the PluginDirectoryAlterationListener
FileRegistry fileRegistry = registry.getFileRegistry();
if (fileRegistry != null) {
fileRegistry.uninstallAddon(addonSpec);
}
}
}
|
package de.hbt.hackathon.rtb.agent;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import de.hbt.hackathon.rtb.protocol.Reader;
import de.hbt.hackathon.rtb.protocol.Writer;
import de.hbt.hackathon.rtb.protocol.message.input.InitializeMessage;
import de.hbt.hackathon.rtb.protocol.message.input.InputMessage;
import de.hbt.hackathon.rtb.protocol.message.output.ColourMessage;
import de.hbt.hackathon.rtb.protocol.message.output.NameMessage;
import de.hbt.hackathon.rtb.simplebot.SimpleBot;
public class Agent {
public static void main(String[] args) throws IOException {
Writer writer = new Writer();
Communicator communicator = new Communicator();
Thread communcatorThread = new Thread(communicator);
communcatorThread.start();
TimerTask agentTimerTask = new AgentTimerTask(new SimpleBot());
Timer timer = new Timer();
timer.schedule(agentTimerTask, 100, 50);
AbstractStrategy bot = new SimpleBot(writer);
whileloop: do {
} while (true);
}
}
|
package com.sometrik.framework;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.LayoutTransition;
import android.animation.ObjectAnimator;
import android.app.Dialog;
import android.content.res.ColorStateList;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.RippleDrawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RectShape;
import android.graphics.drawable.shapes.RoundRectShape;
import android.text.TextUtils.TruncateAt;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
class ViewStyleManager {
private enum WhiteSpace { NORMAL, NOWRAP };
private enum HorizontalAlignment { INHERIT, LEFT, CENTER, RIGHT };
private enum TextOverflow { CLIP, ELLIPSIS };
private enum FontStyle { NORMAL, ITALIC, OBLIQUE };
private enum IconAttachment { TOP, RIGHT, BOTTOM, LEFT };
private enum BorderStyle { SOLID, DOTTED, DASHED };
private BitmapCache bitmapCache;
private float displayScale = 1.0f;
private float[] padding = null;
private float[] margin = null;
private Integer width = null, height = null;
private Float opacity = null;
private Integer leftPosition = null, topPosition = null;
private Integer rightPosition = null, bottomPosition = null;
private int minWidth = 0, minHeight = 0, maxWidth = 0, maxHeight = 0;
private String title = null;
private Integer weight = null;
private Integer backgroundColor = null;
private Integer color = null;
private Integer gravity = null;
private Float zoom = null;
private Integer shadow = null;
private float[] borderRadius = null;
private Integer borderWidth = null, borderColor = null;
private BorderStyle borderStyle = null;
private Integer fontSize = null;
private WhiteSpace whiteSpace = null;
private HorizontalAlignment textAlign = null;
private TextOverflow textOverflow = null;
private Integer fontWeight = null;
private FontStyle fontStyle = null;
private String fontFamily = null;
private String hint = null;
private String iconFile = null;
private IconAttachment iconAttachment = null;
private int[] gradientColors = null;
private Integer lineHeight = null;
private Integer maxLines = null;
private boolean showDecorations = true;
private boolean isDefault = false;
private boolean animateTransition = false;
private static final float ANDROID_DEFAULT_LINESPACING_MODIFIER = 17.1f;
private boolean isModified = false;
private static Pattern gradientPattern;
public ViewStyleManager(BitmapCache bitmapCache, float displayScale, boolean isDefault) {
this.bitmapCache = bitmapCache;
this.displayScale = displayScale;
this.isDefault = isDefault;
if (isDefault) setDefaults();
}
private void initPadding() {
padding = new float[4];
padding[0] = padding[1] = padding[2] = padding[3] = 0.0f;
}
private void initMargin() {
margin = new float[4];
margin[0] = margin[1] = margin[2] = margin[3] = 0.0f;
}
public void setDefaults() {
zoom = new Float(1.0);
opacity = new Float(1.0);
shadow = new Integer(0);
color = new Integer(Color.parseColor("#000000"));
backgroundColor = new Integer(0);
fontWeight = new Integer(400);
iconFile = "";
initPadding();
initMargin();
}
public boolean isModified() {
return isModified;
}
public void setStyle(String key, String value) {
isModified = true;
if (key.equals("padding")) {
padding = parseFloatArray(value, 4);
} else if (key.equals("padding-top")) {
if (padding == null) initPadding();
padding[0] = Float.parseFloat(value);
} else if (key.equals("padding-right")) {
if (padding == null) initPadding();
padding[1] = Float.parseFloat(value);
} else if (key.equals("padding-bottom")) {
if (padding == null) initPadding();
padding[2] = Float.parseFloat(value);
} else if (key.equals("padding-left")) {
if (padding == null) initPadding();
padding[3] = Float.parseFloat(value);
} else if (key.equals("margin")) {
margin = parseFloatArray(value, 4);
} else if (key.equals("margin-top")) {
if (margin == null) initMargin();
margin[0] = Float.parseFloat(value);
} else if (key.equals("margin-right")) {
if (margin == null) initMargin();
margin[1] = Float.parseFloat(value);
} else if (key.equals("margin-bottom")) {
if (margin == null) initMargin();
margin[2] = Float.parseFloat(value);
} else if (key.equals("margin-left")) {
if (margin == null) initMargin();
margin[3] = Float.parseFloat(value);
} else if (key.equals("weight")) {
weight = new Integer(value);
} else if (key.equals("opacity")) {
opacity = new Float(value);
} else if (key.equals("text-shadow")) {
} else if (key.equals("box-shadow")) {
} else if (key.equals("shadow")) {
shadow = new Integer(value);
} else if (key.equals("left")) {
leftPosition = new Integer(value);
} else if (key.equals("top")) {
topPosition = new Integer(value);
} else if (key.equals("right")) {
rightPosition = new Integer(value);
} else if (key.equals("bottom")) {
bottomPosition = new Integer(value);
} else if (key.equals("min-width")) {
minWidth = Integer.parseInt(value);
} else if (key.equals("min-height")) {
minHeight = Integer.parseInt(value);
} else if (key.equals("max-width")) {
maxWidth = Integer.parseInt(value);
} else if (key.equals("max-height")) {
maxHeight = Integer.parseInt(value);
} else if (key.equals("title")) {
title = value;
} else if (key.equals("width")) {
if (value.equals("wrap-content")) {
width = new Integer(LayoutParams.WRAP_CONTENT);
} else if (value.equals("match-parent")) {
width = new Integer(LayoutParams.FILL_PARENT);
} else {
width = new Integer(value);
}
} else if (key.equals("height")) {
if (value.equals("wrap-content")) {
height = new Integer(LayoutParams.WRAP_CONTENT);
} else if (value.equals("match-parent")) {
height = new Integer(LayoutParams.MATCH_PARENT);
} else {
height = new Integer(value);
}
} else if (key.equals("background")) {
Matcher matcher = gradientPattern.matcher(value);
if (matcher.matches()) {
gradientColors = new int[2];
gradientColors[0] = Color.parseColor(matcher.group(1));
gradientColors[1] = Color.parseColor(matcher.group(2));
} else {
gradientColors = null;
backgroundColor = new Integer(Color.parseColor(value));
}
} else if (key.equals("background-color")) {
gradientColors = null;
backgroundColor = new Integer(Color.parseColor(value));
} else if (key.equals("color")) {
color = new Integer(Color.parseColor(value));
} else if (key.equals("gravity")) {
if (value.equals("bottom")) {
gravity = new Integer(Gravity.BOTTOM);
} else if (value.equals("top")) {
gravity = new Integer(Gravity.TOP);
} else if (value.equals("left")) {
gravity = new Integer(Gravity.LEFT);
} else if (value.equals("right")) {
gravity = new Integer(Gravity.RIGHT);
} else if (value.equals("center")) {
gravity = new Integer(Gravity.CENTER);
} else if (value.equals("center-vertical")) {
gravity = new Integer(Gravity.CENTER_VERTICAL);
} else if (value.equals("center-horizontal")) {
gravity = new Integer(Gravity.CENTER_HORIZONTAL);
} else if (value.equals("start")) {
gravity = new Integer(Gravity.START);
}
} else if (key.equals("zoom")) {
if (value.equals("inherit")) {
zoom = null;
} else {
zoom = new Float(value);
}
} else if (key.equals("border")) {
if (value.equals("none") || value.isEmpty()) {
borderWidth = new Integer(0);
} else {
String[] sets = value.split(" ");
if (sets.length == 1) {
borderColor = new Integer(Color.parseColor(sets[0]));
borderWidth = 1;
borderStyle = BorderStyle.SOLID;
} else {
if (sets.length >= 1) {
borderWidth = new Integer(sets[0]);
} else {
borderWidth = 1;
}
if (sets.length >= 2) {
String s = sets[1];
if (s.equals("dotted")) borderStyle = BorderStyle.DOTTED;
else if (s.equals("dashed")) borderStyle = BorderStyle.DASHED;
else borderStyle = BorderStyle.SOLID;
} else {
borderStyle = BorderStyle.SOLID;
}
if (sets.length >= 3) {
borderColor = new Integer(Color.parseColor(sets[2]));
} else {
borderColor = Color.parseColor("#000000");
}
}
}
} else if (key.equals("border-radius")) {
borderRadius = parseFloatArray(value, 4);
} else if (key.equals("border-color")) {
borderColor = Color.parseColor(value);
} else if (key.equals("font-size")) {
if (value.equals("small")){
fontSize = new Integer(9);
} else if (value.equals("medium")){
fontSize = new Integer(12);
} else if (value.equals("large")){
fontSize = new Integer(15);
} else {
fontSize = new Integer(value);
}
} else if (key.equals("line-height")) {
lineHeight = new Integer(value);
} else if (key.equals("max-lines")) {
maxLines = new Integer(value);
} else if (key.equals("white-space")) {
if (value.equals("normal")) whiteSpace = WhiteSpace.NORMAL;
else if (value.equals("nowrap")) whiteSpace = WhiteSpace.NOWRAP;
} else if (key.equals("text-overflow")) {
if (value.equals("ellipsis")) {
textOverflow = TextOverflow.ELLIPSIS;
}
} else if (key.equals("font-weight")) {
if (value.equals("normal")) {
fontWeight = new Integer(400);
} else if (value.equals("bold")) {
fontWeight = new Integer(700);
} else {
fontWeight = new Integer(value);
}
} else if (key.equals("font-style")) {
if (value.equals("italic")) {
fontStyle = FontStyle.ITALIC;
} else if (value.equals("oblique")) {
fontStyle = FontStyle.OBLIQUE;
} else {
fontStyle = FontStyle.NORMAL;
}
} else if (key.equals("text-align")) {
if (value.equals("inherit")) {
textAlign = HorizontalAlignment.INHERIT;
} else if (value.equals("left")) {
textAlign = HorizontalAlignment.LEFT;
} else if (value.equals("center")) {
textAlign = HorizontalAlignment.CENTER;
} else if (value.equals("right")) {
textAlign = HorizontalAlignment.RIGHT;
}
} else if (key.equals("font-family")) {
fontFamily = value;
} else if (key.equals("hint")) {
hint = value;
} else if (key.equals("icon-attachment")) {
if (value.equals("top")) {
iconAttachment = IconAttachment.TOP;
} else if (value.equals("right")) {
iconAttachment = IconAttachment.RIGHT;
} else if (value.equals("bottom")) {
iconAttachment = IconAttachment.BOTTOM;
} else if (value.equals("left")) {
iconAttachment = IconAttachment.LEFT;
}
// right, top, bottom, left
} else if (key.equals("icon")) {
if (value.equals("none")) {
iconFile = "";
} else {
iconFile = value;
}
} else if (key.equals("decoration")) {
if (value.equals("none")) {
showDecorations = false;
} else {
showDecorations = true;
}
} else if (key.equals("animate-transition")) {
if (!value.equals("none")) {
animateTransition = true;
} else {
animateTransition = false;
}
}
}
public void apply(Dialog dialog) {
if (width != null || height != null) {
ViewGroup.LayoutParams params = dialog.getWindow().getAttributes();
if (width != null) {
params.width = applyScaleToDimension(width);
}
if (height != null) {
params.height = applyScaleToDimension(height);
}
dialog.getWindow().setAttributes((android.view.WindowManager.LayoutParams) params);
}
}
public void apply(View view) {
apply(view, false);
}
public void apply(View view, boolean animate) {
ArrayList<Animator> animators = new ArrayList<Animator>();
if (animateTransition && view instanceof ViewGroup) {
LayoutTransition transition = new LayoutTransition();
transition.enableTransitionType(LayoutTransition.CHANGING);
transition.setDuration(500);
transition.setStartDelay(LayoutTransition.CHANGING, 0);
((ViewGroup)view).setLayoutTransition(transition);
}
if (opacity != null) {
if (animate) {
animators.add(ObjectAnimator.ofFloat(view, View.ALPHA, opacity));
} else {
view.setAlpha(opacity);
}
}
if (zoom != null) {
if (animate) {
animators.add(ObjectAnimator.ofFloat(view, View.SCALE_X, zoom));
animators.add(ObjectAnimator.ofFloat(view, View.SCALE_Y, zoom));
} else {
view.setScaleX(zoom);
view.setScaleY(zoom);
}
}
if (shadow != null) {
if (animate) {
animators.add(ObjectAnimator.ofFloat(view, View.TRANSLATION_Z, shadow));
} else {
view.setTranslationZ(shadow);
}
}
// if (title != null) view.setTooltipText(title);
// Scaled parameters
if (padding != null) {
view.setPadding((int)applyScale(padding[3]),
(int)applyScale(padding[0]),
(int)applyScale(padding[1]),
(int)applyScale(padding[2]));
}
if (leftPosition != null) view.setLeft(applyScale(leftPosition));
if (rightPosition != null) view.setRight(applyScale(rightPosition));
if (topPosition != null) view.setTop(applyScale(topPosition));
if (bottomPosition != null) view.setBottom(applyScale(bottomPosition));
if (minWidth > 0) view.setMinimumWidth(applyScale(minWidth));
if (minHeight > 0) view.setMinimumHeight(applyScale(minHeight));
Drawable backgroundContent = null;
if (borderColor != null && view instanceof EditText) {
((EditText) view).setBackgroundTintList(ColorStateList.valueOf(borderColor));
} else if ((borderColor != null && borderColor != 0 && borderWidth != null && borderWidth != 0) || borderRadius != null || gradientColors != null) {
if (!(view instanceof TextView) && borderRadius != null && gradientColors == null &&
(borderWidth == null || borderWidth == 0 || backgroundColor == null || backgroundColor == 0)) {
RoundRectShape shape = new RoundRectShape(expandRadii(borderRadius), null, null);
ShapeDrawable sd = new ShapeDrawable(shape);
Paint paint = sd.getPaint();
Integer paintColor = 0;
if (borderWidth == null || borderWidth == 0) {
paint.setStyle(Style.FILL);
paintColor = backgroundColor;
} else {
paint.setStyle(Style.STROKE);
paint.setStrokeWidth(applyScale(borderWidth));
paintColor = borderColor;
}
if (paintColor == null || paintColor == 0) {
paint.setColor(Color.parseColor("#00000000"));
} else {
paint.setColor(paintColor);
}
backgroundContent = sd;
} else {
GradientDrawable gradientDrawable = new GradientDrawable();
if (gradientColors != null) {
gradientDrawable.setColors(gradientColors);
} else if (backgroundColor != null) {
gradientDrawable.setColor(backgroundColor);
}
if (borderRadius != null) {
gradientDrawable.setCornerRadius(2); // Might be necessary for zero radiuses to work
gradientDrawable.setCornerRadii(expandRadii(borderRadius));
}
if (borderColor != null && borderWidth != null && borderWidth != 0) {
gradientDrawable.setStroke(borderWidth, borderColor, applyScale(getDashWidth(borderStyle)), applyScale(1));
}
backgroundContent = gradientDrawable;
}
} else if ((backgroundColor != null && backgroundColor != 0) || (!showDecorations && isDefault)) {
backgroundContent = new ColorDrawable(backgroundColor);
}
if (showDecorations && (shadow == null || shadow == 0) && (view instanceof Button || view instanceof FWEventLayout)) {
Drawable backgroundMask = null;
if (borderRadius != null) {
RoundRectShape shape = new RoundRectShape(expandRadii(borderRadius), null, null);
backgroundMask = new ShapeDrawable(shape);
} else {
RectShape shape = new RectShape();
backgroundMask = new ShapeDrawable(shape);
}
int color1 = 0, color2 = 0;
if (backgroundColor != null && backgroundColor != 0) {
color1 = Color.parseColor("#80ffffff");
color2 = Color.parseColor("#80000000");
} else {
color1 = Color.parseColor("#30ff0000");
color2 = Color.parseColor("#30000000");
}
ColorStateList colors = new ColorStateList(
new int[][]
{
new int[]{android.R.attr.state_pressed},
new int[]{android.R.attr.state_focused},
new int[]{android.R.attr.state_activated},
new int[]{}
},
new int[]
{
color2,
color2,
color2,
color1
}
);
RippleDrawable rd = new RippleDrawable(colors, backgroundContent, backgroundMask);
view.setBackground(rd);
} else if (backgroundContent != null) {
view.setBackground(backgroundContent);
}
// Layout parameters
if (weight != null || width != null || height != null ||
margin != null || gravity != null) {
if (view.getParent() instanceof ScrollView) { // stupid hack
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
view.setLayoutParams(params);
} else if (view.getParent() instanceof LinearLayout) {
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)view.getLayoutParams();
if (weight != null) params.weight = weight;
if (margin != null) {
params.topMargin = (int)applyScale(margin[0]);
params.rightMargin = (int)applyScale(margin[1]);
params.bottomMargin = (int)applyScale(margin[2]);
params.leftMargin = (int)applyScale(margin[3]);
}
if (width != null) {
params.width = applyScaleToDimension(width);
}
if (height != null) {
params.height = applyScaleToDimension(height);
}
if (gravity != null) params.gravity = gravity;
view.setLayoutParams(params);
} else if (view.getParent() instanceof FrameLayout) {
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams)view.getLayoutParams();
if (margin != null) {
params.topMargin = (int)applyScale(margin[0]);
params.rightMargin = (int)applyScale(margin[1]);
params.bottomMargin = (int)applyScale(margin[2]);
params.leftMargin = (int)applyScale(margin[3]);
}
if (width != null) {
params.width = applyScaleToDimension(width);
}
if (height != null) {
params.height = applyScaleToDimension(height);
}
if (gravity != null) params.gravity = gravity;
view.setLayoutParams(params);
} else if (view.getParent() instanceof RelativeLayout) {
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)view.getLayoutParams();
if (margin != null) {
params.topMargin = (int)applyScale(margin[0]);
params.rightMargin = (int)applyScale(margin[1]);
params.bottomMargin = (int)applyScale(margin[2]);
params.leftMargin = (int)applyScale(margin[3]);
}
if (width != null) {
params.width = applyScaleToDimension(width);
}
if (height != null) {
params.height = applyScaleToDimension(height);
}
view.setLayoutParams(params);
} else if (view.getParent() instanceof ViewGroup) {
ViewGroup.LayoutParams params = (ViewGroup.LayoutParams)view.getLayoutParams();
if (width != null) {
params.width = applyScaleToDimension(width);
}
if (height != null) {
params.height = applyScaleToDimension(height);
}
view.setLayoutParams(params);
} else {
System.out.println("this style cannot be applied to view that doesn't have valid layout as parent");
}
}
if (view instanceof ImageView) {
ImageView imageView = (ImageView)view;
if (maxWidth > 0) imageView.setMaxWidth(applyScale(maxWidth));
if (maxHeight > 0) imageView.setMaxHeight(applyScale(maxHeight));
} else if (view instanceof TextView) {
TextView textView = (TextView)view;
if (maxWidth > 0) textView.setMaxWidth(applyScale(maxWidth));
if (maxHeight > 0) textView.setMaxHeight(applyScale(maxHeight));
}
if (view instanceof EditText) {
EditText editText = (EditText) view;
if (whiteSpace != null) {
switch (whiteSpace) {
case NORMAL:
editText.setSingleLine(false);
// editText.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE);
break;
case NOWRAP:
editText.setSingleLine(true);
break;
}
}
}
if (view instanceof TextView) { // also Buttons
TextView textView = (TextView)view;
if (color != null) textView.setTextColor(color);
if (fontSize != null) {
textView.setTextSize(fontSize);
}
if (lineHeight != null) {
if (fontSize == null) {
//15 is android default text size
textView.setLineSpacing(lineHeight - 15, 1);
} else {
textView.setLineSpacing(lineHeight - fontSize, 1);
}
}
if (maxLines != null && maxLines != 0) {
textView.setMaxLines(maxLines);
}
if (whiteSpace != null) {
switch (whiteSpace) {
case NORMAL:
textView.setSingleLine(false);
break;
case NOWRAP:
textView.setSingleLine(true);
break;
}
}
if (textAlign != null) {
textView.setTextAlignment(convertTextAlignment(textAlign));
textView.setGravity(convertTextAlignmentToGravity(textAlign));
}
if (textOverflow != null) {
switch (textOverflow) {
case CLIP:
textView.setEllipsize(null);
break;
case ELLIPSIS:
textView.setEllipsize(TruncateAt.END);
break;
}
}
if (fontFamily != null || fontWeight != null || fontStyle != null) {
int flags = 0;
if (fontWeight != null && fontWeight > 550) flags |= Typeface.BOLD;
if (fontStyle != null && (fontStyle == FontStyle.ITALIC || fontStyle == FontStyle.OBLIQUE)) flags |= Typeface.ITALIC;
if (fontFamily != null) {
textView.setTypeface(Typeface.create(fontFamily, flags), flags);
} else {
textView.setTypeface(null, flags);
}
}
if (hint != null) textView.setHint(hint);
if (iconFile != null) {
BitmapDrawable drawable = null;
if (!iconFile.isEmpty()) {
Bitmap bitmap = bitmapCache.loadBitmapForButton(iconFile);
if (bitmap != null) {
drawable = new BitmapDrawable(bitmap);
}
}
if (iconAttachment == null || iconAttachment == IconAttachment.TOP) {
textView.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null);
} else if (iconAttachment == IconAttachment.RIGHT) {
textView.setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null);
} else if (iconAttachment == IconAttachment.BOTTOM) {
textView.setCompoundDrawablesWithIntrinsicBounds(null, null, null, drawable);
} else if (iconAttachment == IconAttachment.LEFT) {
textView.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);
}
}
}
if (!animators.isEmpty()) {
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.playTogether(animators);
animatorSet.setDuration(200);
animatorSet.start();
}
}
public void applyLinkColor(View view) {
if (view instanceof TextView) { // also Buttons
TextView textView = (TextView)view;
if (color != null) textView.setLinkTextColor(color);
}
}
protected int applyScaleToDimension(int v) {
if (v == LayoutParams.MATCH_PARENT || v == LayoutParams.WRAP_CONTENT || v == LayoutParams.FILL_PARENT) {
return v;
} else {
return applyScale(v);
}
}
protected int applyScale(int v) {
return (int)(v * displayScale + 0.5f);
}
protected float applyScale(float v) {
return v * displayScale;
}
protected float[] applyScale(float[] input) {
float[] r = new float[input.length];
for (int i = 0; i < input.length; i++) {
r[i] = applyScale(borderRadius[i]);
}
return r;
}
protected float[] expandRadii(float[] input) {
float[] r = new float[8];
for (int i = 0; i < 4; i++) {
r[2 * i] = r[2 * i + 1] = applyScale(borderRadius[i]);
}
return r;
}
protected float[] parseFloatArray(String value, int size) {
String[] values = value.split(" ");
float[] r = new float[size];
float prev = 0.0f;
for (int i = 0; i < size; i++) {
if (i < values.length) prev = Float.valueOf(values[i].trim());
r[i] = prev;
}
return r;
}
protected int convertTextAlignment(HorizontalAlignment alignment) {
switch (textAlign) {
case INHERIT: return View.TEXT_ALIGNMENT_INHERIT;
case LEFT: return View.TEXT_ALIGNMENT_TEXT_START;
case CENTER: return View.TEXT_ALIGNMENT_CENTER;
case RIGHT: return View.TEXT_ALIGNMENT_TEXT_END;
}
return 0;
}
protected int convertTextAlignmentToGravity(HorizontalAlignment alignment) {
switch (alignment) {
case INHERIT: return Gravity.LEFT;
case CENTER: return Gravity.CENTER;
case LEFT: return Gravity.LEFT;
case RIGHT: return Gravity.RIGHT;
}
return Gravity.LEFT;
}
protected int getDashWidth(BorderStyle style) {
switch (style) {
case SOLID: return 0;
case DOTTED: return 1;
case DASHED: return 2;
}
return 0;
}
static {
gradientPattern = Pattern.compile("^linear-gradient\\(\\s*([^, ]+),\\s*([^, ]+)\\s*\\)$");
}
}
|
package br.com.liveo.liveogcm;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import br.com.liveo.liveogcm.gcm.GcmHelper;
import br.com.liveo.liveogcm.util.Util;
public class MainActivity extends AppCompatActivity {
private ListView mListaEntrada;
private int mPosicaoAtualEntrada = 0;
private ArrayAdapter<String> mlstEntradaAdapter;
private ArrayList<String> mEntrada = new ArrayList<>();
private ListView mListaSaida;
private int mPosicaoAtualSaida = 0;
private ArrayAdapter<String> mlstSaidaAdapter;
private ArrayList<String> mSaida = new ArrayList<>();
private DataUpdateReceiver dataUpdateReceiver;
private static final String STATE_LISTA_ENTRADA = "mListaEntrada_position";
private static final String STATE_LISTA_ENTRADA_DADOS = "mListaEntrada_dados";
private static final String STATE_LISTA_SAIDA = "mListaSaida_position";
private static final String STATE_LISTA_SAIDA_DADOS = "mListaSaida_dados";
@Override
protected void onResume() {
super.onResume();
if (dataUpdateReceiver == null) {
dataUpdateReceiver = new DataUpdateReceiver();
}
IntentFilter intentFilter = new IntentFilter(Util.REFRESH_DATA_INTENT);
registerReceiver(dataUpdateReceiver, intentFilter);
}
@Override
public void onSaveInstanceState(Bundle outState) {
mPosicaoAtualEntrada = mListaEntrada.getFirstVisiblePosition();
mPosicaoAtualSaida = mListaSaida.getFirstVisiblePosition();
outState.putInt(STATE_LISTA_ENTRADA, mPosicaoAtualEntrada);
outState.putStringArrayList(STATE_LISTA_ENTRADA_DADOS, mEntrada);
outState.putInt(STATE_LISTA_SAIDA, mPosicaoAtualSaida);
outState.putStringArrayList(STATE_LISTA_SAIDA_DADOS, mSaida);
super.onSaveInstanceState(outState);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore state members from saved instance
mPosicaoAtualEntrada = savedInstanceState.getInt(STATE_LISTA_ENTRADA);
mEntrada = savedInstanceState.getStringArrayList(STATE_LISTA_ENTRADA_DADOS);
mPosicaoAtualSaida = savedInstanceState.getInt(STATE_LISTA_SAIDA);
mSaida = savedInstanceState.getStringArrayList(STATE_LISTA_SAIDA_DADOS);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mListaEntrada = (ListView) findViewById(R.id.lstEntrada);
mListaSaida = (ListView) findViewById(R.id.lstSaida);
if (savedInstanceState != null) {
mPosicaoAtualEntrada = savedInstanceState.getInt(STATE_LISTA_ENTRADA);
mEntrada = savedInstanceState.getStringArrayList(STATE_LISTA_ENTRADA_DADOS);
mPosicaoAtualSaida = savedInstanceState.getInt(STATE_LISTA_SAIDA);
mSaida = savedInstanceState.getStringArrayList(STATE_LISTA_SAIDA_DADOS);
mListaEntrada.setSelection(mPosicaoAtualEntrada);
mListaSaida.setSelection(mPosicaoAtualSaida);
}
mlstEntradaAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, mEntrada);
mlstSaidaAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, mSaida);
mListaEntrada.setAdapter(mlstEntradaAdapter);
mListaSaida.setAdapter(mlstSaidaAdapter);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
addInfo(mlstSaidaAdapter, mSaida, getString(R.string.registro_gcm));
setupGCM();
}
});
}
private void setupGCM() {
try {
if (Util.checkConnection(this)) {
if (GcmHelper.googlePlayServicesIsAvailable(this)) {
GcmHelper.register(this, new GcmHelper.TheRegisterDevice() {
@Override
public void toRegister(String regId, boolean inBackground) {
addInfo(mlstSaidaAdapter, mSaida, getString(R.string.gcm_registred_id, regId));
}
});
} else {
Toast.makeText(this, R.string.error_gcmplay_unavailable, Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, R.string.error_gcmplay_register_failure, Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.getStackTrace();
}
}
public void addInfo(ArrayAdapter<String> adapter, ArrayList<String> lista, String texto) {
lista.add(texto);
adapter.notifyDataSetChanged();
}
private class DataUpdateReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Util.REFRESH_DATA_INTENT)) {
String msg = intent.getStringExtra("gcm_texto");
if (msg == null) {
msg = getString(R.string.notificacao_sem_texto);
}
addInfo(mlstEntradaAdapter, mEntrada, msg);
}
}
}
}
|
package com.andela.webservice;
import android.app.ListActivity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.andela.webservice.model.Flower;
import com.andela.webservice.parser.FlowerJsonParser;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends ListActivity {
private TextView output;
private ProgressBar progressBar;
private List<MyTask> tasks;
private List<Flower> flowerList;
private static final String PHOTO_BASE_URL = "http://services.hanselandpetal.com/photos/";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
progressBar.setVisibility(View.INVISIBLE);
tasks = new ArrayList<>();
//output = (TextView) findViewById(R.id.textView);
//output.setMovementMethod(new ScrollingMovementMethod());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.action_do_task) {
if(isOnline()) {
requestData("http://services.hanselandpetal.com/secure/flowers.json");
} else {
Toast.makeText(this, "Network isn't available", Toast.LENGTH_LONG).show();
}
}
return true;
}
private void requestData(String uri) {
MyTask task = new MyTask();
//This makes serial request
task.execute(uri);
//For parrallel processing
//task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "param1", "param2", "param3");
}
private void updateDisplay() {
/*if(flowerList != null) {
for (Flower flower : flowerList) {
output.append(flower.getName() + "\n");
}
}*/
FlowerAdapter adapter = new FlowerAdapter(this, R.layout.item_flower, flowerList);
setListAdapter(adapter);
}
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if(netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
private class MyTask extends AsyncTask<String, String, List<Flower>> {
//Async task now returns a List of Flower objects
@Override
protected void onPreExecute() {
//updateDisplay("Starting task");
if(tasks.size() == 0) {
progressBar.setVisibility(View.VISIBLE);
}
tasks.add(this);
}
/*
Doin the background parsing in the background thread
*/
@Override
protected List<Flower> doInBackground(String... params) {
String content = HttpManager.getData(params[0],"feeduser","feedpassword");
flowerList = FlowerJsonParser.parseFeed(content); //getting data from JSon feed
//Getting image for each flower name in the list
for(Flower flower : flowerList) {
String imageUrl = PHOTO_BASE_URL + flower.getPhoto();
try {
InputStream in = (InputStream) new URL(imageUrl).getContent();
//This retrieves the entire content of the location in one request
//It comes back as a blub of data n we can access it through the input stream
Bitmap bitmap = BitmapFactory.decodeStream(in);
flower.setBitmap(bitmap);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return flowerList;
}
@Override
protected void onPostExecute(List<Flower> result) {
tasks.remove(this);
if(tasks.size() == 0) {
progressBar.setVisibility(View.INVISIBLE);
}
//flowerList = FlowerXmlParser.parseFeed(result);
if(result == null) {
Toast.makeText(MainActivity.this, "Can't connect to webservice", Toast.LENGTH_LONG).show();
return;
}
flowerList = result;
updateDisplay();
}
@Override
protected void onProgressUpdate(String... values) {
//updateDisplay(values[0]);
}
}
}
|
package com.andela.webservice;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private TextView output;
private ProgressBar progressBar;
List<MyTask> tasks;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
progressBar.setVisibility(View.INVISIBLE);
tasks = new ArrayList<>();
output = (TextView) findViewById(R.id.textView);
output.setMovementMethod(new ScrollingMovementMethod());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
MyTask task = new MyTask();
//This makes serial request
//task.execute("param1", "param2", "param3");
//For parrallel processing
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "param1", "param2", "param3");
return true;
}
private void updateDisplay(String s) {
output.append(s + "\n");
}
private class MyTask extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
updateDisplay("Starting task");
if(tasks.size() == 0) {
progressBar.setVisibility(View.VISIBLE);
}
tasks.add(this);
}
@Override
protected String doInBackground(String... params) {
for(int i = 0; i< params.length; i++) {
publishProgress("working with " + params[i]);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return "Task Complete";
}
@Override
protected void onPostExecute(String result) {
updateDisplay(result);
tasks.remove(this);
if(tasks.size() == 0) {
progressBar.setVisibility(View.INVISIBLE);
}
}
@Override
protected void onProgressUpdate(String... values) {
updateDisplay(values[0]);
}
}
}
|
package com.jdoneill.slopeangle;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.Log;
import android.view.View;
import java.math.BigDecimal;
import java.math.RoundingMode;
/**
* The implementation of slope angle arrow. Thee mode of operation for rotating
* the arrow is using device motion sensors.
*/
public class SlopeArrow extends View implements SensorEventListener{
private static final String TAG = "SlopeArrowSensor";
// context
private Context mContext;
// sensors
private SensorManager sensorManager;
private Sensor aSensor;
private Sensor gSensor;
private SensorEventListener mListener;
private float[] mGravity;
private float[] mGeomagnetic;
private float slopeAngle;
// bitmap
private Bitmap arrowBitmap;
private Matrix arrowMatrix;
private Paint arrowPaint;
public SlopeArrow(Context context){
super(context);
this.mContext = context;
this.setWillNotDraw(false);
// create the bitmap drawable
arrowBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_arrow_downward_black_24dp);
arrowMatrix = new Matrix();
arrowPaint = new Paint();
// Get the default sensor for the sensor type from the SensorManager
sensorManager = (SensorManager)mContext.getSystemService(Activity.SENSOR_SERVICE);
aSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
gSensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
}
/**
* Draws the slope arrow at the current angle of slope
*/
protected void onDraw(Canvas canvas){
// reset the matrix to default values
arrowMatrix.reset();
// pass the current slope angle to the matrix
arrowMatrix.postRotate(slopeAngle);
// use the matrix to draw the bitmap
canvas.drawBitmap(arrowBitmap, arrowMatrix, arrowPaint);
super.onDraw(canvas);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// Try for a width based on our minimum
int minw = getPaddingLeft() + getPaddingRight() + getSuggestedMinimumWidth();
int w = Math.max(minw, MeasureSpec.getSize(widthMeasureSpec));
// Whatever the width ends up being, ask for a height that would let the pie
// get as big as it can
int minh = getPaddingTop() + getPaddingBottom();
int h = Math.min(MeasureSpec.getSize(heightMeasureSpec), minh);
setMeasuredDimension(w, h);
}
/**
* Updates the slope angle, in degrees, such that
* the slope arrow is drawn within view
*/
private void setRotationAngle(double angle){
// save the angle
slopeAngle = (float)angle;
// force the arrow to re-paint itself
postInvalidate();
}
/**
* Rounds a double to specified number of decimal places.
* Note the rounding mode is UP.
*
* @param value double to be rounded
* @param places number of decimal places to round to.
* @return
*/
private static double round(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.doubleValue();
}
/**
* Unregisters the sensor listener if it is registered.
*/
public void unregisterListeners() {
sensorManager.unregisterListener(mListener);
Log.i(TAG, "Sensor listener unregistered.");
}
@Override
public void onSensorChanged(SensorEvent event) {
if(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
mGravity = event.values;
if(event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD)
mGeomagnetic = event.values;
if(mGravity != null && mGeomagnetic != null){
float[] R = new float[9];
float[] I = new float[9];
boolean success = SensorManager.getRotationMatrix(R, I, mGravity, mGeomagnetic);
if(success){
float[] outR = new float[9];
SensorManager.remapCoordinateSystem(R, SensorManager.AXIS_X, SensorManager.AXIS_Y, outR);
float[] orientation = new float[3];
SensorManager.getOrientation(outR, orientation);
float[] smoothOrientation = new float[3];
// pitch angle
float pitch = (float)Math.toDegrees(smoothOrientation[1]);
// pitch is positive no matter which way device is tilted
double pitchAngle = (double) Math.abs(pitch);
// round angle to 2 decimal places
pitchAngle = round(pitchAngle, 2);
String pitchAngleString = Double.toString(pitchAngle);
setRotationAngle(pitchAngle);
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
|
package com.samourai.wallet.api;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import com.samourai.wallet.JSONRPC.JSONRPC;
import com.samourai.wallet.JSONRPC.TrustedNodeUtil;
import com.samourai.wallet.bip47.BIP47Meta;
import com.samourai.wallet.bip47.BIP47Util;
import com.samourai.wallet.hd.HD_Wallet;
import com.samourai.wallet.hd.HD_WalletFactory;
import com.samourai.wallet.send.FeeUtil;
import com.samourai.wallet.send.MyTransactionOutPoint;
import com.samourai.wallet.send.RBFUtil;
import com.samourai.wallet.send.SuggestedFee;
import com.samourai.wallet.send.UTXO;
import com.samourai.wallet.util.AddressFactory;
import com.samourai.wallet.util.ConnectivityStatus;
import com.samourai.wallet.util.FormatsUtil;
import com.samourai.wallet.util.PrefsUtil;
import com.samourai.wallet.util.TorUtil;
import com.samourai.wallet.util.WebUtil;
import com.samourai.wallet.bip47.rpc.PaymentCode;
import com.samourai.wallet.bip47.rpc.PaymentAddress;
import com.samourai.wallet.R;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.bitcoinj.core.AddressFormatException;
import org.bitcoinj.core.ECKey;
import org.bitcoinj.core.Sha256Hash;
import org.bitcoinj.core.TransactionOutPoint;
import org.bitcoinj.crypto.MnemonicException;
import org.bitcoinj.params.MainNetParams;
import org.bitcoinj.script.Script;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.spongycastle.util.encoders.Hex;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
public class APIFactory {
private static long xpub_balance = 0L;
private static HashMap<String, Long> xpub_amounts = null;
private static HashMap<String,List<Tx>> xpub_txs = null;
private static HashMap<String,Integer> unspentAccounts = null;
private static HashMap<String,String> unspentPaths = null;
private static HashMap<String,UTXO> utxos = null;
private static HashMap<String, Long> bip47_amounts = null;
private static long latest_block_height = -1L;
private static String latest_block_hash = null;
private static APIFactory instance = null;
private static Context context = null;
private static AlertDialog alertDialog = null;
private APIFactory() { ; }
public static APIFactory getInstance(Context ctx) {
context = ctx;
if(instance == null) {
xpub_amounts = new HashMap<String, Long>();
xpub_txs = new HashMap<String,List<Tx>>();
xpub_balance = 0L;
bip47_amounts = new HashMap<String, Long>();
unspentPaths = new HashMap<String, String>();
unspentAccounts = new HashMap<String, Integer>();
utxos = new HashMap<String, UTXO>();
instance = new APIFactory();
}
return instance;
}
public synchronized void reset() {
xpub_balance = 0L;
xpub_amounts.clear();
bip47_amounts.clear();
xpub_txs.clear();
unspentPaths = new HashMap<String, String>();
unspentAccounts = new HashMap<String, Integer>();
utxos = new HashMap<String, UTXO>();
}
private synchronized JSONObject getXPUB(String[] xpubs) {
JSONObject jsonObject = null;
try {
String response = null;
if(!TorUtil.getInstance(context).statusFromBroadcast()) {
// use POST
StringBuilder args = new StringBuilder();
args.append("active=");
args.append(StringUtils.join(xpubs, URLEncoder.encode("|", "UTF-8")));
Log.i("APIFactory", "XPUB:" + args.toString());
response = WebUtil.getInstance(context).postURL(WebUtil.SAMOURAI_API2 + "multiaddr?", args.toString());
Log.i("APIFactory", "XPUB response:" + response);
}
else {
HashMap<String,String> args = new HashMap<String,String>();
args.put("active", StringUtils.join(xpubs, "|"));
Log.i("APIFactory", "XPUB:" + args.toString());
response = WebUtil.getInstance(context).tor_postURL(WebUtil.SAMOURAI_API2 + "multiaddr", args);
Log.i("APIFactory", "XPUB response:" + response);
}
try {
jsonObject = new JSONObject(response);
xpub_txs.put(xpubs[0], new ArrayList<Tx>());
parseXPUB(jsonObject);
xpub_amounts.put(HD_WalletFactory.getInstance(context).get().getAccount(0).xpubstr(), xpub_balance);
}
catch(JSONException je) {
je.printStackTrace();
jsonObject = null;
}
}
catch(Exception e) {
jsonObject = null;
e.printStackTrace();
}
return jsonObject;
}
private synchronized boolean parseXPUB(JSONObject jsonObject) throws JSONException {
if(jsonObject != null) {
if(jsonObject.has("wallet")) {
JSONObject walletObj = (JSONObject)jsonObject.get("wallet");
if(walletObj.has("final_balance")) {
xpub_balance = walletObj.getLong("final_balance");
Log.d("APIFactory", "xpub_balance:" + xpub_balance);
}
}
if(jsonObject.has("info")) {
JSONObject infoObj = (JSONObject)jsonObject.get("info");
if(infoObj.has("latest_block")) {
JSONObject blockObj = (JSONObject)infoObj.get("latest_block");
if(blockObj.has("height")) {
latest_block_height = blockObj.getLong("height");
}
if(blockObj.has("hash")) {
latest_block_hash = blockObj.getString("hash");
}
}
}
if(jsonObject.has("addresses")) {
JSONArray addressesArray = (JSONArray)jsonObject.get("addresses");
JSONObject addrObj = null;
for(int i = 0; i < addressesArray.length(); i++) {
addrObj = (JSONObject)addressesArray.get(i);
if(addrObj != null && addrObj.has("final_balance") && addrObj.has("address")) {
if(FormatsUtil.getInstance().isValidXpub((String)addrObj.get("address"))) {
xpub_amounts.put((String)addrObj.get("address"), addrObj.getLong("final_balance"));
AddressFactory.getInstance().setHighestTxReceiveIdx(AddressFactory.getInstance().xpub2account().get((String) addrObj.get("address")), addrObj.has("account_index") ? addrObj.getInt("account_index") : 0);
AddressFactory.getInstance().setHighestTxChangeIdx(AddressFactory.getInstance().xpub2account().get((String)addrObj.get("address")), addrObj.has("change_index") ? addrObj.getInt("change_index") : 0);
}
else {
long amount = 0L;
String addr = null;
addr = (String)addrObj.get("address");
amount = addrObj.getLong("final_balance");
String pcode = BIP47Meta.getInstance().getPCode4Addr(addr);
int idx = BIP47Meta.getInstance().getIdx4Addr(addr);
if(pcode != null && pcode.length() > 0) {
if(amount > 0L) {
BIP47Meta.getInstance().addUnspent(pcode, idx);
}
else {
BIP47Meta.getInstance().removeUnspent(pcode, Integer.valueOf(idx));
}
}
if(addr != null) {
bip47_amounts.put(addr, amount);
}
}
}
}
}
if(jsonObject.has("txs")) {
JSONArray txArray = (JSONArray)jsonObject.get("txs");
JSONObject txObj = null;
for(int i = 0; i < txArray.length(); i++) {
txObj = (JSONObject)txArray.get(i);
long height = 0L;
long amount = 0L;
long ts = 0L;
String hash = null;
String addr = null;
String _addr = null;
if(txObj.has("block_height")) {
height = txObj.getLong("block_height");
}
else {
height = -1L; // 0 confirmations
}
if(txObj.has("hash")) {
hash = (String)txObj.get("hash");
}
if(txObj.has("result")) {
amount = txObj.getLong("result");
}
if(txObj.has("time")) {
ts = txObj.getLong("time");
}
if(txObj.has("inputs")) {
JSONArray inputArray = (JSONArray)txObj.get("inputs");
JSONObject inputObj = null;
for(int j = 0; j < inputArray.length(); j++) {
inputObj = (JSONObject)inputArray.get(j);
if(inputObj.has("prev_out")) {
JSONObject prevOutObj = (JSONObject)inputObj.get("prev_out");
if(prevOutObj.has("xpub")) {
JSONObject xpubObj = (JSONObject)prevOutObj.get("xpub");
addr = (String)xpubObj.get("m");
}
else if(prevOutObj.has("addr") && BIP47Meta.getInstance().getPCode4Addr((String)prevOutObj.get("addr")) != null) {
_addr = (String)prevOutObj.get("addr");
}
else {
_addr = (String)prevOutObj.get("addr");
}
}
}
}
if(txObj.has("out")) {
JSONArray outArray = (JSONArray)txObj.get("out");
JSONObject outObj = null;
for(int j = 0; j < outArray.length(); j++) {
outObj = (JSONObject)outArray.get(j);
if(outObj.has("xpub")) {
JSONObject xpubObj = (JSONObject)outObj.get("xpub");
addr = (String)xpubObj.get("m");
}
else {
_addr = (String)outObj.get("addr");
}
}
}
if(addr != null || _addr != null) {
if(addr == null) {
addr = _addr;
}
Tx tx = new Tx(hash, addr, amount, ts, (latest_block_height > 0L && height > 0L) ? (latest_block_height - height) + 1 : 0);
if(BIP47Meta.getInstance().getPCode4Addr(addr) != null) {
tx.setPaymentCode(BIP47Meta.getInstance().getPCode4Addr(addr));
}
if(!xpub_txs.containsKey(addr)) {
xpub_txs.put(addr, new ArrayList<Tx>());
}
if(FormatsUtil.getInstance().isValidXpub(addr)) {
xpub_txs.get(addr).add(tx);
}
else {
xpub_txs.get(AddressFactory.getInstance().account2xpub().get(0)).add(tx);
}
if(height > 0L) {
RBFUtil.getInstance().remove(hash);
}
}
}
}
return true;
}
return false;
}
public long getLatestBlockHeight() {
return latest_block_height;
}
public String getLatestBlockHash() {
return latest_block_hash;
}
public JSONObject getNotifTx(String hash, String addr) {
JSONObject jsonObject = null;
try {
StringBuilder url = new StringBuilder(WebUtil.SAMOURAI_API2);
url.append("tx/");
url.append(hash);
url.append("?fees=1");
// Log.i("APIFactory", "Notif tx:" + url.toString());
String response = WebUtil.getInstance(null).getURL(url.toString());
// Log.i("APIFactory", "Notif tx:" + response);
try {
jsonObject = new JSONObject(response);
parseNotifTx(jsonObject, addr, hash);
}
catch(JSONException je) {
je.printStackTrace();
jsonObject = null;
}
}
catch(Exception e) {
jsonObject = null;
e.printStackTrace();
}
return jsonObject;
}
public JSONObject getNotifAddress(String addr) {
JSONObject jsonObject = null;
try {
StringBuilder url = new StringBuilder(WebUtil.SAMOURAI_API2);
url.append("multiaddr?active=");
url.append(addr);
// Log.i("APIFactory", "Notif address:" + url.toString());
String response = WebUtil.getInstance(null).getURL(url.toString());
// Log.i("APIFactory", "Notif address:" + response);
try {
jsonObject = new JSONObject(response);
parseNotifAddress(jsonObject, addr);
}
catch(JSONException je) {
je.printStackTrace();
jsonObject = null;
}
}
catch(Exception e) {
jsonObject = null;
e.printStackTrace();
}
return jsonObject;
}
public void parseNotifAddress(JSONObject jsonObject, String addr) throws JSONException {
if(jsonObject != null && jsonObject.has("txs")) {
JSONArray txArray = jsonObject.getJSONArray("txs");
JSONObject txObj = null;
for(int i = 0; i < txArray.length(); i++) {
txObj = (JSONObject)txArray.get(i);
if(!txObj.has("block_height") || (txObj.has("block_height") && txObj.getLong("block_height") < 1L)) {
return;
}
String hash = null;
if(txObj.has("hash")) {
hash = (String)txObj.get("hash");
if(BIP47Meta.getInstance().getIncomingStatus(hash) == null) {
getNotifTx(hash, addr);
}
}
}
}
}
public void parseNotifTx(JSONObject jsonObject, String addr, String hash) throws JSONException {
if(jsonObject != null) {
byte[] mask = null;
byte[] payload = null;
PaymentCode pcode = null;
if(jsonObject.has("inputs")) {
JSONArray inArray = (JSONArray)jsonObject.get("inputs");
if(inArray.length() > 0 && ((JSONObject)inArray.get(0)).has("sig")) {
String strScript = ((JSONObject)inArray.get(0)).getString("sig");
Script script = new Script(Hex.decode(strScript));
// Log.i("APIFactory", "pubkey from script:" + Hex.toHexString(script.getPubKey()));
ECKey pKey = new ECKey(null, script.getPubKey(), true);
// Log.i("APIFactory", "address from script:" + pKey.toAddress(MainNetParams.get()).toString());
// Log.i("APIFactory", "uncompressed public key from script:" + Hex.toHexString(pKey.decompress().getPubKey()));
if(((JSONObject)inArray.get(0)).has("outpoint")) {
JSONObject received_from = ((JSONObject) inArray.get(0)).getJSONObject("outpoint");
String strHash = received_from.getString("txid");
int idx = received_from.getInt("vout");
byte[] hashBytes = Hex.decode(strHash);
Sha256Hash txHash = new Sha256Hash(hashBytes);
TransactionOutPoint outPoint = new TransactionOutPoint(MainNetParams.get(), idx, txHash);
byte[] outpoint = outPoint.bitcoinSerialize();
// Log.i("APIFactory", "outpoint:" + Hex.toHexString(outpoint));
try {
mask = BIP47Util.getInstance(context).getIncomingMask(script.getPubKey(), outpoint);
// Log.i("APIFactory", "mask:" + Hex.toHexString(mask));
}
catch(Exception e) {
e.printStackTrace();
}
}
}
}
if(jsonObject.has("outputs")) {
JSONArray outArray = (JSONArray)jsonObject.get("outputs");
JSONObject outObj = null;
boolean isIncoming = false;
String _addr = null;
String script = null;
String op_return = null;
for(int j = 0; j < outArray.length(); j++) {
outObj = (JSONObject)outArray.get(j);
if(outObj.has("address")) {
_addr = outObj.getString("address");
if(addr.equals(_addr)) {
isIncoming = true;
}
}
if(outObj.has("scriptpubkey")) {
script = outObj.getString("scriptpubkey");
if(script.startsWith("6a4c50")) {
op_return = script;
}
}
}
if(isIncoming && op_return != null && op_return.startsWith("6a4c50")) {
payload = Hex.decode(op_return.substring(6));
}
}
if(mask != null && payload != null) {
try {
byte[] xlat_payload = PaymentCode.blind(payload, mask);
// Log.i("APIFactory", "xlat_payload:" + Hex.toHexString(xlat_payload));
pcode = new PaymentCode(xlat_payload);
// Log.i("APIFactory", "incoming payment code:" + pcode.toString());
if(!pcode.toString().equals(BIP47Util.getInstance(context).getPaymentCode().toString()) && pcode.isValid() && !BIP47Meta.getInstance().incomingExists(pcode.toString())) {
BIP47Meta.getInstance().setLabel(pcode.toString(), "");
BIP47Meta.getInstance().setIncomingStatus(hash);
}
}
catch(AddressFormatException afe) {
afe.printStackTrace();
}
}
// get receiving addresses for spends from decoded payment code
if(pcode != null) {
try {
// initial lookup
for(int i = 0; i < 3; i++) {
PaymentAddress receiveAddress = BIP47Util.getInstance(context).getReceiveAddress(pcode, i);
// Log.i("APIFactory", "receive from " + i + ":" + receiveAddress.getReceiveECKey().toAddress(MainNetParams.get()).toString());
BIP47Meta.getInstance().setIncomingIdx(pcode.toString(), i, receiveAddress.getReceiveECKey().toAddress(MainNetParams.get()).toString());
BIP47Meta.getInstance().getIdx4AddrLookup().put(receiveAddress.getReceiveECKey().toAddress(MainNetParams.get()).toString(), i);
BIP47Meta.getInstance().getPCode4AddrLookup().put(receiveAddress.getReceiveECKey().toAddress(MainNetParams.get()).toString(), pcode.toString());
// PaymentAddress sendAddress = BIP47Util.getInstance(context).getSendAddress(pcode, i);
// Log.i("APIFactory", "send to " + i + ":" + sendAddress.getSendECKey().toAddress(MainNetParams.get()).toString());
}
}
catch(Exception e) {
;
}
}
}
}
public synchronized int getNotifTxConfirmations(String hash) {
// Log.i("APIFactory", "Notif tx:" + hash);
JSONObject jsonObject = null;
try {
StringBuilder url = new StringBuilder(WebUtil.SAMOURAI_API2);
url.append("tx/");
url.append(hash);
url.append("?fees=1");
// Log.i("APIFactory", "Notif tx:" + url.toString());
String response = WebUtil.getInstance(null).getURL(url.toString());
// Log.i("APIFactory", "Notif tx:" + response);
jsonObject = new JSONObject(response);
// Log.i("APIFactory", "Notif tx json:" + jsonObject.toString());
return parseNotifTx(jsonObject);
}
catch(Exception e) {
jsonObject = null;
e.printStackTrace();
}
return 0;
}
public synchronized int parseNotifTx(JSONObject jsonObject) throws JSONException {
int cf = 0;
if(jsonObject != null && jsonObject.has("block") && jsonObject.getJSONObject("block").has("height")) {
long latestBlockHeght = getLatestBlockHeight();
long height = jsonObject.getJSONObject("block").getLong("height");
cf = (int)((latestBlockHeght - height) + 1);
if(cf < 0) {
cf = 0;
}
}
return cf;
}
public synchronized JSONObject getUnspentOutputs(String[] xpubs) {
JSONObject jsonObject = null;
try {
String response = null;
if(!TorUtil.getInstance(context).statusFromBroadcast()) {
StringBuilder args = new StringBuilder();
args.append("active=");
args.append(StringUtils.join(xpubs, URLEncoder.encode("|", "UTF-8")));
response = WebUtil.getInstance(context).postURL(WebUtil.SAMOURAI_API2 + "unspent?", args.toString());
}
else {
HashMap<String,String> args = new HashMap<String,String>();
args.put("active", StringUtils.join(xpubs, "|"));
response = WebUtil.getInstance(context).tor_postURL(WebUtil.SAMOURAI_API2 + "unspent", args);
}
parseUnspentOutputs(response);
}
catch(Exception e) {
jsonObject = null;
e.printStackTrace();
}
return jsonObject;
}
private synchronized boolean parseUnspentOutputs(String unspents) {
if(unspents != null) {
try {
JSONObject jsonObj = new JSONObject(unspents);
if(jsonObj == null || !jsonObj.has("unspent_outputs")) {
return false;
}
JSONArray utxoArray = jsonObj.getJSONArray("unspent_outputs");
if(utxoArray == null || utxoArray.length() == 0) {
return false;
}
for (int i = 0; i < utxoArray.length(); i++) {
JSONObject outDict = utxoArray.getJSONObject(i);
byte[] hashBytes = Hex.decode((String)outDict.get("tx_hash"));
Sha256Hash txHash = Sha256Hash.wrap(hashBytes);
int txOutputN = ((Number)outDict.get("tx_output_n")).intValue();
BigInteger value = BigInteger.valueOf(((Number)outDict.get("value")).longValue());
String script = (String)outDict.get("script");
byte[] scriptBytes = Hex.decode(script);
int confirmations = ((Number)outDict.get("confirmations")).intValue();
try {
String address = new Script(scriptBytes).getToAddress(MainNetParams.get()).toString();
if(outDict.has("xpub")) {
JSONObject xpubObj = (JSONObject)outDict.get("xpub");
String path = (String)xpubObj.get("path");
String m = (String)xpubObj.get("m");
unspentPaths.put(address, path);
unspentAccounts.put(address, AddressFactory.getInstance(context).xpub2account().get(m));
}
// Construct the output
MyTransactionOutPoint outPoint = new MyTransactionOutPoint(txHash, txOutputN, value, scriptBytes, address);
outPoint.setConfirmations(confirmations);
if(utxos.containsKey(script)) {
utxos.get(script).getOutpoints().add(outPoint);
}
else {
UTXO utxo = new UTXO();
utxo.getOutpoints().add(outPoint);
utxos.put(script, utxo);
}
}
catch(Exception e) {
;
}
}
return true;
}
catch(JSONException je) {
;
}
}
return false;
}
public synchronized JSONObject getAddressInfo(String addr) {
return getXPUB(new String[] { addr });
}
public synchronized JSONObject getTxInfo(String hash) {
JSONObject jsonObject = null;
try {
StringBuilder url = new StringBuilder(WebUtil.SAMOURAI_API2);
url.append("tx/");
url.append(hash);
url.append("?fees=true");
String response = WebUtil.getInstance(context).getURL(url.toString());
jsonObject = new JSONObject(response);
}
catch(Exception e) {
jsonObject = null;
e.printStackTrace();
}
return jsonObject;
}
public synchronized JSONObject getBlockHeader(String hash) {
JSONObject jsonObject = null;
try {
StringBuilder url = new StringBuilder(WebUtil.SAMOURAI_API2);
url.append("header/");
url.append(hash);
String response = WebUtil.getInstance(context).getURL(url.toString());
jsonObject = new JSONObject(response);
}
catch(Exception e) {
jsonObject = null;
e.printStackTrace();
}
return jsonObject;
}
public synchronized JSONObject getDynamicFees() {
JSONObject jsonObject = null;
try {
int sel = PrefsUtil.getInstance(context).getValue(PrefsUtil.FEE_PROVIDER_SEL, 0);
if(sel == 2) {
int[] blocks = new int[] { 2, 6, 24 };
List<SuggestedFee> suggestedFees = new ArrayList<SuggestedFee>();
JSONRPC jsonrpc = new JSONRPC(TrustedNodeUtil.getInstance().getUser(), TrustedNodeUtil.getInstance().getPassword(), TrustedNodeUtil.getInstance().getNode(), TrustedNodeUtil.getInstance().getPort());
for(int i = 0; i < blocks.length; i++) {
JSONObject feeObj = jsonrpc.getFeeEstimate(blocks[i]);
if(feeObj != null && feeObj.has("result")) {
double fee = feeObj.getDouble("result");
SuggestedFee suggestedFee = new SuggestedFee();
suggestedFee.setDefaultPerKB(BigInteger.valueOf((long)(fee * 1e8)));
suggestedFee.setStressed(false);
suggestedFee.setOK(true);
suggestedFees.add(suggestedFee);
}
}
if(suggestedFees.size() > 0) {
FeeUtil.getInstance().setEstimatedFees(suggestedFees);
}
}
else {
StringBuilder url = new StringBuilder(sel == 0 ? WebUtil._21CO_FEE_URL : WebUtil.BITCOIND_FEE_URL);
// Log.i("APIFactory", "Dynamic fees:" + url.toString());
String response = WebUtil.getInstance(null).getURL(url.toString());
// Log.i("APIFactory", "Dynamic fees response:" + response);
try {
jsonObject = new JSONObject(response);
if(sel == 0) {
parseDynamicFees_21(jsonObject);
}
else {
parseDynamicFees_bitcoind(jsonObject);
}
}
catch(JSONException je) {
je.printStackTrace();
jsonObject = null;
}
}
}
catch(Exception e) {
jsonObject = null;
e.printStackTrace();
}
return jsonObject;
}
private synchronized boolean parseDynamicFees_21(JSONObject jsonObject) throws JSONException {
if(jsonObject != null) {
// 21.co API
List<SuggestedFee> suggestedFees = new ArrayList<SuggestedFee>();
if(jsonObject.has("fastestFee")) {
long fee = jsonObject.getInt("fastestFee");
SuggestedFee suggestedFee = new SuggestedFee();
suggestedFee.setDefaultPerKB(BigInteger.valueOf(fee * 1000L));
suggestedFee.setStressed(false);
suggestedFee.setOK(true);
suggestedFees.add(suggestedFee);
}
if(jsonObject.has("halfHourFee")) {
long fee = jsonObject.getInt("halfHourFee");
SuggestedFee suggestedFee = new SuggestedFee();
suggestedFee.setDefaultPerKB(BigInteger.valueOf(fee * 1000L));
suggestedFee.setStressed(false);
suggestedFee.setOK(true);
suggestedFees.add(suggestedFee);
}
if(jsonObject.has("hourFee")) {
long fee = jsonObject.getInt("hourFee");
SuggestedFee suggestedFee = new SuggestedFee();
suggestedFee.setDefaultPerKB(BigInteger.valueOf(fee * 1000L));
suggestedFee.setStressed(false);
suggestedFee.setOK(true);
suggestedFees.add(suggestedFee);
}
if(suggestedFees.size() > 0) {
FeeUtil.getInstance().setEstimatedFees(suggestedFees);
// Log.d("APIFactory", "high fee:" + FeeUtil.getInstance().getHighFee().getDefaultPerKB().toString());
// Log.d("APIFactory", "suggested fee:" + FeeUtil.getInstance().getSuggestedFee().getDefaultPerKB().toString());
// Log.d("APIFactory", "low fee:" + FeeUtil.getInstance().getLowFee().getDefaultPerKB().toString());
}
return true;
}
return false;
}
private synchronized boolean parseDynamicFees_bitcoind(JSONObject jsonObject) throws JSONException {
if(jsonObject != null) {
// bitcoind
List<SuggestedFee> suggestedFees = new ArrayList<SuggestedFee>();
if(jsonObject.has("2")) {
long fee = jsonObject.getInt("2");
SuggestedFee suggestedFee = new SuggestedFee();
suggestedFee.setDefaultPerKB(BigInteger.valueOf(fee * 1000L));
suggestedFee.setStressed(false);
suggestedFee.setOK(true);
suggestedFees.add(suggestedFee);
}
if(jsonObject.has("6")) {
long fee = jsonObject.getInt("6");
SuggestedFee suggestedFee = new SuggestedFee();
suggestedFee.setDefaultPerKB(BigInteger.valueOf(fee * 1000L));
suggestedFee.setStressed(false);
suggestedFee.setOK(true);
suggestedFees.add(suggestedFee);
}
if(jsonObject.has("24")) {
long fee = jsonObject.getInt("24");
SuggestedFee suggestedFee = new SuggestedFee();
suggestedFee.setDefaultPerKB(BigInteger.valueOf(fee * 1000L));
suggestedFee.setStressed(false);
suggestedFee.setOK(true);
suggestedFees.add(suggestedFee);
}
if(suggestedFees.size() > 0) {
FeeUtil.getInstance().setEstimatedFees(suggestedFees);
// Log.d("APIFactory", "high fee:" + FeeUtil.getInstance().getHighFee().getDefaultPerKB().toString());
// Log.d("APIFactory", "suggested fee:" + FeeUtil.getInstance().getSuggestedFee().getDefaultPerKB().toString());
// Log.d("APIFactory", "low fee:" + FeeUtil.getInstance().getLowFee().getDefaultPerKB().toString());
}
return true;
}
return false;
}
public synchronized void validateAPIThread() {
final Handler handler = new Handler();
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
if(ConnectivityStatus.hasConnectivity(context)) {
try {
String response = WebUtil.getInstance(context).getURL(WebUtil.SAMOURAI_API_CHECK);
JSONObject jsonObject = new JSONObject(response);
if(!jsonObject.has("process")) {
showAlertDialog(context.getString(R.string.api_error), false);
}
}
catch(Exception e) {
showAlertDialog(context.getString(R.string.cannot_reach_api), false);
}
} else {
showAlertDialog(context.getString(R.string.no_internet), false);
}
handler.post(new Runnable() {
@Override
public void run() {
;
}
});
Looper.loop();
}
}).start();
}
private void showAlertDialog(final String message, final boolean forceExit){
if (!((Activity) context).isFinishing()) {
if(alertDialog != null)alertDialog.dismiss();
final AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(message);
builder.setCancelable(false);
if(!forceExit) {
builder.setPositiveButton(R.string.retry,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface d, int id) {
d.dismiss();
//Retry
validateAPIThread();
}
});
}
builder.setNegativeButton(R.string.exit,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface d, int id) {
d.dismiss();
((Activity) context).finish();
}
});
alertDialog = builder.create();
alertDialog.show();
}
}
public synchronized void initWallet() {
Log.i("APIFactory", "initWallet()");
initWalletAmounts();
}
private synchronized void initWalletAmounts() {
APIFactory.getInstance(context).reset();
List<String> addressStrings = new ArrayList<String>();
String[] s = null;
try {
xpub_txs.put(HD_WalletFactory.getInstance(context).get().getAccount(0).xpubstr(), new ArrayList<Tx>());
addressStrings.addAll(Arrays.asList(BIP47Meta.getInstance().getIncomingAddresses(false)));
for(String pcode : BIP47Meta.getInstance().getUnspentProviders()) {
for(String addr : BIP47Meta.getInstance().getUnspentAddresses(context, pcode)) {
if(!addressStrings.contains(addr)) {
addressStrings.add(addr);
}
}
}
if(addressStrings.size() > 0) {
s = addressStrings.toArray(new String[0]);
// Log.i("APIFactory", addressStrings.toString());
getUnspentOutputs(s);
}
HD_Wallet hdw = HD_WalletFactory.getInstance(context).get();
if(hdw != null && hdw.getXPUBs() != null) {
String[] all = null;
if(s != null && s.length > 0) {
all = new String[hdw.getXPUBs().length + s.length];
System.arraycopy(hdw.getXPUBs(), 0, all, 0, hdw.getXPUBs().length);
System.arraycopy(s, 0, all, hdw.getXPUBs().length, s.length);
}
else {
all = hdw.getXPUBs();
}
APIFactory.getInstance(context).getXPUB(all);
String[] xs = new String[2];
xs[0] = HD_WalletFactory.getInstance(context).get().getAccount(0).xpubstr();
xs[1] = HD_WalletFactory.getInstance(context).get().getAccount(1).xpubstr();
getUnspentOutputs(xs);
getDynamicFees();
}
}
catch (IndexOutOfBoundsException ioobe) {
ioobe.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
}
public synchronized int syncBIP47Incoming(String[] addresses) {
JSONObject jsonObject = getXPUB(addresses);
int ret = 0;
try {
if(jsonObject != null && jsonObject.has("addresses")) {
JSONArray addressArray = (JSONArray)jsonObject.get("addresses");
JSONObject addrObj = null;
for(int i = 0; i < addressArray.length(); i++) {
addrObj = (JSONObject)addressArray.get(i);
long amount = 0L;
int nbTx = 0;
String addr = null;
String pcode = null;
int idx = -1;
if(addrObj.has("address")) {
addr = (String)addrObj.get("address");
pcode = BIP47Meta.getInstance().getPCode4Addr(addr);
idx = BIP47Meta.getInstance().getIdx4Addr(addr);
if(addrObj.has("final_balance")) {
amount = addrObj.getLong("final_balance");
if(amount > 0L) {
BIP47Meta.getInstance().addUnspent(pcode, idx);
}
else {
BIP47Meta.getInstance().removeUnspent(pcode, Integer.valueOf(idx));
}
}
if(addrObj.has("n_tx")) {
nbTx = addrObj.getInt("n_tx");
if(nbTx > 0) {
// Log.i("APIFactory", "sync receive idx:" + idx + ", " + addr);
ret++;
}
}
}
}
}
}
catch(Exception e) {
jsonObject = null;
e.printStackTrace();
}
return ret;
}
public synchronized int syncBIP47Outgoing(String[] addresses) {
JSONObject jsonObject = getXPUB(addresses);
int ret = 0;
try {
if(jsonObject != null && jsonObject.has("addresses")) {
JSONArray addressArray = (JSONArray)jsonObject.get("addresses");
JSONObject addrObj = null;
for(int i = 0; i < addressArray.length(); i++) {
addrObj = (JSONObject)addressArray.get(i);
int nbTx = 0;
String addr = null;
String pcode = null;
int idx = -1;
if(addrObj.has("address")) {
addr = (String)addrObj.get("address");
pcode = BIP47Meta.getInstance().getPCode4Addr(addr);
idx = BIP47Meta.getInstance().getIdx4Addr(addr);
if(addrObj.has("n_tx")) {
nbTx = addrObj.getInt("n_tx");
if(nbTx > 0) {
int stored = BIP47Meta.getInstance().getOutgoingIdx(pcode);
if(idx >= stored) {
// Log.i("APIFactory", "sync send idx:" + idx + ", " + addr);
BIP47Meta.getInstance().setOutgoingIdx(pcode, idx + 1);
}
ret++;
}
}
}
}
}
}
catch(Exception e) {
jsonObject = null;
e.printStackTrace();
}
return ret;
}
public long getXpubBalance() {
return xpub_balance;
}
public void setXpubBalance(long value) {
xpub_balance = value;
}
public HashMap<String,Long> getXpubAmounts() {
return xpub_amounts;
}
public HashMap<String,List<Tx>> getXpubTxs() {
return xpub_txs;
}
public HashMap<String, String> getUnspentPaths() {
return unspentPaths;
}
public HashMap<String, Integer> getUnspentAccounts() {
return unspentAccounts;
}
public List<UTXO> getUtxos() {
List<UTXO> unspents = new ArrayList<UTXO>();
unspents.addAll(utxos.values());
return unspents;
}
public void setUtxos(HashMap<String, UTXO> utxos) {
APIFactory.utxos = utxos;
}
public synchronized List<Tx> getAllXpubTxs() {
List<Tx> ret = new ArrayList<Tx>();
for(String key : xpub_txs.keySet()) {
List<Tx> txs = xpub_txs.get(key);
for(Tx tx : txs) {
ret.add(tx);
}
}
Collections.sort(ret, new TxMostRecentDateComparator());
return ret;
}
public synchronized UTXO getUnspentOutputsForSweep(String address) {
try {
String response = null;
if(!TorUtil.getInstance(context).statusFromBroadcast()) {
StringBuilder args = new StringBuilder();
args.append("active=");
args.append(address);
response = WebUtil.getInstance(context).postURL(WebUtil.SAMOURAI_API2 + "unspent?", args.toString());
}
else {
HashMap<String,String> args = new HashMap<String,String>();
args.put("active", address);
response = WebUtil.getInstance(context).tor_postURL(WebUtil.SAMOURAI_API2 + "unspent", args);
}
return parseUnspentOutputsForSweep(response);
}
catch(Exception e) {
e.printStackTrace();
}
return null;
}
private synchronized UTXO parseUnspentOutputsForSweep(String unspents) {
UTXO utxo = null;
if(unspents != null) {
try {
JSONObject jsonObj = new JSONObject(unspents);
if(jsonObj == null || !jsonObj.has("unspent_outputs")) {
return null;
}
JSONArray utxoArray = jsonObj.getJSONArray("unspent_outputs");
if(utxoArray == null || utxoArray.length() == 0) {
return null;
}
// Log.d("APIFactory", "unspents found:" + outputsRoot.size());
for (int i = 0; i < utxoArray.length(); i++) {
JSONObject outDict = utxoArray.getJSONObject(i);
byte[] hashBytes = Hex.decode((String)outDict.get("tx_hash"));
Sha256Hash txHash = Sha256Hash.wrap(hashBytes);
int txOutputN = ((Number)outDict.get("tx_output_n")).intValue();
BigInteger value = BigInteger.valueOf(((Number)outDict.get("value")).longValue());
String script = (String)outDict.get("script");
byte[] scriptBytes = Hex.decode(script);
int confirmations = ((Number)outDict.get("confirmations")).intValue();
try {
String address = new Script(scriptBytes).getToAddress(MainNetParams.get()).toString();
// Construct the output
MyTransactionOutPoint outPoint = new MyTransactionOutPoint(txHash, txOutputN, value, scriptBytes, address);
outPoint.setConfirmations(confirmations);
if(utxo == null) {
utxo = new UTXO();
}
utxo.getOutpoints().add(outPoint);
}
catch(Exception e) {
;
}
}
}
catch(JSONException je) {
;
}
}
return utxo;
}
public static class TxMostRecentDateComparator implements Comparator<Tx> {
public int compare(Tx t1, Tx t2) {
final int BEFORE = -1;
final int EQUAL = 0;
final int AFTER = 1;
int ret = 0;
if(t1.getTS() > t2.getTS()) {
ret = BEFORE;
}
else if(t1.getTS() < t2.getTS()) {
ret = AFTER;
}
else {
ret = EQUAL;
}
return ret;
}
}
}
|
package com.zigapk.weather;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
public class DetailsActivity extends AppCompatActivity {
private static TextView cityNameTv;
private static TextView temperatureTv;
private static TextView humidityTv;
private static TextView descriptionTv;
private static ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
cityNameTv = (TextView) findViewById(R.id.city_name);
temperatureTv = (TextView) findViewById(R.id.temperature);
humidityTv = (TextView) findViewById(R.id.humidity);
descriptionTv = (TextView) findViewById(R.id.description);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
Intent intent = getIntent();
final City city = (City) intent.getSerializableExtra("city");
if (city.get_performed) {
cityNameTv.setText(city.user_input_name);
temperatureTv.setText(city.main.formatedTemp());
humidityTv.setText(Integer.toString(city.main.humidity));
descriptionTv.setText(city.weather[0].description);
}else {
progressBar.setVisibility(View.VISIBLE);
cityNameTv.setText(city.user_input_name);
new Thread(new Runnable() {
@Override
public void run() {
try {
final City tempCity = city.get();
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
cityNameTv.setText(tempCity.name);
temperatureTv.setText(tempCity.main.formatedTemp());
humidityTv.setText(Integer.toString(tempCity.main.humidity));
descriptionTv.setText(tempCity.weather[0].description);
progressBar.setVisibility(View.GONE);
}
});
} catch (Exception e) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
cityNameTv.setText(MainActivity.context.getResources().getString(
R.string.no_data_for, city.user_input_name));
cityNameTv.setTextColor(MainActivity.context.getResources().
getColor(R.color.red));
temperatureTv.setText("/");
humidityTv.setText("/");
descriptionTv.setText("/");
progressBar.setVisibility(View.GONE);
}
});
}
}
}).start();
}
}
}
|
package de.mygrades.main;
import android.content.Context;
import android.content.Intent;
/**
* Helper class with convenience methods to start background
* threads by sending intents to the MainService.
*
* This class is responsible for creating unique request ids for different requests.
*/
public class MainServiceHelper {
private Context context;
public MainServiceHelper(Context context) {
this.context = context.getApplicationContext();
}
/**
* Start a worker thread to load all universities from the server.
*
* @param publishedOnly - only published universities or all.
*/
public void getUniversities(boolean publishedOnly) {
int method = MainService.METHOD_GET_UNIVERSITIES;
// set request id
long requestId = concatenateLong(method, 0);
// start worker thread in background
Intent intent = getBasicIntent(MainService.PROCESSOR_UNIVERSITY, method, requestId);
intent.putExtra(MainService.PUBLISHED_ONLY, publishedOnly);
context.startService(intent);
}
/**
* Starts a worker thread to get a detailed university from the server.
*
* @param universityId - university id
*/
public void getDetailedUniversity(long universityId) {
int method = MainService.METHOD_GET_DETAILED_UNIVERSITY;
// set request id
long requestId = concatenateLong(method, universityId);
// start worker thread in background
Intent intent = getBasicIntent(MainService.PROCESSOR_UNIVERSITY, method, requestId);
intent.putExtra(MainService.UNIVERSITY_ID, universityId);
context.startService(intent);
}
/**
* Load all grades from the database.
*/
public void getGradesFromDatabase() {
int method = MainService.METHOD_GET_GRADES_FROM_DATABASE;
// set request id
long requestId = concatenateLong(method, 0);
// start worker thread in background
Intent intent = getBasicIntent(MainService.PROCESSOR_GRADES, method, requestId);
context.startService(intent);
}
/**
* Load all universities from the database.
*
* @param publishedOnly - only published universities or all.
*/
public void getUniversitiesFromDatabase(boolean publishedOnly) {
int method = MainService.METHOD_GET_UNIVERSITIES_FROM_DATABASE;
// set request id
long requestId = concatenateLong(method, 0);
// start worker thread in background
Intent intent = getBasicIntent(MainService.PROCESSOR_UNIVERSITY, method, requestId);
intent.putExtra(MainService.PUBLISHED_ONLY, publishedOnly);
context.startService(intent);
}
/**
* Starts a worker thread to scrape for new grades.
*/
public void scrapeForGrades() {
int method = MainService.METHOD_SCRAPE_FOR_GRADES;
// set request id
long requestId = concatenateLong(method, 0);
// start worker thread in background
Intent intent = getBasicIntent(MainService.PROCESSOR_GRADES, method, requestId);
context.startService(intent);
}
/**
* Starts a worker thread to save the username and password
* and starts scraping for grades afterwards.
*
* @param username - username
* @param password - password
*/
public void loginAndScrapeForGrades(String username, String password) {
int method = MainService.METHOD_LOGIN_AND_SCRAPE_FOR_GRADES;
// set request id
long requestId = concatenateLong(method, 0);
// start worker thread in background
Intent intent = getBasicIntent(MainService.PROCESSOR_LOGIN, method, requestId);
intent.putExtra(MainService.USERNAME, username);
intent.putExtra(MainService.PASSWORD, password);
context.startService(intent);
}
/**
* Starts a worker thread to delete all userdata and grades from the database.
*/
public void logout() {
int method = MainService.METHOD_LOGOUT;
// set request id
long requestId = concatenateLong(method, 0);
// start worker thread in background
Intent intent = getBasicIntent(MainService.PROCESSOR_LOGIN, method, requestId);
context.startService(intent);
}
/**
* Build a basic intent with required extra data for each request.
*
* @param processor - processor to create (declared in the MainService)
* @param method - method to call (declared in the MainService)
* @param requestId - request id
* @return intent
*/
private Intent getBasicIntent(int processor, int method, long requestId) {
Intent intent = new Intent(context, MainService.class);
intent.putExtra(MainService.PROCESSOR_KEY, processor);
intent.putExtra(MainService.METHOD_KEY, method);
intent.putExtra(MainService.REQUEST_ID, requestId);
return intent;
}
/**
* Concatenates two long values.
* This can be used to generate unique request ids.
*
* @param a first long value
* @param b second long value
* @return ab as long
*/
private long concatenateLong(long a, long b) {
return Long.parseLong("" + a + b);
}
}
|
package info.nightscout.androidaps;
import android.app.Application;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import com.crashlytics.android.Crashlytics;
import com.crashlytics.android.answers.Answers;
import com.crashlytics.android.answers.CustomEvent;
import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.squareup.otto.Bus;
import com.squareup.otto.ThreadEnforcer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import info.nightscout.androidaps.Services.Intents;
import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.interfaces.InsulinInterface;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.Actions.ActionsFragment;
import info.nightscout.androidaps.plugins.Careportal.CareportalFragment;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderFragment;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.ConstraintsObjectives.ObjectivesFragment;
import info.nightscout.androidaps.plugins.ConstraintsSafety.SafetyPlugin;
import info.nightscout.androidaps.plugins.InsulinFastacting.InsulinFastactingFragment;
import info.nightscout.androidaps.plugins.InsulinFastactingProlonged.InsulinFastactingProlongedFragment;
import info.nightscout.androidaps.plugins.InsulinOrefCurves.InsulinOrefFreePeakFragment;
import info.nightscout.androidaps.plugins.InsulinOrefCurves.InsulinOrefRapidActingFragment;
import info.nightscout.androidaps.plugins.InsulinOrefCurves.InsulinOrefUltraRapidActingFragment;
import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.Loop.LoopFragment;
import info.nightscout.androidaps.plugins.NSClientInternal.NSClientInternalFragment;
import info.nightscout.androidaps.plugins.NSClientInternal.receivers.AckAlarmReceiver;
import info.nightscout.androidaps.plugins.OpenAPSAMA.OpenAPSAMAFragment;
import info.nightscout.androidaps.plugins.OpenAPSMA.OpenAPSMAFragment;
import info.nightscout.androidaps.plugins.Overview.OverviewFragment;
import info.nightscout.androidaps.plugins.Persistentnotification.PersistentNotificationPlugin;
import info.nightscout.androidaps.plugins.ProfileCircadianPercentage.CircadianPercentageProfileFragment;
import info.nightscout.androidaps.plugins.ProfileLocal.LocalProfileFragment;
import info.nightscout.androidaps.plugins.ProfileNS.NSProfileFragment;
import info.nightscout.androidaps.plugins.ProfileSimple.SimpleProfileFragment;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRFragment;
import info.nightscout.androidaps.plugins.PumpDanaR.services.DanaRExecutionService;
import info.nightscout.androidaps.plugins.PumpDanaRKorean.DanaRKoreanFragment;
import info.nightscout.androidaps.plugins.PumpDanaRKorean.services.DanaRKoreanExecutionService;
import info.nightscout.androidaps.plugins.PumpDanaRv2.DanaRv2Fragment;
import info.nightscout.androidaps.plugins.PumpDanaRv2.services.DanaRv2ExecutionService;
import info.nightscout.androidaps.plugins.PumpMDI.MDIPlugin;
import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin;
import info.nightscout.androidaps.plugins.SensitivityAAPS.SensitivityAAPSPlugin;
import info.nightscout.androidaps.plugins.SensitivityOref0.SensitivityOref0Plugin;
import info.nightscout.androidaps.plugins.SensitivityWeightedAverage.SensitivityWeightedAveragePlugin;
import info.nightscout.androidaps.plugins.SmsCommunicator.SmsCommunicatorFragment;
import info.nightscout.androidaps.plugins.SourceGlimp.SourceGlimpPlugin;
import info.nightscout.androidaps.plugins.SourceMM640g.SourceMM640gPlugin;
import info.nightscout.androidaps.plugins.SourceNSClient.SourceNSClientPlugin;
import info.nightscout.androidaps.plugins.SourceXdrip.SourceXdripPlugin;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsFragment;
import info.nightscout.androidaps.plugins.Wear.WearFragment;
import info.nightscout.androidaps.plugins.XDripStatusline.StatuslinePlugin;
import info.nightscout.androidaps.receivers.DataReceiver;
import info.nightscout.androidaps.receivers.KeepAliveReceiver;
import info.nightscout.androidaps.receivers.NSAlarmReceiver;
import info.nightscout.utils.NSUpload;
import io.fabric.sdk.android.Fabric;
public class MainApp extends Application {
private static Logger log = LoggerFactory.getLogger(MainApp.class);
private static KeepAliveReceiver keepAliveReceiver;
private static Bus sBus;
private static MainApp sInstance;
public static Resources sResources;
private static DatabaseHelper sDatabaseHelper = null;
private static ConfigBuilderPlugin sConfigBuilder = null;
private static ArrayList<PluginBase> pluginsList = null;
private static DataReceiver dataReceiver = new DataReceiver();
private static NSAlarmReceiver alarmReciever = new NSAlarmReceiver();
private static AckAlarmReceiver ackAlarmReciever = new AckAlarmReceiver();
private LocalBroadcastManager lbm;
@Override
public void onCreate() {
super.onCreate();
Fabric.with(this, new Crashlytics());
Fabric.with(this, new Answers());
Crashlytics.setString("BUILDVERSION", BuildConfig.BUILDVERSION);
log.info("Version: " + BuildConfig.VERSION_NAME);
log.info("BuildVersion: " + BuildConfig.BUILDVERSION);
sBus = new Bus(ThreadEnforcer.ANY);
sInstance = this;
sResources = getResources();
registerLocalBroadcastReceiver();
if (pluginsList == null) {
pluginsList = new ArrayList<>();
// Register all tabs in app here
pluginsList.add(OverviewFragment.getPlugin());
pluginsList.add(IobCobCalculatorPlugin.getPlugin());
if (Config.ACTION) pluginsList.add(ActionsFragment.getPlugin());
pluginsList.add(InsulinFastactingFragment.getPlugin());
pluginsList.add(InsulinFastactingProlongedFragment.getPlugin());
pluginsList.add(InsulinOrefRapidActingFragment.getPlugin());
pluginsList.add(InsulinOrefUltraRapidActingFragment.getPlugin());
pluginsList.add(InsulinOrefFreePeakFragment.getPlugin());
pluginsList.add(SensitivityOref0Plugin.getPlugin());
//pluginsList.add(SensitivityAAPSPlugin.getPlugin());
//pluginsList.add(SensitivityWeightedAveragePlugin.getPlugin());
if (Config.DANAR) pluginsList.add(DanaRFragment.getPlugin());
if (Config.DANAR) pluginsList.add(DanaRKoreanFragment.getPlugin());
if (Config.DANARv2) pluginsList.add(DanaRv2Fragment.getPlugin());
pluginsList.add(CareportalFragment.getPlugin());
if (Config.MDI) pluginsList.add(MDIPlugin.getPlugin());
if (Config.VIRTUALPUMP) pluginsList.add(VirtualPumpPlugin.getInstance());
if (Config.LOOPENABLED) pluginsList.add(LoopFragment.getPlugin());
if (Config.OPENAPSENABLED) pluginsList.add(OpenAPSMAFragment.getPlugin());
if (Config.OPENAPSENABLED) pluginsList.add(OpenAPSAMAFragment.getPlugin());
pluginsList.add(NSProfileFragment.getPlugin());
if (Config.OTHERPROFILES) pluginsList.add(SimpleProfileFragment.getPlugin());
if (Config.OTHERPROFILES) pluginsList.add(LocalProfileFragment.getPlugin());
if (Config.OTHERPROFILES)
pluginsList.add(CircadianPercentageProfileFragment.getPlugin());
pluginsList.add(TreatmentsFragment.getPlugin());
if (Config.SAFETY) pluginsList.add(SafetyPlugin.getPlugin());
if (Config.APS) pluginsList.add(ObjectivesFragment.getPlugin());
if (!Config.NSCLIENT)
pluginsList.add(SourceXdripPlugin.getPlugin());
pluginsList.add(SourceNSClientPlugin.getPlugin());
if (!Config.NSCLIENT)
pluginsList.add(SourceMM640gPlugin.getPlugin());
if (!Config.NSCLIENT)
pluginsList.add(SourceGlimpPlugin.getPlugin());
if (Config.SMSCOMMUNICATORENABLED) pluginsList.add(SmsCommunicatorFragment.getPlugin());
if (Config.WEAR) pluginsList.add(WearFragment.getPlugin(this));
pluginsList.add(StatuslinePlugin.getPlugin(this));
pluginsList.add(new PersistentNotificationPlugin(this));
pluginsList.add(NSClientInternalFragment.getPlugin());
pluginsList.add(sConfigBuilder = ConfigBuilderFragment.getPlugin());
MainApp.getConfigBuilder().initialize();
}
NSUpload.uploadAppStart();
if (MainApp.getConfigBuilder().isClosedModeEnabled())
Answers.getInstance().logCustom(new CustomEvent("AppStart-ClosedLoop"));
else
Answers.getInstance().logCustom(new CustomEvent("AppStart"));
startKeepAliveService();
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
PumpInterface pump = MainApp.getConfigBuilder();
if (pump != null)
pump.refreshDataFromPump("Initialization");
}
});
t.start();
}
private void registerLocalBroadcastReceiver() {
lbm = LocalBroadcastManager.getInstance(this);
lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_NEW_TREATMENT));
lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_CHANGED_TREATMENT));
lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_REMOVED_TREATMENT));
lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_NEW_SGV));
lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_NEW_PROFILE));
lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_NEW_STATUS));
lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_NEW_MBG));
lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_NEW_DEVICESTATUS));
lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_NEW_CAL));
//register alarms
lbm.registerReceiver(alarmReciever, new IntentFilter(Intents.ACTION_ALARM));
lbm.registerReceiver(alarmReciever, new IntentFilter(Intents.ACTION_ANNOUNCEMENT));
lbm.registerReceiver(alarmReciever, new IntentFilter(Intents.ACTION_CLEAR_ALARM));
lbm.registerReceiver(alarmReciever, new IntentFilter(Intents.ACTION_URGENT_ALARM));
//register ack alarm
lbm.registerReceiver(ackAlarmReciever, new IntentFilter(Intents.ACTION_ACK_ALARM));
}
private void startKeepAliveService() {
if (keepAliveReceiver == null) {
keepAliveReceiver = new KeepAliveReceiver();
if (Config.DANAR) {
startService(new Intent(this, DanaRExecutionService.class));
startService(new Intent(this, DanaRKoreanExecutionService.class));
startService(new Intent(this, DanaRv2ExecutionService.class));
}
keepAliveReceiver.setAlarm(this);
}
}
public void stopKeepAliveService() {
if (keepAliveReceiver != null)
keepAliveReceiver.cancelAlarm(this);
}
public static Bus bus() {
return sBus;
}
public static MainApp instance() {
return sInstance;
}
public static DatabaseHelper getDbHelper() {
if (sDatabaseHelper == null) {
sDatabaseHelper = OpenHelperManager.getHelper(sInstance, DatabaseHelper.class);
}
return sDatabaseHelper;
}
public static void closeDbHelper() {
if (sDatabaseHelper != null) {
sDatabaseHelper.close();
sDatabaseHelper = null;
}
}
public static ConfigBuilderPlugin getConfigBuilder() {
return sConfigBuilder;
}
public static ArrayList<PluginBase> getPluginsList() {
return pluginsList;
}
public static ArrayList<PluginBase> getSpecificPluginsList(int type) {
ArrayList<PluginBase> newList = new ArrayList<>();
if (pluginsList != null) {
for (PluginBase p : pluginsList) {
if (p.getType() == type)
newList.add(p);
}
} else {
log.error("pluginsList=null");
}
return newList;
}
@Nullable
public static InsulinInterface getInsulinIterfaceById(int id) {
if (pluginsList != null) {
for (PluginBase p : pluginsList) {
if (p.getType() == PluginBase.INSULIN && ((InsulinInterface) p).getId() == id)
return (InsulinInterface) p;
}
} else {
log.error("InsulinInterface not found");
}
return null;
}
public static ArrayList<PluginBase> getSpecificPluginsVisibleInList(int type) {
ArrayList<PluginBase> newList = new ArrayList<>();
if (pluginsList != null) {
for (PluginBase p : pluginsList) {
if (p.getType() == type)
if (p.showInList(type))
newList.add(p);
}
} else {
log.error("pluginsList=null");
}
return newList;
}
public static ArrayList<PluginBase> getSpecificPluginsListByInterface(Class interfaceClass) {
ArrayList<PluginBase> newList = new ArrayList<>();
if (pluginsList != null) {
for (PluginBase p : pluginsList) {
if (p.getClass() != ConfigBuilderPlugin.class && interfaceClass.isAssignableFrom(p.getClass()))
newList.add(p);
}
} else {
log.error("pluginsList=null");
}
return newList;
}
public static ArrayList<PluginBase> getSpecificPluginsVisibleInListByInterface(Class interfaceClass, int type) {
ArrayList<PluginBase> newList = new ArrayList<>();
if (pluginsList != null) {
for (PluginBase p : pluginsList) {
if (p.getClass() != ConfigBuilderPlugin.class && interfaceClass.isAssignableFrom(p.getClass()))
if (p.showInList(type))
newList.add(p);
}
} else {
log.error("pluginsList=null");
}
return newList;
}
@Nullable
public static <T extends PluginBase> T getSpecificPlugin(Class<T> pluginClass) {
if (pluginsList != null) {
for (PluginBase p : pluginsList) {
if (pluginClass.isAssignableFrom(p.getClass()))
return (T) p;
}
} else {
log.error("pluginsList=null");
}
return null;
}
@Override
public void onTerminate() {
super.onTerminate();
sDatabaseHelper.close();
}
}
|
package info.nightscout.androidaps;
import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.os.SystemClock;
import androidx.annotation.PluralsRes;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import com.crashlytics.android.Crashlytics;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.j256.ormlite.android.apptools.OpenHelperManager;
import net.danlew.android.joda.JodaTimeAndroid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.ArrayList;
import info.nightscout.androidaps.data.ConstraintChecker;
import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin;
import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAPlugin;
import info.nightscout.androidaps.plugins.aps.openAPSMA.OpenAPSMAPlugin;
import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.constraints.dstHelper.DstHelperPlugin;
import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugin;
import info.nightscout.androidaps.plugins.constraints.safety.SafetyPlugin;
import info.nightscout.androidaps.plugins.constraints.signatureVerifier.SignatureVerifierPlugin;
import info.nightscout.androidaps.plugins.constraints.storage.StorageConstraintPlugin;
import info.nightscout.androidaps.plugins.constraints.versionChecker.VersionCheckerPlugin;
import info.nightscout.androidaps.plugins.general.actions.ActionsPlugin;
import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin;
import info.nightscout.androidaps.plugins.general.careportal.CareportalPlugin;
import info.nightscout.androidaps.plugins.general.food.FoodPlugin;
import info.nightscout.androidaps.plugins.general.maintenance.LoggerUtils;
import info.nightscout.androidaps.plugins.general.maintenance.MaintenancePlugin;
import info.nightscout.androidaps.plugins.general.nsclient.NSClientPlugin;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.plugins.general.nsclient.receivers.AckAlarmReceiver;
import info.nightscout.androidaps.plugins.general.nsclient.receivers.DBAccessReceiver;
import info.nightscout.androidaps.plugins.general.overview.OverviewPlugin;
import info.nightscout.androidaps.plugins.general.persistentNotification.PersistentNotificationPlugin;
import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorPlugin;
import info.nightscout.androidaps.plugins.general.wear.WearPlugin;
import info.nightscout.androidaps.plugins.general.xdripStatusline.StatuslinePlugin;
import info.nightscout.androidaps.plugins.insulin.InsulinOrefFreePeakPlugin;
import info.nightscout.androidaps.plugins.insulin.InsulinOrefRapidActingPlugin;
import info.nightscout.androidaps.plugins.insulin.InsulinOrefUltraRapidActingPlugin;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.profile.local.LocalProfilePlugin;
import info.nightscout.androidaps.plugins.profile.ns.NSProfilePlugin;
import info.nightscout.androidaps.plugins.profile.simple.SimpleProfilePlugin;
import info.nightscout.androidaps.plugins.pump.combo.ComboPlugin;
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin;
import info.nightscout.androidaps.plugins.pump.danaRKorean.DanaRKoreanPlugin;
import info.nightscout.androidaps.plugins.pump.danaRS.DanaRSPlugin;
import info.nightscout.androidaps.plugins.pump.danaRv2.DanaRv2Plugin;
import info.nightscout.androidaps.plugins.pump.insight.LocalInsightPlugin;
import info.nightscout.androidaps.plugins.pump.mdi.MDIPlugin;
import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin;
import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin;
import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin;
import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref0Plugin;
import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin;
import info.nightscout.androidaps.plugins.sensitivity.SensitivityWeightedAveragePlugin;
import info.nightscout.androidaps.plugins.source.SourceDexcomPlugin;
import info.nightscout.androidaps.plugins.source.SourceEversensePlugin;
import info.nightscout.androidaps.plugins.source.SourceGlimpPlugin;
import info.nightscout.androidaps.plugins.source.SourceMM640gPlugin;
import info.nightscout.androidaps.plugins.source.SourceNSClientPlugin;
import info.nightscout.androidaps.plugins.source.SourcePoctechPlugin;
import info.nightscout.androidaps.plugins.source.SourceTomatoPlugin;
import info.nightscout.androidaps.plugins.source.SourceXdripPlugin;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.receivers.DataReceiver;
import info.nightscout.androidaps.receivers.KeepAliveReceiver;
import info.nightscout.androidaps.receivers.NSAlarmReceiver;
import info.nightscout.androidaps.receivers.TimeDateOrTZChangeReceiver;
import info.nightscout.androidaps.services.Intents;
import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.LocaleHelper;
import io.fabric.sdk.android.Fabric;
import static info.nightscout.androidaps.plugins.constraints.versionChecker.VersionCheckerUtilsKt.triggerCheckVersion;
public class MainApp extends Application {
private static Logger log = LoggerFactory.getLogger(L.CORE);
private static KeepAliveReceiver keepAliveReceiver;
private static MainApp sInstance;
public static Resources sResources;
private static FirebaseAnalytics mFirebaseAnalytics;
private static DatabaseHelper sDatabaseHelper = null;
private static ConstraintChecker sConstraintsChecker = null;
private static ArrayList<PluginBase> pluginsList = null;
private static DataReceiver dataReceiver = new DataReceiver();
private static NSAlarmReceiver alarmReciever = new NSAlarmReceiver();
private static AckAlarmReceiver ackAlarmReciever = new AckAlarmReceiver();
private static DBAccessReceiver dbAccessReciever = new DBAccessReceiver();
private LocalBroadcastManager lbm;
BroadcastReceiver btReceiver;
TimeDateOrTZChangeReceiver timeDateOrTZChangeReceiver;
public static boolean devBranch;
public static boolean engineeringMode;
@Override
public void onCreate() {
super.onCreate();
log.debug("onCreate");
sInstance = this;
sResources = getResources();
LocaleHelper.INSTANCE.update(this);
sConstraintsChecker = new ConstraintChecker();
sDatabaseHelper = OpenHelperManager.getHelper(sInstance, DatabaseHelper.class);
Thread.setDefaultUncaughtExceptionHandler((thread, ex) -> {
if (ex instanceof InternalError) {
// usually the app trying to spawn a thread while being killed
return;
}
log.error("Uncaught exception crashing app", ex);
});
try {
if (FabricPrivacy.fabricEnabled()) {
Fabric.with(this, new Crashlytics());
}
} catch (Exception e) {
log.error("Error with Fabric init! " + e);
}
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
mFirebaseAnalytics.setAnalyticsCollectionEnabled(!Boolean.getBoolean("disableFirebase"));
JodaTimeAndroid.init(this);
log.info("Version: " + BuildConfig.VERSION_NAME);
log.info("BuildVersion: " + BuildConfig.BUILDVERSION);
log.info("Remote: " + BuildConfig.REMOTE);
String extFilesDir = LoggerUtils.getLogDirectory();
File engineeringModeSemaphore = new File(extFilesDir, "engineering_mode");
engineeringMode = engineeringModeSemaphore.exists() && engineeringModeSemaphore.isFile();
devBranch = BuildConfig.VERSION.contains("-") || BuildConfig.VERSION.matches(".*[a-zA-Z]+.*");
registerLocalBroadcastReceiver();
//trigger here to see the new version on app start after an update
triggerCheckVersion();
//setBTReceiver();
if (pluginsList == null) {
pluginsList = new ArrayList<>();
// Register all tabs in app here
pluginsList.add(OverviewPlugin.INSTANCE);
pluginsList.add(IobCobCalculatorPlugin.getPlugin());
if (!Config.NSCLIENT) pluginsList.add(ActionsPlugin.INSTANCE);
pluginsList.add(InsulinOrefRapidActingPlugin.getPlugin());
pluginsList.add(InsulinOrefUltraRapidActingPlugin.getPlugin());
pluginsList.add(InsulinOrefFreePeakPlugin.getPlugin());
pluginsList.add(SensitivityOref0Plugin.getPlugin());
pluginsList.add(SensitivityAAPSPlugin.getPlugin());
pluginsList.add(SensitivityWeightedAveragePlugin.getPlugin());
pluginsList.add(SensitivityOref1Plugin.getPlugin());
if (Config.PUMPDRIVERS) pluginsList.add(DanaRPlugin.getPlugin());
if (Config.PUMPDRIVERS) pluginsList.add(DanaRKoreanPlugin.getPlugin());
if (Config.PUMPDRIVERS) pluginsList.add(DanaRv2Plugin.getPlugin());
if (Config.PUMPDRIVERS) pluginsList.add(DanaRSPlugin.getPlugin());
if (Config.PUMPDRIVERS) pluginsList.add(LocalInsightPlugin.getPlugin());
if (Config.PUMPDRIVERS) pluginsList.add(ComboPlugin.getPlugin());
if (Config.PUMPDRIVERS) pluginsList.add(MedtronicPumpPlugin.getPlugin());
if (!Config.NSCLIENT) pluginsList.add(MDIPlugin.getPlugin());
pluginsList.add(VirtualPumpPlugin.getPlugin());
pluginsList.add(CareportalPlugin.getPlugin());
if (Config.APS) pluginsList.add(LoopPlugin.getPlugin());
if (Config.APS) pluginsList.add(OpenAPSMAPlugin.getPlugin());
if (Config.APS) pluginsList.add(OpenAPSAMAPlugin.getPlugin());
if (Config.APS) pluginsList.add(OpenAPSSMBPlugin.getPlugin());
pluginsList.add(NSProfilePlugin.getPlugin());
if (!Config.NSCLIENT) pluginsList.add(SimpleProfilePlugin.getPlugin());
if (!Config.NSCLIENT) pluginsList.add(LocalProfilePlugin.getPlugin());
pluginsList.add(TreatmentsPlugin.getPlugin());
if (!Config.NSCLIENT) pluginsList.add(SafetyPlugin.getPlugin());
if (!Config.NSCLIENT) pluginsList.add(VersionCheckerPlugin.INSTANCE);
if (Config.APS) pluginsList.add(StorageConstraintPlugin.getPlugin());
if (Config.APS) pluginsList.add(SignatureVerifierPlugin.getPlugin());
if (Config.APS) pluginsList.add(ObjectivesPlugin.INSTANCE);
pluginsList.add(SourceXdripPlugin.getPlugin());
pluginsList.add(SourceNSClientPlugin.getPlugin());
pluginsList.add(SourceMM640gPlugin.getPlugin());
pluginsList.add(SourceGlimpPlugin.getPlugin());
pluginsList.add(SourceDexcomPlugin.INSTANCE);
pluginsList.add(SourcePoctechPlugin.getPlugin());
pluginsList.add(SourceTomatoPlugin.getPlugin());
pluginsList.add(SourceEversensePlugin.getPlugin());
if (!Config.NSCLIENT) pluginsList.add(SmsCommunicatorPlugin.getPlugin());
pluginsList.add(FoodPlugin.getPlugin());
pluginsList.add(WearPlugin.initPlugin(this));
pluginsList.add(StatuslinePlugin.initPlugin(this));
pluginsList.add(PersistentNotificationPlugin.getPlugin());
pluginsList.add(NSClientPlugin.getPlugin());
// if (engineeringMode) pluginsList.add(TidepoolPlugin.INSTANCE);
pluginsList.add(MaintenancePlugin.initPlugin(this));
pluginsList.add(AutomationPlugin.INSTANCE);
pluginsList.add(ConfigBuilderPlugin.getPlugin());
pluginsList.add(DstHelperPlugin.getPlugin());
ConfigBuilderPlugin.getPlugin().initialize();
}
NSUpload.uploadAppStart();
final PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
if (pump != null) {
new Thread(() -> {
SystemClock.sleep(5000);
ConfigBuilderPlugin.getPlugin().getCommandQueue().readStatus("Initialization", null);
startKeepAliveService();
}).start();
}
}
private void registerLocalBroadcastReceiver() {
lbm = LocalBroadcastManager.getInstance(this);
lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_NEW_TREATMENT));
lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_CHANGED_TREATMENT));
lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_REMOVED_TREATMENT));
lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_NEW_FOOD));
lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_CHANGED_FOOD));
lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_REMOVED_FOOD));
lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_NEW_SGV));
lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_NEW_PROFILE));
lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_NEW_STATUS));
lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_NEW_MBG));
lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_NEW_DEVICESTATUS));
lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_NEW_CAL));
//register alarms
lbm.registerReceiver(alarmReciever, new IntentFilter(Intents.ACTION_ALARM));
lbm.registerReceiver(alarmReciever, new IntentFilter(Intents.ACTION_ANNOUNCEMENT));
lbm.registerReceiver(alarmReciever, new IntentFilter(Intents.ACTION_CLEAR_ALARM));
lbm.registerReceiver(alarmReciever, new IntentFilter(Intents.ACTION_URGENT_ALARM));
//register ack alarm
lbm.registerReceiver(ackAlarmReciever, new IntentFilter(Intents.ACTION_ACK_ALARM));
//register dbaccess
lbm.registerReceiver(dbAccessReciever, new IntentFilter(Intents.ACTION_DATABASE));
this.timeDateOrTZChangeReceiver = new TimeDateOrTZChangeReceiver();
this.timeDateOrTZChangeReceiver.registerBroadcasts(this);
}
private void startKeepAliveService() {
if (keepAliveReceiver == null) {
keepAliveReceiver = new KeepAliveReceiver();
keepAliveReceiver.setAlarm(this);
}
}
public void stopKeepAliveService() {
if (keepAliveReceiver != null)
KeepAliveReceiver.cancelAlarm(this);
}
public static String gs(int id) {
return sResources.getString(id);
}
public static String gs(int id, Object... args) {
return sResources.getString(id, args);
}
public static String gq(@PluralsRes int id, int quantity, Object... args) {
return sResources.getQuantityString(id, quantity, args);
}
public static int gc(int id) {
return sResources.getColor(id);
}
public static MainApp instance() {
return sInstance;
}
public static DatabaseHelper getDbHelper() {
return sDatabaseHelper;
}
public static void closeDbHelper() {
if (sDatabaseHelper != null) {
sDatabaseHelper.close();
sDatabaseHelper = null;
}
}
public static FirebaseAnalytics getFirebaseAnalytics() {
return mFirebaseAnalytics;
}
public static ConstraintChecker getConstraintChecker() {
return sConstraintsChecker;
}
public static ArrayList<PluginBase> getPluginsList() {
return pluginsList;
}
public static ArrayList<PluginBase> getSpecificPluginsList(PluginType type) {
ArrayList<PluginBase> newList = new ArrayList<>();
if (pluginsList != null) {
for (PluginBase p : pluginsList) {
if (p.getType() == type)
newList.add(p);
}
} else {
log.error("pluginsList=null");
}
return newList;
}
public static ArrayList<PluginBase> getSpecificPluginsVisibleInList(PluginType type) {
ArrayList<PluginBase> newList = new ArrayList<>();
if (pluginsList != null) {
for (PluginBase p : pluginsList) {
if (p.getType() == type)
if (p.showInList(type))
newList.add(p);
}
} else {
log.error("pluginsList=null");
}
return newList;
}
public static ArrayList<PluginBase> getSpecificPluginsListByInterface(Class interfaceClass) {
ArrayList<PluginBase> newList = new ArrayList<>();
if (pluginsList != null) {
for (PluginBase p : pluginsList) {
if (p.getClass() != ConfigBuilderPlugin.class && interfaceClass.isAssignableFrom(p.getClass()))
newList.add(p);
}
} else {
log.error("pluginsList=null");
}
return newList;
}
public static ArrayList<PluginBase> getSpecificPluginsVisibleInListByInterface(Class interfaceClass, PluginType type) {
ArrayList<PluginBase> newList = new ArrayList<>();
if (pluginsList != null) {
for (PluginBase p : pluginsList) {
if (p.getClass() != ConfigBuilderPlugin.class && interfaceClass.isAssignableFrom(p.getClass()))
if (p.showInList(type))
newList.add(p);
}
} else {
log.error("pluginsList=null");
}
return newList;
}
public static boolean isEngineeringModeOrRelease() {
if (!Config.APS)
return true;
return engineeringMode || !devBranch;
}
public static boolean isDev() {
return devBranch;
}
public static int getIcon() {
if (Config.NSCLIENT)
return R.mipmap.ic_yellowowl;
else if (Config.PUMPCONTROL)
return R.mipmap.ic_pumpcontrol;
else
return R.mipmap.ic_launcher;
}
public static int getNotificationIcon() {
if (Config.NSCLIENT)
return R.drawable.ic_notif_nsclient;
else if (Config.PUMPCONTROL)
return R.drawable.ic_notif_pumpcontrol;
else
return R.drawable.ic_notif_aaps;
}
@Override
public void onTerminate() {
if (L.isEnabled(L.CORE))
log.debug("onTerminate");
super.onTerminate();
if (sDatabaseHelper != null) {
sDatabaseHelper.close();
sDatabaseHelper = null;
}
if (btReceiver != null) {
unregisterReceiver(btReceiver);
}
if (timeDateOrTZChangeReceiver != null) {
unregisterReceiver(timeDateOrTZChangeReceiver);
}
}
public static int dpToPx(int dp) {
float scale = sResources.getDisplayMetrics().density;
return (int) (dp * scale + 0.5f);
}
}
|
package org.mozilla.focus.utils;
import android.content.Context;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RawRes;
import android.util.Base64;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;
public class HtmlLoader {
/**
* Load a given (html or css) resource file into a String. The input can contain tokens that will
* be replaced with localised strings.
*
* @param substitutionTable A table of substitions, e.g. %shortMessage% -> "Error loading page..."
* Can be null, in which case no substitutions will be made.
* @return The file content, with all substitutions having being made.
*/
public static String loadResourceFile(@NonNull final Context context,
@NonNull final @RawRes int resourceID,
@Nullable final Map<String, String> substitutionTable) {
BufferedReader fileReader = null;
try {
final InputStream fileStream = context.getResources().openRawResource(resourceID);
fileReader = new BufferedReader(new InputStreamReader(fileStream));
final StringBuilder outputBuffer = new StringBuilder();
String line;
while ((line = fileReader.readLine()) != null) {
if (substitutionTable != null) {
for (final Map.Entry<String, String> entry : substitutionTable.entrySet()) {
line = line.replace(entry.getKey(), entry.getValue());
}
}
outputBuffer.append(line);
}
return outputBuffer.toString();
} catch (final IOException e) {
throw new IllegalStateException("Unable to load error page data");
} finally {
try {
if (fileReader != null) {
fileReader.close();
}
} catch (IOException e) {
// There's pretty much nothing we can do here. It doesn't seem right to crash
// just because we couldn't close a file?
}
}
}
private final static byte[] pngHeader = new byte[] { -119, 80, 78, 71, 13, 10, 26, 10 };
public static String loadPngAsDataURI(@NonNull final Context context,
@NonNull final @DrawableRes int resourceID) {
// We are copying the approach BitmapFactory.decodeResource(Resources, int, Options)
// uses - you are explicitly allowed to open Drawables, but the method has a @RawRes
// annotation (despite officially supporting Drawables).
//noinspection ResourceType
final InputStream pngInputStream = context.getResources().openRawResource(resourceID);
final BufferedReader reader = new BufferedReader(new InputStreamReader(pngInputStream));
final StringBuilder builder = new StringBuilder();
builder.append("data:image/png;base64,");
try {
// Base64 encodes 3 bytes at a time, make sure we have a multiple of 3 here
// I don't know what a sensible chunk size is, let's just go with 300b.
final byte[] data = new byte[3*100];
int bytesRead;
boolean headerVerified = false;
while ((bytesRead = pngInputStream.read(data)) > 0) {
// Sanity check: lets make sure this is still a png (i.e. make sure the build system
// or Android haven't broken / change the image format).
if (!headerVerified) {
if (bytesRead < 8) {
throw new IllegalStateException("Loaded drawable is improbably small");
}
for (int i = 0; i < pngHeader.length; i++) {
if (data[i] != pngHeader[i]) {
throw new IllegalStateException("Invalid png detected");
}
}
headerVerified = true;
}
builder.append(Base64.encodeToString(data, 0, bytesRead, 0));
}
} catch (IOException e) {
throw new IllegalStateException("Unable to load png data");
}
return builder.toString();
}
}
|
package mx.udlap.is522.tedroid.activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import mx.udlap.is522.tedroid.R;
import mx.udlap.is522.tedroid.data.Score;
import mx.udlap.is522.tedroid.data.dao.DAOFactory;
import mx.udlap.is522.tedroid.data.dao.ScoreDAO;
import mx.udlap.is522.tedroid.view.GameBoardView;
import mx.udlap.is522.tedroid.view.NextTetrominoView;
import mx.udlap.is522.tedroid.view.model.Tetromino;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Actividad principal del juego donde se puede jugar realmente.
*
* @author Daniel Pedraza-Arcega
* @since 1.0
*/
public class GameActivity extends BaseGameActivity {
private int totalLines;
private int score;
private int level;
private NextTetrominoView nextTetrominoView;
private GameBoardView gameBoardView;
private TextView pauseTextView;
private TextView gameOverTextView;
private TextView scoreTextView;
private TextView levelTextView;
private TextView linesTextView;
private MediaPlayer mediaPlayer;
private Menu menu;
private AlertDialog restartDialog;
private AlertDialog exitDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
mediaPlayer = MediaPlayer.create(this, R.raw.tetris_theme);
mediaPlayer.setLooping(true);
mediaPlayer.start();
pauseTextView = (TextView) findViewById(R.id.pause_text);
gameOverTextView = (TextView) findViewById(R.id.game_over_text);
scoreTextView = (TextView) findViewById(R.id.score);
levelTextView = (TextView) findViewById(R.id.levels);
linesTextView = (TextView) findViewById(R.id.lines);
nextTetrominoView = (NextTetrominoView) findViewById(R.id.next_tetromino);
gameBoardView = (GameBoardView) findViewById(R.id.game_board);
gameBoardView.setOnCommingNextTetrominoListener(new GameBoardView.OnCommingNextTetrominoListener() {
@Override
public void onCommingNextTetromino(Tetromino nextTetromino) {
nextTetrominoView.setTetromino(nextTetromino);
}
});
gameBoardView.setOnPointsAwardedListener(new GameBoardView.OnPointsAwardedListener() {
@Override
public void onHardDropped(int gridSpaces) {
score += gridSpaces * 2;
scoreTextView.setText(String.valueOf(score));
}
@Override
public void onSoftDropped(int gridSpaces) {
score += gridSpaces;
scoreTextView.setText(String.valueOf(score));
}
public void onClearedLines(int linesCleared) {
if (updateLevelIfNeeded(linesCleared)) gameBoardView.levelUp();
updateScoreWhenClearLines(linesCleared);
linesTextView.setText(String.valueOf(totalLines));
scoreTextView.setText(String.valueOf(score));
levelTextView.setText(String.valueOf(level));
}
});
gameBoardView.setOnGameOverListener(new GameBoardView.OnGameOverListener() {
@Override
public void onGameOver() {
mediaPlayer.pause();
gameBoardView.setVisibility(View.GONE);
gameOverTextView.setVisibility(View.VISIBLE);
Score newScore = new Score();
newScore.setLevel(level);
newScore.setLines(totalLines);
newScore.setPoints(score);
new ScoresAsyncTask().execute(newScore);
}
});
restartDialog = new AlertDialog.Builder(this)
.setMessage(R.string.restart_message)
.setCancelable(false)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
resetCounters();
scoreTextView.setText(String.valueOf(score));
levelTextView.setText(String.valueOf(level));
linesTextView.setText(String.valueOf(totalLines));
pauseTextView.setVisibility(View.GONE);
gameOverTextView.setVisibility(View.GONE);
gameBoardView.setVisibility(View.VISIBLE);
gameBoardView.setLevel(GameBoardView.DEFAULT_LEVEL); // TODO: resetear el nivel seleccionado
gameBoardView.restartGame();
MenuItem pauseResumeItem = menu.findItem(R.id.action_pause_resume);
pauseResumeItem.setIcon(R.drawable.ic_action_pause);
if (!mediaPlayer.isPlaying()) mediaPlayer.start();
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
if (pauseTextView.getVisibility() == View.GONE &&
!gameBoardView.isGameOver()) {
gameBoardView.resumeGame();
if (!mediaPlayer.isPlaying()) mediaPlayer.start();
}
}
})
.create();
exitDialog = new AlertDialog.Builder(this)
.setMessage(R.string.exit_message)
.setCancelable(false)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
if (pauseTextView.getVisibility() == View.GONE &&
!gameBoardView.isGameOver()) {
gameBoardView.resumeGame();
if (!mediaPlayer.isPlaying()) mediaPlayer.start();
}
}
})
.create();
scoreTextView.setText(String.valueOf(score));
levelTextView.setText(String.valueOf(level));
linesTextView.setText(String.valueOf(totalLines));
}
@Override
protected void onResume() {
super.onResume();
if (gameBoardView.isPaused()) {
if (pauseTextView.getVisibility() == View.GONE &&
!exitDialog.isShowing() &&
!restartDialog.isShowing()) {
gameBoardView.resumeGame();
if (!mediaPlayer.isPlaying()) mediaPlayer.start();
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.game, menu);
this.menu = menu;
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_pause_resume:
if (!gameBoardView.isGameOver()) {
if (gameBoardView.isPaused()) {
pauseTextView.setVisibility(View.GONE);
gameBoardView.setVisibility(View.VISIBLE);
gameBoardView.resumeGame();
if (!mediaPlayer.isPlaying()) mediaPlayer.start();
item.setIcon(R.drawable.ic_action_pause);
} else {
gameBoardView.setVisibility(View.GONE);
pauseTextView.setVisibility(View.VISIBLE);
gameBoardView.pauseGame();
mediaPlayer.pause();
item.setIcon(R.drawable.ic_action_play);
}
}
return true;
case R.id.action_restart:
gameBoardView.pauseGame();
mediaPlayer.pause();
restartDialog.show();
return true;
default: return super.onOptionsItemSelected(item);
}
}
@Override
protected void onPause() {
super.onPause();
if (mediaPlayer != null && mediaPlayer.isPlaying()) mediaPlayer.pause();
if (!gameBoardView.isPaused()) gameBoardView.pauseGame();
}
@Override
public void onBackPressed() {
gameBoardView.pauseGame();
mediaPlayer.pause();
exitDialog.show();
}
@Override
public void finish() {
super.finish();
gameBoardView.stopGame();
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
/**
* Actualiza el puntaje del juego cuando hay lineas borradas y desbloquea
* logros.
*
* @param linesCleared las lineas borradas.
*/
private void updateScoreWhenClearLines(int linesCleared) {
int factor;
switch (linesCleared) {
case 1: factor = 40; break;
case 2: factor = 100; break;
case 3: factor = 300; break;
case 4: factor = 1200; unlockAchievement(R.string.in_a_row_achievement_id); break;
default: factor = 1; break;
}
score += factor * (level + 1);
if (score >= 999999) unlockAchievement(R.string.believe_it_or_not_achievement_id);
}
/**
* Actualiza el nivel del juego al checar las lineas borradas y desbloquea
* logros.
*
* @param linesCleared las lineas borradas.
* @param si se subio de nivel o no.
*/
private boolean updateLevelIfNeeded(int linesCleared) {
boolean shouldLevelUp = totalLines % 10 >= 6;
totalLines += linesCleared;
if (totalLines >= 9999) unlockAchievement(R.string.like_a_boss_achievement_id);
if (shouldLevelUp && totalLines % 10 <= 3) {
level++;
if (level >= 10) unlockAchievement(R.string.whats_next_achievement_id);
else {
switch(level) {
case 1: unlockAchievement(R.string.for_dummies_achievement_id); break;
case 2: unlockAchievement(R.string.as_easy_as_pie_achievement_id); break;
case 3: unlockAchievement(R.string.beginner_achievement_id); break;
case 4: unlockAchievement(R.string.amateur_achievement_id); break;
case 5: unlockAchievement(R.string.expert_achievement_id); break;
case 6: unlockAchievement(R.string.master_achievement_id); break;
case 7: unlockAchievement(R.string.pro_achievement_id); break;
case 8: unlockAchievement(R.string.pro_plus_plus_achievement_id); break;
case 9: unlockAchievement(R.string.lucky_you_achievement_id); break;
}
}
return true;
}
return false;
}
/**
* Resetea todos los contadores.
*/
private void resetCounters() {
score = 0;
level = 0;
totalLines = 0;
}
/**
* Solo se usa para pruebas.
*
* @return el menu de esta actividad.
*/
public Menu getMenu() {
return menu;
}
private class ScoresAsyncTask extends AsyncTask<Score, Void, List<Integer>> {
private ScoreDAO scoreDAO;
@Override
protected void onPreExecute() {
scoreDAO = new DAOFactory(getApplicationContext()).get(ScoreDAO.class);
}
@Override
protected List<Integer> doInBackground(Score... score) {
scoreDAO.save(score[0]);
ArrayList<Integer> unlockedAchievements = new ArrayList<Integer>();
Map<String, Integer> sums = scoreDAO.readSumOfLinesAndPoints();
int linesSum = sums.get("lines_sum");
int pointsSum = sums.get("points_sum");
if (linesSum >= 9999) unlockedAchievements.add(R.string.nothing_to_do_achievement_id);
if (linesSum >= 999999) unlockedAchievements.add(R.string.get_a_life_achievement_id);
if (pointsSum >= 9999) unlockedAchievements.add(R.string.boooooring_achievement_id);
if (pointsSum >= 999999) unlockedAchievements.add(R.string.tenacious_achievement_id);
return unlockedAchievements;
}
@Override
protected void onPostExecute(List<Integer> unlockedAchievements) {
for (int id : unlockedAchievements) {
unlockAchievement(id);
}
}
}
}
|
package com.rultor.env.ec2;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.model.CreateTagsRequest;
import com.amazonaws.services.ec2.model.Instance;
import com.amazonaws.services.ec2.model.RunInstancesRequest;
import com.amazonaws.services.ec2.model.RunInstancesResult;
import com.amazonaws.services.ec2.model.Tag;
import com.jcabi.aspects.Immutable;
import com.jcabi.aspects.Loggable;
import com.jcabi.aspects.RetryOnFailure;
import com.rultor.aws.EC2Client;
import com.rultor.env.Environment;
import com.rultor.env.Environments;
import com.rultor.spi.Signal;
import com.rultor.spi.Work;
import java.io.IOException;
import java.util.List;
import javax.validation.constraints.NotNull;
import lombok.EqualsAndHashCode;
/**
* Amazon EC2 environments.
*
* @author Yegor Bugayenko (yegor@tpc2.com)
* @version $Id$
* @since 1.0
*/
@Immutable
@EqualsAndHashCode(of = { "type", "ami", "group", "client" })
@Loggable(Loggable.DEBUG)
public final class EC2 implements Environments {
/**
* Work we're in.
*/
private final transient Work work;
/**
* Type of EC2 instance.
*/
private final transient String type;
/**
* Name of AMI.
*/
private final transient String ami;
/**
* EC2 security group.
*/
private final transient String group;
/**
* EC2 key pair.
*/
private final transient String pair;
/**
* EC2 client.
*/
private final transient EC2Client client;
/**
* Public ctor.
* @param wrk Work we're in
* @param tpe Instance type, for example "t1.micro"
* @param image AMI name
* @param grp Security group
* @param par Key pair
* @param akey AWS key
* @param scrt AWS secret
* @checkstyle ParameterNumber (5 lines)
*/
public EC2(final Work wrk, final String tpe, final String image,
final String grp, final String par, final String akey,
final String scrt) {
this(wrk, tpe, image, grp, par, new EC2Client.Simple(akey, scrt));
}
/**
* Public ctor.
* @param wrk Work we're in
* @param tpe Instance type, for example "t1.micro"
* @param image AMI name
* @param grp Security group
* @param par Key pair
* @param clnt EC2 client
* @checkstyle ParameterNumber (5 lines)
*/
public EC2(
@NotNull(message = "work can't be NULL") final Work wrk,
@NotNull(message = "instance type can't be NULL") final String tpe,
@NotNull(message = "AMI can't be NULL") final String image,
@NotNull(message = "security group can't be NULL") final String grp,
@NotNull(message = "key pair can't be NULL") final String par,
@NotNull(message = "AWS client can't be NULL") final EC2Client clnt) {
this.work = wrk;
this.type = tpe;
this.ami = image;
this.group = grp;
this.pair = par;
this.client = clnt;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
return String.format(
// @checkstyle LineLength (1 line)
"EC2 `%s` instances with `%s` in `%s` security group with `%s` key pair accessed with %s",
this.type, this.ami, this.group, this.pair, this.client
);
}
/**
* {@inheritDoc}
*/
@Override
public Environment acquire() throws IOException {
final AmazonEC2 aws = this.client.get();
try {
final RunInstancesResult result = aws.runInstances(
new RunInstancesRequest()
.withInstanceType(this.type)
.withImageId(this.ami)
.withSecurityGroups(this.group)
.withKeyName(this.pair)
.withMinCount(1)
.withMaxCount(1)
);
final List<Instance> instances =
result.getReservation().getInstances();
if (instances.isEmpty()) {
throw new IllegalStateException(
String.format(
"failed to run an EC2 instance `%s` with AMI `%s`",
this.type,
this.ami
)
);
}
final Instance instance = instances.get(0);
Signal.log(
Signal.Mnemo.SUCCESS,
// @checkstyle LineLength (1 line)
"EC2 instance `%s` created, type=`%s`, ami=`%s`, key=`%s`, platform=`%s`",
instance.getInstanceId(),
this.type,
this.ami,
instance.getKeyName(),
instance.getPlatform()
);
return new EC2Environment(
this.work,
this.wrap(aws, instance).getInstanceId(),
this.client
);
} finally {
aws.shutdown();
}
}
/**
* Add tags and do some other wrapping to the running instance.
* @param aws AWS client
* @param instance Instance running (maybe already)
* @return The same instance
*/
@RetryOnFailure
private Instance wrap(final AmazonEC2 aws, final Instance instance) {
aws.createTags(
new CreateTagsRequest()
.withResources(instance.getInstanceId())
.withTags(
new Tag()
.withKey("Name")
.withValue(this.work.unit()),
new Tag()
.withKey("rultor:work:unit")
.withValue(this.work.unit()),
new Tag()
.withKey("rultor:work:owner")
.withValue(this.work.owner().toString()),
new Tag()
.withKey("rultor:work:started")
.withValue(this.work.started().toString())
)
);
return instance;
}
}
|
package com.exedio.cope;
import java.sql.Connection;
import com.exedio.dsmf.Schema;
import com.exedio.dsmf.Sequence;
final class PkSourceSequenceImpl implements PkSourceImpl
{
private final Type type;
private final String name;
PkSourceSequenceImpl(final Type type, final Database database)
{
this.type = type;
this.name = /*database.makeName(*/type.id + "_PkSeq"/*)*/; // TODO
}
public void makeSchema(final Schema schema)
{
new Sequence(schema, name);
}
public int next(final Connection connection)
{
return type.table.database.dialect.nextSequence(type.table.database, connection, name);
}
public void flush()
{
// empty
}
}
|
package com.joa_ebert.apparat.tools.dump;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import com.joa_ebert.apparat.abc.Abc;
import com.joa_ebert.apparat.abc.AbcPrinter;
import com.joa_ebert.apparat.swf.tags.ITag;
import com.joa_ebert.apparat.swf.tags.Tags;
import com.joa_ebert.apparat.swf.tags.control.DoABCTag;
import com.joa_ebert.apparat.swf.tags.define.DefineBitsJPEG2Tag;
import com.joa_ebert.apparat.tools.ITool;
import com.joa_ebert.apparat.tools.IToolConfiguration;
import com.joa_ebert.apparat.tools.ToolLog;
import com.joa_ebert.apparat.tools.ToolRunner;
import com.joa_ebert.apparat.tools.io.TagIO;
/**
*
* @author Joa Ebert
*
*/
public final class Dump implements ITool
{
public static void main( final String[] arguments )
{
final ToolRunner toolRunner = new ToolRunner( new Dump(), arguments );
toolRunner.run();
}
private IToolConfiguration config;
public String getHelp()
{
return "-input [file]\tThe input file\n" + "-abc\tWill dump ABCs.\n"
+ "-tags\t\tWill dump known tags.\n"
+ "-images\tWill dump images.";
}
public String getName()
{
return "Dump";
}
public boolean needsOutput()
{
return false;
}
public void run() throws Exception
{
if( config.getInput().endsWith( ".abc" ) )
{
final File input = new File( config.getInput() );
final Abc abc = new Abc();
abc.read( input );
final File file = new File( input.getName() + ".txt" );
ToolLog.info( "Exporting ABC to \"" + file.getName() + ".txt\"." );
final FileOutputStream fileOutputStream = new FileOutputStream(
file );
new AbcPrinter( new PrintWriter( fileOutputStream ) ).print( abc );
fileOutputStream.flush();
fileOutputStream.close();
}
else
{
final TagIO tagIO = new TagIO( config.getInput() );
tagIO.read();
if( config.hasOption( "tags" ) )
{
ToolLog.info( "Tags:" );
for( final ITag tag : tagIO.getTags() )
{
final String tagString = Tags.typeToString( tag.getType() );
String output = tagString;
if( tagString.length() < 5 )
{
output += "\t\t\t";
}
else if( tagString.length() < 12 )
{
output += "\t\t";
}
else
{
output += "\t";
}
ToolLog.success( output + tag.toString() );
}
}
if( config.hasOption( "images" ) )
{
for( final ITag tag : tagIO.getTags() )
{
if( tag.getType() == Tags.DefineBitsJPEG2 )
{
final DefineBitsJPEG2Tag defineBitsJPEG2 = (DefineBitsJPEG2Tag)tag;
String extension = "";
if( defineBitsJPEG2.imageData[ 0 ] == (byte)0xff )
{
extension = ".jpg";
}
else if( defineBitsJPEG2.imageData[ 0 ] == (byte)0x89 )
{
extension = ".png";
}
else if( defineBitsJPEG2.imageData[ 0 ] == (byte)0x47 )
{
extension = ".gif";
}
new File( "images" ).mkdirs();
final File file = new File( "images" + File.separator
+ defineBitsJPEG2.characterId + extension );
ToolLog.info( "Exporting JPEG image to \"images/"
+ file.getName() + "\"." );
final FileOutputStream fileOutputStream = new FileOutputStream(
file );
fileOutputStream.write( defineBitsJPEG2.imageData );
fileOutputStream.flush();
fileOutputStream.close();
}
}
}
if( config.hasOption( "abc" ) )
{
for( final ITag tag : tagIO.getTags() )
{
if( tag.getType() == Tags.DoABC )
{
final DoABCTag doABC = (DoABCTag)tag;
final Abc abc = new Abc();
abc.read( doABC );
final File file = new File( doABC.name + ".txt" );
ToolLog.info( "Exporting ABC to \"" + file.getName()
+ "\"." );
final FileOutputStream fileOutputStream = new FileOutputStream(
file );
new AbcPrinter( new PrintWriter( fileOutputStream ) )
.print( abc );
fileOutputStream.flush();
fileOutputStream.close();
}
}
}
tagIO.close();
}
}
public void setConfiguration( final IToolConfiguration configuration )
{
config = configuration;
}
}
|
package com.jme3.gde.core.util.notify;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.PrintWriter;
import java.io.StringWriter;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.awt.Notification;
import org.openide.awt.NotificationDisplayer;
import org.openide.util.RequestProcessor;
/**
*
* @author qbeukes.blogspot.com, used by metalklesk
*/
public class NotifyUtil {
/**
* Own request processor (thread pool) for NotifyUtil handling
* background tasks
*/
private static final RequestProcessor REQUEST_PROCESSOR =
new RequestProcessor("Notification processor", 1);
private NotifyUtil() {
}
/**
* Show message with the specified type and action listener
*/
public static Notification show(String title, String message, MessageType type, ActionListener actionListener, final int timeout) {
if (message == null) {
message = "null";
}
if (title == null) {
title = "null";
}
final Notification n = NotificationDisplayer.getDefault().
notify(title, type.getIcon(), message, actionListener);
if (timeout > 0) {
REQUEST_PROCESSOR.post(new Runnable() {
@Override
public void run() {
n.clear();
}
}, timeout);
}
return n;
}
/**
* Show message with the specified type and a default action which displays
* the message using {@link MessageUtil} with the same message type
*/
public static Notification show(String title, final String message, final MessageType type, int timeout) {
ActionListener actionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
MessageUtil.show(message, type);
}
};
return show(title, message, type, actionListener, timeout);
}
/**
* Show an information notification
*
* @param message
*/
public static Notification info(String title, String message) {
return info(title, message, true);
}
/**
* Show an information notification
*
* @param message
*/
public static Notification info(String title, String message, boolean clear) {
return show(title, message, MessageType.INFO, clear ? 3000 : 0);
}
/**
* Show an error notification
*
* @param message
*/
public static Notification error(String title, String message, boolean clear) {
return show(title, message, MessageType.ERROR, clear ? 10000 : 0);
}
/**
* Show an exception
*
* @param exception
*/
public static Notification error(Throwable exception) {
return error("Exception", exception.getMessage(), exception, false);
}
public static Notification error(String title, Throwable exception) {
return error(title, exception, false);
}
public static Notification error(String title, Throwable exception, boolean clear) {
return error(title, exception.getMessage(), exception, clear);
}
/**
* Show an error notification for an exception
*
* @param message
* @param exception
*/
public static Notification error(String title, String message, final Throwable exception, boolean clear) {
final NoteKeeper keeper = new NoteKeeper();
if (message == null) {
message = exception.getMessage();
}
if (title == null) {
message = exception.getMessage();
}
ActionListener actionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
StringWriter out = new StringWriter();
exception.printStackTrace(new PrintWriter(out));
String exception = out.toString();
DialogDisplayer.getDefault().notifyLater(new NotifyDescriptor.Message(exception, NotifyDescriptor.ERROR_MESSAGE));
keeper.note.clear();
}
};
keeper.note = show(title, message, MessageType.EXCEPTION, actionListener, clear ? 10000 : 0);
return keeper.note;
}
/**
* Show an warning notification
*
* @param message
*/
public static Notification warn(String title, String message, boolean clear) {
return show(title, message, MessageType.WARNING, clear ? 5000 : 0);
}
/**
* Show an plain notification
*
* @param message
*/
public static Notification plain(String title, String message, boolean clear) {
return show(title, message, MessageType.PLAIN, clear ? 3000 : 0);
}
private static class NoteKeeper {
Notification note;
}
}
|
package com.enioka.jqm.jdbc;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Entry point for all database-related operations, from initialization to schema upgrade, as well as creating sessions for querying the
* database.
*/
public class Db
{
private static Logger jqmlogger = LoggerFactory.getLogger(Db.class);
/**
* The version of the schema as it described in the current Maven artifact
*/
private static final int SCHEMA_VERSION = 1;
/**
* The SCHEMA_VERSION version is backward compatible until this version
*/
private static final int SCHEMA_COMPATIBLE_VERSION = 1;
/**
* The list of different database adapters. We are using reflection for loading them for future extensibility.
*/
private static String[] ADAPTERS = new String[] { "com.enioka.jqm.jdbc.DbImplPg", "com.enioka.jqm.jdbc.DbImplHsql",
"com.enioka.jqm.jdbc.DbImplOracle", "com.enioka.jqm.jdbc.DbImplMySql", "com.enioka.jqm.jdbc.DbImplDb2" };
private DataSource _ds;
private DbAdapter adapter = null;
private String product;
private Properties p = null;
/**
* Connects to the database by retrieving a DataDource from JNDI (with every parameter set to default, including the JNDI alias for the
* DataSource being jdbc/jqm).
*/
public Db()
{
this(null);
}
/**
* Constructor for cases when a DataSource is readily available (and not retrieved through JNDI).
*
* @param ds
* the existing DataSource.
* @param updateSchema
* set to true if the database schema should upgrade (if needed) during initialization
*/
public Db(DataSource ds, boolean updateSchema)
{
this._ds = ds;
this.p = new Properties();
init(updateSchema);
}
/**
* Main constructor. Properties may be null. Properties are not documented on purpose, as this is a private JQM API.
*
* @param props
*/
@SuppressWarnings("unchecked")
public Db(Properties properties)
{
this.p = properties != null ? properties : new Properties();
if (p.containsKey("com.enioka.jqm.jdbc.url"))
{
// In this case - full JDBC construction, not from JNDI. Only works for HSQLDB.
// Allow upgrade by default in this case (this is used only in tests)
boolean upgrade = Boolean.parseBoolean(p.getProperty("com.enioka.jqm.jdbc.allowSchemaUpdate", "true"));
String url = p.getProperty("com.enioka.jqm.jdbc.url");
DataSource ds = null;
if (url.contains("jdbc:hsqldb"))
{
Class<? extends DataSource> dsclass;
try
{
dsclass = (Class<? extends DataSource>) Class.forName("org.hsqldb.jdbc.JDBCDataSource");
}
catch (ClassNotFoundException e)
{
throw new IllegalStateException("The driver for database HSQLDB was not found in the classpath");
}
try
{
ds = dsclass.newInstance();
dsclass.getMethod("setDatabase", String.class).invoke(ds, "jdbc:hsqldb:mem:testdbengine");
}
catch (Exception e)
{
throw new DatabaseException("could not create datasource. See errors below.", e);
}
}
else
{
throw new IllegalArgumentException("this constructor does not support this database type - URL " + url);
}
this._ds = ds;
init(upgrade);
}
else
{
// Standard case: fetch a DataSource from JNDI.
String dsName = p.getProperty("com.enioka.jqm.jdbc.datasource", "jdbc/jqm");
// Ascending compatibility with v1.x: old name for the DataSource.
String oldName = p.getProperty("javax.persistence.nonJtaDataSource");
if (oldName != null)
{
dsName = oldName;
}
boolean upgrade = Boolean.parseBoolean(p.getProperty("com.enioka.jqm.jdbc.allowSchemaUpdate", "false"));
// This is a hack. Some containers will use root context as default for JNDI (WebSphere, Glassfish...), other will use
// java:/comp/env/ (Tomcat...). So if we actually know the required alias, we try both, and the user only has to provide a
// root JNDI alias that will work in both cases.
try
{
this._ds = (DataSource) InitialContext.doLookup(dsName);
}
catch (NamingException e)
{
jqmlogger.warn("JNDI alias {} was not found. Trying with java:/comp/env/ prefix", dsName);
dsName = "java:/comp/env/" + dsName;
try
{
this._ds = (DataSource) InitialContext.doLookup(dsName);
}
catch (NamingException e2)
{
throw new DatabaseException("Could not retrieve datasource resource named " + dsName, e);
}
}
if (this._ds == null)
{
throw new DatabaseException("no data source found");
}
init(upgrade);
}
}
/**
* Helper method to load the standard JQM property files from class path.
*
* @return a Properties object, which may be empty but not null.
*/
public static Properties loadProperties()
{
return loadProperties(new String[] { "META-INF/jqm.properties", "jqm.properties" });
}
/**
* Helper method to load a property file from class path.
*
* @param filesToLoad
* an array of paths (class path paths) designating where the files may be. All files are loaded, in the order given. Missing
* files are silently ignored.
*
* @return a Properties object, which may be empty but not null.
*/
public static Properties loadProperties(String[] filesToLoad)
{
Properties p = new Properties();
InputStream fis = null;
for (String path : filesToLoad)
{
try
{
fis = Db.class.getClassLoader().getResourceAsStream(path);
if (fis != null)
{
p.load(fis);
jqmlogger.info("A jqm.properties file was found at {}", path);
}
}
catch (IOException e)
{
// We allow no configuration files, but not an unreadable configuration file.
throw new DatabaseException("META-INF/jqm.properties file is invalid", e);
}
finally
{
closeQuietly(fis);
}
}
return p;
}
/**
* Main database initialization. To be called only when _ds is a valid DataSource.
*/
private void init(boolean upgrade)
{
initAdapter();
initQueries();
if (upgrade)
{
dbUpgrade();
}
// First contact with the DB is version checking.
// If DB is in wrong version or not available, just wait for it to be ready.
boolean versionValid = false;
while (!versionValid)
{
try
{
checkSchemaVersion();
versionValid = true;
}
catch (Exception e)
{
String msg = e.getLocalizedMessage();
if (e.getCause() != null)
{
msg += " - " + e.getCause().getLocalizedMessage();
}
jqmlogger.error("Database not ready: " + msg + ". Waiting for database...");
try
{
Thread.sleep(10000);
}
catch (Exception e2)
{
}
}
}
}
private void checkSchemaVersion()
{
DbConn cnx = this.getConn();
int db_schema_version = 0;
int db_schema_compat_version = 0;
Map<String, Object> rs = null;
try
{
rs = cnx.runSelectSingleRow("version_select_latest");
db_schema_version = (Integer) rs.get("VERSION_D1");
db_schema_compat_version = (Integer) rs.get("COMPAT_D1");
}
catch (NoResultException e)
{
// Database is to be created, so version 0.
}
catch (Exception z)
{
throw new DatabaseException("could not retrieve version information from database", z);
}
finally
{
cnx.close();
}
if (SCHEMA_VERSION > db_schema_version)
{
if (SCHEMA_COMPATIBLE_VERSION <= db_schema_version)
{
return;
}
}
if (SCHEMA_VERSION == db_schema_version)
{
return;
}
if (SCHEMA_VERSION < db_schema_version)
{
if (SCHEMA_VERSION >= db_schema_compat_version)
{
return;
}
}
// If here, not OK at all.
throw new DatabaseException("Database schema version mismatch. This library can work with schema versions from "
+ SCHEMA_COMPATIBLE_VERSION + " to at least " + SCHEMA_VERSION + " but database is in version " + db_schema_version);
}
/**
* Updates the database. Never call this during normal operations, upgrade is a user-controlled operation.
*/
private void dbUpgrade()
{
DbConn cnx = this.getConn();
Map<String, Object> rs = null;
int db_schema_version = 0;
try
{
rs = cnx.runSelectSingleRow("version_select_latest");
db_schema_version = (Integer) rs.get("VERSION_D1");
}
catch (Exception e)
{
// Database is to be created, so version 0 is OK.
}
cnx.rollback();
if (SCHEMA_VERSION > db_schema_version)
{
jqmlogger.warn("Database is being upgraded from version {} to version {}", db_schema_version, SCHEMA_VERSION);
// Upgrade scripts are named from_to.sql with 5 padding (e.g. 00000_00003.sql)
// We try to find the fastest path (e.g. a direct 00000_00005.sql for creating a version 5 schema from nothing)
// This is a simplistic and non-optimal algorithm as we try only a single path (no going back)
int loop_from = db_schema_version;
int to = db_schema_version;
List<String> toApply = new ArrayList<String>();
toApply.addAll(adapter.preSchemaCreationScripts());
while (to != SCHEMA_VERSION)
{
boolean progressed = false;
for (int loop_to = SCHEMA_VERSION; loop_to > db_schema_version; loop_to
{
String migrationFileName = String.format("/sql/%05d_%05d.sql", loop_from, loop_to);
jqmlogger.debug("Trying migration script {}", migrationFileName);
if (Db.class.getResource(migrationFileName) != null)
{
toApply.add(migrationFileName);
to = loop_to;
loop_from = loop_to;
progressed = true;
break;
}
}
if (!progressed)
{
break;
}
}
if (to != SCHEMA_VERSION)
{
throw new DatabaseException(
"There is no migration path from version " + db_schema_version + " to version " + SCHEMA_VERSION);
}
for (String s : toApply)
{
jqmlogger.info("Running migration script {}", s);
ScriptRunner.run(cnx, s);
}
cnx.commit(); // Yes, really. For advanced DB!
cnx.close(); // HSQLDB does not refresh its schema without this.
cnx = getConn();
cnx.runUpdate("version_insert", SCHEMA_VERSION, SCHEMA_COMPATIBLE_VERSION);
cnx.commit();
jqmlogger.info("Database is now up to date");
}
else
{
jqmlogger.info("Database is already up to date");
}
cnx.close();
}
/**
* Creates the adapter for the target database.
*/
private void initAdapter()
{
Connection tmp = null;
try
{
tmp = _ds.getConnection();
product = tmp.getMetaData().getDatabaseProductName().toLowerCase();
}
catch (SQLException e)
{
throw new DatabaseException("Cannot connect to the database", e);
}
finally
{
try
{
if (tmp != null)
{
tmp.close();
}
}
catch (SQLException e)
{
// Nothing to do.
}
}
jqmlogger.info("Database reports it is " + product);
DbAdapter newAdpt = null;
for (String s : ADAPTERS)
{
try
{
Class<? extends DbAdapter> clazz = Db.class.getClassLoader().loadClass(s).asSubclass(DbAdapter.class);
newAdpt = clazz.newInstance();
if (newAdpt.compatibleWith(product))
{
adapter = newAdpt;
break;
}
}
catch (Exception e)
{
throw new DatabaseException("Issue when loading database adapter named: " + s, e);
}
}
if (adapter == null)
{
throw new DatabaseException("Unsupported database! There is no JQM database adapter compatible with product name " + product);
}
// TODO: go to DS metadata and check supported versions of databases.
}
/**
* Create the query cache (with db-specific queries)
*/
private void initQueries()
{
DbConn cnx = getConn();
adapter.prepare(p, cnx._cnx);
cnx.close();
}
/**
* A connection to the database. Should be short-lived. No transaction active by default.
*
* @return a new open connection.
*/
public DbConn getConn()
{
try
{
Connection cnx = _ds.getConnection();
if (cnx.getAutoCommit())
{
cnx.setAutoCommit(false);
cnx.rollback();
}
if (cnx.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED)
{
cnx.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
}
return new DbConn(this, cnx);
}
catch (SQLException e)
{
throw new DatabaseException(e);
}
}
/**
* Gets the interpolated text of a query from cache. If key does not exist, an exception is thrown.
*
* @param key
* name of the query
* @return the query text
*/
String getQuery(String key)
{
String res = this.adapter.getSqlText(key);
if (res == null)
{
throw new DatabaseException("Query " + key + " does not exist");
}
return res;
}
DbAdapter getAdapter()
{
return this.adapter;
}
public String getProduct()
{
return this.product;
}
/**
* Close utility method.
*
* @param ps
* statement to close.
*/
private static void closeQuietly(Closeable ps)
{
if (ps != null)
{
try
{
ps.close();
}
catch (Exception e)
{
// Do nothing.
}
}
}
}
|
package com.app.ui.assignment.barrelrace.views;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.SystemClock;
import android.os.Vibrator;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.TextView;
import com.app.ui.assignment.barrelrace.FailureActivity;
import com.app.ui.assignment.barrelrace.R;
import com.app.ui.assignment.barrelrace.SuccessActivity;
import com.app.ui.assignment.barrelrace.objects.Barrel;
import com.app.ui.assignment.barrelrace.objects.Fence;
import com.app.ui.assignment.barrelrace.objects.Horse;
public class BarrelRaceView extends SurfaceView implements Runnable, OnTouchListener, SensorEventListener, Callback {
private SensorManager sensorManager;
Thread t = null;
SurfaceHolder holder;
boolean isThreadRunning = true;
private Context context;
private Canvas canvas;
private Fence fence1, fence2, fence3, fence4, fence5;
private Horse horse;
private Barrel barrel1, barrel2, barrel3;
private float x,y;
private float height, width;
private float accelX, accelY;
private float barrel1X, barrel1Y, barrel2X, barrel2Y, barrel3X, barrel3Y;
private float fence1StartX, fence1StartY, fence1StopX, fence1StopY;
private float fence2StartX, fence2StartY, fence2StopX, fence2StopY;
private float fence3StartX, fence3StartY, fence3StopX, fence3StopY;
private float fence4StartX, fence4StartY, fence4StopX, fence4StopY;
private float fence5StartX, fence5StartY, fence5StopX, fence5StopY;
private float horseRadius, barrelRadius;
private boolean hasEntered = false;
private boolean isGameFinished = false;
private boolean isPenaltyReduced = false;
private Object TIMER_LOCK = new Object();
private long startTime = 0L, timeDiffMil = 0L;
private Vibrator vibrator;
private MediaPlayer bMedia, fMedia;
private TextView textViewTime;
private Handler handler;
public BarrelRaceView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
getHolder().addCallback(this);
}
public void initialize(Context context, int width, int height, TextView textViewTime) {
this.context = context;
this.height = height;
this.width = width;
holder = getHolder();
sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_GAME);
initalizeCoordinates();
initializeObjects();
initializeMedia();
initializeTimer();
this.textViewTime = textViewTime;
setOnTouchListener(this);
}
private void initializeTimer() {
// TODO Auto-generated method stub
startTime = SystemClock.uptimeMillis();
handler = new Handler();
handler.postDelayed(updateTimer, 0);
}
private void initializeMedia() {
// TODO Auto-generated method stub
vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
bMedia = MediaPlayer.create(context, R.raw.barrel_hit);
fMedia = MediaPlayer.create(context, R.raw.fence_hit);
}
private void initalizeCoordinates() {
// TODO Auto-generated method stub
x = width/2;
y = height-50;
horseRadius = 25;
barrelRadius = 25;
barrel1X = (width/2);
barrel1Y = height-225;
barrel2X = (width/2)+250;
barrel2Y = 125;
barrel3X = (width/2)-250;
barrel3Y = 125;
fence1StartX = 30;
fence1StartY = 30;
fence1StopX = width-30;
fence1StopY = 30;
fence2StartX = 30;
fence2StartY = 30;
fence2StopX = 30;
fence2StopY = height-80;
fence3StartX = width-30;
fence3StartY = 30;
fence3StopX = width-30;
fence3StopY = height-80;
fence4StartX = 30;
fence4StartY = height-80;
fence4StopX = (width/2)-50;
fence4StopY = height-80;
fence5StartX = width-30;
fence5StartY = height-80;
fence5StopX = (width/2)+50;
fence5StopY = height-80;
}
private void initializeObjects() {
// TODO Auto-generated method stub
horse = new Horse();
fence1 = new Fence(context, fence1StartX, fence1StartY, fence1StopX, fence1StopY);
fence2 = new Fence(context, fence2StartX, fence2StartY, fence2StopX, fence2StopY);
fence3 = new Fence(context, fence3StartX, fence3StartY, fence3StopX, fence3StopY);
fence4 = new Fence(context, fence4StartX, fence4StartY, fence4StopX, fence4StopY);
fence5 = new Fence(context, fence5StartX, fence5StartY, fence5StopX, fence5StopY);
barrel1 = new Barrel(context, barrel1X, barrel1Y, barrelRadius);
barrel2 = new Barrel(context, barrel2X, barrel2Y, barrelRadius);
barrel3 = new Barrel(context, barrel3X, barrel3Y, barrelRadius);
}
@Override
public void run() {
// TODO Auto-generated method stub
while(isThreadRunning) {
if(!holder.getSurface().isValid()) {
continue;
}
canvas = holder.lockCanvas();
canvas.drawColor(context.getResources().getColor(R.color.bg_color));
fence1.draw(canvas);
fence2.draw(canvas);
fence3.draw(canvas);
fence4.draw(canvas);
fence5.draw(canvas);
barrel1.draw(canvas);
barrel2.draw(canvas);
barrel3.draw(canvas);
x += accelX;
y += accelY;
if(y > height-50) {
y = height-50;
}
horse.draw(x, y, 20, canvas);
if(y <= canvas.getHeight()-60-horseRadius) {
hasEntered = true;
} else {
hasEntered = false;
}
if(collides()) {
handleCollision();
}
if(collidesFence()) {
handleCollisionWithFence();
} else {
isPenaltyReduced = false;
}
if(checkCircleBarrel(barrel1) && checkCircleBarrel(barrel2)
&& checkCircleBarrel(barrel3)) {
isThreadRunning = false;
t.interrupt();
if(!isGameFinished) {
Intent toSuccessActivity = new Intent(context, SuccessActivity.class);
toSuccessActivity.putExtra("timeElapsed", SystemClock.uptimeMillis()-startTime);
context.startActivity(toSuccessActivity);
((Activity) context).finish();
isGameFinished = true;
}
}
holder.unlockCanvasAndPost(canvas);
}
}
private void handleCollisionWithFence() {
// TODO Auto-generated method stub
if(!isPenaltyReduced) {
fMedia.start();
/*if(vibrator.hasVibrator()) {
vibrator.vibrate(100);
}*/
synchronized (TIMER_LOCK) {
startTime -= 5000;
}
isPenaltyReduced = true;
}
}
private boolean checkCircleBarrel(Barrel barrel) {
// TODO Auto-generated method stub
if(x >= (barrel.getX()+barrelRadius+10)
&& y >= (barrel.getY()+barrelRadius+10)) {
barrel.setRightBottomQuad(true);
}
if(x >= (barrel.getX()+barrelRadius+10)
&& y <= (barrel.getY()-barrelRadius-10)) {
barrel.setRightTopQuad(true);
}
if(x <= (barrel.getX()-barrelRadius-10)
&& y <= (barrel.getY()-barrelRadius-10)) {
barrel.setLeftTopQuad(true);
}
if(x <= (barrel.getX()-barrelRadius-10)
&& y >= (barrel.getY()+barrelRadius+10)) {
barrel.setLeftBottomQuad(true);
}
return hasEntered && barrel.isCircled();
}
private boolean collidesFence() {
// TODO Auto-generated method stub
if(x <= (horseRadius+35)) {
x = 30+horseRadius;
}
if(x >= (canvas.getWidth()-35-horseRadius)) {
x = canvas.getWidth()-30-horseRadius;
}
if(y <= (horseRadius+35)) {
y = 30+horseRadius;
}
if(y >= canvas.getHeight()-80-horseRadius) {
if(x >= (canvas.getWidth()/2)-50-horseRadius && x <= ((canvas.getWidth()/2)+50+horseRadius)) {
return false;
} else {
if(hasEntered) {
y -= 1f;
} else {
y = canvas.getHeight()-50;
return false;
}
}
}
return false;
}
private void handleCollision() {
// TODO Auto-generated method stub
isThreadRunning = false;
t.interrupt();
if(!isGameFinished) {
bMedia.start();
if(vibrator.hasVibrator()) {
vibrator.vibrate(100);
}
Intent toFailureActivity = new Intent(context, FailureActivity.class);
context.startActivity(toFailureActivity);
((Activity) context).finish();
isGameFinished = true;
}
}
private boolean collides() {
// TODO Auto-generated method stub
if(checkCriteria(barrel1)) {
readjustHorse(barrel1);
} else if(checkCriteria(barrel2)) {
readjustHorse(barrel2);
} else if(checkCriteria(barrel3)) {
readjustHorse(barrel3);
} else {
return false;
}
return true;
}
private void readjustHorse(Barrel barrel) {
// TODO Auto-generated method stub
if(x > barrel.getX()) {
x = x + 1f;
} else {
x = x - 1f;
}
if(y > barrel.getY()) {
y = y + 1f;
} else {
y = y - 1f;
}
}
private boolean checkCriteria(Barrel barrel) {
return (Math.pow((x - barrel.getX()), 2) + Math.pow((y - barrel.getY()), 2))
<= Math.pow((horseRadius + barrelRadius), 2);
}
public void pause() {
isThreadRunning = false;
while(true) {
try {
t.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
t = null;
}
public void resume() {
isThreadRunning = true;
t = new Thread(this);
t.start();
}
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
x = event.getX();
y = event.getY();
return true;
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
private Runnable updateTimer = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
timeDiffMil = (SystemClock.uptimeMillis() - startTime);
int timeDiff = (int) (timeDiffMil/1000);
int minutes = timeDiff/60;
int seconds = timeDiff % 60;
int milliseconds = (int) (timeDiffMil % 1000);
textViewTime.setText(minutes + ":" + String.format("%02d", seconds)
+ ":" + String.format("%03d", milliseconds));
handler.postDelayed(this, 0);
}
};
@Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
/*x = event.values[0]*350;
y = event.values[1]*150;*/
/*x = (float) (Math.signum(event.values[0]) * Math.abs(event.values[0]) * (1 - 0.5 * Math.abs(event.values[2]) / 9.8));
y = (float) (Math.signum(event.values[1]) * Math.abs(event.values[1]) * (1 - 0.5 * Math.abs(event.values[2]) / 9.8));
x = x*250;
y=y*250;*/
accelX = (float) (event.values[1] * 1.2);
accelY = (float) (event.values[0] * 1.5);
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
}
|
package com.app.ui.assignment.barrelrace.views;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.media.MediaPlayer;
import android.os.Vibrator;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;
import com.app.ui.assignment.barrelrace.R;
import com.app.ui.assignment.barrelrace.objects.Barrel;
import com.app.ui.assignment.barrelrace.objects.Fence;
import com.app.ui.assignment.barrelrace.objects.Horse;
public class BarrelRaceView extends SurfaceView implements Runnable, OnTouchListener {
Thread t = null;
SurfaceHolder holder;
boolean isThreadRunning = true;
private Context context;
private Canvas canvas;
private Fence fence1, fence2, fence3, fence4, fence5;
private Horse horse;
private Barrel barrel1, barrel2, barrel3;
private float x,y;
private float barrel1X, barrel1Y, barrel2X, barrel2Y, barrel3X, barrel3Y;
private float fence1StartX, fence1StartY, fence1StopX, fence1StopY;
private float fence2StartX, fence2StartY, fence2StopX, fence2StopY;
private float fence3StartX, fence3StartY, fence3StopX, fence3StopY;
private float fence4StartX, fence4StartY, fence4StopX, fence4StopY;
private float fence5StartX, fence5StartY, fence5StopX, fence5StopY;
private float horseRadius, barrelRadius;
boolean isTouched = false;
boolean hasEntered = false;
boolean isGameFinished = false;
float left, right, top, bottom;
private Vibrator vibrator;
private MediaPlayer bMedia, fMedia;
public BarrelRaceView(Context context, int width, int height) {
super(context);
// TODO Auto-generated constructor stub
this.context = context;
initalizeCoordinates(width, height);
initializeObject();
holder = getHolder();
vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
bMedia = MediaPlayer.create(context, R.raw.barrel_hit);
fMedia = MediaPlayer.create(context, R.raw.fence_hit);
setOnTouchListener(this);
}
private void initalizeCoordinates(float width, float height) {
// TODO Auto-generated method stub
x = width/2;
y = height-50;
horseRadius = 25;
barrelRadius = 25;
barrel1X = (width/2);
barrel1Y = height-225;
barrel2X = (width/2)+250;
barrel2Y = 125;
barrel3X = (width/2)-250;
barrel3Y = 125;
fence1StartX = 30;
fence1StartY = 30;
fence1StopX = width-30;
fence1StopY = 30;
fence2StartX = 30;
fence2StartY = 30;
fence2StopX = 30;
fence2StopY = height-80;
fence3StartX = width-30;
fence3StartY = 30;
fence3StopX = width-30;
fence3StopY = height-80;
fence4StartX = 30;
fence4StartY = height-80;
fence4StopX = (width/2)-50;
fence4StopY = height-80;
fence5StartX = width-30;
fence5StartY = height-80;
fence5StopX = (width/2)+50;
fence5StopY = height-80;
}
private void initializeObject() {
// TODO Auto-generated method stub
horse = new Horse();
fence1 = new Fence(context, fence1StartX, fence1StartY, fence1StopX, fence1StopY);
fence2 = new Fence(context, fence2StartX, fence2StartY, fence2StopX, fence2StopY);
fence3 = new Fence(context, fence3StartX, fence3StartY, fence3StopX, fence3StopY);
fence4 = new Fence(context, fence4StartX, fence4StartY, fence4StopX, fence4StopY);
fence5 = new Fence(context, fence5StartX, fence5StartY, fence5StopX, fence5StopY);
barrel1 = new Barrel(context, barrel1X, barrel1Y, barrelRadius);
barrel2 = new Barrel(context, barrel2X, barrel2Y, barrelRadius);
barrel3 = new Barrel(context, barrel3X, barrel3Y, barrelRadius);
}
@Override
public void run() {
// TODO Auto-generated method stub
while(isThreadRunning) {
if(!holder.getSurface().isValid()) {
continue;
}
canvas = holder.lockCanvas();
canvas.drawColor(context.getResources().getColor(R.color.bg_color));
fence1.draw(canvas);
fence2.draw(canvas);
fence3.draw(canvas);
fence4.draw(canvas);
fence5.draw(canvas);
barrel1.draw(canvas);
barrel2.draw(canvas);
barrel3.draw(canvas);
horse.draw(x, y, 20, canvas);
if(y <= canvas.getHeight()-60-horseRadius) {
hasEntered = true;
} else {
hasEntered = false;
}
if(collides()) {
handleCollision();
}
if(collidesFence(fence1)) {
fMedia.start();
}
if(checkCircleBarrel(barrel1) && checkCircleBarrel(barrel2)
&& checkCircleBarrel(barrel3)) {
isThreadRunning = false;
t.interrupt();
if(!isGameFinished) {
((Activity) context).finish();
isGameFinished = true;
}
}
holder.unlockCanvasAndPost(canvas);
}
}
private boolean checkCircleBarrel(Barrel barrel) {
// TODO Auto-generated method stub
if(x >= (barrel.getX()+barrelRadius+10)
&& y >= (barrel.getY()+barrelRadius+10)) {
barrel.setRightBottomQuad(true);
}
if(x >= (barrel.getX()+barrelRadius+10)
&& y <= (barrel.getY()-barrelRadius-10)) {
barrel.setRightTopQuad(true);
}
if(x <= (barrel.getX()-barrelRadius-10)
&& y <= (barrel.getY()-barrelRadius-10)) {
barrel.setLeftTopQuad(true);
}
if(x <= (barrel.getX()-barrelRadius-10)
&& y >= (barrel.getY()+barrelRadius+10)) {
barrel.setLeftBottomQuad(true);
}
return hasEntered && barrel.isCircled();
}
private boolean collidesFence(Fence fence) {
// TODO Auto-generated method stub
if(x <= (horseRadius+30)) {
x += 1f;
} else if(x >= (canvas.getWidth()-30-horseRadius)) {
x -= 1f;
} else if(y <= (horseRadius+30)) {
y += 1f;
} else if(y >= canvas.getHeight()-80-horseRadius) {
if(x >= (canvas.getWidth()/2)-50-horseRadius && x <= ((canvas.getWidth()/2)+50+horseRadius)) {
return false;
} else {
if(hasEntered) {
y -= 1f;
} else {
y = canvas.getHeight()-50;
return false;
}
}
} else {
return false;
}
return true;
}
private void handleCollision() {
// TODO Auto-generated method stub
bMedia.start();
if(vibrator.hasVibrator()) {
vibrator.vibrate(10);
}
}
private boolean collides() {
// TODO Auto-generated method stub
if(checkCriteria(barrel1)) {
readjustHorse(barrel1);
} else if(checkCriteria(barrel2)) {
readjustHorse(barrel2);
} else if(checkCriteria(barrel3)) {
readjustHorse(barrel3);
} else {
return false;
}
return true;
}
private void readjustHorse(Barrel barrel) {
// TODO Auto-generated method stub
if(x > barrel.getX()) {
x = x + 1f;
} else {
x = x - 1f;
}
if(y > barrel.getY()) {
y = y + 1f;
} else {
y = y - 1f;
}
}
private boolean checkCriteria(Barrel barrel) {
return (Math.pow((x - barrel.getX()), 2) + Math.pow((y - barrel.getY()), 2))
<= Math.pow((horseRadius + barrelRadius), 2);
}
public void pause() {
isThreadRunning = false;
while(true) {
try {
t.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
t = null;
}
public void resume() {
isThreadRunning = true;
t = new Thread(this);
t.start();
}
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
x = event.getX();
y = event.getY();
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
isTouched = true;
break;
case MotionEvent.ACTION_UP:
isTouched = false;
break;
case MotionEvent.ACTION_MOVE:
isTouched = true;
break;
}
return true;
}
}
|
package com.blazeloader.api.client.api.render;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.gui.ScaledResolution;
/**
* Contains functions related to game rendering.
*/
public class ApiRenderClient {
private static int lastWidth = -1;
private static int lastHeight = -1;
private static int lastScale = -1;
private static ScaledResolution scale = null;
/**
* Generates a FontRenderer-compatible ARGB color int.
*
* @param alpha Alpha-channel value.
* @param red Red-channel value.
* @param green Green-channel value.
* @param blue Blue-channel value.
* @return Return the alpha, red, green, and blue compressed into an ARGB int.
*/
public static int getARGB(int alpha, int red, int green, int blue) {
int arbg = 0;
arbg |= (alpha & 255) << 24;
arbg |= (red & 255) << 16;
arbg |= (green & 255) << 8;
arbg |= (blue & 255);
return arbg;
}
/**
* Draws a string onto the screen.
*
* @param string The string to draw.
* @param x The X-coord to display at.
* @param y The Y-coord to display at.
* @param color The color to display. Should be an ARBG returned from getARBG()
* @param shadow Render a shadow behind the text.
* @param centered Center the text around the coordinates specified.
*/
public static void drawString(String string, int x, int y, int color, boolean shadow, boolean centered) {
FontRenderer render = Minecraft.getMinecraft().fontRendererObj;
if (centered) {
x -= render.getStringWidth(string) / 2;
}
render.drawString(string, x, y, color, shadow);
}
/**
* Draws a string onto the screen, without centering it.
*
* @param string The string to draw.
* @param x The X-coord to display at.
* @param y The Y-coord to display at.
* @param color The color to display. Should be an ARBG returned from getARBG()
* @param shadow Render a shadow behind the text.
*/
public static void drawString(String string, int x, int y, int color, boolean shadow) {
drawString(string, x, y, color, shadow, false);
}
/**
* Draws a string onto the screen, without centering it and without a shadow.
*
* @param string The string to draw.
* @param x The X-coord to display at.
* @param y The Y-coord to display at.
* @param color The color to display. Should be an ARBG returned from getARBG()
*/
public static void drawString(String string, int x, int y, int color) {
drawString(string, x, y, color, false, false);
}
/**
* Draws a rectangle onto the screen.
*
* @param x The x-coordinate
* @param y The y-coordinate
* @param width The width
* @param height The height
* @param color The ARGB color
*/
public static void drawRect(int x, int y, int width, int height, int color) {
Gui.drawRect(x, y, x + width, y + height, color);
}
/**
* Draws a square onto the screen.
*
* @param x The x-coordinate
* @param y The y-coordinate
* @param size The length of each side
* @param color The ARGB color
*/
public static void drawSquare(int x, int y, int size, int color) {
drawRect(x, y, size, size, color);
}
/**
* Draws a horizontal line onto the screen.
*
* @param x The x-coordinate
* @param y The y-coordinate
* @param length The length
* @param color The ARGB color
*/
public static void drawHLine(int x, int y, int length, int color) {
drawRect(x, y, length, 1, color);
}
/**
* Draws a vertical line onto the screen.
*
* @param x The x-coordinate
* @param y The y-coordinate
* @param length The length
* @param color The ARGB color
*/
public static void drawVLine(int x, int y, int length, int color) {
drawRect(x, y, 1, length, color);
}
/**
* Draws a point on the screen
*
* @param x The x-coordinate
* @param y The y-coordinate
* @param color The ARGB color
*/
public static void drawPoint(int x, int y, int color) {
drawRect(x, y, 1, 1, color);
}
/**
* Gets the scaled width of the screen
*
* @return return the scaled width of the screen as returned by a ScaledResolution
*/
public static int getScaledWidth() {
return getScaledResolution().getScaledWidth();
}
/**
* Gets the scaled height of the screen
*
* @return return the scaled height of the screen as returned by a ScaledResolution
*/
public static int getScaledHeight() {
return getScaledResolution().getScaledWidth();
}
/**
* Gets a shared, updated instance of ScaledResolution that can be used to get screen scale
*
* @return Return a scaled, correct instance of ScaledResolution
*/
public static ScaledResolution getScaledResolution() {
Minecraft minecraft = Minecraft.getMinecraft();
if (scale == null || minecraft.displayWidth != lastWidth || minecraft.displayHeight != lastHeight || minecraft.gameSettings.guiScale != lastScale) {
lastWidth = minecraft.displayWidth;
lastHeight = minecraft.displayHeight;
lastScale = minecraft.gameSettings.guiScale;
scale = new ScaledResolution(minecraft, lastWidth, lastHeight);
}
return scale;
}
}
|
package com.haskforce.highlighting.annotation.external;
import com.haskforce.features.intentions.AddLanguagePragma;
import com.haskforce.features.intentions.AddTypeSignature;
import com.haskforce.features.intentions.RemoveForall;
import com.haskforce.highlighting.annotation.HaskellAnnotationHolder;
import com.haskforce.highlighting.annotation.HaskellProblem;
import com.haskforce.highlighting.annotation.Problems;
import com.haskforce.utils.ExecUtil;
import com.haskforce.utils.NotificationUtil;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.execution.configurations.ParametersList;
import com.intellij.lang.annotation.Annotation;
import com.intellij.notification.NotificationType;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiFile;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Interface + encapsulation of details concerning ghc-mod communication and annotation.
*/
public class GhcMod {
@SuppressWarnings("UnusedDeclaration")
private static final Logger LOG = Logger.getInstance(GhcMod.class);
// Map of project -> errorMessage. Useful to ensure we don't output the same error multiple times.
private static Map<Project, String> errorState = new HashMap<Project, String>(0);
@Nullable
public static String getPath(@NotNull Project project) {
return ExecUtil.GHC_MOD_KEY.getPath(project);
}
@NotNull
public static String getFlags(@NotNull Project project) {
return ExecUtil.GHC_MOD_KEY.getFlags(project);
}
@Nullable
public static Problems check(@NotNull Project project, @NotNull String workingDirectory, @NotNull String file) {
final String stdout = simpleExec(project, workingDirectory, getFlags(project), "check", file);
return stdout == null ? new Problems() : handleCheck(project, stdout);
}
@Nullable
public static Problems handleCheck(@NotNull Project project, @NotNull String stdout) {
final Problems problems = parseProblems(new Scanner(stdout));
if (problems == null) {
// parseProblems should have returned something, so let's just dump the output to the user.
displayError(project, stdout);
return null;
} else if (problems.size() == 1) {
final Problem problem = (Problem)problems.get(0);
if (problem.startLine == 0 && problem.startColumn == 0) {
displayError(project, problem.message);
return null;
}
}
// Clear the errorState since ghc-mod was successful.
errorState.remove(project);
return problems;
}
@Nullable
public static String[] list(@NotNull Project project, @NotNull String workingDirectory) {
return simpleExecToLines(project, workingDirectory, "", "list");
}
@Nullable
public static String[] lang(@NotNull Project project, @NotNull String workingDirectory) {
return simpleExecToLines(project, workingDirectory, "", "lang");
}
@Nullable
public static String[] flag(@NotNull Project project, @NotNull String workingDirectory) {
return simpleExecToLines(project, workingDirectory, "", "flag");
}
public static void displayError(@NotNull Project project, @NotNull String message) {
if (!message.equals(errorState.get(project))) {
errorState.put(project, message);
NotificationUtil.displayToolsNotification(NotificationType.ERROR, project, "ghc-mod error", message);
}
}
@Nullable
public static String simpleExec(@NotNull Project project, @NotNull String workingDirectory,
@NotNull String ghcModFlags, @NotNull String command, String... params) {
final String ghcModPath = getPath(project);
final String stdout;
if (ghcModPath == null
|| (stdout = exec(workingDirectory, ghcModPath, command, ghcModFlags, params)) == null
|| stdout.length() == 0) {
return null;
}
return stdout;
}
@Nullable
public static String[] simpleExecToLines(@NotNull Project project, @NotNull String workingDirectory,
@NotNull String ghcModFlags, @NotNull String command, String... params) {
final String result = simpleExec(project, workingDirectory, ghcModFlags, command, params);
return result == null ? null : StringUtil.splitByLines(result);
}
@Nullable
public static String exec(@NotNull String workingDirectory, @NotNull String ghcModPath,
@NotNull String command, @NotNull String ghcModFlags, String... params) {
GeneralCommandLine commandLine = new GeneralCommandLine(ghcModPath, command);
ParametersList parametersList = commandLine.getParametersList();
parametersList.addParametersString(ghcModFlags);
parametersList.addAll(params);
// setWorkDirectory is deprecated but is needed to work with IntelliJ 13 which does not have withWorkDirectory.
commandLine.setWorkDirectory(workingDirectory);
// Make sure we can actually see the errors.
commandLine.setRedirectErrorStream(true);
return ExecUtil.readCommandLine(commandLine);
}
@Nullable
public static Problems parseProblems(@NotNull Scanner scanner) {
Problems result = new Problems();
Problem problem;
while ((problem = parseProblem(scanner)) != null) {
result.add(problem);
}
// We only call this function if ghc-mod returned errors, so if we couldn't parse a result something
// bad happened. We'll check for a null return value in handleCheck.
return result.size() == 0 ? null : result;
}
private static final Pattern IN_A_STMT_REGEX = Pattern.compile("\nIn a stmt.*");
private static final Pattern USE_V_REGEX = Pattern.compile("\nUse -v.*");
@Nullable
public static Problem parseProblem(@NotNull Scanner scanner) {
scanner.useDelimiter(":");
if (!scanner.hasNext()) {
return null;
}
String file = scanner.next();
if (!scanner.hasNext()) {
return null;
}
if (!scanner.hasNextInt()) {
// We're probably parsing something like C:\path\to\file.hs
file += ':' + scanner.next();
if (!scanner.hasNextInt()) {
return null;
}
}
final int startLine = scanner.nextInt();
if (!scanner.hasNextInt()) {
return null;
}
final int startColumn = scanner.nextInt();
scanner.skip(":");
scanner.useDelimiter("\n");
if (!scanner.hasNext()) {
return null;
}
// Remove "In a stmt..." text and set newlines.
String message = scanner.next().replace('\0', '\n');
// Remove "In a stmt ..."
message = IN_A_STMT_REGEX.matcher(message).replaceAll("");
// Remove "Use -v ..."
message = USE_V_REGEX.matcher(message).replaceAll("");
// Remove newlines from filename.
file = file.trim();
return new Problem(file, startLine, startColumn, message);
}
public static class Problem extends HaskellProblem {
public String file;
public String message;
public boolean isError;
public Problem(String file, int startLine, int startColumn, String message) {
this.file = file;
this.startLine = startLine;
this.startColumn = startColumn;
this.message = message;
this.isError = !message.startsWith("Warning: ");
if (this.isError) {
this.message = message;
} else {
this.message = message.substring("Warning: ".length());
}
}
abstract static class RegisterFixHandler {
abstract public void apply(Matcher matcher, Annotation annotation, Problem problem);
}
/**
* Intentions are identified using regex against the message received from ghc-mod.
* The first regex match wins; all others will be ignored.
* The RegisterFixHandler is used as an anonymous class so you can determine which fix, or fixes, to register.
*/
static final List<Pair<Pattern, RegisterFixHandler>> fixHandlers;
static {
fixHandlers = new ArrayList(Arrays.asList(
new Pair(Pattern.compile("^Top-level binding with no type signature"),
new RegisterFixHandler() {
@Override
public void apply(Matcher matcher, Annotation annotation, Problem problem) {
annotation.registerFix(new AddTypeSignature(problem));
}
}),
new Pair(Pattern.compile("^Illegal symbol '.' in type"),
new RegisterFixHandler() {
@Override
public void apply(Matcher matcher, Annotation annotation, Problem problem) {
annotation.registerFix(new AddLanguagePragma("RankNTypes"));
annotation.registerFix(new RemoveForall(problem));
}
}),
new Pair(Pattern.compile(" -X([A-Z][A-Za-z0-9]+)"),
new RegisterFixHandler() {
@Override
public void apply(Matcher matcher, Annotation annotation, Problem problem) {
annotation.registerFix(new AddLanguagePragma(matcher.group(1)));
}
})
));
}
public void registerFix(Annotation annotation) {
for (Pair<Pattern, RegisterFixHandler> p : fixHandlers) {
final Matcher matcher = p.first.matcher(message);
if (matcher.find()) {
p.second.apply(matcher, annotation, this);
// Bail out on first match.
return;
}
}
}
public static final Pattern WHITESPACE_REGEX = Pattern.compile("\\s");
/**
* Create an annotation from this problem and add it to the annotation holder.
*/
@Override
public void createAnnotations(@NotNull PsiFile psiFile, @NotNull HaskellAnnotationHolder holder) {
final String text = psiFile.getText();
final int offsetStart = getOffsetStart(text);
if (offsetStart == -1) {
return;
}
// TODO: There is probably a better way to compare these two file paths.
// The problem might not be ours; ignore this problem in that case.
// Note that Windows paths end up with different slashes, so getPresentableUrl() normalizes them.
final VirtualFile vFile = psiFile.getVirtualFile();
if (!(file.equals(vFile.getCanonicalPath()) || file.equals(vFile.getPresentableUrl()))) {
return;
}
// Since we don't have ending regions from ghc-mod, highlight until the first whitespace.
Matcher matcher = WHITESPACE_REGEX.matcher(text.substring(offsetStart));
final int offsetEnd = matcher.find() ? offsetStart + matcher.start() : text.length();
final TextRange range = TextRange.create(offsetStart, offsetEnd);
final Annotation annotation;
if (isError) {
annotation = holder.createErrorAnnotation(range, message);
} else {
annotation = holder.createWeakWarningAnnotation(range, message);
}
registerFix(annotation);
}
}
}
|
package com.karateca.ddescriber.dialog;
import com.intellij.openapi.util.IconLoader;
import com.karateca.ddescriber.model.TestFindResult;
import com.karateca.ddescriber.model.TreeNode;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import java.awt.*;
/**
* @author Andres Dominguez.
*/
public class CustomTreeCellRenderer extends DefaultTreeCellRenderer {
private static final Color GREEN_BG_COLOR = new Color(182, 232, 172);
private static final Color GREEN_FG_COLOR = new Color(57, 194, 70);
private final Color defaultNonSelColor = getBackgroundNonSelectionColor();
private final Color defaultBgSelColor = getBackgroundSelectionColor();
private final Icon itIcon = IconLoader.findIcon("/icons/it-icon.png");
private final Icon descIcon = IconLoader.findIcon("/icons/desc-icon.png");
private final boolean showFileName;
public CustomTreeCellRenderer(boolean showFileName) {
this.showFileName = showFileName;
}
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
Component component = super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
// Ignore non test nodes.
if (!(node.getUserObject() instanceof TestFindResult)) {
return component;
}
TreeNode treeNode = (TreeNode) node;
TestFindResult findResult = treeNode.getNodeValue();
if (findResult.isMarkedForRun()) {
setBackgroundNonSelectionColor(GREEN_BG_COLOR);
setBackgroundSelectionColor(GREEN_FG_COLOR);
} else {
setBackgroundNonSelectionColor(defaultNonSelColor);
setBackgroundSelectionColor(defaultBgSelColor);
}
// Set the icon depending on the type.
setIcon(findResult.isDescribe() ? descIcon : itIcon);
String name = findResult.toString();
if (showFileName && treeNode.isTopNode()) {
name = String.format("%s - [%s]", name, treeNode.getVirtualFile().getName());
}
setText(name);
return component;
}
}
|
package com.miviclin.droidengine2d.input;
import android.view.MotionEvent;
import com.miviclin.collections.PooledLinkedQueue;
/**
* TouchInputController.
*
* @author Miguel Vicente Linares
*
*/
public class TouchInputController {
private final Object motionEventQueueLock = new Object();
private TouchInputProcessor touchInputProcessor;
private PooledLinkedQueue<MotionEvent> motionEventQueue;
/**
* Creates a new TouchInputController.
*/
public TouchInputController() {
this.touchInputProcessor = null;
this.motionEventQueue = new PooledLinkedQueue<MotionEvent>(60);
}
/**
* Queues a copy of the specified MotionEvent for later processing. The event will be recycled when
* {@link TouchInputController#processTouchInput()} is called.
*
* @param motionEvent MotionEvent.
*/
public void queueCopyOfMotionEvent(MotionEvent motionEvent) {
if (motionEvent != null) {
synchronized (motionEventQueueLock) {
MotionEvent motionEventToQueue = MotionEvent.obtain(motionEvent);
motionEventQueue.add(motionEventToQueue);
}
}
}
/**
* Processes touch input.<br>
* This method should be called when the game updates, before the update is processed.<br>
* {@link TouchInputProcessor#processMotionEvent(MotionEvent)} will be called once per MotionEvent queued in this
* TouchInputController. After that call, {@link MotionEvent#recycle()} will be called on the MotionEvent.
*/
public void processTouchInput() {
if (touchInputProcessor != null) {
synchronized (motionEventQueueLock) {
while (!motionEventQueue.isEmpty()) {
MotionEvent motionEvent = motionEventQueue.poll();
touchInputProcessor.processMotionEvent(motionEvent);
motionEvent.recycle();
}
}
}
}
/**
* Sets the {@link TouchInputProcessor} of this TouchInputController.
*
* @param touchInputProcessor TouchListener.
*/
public void setTouchInputProcessor(TouchInputProcessor touchInputProcessor) {
this.touchInputProcessor = touchInputProcessor;
}
}
|
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.
package com.team3546.season2014.RoboBuilt.commands;
import com.team3546.season2014.RoboBuilt.RobotSystemsGroup;
import com.team3546.season2014.RoboBuilt.StatusManager;
import com.team3546.season2014.RoboBuilt.subsystems.PickupArm;
import com.team3546.season2014.RoboBuilt.subsystems.Shooter;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.command.Command;
import com.team3546.season2014.RoboBuilt.Robot;
/**
* Rewinds an away catapult until it is rewound
*/
public class AutoRewind extends Command {
//Stores the systems this command uses
RobotSystemsGroup requiredSystems;
//Stores the result given by the status manager so we don't undo what we haven't done
boolean executeCommand;
//Stores whether this command has retracted the arm yet
private boolean retractedArmYet = false;
//Stores the time the command was initiated
double initialTime;
public AutoRewind() {
//Build a profile to describe the usage of this command
requiredSystems = new RobotSystemsGroup();
//This command uses almost every system
requiredSystems.armMovementSolenoid.value = StatusManager.uses;
requiredSystems.backboardSolenoid.value = StatusManager.dependentOn;
requiredSystems.shooterWinchMotor.value = StatusManager.uses;
requiredSystems.secondaryShooterReleaseSolenoid.value = StatusManager.uses;
requiredSystems.shooterReleaseSolenoid.value = StatusManager.uses;
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES
}
// Called just before this Command runs the first time
protected void initialize() {
executeCommand = Robot.statusManager.checkForConflictsAndSetNewStatus(requiredSystems);
if (executeCommand) {
Robot.shooter.setShooterRelease(Shooter.shooterReleaseEngaged);
Robot.shooter.setSecondaryShooterRelease(Shooter.secondaryShooterReleaseEngaged);
Robot.shooter.setShooterWinchMotor(Shooter.shooterWinchMotorWind);
initialTime = Timer.getFPGATimestamp();
}
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
if (executeCommand) {
Robot.shooter.setShooterWinchMotor(Shooter.shooterWinchMotorWind);
if (!retractedArmYet) {
//This is so that the pickup arm, which was extended in shoot can be retracted
//The delay is so it doesn't hit the catapult
//^^ Thanks self, love ya
if (Timer.getFPGATimestamp() - initialTime > 1.5){
Robot.pickupArm.setArmMovementSolenoid(PickupArm.pickupArmIn);
retractedArmYet = true;
}
}
}
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
return Robot.shooter.eitherFinalSwitchPressed();
}
// Called once after isFinished returns true
protected void end() {
if (executeCommand) {
if (!retractedArmYet) {
//If the arm wasn't retracted yet, do so
Robot.pickupArm.setArmMovementSolenoid(PickupArm.pickupArmIn);
retractedArmYet = true;
}
Robot.shooter.setShooterWinchMotor(Shooter.shooterWinchMotorOff);
Robot.statusManager.doneWithSystems(requiredSystems);
}
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
end();
}
}
|
package org.apache.jmeter.modifiers;
import java.io.Serializable;
import java.util.Collection;
import java.util.LinkedList;
import org.apache.jmeter.engine.event.LoopIterationEvent;
import org.apache.jmeter.engine.event.LoopIterationListener;
import org.apache.jmeter.processor.PreProcessor;
import org.apache.jmeter.testelement.AbstractTestElement;
import org.apache.jmeter.testelement.TestElement;
import org.apache.jmeter.testelement.property.BooleanProperty;
import org.apache.jmeter.testelement.property.CollectionProperty;
import org.apache.jmeter.testelement.property.PropertyIterator;
import org.apache.jmeter.threads.JMeterContextService;
import org.apache.jmeter.threads.JMeterVariables;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.log.Logger;
/**
* @version $Revision$
*/
public class UserParameters
extends AbstractTestElement
implements Serializable, PreProcessor, LoopIterationListener
{
private static final Logger log = LoggingManager.getLoggerForClass();
public static final String NAMES = "UserParameters.names";
public static final String THREAD_VALUES = "UserParameters.thread_values";
public static final String PER_ITERATION = "UserParameters.per_iteration";
private Integer lock = new Integer(0);
public CollectionProperty getNames()
{
return (CollectionProperty) getProperty(NAMES);
}
public CollectionProperty getThreadLists()
{
return (CollectionProperty) getProperty(THREAD_VALUES);
}
/**
* The list of names of the variables to hold values. This list must come
* in the same order as the sub lists that are given to
* {@link #setThreadLists(Collection)}.
*/
public void setNames(Collection list)
{
setProperty(new CollectionProperty(NAMES, list));
}
/**
* The list of names of the variables to hold values. This list must come
* in the same order as the sub lists that are given to
* {@link #setThreadLists(CollectionProperty)}.
*/
public void setNames(CollectionProperty list)
{
setProperty(list);
}
/**
* The thread list is a list of lists. Each list within the parent list is
* a collection of values for a simulated user. As many different sets of
* values can be supplied in this fashion to cause JMeter to set different
* values to variables for different test threads.
*/
public void setThreadLists(Collection threadLists)
{
setProperty(new CollectionProperty(THREAD_VALUES, threadLists));
}
/**
* The thread list is a list of lists. Each list within the parent list is
* a collection of values for a simulated user. As many different sets of
* values can be supplied in this fashion to cause JMeter to set different
* values to variables for different test threads.
*/
public void setThreadLists(CollectionProperty threadLists)
{
setProperty(threadLists);
}
private CollectionProperty getValues()
{
CollectionProperty threadValues =
(CollectionProperty) getProperty(THREAD_VALUES);
if (threadValues.size() > 0)
{
return (CollectionProperty) threadValues.get(
JMeterContextService.getContext().getThreadNum()
% threadValues.size());
}
else
{
return new CollectionProperty("noname", new LinkedList());
}
}
public boolean isPerIteration()
{
return getPropertyAsBoolean(PER_ITERATION);
}
public void setPerIteration(boolean perIter)
{
setProperty(new BooleanProperty(PER_ITERATION, perIter));
}
public void process()
{
if (log.isDebugEnabled())
{
log.debug(Thread.currentThread().getName() + " process " + isPerIteration());//$NON-NLS-1$
}
if (!isPerIteration())
{
setValues();
}
}
private void setValues()
{
synchronized (lock)
{
if (log.isDebugEnabled())
{
log.debug(Thread.currentThread().getName() + " Running up named: " + getName());//$NON-NLS-1$
}
PropertyIterator namesIter = getNames().iterator();
PropertyIterator valueIter = getValues().iterator();
JMeterVariables jmvars =
JMeterContextService.getContext().getVariables();
while (namesIter.hasNext() && valueIter.hasNext())
{
String name = namesIter.next().getStringValue();
String value = valueIter.next().getStringValue();
if (log.isDebugEnabled())
{
log.debug(Thread.currentThread().getName()+" saving variable: "+name+"="+value);//$NON-NLS-1$
}
jmvars.put(name, value);
}
}
}
/**
* @see LoopIterationListener#iterationStart(LoopIterationEvent)
*/
public void iterationStart(LoopIterationEvent event)
{
if (log.isDebugEnabled())
{
log.debug(Thread.currentThread().getName() + " iteration start " + isPerIteration());//$NON-NLS-1$
}
if (isPerIteration())
{
setValues();
}
}
/* This method doesn't appear to be used anymore.
* jeremy_a@bigfoot.com 03 May 2003
*
* @see ThreadListener#setJMeterVariables(JMeterVariables)
public void setJMeterVariables(JMeterVariables jmVars)
{}
*/
/* (non-Javadoc)
* @see java.lang.Object#clone()
*/
public Object clone()
{
UserParameters up = (UserParameters) super.clone();
up.lock = lock;
return up;
}
/* (non-Javadoc)
* @see AbstractTestElement#mergeIn(TestElement)
*/
protected void mergeIn(TestElement element)
{
// super.mergeIn(element);
}
}
|
package com.camerakit;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.pm.PackageManager;
import android.content.res.TypedArray;
import android.os.Build;
import android.support.annotation.IntDef;
import android.support.annotation.NonNull;
import android.support.annotation.RestrictTo;
import android.support.annotation.RestrictTo.Scope;
import android.util.AttributeSet;
import android.util.Log;
import android.view.ViewGroup;
import com.camerakit.type.CameraFacing;
import com.camerakit.type.CameraFlash;
import com.camerakit.type.CameraSize;
import com.jpegkit.Jpeg;
import org.jetbrains.annotations.NotNull;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.List;
import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
/**
* CameraKitView provides a high-level, easy to implement, and safe to use way to work with
* the Android camera.
*
* @since v1.0.0
*/
public class CameraKitView extends GestureLayout {
private static final int PERMISSION_REQUEST_CODE = 99107;
public static final int PERMISSION_CAMERA = 1;
public static final int PERMISSION_MICROPHONE = 1 << 1;
public static final int PERMISSION_STORAGE = 1 << 2;
public static final int PERMISSION_LOCATION = 1 << 3;
@RestrictTo(Scope.LIBRARY_GROUP)
@Retention(RetentionPolicy.SOURCE)
@IntDef(flag = true,
value = {PERMISSION_CAMERA, PERMISSION_MICROPHONE, PERMISSION_STORAGE, PERMISSION_LOCATION})
@interface Permission {
}
public interface CameraListener {
void onOpened();
void onClosed();
}
public interface PreviewListener {
void onStart();
void onStop();
}
public interface ErrorListener {
/**
* @param view
* @param error
*/
void onError(CameraKitView view, CameraException error);
}
public interface GestureListener {
/**
* @param view
* @param x
* @param y
*/
void onTap(CameraKitView view, float x, float y);
/**
* @param view
* @param x
* @param y
*/
void onLongTap(CameraKitView view, float x, float y);
/**
* @param view
* @param x
* @param y
*/
void onDoubleTap(CameraKitView view, float x, float y);
/**
* @param view
* @param ds
* @param dsx
* @param dsy
*/
void onPinch(CameraKitView view, float ds, float dsx, float dsy);
}
public interface PermissionsListener {
void onPermissionsSuccess();
void onPermissionsFailure();
}
public interface ImageCallback {
/**
* @param view
* @param jpeg
*/
void onImage(CameraKitView view, byte[] jpeg);
}
public interface VideoCallback {
/**
* @param view
* @param video
*/
void onVideo(CameraKitView view, Object video);
}
public interface FrameCallback {
/**
* @param view
* @param jpeg
*/
void onFrame(CameraKitView view, byte[] jpeg);
}
private boolean mAdjustViewBounds;
private float mAspectRatio;
private int mFacing;
private int mFlash;
private int mFocus;
private float mZoomFactor;
private int mSensorPreset;
private int mPreviewEffect;
private int mPermissions;
private float mImageMegaPixels;
private int mImageJpegQuality;
private GestureListener mGestureListener;
private CameraListener mCameraListener;
private PreviewListener mPreviewListener;
private ErrorListener mErrorListener;
private PermissionsListener mPermissionsListener;
private static CameraFacing cameraFacing;
private static CameraFlash cameraFlash;
private CameraPreview mCameraPreview;
public CameraKitView(Context context) {
super(context);
obtainAttributes(context, null);
}
public CameraKitView(Context context, AttributeSet attrs) {
super(context, attrs);
obtainAttributes(context, attrs);
}
public CameraKitView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
obtainAttributes(context, attrs);
}
private void obtainAttributes(Context context, AttributeSet attrs) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CameraKitView);
mAdjustViewBounds = a.getBoolean(R.styleable.CameraKitView_android_adjustViewBounds, false);
mAspectRatio = a.getFloat(R.styleable.CameraKitView_camera_aspectRatio, -1f);
mFacing = a.getInteger(R.styleable.CameraKitView_camera_facing, CameraKit.FACING_BACK);
if (cameraFacing == CameraFacing.FRONT) {
mFacing = CameraKit.FACING_FRONT;
}
mFlash = a.getInteger(R.styleable.CameraKitView_camera_flash, CameraKit.FLASH_OFF);
if (cameraFlash == CameraFlash.ON) {
mFlash = CameraKit.FLASH_ON;
}
mFocus = a.getInteger(R.styleable.CameraKitView_camera_focus, CameraKit.FOCUS_AUTO);
mZoomFactor = a.getFloat(R.styleable.CameraKitView_camera_zoomFactor, 1.0f);
mPermissions = a.getInteger(R.styleable.CameraKitView_camera_permissions, PERMISSION_CAMERA);
mImageMegaPixels = a.getFloat(R.styleable.CameraKitView_camera_imageMegaPixels, 2f);
mImageJpegQuality = a.getInteger(R.styleable.CameraKitView_camera_imageJpegQuality, 100);
a.recycle();
mCameraPreview = new CameraPreview(getContext());
addView(mCameraPreview);
mCameraPreview.setListener(new CameraPreview.Listener() {
@Override
public void onCameraOpened() {
if (mCameraListener != null) {
post(new Runnable() {
@Override
public void run() {
mCameraListener.onOpened();
}
});
}
}
@Override
public void onCameraClosed() {
if (mCameraListener != null) {
post(new Runnable() {
@Override
public void run() {
mCameraListener.onClosed();
}
});
}
}
@Override
public void onPreviewStarted() {
if (mPreviewListener != null) {
post(new Runnable() {
@Override
public void run() {
mPreviewListener.onStart();
}
});
}
}
@Override
public void onPreviewStopped() {
if (mPreviewListener != null) {
post(new Runnable() {
@Override
public void run() {
mPreviewListener.onStop();
}
});
}
}
});
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (mAdjustViewBounds) {
ViewGroup.LayoutParams layoutParams = getLayoutParams();
if (layoutParams.width == WRAP_CONTENT && layoutParams.height == WRAP_CONTENT) {
throw new CameraException("android:adjustViewBounds=true while both layout_width and layout_height are setView to wrap_content - only 1 is allowed.");
} else if (layoutParams.width == WRAP_CONTENT) {
int width = 0;
int height = MeasureSpec.getSize(heightMeasureSpec);
if (mAspectRatio > 0) {
width = (int) (height * mAspectRatio);
widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
} else if (mCameraPreview != null && mCameraPreview.getSurfaceSize().area() > 0) {
CameraSize previewSize = mCameraPreview.getSurfaceSize();
width = (int) (((float) height / (float) previewSize.getHeight()) * previewSize.getWidth());
widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
}
} else if (layoutParams.height == WRAP_CONTENT) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = 0;
if (mAspectRatio > 0) {
height = (int) (width * mAspectRatio);
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
} else if (mCameraPreview != null && mCameraPreview.getSurfaceSize().area() > 0) {
CameraSize previewSize = mCameraPreview.getSurfaceSize();
height = (int) (((float) width / (float) previewSize.getWidth()) * previewSize.getHeight());
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
}
}
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@Override
protected void onTap(float x, float y) {
if (mGestureListener != null) {
mGestureListener.onTap(this, x, y);
}
}
@Override
protected void onLongTap(float x, float y) {
if (mGestureListener != null) {
mGestureListener.onLongTap(this, x, y);
}
}
@Override
protected void onDoubleTap(float x, float y) {
if (mGestureListener != null) {
mGestureListener.onDoubleTap(this, x, y);
}
}
@Override
protected void onPinch(float ds, float dsx, float dsy) {
if (mGestureListener != null) {
mGestureListener.onPinch(this, ds, dsx, dsy);
}
}
public void onStart() {
if (isInEditMode()) {
return;
}
List<String> missingPermissions = getMissingPermissions();
if (Build.VERSION.SDK_INT >= 23 && missingPermissions.size() > 0) {
Activity activity = null;
Context context = getContext();
while (context instanceof ContextWrapper) {
if (context instanceof Activity) {
activity = (Activity) context;
}
context = ((ContextWrapper) context).getBaseContext();
}
if (activity != null) {
List<String> requestPermissions = new ArrayList<>();
List<String> rationalePermissions = new ArrayList<>();
for (String permission : missingPermissions) {
if (!activity.shouldShowRequestPermissionRationale(permission)) {
requestPermissions.add(permission);
} else {
rationalePermissions.add(permission);
}
}
if (requestPermissions.size() > 0) {
activity.requestPermissions(requestPermissions.toArray(new String[requestPermissions.size()]), PERMISSION_REQUEST_CODE);
}
if (rationalePermissions.size() > 0 && mPermissionsListener != null) {
mPermissionsListener.onPermissionsFailure();
}
}
return;
}
if (mPermissionsListener != null) {
mPermissionsListener.onPermissionsSuccess();
}
setFlash(mFlash);
setImageMegaPixels(mImageMegaPixels);
cameraFacing = getFacing() == CameraKit.FACING_BACK ? CameraFacing.BACK : CameraFacing.FRONT;
mCameraPreview.start(cameraFacing);
}
public void onStop() {
if (isInEditMode()) {
return;
}
mCameraPreview.stop();
}
public void onResume() {
if (isInEditMode()) {
return;
}
mCameraPreview.resume();
}
public void onPause() {
if (isInEditMode()) {
return;
}
mCameraPreview.pause();
}
/**
* @param callback
*/
public void captureImage(final ImageCallback callback) {
mCameraPreview.capturePhoto(new CameraPreview.PhotoCallback() {
@Override
public void onCapture(@NotNull final byte[] jpeg) {
post(new Runnable() {
@Override
public void run() {
callback.onImage(CameraKitView.this, jpeg);
}
});
}
});
}
public void startVideo() {
}
public void stopVideo() {
}
/**
* @param callback
*/
public void captureVideo(VideoCallback callback) {
}
public void captureFrame(FrameCallback callback) {
}
public void setFrameCallback(FrameCallback callback) {
}
/**
* @return
*/
private List<String> getMissingPermissions() {
List<String> manifestPermissions = new ArrayList<>();
if (Build.VERSION.SDK_INT < 23) {
return manifestPermissions;
}
if ((mPermissions | PERMISSION_CAMERA) == mPermissions) {
String manifestPermission = Manifest.permission.CAMERA;
if (getContext().checkSelfPermission(manifestPermission) == PackageManager.PERMISSION_DENIED) {
manifestPermissions.add(manifestPermission);
}
}
if ((mPermissions | PERMISSION_MICROPHONE) == mPermissions) {
String manifestPermission = Manifest.permission.RECORD_AUDIO;
if (getContext().checkSelfPermission(manifestPermission) == PackageManager.PERMISSION_DENIED) {
manifestPermissions.add(manifestPermission);
}
}
if ((mPermissions | PERMISSION_STORAGE) == mPermissions) {
String manifestPermission = Manifest.permission.WRITE_EXTERNAL_STORAGE;
if (getContext().checkSelfPermission(manifestPermission) == PackageManager.PERMISSION_DENIED) {
manifestPermissions.add(manifestPermission);
}
}
if ((mPermissions | PERMISSION_LOCATION) == mPermissions) {
String manifestPermission = Manifest.permission.ACCESS_FINE_LOCATION;
if (getContext().checkSelfPermission(manifestPermission) == PackageManager.PERMISSION_DENIED) {
manifestPermissions.add(manifestPermission);
}
}
return manifestPermissions;
}
public void setPermissionsListener(PermissionsListener permissionsListener) {
mPermissionsListener = permissionsListener;
}
public void requestPermissions(Activity activity) {
if (Build.VERSION.SDK_INT >= 23) {
List<String> manifestPermissions = getMissingPermissions();
if (manifestPermissions.size() > 0) {
activity.requestPermissions(manifestPermissions.toArray(new String[manifestPermissions.size()]), PERMISSION_REQUEST_CODE);
}
}
}
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == PERMISSION_REQUEST_CODE) {
int approvedPermissions = 0;
int deniedPermissions = 0;
for (int i = 0; i < permissions.length; i++) {
int flag = 0;
switch (permissions[i]) {
case Manifest.permission.CAMERA: {
flag = PERMISSION_CAMERA;
break;
}
case Manifest.permission.RECORD_AUDIO: {
flag = PERMISSION_MICROPHONE;
break;
}
case Manifest.permission.WRITE_EXTERNAL_STORAGE: {
flag = PERMISSION_STORAGE;
break;
}
}
if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
approvedPermissions = approvedPermissions | flag;
} else {
deniedPermissions = deniedPermissions | flag;
}
}
onStart();
}
}
/**
* @param adjustViewBounds
*/
public void setAdjustViewBounds(boolean adjustViewBounds) {
mAdjustViewBounds = adjustViewBounds;
}
/**
* @return
* @see #setAdjustViewBounds(boolean)
*/
public boolean getAdjustViewBounds() {
return mAdjustViewBounds;
}
/**
* @param aspectRatio
*/
public void setAspectRatio(float aspectRatio) {
this.mAspectRatio = aspectRatio;
}
/**
* @return
* @see #setAspectRatio(float)
*/
public float getAspectRatio() {
return mAspectRatio;
}
/**
* @param facing one of {@link CameraKit.Facing}'s constants.
* @see CameraKit#FACING_BACK
* @see CameraKit#FACING_FRONT
*/
public void setFacing(@CameraKit.Facing int facing) {
mFacing = facing;
switch (mCameraPreview.getLifecycleState()) {
case PAUSED:
case STARTED: {
onStop();
onStart();
break;
}
case RESUMED: {
onStop();
onStart();
onResume();
break;
}
}
}
/**
* @return one of {@link CameraKit.Facing}'s constants.
* @see #setFacing(int)
*/
@CameraKit.Facing
public int getFacing() {
return mFacing;
}
public void toggleFacing() {
if (getFacing() == CameraKit.FACING_BACK) {
setFacing(CameraKit.FACING_FRONT);
} else {
setFacing(CameraKit.FACING_BACK);
}
}
/**
* @param flash one of {@link CameraKit.Flash}'s constants.
* @see CameraKit#FLASH_OFF
* @see CameraKit#FLASH_ON
* @see CameraKit#FLASH_AUTO
* @see CameraKit#FLASH_TORCH
*/
public void setFlash(@CameraKit.Flash int flash) {
mFlash = flash;
try {
switch (flash) {
case CameraKit.FLASH_OFF: {
cameraFlash = CameraFlash.OFF;
break;
}
case CameraKit.FLASH_ON: {
cameraFlash = CameraFlash.ON;
break;
}
case CameraKit.FLASH_AUTO: {
throw new CameraException("FLASH_AUTO is not supported in this version of CameraKit.");
}
case CameraKit.FLASH_TORCH: {
throw new CameraException("FLASH_TORCH is not supported in this version of CameraKit.");
}
}
} catch(CameraException exception) {
Log.e("CameraException: Flash", exception.getMessage());
return;
}
mCameraPreview.setFlash(cameraFlash);
}
/**
* @return one of {@link CameraKit.Flash}'s constants.
* @see #setFlash(int)
*/
@CameraKit.Flash
public int getFlash() {
return mFlash;
}
/**
* @param focus one of {@link CameraKit.Focus}'s constants.
* @see CameraKit#FOCUS_OFF
* @see CameraKit#FOCUS_AUTO
* @see CameraKit#FOCUS_CONTINUOUS
*/
public void setFocus(@CameraKit.Focus int focus) {
mFocus = focus;
}
/**
* @return one of {@link CameraKit.Focus}'s constants.
* @see #setFocus(int)
*/
@CameraKit.Focus
public int getFocus() {
return mFocus;
}
/**
* @param zoomFactor
*/
public void setZoomFactor(float zoomFactor) {
mZoomFactor = zoomFactor;
}
/**
* @return
* @see #setZoomFactor(float)
*/
public float getZoomFactor() {
return mZoomFactor;
}
/**
* @param sensorPreset one of {@link CameraKit.SensorPreset}'s constants.
* @see CameraKit#SENSOR_PRESET_NONE
* @see CameraKit#SENSOR_PRESET_ACTION
* @see CameraKit#SENSOR_PRESET_PORTRAIT
* @see CameraKit#SENSOR_PRESET_LANDSCAPE
* @see CameraKit#SENSOR_PRESET_NIGHT
* @see CameraKit#SENSOR_PRESET_NIGHT_PORTRAIT
* @see CameraKit#SENSOR_PRESET_THEATRE
* @see CameraKit#SENSOR_PRESET_BEACH
* @see CameraKit#SENSOR_PRESET_SNOW
* @see CameraKit#SENSOR_PRESET_SUNSET
* @see CameraKit#SENSOR_PRESET_STEADYPHOTO
* @see CameraKit#SENSOR_PRESET_FIREWORKS
* @see CameraKit#SENSOR_PRESET_SPORTS
* @see CameraKit#SENSOR_PRESET_PARTY
* @see CameraKit#SENSOR_PRESET_CANDLELIGHT
* @see CameraKit#SENSOR_PRESET_BARCODE
*/
public void setSensorPreset(@CameraKit.SensorPreset int sensorPreset) {
mSensorPreset = sensorPreset;
}
/**
* @return one of {@link CameraKit.SensorPreset}'s constants.
* @see #setSensorPreset(int)
*/
@CameraKit.SensorPreset
public int getSensorPreset() {
return mSensorPreset;
}
/**
* @param previewEffect one of {@link CameraKit.PreviewEffect}'s constants.
* @see CameraKit#PREVIEW_EFFECT_NONE
* @see CameraKit#PREVIEW_EFFECT_MONO
* @see CameraKit#PREVIEW_EFFECT_SOLARIZE
* @see CameraKit#PREVIEW_EFFECT_SEPIA
* @see CameraKit#PREVIEW_EFFECT_POSTERIZE
* @see CameraKit#PREVIEW_EFFECT_WHITEBOARD
* @see CameraKit#PREVIEW_EFFECT_BLACKBOARD
* @see CameraKit#PREVIEW_EFFECT_AQUA
*/
public void setPreviewEffect(@CameraKit.PreviewEffect int previewEffect) {
mPreviewEffect = previewEffect;
}
/**
* @return one of {@link CameraKit.PreviewEffect}'s constants.
* @see #setPreviewEffect(int)
*/
@CameraKit.PreviewEffect
public int getPreviewEffect() {
return mPreviewEffect;
}
public void setPermissions(@Permission int permissions) {
mPermissions = permissions;
}
@Permission
public int getPermissions() {
return mPermissions;
}
public void setImageMegaPixels(float imageMegaPixels) {
mImageMegaPixels = imageMegaPixels;
mCameraPreview.setImageMegaPixels(mImageMegaPixels);
}
public float getImageMegaPixels() {
return mImageMegaPixels;
}
/**
* @param gestureListener
*/
public void setGestureListener(GestureListener gestureListener) {
mGestureListener = gestureListener;
}
/**
* @return
* @see #setGestureListener(GestureListener)
*/
public GestureListener getGestureListener() {
return mGestureListener;
}
/**
* This adapter class provides empty implementations of the methods from {@link GestureListener}.
* Any custom listener that cares only about a subset of the methods of this listener can
* simply subclass this adapter class instead of implementing the interface directly.
*/
public static class GestureListenerAdapter implements GestureListener {
/**
* @see GestureListener#onTap(CameraKitView, float, float)
*/
@Override
public void onTap(CameraKitView view, float x, float y) {
}
/**
* @see GestureListener#onLongTap(CameraKitView, float, float)
*/
@Override
public void onLongTap(CameraKitView view, float x, float y) {
}
/**
* @see GestureListener#onDoubleTap(CameraKitView, float, float)
*/
@Override
public void onDoubleTap(CameraKitView view, float x, float y) {
}
/**
* @see GestureListener#onPinch(CameraKitView, float, float, float)
*/
@Override
public void onPinch(CameraKitView view, float ds, float dsx, float dsy) {
}
}
/**
* @param cameraListener
*/
public void setCameraListener(CameraListener cameraListener) {
mCameraListener = cameraListener;
}
/**
* @return
*/
public CameraListener getCameraListener() {
return mCameraListener;
}
/**
* @param previewListener
*/
public void setPreviewListener(PreviewListener previewListener) {
mPreviewListener = previewListener;
}
/**
* @return
*/
public PreviewListener getPreviewListener() {
return mPreviewListener;
}
/**
* @param errorListener
*/
public void setErrorListener(ErrorListener errorListener) {
mErrorListener = errorListener;
}
/**
* @return
* @see #setErrorListener(ErrorListener)
*/
public ErrorListener getErrorListener() {
return mErrorListener;
}
public CameraSize getPreviewResolution() {
if (mCameraPreview.getPreviewSize().area() == 0) {
return null;
}
return mCameraPreview.getPreviewSize();
}
public CameraSize getPhotoResolution() {
if (mCameraPreview.getPhotoSize().area() == 0) {
return null;
}
return mCameraPreview.getPhotoSize();
}
public interface JpegCallback {
void onJpeg(Jpeg jpeg);
}
public static class Size implements Comparable<Size> {
private final int mWidth;
private final int mHeight;
public Size(int width, int height) {
mWidth = width;
mHeight = height;
}
public int getWidth() {
return mWidth;
}
public int getHeight() {
return mHeight;
}
@Override
public boolean equals(Object o) {
if (o == null) {
return false;
} else if (this == o) {
return true;
} else if (o instanceof Size) {
Size size = (Size) o;
return mWidth == size.mWidth && mHeight == size.mHeight;
} else {
return false;
}
}
@Override
public String toString() {
return mWidth + "x" + mHeight;
}
@Override
public int hashCode() {
return mHeight ^ ((mWidth << (Integer.SIZE / 2)) | (mWidth >>> (Integer.SIZE / 2)));
}
@Override
public int compareTo(@NonNull Size another) {
return mWidth * mHeight - another.mWidth * another.mHeight;
}
}
public static class CameraException extends RuntimeException {
public CameraException() {
super();
}
public CameraException(String message) {
super(message);
}
public CameraException(String message, Throwable cause) {
super(message, cause);
}
public boolean isFatal() {
return false;
}
}
}
|
package thredds.cataloggen;
import thredds.catalog.InvCatalog;
import thredds.catalog.InvCatalogImpl;
import thredds.crawlabledataset.CrawlableDataset;
import java.io.IOException;
import java.util.List;
import org.jdom.Document;
/**
* An interface for building catalogs where each instance only builds
* catalogs for the dataset collection root it was setup to handle.
*
*
* @author edavis
* @since Dec 6, 2005 12:09:36 PM
*/
public interface CatalogBuilder
{
public CrawlableDataset requestCrawlableDataset( String path )
throws IOException;
/**
* Return an InvCatalog for the level in the collection hierarchy specified by catalogPath.
*
* @param catalogCrDs the location in the collection at which to generate a catalog
* @return an InvCatalog for the specified location
* @throws IOException if problems accessing the dataset collection.
*/
public InvCatalogImpl generateCatalog( CrawlableDataset catalogCrDs ) throws IOException;
public InvCatalogImpl generateProxyDsResolverCatalog( CrawlableDataset catalogCrDs, ProxyDatasetHandler pdh )
throws IOException;
/**
* Return a JDOM Document representation of the catalog for the level in
* the collection hierarchy specified by catalogPath.
*
* @param catalogCrDs the location in the collection at which to generate a catalog
* @return an org.jdom.Document representing the catalog for the specified location
* @throws IOException if problems accessing the dataset collection.
*/
public Document generateCatalogAsDocument( CrawlableDataset catalogCrDs ) throws IOException;
/**
* Return a String containing the XML representation of the catalog for the
* level in the collection hierarchy specified by catalogPath.
*
* @param catalogCrDs the location in the collection at which to generate a catalog
* @return a String containing the XML representation of the catalog for the specified location
* @throws IOException if problems accessing the dataset collection.
*/
public String generateCatalogAsString( CrawlableDataset catalogCrDs ) throws IOException;
}
/*
* $Log: CatalogBuilder.java,v $
* Revision 1.7 2006/05/19 19:23:04 edavis
* Convert DatasetInserter to ProxyDatasetHandler and allow for a list of them (rather than one) in
* CatalogBuilders and CollectionLevelScanner. Clean up division between use of url paths (req.getPathInfo())
* and translated (CrawlableDataset) paths.
*
* Revision 1.6 2006/01/26 18:20:45 edavis
* Add CatalogRootHandler.findRequestedDataset() method (and supporting methods)
* to check that the requested dataset is allowed, i.e., not filtered out.
*
* Revision 1.5 2005/12/16 23:19:35 edavis
* Convert InvDatasetScan to use CrawlableDataset and DatasetScanCatalogBuilder.
*
* Revision 1.4 2005/12/06 19:39:20 edavis
* Last CatalogBuilder/CrawlableDataset changes before start using in InvDatasetScan.
*
*/
|
package de.timmyrs.suprdiscordbot.websocket;
import de.timmyrs.suprdiscordbot.Main;
import de.timmyrs.suprdiscordbot.apis.DiscordAPI;
import javax.websocket.*;
import java.net.URI;
@SuppressWarnings("unused")
@ClientEndpoint
public class WebSocketEndpoint
{
Session userSession = null;
private MessageHandler messageHandler;
WebSocketEndpoint(URI endpointURI)
{
try
{
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
container.connectToServer(this, endpointURI);
} catch(Exception e)
{
DiscordAPI.closeWebSocket("Connection failed.");
DiscordAPI.getWebSocket();
}
}
@OnOpen
public void onOpen(Session userSession)
{
System.out.println("[WebSocket] WebSocket opened.");
this.userSession = userSession;
}
@OnError
public void onError(Session userSession, Throwable e)
{
e.printStackTrace();
}
@OnClose
public void onClose(Session userSession, CloseReason reason)
{
System.out.println("[WebSocket] WebSocket closed: " + reason.getReasonPhrase() + " (" + reason.getCloseCode().getCode() + ")");
this.userSession = null;
Main.scriptManager.fireEvent("DISCONNECTED");
DiscordAPI.closeWebSocket(null);
DiscordAPI.getWebSocket();
}
@OnMessage
public void onMessage(String msg)
{
System.out.println("[WebSocket] > " + msg);
this.messageHandler.handleMessage(msg);
}
void addMessageHandler(MessageHandler msgHandler)
{
this.messageHandler = msgHandler;
}
void send(String msg)
{
System.out.println("[WebSocket] < " + msg);
this.userSession.getAsyncRemote().sendText(msg);
}
public interface MessageHandler
{
void handleMessage(String message);
}
}
|
package dr.inference.operators.hmc;
import dr.inference.hmc.GradientWrtParameterProvider;
import dr.inference.hmc.PrecisionColumnProvider;
import dr.inference.hmc.PrecisionMatrixVectorProductProvider;
import dr.inference.model.Parameter;
import dr.math.MathUtils;
import dr.math.matrixAlgebra.ReadableVector;
import dr.math.matrixAlgebra.WrappedVector;
import dr.xml.Reportable;
import java.util.Arrays;
/**
* @author Zhenyu Zhang
* @author Marc A. Suchard
*/
public class IrreversibleZigZagOperator extends AbstractZigZagOperator implements Reportable {
public IrreversibleZigZagOperator(GradientWrtParameterProvider gradientProvider,
PrecisionMatrixVectorProductProvider multiplicationProvider,
PrecisionColumnProvider columnProvider,
double weight, Options runtimeOptions, Parameter mask,
int threadCount) {
super(gradientProvider, multiplicationProvider, columnProvider, weight, runtimeOptions, mask, threadCount);
}
@Override
WrappedVector drawInitialVelocity(WrappedVector momentum) {
ReadableVector mass = preconditioning.mass;
double[] velocity = new double[mass.getDim()];
for (int i = 0, len = mass.getDim(); i < len; ++i) {
velocity[i] = (MathUtils.nextDouble() > 0.5) ? 1.0 : -1.0;
}
if (mask != null) {
applyMask(velocity);
}
return new WrappedVector.Raw(velocity);
}
@Override
void updatePositionAndMomentum(WrappedVector position,
WrappedVector velocity,
WrappedVector action,
WrappedVector gradient,
WrappedVector momentum,
double time) {
updatePosition(position.getBuffer(), velocity.getBuffer(), time);
}
private MinimumTravelInformation testNative(WrappedVector position,
WrappedVector velocity,
WrappedVector action,
WrappedVector gradient) {
if (TIMING) {
timer.startTimer("getNextC++");
}
final MinimumTravelInformation mti;
mti = nativeZigZag.getNextIrreversibleEvent(position.getBuffer(), velocity.getBuffer(),
action.getBuffer(), gradient.getBuffer());
if (TIMING) {
timer.stopTimer("getNextC++");
}
return mti;
}
@SuppressWarnings("Duplicates")
@Override
MinimumTravelInformation getNextBounce(WrappedVector position,
WrappedVector velocity,
WrappedVector action,
WrappedVector gradient,
WrappedVector momentum) {
final MinimumTravelInformation firstBounce;
if (TIMING) {
timer.startTimer("getNext");
}
firstBounce = getNextBounceImpl(position.getBuffer(), velocity.getBuffer(),
action.getBuffer(), gradient.getBuffer());
if (TIMING) {
timer.stopTimer("getNext");
}
if (TEST_NATIVE_BOUNCE) {
firstBounce = testNative(position, velocity, action, gradient);
}
return firstBounce;
}
@SuppressWarnings("Duplicates")
private MinimumTravelInformation getNextBounceImpl(double[] p,
double[] v,
double[] a,
double[] g) {
double minimumTime = Double.POSITIVE_INFINITY;
int index = -1;
Type type = Type.NONE;
double gradientTime;
if (NEW_WAY) {
double[] roots = getRoots(a, g);
double[] rootsSorted = roots.clone();
Arrays.sort(rootsSorted);
double minBoundaryTime = Double.POSITIVE_INFINITY;
gradientTime = getSwitchTimeByMergedProcesses(a, g, v, roots, rootsSorted);
int gradientIndex = getEventDimension(v, g, a, gradientTime);
for (int i = 0, end = p.length; i < end; i++) {
double boundaryTime = findBoundaryTime(i, p[i], v[i]);
if (boundaryTime < minBoundaryTime) {
minBoundaryTime = boundaryTime;
index = i;
}
}
if (gradientTime < minBoundaryTime) {
index = gradientIndex;
minimumTime = gradientTime;
type = Type.GRADIENT;
} else {
minimumTime = minBoundaryTime;
type = Type.BOUNDARY;
}
} else {
for (int i = 0, end = p.length; i < end; ++i) {
double boundaryTime = findBoundaryTime(i, p[i], v[i]);
if (boundaryTime < minimumTime) {
minimumTime = boundaryTime;
index = i;
type = Type.BOUNDARY;
}
double T = MathUtils.nextExponential(1);
gradientTime = getSwitchTime(-v[i] * g[i], v[i] * a[i], T);
if (gradientTime < minimumTime) {
minimumTime = gradientTime;
index = i;
type = Type.GRADIENT;
}
}
}
return new MinimumTravelInformation(minimumTime, index, type);
}
private double[] getRoots(double[] action, double[] gradient) {
// for the linear piece wise line: y = bx + a, where a = -velocity * gradient, b = velocity * action
// root = - a / b = gradient / action
double[] roots = new double[action.length];
double root;
for (int i = 0; i < action.length; i++) {
root = gradient[i] / action[i];
roots[i] = root >= 0 ? root : 0;
}
return roots;
}
private double getSwitchTimeByMergedProcesses(double[] action, double[] gradient, double[] velocity,
double[] roots, double[] rootsSorted) {
// for the linear piece wise line: y = bx + a, where a = -velocity * gradient (as gradient is negated), b =
// velocity * action
// root = - a / b = gradient / action
double T = MathUtils.nextExponential(1);
double minFirstEvent = -1;
double cumulativeS = 0;
PiecewiseLinearEndpoints endPoints;
if (rootsSorted[rootsSorted.length - 1] == 0) {
endPoints = getEndpointInfo(0, 0, velocity, gradient, action, roots);
minFirstEvent = integrateLinearFunctionToArea(endPoints, T, false);
} else {
int j = 1;
double c0;
double c1;
double trapezoidArea;
double residualArea;
c0 = rootsSorted[0];
while (j < rootsSorted.length) {
if (rootsSorted[j] > 0) {
c1 = rootsSorted[j];
endPoints = getEndpointInfo(c0, c1, velocity, gradient, action, roots);
trapezoidArea = getTrapezoidArea(endPoints);
cumulativeS += trapezoidArea;
if (cumulativeS > T) {
residualArea = T - (cumulativeS - trapezoidArea);
minFirstEvent = integrateLinearFunctionToArea(endPoints, residualArea, true);
break;
} else if (j == rootsSorted.length - 1) {
residualArea = T - cumulativeS;
minFirstEvent = integrateLinearFunctionToArea(endPoints, residualArea, false);
break;
} else {
c0 = c1;
j++;
}
} else {
j++;
}
}
}
return minFirstEvent;
}
private double integrateLinearFunctionToArea(PiecewiseLinearEndpoints f, double residual, boolean fromC0) {
double slope;
double intercept;
if (fromC0) {
slope = f.slope0;
intercept = f.f0 - slope * f.c0;
return onlyPositiveRoot(slope * 0.5, intercept, -(slope * 0.5 * f.c0 * f.c0 + intercept * f.c0 + residual));
} else {
slope = f.slope1;
intercept = f.f1 - slope * f.c1;
return onlyPositiveRoot(slope * 0.5, intercept, -(slope * 0.5 * f.c1 * f.c1 + intercept * f.c1 + residual));
}
}
private double onlyPositiveRoot(double a, double b, double c) {
return (-b + Math.sqrt(b * b - 4 * a * c)) / (2 * a);
}
private PiecewiseLinearEndpoints getEndpointInfo(double c0, double c1, double[] velocity, double[] gradient,
double[] action,
double[] roots) {
double[] c0Coefficients = new double[2];
double[] c1Coefficients = new double[2];
for (int i = 0; i < roots.length; i++) {
accumulateCoefficients(c0, velocity, gradient, action, roots, c0Coefficients, i);
accumulateCoefficients(c1, velocity, gradient, action, roots, c1Coefficients, i);
}
return new PiecewiseLinearEndpoints(c0, c1,
c0Coefficients[0] * c0 + c0Coefficients[1],
c1Coefficients[0] * c1 + c1Coefficients[1],
c0Coefficients[0], c1Coefficients[0]);
}
private void accumulateCoefficients(double c, double[] velocity, double[] gradient, double[] action, double[] roots,
double[] coefficients, int i) {
if ((roots[i] >= c && velocity[i] * action[i] <= 0) || (roots[i] <= c && velocity[i] * action[i] >= 0)) {
coefficients[0] += velocity[i] * action[i];
coefficients[1] += -velocity[i] * gradient[i];
}
}
private double getTrapezoidArea(PiecewiseLinearEndpoints f) {
return (f.f0 + f.f1) * (f.c1 - f.c0) / 2.0;
}
private int getEventDimension(double[] velocity, double[] gradient, double[] action, double eventTime) {
double[] proportions = new double[velocity.length];
double rateAtEvent;
double rateSum = 0.0;
for (int i = 0; i < velocity.length; i++) {
rateAtEvent = eventTime * velocity[i] * action[i] - velocity[i] * gradient[i];
proportions[i] = rateAtEvent > 0.0 ? rateAtEvent : 0.0;
rateSum += proportions[i];
}
double u = MathUtils.nextDouble();
double t = 0.0;
int index = -1;
for (int i = 0; i < proportions.length; i++) {
t += proportions[i] / rateSum;
if (u <= t) {
index = i;
break;
}
}
return index;
}
private class PiecewiseLinearEndpoints {
final double c0;
final double c1;
final double f0;
final double f1;
final double slope0;
final double slope1;
private PiecewiseLinearEndpoints(double c0, double c1, double f0, double f1, double slope0, double slope1) {
this.c0 = c0;
this.c1 = c1;
this.f0 = f0;
this.f1 = f1;
this.slope0 = slope0;
this.slope1 = slope1;
}
}
private double getSwitchTime(double a, double b, double u) {
// simulate T such that P(T>= t) = exp(-at-bt^2/2), using uniform random input u
if (b > 0) {
if (a < 0)
return -a / b + Math.sqrt(2 * u / b);
else // a >= 0
return -a / b + Math.sqrt(a * a / (b * b) + 2 * u / b);
} else if (b == 0) {
if (a > 0)
return u / a;
else
return Double.POSITIVE_INFINITY;
} else { // b < 0
if (a <= 0)
return Double.POSITIVE_INFINITY;
else {
// a > 0
double t1 = -a / b;
if (u <= a * t1 + b * t1 * t1 / 2)
return t1 - Math.sqrt(t1 * t1 + 2 * u / b);
else
return Double.POSITIVE_INFINITY;
}
}
}
@SuppressWarnings("Duplicates")
@Override
void updateDynamics(WrappedVector position,
WrappedVector velocity,
WrappedVector action,
WrappedVector gradient,
WrappedVector momentum,
WrappedVector column,
double time,
int index,
Type eventType) {
final double[] p = position.getBuffer();
final double[] v = velocity.getBuffer();
final double[] a = action.getBuffer();
final double[] g = gradient.getBuffer();
final double[] c = column.getBuffer();
final double twoV = 2 * v[index];
for (int i = 0, len = p.length; i < len; ++i) {
final double ai = a[i];
p[i] = p[i] + time * v[i];
g[i] = g[i] - time * ai;
a[i] = ai - twoV * c[i];
}
if (NOT_YET_IMPLEMENTED) {
nativeZigZag.updateIrreversibleDynamics(p, v, a, g, c, time, index, eventType.ordinal());
}
}
@Override
public String getOperatorName() {
return "Irreversible zig-zag operator";
}
static final boolean CPP_NEXT_BOUNCE = false;
private static final boolean NEW_WAY = true;
private static final boolean NOT_YET_IMPLEMENTED = false;
}
|
package edu.psu.compbio.seqcode.projects.sequtils;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import edu.psu.compbio.seqcode.genome.Genome;
import edu.psu.compbio.seqcode.genome.Organism;
import edu.psu.compbio.seqcode.genome.location.NamedRegion;
import edu.psu.compbio.seqcode.genome.location.Region;
import edu.psu.compbio.seqcode.gse.datasets.seqdata.SeqLocator;
import edu.psu.compbio.seqcode.gse.gsebricks.verbs.location.ChromRegionIterator;
import edu.psu.compbio.seqcode.gse.projects.gps.DeepSeqExpt;
import edu.psu.compbio.seqcode.gse.projects.gps.ReadHit;
import edu.psu.compbio.seqcode.gse.projects.gps.discovery.SingleConditionFeatureFinder;
import edu.psu.compbio.seqcode.gse.tools.utils.Args;
import edu.psu.compbio.seqcode.gse.utils.ArgParser;
import edu.psu.compbio.seqcode.gse.utils.NotFoundException;
import edu.psu.compbio.seqcode.gse.utils.Pair;
public class BEDExporter {
private Organism org;
private Genome gen;
protected DeepSeqExpt expt;
protected int [] stackedHitCountsPos;
protected int [] stackedHitCountsNeg;
private int readLength=1;
private String outName="out";
private boolean dbconnected=false;
private int perBaseMax=-1;
private boolean needlefiltering=false;
private static final Logger logger = Logger.getLogger(SingleConditionFeatureFinder.class);
public static void main(String[] args) throws SQLException, NotFoundException {
BEDExporter wig = new BEDExporter(args);
wig.execute();
wig.close();
}
public BEDExporter(String [] args) {
if(args.length==0){
System.err.println("BEDExporter usage:\n" +
"\t--species <organism;genome>\n" +
"\t--(rdb)expt <experiment names>\n" +
"\t--pbmax <max read count per base>\n" +
"\t--out <output file name>");
System.exit(1);
}
ArgParser ap = new ArgParser(args);
try {
if(ap.hasKey("species")){
Pair<Organism, Genome> pair = Args.parseGenome(args);
if(pair != null){
gen = pair.cdr();
dbconnected=true;
}
}else{
//Make fake genome... chr lengths provided???
if(ap.hasKey("geninfo") || ap.hasKey("g")){
String fName = ap.hasKey("geninfo") ? ap.getKeyValue("geninfo") : ap.getKeyValue("g");
gen = new Genome("Genome", new File(fName), true);
}else{
gen = null;
}
}
}catch (NotFoundException e) {
e.printStackTrace();
}
outName = Args.parseString(args,"out",outName);
perBaseMax = Args.parseInteger(args,"pbmax",perBaseMax);
if(ap.hasKey("pbmax")){needlefiltering=true;}
// Load the experiments
List<SeqLocator> dbexpts = Args.parseSeqExpt(args, "dbexpt");
List<SeqLocator> rdbexpts = Args.parseSeqExpt(args,"rdbexpt");
List<File> expts = Args.parseFileHandles(args, "expt");
boolean nonUnique = ap.hasKey("nonunique") ? true : false;
String fileFormat = Args.parseString(args, "format", "ELAND");
if(expts.size()>0 && dbexpts.size() == 0 && rdbexpts.size()==0){
expt= new DeepSeqExpt(gen, expts, nonUnique, fileFormat, (int)readLength);
}else if (dbexpts.size() > 0 && expts.size() == 0) {
expt = new DeepSeqExpt(gen, dbexpts, "db", (int)readLength);
dbconnected = true;
}else if (rdbexpts.size()>0 && expts.size() == 0){
expt = new DeepSeqExpt(gen, rdbexpts, "readdb", -1);
dbconnected=true;
}else {
logger.error("Must provide either an aligner output file or Gifford lab DB experiment name for the signal experiment (but not both)");
System.exit(1);
}
logger.info("Expt hit count: " + (int) expt.getHitCount() + ", weight: " + (int) expt.getWeightTotal());
}
public void execute(){
try {
FileWriter fw = new FileWriter(outName);
fw.write("chrom\tstart\tend\tstrand\n");
double basesDone=0, printStep=10000000, numPrint=0;
ChromRegionIterator chroms = new ChromRegionIterator(gen);
while(chroms.hasNext()){
NamedRegion currentRegion = chroms.next();
//Split the job up into chunks of 100Mbp
for(int x=currentRegion.getStart(); x<=currentRegion.getEnd(); x+=100000000){
int y = x+100000000;
if(y>currentRegion.getEnd()){y=currentRegion.getEnd();}
Region currSubRegion = new Region(gen, currentRegion.getChrom(), x, y);
ArrayList<ReadHit> hits = new ArrayList<ReadHit>();
hits.addAll(expt.loadHits(currSubRegion));
int read_length = (int)hits.get(0).getReadLength();
double stackedHitCountsPos[] = make5PrimeLandscape(hits, currSubRegion, perBaseMax, '+');
double stackedHitCountsNeg[] = make5PrimeLandscape(hits, currSubRegion, perBaseMax, '-');
//Scan regions
for(int i=currSubRegion.getStart(); i<currSubRegion.getEnd(); i++){
int offset = i-currSubRegion.getStart();
double posHits=stackedHitCountsPos[offset];
double negHits=stackedHitCountsNeg[offset];
double sum = posHits+negHits;
if(posHits>0 || negHits>0){
for(int c=0; c<(int)posHits; c++){
fw.write("chr"+currSubRegion.getChrom()+"\t"+i+"\t"+(i+read_length)+"\t"+"+"+"\n");
}
for(int c=0; c<(int)negHits; c++){
fw.write("chr"+currSubRegion.getChrom()+"\t"+(i+1-read_length)+"\t"+(i+1)+"\t"+"-"+"\n");
}
}
//Print out progress
basesDone++;
if(basesDone > numPrint*printStep){
if(numPrint%10==0){System.out.print(String.format("(%.0f)", (numPrint*printStep)));}
else{System.out.print(".");}
if(numPrint%50==0 && numPrint!=0){System.out.print("\n");}
numPrint++;
}
}
}
}
System.out.print("\n");
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void close(){
if(expt!=null)
expt.closeLoaders();
}
protected double[] make5PrimeLandscape(ArrayList<ReadHit> hits, Region currReg, int perBaseMax, char strand){
double[] startcounts = new double[(int)currReg.getWidth()+1];
for(int i=0; i<=currReg.getWidth(); i++){startcounts[i]=0;}
for(ReadHit r : hits){
if(strand=='.' || r.getStrand()==strand){
if(r.getFivePrime()>=currReg.getStart() && r.getFivePrime()<=currReg.getEnd()){
int offset5=inBounds(r.getFivePrime()-currReg.getStart(),0,currReg.getWidth());
if(!needlefiltering || (startcounts[offset5] <= perBaseMax)){
if(needlefiltering && (startcounts[offset5]+r.getWeight() > perBaseMax))
startcounts[offset5]=perBaseMax;
else
startcounts[offset5]+=r.getWeight();
}
}
}
}
return(startcounts);
}
//keep the number in bounds
protected final double inBounds(double x, double min, double max){
if(x<min){return min;}
if(x>max){return max;}
return x;
}
protected final int inBounds(int x, int min, int max){
if(x<min){return min;}
if(x>max){return max;}
return x;
}
}
|
package es.uniovi.imovil.fcrtrainer;
import java.util.ArrayList;
import java.util.Date;
import java.util.Random;
import org.json.JSONException;
import es.uniovi.imovil.fcrtrainer.highscores.HighscoreManager;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
public class LogicGateExerciseFragment extends BaseExerciseFragment implements
OnClickListener, OnItemSelectedListener {
private static final int RANDOM = 6;
private static final int POINTS_FOR_QUESTION = 10;
private static final long GAME_DURATION_MS = 1 * 1000 * 60;// 1 min
private Button mButtoncheck;
private String[] mLogicstring;
private View mRootView;
private int mCurrentQuestion;
private TypedArray mImageArray;
private ImageView mImageView;
private Button mSolutionButton;
private Spinner mSpinner;
private int mN;
private TextView mClock;
private int mGameEnd = 0;
private int mInitialValue = 0;
private int mFinalValue = 5;
private ArrayList<Integer> mNumberList = new ArrayList<Integer>();
private int mPoints;
private TextView mScore;
private TextView mScoreTitle;
public static LogicGateExerciseFragment newInstance() {
LogicGateExerciseFragment fragment = new LogicGateExerciseFragment();
return fragment;
}
public LogicGateExerciseFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inicializamos la variable contador con el fin de recorrer el array
mCurrentQuestion = random();
// Inflamos el Layout
mRootView = inflater.inflate(R.layout.fragment_logic_gate, container,
false);
// Cargamos el array con las puertas logicas
mLogicstring = getResources().getStringArray(R.array.logic_gates);
// Inicializamos las vistas de los botones y sus respectivos Listener
mButtoncheck = (Button) mRootView.findViewById(R.id.cButton);
mSolutionButton = (Button) mRootView.findViewById(R.id.sButton);
mButtoncheck.setOnClickListener(this);
mSolutionButton.setOnClickListener(this);
// Cargamos un array con las imagenes de las puertas logicas
mImageArray = getResources().obtainTypedArray(
R.array.logic_gates_images);
// Inicializamos las vistas de las imagenes
mImageView = (ImageView) mRootView.findViewById(R.id.imagelogicgate);
mImageView.setImageResource(mImageArray.getResourceId(mCurrentQuestion,
0));
// Inicializamos el spinner y le cargamos los elementos
mSpinner = (Spinner) mRootView.findViewById(R.id.spinner_logic_gate);
// Create an ArrayAdapter using the string array and a default spinner
// layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this.getActivity(), R.array.logic_gates,
android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
mSpinner.setAdapter(adapter);
mSpinner.setOnItemSelectedListener(this);
// Inicializamos views para el modo juego
mClock = (TextView) mRootView.findViewById(R.id.text_view_clock);
mScore = (TextView) mRootView.findViewById(R.id.puntuacion);
mScoreTitle = (TextView) mRootView.findViewById(R.id.title_puntuacion);
return mRootView;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.cButton:
checkAnswer();
break;
case R.id.sButton:
solutionLogicGate();
break;
}
}
public void checkAnswer() {
if (mIsPlaying) {
if (mGameEnd < mLogicstring.length - 1) {
compruebaModo(mCurrentQuestion);
} else {
endGame();
dialogGameOver();
}
} else {
compruebaModo(mCurrentQuestion);
}
}
// Metodo para seleccionar en el spinner la respuesta.
public void solutionLogicGate() {
mSpinner.setSelection(mCurrentQuestion);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
// Metodo para generar un nmero aleatorio
private int random() {
Random ran = new Random();
mN = ran.nextInt(RANDOM);
return mN;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_change_game_mode:
if (mIsPlaying) {
cancelGame();
} else {
startGame();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
void startGame() {
super.startGame();
// Fijamos el contador en 1 minuto
setGameDuration(GAME_DURATION_MS);
// Cambiamos el layout y se adapta al modo juego
mSolutionButton.setVisibility(View.GONE);
mButtoncheck.setText("Ok");
mPoints = 0;
mCurrentQuestion = generar();
mImageView.setImageResource(mImageArray.getResourceId(mCurrentQuestion,
0));
mScore.setVisibility(View.VISIBLE);
mScoreTitle.setVisibility(View.VISIBLE);
mScoreTitle.setText(R.string.title_puntuacion);
mScore.setText("0");
}
@Override
void cancelGame() {
super.cancelGame();
// Cambiamos el layout y lo dejamos otra vez como el modo ejercicio
mScore.setVisibility(View.GONE);
mScoreTitle.setVisibility(View.GONE);
mSolutionButton.setVisibility(View.VISIBLE);
mButtoncheck.setText("Comprobar");
}
void endGame() {
super.endGame();
// convert to seconds
int remainingTimeInSeconds = (int) super.getRemainingTimeMs() / 1000;
// every remaining second gives one extra point.
mPoints = (int) (mPoints + remainingTimeInSeconds);
// Guardamos los puntos
savePoints();
// Vaciamos la lista que contiene todos los resultados posibles del
// metodo generar()
mNumberList.clear();
// Cambiamos el layout para dejarlo en modo ejercicio
mScoreTitle.setVisibility(View.GONE);
mScore.setVisibility(View.GONE);
mClock.setVisibility(View.GONE);
mSolutionButton.setVisibility(View.VISIBLE);
mButtoncheck.setText("Comprobar");
mGameEnd = 0;
}
private void savePoints() {
String username = getResources().getString(R.string.default_user_name);
try {
HighscoreManager.addScore(getActivity().getApplicationContext(),
this.mPoints, R.string.logic_gate, new Date(), username);
} catch (JSONException e) {
e.printStackTrace();
}
}
// Metodo para generar numeros aleatorios sin repetir numeros.
public int generar() {
if (mNumberList.size() < (mFinalValue - mInitialValue) + 1) {
// Aun no se han generado todos los numeros
int numero = numeroAleatorio();// genero un numero
if (mNumberList.isEmpty()) {// si la lista esta vacia
mNumberList.add(numero);
return numero;
} else {// si no esta vacia
if (mNumberList.contains(numero)) {// Si el numero que gener
// esta contenido en la
// lista
return generar();// recursivamente lo mando a generar otra
// vez
} else {// Si no esta contenido en la lista
mNumberList.add(numero);
return numero;
}
}
} else {// ya se generaron todos los numeros
return -1;
}
}
// Genera un numero aleatorio
private int numeroAleatorio() {
return (int) (Math.random() * (mFinalValue - mInitialValue + 1) + mInitialValue);
}
// Metodo para comprobar el modo en el que se ecuentra (juego o ejercicio) y
// segun el modo
// Si estas en modo juego genera solo 6 numeros aleatorios sin repetir y si
// no, genera numeros aleatorios infinitos
public void compruebaModo(int pregunta) {
String textosUpper = mSpinner.getSelectedItem().toString();
if (mLogicstring[pregunta].equals(textosUpper)) {
mGameEnd++;
showAnimationAnswer(true);
// Ponemos el texto en verde y ponemos la imagen de un tic verde.
if (mIsPlaying) {
pregunta = generar();
mCurrentQuestion = pregunta;
mPoints += POINTS_FOR_QUESTION;
mScore.setText(Integer.toString(mPoints));
} else {
pregunta = random();
mCurrentQuestion = pregunta;
}
mImageView.setImageResource(mImageArray.getResourceId(pregunta, 0));
} else {
// Si no es igual es texto del string con el del editText
showAnimationAnswer(false);
}
}
// Simple GameOver Dialog
private void dialogGameOver() {
String message = getResources().getString(R.string.lost);
message = getResources().getString(R.string.points_final) + " "
+ mPoints + " " + "puntos";
Builder alert = new AlertDialog.Builder(getActivity());
alert.setTitle(getResources().getString(R.string.end_game));
alert.setMessage(message);
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alert.show();
}
@Override
public void onPause() {
super.onPause();
if (mIsPlaying) {
cancelGame();
}
}
}
|
package org.rstudio.core.client.widget;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.dom.client.Style.Visibility;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.Event.NativePreviewEvent;
import com.google.gwt.user.client.ui.*;
import org.rstudio.core.client.BrowseCap;
import org.rstudio.core.client.HandlerRegistrations;
import org.rstudio.core.client.command.KeyboardShortcut;
public abstract class ProgressDialog extends ModalDialogBase
{
interface Resources extends ClientBundle
{
ImageResource progress();
@Source("ProgressDialog.css")
Styles styles();
}
interface Styles extends CssResource
{
String progressDialog();
String labelCell();
String progressCell();
String buttonCell();
String displayWidget();
}
interface Binder extends UiBinder<Widget, ProgressDialog>
{}
public static void ensureStylesInjected()
{
resources_.styles().ensureInjected();
}
public ProgressDialog(String title)
{
addStyleName(resources_.styles().progressDialog());
setText(title);
display_ = createDisplayWidget();
display_.addStyleName(resources_.styles().displayWidget());
Style style = display_.getElement().getStyle();
double skewFactor = (12 + BrowseCap.getFontSkew()) / 12.0;
int width = Math.min((int)(skewFactor * 660),
Window.getClientWidth() - 100);
style.setWidth(width, Unit.PX);
progressAnim_ = new Image(resources_.progress().getSafeUri());
stopButton_ = new ThemedButton("Stop");
centralWidget_ = GWT.<Binder>create(Binder.class).createAndBindUi(this);
label_.setText(title);
}
@Override
protected Widget createMainWidget()
{
return centralWidget_;
}
protected abstract Widget createDisplayWidget();
@Override
protected void onUnload()
{
super.onUnload();
unregisterHandlers();
}
@Override
public void onPreviewNativeEvent(NativePreviewEvent event)
{
if (event.getTypeInt() == Event.ONKEYDOWN
&& KeyboardShortcut.getModifierValue(event.getNativeEvent()) == KeyboardShortcut.NONE)
{
if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ESCAPE)
{
stopButton_.click();
event.cancel();
return;
}
else if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ENTER)
{
if (handleEnterKey())
{
event.cancel();
return;
}
}
}
super.onPreviewNativeEvent(event);
}
protected ThemedButton stopButton()
{
return stopButton_;
}
protected void addHandlerRegistration(HandlerRegistration reg)
{
registrations_.add(reg);
}
protected void unregisterHandlers()
{
registrations_.removeHandler();
}
protected void setLabel(String text)
{
label_.setText(text);
}
protected void hideProgress()
{
progressAnim_.getElement().getStyle().setDisplay(Style.Display.NONE);
}
protected boolean handleEnterKey()
{
return false;
}
private HandlerRegistrations registrations_ = new HandlerRegistrations();
@UiField(provided = true)
Widget display_;
@UiField(provided = true)
Image progressAnim_;
@UiField
Label label_;
@UiField(provided = true)
ThemedButton stopButton_;
private Widget centralWidget_;
private static final Resources resources_ = GWT.<Resources>create(Resources.class);
}
|
package io.xchris6041x.devin.commands;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.util.StringUtil;
import io.xchris6041x.devin.MessageSender;
/**
* A class that contains CommandHandlers.
* @author Christopher Bishop
*/
class CommandHandlerContainer implements TabCompleter {
private String name;
private String[] aliases = new String[0];
private String description = "";
private MessageSender msgSender;
private CommandHandlerContainer parent = null;
private List<CommandHandlerContainer> children = new ArrayList<CommandHandlerContainer>();
public CommandHandlerContainer(String name, MessageSender msgSender) {
this.name = name;
this.msgSender = msgSender;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String[] getAliases() {
return aliases;
}
public void setAliases(String[] aliases) {
this.aliases = aliases;
}
/**
* @param name - The name to check.
* @return whether {@code name} matches any valid name or alias.
*/
public boolean isValidName(String name) {
if(name.equals(this.name)) {
return true;
}
for(String str : this.aliases) {
if(name.equals(str)) {
return true;
}
}
return false;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public MessageSender getMessageSender() {
return msgSender;
}
public void setMessageSender(MessageSender msgSender) {
this.msgSender = msgSender;
}
public CommandHandlerContainer getParent() {
return parent;
}
public void setParent(CommandHandlerContainer parent) {
if(this.parent != null) {
this.parent.children.remove(this);
}
if(parent != null) {
parent.children.add(this);
}
this.parent = parent;
}
/**
* @return all the children in this container.
*/
public CommandHandlerContainer[] getChildren() {
return children.toArray(new CommandHandlerContainer[0]);
}
/**
* Get child with the name or aliase of {@code name}
* @param name
* @return
*/
public CommandHandler getHandler(String name) {
return getHandler(name, false);
}
/**
* @param name
* @return a CommandHandler with the same name or alias as {@code name}
*/
public CommandHandler getHandler(String name, boolean create) {
for(CommandHandlerContainer handler : children) {
if(!(handler instanceof CommandHandler)) continue;
if(handler.isValidName(name)) return (CommandHandler) handler;
}
if(create) {
CommandHandler handler = new CommandHandler(name, msgSender);
handler.setParent(this);
return handler;
}
else {
return null;
}
}
@Override
public List<String> onTabComplete(CommandSender sender, Command cmd, String label, String[] args) {
// Check if it belongs to sub-command.
if(args.length > 1) {
String sub = args[0];
CommandHandlerContainer child = null;
for(CommandHandlerContainer chc : children) {
if(chc.isValidName(args[0])) {
child = chc;
break;
}
}
if(child != null) {
// Remove first arg.
String[] newArgs = new String[args.length - 1];
for(int i = 1; i < args.length; i++) {
newArgs[i - 1] = args[i];
}
return child.onTabComplete(sender, cmd, label + " " + sub, newArgs);
}
return new ArrayList<String>();
}
else {
List<String> commands = new ArrayList<String>();
for(CommandHandlerContainer child : children) {
commands.add(child.getName());
}
final List<String> completions = new ArrayList<String>(commands);
StringUtil.copyPartialMatches(args[0], commands, completions);
Collections.sort(completions);
return completions;
}
}
}
|
package com.astoev.cave.survey.activity.main;
import java.sql.SQLException;
import android.location.Location;
import android.location.LocationProvider;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import com.astoev.cave.survey.Constants;
import com.astoev.cave.survey.R;
import com.astoev.cave.survey.activity.MainMenuActivity;
import com.astoev.cave.survey.activity.UIUtilities;
import com.astoev.cave.survey.activity.dialog.TurnOnGPSDialogFragment;
import com.astoev.cave.survey.fragment.LocationFragment;
import com.astoev.cave.survey.fragment.UpdatebleLocationFragment;
import com.astoev.cave.survey.model.Point;
import com.astoev.cave.survey.service.gps.GPSProcessor;
import com.astoev.cave.survey.service.gps.LocationListenerAdapter;
import com.astoev.cave.survey.util.DaoUtil;
/**
* Activity that handles capturing GPS location
*
* @author jmitrev
*/
public class GPSActivity extends MainMenuActivity {
/** Dialog name for enable GPS dialog */
private static final String GPS_DIALOG = "GPS_DIALOG";
/** Intent key where the parent point is placed*/
public static final String POINT = "POINT";
/** GPS processor to handle the work with GPS */
private GPSProcessor gpsProcessor;
/** Flag if GPS enable is already requested */
private boolean gpsRequested = false;
/** Point owner of the location*/
private Point parentPoint;
private boolean hasLocation;
/**
* @see com.astoev.cave.survey.activity.BaseActivity#onCreate(android.os.Bundle)
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gps);
Bundle extras = getIntent().getExtras();
parentPoint = (Point)extras.get(POINT);
gpsProcessor = getGPSProcessor();
initSavedLocationContainer(parentPoint, this, savedInstanceState);
// if (parentPoint != null){
// try {
// currentLocation = DaoUtil.getLocationByPoint(parentPoint);
// } catch (SQLException sqle) {
// Log.e(Constants.LOG_TAG_UI, "Unable to load location", sqle);
// if (/*findViewById(R.id.current_location_container) != null &&*/ currentLocation != null) {
// // However, if we're being restored from a previous state,
// // then we don't need to do anything and should return or else
// // we could end up with overlapping fragments.
// if (savedInstanceState != null) {
// return;
// LocationFragment locationFragment = new LocationFragment();
// Bundle bundle = new Bundle();
// bundle.putSerializable(LocationFragment.LOCATION_KEY, currentLocation);
// locationFragment.setArguments(bundle);
// FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// transaction.replace(R.id.saved_location_container, locationFragment);
// transaction.commit();
}
/**
* @see com.astoev.cave.survey.activity.BaseActivity#onResume()
*/
@Override
protected void onResume() {
super.onResume();
GPSProcessor gpsProcessor = getGPSProcessor();
if (!getGPSProcessor().canRead()){
if (!gpsRequested){
// one request to turn on gps if disabled on settings page
gpsRequested = true;
TurnOnGPSDialogFragment turnOnGPSDialog = new TurnOnGPSDialogFragment();
turnOnGPSDialog.show(getSupportFragmentManager(), GPS_DIALOG);
}
// show GPS disabled layout
gpsDisabled();
}else {
waitingForSignal();
}
gpsProcessor.startListening();
}
/**
* @see android.support.v4.app.FragmentActivity#onPause()
*/
@Override
protected void onPause() {
super.onPause();
gpsProcessor.stopListening();
}
/**
* @see com.astoev.cave.survey.activity.BaseActivity#getScreenTitle()
*/
@Override
protected String getScreenTitle() {
return getString(R.string.gps_title);
}
/**
* @see com.astoev.cave.survey.activity.MainMenuActivity#getChildsOptionsMenu()
*/
@Override
protected int getChildsOptionsMenu() {
return R.menu.gpsmenu;
}
/**
* @see com.astoev.cave.survey.activity.MainMenuActivity#onOptionsItemSelected(android.view.MenuItem)
*/
@Override
public boolean onOptionsItemSelected(MenuItem itemArg) {
Log.i(Constants.LOG_TAG_UI, "GPS activity's menu selected - " + itemArg.toString());
switch (itemArg.getItemId()) {
case R.id.note_action_save: {
saveLocation();
}
default:
return super.onOptionsItemSelected(itemArg);
}
}
/**
* Action method to save the gps location
*/
private void saveLocation(){
UpdatebleLocationFragment fragment = (UpdatebleLocationFragment)getSupportFragmentManager().findFragmentById(R.id.current_location_container);
Location lastLocation = fragment.getLastLocation();
if (lastLocation != null){
try {
DaoUtil.saveLocationToPoint(parentPoint, lastLocation);
} catch (SQLException sqle) {
UIUtilities.showNotification(R.string.gps_db_error);
Log.e(Constants.LOG_TAG_SERVICE, "Unable to save location for point:" + parentPoint, sqle);
}
finish();
} else {
UIUtilities.showNotification(R.string.gps_error_no_location);
}
}
/**
* Helper method that obtains a GPS processor
*
* @return GPSProcessor with attached listener
*/
private GPSProcessor getGPSProcessor(){
if (gpsProcessor == null){
LocationListenerAdapter listener = new LocationListenerAdapter(){
@Override
public void onStatusChanged(String providerArg, int statusArg, Bundle extrasArg) {
switch (statusArg) {
case LocationProvider.AVAILABLE:
Log.d(Constants.LOG_TAG_UI, "onStatusChanged: AVAILABLE :" + statusArg);
signalFound();
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
Log.d(Constants.LOG_TAG_UI, "onStatusChanged: TEMPORARILY_UNAVAILABLE :" + statusArg);
waitingForSignal();
break;
case LocationProvider.OUT_OF_SERVICE:
Log.d(Constants.LOG_TAG_UI, "onStatusChanged: OUT_OF_SERVICE :" + statusArg);
waitingForSignal();
break;
default:
Log.d(Constants.LOG_TAG_UI, "onStatusChanged: UNKNOWN :" + statusArg);
}
}
/**
* @see com.astoev.cave.survey.service.gps.LocationListenerAdapter#onLocationChanged(android.location.Location)
*/
@Override
public void onLocationChanged(Location locationArg) {
if (!hasLocation){
// hack for Hero I do not receive the status updates
hasLocation = true;
signalFound();
}
}
};
gpsProcessor = new GPSProcessor(this, listener);
}
return gpsProcessor;
}
private void gpsDisabled(){
findViewById(R.id.no_gps_include).setVisibility(View.VISIBLE);
findViewById(R.id.no_gps_signal_include).setVisibility(View.GONE);
findViewById(R.id.current_location_container).setVisibility(View.GONE);
hasLocation = false;
}
private void waitingForSignal(){
findViewById(R.id.no_gps_include).setVisibility(View.GONE);
findViewById(R.id.no_gps_signal_include).setVisibility(View.VISIBLE);
findViewById(R.id.current_location_container).setVisibility(View.GONE);
hasLocation = false;
}
private void signalFound(){
findViewById(R.id.no_gps_include).setVisibility(View.GONE);
findViewById(R.id.no_gps_signal_include).setVisibility(View.GONE);
findViewById(R.id.current_location_container).setVisibility(View.VISIBLE);
hasLocation = true;
}
/**
* Helper method that defines how to initialize saved_location_container fragment with Location
*
* @param parentPoint - parent point
* @param activity - parent activity
* @param savedInstanceState - Bundle
* @return Location if available for the parent point
*/
public static com.astoev.cave.survey.model.Location initSavedLocationContainer(Point parentPoint, MainMenuActivity activity, Bundle savedInstanceState){
com.astoev.cave.survey.model.Location currentLocation = null;
if (parentPoint != null){
try {
currentLocation = DaoUtil.getLocationByPoint(parentPoint);
} catch (SQLException sqle) {
Log.e(Constants.LOG_TAG_UI, "Unable to load location", sqle);
}
}
if (/*findViewById(R.id.current_location_container) != null &&*/ currentLocation != null) {
// However, if we're being restored from a previous state,
// then we don't need to do anything and should return or else
// we could end up with overlapping fragments.
if (savedInstanceState != null) {
return null;
}
LocationFragment locationFragment = new LocationFragment();
Bundle bundle = new Bundle();
bundle.putSerializable(LocationFragment.LOCATION_KEY, currentLocation);
locationFragment.setArguments(bundle);
FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.saved_location_container, locationFragment);
transaction.commit();
}
return currentLocation;
}
}
|
package boundary.Point;
import boundary.Representation;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiResponse;
import com.wordnik.swagger.annotations.ApiResponses;
import entity.Point;
import entity.UserRole;
import provider.Secured;
import javax.ejb.EJB;
import javax.ws.rs.*;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.List;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
@Path("/points")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Api(value = "/points", description = "Points management")
public class PointRepresentation extends Representation {
@EJB
private PointResource pointResource;
@GET
@ApiOperation(value = "Get all the points", notes = "Access : Everyone")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK"),
@ApiResponse(code = 500, message = "Internal server error")
})
public Response getAll() {
GenericEntity<List<Point>> list = new GenericEntity<List<Point>>(pointResource.findAll()) {};
return Response.ok(list, MediaType.APPLICATION_JSON).build();
}
@GET
@Path("/{id}")
@ApiOperation(value = "Get a point by its id", notes = "Access : Everyone")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK"),
@ApiResponse(code = 404, message = "Not Found"),
@ApiResponse(code = 500, message = "Internal server error")
})
public Response get(@PathParam("id") String id) {
Point point = pointResource.findById(id);
if (point == null)
flash(404, "Error : point does not exist");
return Response.ok(point, MediaType.APPLICATION_JSON).build();
}
@POST
@Secured({UserRole.CUSTOMER, UserRole.ADMIN})
@ApiOperation(value = "Get a point by its id", notes = "Access : Customer and Admin only")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK"),
@ApiResponse(code = 400, message = "Bad Request"),
@ApiResponse(code = 500, message = "Internal server error")
})
public Response add(@Context UriInfo uriInfo, Point point) {
if (point == null)
flash(400, EMPTY_JSON);
point = pointResource.insert(point);
return Response.ok(point, MediaType.APPLICATION_JSON).build();
}
@PUT
@Path("/{id}")
@Secured({UserRole.CUSTOMER, UserRole.ADMIN})
@ApiOperation(value = "Edit a point by its id", notes = "Access : Owner and Admin only")
@ApiResponses(value = {
@ApiResponse(code = 204, message = "No content"),
@ApiResponse(code = 400, message = "Bad Request"),
@ApiResponse(code = 404, message = "Not found"),
@ApiResponse(code = 500, message = "Internal server error")
})
public Response update(@PathParam("id") String id, Point point) {
if (point == null)
flash(400, EMPTY_JSON);
Point originalPoint = pointResource.findById(id);
if (originalPoint == null)
return Response.status(Response.Status.NOT_FOUND).build();
if (!point.isValid())
flash(400, INVALID_JSON);
originalPoint.update(point);
pointResource.update(point);
return Response.status(Response.Status.NO_CONTENT).build();
}
@DELETE
@Path("/{id}")
@Secured({UserRole.CUSTOMER, UserRole.ADMIN})
@ApiOperation(value = "Delete a point by its id", notes = "Access : Owner and Admin only")
@ApiResponses(value = {
@ApiResponse(code = 204, message = "No content"),
@ApiResponse(code = 404, message = "Not found"),
@ApiResponse(code = 500, message = "Internal server error")
})
public Response delete(@PathParam("id") String id) {
Point point = pointResource.findById(id);
if (point == null)
flash(404, "Error : point does not exist");
pointResource.delete(point);
return Response.status(204).build();
}
}
|
package br.edu.ifrn.sistcc.entidades;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.OneToMany;
@Entity
public class AutorPrincipal extends Usuario {
private static final long serialVersionUID = -5533463694044960350L;
@SuppressWarnings("unused")
private String vinculacao;
@OneToMany(mappedBy="autor")
private List<Submissao> submissoes;
public AutorPrincipal() {
super();
}
}
|
package org.apache.commons.lang.exception;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.StringTokenizer;
import org.apache.commons.lang.SystemUtils;
/**
* Utility routines for manipulating <code>Throwable</code> objects.
*
* @author <a href="mailto:dlr@finemaltcoding.com">Daniel Rall</a>
* @since 1.0
*/
public class ExceptionUtils
{
/**
* The names of methods commonly used to access a wrapped
* exception.
*/
protected static final String[] CAUSE_METHOD_NAMES =
{
"getCause",
"getNextException",
"getTargetException",
"getException",
"getSourceException",
"getRootCause",
"getCausedByException"
};
/**
* The empty parameter list passed to methods used to access a
* wrapped exception.
*/
protected static final Object[] CAUSE_METHOD_PARAMS = {};
/**
* Constructs a new <code>ExceptionUtils</code>. Protected to
* discourage instantiation.
*/
protected ExceptionUtils()
{
}
/**
* Introspects the specified <code>Throwable</code> for a
* <code>getCause()</code>, <code>getNextException()</code>,
* <code>getTargetException()</code>, or
* <code>getException()</code> method which returns a
* <code>Throwable</code> object (standard as of JDK 1.4, and part
* of the {@link
* org.apache.commons.lang.exception.NestableException} API),
* extracting and returning the cause of the exception. In the
* absence of any such method, the object is inspected for a
* <code>detail</code> field assignable to a
* <code>Throwable</code>. If none of the above is found, returns
* <code>null</code>.
*
* @param t The exception to introspect for a cause.
* @return The cause of the <code>Throwable</code>.
*/
public static Throwable getCause(Throwable t)
{
return getCause(t, CAUSE_METHOD_NAMES);
}
/**
* Extends the API of {@link #getCause(Throwable)} by
* introspecting for only user-specified method names.
*
* @see #getCause(Throwable)
*/
public static Throwable getCause(Throwable t, String[] methodNames)
{
Throwable cause = getCauseUsingWellKnownTypes(t);
if (cause == null)
{
for (int i = 0; i < methodNames.length; i++)
{
cause = getCauseUsingMethodName(t, methodNames[i]);
if (cause != null)
{
break;
}
}
if (cause == null)
{
cause = getCauseUsingFieldName(t, "detail");
}
}
return cause;
}
/**
* Walks through the exception chain to the last element -- the
* "root" of the tree -- using {@link #getCause(Throwable)}, and
* returns that exception.
*
* @return The root cause of the <code>Throwable</code>.
* @see #getCause(Throwable)
*/
public static Throwable getRootCause(Throwable t)
{
Throwable cause = getCause(t);
if (cause != null)
{
t = cause;
while ((t = getCause(t)) != null)
{
cause = t;
}
}
return cause;
}
/**
* Uses <code>instanceof</code> checks to examine the exception,
* looking for well known types which could contain chained or
* wrapped exceptions.
*
* @param t The exception to examine.
* @return The wrapped exception, or <code>null</code> if not
* found.
*/
private static Throwable getCauseUsingWellKnownTypes(Throwable t)
{
if (t instanceof Nestable)
{
return ((Nestable) t).getCause();
}
else if (t instanceof SQLException)
{
return ((SQLException) t).getNextException();
}
else if (t instanceof InvocationTargetException)
{
return ((InvocationTargetException) t).getTargetException();
}
else
{
return null;
}
}
/**
* @param t The exception to examine.
* @param methodName The name of the method to find and invoke.
* @return The wrapped exception, or <code>null</code> if not
* found.
*/
private static Throwable getCauseUsingMethodName(Throwable t,
String methodName)
{
Method method = null;
try
{
method = t.getClass().getMethod(methodName, null);
}
catch (NoSuchMethodException ignored)
{
}
catch (SecurityException ignored)
{
}
if (method != null &&
Throwable.class.isAssignableFrom(method.getReturnType()))
{
try
{
return (Throwable) method.invoke(t, CAUSE_METHOD_PARAMS);
}
catch (IllegalAccessException ignored)
{
}
catch (IllegalArgumentException ignored)
{
}
catch (InvocationTargetException ignored)
{
}
}
return null;
}
/**
* @param t The exception to examine.
* @param fieldName The name of the attribute to examine.
* @return The wrapped exception, or <code>null</code> if not
* found.
*/
private static Throwable getCauseUsingFieldName(Throwable t,
String fieldName)
{
Field field = null;
try
{
field = t.getClass().getField(fieldName);
}
catch (NoSuchFieldException ignored)
{
}
catch (SecurityException ignored)
{
}
if (field != null &&
Throwable.class.isAssignableFrom(field.getType()))
{
try
{
return (Throwable) field.get(t);
}
catch (IllegalAccessException ignored)
{
}
catch (IllegalArgumentException ignored)
{
}
}
return null;
}
/**
* Returns the number of <code>Throwable</code> objects in the
* exception chain.
*
* @param t The exception to inspect.
* @return The throwable count.
*/
public static int getThrowableCount(Throwable t)
{
// Count the number of throwables
int count = 0;
while (t != null)
{
count++;
t = ExceptionUtils.getCause(t);
}
return count;
}
/**
* Returns the list of <code>Throwable</code> objects in the
* exception chain.
*
* @param t The exception to inspect.
* @return The list of <code>Throwable</code> objects.
*/
public static Throwable[] getThrowables(Throwable t)
{
List list = new ArrayList();
while (t != null)
{
list.add(t);
t = ExceptionUtils.getCause(t);
}
return (Throwable []) list.toArray(new Throwable[list.size()]);
}
/**
* Delegates to {@link #indexOfThrowable(Throwable, Class, int)},
* starting the search at the beginning of the exception chain.
*
* @see #indexOfThrowable(Throwable, Class, int)
*/
public static int indexOfThrowable(Throwable t, Class type)
{
return indexOfThrowable(t, type, 0);
}
/**
* Returns the (zero based) index, of the first
* <code>Throwable</code> that matches the specified type in the
* exception chain of <code>Throwable</code> objects with an index
* greater than or equal to the specified index, or
* <code>-1</code> if the type is not found.
*
* @param t The exception to inspect.
* @param type <code>Class</code> to look for.
* @param fromIndex The (zero based) index of the starting
* position in the chain to be searched.
* @return index The first occurrence of the type in the chain, or
* <code>-1</code> if the type is not found.
* @throws IndexOutOfBoundsException If the <code>fromIndex</code>
* argument is negative or not less than the count of
* <code>Throwable</code>s in the chain.
*/
public static int indexOfThrowable(Throwable t, Class type, int fromIndex)
{
if (fromIndex < 0)
{
throw new IndexOutOfBoundsException
("Throwable index out of range: " + fromIndex);
}
Throwable[] throwables = ExceptionUtils.getThrowables(t);
if (fromIndex >= throwables.length)
{
throw new IndexOutOfBoundsException
("Throwable index out of range: " + fromIndex);
}
for (int i = fromIndex; i < throwables.length; i++)
{
if (throwables[i].getClass().equals(type))
{
return i;
}
}
return -1;
}
/**
* A convenient way of extracting the stack trace from an
* exception.
*
* @param t The <code>Throwable</code>.
* @return The stack trace as generated by the exception's
* <code>printStackTrace(PrintWriter)</code> method.
*/
public static String getStackTrace(Throwable t)
{
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw, true);
t.printStackTrace(pw);
return sw.getBuffer().toString();
}
/**
* Captures the stack trace associated with the specified
* <code>Throwable</code> object, decomposing it into a list of
* stack frames.
*
* @param t The <code>Throwable</code>.
* @return An array of strings describing each stack frame.
*/
public static String[] getStackFrames(Throwable t)
{
return getStackFrames(getStackTrace(t));
}
/**
* Functionality shared between the
* <code>getStackFrames(Throwable)</code> methods of this and the
* {@link org.apache.commons.lang.exception.NestableDelegate}
* classes.
*/
static String[] getStackFrames(String stackTrace)
{
String linebreak = SystemUtils.LINE_SEPARATOR;
StringTokenizer frames = new StringTokenizer(stackTrace, linebreak);
List list = new LinkedList();
while (frames.hasMoreTokens())
{
list.add(frames.nextToken());
}
return (String []) list.toArray(new String[] {});
}
}
|
package org.apache.commons.lang.exception;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.SQLException;
/**
* Utility routines for manipulating <code>Throwable</code> objects.
*
* @author <a href="mailto:dlr@finemaltcoding.com">Daniel Rall</a>
* @since 1.0
*/
public class ExceptionUtils
{
/**
* The name of the <code>getCause()</code> method.
*/
protected static final String[] CAUSE_METHOD_NAMES =
{
"getCause",
"getNextException",
"getTargetException",
"getException"
};
/**
* The parameters of the <code>getCause()</code> method.
*/
protected static final Object[] CAUSE_METHOD_PARAMS = {};
/**
* Constructs a new <code>ExceptionUtils</code>. Protected to
* discourage instantiation.
*/
protected ExceptionUtils()
{
}
/**
* Introspects the specified <code>Throwable</code> for a
* <code>getCause()</code>, <code>getNextException()</code>,
* <code>getTargetException()</code>, or
* <code>getException()</code> method which returns a
* <code>Throwable</code> object (standard as of JDK 1.4, and part
* of the {@link
* org.apache.commons.lang.exception.NestableException} API),
* extracting and returning the cause of the exception. In the
* absence of any such method, the object is inspected for a
* <code>detail</code> field assignable to a
* <code>Throwable</code>. If none of the above is found, returns
* <code>null</code>.
*
* @param t The exception to introspect for a cause.
* @return The cause of the <code>Throwable</code>.
*/
public static Throwable getCause(Throwable t)
{
return getCause(t, CAUSE_METHOD_NAMES);
}
/**
* Extends the API of {@link #getCause(Throwable)} by
* introspecting for only user-specified method names.
*
* @see #getCause(Throwable)
*/
public static Throwable getCause(Throwable t, String[] methodNames)
{
Throwable cause = getCauseUsingWellKnownTypes(t);
if (cause == null)
{
for (int i = 0; i < methodNames.length; i++)
{
cause = getCauseUsingMethodName(t, methodNames[i]);
if (cause != null)
{
break;
}
}
if (cause == null)
{
cause = getCauseUsingFieldName(t, "detail");
}
}
return cause;
}
/**
* Walks through the exception chain to the last element -- the
* "root" of the tree -- using {@link #getCause(Throwable)}, and
* returns that exception.
*
* @return The root cause of the <code>Throwable</code>.
* @see #getCause(Throwable)
*/
public static Throwable getRootCause(Throwable t)
{
Throwable cause = getCause(t);
if (cause != null)
{
t = cause;
while ((t = getCause(t)) != null)
{
cause = t;
}
}
return cause;
}
/**
* Uses <code>instanceof</code> checks to examine the exception,
* looking for well known types which could contain chained or
* wrapped exceptions.
*
* @param t The exception to examine.
* @return The wrapped exception, or <code>null</code> if not
* found.
*/
private static Throwable getCauseUsingWellKnownTypes(Throwable t)
{
if (t instanceof NestableException)
{
return ((NestableException) t).getCause();
}
else if (t instanceof NestableRuntimeException)
{
return ((NestableRuntimeException) t).getCause();
}
else if (t instanceof SQLException)
{
return ((SQLException) t).getNextException();
}
else if (t instanceof InvocationTargetException)
{
return ((InvocationTargetException) t).getTargetException();
}
else
{
return null;
}
}
/**
* @param t The exception to examine.
* @param methodName The name of the method to find and invoke.
* @return The wrapped exception, or <code>null</code> if not
* found.
*/
private static Throwable getCauseUsingMethodName(Throwable t,
String methodName)
{
Method method = null;
try
{
method = t.getClass().getMethod(methodName, null);
}
catch (NoSuchMethodException ignored)
{
}
catch (SecurityException ignored)
{
}
if (method != null &&
Throwable.class.isAssignableFrom(method.getReturnType()))
{
try
{
return (Throwable) method.invoke(t, CAUSE_METHOD_PARAMS);
}
catch (IllegalAccessException ignored)
{
}
catch (IllegalArgumentException ignored)
{
}
catch (InvocationTargetException ignored)
{
}
}
return null;
}
/**
* @param t The exception to examine.
* @param fieldName The name of the attribute to examine.
* @return The wrapped exception, or <code>null</code> if not
* found.
*/
private static Throwable getCauseUsingFieldName(Throwable t,
String fieldName)
{
Field field = null;
try
{
field = t.getClass().getField(fieldName);
}
catch (NoSuchFieldException ignored)
{
}
catch (SecurityException ignored)
{
}
if (field != null &&
Throwable.class.isAssignableFrom(field.getType()))
{
try
{
return (Throwable) field.get(t);
}
catch (IllegalAccessException ignored)
{
}
catch (IllegalArgumentException ignored)
{
}
}
return null;
}
}
|
package org.smoothbuild.builtin.java.junit;
import static org.smoothbuild.builtin.java.junit.BinaryNameToClassFile.binaryNameToClassFile;
import static org.smoothbuild.message.base.MessageType.ERROR;
import static org.smoothbuild.util.Empty.nullToEmpty;
import java.util.Map;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
import org.smoothbuild.message.base.Message;
import org.smoothbuild.message.listen.ErrorMessageException;
import org.smoothbuild.plugin.File;
import org.smoothbuild.plugin.FileSet;
import org.smoothbuild.plugin.SmoothFunction;
import org.smoothbuild.plugin.StringValue;
import org.smoothbuild.task.exec.SandboxImpl;
/*
* TODO
* Current implementation requires classes from junit.jar being present in
* smooth.jar. Once plugin system is in place this function should be moved to a
* plugin and should require junitLib parameter that would provide junit binary.
*/
public class JunitFunction {
public interface Parameters {
FileSet libs();
}
@SmoothFunction(name = "junit")
public static StringValue execute(SandboxImpl sandbox, Parameters params) {
return new Worker(sandbox, params).execute();
}
private static class Worker {
private final SandboxImpl sandbox;
private final Parameters params;
public Worker(SandboxImpl sandbox, Parameters params) {
this.sandbox = sandbox;
this.params = params;
}
public StringValue execute() {
Map<String, File> binaryNameToClassFile = binaryNameToClassFile(sandbox,
nullToEmpty(params.libs()));
FileClassLoader classLoader = new FileClassLoader(binaryNameToClassFile);
JUnitCore jUnitCore = new JUnitCore();
for (String binaryName : binaryNameToClassFile.keySet()) {
if (binaryName.endsWith("Test")) {
Class<?> testClass = loadClass(classLoader, binaryName);
Result result = jUnitCore.run(testClass);
if (!result.wasSuccessful()) {
for (Failure failure : result.getFailures()) {
sandbox.report(new JunitTestFailedError(failure));
}
return sandbox.string("FAILURE");
}
}
}
return sandbox.string("SUCCESS");
}
private static Class<?> loadClass(FileClassLoader classLoader, String binaryName) {
try {
return classLoader.loadClass(binaryName);
} catch (ClassNotFoundException e) {
Message errorMessage = new Message(ERROR, "Couldn't find class for binaryName = "
+ binaryName);
throw new ErrorMessageException(errorMessage);
}
}
}
}
|
package org.burroloco.donkey.spit.http;
import au.net.netstorm.boost.spider.api.runtime.Nu;
import edge.org.apache.http.HttpEntity;
import edge.org.apache.http.client.HttpClient;
import edge.org.apache.http.client.methods.CloseableHttpResponse;
import edge.org.apache.http.client.methods.HttpPost;
import edge.org.apache.http.entity.StringEntity;
import org.burroloco.config.core.Config;
import org.burroloco.config.core.WeakConfig;
import org.burroloco.donkey.config.HttpsUrl;
import org.burroloco.donkey.config.KeyStoreLocation;
import org.burroloco.donkey.config.KeyStorePassword;
import org.burroloco.donkey.data.core.Data;
import org.burroloco.donkey.data.core.Tuple;
import org.burroloco.donkey.spit.core.Spitter;
import java.util.List;
import static org.burroloco.donkey.data.core.Tuple.UNIT_KEY;
public class HttpsSpitter implements Spitter {
HttpsClients clients;
WeakConfig weak;
Nu nu;
public void spit(Config config, Data data) {
HttpClient client = client(config);
String url = weak.get(config, HttpsUrl.class);
List<Tuple> tuples = data.tuples();
for (Tuple t : tuples) spit(client, t, url);
}
private HttpClient client(Config config) {
KeyStoreLocation l = config.get(KeyStoreLocation.class);
KeyStorePassword p = config.get(KeyStorePassword.class);
return clients.nu(l, p);
}
// TODO - Error handling. Handle non-200 return codes.
private void spit(HttpClient client, Tuple t, String url) {
HttpPost request = post(t, url);
CloseableHttpResponse response = client.execute(request);
try {
HttpEntity entity = response.getEntity();
entity.consumeContent();
} finally {
response.close();
}
}
private HttpPost post(Tuple tuple, String url) {
HttpPost post = nu.nu(HttpPost.class, url);
setBody(post, tuple);
return post;
}
private void setBody(HttpPost post, Tuple tuple) {
HttpEntity body = body(tuple);
post.setEntity(body);
}
private HttpEntity body(Tuple tuple) {
String xmlString = (String) tuple.value(UNIT_KEY);
return nu.nu(StringEntity.class, xmlString);
}
}
|
package aphelion.shared.physics.entities;
import aphelion.shared.gameconfig.GCBoolean;
import aphelion.shared.gameconfig.GCBooleanList;
import aphelion.shared.gameconfig.GCColour;
import aphelion.shared.gameconfig.GCImage;
import aphelion.shared.gameconfig.GCInteger;
import aphelion.shared.gameconfig.GCIntegerFixed;
import aphelion.shared.gameconfig.GCIntegerList;
import aphelion.shared.gameconfig.GCString;
import aphelion.shared.gameconfig.GCStringList;
import aphelion.shared.net.protobuf.GameOperation;
import aphelion.shared.physics.*;
import aphelion.shared.physics.events.ProjectileExplosion;
import aphelion.shared.physics.events.pub.ProjectileExplosionPublic;
import aphelion.shared.physics.events.pub.ProjectileExplosionPublic.EXPLODE_REASON;
import aphelion.shared.physics.valueobjects.PhysicsPoint;
import aphelion.shared.physics.valueobjects.PhysicsPositionVector;
import aphelion.shared.physics.valueobjects.PhysicsShipPosition;
import aphelion.shared.resource.ResourceDB;
import aphelion.shared.swissarmyknife.AttachmentData;
import aphelion.shared.swissarmyknife.AttachmentManager;
import aphelion.shared.swissarmyknife.LinkedListEntry;
import aphelion.shared.swissarmyknife.LoopFilter;
import aphelion.shared.swissarmyknife.SwissArmyKnife;
import static aphelion.shared.swissarmyknife.SwissArmyKnife.max;
import static aphelion.shared.swissarmyknife.SwissArmyKnife.min;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import javax.annotation.Nullable;
/**
*
* @author Joris
*/
public final class Projectile extends MapEntity implements ProjectilePublic
{
public static final AttachmentManager attachmentManager = new AttachmentManager();
private final AttachmentData attachments = attachmentManager.getNewDataContainer();
public final ProjectileKey key;
public final LinkedListEntry<Projectile> projectileListLink_state = new LinkedListEntry<>(this);
public final LinkedListEntry<Projectile> forceEmitterListLink_state = new LinkedListEntry<>(this);
public final LinkedListEntry<Projectile> projectileListLink_actor = new LinkedListEntry<>(this);
// circular headless linked list
final public LinkedListEntry<Projectile> coupled = new LinkedListEntry<>(this);
/** Has initFire or initFromSync been called?. */
private boolean initialized;
public Actor owner;
public WeaponConfig config;
public final int configIndex; // the config index
// IF AN ATTRIBUTE IS ADDED, DO NOT FORGET TO UPDATE resetTo()
// (except config, etc)
public long expiresAt_tick;
public int bouncesLeft; // -1 for infinite
public int activateBouncesLeft;
// Settings that are read when the projectile is spawned, instead of on usage.
// This mainly affects settings that are randomized based on tick.
// This is because of performance.
// All of these attributes will have to go into the WeaponSync message
public boolean collideTile;
public boolean collideShip;
public boolean damageSelf;
public boolean damageTeam;
public int bounceFriction;
public int bounceOtherAxisFriction;
public int proxDist;
public int proxExplodeDelay;
public int forceDistanceShip;
public int forceVelocityShip;
public int forceDistanceProjectile;
public int forceVelocityProjectile;
/** If set, we hit a tile during during performDeadReckoning() and an event should be fired soon. */
private final PhysicsPoint hitTile = new PhysicsPoint();
public Actor proxActivatedBy;
public long proxLastSeenDist;
public long proxLastSeenDist_tick;
public long proxActivatedAt_tick;
public Projectile(
ProjectileKey key,
State state,
MapEntity[] crossStateList,
Actor owner,
long createdAt_tick,
WeaponConfig config,
int projectile_index)
{
super(state,
crossStateList,
createdAt_tick,
(state.isLast ? 0 : state.econfig.TRAILING_STATE_DELAY) + state.econfig.MINIMUM_HISTORY_TICKS);
this.key = key;
this.owner = owner; // note may be null for now, will be resolved by resetTo
this.config = config; // note may be null for now, will be resolved by resetTo
this.configIndex = projectile_index;
this.radius = GCIntegerFixed.ZERO;
}
@Override
public void getSync(GameOperation.WeaponSync.Projectile.Builder p)
{
p.setIndex(configIndex);
p.setX(pos.pos.x);
p.setY(pos.pos.y);
p.setXVel(pos.vel.x);
p.setYVel(pos.vel.y);
p.setExpiresAt(this.expiresAt_tick);
p.setBouncesLeft(bouncesLeft);
p.setActivateBouncesLeft(activateBouncesLeft);
p.setCollideTile(collideTile);
p.setCollideShip(collideShip);
p.setDamageSelf(damageSelf);
p.setDamageTeam(damageTeam);
p.setBounceFriction(bounceFriction);
p.setBounceOtherAxisFriction(bounceOtherAxisFriction);
p.setProxDist(proxDist);
p.setProxExplodeDelay(proxExplodeDelay);
p.setProxActivatedBy(proxActivatedBy == null || proxActivatedBy.isRemoved() ? 0 : proxActivatedBy.pid);
p.setProxLastSeenDist(proxLastSeenDist);
p.setProxLastSeenDistTick(proxLastSeenDist_tick);
p.setProxActivatedAtTick(proxActivatedAt_tick);
p.setForceDistanceShip(forceDistanceShip);
p.setForceVelocityShip(forceVelocityShip);
p.setForceDistanceProjectile(forceDistanceProjectile);
p.setForceVelocityProjectile(forceVelocityProjectile);
}
public void initFromSync(GameOperation.WeaponSync.Projectile s, long tick_now)
{
initialized = true;
assert configIndex == s.getIndex();
pos.pos.x = s.getX();
pos.pos.y = s.getY();
pos.vel.x = s.getXVel();
pos.vel.y = s.getYVel();
expiresAt_tick = s.getExpiresAt();
bouncesLeft = s.getBouncesLeft();
activateBouncesLeft = s.getActivateBouncesLeft();
collideTile = s.getCollideTile();
collideShip = s.getCollideShip();
damageSelf = s.getDamageSelf();
damageTeam = s.getDamageTeam();
bounceFriction = s.getBounceFriction();
bounceOtherAxisFriction = s.getBounceOtherAxisFriction();
proxDist = s.getProxDist();
proxExplodeDelay = s.getProxExplodeDelay();
proxActivatedBy = s.getProxActivatedBy() == 0 ? null : state.actors.get(new ActorKey(s.getProxActivatedBy()));
proxLastSeenDist = s.getProxLastSeenDist();
proxLastSeenDist_tick = s.getProxLastSeenDistTick();
proxActivatedAt_tick = s.getProxActivatedAtTick();
forceDistanceShip = s.getForceDistanceShip();
forceVelocityShip = s.getForceVelocityShip();
forceDistanceProjectile = s.getForceDistanceProjectile();
forceVelocityProjectile = s.getForceVelocityProjectile();
}
public void register()
{
Projectile oldValue = state.projectiles.put(this.key, this);
assert oldValue == null;
state.projectilesList.append(this.projectileListLink_state);
this.owner.projectiles.append(this.projectileListLink_actor);
if (this.isForceEmitter())
{
state.forceEmitterList.append(this.forceEmitterListLink_state);
}
}
@Override
public void hardRemove(long tick)
{
super.hardRemove(tick);
projectileListLink_actor.remove();
projectileListLink_state.remove();
forceEmitterListLink_state.remove();
state.projectiles.remove(this.key);
coupled.remove();
// only modify the entry for _this_ projectile in the state list!
// this method may be called while looping over this state list
}
public void initFire(long tick, PhysicsShipPosition actorPos)
{
initialized = true;
pos.pos.set(actorPos.x, actorPos.y);
int rot = 0;
if (cfg(config.projectile_angleRelative, tick))
{
rot = actorPos.rot_snapped;
}
rot += cfg(config.projectile_angle, tick);
// relative to rot 0
int offsetX = cfg(config.projectile_offsetX, tick);
int offsetY = config.projectile_offsetY.isIndexSet(configIndex)?
cfg(config.projectile_offsetY, tick) :
owner.radius.get();
PhysicsPoint offset = new PhysicsPoint(0, 0);
PhysicsMath.rotationToPoint(
offset,
rot + EnvironmentConf.ROTATION_1_4TH,
offsetX);
PhysicsMath.rotationToPoint(
offset,
rot,
offsetY);
Collision collision = state.collision;
collision.reset();
collision.setPreviousPosition(pos.pos);
if (cfg(config.projectile_hitTile, tick))
{
collision.setMap(state.env.getMap());
}
collision.setVelocity(offset);
collision.setRadius(radius.get());
collision.setBouncesLeft(0); // 0 bounces, the resulting position will be set at the collide position
collision.tickMap(tick);
collision.getNewPosition(pos.pos);
// make sure the projectile does not spawn inside of a tile (unless the ship is inside a tile too)
if (cfg(config.projectile_speedRelative, tick))
{
pos.vel.set(actorPos.x_vel, actorPos.y_vel);
}
PhysicsMath.rotationToPoint(
pos.vel,
rot,
cfg(config.projectile_speed, tick));
pos.enforceOverflowLimit();
collideTile = cfg(config.projectile_hitTile, tick);
collideShip = cfg(config.projectile_hitShip, tick);
damageSelf = cfg(config.projectile_damageSelf, tick);
damageTeam = cfg(config.projectile_damageTeam, tick);
expiresAt_tick = tick + cfg(config.projectile_expirationTicks, tick);
bouncesLeft = cfg(config.projectile_bounces, tick);
activateBouncesLeft = cfg(config.projectile_activateBounces, tick);
bounceFriction = cfg(config.projectile_bounceFriction, tick);
bounceOtherAxisFriction = cfg(config.projectile_bounceOtherAxisFriction, tick);
proxDist = cfg(config.projectile_proxDistance, tick);
proxExplodeDelay = config.projectile_proxExplodeTicks.isSet()
? cfg(config.projectile_proxExplodeTicks, tick)
: -1;
forceDistanceShip = cfg(config.projectile_forceDistanceShip, tick);
forceVelocityShip = cfg(config.projectile_forceVelocityShip, tick);
forceDistanceProjectile = cfg(config.projectile_forceDistanceProjectile, tick);
forceVelocityProjectile = cfg(config.projectile_forceVelocityProjectile, tick);
}
public void attemptCorrectionForLateProjectile(long operation_tick, boolean operation_late)
{
// dead reckon current position so that it is no longer late
// the position at the tick of this operation should not be dead reckoned, therefor +1
// First update the projectile up to the expiry...
long expiry_tick = max(operation_tick, this.getExpiry());
long untilExpiry_ticks = min(expiry_tick - operation_tick, state.tick_now - operation_tick);
long afterExpiry_ticks = max(state.tick_now - expiry_tick, 0);
this.performDeadReckoning(state.env.getMap(), operation_tick + 1, untilExpiry_ticks);
if (this.isForceEmitter() && operation_late)
{
// however a force emitter should emit for the current tick also ( <= ).
// If late=false, State.tickForceEmitters will be called soon
long tick = operation_tick;
for (long t = 0; t <= untilExpiry_ticks; ++t)
{
tick = operation_tick + t;
this.emitForce(tick);
}
assert tick == state.tick_now ||
tick == expiry_tick;
}
if (expiry_tick <= state.tick_now)
{
// (performDeadReckoning and emitForce check for isRemoved(tick))
this.explodeWithoutHit(expiry_tick, EXPLODE_REASON.EXPIRATION);
this.softRemove(expiry_tick);
// The expiry itself has already been simulated
this.performDeadReckoning(state.env.getMap(), expiry_tick + 1, afterExpiry_ticks);
}
assert this.posHistory.getHighestTick() == state.tick_now;
}
@SuppressWarnings("unchecked")
@Override
public void performDeadReckoning(PhysicsMap map, long tick_now, long reckon_ticks)
{
Collision collision = state.collision;
collision.reset();
collision.setMap(this.collideTile ? map : null);
collision.setRadius(this.radius.get());
final PhysicsPoint prevForce = new PhysicsPoint();
for (long t = 0; t < reckon_ticks; ++t)
{
long tick = tick_now + t;
dirtyPositionPathTracker.resolved(tick);
assert !dirtyPositionPathTracker.isDirty(tick) : "performDeadReckoning: Skipped a tick!";
if (this.isRemoved(tick) || hitTile.set)
{
updatedPosition(tick);
continue;
}
// force for _this_ tick is added AFTER we dead reckon.
// so wait for the next tick to do the force for _this_ tick.
// otherwise all entities have to be looped an extra time.
this.forceHistory.get(prevForce, tick - 1);
this.pos.vel.add(prevForce);
collision.setPreviousPosition(pos.pos);
collision.setVelocity(pos.vel);
collision.setBouncesLeft(bouncesLeft);
collision.tickMap(tick);
collision.getNewPosition(pos.pos);
collision.getVelocity(pos.vel);
if (bouncesLeft >= 0)
{
bouncesLeft -= collision.getBounces();
if (bouncesLeft < 0) bouncesLeft = 0;
}
if (activateBouncesLeft > 0)
{
activateBouncesLeft -= collision.getBounces();
if (activateBouncesLeft < 0) activateBouncesLeft = 0;
}
updatedPosition(tick);
// hit a tile?
if (collision.hasExhaustedBounces())
{
collision.getHitTile(hitTile);
hitTile.set = true;
// The event is not really executed until actors have ticked (see tickProjectileAfterActor)
// This is so that hitting an actor is prioritized over hitting a tile.
}
}
}
public void hitByActor(long tick, Actor actor, PhysicsPoint location)
{
// note: we may execute the event multiple times on the same state
// This is valid. (it happens when a timewarp occurs)
// The event should discard the previous consistency information.
if (location.set)
{
this.pos.pos.set(location);
updatedPosition(tick);
}
// Do not execute the hit tile event if it was planned.
hitTile.unset();
ProjectileExplosion.Key eventKey = new ProjectileExplosion.Key(this.key);
ProjectileExplosion event = (ProjectileExplosion) state.env.findEvent(eventKey);
if (event == null)
{
event = new ProjectileExplosion(state.env, eventKey);
}
state.env.registerEvent(event);
event.execute(tick, this.state, this, ProjectileExplosionPublic.EXPLODE_REASON.HIT_SHIP, actor, null);
}
public void tickProjectileAfterActor(long tick)
{
if (this.isRemoved(tick))
{
return;
}
if (this.hitTile.set)
{
// note: we may execute the event multiple times on the same state
// This is valid. (it happens when a timewarp occurs)
// The event should discard the previous consistency information.
ProjectileExplosion.Key eventKey = new ProjectileExplosion.Key(this.key);
ProjectileExplosion event = (ProjectileExplosion) state.env.findEvent(eventKey);
if (event == null)
{
event = new ProjectileExplosion(state.env, eventKey);
}
if (event.hasOccurred(this.state.id))
{
System.out.println("already occured??");
}
state.env.registerEvent(event);
event.execute(tick, this.state, this, ProjectileExplosionPublic.EXPLODE_REASON.HIT_TILE, null, hitTile);
assert this.isRemoved(tick); // Otherwise this event fires over and over and over
return;
}
// TODO: Use state.entityGrid if it is much faster?
// Proximity bombs
// (unlike continuum prox bombs still take part in regular collision unless
// disabled by config)
if (proxDist > 0 && (this.proxActivatedBy == null || this.proxActivatedBy.isRemoved(tick)))
{
long proxDistSq = proxDist * (long) proxDist;
for (Actor actor : state.actorsList)
{
if (this.collidesWithFilter.loopFilter(actor, tick))
{
continue;
}
// easy case
long distSq = this.pos.pos.distanceSquared(actor.pos.pos);
if (distSq > proxDistSq)
{
continue;
}
long dist = this.pos.pos.distance(actor.pos.pos, distSq);
if (dist > proxDist)
{
continue;
}
this.proxActivatedBy = actor;
this.proxActivatedAt_tick = tick;
this.proxLastSeenDist = dist;
this.proxLastSeenDist_tick = tick;
break;
}
}
if (this.proxActivatedBy != null)
{
long dist = this.pos.pos.distance(this.proxActivatedBy.pos.pos);
if (tick <= this.proxLastSeenDist_tick)
{
// Reexecuting moves, reset the last seen distance
}
else
{
if (dist > this.proxLastSeenDist)
{
// moving away! detonate
explodeWithoutHit(tick, EXPLODE_REASON.PROX_DIST);
assert this.isRemoved(tick); // Otherwise this event fires over and over and over
return;
}
}
this.proxLastSeenDist = dist;
this.proxLastSeenDist_tick = tick;
if (proxExplodeDelay >= 0 && tick - this.proxActivatedAt_tick >= proxExplodeDelay)
{
explodeWithoutHit(tick, EXPLODE_REASON.PROX_DELAY);
assert this.isRemoved(tick); // Otherwise this event fires over and over and over
return;
}
}
}
public void explodeWithoutHit(long tick, ProjectileExplosionPublic.EXPLODE_REASON reason)
{
assert !this.isRemoved(tick);
ProjectileExplosion.Key eventKey = new ProjectileExplosion.Key(this.key);
ProjectileExplosion event = (ProjectileExplosion) state.env.findEvent(eventKey);
if (event == null)
{
event = new ProjectileExplosion(state.env, eventKey);
}
state.env.registerEvent(event);
event.execute(tick, this.state, this, reason, null, null);
}
public @Nullable Projectile findInOtherState(State otherState)
{
if (this.state.isForeign(otherState))
{
return otherState.projectiles.get(this.key);
}
else
{
return (Projectile) this.crossStateList[otherState.id];
}
}
@Override
public void resetTo(State myState, MapEntity other_)
{
super.resetTo(myState, other_);
Projectile other = (Projectile) other_;
assert this.key.equals(other.key);
this.initialized = other.initialized;
if (this.owner == null)
{
if (other.owner != null)
{
this.owner = (Actor) other.owner.findInOtherState(state);
this.config = this.owner.config.getWeaponConfig(other.config.weaponKey);
}
}
else
{
assert this.owner.pid == other.owner.pid : "Projectiles should never change owners in a timewarp";
}
this.coupled.previous = null;
this.coupled.next = null;
if (other.coupled.previous != null && other.coupled.next != null)
{
Projectile otherPrev = other.coupled.previous.data;
Projectile otherNext = other.coupled.next.data;
Projectile prev = otherPrev.findInOtherState(this.state);
Projectile next = otherNext.findInOtherState(this.state);
// Note that the coupled projectile might not exist yet!
// it will be created at a different moment in the timewarp
// therefor prev or next (or both) might be null.
// State.resetTo has an assertion check to make sure the code below is proper
if (prev != null)
{
this.coupled.previous = prev.coupled;
prev.coupled.next = this.coupled;
}
if (next != null)
{
this.coupled.next = next.coupled;
next.coupled.previous = this.coupled;
}
}
else
{
assert other.coupled.previous == null;
assert other.coupled.next == null;
}
this.expiresAt_tick = other.expiresAt_tick;
this.bouncesLeft = other.bouncesLeft;
this.activateBouncesLeft = other.activateBouncesLeft;
if (other.proxActivatedBy == null)
{
this.proxActivatedBy = null;
}
else
{
this.proxActivatedBy = (Actor) other.proxActivatedBy.findInOtherState(state);
}
this.proxLastSeenDist = other.proxLastSeenDist;
this.proxLastSeenDist_tick = other.proxLastSeenDist_tick;
this.proxActivatedAt_tick = other.proxActivatedAt_tick;
// do not reset references to events
}
public void resetToEmpty(long tick)
{
Projectile dummy = new Projectile(this.key, this.state, crossStateList, this.owner, tick, this.config, this.configIndex);
crossStateList[this.state.id] = null; // skip assertion in resetTo
this.resetTo(this.state, dummy);
crossStateList[this.state.id] = (MapEntity) this;
}
public int getSplashDamage(Actor actor, long tick, int damage, int range, long rangeSq)
{
final PhysicsPositionVector myPos = new PhysicsPositionVector();
final PhysicsPositionVector actorPos = new PhysicsPositionVector();
if (!this.getHistoricPosition(myPos, tick, false))
{
return 0;
}
if (!actor.getHistoricPosition(actorPos, tick, false))
{
return 0;
}
long distSq = myPos.pos.distanceSquared(actorPos.pos);
if (distSq >= rangeSq)
{
return 0; // out of range
}
long ldist = myPos.pos.distance(actorPos.pos, distSq);
assert ldist >= 0;
int dist = ldist > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) ldist;
assert range >= dist;
// if dist == splash do 0 damage
return (int) ((long) (range - dist) * damage / range);
}
public void doSplashDamage(Actor except, long tick, Collection<Integer> killed)
{
int splash = cfg(config.projectile_damageSplash, tick) * 1024;
if (splash == 0)
{
return;
}
int damage = cfg(config.projectile_damage, tick) * 1024;
long splashSq = splash * (long) splash;
boolean damageSelfKill = cfg(config.projectile_damageSelfKill, tick);
boolean damageTeamKill = cfg(config.projectile_damageTeamKill, tick);
for (Actor actor : state.actorsList)
{
if (actor.isRemoved(tick) || actor.isDead(tick)) { continue; }
if (actor == except) { continue; }
if (actor == this.owner && !damageSelf) { continue; }
// todo team
int effectiveDamage = getSplashDamage(actor, tick, damage, splash, splashSq);
actor.energy.addRelativeValue(
Actor.ENERGY_SETTER.OTHER.id,
tick,
-effectiveDamage);
if (actor.energy.get(tick) <= 0)
{
if (!damageSelfKill && actor == this.owner)
{
}
else
{
actor.died(tick);
killed.add(actor.pid);
}
}
}
}
public void doSplashEmp(Actor except, long tick)
{
int p = this.configIndex;
int splash = cfg(config.projectile_empSplash, tick) * 1024;
if (splash == 0)
{
return;
}
int damage = cfg(config.projectile_empTime, tick);
long splashSq = splash * (long) splash;
boolean empSelf = cfg(config.projectile_empSelf, tick);
boolean empTeam = cfg(config.projectile_empTeam, tick);
for (Actor actor : state.actorsList)
{
if (actor.isRemoved(tick) || actor.isDead(tick)) { continue; }
if (actor == except) { continue; }
if (actor == this.owner && !empSelf) { continue; }
// todo team
actor.applyEmp(tick, getSplashDamage(actor, tick, damage, splash, splashSq));
}
}
@Override
public int getStateId()
{
return state.id;
}
@Override
public int getOwner()
{
return owner.pid;
}
@Override
public long getExpiry()
{
return expiresAt_tick;
}
@Override
public AttachmentData getAttachments()
{
return attachments;
}
public List<MapEntity> getCollidesWith()
{
return (List<MapEntity>) (Object) state.actorsList;
}
// second arg = tick
public final LoopFilter<MapEntity, Long> collidesWithFilter = new LoopFilter<MapEntity, Long>()
{
@Override
public boolean loopFilter(MapEntity en, Long arg)
{
if (en instanceof Actor)
{
Actor actor = (Actor) en;
if (actor.isRemoved(arg) || actor.isDead(arg))
{
return true;
}
// never hit your own weapons...
if (owner != null && owner.pid == actor.pid)
{
return true;
}
// todo freqs
}
return false;
}
};
@Override
public int getBouncesLeft()
{
return this.bouncesLeft;
}
@Override
public int getActivateBouncesLeft()
{
return this.activateBouncesLeft;
}
@Override
public boolean isActive()
{
if (this.activateBouncesLeft > 0)
{
return false;
}
return true;
}
public boolean isForceEmitter()
{
if (!initialized)
{
throw new IllegalStateException();
}
final boolean doShip = this.forceDistanceShip > 0 && this.forceVelocityShip != 0;
final boolean doProjectile = this.forceDistanceProjectile > 0 && this.forceVelocityProjectile != 0;
return doShip || doProjectile;
}
/** Emit the configured force on the "forceHistory" of other entities, without updating the velocity or position.
* The velocity and position must be updated in a separate step.
* @param tick
*/
public void emitForce(long tick)
{
final boolean doShip = this.forceDistanceShip > 0 && this.forceVelocityShip != 0;
final boolean doProjectile = this.forceDistanceProjectile > 0 && this.forceVelocityProjectile != 0;
if (!doShip && !doProjectile)
{
return;
}
if (this.isRemoved(tick))
{
return;
}
final PhysicsPositionVector myPos = new PhysicsPositionVector();
this.getHistoricPosition(myPos, tick, false);
final PhysicsPoint forcePoint = new PhysicsPoint(myPos.pos);
Iterator<MapEntity> it = state.entityGrid.iterator(
forcePoint,
SwissArmyKnife.max(this.forceDistanceShip, this.forceDistanceProjectile));
final PhysicsPositionVector otherPosition = new PhysicsPositionVector();
final PhysicsPoint velocity = new PhysicsPoint();
final PhysicsPoint forceHist = new PhysicsPoint();
while (it.hasNext())
{
MapEntity en = it.next();
if (en == this) { continue; }
if (doShip && en instanceof Actor)
{
Actor actor = (Actor) en;
if (actor.isDead(tick)) { continue; }
if (!damageSelf && en == this.owner)
{
continue;
}
}
else if (doProjectile && en instanceof Projectile)
{
Projectile proj = (Projectile) en;
if (!damageSelf && proj.owner == this.owner)
{
continue;
}
// Force emitters never affect other force emitters
// (or, at least for now, it causes too many inconsistencies)
if (proj.isForceEmitter())
{
continue;
}
}
en.getHistoricPosition(otherPosition, tick, false);
PhysicsMath.force(velocity, otherPosition.pos, forcePoint, forceDistanceShip, forceVelocityShip);
if (!velocity.isZero())
{
en.markDirtyPositionPath(tick + 1);
en.forceHistory.get(forceHist, tick);
forceHist.add(velocity);
forceHist.enforceOverflowLimit();
en.forceHistory.setHistory(tick, forceHist);
}
}
}
@Override
public GCInteger getWeaponConfigInteger(String name)
{
return config.selection.getInteger(name);
}
@Override
public GCString getWeaponConfigString(String name)
{
return config.selection.getString(name);
}
@Override
public GCBoolean getWeaponConfigBoolean(String name)
{
return config.selection.getBoolean(name);
}
@Override
public GCIntegerList getWeaponConfigIntegerList(String name)
{
return config.selection.getIntegerList(name);
}
@Override
public GCStringList getWeaponConfigStringList(String name)
{
return config.selection.getStringList(name);
}
@Override
public GCBooleanList getWeaponConfigBooleanList(String name)
{
return config.selection.getBooleanList(name);
}
@Override
public GCImage getWeaponConfigImage(String name, ResourceDB db)
{
return config.selection.getImage(name, db);
}
@Override
public GCColour getWeaponConfigColour(String name)
{
return config.selection.getColour(name);
}
@Override
public String getWeaponKey()
{
return config.weaponKey;
}
@Override
public int getProjectileIndex()
{
return this.configIndex;
}
@Override
public Iterator<ProjectilePublic> getCoupledProjectiles()
{
return (Iterator<ProjectilePublic>) (Object) coupled.iteratorReadOnly();
}
public int configSeed(long tick)
{
assert owner != null;
return owner.seed_low ^ ((int) tick);
}
// some short hands to save typing
public int cfg(GCIntegerList configValue, long tick)
{
return configValue.get(this.configIndex, configSeed(tick));
}
public boolean cfg(GCBooleanList configValue, long tick)
{
return configValue.get(this.configIndex, configSeed(tick));
}
public String cfg(GCStringList configValue, long tick)
{
return configValue.get(this.configIndex, configSeed(tick));
}
}
|
package archimulator.sim.uncore;
import archimulator.sim.base.event.DumpStatEvent;
import archimulator.sim.base.simulation.BasicSimulationObject;
import archimulator.sim.core.ProcessorConfig;
import archimulator.sim.uncore.coherence.msi.controller.CacheController;
import archimulator.sim.uncore.coherence.msi.controller.Controller;
import archimulator.sim.uncore.coherence.msi.controller.DirectoryController;
import archimulator.sim.uncore.coherence.msi.message.CoherenceMessage;
import archimulator.sim.uncore.dram.*;
import archimulator.sim.uncore.net.L1sToL2Net;
import archimulator.sim.uncore.net.L2ToMemNet;
import archimulator.sim.uncore.net.Net;
import archimulator.sim.uncore.tlb.TranslationLookasideBuffer;
import net.pickapack.action.Action;
import net.pickapack.action.Action1;
import net.pickapack.event.BlockingEvent;
import net.pickapack.event.BlockingEventDispatcher;
import net.pickapack.event.CycleAccurateEventQueue;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class BasicCacheHierarchy extends BasicSimulationObject implements CacheHierarchy {
private MemoryController mainMemory;
private DirectoryController l2Cache;
private List<CacheController> instructionCaches;
private List<CacheController> dataCaches;
private List<TranslationLookasideBuffer> itlbs;
private List<TranslationLookasideBuffer> dtlbs;
private L1sToL2Net l1sToL2Network;
private L2ToMemNet l2ToMemNetwork;
private Map<Controller, Map<Controller, PointToPointReorderBuffer>> p2pReorderBuffers;
public BasicCacheHierarchy(BlockingEventDispatcher<BlockingEvent> blockingEventDispatcher, CycleAccurateEventQueue cycleAccurateEventQueue, ProcessorConfig processorConfig) {
super(blockingEventDispatcher, cycleAccurateEventQueue);
switch (processorConfig.getMemoryHierarchyConfig().getMainMemory().getType()) {
case SIMPLE:
this.mainMemory = new SimpleMemoryController(this, (SimpleMainMemoryConfig) processorConfig.getMemoryHierarchyConfig().getMainMemory());
break;
case BASIC:
this.mainMemory = new BasicMemoryController(this, (BasicMainMemoryConfig) processorConfig.getMemoryHierarchyConfig().getMainMemory());
break;
default:
this.mainMemory = new FixedLatencyMemoryController(this, (FixedLatencyMainMemoryConfig) processorConfig.getMemoryHierarchyConfig().getMainMemory());
break;
}
this.l2Cache = new DirectoryController(this, "llc", processorConfig.getMemoryHierarchyConfig().getL2Cache());
this.l2Cache.setNext(this.mainMemory);
this.instructionCaches = new ArrayList<CacheController>();
this.dataCaches = new ArrayList<CacheController>();
this.itlbs = new ArrayList<TranslationLookasideBuffer>();
this.dtlbs = new ArrayList<TranslationLookasideBuffer>();
for (int i = 0; i < processorConfig.getNumCores(); i++) {
CacheController instructionCache = new CacheController(this, "c" + i + ".icache", processorConfig.getMemoryHierarchyConfig().getInstructionCache());
instructionCache.setNext(this.l2Cache);
this.instructionCaches.add(instructionCache);
CacheController dataCache = new CacheController(this, "c" + i + ".dcache", processorConfig.getMemoryHierarchyConfig().getDataCache());
dataCache.setNext(this.l2Cache);
this.dataCaches.add(dataCache);
for (int j = 0; j < processorConfig.getNumThreadsPerCore(); j++) {
TranslationLookasideBuffer itlb = new TranslationLookasideBuffer(this, "c" + i + "t" + j + ".itlb", processorConfig.getTlb());
this.itlbs.add(itlb);
TranslationLookasideBuffer dtlb = new TranslationLookasideBuffer(this, "c" + i + "t" + j + ".dtlb", processorConfig.getTlb());
this.dtlbs.add(dtlb);
}
}
this.l1sToL2Network = new L1sToL2Net(this);
this.l2ToMemNetwork = new L2ToMemNet(this);
this.p2pReorderBuffers = new HashMap<Controller, Map<Controller, PointToPointReorderBuffer>>();
this.getBlockingEventDispatcher().addListener(DumpStatEvent.class, new Action1<DumpStatEvent>() {
public void apply(DumpStatEvent event) {
if (event.getType() == DumpStatEvent.Type.DETAILED_SIMULATION) {
dumpStats();
}
}
});
}
public void dumpStats() {
for(CacheController instructionCache : this.instructionCaches) {
System.out.println("Cache Controller " + instructionCache.getName() + " FSM: ");
System.out.println("
instructionCache.getFsmFactory().dump();
}
System.out.println();
System.out.println();
for(CacheController dataCache : this.dataCaches) {
System.out.println("Cache Controller " + dataCache.getName() + " FSM: ");
System.out.println("
dataCache.getFsmFactory().dump();
}
System.out.println();
System.out.println();
System.out.println("
System.out.println("Directory Controller " + this.l2Cache.getName() + " FSM: ");
this.l2Cache.getFsmFactory().dump();
}
@Override
public void transfer(final Controller from, final Controller to, int size, final CoherenceMessage message) {
if(!this.p2pReorderBuffers.containsKey(from)) {
this.p2pReorderBuffers.put(from, new HashMap<Controller, PointToPointReorderBuffer>());
}
if(!this.p2pReorderBuffers.get(from).containsKey(to)) {
this.p2pReorderBuffers.get(from).put(to, new PointToPointReorderBuffer(from, to));
}
this.p2pReorderBuffers.get(from).get(to).transfer(message);
from.getNet(to).transfer(from, to, size, new Action() {
@Override
public void apply() {
p2pReorderBuffers.get(from).get(to).onDestinationArrived(message);
}
});
}
public MemoryController getMainMemory() {
return mainMemory;
}
public DirectoryController getL2Cache() {
return l2Cache;
}
public List<CacheController> getInstructionCaches() {
return instructionCaches;
}
public List<CacheController> getDataCaches() {
return dataCaches;
}
public List<TranslationLookasideBuffer> getItlbs() {
return itlbs;
}
public List<TranslationLookasideBuffer> getDtlbs() {
return dtlbs;
}
public Net getL1sToL2Network() {
return l1sToL2Network;
}
public L2ToMemNet getL2ToMemNetwork() {
return l2ToMemNetwork;
}
}
|
package ca.krasnay.sqlbuilder;
import java.security.SecureRandom;
public class UniqueStringGenerator implements Supplier<String> {
public static final String BASE36 = "0123456789abcdefghijklmnopqrstuvwxyz";
public static final String BASE62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
private String[] blacklist = "anal,anus,ass,boob,butt,clit,cock,cum,cunt,dick,fuck,gay,nigg,poon,poop,porn,pube,sex,shit,smut,tit,twat,vag".split(",");
private String alphabet;
private int length;
public UniqueStringGenerator(int length) {
this(BASE62, length);
}
public UniqueStringGenerator(String alphabet, int length) {
this.alphabet = alphabet;
this.length = length;
}
boolean isOffensive(String s) {
String normalized = s.toLowerCase()
.replace("0", "o")
.replace("1", "i")
.replace("5", "s")
.replace("v", "u");
for (String badWord : blacklist) {
if (normalized.contains(badWord)) {
return true;
}
}
return false;
}
@Override
public String get() {
while (true) {
String s = generate();
if (!isOffensive(s)) {
return s;
}
}
}
private String generate() {
SecureRandom random = new SecureRandom();
StringBuilder sb = new StringBuilder();
int n = alphabet.length();
for (int i = 0; i < length; i++) {
sb.append(alphabet.charAt(random.nextInt(n)));
}
return sb.toString();
}
}
|
package club.magicfun.aquila.job;
import java.io.File;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriver.Options;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TestWebDriverBaidu {
private static final Logger logger = LoggerFactory.getLogger(TestWebDriverBaidu.class);
private static final String BAIDU_SEARCH_URL = "http:
public static final long SLEEP_TIME = 1000l;
public static void main(String[] args) {
String dir = System.getProperty("user.dir");
String osName = System.getProperty("os.name");
// load the appropriate chrome drivers according to the OS type
if (osName.toLowerCase().indexOf("windows") > -1) {
System.setProperty("webdriver.chrome.driver", dir + File.separator + "drivers" + File.separator + "win"
+ File.separator + "chromedriver.exe");
} else if (osName.toLowerCase().indexOf("mac") > -1) {
System.setProperty("webdriver.chrome.driver", dir + File.separator + "drivers" + File.separator + "mac"
+ File.separator + "chromedriver");
}
String searchKeyword = "";
String targetLinkPartialText = " ";
WebDriver webDriver = new ChromeDriver();
String url = BAIDU_SEARCH_URL.replaceFirst("\\{KEYWORD\\}", searchKeyword);
int maxRetryCount = 20;
for (int i = 1; i < maxRetryCount; i++) {
webDriver.get(url);
try {
WebElement targetLink = webDriver.findElement(By.partialLinkText(targetLinkPartialText));
// fount out, click now!
logger.info("found out! click now! ");
targetLink.click();
try {
Thread.sleep(SLEEP_TIME);
} catch (InterruptedException e) {
e.printStackTrace();
}
break;
} catch (NoSuchElementException nsex) {
// do nothing
}
}
webDriver.close();
webDriver.quit();
}
}
|
package co.ecso.jdao.cache;
import co.ecso.jdao.config.ApplicationConfig;
import co.ecso.jdao.connection.ConnectionPool;
import co.ecso.jdao.database.DatabaseField;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
/**
* CachingConnectionWrapper.
*
* @author Christian Senkowski (cs@2scale.net)
* @version $Id:$
* @since 02.07.16
*/
public class CachingConnectionWrapper {
private static final Object MUTEX = new Object();
private static final Map<Integer, Cache<CacheKey<?>, CompletableFuture<?>>> CACHE_MAP = new ConcurrentHashMap<>();
private static final Map<Integer, ConnectionPool<Connection>> CONNECTION_POOL_MAP = new ConcurrentHashMap<>();
private final Connection databaseConnection;
private final ApplicationConfig config;
public CachingConnectionWrapper(final ApplicationConfig config,
final Cache<CacheKey<?>, CompletableFuture<?>> cache) throws SQLException {
synchronized (MUTEX) {
if (!CONNECTION_POOL_MAP.containsKey(config.hashCode())) {
CONNECTION_POOL_MAP.putIfAbsent(config.hashCode(), config.getConnectionPool());
}
this.databaseConnection = CONNECTION_POOL_MAP.get(config.hashCode()).getConnection();
this.config = config;
CACHE_MAP.putIfAbsent(databaseConnection.hashCode(), cache);
}
}
// public final CompletableFuture<Boolean> truncate(final String query) {
// return ((Truncater) () -> config).truncate(query)
// .thenApply(rVal -> {
// if (rVal) {
// synchronized (MUTEX) {
// CACHE_MAP.get(databaseConnection.hashCode()).invalidateAll();
// CACHE_MAP.get(databaseConnection.hashCode()).cleanUp();
// return rVal;
// public final CompletableFuture<Long> insert(final String query, final Map<DatabaseField<?>, ?> map) {
// synchronized (MUTEX) {
// CACHE_MAP.get(databaseConnection.hashCode()).invalidateAll();
// CACHE_MAP.get(databaseConnection.hashCode()).cleanUp();
// return ((Inserter<Long>) () -> config).insert(query, map);
// /*
// public final CompletableFuture<?> findMany(final String query, final DatabaseField<?> column,
// final CompletableFuture<Long> whereIdFuture) throws ExecutionException {
// synchronized (MUTEX) {
// final CacheKey cacheKey = new CacheKey<>(query.getQuery(), column, whereIdFuture);
// return CACHE_MAP.get(databaseConnection.hashCode()).get(cacheKey, () ->
// ((MultipleColumnFinder<Long>) () -> config)
// .findMany(query, cacheKey.columnName(), cacheKey.whereId()));
// }
// }
// */
// SELECT %s from customer
// public final CompletableFuture<List<?>> findMany(final String query,
// final DatabaseField<?> columnToSelect,
// final Map<DatabaseField<?>, CompletableFuture<?>>
// columnsWhere) throws ExecutionException {
// todo
// final CacheKey cacheKey = new CacheKey<>(query, null, CompletableFuture.completedFuture(columnsWhere));
// noinspection unchecked
// return (CompletableFuture<List<?>>) CACHE_MAP.get(databaseConnection.hashCode()).get(cacheKey, () ->
// ((SingleColumnFinder) () -> config)
// .find(new ListFindQuery(query, columnToSelect, columnsWhere)));
// /*
// public final CompletableFuture<List<?>> findMany(final Query query, final DatabaseField<?> selector,
// final LinkedHashMap<DatabaseField<?>, ?> map) throws SQLException,
// ExecutionException {
// synchronized (MUTEX) {
// final CacheKey cacheKey = new CacheKey(query.getQuery(), selector,
// CompletableFuture.completedFuture(null));
// return (CompletableFuture<List<?>>) CACHE_MAP.get(databaseConnection.hashCode())
// .get(cacheKey, () -> ((MultipleColumnFinder<Long>) () -> config).findMany(query, selector, map));
// }
// }
//
// public CompletableFuture<Boolean> update(final Query query, final LinkedHashMap<DatabaseField<?>, ?> map,
// final CompletableFuture<?> whereId) {
// CACHE_MAP.get(databaseConnection.hashCode()).invalidateAll();
// CACHE_MAP.get(databaseConnection.hashCode()).cleanUp();
// return ((Updater) () -> config).update(query, map, whereId);
// }
// */
@SuppressWarnings("WeakerAccess")
public static final class CacheKey<T> implements Serializable {
private static final long serialVersionUID = -384732894789324L;
private final String tableName;
private final DatabaseField<?> columnName;
private final CompletableFuture<T> whereId;
private final Map<DatabaseField<?>, ?> values;
CacheKey(final String tableName, final DatabaseField<?> columnName, final CompletableFuture<T> whereId) {
this.tableName = tableName;
this.columnName = columnName;
this.whereId = whereId;
this.values = null;
}
@Override
public String toString() {
return "CacheKey{" +
"tableName='" + tableName + '\'' +
", columnName='" + columnName + '\'' +
", whereId=" + whereId +
", values=" + values +
'}';
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final CacheKey cacheKey = (CacheKey) o;
return whereId == cacheKey.whereId &&
Objects.equals(tableName, cacheKey.tableName) &&
Objects.equals(columnName, cacheKey.columnName) &&
Objects.equals(values, cacheKey.values);
}
@Override
public int hashCode() {
return Objects.hash(tableName, columnName, whereId, values);
}
}
}
|
package co.edu.uniandes.ecos.tarea7.util;
/**
* Clase utilitaria de constantes
* @author Daniel
*/
public class Constantes {
public static final String PROGRAM_NUMBER = "PN";
public static final String ESTIMATED_PROXY_SIZE = "EPS";
public static final String PLAN_ADDED_MODIFIED_SIZE = "PAMS";
public static final String ACTUAL_ADDED_MODIFIED_SIZE = "AAMS";
public static final String ACTUAL_DEVELOPMENT_HOURS = "ADH";
public static final Double NUMBER_OF_SEGMENTS = 10D;
public static final Double ERROR = 0.00001;
public static final Double XK_1 = 386D;
public static final Double XK_2 = 227D;
public static final Double P_70 = 0.35D;
}
|
package com.aitusoftware.transport.buffer;
import com.aitusoftware.transport.files.Directories;
import com.aitusoftware.transport.files.Filenames;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Path;
public final class PageCache
{
private static final VarHandle CURRENT_PAGE_VH;
private static final VarHandle CURRENT_PAGE_NUMBER_VH;
private static final int INITIAL_PAGE_NUMBER = 0;
static
{
try
{
CURRENT_PAGE_VH = MethodHandles.lookup().
findVarHandle(PageCache.class, "currentPage", Page.class);
CURRENT_PAGE_NUMBER_VH = MethodHandles.lookup().
findVarHandle(PageCache.class, "currentPageNumber", int.class);
}
catch (NoSuchFieldException | IllegalAccessException e)
{
throw new IllegalStateException("Unable to obtain VarHandle");
}
}
private static final ThreadLocal<WritableRecord> RECORD_BUFFER =
ThreadLocal.withInitial(WritableRecord::new);
private final PageAllocator allocator;
private final Path path;
private final int pageSize;
private volatile Page currentPage;
private volatile int currentPageNumber;
private PageCache(final int pageSize, final Path path)
{
// TODO should handle initialisation from existing file-system resources
this.path = path;
allocator = new PageAllocator(this.path, pageSize);
CURRENT_PAGE_VH.setRelease(this, allocator.safelyAllocatePage(INITIAL_PAGE_NUMBER));
CURRENT_PAGE_NUMBER_VH.setRelease(this, INITIAL_PAGE_NUMBER);
this.pageSize = pageSize;
}
public WritableRecord acquireRecordBuffer(final int recordLength)
{
final Page page = (Page) CURRENT_PAGE_VH.getVolatile(this);
final int position = page.acquireSpaceInBuffer(recordLength);
if (position >= 0)
{
final WritableRecord record = RECORD_BUFFER.get();
record.set(page.slice(position, recordLength), page, position);
return record;
}
else if (position == Page.ERR_MESSAGE_TOO_LARGE)
{
throw new RuntimeException(String.format(
"Message too large for current page: %s", currentPage));
}
else if (position == Page.ERR_NOT_ENOUGH_SPACE)
{
int pageNumber = page.getPageNumber();
while (!Thread.currentThread().isInterrupted())
{
if (((int) CURRENT_PAGE_NUMBER_VH.get(this)) > pageNumber &&
((Page) CURRENT_PAGE_VH.get(this)).getPageNumber() == pageNumber)
{
// another write has won, and will allocate a new page
while ((((Page) CURRENT_PAGE_VH.get(this)).getPageNumber() == pageNumber))
{
Thread.yield();
}
break;
}
pageNumber = (int) CURRENT_PAGE_NUMBER_VH.get(this);
if (CURRENT_PAGE_NUMBER_VH.compareAndSet(this, pageNumber, pageNumber + 1))
{
// this thread won, allocate a new page
CURRENT_PAGE_VH.setRelease(this, allocator.safelyAllocatePage(pageNumber + 1));
break;
}
}
return acquireRecordBuffer(recordLength);
}
else
{
throw new IllegalStateException();
}
}
// contain page-cache header
void append(final ByteBuffer source)
{
final WritableRecord record = acquireRecordBuffer(source.remaining());
record.buffer().put(source);
record.commit();
}
public long estimateTotalLength()
{
final Page page = (Page) CURRENT_PAGE_VH.get(this);
return ((long) page.getPageNumber()) * page.totalDataSize() +
page.nextAvailablePosition();
}
public boolean isPageAvailable(final int pageNumber)
{
// optimisation - cache file names
return Files.exists(Filenames.forPageNumber(pageNumber, path));
}
public Page getPage(final int pageNumber)
{
// optimisation - cache pages
return allocator.loadExisting(pageNumber);
}
public int getPageSize()
{
return pageSize;
}
public static PageCache create(final Path path, final int pageSize)
{
Directories.ensureDirectoryExists(path);
return new PageCache(pageSize, path);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.