answer
stringlengths
17
10.2M
package org.jtalks.poulpe.web.controller.component; import org.jtalks.common.model.entity.Component; import org.jtalks.common.model.entity.ComponentType; import org.jtalks.poulpe.model.entity.Jcommune; import org.jtalks.poulpe.service.ComponentService; import org.jtalks.poulpe.web.controller.DialogManager; import org.jtalks.poulpe.web.controller.WindowManager; import org.jtalks.poulpe.web.controller.zkutils.BindUtilsWrapper; import org.zkoss.bind.annotation.BindingParam; import org.zkoss.bind.annotation.Command; import org.zkoss.bind.annotation.Init; import org.zkoss.bind.annotation.NotifyChange; import java.util.ArrayList; import java.util.List; /** * The class which manages actions and represents information about components displayed in administrator panel. * * @author Vermut */ public class ComponentsVm { public static final String EDIT_WINDOW_VISIBLE = "editWindowVisible", AVAILABLE_COMPONENT_TYPES = "availableComponentTypes", SELECTED_COMPONENT_TYPE = "selectedComponentType", SELECTED = "selected", CAN_CREATE_NEW_COMPPONENT = "canCreateNewComponent", COMPONENT_LIST = "componentList"; private Component selected; private boolean editWindowVisible; private boolean canCreateNewComponent; private List<Component> componentList; private List<ComponentType> availableComponentTypes; private BindUtilsWrapper bindWrapper = new BindUtilsWrapper(); // List of injectable properties private ComponentService componentService; private DialogManager dialogManager; private WindowManager windowManager; /** * Inits the data on the form. */ @Init public void init() { updateListComponentsData(); } /** * Creates new TopicType and adds it on form */ @Command @NotifyChange({EDIT_WINDOW_VISIBLE, AVAILABLE_COMPONENT_TYPES, SELECTED_COMPONENT_TYPE}) public void showAddComponentDialog() { selected = new Jcommune(); editWindowVisible = true; } /** * Edits the selected component. * * @param component selected component */ @Command @NotifyChange({SELECTED, EDIT_WINDOW_VISIBLE, AVAILABLE_COMPONENT_TYPES, SELECTED_COMPONENT_TYPE}) public void editComponent(@BindingParam("component") Component component) { selected = component; availableComponentTypes.add(selected.getComponentType()); editWindowVisible = true; } /** * Deletes the selected component */ @Command public void deleteComponent() { DialogManager.Performable dc = new DialogManager.Performable() { /** {@inheritDoc} */ @Override public void execute() { componentService.deleteComponent(selected); updateListComponentsData(); selected = null; /* * Because confirmation needed, we need to send notification * event programmatically */ bindWrapper.postNotifyChange(null, null, ComponentsVm.this, SELECTED); bindWrapper.postNotifyChange(null, null, ComponentsVm.this, COMPONENT_LIST); bindWrapper.postNotifyChange(null, null, ComponentsVm.this, CAN_CREATE_NEW_COMPPONENT); } }; dialogManager.confirmDeletion(selected.getName(), dc); } /** * Shows a component edit window */ @Command public void configureComponent() { EditComponentVm.openWindowForEdit(windowManager, selected); } /** * Saves the created or edited component in component list. */ @Command @NotifyChange({COMPONENT_LIST, SELECTED, CAN_CREATE_NEW_COMPPONENT, EDIT_WINDOW_VISIBLE}) public void saveComponent() { // if(selected.getComponentType().equals(ComponentType.FORUM)){ // String name = selected.getName(); // String description = selected.getDescription(); // selected = new Jcommune(); // selected.setName(name); // selected.setDescription(description); // selected.setComponentType(ComponentType.FORUM); // if(selected.getComponentType().equals(ComponentType.ADMIN_PANEL)){ // String name = selected.getName(); // String description = selected.getDescription(); // selected = new Poulpe(); // selected.setName(name); // selected.setDescription(description); // selected.setComponentType(ComponentType.ADMIN_PANEL); componentService.saveComponent(selected); editWindowVisible = false; updateListComponentsData(); } /** * Event which happen when user cansel editing of component. */ @Command @NotifyChange({SELECTED, EDIT_WINDOW_VISIBLE}) public void cancelEdit() { selected = null; editWindowVisible = false; updateListComponentsData(); } /** * Returns the list of all components. * * @return list of components */ public List<Component> getComponentList() { return componentList; } /** * @return {@code true} if the window for editing component should be visible, unless false. */ public boolean isEditWindowVisible() { return editWindowVisible; } /** * Sets the selected component from the list which displays components. * * @param selected {@link org.jtalks.common.model.entity.Component} */ public void setSelected(Component selected) { this.selected = selected; } /** * Returns the component which currently is edited, created or selected in a list which displays components. * * @return {@link org.jtalks.common.model.entity.Component} */ public Component getSelected() { return selected; } /** * @return {@code true} only if new component can be created, {@code false} in other cases. */ public boolean isCanCreateNewComponent() { return canCreateNewComponent; } /** * Returns all available component types which available to be set to editable component. * * @return list of available component types */ public List<ComponentType> getAvailableComponentTypes() { return availableComponentTypes; } private void updateListComponentsData() { availableComponentTypes = new ArrayList<ComponentType>(componentService.getAvailableTypes()); componentList = componentService.getAll(); canCreateNewComponent = !availableComponentTypes.isEmpty(); } /** * Sets the service instance which is used for manipulating with stored components. * * @param componentService the new value of the service instance */ public void setComponentService(ComponentService componentService) { this.componentService = componentService; } /** * Sets the dialog manager which is used for showing different types of dialog messages. * * @param dialogManager the new value of the dialog manager */ public void setDialogManager(DialogManager dialogManager) { this.dialogManager = dialogManager; } /** * Sets window manager. * * @param windowManager the new window manager */ public void setWindowManager(WindowManager windowManager) { this.windowManager = windowManager; } }
package org.rabix.engine.store.postgres.jdbi.impl; import org.rabix.common.helper.JSONHelper; import org.rabix.engine.store.model.EventRecord; import org.rabix.engine.store.repository.EventRepository; import org.skife.jdbi.v2.SQLStatement; import org.skife.jdbi.v2.StatementContext; import org.skife.jdbi.v2.sqlobject.*; import org.skife.jdbi.v2.sqlobject.customizers.RegisterMapper; import org.skife.jdbi.v2.sqlobject.stringtemplate.UseStringTemplate3StatementLocator; import org.skife.jdbi.v2.tweak.ResultSetMapper; import org.skife.jdbi.v2.unstable.BindIn; import java.lang.annotation.*; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; @RegisterMapper(value = JDBIEventRepository.EventMapper.class) @UseStringTemplate3StatementLocator public interface JDBIEventRepository extends EventRepository { @Override @SqlUpdate("insert into event (id,event,status,root_id) values (:id,:event,:status::event_status,:root_id)") void insert(@BindEvent EventRecord eventRecord); @Override @SqlUpdate("delete from event where id=:id") void deleteGroup(@Bind("id") UUID id); @Override @SqlUpdate("delete from event where root_id=:root_id") void deleteByRootId(@Bind("root_id") UUID rootId); @Override @SqlUpdate("delete from event where root_id=:root_id and id in (<ids>)") void deleteByGroupIds(@Bind("root_id") UUID rootId, @BindIn("ids") Set<UUID> groupIds); @Override @SqlUpdate("update event set status=:status::event_status where id=:id") void updateStatus(@Bind("id") UUID groupId, @Bind("status") EventRecord.Status status); @Override @SqlQuery("select * from event where status::text != 'FAILED' order by created_at asc") List<EventRecord> getPendingEvents(); public static class EventMapper implements ResultSetMapper<EventRecord> { public EventRecord map(int index, ResultSet r, StatementContext ctx) throws SQLException { EventRecord.Status status = EventRecord.Status.valueOf(r.getString("status")); Map<String, ?> event = JSONHelper.readMap(new String(r.getBytes("event"))); UUID rootId = r.getString("root_id") != null ? UUID.fromString(r.getString("root_id")) : null; return new EventRecord(rootId, UUID.fromString(r.getString("id")), status, event); } } @BindingAnnotation(JDBIEventRepository.BindEvent.EventBinderFactory.class) @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.PARAMETER }) public static @interface BindEvent { public static class EventBinderFactory implements BinderFactory<Annotation> { public Binder<JDBIEventRepository.BindEvent, EventRecord> build(Annotation annotation) { return new Binder<JDBIEventRepository.BindEvent, EventRecord>() { public void bind(SQLStatement<?> q, JDBIEventRepository.BindEvent bind, EventRecord event) { q.bind("id", event.getGroupId()); q.bind("event", JSONHelper.writeObject(event.getEvent()).getBytes()); q.bind("status", event.getStatus().toString()); q.bind("root_id", event.getRootId()); } }; } } } }
package de.itemis.mosig.racecar.textconv; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.nio.file.Paths; public class HtmlTextConverter { public HtmlTextConverter() { } public String convertToHtml(String input) { return "&lt;&gt;"; } }
package com.wzgiceman.rxretrofitlibrary.retrofit_rx.exception; public class HttpTimeException extends RuntimeException { public static final int UNKOWN_ERROR = 0x1002; public static final int NO_CHACHE_ERROR = 0x1003; public static final int CHACHE_TIMEOUT_ERROR = 0x1004; public HttpTimeException(int resultCode) { this(getApiExceptionMessage(resultCode)); } public HttpTimeException(String detailMessage) { super(detailMessage); } /** * * * @param code * @return */ private static String getApiExceptionMessage(int code) { switch (code) { case UNKOWN_ERROR: return ""; case NO_CHACHE_ERROR: return ""; case CHACHE_TIMEOUT_ERROR: return ""; default: return ""; } } }
package com.ge.research.sadl.owl2sadl; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStream; import java.io.StringWriter; import java.io.Writer; import java.net.URL; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ge.research.sadl.external.XMLHelper; import com.ge.research.sadl.reasoner.TranslationException; import com.google.common.base.Optional; import com.hp.hpl.jena.graph.GetTriple; import com.hp.hpl.jena.graph.Node; import com.hp.hpl.jena.graph.Triple; import com.hp.hpl.jena.ontology.AllValuesFromRestriction; import com.hp.hpl.jena.ontology.AnnotationProperty; import com.hp.hpl.jena.ontology.CardinalityRestriction; import com.hp.hpl.jena.ontology.ComplementClass; import com.hp.hpl.jena.ontology.ConversionException; import com.hp.hpl.jena.ontology.DatatypeProperty; import com.hp.hpl.jena.ontology.EnumeratedClass; import com.hp.hpl.jena.ontology.HasValueRestriction; import com.hp.hpl.jena.ontology.Individual; import com.hp.hpl.jena.ontology.IntersectionClass; import com.hp.hpl.jena.ontology.MaxCardinalityRestriction; import com.hp.hpl.jena.ontology.MinCardinalityRestriction; import com.hp.hpl.jena.ontology.ObjectProperty; import com.hp.hpl.jena.ontology.OntClass; import com.hp.hpl.jena.ontology.OntModel; import com.hp.hpl.jena.ontology.OntModelSpec; import com.hp.hpl.jena.ontology.OntProperty; import com.hp.hpl.jena.ontology.OntResource; import com.hp.hpl.jena.ontology.Ontology; import com.hp.hpl.jena.ontology.Restriction; import com.hp.hpl.jena.ontology.SomeValuesFromRestriction; import com.hp.hpl.jena.ontology.UnionClass; import com.hp.hpl.jena.query.QueryExecution; import com.hp.hpl.jena.query.QueryExecutionFactory; import com.hp.hpl.jena.query.QueryFactory; import com.hp.hpl.jena.query.QuerySolution; import com.hp.hpl.jena.query.ResultSet; import com.hp.hpl.jena.query.Syntax; import com.hp.hpl.jena.rdf.model.Literal; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.rdf.model.NodeIterator; import com.hp.hpl.jena.rdf.model.Property; import com.hp.hpl.jena.rdf.model.RDFList; import com.hp.hpl.jena.rdf.model.RDFNode; import com.hp.hpl.jena.rdf.model.ResIterator; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.rdf.model.ResourceFactory; import com.hp.hpl.jena.rdf.model.Statement; import com.hp.hpl.jena.rdf.model.StmtIterator; import com.hp.hpl.jena.util.iterator.ExtendedIterator; import com.hp.hpl.jena.vocabulary.OWL; import com.hp.hpl.jena.vocabulary.OWL2; import com.hp.hpl.jena.vocabulary.RDF; import com.hp.hpl.jena.vocabulary.RDFS; import com.hp.hpl.jena.vocabulary.XSD; /** * This class converts an OWL file to a SADL file. * * @author 200005201 * */ public class OwlToSadl { private static final Logger logger = LoggerFactory.getLogger(OwlToSadl.class); private OntModel theModel = null; private OntModel theBaseModel = null; private List<String> imports = null; private Map<String,String> qNamePrefixes = new HashMap<String,String>(); private StringBuilder sadlModel = null; private List<String> allTokens = null; private List<OntResource> resourcesOutput = new ArrayList<OntResource>(); private HashMap<String, OntResource> restrictions = null; private boolean neverUsePrefixes = false; // replaced with getSadlKeywords to get straight from grammar // // copied from com.ge.research.sadl.parser.antlr.internal.InternalSadlParser in com.ge.research.sadl project. // public static final String[] tokenNames = new String[] { // "<invalid>", "<EOR>", "<DOWN>", "<UP>", "RULE_STRING", "RULE_EOS", "RULE_ID", "RULE_UNSIGNED_NUMBER", "RULE_INT", "RULE_ML_COMMENT", "RULE_SL_COMMENT", "RULE_WS", "RULE_ANY_OTHER", "'uri'", "'alias'", "'version'", "'import'", "'as'", "'('", "'note'", "')'", "'{'", "','", "'}'", "'or'", "'and'", "'is'", "'a'", "'top-level'", "'class'", "'are'", "'classes'", "'type'", "'of'", "'types'", "'must'", "'be'", "'one'", "'described'", "'by'", "'has'", "'with'", "'single'", "'value'", "'values'", "'A'", "'An'", "'an'", "'The'", "'the'", "'same'", "'disjoint'", "'not'", "'only'", "'can'", "'level'", "'default'", "'at'", "'least'", "'each'", "'always'", "'most'", "'exactly'", "'if'", "'relationship'", "'to'", "'annotation'", "'describes'", "'subject'", "'symmetrical'", "'transitive'", "'inverse'", "'any'", "'Rule'", "':'", "'given'", "'then'", "'Ask:'", "'Test:'", "'Expr:'", "'Print:'", "'Deductions'", "'Model'", "'Explain:'", "'select'", "'distinct'", "'*'", "'where'", "'order by'", "'asc'", "'desc'", "'||'", "'&&'", "'='", "'=='", "'!='", "'<'", "'<='", "'>'", "'>='", "'+'", "'-'", "'/'", "'^'", "'%'", "'!'", "'PI'", "'known'", "'['", "']'", "'true'", "'false'", "'.'", "'~'", "'string'", "'boolean'", "'decimal'", "'int'", "'long'", "'float'", "'double'", "'duration'", "'dateTime'", "'time'", "'date'", "'gYearMonth'", "'gYear'", "'gMonthDay'", "'gDay'", "'gMonth'", "'hexBinary'", "'base64Binary'", "'anyURI'", "'data'" private String baseUri; private String prefix; private String sourceFile = null; private OntModelSpec spec; private List<String> propertiesProcessed = new ArrayList<String>(); // properties already completely processed private List<Statement> statementsProcessed = new ArrayList<Statement>(); private boolean verboseMode = false; private StringBuilder verboseModeStringBuilder = null; public class ModelConcepts { private List<Ontology> ontologies = new ArrayList<Ontology>(); private List<OntClass> classes = new ArrayList<OntClass>(); private List<OntClass> anonClasses = new ArrayList<OntClass>(); private List<ObjectProperty> objProperties = new ArrayList<ObjectProperty>(); private List<DatatypeProperty> dtProperties = new ArrayList<DatatypeProperty>(); private List<Property> rdfProperties = new ArrayList<Property>(); private List<Resource> pseudoObjProperties = new ArrayList<Resource>(); private List<Resource> pseudoDtProperties = new ArrayList<Resource>(); private List<AnnotationProperty> annProperties = new ArrayList<AnnotationProperty>(); private List<Individual> instances = new ArrayList<Individual>(); private List<Statement> statements = new ArrayList<Statement>(); private List<Restriction> unMappedRestrictions = new ArrayList<Restriction>(); private Map<OntClass, List<Restriction>> mappedRestrictions = new HashMap<OntClass, List<Restriction>>(); private List<Resource> completed = new ArrayList<Resource>(); private List<OntResource> datatypes = new ArrayList<OntResource>(); private List<String> errorMessages = new ArrayList<String>(); private List<String> warningMessages = new ArrayList<String>(); private List<String> infoMessages = new ArrayList<String>(); protected void sort() { sortOntResources(ontologies); sortOntResources(classes); sortOntResources(objProperties); sortOntResources(dtProperties); sortOntResources(annProperties); sortOntResources(instances); } protected void sortOntResources(List rlist) { java.util.Collections.sort(rlist, new Comparator<OntResource>(){ public int compare(OntResource r1,OntResource r2){ if (!r1.isURIResource() || !r2.isURIResource()) { return 0; } else if (r1.getURI().equals(r2.getURI())) { return 0; } else { return (r1.getURI().compareTo(r2.getURI())); } }}); } protected List<OntClass> getClasses() { return classes; } protected boolean addClass(OntClass cls) { if (!classes.contains(cls)) { classes.add(cls); return true; } return false; } protected List<ObjectProperty> getObjProperties() { return objProperties; } protected boolean addObjProperty(ObjectProperty objProperty) { if (!objProperties.contains(objProperty)) { objProperties.add(objProperty); return true; } return false; } protected List<DatatypeProperty> getDtProperties() { return dtProperties; } protected boolean addDtProperty(DatatypeProperty dtProperty) { if (!dtProperties.contains(dtProperty)) { dtProperties.add(dtProperty); return true; } return false; } protected List<Individual> getInstances() { return instances; } protected boolean addInstance(Individual instance) { if (!getInstances().contains(instance)) { getInstances().add(instance); return true; } return false; } protected List<Statement> getStatements() { return statements; } protected void setStatements(List<Statement> statements) { this.statements = statements; } protected List<Ontology> getOntologies() { return ontologies; } protected boolean addOntology(Ontology ontology) { if (!ontologies.contains(ontology)) { ontologies.add(ontology); return true; } return false; } protected List<AnnotationProperty> getAnnProperties() { return annProperties; } protected boolean addAnnProperty(AnnotationProperty annProperty) { if (!annProperties.contains(annProperty)) { annProperties.add(annProperty); return true; } return false; } protected List<Restriction> getUnMappedRestrictions() { return unMappedRestrictions; } protected void addUnMappedRestriction(Restriction unMappedRestriction) { if (!unMappedRestrictions.contains(unMappedRestriction)) { unMappedRestrictions.add(unMappedRestriction); logger.debug("Unmapped restriction information:"); StmtIterator sitr = unMappedRestriction.listProperties(); while (sitr.hasNext()) { logger.debug(" " + sitr.nextStatement().toString()); } OntClass equiv = unMappedRestriction.getEquivalentClass(); if (equiv != null) { logger.debug(" equivalent class:" + equiv.toString()); } } } protected Map<OntClass, List<Restriction>> getMappedRestrictions() { return mappedRestrictions; } protected void addMappedRestriction(OntClass cls, Restriction restriction) { if (mappedRestrictions.containsKey(cls)) { List<Restriction> restList = mappedRestrictions.get(cls); if (!restList.contains(restriction)) { restList.add(restriction); } } else { List<Restriction> restList = new ArrayList<Restriction>(); restList.add(restriction); this.mappedRestrictions.put(cls, restList); } } protected List<Resource> getCompleted() { return completed; } protected void addCompleted(Resource complete) { if (!completed.contains(complete)) { completed.add(complete); } } protected List<OntResource> getDatatypes() { return datatypes; } protected void addDatatype(OntResource datatype) { if (!datatypes.contains(datatype)) { datatypes.add(datatype); } } protected List<Resource> getPseudoObjProperties() { return pseudoObjProperties; } protected void addPseudoObjProperty(Resource pseudoObjProperty) { if (!pseudoObjProperties.contains(pseudoObjProperty)) { pseudoObjProperties.add(pseudoObjProperty); } } protected List<Resource> getPseudoDtProperties() { return pseudoDtProperties; } protected void addPseudoDtProperty(Resource pseudoDtProperty) { if (!pseudoDtProperties.contains(pseudoDtProperty)) { pseudoDtProperties.add(pseudoDtProperty); } } protected List<Property> getRdfProperties() { return rdfProperties; } protected void addRdfProperty(Property rdfProperty) { if (!rdfProperties.contains(rdfProperty)) { rdfProperties.add(rdfProperty); } } protected List<String> getErrorMessages() { return errorMessages; } protected void addErrorMessage(String errorMessage) { if (!errorMessages.contains(errorMessage)) { errorMessages.add(errorMessage); } } protected List<String> getWarningMessages() { return warningMessages; } protected void addWarningMessage(String warningMessage) { if (!warningMessages.contains(warningMessage)) { warningMessages.add(warningMessage); } } protected List<String> getInfoMessages() { return infoMessages; } protected void addInfoMessage(String infoMessage) { if (!infoMessages.contains(infoMessage)) { infoMessages.add(infoMessage); } } private List<OntClass> getAnonClasses() { return anonClasses; } private void addAnonClass(OntClass anonClass) { this.anonClasses.add(anonClass); } } /** * Constructor taking only Jena OntModel to be converted to SADL * * @param model * @throws Exception */ public OwlToSadl(OntModel model) { theModel = model; } /** * Constructor taking only Jena OntModel to be converted to SADL * * @param model * @throws Exception */ public OwlToSadl(OntModel model, String baseUri) { theModel = model; this.setBaseUri(baseUri); } /** * Constructor taking the URL of an OWL file to be converted to SADL. * * @param owlFileUrl * @throws IOException */ public OwlToSadl(URL owlFileUrl) throws IOException { String modelUrl = owlFileUrl.toString(); validateOntologyName(modelUrl); OntModelSpec spec = new OntModelSpec(OntModelSpec.OWL_MEM); setSpec(spec); theModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM); //_RDFS_INF); theModel.getDocumentManager().setProcessImports(false); theModel.read(modelUrl); } public OwlToSadl(URL owlFileUrl, String modelUri) throws IOException { setBaseUri(modelUri); String modelUrl = owlFileUrl.toString(); validateOntologyName(modelUrl); OntModelSpec spec = new OntModelSpec(OntModelSpec.OWL_MEM); setSpec(spec); theModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM); //_RDFS_INF); theModel.getDocumentManager().setProcessImports(false); theModel.read(modelUrl); } /** * Constructor taking an OWL File to be converted to SADL. * * @param owlFile * @throws IOException * @throws OwlImportException */ public OwlToSadl(File owlFile) throws IOException, OwlImportException { if (!owlFile.exists()) { throw new OwlImportException("File '" + owlFile.getCanonicalPath() + "' does not exist."); } if (!owlFile.isFile()) { throw new OwlImportException("File '" + owlFile.getCanonicalPath() + "' is not a file."); } OntModelSpec spec = new OntModelSpec(OntModelSpec.OWL_MEM); setSpec(spec); theModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM); //_RDFS_INF); theModel.getDocumentManager().setProcessImports(false); theModel.read(new FileInputStream(owlFile), getBaseUri()); // theModel.read(owlFile.getCanonicalPath()); } public OwlToSadl(String owlContent) { OntModelSpec spec = new OntModelSpec(OntModelSpec.OWL_MEM); setSpec(spec); theModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM); //_RDFS_INF); theModel.getDocumentManager().setProcessImports(false); theModel.read(new ByteArrayInputStream(owlContent.getBytes()), null); } public OwlToSadl(String owlContent, String modelUri) { setBaseUri(modelUri); OntModelSpec spec = new OntModelSpec(OntModelSpec.OWL_MEM); setSpec(spec); theModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM); //_RDFS_INF); theModel.getDocumentManager().setProcessImports(false); theModel.read(new ByteArrayInputStream(owlContent.getBytes()), null); } // This is a hack public static List<String> getSadlKeywords() { return Arrays.asList("select", "Test:", "construct", "type", "disjoint", "symmetrical", "property", "Stage", "if", "transitive", "order", "element", "!", "using", "in", "%", "double", "byte", "(", ")", "index", "is", "*", "then", "+", ",", "anyURI", "version", "-", "an", ".", "/", "as", "contains", "at", "Graph", "seventh", "unique", "returns", ":", "must", "Rule", "!=", "<", "=", ">", "dateTime", "A", "other", "be", "E", "top-level", "another", "least", "An", "long", "matching", "The", "sixth", "default", "same", "known", "are", "does", "by", "Ask", "where", "[", "after", "relationship", "]", "table", "^", "annotation", "a", "contain", "e", "one", "uri", "gMonth", "...", "describes", "the", "single", "asc", "sublist", "ask", "Model", "located", "fifth", "exists", "{", "to", "fourth", "}", "None", "return", "first", "||", "date", "<=", "data", "before", "subject", "anySimpleType", "integer", "Update", "float", "second", "gYear", "negativeInteger", "only", "Explain:", "unsignedByte", "List", "from", "gDay", "has", "described", " "always", "==", "=>", "given", "last", "level", "count", "most", "base64Binary", "Print:", "Write:", "External", "true", "decimal", "desc", ">=", "&&", "note", "some", "Expr:", "tenth", "import", "string", "instances", "classes", "values", "for", "insert", "distinct", "nonNegativeInteger", "delete", "duration", "can", "not", "and", "hexBinary", "of", "alias", "class", "value", "gMonthDay", "inverse", "types", "or", "length", "false", "eighth", "Equation", "exactly", "any", "int", "nonPositiveInteger", "with", "boolean", "third", "Read:", "there", "positiveInteger", "ninth", "unsignedInt", "PI", "Deductions", "time", "gYearMonth"); } /** * Save the SADL model to the specified file * * @param sadlFile -- complete path and name of the SADL file to which the translated model is to be saved * @return * @throws IOException * @throws OwlImportException */ public boolean saveSadlModel(String sadlFile) throws IOException, OwlImportException { if (sadlModel == null) { process(); } boolean writeProtect = true; File aFile = new File(sadlFile); if (aFile.exists() && !aFile.isFile()) { throw new IllegalArgumentException("Should not be a directory: " + aFile); } if (aFile.exists()) { aFile.delete(); } if (!aFile.exists()) { aFile.createNewFile(); } if (!aFile.canWrite()) { throw new IllegalArgumentException("File cannot be written: " + aFile); } //declared here only to make visible to finally clause; generic reference Writer output = null; try { //use buffering //FileWriter always assumes default encoding is OK! output = new BufferedWriter( new FileWriter(aFile) ); output.write( sadlModel.toString() ); } finally { //flush and close both "output" and its underlying FileWriter if (output != null) output.close(); } if (writeProtect) { try { aFile.setReadOnly(); } catch (SecurityException e) { e.printStackTrace(); } } return true; } /** * Get the SADL model resulting from the OWL translation as a DataSource * * @return * @throws OwlImportException * @throws Exception */ public String getSadlModel() throws OwlImportException { if (sadlModel == null) { process(); } if (sadlModel != null) { return sadlModel.toString(); } return null; } public void process() throws OwlImportException { if (theModel == null) { throw new OwlImportException("There is no OWL model to translate!"); } initialize(); if (sadlModel == null) { sadlModel = new StringBuilder(); } sadlModel.append("uri \""); sadlModel.append(getBaseUri()); sadlModel.append("\""); String alias = null; if (alias == null) { if (qNamePrefixes.containsKey(getBaseUri() + " alias = qNamePrefixes.get(getBaseUri() + " } } if (alias != null && alias.length() > 0) { sadlModel.append(" alias "); sadlModel.append(alias); } Ontology ont = theModel.getOntology(getBaseUri());; String version; if (ont != null && (version = ont.getVersionInfo()) != null) { sadlModel.append("\n version \""); sadlModel.append(version); sadlModel.append("\""); } StmtIterator sitr = theModel.listStatements(ont, RDFS.label, (RDFNode)null); if (sitr.hasNext()) { int cnt = 0; sadlModel.append("\n (alias "); while (sitr.hasNext()) { Statement s = sitr.nextStatement(); RDFNode obj = s.getObject(); String label = obj.isLiteral() ? ((Literal)obj).getString() : obj.toString(); if (cnt++ > 0) { sadlModel.append(", "); } sadlModel.append("\""); sadlModel.append(label); sadlModel.append("\""); } sadlModel.append(")"); } sitr = theModel.listStatements(ont, RDFS.comment, (RDFNode)null); if (sitr.hasNext()) { int cnt = 0; sadlModel.append("\n (note "); while (sitr.hasNext()) { Statement s = sitr.nextStatement(); RDFNode obj = s.getObject(); String comment = obj.isLiteral() ? ((Literal)obj).getString() : obj.toString(); if (cnt++ > 0) { sadlModel.append(", "); } sadlModel.append("\""); sadlModel.append(comment); sadlModel.append("\""); } sadlModel.append(")"); } if (sourceFile != null) { sadlModel.append("\n (note \""); sadlModel.append("This model was generated from the OWL model in file '"); sadlModel.append(sourceFile); sadlModel.append("'\")"); } addEndOfStatement(sadlModel, 2); if (isVerboseMode()) { ExtendedIterator<RDFNode> citr = ont.listComments(null); while (citr.hasNext()) { RDFNode comment = citr.next(); sadlModel.append("// " + comment.toString()); sadlModel.append(".\n"); } } // 2. imports if (logger.isDebugEnabled()) { OutputStream os = new ByteArrayOutputStream(); theModel.getBaseModel().write(os); logger.debug(os.toString()); } if (ont != null) { Iterator<Statement> impitr = theModel.listStatements(theModel.getResource(getBaseUri()), OWL.imports, (RDFNode)null); while (impitr.hasNext()) { String impuri = impitr.next().getObject().toString(); System.out.println(impuri); } ExtendedIterator<OntResource> iitr = ont.listImports(); int prefixCntr = 0; while (iitr.hasNext()) { OntResource imp = iitr.next(); String impUri; try { impUri = imp.asOntology().getURI(); //getNameSpace(); } catch (Exception e) { impUri = imp.toString(); } if (isImplicitUri(impUri)) { continue; } String prefix = theModel.getNsURIPrefix(impUri); sadlModel.append("import \""); sadlModel.append(impUri); sadlModel.append("\""); if (prefix == null) { prefix = theModel.getNsURIPrefix(impUri+" prefix = sadlizePrefix(prefix); } if (prefix != null && prefix.length() > 0) { sadlModel.append(" as "); sadlModel.append(prefix); theModel.setNsPrefix(prefix, impUri + " } sadlModel.append(".\n"); if (imports == null) { imports = new ArrayList<String>(); } imports.add(impUri); } } // // 3. classes with their properties // sadlModel.append("\n// Classes and class restrictions\n"); // List<OntClass> classes = namedClassesAlphabeticalOrder(); // addClasses(classes, null); // ExtendedIterator<ComplementClass> citr = theModel.listComplementClasses(); // if (citr.hasNext()) { // ComplementClass ccls = citr.next(); // OntClass comp = ccls.getOperand(); // if (!ccls.isAnon()) { // sadlModel.append(resourceToString(ccls, false)); // sadlModel.append(" is the same as not "); // sadlModel.append(resourceToString(comp, false)); // else { // sadlModel.append("not " ); // sadlModel.append(resourceToString(comp, false)); // sadlModel.append(".\n"); // // 4. pick up any properties not already covered // sadlModel.append("\n// Properties\n"); // List<OntProperty> properties = namedPropertiesAlphabeticalOrder(true); // addProperties(properties, true); // // 6. Any restrictions not already output (shouldn't be any?) // if (restrictions != null && restrictions.size() > 0) { // sadlModel.append("\n// Additional restrictions\n"); // Iterator<String> itr = restrictions.keySet().iterator(); // while (itr.hasNext()) { // String key = itr.next(); // if (restrictions.get(key) != null) { // sadlModel.append(key); // restrictions.clear(); // // 5. finally add instance declarations // sadlModel.append("\n// Instance declarations\n"); // List<Individual> individuals = individualsAlphabeticalOrder(); // addIndividuals(individuals); // TODO /* * change this approach: * 1. get the base model (theModel.getBaseModel()) * 2. get all statements of the model * 3. if the subject is a resource in this namespace, make sure it is output * 4. if the predicate is a resource in this namespace, do likewise * 5. if the object is a resource in this namespace, do likewise * 6. output the statements that remain (how do we know what remains?) */ List<Statement> statements = new ArrayList<Statement>(); StmtIterator siter = theModel.getBaseModel().listStatements(); while (siter.hasNext()) { Statement s = siter.nextStatement(); statements.add(s); logger.debug("Processing model statement: " + s.toString()); if (isVerboseMode()) { verboseModeStringBuilder.append("// Processed statement: "); verboseModeStringBuilder.append(s.toString()); verboseModeStringBuilder.append("\n"); } Resource subj = s.getSubject(); OntResource ontSubj = theModel.getOntResource(subj); if (shouldResourceBeOutput(ontSubj, false, false, true)) { if (!addResourceToList(getConcepts(), ontSubj)) { logger.debug("subject resource not added to a list: " + ontSubj.toString()); if (isVerboseMode()) { verboseModeStringBuilder.append("// subject resource not added to processing list: \": "); verboseModeStringBuilder.append(ontSubj.toString()); verboseModeStringBuilder.append("\n"); } } } Property prop = s.getPredicate(); Property mprop = theModel.getProperty(prop.getURI()); if (mprop.canAs(OntProperty.class)) { OntProperty ontProp = mprop.as(OntProperty.class); if (shouldResourceBeOutput(ontProp, false, false, true)) { if(!addResourceToList(getConcepts(), ontProp)) { logger.debug("predicate resource not added to a list: " + ontProp.toString()); if (isVerboseMode()) { verboseModeStringBuilder.append("// predicate resource not added to processing list: \": "); verboseModeStringBuilder.append(ontProp.toString()); verboseModeStringBuilder.append("\n"); } } } } else { if (shouldResourceBeOutput(mprop, false, false, true)) { getConcepts().addRdfProperty(mprop); } } RDFNode obj = s.getObject(); if (obj.isResource()) { OntResource ontObj = theModel.getOntResource(obj.asResource()); if (shouldResourceBeOutput(ontObj, false, false, true)) { if(!addResourceToList(getConcepts(), ontObj)) { logger.debug("object resource not added to a list: " + ontObj.toString()); if (isVerboseMode()) { verboseModeStringBuilder.append("// object resource not added to processing list: \": "); verboseModeStringBuilder.append(ontObj.toString()); verboseModeStringBuilder.append("\n"); } } } } else { // this is a literal, object of a Datatype property } /* Is this statement only in the base model? * */ if (theModel.getBaseModel().contains(s)) { getConcepts().getStatements().add(s); } } // Output messages as SADL comments if (getConcepts().getErrorMessages() != null && getConcepts().getErrorMessages().size() > 0) { sadlModel.append("\n\n// Errors:\n"); Iterator<String> erritr = getConcepts().getErrorMessages().iterator(); while (erritr.hasNext()) { sadlModel.append(" sadlModel.append(erritr.next()); sadlModel.append("\n"); } } else if (isVerboseMode()) { sadlModel.append("\n\n// No Errors\n"); } if (getConcepts().getWarningMessages() != null && getConcepts().getWarningMessages().size() > 0) { sadlModel.append("\n\n// Warnings:\n"); Iterator<String> erritr = getConcepts().getWarningMessages().iterator(); while (erritr.hasNext()) { sadlModel.append(" sadlModel.append(erritr.next()); sadlModel.append("\n"); } } else if (isVerboseMode()) { sadlModel.append("\n\n// No Warnings\n"); } if (getConcepts().getInfoMessages() != null && getConcepts().getInfoMessages().size() > 0) { sadlModel.append("\n\n// Info:\n"); Iterator<String> erritr = getConcepts().getInfoMessages().iterator(); while (erritr.hasNext()) { sadlModel.append(" sadlModel.append(erritr.next()); sadlModel.append("\n"); } } else if (isVerboseMode()) { sadlModel.append("\n\n// No Info output\n"); } // sort before starting to generate output getConcepts().sort(); if (isVerboseMode()) { sadlModel.append("\n\n// Ontologies:\n"); List<Ontology> onts = getConcepts().getOntologies(); for (int i = 0; i < onts.size(); i++) { Ontology onti = onts.get(i); sadlModel.append(" sadlModel.append(onti.toString()); sadlModel.append("\n"); } } if (isVerboseMode() || !getConcepts().getDatatypes().isEmpty()) { sadlModel.append("\n\n// Datatype Declarations:\n"); List<OntResource> datatypes = getConcepts().getDatatypes(); for (int i = 0; i < datatypes.size(); i++) { sadlModel.append(datatypeToSadl(getConcepts(), datatypes.get(i))); } } if (isVerboseMode() || !getConcepts().getAnnProperties().isEmpty()) { sadlModel.append("\n\n// Annotation Properties:\n"); List<AnnotationProperty> anns = getConcepts().getAnnProperties(); for (int i = 0; i < anns.size(); i++) { AnnotationProperty ann = anns.get(i); if (!getConcepts().getCompleted().contains(ann)) { sadlModel.append(annotationsToSadl(getConcepts(), ann)); getConcepts().addCompleted(ann); } } } if (isVerboseMode() || !getConcepts().getRdfProperties().isEmpty()) { sadlModel.append("\n\n// RDF Properties:\n"); List<Property> rdfProperties = getConcepts().getRdfProperties(); for (int i = 0; i < rdfProperties.size(); i++) { Property prop = rdfProperties.get(i); addRdfProperty(getConcepts(), sadlModel, prop); getConcepts().addCompleted(prop); } } List<ObjectProperty> objProperties = getConcepts().getObjProperties(); if (isVerboseMode() || !objProperties.isEmpty()) { StringBuilder tempSb = new StringBuilder(); for (int i = 0; i < objProperties.size(); i++) { OntResource prop = objProperties.get(i); addSuperPropertiesWithoutRange(getConcepts(), tempSb, prop); getConcepts().addCompleted(prop); } if (isVerboseMode() || tempSb.length() > 0) { sadlModel.append("\n\n// Object properties without specified range:\n"); sadlModel.append(tempSb); } } List<DatatypeProperty> dtProperties = getConcepts().getDtProperties(); if (isVerboseMode() || !dtProperties.isEmpty()) { StringBuilder tempSb = new StringBuilder(); for (int i = 0; i < dtProperties.size(); i++) { OntResource prop = dtProperties.get(i); addSuperPropertiesWithoutRange(getConcepts(), tempSb, prop); } if (isVerboseMode() || tempSb.length() > 0) { sadlModel.append("\n\n// Datatype properties without specified range:\n"); sadlModel.append(tempSb); } } if (isVerboseMode() || !getConcepts().getClasses().isEmpty()) { sadlModel.append("\n\n// Class definitions:\n"); List<OntClass> classes = getConcepts().getClasses(); for (int i = 0; i < classes.size(); i++) { OntClass cls = classes.get(i); sadlModel.append(classToSadl(getConcepts(), cls)); } } if (isVerboseMode() || objProperties.size() > 0) { StringBuilder tempSb = new StringBuilder(); objProperties = getConcepts().getObjProperties(); for (int i = 0; i < objProperties.size(); i++) { OntResource prop = objProperties.get(i); if (!getConcepts().getCompleted().contains(prop)) { tempSb.append(objPropertyToSadl(getConcepts(), prop)); } } if (isVerboseMode() || tempSb.length() > 0) { sadlModel.append("\n\n// Other object Properties:\n"); sadlModel.append(tempSb); } } if (isVerboseMode() || dtProperties.size() > 0) { StringBuilder tempSb = new StringBuilder(); dtProperties = getConcepts().getDtProperties(); for (int i = 0; i < dtProperties.size(); i++) { OntResource prop = dtProperties.get(i); if (!getConcepts().getCompleted().contains(prop)) { if (!ignoreNamespace(prop, true)) { tempSb.append(dtPropertyToSadl(getConcepts(), prop)); } } } if (isVerboseMode() || tempSb.length() > 0) { sadlModel.append("\n\n// Other datatype Properties:\n"); sadlModel.append(tempSb); } } if (isVerboseMode() || !getConcepts().getInstances().isEmpty()) { sadlModel.append("\n\n// Individuals:\n"); List<Individual> instances = getConcepts().getInstances(); for (int i = 0; i < instances.size(); i++) { Individual inst = instances.get(i); sadlModel.append(individualToSadl(getConcepts(), inst, false)); } } if (isVerboseMode() || !getConcepts().getUnMappedRestrictions().isEmpty()) { sadlModel.append("\n\n// Other restrictions:\n"); List<Restriction> ress = getConcepts().getUnMappedRestrictions(); for (int i = 0; i < ress.size(); i++) { Restriction res = ress.get(i); boolean invalid = false; // what is a subclasses of this restriction? StmtIterator oitr = theModel.listStatements(null, RDFS.subClassOf, res); while (oitr.hasNext()) { Statement s1 = oitr.nextStatement(); logger.debug(s1.toString()); Resource subj = s1.getSubject(); if (subj.canAs(Ontology.class) || subj.equals(OWL.Ontology)) { sadlModel.append("// restriction on Ontology not supported in SADL: \n // "); sadlModel.append(restrictionToString(getConcepts(), null, res)); sadlModel.append("\n"); invalid = true; break; } } if (!invalid) { sadlModel.append(restrictionToString(getConcepts(), null, res)); addEndOfStatement(sadlModel, 1); } } } if (isVerboseMode() || !getConcepts().getStatements().isEmpty()) { getConcepts().getStatements().removeAll(statementsProcessed); StringBuilder otherSB = new StringBuilder(); Iterator<Statement> stmtitr = getConcepts().getStatements().iterator(); while (stmtitr.hasNext()) { Statement s = stmtitr.next(); String stmtstr = statementToString(s); if (stmtstr != null) { otherSB.append(stmtstr); statementsProcessed.add(s); } } getConcepts().getStatements().removeAll(statementsProcessed); stmtitr = getConcepts().getStatements().iterator(); while (stmtitr.hasNext()) { Statement s = stmtitr.next(); Iterator<Statement> pitr = statementsProcessed.iterator(); boolean alreadyDone = false; while (pitr.hasNext()) { if (pitr.next().getObject().equals(s.getSubject())) { alreadyDone = true; break; } }if (!alreadyDone) { String stmtstr = blankNodeSubjectStatementToString(s); if (stmtstr != null) { otherSB.append(stmtstr); } } } if (otherSB.length() > 0) { sadlModel.append("\n\n// Other statements:\n"); sadlModel.append(otherSB.toString()); } } if (isVerboseMode() && verboseModeStringBuilder.length() > 0) { sadlModel.append("\n\n"); sadlModel.append(verboseModeStringBuilder); } } private void initialize() throws OwlImportException { setConcepts(new ModelConcepts()); theModel.getDocumentManager().setProcessImports(false); Map<String,String> modelPrefixMap = theModel.getNsPrefixMap(); if (modelPrefixMap != null) { Iterator<String> pitr = modelPrefixMap.keySet().iterator(); while (pitr.hasNext()) { String prefix = pitr.next(); String uri = modelPrefixMap.get(prefix); if (getBaseUri() != null && stripNamespaceDelimiter(uri).equals(stripNamespaceDelimiter(getBaseUri()))) { setPrefix(prefix); } qNamePrefixes.put(uri, prefix); } } if (logger.isDebugEnabled()) { OutputStream os = new ByteArrayOutputStream(); theModel.getBaseModel().write(os); logger.debug(os.toString()); } getSpec().getDocumentManager().setProcessImports(false); theBaseModel = ModelFactory.createOntologyModel(getSpec(), theModel); if (allTokens == null) { allTokens = getSadlKeywords(); } if (getBaseUri() == null) { String uri = modelPrefixMap.get(""); if (uri != null) { setBaseUri(uri); } else { try { Writer writer = new StringWriter(); theModel.write(writer, "RDF/XML"); Optional<String> xmlbaseuri = new XMLHelper().tryReadBaseUri(writer.toString()); if (xmlbaseuri.isPresent()) { uri = xmlbaseuri.get(); } } catch (Exception e) { throw new OwlImportException(e.getMessage(), e); } if (uri == null) { throw new OwlImportException("Namespace of model to import cannot be identified"); } } } if (getBaseUri() == null) { ExtendedIterator<Ontology> eitr = theModel.listOntologies(); while (eitr.hasNext()) { Ontology ont = eitr.next(); setBaseUri(ont.getURI()); break; // will this model's ontology always be first? } } if (getBaseUri() == null) { Map<String, String> map = theModel.getNsPrefixMap(); Iterator<String> mitr = map.keySet().iterator(); while (mitr.hasNext()) { String prefix = mitr.next(); logger.debug("Mapping: " + prefix + " = " + map.get(prefix)); } setBaseUri("http://sadl.org/baseless"); } if (getBaseUri().endsWith(" setBaseUri(getBaseUri().substring(0, getBaseUri().length() - 1)); } } public static final String SADL_BASE_MODEL_URI = "http://sadl.org/sadlbasemodel"; public static final String SADL_LIST_MODEL_URI = "http://sadl.org/sadllistmodel"; public static final String SADL_IMPLICIT_MODEL_URI = "http://sadl.org/sadlimplicitmodel"; public static final String SADL_BUILTIN_FUNCTIONS_URI = "http://sadl.org/builtinfunctions"; private ModelConcepts concepts; private String stripNamespaceDelimiter(String ns) { if (ns.endsWith(" ns = ns.substring(0, ns.length() - 1); } return ns; } private boolean isImplicitUri(String impUri) { if (impUri.equals(SADL_BASE_MODEL_URI)) { return true; } else if (impUri.equals(SADL_BUILTIN_FUNCTIONS_URI)) { return true; } else if (impUri.equals(SADL_IMPLICIT_MODEL_URI)) { return true; } else if (impUri.equals(SADL_LIST_MODEL_URI)) { return true; } return false; } private void addEndOfStatement(StringBuilder sb, int numLineFeeds) { if (sb.length() > 1 && Character.isDigit(sb.charAt(sb.length() - 1))) { sb.append(" ."); } else { sb.append("."); } for (int i = 0; i < numLineFeeds; i++) { sb.append("\n"); } } private void addRdfProperty(ModelConcepts concepts, StringBuilder sb, Property prop) { sb.append(rdfPropertyToSadl(concepts, prop)); } private void addSuperPropertiesWithoutRange(ModelConcepts concepts, StringBuilder sb, OntResource prop) { if (!hasRange(prop)) { String thisPropString; if (prop.isObjectProperty() || concepts.getPseudoObjProperties().contains(prop)) { thisPropString = objPropertyToSadl(concepts, prop); } else { thisPropString = dtPropertyToSadl(concepts, prop); } if (concepts.getPseudoObjProperties().contains(prop)) { sb.append(" sb.append(prop.getLocalName()); sb.append(" is not typed in the input but SADL requires typed properties\n// --typed as object property to match subproperties\n"); } else if (concepts.getPseudoDtProperties().contains(prop)) { sb.append(" sb.append(prop.getLocalName()); sb.append(" is not typed in the input but SADL requires typed properties\n// --typed as datatype property to match subproperties\n"); } concepts.addCompleted(prop); NodeIterator nitr2 = prop.listPropertyValues(RDFS.subPropertyOf); if (nitr2.hasNext()) { RDFNode superprop = nitr2.nextNode(); if (superprop.canAs(OntProperty.class)){ OntProperty supProp = superprop.as(OntProperty.class); addSuperPropertiesWithoutRange(concepts, sb, supProp); } } sb.append(thisPropString); } } private boolean hasRange(OntResource prop) { NodeIterator nitr = prop.listPropertyValues(RDFS.range); if (!nitr.hasNext()) { return false; } else { RDFNode rng = nitr.nextNode(); if (rng.equals(RDFS.Resource)) { // rdfs:Resource is treated (for now?) as not a range as it adds no information and creates a SADL error. return false; } } return true; } private boolean isRDFDatatypeString(String dturi, RDFNode value) { if (dturi.startsWith(XSD.getURI())) { // this is a direct type if (dturi.equals(XSD.xstring.getURI()) || dturi.equals(XSD.date.getURI()) || dturi.equals(XSD.dateTime.getURI()) || dturi.equals(XSD.time.getURI()) || dturi.equals(XSD.anyURI.getURI())) { return true; } else { return false; } } Resource rsrc = theModel.getResource(dturi); // is there an equivalent class? List<String> intersection = null; List<String> union = null; String xsdtype = null; RDFNode eqCls = null; StmtIterator eqitr = rsrc.listProperties(OWL.equivalentClass); if (eqitr.hasNext()) { eqCls = eqitr.nextStatement().getObject(); if (eqCls.canAs(Resource.class)) { if (eqCls.canAs(UnionClass.class)) { union = new ArrayList<String>(); RDFList opList = eqCls.as(UnionClass.class).getOperands(); for (int i = 0; i < opList.size(); i++) { RDFNode opnode = opList.get(i); union.add(opnode.asResource().getLocalName()); } } else if (eqCls.canAs(IntersectionClass.class)) { intersection = new ArrayList<String>(); RDFList opList = eqCls.as(IntersectionClass.class).getOperands(); for (int i = 0; i < opList.size(); i++) { RDFNode opnode = opList.get(i); intersection.add(opnode.asResource().getLocalName()); } } else { RDFNode odt = eqCls.as(OntResource.class).getPropertyValue(OWL2.onDatatype); if (odt != null && odt.canAs(Resource.class)) { String ns = odt.as(Resource.class).getNameSpace(); if (ns.startsWith(XSD.getURI())) { xsdtype = odt.as(Resource.class).getLocalName(); } } } } } else { System.err.println("Unable to determine if RDFDatatype '" + dturi + " has string value."); } if (xsdtype != null && xsdtype.equals(XSD.xstring.getLocalName())) { return true; } if (union != null) { if (union.contains(XSD.xstring.getLocalName())) { if (value.asLiteral().getValue() instanceof Number) { return false; } return true; } } return false; } public String datatypeToSadl(String rsrcUri) throws OwlImportException { OntResource rsrc = theModel.getOntResource(rsrcUri); if (rsrc != null) { return datatypeToSadl(getConcepts(), rsrc).toString(); } return null; } private Object datatypeToSadl(ModelConcepts concepts, OntResource rsrc) { StringBuilder sb = new StringBuilder(); if (rsrc.isURIResource()) { // is there an equivalent class? List<String> intersection = null; List<String> union = null; String xsdtype = null; RDFNode eqCls = null; StmtIterator eqitr = rsrc.listProperties(OWL.equivalentClass); if (eqitr.hasNext()) { eqCls = eqitr.nextStatement().getObject(); if (eqCls.canAs(Resource.class)) { if (eqCls.canAs(UnionClass.class)) { union = new ArrayList<String>(); RDFList opList = eqCls.as(UnionClass.class).getOperands(); for (int i = 0; i < opList.size(); i++) { RDFNode opnode = opList.get(i); union.add(opnode.asResource().getLocalName()); } } else if (eqCls.canAs(IntersectionClass.class)) { intersection = new ArrayList<String>(); RDFList opList = eqCls.as(IntersectionClass.class).getOperands(); for (int i = 0; i < opList.size(); i++) { RDFNode opnode = opList.get(i); intersection.add(opnode.asResource().getLocalName()); } } else { RDFNode odt = eqCls.as(OntResource.class).getPropertyValue(OWL2.onDatatype); if (odt != null && odt.canAs(Resource.class)) { String ns = odt.as(Resource.class).getNameSpace(); if (ns.startsWith(XSD.getURI())) { xsdtype = odt.as(Resource.class).getLocalName(); } } } } } if (eqCls == null) { sb.append("// Error: RDFDatatype '" + uriToSadlString(concepts, rsrc) + "' does not have an equivalent class.\n"); } else if ((union == null || union.size() == 0) && (intersection == null || intersection.size() == 0) && xsdtype == null) { sb.append("// Error: RDFDatatype '" + uriToSadlString(concepts, rsrc) + "' does not have a union, intersection, nor xsd datatype.\n"); } else { sb.append(uriToSadlString(concepts, rsrc)); addNotesAndAliases(sb, rsrc); sb.append(" is a type of "); if (union != null && union.size() > 0) { sb.append("{"); for (int i = 0; i < union.size(); i++) { if (i > 0) { sb.append(" or "); } sb.append(union.get(i)); } sb.append("}"); } else if (intersection != null && intersection.size() > 0) { sb.append("{"); for (int i = 0; i < union.size(); i++) { if (i > 0) { sb.append(" and "); } sb.append(union.get(i)); } sb.append("}"); } else if (xsdtype != null) { String facets = rdfDatatypeFacetsToSadl(eqCls); if (facets == null) { sb.append("// Error: RDFDatatype '" + uriToSadlString(concepts, rsrc) + "' is of type '" + xsdtype + "' but has no facets to define it."); } else { sb.append(xsdtype); sb.append(" "); sb.append(facets); } } addEndOfStatement(sb, 1); } } else { sb.append("// anonymous rdfs:Datatype encountered: "); sb.append(rsrc.toString()); sb.append("\n"); } return sb.toString(); } private String rdfDatatypeFacetsToSadl(RDFNode eqCls) { List<String> enums = null; String len = null; String minLen = null; String maxLen = null; String pattern = null; String minIncl = null; String maxIncl = null; String minExcl = null; String maxExcl = null; NodeIterator nitr = eqCls.as(OntResource.class).listPropertyValues(OWL2.withRestrictions); while (nitr.hasNext()) { RDFNode n = nitr.next(); if (n != null && n.canAs(RDFList.class)){ RDFList lst = n.as(RDFList.class); List<Triple> list = rdfListToList(lst.asNode(), null); if (list != null) { Iterator<Triple> titr = list.iterator(); while (titr.hasNext()) { Triple t = titr.next(); if (t.getMatchPredicate().equals(xsdProperty("minLength").asNode())) { minLen = t.getMatchObject().getLiteralValue().toString(); } else if (t.getMatchPredicate().equals(xsdProperty("maxLength").asNode())) { maxLen = t.getMatchObject().getLiteralValue().toString(); } else if (t.getMatchPredicate().equals(xsdProperty("length").asNode())) { len = t.getMatchObject().getLiteralValue().toString(); } else if (t.getMatchPredicate().equals(xsdProperty("pattern").asNode())) { pattern = t.getMatchObject().getLiteralValue().toString(); } else if (t.getMatchPredicate().equals(xsdProperty("enumeration").asNode())) { if (enums == null) { enums = new ArrayList<String>(); } enums.add(t.getMatchObject().getLiteralValue().toString()); } else if (t.getMatchPredicate().equals(xsdProperty("minInclusive").asNode())) { minIncl = t.getMatchObject().getLiteralValue().toString(); } else if (t.getMatchPredicate().equals(xsdProperty("maxInclusive").asNode())) { maxIncl = t.getMatchObject().getLiteralValue().toString(); } else if (t.getMatchPredicate().equals(xsdProperty("minExclusive").asNode())) { minExcl = t.getMatchObject().getLiteralValue().toString(); } else if (t.getMatchPredicate().equals(xsdProperty("maxExclusive").asNode())) { maxExcl = t.getMatchObject().getLiteralValue().toString(); } else if (t.getMatchPredicate().equals(xsdProperty("regex").asNode())) { pattern = t.getMatchObject().getLiteralValue().toString(); } } } } else if (n.canAs(OntResource.class)){ StmtIterator sitr = n.as(OntResource.class).listProperties(); while (sitr.hasNext()) { logger.debug(sitr.nextStatement().toString()); } } } StringBuilder sb = new StringBuilder(); if (minIncl != null || minExcl != null || maxIncl != null || maxExcl != null) { if (minIncl != null) { sb.append("["); sb.append(minIncl); sb.append(","); } else if (minExcl != null) { sb.append("("); sb.append(minExcl); sb.append(","); } else { sb.append("( ,"); } if (maxIncl != null) { sb.append(maxIncl); sb.append("]"); } else if (maxExcl != null) { sb.append(maxExcl); sb.append(")"); } else { sb.append(" )"); } } else if (len != null) { sb.append("length "); sb.append(len); } else if (minLen != null || maxLen != null) { sb.append("length "); if (minLen != null) { sb.append(minLen); } else { sb.append("0"); } sb.append("-"); if (maxLen != null) { sb.append(maxLen); } } else if (pattern != null) { sb.append("pattern"); } return sb.toString(); } private final static Property xsdProperty(String local) { return ResourceFactory.createProperty(XSD.getURI() + local); } private List<Triple> rdfListToList(Node lst, List<Triple> trLst) { ExtendedIterator<Triple> litr = theModel.getGraph().find(lst, RDF.Nodes.first, null); while (litr.hasNext()) { Triple t = litr.next(); logger.debug("Triple with 'first': " + t.toString()); Node mo = t.getMatchObject(); ExtendedIterator<Triple> litr2 = theModel.getGraph().find(mo, null, null); while (litr2.hasNext()) { Triple t2 = litr2.next(); if (t2.getMatchPredicate().equals(RDF.Nodes.rest)) { if (!t2.getMatchObject().equals(RDF.Nodes.nil)) { trLst = rdfListToList(t2.getMatchObject(), trLst); } } else { if (trLst == null) { trLst = new ArrayList<Triple>(); } if (!trLst.contains(t2)) { trLst.add(t2); logger.debug("Adding triple: " + t2.toString()); } } } } return trLst; } private String individualNameAndAnnotations(ModelConcepts concepts, Individual inst) { StringBuilder sb = new StringBuilder(); if (!isNeverUsePrefixes() && !inst.getNameSpace().equals(getBaseUri()+' if (qNamePrefixes.containsKey(inst.getNameSpace())) { String prefix = qNamePrefixes.get(inst.getNameSpace()); sb.append(checkLocalnameForKeyword(inst.getLocalName())); sb.append(" /* Given URI of instance is '"); sb.append(inst.getNameSpace()); sb.append("'"); if (prefix != null) { sb.append("(prefix "); sb.append(prefix); sb.append(")"); } sb.append(" but creating an instance in another namespace is not currently supported in SADL; creating in this namespace */\n"); } else { String ln = inst.getLocalName(); if (ln != null && ln.length() > 0) { sb.append(checkLocalnameForKeyword(inst.getLocalName())); } else if (inst.isURIResource()){ sb.append(inst.getURI()); } else { sb.append(inst.toString()); } } } else { sb.append(uriToSadlString(concepts, inst)); } addNotesAndAliases(sb, inst); return sb.toString(); } private String listToSadl(ModelConcepts concepts, Individual inst, boolean embeddedBNode) { Individual rest = inst; StringBuilder sb = new StringBuilder("["); int cntr = 0; while (rest != null) { RDFNode first = rest.getProperty(RDF.first).getObject(); if (cntr++ > 0) sb.append(","); sb.append(rdfNodeToSadlString(concepts, first, true)); Statement rststmt = rest.getProperty(RDF.rest); if (rststmt != null) { RDFNode rstobj = rststmt.getObject(); if (rstobj != null && !rstobj.equals(RDF.nil) && rstobj.canAs(Individual.class)) { rest = rstobj.as(Individual.class); } else { rest = null; } } } sb.append("]"); return sb.toString(); } public String individualToSadl(String instUri, boolean embeddedBNode) throws OwlImportException { Individual inst = theModel.getIndividual(instUri); if (inst != null) { return individualToSadl(getConcepts(), inst, embeddedBNode); } return null; } private String individualToSadl(ModelConcepts concepts, Individual inst, boolean embeddedBNode) { StringBuilder sb = new StringBuilder(); boolean bnode = false; if (inst.isURIResource()) { sb.append(individualNameAndAnnotations(concepts, inst)); if (isNewLineAtEndOfBuffer(sb)) { sb.append(" "); } sb.append(" is a "); } else { sb.append("(a "); bnode = true; } ExtendedIterator<OntClass> eitr = inst.listOntClasses(true); int itercnt = 0; boolean intersectionClass = false; while (eitr.hasNext()) { try { OntClass cls = eitr.next(); if (itercnt == 0) { if (eitr.hasNext()) { intersectionClass = true; } if (intersectionClass) { sb.append("{"); } } if (itercnt++ > 0 && eitr.hasNext()) { sb.append(" or "); } sb.append(uriToSadlString(concepts, cls)); } catch (Exception e){ System.err.println(e.getMessage()); } } if (intersectionClass) { sb.append("}"); } addResourceProperties(sb, concepts, inst, embeddedBNode); if (bnode) { sb.append(")"); } else { addEndOfStatement(sb, 1); } return sb.toString(); } private void addResourceProperties(StringBuilder sb, ModelConcepts concepts, Resource inst, boolean embeddedBNode) { StmtIterator insitr = inst.listProperties(); int cntr = 0; while (insitr.hasNext()) { Statement s = insitr.next(); if (s.getPredicate().equals(RDF.type) || s.getPredicate().equals(RDFS.label) || s.getPredicate().equals(RDFS.comment)) { continue; } if (embeddedBNode) { if (cntr > 0) { sb.append(","); } sb.append("\n with "); } else { sb.append(",\n has "); } sb.append(uriToSadlString(concepts, s.getPredicate())); sb.append(" "); sb.append(rdfNodeToSadlString(concepts, s.getObject(), false)); statementsProcessed.add(s); cntr++; } } private String statementToString(Statement s) throws OwlImportException { if (s.getSubject().isAnon()) { return null; // wait and see if this is the object of a statement } if (ignoreNamespace(s.getPredicate(), false)) { return null; } StringBuilder sb = new StringBuilder(); Resource subj = s.getSubject(); if (subj.canAs(Individual.class)) { sb.append(individualToSadl(getConcepts(), subj.as(Individual.class), false)); } else if (subj.canAs(OntClass.class)){ sb.append(ontClassToString(subj.as(OntClass.class), null)); } else if (subj.isURIResource()) { sb.append(uriToSadlString(getConcepts(), subj)); } sb.append(" has "); sb.append(uriToSadlString(getConcepts(), s.getPredicate())); sb.append(" "); RDFNode obj = s.getObject(); if (obj.isAnon()) { sb.append(blankNodeToString(obj.asResource(), true)); } else { sb.append(rdfNodeToString(obj, 0)); } sb.append(".\n"); return sb.toString(); } private String blankNodeSubjectStatementToString(Statement s) throws OwlImportException { if (ignoreNamespace(s.getPredicate(), false)) { return null; } StringBuilder sb = new StringBuilder(); Resource bnodeSubj = s.getSubject(); sb.append(blankNodeToString(bnodeSubj, false)); sb.append(".\n"); return sb.toString(); } private String blankNodeToString(Resource bnodeSubj, boolean embedded) throws OwlImportException { StringBuilder sb = new StringBuilder(); if (bnodeSubj.canAs(Individual.class)) { return individualToSadl(getConcepts(), bnodeSubj.as(Individual.class), true); } // find type statement StmtIterator stmtitr = theModel.listStatements(bnodeSubj, RDF.type, (RDFNode)null); if (stmtitr.hasNext()) { RDFNode typ = stmtitr.nextStatement().getObject(); if (typ.canAs(OntClass.class)) { if (embedded) { sb.append("("); sb.append("a "); } else { sb.append("A "); } sb.append(ontClassToString(typ.as(OntClass.class), null)); addResourceProperties(sb, getConcepts(), bnodeSubj, true); if (embedded) { sb.append(")"); } } } return sb.toString(); } private String annotationsToSadl(ModelConcepts concepts, AnnotationProperty ann) { StringBuilder sb = new StringBuilder(); sb.append(uriToSadlString(concepts, ann)); addNotesAndAliases(sb, ann); sb.append(" is a type of annotation.\n"); return sb.toString(); } public String rdfPropertyToSadl(String propUri) throws OwlImportException { Property prop = theModel.getProperty(propUri); if (prop != null) { return rdfPropertyToSadl(getConcepts(), prop); } return null; } private String rdfPropertyToSadl(ModelConcepts concepts, Property prop) { StringBuilder sb = new StringBuilder(); sb.append(uriToSadlString(concepts, prop)); sb.append(" is a property.\n"); return sb.toString(); } public String dtPropertyToSadl(String propUri) throws OwlImportException { OntResource or = theModel.getOntResource(propUri); if (or != null) { return dtPropertyToSadl(getConcepts(), or); } return null; } private String dtPropertyToSadl(ModelConcepts concepts, OntResource prop) { StringBuilder sb = new StringBuilder(); boolean useTranslation = true; sb.append(uriToSadlString(concepts, prop)); addNotesAndAliases(sb, prop); if (prop.canAs(DatatypeProperty.class)) { useTranslation = propertyToSadl(sb, concepts, prop); } else { sb.append(" is a property"); } if (!sb.toString().contains("with values")) { sb.append(" with values of type data"); } if (useTranslation) { addEndOfStatement(sb, 1); } else { sb.setLength(0); } return sb.toString(); } public String objPropertyToSadl(String propUri) throws OwlImportException { OntResource prop = theModel.getOntResource(propUri); if (prop != null) { return objPropertyToSadl(getConcepts(), prop); } return null; } private String objPropertyToSadl(ModelConcepts concepts, OntResource prop) { StringBuilder sb = new StringBuilder(); boolean useTranslation = true; sb.append(uriToSadlString(concepts, prop)); addNotesAndAliases(sb, prop); if (prop.canAs(ObjectProperty.class)) { useTranslation = propertyToSadl(sb, concepts, prop); } else { sb.append(" is a property"); } if (useTranslation) { addEndOfStatement(sb, 1); } else { sb.setLength(0); } return sb.toString(); } public String classToSadl(String clsUri) throws OwlImportException { OntClass cls = theModel.getOntClass(clsUri); if (cls != null) { return classToSadl(getConcepts(), cls); } return null; } private String classToSadl(ModelConcepts concepts, OntClass cls) { StringBuilder sb = new StringBuilder(); sb.append(uriToSadlString(concepts, cls)); addNotesAndAliases(sb, cls); List<Resource> supers = new ArrayList<Resource>(); List<OntClass> mappedRestrictions = new ArrayList<OntClass>(); // ExtendedIterator<OntClass> eitr = ((OntClass)cls.as(OntClass.class)).listSuperClasses(true); StmtIterator eitr = theModel.listStatements(cls, RDFS.subClassOf, (RDFNode)null); if (eitr.hasNext()) { while (eitr.hasNext()) { RDFNode spcls = eitr.next().getObject(); if (spcls.canAs(OntClass.class)) { if (concepts.getMappedRestrictions().containsValue(spcls)) { mappedRestrictions.add(spcls.as(OntClass.class)); } else if (spcls.isAnon()) { if (spcls.as(OntClass.class).isRestriction()) { mappedRestrictions.add(spcls.as(OntClass.class)); } else { supers.add(spcls.as(OntClass.class)); } } else if (!spcls.equals(OWL.Thing)) { supers.add(spcls.as(OntClass.class)); } } else { // this must be in an imported model supers.add(spcls.asResource()); } } } if (supers.size() > 0) { sb.append(" is a type of "); if (supers.size() > 1) { sb.append("{"); Iterator<Resource> spIter = supers.iterator(); int itercnt = 0; while (spIter.hasNext()) { if (itercnt++ > 0) { sb.append(" and "); } Resource spcls = spIter.next(); String spStr = uriToSadlString(concepts, spcls); sb.append(spStr); } sb.append("}"); } else { sb.append(uriToSadlString(concepts, supers.get(0))); } } else { sb.append(" is a class"); } OntClass eqcls = cls.getEquivalentClass(); if (eqcls != null) { if (concepts.getAnonClasses().contains(eqcls)) { concepts.getAnonClasses().remove(eqcls); String str = uriToSadlString(concepts, eqcls); sb.append(" must be "); sb.append(str); } } // add properties with this class in the domain List<Property> pList = new ArrayList<Property>(); StmtIterator eitr2 = theModel.listStatements(null, RDFS.domain, cls); while (eitr2.hasNext()) { Property p = eitr2.next().getSubject().as(Property.class); if (p.equals(RDFS.subClassOf) || p.canAs(AnnotationProperty.class)) { // p.isAnnotationProperty()) { continue; } pList.add(p); } // sort p alphabetically pList = sortResources(pList); for (int i = 0; i < pList.size(); i++) { Property p = pList.get(i); String key = null; if (p.isURIResource()) { key = p.getURI(); key += cls.getURI(); } // TODO remove p from list? what if it has other domain classes? sb.append(",\n"); sb.append(" described by "); sb.append(uriToSadlString(concepts, p)); if (!concepts.getCompleted().contains(p)) { addNotesAndAliases(sb, p); } key = generateSadlRangeStatement(concepts, p, sb, key); // ExtendedIterator<? extends OntResource> eitr3 = p.listRange(); // while (eitr3.hasNext()) { // OntResource r = eitr3.next(); // if (!r.equals(RDFS.Resource)) { // sb.append(" with values of type "); // sb.append(uriToSadlString(concepts, r)); propertyAlreadyProcessed(key); // add to properties already processed } addEndOfStatement(sb, 1); if (concepts.getMappedRestrictions().containsKey(cls)) { List<Restriction> restList = concepts.getMappedRestrictions().get(cls); for (int i = 0; restList != null && i < restList.size(); i++) { Restriction res = restList.get(i); try { OntProperty op = res.getOnProperty(); if (!concepts.getCompleted().contains(op)) { if (op.isObjectProperty()) { sb.append(objPropertyToSadl(concepts, op)); } else { sb.append(dtPropertyToSadl(concepts, op)); } concepts.addCompleted(op); } } catch (Throwable t) { concepts.addErrorMessage(t.getMessage()); } sb.append(restrictionToString(concepts, cls, res)); addEndOfStatement(sb, 1); } } return sb.toString(); } private List<Property> sortResources(List<Property> pList) { if (pList.isEmpty()) { return pList; } List<Property> newList = new ArrayList<Property>(); newList.add(pList.get(0)); for (int i = 1; i < pList.size(); i++) { Property nxt = pList.get(i); for (int j = 0; j < newList.size(); j++) { Property nlp = newList.get(j); String s1 = nxt.getURI(); String s2 = nlp.getURI(); if (s1.compareTo(s2) < 0) { newList.add(j, nxt); nxt = null; break; } } if (nxt != null) { newList.add(nxt); } } return newList; } private void addNotesAndAliases(StringBuilder sb, Resource rsrc) { StmtIterator sitr = rsrc.listProperties(RDFS.label); if (sitr.hasNext()) { // addNewLineIfNotAtEndOfBuffer(sb); sb.append(" (alias "); int cntr = 0; while (sitr.hasNext()) { RDFNode alias = sitr.nextStatement().getObject(); if (cntr++ > 0) { sb.append(", "); } sb.append(rdfNodeToSadlString(null, alias, true)); } sb.append(")"); } sitr = rsrc.listProperties(RDFS.comment); if (sitr.hasNext()) { addNewLineIfNotAtEndOfBuffer(sb); sb.append(" (note "); int cntr = 0; while (sitr.hasNext()) { RDFNode note = sitr.nextStatement().getObject(); if (cntr++ > 0) { sb.append(", "); } sb.append(rdfNodeToSadlString(null, note, true)); } sb.append(")\n "); } } private String restrictionToString(ModelConcepts concepts, OntClass restrictedClass, Restriction res) { if (res.isURIResource()) { return uriToSadlString(concepts, res); } StringBuilder sb = new StringBuilder(); OntProperty onprop = null; try { onprop = res.getOnProperty(); } catch (ConversionException e) { onprop = getOnPropertyFromConversionException(e); if (onprop == null) { sb.append("// Error: " + e.getMessage()); return sb.toString(); } } sb.append(uriToSadlString(concepts,onprop)); if (restrictedClass == null) { OntClass supcls = res.getSuperClass(); if (supcls != null) { restrictedClass = supcls; } } if (restrictedClass != null) { sb.append(" of "); sb.append(uriToSadlString(concepts, restrictedClass)); } if (res.isHasValueRestriction()) { sb.append(" always has value "); sb.append(rdfNodeToSadlString(concepts, res.asHasValueRestriction().getHasValue(), false)); } else if (res.isAllValuesFromRestriction()) { sb.append(" only has values of type "); sb.append(uriToSadlString(concepts, res.asAllValuesFromRestriction().getAllValuesFrom())); } else if (res.isSomeValuesFromRestriction()) { sb.append(" has at least one value of type "); sb.append(uriToSadlString(concepts, res.asSomeValuesFromRestriction().getSomeValuesFrom())); } else if (res.isCardinalityRestriction()) { sb.append(" has exactly "); int card = res.asCardinalityRestriction().getCardinality(); sb.append(card); if (card == 1) { sb.append(" value"); } else { sb.append(" values"); } RDFNode onCls = res.getPropertyValue(OWL2.onClass); if (onCls != null) { sb.append(" of type "); sb.append(rdfNodeToSadlString(concepts, onCls, false)); } } else if (res.isMinCardinalityRestriction()) { sb.append(" has at least "); int card = res.asMinCardinalityRestriction().getMinCardinality(); sb.append(card); if (card == 1) { sb.append(" value"); } else { sb.append(" values"); } RDFNode onCls = res.getPropertyValue(OWL2.onClass); if (onCls != null) { sb.append(" of type "); sb.append(rdfNodeToSadlString(concepts, onCls, false)); } } else if (res.isMaxCardinalityRestriction()) { sb.append(" has at most "); int card = res.asMaxCardinalityRestriction().getMaxCardinality(); sb.append(card); if (card == 1) { sb.append(" value"); } else { sb.append(" values"); } RDFNode onCls = res.getPropertyValue(OWL2.onClass); if (onCls != null) { sb.append(" of type "); sb.append(rdfNodeToSadlString(concepts, onCls, false)); } } return sb.toString(); } private OntProperty getOnPropertyFromConversionException(ConversionException e) { String msg = e.getMessage(); int start = msg.indexOf("Cannot convert node ") + 20; int end = start; if (start > 0 && end > start) { while (!Character.isWhitespace(msg.charAt(++end))) {} String uri = msg.substring(start, end); return theModel.createOntProperty(uri); } return null; } private boolean propertyToSadl(StringBuilder sb, ModelConcepts concepts, OntResource prop) { boolean retVal = true; String key = null; OntProperty ontprop = prop.asProperty(); if (ontprop.isURIResource()) { key = ontprop.getURI(); } ExtendedIterator<? extends OntResource> deitr = ontprop.listDomain(); OntProperty sprprop = null; try { sprprop = ontprop.getSuperProperty(); } catch(Exception e) { concepts.addErrorMessage(e.getMessage()); } if (sprprop != null) { sb.append(" is a type of "); sb.append(uriToSadlString(concepts, sprprop)); } if (deitr.hasNext()) { sb.append(" describes "); boolean unionDomain = false; int domainctr = 0; while (deitr.hasNext()) { OntResource dr = deitr.next(); if (deitr.hasNext() && domainctr == 0) { unionDomain = true; sb.append("{"); } if (domainctr++ > 0) { sb.append(" or "); } sb.append(uriToSadlString(concepts, dr)); if (key != null && dr.isURIResource()) { key += dr.getURI(); } } if (unionDomain) { sb.append("}"); } } else if (sprprop == null) { sb.append(" is a property"); } key = generateSadlRangeStatement(concepts, ontprop, sb, key); if (key != null) { if (propertyAlreadyProcessed(key)) { retVal = false; } } return retVal; } private String generateSadlRangeStatement(ModelConcepts concepts, Property prop, StringBuilder sb, String key) { // ExtendedIterator<? extends OntResource> reitr = ontprop.listRange(); StmtIterator reitr = theModel.listStatements(prop, RDFS.range, (RDFNode)null); List<Resource> rngList = new ArrayList<Resource>(); while (reitr.hasNext()) { RDFNode rr = reitr.next().getObject(); if (rr.isResource()) { rngList.add(rr.asResource()); } } int rngcnt = rngList.size(); if (rngcnt > 0) { sb.append(" with values of type "); if (rngcnt == 1) { sb.append(uriToSadlString(concepts, rngList.get(0))); if (key != null && rngList.get(0).isURIResource()) { key += rngList.get(0).getURI(); } } else { sb.append("{"); for (int i = 0; i < rngcnt; i++) { if (i > 0) { sb.append(" or "); } sb.append(uriToSadlString(concepts, rngList.get(i))); if (key != null && rngList.get(i).isURIResource()) { key += rngList.get(i).getURI(); } } sb.append("}"); } } return key; } /** * Method to determine if the property (key is property + domain + range) has already been processed * @param key * @return */ private boolean propertyAlreadyProcessed(String key) { if (propertiesProcessed.contains(key)) { return true; } propertiesProcessed.add(key); return false; } private String rdfNodeToSadlString(ModelConcepts concepts, RDFNode object, boolean forceQuotes) { if (object.isURIResource()) { return uriToSadlString(concepts, object.asResource()); } else if (object.isLiteral()) { String dturi = object.asLiteral().getDatatypeURI(); forceQuotes = forceQuotes ? true : (dturi != null ? isRDFDatatypeString(dturi, object) : true); if (object.asLiteral().getDatatypeURI() == null) { String lf = object.asLiteral().getLexicalForm(); if (forceQuotes || lf.contains(" ") || lf.contains("\"")) { String s = object.asLiteral().getLexicalForm(); s = s.replace("\"", "\\\""); return "\"" + s + "\""; } return object.asLiteral().getLexicalForm(); } if (forceQuotes || object.asLiteral().getDatatypeURI().equals(XSD.xstring.getURI())) { String s = object.asLiteral().getLexicalForm(); if (s.startsWith("\"") && s.endsWith("\"")) { s = s.substring(1, s.length() - 2); } s = s.replace("\"", "\\\""); return "\"" + s + "\""; } else { return object.asLiteral().getLexicalForm(); } } else if (object.canAs(Individual.class)){ // a bnode if (concepts.getInstances().contains(object)) { concepts.getInstances().remove(object); } // is it a list? if (object.as(Individual.class).getProperty(RDF.first) != null) { return listToSadl(concepts, object.as(Individual.class), true); } return individualToSadl(concepts, object.as(Individual.class), true); } else { return object.toString(); } } private String uriToSadlString(ModelConcepts concepts, Resource rsrc) { if (rsrc.isURIResource()) { if (rsrc.getNameSpace().equals(getBaseUri() + "#") || isNeverUsePrefixes()) { String ln = rsrc.getLocalName(); if (allTokens.contains(ln)) { if (rsrc.getNameSpace().equals(XSD.getURI())) { // don't escape a localname if it is a keyword in the XSD types. return ln; } } return checkLocalnameForKeyword(ln); } else { if (rsrc.getNameSpace().equals(XSD.getURI())) { return rsrc.getLocalName(); } String ns = rsrc.getNameSpace(); String trimmedNs = ns.endsWith("#") ? ns.substring(0, ns.length() - 1) : null; if (qNamePrefixes.containsKey(ns)) { String prefix = qNamePrefixes.get(ns).trim(); if (prefix.length() > 0) { return prefix + ":" + checkLocalnameForKeyword(rsrc.getLocalName()); } else { return checkLocalnameForKeyword(rsrc.getLocalName()); } } else { if (trimmedNs != null) { if (qNamePrefixes.containsKey(trimmedNs)) { String prefix = qNamePrefixes.get(trimmedNs).trim(); if (prefix.length() > 0 && isAmbiguousName(rsrc)) { return prefix + ":" + checkLocalnameForKeyword(rsrc.getLocalName()); } else { return checkLocalnameForKeyword(rsrc.getLocalName()); } } } return rsrc.getURI(); } } } else { if (concepts.getMappedRestrictions().containsValue(rsrc)) { return null; } else if (rsrc.canAs(Restriction.class)) { return restrictionToString(concepts, null, rsrc.as(Restriction.class)); } else if (rsrc instanceof OntClass) { // OntClass eqcls = ((OntClass)rsrc).getEquivalentClass(); // if (eqcls != null) { // return uriToSadlString(concepts, eqcls); if (((OntClass)rsrc).isEnumeratedClass()) { EnumeratedClass enumcls = ((OntClass)rsrc).asEnumeratedClass(); return enumeratedClassToString(enumcls); // if (enumcls != null) { // ExtendedIterator<? extends OntResource> eitr = enumcls.listInstances(); // while (eitr.hasNext()) { // OntResource en = eitr.next(); // en.toString(); // ExtendedIterator<RDFNode> eitr2 = enumcls.listIsDefinedBy(); // while (eitr2.hasNext()) { // RDFNode en = eitr2.next(); // en.toString(); // RDFList oneoflst = enumcls.getOneOf(); // List<RDFNode> nodeLst = oneoflst.asJavaList(); // if (nodeLst != null && nodeLst.size() > 0) { // StringBuilder sb = new StringBuilder(); // sb.append("one of {"); // int cntr = 0; // for (int i = 0; i < nodeLst.size(); i++) { // RDFNode n = nodeLst.get(i); // if (cntr > 0) sb.append(", "); // sb.append("\n "); // if (n.canAs(Individual.class)&& concepts.getInstances().contains(n)) { // sb.append(individualNameAndAnnotations(concepts, n.as(Individual.class))); // concepts.getInstances().remove(n); // else { // sb.append(rdfNodeToSadlString(concepts, n, false)); // cntr++; // sb.append("}"); // return sb.toString(); } else { return ontClassToString((OntClass)rsrc, null); // System.err.println("Blank node OntClass is not of handled type: " + rsrc.getClass().getCanonicalName()); } } } return rsrc.toString(); } private boolean isAmbiguousName(Resource rsrc) { int cntr = 0; ExtendedIterator<OntModel> smitr = theModel.listSubModels(true); while (smitr.hasNext()) { if (smitr.next().containsResource(rsrc)) { cntr++; } } return (cntr > 1); } private String checkLocalnameForKeyword(String localName) { String ln = localName; if (allTokens.contains(ln)) { return "^" + ln; } return localName; } private boolean addResourceToList(ModelConcepts concepts, OntResource ontRsrc) { Resource type = ontRsrc.getRDFType(); if (type.equals(OWL.Class)) { if (ontRsrc.isAnon() && ontRsrc.canAs(OntClass.class)) { concepts.addAnonClass(ontRsrc.as(OntClass.class)); return true; } else { if (!ignoreNamespace(ontRsrc, true)) { concepts.addClass(ontRsrc.as(OntClass.class)); return true; } } } else if (type.equals(OWL.ObjectProperty)) { concepts.addObjProperty(ontRsrc.asObjectProperty()); return true; } else if (type.equals(OWL.DatatypeProperty)) { concepts.addDtProperty(ontRsrc.asDatatypeProperty()); return true; } else if (type.equals(RDF.Property)) { // does anything a subproperty of this property? // Resource superPropType = getSuperPropertyType(ontRsrc); // if (superPropType != null) { // if (superPropType.equals(OWL.DatatypeProperty)) { // concepts.addPseudoDtProperty(ontRsrc); // return true; // else { // concepts.addPseudoObjProperty(ontRsrc); // return true; concepts.addRdfProperty(ontRsrc.asProperty()); return true; } else if (type.equals(OWL.AnnotationProperty)) { concepts.addAnnProperty(ontRsrc.asAnnotationProperty()); return true; } else if (type.equals(OWL.Ontology)) { if (!isImplicitUri(ontRsrc.getURI())) { concepts.addOntology(ontRsrc.asOntology()); return true; } else { return false; } } else if (type.equals(RDFS.Datatype)) { if (ontRsrc.isAnon()) { // This should be the equivalent class so ignore this one RDFNode eqcls = ontRsrc.getPropertyValue(OWL.equivalentClass); if (eqcls == null) { StmtIterator itr = theModel.listStatements(null, OWL.equivalentClass, ontRsrc); if (itr.hasNext()) { eqcls = itr.nextStatement().getSubject(); } } if (eqcls != null) { logger.debug("Ignoring RDFDatatype blank node which is equivalent to '" + eqcls.toString() + "'"); } return false; } logger.debug("Examining rdfs:Datatype: " + ontRsrc.toString()); ExtendedIterator<Resource> eitr = ontRsrc.listRDFTypes(true); while (eitr.hasNext()) { logger.debug(" " + eitr.next().toString()); } concepts.addDatatype(ontRsrc); return false; } else if (type.equals(OWL.Restriction)) { try { if (ontRsrc.canAs(Restriction.class) && ontRsrc.as(Restriction.class).getOnProperty().equals(RDFS.Resource)) { return false; } } catch (Throwable t) { concepts.addErrorMessage(t.getMessage()); } if (ontRsrc.canAs(HasValueRestriction.class)) { HasValueRestriction res = ontRsrc.as(HasValueRestriction.class); OntClass supcls = res.getSuperClass(); if (supcls != null) { concepts.addMappedRestriction(supcls, res); return true; } else { try { OntClass subcls = res.getSubClass(); if (subcls != null) { concepts.addMappedRestriction(subcls, res); return true; } } catch (Throwable t) { // this one is not necessarily a real issue--don't report? } } concepts.addUnMappedRestriction(res); return true; } else if (ontRsrc.canAs(SomeValuesFromRestriction.class)) { SomeValuesFromRestriction res = ontRsrc.as(SomeValuesFromRestriction.class); OntClass supcls = res.getSuperClass(); if (supcls != null) { concepts.addMappedRestriction(supcls, res); return true; } else { try { OntClass subcls = res.getSubClass(); if (subcls != null) { concepts.addMappedRestriction(subcls, res); return true; } } catch (Throwable t) { // not necessarily a real error? } } concepts.addUnMappedRestriction(res); return true; } else if (ontRsrc.canAs(AllValuesFromRestriction.class)) { AllValuesFromRestriction res = ontRsrc.as(AllValuesFromRestriction.class); OntClass supcls = res.getSuperClass(); if (supcls != null) { concepts.addMappedRestriction(supcls, res); return true; } else { try { OntClass subcls = res.getSubClass(); if (subcls != null) { concepts.addMappedRestriction(subcls, res); return true; } } catch (Throwable t) { // not necessarily a real error? } } concepts.addUnMappedRestriction(res); return true; } else if (ontRsrc.canAs(CardinalityRestriction.class)) { CardinalityRestriction res = ontRsrc.as(CardinalityRestriction.class); OntClass supcls = res.getSuperClass(); if (supcls != null) { concepts.addMappedRestriction(supcls, res); return true; } else { try { OntClass subcls = res.getSubClass(); if (subcls != null) { concepts.addMappedRestriction(subcls, res); return true; } } catch (Throwable t) { // not necessarily a real error? } } concepts.addUnMappedRestriction(res); return true; } else if (ontRsrc.canAs(MinCardinalityRestriction.class)) { MinCardinalityRestriction res = ontRsrc.as(MinCardinalityRestriction.class); OntClass supcls = res.getSuperClass(); if (supcls != null) { concepts.addMappedRestriction(supcls, res); return true; } else { try { OntClass subcls = res.getSubClass(); if (subcls != null) { concepts.addMappedRestriction(subcls, res); return true; } } catch (Throwable t) { // not necessarily a real error? } } concepts.addUnMappedRestriction(res); return true; } else if (ontRsrc.canAs(MaxCardinalityRestriction.class)) { MaxCardinalityRestriction res = ontRsrc.as(MaxCardinalityRestriction.class); OntClass supcls = res.getSuperClass(); if (supcls != null) { concepts.addMappedRestriction(supcls, res); return true; } else { try { OntClass subcls = res.getSubClass(); if (subcls != null) { concepts.addMappedRestriction(subcls, res); return true; } } catch (Throwable t) { // not necessarily a real error? } } concepts.addUnMappedRestriction(res); return true; } return false; // for now } else if (ontRsrc.canAs(Individual.class)) { Individual inst = ontRsrc.asIndividual(); // only named instances can stand alone if (inst.isURIResource() && !ignoreNamespace(ontRsrc, true)) { concepts.addInstance(inst); return true; } } return false; } private Resource getSuperPropertyType(Resource ontRsrc) { StmtIterator sitr = theModel.listStatements(null, RDFS.subPropertyOf, ontRsrc); if (sitr.hasNext()) { Statement s = sitr.nextStatement(); Resource superprop = s.getSubject(); if (superprop.canAs(ObjectProperty.class)) { return OWL.ObjectProperty; } else if (superprop.canAs(DatatypeProperty.class)) { return OWL.DatatypeProperty; } else { return getSuperPropertyType(superprop); } } return null; } private boolean isNewLineAtEndOfBuffer(StringBuilder sb) { int len = sb.length(); if (len < 1) return false; char ch = sb.charAt(--len); boolean done = false; while (!done) { if (ch == '\n') { return true; } else if (!Character.isWhitespace(ch)) { done = true; } else if (--len <= 0) { done = true; } } return false; } private void addNewLineIfNotAtEndOfBuffer(StringBuilder sb) { if (!isNewLineAtEndOfBuffer(sb)) { sb.append("\n"); } } private List<OntClass> namedClassesAlphabeticalOrder() { ExtendedIterator<OntClass> citr = theBaseModel.listNamedClasses(); if (citr.hasNext()) { List<OntClass> lst = new ArrayList<OntClass>(); while (citr.hasNext()) { OntClass cls = citr.next(); // OntClass equivCls = cls.getEquivalentClass(); // if (equivCls != null) { // ExtendedIterator<OntClass> eitr = cls.listEquivalentClasses(); // while (eitr.hasNext()) { // equivCls = eitr.next(); // logger.debug("Equivalent class to '" + ontClassToString(cls, null) + "': " + ontClassToString(equivCls, null)); if (shouldResourceBeOutput(cls, true, false, false)) { if (lst.size() > 0) { for (int i = 0; i < lst.size(); i++) { // String lstUri = lst.get(i).getURI(); // String clsUri = cls.getURI(); if (lst.get(i).getURI().compareTo(cls.getURI()) > 0) { // if this [ith] item in the list is after cls, insert cls here before it lst.add(i, cls); cls = null; break; } } } if (cls != null) { lst.add(cls); } } } return lst; } return null; } private List<OntProperty> namedPropertiesAlphabeticalOrder(boolean includeEvenIfProcessed) { ExtendedIterator<OntProperty> pitr = theBaseModel.listAllOntProperties(); if (pitr.hasNext()) { List<OntProperty> lst = new ArrayList<OntProperty>(); while (pitr.hasNext()) { OntProperty prop = pitr.next(); if (shouldResourceBeOutput(prop, true, includeEvenIfProcessed, false)) { if (lst.size() > 0) { for (int i = 0; i < lst.size(); i++) { if (lst.get(i).getURI().compareTo(prop.getURI()) > 0) { lst.add(i, prop); prop = null; break; } } } if (prop != null) { lst.add(prop); } } } return lst; } return null; } private List<Individual> individualsAlphabeticalOrder() { ExtendedIterator<Individual> institr = theBaseModel.listIndividuals(); List<Individual> lst = new ArrayList<Individual>(); if (institr.hasNext()) { while (institr.hasNext()) { Individual inst = institr.next(); if (shouldResourceBeOutput(inst, true, false, true)) { if (lst.size() > 0 && !inst.isAnon()) { for (int i = 0; i < lst.size(); i++) { Individual lstinst = lst.get(i); if (lstinst.isAnon() || lstinst.getURI().compareTo(inst.getURI()) > 0) { lst.add(i, inst); inst = null; break; } } } if (inst != null) { lst.add(inst); } } } } ResIterator subjItr = theBaseModel.listSubjects(); while (subjItr.hasNext()) { Resource r = subjItr.nextResource(); if (r.canAs(Individual.class) && r.getURI() != null && r.getURI().indexOf('#') > 0 && shouldResourceBeOutput(r.as(Individual.class), true, false, false)) { if (!lst.contains(r)) { boolean added = false; if (lst.isEmpty()) { lst.add(r.as(Individual.class)); added = true; } else { for (int i = 0; i < lst.size(); i++) { Individual lstinst = lst.get(i); if (lstinst.isAnon() || lstinst.getURI().compareTo(r.getURI()) > 0) { lst.add(r.as(Individual.class)); added = true; break; } } } if (!added) { lst.add(r.as(Individual.class)); } } } } return lst.size() > 0 ? lst : null; } private String addClasses(List<OntClass> clist, OntClass subclass) { int cnt = 0; String clsses = ""; for (int i = 0; clist != null && i < clist.size(); i++) { OntClass cls = clist.get(i); if (cls.isAnon() || !ignoreNamespace(cls, false)) { String addlName = ontClassToString(cls, subclass); if (addlName != null) { if (cnt > 0) { clsses += " and "; } clsses += addlName; cnt++; } } List<OntClass> sclst = getSuperclasses(cls); String superClsses = null; if (sclst != null) { superClsses = addClasses(sclst, cls); } if (shouldResourceBeOutput(cls, true, false, false)) { // this is a top-level class resourcesOutput.add(cls); sadlModel.append(resourceToString(cls, true)); if (superClsses == null) { sadlModel.append(" is a class"); } else { sadlModel.append(" is a type of "); sadlModel.append(superClsses); } ExtendedIterator<OntClass> eitr = cls.listEquivalentClasses(); if (eitr.hasNext()) { while (eitr.hasNext()) { OntClass ec = eitr.next(); if (!ec.equals(cls)) { // don't do equivalence to self (which may be inferred) if (!cls.isAnon() && !ec.isAnon()) { sadlModel.append(resourceToString(cls, false)); sadlModel.append(" is the same as "); sadlModel.append(resourceToString(ec, false)); addEndOfStatement(sadlModel, 1); } else { sadlModel.append(", "); sadlModel.append(ontClassToString(ec, cls)); } } } } try { ExtendedIterator<OntProperty> pitr = cls.listDeclaredProperties(true); while (pitr.hasNext()) { OntProperty prop = pitr.next(); if (shouldResourceBeOutput(prop, true, false, false)) { sadlModel.append(",\n described by "); sadlModel.append(resourceToString(prop, false)); String rngString = rangeToString(prop); if (rngString != null && rngString.length() > 0) { if (isSingleValued(cls, prop, rngString)) { //if (prop.isFunctionalProperty()) { sadlModel.append(" with a single value of type "); } else { sadlModel.append(" with values of type "); } sadlModel.append(rngString); // resourcesOutput.add(prop); // if we get to here consider the property defined. No, it can have multiple classes in domain. } } } } catch (Throwable t) { logger.debug("Unexpected error processing class '" + cls.toString() + "': " + t.getMessage()); } addEndOfStatement(sadlModel, 1); addRestrictionsToOutput(cls, true); ExtendedIterator<OntClass> ditr = cls.listDisjointWith(); if (ditr.hasNext()) { OntClass dcls = ditr.next(); sadlModel.append(resourceToString(cls, false)); sadlModel.append(" is disjoint with "); sadlModel.append(resourceToString(dcls, false)); addEndOfStatement(sadlModel, 1); } } } if (cnt > 1) { clsses = "{" + clsses + "}"; } return clsses.length() > 0 ? clsses : null; } private List<OntClass> getSuperclasses(OntClass cls) { try { ExtendedIterator<OntClass> eitr = cls.listSuperClasses(true); if (eitr.hasNext()) { List<OntClass> lst = new ArrayList<OntClass>(); while (eitr.hasNext()) { lst.add(eitr.next()); } return lst; } } catch (Throwable t) { logger.debug("Unexpected erro getting super classes of '" + cls.toString() + "': " + t.getLocalizedMessage()); } return null; } private void addProperties(List<OntProperty> plst, boolean outputEvenIfDuplicate) throws IOException { for (int i = 0; plst != null && i < plst.size(); i++) { OntProperty prop = plst.get(i); if (shouldResourceBeOutput(prop, true, outputEvenIfDuplicate, false)) { resourcesOutput.add(prop); if (prop.isObjectProperty() && !prop.isFunctionalProperty() && !prop.isInverseFunctionalProperty()) { sadlModel.append("relationship of "); sadlModel.append(domainToString(prop)); sadlModel.append(" to "); sadlModel.append(rangeToString(prop)); sadlModel.append(" is "); sadlModel.append(resourceToString(prop, false)); addEndOfStatement(sadlModel, 1); if (prop.isFunctionalProperty()) { sadlModel.append("\t"); sadlModel.append(resourceToString(prop, false)); sadlModel.append(" has a single value.\n"); } } else { sadlModel.append(resourceToString(prop, false)); sadlModel.append(" describes "); sadlModel.append(domainToString(prop)); if (prop.isFunctionalProperty()) { sadlModel.append(" with a single value of type "); } else { sadlModel.append(" with values of type "); } sadlModel.append(rangeToString(prop)); sadlModel.append(".\n"); } } } } private void addIndividuals(List<Individual> instlst) throws Exception { Individual inst; for (int i = 0; instlst != null && i < instlst.size(); i++) { inst = instlst.get(i); if (shouldResourceBeOutput(inst, true, false, true)) { ExtendedIterator<OntClass> typeitr = inst.listOntClasses(true); if (typeitr.hasNext()) { List<OntClass> types = new ArrayList<OntClass>(); while (typeitr.hasNext()) { try { OntClass type = typeitr.next(); types.add(type); } catch (Exception e) { ExtendedIterator<Resource> eitr = inst.listRDFTypes(true); while (eitr.hasNext()) { Resource rtype = eitr.next(); if (!rtype.isAnon()) { OntClass newClass = theBaseModel.createClass(rtype.getURI()); types.add(newClass); } } } } String typeString = classListToString(types, null); if (inst.isAnon()) { sadlModel.append("A "); sadlModel.append(typeString); } else { sadlModel.append(resourceToString(inst, false)); sadlModel.append(" is a "); sadlModel.append(typeString); } String instProps = instancePropertiesToString(inst, false, 1); if (instProps != null) { sadlModel.append(instProps); } addEndOfStatement(sadlModel, 1); resourcesOutput.add(inst); } else { throw new Exception("The instance '" + inst.toString() + "' does not have a specified type (class); SADL cannot import it."); } } } } private String instancePropertiesToString(Individual inst, boolean useWith, int indentLevel) { List<Statement> orderedStatements = getInstancePropertiesOrdered(inst); // StmtIterator sitr = inst.listProperties(); Iterator<Statement> sitr = orderedStatements.iterator(); if (sitr.hasNext()) { List<Statement> stmts = new ArrayList<Statement>(); while (sitr.hasNext()) { stmts.add(sitr.next()); } stmts = mostPreciseStatementsOnly(stmts); StringBuilder sb = new StringBuilder(); for (int i = 0; i < stmts.size(); i++) { Statement s = stmts.get(i); if (!ignoreNamespace(s.getSubject(), false) && !ignoreNamespace(s.getPredicate(), false)) { sb.append(",\n"); for (int j = 0; j < indentLevel; j++) { sb.append("\t"); } sb.append((useWith ? "with " : "has ") + resourceToString(s.getPredicate(), false)); sb.append(" "); sb.append(rdfNodeToString(s.getObject(), indentLevel)); } } return sb.toString(); } return null; } private List<Statement> getInstancePropertiesOrdered(Individual inst) { List<Statement> results = new ArrayList<Statement>(); if (!inst.isAnon()) { String query = "select ?p ?v where {<" + inst.getURI() + "> ?p ?v} order by ?p ?v"; logger.debug("Owl2Sadl query: " + query); QueryExecution qexec = null; qexec = QueryExecutionFactory.create(QueryFactory.create(query, Syntax.syntaxARQ), theModel); ResultSet rs = qexec.execSelect(); while (rs.hasNext()) { QuerySolution soln = rs.next(); Resource p = soln.getResource("p"); if (p.canAs(Property.class)) { RDFNode v = soln.get("v"); StmtIterator sitr = theBaseModel.listStatements(inst, p.as(Property.class), v); Statement s = sitr.next(); if (s != null) { results.add(s); } } } } else { StmtIterator sitr = theBaseModel.listStatements(inst, (Property)null, (RDFNode)null); while (sitr.hasNext()) { results.add(sitr.nextStatement()); } } return results; } private List<Statement> mostPreciseStatementsOnly(List<Statement> stmts) { List<Statement> removals = null; for (int i = 0; i < stmts.size(); i++) { Statement si = stmts.get(i); for (int j = 0; j < stmts.size(); j++) { if (i != j) { Statement sj = stmts.get(j); if (si.getObject().equals(sj.getObject())) { Property pi = si.getPredicate(); Property pj = sj.getPredicate(); if (!pi.equals(pj) && pi.canAs(OntProperty.class) && pj.canAs(OntProperty.class)){ if (pi.as(OntProperty.class).hasSuperProperty(pj, false)) { if (removals == null) removals = new ArrayList<Statement>(); removals.add(sj); } } } } } } if (removals != null) { for (int i = 0; i < removals.size(); i++) { stmts.remove(removals.get(i)); } } return stmts; } private String getIntersectionClassRangeString(IntersectionClass intersectionClass) { String rslt = ""; int cnt = 0; RDFList iclsses = intersectionClass.getOperands(); if (iclsses != null) { ExtendedIterator<RDFNode> eitr = iclsses.iterator(); while (eitr.hasNext()) { RDFNode node = eitr.next(); if (cnt > 0) rslt += " and "; if (node.canAs(OntClass.class)) { rslt += ontClassToString(node.as(OntClass.class), null); } cnt++; } if (cnt > 1) { rslt = "{" + rslt + "}"; } } return rslt; } private String getUnionClassRangeString(UnionClass unionClass) { String rslt = ""; int cnt = 0; RDFList uclsses = unionClass.getOperands(); if (uclsses != null) { ExtendedIterator<RDFNode> eitr = uclsses.iterator(); while (eitr.hasNext()) { RDFNode node = eitr.next(); if (cnt > 0) rslt += " or "; if (node.canAs(OntClass.class)) { rslt += ontClassToString(node.as(OntClass.class), null); } cnt++; } if (cnt > 1) { rslt = "{" + rslt + "}"; } } return rslt; } /** * Method to convert a list of types (superclasses) into a string containing only the most immediate supertypes * @param types * @return */ private String classListToString(List<OntClass> types, OntClass subClass) { types = lowestIndependentClassesOnly(types); String rslt = ""; for (int i = 0; i < types.size(); i++) { OntClass r = types.get(i); if (i > 0) rslt += " or "; rslt += ontClassToString(r, subClass); } if (types.size() > 1) { rslt = "{" + rslt + "}"; } return rslt; } private List<OntClass> lowestIndependentClassesOnly(List<OntClass> types) { List<OntClass> removals = null; for (int i = 0; i < types.size(); i++) { for (int j = 0; j < types.size(); j++) { if (j != i) { OntClass clsi = types.get(i); OntClass clsj = types.get(j); if (clsi.isUnionClass()) { if (unionClassContainsSuperclass(clsi.asUnionClass(), clsj)) { if (removals == null) removals = new ArrayList<OntClass>(); removals.add(clsi); } } else if (clsj.isUnionClass()) { if (unionClassContainsSuperclass(clsj.asUnionClass(), clsi)) { if (removals == null) removals = new ArrayList<OntClass>(); removals.add(clsj); } } else if (clsi.hasSuperClass(clsj)) { if (removals == null) removals = new ArrayList<OntClass>(); removals.add(clsj); } else if (clsj.hasSuperClass(clsi)) { if (removals == null) removals = new ArrayList<OntClass>(); removals.add(clsi); } } } } if (removals != null) { for (int i = 0; i < removals.size(); i++) { if (types.contains(removals.get(i))) { types.remove(removals.get(i)); } } } return types; } private boolean unionClassContainsSuperclass(UnionClass unionCls, OntClass cls) { ExtendedIterator<RDFNode> eitr = unionCls.getOperands().iterator(); while (eitr.hasNext()) { RDFNode node = eitr.next(); if (node.equals(cls) || (node.canAs(OntClass.class) && cls.hasSuperClass((OntClass)node.as(OntClass.class)))) { eitr.close(); return true; } } return false; } private String domainToString(OntProperty prop) throws IOException { ExtendedIterator<? extends OntResource> ditr = prop.listDomain(); while (ditr.hasNext()) { OntResource dmnNode = ditr.next(); if (dmnNode.canAs(OntClass.class)) { return ontClassToString(dmnNode.as(OntClass.class), null); } else { throw new IOException("Domain of property '" + prop.toString() + "' is not an OntClass!"); } } return null; } private String rangeToString(OntProperty prop) { ExtendedIterator<? extends OntResource> ritr = prop.listRange(); String rng = ""; int cnt = 0; while (ritr.hasNext()) { OntResource rngNode = ritr.next(); if (!rngNode.isAnon() && rngNode.getNameSpace().equals(XSD.getURI())) { rng += rngNode.getLocalName(); } else if (rngNode.canAs(OntClass.class)) { rng += ontClassToString((OntClass)rngNode.as(OntClass.class), null); } else { rng += rngNode.toString(); } cnt++; } if (cnt > 1) { rng = "{" + rng + "}"; } return rng; } private String ontClassToString(OntClass cls, OntClass subclass) { if (cls.isUnionClass()) { return getUnionClassRangeString(cls.asUnionClass()); } else if (cls.isIntersectionClass()) { return getIntersectionClassRangeString(cls.asIntersectionClass()); } else if (cls.isRestriction()) { if (!shouldResourceBeOutput(cls, true, false, false)) { Restriction rest = cls.asRestriction(); Property onProp = rest.getOnProperty(); if (rest.isAllValuesFromRestriction()) { Resource avfr = rest.asAllValuesFromRestriction().getAllValuesFrom(); addRestriction(subclass, resourceToString(onProp, false) + " of " + resourceToString(subclass, false) + " only has values of type " + resourceToString(avfr, false) + ".\n"); } else if (rest.isSomeValuesFromRestriction()) { Resource svfr = rest.asSomeValuesFromRestriction().getSomeValuesFrom(); addRestriction(subclass, resourceToString(onProp, false) + " of " + resourceToString(subclass, false) + " has at least one value of type " + resourceToString(svfr, false) + ".\n"); } else if (rest.isMaxCardinalityRestriction()) { int maxCard = rest.asMaxCardinalityRestriction().getMaxCardinality(); addRestriction(subclass, resourceToString(onProp, false) + " of " + resourceToString(subclass, false) + " has at most " + maxCard + (maxCard > 1 ? " values.\n" : " value.\n")); } else if (rest.isMinCardinalityRestriction()) { int minCard = rest.asMinCardinalityRestriction().getMinCardinality(); addRestriction(subclass, resourceToString(onProp, false) + " of " + resourceToString(subclass, false) + " has at least " + minCard + (minCard > 1 ? " values.\n" : " value.\n")); } else if (rest.isCardinalityRestriction()) { int card = rest.asCardinalityRestriction().getCardinality(); addRestriction(subclass, resourceToString(onProp, false) + " of " + resourceToString(subclass, false) + " has exactly " + card + (card > 1 ? " values.\n" : " value.\n")); } else if (rest.isHasValueRestriction()) { RDFNode hvr = rest.asHasValueRestriction().getHasValue(); addRestriction(subclass, resourceToString(onProp, false) + " of " + resourceToString(subclass, false) + " always has value " + rdfNodeToString(hvr, 0) + " .\n"); } else { logger.debug("Unhandled restriction: " + rest.getClass()); } resourcesOutput.add(cls); } if (cls.isAnon()) { // logger.debug("returning null on anon restriction--should this happen??"); return null; } else { return cls.toString(); } } else if (cls.isEnumeratedClass()) { EnumeratedClass enumcls = cls.asEnumeratedClass(); return enumeratedClassToString(enumcls); } else if (cls.isComplementClass()) { ComplementClass ccls = cls.asComplementClass(); OntClass thecls = ccls.getDisjointWith(); if (thecls != null) { return resourceToString(thecls, false); } else { return null; } } else if (!cls.isAnon()) { return resourceToString(cls, false); } else { logger.debug("Anon class; returning string equivalent--this shouldn't happen."); return cls.toString(); } } private String enumeratedClassToString(EnumeratedClass enumcls) { StringBuilder sb = new StringBuilder("must be one of {"); ExtendedIterator<? extends OntResource> eitr = enumcls.listOneOf(); int cnt = 0; while (eitr.hasNext()) { OntResource r = eitr.next(); if (cnt++ > 0) { sb.append(", "); } sb.append(resourceToString(r, false)); checkResourceOutputComplete(r); } sb.append("}"); return sb.toString(); } private void checkResourceOutputComplete(OntResource r) { if (r.canAs(Individual.class)) { Individual inst = r.asIndividual(); StmtIterator sitr = inst.listProperties(); while (sitr.hasNext()) { Statement s = sitr.next(); if (!s.getPredicate().equals(RDF.type)) { logger.debug(s.toString()); sitr.close(); return; } } resourcesOutput.add(r); sitr.close(); } } private void addRestriction(OntResource cls, String rest) { if (restrictions == null) restrictions = new HashMap<String, OntResource>(); if (!restrictions.containsKey(rest)) { restrictions.put(rest, cls); } } private void addRestrictionsToOutput(OntResource cls, boolean indent) { if (restrictions != null && restrictions.containsValue(cls)) { Iterator<String> itr = restrictions.keySet().iterator(); while (itr.hasNext()) { String key = itr.next(); OntResource r = restrictions.get(key); if (r != null && r.equals(cls)) { if (indent) { sadlModel.append("\t"); } sadlModel.append(key); restrictions.put(key, null); // clear } } } } private String resourceToString(Resource rsrc, boolean includeAnnotations) { if (rsrc == null) { return "null"; } if (rsrc.isAnon()) { if (rsrc.canAs(OntClass.class)) { return ontClassToString(rsrc.as(OntClass.class), null); } else { return rdfNodeToString(rsrc, 0); } } String ns; String ln; String uri = rsrc.getURI(); if (uri.indexOf(' ns = uri.substring(0, uri.indexOf(' ln = uri.substring(uri.indexOf(' } else { ns = rsrc.getNameSpace(); ln = rsrc.getLocalName(); } String prefix = null; if (prefix == null) { prefix = theModel.getNsURIPrefix(ns); } prefix = sadlizePrefix(prefix); if (allTokens.contains(ln)) { ln = "^" + ln; } if (prefix != null && prefix.length() > 0) { ln = prefix + ":" + ln; } if (rsrc.canAs(OntResource.class) && shouldResourceBeOutput(rsrc.as(OntResource.class), true, includeAnnotations, true)) { if (includeAnnotations) { StmtIterator sitr = rsrc.listProperties(RDFS.label); if (sitr.hasNext()) { ln += " (alias "; int cntr = 0; while (sitr.hasNext()) { Statement stmt = sitr.nextStatement(); if (cntr++ > 0) { ln += ", "; } ln += "\"" + stmt.getObject().asLiteral().getLexicalForm() + "\""; } ln += ")"; } sitr = rsrc.listProperties(RDFS.comment); if (sitr.hasNext()) { ln += " (note "; int cntr = 0; while (sitr.hasNext()) { Statement stmt = sitr.nextStatement(); if (cntr++ > 0) { ln += ", "; } ln += "\"" + stmt.getObject().asLiteral().getLexicalForm() + "\""; } ln += ")"; } } } return ln; } private String sadlizePrefix(String prefix) { if (prefix != null) { prefix = prefix.replace('.', '_'); // Jena likes to create prefixes with period. prefix = prefix.replace('-', '_'); } return prefix; } private String rdfNodeToString(RDFNode node, int indentLevel) { if (node.isAnon()) { if (node instanceof Resource && ((Resource)node).canAs(Individual.class)) { // this is an unnamed individual Individual bnodeInst = ((Resource)node).as(Individual.class); resourcesOutput.add(bnodeInst); String typedBNode = "(a "; ExtendedIterator<Resource> eitr = bnodeInst.listRDFTypes(true); if (eitr.hasNext()) { Resource dcls = eitr.next(); typedBNode += resourceToString(dcls, false); } else { typedBNode += "bnode_missing_type"; } String instProps = instancePropertiesToString(bnodeInst, true, indentLevel + 1); if (instProps != null) { typedBNode += instProps; } typedBNode += ")"; return typedBNode; } } if (node instanceof Resource) { return resourceToString((Resource) node, false); } else if (node instanceof Literal) { Object objVal = ((Literal)node).getValue(); if (objVal instanceof Integer || objVal instanceof Long) { return objVal.toString() + " "; } else if (objVal instanceof Number) { return objVal.toString(); } else if (objVal instanceof Boolean) { return objVal.toString(); } else { String val = objVal.toString().trim(); if (val.startsWith("\"") && val.endsWith("\"")) { // string is already quoted return objVal.toString(); } else { return "\"" + objVal.toString() + "\""; } } // else { // return "\"" + objVal.toString() + "\""; } return "this shouldn't happen in rdfNodeToString"; } protected boolean shouldResourceBeOutput(OntResource rsrc, boolean bThisModelOnly, boolean includeProcessed, boolean includeAnon) { if (rsrc.isAnon() && !includeAnon) { return false; } // if (!includeProcessed && resourcesOutput.contains(rsrc)) { // return false; if (! rsrc.isAnon() && ignoreNamespace(rsrc, bThisModelOnly)) { return false; } if (!theModel.getBaseModel().containsResource(rsrc)) { return false; } StmtIterator typitr = theModel.listStatements(rsrc, RDF.type, (RDFNode)null); if (typitr.hasNext()) { return true; } if (rsrc.getRDFType() == null) { return false; } return true; } protected boolean shouldResourceBeOutput(Resource rsrc, boolean bThisModelOnly, boolean includeProcessed, boolean includeAnon) { if (rsrc.isAnon() && !includeAnon) { return false; } // if (!includeProcessed && resourcesOutput.contains(rsrc)) { // return false; if (! rsrc.isAnon() && ignoreNamespace(rsrc, bThisModelOnly)) { return false; } if (!theModel.getBaseModel().containsResource(rsrc)) { return false; } return true; } protected boolean ignoreNamespace(Resource rsrc, boolean bThisModelOnly) { String uri = rsrc.getNameSpace(); if (uri == null) { return true; } String nm = uri.endsWith("#") ? uri.substring(0, uri.length() - 1) : uri; if (nm.equals(getBaseUri())) { return false; } if (bThisModelOnly && imports != null && imports.contains(nm)) { // if this is in an import namespace, ignore it. return true; } // namespaces to ingore: rdf, rdfs, owl if (uri.equals("http://www.w3.org/2000/01/rdf-schema uri.equals("http://www.w3.org/1999/02/22-rdf-syntax-ns uri.equals("http://www.w3.org/2002/07/owl uri.startsWith("http://purl.org/dc/elements/1.1") || uri.startsWith("http://www.w3.org/2001/XMLSchema uri.equals("")) { return true; } else if (bThisModelOnly){ if (!rsrc.isAnon() && sameNs(rsrc.getNameSpace(),getBaseUri())) { return false; } String prefix = theModel.getNsURIPrefix(uri); if (prefix != null && prefix.length() > 0) { return true; } } return false; } private boolean sameNs(String ns1, String ns2) { if (ns1.endsWith(" ns1 = ns1.substring(0, ns1.length() - 1); } if (ns2.endsWith(" ns2 = ns2.substring(0, ns2.length() - 1); } if (ns1.equals(ns2)) { return true; } return false; } // protected OntDocumentManager prepare(String modelUrl, String policyFilename) throws IOException { // File of = validateOntologyName(modelUrl); // File pf; // if (policyFilename != null && policyFilename.length() > 0) { // pf = new File(policyFilename); // else { // throw new IOException("Policy file name is invalid"); // return new UtilsForJena().loadMappings(pf); // OntModel m = new UtilsForJena().createAndInitializeJenaModel(policyFilename); // m.getSpecification(); protected File validateOntologyName(String ontology) throws IOException { URL url = new URL(ontology); String filename = URLDecoder.decode(url.getFile(), "UTF-8"); File of = new File(filename); if (!of.exists()) { File cd = new File("."); if (cd.exists()) { logger.debug("Current directory: " + cd.getCanonicalPath()); } throw new IOException("Ontology file '" + ontology + "' does not exist."); } else if (of.isDirectory()) { throw new IOException("Ontology file '" + ontology + "' is a directory."); } sourceFile = of.getName(); return of; } protected File validateFileName(String urlStr) throws IOException { URL url = new URL(urlStr); String filename = URLDecoder.decode(url.getFile(), "UTF-8"); File of = new File(filename); if (of.exists()) { return of; } throw new IOException("File '" + filename + "' does not exist."); } protected File getSiblingFile(File theFile, String fileName) throws IOException { File parentDir = theFile.getParentFile(); String siblingFileName = parentDir.getCanonicalPath() + File.separator + fileName; File siblingFile = new File(siblingFileName); if (siblingFile.exists()) { return siblingFile; } return null; } protected static boolean isSingleValued(OntClass cls, OntProperty prop, String rngString) { if (prop.isFunctionalProperty()) { return true; } if (cls != null) { ExtendedIterator<OntClass> eitr = cls.listSuperClasses(false); while (eitr.hasNext()) { OntClass supercls = eitr.next(); if (supercls.isRestriction()) { Restriction rstrct = supercls.asRestriction(); if (rstrct.isMaxCardinalityRestriction()) { MaxCardinalityRestriction mxcr = rstrct.asMaxCardinalityRestriction(); if (mxcr.getOnProperty().equals(prop) && mxcr.getMaxCardinality() == 1) { return true; } } else if (rstrct.isCardinalityRestriction()) { if (rstrct.isCardinalityRestriction()) { CardinalityRestriction cr = rstrct.asCardinalityRestriction(); if (cr.getOnProperty().equals(prop) && cr.getCardinality() == 1) { return true; } } } else { if (rstrct.hasProperty(OWL2.maxQualifiedCardinality)) { if (rstrct.getOnProperty().equals(prop) && rstrct.getProperty(OWL2.maxQualifiedCardinality).getInt() == 1) { // check class if (rstrct.getProperty(OWL2.onClass).getResource().toString().equals(rngString)) { return true; } } } else if (rstrct.hasProperty(OWL2.qualifiedCardinality)) { if (rstrct.getOnProperty().equals(prop) && rstrct.getProperty(OWL2.qualifiedCardinality).getInt() == 1) { // check class if (rstrct.getProperty(OWL2.onClass).getResource().toString().equals(rngString)) { return true; } } } // StmtIterator siter = rstrct.listProperties(); // while (siter.hasNext()) { // logger.debug(siter.nextStatement().toString()); } } } } return false; } /** * Call this method to remove double quotes from the beginning and end of a * string so quoted. * * @param quotedString * -- the string from which quotes are to be removed */ protected String stripQuotes(String quotedString) { if (quotedString != null && !quotedString.isEmpty()) { if (quotedString.charAt(0) == '\"') { while (quotedString.charAt(0) == '\"') { quotedString = quotedString.substring(1); } while (quotedString.length() > 0 && quotedString.charAt(quotedString.length() - 1) == '\"') { quotedString = quotedString.substring(0, quotedString.length() - 1); } } else if (quotedString.charAt(0) == '\'') { while (quotedString.charAt(0) == '\'') { quotedString = quotedString.substring(1); } while (quotedString.length() > 0 && quotedString.charAt(quotedString.length() - 1) == '\'') { quotedString = quotedString.substring(0, quotedString.length() - 1); } } } return quotedString; } private OntModelSpec getSpec() { if (spec == null) { spec = OntModelSpec.OWL_MEM; } return spec; } private void setSpec(OntModelSpec spec) { this.spec = spec; } public boolean isVerboseMode() { return verboseMode; } public void setVerboseMode(boolean verboseMode) { this.verboseMode = verboseMode; if (verboseMode && verboseModeStringBuilder == null) { verboseModeStringBuilder = new StringBuilder(); } } private ModelConcepts getConcepts() throws OwlImportException { if (concepts == null) { initialize(); } return concepts; } private void setConcepts(ModelConcepts concepts) { this.concepts = concepts; } public boolean isNeverUsePrefixes() { return neverUsePrefixes; } public void setNeverUsePrefixes(boolean neverUsePrefixes) { this.neverUsePrefixes = neverUsePrefixes; } public String getBaseUri() { return baseUri; } public void setBaseUri(String baseUri) { this.baseUri = baseUri; } private String getPrefix() { return prefix; } private void setPrefix(String prefix) { this.prefix = prefix; } }
package org.sensorhub.test.sensor.angel; import java.io.IOException; import net.opengis.sensorml.v20.AbstractProcess; import net.opengis.swe.v20.DataComponent; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.sensorhub.api.common.Event; import org.sensorhub.api.common.IEventListener; import org.sensorhub.api.common.SensorHubException; import org.sensorhub.api.sensor.ISensorDataInterface; import org.sensorhub.api.sensor.SensorDataEvent; import org.sensorhub.impl.SensorHub; import org.sensorhub.impl.comm.ble.dbus.BleDbusCommNetwork; import org.sensorhub.impl.comm.ble.dbus.BluetoothNetworkConfig; import org.sensorhub.impl.module.ModuleRegistry; import org.sensorhub.impl.sensor.angel.AngelSensorConfig; import org.sensorhub.impl.sensor.angel.AngelSensor; import org.vast.data.TextEncodingImpl; import org.vast.sensorML.SMLUtils; import org.vast.swe.AsciiDataWriter; import org.vast.swe.SWEUtils; import static org.junit.Assert.*; public class TestAngelSensorDriverBleDbus implements IEventListener { AngelSensor driver; AngelSensorConfig config; AsciiDataWriter writer; int sampleCount = 0; @Before public void init() throws Exception { ModuleRegistry reg = SensorHub.getInstance().getModuleRegistry(); BluetoothNetworkConfig netConf = new BluetoothNetworkConfig(); netConf.id = "BLE"; netConf.moduleClass = BleDbusCommNetwork.class.getCanonicalName(); netConf.deviceName = "hci0"; netConf.autoStart = true; reg.loadModule(netConf); config = new AngelSensorConfig(); config.id = "ANGEL"; config.networkID = netConf.id; //config.btAddress = "00:07:80:79:04:AF"; config.btAddress = "00:07:80:03:0E:0A"; config.autoStart = true; driver = (AngelSensor)reg.loadModule(config); } @Test public void testGetOutputDesc() throws Exception { for (ISensorDataInterface di: driver.getObservationOutputs().values()) { System.out.println(); DataComponent dataMsg = di.getRecordDescription(); new SWEUtils(SWEUtils.V2_0).writeComponent(System.out, dataMsg, false, true); } } @Test public void testGetSensorDesc() throws Exception { System.out.println(); AbstractProcess smlDesc = driver.getCurrentDescription(); new SMLUtils(SWEUtils.V2_0).writeProcess(System.out, smlDesc, true); } @Test public void testSendMeasurements() throws Exception { System.out.println(); ISensorDataInterface output = driver.getObservationOutputs().get("healthData"); writer = new AsciiDataWriter(); writer.setDataEncoding(new TextEncodingImpl(",", "\n")); writer.setDataComponents(output.getRecordDescription()); writer.setOutput(System.out); output.registerListener(this); driver.start(); synchronized (this) { while (sampleCount < 20) wait(); } System.out.println(); } @Override public void handleEvent(Event<?> e) { assertTrue(e instanceof SensorDataEvent); SensorDataEvent newDataEvent = (SensorDataEvent)e; try { //System.out.print("\nNew data received from sensor " + newDataEvent.getSensorId()); writer.write(newDataEvent.getRecords()[0]); writer.flush(); sampleCount++; } catch (IOException e1) { e1.printStackTrace(); } synchronized (this) { this.notify(); } } @After public void cleanup() { try { driver.stop(); } catch (SensorHubException e) { e.printStackTrace(); } } }
package org.rstudio.studio.client.workbench.views.source.editors.text.rmd; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Queue; import java.util.Set; import org.rstudio.core.client.CommandWithArg; import org.rstudio.core.client.StringUtil; import org.rstudio.core.client.layout.FadeOutAnimation; import org.rstudio.core.client.theme.res.ThemeStyles; import org.rstudio.core.client.widget.Operation; import org.rstudio.studio.client.RStudioGinjector; import org.rstudio.studio.client.application.events.EventBus; import org.rstudio.studio.client.application.events.InterruptStatusEvent; import org.rstudio.studio.client.application.events.RestartStatusEvent; import org.rstudio.studio.client.common.GlobalDisplay; import org.rstudio.studio.client.rmarkdown.events.RmdChunkOutputEvent; import org.rstudio.studio.client.rmarkdown.events.RmdChunkOutputFinishedEvent; import org.rstudio.studio.client.rmarkdown.events.SendToChunkConsoleEvent; import org.rstudio.studio.client.rmarkdown.model.RMarkdownServerOperations; import org.rstudio.studio.client.server.ServerError; import org.rstudio.studio.client.server.ServerRequestCallback; import org.rstudio.studio.client.server.VoidServerRequestCallback; import org.rstudio.studio.client.server.Void; import org.rstudio.studio.client.workbench.model.Session; import org.rstudio.studio.client.workbench.prefs.model.UIPrefs; import org.rstudio.studio.client.workbench.views.console.events.ConsolePromptEvent; import org.rstudio.studio.client.workbench.views.console.events.ConsolePromptHandler; import org.rstudio.studio.client.workbench.views.console.model.ConsoleServerOperations; import org.rstudio.studio.client.workbench.views.source.SourceWindowManager; import org.rstudio.studio.client.workbench.views.source.editors.text.ChunkOutputWidget; import org.rstudio.studio.client.workbench.views.source.editors.text.DocDisplay; import org.rstudio.studio.client.workbench.views.source.editors.text.Scope; import org.rstudio.studio.client.workbench.views.source.editors.text.TextEditingTarget; import org.rstudio.studio.client.workbench.views.source.editors.text.TextEditingTargetRMarkdownHelper; import org.rstudio.studio.client.workbench.views.source.editors.text.ace.LineWidget; import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Position; import org.rstudio.studio.client.workbench.views.source.editors.text.events.RenderFinishedEvent; import org.rstudio.studio.client.workbench.views.source.editors.text.events.EditorThemeStyleChangedEvent; import org.rstudio.studio.client.workbench.views.source.editors.text.events.FoldChangeEvent; import org.rstudio.studio.client.workbench.views.source.events.ChunkChangeEvent; import org.rstudio.studio.client.workbench.views.source.events.ChunkContextChangeEvent; import org.rstudio.studio.client.workbench.views.source.model.DocUpdateSentinel; import org.rstudio.studio.client.workbench.views.source.model.SourceDocument; import com.google.gwt.core.client.JsArray; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.Style; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.event.dom.client.FocusEvent; import com.google.gwt.event.dom.client.FocusHandler; import com.google.gwt.event.logical.shared.ResizeEvent; import com.google.gwt.event.logical.shared.ResizeHandler; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.user.client.Command; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; import com.google.inject.Provider; public class TextEditingTargetNotebook implements EditorThemeStyleChangedEvent.Handler, RmdChunkOutputEvent.Handler, RmdChunkOutputFinishedEvent.Handler, SendToChunkConsoleEvent.Handler, ChunkChangeEvent.Handler, ChunkContextChangeEvent.Handler, ConsolePromptHandler, ResizeHandler, InterruptStatusEvent.Handler, RestartStatusEvent.Handler { private class ChunkExecQueueUnit { public ChunkExecQueueUnit(String chunkIdIn, String codeIn, String optionsIn, String setupCrc32In) { chunkId = chunkIdIn; options = optionsIn; code = codeIn; setupCrc32 = setupCrc32In; } public String chunkId; public String options; public String code; public String setupCrc32; }; public TextEditingTargetNotebook(final TextEditingTarget editingTarget, DocDisplay docDisplay, DocUpdateSentinel docUpdateSentinel, SourceDocument document) { docDisplay_ = docDisplay; docUpdateSentinel_ = docUpdateSentinel; initialChunkDefs_ = document.getChunkDefs(); outputWidgets_ = new HashMap<String, ChunkOutputWidget>(); lineWidgets_ = new HashMap<String, LineWidget>(); chunkExecQueue_ = new LinkedList<ChunkExecQueueUnit>(); setupCrc32_ = docUpdateSentinel_.getProperty(LAST_SETUP_CRC32); editingTarget_ = editingTarget; RStudioGinjector.INSTANCE.injectMembers(this); // initialize the display's default output mode String outputType = document.getProperties().getAsString(CHUNK_OUTPUT_TYPE); if (!outputType.isEmpty() && outputType != "undefined") { // if the document property is set, apply it directly docDisplay_.setShowChunkOutputInline( outputType == CHUNK_OUTPUT_INLINE); } else { // otherwise, use the global preference to set the value docDisplay_.setShowChunkOutputInline( RStudioGinjector.INSTANCE.getUIPrefs() .showRmdChunkOutputInline().getValue()); } docDisplay_.addEditorFocusHandler(new FocusHandler() { @Override public void onFocus(FocusEvent arg0) { if (queuedResize_ != null) { onResize(queuedResize_); queuedResize_ = null; } } }); // listen for future changes to the preference and sync accordingly docUpdateSentinel_.addPropertyValueChangeHandler(CHUNK_OUTPUT_TYPE, new ValueChangeHandler<String>() { @Override public void onValueChange(ValueChangeEvent<String> event) { changeOutputMode(event.getValue()); } }); docDisplay_.addValueChangeHandler(new ValueChangeHandler<Void>() { @Override public void onValueChange(ValueChangeEvent<Void> arg0) { validateSetupChunk_ = true; } }); // single shot rendering of chunk output line widgets // (we wait until after the first render to ensure that // ace places the line widgets correctly) docDisplay_.addRenderFinishedHandler(new RenderFinishedEvent.Handler() { @Override public void onRenderFinished(RenderFinishedEvent event) { if (initialChunkDefs_ != null) { for (int i = 0; i<initialChunkDefs_.length(); i++) { ChunkDefinition chunkOutput = initialChunkDefs_.get(i); LineWidget widget = LineWidget.create( ChunkDefinition.LINE_WIDGET_TYPE, chunkOutput.getRow(), elementForChunkDef(chunkOutput), chunkOutput); lineWidgets_.put(chunkOutput.getChunkId(), widget); widget.setFixedWidth(true); docDisplay_.addLineWidget(widget); } // if we got chunk content, load initial chunk output from server if (initialChunkDefs_.length() > 0) loadInitialChunkOutput(); initialChunkDefs_ = null; // sync to editor style changes editingTarget.addEditorThemeStyleChangedHandler( TextEditingTargetNotebook.this); } } }); } @Inject public void initialize(EventBus events, RMarkdownServerOperations server, ConsoleServerOperations console, Session session, UIPrefs prefs, Provider<SourceWindowManager> pSourceWindowManager) { events_ = events; server_ = server; console_ = console; session_ = session; prefs_ = prefs; pSourceWindowManager_ = pSourceWindowManager; events_.addHandler(RmdChunkOutputEvent.TYPE, this); events_.addHandler(RmdChunkOutputFinishedEvent.TYPE, this); events_.addHandler(SendToChunkConsoleEvent.TYPE, this); events_.addHandler(ChunkChangeEvent.TYPE, this); events_.addHandler(ChunkContextChangeEvent.TYPE, this); events_.addHandler(ConsolePromptEvent.TYPE, this); events_.addHandler(InterruptStatusEvent.TYPE, this); events_.addHandler(RestartStatusEvent.TYPE, this); } public void executeChunk(Scope chunk, String code, String options) { // maximize the source window if it's paired with the console pSourceWindowManager_.get().maximizeSourcePaneIfNecessary(); // get the row that ends the chunk int row = chunk.getEnd().getRow(); String chunkId = ""; String setupCrc32 = ""; if (isSetupChunkScope(chunk)) { setupCrc32 = setupCrc32_; chunkId = SETUP_CHUNK_ID; } else { // find or create a matching chunk definition ChunkDefinition chunkDef = getChunkDefAtRow(row); if (chunkDef == null) return; chunkId = chunkDef.getChunkId(); ensureSetupChunkExecuted(); } // check to see if this chunk is already in the execution queue--if so // just update the code and leave it queued for (ChunkExecQueueUnit unit: chunkExecQueue_) { if (unit.chunkId == chunkId) { unit.code = code; unit.options = options; unit.setupCrc32 = setupCrc32; return; } } // put it in the queue chunkExecQueue_.add(new ChunkExecQueueUnit(chunkId, code, options, setupCrc32)); // TODO: decorate chunk in some way so that it's clear the chunk is // queued for execution // initiate queue processing processChunkExecQueue(); } private void processChunkExecQueue() { if (chunkExecQueue_.isEmpty() || executingChunk_ != null) return; // begin chunk execution final ChunkExecQueueUnit unit = chunkExecQueue_.remove(); executingChunk_ = unit; // let the chunk widget know it's started executing if (outputWidgets_.containsKey(unit.chunkId)) outputWidgets_.get(unit.chunkId).setCodeExecuting(true); server_.setChunkConsole(docUpdateSentinel_.getId(), unit.chunkId, unit.options, true, new ServerRequestCallback<Void>() { @Override public void onResponseReceived(Void v) { console_.consoleInput(unit.code, unit.chunkId, new VoidServerRequestCallback()); // if this was the setup chunk, mark it if (!StringUtil.isNullOrEmpty(unit.setupCrc32)) writeSetupCrc32(unit.setupCrc32); } @Override public void onError(ServerError error) { // don't leave the chunk hung in execution state if (executingChunk_ != null) { ChunkOutputWidget w = outputWidgets_.get( executingChunk_.chunkId); if (w != null) w.onOutputFinished(); } // if the queue is empty, show an error; if it's not, prompt // for continuing if (chunkExecQueue_.isEmpty()) RStudioGinjector.INSTANCE.getGlobalDisplay() .showErrorMessage("Chunk Execution Failed", error.getUserMessage()); else RStudioGinjector.INSTANCE.getGlobalDisplay() .showYesNoMessage( GlobalDisplay.MSG_QUESTION, "Continue Execution?", "The following error was encountered during chunk " + "execution: \n\n" + error.getUserMessage() + "\n\n" + "Do you want to continue executing notebook chunks?", false, new Operation() { @Override public void execute() { processChunkExecQueue(); } }, null, null, "Continue", "Abort", true); } }); } @Override public void onEditorThemeStyleChanged(EditorThemeStyleChangedEvent event) { // update cached style editorStyle_ = event.getStyle(); ChunkOutputWidget.cacheEditorStyle(event.getEditorContent(), editorStyle_); for (ChunkOutputWidget widget: outputWidgets_.values()) { widget.applyCachedEditorStyle(); } } @Override public void onSendToChunkConsole(final SendToChunkConsoleEvent event) { // not for our doc if (event.getDocId() != docUpdateSentinel_.getId()) return; // create or update the chunk at the given row final ChunkDefinition chunkDef = getChunkDefAtRow(event.getRow()); String options = TextEditingTargetRMarkdownHelper.getRmdChunkOptionText( event.getScope(), docDisplay_); // have the server start recording output from this chunk server_.setChunkConsole(docUpdateSentinel_.getId(), chunkDef.getChunkId(), options, false, new ServerRequestCallback<Void>() { @Override public void onResponseReceived(Void v) { // execute the input console_.consoleInput(event.getCode(), chunkDef.getChunkId(), new VoidServerRequestCallback()); } @Override public void onError(ServerError error) { RStudioGinjector.INSTANCE.getGlobalDisplay().showErrorMessage( "Chunk Execution Error", error.getMessage()); } }); if (outputWidgets_.containsKey(chunkDef.getChunkId())) outputWidgets_.get(chunkDef.getChunkId()).setCodeExecuting(false); } @Override public void onRmdChunkOutput(RmdChunkOutputEvent event) { // ignore if not targeted at this document if (event.getOutput().getDocId() != docUpdateSentinel_.getId()) return; // mark chunk execution as finished if (executingChunk_ != null && event.getOutput().getChunkId() == executingChunk_.chunkId) executingChunk_ = null; // if nothing at all was returned, this means the chunk doesn't exist on // the server, so clean it up here. if (event.getOutput().isEmpty()) { events_.fireEvent(new ChunkChangeEvent( docUpdateSentinel_.getId(), event.getOutput().getChunkId(), 0, ChunkChangeEvent.CHANGE_REMOVE)); return; } // show output in matching chunk String chunkId = event.getOutput().getChunkId(); if (outputWidgets_.containsKey(chunkId)) { outputWidgets_.get(chunkId).showChunkOutput(event.getOutput()); } // process next chunk in execution queue processChunkExecQueue(); } @Override public void onRmdChunkOutputFinished(RmdChunkOutputFinishedEvent event) { RmdChunkOutputFinishedEvent.Data data = event.getData(); if (data.getType() == RmdChunkOutputFinishedEvent.TYPE_REPLAY && data.getRequestId() == Integer.toHexString(requestId_)) { state_ = STATE_INITIALIZED; } else if (data.getType() == RmdChunkOutputFinishedEvent.TYPE_INTERACTIVE && data.getDocId() == docUpdateSentinel_.getId()) { if (outputWidgets_.containsKey(data.getChunkId())) { outputWidgets_.get(data.getChunkId()).onOutputFinished(); } } } @Override public void onChunkChange(ChunkChangeEvent event) { if (event.getDocId() != docUpdateSentinel_.getId()) return; switch(event.getChangeType()) { case ChunkChangeEvent.CHANGE_CREATE: ChunkDefinition chunkDef = ChunkDefinition.create(event.getRow(), 1, true, event.getChunkId()); LineWidget widget = LineWidget.create( ChunkDefinition.LINE_WIDGET_TYPE, event.getRow(), elementForChunkDef(chunkDef), chunkDef); widget.setFixedWidth(true); docDisplay_.addLineWidget(widget); lineWidgets_.put(chunkDef.getChunkId(), widget); break; case ChunkChangeEvent.CHANGE_REMOVE: removeChunk(event.getChunkId()); break; } } @Override public void onChunkContextChange(ChunkContextChangeEvent event) { contextId_ = event.getContextId(); if (docDisplay_.isRendered()) { // if the doc is already up, clean it out and replace the contents removeAllChunks(); populateChunkDefs(event.getChunkDefs()); } else { // otherwise, just queue up for when we do render initialChunkDefs_ = event.getChunkDefs(); } } @Override public void onConsolePrompt(ConsolePromptEvent event) { // mark chunk execution as finished if (executingChunk_ != null) executingChunk_ = null; processChunkExecQueue(); } @Override public void onResize(ResizeEvent event) { // queue resize rather than processing it right away if we're not the // active document--in addition to being wasteful we're likely to compute // incorrect sizes if (!editingTarget_.isActiveDocument()) { queuedResize_ = event; return; } for (ChunkOutputWidget widget: outputWidgets_.values()) { widget.syncHeight(false); } } @Override public void onInterruptStatus(InterruptStatusEvent event) { if (event.getStatus() != InterruptStatusEvent.INTERRUPT_INITIATED) return; // when the user interrupts R, clear any pending chunk executions chunkExecQueue_.clear(); } @Override public void onRestartStatus(RestartStatusEvent event) { // if we had recorded a run of the setup chunk prior to restart, clear it if (event.getStatus() == RestartStatusEvent.RESTART_COMPLETED && !StringUtil.isNullOrEmpty(setupCrc32_)) { writeSetupCrc32(""); } } private void loadInitialChunkOutput() { if (state_ != STATE_NONE) return; // start listening for fold change events docDisplay_.addFoldChangeHandler(new FoldChangeEvent.Handler() { @Override public void onFoldChange(FoldChangeEvent event) { // the Ace line widget manage emits a 'changeFold' event when a line // widget is destroyed; this is our only signal that it's been // removed, so when it happens, we need to synchronize the notebook // state in this class with the state in the document. syncLineWidgets(); } }); state_ = STATE_INITIALIZING; requestId_ = nextRequestId_++; server_.refreshChunkOutput( docUpdateSentinel_.getPath(), docUpdateSentinel_.getId(), contextId_, Integer.toHexString(requestId_), new VoidServerRequestCallback()); } private Element elementForChunkDef(final ChunkDefinition def) { ChunkOutputWidget widget; final String chunkId = def.getChunkId(); if (outputWidgets_.containsKey(chunkId)) { widget = outputWidgets_.get(chunkId); } else { widget = new ChunkOutputWidget(chunkId, new CommandWithArg<Integer>() { @Override public void execute(Integer arg) { if (!outputWidgets_.containsKey(chunkId)) return; outputWidgets_.get(chunkId).getElement().getStyle().setHeight( Math.max(MIN_CHUNK_HEIGHT, Math.min(arg.intValue(), MAX_CHUNK_HEIGHT)), Unit.PX); if (!lineWidgets_.containsKey(chunkId)) return; docDisplay_.onLineWidgetChanged(lineWidgets_.get(chunkId)); } }, new Command() { @Override public void execute() { events_.fireEvent(new ChunkChangeEvent( docUpdateSentinel_.getId(), chunkId, 0, ChunkChangeEvent.CHANGE_REMOVE)); } }); widget.getElement().addClassName(ThemeStyles.INSTANCE.selectableText()); widget.getElement().getStyle().setHeight(MIN_CHUNK_HEIGHT, Unit.PX); outputWidgets_.put(def.getChunkId(), widget); } return widget.getElement(); } private ChunkDefinition getChunkDefAtRow(int row) { ChunkDefinition chunkDef; // if there is an existing widget just modify it in place LineWidget widget = docDisplay_.getLineWidgetForRow(row); if (widget != null && widget.getType().equals(ChunkDefinition.LINE_WIDGET_TYPE)) { chunkDef = widget.getData(); } // otherwise create a new one else { chunkDef = ChunkDefinition.create(row, 1, true, "c" + StringUtil.makeRandomId(12)); events_.fireEvent(new ChunkChangeEvent( docUpdateSentinel_.getId(), chunkDef.getChunkId(), row, ChunkChangeEvent.CHANGE_CREATE)); } return chunkDef; } // NOTE: this implements chunk removal locally; prefer firing a // ChunkChangeEvent if you're removing a chunk so appropriate hooks are // invoked elsewhere private void removeChunk(final String chunkId) { final LineWidget widget = lineWidgets_.get(chunkId); if (widget == null) return; ArrayList<Widget> widgets = new ArrayList<Widget>(); widgets.add(outputWidgets_.get(chunkId)); FadeOutAnimation anim = new FadeOutAnimation(widgets, new Command() { @Override public void execute() { // remove the widget from the document docDisplay_.removeLineWidget(widget); // remove it from our internal cache lineWidgets_.remove(chunkId); outputWidgets_.remove(chunkId); } }); anim.run(400); } private void removeAllChunks() { docDisplay_.removeAllLineWidgets(); lineWidgets_.clear(); outputWidgets_.clear(); } private void changeOutputMode(String mode) { docDisplay_.setShowChunkOutputInline(mode == CHUNK_OUTPUT_INLINE); // if we don't have any inline output, we're done if (lineWidgets_.size() == 0 || mode != CHUNK_OUTPUT_CONSOLE) return; // if we do have inline output, offer to clean it up RStudioGinjector.INSTANCE.getGlobalDisplay().showYesNoMessage( GlobalDisplay.MSG_QUESTION, "Remove Inline Chunk Output", "Do you want to clear all the existing chunk output from your " + "notebook?", false, new Operation() { @Override public void execute() { removeAllChunks(); } }, new Operation() { @Override public void execute() { // no action necessary } }, null, "Remove Output", "Keep Output", false); } private void populateChunkDefs(JsArray<ChunkDefinition> defs) { for (int i = 0; i < defs.length(); i++) { ChunkDefinition chunkOutput = defs.get(i); LineWidget widget = LineWidget.create( ChunkDefinition.LINE_WIDGET_TYPE, chunkOutput.getRow(), elementForChunkDef(chunkOutput), chunkOutput); lineWidgets_.put(chunkOutput.getChunkId(), widget); widget.setFixedWidth(true); docDisplay_.addLineWidget(widget); } } private void ensureSetupChunkExecuted() { // ignore if disabled if (!prefs_.autoRunSetupChunk().getValue()) return; // no reason to do work if we don't need to re-validate the setup chunk if (!validateSetupChunk_ && !StringUtil.isNullOrEmpty(setupCrc32_)) return; validateSetupChunk_ = false; // find the setup chunk JsArray<Scope> scopes = docDisplay_.getScopeTree(); for (int i = 0; i < scopes.length(); i++) { if (isSetupChunkScope(scopes.get(i))) { // extract the body of the chunk String setupCode = docDisplay_.getCode( scopes.get(i).getBodyStart(), Position.create(scopes.get(i).getEnd().getRow(), 0)); // hash the body and prefix with the virtual session ID (so all // hashes are automatically invalidated when the session changes) String crc32 = session_.getSessionInfo().getSessionId() + StringUtil.crc32(setupCode); // compare with previously known hash; if it differs, re-run the // setup chunk if (crc32 != setupCrc32_) { setupCrc32_ = crc32; executeChunk(scopes.get(i), setupCode, ""); } } } } private static boolean isSetupChunkScope(Scope scope) { if (!scope.isChunk()) return false; if (scope.getChunkLabel() == null) return false; return scope.getChunkLabel().toLowerCase() == "setup"; } private void writeSetupCrc32(String crc32) { setupCrc32_ = crc32; docUpdateSentinel_.setProperty(LAST_SETUP_CRC32, crc32); } private void syncLineWidgets() { // no work to do if we don't have any output widgets if (outputWidgets_.size() == 0) return; JsArray<LineWidget> widgets = docDisplay_.getLineWidgets(); Set<String> newChunkIds = new HashSet<String>(); for (int i = 0; i < widgets.length(); i++) { // only handle our own line widget type LineWidget widget = widgets.get(i); if (!widget.getType().equals(ChunkDefinition.LINE_WIDGET_TYPE)) continue; ChunkDefinition def = widget.getData(); if (def != null && !StringUtil.isNullOrEmpty(def.getChunkId())) { newChunkIds.add(def.getChunkId()); } } // remove all the chunk IDs that are actually in the document; any that // are remaining are stale and need to be cleaned up Set<String> oldChunkIds = new HashSet<String>(); oldChunkIds.addAll(outputWidgets_.keySet()); oldChunkIds.removeAll(newChunkIds); for (String chunkId: oldChunkIds) { lineWidgets_.remove(chunkId); outputWidgets_.remove(chunkId); } } private JsArray<ChunkDefinition> initialChunkDefs_; private HashMap<String, ChunkOutputWidget> outputWidgets_; private HashMap<String, LineWidget> lineWidgets_; private Queue<ChunkExecQueueUnit> chunkExecQueue_; private ChunkExecQueueUnit executingChunk_; private final DocDisplay docDisplay_; private final DocUpdateSentinel docUpdateSentinel_; private final TextEditingTarget editingTarget_; private Session session_; private Provider<SourceWindowManager> pSourceWindowManager_; private UIPrefs prefs_; private RMarkdownServerOperations server_; private ConsoleServerOperations console_; private EventBus events_; private Style editorStyle_; private static int nextRequestId_ = 0; private int requestId_ = 0; private String contextId_ = ""; private ResizeEvent queuedResize_ = null; private boolean validateSetupChunk_ = false; private String setupCrc32_ = ""; private int state_ = STATE_NONE; // no chunk state private final static int STATE_NONE = 0; // synchronizing chunk state from server private final static int STATE_INITIALIZING = 0; // chunk state synchronized private final static int STATE_INITIALIZED = 0; private final static int MIN_CHUNK_HEIGHT = 75; private final static int MAX_CHUNK_HEIGHT = 750; public final static String CHUNK_OUTPUT_TYPE = "chunk_output_type"; public final static String CHUNK_OUTPUT_INLINE = "inline"; public final static String CHUNK_OUTPUT_CONSOLE = "console"; private final static String LAST_SETUP_CRC32 = "last_setup_crc32"; private final static String SETUP_CHUNK_ID = "csetup_chunk"; }
package ca.corefacility.bioinformatics.irida.config.repository; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import ca.corefacility.bioinformatics.irida.model.project.ReferenceFile; import ca.corefacility.bioinformatics.irida.model.sequenceFile.SequenceFile; import ca.corefacility.bioinformatics.irida.model.workflow.analysis.AnalysisOutputFile; import ca.corefacility.bioinformatics.irida.repositories.filesystem.FilesystemSupplementedRepositoryImpl.RelativePathTranslatorListener; /** * Configuration for filesystem repositories in IRIDA */ @Configuration public class IridaApiFilesystemRepositoryConfig { private static final Logger logger = LoggerFactory.getLogger(IridaApiFilesystemRepositoryConfig.class); private @Value("${sequence.file.base.directory}") String sequenceFileBaseDirectory; private @Value("${reference.file.base.directory}") String referenceFileBaseDirectory; private @Value("${output.file.base.directory}") String outputFileBaseDirectory; @Autowired private ApplicationContext applicationContext; @Bean public RelativePathTranslatorListener relativePathTranslatorListener( final @Qualifier("referenceFileBaseDirectory") Path referenceFileBaseDirectory, final @Qualifier("sequenceFileBaseDirectory") Path sequenceFileBaseDirectory, final @Qualifier("outputFileBaseDirectory") Path outputFileBaseDirectory) { RelativePathTranslatorListener.addBaseDirectory(SequenceFile.class, sequenceFileBaseDirectory); RelativePathTranslatorListener.addBaseDirectory(ReferenceFile.class, referenceFileBaseDirectory); RelativePathTranslatorListener.addBaseDirectory(AnalysisOutputFile.class, outputFileBaseDirectory); return new RelativePathTranslatorListener(); } @Bean(name = "referenceFileBaseDirectory") public Path referenceFileBaseDirectory() throws IOException { if (applicationContext.getEnvironment().acceptsProfiles("dev", "it", "test")) { return configureDirectory(referenceFileBaseDirectory, "reference-file-dev"); } return getExistingPathOrThrow(referenceFileBaseDirectory); } @Bean(name = "sequenceFileBaseDirectory") public Path sequenceFileBaseDirectoryProd() throws IOException { if (applicationContext.getEnvironment().acceptsProfiles("dev", "it", "test")) { return configureDirectory(sequenceFileBaseDirectory, "sequence-file-dev"); } return getExistingPathOrThrow(sequenceFileBaseDirectory); } @Bean(name = "outputFileBaseDirectory") public Path outputFileBaseDirectory() throws IOException { if (applicationContext.getEnvironment().acceptsProfiles("dev", "it", "test")) { return configureDirectory(outputFileBaseDirectory, "output-file-dev"); } return getExistingPathOrThrow(outputFileBaseDirectory); } private Path getExistingPathOrThrow(String directory) { Path baseDirectory = Paths.get(directory); if (!Files.exists(baseDirectory)) { throw new IllegalStateException( String.format("Cannot continue startup; base directory [%s] does not exist!", baseDirectory.toString())); } else { logger.info(String.format( "Using specified existing directory at [%s]. The directory *will not* be removed at shutdown time.", baseDirectory.toString())); } return baseDirectory; } private Path configureDirectory(String pathName, String defaultDevPathPrefix) throws IOException { Path baseDirectory = Paths.get(pathName); if (!Files.exists(baseDirectory)) { baseDirectory = Files.createDirectories(baseDirectory); logger.info(String.format( "The directory [%s] does not exist, but it looks like you're running in a dev environment, " + "so I created a temporary location at [%s]. This directory *may* be removed at shutdown time.", pathName, baseDirectory.toString())); } return baseDirectory; } }
package de.terrestris.shogun2.service; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.doReturn; import static org.mockito.Matchers.any; import static org.mockito.Mockito.verify; import java.util.HashMap; import java.util.Map; import org.junit.Before; import org.junit.Test; import de.terrestris.shogun2.dao.GenericHibernateDao; import de.terrestris.shogun2.dao.PermissionCollectionDao; import de.terrestris.shogun2.model.SecuredPersistentObject; import de.terrestris.shogun2.model.User; import de.terrestris.shogun2.model.security.Permission; import de.terrestris.shogun2.model.security.PermissionCollection; public abstract class AbstractSecuredPersistentObjectServiceTest<E extends SecuredPersistentObject, D extends GenericHibernateDao<E, Integer>, S extends AbstractSecuredPersistentObjectService<E, D>> extends AbstractCrudServiceTest<E, D, S> { protected PermissionCollectionService<PermissionCollection, PermissionCollectionDao<PermissionCollection>> permissionCollectionService; @SuppressWarnings("unchecked") @Before @Override public void setUp() { final Class<PermissionCollectionService<PermissionCollection, PermissionCollectionDao<PermissionCollection>>> permissionCollectionServiceClass = (Class<PermissionCollectionService<PermissionCollection, PermissionCollectionDao<PermissionCollection>>>) new PermissionCollectionService<PermissionCollection, PermissionCollectionDao<PermissionCollection>>().getClass(); // see here why we are mocking this way: this.permissionCollectionService = mock(permissionCollectionServiceClass); // call parent/super, which will init mocks super.setUp(); } @Test public void addUserPermissions_shouldDoNothingWhenPassedEntityIsNull() { Permission permissions = Permission.ADMIN; User user = new User("Dummy", "Dummy", "dummy"); crudService.addUserPermissions(null, user , permissions); // be sure that nothing happened verify(permissionCollectionService, times(0)).saveOrUpdate(any(PermissionCollection.class)); verify(dao, times(0)).saveOrUpdate(any(getCrudService().getEntityClass())); assertTrue(implToTest.getUserPermissions().keySet().isEmpty()); } @Test public void addUserPermissions_shouldDoNothingWhenNoPermissionsHaveBeenPassed() { User user = new User("Dummy", "Dummy", "dummy"); crudService.addUserPermissions(implToTest, user); // be sure that nothing happened verify(permissionCollectionService, times(0)).saveOrUpdate(any(PermissionCollection.class)); verify(dao, times(0)).saveOrUpdate(implToTest); assertTrue(implToTest.getUserPermissions().keySet().isEmpty()); } @Test public void addUserPermissions_shouldCreateNewPermissionCollectionWithOneElement() { final Permission adminPermission = Permission.ADMIN; PermissionCollection permissionCollection = new PermissionCollection(); permissionCollection.getPermissions().add(adminPermission); User user = new User("Dummy", "Dummy", "dummy"); assertTrue(implToTest.getUserPermissions().keySet().isEmpty()); // mock doReturn(permissionCollection).when(permissionCollectionService).saveOrUpdate(any(PermissionCollection.class)); doNothing().when(dao).saveOrUpdate(implToTest); // invoke method to test crudService.addUserPermissions(implToTest, user, adminPermission); verify(permissionCollectionService, times(1)).saveOrUpdate(any(PermissionCollection.class)); verify(dao, times(1)).saveOrUpdate(implToTest); assertEquals(1, implToTest.getUserPermissions().keySet().size()); assertEquals(permissionCollection.getPermissions().size(), implToTest.getUserPermissions().get(user).getPermissions().size()); } @Test public void addUserPermissions_shouldCreateNewPermissionCollectionWithMultipleElements() { final Permission readPermission = Permission.READ; final Permission writePermission = Permission.WRITE; final Permission deletePermission = Permission.DELETE; PermissionCollection permissionCollection = new PermissionCollection(); permissionCollection.getPermissions().add(readPermission); permissionCollection.getPermissions().add(writePermission); permissionCollection.getPermissions().add(deletePermission); User user = new User("Dummy", "Dummy", "dummy"); assertTrue(implToTest.getUserPermissions().keySet().isEmpty()); // mock doReturn(permissionCollection).when(permissionCollectionService).saveOrUpdate(any(PermissionCollection.class)); doNothing().when(dao).saveOrUpdate(implToTest); // invoke method to test crudService.addUserPermissions(implToTest, user, readPermission, writePermission, deletePermission); verify(permissionCollectionService, times(1)).saveOrUpdate(any(PermissionCollection.class)); verify(dao, times(1)).saveOrUpdate(implToTest); assertEquals(1, implToTest.getUserPermissions().keySet().size()); assertEquals(permissionCollection.getPermissions().size(), implToTest.getUserPermissions().get(user).getPermissions().size()); } @Test public void addUserPermissions_shouldAddPermissionToExistingPermissionCollection() { final Permission existingPermission = Permission.READ; final Permission newPermission = Permission.WRITE; PermissionCollection existingPermissionCollection = new PermissionCollection(); PermissionCollection newPermissionCollection = new PermissionCollection(); existingPermissionCollection.getPermissions().add(existingPermission); newPermissionCollection.getPermissions().add(existingPermission); newPermissionCollection.getPermissions().add(newPermission); User user = new User("Dummy", "Dummy", "dummy"); Map<User, PermissionCollection> existingUserPermissionsMap = new HashMap<User, PermissionCollection>(); existingUserPermissionsMap.put(user, existingPermissionCollection); implToTest.setUserPermissions(existingUserPermissionsMap); assertEquals(1, implToTest.getUserPermissions().keySet().size()); assertEquals(existingPermissionCollection.getPermissions().size(), implToTest.getUserPermissions().get(user).getPermissions().size()); // mock doReturn(newPermissionCollection).when(permissionCollectionService).saveOrUpdate(any(PermissionCollection.class)); // invoke method to test crudService.addUserPermissions(implToTest, user, newPermission); verify(permissionCollectionService, times(1)).saveOrUpdate(any(PermissionCollection.class)); verify(dao, times(0)).saveOrUpdate(implToTest); assertEquals(1, implToTest.getUserPermissions().keySet().size()); assertEquals(existingPermissionCollection.getPermissions().size(), implToTest.getUserPermissions().get(user).getPermissions().size()); } @Test public void removeUserPermissions_shouldDoNothingWhenPassedEntityIsNull() { Permission permissions = Permission.ADMIN; User user = new User("Dummy", "Dummy", "dummy"); crudService.removeUserPermissions(null, user , permissions); // be sure that nothing happened verify(permissionCollectionService, times(0)).saveOrUpdate(any(PermissionCollection.class)); verify(dao, times(0)).saveOrUpdate(any(getCrudService().getEntityClass())); assertTrue(implToTest.getUserPermissions().keySet().isEmpty()); } @Test public void removeUserPermissions_shouldDoNothingWhenNoPermissionsHaveBeenPassed() { User user = new User("Dummy", "Dummy", "dummy"); crudService.removeUserPermissions(implToTest, user); // be sure that nothing happened verify(permissionCollectionService, times(0)).saveOrUpdate(any(PermissionCollection.class)); verify(dao, times(0)).saveOrUpdate(implToTest); assertTrue(implToTest.getUserPermissions().keySet().isEmpty()); } @Test public void removeUserPermissions_shouldDoNothingWhenNoPermissionsExist() { final Permission writePermission = Permission.WRITE; User user = new User("Dummy", "Dummy", "dummy"); crudService.removeUserPermissions(implToTest, user, writePermission); // be sure that nothing happened verify(permissionCollectionService, times(0)).saveOrUpdate(any(PermissionCollection.class)); verify(dao, times(0)).saveOrUpdate(implToTest); assertEquals(0, implToTest.getUserPermissions().keySet().size()); } @Test public void removeUserPermissions_shouldRemoveExistingPermission() { final Permission readPermission = Permission.READ; final Permission writePermission = Permission.WRITE; PermissionCollection existingPermissionCollection = new PermissionCollection(); existingPermissionCollection.getPermissions().add(readPermission); existingPermissionCollection.getPermissions().add(writePermission); User user = new User("Dummy", "Dummy", "dummy"); Map<User, PermissionCollection> existingUserPermissionsMap = new HashMap<User, PermissionCollection>(); existingUserPermissionsMap.put(user, existingPermissionCollection); implToTest.setUserPermissions(existingUserPermissionsMap); crudService.removeUserPermissions(implToTest, user, writePermission); verify(permissionCollectionService, times(1)).saveOrUpdate(any(PermissionCollection.class)); verify(dao, times(0)).saveOrUpdate(implToTest); assertEquals(1, implToTest.getUserPermissions().keySet().size()); } }
package com.welovecoding.netbeans.plugin.editorconfig.processor.operation; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.prefs.BackingStoreException; import java.util.prefs.Preferences; import javax.swing.text.BadLocationException; import javax.swing.text.StyledDocument; import org.junit.After; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import org.netbeans.api.editor.settings.SimpleValueNames; import org.netbeans.modules.editor.indent.api.Reformat; import org.netbeans.modules.editor.indent.spi.CodeStylePreferences; import org.openide.cookies.EditorCookie; import org.openide.filesystems.FileUtil; import org.openide.loaders.DataObject; import org.openide.text.NbDocument; import org.openide.util.Exceptions; import org.openide.util.Utilities; public class IndentSizeOperationTest { private DataObject dataObject; private File file; @Before public void setUp() { String codeWith4SpacesIndent = "(function(){" + System.lineSeparator(); codeWith4SpacesIndent += " alert('Hello World!');" + System.lineSeparator(); codeWith4SpacesIndent += "})();"; try { file = File.createTempFile(this.getClass().getSimpleName(), ".js"); Path path = Paths.get(Utilities.toURI(file)); Files.write(path, codeWith4SpacesIndent.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE); dataObject = DataObject.find(FileUtil.toFileObject(file)); } catch (IOException ex) { Exceptions.printStackTrace(ex); } } @After public void tearDown() { file.delete(); } public IndentSizeOperationTest() { } @Test public void itDetectsIfChangesAreNeeded() throws IOException, BadLocationException, BackingStoreException { int indentWidth = 2; String codeWith2SpacesIndent = "(function(){" + System.lineSeparator(); codeWith2SpacesIndent += " alert('Hello World!');" + System.lineSeparator(); codeWith2SpacesIndent += "})();"; Preferences codeStyle = CodeStylePreferences.get( dataObject.getPrimaryFile(), dataObject.getPrimaryFile().getMIMEType() ).getPreferences(); // Check indent size before change int indentSizeBefore = codeStyle.getInt(SimpleValueNames.INDENT_SHIFT_WIDTH, -1); // XXX 4 is returned if org-netbeans-modules-csl-api is added // assertEquals(-1, indentSizeBefore); // Change indent size within an operation boolean changeNeeded = new IndentSizeOperation(dataObject.getPrimaryFile()).changeIndentSize(indentWidth); assertEquals(true, changeNeeded); // Update code style reference codeStyle = CodeStylePreferences.get( dataObject.getPrimaryFile(), dataObject.getPrimaryFile().getMIMEType() ).getPreferences(); // Save the new style codeStyle.flush(); // Check that new style has been applied int indentSizeAfter = codeStyle.getInt(SimpleValueNames.INDENT_SHIFT_WIDTH, -1); assertEquals(indentWidth, indentSizeAfter); // Save indent size EditorCookie cookie = dataObject.getLookup().lookup(EditorCookie.class); cookie.open(); StyledDocument document = cookie.openDocument(); NbDocument.runAtomicAsUser(document, () -> { try { // Save test file cookie.saveDocument(); // Reformat test file Reformat reformat = Reformat.get(document); reformat.lock(); try { reformat.reformat(0, document.getLength()); } catch (BadLocationException ex) { Exceptions.printStackTrace(ex); } finally { reformat.unlock(); try { // Save formatted document cookie.saveDocument(); System.out.println("Content saved:"); System.out.println(document.getText(0, document.getLength())); } catch (IOException | BadLocationException ex) { Exceptions.printStackTrace(ex); } } } catch (IOException ex) { Exceptions.printStackTrace(ex); } }); // TODO: This check fails // assertEquals(codeWith2SpacesIndent, dataObject.getPrimaryFile().asText()); } }
package org.cytoscape.internal.actions.welcomescreen; import java.awt.Color; import java.awt.GridLayout; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.io.IOException; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import javax.imageio.ImageIO; import javax.swing.DefaultComboBoxModel; import javax.swing.ImageIcon; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.border.LineBorder; import org.cytoscape.application.CyApplicationConfiguration; import org.cytoscape.application.swing.CyAction; import org.cytoscape.datasource.DataSource; import org.cytoscape.datasource.DataSourceManager; import org.cytoscape.io.DataCategory; import org.cytoscape.model.CyNetwork; import org.cytoscape.task.NetworkTaskFactory; import org.cytoscape.task.creation.ImportNetworksTaskFactory; import org.cytoscape.work.AbstractTask; import org.cytoscape.work.TaskFactory; import org.cytoscape.work.TaskIterator; import org.cytoscape.work.TaskManager; import org.cytoscape.work.TaskMonitor; import org.osgi.framework.BundleContext; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CreateNewNetworkPanel extends JPanel implements ActionListener { private static final long serialVersionUID = -8750909701276867389L; private static final Logger logger = LoggerFactory.getLogger(CreateNewNetworkPanel.class); private static final String VIEW_THRESHOLD = "viewThreshold"; private static final int DEF_VIEW_THRESHOLD = 3000; private static final String ICON_OPEN = "images/Icons/net_file_import_small.png"; private static final String ICON_DATABASE = "images/Icons/net_db_import_small.png"; private JLabel loadNetwork; private JLabel fromDB; private JLabel fromWebService; private JComboBox networkList; private JCheckBox layout; private final TaskManager guiTaskManager; private Window parent; private final BundleContext bc; private final ImportNetworksTaskFactory importNetworkFromURLTF; private final TaskFactory importNetworkFileTF; private final NetworkTaskFactory createViewTaskFactory; private final DataSourceManager dsManager; private final Map<String, String> dataSourceMap; private final int viewThreshold; private boolean firstSelection = false; CreateNewNetworkPanel(Window parent, final BundleContext bc, final TaskManager guiTaskManager, final TaskFactory importNetworkFileTF, final ImportNetworksTaskFactory loadTF, final NetworkTaskFactory createViewTaskFactory, final CyApplicationConfiguration config, final DataSourceManager dsManager, final Properties props) { this.parent = parent; this.bc = bc; this.importNetworkFromURLTF = loadTF; this.createViewTaskFactory = createViewTaskFactory; this.importNetworkFileTF = importNetworkFileTF; this.guiTaskManager = guiTaskManager; this.dsManager = dsManager; this.viewThreshold = getViewThreshold(props); this.dataSourceMap = new HashMap<String, String>(); this.networkList = new JComboBox(); setFromDataSource(); initComponents(); // Enable combo box listener here to avoid unnecessary reaction. this.networkList.addActionListener(this); } private void setFromDataSource() { DefaultComboBoxModel theModel = new DefaultComboBoxModel(); // Extract the URL entries final Collection<DataSource> dataSources = dsManager.getDataSources(DataCategory.NETWORK); final SortedSet<String> labelSet = new TreeSet<String>(); if (dataSources != null) { for (DataSource ds : dataSources) { String link = null; link = ds.getLocation().toString(); final String sourceName = ds.getName(); final String provider = ds.getProvider(); final String sourceLabel = provider + ":" + sourceName; dataSourceMap.put(sourceLabel, link); labelSet.add(sourceLabel); } } theModel.addElement("Select a network ..."); for (final String label : labelSet) theModel.addElement(label); this.networkList.setModel(theModel); } private void initComponents() { BufferedImage openIconImg = null; BufferedImage databaseIconImg = null; try { openIconImg = ImageIO.read(WelcomeScreenDialog.class.getClassLoader().getResource(ICON_OPEN)); databaseIconImg = ImageIO.read(WelcomeScreenDialog.class.getClassLoader().getResource(ICON_DATABASE)); } catch (IOException e) { logger.error("Could not load icons", e); } ImageIcon openIcon = new ImageIcon(openIconImg); ImageIcon databaseIcon = new ImageIcon(databaseIconImg); this.layout = new JCheckBox(); layout.setText("Apply default layout"); layout.setToolTipText("Note: This option may take minutes to finish for large networks!"); this.loadNetwork = new JLabel("From file..."); this.loadNetwork.setIcon(openIcon); loadNetwork.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent ev) { // Load network from file. parent.dispose(); guiTaskManager.execute(importNetworkFileTF); } }); this.setBorder(new LineBorder(new Color(0, 0, 0, 0), 10)); this.fromDB = new JLabel("From Reference Network Data:"); this.fromDB.setIcon(databaseIcon); this.fromWebService = new JLabel("From Public Web Service..."); this.fromWebService.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent ev) { // Load network from web service. parent.dispose(); try { execute(bc); } catch (InvalidSyntaxException e) { logger.error("Could not execute the action", e); } } }); this.setLayout(new GridLayout(5, 1)); this.add(loadNetwork); this.add(fromWebService); this.add(fromDB); this.add(networkList); this.add(layout); } private void loadNetwork() throws URISyntaxException, MalformedURLException { // Get selected file from the combo box final Object file = networkList.getSelectedItem(); if (file == null) return; if (!dataSourceMap.containsKey(file)) return; final URL url = new URL(dataSourceMap.get(file)); parent.dispose(); // TODO REFACTOR!!!!!!!!!!!!!!!!!!! guiTaskManager.execute(new TaskFactory() { @Override public TaskIterator createTaskIterator() { return new TaskIterator(2, new CreateNetworkViewTask(url, importNetworkFromURLTF, createViewTaskFactory)); } }); } private int getViewThreshold(final Properties props) { final String vts = props.getProperty(VIEW_THRESHOLD); int threshold; try { threshold = Integer.parseInt(vts); } catch (Exception e) { threshold = DEF_VIEW_THRESHOLD; } return threshold; } private final class CreateNetworkViewTask extends AbstractTask { private final ImportNetworksTaskFactory loadNetworkFileTF; private final NetworkTaskFactory createViewTaskFactory; private final URL url; public CreateNetworkViewTask(final URL url, final ImportNetworksTaskFactory loadNetworkFileTF, final NetworkTaskFactory createViewTaskFactory) { this.loadNetworkFileTF = loadNetworkFileTF; this.createViewTaskFactory = createViewTaskFactory; this.url = url; } @Override public void run(TaskMonitor taskMonitor) throws Exception { taskMonitor.setTitle("Loading network..."); taskMonitor.setStatusMessage("Loading network. Please wait..."); taskMonitor.setProgress(0.01d); final Set<CyNetwork> networks = this.loadNetworkFileTF.loadCyNetworks(url); taskMonitor.setProgress(1.0d); /* if (networks.size() != 0) { taskMonitor.setTitle("Creating View for the new network"); CyNetwork network = networks.iterator().next(); final int numGraphObjects = network.getNodeCount() + network.getEdgeCount(); if (numGraphObjects >= viewThreshold) { // Force to create view. createViewTaskFactory.setNetwork(network); taskMonitor.setStatusMessage("Loading done. Creating view for the network..."); insertTasksAfterCurrentTask(createViewTaskFactory.createTaskIterator()); } } */ } } @Override public void actionPerformed(ActionEvent e) { try { loadNetwork(); } catch (Exception ex) { logger.error("Could not load network.", ex); } } /** * Due to its dependency, we need to import this service dynamically. * * @throws InvalidSyntaxException */ private void execute(BundleContext bc) throws InvalidSyntaxException { final ServiceReference[] actions = bc.getAllServiceReferences("org.cytoscape.application.swing.CyAction", "(id=showImportNetworkFromWebServiceDialogAction)"); if (actions == null || actions.length != 1) { logger.error("Could not find action"); return; } final ServiceReference ref = actions[0]; final CyAction action = (CyAction) bc.getService(ref); action.actionPerformed(null); } }
package edu.northwestern.bioinformatics.studycalendar.web.schedule; import edu.northwestern.bioinformatics.studycalendar.dao.ScheduledActivityDao; import edu.northwestern.bioinformatics.studycalendar.dao.ScheduledCalendarDao; import edu.northwestern.bioinformatics.studycalendar.domain.Role; import edu.northwestern.bioinformatics.studycalendar.domain.ScheduledActivity; import edu.northwestern.bioinformatics.studycalendar.domain.ScheduledActivityMode; import edu.northwestern.bioinformatics.studycalendar.domain.ScheduledStudySegment; import edu.northwestern.bioinformatics.studycalendar.service.ActivityService; import edu.northwestern.bioinformatics.studycalendar.tools.FormatTools; import edu.northwestern.bioinformatics.studycalendar.utils.breadcrumbs.BreadcrumbContext; import edu.northwestern.bioinformatics.studycalendar.utils.breadcrumbs.DefaultCrumb; import edu.northwestern.bioinformatics.studycalendar.utils.editors.ControlledVocabularyEditor; import edu.northwestern.bioinformatics.studycalendar.web.PscSimpleFormController; import edu.northwestern.bioinformatics.studycalendar.web.accesscontrol.AccessControl; import gov.nih.nci.cabig.ctms.editors.GridIdentifiableDaoBasedEditor; import org.springframework.beans.propertyeditors.StringTrimmerEditor; import org.springframework.validation.BindException; import org.springframework.web.bind.ServletRequestDataBinder; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.TreeMap; /** * @author Rhett Sutphin */ @AccessControl(roles = Role.SUBJECT_COORDINATOR) public class ScheduleActivityController extends PscSimpleFormController { private ScheduledCalendarDao scheduledCalendarDao; private ScheduledActivityDao scheduledActivityDao; private ActivityService activityService; public ScheduleActivityController() { setBindOnNewForm(true); setCommandClass(ScheduleActivityCommand.class); setCrumb(new Crumb()); } protected Object formBackingObject(HttpServletRequest request) throws Exception { return new ScheduleActivityCommand(scheduledCalendarDao); } protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception { super.initBinder(request, binder); binder.registerCustomEditor(Date.class, getControllerTools().getDateEditor(true)); binder.registerCustomEditor(ScheduledActivity.class, "event", new GridIdentifiableDaoBasedEditor(scheduledActivityDao)); binder.registerCustomEditor(ScheduledActivityMode.class, "newMode", new ControlledVocabularyEditor(ScheduledActivityMode.class, true)); binder.registerCustomEditor(String.class, new StringTrimmerEditor(true)); } protected ModelAndView showForm( HttpServletRequest request, HttpServletResponse response, BindException errors ) throws Exception { Map<String, Object> model = errors.getModel(); ScheduleActivityCommand command = (ScheduleActivityCommand) errors.getTarget(); getControllerTools().addHierarchyToModel(command.getEvent(), model); Map<String,String> uriMap = new TreeMap<String,String>(); Collection<List<String>> uriList = activityService.createActivityUriList(command.getEvent().getActivity()).values(); Iterator iterator = uriList.iterator(); while(iterator.hasNext()) { List<String> values = (List)(iterator.next()); uriMap.put(values.get(0),values.get(1)); } model.put("uri",uriMap); // model.put("modes", ScheduledActivityMode.values()); model.put("modes", command.getEventSpecificMode()); return new ModelAndView("schedule/event", model); } protected ModelAndView onSubmit(Object oCommand) throws Exception { ScheduleActivityCommand command = (ScheduleActivityCommand) oCommand; command.apply(); Map<String, Object> model = new HashMap<String, Object>(); ScheduledStudySegment studySegment = command.getEvent().getScheduledStudySegment(); model.put("studySegment", studySegment.getId()); model.put("calendar", studySegment.getScheduledCalendar().getId()); return new ModelAndView("redirectToSchedule", model); } ////// CONFIGURATION public void setScheduledCalendarDao(ScheduledCalendarDao scheduledCalendarDao) { this.scheduledCalendarDao = scheduledCalendarDao; } public void setScheduledActivityDao(ScheduledActivityDao scheduledActivityDao) { this.scheduledActivityDao = scheduledActivityDao; } public void setActivityService(ActivityService activityService) { this.activityService = activityService; } private class Crumb extends DefaultCrumb { public String getName(BreadcrumbContext context) { ScheduledActivity evt = context.getScheduledActivity(); return new StringBuilder() .append(evt.getActivity().getName()) .append(" on ") .append(FormatTools.formatDate(evt.getActualDate())) .toString(); } public Map<String, String> getParameters(BreadcrumbContext context) { return createParameters("event", context.getScheduledActivity().getId().toString()); } } }
package org.elasticsearch.xpack.watcher.execution; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.message.ParameterizedMessage; import org.apache.logging.log4j.util.Supplier; import org.elasticsearch.xpack.core.watcher.trigger.TriggerEvent; import java.util.function.Consumer; import static java.util.stream.StreamSupport.stream; public class AsyncTriggerEventConsumer implements Consumer<Iterable<TriggerEvent>> { private static final Logger logger = LogManager.getLogger(AsyncTriggerEventConsumer.class); private final ExecutionService executionService; public AsyncTriggerEventConsumer(ExecutionService executionService) { this.executionService = executionService; } @Override public void accept(Iterable<TriggerEvent> events) { try { executionService.processEventsAsync(events); } catch (Exception e) { logger.error( (Supplier<?>) () -> new ParameterizedMessage( "failed to process triggered events [{}]", (Object) stream(events.spliterator(), false).toArray(size -> new TriggerEvent[size])), e); } } }
import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.geom.Ellipse2D; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.SwingUtilities; public class Ball extends JComponent implements Runnable { private Point center; private double radius; private Point velocity; private static final int UPDATE_RATE = 30; // Number of refresh per second public Ball(Point c) { center = c; // Random velocity velocity = new Point(1, 1); radius = 20; repaint(); } // Draw a Circle public void paintComponent(Graphics g) { super.paintComponent(g); //Convert to Java2D Object Graphics2D g2 = (Graphics2D) g; // Create the circle Ellipse2D circle = new Ellipse2D.Double(); circle.setFrameFromCenter(radius, radius, 2*radius, 2*radius); this.setBounds((int) center.getX(), (int) center.getY(), (int) (radius*4), (int) (radius*4)); //System.out.println(center); // Draw it g2.draw(circle); //g2.fill(circle); }// end paintComponent protected void move() { center.x += velocity.x; center.y += velocity.y; } protected void collisions() { JFrame frame = (JFrame) SwingUtilities.getRoot(this); Dimension d = frame.getContentPane().getSize(); // Check top if (0 > (center.getY() + 0*radius)) { velocity.y = Math.abs(velocity.y); // Velocity to DOWN // Fix position center.y = (int) (0+0*radius); } // Check bottom else if (d.getHeight() < (center.getY() + 2*radius) ) { velocity.y = -1 * Math.abs(velocity.y); // Velocity to UP // Fix position center.y = (int) (d.getHeight() - 2*radius); } // Check left if (0 > (center.getX() + 0*radius)) { velocity.x = Math.abs(velocity.x); // Velocity to RIGHT // Fix position center.x = (int) (0+0*radius); } // Check right else if (d.getWidth() < (center.getX() + 2*radius) ) { velocity.x = -1 * Math.abs(velocity.x); // Velocity to LEFT // Fix position center.x = (int) (d.getWidth() - 2*radius); } } @Override public void run() { // TODO Auto-generated method stub while (true) { move(); collisions(); // Refresh the display repaint(); // Callback paintComponent() // Delay for timing control and give other threads a chance try { Thread.sleep(1000 / UPDATE_RATE); // milliseconds } catch (InterruptedException ex) { } } } }
package co.smartreceipts.android.model.converters; import android.content.Context; import android.support.annotation.NonNull; import android.text.TextUtils; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import co.smartreceipts.android.R; import co.smartreceipts.android.model.Distance; import co.smartreceipts.android.model.Receipt; import co.smartreceipts.android.model.WBCurrency; import co.smartreceipts.android.model.factory.PriceBuilderFactory; import co.smartreceipts.android.model.factory.ReceiptBuilderFactory; import co.smartreceipts.android.persistence.Preferences; /** * An implementation of the {@link co.smartreceipts.android.model.converters.ModelConverter} contract, which * allows us to print {@link co.smartreceipts.android.model.Distance} values in a receipt table. Distances * will be summed up based of a given day. * * @author williambaumann */ public class DistanceToReceiptsConverter implements ModelConverter<Distance, Receipt> { private final Context mContext; private final String mDateSeparator; /** * Convenience constructor for this class. * * @param context - the current application {@link android.content.Context} * @param preferences - the user's {@link co.smartreceipts.android.persistence.Preferences} */ public DistanceToReceiptsConverter(@NonNull Context context, @NonNull Preferences preferences) { this(context, preferences.getDateSeparator()); } /** * Default constructor for this class. * * @param context - the current application {@link android.content.Context} * @param dateSeparator - the user's preferred date separator (e.g. "/") */ public DistanceToReceiptsConverter(@NonNull Context context, @NonNull String dateSeparator) { mContext = context.getApplicationContext(); mDateSeparator = dateSeparator; } @Override @NonNull public List<Receipt> convert(@NonNull List<Distance> distances) { final int size = distances.size(); final HashMap<String, List<Distance>> distancesPerDay = new HashMap<String, List<Distance>>(); // First, let's separate our distances to find what occurs each day for (int i = 0; i < size; i++) { final Distance distance = distances.get(i); final String formattedDate = distance.getFormattedDate(mContext, mDateSeparator); if (distancesPerDay.containsKey(formattedDate)) { distancesPerDay.get(formattedDate).add(distance); } else { final List<Distance> distanceList = new ArrayList<Distance>(); distanceList.add(distance); distancesPerDay.put(formattedDate, distanceList); } } final List<Receipt> receipts = new ArrayList<Receipt>(distancesPerDay.keySet().size()); for (Map.Entry<String, List<Distance>> entry : distancesPerDay.entrySet()) { if (!entry.getValue().isEmpty()) { receipts.add(generateReceipt(entry.getKey(), entry.getValue())); } } return receipts; } @NonNull private Receipt generateReceipt(@NonNull String formattedDay, @NonNull List<Distance> distancesThisDay) { if (distancesThisDay.isEmpty()) { throw new IllegalArgumentException("distancesThisDay must not be empty"); } // Set up default values for everything final Distance distance0 = distancesThisDay.get(0); final ReceiptBuilderFactory factory = new ReceiptBuilderFactory(-1); // Randomize the id final ArrayList<String> names = new ArrayList<String>(); for (int i = 0; i < distancesThisDay.size(); i++) { final Distance distance = distancesThisDay.get(i); if (!names.contains(distance.getLocation())) { names.add(distance.getLocation()); } } factory.setName(TextUtils.join("; ", names)); factory.setDate(distance0.getDate()); factory.setImage(null); factory.setIsExpenseable(true); factory.setTimeZone(distance0.getTimeZone()); factory.setCategory(mContext.getString(R.string.distance)); factory.setCurrency(distance0.getPrice().getCurrency()); factory.setPrice(new PriceBuilderFactory().setPriceables(distancesThisDay).build()); return factory.build(); } }
/** * A program to carry on conversations with a human user. */ import java.util.Scanner; public class Magpie { /** * Gives a response to a user statement * * @param statement - the user statement * @return a response based on the rules given */ public String getResponse(String statement) { if (statement.length() == 0) { return "Say something, please."; } if (findKeyword(statement, "no") >= 0) { return "Why so negative?"; } if (findKeyword(statement, "mother") >= 0 || findKeyword(statement, "father") >= 0 || findKeyword(statement, "sister") >= 0 || findKeyword(statement, "brother") >= 0) { return "Tell me more about your family."; } /** <<< Add your code for Activity 2 here >>> **/ if (findKeyword(statement, "dog") >= 0 || findKeyword(statement, "cat") >= 0) { return "Tell me more about your pets."; } if (findKeyword(statement, "Haas") >= 0) { return "He sounds like a good teacher."; } if (statement.trim().length() == 0) { return "Say something, please."; } /*** * Responses that Transform Statements */ if (findKeyword(statement, "I want to") >= 0) { return transformIWantToStatement(statement); } if (findKeyword(statement, "I want") >= 0) { return transformIWantStatement(statement); } if (findKeyword(statement, "you") != -1 && findKeyword(statement, "you") < findKeyword(statement, "me")) { return transformYouMeStatement(statement); } if (findKeyword(statement, "I") != -1 && findKeyword(statement, "I") < findKeyword(statement, "you")) { return transformIYouStatement(statement); } return getRandomResponse(); } private String getRandomResponse() { /** <<< Add your code for Activity 2 here >>> **/ String[] responses = { "Interesting, tell me more.", "Hmmm.", "Do you really think so?", "You don't say.", "How does that make you feel?" }; return responses[(int) Math.floor(Math.random() * responses.length)]; } /** * runs the method: findKeyword passing in a default value of 0 */ private int findKeyword(String statement, String goal) { return findKeyword (statement, goal, 0); } /** * This method returns the index of a given goal in a longer string. * * @param statement the string to search * @param goal the string to search for * @param startPos the character of the string to begin the search at * @return the index of the first occurrence of goal in statement or -1 if it's not found */ private int findKeyword(String statement, String goal, int startPos) { /** convert to lower case **/ statement = statement.toLowerCase(); goal = goal.toLowerCase(); String letters = "abcdefghijklmnopqrstuvwxyz"; for (int tentativeIndex=0; tentativeIndex <= statement.length()-goal.length(); tentativeIndex++) { if (statement.substring(tentativeIndex, tentativeIndex+goal.length()).equals(goal)) { // Is there a letter before it? boolean isLetterBefore = false; if (tentativeIndex > 0) isLetterBefore = letters.contains(statement.substring(tentativeIndex-1, tentativeIndex)); // Is there a letter after the end? String charAfter; boolean isLetterAfter = false; if (tentativeIndex + goal.length() < statement.length()) { charAfter = statement.substring(tentativeIndex + goal.length(), tentativeIndex + goal.length() + 1); isLetterAfter = letters.contains(charAfter); } if (!isLetterBefore && !isLetterAfter) return tentativeIndex; } } return -1; } private String transformIWantToStatement(String statement) { // Remove the final period, if there is one statement = statement.trim(); String lastChar = statement.substring(statement.length() - 1); if (lastChar.equals(".")) { statement = statement.substring(0, statement.length() - 1); } int psn = findKeyword(statement, "I want to", 0); String restOfStatement = statement.substring(psn + 9).trim(); return "What would it mean to " + restOfStatement + "?"; } private String transformIWantStatement(String statement) { // <<< Complete the code >>> return statement.replace("I want", "Would you really be happy if you had") + "?"; } private String transformYouMeStatement(String statement) { // Remove the final period, if there is one statement = statement.trim(); String lastChar = statement.substring(statement.length() - 1); if (lastChar.equals(".")) { statement = statement.substring(0, statement.length() - 1); } int psnOfYou = findKeyword(statement, "you", 0); int psnOfMe = findKeyword(statement, "me", psnOfYou + 3); String restOfStatement = statement.substring(psnOfYou + 3, psnOfMe).trim(); return "What makes you think that I " + restOfStatement + " you?"; } private String transformIYouStatement(String statement) { return statement.replace("you", "me").replace("I", "Why do you") + "?"; } /** * Create a Magpie, give it user input, and print its replies. */ public static void main(String[] args) { Magpie maggie = new Magpie(); System.out.println("Hello, let's talk."); Scanner in = new Scanner (System.in); String statement = in.nextLine(); while (!statement.equals("q")) { System.out.println(maggie.getResponse(statement)); statement = in.nextLine(); } } }
package com.worldspotlightapp.android.maincontroller.modules.videosmodule; import android.content.Context; import android.location.Address; import android.location.Geocoder; import android.os.Debug; import android.text.TextUtils; import android.util.Log; import com.google.android.gms.maps.model.LatLng; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.services.youtube.YouTube; import com.google.api.services.youtube.model.Channel; import com.google.api.services.youtube.model.ChannelListResponse; import com.google.api.services.youtube.model.SearchListResponse; import com.google.api.services.youtube.model.SearchResult; import com.parse.FindCallback; import com.parse.GetCallback; import com.parse.Parse; import com.parse.ParseException; import com.parse.ParseObject; import com.parse.ParseQuery; import com.parse.SaveCallback; import com.squareup.picasso.Picasso; import com.worldspotlightapp.android.R; import com.worldspotlightapp.android.maincontroller.Preferences; import com.worldspotlightapp.android.maincontroller.Preferences.LongId; import com.worldspotlightapp.android.maincontroller.database.VideoDataLayer; import com.worldspotlightapp.android.maincontroller.modules.ParseResponse; import com.worldspotlightapp.android.maincontroller.modules.videosmodule.response.VideosModuleAddAVideoResponse; import com.worldspotlightapp.android.maincontroller.modules.videosmodule.response.VideosModuleAuthorResponse; import com.worldspotlightapp.android.maincontroller.modules.videosmodule.response.VideosModuleHashTagsListByVideoResponse; import com.worldspotlightapp.android.maincontroller.modules.videosmodule.response.VideosModuleHashTagsListResponse; import com.worldspotlightapp.android.maincontroller.modules.videosmodule.response.VideosModuleLikedVideosListResponse; import com.worldspotlightapp.android.maincontroller.modules.videosmodule.response.VideosModuleUpdateVideosListResponse; import com.worldspotlightapp.android.maincontroller.modules.videosmodule.response.VideosModuleVideoResponse; import com.worldspotlightapp.android.maincontroller.modules.videosmodule.response.VideosModuleVideosListResponse; import com.worldspotlightapp.android.model.Author; import com.worldspotlightapp.android.model.HashTag; import com.worldspotlightapp.android.model.Like; import com.worldspotlightapp.android.model.Video; import com.worldspotlightapp.android.ui.MainApplication; import com.worldspotlightapp.android.utils.DebugOptions; import com.worldspotlightapp.android.utils.Secret; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Observer; import java.util.Scanner; import java.util.concurrent.ExecutorService; public class VideosModuleObserver extends AbstractVideosModuleObservable { private static final String TAG = "VideosModuleObserver"; private static final String REGEX_INPUT_BOUNDARY_BEGINNING = "\\A"; private static final String JSON_FILE_RESULTS_KEY = "results"; private static final int MAX_PARSE_QUERY_RESULT = 500; /** * The last time the videos list is updated. The value of this variable * matches with the last time the videos.json was updated. * */ private static final Long LAST_VIDEOS_LIST_UPDATED_TIME = 1442435566000L; //Some keys for the Parse Object private static final String PARSE_COLUMN_CREATED_AT = "createdAt"; private static final String PARSE_COLUMN_UPDATED_AT = "updatedAt"; /** * The maximum number of results expected */ private static final int MAX_PARSE_QUERY_RESULT_FOR_HASHTAG = 1000; // The list of all the videos private List<Video> mVideosList; // The list of all the hashTags private List<HashTag> mHashTagsList; private Context mContext; private ExecutorService mExecutorService; private VideoDataLayer mVideoDataLayer; private Preferences mPreferences; // Boolean used to detect if the hashtags private boolean mUpdateHashTagsListForAllVideosPending; public VideosModuleObserver(Context context, ExecutorService executorService, VideoDataLayer videoDataLayer, Preferences preferences) { mContext = context; mExecutorService = executorService; mVideoDataLayer = videoDataLayer; mPreferences = preferences; } @Override public void requestAllVideos(final Observer observer) { Log.v(TAG, "All the videos requested from the observer " + observer); // Register the observer addObserver(observer); Log.v(TAG, "The number of observers after add is " + countObservers()); // if the video list was retrieved before, don't do anything if (mVideosList != null) { Log.v(TAG, "The list of video is has been cached. Return it"); ParseResponse parseResponse = new ParseResponse.Builder(null).build(); VideosModuleVideosListResponse videosModuleVideosListResponse = new VideosModuleVideosListResponse(parseResponse, mVideosList, false); setChanged(); notifyObservers(videosModuleVideosListResponse); return; } // The list of videos that should be added into the database final List<Video> videosListToBeAddedToTheDatabase = new ArrayList<Video>(); // 1. Retrieve the list of the videos from the database mVideosList = mVideoDataLayer.getListAllVideos(); Log.v(TAG, mVideosList.size() + " retrieved from local database"); // If the list of videos is empty, retrieve the list of elements from row file // and save them into the database if (mVideosList.isEmpty()) { Log.v(TAG, "The list of the video in the database is empty. Retrieve the ones saved" + "in the local file"); mVideosList = retrieveVideosListFromRawFile(); // If only debug data is used, save the current debug data into the database // Then notifiy the observer and finally, finish. if (!DebugOptions.shouldUseProductionData()) { videosListToBeAddedToTheDatabase.addAll(mVideosList); saveVideosListToDatabase(videosListToBeAddedToTheDatabase); //Remove the list of videos to be added to the database since they are already // added videosListToBeAddedToTheDatabase.clear(); } } // Notify to the observable about the new data ParseResponse parseResponse = new ParseResponse.Builder(null).build(); boolean areExtraVideos = false; VideosModuleVideosListResponse videosModuleVideosListResponse = new VideosModuleVideosListResponse(parseResponse, mVideosList, areExtraVideos); setChanged(); notifyObservers(videosModuleVideosListResponse); // If it is not using production data, it is good enough to use just the data from the // database or from the raw file. if (!DebugOptions.shouldUseProductionData()) { return; } // 2. Retrieve the rest of the videos from the parse server // Callback prepared to retrieve all the videos from the parse server final FindCallback<Video> updateVideoIndexFromParseServerCallback = new FindCallback<Video>() { @Override public void done(List<Video> videosList, ParseException e) { boolean areExtraVideos = true; ParseResponse parseResponse = new ParseResponse.Builder(e).build(); Log.v(TAG, "List of videos received from the parse server"); if (!parseResponse.isError()) { Log.v(TAG, "The list of videos has been correctly retrieved " + videosList.size()); // Add all the content to the general videos list so it will be available next time mVideosList.addAll(videosList); // Save the list to be added to the database later videosListToBeAddedToTheDatabase.addAll(videosList); VideosModuleVideosListResponse videosModuleVideosListResponse = new VideosModuleVideosListResponse(parseResponse, videosList, areExtraVideos); setChanged(); notifyObservers(videosModuleVideosListResponse); // If parse has returned the max number of results, that means there are more // video available. So, request more videos if (videosList.size() == MAX_PARSE_QUERY_RESULT) { Log.v(TAG, MAX_PARSE_QUERY_RESULT + " videos retrieved. Requesting for more"); requestVideoToParse(mVideosList.size(), this); } else { Log.v(TAG, "All the videos has been retrieved. Save the needed to the database"); saveVideosListToDatabase(videosListToBeAddedToTheDatabase); // Ask parse to update the list of videos SyncVideoInfo(observer); // Print the possible hash tags only not in production if (DebugOptions.shouldPrintKeywords()) { printPossibleHashTagsFromTheVideo(); } // Update the hashtags for all the videos if (DebugOptions.shouldUpdateHashTagsForAllTheVideos()) { // Update automatically the hashtags if it is not ready if (mHashTagsList == null) { mUpdateHashTagsListForAllVideosPending = true; } else { updateHashTagsListForAllVideos(); } } } } else { Log.e(TAG, "Error retrieving data from backend"); VideosModuleVideosListResponse videosModuleVideosListResponse = new VideosModuleVideosListResponse(parseResponse, null, areExtraVideos); setChanged(); notifyObservers(videosModuleVideosListResponse); } } }; requestVideoToParse(mVideosList.size(), updateVideoIndexFromParseServerCallback); } @Override public void requestLikedVideosInfo(Observer observer, List<Like> likesList) { // Register the observer addObserver(observer); List<Video> likedVideos = new ArrayList<Video>(); for (Like like : likesList) { likedVideos.add(getVideoInfo(like.getVideoId())); } ParseResponse parseResponse = new ParseResponse.Builder(null).build(); VideosModuleLikedVideosListResponse videosModuleLikedVideosListResponse = new VideosModuleLikedVideosListResponse(parseResponse, likedVideos); setChanged(); notifyObservers(videosModuleLikedVideosListResponse); } private void requestVideoToParse(int initialPosition, FindCallback<Video> findCallback) { Log.v(TAG, "Requesting videos to parse. The initial position is " + initialPosition); //Retrieve element from background ParseQuery<Video> query = ParseQuery.getQuery(Video.class); query.setSkip(initialPosition); query.orderByAscending(PARSE_COLUMN_CREATED_AT); query.setLimit(MAX_PARSE_QUERY_RESULT); query.findInBackground(findCallback); } /** * Request a list of video udpated since the last time */ @Override public void SyncVideoInfo(Observer observer) { addObserver(observer); // Check the last updated time final Long lastUpdatedTime = mPreferences.contains(LongId.VIDEOS_LIST_LAST_UPDATE_TIME) ? mPreferences.get(LongId.VIDEOS_LIST_LAST_UPDATE_TIME) : LAST_VIDEOS_LIST_UPDATED_TIME; ParseQuery<Video> requestVideosUpdatedSinceLastTimeQuery = ParseQuery.getQuery(Video.class); requestVideosUpdatedSinceLastTimeQuery.whereGreaterThan(PARSE_COLUMN_UPDATED_AT, new Date(lastUpdatedTime)); requestVideosUpdatedSinceLastTimeQuery.setLimit(MAX_PARSE_QUERY_RESULT); requestVideosUpdatedSinceLastTimeQuery.findInBackground(new FindCallback<Video>() { @Override public void done(List<Video> videosListToBeUpdated, ParseException e) { ParseResponse parseResponse = new ParseResponse.Builder(e).build(); if (!parseResponse.isError()) { Log.v(TAG, "List of video to be updated received " + videosListToBeUpdated.size()); // Update the last updated time mPreferences.set(LongId.VIDEOS_LIST_LAST_UPDATE_TIME, new Date().getTime()); // Update the internal list for (Video video : videosListToBeUpdated) { // Only do it if the video list contains it if (mVideosList.contains(video)) { Video videoToBeUpdated = mVideosList.get(mVideosList.indexOf(video)); videoToBeUpdated.update(video); } // Update the database mVideoDataLayer.updateVideo(video); } // Notify only if the list of updated if (videosListToBeUpdated.size() > 0) { VideosModuleUpdateVideosListResponse videosModuleUpdateVideosListResponse = new VideosModuleUpdateVideosListResponse(parseResponse, videosListToBeUpdated); setChanged(); notifyObservers(videosModuleUpdateVideosListResponse); } } else { Log.v(TAG, "Error retrieving the list of videos updated"); // TODO: create retry policy } } }); } @Override public Video getVideoInfo(String videoObjectId) { // Get the video directly from the list of videos in the database // The database could be not ready at beginning Video videoInfo = mVideoDataLayer.getVideoDetails(videoObjectId); if (videoInfo != null) { return videoInfo; } Log.w(TAG, "Video not found in the database. Looking it in the temporal memory"); // The video info is null, try to get the data from the memory list if (mVideosList != null) { for (Video video: mVideosList) { if (video.getObjectId().equals(videoObjectId)) { Log.v(TAG, "Video found in the temporal memory " + video); return video; } } } return null; } @Override public void searchByKeyword(Observer observer, String keyword) { // Register the observer addObserver(observer); if (mVideosList == null) { Log.e(TAG, "The list of video is empty"); ParseResponse parseResponse = new ParseResponse.Builder(null).build(); // In case of error, do not update the existent list of videos boolean areExtraVideos = true; VideosModuleVideosListResponse videosModuleVideosListResponse = new VideosModuleVideosListResponse(parseResponse, mVideosList, areExtraVideos); setChanged(); notifyObservers(videosModuleVideosListResponse); return; } if (keyword == null || keyword.isEmpty()) { Log.e(TAG, "The keyword is empty or null"); ParseResponse parseResponse = new ParseResponse.Builder(null).build(); // In case of error, do not update the existent list of videos boolean areExtraVideos = true; VideosModuleVideosListResponse videosModuleVideosListResponse = new VideosModuleVideosListResponse(parseResponse, mVideosList, areExtraVideos); setChanged(); notifyObservers(videosModuleVideosListResponse); return; } List<Video> resultVideosList = new ArrayList<Video>(); keyword = keyword.toLowerCase(); for (Video video : mVideosList) { // By passing all the characters to lower case, we are looking for the // content of the string, instead of looking for Strings which has the // same characters in mayus and minus. // Looking for the title String title = video.getTitle(); String description = video.getDescription(); String city = video.getCity(); String country = video.getCountry(); ArrayList<String> hashTagsList = video.getHashTags(); if (!TextUtils.isEmpty(title) && (title.toLowerCase().contains(keyword) || keyword.contains(title))) { resultVideosList.add(video); } else if (!TextUtils.isEmpty(description) && (description.toLowerCase().contains(keyword) || keyword.contains(description))) { resultVideosList.add(video); } else if (!TextUtils.isEmpty(city)&& (city.toLowerCase().contains(keyword) || keyword.contains(city))) { resultVideosList.add(video); } else if (!TextUtils.isEmpty(country) && (country.toLowerCase().contains(keyword) || keyword.contains(country))) { resultVideosList.add(video); // For other fields } else { // HashTags for (String hashTag : hashTagsList) { if (hashTag.toLowerCase().contains(keyword) || keyword.contains(hashTag.toLowerCase())) { resultVideosList.add(video); break; } } } } Log.v(TAG, "Number of videos find " + resultVideosList.size()); ParseResponse parseResponse = new ParseResponse.Builder(null).build(); boolean areExtraVideos = false; VideosModuleVideosListResponse videosModuleVideosListResponse = new VideosModuleVideosListResponse(parseResponse, resultVideosList, areExtraVideos); setChanged(); notifyObservers(videosModuleVideosListResponse); } @Override public void requestAuthorInfo(Observer observer, final String videoId) { addObserver(observer); mExecutorService.execute(new RetrieveAuthorInfoRunnable(videoId, new RequestAuthorInfoCallback() { @Override public void done(Author author) { // In case that the author has some problems, just don't do anything if (author != null) { ParseResponse parseResponse = new ParseResponse.Builder(null).build(); VideosModuleAuthorResponse videosModuleAuthorResponse = new VideosModuleAuthorResponse(parseResponse, author, videoId); setChanged(); notifyObservers(videosModuleAuthorResponse); } } })); } @Override public void addAVideo(final String videoId, final LatLng videoLocation, final ArrayList<String> hashTagsList) { Log.v(TAG, "Adding a video with id " + videoId + ", location " + videoLocation); boolean videoAlreadyExists = false; Video videoToBeAdded = new Video(videoId); // Check if the video already existed if (mVideosList != null && !mVideosList.isEmpty()) { // If the video already exists if (mVideosList.contains(videoToBeAdded)) { videoAlreadyExists = true; } // Check the database } else { if (mVideoDataLayer.hasVideoByVideoId(videoId)) { videoAlreadyExists = true; } } // The video already exists if (videoAlreadyExists) { Log.w(TAG, "The video with video id " + videoId + " already exists."); ParseResponse parseResponse = new ParseResponse.Builder(null).statusCode(ParseResponse.ERROR_ADDING_AN_EXISTING_VIDEO).build(); VideosModuleAddAVideoResponse videosModuleAddAVideoResponse = new VideosModuleAddAVideoResponse(parseResponse, null); setChanged(); notifyObservers(videosModuleAddAVideoResponse); return; } // Get the information about the video // Get the title and description mExecutorService.execute(new RetrieveTitleDescriptionRunnable(videoId, new RequestTitleAndDescriptionCallback() { @Override public void done(String title, String description) { addAVideo(videoId, title, description, videoLocation, hashTagsList); } })); } @Override public void requestHashTagsListForAVideo(Observer observer, final String videoObjectId) { Log.v(TAG, "Requesting the hash tags list for the video " + videoObjectId); // Add the observer addObserver(observer); ParseQuery<Video> query = ParseQuery.getQuery(Video.class); query.getInBackground(videoObjectId, new GetCallback<Video>() { @Override public void done(Video video, ParseException e) { ParseResponse parseResponse = new ParseResponse.Builder(e).build(); Log.v(TAG, "Parse response received " + parseResponse); if (!parseResponse.isError()) { Log.v(TAG, "Object correctly retrieved " + video); VideosModuleHashTagsListByVideoResponse videosModuleHashTagsListByVideoResponse = new VideosModuleHashTagsListByVideoResponse(parseResponse, video.getHashTags(), videoObjectId); setChanged(); notifyObservers(videosModuleHashTagsListByVideoResponse); } else { Log.e(TAG, "Error retrieving the video details"); VideosModuleHashTagsListByVideoResponse videosModuleHashTagsListByVideoResponse = new VideosModuleHashTagsListByVideoResponse(parseResponse, null, videoObjectId); setChanged(); notifyObservers(videosModuleHashTagsListByVideoResponse); } } }); } @Override public void requestAllHashTags(Observer observer) { // Register the observer addObserver(observer); // Return cached list if any if (mHashTagsList != null) { ParseResponse parseResponse = new ParseResponse.Builder(null).build(); VideosModuleHashTagsListResponse videosModuleHashTagsListResponse = new VideosModuleHashTagsListResponse(parseResponse, mHashTagsList); setChanged(); notifyObservers(videosModuleHashTagsListResponse); return; } //Retrieve element from background ParseQuery<HashTag> query = ParseQuery.getQuery(HashTag.class); query.orderByAscending(HashTag.PARSE_TABLE_COLUMN_HASH_TAG); query.setLimit(MAX_PARSE_QUERY_RESULT_FOR_HASHTAG); query.findInBackground(new FindCallback<HashTag>() { @Override public void done(List<HashTag> hashTagsList, ParseException e) { ParseResponse parseResponse = new ParseResponse.Builder(e).build(); if (!parseResponse.isError()) { mHashTagsList = hashTagsList; VideosModuleHashTagsListResponse videosModuleHashTagsListResponse = new VideosModuleHashTagsListResponse(parseResponse, mHashTagsList); setChanged(); notifyObservers(videosModuleHashTagsListResponse); // Update the list of hashtags in the videos. if (DebugOptions.shouldUpdateHashTagsForAllTheVideos() && mUpdateHashTagsListForAllVideosPending) { updateHashTagsListForAllVideos(); } } else { VideosModuleHashTagsListResponse videosModuleHashTagsListResponse = new VideosModuleHashTagsListResponse(parseResponse, null); setChanged(); notifyObservers(videosModuleHashTagsListResponse); } } }); } @Override public void updateHashTagsList(Observer observer, final String videoObjectId, ArrayList<String> hashTagsList) { if (TextUtils.isEmpty(videoObjectId)) { Log.e(TAG, "The video object id cannot be null"); return; } // Update the hashtag for the database final Video video = mVideoDataLayer.getVideoDetails(videoObjectId); // The video shouldn't be null if (video == null) { Log.e(TAG, "The video with id " + videoObjectId + " does not exists in the databse."); return; } video.setHashTags(hashTagsList); mVideoDataLayer.updateVideo(video); // Update the hashtag for the backend video.saveInBackground(new SaveCallback() { @Override public void done(ParseException e) { ParseResponse parseResponse = new ParseResponse.Builder(e).build(); if (!parseResponse.isError()) { Log.v(TAG, "Video " + video + " saved correctly"); } else { Log.e(TAG, "Error saving the video " + video); } } }); } /** * Special method used internally to add specific hash tags. This is useful when the hashtag is added automatically * * @param videoObjectId * The object id of the video where the hash tag should be added * @param hashTagToBeAdded * The hashtag to be added */ private void addHashTag(String videoObjectId, String hashTagToBeAdded) { if (TextUtils.isEmpty(videoObjectId)) { Log.e(TAG, "The video object id cannot be null"); return; } // Update the hashtag for the database final Video video = mVideoDataLayer.getVideoDetails(videoObjectId); // The video shouldn't be null if (video == null) { Log.e(TAG, "The video with id " + videoObjectId + " does not exists in the databse."); return; } ArrayList<String> hashTags = video.getHashTags(); if (hashTags.contains(hashTagToBeAdded)) { Log.v(TAG, "The hash tag already exists for this video"); return; } hashTags.add(hashTagToBeAdded); video.setHashTags(hashTags); mVideoDataLayer.updateVideo(video); // Update the hashtag for the backend video.saveInBackground(new SaveCallback() { @Override public void done(ParseException e) { ParseResponse parseResponse = new ParseResponse.Builder(e).build(); if (!parseResponse.isError()) { Log.v(TAG, "Video " + video + " saved correctly"); } else { Log.e(TAG, "Error saving the video " + video); } } }); } /** * Add a video into the backend. This method might not be running in the main thread * @param videoId * The id of the video to be added * @param title * The title of the video to be added * @param description * The description of the video to be added. Since this is retrieved from YouTube Data API, it does not contain * all the information * @param videoLocation * The location where the video was filmed * @param hashTagsList * The list of hash tags */ private void addAVideo(String videoId, String title, String description, LatLng videoLocation, ArrayList<String> hashTagsList) { Log.v(TAG, "Adding a video with id " + videoId + ", Title: " + title + ", description " + description + ", location " + videoLocation); String city = ""; String country = ""; // Get the city and the country Geocoder geocoder = new Geocoder(mContext, Locale.getDefault()); List<Address> addressesList = null; try { addressesList = geocoder.getFromLocation(videoLocation.latitude, videoLocation.longitude, 1); } catch (IOException ioException) { // Service not available Log.e(TAG, "Error getting the city from the geocoder. Service not available", ioException); } catch (IllegalArgumentException illegalArgumentException) { // Invalid latitude and longitude Log.e(TAG, "Error getting the city form the geocoder. The latitude or/and the longitude are" + "not correct. " + videoLocation.latitude + ", " + videoLocation.longitude + ".", illegalArgumentException); } // If there was not address retrieved if (addressesList != null && !addressesList.isEmpty()) { Address address = addressesList.get(0); Log.v(TAG, "Address found " + address); Log.v(TAG, "The locality is " + address.getLocality()); Log.v(TAG, "The country is " + address.getCountryName()); // Set the city if exists String locality = address.getLocality(); if (locality != null) { city = locality; } // Set the country if exists String countryName = address.getCountryName(); if (countryName != null) { country = countryName; } } addAVideo(videoId, title, description, videoLocation, city, country, hashTagsList); } /** * Method used to save a video to the backend. The video Id shouldn't exist before. * @param videoId * The id of the video in YouTube * @param title * The title of the video * @param description * The description of the video * @param videoLocation * The location where the video was filmed * @param city * The city where the video was filmed * @param country * The country where the video was filmed. * @param hashTagsList * The list of hash tags */ private void addAVideo(final String videoId, String title, String description, LatLng videoLocation, String city, String country, final ArrayList<String> hashTagsList) { Log.v(TAG, "Adding a video with id " + videoId + ", Title: " + title + ", description " + description + ", location " + videoLocation + ", city " + city + ", country " + country); final Video video = new Video(title, description, videoId, city, country, videoLocation, hashTagsList); video.saveInBackground(new SaveCallback() { @Override public void done(ParseException e) { ParseResponse parseResponse = new ParseResponse.Builder(e).build(); if (!parseResponse.isError()) { Log.v(TAG, "Video " + video + " added correctly to the backend"); // Update the video list mVideosList.add(video); // The database should be updated according to the backend. This is because there could be several user adding // videos at the same time. So, the order the video was added are different. Since we based on the number of existence // videos in the database to update the list of videos, it is more safe do it asking directly to Parse. VideosModuleAddAVideoResponse videosModuleAddAVideoResponse = new VideosModuleAddAVideoResponse(parseResponse, video); setChanged(); notifyObservers(videosModuleAddAVideoResponse); } else { Log.e(TAG, "Error adding video " + video + " to the backend. ", e); VideosModuleAddAVideoResponse videosModuleAddAVideoResponse = new VideosModuleAddAVideoResponse(parseResponse, null); setChanged(); notifyObservers(videosModuleAddAVideoResponse); } } }); } /** * Interface created to be passed to {@link RetrieveAuthorInfoRunnable} to inform when the author * info is ready */ private interface RequestTitleAndDescriptionCallback { void done(String title, String description); } private class RetrieveTitleDescriptionRunnable implements Runnable { private String mVideoId; private RequestTitleAndDescriptionCallback mRequestTitleAndDescriptionCallback; public RetrieveTitleDescriptionRunnable(String videoId, RequestTitleAndDescriptionCallback requestTitleAndDescriptionCallback) { mVideoId = videoId; mRequestTitleAndDescriptionCallback = requestTitleAndDescriptionCallback; } @Override public void run() { // Set empty title and description as default String title = ""; String description = ""; YouTube youtube = new YouTube.Builder(new NetHttpTransport(), new JacksonFactory(), new HttpRequestInitializer() { @Override public void initialize(HttpRequest httpRequest) throws IOException { } }).setApplicationName(mContext.getString(R.string.app_name)).build(); try { YouTube.Search.List query = youtube.search().list("id,snippet"); query.setKey(Secret.YOUTUBE_DATA_API_KEY); query.setType("video"); query.setFields("items(id,snippet/title,snippet/description)"); query.setQ("v=" + mVideoId); query.setType("video"); SearchListResponse response = query.execute(); List<SearchResult> results = response.getItems(); Log.v(TAG, "List of search results retrieved. " + results.size()); for (final SearchResult searchResult : results) { Log.v(TAG, searchResult.toPrettyString()); if (!searchResult.getId().getVideoId().equals(mVideoId)) { continue; } // Get the title and description title = searchResult.getSnippet().getTitle(); description = searchResult.getSnippet().getDescription(); } } catch (IOException e) { Log.e(TAG, "Could not search video data: ", e); } mRequestTitleAndDescriptionCallback.done(title, description); } } /** * Interface created to be passed to {@link RetrieveAuthorInfoRunnable} to inform when the author * info is ready */ private interface RequestAuthorInfoCallback { void done(Author author); } private class RetrieveAuthorInfoRunnable implements Runnable { private String mVideoId; private RequestAuthorInfoCallback mRequestAuthorInfoCallback; public RetrieveAuthorInfoRunnable(String videoId, RequestAuthorInfoCallback requestAuthorInfoCallback) { mVideoId = videoId; mRequestAuthorInfoCallback = requestAuthorInfoCallback; } @Override public void run() { Author author = null; YouTube youtube = new YouTube.Builder(new NetHttpTransport(), new JacksonFactory(), new HttpRequestInitializer() { @Override public void initialize(HttpRequest httpRequest) throws IOException { } }).setApplicationName(mContext.getString(R.string.app_name)).build(); try { YouTube.Search.List query = youtube.search().list("id,snippet"); query.setKey(Secret.YOUTUBE_DATA_API_KEY); query.setType("video"); query.setFields("items(id/videoId,snippet/channelId,snippet/channelTitle)"); query.setQ("v=" + mVideoId); query.setType("video"); SearchListResponse response = query.execute(); List<SearchResult> results = response.getItems(); Log.v(TAG, "List of search results retrieved. " + results.size()); for (final SearchResult searchResult : results) { Log.v(TAG, searchResult.toPrettyString()); if (!searchResult.getId().getVideoId().equals(mVideoId)) { continue; } // Get the channel id YouTube.Channels.List queryChannel = youtube.channels().list("id, snippet"); queryChannel.setKey(Secret.YOUTUBE_DATA_API_KEY); queryChannel.setFields("items(id,snippet/thumbnails/medium,snippet/title)"); queryChannel.setId(searchResult.getSnippet().getChannelId()); ChannelListResponse channelListResponse = queryChannel.execute(); List<Channel> channelsList = channelListResponse.getItems(); Log.v(TAG, "List of channels retrieved " + channelsList); for (final Channel channel : channelsList) { Log.v(TAG, channel.toPrettyString()); author = new Author(channel.getId(), channel.getSnippet().getTitle(), channel.getSnippet().getThumbnails().getMedium().getUrl()); } } } catch (IOException e) { Log.e(TAG, "Could not search video data: ", e); } mRequestAuthorInfoCallback.done(author); } } private List<Video> retrieveVideosListFromRawFile() { InputStream inputStream = DebugOptions.shouldUseProductionData()? mContext.getResources().openRawResource(R.raw.videos): mContext.getResources().openRawResource(R.raw.videos_debug); List<Video> videosList = new ArrayList<Video>(); String json = new Scanner(inputStream).useDelimiter(REGEX_INPUT_BOUNDARY_BEGINNING).next(); // TODO: Replace the follow code with gson try { JSONObject jsonObject = new JSONObject(json); JSONArray jsonArray = jsonObject.getJSONArray(JSON_FILE_RESULTS_KEY); for (int i = 0; i < jsonArray.length(); i++) { JSONObject videoJsonObject = jsonArray.getJSONObject(i); try { Video video = new Video(videoJsonObject); videosList.add(video); } catch (JSONException jsonException) { Log.e(TAG, "Error create a vide from json object " + jsonObject, jsonException); } } } catch (JSONException e) { Log.e(TAG, "Error reading video file", e); } Log.v(TAG, "The size of the video retrieved from json file is " + videosList.size()); return videosList; } /** * Save the list of the videos into the database * @param videosList */ private void saveVideosListToDatabase(List<Video> videosList) { // Execute it in another thread mExecutorService.execute(new SaveVideosListToDatabaseRunnable(videosList)); } private class SaveVideosListToDatabaseRunnable implements Runnable { // The own copy of the video list. private List<Video> mVideosList; public SaveVideosListToDatabaseRunnable(List<Video> videosList) { super(); // Since we are running in another thread, it is more safe using the copy // of the data instead of using the pointer to the list this.mVideosList = new ArrayList<Video>(videosList); } @Override public void run() { mVideoDataLayer.insertListDataToDatabase(mVideosList); } } /** * Print all the possible hashtags from the list of the actual videos */ private void printPossibleHashTagsFromTheVideo() { // Get the list of hashtags HashMap<String, Integer> hashTagsMap = new HashMap<String, Integer>(); for (Video video: mVideosList) { // Get the title String title = video.getTitle(); if (!TextUtils.isEmpty(title)) { String[] titles = title.split(" "); addWordsToHashMap(hashTagsMap, titles); } // Ge the description String description = video.getDescription(); if (!TextUtils.isEmpty(description)) { String[] descriptions = description.split(" "); addWordsToHashMap(hashTagsMap, descriptions); } } // Sort the content Map<String, Integer> hashTagsMapSorted = sortHashTagsMap(hashTagsMap); // Print the content printMap(hashTagsMapSorted); } private void addWordsToHashMap(HashMap<String, Integer> hashTagsMap, String[] words) { for (String word : words) { String lowerCaseWord = word.toLowerCase(); if (hashTagsMap.containsKey(lowerCaseWord)) { Integer counter = hashTagsMap.get(lowerCaseWord); counter++; hashTagsMap.put(lowerCaseWord, counter); } else { hashTagsMap.put(lowerCaseWord, 1); } } } private Map<String, Integer> sortHashTagsMap(HashMap<String, Integer> hashTagsMap) { // Convert map to list List<Map.Entry<String, Integer>> list = new LinkedList<Map.Entry<String, Integer>>(hashTagsMap.entrySet()); // Sort list with comparator, to compare the map values Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() { public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { return (o2.getValue()).compareTo(o1.getValue()); } }); // Convert sorted mpa back to a map Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>(); for (Iterator<Map.Entry<String, Integer>> it = list.iterator(); it.hasNext();) { Map.Entry<String, Integer> entry = it.next(); sortedMap.put(entry.getKey(), entry.getValue()); } return sortedMap; } /** * Print the content of a Map, with key and value * @param map * The content of the map to be printed */ private void printMap(Map<String, Integer> map) { for (Map.Entry<String, Integer> entry : map.entrySet()) { Log.v(TAG, entry.getKey() + ":" + entry.getValue()); } } /** * Update the hash tags list for all the videos. * Precondition * - The list of the videos cannot be empty * - The list of the hash tags cannot be empty */ private void updateHashTagsListForAllVideos() { if (mHashTagsList == null) { Log.e(TAG, "Trying to update the hash tags list for all the videos but the hash tags list is empty"); return; } if (mVideosList == null || mVideosList.isEmpty()) { Log.e(TAG, "Trying to update the hash tags list for all the videos but the videos list is empty"); return; } // Check for each video for (Video video :mVideosList) { Log.d(TAG, " Log.d(TAG, "Checking for the video " + video); for (HashTag hashTag : mHashTagsList) { Log.d(TAG, "Checking for the hashtag " + hashTag.getName()); Log.d(TAG, " if (video.shouldAddHashTag(hashTag)) { Log.d(TAG, "The hashtag should be added"); addHashTag(video.getObjectId(), hashTag.getName()); } } } mUpdateHashTagsListForAllVideosPending = false; } }
package sesim; import java.util.*; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.function.BiConsumer; import java.util.logging.Level; import java.util.logging.Logger; import org.json.JSONArray; import org.json.JSONObject; /** * @desc Echchange class * @author 7u83 */ public class Exchange { ConcurrentLinkedQueue<Order> order_queue = new ConcurrentLinkedQueue(); private double money_df = 10000; /** * Set the number of decimals used with money * * @param n number of decimals */ public void setMoneyDecimals(int n) { money_df = Math.pow(10, n); } private double shares_df = 1; /** * Set the number of decimals for shares * * @param n number of decimals */ public void setSharesDecimals(int n) { shares_df = Math.pow(10, n); } public double roundToDecimals(double val, double f) { return Math.floor(val * f) / f; } public double roundShares(double shares) { return roundToDecimals(shares, shares_df); } public double roundMoney(double money) { return roundToDecimals(money, money_df); } /** * Definition of order types */ public enum OrderType { BUYLIMIT, SELLLIMIT, STOPLOSS, STOPBUY, BUY, SELL } IDGenerator account_id = new IDGenerator(); //public static Timer timer = new Timer(); public Scheduler timer; // = new Scheduler(); public ArrayList<AutoTraderInterface> traders; public interface AccountListener { public void accountUpdated(Account a, Order o); } public interface OrderListener { public void orderUpdated(Order o); } HashMap<Integer, OHLCData> ohlc_data = new HashMap<>(); public OHLCData buildOHLCData(int timeFrame) { OHLCData data = new OHLCData(timeFrame); if (this.quoteHistory == null) { return data; } Iterator<Quote> it = quoteHistory.iterator(); while (it.hasNext()) { Quote q = it.next(); data.realTimeAdd(q.time, (float) q.price, (float) q.volume); } return data; } public void injectMoney() { accounts.forEach(new BiConsumer() { @Override public void accept(Object t, Object u) { Account a = (Account) u; a.money += 20000.0; } }); } public void pointZero() { accounts.forEach(new BiConsumer() { @Override public void accept(Object t, Object u) { Account a = (Account) u; a.money = 20000.0; } }); } public OHLCData getOHLCdata(Integer timeFrame) { OHLCData data; //=new OHLCData(timeFrame); data = ohlc_data.get(timeFrame); if (data == null) { synchronized (executor) { data = this.buildOHLCData(timeFrame); ohlc_data.put(timeFrame, data); } } return data; /* try { data = ohlc_data.get(timeFrame); } catch (Exception e) { data = null; } if (data == null) { data = buildOHLCData(timeFrame); } */ } void updateOHLCData(Quote q) { Iterator<OHLCData> it = ohlc_data.values().iterator(); while (it.hasNext()) { OHLCData data = it.next(); data.realTimeAdd(q.time, (float) q.price, (float) q.volume); } } /** * Implements a trading account */ public class Account implements Comparable { private AccountListener listener = null; private final double id; private double shares; private double money; protected AutoTraderInterface owner; private final ConcurrentHashMap<Long, Order> orders; @Override public int compareTo(Object a) { Account account = (Account) a; return this.id - account.id < 0 ? -1 : 1; } Account(double money, double shares) { id = (random.nextDouble() + (account_id.getNext())); orders = new ConcurrentHashMap(); this.money = money; this.shares = shares; } public double getID() { return id; } public double getShares() { return shares; } public double getMoney() { return money; } public AutoTraderInterface getOwner() { return owner; } public ConcurrentHashMap<Long, Order> getOrders() { return orders; } public void setListener(AccountListener al) { this.listener = al; } public void update(Order o) { if (listener == null) { return; } listener.accountUpdated(this, o); } } public void createTraders(JSONArray traderdefs) { for (int i = 0; i < traderdefs.length(); i++) { JSONObject o = traderdefs.getJSONObject(i); } // this.traders.add(randt); // randt.setName("Bob"); // randt.start(); } // private final ConcurrentHashMap<Double, Account> accounts = new ConcurrentHashMap<>(); private ConcurrentHashMap<Double, Account> accounts; public double createAccount(double money, double shares) { Account a = new Account(money, shares); accounts.put(a.id, a); return a.id; } public enum OrderStatus { OPEN, PARTIALLY_EXECUTED, CLOSED, CANCELED } class OrderComparator implements Comparator<Order> { OrderType type; OrderComparator(OrderType type) { this.type = type; } @Override public int compare(Order left, Order right) { double d; switch (this.type) { case BUYLIMIT: case STOPBUY: case BUY: d = right.limit - left.limit; break; case SELLLIMIT: case STOPLOSS: case SELL: d = left.limit - right.limit; break; default: d = 0; } if (d != 0) { return d > 0 ? 1 : -1; } d = right.initial_volume - left.initial_volume; if (d != 0) { return d > 0 ? 1 : -1; } if (left.id < right.id) { return -1; } if (left.id > right.id) { return 1; } return 0; } } HashMap<OrderType, SortedSet<Order>> order_books; IDGenerator order_id = new IDGenerator(); public class Order { OrderStatus status; OrderType type; private double limit; private double volume; private final double initial_volume; private final long id; private final long created; private final Account account; double cost; Order(Account account, OrderType type, double volume, double limit) { id = order_id.getNext(); this.account = account; this.type = type; this.limit = roundMoney(limit); this.volume = roundShares(volume); this.initial_volume = this.volume; this.created = timer.currentTimeMillis(); this.status = OrderStatus.OPEN; this.cost = 0; } public long getID() { return id; } public double getVolume() { return volume; } public double getLimit() { return limit; } public OrderType getType() { return type; } public double getExecuted() { return initial_volume - volume; } public double getInitialVolume() { return initial_volume; } public double getCost() { return cost; } public double getAvaragePrice() { double e = getExecuted(); if (e <= 0) { return -1; } return cost / e; } public Account getAccount() { return account; } public OrderStatus getOrderStatus() { return status; } public long getCreated() { return created; } } /** * Histrory of quotes */ public TreeSet<Quote> quoteHistory; // = new TreeSet<>(); final void initExchange() { buy_orders = 0; sell_orders = 0; timer = new Scheduler(); // timer = new Scheduler(); // random = new Random(12); random = new Random(); quoteHistory = new TreeSet(); accounts = new ConcurrentHashMap<>(); traders = new ArrayList(); num_trades = 0; this.ohlc_data = new HashMap(); // Create order books order_books = new HashMap(); for (OrderType type : OrderType.values()) { order_books.put(type, new TreeSet(new OrderComparator(type))); } } /** * Constructor */ public Exchange() { qrlist = (new CopyOnWriteArrayList<>()); initExchange(); executor.start(); } public class Statistics { public long trades; public long orders; void reset() { trades = 0; } Statistics() { } }; Statistics statistics; long num_trades = 0; long num_orders = 0; public Statistics getStatistics() { Statistics s = new Statistics(); s.trades = num_trades; s.orders = num_orders; return s; } class Executor extends Thread { @Override public void run() { synchronized (this) { try { while (true) { this.wait(); Order o; while (null != (o = order_queue.poll())) { addOrderToBook(o); Account a = o.account; a.orders.put(o.id, o); a.update(o); executeOrders(); } updateBookReceivers(OrderType.SELLLIMIT); updateBookReceivers(OrderType.BUYLIMIT); } } catch (InterruptedException ex) { Logger.getLogger(Exchange.class.getName()).log(Level.SEVERE, null, ex); } } } } final Executor executor = new Executor(); /** * Start the exchange */ public void start() { timer.start(); } public void reset() { initExchange(); } public void terminate() { timer.terminate(); } /* class BidBook extends TreeSet { TreeSet t = new TreeSet(); boolean hallo() { t.comparator(); return true; } } */ public SortedSet<Quote> getQuoteHistory(long start) { Quote s = new Quote(); s.time = start * 1000; s.id = 0; TreeSet<Quote> result = new TreeSet<>(); result.addAll(this.quoteHistory.tailSet(s)); return result; } public final String CFG_MONEY_DECIMALS = "money_decimals"; public final String CFG_SHARES_DECIMALS = "shares_decimals"; public void putConfig(JSONObject cfg) { try { this.setMoneyDecimals(cfg.getInt(CFG_MONEY_DECIMALS)); this.setSharesDecimals(cfg.getInt(CFG_SHARES_DECIMALS)); } catch (Exception e) { } } public Double getBestPrice() { System.out.printf("Get BP\n"); SortedSet<Order> bid = order_books.get(OrderType.BUYLIMIT); SortedSet<Order> ask = order_books.get(OrderType.SELLLIMIT); Quote lq = this.getLastQuoete(); Order b = null, a = null; if (!bid.isEmpty()) { b = bid.first(); } if (!ask.isEmpty()) { a = ask.first(); } // If there is neither bid nor ask and no last quote // we can't return a quote if (lq == null && b == null && a == null) { return null; } // there is bid and ask if (a != null && b != null) { Quote q = new Quote(); System.out.printf("aaaaa bbbbb %f %f \n", a.limit, b.limit); // if there is no last quote calculate from bid and ask //if (lq == null) { double rc = (bid.first().limit + ask.first().limit) / 2.0; System.out.printf("RCRC2.0: %f\n", rc); return rc; /* if (lq.price < b.limit) { return b.limit; } if (lq.price > a.limit) { return a.limit; } return lq.price; */ } if (a != null) { Quote q = new Quote(); if (lq == null) { return a.limit; } if (lq.price > a.limit) { return a.limit; } return lq.price; } if (b != null) { Quote q = new Quote(); if (lq == null) { return b.limit; } if (lq.price < b.limit) { return b.limit; } return lq.price; } if (lq == null) { return null; } return lq.price; } public Quote getBestPrice_0() { synchronized (executor) { SortedSet<Order> bid = order_books.get(OrderType.BUYLIMIT); SortedSet<Order> ask = order_books.get(OrderType.SELLLIMIT); Quote lq = this.getLastQuoete(); Order b = null, a = null; if (!bid.isEmpty()) { b = bid.first(); } if (!ask.isEmpty()) { a = ask.first(); } // If there is neither bid nor ask and no last quote // we can't return a quote if (lq == null && b == null && a == null) { return null; } // there is bid and ask if (a != null && b != null) { Quote q = new Quote(); // if there is no last quote calculate from bid and ask if (lq == null) { q.price = (bid.first().limit + ask.first().limit) / 2.0; return q; } if (lq.price < b.limit) { q.price = b.limit; return q; } if (lq.price > a.limit) { q.price = a.limit; return q; } return lq; } if (a != null) { Quote q = new Quote(); if (lq == null) { q.price = a.limit; return q; } if (lq.price > a.limit) { q.price = a.limit; return q; } return lq; } if (b != null) { Quote q = new Quote(); if (lq == null) { q.price = b.limit; return q; } if (lq.price < b.limit) { q.price = b.limit; return q; } return lq; } return lq; } } // Class to describe an executed order // QuoteReceiver has to be implemented by objects that wants // to receive quote updates public interface QuoteReceiver { void UpdateQuote(Quote q); } /** * Bookreceiver Interface */ public interface BookReceiver { void UpdateOrderBook(); } final private ArrayList<BookReceiver> ask_bookreceivers = new ArrayList<>(); final private ArrayList<BookReceiver> bid_bookreceivers = new ArrayList<>(); private ArrayList<BookReceiver> selectBookReceiver(OrderType t) { switch (t) { case SELLLIMIT: return ask_bookreceivers; case BUYLIMIT: return bid_bookreceivers; } return null; } public void addBookReceiver(OrderType t, BookReceiver br) { if (br == null) { // System.out.printf("Br is null\n"); } else { // System.out.printf("Br is not Nukk\n"); } ArrayList<BookReceiver> bookreceivers; bookreceivers = selectBookReceiver(t); if (bookreceivers == null) { // System.out.printf("null in bookreceivers\n"); } bookreceivers.add(br); } void updateBookReceivers(OrderType t) { ArrayList<BookReceiver> bookreceivers; bookreceivers = selectBookReceiver(t); Iterator<BookReceiver> i = bookreceivers.iterator(); while (i.hasNext()) { i.next().UpdateOrderBook(); } } // Here we store the list of quote receivers private final List<QuoteReceiver> qrlist; /** * * @param qr */ public void addQuoteReceiver(QuoteReceiver qr) { qrlist.add(qr); } // send updated quotes to all quote receivers private void updateQuoteReceivers(Quote q) { Iterator<QuoteReceiver> i = qrlist.iterator(); while (i.hasNext()) { i.next().UpdateQuote(q); } } // long time = 0; //double theprice = 12.9; // long orderid = 1; double lastprice = 100.0; long lastsvolume; // private final Locker tradelock = new Locker(); public ArrayList<Order> getOrderBook(OrderType type, int depth) { SortedSet<Order> book = order_books.get(type); if (book == null) { return null; } ArrayList<Order> ret; synchronized (executor) { ret = new ArrayList<>(); Iterator<Order> it = book.iterator(); for (int i = 0; i < depth && it.hasNext(); i++) { Order o = it.next(); // System.out.print(o.volume); if (o.volume <= 0) { System.out.printf("Volume < 0\n"); System.exit(0); } ret.add(o); } // System.out.println(); } return ret; } public Quote getLastQuoete() { if (this.quoteHistory.isEmpty()) { return null; } return this.quoteHistory.last(); } private void transferMoneyAndShares(Account src, Account dst, double money, double shares) { src.money -= money; dst.money += money; src.shares -= shares; dst.shares += shares; } public boolean cancelOrder(double account_id, long order_id) { Account a = accounts.get(account_id); if (a == null) { return false; } boolean ret = false; Order o; // System.out.printf("Getting executor %d\n", Thread.currentThread().getId()); synchronized (executor) { // System.out.printf("Have executor %d\n", Thread.currentThread().getId()); o = a.orders.get(order_id); // System.out.print("The Order:"+o.limit+"\n"); if (o != null) { SortedSet ob = order_books.get(o.type); boolean rc = ob.remove(o); a.orders.remove(o.id); a.update(o); ret = true; } } if (ret) { this.updateBookReceivers(o.type); } // System.out.printf("Levave executor %d\n", Thread.currentThread().getId()); return ret; } Random random; public int randNextInt() { return random.nextInt(); } public int randNextInt(int bounds) { return random.nextInt(bounds); } public double randNextDouble() { return random.nextDouble(); } /** * * @param o */ long nextQuoteId = 0; public double fairValue = 0; private void removeOrderIfExecuted(Order o) { if (o.getAccount().getOwner().getName().equals("Tobias0")) { // System.out.printf("Tobias 0 test\n"); } if (o.volume != 0) { if (o.getAccount().getOwner().getName().equals("Tobias0")) { // System.out.printf("Patially remove tobias\n"); } o.status = OrderStatus.PARTIALLY_EXECUTED; o.account.update(o); return; } if (o.getAccount().getOwner().getName().equals("Tobias0")) { // System.out.printf("Fully remove tobias\n"); } o.account.orders.remove(o.id); SortedSet book = order_books.get(o.type); book.remove(book.first()); o.status = OrderStatus.CLOSED; o.account.update(o); } void checkSLOrders(double price) { SortedSet<Order> sl = order_books.get(OrderType.STOPLOSS); SortedSet<Order> ask = order_books.get(OrderType.SELLLIMIT); if (sl.isEmpty()) { return; } Order s = sl.first(); if (price <= s.limit) { sl.remove(s); s.type = OrderType.SELL; addOrderToBook(s); // System.out.printf("Stoploss hit %f %f\n", s.volume, s.limit); } } public void executeUnlimitedOrders() { } private void finishTrade(Order b, Order a, double price, double volume) { // Transfer money and shares transferMoneyAndShares(b.account, a.account, volume * price, -volume); // Update volume b.volume -= volume; a.volume -= volume; b.cost += price * volume; a.cost += price * volume; removeOrderIfExecuted(a); removeOrderIfExecuted(b); } public void executeOrders() { // System.out.printf("Exec Orders\n"); SortedSet<Order> bid = order_books.get(OrderType.BUYLIMIT); SortedSet<Order> ask = order_books.get(OrderType.SELLLIMIT); SortedSet<Order> ul_buy = order_books.get(OrderType.BUY); SortedSet<Order> ul_sell = order_books.get(OrderType.SELL); double volume_total = 0; double money_total = 0; while (true) { // Match unlimited sell orders against unlimited buy orders if (!ul_sell.isEmpty() && !ul_buy.isEmpty()) { Order a = ul_sell.first(); Order b = ul_buy.first(); Double price = getBestPrice(); if (price == null) { break; } double volume = b.volume >= a.volume ? a.volume : b.volume; finishTrade(b, a, price, volume); volume_total += volume; money_total += price * volume; this.checkSLOrders(price); //System.out.printf("Cannot match two unlimited orders!\n"); //System.exit(0); } while (!ul_buy.isEmpty() && !ask.isEmpty()) { Order a = ask.first(); Order b = ul_buy.first(); double price = a.limit; double volume = b.volume >= a.volume ? a.volume : b.volume; finishTrade(b, a, price, volume); volume_total += volume; money_total += price * volume; this.checkSLOrders(price); } // Match unlimited sell orders against limited buy orders while (!ul_sell.isEmpty() && !bid.isEmpty()) { Order b = bid.first(); Order a = ul_sell.first(); double price = b.limit; double volume = b.volume >= a.volume ? a.volume : b.volume; finishTrade(b, a, price, volume); volume_total += volume; money_total += price * volume; this.checkSLOrders(price); } // Match limited against limited orders if (bid.isEmpty() || ask.isEmpty()) { break; } Order b = bid.first(); Order a = ask.first(); if (b.limit < a.limit) { break; } // There is a match, calculate price and volume double price = b.id < a.id ? b.limit : a.limit; double volume = b.volume >= a.volume ? a.volume : b.volume; finishTrade(b, a, price, volume); volume_total += volume; money_total += price * volume; num_trades++; this.checkSLOrders(price); } if (volume_total == 0) { return; } Quote q = new Quote(); q.price = money_total / volume_total; q.volume = volume_total; q.time = timer.currentTimeMillis(); this.quoteHistory.add(q); this.updateOHLCData(q); this.updateQuoteReceivers(q); } long buy_orders = 0; long sell_orders = 0; private void addOrderToBook(Order o) { order_books.get(o.type).add(o); switch (o.type) { case BUY: case BUYLIMIT: buy_orders++; break; case SELL: case SELLLIMIT: sell_orders++; break; } // System.out.printf("B/S %d/%d Failed B/S: %d/%d\n", buy_orders, sell_orders,buy_failed,sell_failed); } long buy_failed = 0; long sell_failed = 0; /** * * @param account_id * @param type * @param volume * @param limit * @return */ public long createOrder(double account_id, OrderType type, double volume, double limit) { Account a = accounts.get(account_id); if (a == null) { return -1; } Order o = new Order(a, type, volume, limit); if (o.volume <= 0 || o.limit <= 0) { switch (o.type) { case SELL: case SELLLIMIT: sell_failed++; break; case BUY: case BUYLIMIT: buy_failed++; break; } return -1; } // System.out.printf("Getting executor in create Order\n", Thread.currentThread().getId()); synchronized (executor) { num_orders++; addOrderToBook(o); a.orders.put(o.id, o); a.update(o); executeOrders(); updateBookReceivers(OrderType.SELLLIMIT); updateBookReceivers(OrderType.BUYLIMIT); // System.out.printf("Order to Queeue %s %f %f\n",o.type.toString(),o.volume,o.limit); // order_queue.add(o); // executor.notify(); } // a.update(o); return o.id; } public double getBestLimit(OrderType type) { Order o = order_books.get(type).first(); if (o == null) { return -1; } return o.limit; } public int getNumberOfOpenOrders(double account_id) { Account a = accounts.get(account_id); if (a == null) { return 0; } return a.orders.size(); } public Account getAccount(double account_id) { return accounts.get(account_id); } /*public AccountData getAccountData(double account_id) { tradelock.lock(); Account a = accounts.get(account_id); tradelock.unlock(); if (a == null) { return null; } AccountData ad = new AccountData(); ad.id = account_id; ad.money = a.money; ad.shares = a.shares; ad.orders = new ArrayList<>(); ad.orders.iterator(); a.orders.values(); Set s = a.orders.keySet(); Iterator it = s.iterator(); while (it.hasNext()) { long x = (long) it.next(); Order o = a.orders.get(x); OrderData od = new OrderData(); od.id = o.id; od.limit = o.limit; od.volume = o.volume; ad.orders.add(od); } //System.exit(0); //a.orders.keySet(); //KeySet ks = a.orders.keySet(); return ad; } */ public ArrayList<OrderData> getOpenOrders(double account_id) { Account a = accounts.get(account_id); if (a == null) { return null; } ArrayList<OrderData> al = new ArrayList(); Iterator it = a.orders.entrySet().iterator(); while (it.hasNext()) { Order o = (Order) it.next(); OrderData od = new OrderData(); od.limit = o.limit; od.volume = o.initial_volume; od.executed = o.initial_volume - o.volume; od.id = o.id; al.add(od); } return al; } }
package org.eclipse.birt.chart.reportitem; import java.util.ArrayList; import java.util.List; import javax.olap.OLAPException; import javax.olap.cursor.EdgeCursor; import org.eclipse.birt.chart.exception.ChartException; import org.eclipse.birt.chart.factory.DataRowExpressionEvaluatorAdapter; import org.eclipse.birt.chart.factory.IGroupedDataRowExpressionEvaluator; import org.eclipse.birt.chart.log.ILogger; import org.eclipse.birt.chart.log.Logger; import org.eclipse.birt.chart.reportitem.i18n.Messages; import org.eclipse.birt.chart.reportitem.plugin.ChartReportItemPlugin; import org.eclipse.birt.core.exception.BirtException; import org.eclipse.birt.data.engine.core.DataException; import org.eclipse.birt.data.engine.olap.api.ICubeCursor; import org.eclipse.birt.data.engine.olap.api.ICubeQueryResults; import org.eclipse.birt.report.engine.extension.ICubeResultSet; /** * Data expression evaluator for cube query. * */ public class BIRTCubeResultSetEvaluator extends DataRowExpressionEvaluatorAdapter implements IGroupedDataRowExpressionEvaluator { protected static final ILogger logger = Logger.getLogger( "org.eclipse.birt.chart.reportitem/trace" ); //$NON-NLS-1$ protected final ICubeResultSet rs; protected final ICubeQueryResults qr; protected ICubeCursor cubeCursor; /** * If there is Y optional expression, the cursor is related to Y optional * expression. Otherwise, it is related to category expression. */ protected EdgeCursor mainEdgeCursor; /** * The there is Y optional expression, the cursor is related to category * expression. Otherwise it should be null. */ protected EdgeCursor subEdgeCursor; protected List<Integer> lstBreaks = new ArrayList<Integer>( ); protected int iIndex = 0; protected boolean bWithoutSub = false; public BIRTCubeResultSetEvaluator( ICubeResultSet rs ) { this.rs = rs; this.qr = null; } public BIRTCubeResultSetEvaluator( ICubeQueryResults qr ) throws BirtException { this.rs = null; this.qr = qr; try { initCubeCursor( ); } catch ( OLAPException e ) { logger.log( e ); } } public int[] getGroupBreaks( int groupLevel ) { if ( lstBreaks.size( ) <= 1 ) { if ( bWithoutSub && iIndex > 0 ) { // If no sub edge cursor, break every data int[] breaks = new int[iIndex - 1]; for ( int i = 0; i < breaks.length; i++ ) { breaks[i] = i + 1; } return breaks; } return new int[0]; } // Remove the last index as requirement int[] breaks = new int[lstBreaks.size( ) - 1]; for ( int i = 0; i < breaks.length; i++ ) { breaks[i] = lstBreaks.get( i ); } return breaks; } @Override public Object evaluate( String expression ) { Object result = null; try { exprCodec.decode( expression ); if ( rs != null ) { // If not binding name, evaluate it via report engine result = rs.evaluate( exprCodec.getType( ), exprCodec.getExpression( ) ); } else { // DTE only supports evaluating data binding name, so chart // engine must check if it's binding name. final String bindingName; if ( exprCodec.isCubeBinding( false ) ) { bindingName = exprCodec.getCubeBindingName( false ); } else { // Directly use the binding created in query definition bindingName = exprCodec.getExpression( ); } result = cubeCursor.getObject( bindingName ); } } catch ( OLAPException e ) { result = e; } catch ( BirtException e ) { result = e; } catch ( RuntimeException e ) { // Bugzilla#284528 During axis chart's evaluation, the cube cursor // may be after the last. However we don't need the actual value. // Shared scale can be used to draw an axis. Runtime exception // should be caught here to avoid stopping later rendering. logger.log( e ); result = e; } return result; } @Override public Object evaluateGlobal( String expression ) { return evaluate( expression ); } @Override public boolean next( ) { iIndex++; try { if ( subEdgeCursor != null ) { // Break if sub cursor reaches end if ( subEdgeCursor.next( ) ) { return true; } // Add break index for each start point lstBreaks.add( Integer.valueOf( iIndex ) ); subEdgeCursor.first( ); return mainEdgeCursor.next( ); } return mainEdgeCursor.next( ); } catch ( OLAPException e ) { logger.log( e ); } return false; } @Override public void close( ) { if ( rs != null ) { rs.close( ); } if ( qr != null ) { try { qr.close( ); } catch ( BirtException e ) { logger.log( e ); } } } @Override public boolean first( ) { try { initCubeCursor( ); if ( mainEdgeCursor.first( ) ) { if ( subEdgeCursor != null ) { subEdgeCursor.first( ); } else { bWithoutSub = true; } return true; } } catch ( OLAPException e ) { logger.log( e ); } catch ( BirtException e ) { logger.log( e ); } return false; } protected void initCubeCursor( ) throws OLAPException, BirtException { if ( cubeCursor == null ) { cubeCursor = getCubeCursor( ); initCursors( ); } } /** * @throws OLAPException * @throws ChartException */ protected void initCursors( ) throws OLAPException, ChartException { List<EdgeCursor> edges = cubeCursor.getOrdinateEdge( ); if ( edges.size( ) == 0 ) { throw new ChartException( ChartReportItemPlugin.ID, ChartException.DATA_BINDING, Messages.getString( "exception.no.cube.edge" ) ); //$NON-NLS-1$ } else if ( edges.size( ) == 1 ) { this.mainEdgeCursor = edges.get( 0 ); this.subEdgeCursor = null; } else { this.mainEdgeCursor = edges.get( 0 ); this.subEdgeCursor = edges.get( 1 ); } } /** * Returns cube cursor. * * @throws DataException */ protected ICubeCursor getCubeCursor( ) throws BirtException { if ( rs != null ) { return (ICubeCursor) rs.getCubeCursor( ); } return qr.getCubeCursor( ); } public boolean needCategoryGrouping( ) { return false; } public boolean needOptionalGrouping( ) { return false; } }
package org.realityforge.replicant.client.subscription; import arez.Arez; import arez.Disposable; import org.realityforge.replicant.client.AbstractReplicantTest; import org.realityforge.replicant.client.ChannelAddress; import org.testng.IHookCallBack; import org.testng.IHookable; import org.testng.ITestResult; import org.testng.annotations.Test; import static org.testng.Assert.*; public class EntitySubscriptionManagerTest extends AbstractReplicantTest implements IHookable { @Override public void run( final IHookCallBack callBack, final ITestResult testResult ) { Arez.context().safeAction( () -> callBack.runTestMethod( testResult ) ); } @Test public void typeChannelRegistrations() { final EntitySubscriptionManager sm = EntitySubscriptionManager.create(); assertNull( sm.findChannelSubscription( new ChannelAddress( G.G1 ) ) ); assertEquals( sm.getTypeChannelSubscriptions().size(), 0 ); assertFalse( sm.getTypeChannelSubscriptions().contains( G.G1 ) ); final boolean explicitSubscription = true; sm.recordChannelSubscription( new ChannelAddress( G.G1 ), null, explicitSubscription ); assertEquals( sm.getTypeChannelSubscriptions().size(), 1 ); assertTrue( sm.getTypeChannelSubscriptions().contains( G.G1 ) ); final ChannelSubscriptionEntry s = sm.findChannelSubscription( new ChannelAddress( G.G1 ) ); assertNotNull( s ); assertNotNull( sm.getChannelSubscription( new ChannelAddress( G.G1 ) ) ); assertEquals( s.getChannel().getAddress(), new ChannelAddress( G.G1 ) ); assertEquals( s.isExplicitSubscription(), explicitSubscription ); assertEquals( s.getEntities().size(), 0 ); sm.removeChannelSubscription( new ChannelAddress( G.G1 ) ); assertNull( sm.findChannelSubscription( new ChannelAddress( G.G1 ) ) ); } @Test public void instanceChannelRegistrations() { final EntitySubscriptionManager sm = EntitySubscriptionManager.create(); assertNull( sm.findChannelSubscription( new ChannelAddress( G.G2, 1 ) ) ); assertEquals( sm.getInstanceChannelSubscriptionKeys().size(), 0 ); assertEquals( sm.getInstanceChannelSubscriptions( G.G2 ).size(), 0 ); final boolean explicitSubscription = false; sm.recordChannelSubscription( new ChannelAddress( G.G2, 1 ), null, explicitSubscription ); assertEquals( sm.getInstanceChannelSubscriptionKeys().size(), 1 ); assertEquals( sm.getInstanceChannelSubscriptions( G.G2 ).size(), 1 ); assertNull( sm.findChannelSubscription( new ChannelAddress( G.G2, 2 ) ) ); final ChannelSubscriptionEntry s = sm.findChannelSubscription( new ChannelAddress( G.G2, 1 ) ); assertNotNull( s ); assertNotNull( sm.getChannelSubscription( new ChannelAddress( G.G2, 1 ) ) ); assertEquals( s.getChannel().getAddress(), new ChannelAddress( G.G2, 1 ) ); assertEquals( s.isExplicitSubscription(), explicitSubscription ); assertEquals( s.getEntities().size(), 0 ); sm.removeChannelSubscription( new ChannelAddress( G.G2, 1 ) ); assertNull( sm.findChannelSubscription( new ChannelAddress( G.G2, 1 ) ) ); } @Test public void entitySubscriptionInTypeChannel() { final Class<A> type = A.class; final Object id = 1; final EntitySubscriptionManager sm = EntitySubscriptionManager.create(); assertNull( sm.findChannelSubscription( new ChannelAddress( G.G1 ) ) ); final ChannelSubscriptionEntry e1 = sm.recordChannelSubscription( new ChannelAddress( G.G1 ), null, false ); assertEntityNotSubscribed( sm, new ChannelAddress( G.G1, null ), type, id ); final A entity = new A(); sm.updateEntity( type, id, new ChannelAddress[]{ new ChannelAddress( G.G1 ) }, entity ); assertEntitySubscribed( sm, new ChannelAddress( G.G1, null ), type, id, entity ); sm.updateEntity( type, id, new ChannelAddress[]{ new ChannelAddress( G.G1 ) }, entity ); sm.removeChannelSubscription( new ChannelAddress( G.G1 ) ); assertEntityNotSubscribed( sm, new ChannelAddress( G.G1, null ), type, id ); assertTrue( Disposable.isDisposed( e1 ) ); } @Test public void entitySubscriptionInTypeChannel_removeEntity() { final Class<A> type = A.class; final Object id = 1; final EntitySubscriptionManager sm = EntitySubscriptionManager.create(); assertNull( sm.findChannelSubscription( new ChannelAddress( G.G1 ) ) ); final ChannelSubscriptionEntry s1 = sm.recordChannelSubscription( new ChannelAddress( G.G1 ), null, false ); final A entity = new A(); sm.updateEntity( type, id, new ChannelAddress[]{ new ChannelAddress( G.G1 ) }, entity ); assertEntitySubscribed( sm, new ChannelAddress( G.G1, null ), type, id, entity ); sm.updateEntity( type, id, new ChannelAddress[]{ new ChannelAddress( G.G1 ) }, entity ); assertEntitySubscribed( sm, new ChannelAddress( G.G1, null ), type, id, entity ); sm.removeEntity( type, id ); assertEntityNotSubscribed( sm, new ChannelAddress( G.G1, null ), type, id ); //assertEntityPresent( type, id, r ); sm.removeChannelSubscription( new ChannelAddress( G.G1 ) ); assertTrue( Disposable.isDisposed( s1 ) ); // Entity still here as unsubscribe did not unload as removed from subscription manager //assertEntityPresent( type, id, r ); } @Test public void entitySubscriptionInInstanceChannel() { final Class<A> type = A.class; final Object id = 1; final EntitySubscriptionManager sm = EntitySubscriptionManager.create(); assertNull( sm.findChannelSubscription( new ChannelAddress( G.G2, 1 ) ) ); sm.recordChannelSubscription( new ChannelAddress( G.G2, 1 ), null, false ); assertEntityNotSubscribed( sm, new ChannelAddress( G.G2, 1 ), type, id ); final A entity = new A(); sm.updateEntity( type, id, new ChannelAddress[]{ new ChannelAddress( G.G2, 1 ) }, entity ); assertEntitySubscribed( sm, new ChannelAddress( G.G2, 1 ), type, id, entity ); sm.updateEntity( type, id, new ChannelAddress[]{ new ChannelAddress( G.G2, 1 ) }, entity ); sm.removeChannelSubscription( new ChannelAddress( G.G2, 1 ) ); assertEntityNotSubscribed( sm, new ChannelAddress( G.G2, 1 ), type, id ); } @Test public void entitySubscriptionAndUpdateInInstanceChannel() { final EntitySubscriptionManager sm = EntitySubscriptionManager.create(); assertNull( sm.findChannelSubscription( new ChannelAddress( G.G2, 1 ) ) ); final ChannelSubscriptionEntry e1 = sm.recordChannelSubscription( new ChannelAddress( G.G2, 1 ), "F1", false ); assertEquals( sm.getChannelSubscription( new ChannelAddress( G.G2, 1 ) ).getChannel().getFilter(), "F1" ); final ChannelSubscriptionEntry e2 = sm.updateChannelSubscription( new ChannelAddress( G.G2, 1 ), "F2" ); assertEquals( sm.getChannelSubscription( new ChannelAddress( G.G2, 1 ) ).getChannel().getFilter(), "F2" ); assertEquals( e1, e2 ); } @Test public void entitySubscriptionAndUpdateInTypeChannel() { final EntitySubscriptionManager sm = EntitySubscriptionManager.create(); assertNull( sm.findChannelSubscription( new ChannelAddress( G.G1 ) ) ); final ChannelSubscriptionEntry e1 = sm.recordChannelSubscription( new ChannelAddress( G.G1 ), "F1", false ); assertEquals( sm.getChannelSubscription( new ChannelAddress( G.G1 ) ).getChannel().getFilter(), "F1" ); final ChannelSubscriptionEntry e2 = sm.updateChannelSubscription( new ChannelAddress( G.G1 ), "F2" ); assertEquals( sm.getChannelSubscription( new ChannelAddress( G.G1 ) ).getChannel().getFilter(), "F2" ); assertEquals( e1, e2 ); } @Test public void entitySubscriptionInInstanceChannel_removeEntity() { final Class<A> type = A.class; final Object id = 1; final EntitySubscriptionManager sm = EntitySubscriptionManager.create(); assertNull( sm.findChannelSubscription( new ChannelAddress( G.G2, 1 ) ) ); sm.recordChannelSubscription( new ChannelAddress( G.G2, 1 ), null, false ); final A entity = new A(); sm.updateEntity( type, id, new ChannelAddress[]{ new ChannelAddress( G.G2, 1 ) }, entity ); assertEntitySubscribed( sm, new ChannelAddress( G.G2, 1 ), type, id, entity ); sm.updateEntity( type, id, new ChannelAddress[]{ new ChannelAddress( G.G2, 1 ) }, entity ); assertEntitySubscribed( sm, new ChannelAddress( G.G2, 1 ), type, id, entity ); sm.removeEntity( type, id ); assertEntityNotSubscribed( sm, new ChannelAddress( G.G2, 1 ), type, id ); sm.removeChannelSubscription( new ChannelAddress( G.G2, 1 ) ); } @Test public void entityOverlappingSubscriptions() { final Class<A> type = A.class; final Object id = 1; final EntitySubscriptionManager sm = EntitySubscriptionManager.create(); assertNull( sm.findChannelSubscription( new ChannelAddress( G.G1 ) ) ); assertNull( sm.findChannelSubscription( new ChannelAddress( G.G2, 1 ) ) ); sm.recordChannelSubscription( new ChannelAddress( G.G1 ), null, false ); sm.recordChannelSubscription( new ChannelAddress( G.G2, 1 ), null, false ); assertEntityNotSubscribed( sm, new ChannelAddress( G.G1, null ), type, id ); assertEntityNotSubscribed( sm, new ChannelAddress( G.G2, 1 ), type, id ); final A entity = new A(); sm.updateEntity( type, id, new ChannelAddress[]{ new ChannelAddress( G.G1 ) }, entity ); assertEntitySubscribed( sm, new ChannelAddress( G.G1, null ), type, id, entity ); assertEntityNotSubscribed( sm, new ChannelAddress( G.G2, 1 ), type, id ); sm.updateEntity( type, id, new ChannelAddress[]{ new ChannelAddress( G.G2, 1 ) }, entity ); assertEntitySubscribed( sm, new ChannelAddress( G.G1, null ), type, id, entity ); assertEntitySubscribed( sm, new ChannelAddress( G.G2, 1 ), type, id, entity ); sm.removeChannelSubscription( new ChannelAddress( G.G1 ) ); assertEntityNotSubscribed( sm, new ChannelAddress( G.G1, null ), type, id ); assertEntitySubscribed( sm, new ChannelAddress( G.G2, 1 ), type, id, entity ); sm.removeChannelSubscription( new ChannelAddress( G.G2, 1 ) ); assertEntityNotSubscribed( sm, new ChannelAddress( G.G1, null ), type, id ); assertEntityNotSubscribed( sm, new ChannelAddress( G.G2, 1 ), type, id ); } @Test public void removeEntityFromChannel() { final Class<A> type = A.class; final Object id = 1; final EntitySubscriptionManager sm = EntitySubscriptionManager.create(); assertNull( sm.findChannelSubscription( new ChannelAddress( G.G1 ) ) ); assertNull( sm.findChannelSubscription( new ChannelAddress( G.G2 ) ) ); final ChannelSubscriptionEntry s1 = sm.recordChannelSubscription( new ChannelAddress( G.G1 ), "X", false ); assertEquals( s1.getChannel().getFilter(), "X" ); final ChannelSubscriptionEntry s2 = sm.recordChannelSubscription( new ChannelAddress( G.G2 ), null, false ); assertEquals( s2.getChannel().getFilter(), null ); assertEntityNotSubscribed( sm, new ChannelAddress( G.G1, null ), type, id ); assertEntityNotSubscribed( sm, new ChannelAddress( G.G2, null ), type, id ); final A entity1 = new A(); sm.updateEntity( type, id, new ChannelAddress[]{ new ChannelAddress( G.G1 ) }, entity1 ); assertEntitySubscribed( sm, new ChannelAddress( G.G1, null ), type, id, entity1 ); assertEntityNotSubscribed( sm, new ChannelAddress( G.G2, null ), type, id ); sm.updateEntity( type, id, new ChannelAddress[]{ new ChannelAddress( G.G1 ), new ChannelAddress( G.G2 ) }, entity1 ); assertEntitySubscribed( sm, new ChannelAddress( G.G1, null ), type, id, entity1 ); assertEntitySubscribed( sm, new ChannelAddress( G.G2, null ), type, id, entity1 ); sm.removeEntityFromChannel( type, id, new ChannelAddress( G.G1 ) ); assertEntityNotSubscribed( sm, new ChannelAddress( G.G1, null ), type, id ); assertEntitySubscribed( sm, new ChannelAddress( G.G2, null ), type, id, entity1 ); final Entity e = sm.removeEntityFromChannel( type, id, new ChannelAddress( G.G2 ) ); assertEntityNotSubscribed( sm, new ChannelAddress( G.G1, null ), type, id ); assertEntityNotSubscribed( sm, new ChannelAddress( G.G2, null ), type, id ); assertEquals( e.getChannelSubscriptions().size(), 0 ); } private void assertEntitySubscribed( final EntitySubscriptionManager sm, final ChannelAddress descriptor, final Class<A> type, final Object id, final A entity ) { final ChannelSubscriptionEntry entry = sm.getChannelSubscription( descriptor ); assertNotNull( entry.getEntities().get( type ).get( id ) ); assertTrue( sm.getEntity( type, id ) .getChannelSubscriptions() .stream() .anyMatch( s -> s.getChannel().getAddress().equals( descriptor ) ) ); assertEquals( sm.getEntity( type, id ).getUserObject(), entity ); } private void assertEntityNotSubscribed( final EntitySubscriptionManager sm, final ChannelAddress descriptor, final Class<A> type, final Object id ) { boolean found; try { final ChannelSubscriptionEntry subscription = sm.getChannelSubscription( descriptor ); assertNotNull( subscription.getEntities().get( type ).get( id ) ); found = true; } catch ( final Throwable t ) { found = false; } assertFalse( found, "Found subscription unexpectedly" ); } @Test( expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = "Channel already subscribed: .*" ) public void subscribe_nonExistentTypeChannel() { final EntitySubscriptionManager sm = EntitySubscriptionManager.create(); sm.recordChannelSubscription( new ChannelAddress( G.G1 ), null, false ); sm.recordChannelSubscription( new ChannelAddress( G.G1 ), null, false ); } @Test( expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = "Channel not subscribed: .*" ) public void getSubscription_nonExistentTypeChannel() { final EntitySubscriptionManager sm = EntitySubscriptionManager.create(); sm.getChannelSubscription( new ChannelAddress( G.G1 ) ); } @Test( expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = "Channel not subscribed: .*" ) public void unsubscribe_nonExistentTypeChannel() { final EntitySubscriptionManager sm = EntitySubscriptionManager.create(); sm.removeChannelSubscription( new ChannelAddress( G.G1 ) ); } @Test( expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = "Channel already subscribed: .*:1" ) public void subscribe_nonExistentInstanceChannel() { final EntitySubscriptionManager sm = EntitySubscriptionManager.create(); sm.recordChannelSubscription( new ChannelAddress( G.G1, "1" ), null, false ); sm.recordChannelSubscription( new ChannelAddress( G.G1, "1" ), null, false ); } @Test( expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = "Channel not subscribed: .*" ) public void getSubscription_nonExistentInstanceChannel() { final EntitySubscriptionManager sm = EntitySubscriptionManager.create(); sm.getChannelSubscription( new ChannelAddress( G.G1, "1" ) ); } @Test( expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = "Channel not subscribed: .*" ) public void unsubscribe_nonExistentInstanceChannel() { final EntitySubscriptionManager sm = EntitySubscriptionManager.create(); sm.removeChannelSubscription( new ChannelAddress( G.G1, "1" ) ); } @Test( expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = "Channel not subscribed: .*" ) public void unsubscribe_nonExistentInstanceChannel_whenTypeCreated() { final EntitySubscriptionManager sm = EntitySubscriptionManager.create(); sm.recordChannelSubscription( new ChannelAddress( G.G1 ), "1", false ); sm.removeChannelSubscription( new ChannelAddress( G.G1, "2" ) ); } enum G { G1, G2 } static class A { } }
package com.sap.core.odata.processor.ref.jpa; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.TimeZone; import javax.persistence.*; @Entity @Table(name = "T_SALESORDERHEADER") @NamedQuery(name = "AllSOHeader", query = "select so from SalesOrderHeader so") public class SalesOrderHeader { public SalesOrderHeader() { //No arg constructor } public SalesOrderHeader(Date creationDate,int buyerId, String buyerName, Address buyerAddress, String currencyCode, double netAmount, boolean deliveryStatus) { super(); this.creationDate = creationDate; this.buyerId = buyerId; this.buyerName = buyerName; this.buyerAddress = buyerAddress; this.currencyCode = currencyCode; this.deliveryStatus = deliveryStatus; } @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "SO_ID") private long soId; @Temporal(TemporalType.DATE) private Date creationDate; @Column(name = "BUYER_ID") private int buyerId; @Column(name = "BUYER_NAME",length = 255) private String buyerName; @Embedded private Address buyerAddress; @Column(name = "CURRENCY_CODE",length = 10) private String currencyCode; @Column(name = "DELIVERY_STATUS") private boolean deliveryStatus; @Column(precision = 5) private double grossAmount; @Column(precision = 8) private double netAmount; @OneToMany(mappedBy = "salesOrderHeader", cascade = CascadeType.ALL) private List<SalesOrderItem> salesOrderItem = new ArrayList<SalesOrderItem>(); @OneToMany(mappedBy = "salesOrderHeader", cascade = CascadeType.ALL) private List<Note> notes = new ArrayList<Note>(); public long getSoId() { return soId; } public void setSoId(long soId) { this.soId = soId; } public Date getCreationDate() { long dbTime = creationDate.getTime(); Date originalDate = new Date(dbTime + TimeZone.getDefault().getOffset(dbTime)); return originalDate; } public void setCreationDate(Date creationDate) { long originalTime = creationDate.getTime(); Date newDate = new Date(originalTime - TimeZone.getDefault().getOffset(originalTime)); this.creationDate = newDate; } public int getBuyerId() { return buyerId; } public void setBuyerId(int buyerId) { this.buyerId = buyerId; } public String getBuyerName() { return buyerName; } public void setBuyerName(String buyerName) { this.buyerName = buyerName; } public Address getBuyerAddress() { return buyerAddress; } public void setBuyerAddress(Address buyerAddress) { this.buyerAddress = buyerAddress; } public String getCurrencyCode() { return currencyCode; } public void setCurrencyCode(String currencyCode) { this.currencyCode = currencyCode; } public boolean getDeliveryStatus() { return deliveryStatus; } public void setDeliveryStatus(boolean deliveryStatus) { this.deliveryStatus = deliveryStatus; } public double getGrossAmount() { return grossAmount; } public void setGrossAmount(double grossAmount) { this.grossAmount = grossAmount; } public double getNetAmount() { return netAmount; } public void setNetAmount(double netAmount) { this.netAmount = netAmount; } public List<SalesOrderItem> getSalesOrderItem() { return salesOrderItem; } public void setSalesOrderItem(List<SalesOrderItem> salesOrderItem) { this.salesOrderItem = salesOrderItem; } public List<Note> getNotes() { return notes; } public void setNotes(List<Note> notes) { this.notes = notes; } }
package org.apereo.cas.web.support; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.StringUtils; import org.apereo.cas.authentication.Authentication; import org.apereo.cas.authentication.RememberMeCredential; import org.apereo.cas.util.CollectionUtils; import org.springframework.web.util.CookieGenerator; import org.springframework.webflow.execution.RequestContext; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import lombok.Setter; import java.util.Map; /** * Extends CookieGenerator to allow you to retrieve a value from a request. * The cookie is automatically marked as httpOnly, if the servlet container has support for it. * Also has support for remember-me. * * @author Scott Battaglia * @author Misagh Moayyed * @since 3.1 */ @Slf4j @Setter public class CookieRetrievingCookieGenerator extends CookieGenerator { private static final int DEFAULT_REMEMBER_ME_MAX_AGE = 7889231; /** * The maximum age the cookie should be remembered for. * The default is three months ({@value} in seconds, according to Google) */ private int rememberMeMaxAge = DEFAULT_REMEMBER_ME_MAX_AGE; /** * Responsible for manging and verifying the cookie value. **/ private final CookieValueManager casCookieValueManager; /** * Instantiates a new cookie retrieving cookie generator * with a default cipher of {@link NoOpCookieValueManager}. * * @param name cookie name * @param path cookie path * @param maxAge cookie max age * @param secure if cookie is only for HTTPS * @param domain cookie domain * @param httpOnly the http only */ public CookieRetrievingCookieGenerator(final String name, final String path, final int maxAge, final boolean secure, final String domain, final boolean httpOnly) { this(name, path, maxAge, secure, domain, new NoOpCookieValueManager(), DEFAULT_REMEMBER_ME_MAX_AGE, httpOnly); } /** * Instantiates a new Cookie retrieving cookie generator. * * @param name cookie name * @param path cookie path * @param maxAge cookie max age * @param secure if cookie is only for HTTPS * @param domain cookie domain * @param casCookieValueManager the cookie manager * @param rememberMeMaxAge cookie rememberMe max age * @param httpOnly the http only */ public CookieRetrievingCookieGenerator(final String name, final String path, final int maxAge, final boolean secure, final String domain, final CookieValueManager casCookieValueManager, final int rememberMeMaxAge, final boolean httpOnly) { super.setCookieName(name); super.setCookiePath(path); this.setCookieDomain(domain); super.setCookieMaxAge(maxAge); super.setCookieSecure(secure); super.setCookieHttpOnly(httpOnly); this.casCookieValueManager = casCookieValueManager; this.rememberMeMaxAge = rememberMeMaxAge; } /** * Adds the cookie, taking into account {@link RememberMeCredential#REQUEST_PARAMETER_REMEMBER_ME} * in the request. * * @param requestContext the request context * @param cookieValue the cookie value */ public void addCookie(final RequestContext requestContext, final String cookieValue) { final HttpServletRequest request = WebUtils.getHttpServletRequestFromExternalWebflowContext(requestContext); final HttpServletResponse response = WebUtils.getHttpServletResponseFromExternalWebflowContext(requestContext); final String theCookieValue = this.casCookieValueManager.buildCookieValue(cookieValue, request); if (isRememberMeAuthentication(requestContext)) { LOGGER.debug("Creating cookie [{}] for remember-me authentication with max-age [{}]", getCookieName(), this.rememberMeMaxAge); final Cookie cookie = createCookie(theCookieValue); cookie.setMaxAge(this.rememberMeMaxAge); cookie.setSecure(isCookieSecure()); cookie.setHttpOnly(isCookieHttpOnly()); cookie.setComment("CAS Cookie w/ Remember-Me"); response.addCookie(cookie); } else { LOGGER.debug("Creating cookie [{}]", getCookieName()); super.addCookie(response, theCookieValue); } } private boolean isRememberMeAuthentication(final RequestContext requestContext) { final HttpServletRequest request = WebUtils.getHttpServletRequestFromExternalWebflowContext(requestContext); final String value = request.getParameter(RememberMeCredential.REQUEST_PARAMETER_REMEMBER_ME); LOGGER.debug("Locating request parameter [{}] with value [{}]", RememberMeCredential.REQUEST_PARAMETER_REMEMBER_ME, value); boolean isRememberMe = StringUtils.isNotBlank(value) && WebUtils.isRememberMeAuthenticationEnabled(requestContext); if (!isRememberMe) { LOGGER.debug("Request does not indicate a remember-me authentication event. Locating authentication object from the request context..."); final Authentication auth = WebUtils.getAuthentication(requestContext); if (auth != null) { final Map<String, Object> attributes = auth.getAttributes(); LOGGER.debug("Located authentication attributes [{}]", attributes); if (attributes.containsKey(RememberMeCredential.AUTHENTICATION_ATTRIBUTE_REMEMBER_ME)) { final Object rememberMeValue = attributes.getOrDefault(RememberMeCredential.AUTHENTICATION_ATTRIBUTE_REMEMBER_ME, false); LOGGER.debug("Located remember-me authentication attribute [{}]", rememberMeValue); isRememberMe = CollectionUtils.wrapSet(rememberMeValue).contains(true); } } } LOGGER.debug("Is this request from a remember-me authentication event? [{}]", BooleanUtils.toStringYesNo(isRememberMe)); return isRememberMe; } /** * Retrieve cookie value. * * @param request the request * @return the cookie value */ public String retrieveCookieValue(final HttpServletRequest request) { try { final Cookie cookie = org.springframework.web.util.WebUtils.getCookie(request, getCookieName()); return cookie == null ? null : this.casCookieValueManager.obtainCookieValue(cookie, request); } catch (final Exception e) { LOGGER.debug(e.getMessage(), e); } return null; } @Override public void setCookieDomain(final String cookieDomain) { super.setCookieDomain(StringUtils.defaultIfEmpty(cookieDomain, null)); } @Override protected Cookie createCookie(final String cookieValue) { final Cookie c = super.createCookie(cookieValue); c.setComment("CAS Cookie"); return c; } }
package org.hisp.dhis.program; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hisp.dhis.common.AccessLevel; import org.hisp.dhis.common.AuditType; import org.hisp.dhis.common.CodeGenerator; import org.hisp.dhis.common.IllegalQueryException; import org.hisp.dhis.common.OrganisationUnitSelectionMode; import org.hisp.dhis.event.EventStatus; import org.hisp.dhis.organisationunit.OrganisationUnit; import org.hisp.dhis.organisationunit.OrganisationUnitService; import org.hisp.dhis.program.notification.event.ProgramEnrollmentCompletionNotificationEvent; import org.hisp.dhis.program.notification.event.ProgramEnrollmentNotificationEvent; import org.hisp.dhis.programrule.engine.EnrollmentEvaluationEvent; import org.hisp.dhis.security.acl.AclService; import org.hisp.dhis.trackedentity.TrackedEntityInstance; import org.hisp.dhis.trackedentity.TrackedEntityInstanceService; import org.hisp.dhis.trackedentity.TrackedEntityType; import org.hisp.dhis.trackedentity.TrackedEntityTypeService; import org.hisp.dhis.trackedentity.TrackerOwnershipManager; import org.hisp.dhis.user.CurrentUserService; import org.hisp.dhis.user.User; import org.hisp.dhis.util.DateUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEventPublisher; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import static org.hisp.dhis.common.OrganisationUnitSelectionMode.*; /** * @author Abyot Asalefew */ @Service( "org.hisp.dhis.program.ProgramInstanceService" ) public class DefaultProgramInstanceService implements ProgramInstanceService { private static final Log log = LogFactory.getLog( DefaultProgramInstanceService.class ); // Dependencies @Autowired private ProgramInstanceStore programInstanceStore; @Autowired private ProgramStageInstanceStore programStageInstanceStore; @Autowired private ProgramService programService; @Autowired private CurrentUserService currentUserService; @Autowired private TrackedEntityInstanceService trackedEntityInstanceService; @Autowired private OrganisationUnitService organisationUnitService; @Autowired private TrackedEntityTypeService trackedEntityTypeService; @Autowired private ApplicationEventPublisher eventPublisher; @Autowired private TrackerOwnershipManager trackerOwnershipAccessManager; @Autowired private ProgramInstanceAuditService programInstanceAuditService; @Autowired private AclService aclService; // Implementation methods @Override @Transactional public long addProgramInstance( ProgramInstance programInstance ) { programInstanceStore.save( programInstance ); return programInstance.getId(); } @Override @Transactional public void deleteProgramInstance( ProgramInstance programInstance ) { deleteProgramInstance( programInstance, false ); } @Override @Transactional public void deleteProgramInstance( ProgramInstance programInstance, boolean forceDelete ) { if ( forceDelete ) { programInstanceStore.delete( programInstance ); } else { programInstance.setDeleted( true ); programInstance.setStatus( ProgramStatus.CANCELLED ); programInstanceStore.update( programInstance ); } } @Override @Transactional( readOnly = true ) public ProgramInstance getProgramInstance( long id ) { ProgramInstance programInstance = programInstanceStore.get( id ); User user = currentUserService.getCurrentUser(); if ( user != null ) { addProgramInstanceAudit( programInstance, user.getUsername() ); } return programInstance; } @Override @Transactional( readOnly = true ) public ProgramInstance getProgramInstance( String uid ) { ProgramInstance programInstance = programInstanceStore.getByUid( uid ); User user = currentUserService.getCurrentUser(); if ( user != null ) { addProgramInstanceAudit( programInstance, user.getUsername() ); } return programInstance; } @Override @Transactional( readOnly = true ) public boolean programInstanceExists( String uid ) { return programInstanceStore.exists( uid ); } @Override @Transactional( readOnly = true ) public boolean programInstanceExistsIncludingDeleted( String uid ) { return programInstanceStore.existsIncludingDeleted( uid ); } @Override @Transactional( readOnly = true ) public List<String> getProgramInstancesUidsIncludingDeleted( List<String> uids ) { return programInstanceStore.getUidsIncludingDeleted( uids ); } @Override @Transactional public void updateProgramInstance( ProgramInstance programInstance ) { programInstanceStore.update( programInstance ); } @Override @Transactional( readOnly = true ) public ProgramInstanceQueryParams getFromUrl( Set<String> ou, OrganisationUnitSelectionMode ouMode, Date lastUpdated, String lastUpdatedDuration, String program, ProgramStatus programStatus, Date programStartDate, Date programEndDate, String trackedEntityType, String trackedEntityInstance, Boolean followUp, Integer page, Integer pageSize, boolean totalPages, boolean skipPaging, boolean includeDeleted ) { ProgramInstanceQueryParams params = new ProgramInstanceQueryParams(); Set<OrganisationUnit> possibleSearchOrgUnits = new HashSet<>(); User user = currentUserService.getCurrentUser(); if ( user != null ) { possibleSearchOrgUnits = user.getTeiSearchOrganisationUnitsWithFallback(); } if ( ou != null ) { for ( String orgUnit : ou ) { OrganisationUnit organisationUnit = organisationUnitService.getOrganisationUnit( orgUnit ); if ( organisationUnit == null ) { throw new IllegalQueryException( "Organisation unit does not exist: " + orgUnit ); } if ( !organisationUnitService.isInUserHierarchy( organisationUnit.getUid(), possibleSearchOrgUnits ) ) { throw new IllegalQueryException( "Organisation unit is not part of the search scope: " + orgUnit ); } params.getOrganisationUnits().add( organisationUnit ); } } Program pr = program != null ? programService.getProgram( program ) : null; if ( program != null && pr == null ) { throw new IllegalQueryException( "Program does not exist: " + program ); } TrackedEntityType te = trackedEntityType != null ? trackedEntityTypeService.getTrackedEntityType( trackedEntityType ) : null; if ( trackedEntityType != null && te == null ) { throw new IllegalQueryException( "Tracked entity does not exist: " + program ); } TrackedEntityInstance tei = trackedEntityInstance != null ? trackedEntityInstanceService.getTrackedEntityInstance( trackedEntityInstance ) : null; if ( trackedEntityInstance != null && tei == null ) { throw new IllegalQueryException( "Tracked entity instance does not exist: " + program ); } params.setProgram( pr ); params.setProgramStatus( programStatus ); params.setFollowUp( followUp ); params.setLastUpdated( lastUpdated ); params.setLastUpdatedDuration( lastUpdatedDuration ); params.setProgramStartDate( programStartDate ); params.setProgramEndDate( programEndDate ); params.setTrackedEntityType( te ); params.setTrackedEntityInstance( tei ); params.setOrganisationUnitMode( ouMode ); params.setPage( page ); params.setPageSize( pageSize ); params.setTotalPages( totalPages ); params.setSkipPaging( skipPaging ); params.setIncludeDeleted( includeDeleted ); params.setUser( user ); return params; } // TODO consider security @Override @Transactional( readOnly = true ) public List<ProgramInstance> getProgramInstances( ProgramInstanceQueryParams params ) { decideAccess( params ); validate( params ); User user = currentUserService.getCurrentUser(); if ( user != null && params.isOrganisationUnitMode( OrganisationUnitSelectionMode.ACCESSIBLE ) ) { params.setOrganisationUnits( user.getTeiSearchOrganisationUnitsWithFallback() ); params.setOrganisationUnitMode( OrganisationUnitSelectionMode.DESCENDANTS ); } else if ( params.isOrganisationUnitMode( CHILDREN ) ) { Set<OrganisationUnit> organisationUnits = new HashSet<>(); organisationUnits.addAll( params.getOrganisationUnits() ); for ( OrganisationUnit organisationUnit : params.getOrganisationUnits() ) { organisationUnits.addAll( organisationUnit.getChildren() ); } params.setOrganisationUnits( organisationUnits ); } if ( !params.isPaging() && !params.isSkipPaging() ) { params.setDefaultPaging(); } List<ProgramInstance> programInstances = programInstanceStore.getProgramInstances( params ); if ( user != null ) { addProrgamInstanceAudits( programInstances, user.getUsername() ); } return programInstances; } @Override @Transactional( readOnly = true ) public int countProgramInstances( ProgramInstanceQueryParams params ) { decideAccess( params ); validate( params ); User user = currentUserService.getCurrentUser(); if ( user != null && params.isOrganisationUnitMode( OrganisationUnitSelectionMode.ACCESSIBLE ) ) { params.setOrganisationUnits( user.getTeiSearchOrganisationUnitsWithFallback() ); params.setOrganisationUnitMode( OrganisationUnitSelectionMode.DESCENDANTS ); } else if ( params.isOrganisationUnitMode( CHILDREN ) ) { Set<OrganisationUnit> organisationUnits = new HashSet<>(); organisationUnits.addAll( params.getOrganisationUnits() ); for ( OrganisationUnit organisationUnit : params.getOrganisationUnits() ) { organisationUnits.addAll( organisationUnit.getChildren() ); } params.setOrganisationUnits( organisationUnits ); } params.setSkipPaging( true ); return programInstanceStore.countProgramInstances( params ); } @Override @Transactional( readOnly = true ) public void decideAccess( ProgramInstanceQueryParams params ) { if ( params.hasProgram() ) { if ( !aclService.canDataRead( params.getUser(), params.getProgram() ) ) { throw new IllegalQueryException( "Current user is not authorized to read data from selected program: " + params.getProgram().getUid() ); } if ( params.getProgram().getTrackedEntityType() != null && !aclService.canDataRead( params.getUser(), params.getProgram().getTrackedEntityType() ) ) { throw new IllegalQueryException( "Current user is not authorized to read data from selected program's tracked entity type: " + params.getProgram().getTrackedEntityType().getUid() ); } } if ( params.hasTrackedEntityType() && !aclService.canDataRead( params.getUser(), params.getTrackedEntityType() ) ) { throw new IllegalQueryException( "Current user is not authorized to read data from selected tracked entity type: " + params.getTrackedEntityType().getUid() ); } } @Override public void validate( ProgramInstanceQueryParams params ) throws IllegalQueryException { String violation = null; if ( params == null ) { throw new IllegalQueryException( "Params cannot be null" ); } User user = params.getUser(); if ( !params.hasOrganisationUnits() && !(params.isOrganisationUnitMode( ALL ) || params.isOrganisationUnitMode( ACCESSIBLE )) ) { violation = "At least one organisation unit must be specified"; } if ( params.isOrganisationUnitMode( ACCESSIBLE ) && (user == null || !user.hasDataViewOrganisationUnitWithFallback()) ) { violation = "Current user must be associated with at least one organisation unit when selection mode is ACCESSIBLE"; } if ( params.hasProgram() && params.hasTrackedEntityType() ) { violation = "Program and tracked entity cannot be specified simultaneously"; } if ( params.hasProgramStatus() && !params.hasProgram() ) { violation = "Program must be defined when program status is defined"; } if ( params.hasFollowUp() && !params.hasProgram() ) { violation = "Program must be defined when follow up status is defined"; } if ( params.hasProgramStartDate() && !params.hasProgram() ) { violation = "Program must be defined when program start date is specified"; } if ( params.hasProgramEndDate() && !params.hasProgram() ) { violation = "Program must be defined when program end date is specified"; } if ( params.hasLastUpdated() && params.hasLastUpdatedDuration() ) { violation = "Last updated and last updated duration cannot be specified simultaneously"; } if ( params.hasLastUpdatedDuration() && DateUtils.getDuration( params.getLastUpdatedDuration() ) == null ) { violation = "Duration is not valid: " + params.getLastUpdatedDuration(); } if ( violation != null ) { log.warn( "Validation failed: " + violation ); throw new IllegalQueryException( violation ); } } @Override @Transactional( readOnly = true ) public List<ProgramInstance> getProgramInstances( Program program ) { return programInstanceStore.get( program ); } @Override @Transactional( readOnly = true ) public List<ProgramInstance> getProgramInstances( Program program, ProgramStatus status ) { return programInstanceStore.get( program, status ); } @Override @Transactional( readOnly = true ) public List<ProgramInstance> getProgramInstances( TrackedEntityInstance entityInstance, Program program, ProgramStatus status ) { return programInstanceStore.get( entityInstance, program, status ); } @Override @Transactional public ProgramInstance prepareProgramInstance( TrackedEntityInstance trackedEntityInstance, Program program, ProgramStatus programStatus, Date enrollmentDate, Date incidentDate, OrganisationUnit organisationUnit, String uid ) { if ( program.getTrackedEntityType() != null && !program.getTrackedEntityType().equals( trackedEntityInstance.getTrackedEntityType() ) ) { throw new IllegalQueryException( "Tracked entity instance must have same tracked entity as program: " + program.getUid() ); } ProgramInstance programInstance = new ProgramInstance(); programInstance.setUid( CodeGenerator.isValidUid( uid ) ? uid : CodeGenerator.generateUid() ); programInstance.setOrganisationUnit( organisationUnit ); programInstance.enrollTrackedEntityInstance( trackedEntityInstance, program ); if ( enrollmentDate != null ) { programInstance.setEnrollmentDate( enrollmentDate ); } else { programInstance.setEnrollmentDate( new Date() ); } if ( incidentDate != null ) { programInstance.setIncidentDate( incidentDate ); } else { programInstance.setIncidentDate( new Date() ); } programInstance.setStatus( programStatus ); return programInstance; } @Override @Transactional public ProgramInstance enrollTrackedEntityInstance( TrackedEntityInstance trackedEntityInstance, Program program, Date enrollmentDate, Date incidentDate, OrganisationUnit organisationUnit ) { return enrollTrackedEntityInstance( trackedEntityInstance, program, enrollmentDate, incidentDate, organisationUnit, CodeGenerator.generateUid() ); } @Override @Transactional public ProgramInstance enrollTrackedEntityInstance( TrackedEntityInstance trackedEntityInstance, Program program, Date enrollmentDate, Date incidentDate, OrganisationUnit organisationUnit, String uid ) { // Add program instance ProgramInstance programInstance = prepareProgramInstance( trackedEntityInstance, program, ProgramStatus.ACTIVE, enrollmentDate, incidentDate, organisationUnit, uid ); addProgramInstance( programInstance ); // Add program owner and overwrite if already exists. trackerOwnershipAccessManager.assignOwnership( trackedEntityInstance, program, organisationUnit, true, true ); // Send enrollment notifications (if any) eventPublisher.publishEvent( new ProgramEnrollmentNotificationEvent( this, programInstance.getId() ) ); eventPublisher.publishEvent( new EnrollmentEvaluationEvent( this, programInstance.getId() ) ); // Update ProgramInstance and TEI updateProgramInstance( programInstance ); trackedEntityInstanceService.updateTrackedEntityInstance( trackedEntityInstance ); return programInstance; } @Override @Transactional( readOnly = true ) public boolean canAutoCompleteProgramInstanceStatus( ProgramInstance programInstance ) { Set<ProgramStageInstance> programStageInstances = new HashSet<>( programInstance.getProgramStageInstances() ); Set<ProgramStage> programStages = new HashSet<>(); for ( ProgramStageInstance programStageInstance : programStageInstances ) { if ( (!programStageInstance.isCompleted() && programStageInstance.getStatus() != EventStatus.SKIPPED) || programStageInstance.getProgramStage().getRepeatable() ) { return false; } programStages.add( programStageInstance.getProgramStage() ); } return programStages.size() == programInstance.getProgram().getProgramStages().size(); } @Override @Transactional public void completeProgramInstanceStatus( ProgramInstance programInstance ) { // Update program-instance programInstance.setStatus( ProgramStatus.COMPLETED ); updateProgramInstance( programInstance ); // Send sms-message after program completion eventPublisher.publishEvent( new ProgramEnrollmentCompletionNotificationEvent( this, programInstance.getId() ) ); eventPublisher.publishEvent( new EnrollmentEvaluationEvent( this, programInstance.getId() ) ); } @Override @Transactional public void cancelProgramInstanceStatus( ProgramInstance programInstance ) { // Set status of the program-instance programInstance.setStatus( ProgramStatus.CANCELLED ); updateProgramInstance( programInstance ); // Set statuses of the program-stage-instances for ( ProgramStageInstance programStageInstance : programInstance.getProgramStageInstances() ) { if ( programStageInstance.getExecutionDate() == null ) { // Set status as skipped for overdue events, or delete if ( programStageInstance.getDueDate().before( programInstance.getEndDate() ) ) { programStageInstance.setStatus( EventStatus.SKIPPED ); programStageInstanceStore.update( programStageInstance ); } else { programStageInstanceStore.delete( programStageInstance ); } } } } @Override @Transactional public void incompleteProgramInstanceStatus( ProgramInstance programInstance ) { Program program = programInstance.getProgram(); TrackedEntityInstance tei = programInstance.getEntityInstance(); if ( getProgramInstances( tei, program, ProgramStatus.ACTIVE ).size() > 0 ) { log.warn( "Program has another active enrollment going on. Not possible to incomplete" ); throw new IllegalQueryException( "Program has another active enrollment going on. Not possible to incomplete" ); } // Update program-instance programInstance.setStatus( ProgramStatus.ACTIVE ); programInstance.setEndDate( null ); updateProgramInstance( programInstance ); } private void addProgramInstanceAudit( ProgramInstance programInstance, String accessedBy ) { if ( programInstance != null && programInstance.getProgram().getAccessLevel() != null && programInstance.getProgram().getAccessLevel() != AccessLevel.OPEN && accessedBy != null ) { ProgramInstanceAudit programInstanceAudit = new ProgramInstanceAudit( programInstance, accessedBy, AuditType.READ ); programInstanceAuditService.addProgramInstanceAudit( programInstanceAudit ); } } private void addProrgamInstanceAudits( List<ProgramInstance> programInstances, String accessedBy ) { for ( ProgramInstance programInstance : programInstances ) { addProgramInstanceAudit( programInstance, accessedBy ); } } }
package org.monarchinitiative.exomiser.data.genome; import org.junit.Test; import org.monarchinitiative.exomiser.data.genome.archive.AlleleArchive; import org.monarchinitiative.exomiser.data.genome.archive.TabixAlleleArchive; import org.monarchinitiative.exomiser.data.genome.model.Allele; import org.monarchinitiative.exomiser.data.genome.parsers.DbSnpAlleleParser; import org.monarchinitiative.exomiser.data.genome.writers.AlleleWriter; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; /** * @author Jules Jacobsen <j.jacobsen@qmul.ac.uk> */ public class AlleleArchiveProcessorTest { @Test public void process() throws Exception { AlleleArchive dbsnpArchive = new TabixAlleleArchive(Paths.get("src/test/resources/test_first_ten_dbsnp.vcf.gz")); AlleleArchiveProcessor instance = new AlleleArchiveProcessor(dbsnpArchive, new DbSnpAlleleParser()); TestAlleleWriter testAlleleWriter = new TestAlleleWriter(); instance.process(testAlleleWriter); assertThat(testAlleleWriter.count(), equalTo(10L)); testAlleleWriter.getAlleles().forEach(System.out::println); } private class TestAlleleWriter implements AlleleWriter { private final List<Allele> alleles = new ArrayList<>(); public List<Allele> getAlleles() { return alleles; } @Override public void writeAllele(Allele allele) { alleles.add(allele); } @Override public long count() { return alleles.size(); } } }
package org.innovateuk.ifs.project.transactional; import org.apache.commons.lang3.tuple.Pair; import org.innovateuk.ifs.BaseServiceUnitTest; import org.innovateuk.ifs.address.builder.AddressBuilder; import org.innovateuk.ifs.address.domain.Address; import org.innovateuk.ifs.application.domain.Application; import org.innovateuk.ifs.commons.error.CommonErrors; import org.innovateuk.ifs.commons.error.CommonFailureKeys; import org.innovateuk.ifs.commons.rest.LocalDateResource; import org.innovateuk.ifs.commons.service.ServiceResult; import org.innovateuk.ifs.competition.domain.Competition; import org.innovateuk.ifs.file.domain.FileEntry; import org.innovateuk.ifs.file.resource.FileEntryResource; import org.innovateuk.ifs.finance.resource.ApplicationFinanceResource; import org.innovateuk.ifs.project.builder.PartnerOrganisationBuilder; import org.innovateuk.ifs.project.domain.PartnerOrganisation; import org.innovateuk.ifs.project.domain.Project; import org.innovateuk.ifs.project.domain.ProjectUser; import org.innovateuk.ifs.project.finance.resource.FinanceCheckSummaryResource; import org.innovateuk.ifs.project.resource.ApprovalType; import org.innovateuk.ifs.project.resource.ProjectOrganisationCompositeId; import org.innovateuk.ifs.project.resource.ProjectResource; import org.innovateuk.ifs.project.resource.SpendProfileTableResource; import org.innovateuk.ifs.user.domain.Organisation; import org.innovateuk.ifs.user.domain.ProcessRole; import org.innovateuk.ifs.user.domain.Role; import org.innovateuk.ifs.user.domain.User; import org.innovateuk.ifs.user.resource.OrganisationResource; import org.innovateuk.ifs.user.resource.UserResource; import org.innovateuk.ifs.user.resource.UserRoleType; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.nio.charset.StandardCharsets; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Supplier; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.hamcrest.core.IsNull.notNullValue; import static org.hamcrest.core.IsNull.nullValue; import static org.innovateuk.ifs.address.builder.AddressBuilder.newAddress; import static org.innovateuk.ifs.application.builder.ApplicationBuilder.newApplication; import static org.innovateuk.ifs.commons.service.ServiceResult.serviceSuccess; import static org.innovateuk.ifs.competition.builder.CompetitionBuilder.newCompetition; import static org.innovateuk.ifs.file.builder.FileEntryBuilder.newFileEntry; import static org.innovateuk.ifs.file.builder.FileEntryResourceBuilder.newFileEntryResource; import static org.innovateuk.ifs.finance.builder.ApplicationFinanceResourceBuilder.newApplicationFinanceResource; import static org.innovateuk.ifs.finance.resource.cost.FinanceRowType.LABOUR; import static org.innovateuk.ifs.invite.domain.ProjectParticipantRole.PROJECT_MANAGER; import static org.innovateuk.ifs.invite.domain.ProjectParticipantRole.PROJECT_PARTNER; import static org.innovateuk.ifs.project.builder.CostCategoryResourceBuilder.newCostCategoryResource; import static org.innovateuk.ifs.project.builder.PartnerOrganisationBuilder.newPartnerOrganisation; import static org.innovateuk.ifs.project.builder.ProjectBuilder.newProject; import static org.innovateuk.ifs.project.builder.ProjectUserBuilder.newProjectUser; import static org.innovateuk.ifs.project.finance.builder.FinanceCheckSummaryResourceBuilder.newFinanceCheckSummaryResource; import static org.innovateuk.ifs.user.builder.OrganisationBuilder.newOrganisation; import static org.innovateuk.ifs.user.builder.OrganisationResourceBuilder.newOrganisationResource; import static org.innovateuk.ifs.user.builder.ProcessRoleBuilder.newProcessRole; import static org.innovateuk.ifs.user.builder.RoleBuilder.newRole; import static org.innovateuk.ifs.user.builder.UserBuilder.newUser; import static org.innovateuk.ifs.user.builder.UserResourceBuilder.newUserResource; import static org.innovateuk.ifs.user.resource.OrganisationTypeEnum.ACADEMIC; import static org.innovateuk.ifs.user.resource.OrganisationTypeEnum.BUSINESS; import static org.innovateuk.ifs.util.MapFunctions.asMap; import static org.junit.Assert.*; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.*; public class ProjectGrantOfferServiceImplTest extends BaseServiceUnitTest<ProjectGrantOfferService> { private Long projectId = 123L; private Long applicationId = 456L; private Long userId = 7L; private Application application; private List<Organisation> organisations; private Role leadApplicantRole; private User user; private ProcessRole leadApplicantProcessRole; private ProjectUser leadPartnerProjectUser; private Project project; private List<OrganisationResource> organisationResources; private SpendProfileTableResource table; @Captor ArgumentCaptor<Map<String, Object> > templateArgsCaptor; @Captor ArgumentCaptor<String> templateCaptor; @Captor ArgumentCaptor<FileEntryResource> fileEntryResCaptor; @Captor ArgumentCaptor<Supplier<InputStream>> supplierCaptor; @Before public void setUp() { ApplicationFinanceResource applicationFinanceResource = newApplicationFinanceResource().withGrantClaimPercentage(30) .withApplication(456L).withOrganisation(3L) .build(); table = new SpendProfileTableResource(); table.setMarkedAsComplete(true); table.setMonthlyCostsPerCategoryMap(asMap( 1L, asList(new BigDecimal("30.44"), new BigDecimal("30"), new BigDecimal("40")), 2L, asList(new BigDecimal("70"), new BigDecimal("50.10"), new BigDecimal("60")), 3L, asList(new BigDecimal("50"), new BigDecimal("5"), new BigDecimal("10.31")))); table.setCostCategoryGroupMap(asMap( LABOUR, asList(asMap( 1L, asList(new BigDecimal("30.44"), new BigDecimal("30"), new BigDecimal("40")), 2L, asList(new BigDecimal("70"), new BigDecimal("50.10"), new BigDecimal("60")), 3L, asList(new BigDecimal("50"), new BigDecimal("5"), new BigDecimal("10.31"))) ))); table.setEligibleCostPerCategoryMap(asMap( 1L, asList(new BigDecimal("30.44"), new BigDecimal("30"), new BigDecimal("40")), 2L, asList(new BigDecimal("70"), new BigDecimal("50.10"), new BigDecimal("60")), 3L, asList(new BigDecimal("50"), new BigDecimal("5"), new BigDecimal("10.31")) )); table.setCostCategoryResourceMap(asMap( 1L, newCostCategoryResource().withName("Labour").build(), 2L, newCostCategoryResource().withName("Materials").build(), 3L, newCostCategoryResource().withName("Other").build() )); table.setMonths(asList( new LocalDateResource(1, 3, 2019),new LocalDateResource(1, 4, 2019))); organisations = newOrganisation().withOrganisationType(ACADEMIC).build(3); organisationResources = newOrganisationResource().build(3); Competition competition = newCompetition().build(); Address address = newAddress().withAddressLine1("test1") .withAddressLine2("test2") .withPostcode("PST") .withTown("town").build(); leadApplicantRole = newRole(UserRoleType.LEADAPPLICANT).build(); user = newUser(). withId(userId). build(); leadApplicantProcessRole = newProcessRole(). withOrganisation(organisations.get(0)). withRole(leadApplicantRole). withUser(user). build(); leadPartnerProjectUser = newProjectUser(). withOrganisation(this.organisations.get(0)). withRole(PROJECT_PARTNER). withUser(user). build(); application = newApplication(). withId(applicationId). withCompetition(competition). withProcessRoles(leadApplicantProcessRole). withName("My Application"). withDurationInMonths(5L). withStartDate(LocalDate.of(2017, 3, 2)). build(); PartnerOrganisation partnerOrganisation = newPartnerOrganisation().withOrganisation(organisations.get(0)).build(); PartnerOrganisation partnerOrganisation2 = newPartnerOrganisation().withOrganisation(organisations.get(1)).build(); PartnerOrganisation partnerOrganisation3 = newPartnerOrganisation().withOrganisation(organisations.get(2)).build(); List<PartnerOrganisation> partnerOrganisations = new ArrayList<>(); partnerOrganisations.add(partnerOrganisation); partnerOrganisations.add(partnerOrganisation2); partnerOrganisations.add(partnerOrganisation3); project = newProject(). withId(projectId). withPartnerOrganisations(partnerOrganisations). withAddress(address). withApplication(application). withProjectUsers(singletonList(leadPartnerProjectUser)). build(); FinanceCheckSummaryResource financeCheckSummaryResource = newFinanceCheckSummaryResource() .withTotalPercentageGrant(BigDecimal.valueOf(25)) .build(); List<BigDecimal> monthlyTotals = asList( BigDecimal.valueOf(50), BigDecimal.valueOf(10), BigDecimal.valueOf(20)); List<BigDecimal> yearlyCosts = asList( BigDecimal.valueOf(500), BigDecimal.valueOf(100), BigDecimal.valueOf(200)); when(projectRepositoryMock.findOne(projectId)).thenReturn(project); when(organisationMapperMock.mapToResource(organisations.get(0))).thenReturn(organisationResources.get(0)); when(organisationMapperMock.mapToResource(organisations.get(1))).thenReturn(organisationResources.get(1)); when(organisationMapperMock.mapToResource(organisations.get(2))).thenReturn(organisationResources.get(2)); when(organisationFinanceDelegateMock.isUsingJesFinances(ACADEMIC.name())).thenReturn(true); when(financeRowServiceMock.financeDetails(project.getApplication().getId(), organisations.get(0).getId())).thenReturn(ServiceResult.serviceSuccess(applicationFinanceResource)); when(financeRowServiceMock.financeDetails(project.getApplication().getId(), organisations.get(1).getId())).thenReturn(ServiceResult.serviceSuccess(applicationFinanceResource)); when(financeRowServiceMock.financeDetails(project.getApplication().getId(), organisations.get(2).getId())).thenReturn(ServiceResult.serviceSuccess(applicationFinanceResource)); when(projectFinanceServiceMock.getSpendProfileTable(any(ProjectOrganisationCompositeId.class))) .thenReturn(ServiceResult.serviceSuccess(table)); when(spendProfileTableCalculatorMock.calculateMonthlyTotals(table.getMonthlyCostsPerCategoryMap(), table.getMonths().size())).thenReturn(monthlyTotals); when(spendProfileTableCalculatorMock.calculateEligibleCostPerYear(any(ProjectResource.class), any(List.class), any(List.class))).thenReturn(yearlyCosts); when(financeCheckServiceMock.getFinanceCheckSummary(project.getId())).thenReturn(ServiceResult.serviceSuccess(financeCheckSummaryResource)); } @Test public void testCreateSignedGrantOfferLetterFileEntry() { assertCreateFile( project::getSignedGrantOfferLetter, (fileToCreate, inputStreamSupplier) -> service.createSignedGrantOfferLetterFileEntry(123L, fileToCreate, inputStreamSupplier)); } @Test public void testCreateGrantOfferLetterFileEntry() { assertCreateFile( project::getGrantOfferLetter, (fileToCreate, inputStreamSupplier) -> service.createGrantOfferLetterFileEntry(123L, fileToCreate, inputStreamSupplier)); } @Test public void testCreateAdditionalContractFileEntry() { assertCreateFile( project::getAdditionalContractFile, (fileToCreate, inputStreamSupplier) -> service.createAdditionalContractFileEntry(123L, fileToCreate, inputStreamSupplier)); } @Test public void testGetAdditionalContractFileEntryDetails() { assertGetFileDetails( project::setAdditionalContractFile, () -> service.getAdditionalContractFileEntryDetails(123L)); } @Test public void testGetGrantOfferLetterFileEntryDetails() { assertGetFileDetails( project::setGrantOfferLetter, () -> service.getGrantOfferLetterFileEntryDetails(123L)); } @Test public void testGetSignedGrantOfferLetterFileEntryDetails() { assertGetFileDetails( project::setSignedGrantOfferLetter, () -> service.getSignedGrantOfferLetterFileEntryDetails(123L)); } @Test public void testGetAdditionalContractFileContents() { assertGetFileContents( project::setAdditionalContractFile, () -> service.getAdditionalContractFileAndContents(123L)); } @Test public void testGetGrantOfferLetterFileContents() { assertGetFileContents( project::setGrantOfferLetter, () -> service.getGrantOfferLetterFileAndContents(123L)); } @Test public void testGetSignedGrantOfferLetterFileContents() { assertGetFileContents( project::setSignedGrantOfferLetter, () -> service.getSignedGrantOfferLetterFileAndContents(123L)); } @Test public void testUpdateSignedGrantOfferLetterFileEntry() { when(golWorkflowHandlerMock.isSent(any())).thenReturn(Boolean.TRUE); assertUpdateFile( project::getSignedGrantOfferLetter, (fileToUpdate, inputStreamSupplier) -> service.updateSignedGrantOfferLetterFile(123L, fileToUpdate, inputStreamSupplier)); } @Test public void testUpdateSignedGrantOfferLetterFileEntryGolNotSent() { FileEntryResource fileToUpdate = newFileEntryResource().build(); Supplier<InputStream> inputStreamSupplier = () -> null; when(golWorkflowHandlerMock.isSent(any())).thenReturn(Boolean.FALSE); ServiceResult<Void> result = service.updateSignedGrantOfferLetterFile(123L, fileToUpdate, inputStreamSupplier); assertTrue(result.isFailure()); assertEquals(result.getErrors().get(0).getErrorKey(), CommonFailureKeys.GRANT_OFFER_LETTER_MUST_BE_SENT_BEFORE_UPLOADING_SIGNED_COPY.toString()); } @Test public void testSubmitGrantOfferLetterFailureNoSignedGolFile() { ServiceResult<Void> result = service.submitGrantOfferLetter(projectId); assertTrue(result.getFailure().is(CommonFailureKeys.SIGNED_GRANT_OFFER_LETTER_MUST_BE_UPLOADED_BEFORE_SUBMIT)); Assert.assertThat(project.getOfferSubmittedDate(), nullValue()); } @Test public void testSubmitGrantOfferLetterFailureCannotReachSignedState() { project.setSignedGrantOfferLetter(mock(FileEntry.class)); when(golWorkflowHandlerMock.sign(any())).thenReturn(Boolean.FALSE); ServiceResult<Void> result = service.submitGrantOfferLetter(projectId); assertTrue(result.getFailure().is(CommonFailureKeys.GRANT_OFFER_LETTER_CANNOT_SET_SIGNED_STATE)); Assert.assertThat(project.getOfferSubmittedDate(), nullValue()); } @Test public void testSubmitGrantOfferLetterSuccess() { project.setSignedGrantOfferLetter(mock(FileEntry.class)); when(golWorkflowHandlerMock.sign(any())).thenReturn(Boolean.TRUE); ServiceResult<Void> result = service.submitGrantOfferLetter(projectId); assertTrue(result.isSuccess()); Assert.assertThat(project.getOfferSubmittedDate(), notNullValue()); } @Test public void testGenerateGrantOfferLetter() { assertGenerateFile( fileEntryResource -> service.generateGrantOfferLetter(123L, fileEntryResource)); } @Test public void testRemoveGrantOfferLetterFileEntry() { UserResource internalUserResource = newUserResource().build(); User internalUser = newUser().withId(internalUserResource.getId()).build(); setLoggedInUser(internalUserResource); FileEntry existingGOLFile = newFileEntry().build(); project.setGrantOfferLetter(existingGOLFile); when(userRepositoryMock.findOne(internalUserResource.getId())).thenReturn(internalUser); when(golWorkflowHandlerMock.removeGrantOfferLetter(project, internalUser)).thenReturn(true); when(fileServiceMock.deleteFile(existingGOLFile.getId())).thenReturn(serviceSuccess(existingGOLFile)); ServiceResult<Void> result = service.removeGrantOfferLetterFileEntry(123L); assertTrue(result.isSuccess()); assertNull(project.getGrantOfferLetter()); verify(golWorkflowHandlerMock).removeGrantOfferLetter(project, internalUser); verify(fileServiceMock).deleteFile(existingGOLFile.getId()); } @Test public void testRemoveGrantOfferLetterFileEntryButWorkflowRejected() { UserResource internalUserResource = newUserResource().build(); User internalUser = newUser().withId(internalUserResource.getId()).build(); setLoggedInUser(internalUserResource); FileEntry existingGOLFile = newFileEntry().build(); project.setGrantOfferLetter(existingGOLFile); when(userRepositoryMock.findOne(internalUserResource.getId())).thenReturn(internalUser); when(golWorkflowHandlerMock.removeGrantOfferLetter(project, internalUser)).thenReturn(false); ServiceResult<Void> result = service.removeGrantOfferLetterFileEntry(123L); assertTrue(result.isFailure()); assertTrue(result.getFailure().is(CommonFailureKeys.GRANT_OFFER_LETTER_CANNOT_BE_REMOVED)); assertEquals(existingGOLFile, project.getGrantOfferLetter()); verify(golWorkflowHandlerMock).removeGrantOfferLetter(project, internalUser); verify(fileServiceMock, never()).deleteFile(existingGOLFile.getId()); } @Test public void testGenerateGrantOfferLetterIfReadySuccess() { FileEntryResource fileEntryResource = newFileEntryResource(). withFilesizeBytes(1024). withMediaType("application/pdf"). withName("grant_offer_letter"). build(); FileEntry createdFile = newFileEntry().build(); Pair<File, FileEntry> fileEntryPair = Pair.of(new File("blah"), createdFile); StringBuilder stringBuilder = new StringBuilder(); String htmlFile = stringBuilder.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n") .append("<html dir=\"ltr\" lang=\"en\">\n") .append("<head>\n") .append("<meta charset=\"UTF-8\"></meta>\n") .append("</head>\n") .append("<body>\n") .append("<p>\n") .append("${LeadContact}<br/>\n") .append("</p>\n") .append("</body>\n") .append("</html>\n").toString(); Competition comp = newCompetition().withName("Test Comp").build(); Organisation o = newOrganisation().withOrganisationType(BUSINESS).withName("Org1").build(); Role leadAppRole = newRole(UserRoleType.LEADAPPLICANT).build(); User u = newUser().withFirstName("ab").withLastName("cd").build(); ProcessRole leadAppProcessRole = newProcessRole().withOrganisation(o).withUser(u).withRole(leadAppRole).build(); Application app = newApplication().withCompetition(comp).withProcessRoles(leadAppProcessRole).withId(3L).build(); ProjectUser pm = newProjectUser().withRole(PROJECT_MANAGER).withOrganisation(o).build(); PartnerOrganisation po = PartnerOrganisationBuilder.newPartnerOrganisation().withOrganisation(o).withLeadOrganisation(true).build(); Address address = AddressBuilder.newAddress().withAddressLine1("InnovateUK").withAddressLine2("Northstar House").withTown("Swindon").withPostcode("SN1 1AA").build(); Project project = newProject().withOtherDocumentsApproved(Boolean.TRUE).withName("project 1").withApplication(app).withPartnerOrganisations(asList(po)).withProjectUsers(asList(pm)).withDuration(10L).withAddress(address).build(); ApplicationFinanceResource applicationFinanceResource = newApplicationFinanceResource().withGrantClaimPercentage(30).withApplication(456L).withOrganisation(3L) .build(); FinanceCheckSummaryResource financeCheckSummaryResource = newFinanceCheckSummaryResource() .withTotalPercentageGrant(BigDecimal.valueOf(25)) .build(); Map<String, Object> templateArgs = new HashMap<String, Object>(); templateArgs.put("ProjectLength", 10L); templateArgs.put("ProjectTitle", "project 1"); templateArgs.put("LeadContact", "ab cd"); templateArgs.put("ApplicationNumber", 3L); templateArgs.put("LeadOrgName", "Org1"); templateArgs.put("CompetitionName", "Test Comp"); templateArgs.put("Address1", "InnovateUK"); templateArgs.put("Address2", "Northstar House"); templateArgs.put("Address3", ""); templateArgs.put("TownCity", "Swindon"); templateArgs.put("PostCode", "SN1 1AA"); templateArgs.put("ProjectStartDate",""); templateArgs.put("Date", LocalDateTime.now().toString()); // will never match generated value templateArgs.put("TableData", ""); //TODO this will be complicated to verify... when(projectFinanceServiceMock.getSpendProfileStatusByProjectId(123L)).thenReturn(serviceSuccess(ApprovalType.APPROVED)); when(projectRepositoryMock.findOne(123L)).thenReturn(project); when(rendererMock.renderTemplate(eq("common/grantoffer/grant_offer_letter.html"), any(Map.class))).thenReturn(ServiceResult.serviceSuccess(htmlFile)); when(fileServiceMock.createFile(any(FileEntryResource.class), any(Supplier.class))).thenReturn(ServiceResult.serviceSuccess(fileEntryPair)); when(fileEntryMapperMock.mapToResource(createdFile)).thenReturn(fileEntryResource); when(financeCheckServiceMock.getFinanceCheckSummary(project.getId())).thenReturn(ServiceResult.serviceSuccess(financeCheckSummaryResource)); when(organisationFinanceDelegateMock.isUsingJesFinances(BUSINESS.name())).thenReturn(false); when(financeRowServiceMock.financeDetails(project.getApplication().getId(), o.getId())).thenReturn(ServiceResult.serviceSuccess(applicationFinanceResource)); ServiceResult<Void> result = service.generateGrantOfferLetterIfReady(123L); verify(rendererMock).renderTemplate(templateCaptor.capture(), templateArgsCaptor.capture()); verify(fileServiceMock).createFile(fileEntryResCaptor.capture(), supplierCaptor.capture()); assertEquals(templateArgs.get("ProjectLength"), templateArgsCaptor.getAllValues().get(0).get("ProjectLength")); assertEquals(templateArgs.get("ProjectTitle"), templateArgsCaptor.getAllValues().get(0).get("ProjectTitle")); assertEquals(templateArgs.get("ProjectStartDate"), templateArgsCaptor.getAllValues().get(0).get("ProjectStartDate")); assertEquals(templateArgs.get("LeadContact"), templateArgsCaptor.getAllValues().get(0).get("LeadContact")); assertEquals(templateArgs.get("ApplicationNumber"), templateArgsCaptor.getAllValues().get(0).get("ApplicationNumber")); assertEquals(templateArgs.get("LeadOrgName"), templateArgsCaptor.getAllValues().get(0).get("LeadOrgName")); assertEquals(templateArgs.get("CompetitionName"), templateArgsCaptor.getAllValues().get(0).get("CompetitionName")); assertEquals(templateArgs.get("Address1"), templateArgsCaptor.getAllValues().get(0).get("Address1")); assertEquals(templateArgs.get("Address2"), templateArgsCaptor.getAllValues().get(0).get("Address2")); assertEquals(templateArgs.get("Address3"), templateArgsCaptor.getAllValues().get(0).get("Address3")); assertEquals(templateArgs.get("TownCity"), templateArgsCaptor.getAllValues().get(0).get("TownCity")); assertEquals(templateArgs.get("PostCode"), templateArgsCaptor.getAllValues().get(0).get("PostCode")); assertEquals(fileEntryResource.getMediaType(), fileEntryResCaptor.getAllValues().get(0).getMediaType()); assertEquals(fileEntryResource.getName() + ".pdf", fileEntryResCaptor.getAllValues().get(0).getName()); String startOfGeneratedFileString = null; try { int n = supplierCaptor.getAllValues().get(0).get().available(); byte [] startOfGeneratedFile = new byte[n]; supplierCaptor.getAllValues().get(0).get().read(startOfGeneratedFile, 0, n <9 ? n : 9); startOfGeneratedFileString = new String(startOfGeneratedFile, StandardCharsets.UTF_8); } catch(IOException e) { } String pdfHeader = "%PDF-1.4\n"; assertEquals(pdfHeader, startOfGeneratedFileString.substring(0, pdfHeader.length())); assertTrue(result.isSuccess()); } @Test public void testGenerateGrantOfferLetterFailureSpendProfilesNotApproved() { when(projectFinanceServiceMock.getSpendProfileStatusByProjectId(123L)).thenReturn(serviceSuccess(ApprovalType.REJECTED)); ServiceResult<Void> result = service.generateGrantOfferLetterIfReady(123L); assertTrue(result.isSuccess()); } @Test public void testGenerateGrantOfferLetterOtherDocsNotApproved() { Competition comp = newCompetition().withName("Test Comp").build(); Organisation o = newOrganisation().withName("Org1").build(); Role leadAppRole = newRole(UserRoleType.LEADAPPLICANT).build(); User u = newUser().withFirstName("ab").withLastName("cd").build(); ProcessRole leadAppProcessRole = newProcessRole().withOrganisation(o).withUser(u).withRole(leadAppRole).build(); Application app = newApplication().withCompetition(comp).withProcessRoles(leadAppProcessRole).withId(3L).build(); ProjectUser pm = newProjectUser().withRole(PROJECT_MANAGER).withOrganisation(o).build(); PartnerOrganisation po = PartnerOrganisationBuilder.newPartnerOrganisation().withOrganisation(o).withLeadOrganisation(true).build(); Project project = newProject().withOtherDocumentsApproved(Boolean.FALSE).withApplication(app).withPartnerOrganisations(asList(po)).withProjectUsers(asList(pm)).withDuration(10L).build(); when(projectFinanceServiceMock.getSpendProfileStatusByProjectId(123L)).thenReturn(serviceSuccess(ApprovalType.APPROVED)); when(projectRepositoryMock.findOne(123L)).thenReturn(project); ServiceResult<Void> result = service.generateGrantOfferLetterIfReady(123L); assertTrue(result.isSuccess()); } @Test public void testGenerateGrantOfferLetterNoProject() { when(projectFinanceServiceMock.getSpendProfileStatusByProjectId(123L)).thenReturn(serviceSuccess(ApprovalType.APPROVED)); when(projectRepositoryMock.findOne(123L)).thenReturn(null); ServiceResult<Void> result = service.generateGrantOfferLetterIfReady(123L); assertTrue(result.isFailure()); assertTrue(result.getFailure().is(CommonErrors.notFoundError(Project.class, 123L))); } @Override protected ProjectGrantOfferService supplyServiceUnderTest() { return new ProjectGrantOfferServiceImpl(); } }
package org.eclipse.kura.net.admin.monitor; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.Dictionary; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.eclipse.kura.KuraException; import org.eclipse.kura.comm.CommURI; import org.eclipse.kura.core.net.AbstractNetInterface; import org.eclipse.kura.core.net.NetworkConfiguration; import org.eclipse.kura.linux.net.ConnectionInfoImpl; import org.eclipse.kura.linux.net.modem.SupportedSerialModemInfo; import org.eclipse.kura.linux.net.modem.SupportedSerialModemsInfo; import org.eclipse.kura.linux.net.modem.SupportedUsbModemInfo; import org.eclipse.kura.linux.net.modem.SupportedUsbModemsInfo; import org.eclipse.kura.linux.net.util.LinuxNetworkUtil; import org.eclipse.kura.net.ConnectionInfo; import org.eclipse.kura.net.NetConfig; import org.eclipse.kura.net.NetConfigIP4; import org.eclipse.kura.net.NetInterface; import org.eclipse.kura.net.NetInterfaceAddress; import org.eclipse.kura.net.NetInterfaceAddressConfig; import org.eclipse.kura.net.NetInterfaceConfig; import org.eclipse.kura.net.NetInterfaceStatus; import org.eclipse.kura.net.NetworkService; import org.eclipse.kura.net.admin.NetworkConfigurationService; import org.eclipse.kura.net.admin.event.NetworkConfigurationChangeEvent; import org.eclipse.kura.net.admin.event.NetworkStatusChangeEvent; import org.eclipse.kura.net.admin.modem.CellularModemFactory; import org.eclipse.kura.net.admin.modem.EvdoCellularModem; import org.eclipse.kura.net.admin.modem.HspaCellularModem; import org.eclipse.kura.net.admin.modem.IModemLinkService; import org.eclipse.kura.net.admin.modem.PppFactory; import org.eclipse.kura.net.admin.modem.PppState; import org.eclipse.kura.net.admin.modem.SupportedSerialModemsFactoryInfo; import org.eclipse.kura.net.admin.modem.SupportedSerialModemsFactoryInfo.SerialModemFactoryInfo; import org.eclipse.kura.net.admin.modem.SupportedUsbModemsFactoryInfo; import org.eclipse.kura.net.admin.modem.SupportedUsbModemsFactoryInfo.UsbModemFactoryInfo; import org.eclipse.kura.net.admin.visitor.linux.util.KuranetConfig; import org.eclipse.kura.net.modem.CellularModem; import org.eclipse.kura.net.modem.ModemAddedEvent; import org.eclipse.kura.net.modem.ModemConfig; import org.eclipse.kura.net.modem.ModemDevice; import org.eclipse.kura.net.modem.ModemGpsDisabledEvent; import org.eclipse.kura.net.modem.ModemGpsEnabledEvent; import org.eclipse.kura.net.modem.ModemInterface; import org.eclipse.kura.net.modem.ModemManagerService; import org.eclipse.kura.net.modem.ModemMonitorListener; import org.eclipse.kura.net.modem.ModemMonitorService; import org.eclipse.kura.net.modem.ModemReadyEvent; import org.eclipse.kura.net.modem.ModemRemovedEvent; import org.eclipse.kura.net.modem.ModemTechnologyType; import org.eclipse.kura.net.modem.SerialModemDevice; import org.eclipse.kura.system.SystemService; import org.eclipse.kura.usb.UsbDeviceEvent; import org.eclipse.kura.usb.UsbModemDevice; import org.osgi.service.component.ComponentContext; import org.osgi.service.event.Event; import org.osgi.service.event.EventAdmin; import org.osgi.service.event.EventConstants; import org.osgi.service.event.EventHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ModemMonitorServiceImpl implements ModemMonitorService, ModemManagerService, EventHandler { private static final Logger logger = LoggerFactory.getLogger(ModemMonitorServiceImpl.class); private static final String[] EVENT_TOPICS = new String[] { NetworkConfigurationChangeEvent.NETWORK_EVENT_CONFIG_CHANGE_TOPIC, ModemAddedEvent.MODEM_EVENT_ADDED_TOPIC, ModemRemovedEvent.MODEM_EVENT_REMOVED_TOPIC, }; private static final long THREAD_INTERVAL = 30000; private static final long THREAD_TERMINATION_TOUT = 1; // in seconds private static Object lock = new Object(); private Future<?> task; private static AtomicBoolean stopThread; private SystemService systemService; private NetworkService networkService; private NetworkConfigurationService netConfigService; private EventAdmin eventAdmin; private List<ModemMonitorListener> listeners; private ExecutorService executor; private Map<String, CellularModem> modems; private Map<String, InterfaceState> interfaceStatuses; private NetworkConfiguration networkConfig; private boolean serviceActivated; private PppState pppState; private long resetTimerStart; public void setNetworkService(NetworkService networkService) { this.networkService = networkService; } public void unsetNetworkService(NetworkService networkService) { this.networkService = null; } public void setEventAdmin(EventAdmin eventAdmin) { this.eventAdmin = eventAdmin; } public void unsetEventAdmin(EventAdmin eventAdmin) { this.eventAdmin = null; } public void setNetworkConfigurationService(NetworkConfigurationService netConfigService) { this.netConfigService = netConfigService; } public void unsetNetworkConfigurationService(NetworkConfigurationService netConfigService) { this.netConfigService = null; } public void setSystemService(SystemService systemService) { this.systemService = systemService; } public void unsetSystemService(SystemService systemService) { this.systemService = null; } protected void activate(ComponentContext componentContext) { this.pppState = PppState.NOT_CONNECTED; this.resetTimerStart = 0L; Dictionary<String, String[]> d = new Hashtable<>(); d.put(EventConstants.EVENT_TOPIC, EVENT_TOPICS); componentContext.getBundleContext().registerService(EventHandler.class.getName(), this, d); this.modems = new HashMap<>(); this.interfaceStatuses = new HashMap<>(); this.listeners = new ArrayList<>(); stopThread = new AtomicBoolean(); // must be initialized before trackModem() is called; risk of NPE otherwise this.executor = Executors.newSingleThreadExecutor(); // track currently installed modems try { this.networkConfig = this.netConfigService.getNetworkConfiguration(); for (NetInterface<? extends NetInterfaceAddress> netInterface : this.networkService .getNetworkInterfaces()) { if (netInterface instanceof ModemInterface) { ModemDevice modemDevice = ((ModemInterface<?>) netInterface).getModemDevice(); trackModem(modemDevice); } } } catch (Exception e) { logger.error("Error getting installed modems", e); } submitMonitorTask(); this.serviceActivated = true; logger.debug("ModemMonitor activated and ready to receive events"); } private Future<?> submitMonitorTask() { stopThread.set(false); // is task already prepared? if (task != null) { return task; } // is executor ready? if (this.executor == null) { return null; } task = this.executor.submit(() -> { while (!stopThread.get()) { Thread.currentThread().setName("ModemMonitor"); try { monitor(); monitorWait(); } catch (InterruptedException interruptedException) { Thread.interrupted(); logger.debug("modem monitor interrupted", interruptedException); } catch (Throwable t) { logger.error("Exception while monitoring cellular connection", t); } } }); return task; } protected void deactivate(ComponentContext componentContext) { this.listeners = null; PppFactory.releaseAllPppServices(); if (task != null && !task.isDone()) { stopThread.set(true); monitorNotify(); logger.debug("Cancelling ModemMonitor task ..."); task.cancel(true); logger.info("ModemMonitor task cancelled? = {}", task.isDone()); task = null; } if (this.executor != null) { logger.debug("Terminating ModemMonitor Thread ..."); this.executor.shutdownNow(); try { this.executor.awaitTermination(THREAD_TERMINATION_TOUT, TimeUnit.SECONDS); } catch (InterruptedException e) { logger.warn("Interrupted", e); } logger.info("ModemMonitor Thread terminated? - {}", this.executor.isTerminated()); this.executor = null; } this.serviceActivated = false; this.networkConfig = null; } @Override public void handleEvent(Event event) { logger.debug("handleEvent - topic: {}", event.getTopic()); String topic = event.getTopic(); if (topic.equals(NetworkConfigurationChangeEvent.NETWORK_EVENT_CONFIG_CHANGE_TOPIC)) { NetworkConfigurationChangeEvent netConfigChangedEvent = (NetworkConfigurationChangeEvent) event; String[] propNames = netConfigChangedEvent.getPropertyNames(); if (propNames != null && propNames.length > 0) { Map<String, Object> props = new HashMap<>(); for (String propName : propNames) { Object prop = netConfigChangedEvent.getProperty(propName); if (prop != null) { props.put(propName, prop); } } try { final NetworkConfiguration newNetworkConfig = new NetworkConfiguration(props); ExecutorService ex = Executors.newSingleThreadExecutor(); ex.submit(() -> processNetworkConfigurationChangeEvent(newNetworkConfig)); } catch (Exception e) { logger.error("Failed to handle the NetworkConfigurationChangeEvent ", e); } } } else if (topic.equals(ModemAddedEvent.MODEM_EVENT_ADDED_TOPIC)) { ModemAddedEvent modemAddedEvent = (ModemAddedEvent) event; final ModemDevice modemDevice = modemAddedEvent.getModemDevice(); if (this.serviceActivated) { ExecutorService ex = Executors.newSingleThreadExecutor(); ex.submit(() -> trackModem(modemDevice)); } } else if (topic.equals(ModemRemovedEvent.MODEM_EVENT_REMOVED_TOPIC)) { ModemRemovedEvent modemRemovedEvent = (ModemRemovedEvent) event; String usbPort = (String) modemRemovedEvent.getProperty(UsbDeviceEvent.USB_EVENT_USB_PORT_PROPERTY); this.modems.remove(usbPort); } } @Override public CellularModem getModemService(String usbPort) { return this.modems.get(usbPort); } @Override public Collection<CellularModem> getAllModemServices() { return this.modems.values(); } private NetInterfaceStatus getNetInterfaceStatus(List<NetConfig> netConfigs) { NetInterfaceStatus interfaceStatus = NetInterfaceStatus.netIPv4StatusUnknown; if (netConfigs != null) { for (NetConfig netConfig : netConfigs) { if (netConfig instanceof NetConfigIP4) { interfaceStatus = ((NetConfigIP4) netConfig).getStatus(); break; } } } return interfaceStatus; } private void setNetInterfaceStatus(NetInterfaceStatus netInterfaceStatus, List<NetConfig> netConfigs) { if (netConfigs != null) { for (NetConfig netConfig : netConfigs) { if (netConfig instanceof NetConfigIP4) { ((NetConfigIP4) netConfig).setStatus(netInterfaceStatus); break; } } } } @Override public void registerListener(ModemMonitorListener newListener) { boolean found = false; if (this.listeners == null) { this.listeners = new ArrayList<>(); } if (!this.listeners.isEmpty()) { for (ModemMonitorListener listener : this.listeners) { if (listener.equals(newListener)) { found = true; break; } } } if (!found) { this.listeners.add(newListener); } } @Override public void unregisterListener(ModemMonitorListener listenerToUnregister) { if (this.listeners != null && !this.listeners.isEmpty()) { for (int i = 0; i < this.listeners.size(); i++) { if (this.listeners.get(i).equals(listenerToUnregister)) { this.listeners.remove(i); } } } } private void processNetworkConfigurationChangeEvent(NetworkConfiguration newNetworkConfig) { synchronized (lock) { if (this.modems == null || this.modems.isEmpty()) { return; } for (Map.Entry<String, CellularModem> modemEntry : this.modems.entrySet()) { String usbPort = modemEntry.getKey(); CellularModem modem = modemEntry.getValue(); try { String ifaceName = null; if (this.networkService != null) { ifaceName = this.networkService.getModemPppPort(modem.getModemDevice()); } if (ifaceName != null) { List<NetConfig> oldNetConfigs = modem.getConfiguration(); NetInterfaceConfig<? extends NetInterfaceAddressConfig> netInterfaceConfig = newNetworkConfig .getNetInterfaceConfig(ifaceName); if (netInterfaceConfig == null) { netInterfaceConfig = newNetworkConfig.getNetInterfaceConfig(usbPort); } List<NetConfig> newNetConfigs = null; IModemLinkService pppService = null; int ifaceNo = getInterfaceNumber(oldNetConfigs); if (ifaceNo >= 0) { pppService = PppFactory.obtainPppService(ifaceNo, modem.getDataPort()); } if (netInterfaceConfig != null) { newNetConfigs = ((AbstractNetInterface<?>) netInterfaceConfig).getNetConfigs(); } else { if (oldNetConfigs != null && pppService != null && !ifaceName.equals(pppService.getIfaceName())) { StringBuilder key = new StringBuilder().append("net.interface.").append(ifaceName) .append(".config.ip4.status"); String statusString = KuranetConfig.getProperty(key.toString()); NetInterfaceStatus netInterfaceStatus = NetInterfaceStatus.netIPv4StatusDisabled; if (statusString != null && !statusString.isEmpty()) { netInterfaceStatus = NetInterfaceStatus.valueOf(statusString); } newNetConfigs = oldNetConfigs; oldNetConfigs = null; try { setInterfaceNumber(ifaceName, newNetConfigs); setNetInterfaceStatus(netInterfaceStatus, newNetConfigs); } catch (NumberFormatException e) { logger.error("failed to set new interface number ", e); } } } if (oldNetConfigs == null || !isConfigsEqual(oldNetConfigs, newNetConfigs)) { logger.info("new configuration for cellular modem on usb port {} netinterface {}", usbPort, ifaceName); this.networkConfig = newNetworkConfig; NetInterfaceStatus netInterfaceStatus = getNetInterfaceStatus(newNetConfigs); if (pppService != null && netInterfaceStatus != NetInterfaceStatus.netIPv4StatusUnmanaged) { PppState pppSt = pppService.getPppState(); if (pppSt == PppState.CONNECTED || pppSt == PppState.IN_PROGRESS) { logger.info("disconnecting " + pppService.getIfaceName()); pppService.disconnect(); } PppFactory.releasePppService(pppService.getIfaceName()); } if (modem.isGpsEnabled() && !disableModemGps(modem)) { logger.error("processNetworkConfigurationChangeEvent() :: Failed to disable modem GPS"); modem.reset(); this.resetTimerStart = System.currentTimeMillis(); } modem.setConfiguration(newNetConfigs); if (modem instanceof EvdoCellularModem) { NetInterfaceStatus netIfaceStatus = getNetInterfaceStatus(newNetConfigs); if (netIfaceStatus == NetInterfaceStatus.netIPv4StatusEnabledWAN) { if (!((EvdoCellularModem) modem).isProvisioned()) { logger.info( "NetworkConfigurationChangeEvent :: The {} is not provisioned, will try to provision it ...", modem.getModel()); if (task != null && !task.isCancelled()) { logger.info("NetworkConfigurationChangeEvent :: Cancelling monitor task"); stopThread.set(true); monitorNotify(); task.cancel(true); task = null; } ((EvdoCellularModem) modem).provision(); if (task == null) { logger.info("NetworkConfigurationChangeEvent :: Restarting monitor task"); submitMonitorTask(); } else { monitorNotify(); } } else { logger.info("NetworkConfigurationChangeEvent :: The {} is provisioned", modem.getModel()); } } if (modem.isGpsSupported() && isGpsEnabledInConfig(newNetConfigs) && !modem.isGpsEnabled()) { modem.enableGps(); postModemGpsEvent(modem, true); } } } } } catch (KuraException e) { logger.error("NetworkConfigurationChangeEvent :: Failed to process ", e); } } } } private boolean isConfigsEqual(List<NetConfig> oldConfig, List<NetConfig> newConfig) { if (oldConfig == null || newConfig == null) { return false; } boolean ret = false; ModemConfig oldModemConfig = getModemConfig(oldConfig); ModemConfig newModemConfig = getModemConfig(newConfig); NetConfigIP4 oldNetConfigIP4 = getNetConfigIp4(oldConfig); NetConfigIP4 newNetConfigIP4 = getNetConfigIp4(newConfig); if (oldNetConfigIP4.equals(newNetConfigIP4) && oldModemConfig.equals(newModemConfig)) { ret = true; } return ret; } private ModemConfig getModemConfig(List<NetConfig> netConfigs) { ModemConfig modemConfig = new ModemConfig(); for (NetConfig netConfig : netConfigs) { if (netConfig instanceof ModemConfig) { modemConfig = (ModemConfig) netConfig; break; } } return modemConfig; } private NetConfigIP4 getNetConfigIp4(List<NetConfig> netConfigs) { NetConfigIP4 netConfigIP4 = new NetConfigIP4(NetInterfaceStatus.netIPv4StatusUnknown, false); for (NetConfig netConfig : netConfigs) { if (netConfig instanceof NetConfigIP4) { netConfigIP4 = (NetConfigIP4) netConfig; break; } } return netConfigIP4; } private int getInterfaceNumber(List<NetConfig> netConfigs) { int ifaceNo = -1; if (netConfigs != null) { for (NetConfig netConfig : netConfigs) { if (netConfig instanceof ModemConfig) { ifaceNo = ((ModemConfig) netConfig).getPppNumber(); break; } } } return ifaceNo; } private int getInterfaceNumber(String ifaceName) { return Integer.parseInt(ifaceName.replaceAll("[^0-9]", "")); } private void setInterfaceNumber(String ifaceName, List<NetConfig> netConfigs) { if (netConfigs != null) { for (NetConfig netConfig : netConfigs) { if (netConfig instanceof ModemConfig) { ((ModemConfig) netConfig).setPppNumber(getInterfaceNumber(ifaceName)); break; } } } } private long getModemResetTimeoutMsec(String ifaceName, List<NetConfig> netConfigs) { long resetToutMsec = 0L; if (ifaceName != null && netConfigs != null) { for (NetConfig netConfig : netConfigs) { if (netConfig instanceof ModemConfig) { resetToutMsec = ((ModemConfig) netConfig).getResetTimeout() * 60000; break; } } } return resetToutMsec; } private boolean isGpsEnabledInConfig(List<NetConfig> netConfigs) { boolean isGpsEnabled = false; if (netConfigs != null) { for (NetConfig netConfig : netConfigs) { if (netConfig instanceof ModemConfig) { isGpsEnabled = ((ModemConfig) netConfig).isGpsEnabled(); break; } } } return isGpsEnabled; } private void monitor() { synchronized (lock) { HashMap<String, InterfaceState> newInterfaceStatuses = new HashMap<>(); if (this.modems == null || this.modems.isEmpty()) { return; } for (Map.Entry<String, CellularModem> modemEntry : this.modems.entrySet()) { boolean modemReset = false; CellularModem modem = modemEntry.getValue(); // get signal strength only if somebody needs it if (this.listeners != null && !this.listeners.isEmpty()) { for (ModemMonitorListener listener : this.listeners) { try { int rssi = modem.getSignalStrength(); listener.setCellularSignalLevel(rssi); } catch (KuraException e) { listener.setCellularSignalLevel(0); logger.error("monitor() :: Failed to obtain signal strength - {}", e); } } } IModemLinkService pppService = null; PppState pppSt = null; NetInterfaceStatus netInterfaceStatus = getNetInterfaceStatus(modem.getConfiguration()); try { String ifaceName = this.networkService.getModemPppPort(modem.getModemDevice()); if (netInterfaceStatus == NetInterfaceStatus.netIPv4StatusUnmanaged) { logger.warn( "The {} interface is configured not to be managed by Kura and will not be monitored.", ifaceName); continue; } if (netInterfaceStatus == NetInterfaceStatus.netIPv4StatusEnabledWAN && ifaceName != null) { pppService = PppFactory.obtainPppService(ifaceName, modem.getDataPort()); pppSt = pppService.getPppState(); if (this.pppState != pppSt) { logger.info("monitor() :: previous PppState={}", this.pppState); logger.info("monitor() :: current PppState={}", pppSt); } if (pppSt == PppState.NOT_CONNECTED) { boolean checkIfSimCardReady = false; List<ModemTechnologyType> modemTechnologyTypes = modem.getTechnologyTypes(); for (ModemTechnologyType modemTechnologyType : modemTechnologyTypes) { if (modemTechnologyType == ModemTechnologyType.GSM_GPRS || modemTechnologyType == ModemTechnologyType.UMTS || modemTechnologyType == ModemTechnologyType.HSDPA || modemTechnologyType == ModemTechnologyType.HSPA) { checkIfSimCardReady = true; break; } } if (checkIfSimCardReady) { if (((HspaCellularModem) modem).isSimCardReady()) { logger.info("monitor() :: !!! SIM CARD IS READY !!! connecting ..."); pppService.connect(); if (this.pppState == PppState.NOT_CONNECTED) { this.resetTimerStart = System.currentTimeMillis(); } } else { logger.warn("monitor() :: ! SIM CARD IS NOT READY !"); } } else { logger.info("monitor() :: connecting ..."); pppService.connect(); if (this.pppState == PppState.NOT_CONNECTED) { this.resetTimerStart = System.currentTimeMillis(); } } } else if (pppSt == PppState.IN_PROGRESS) { long modemResetTout = getModemResetTimeoutMsec(ifaceName, modem.getConfiguration()); if (modemResetTout > 0) { long timeElapsed = System.currentTimeMillis() - this.resetTimerStart; if (timeElapsed > modemResetTout) { // reset modem logger.info("monitor() :: Modem Reset TIMEOUT !!!"); pppService.disconnect(); if (modem.isGpsEnabled() && !disableModemGps(modem)) { logger.error("monitor() :: Failed to disable modem GPS"); } modem.reset(); PppFactory.releasePppService(ifaceName); pppSt = PppState.NOT_CONNECTED; this.resetTimerStart = System.currentTimeMillis(); modemReset = true; } else { int timeTillReset = (int) (modemResetTout - timeElapsed) / 1000; logger.info( "monitor() :: PPP connection in progress. Modem will be reset in {} sec if not connected", timeTillReset); } } } else if (pppSt == PppState.CONNECTED) { this.resetTimerStart = System.currentTimeMillis(); } this.pppState = pppSt; ConnectionInfo connInfo = new ConnectionInfoImpl(ifaceName); InterfaceState interfaceState = new InterfaceState(ifaceName, LinuxNetworkUtil.hasAddress(ifaceName), pppSt == PppState.CONNECTED, connInfo.getIpAddress()); newInterfaceStatuses.put(ifaceName, interfaceState); } // If the modem has been reset in this iteration of the monitor, // do not immediately enable GPS to avoid concurrency issues due to asynchronous events // (possible serial port contention between the PositionService and the trackModem() method), // GPS will be eventually enabled by trackModem() or in the next iteration of the monitor. if (!modemReset && modem.isGpsSupported() && isGpsEnabledInConfig(modem.getConfiguration())) { if (modem instanceof HspaCellularModem && !modem.isGpsEnabled()) { modem.enableGps(); } postModemGpsEvent(modem, true); } } catch (Exception e) { logger.error("monitor() :: Exception", e); if (pppService != null && pppSt != null) { try { logger.info("monitor() :: Exception :: PPPD disconnect"); pppService.disconnect(); } catch (KuraException e1) { logger.error("monitor() :: Exception while disconnect", e1); } this.pppState = pppSt; } try { if (modem.isGpsEnabled() && !disableModemGps(modem)) { logger.error("monitor() :: Failed to disable modem GPS"); } } catch (KuraException e1) { logger.error("monitor() :: Exception disableModemGps", e1); } try { logger.info("monitor() :: Exception :: modem reset"); modem.reset(); this.resetTimerStart = System.currentTimeMillis(); } catch (KuraException e1) { logger.error("monitor() :: Exception modem.reset", e1); } } } // post event for any status changes checkStatusChange(this.interfaceStatuses, newInterfaceStatuses); this.interfaceStatuses = newInterfaceStatuses; } } private void checkStatusChange(Map<String, InterfaceState> oldStatuses, Map<String, InterfaceState> newStatuses) { if (newStatuses != null) { // post NetworkStatusChangeEvent on current and new interfaces for (Map.Entry<String, InterfaceState> newStatus : newStatuses.entrySet()) { String interfaceName = newStatus.getKey(); InterfaceState interfaceState = newStatus.getValue(); if (oldStatuses != null && oldStatuses.containsKey(interfaceName)) { if (!interfaceState.equals(oldStatuses.get(interfaceName))) { logger.debug("Posting NetworkStatusChangeEvent on interface: {}", interfaceName); this.eventAdmin.postEvent(new NetworkStatusChangeEvent(interfaceName, interfaceState, null)); } } else { logger.debug("Posting NetworkStatusChangeEvent on enabled interface: {}", interfaceName); this.eventAdmin.postEvent(new NetworkStatusChangeEvent(interfaceName, interfaceState, null)); } } // post NetworkStatusChangeEvent on interfaces that are no longer there if (oldStatuses != null) { for (Map.Entry<String, InterfaceState> oldStatus : oldStatuses.entrySet()) { String interfaceName = oldStatus.getKey(); InterfaceState interfaceState = oldStatus.getValue(); if (!newStatuses.containsKey(interfaceName)) { logger.debug("Posting NetworkStatusChangeEvent on disabled interface: {}", interfaceName); this.eventAdmin.postEvent(new NetworkStatusChangeEvent(interfaceName, interfaceState, null)); } } } } } private void trackModem(ModemDevice modemDevice) { Class<? extends CellularModemFactory> modemFactoryClass = getModemFactoryClass(modemDevice); if (modemFactoryClass != null) { CellularModemFactory modemFactoryService = null; try { try { Method getInstanceMethod = modemFactoryClass.getDeclaredMethod("getInstance", (Class<?>[]) null); getInstanceMethod.setAccessible(true); modemFactoryService = (CellularModemFactory) getInstanceMethod.invoke(null, (Object[]) null); } catch (Exception e) { logger.error("Error calling getInstance() method on {}", modemFactoryClass.getName(), e); } // if unsuccessful in calling getInstance() if (modemFactoryService == null) { modemFactoryService = modemFactoryClass.newInstance(); } String platform = null; if (this.systemService != null) { platform = this.systemService.getPlatform(); } CellularModem modem = modemFactoryService.obtainCellularModemService(modemDevice, platform); try { HashMap<String, String> modemInfoMap = new HashMap<>(); modemInfoMap.put(ModemReadyEvent.IMEI, modem.getSerialNumber()); modemInfoMap.put(ModemReadyEvent.IMSI, modem.getMobileSubscriberIdentity()); modemInfoMap.put(ModemReadyEvent.ICCID, modem.getIntegratedCirquitCardId()); modemInfoMap.put(ModemReadyEvent.RSSI, Integer.toString(modem.getSignalStrength())); logger.info("posting ModemReadyEvent on topic {}", ModemReadyEvent.MODEM_EVENT_READY_TOPIC); this.eventAdmin.postEvent(new ModemReadyEvent(modemInfoMap)); } catch (Exception e) { logger.error("Failed to post the ModemReadyEvent", e); } String ifaceName = this.networkService.getModemPppPort(modemDevice); List<NetConfig> netConfigs = null; if (ifaceName != null) { NetInterfaceConfig<? extends NetInterfaceAddressConfig> netInterfaceConfig = this.networkConfig .getNetInterfaceConfig(ifaceName); if (netInterfaceConfig == null) { this.networkConfig = this.netConfigService.getNetworkConfiguration(); netInterfaceConfig = this.networkConfig.getNetInterfaceConfig(ifaceName); } if (netInterfaceConfig != null) { netConfigs = ((AbstractNetInterface<?>) netInterfaceConfig).getNetConfigs(); if (netConfigs != null && !netConfigs.isEmpty()) { modem.setConfiguration(netConfigs); } } } if (modemDevice instanceof UsbModemDevice) { this.modems.put(((UsbModemDevice) modemDevice).getUsbPort(), modem); } else if (modemDevice instanceof SerialModemDevice) { this.modems.put(modemDevice.getProductName(), modem); } if (modem instanceof EvdoCellularModem) { NetInterfaceStatus netIfaceStatus = getNetInterfaceStatus(netConfigs); if (netIfaceStatus == NetInterfaceStatus.netIPv4StatusEnabledWAN) { if (modem.isGpsEnabled() && !disableModemGps(modem)) { logger.error("trackModem() :: Failed to disable modem GPS, resetting modem ..."); modem.reset(); this.resetTimerStart = System.currentTimeMillis(); } if (!((EvdoCellularModem) modem).isProvisioned()) { logger.info("trackModem() :: The {} is not provisioned, will try to provision it ...", modem.getModel()); if (task != null && !task.isCancelled()) { logger.info("trackModem() :: Cancelling monitor task"); stopThread.set(true); monitorNotify(); task.cancel(true); task = null; } ((EvdoCellularModem) modem).provision(); if (task == null) { logger.info("trackModem() :: Restarting monitor task"); submitMonitorTask(); } else { monitorNotify(); } } else { logger.info("trackModem() :: The {} is provisioned", modem.getModel()); } } if (modem.isGpsSupported() && isGpsEnabledInConfig(netConfigs) && !modem.isGpsEnabled()) { modem.enableGps(); postModemGpsEvent(modem, true); } } } catch (Exception e) { logger.error("trackModem() :: {}", e.getMessage(), e); } } } protected Class<? extends CellularModemFactory> getModemFactoryClass(ModemDevice modemDevice) { Class<? extends CellularModemFactory> modemFactoryClass = null; if (modemDevice instanceof UsbModemDevice) { SupportedUsbModemInfo supportedUsbModemInfo = SupportedUsbModemsInfo.getModem((UsbModemDevice) modemDevice); UsbModemFactoryInfo usbModemFactoryInfo = SupportedUsbModemsFactoryInfo.getModem(supportedUsbModemInfo); modemFactoryClass = usbModemFactoryInfo.getModemFactoryClass(); } else if (modemDevice instanceof SerialModemDevice) { SupportedSerialModemInfo supportedSerialModemInfo = SupportedSerialModemsInfo.getModem(); SerialModemFactoryInfo serialModemFactoryInfo = SupportedSerialModemsFactoryInfo .getModem(supportedSerialModemInfo); modemFactoryClass = serialModemFactoryInfo.getModemFactoryClass(); } return modemFactoryClass; } private boolean disableModemGps(CellularModem modem) throws KuraException { postModemGpsEvent(modem, false); boolean portIsReachable = false; long startTimer = System.currentTimeMillis(); do { try { Thread.sleep(3000); if (modem.isPortReachable(modem.getAtPort())) { logger.debug("disableModemGps() modem is now reachable ..."); portIsReachable = true; break; } else { logger.debug("disableModemGps() waiting for PositionService to release serial port ..."); } } catch (Exception e) { logger.debug("disableModemGps() waiting for PositionService to release serial port ", e); } } while (System.currentTimeMillis() - startTimer < 20000L); modem.disableGps(); try { Thread.sleep(1000); } catch (InterruptedException e) { } boolean ret = false; if (portIsReachable && !modem.isGpsEnabled()) { logger.error("disableModemGps() :: Modem GPS is disabled :: portIsReachable={}, modem.isGpsEnabled()={}", portIsReachable, modem.isGpsEnabled()); ret = true; } return ret; } private void postModemGpsEvent(CellularModem modem, boolean enabled) throws KuraException { if (enabled) { CommURI commUri = modem.getSerialConnectionProperties(CellularModem.SerialPortType.GPSPORT); if (commUri != null) { logger.trace("postModemGpsEvent() :: Modem SeralConnectionProperties: {}", commUri.toString()); HashMap<String, Object> modemInfoMap = new HashMap<>(); modemInfoMap.put(ModemGpsEnabledEvent.Port, modem.getGpsPort()); modemInfoMap.put(ModemGpsEnabledEvent.BaudRate, Integer.valueOf(commUri.getBaudRate())); modemInfoMap.put(ModemGpsEnabledEvent.DataBits, Integer.valueOf(commUri.getDataBits())); modemInfoMap.put(ModemGpsEnabledEvent.StopBits, Integer.valueOf(commUri.getStopBits())); modemInfoMap.put(ModemGpsEnabledEvent.Parity, Integer.valueOf(commUri.getParity())); logger.debug("postModemGpsEvent() :: posting ModemGpsEnabledEvent on topic {}", ModemGpsEnabledEvent.MODEM_EVENT_GPS_ENABLED_TOPIC); this.eventAdmin.postEvent(new ModemGpsEnabledEvent(modemInfoMap)); } } else { logger.debug("postModemGpsEvent() :: posting ModemGpsDisableEvent on topic {}", ModemGpsDisabledEvent.MODEM_EVENT_GPS_DISABLED_TOPIC); HashMap<String, Object> modemInfoMap = new HashMap<>(); this.eventAdmin.postEvent(new ModemGpsDisabledEvent(modemInfoMap)); } } private void monitorNotify() { if (stopThread != null) { synchronized (stopThread) { stopThread.notifyAll(); } } } private void monitorWait() throws InterruptedException { if (stopThread != null) { synchronized (stopThread) { stopThread.wait(THREAD_INTERVAL); } } } }
package org.eclipse.kura.net.admin.visitor.linux; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.Scanner; import org.eclipse.kura.KuraErrorCode; import org.eclipse.kura.KuraException; import org.eclipse.kura.core.net.NetInterfaceAddressConfigImpl; import org.eclipse.kura.core.net.NetworkConfiguration; import org.eclipse.kura.core.net.NetworkConfigurationVisitor; import org.eclipse.kura.core.net.WifiInterfaceAddressConfigImpl; import org.eclipse.kura.core.net.util.NetworkUtil; import org.eclipse.kura.linux.net.dns.LinuxDns; import org.eclipse.kura.linux.net.util.KuraConstants; import org.eclipse.kura.net.IP4Address; import org.eclipse.kura.net.IPAddress; import org.eclipse.kura.net.NetConfig; import org.eclipse.kura.net.NetConfigIP4; import org.eclipse.kura.net.NetInterfaceAddressConfig; import org.eclipse.kura.net.NetInterfaceConfig; import org.eclipse.kura.net.NetInterfaceStatus; import org.eclipse.kura.net.NetInterfaceType; import org.eclipse.kura.net.admin.visitor.linux.util.KuranetConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class IfcfgConfigReader implements NetworkConfigurationVisitor { private static final Logger s_logger = LoggerFactory .getLogger(IfcfgConfigReader.class); private static final String OS_VERSION = System .getProperty("kura.os.version"); private static final String REDHAT_NET_CONFIGURATION_DIRECTORY = "/etc/sysconfig/network-scripts/"; private static final String DEBIAN_NET_CONFIGURATION_DIRECTORY = "/etc/network/"; private static IfcfgConfigReader s_instance; public static IfcfgConfigReader getInstance() { if (s_instance == null) { s_instance = new IfcfgConfigReader(); } return s_instance; } @Override public void visit(NetworkConfiguration config) throws KuraException { List<NetInterfaceConfig<? extends NetInterfaceAddressConfig>> netInterfaceConfigs = config .getNetInterfaceConfigs(); Properties kuraExtendedProps = KuranetConfig.getProperties(); for (NetInterfaceConfig<? extends NetInterfaceAddressConfig> netInterfaceConfig : netInterfaceConfigs) { getConfig(netInterfaceConfig, kuraExtendedProps); } } private void getConfig( NetInterfaceConfig<? extends NetInterfaceAddressConfig> netInterfaceConfig, Properties kuraExtendedProps) throws KuraException { String interfaceName = netInterfaceConfig.getName(); s_logger.debug("Getting config for {}", interfaceName); NetInterfaceType type = netInterfaceConfig.getType(); if (type == NetInterfaceType.ETHERNET || type == NetInterfaceType.WIFI || type == NetInterfaceType.LOOPBACK) { NetInterfaceStatus netInterfaceStatus = null; StringBuilder sb = new StringBuilder().append("net.interface.") .append(netInterfaceConfig.getName()) .append(".config.ip4.status"); if (kuraExtendedProps != null && kuraExtendedProps.getProperty(sb.toString()) != null) { netInterfaceStatus = NetInterfaceStatus .valueOf(kuraExtendedProps.getProperty(sb.toString())); } else { netInterfaceStatus = NetInterfaceStatus.netIPv4StatusDisabled; } s_logger.debug("Setting NetInterfaceStatus to " + netInterfaceStatus + " for " + netInterfaceConfig.getName()); boolean autoConnect = false; // int mtu = -1; // MTU is not currently used boolean dhcp = false; IP4Address address = null; String ipAddress = null; String prefixString = null; String netmask = null; String broadcast = null; String gateway = null; File ifcfgFile = null; if (OS_VERSION.equals(KuraConstants.Mini_Gateway.getImageName() + "_" + KuraConstants.Mini_Gateway.getImageVersion()) || OS_VERSION.equals(KuraConstants.Raspberry_Pi .getImageName()) || OS_VERSION.equals(KuraConstants.BeagleBone.getImageName()) || OS_VERSION.equals(KuraConstants.Intel_Edison.getImageName() + "_" + KuraConstants.Intel_Edison.getImageVersion() + "_" + KuraConstants.Intel_Edison.getTargetName()) || OS_VERSION.equals(KuraConstants.ReliaGATE_50_21_Ubuntu.getImageName() + "_" + KuraConstants.ReliaGATE_50_21_Ubuntu.getImageVersion())) { ifcfgFile = new File(DEBIAN_NET_CONFIGURATION_DIRECTORY + "interfaces"); } else { ifcfgFile = new File(REDHAT_NET_CONFIGURATION_DIRECTORY + "ifcfg-" + interfaceName); } if (ifcfgFile.exists()) { Properties kuraProps; // found our match so load the properties if (OS_VERSION.equals(KuraConstants.Mini_Gateway.getImageName() + "_" + KuraConstants.Mini_Gateway.getImageVersion()) || OS_VERSION.equals(KuraConstants.Raspberry_Pi.getImageName()) || OS_VERSION.equals(KuraConstants.BeagleBone.getImageName()) || OS_VERSION.equals(KuraConstants.Intel_Edison.getImageName() + "_" + KuraConstants.Intel_Edison.getImageVersion() + "_" + KuraConstants.Intel_Edison.getTargetName()) || OS_VERSION.equals(KuraConstants.ReliaGATE_50_21_Ubuntu.getImageName() + "_" + KuraConstants.ReliaGATE_50_21_Ubuntu.getImageVersion())) { kuraProps = parseDebianConfigFile(ifcfgFile, interfaceName); } else { kuraProps = parseRedhatConfigFile(ifcfgFile, interfaceName); } if (kuraProps != null) { String onBoot = kuraProps.getProperty("ONBOOT"); if ("yes".equals(onBoot)) { s_logger.debug("Setting autoConnect to true"); autoConnect = true; } else { s_logger.debug("Setting autoConnect to false"); autoConnect = false; } // override MTU with what is in config if it is present /* IAB: MTU is not currently used String stringMtu = kuraProps.getProperty("MTU"); if (stringMtu == null) { try { mtu = LinuxNetworkUtil.getCurrentMtu(interfaceName); } catch (KuraException e) { // just assume ??? if (interfaceName.equals("lo")) { mtu = 16436; } else { mtu = 1500; } } } else { mtu = Short.parseShort(stringMtu); } */ // get the bootproto String bootproto = kuraProps.getProperty("BOOTPROTO"); if (bootproto == null) { bootproto = "static"; } // get the defroute String defroute = kuraProps.getProperty("DEFROUTE"); if (defroute == null) { defroute = "no"; } // correct the status if needed by validating against the // actual properties if (netInterfaceStatus == NetInterfaceStatus.netIPv4StatusDisabled) { if (autoConnect) { if (defroute.equals("no")) { netInterfaceStatus = NetInterfaceStatus.netIPv4StatusEnabledLAN; } else { netInterfaceStatus = NetInterfaceStatus.netIPv4StatusEnabledWAN; } } } // check for dhcp or static configuration try { ipAddress = kuraProps.getProperty("IPADDR"); prefixString = kuraProps.getProperty("PREFIX"); netmask = kuraProps.getProperty("NETMASK"); broadcast = kuraProps.getProperty("BROADCAST"); try { gateway = kuraProps.getProperty("GATEWAY"); s_logger.debug("got gateway for " + interfaceName + ": " + gateway); } catch (Exception e) { s_logger.warn("missing gateway stanza for " + interfaceName); } if (bootproto.equals("dhcp")) { s_logger.debug("currently set for DHCP"); dhcp = true; ipAddress = null; netmask = null; } else { s_logger.debug("currently set for static address"); dhcp = false; } } catch (Exception e) { throw new KuraException(KuraErrorCode.INTERNAL_ERROR, "malformatted config file: " + ifcfgFile.toString(), e); } if (ipAddress != null && !ipAddress.isEmpty()) { try { address = (IP4Address) IPAddress .parseHostAddress(ipAddress); } catch (UnknownHostException e) { s_logger.warn("Error parsing address: " + ipAddress, e); } } // make sure at least prefix or netmask is present if static if (autoConnect && !dhcp && prefixString == null && netmask == null) { throw new KuraException(KuraErrorCode.INTERNAL_ERROR, "malformatted config file: " + ifcfgFile.toString() + " must contain NETMASK and/or PREFIX"); } } List<? extends NetInterfaceAddressConfig> netInterfaceAddressConfigs = netInterfaceConfig .getNetInterfaceAddresses(); if (netInterfaceAddressConfigs == null) { throw new KuraException(KuraErrorCode.INTERNAL_ERROR, "InterfaceAddressConfig list is null"); } else if (netInterfaceAddressConfigs.size() == 0) { throw new KuraException(KuraErrorCode.INTERNAL_ERROR, "InterfaceAddressConfig list has no entries"); } for (NetInterfaceAddressConfig netInterfaceAddressConfig : netInterfaceAddressConfigs) { List<NetConfig> netConfigs = netInterfaceAddressConfig .getConfigs(); if (netConfigs == null) { netConfigs = new ArrayList<NetConfig>(); if (netInterfaceAddressConfig instanceof NetInterfaceAddressConfigImpl) { ((NetInterfaceAddressConfigImpl) netInterfaceAddressConfig) .setNetConfigs(netConfigs); if (dhcp) { // Replace with DNS provided by DHCP server // (displayed as read-only in Denali) List<? extends IPAddress> dhcpDnsServers = getDhcpDnsServers( interfaceName, netInterfaceAddressConfig.getAddress()); if (dhcpDnsServers != null) { ((NetInterfaceAddressConfigImpl) netInterfaceAddressConfig) .setDnsServers(dhcpDnsServers); } } } else if (netInterfaceAddressConfig instanceof WifiInterfaceAddressConfigImpl) { ((WifiInterfaceAddressConfigImpl) netInterfaceAddressConfig) .setNetConfigs(netConfigs); if (dhcp) { // Replace with DNS provided by DHCP server // (displayed as read-only in Denali) List<? extends IPAddress> dhcpDnsServers = getDhcpDnsServers( interfaceName, netInterfaceAddressConfig.getAddress()); if (dhcpDnsServers != null) { ((WifiInterfaceAddressConfigImpl) netInterfaceAddressConfig) .setDnsServers(dhcpDnsServers); } } } } NetConfigIP4 netConfig = new NetConfigIP4( netInterfaceStatus, autoConnect); setNetConfigIP4(netConfig, autoConnect, dhcp, address, gateway, prefixString, netmask, kuraProps); s_logger.debug("NetConfig: {}", netConfig); netConfigs.add(netConfig); } } } } private Properties parseRedhatConfigFile(File ifcfgFile, String interfaceName) { Properties kuraProps = new Properties(); FileInputStream fis = null; try { fis = new FileInputStream(ifcfgFile); kuraProps.load(fis); // Values in the config file may be surrounded with double quotes or single quotes. for(String key : kuraProps.stringPropertyNames()) { String value = kuraProps.getProperty(key); if(value.length() >= 2 && ((value.startsWith("'") && value.endsWith("'")) || (value.startsWith("\"") && value.endsWith("\"")))) { value = value.substring(1, value.length()-1); kuraProps.put(key, value); } } } catch (Exception e) { s_logger.error("Could not get configuration for " + interfaceName, e); } finally { if(fis != null){ try{ fis.close(); }catch(IOException ex){ s_logger.error("I/O Exception while closing BufferedReader!"); } } } return kuraProps; } static Properties parseDebianConfigFile(File ifcfgFile, String interfaceName) throws KuraException { Properties kuraProps = new Properties(); Scanner scanner = null; try { scanner = new Scanner(new FileInputStream(ifcfgFile)); // Debian specific routine to create Properties object kuraProps.setProperty("ONBOOT", "no"); while (scanner.hasNextLine()) { String line = scanner.nextLine().trim(); // ignore comments and blank lines if (!line.isEmpty()) { if (line.startsWith("#!kura!")) { line = line.substring("#!kura!".length()); } if (!line.startsWith(" String[] args = line.split("\\s+"); try { // must be a line stating that interface starts on // boot if (args[0].equals("auto") && args[1].equals(interfaceName)) { s_logger.debug("Setting ONBOOT to yes for " + interfaceName); kuraProps.setProperty("ONBOOT", "yes"); } // once the correct interface is found, read all // configuration information else if (args[0].equals("iface") && args[1].equals(interfaceName)) { kuraProps.setProperty("BOOTPROTO", args[3]); if (args[3].equals("dhcp")) { kuraProps.setProperty("DEFROUTE", "yes"); } while (scanner.hasNextLine()) { line = scanner.nextLine().trim(); if (line != null && !line.isEmpty()) { if (line.startsWith("auto") || line.startsWith("iface")) { break; } args = line.trim().split("\\s+"); if (args[0].equals("mtu")) { kuraProps.setProperty("mtu", args[1]); } else if (args[0].equals("address")) { kuraProps.setProperty("IPADDR", args[1]); } else if (args[0].equals("netmask")) { kuraProps.setProperty("NETMASK", args[1]); } else if (args[0].equals("gateway")) { kuraProps.setProperty("GATEWAY", args[1]); kuraProps.setProperty("DEFROUTE", "yes"); } else if (args[0] .equals("#dns-nameservers")) { /* * IAB: * If DNS servers are listed, * those entries will be appended to * the /etc/resolv.conf file on * every ifdown/ifup sequence * resulting in multiple entries for * the same servers. (Tested on * 10-20, 10-10, and Raspberry Pi). * Commenting out dns-nameservers in * the /etc/network interfaces file * allows DNS servers to be picked * up by the IfcfgConfigReader and * be displayed on the Web UI but * the /etc/resolv.conf file will * only be updated by Kura. */ if (args.length > 1) { for (int i = 1; i < args.length; i++) { kuraProps .setProperty( "DNS" + Integer .toString(i), args[i]); } } } else if (args[0].equals("post-up")) { StringBuffer sb = new StringBuffer(); for (int i = 1; i < args.length; i++) { sb.append(args[i]); sb.append(' '); } if (sb.toString() .trim() .equals("route del default dev " + interfaceName)) { kuraProps.setProperty( "DEFROUTE", "no"); } } } } // Debian makes assumptions about lo, handle // those here if (interfaceName.equals("lo") && kuraProps.getProperty("IPADDR") == null && kuraProps.getProperty("NETMASK") == null) { kuraProps .setProperty("IPADDR", "127.0.0.1"); kuraProps.setProperty("NETMASK", "255.0.0.0"); } break; } } catch (Exception e) { s_logger.warn( "Possible malformed configuration file for " + interfaceName, e); } } } } } catch (FileNotFoundException err) { throw new KuraException(KuraErrorCode.INTERNAL_ERROR, err); } finally { if(scanner != null){ scanner.close(); } } return kuraProps; } private static void setNetConfigIP4(NetConfigIP4 netConfig, boolean autoConnect, boolean dhcp, IP4Address address, String gateway, String prefixString, String netmask, Properties kuraProps) throws KuraException { netConfig.setDhcp(dhcp); if (kuraProps != null) { // get the DNS List<IP4Address> dnsServers = new ArrayList<IP4Address>(); int count = 1; while (true) { String dns = null; if ((dns = kuraProps.getProperty("DNS" + count)) != null) { try { dnsServers.add((IP4Address) IP4Address .parseHostAddress(dns)); } catch (UnknownHostException e) { s_logger.error("Could not parse address: " + dns, e); } count++; } else { break; } } netConfig.setDnsServers(dnsServers); if (!dhcp) { netConfig.setAddress(address); // TODO ((NetConfigIP4)netConfig).setDomains(domains); if (gateway != null && !gateway.isEmpty()) { try { netConfig.setGateway((IP4Address) IP4Address .parseHostAddress(gateway)); } catch (UnknownHostException e) { s_logger.error("Could not parse address: " + gateway, e); } } if (prefixString != null) { short prefix = Short.parseShort(prefixString); netConfig.setNetworkPrefixLength(prefix); } if (netmask != null) { netConfig.setNetworkPrefixLength(NetworkUtil .getNetmaskShortForm(netmask)); } // TODO netConfig.setWinsServers(winsServers); } } } private static List<? extends IPAddress> getDhcpDnsServers( String interfaceName, IPAddress address) { List<IPAddress> dnsServers = null; if (address != null) { LinuxDns linuxDns = LinuxDns.getInstance(); try { dnsServers = linuxDns.getDhcpDnsServers(interfaceName, address); } catch (KuraException e) { s_logger.error("Error getting DHCP DNS servers", e); } } return dnsServers; } }
package com.shipdream.lib.android.mvc.controller.internal; import com.shipdream.lib.android.mvc.Injector; import com.shipdream.lib.android.mvc.MvcGraphException; import com.shipdream.lib.android.mvc.NavLocation; import com.shipdream.lib.android.mvc.__MvcGraphHelper; import com.shipdream.lib.android.mvc.controller.NavigationController; import com.shipdream.lib.poke.Consumer; import com.shipdream.lib.poke.exception.PokeException; import com.shipdream.lib.poke.exception.ProviderMissingException; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.List; public class Navigator { /** * The callback when the navigation is settled. Since Android Fragment doesn't invoke its call * back like onCreate, onCreateView and etc after a fragment manager commits fragment transaction, * if something needs to be done after the fragment being navigated to is ready to show * (MvcFragment.onViewReady is called), put the actions in here. */ public interface OnSettled { void run(); } private static class PendingReleaseInstance<T> { private Class<T> type; private Annotation qualifier; private T instance; } private final Object sender; private OnSettled onSettled; private NavigationControllerImpl navigationController; private NavigationController.EventC2V.OnLocationChanged navigateEvent; private List<PendingReleaseInstance> pendingReleaseInstances; /** * Construct a {@link Navigator} * @param sender Who wants to navigate * @param navigationController The navigation controller */ Navigator(Object sender, NavigationControllerImpl navigationController) { this.sender = sender; this.navigationController = navigationController; } /** * Who wants to navigate * @return the sender */ public Object getSender() { return sender; } /** * Prepare the instance subject to being injected with no qualifier for the fragment being * navigated to. This instance will be not be released until the navigation is settled. To * config the instance try {@link #with(Class, Preparer)} or {@link #with(Class, Annotation, Preparer)} * * @param type The class type of the instance needs to be prepared * @return This navigator * @throws MvcGraphException Raised when the required injectable object cannot be injected */ public <T> Navigator with(Class<T> type) throws MvcGraphException { with(type, null, null); return this; } /** * Prepare the instance subject to being injected with no qualifier for the fragment being * navigated to. It's an equivalent way to pass arguments to the next fragment.For example, when * next fragment needs to have a pre set page title name, the controller referenced by the * fragment can be prepared here and set the title in the controller's model. Then in the * MvcFragment.onViewReady bind the value of the page title from the controller's model to the * fragment. * * <p>Example:</p> * To initialize the timer of a TimerFragment which counts down seconds,sets the initial value * of its controller by this with method. * <pre> class TimerFragment { @Inject TimerController timerController; } interface TimerController { void setInitialValue(long howManySeconds); } navigationController.navigate(this).with(TimerController.class, new Consumer<TimerController>() { @Override public void consume(TimerController instance) { long fiveMinutes = 60 * 5; instance.setInitialValue(fiveMinutes); } }).to(TimerFragment.class.getName()); * </pre> * @param type The class type of the instance needs to be prepared * @param preparer The preparer in which the injected instance will be prepared * @return This navigator * @throws MvcGraphException Raised when the required injectable object cannot be injected */ public <T> Navigator with(Class<T> type, Preparer<T> preparer) throws MvcGraphException { with(type, null, preparer); return this; } /** * Prepare the instance subject to being injected for the fragment being navigated to. It's an * equivalent way to pass arguments to the next fragment.For example, when next fragment needs * to have a pre set page title name, the controller referenced by the fragment can be prepared * here and set the title in the controller's model. Then in the MvcFragment.onViewReady bind * the value of the page title from the controller's model to the fragment. * * <p>Example:</p> * To initialize the timer of a TimerFragment which counts down seconds,sets the initial value * of its controller by this with method. * <pre> class TimerFragment { @Inject TimerController timerController; } interface TimerController { void setInitialValue(long howManySeconds); } navigationController.navigate(this).with(TimerController.class, null, new Consumer<TimerController>() { @Override public void consume(TimerController instance) { long fiveMinutes = 60 * 5; instance.setInitialValue(fiveMinutes); } }).to(TimerFragment.class.getName()); * </pre> * @param type The class type of the instance needs to be prepared * @param qualifier The qualifier * @param preparer The preparer in which the injected instance will be prepared * @return This navigator * @throws MvcGraphException Raised when the required injectable object cannot be injected */ public <T> Navigator with(Class<T> type, Annotation qualifier, Preparer<T> preparer) throws MvcGraphException { try { T instance = Injector.getGraph().reference(type, qualifier); if (preparer != null) { preparer.prepare(instance); } if (pendingReleaseInstances == null) { pendingReleaseInstances = new ArrayList<>(); } PendingReleaseInstance pendingReleaseInstance = new PendingReleaseInstance(); pendingReleaseInstance.instance = instance; pendingReleaseInstance.type = type; pendingReleaseInstance.qualifier = qualifier; pendingReleaseInstances.add(pendingReleaseInstance); } catch (PokeException e) { throw new MvcGraphException(e.getMessage(), e); } return this; } /** * Navigates to the specified location. Navigation only takes effect when the given locationId * is different from the current location and raises {@link NavigationController.EventC2V.OnLocationForward} * * <p> * To set argument for the next fragment navigating to, use {@link #with(Class, Annotation, Preparer)} * </p> * * <p> * Navigation will automatically manage continuity of state before and after the * navigation is performed. The injected instance will not be released until the next fragment * is settled. So when the current fragment and next fragment share same injected * controller their instance will be same. * </p> * * @param locationId The id of the location navigate to */ public void to(String locationId) { doNavigateTo(locationId, false, null); go(); } /** * Navigates to a new location and exclusively clears history prior to the given * clearTopToLocationId (clearTopToLocationId will be last location below given location). * When clearTopToLocationId is null, it clears all history. In other words, the current given * location will be the only location in the history stack and all other previous locations * will be cleared. Navigation only takes effect when the given locationId is different from the * current location and raises {@link NavigationController.EventC2V.OnLocationForward} * * <p> * To set argument for the next fragment navigating to, use {@link #with(Class, Annotation, Preparer)} * </p> * * <p> * Navigation will automatically manage continuity of state before and after the * navigation is performed. The injected instance will not be released until the next fragment * is settled. So when the current fragment and next fragment share same injected * controller their instance will be same. * </p> * * @param locationId The id of the location navigate to * @param clearTopToLocationId Null if all history locations want to be cleared otherwise, the * id of the location the history will be exclusively cleared up to * which will be the second last location after navigation. */ public void to(String locationId, String clearTopToLocationId) { doNavigateTo(locationId, true, clearTopToLocationId); go(); } private void doNavigateTo(String locationId, boolean clearTop, String clearTopToLocationId) { NavLocation clearedTopToLocation = null; if (clearTop) { if (clearTopToLocationId != null) { //find out the top most location in the history stack with clearTopToLocationId NavLocation currentLoc = navigationController.getModel().getCurrentLocation(); while (currentLoc != null) { if (clearTopToLocationId.equals(currentLoc.getLocationId())) { //Reverse the history to this location clearedTopToLocation = currentLoc; break; } currentLoc = currentLoc.getPreviousLocation(); } if (clearedTopToLocation == null) { //The location to clear up to is not found. Disable clear top. clearTop = false; } } else { clearedTopToLocation = null; } } NavLocation lastLoc = navigationController.getModel().getCurrentLocation(); boolean locationChanged = false; if (clearTop) { locationChanged = true; } else { if (locationId != null) { if(lastLoc == null) { locationChanged = true; } else if(!locationId.equals(lastLoc.getLocationId())) { locationChanged = true; } } } if (locationChanged) { NavLocation currentLoc = new NavLocation(); currentLoc._setLocationId(locationId); if (!clearTop) { //Remember last location as previous location currentLoc._setPreviousLocation(lastLoc); } else { //Remember clear top location location as the previous location currentLoc._setPreviousLocation(clearedTopToLocation); } navigationController.getModel().setCurrentLocation(currentLoc); navigateEvent = new NavigationController.EventC2V.OnLocationForward(sender, lastLoc, currentLoc, clearTop, clearedTopToLocation, this); } } /** * Navigates one step back. If current location is null it doesn't take any effect otherwise * raises a {@link NavigationController.EventC2V.OnLocationBack} event when there is a previous * location. */ public void back() { NavLocation currentLoc = navigationController.getModel().getCurrentLocation(); if (currentLoc == null) { navigationController.logger.warn("Current location should never be null before navigating backwards."); return; } NavLocation previousLoc = currentLoc.getPreviousLocation(); navigationController.getModel().setCurrentLocation(previousLoc); navigateEvent = new NavigationController.EventC2V.OnLocationBack(sender, currentLoc, previousLoc, false, this); go(); } /** * Navigates back. If current location is null it doesn't take any effect. When toLocationId * is null, navigate to the very first location and clear all history prior to it, otherwise * navigate to location with given locationId and clear history prior to it. Then a * {@link NavigationController.EventC2V.OnLocationBack} event will be raised. * * @param toLocationId Null when needs to navigate to the very first location and all history * locations will be above it will be cleared. Otherwise, the id of the * location where the history will be exclusively cleared up to. Then this * location will be the second last one. */ public void back(String toLocationId) { NavLocation currentLoc = navigationController.getModel().getCurrentLocation(); if (currentLoc == null) { navigationController.logger.warn("Current location should never be null before navigating backwards."); return; } if (currentLoc.getPreviousLocation() == null) { //Has already been the first location, don't do anything return; } boolean success = false; NavLocation previousLoc = currentLoc; if(toLocationId == null) { success = true; } while (currentLoc != null) { if(toLocationId != null) { if (toLocationId.equals(currentLoc.getLocationId())) { success = true; break; } } else { if(currentLoc.getPreviousLocation() == null) { break; } } currentLoc = currentLoc.getPreviousLocation(); } if(success) { navigationController.getModel().setCurrentLocation(currentLoc); navigateEvent = new NavigationController.EventC2V.OnLocationBack(sender, previousLoc, currentLoc, true, this); } go(); } /** * Sets the call back when fragment being navigated to is ready to show(MvcFragment.onViewReady * is called). * @param onSettled {@link OnSettled} call back * @return The navigator itself */ public Navigator onSettled(OnSettled onSettled) { this.onSettled = onSettled; return this; } /** * Sends out the navigation event to execute the navigation */ private void go() { if (navigateEvent != null) { navigationController.postC2VEvent(navigateEvent); if (navigateEvent instanceof NavigationController.EventC2V.OnLocationForward) { String lastLocId = navigateEvent.getLastValue() == null ? null : navigateEvent.getLastValue().getLocationId(); navigationController.logger.trace("Nav Controller: Forward: {} -> {}", lastLocId, navigateEvent.getCurrentValue().getLocationId()); } if (navigateEvent instanceof NavigationController.EventC2V.OnLocationBack) { NavLocation lastLoc = navigateEvent.getLastValue(); NavLocation currentLoc = navigateEvent.getCurrentValue(); navigationController.logger.trace("Nav Controller: Backward: {} -> {}", lastLoc.getLocationId(), currentLoc == null ? "null" : currentLoc.getLocationId()); checkAppExit(sender); } } dumpHistory(); } /** * Internal use. Don't do it in your app. */ void __destroy() { if (onSettled != null) { onSettled.run(); } if (pendingReleaseInstances != null) { for (PendingReleaseInstance i : pendingReleaseInstances) { try { Injector.getGraph().dereference(i.instance, i.type, i.qualifier); } catch (ProviderMissingException e) { //should not happen //in case this happens just logs it navigationController.logger.warn("Failed to auto release {} after navigation settled", i.type.getName()); } } } } /** * Check the app is exiting * @param sender The sender */ private void checkAppExit(Object sender) { NavLocation curLocation = navigationController.getModel().getCurrentLocation(); if (curLocation == null) { navigationController.postC2CEvent(new NavigationController.EventC2C.OnAppExit(sender)); } } /** * Prints navigation history */ private void dumpHistory() { if (navigationController.dumpHistoryOnLocationChange) { navigationController.logger.trace(""); navigationController.logger.trace("Nav Controller: dump: begin NavLocation curLoc = navigationController.getModel().getCurrentLocation(); while (curLoc != null) { navigationController.logger.trace("Nav Controller: dump: {}({})", curLoc.getLocationId()); curLoc = curLoc.getPreviousLocation(); } navigationController.logger.trace("Nav Controller: dump: end navigationController.logger.trace(""); } } }
package com.codahale.metrics.httpclient; import com.codahale.metrics.Gauge; import com.codahale.metrics.MetricRegistry; import org.apache.http.config.Registry; import org.apache.http.config.RegistryBuilder; import org.apache.http.conn.DnsResolver; import org.apache.http.conn.HttpClientConnectionManager; import org.apache.http.conn.HttpClientConnectionOperator; import org.apache.http.conn.HttpConnectionFactory; import org.apache.http.conn.ManagedHttpClientConnection; import org.apache.http.conn.SchemePortResolver; import org.apache.http.conn.routing.HttpRoute; import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.http.conn.socket.PlainConnectionSocketFactory; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.conn.DefaultHttpClientConnectionOperator; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.impl.conn.SystemDefaultDnsResolver; import java.util.concurrent.TimeUnit; import static com.codahale.metrics.MetricRegistry.name; /** * A {@link HttpClientConnectionManager} which monitors the number of open connections. */ public class InstrumentedHttpClientConnectionManager extends PoolingHttpClientConnectionManager { protected static Registry<ConnectionSocketFactory> getDefaultRegistry() { return RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", SSLConnectionSocketFactory.getSocketFactory()) .build(); } private final MetricRegistry metricsRegistry; private final String name; public InstrumentedHttpClientConnectionManager(MetricRegistry metricRegistry) { this(metricRegistry, getDefaultRegistry()); } public InstrumentedHttpClientConnectionManager(MetricRegistry metricsRegistry, Registry<ConnectionSocketFactory> socketFactoryRegistry) { this(metricsRegistry, socketFactoryRegistry, -1, TimeUnit.MILLISECONDS); } public InstrumentedHttpClientConnectionManager(MetricRegistry metricsRegistry, Registry<ConnectionSocketFactory> socketFactoryRegistry, long connTTL, TimeUnit connTTLTimeUnit) { this(metricsRegistry, socketFactoryRegistry, null, null, SystemDefaultDnsResolver.INSTANCE, connTTL, connTTLTimeUnit, null); } public InstrumentedHttpClientConnectionManager(MetricRegistry metricsRegistry, Registry<ConnectionSocketFactory> socketFactoryRegistry, HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory, SchemePortResolver schemePortResolver, DnsResolver dnsResolver, long connTTL, TimeUnit connTTLTimeUnit, String name) { this(metricsRegistry, new DefaultHttpClientConnectionOperator(socketFactoryRegistry, schemePortResolver, dnsResolver), connFactory, connTTL, connTTLTimeUnit, name); } public InstrumentedHttpClientConnectionManager(MetricRegistry metricsRegistry, HttpClientConnectionOperator httpClientConnectionOperator, HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory, long connTTL, TimeUnit connTTLTimeUnit, String name) { super(httpClientConnectionOperator, connFactory, connTTL, connTTLTimeUnit); this.metricsRegistry = metricsRegistry; this.name = name; metricsRegistry.register(name(HttpClientConnectionManager.class, name, "available-connections"), (Gauge<Integer>) () -> { // this acquires a lock on the connection pool; remove if contention sucks return getTotalStats().getAvailable(); }); metricsRegistry.register(name(HttpClientConnectionManager.class, name, "leased-connections"), (Gauge<Integer>) () -> { // this acquires a lock on the connection pool; remove if contention sucks return getTotalStats().getLeased(); }); metricsRegistry.register(name(HttpClientConnectionManager.class, name, "max-connections"), (Gauge<Integer>) () -> { // this acquires a lock on the connection pool; remove if contention sucks return getTotalStats().getMax(); }); metricsRegistry.register(name(HttpClientConnectionManager.class, name, "pending-connections"), (Gauge<Integer>) () -> { // this acquires a lock on the connection pool; remove if contention sucks return getTotalStats().getPending(); }); } @Override public void shutdown() { super.shutdown(); metricsRegistry.remove(name(HttpClientConnectionManager.class, name, "available-connections")); metricsRegistry.remove(name(HttpClientConnectionManager.class, name, "leased-connections")); metricsRegistry.remove(name(HttpClientConnectionManager.class, name, "max-connections")); metricsRegistry.remove(name(HttpClientConnectionManager.class, name, "pending-connections")); } }
package org.activiti.engine.impl.agenda; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.activiti.bpmn.model.Activity; import org.activiti.bpmn.model.BoundaryEvent; import org.activiti.bpmn.model.CancelEventDefinition; import org.activiti.bpmn.model.EventSubProcess; import org.activiti.bpmn.model.FlowElement; import org.activiti.bpmn.model.FlowNode; import org.activiti.bpmn.model.Gateway; import org.activiti.bpmn.model.SequenceFlow; import org.activiti.engine.ActivitiException; import org.activiti.engine.delegate.ExecutionListener; import org.activiti.engine.delegate.event.ActivitiEventType; import org.activiti.engine.delegate.event.impl.ActivitiEventBuilder; import org.activiti.engine.impl.bpmn.helper.SkipExpressionUtil; import org.activiti.engine.impl.context.Context; import org.activiti.engine.impl.interceptor.CommandContext; import org.activiti.engine.impl.persistence.entity.ExecutionEntity; import org.activiti.engine.impl.persistence.entity.ExecutionEntityManager; import org.activiti.engine.impl.util.CollectionUtil; import org.activiti.engine.impl.util.condition.ConditionUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Joram Barrez * @author Tijs Rademakers */ public class TakeOutgoingSequenceFlowsOperation extends AbstractOperation { private static final Logger logger = LoggerFactory.getLogger(TakeOutgoingSequenceFlowsOperation.class); protected boolean evaluateConditions; public TakeOutgoingSequenceFlowsOperation(CommandContext commandContext, ExecutionEntity activityExecution, boolean evaluateConditions) { super(commandContext, activityExecution); this.evaluateConditions = evaluateConditions; } @Override public void run() { FlowElement currentFlowElement = execution.getCurrentFlowElement(); if (currentFlowElement == null) { currentFlowElement = findCurrentFlowElement(execution); execution.setCurrentFlowElement(currentFlowElement); } // If execution is a scope (and not the process instance), the scope must first be destroyed before we can continue if (execution.getParentId() != null && execution.isScope()) { agenda.planDestroyScopeOperation(execution); } else if (currentFlowElement instanceof Activity) { Activity activity = (Activity) currentFlowElement; if (CollectionUtil.isNotEmpty(activity.getBoundaryEvents())) { List<String> notToDeleteEvents = new ArrayList<String>(); for (BoundaryEvent event : activity.getBoundaryEvents()) { if (CollectionUtil.isNotEmpty(event.getEventDefinitions()) && event.getEventDefinitions().get(0) instanceof CancelEventDefinition) { notToDeleteEvents.add(event.getId()); } } // Delete all child executions Collection<ExecutionEntity> childExecutions = commandContext.getExecutionEntityManager().findChildExecutionsByParentExecutionId(execution.getId()); for (ExecutionEntity childExecution : childExecutions) { if (childExecution.getCurrentFlowElement() == null || notToDeleteEvents.contains(childExecution.getCurrentFlowElement().getId()) == false) { commandContext.getExecutionEntityManager().deleteExecutionAndRelatedData(childExecution, null, false); } } } } // Execution listener for end: the flow node is now ended if (CollectionUtil.isNotEmpty(currentFlowElement.getExecutionListeners()) && !execution.isProcessInstanceType()) { // a process instance execution can never leave a flownode, but it can pass here whilst cleaning up executeExecutionListeners(currentFlowElement, ExecutionListener.EVENTNAME_END); } // No scope, can continue if (currentFlowElement instanceof FlowNode) { FlowNode flowNode = (FlowNode) currentFlowElement; if (execution.getId().equals(execution.getProcessInstanceId()) == false) { Context.getProcessEngineConfiguration().getEventDispatcher().dispatchEvent( ActivitiEventBuilder.createActivityEvent(ActivitiEventType.ACTIVITY_COMPLETED, flowNode.getId(), flowNode.getName(), execution.getId(), execution.getProcessInstanceId(), execution.getProcessDefinitionId(), flowNode)); } leaveFlowNode(flowNode); } else if (currentFlowElement instanceof SequenceFlow) { // Nothing to do here. The operation wasn't really needed, so simply pass it through agenda.planContinueProcessOperation(execution); } } protected void leaveFlowNode(FlowNode flowNode) { logger.debug("Leaving flow node {} with id '{}' by following it's {} outgoing sequenceflow", flowNode.getClass(), flowNode.getId(), flowNode.getOutgoingFlows().size()); // Get default sequence flow (if set) String defaultSequenceFlowId = null; if (flowNode instanceof Activity) { defaultSequenceFlowId = ((Activity) flowNode).getDefaultFlow(); } else if (flowNode instanceof Gateway) { defaultSequenceFlowId = ((Gateway) flowNode).getDefaultFlow(); } // Determine which sequence flows can be used for leaving List<SequenceFlow> outgoingSequenceFlow = new ArrayList<SequenceFlow>(); for (SequenceFlow sequenceFlow : flowNode.getOutgoingFlows()) { String skipExpressionString = sequenceFlow.getSkipExpression(); if (!SkipExpressionUtil.isSkipExpressionEnabled(execution, skipExpressionString)) { if (!evaluateConditions || (evaluateConditions && ConditionUtil.hasTrueCondition(sequenceFlow, execution) && (defaultSequenceFlowId == null || !defaultSequenceFlowId.equals(sequenceFlow.getId())))) { outgoingSequenceFlow.add(sequenceFlow); } } else if (flowNode.getOutgoingFlows().size() == 1 || SkipExpressionUtil.shouldSkipFlowElement(commandContext, execution, skipExpressionString)) { // The 'skip' for a sequence flow means that we skip the condition, not the sequence flow. outgoingSequenceFlow.add(sequenceFlow); } } // Check if there is a default sequence flow if (outgoingSequenceFlow.size() == 0 && evaluateConditions) { // The elements that set this to false also have no support for default sequence flow if (defaultSequenceFlowId != null) { for (SequenceFlow sequenceFlow : flowNode.getOutgoingFlows()) { if (defaultSequenceFlowId.equals(sequenceFlow.getId())) { outgoingSequenceFlow.add(sequenceFlow); break; } } } } // No outgoing found. Ending the execution if (outgoingSequenceFlow.size() == 0) { if (flowNode.getOutgoingFlows() == null || flowNode.getOutgoingFlows().size() == 0) { logger.debug("No outgoing sequence flow found for flow node '{}'.", flowNode.getId()); if (flowNode.getSubProcess() != null && flowNode.getSubProcess() instanceof EventSubProcess) { ExecutionEntityManager executionEntityManager = commandContext.getExecutionEntityManager(); executionEntityManager.deleteChildExecutions((ExecutionEntity) execution, null, false); executionEntityManager.deleteExecutionAndRelatedData((ExecutionEntity) execution, null, false); // event sub process nested in sub process if (flowNode.getSubProcess().getSubProcess() != null) { executionEntityManager.deleteChildExecutions((ExecutionEntity) execution.getParent(), null, false); executionEntityManager.deleteExecutionAndRelatedData((ExecutionEntity) execution.getParent(), null, false); ExecutionEntity parentExecution = execution.getParent().getParent(); parentExecution.setCurrentFlowElement(flowNode.getSubProcess().getSubProcess()); agenda.planTakeOutgoingSequenceFlowsOperation(parentExecution); // event sub process on process root level } else { executionEntityManager.deleteChildExecutions((ExecutionEntity) execution.getParent(), null, false); agenda.planEndExecutionOperation(execution.getParent()); } } else { agenda.planEndExecutionOperation(execution); } return; } else { throw new ActivitiException("No outgoing sequence flow of element '" + flowNode.getId() + "' could be selected for continuing the process"); } } // Leave, and reuse the incoming sequence flow, make executions for all the others (if applicable) ExecutionEntityManager executionEntityManager = commandContext.getExecutionEntityManager(); List<ExecutionEntity> outgoingExecutions = new ArrayList<ExecutionEntity>(flowNode.getOutgoingFlows().size()); // Reuse existing one SequenceFlow sequenceFlow = outgoingSequenceFlow.get(0); execution.setCurrentFlowElement(sequenceFlow); execution.setActive(true); // execution.setScope(false); outgoingExecutions.add((ExecutionEntity) execution); // Executions for all the other one if (outgoingSequenceFlow.size() > 1) { for (int i = 1; i < outgoingSequenceFlow.size(); i++) { ExecutionEntity outgoingExecutionEntity = commandContext.getExecutionEntityManager().create(); outgoingExecutionEntity.setProcessDefinitionId(execution.getProcessDefinitionId()); outgoingExecutionEntity.setProcessInstanceId(execution.getProcessInstanceId()); outgoingExecutionEntity.setRootProcessInstanceId(execution.getRootProcessInstanceId()); outgoingExecutionEntity.setTenantId(execution.getTenantId()); outgoingExecutionEntity.setScope(false); outgoingExecutionEntity.setActive(true); ExecutionEntity parent = execution.getParentId() != null ? execution.getParent() : execution; outgoingExecutionEntity.setParent(parent); parent.addChildExecution(outgoingExecutionEntity); sequenceFlow = outgoingSequenceFlow.get(i); outgoingExecutionEntity.setCurrentFlowElement(sequenceFlow); executionEntityManager.insert(outgoingExecutionEntity); outgoingExecutions.add(outgoingExecutionEntity); } } // Leave (only done when all executions have been made, since some queries depend on this) for (ExecutionEntity outgoingExecution : outgoingExecutions) { agenda.planContinueProcessOperation(outgoingExecution); } } }
package be.wegenenverkeer.atomium.japi.client.rxhttpclient; import be.wegenenverkeer.atomium.japi.client.AtomiumClient; import be.wegenenverkeer.atomium.japi.client.AtomiumFeed; import be.wegenenverkeer.atomium.japi.client.PageFetcher; import be.wegenenverkeer.rxhttpclient.RxHttpClient; import java.util.ArrayList; import java.util.List; public class RxHttpAtomiumClient implements AtomiumClient { private final List<PageFetcher<?>> pageFetchers = new ArrayList<>(); private final RxHttpClient rxHttpClient; /** * Creates an AtomiumClient from the specified {@code PageFetcher} instance */ public RxHttpAtomiumClient(RxHttpClient rxHttpClient) { this.rxHttpClient = rxHttpClient; } @Override public <E> AtomiumFeed<E> feed(PageFetcher<E> pageFetcher) { pageFetchers.add(pageFetcher); return new AtomiumFeed<>(pageFetcher); } public <E> RxHttpPageFetcher.Builder<E> getPageFetcherBuilder(String feedUrl, Class<E> entityTypeMarker) { return new RxHttpPageFetcher.Builder<>(rxHttpClient, feedUrl, entityTypeMarker); } public void close() { this.pageFetchers.forEach(PageFetcher::close); } }
package peergos.server.storage; import peergos.shared.io.ipfs.api.*; import peergos.shared.io.ipfs.cid.*; import peergos.shared.io.ipfs.multiaddr.*; import peergos.shared.io.ipfs.multihash.*; import peergos.shared.storage.*; import peergos.shared.util.*; import java.io.*; import java.net.*; import java.util.*; import java.util.stream.*; public class IPFS { public static final Version MIN_VERSION = Version.parse("0.4.19-dev"); public enum PinType {all, direct, indirect, recursive} public List<String> ObjectTemplates = Arrays.asList("unixfs-dir"); public List<String> ObjectPatchTypes = Arrays.asList("add-link", "rm-link", "set-data", "append-data"); public final String host; public final int port; private final String version; public final Pin pin = new Pin(); public final Repo repo = new Repo(); public final IPFSObject object = new IPFSObject(); public final Swarm swarm = new Swarm(); public final Bootstrap bootstrap = new Bootstrap(); public final Block block = new Block(); public final Dag dag = new Dag(); public final Diag diag = new Diag(); public final Config config = new Config(); public final Refs refs = new Refs(); public final Update update = new Update(); public final DHT dht = new DHT(); public final File file = new File(); public final Stats stats = new Stats(); public final Name name = new Name(); public IPFS(String host, int port) { this(host, port, "/api/v0/"); } public IPFS(String multiaddr) { this(new MultiAddress(multiaddr)); } public IPFS(MultiAddress addr) { this(addr.getHost(), addr.getTCPPort(), "/api/v0/"); } public IPFS(String host, int port, String version) { this.host = host; this.port = port; this.version = version; // Check IPFS is sufficiently recent try { Version ipfsVersion = Version.parse(version()); if (ipfsVersion.isBefore(MIN_VERSION)) throw new IllegalStateException("You need to use a more recent version of IPFS! >= " + MIN_VERSION); } catch (IOException e) { throw new RuntimeException(e); } } public MerkleNode add(NamedStreamable file) throws IOException { List<MerkleNode> addParts = add(Collections.singletonList(file)); Optional<MerkleNode> sameName = addParts.stream() .filter(node -> node.name.equals(file.getName())) .findAny(); if (sameName.isPresent()) return sameName.get(); return addParts.get(0); } public List<MerkleNode> add(List<NamedStreamable> files) throws IOException { Multipart m = new Multipart("http://" + host + ":" + port + version+"add?stream-channels=true", "UTF-8"); for (NamedStreamable file: files) { if (file.isDirectory()) { m.addSubtree("", ((NamedStreamable.NativeFile)file).getFile()); } else m.addFilePart("file", file); }; String res = m.finish(); return JSONParser.parseStream(res).stream() .map(x -> MerkleNode.fromJSON((Map<String, Object>) x)) .collect(Collectors.toList()); } public List<MerkleNode> ls(Multihash hash) throws IOException { Map res = retrieveMap("ls/" + hash); return ((List<Object>) res.get("Objects")).stream().map(x -> MerkleNode.fromJSON((Map) x)).collect(Collectors.toList()); } public byte[] cat(Multihash hash) throws IOException { return retrieve("cat/" + hash); } public byte[] cat(Multihash hash, String subPath) throws IOException { return retrieve("cat?arg=" + hash + URLEncoder.encode(subPath, "UTF-8")); } public byte[] get(Multihash hash) throws IOException { return retrieve("get/" + hash); } public InputStream catStream(Multihash hash) throws IOException { return retrieveStream("cat/" + hash); } public List<Multihash> refs(Multihash hash, boolean recursive) throws IOException { String jsonStream = new String(retrieve("refs?arg=" + hash + "&r=" + recursive)); return JSONParser.parseStream(jsonStream).stream() .map(m -> (String) (((Map) m).get("Ref"))) .map(Cid::decode) .collect(Collectors.toList()); } public Map resolve(String scheme, Multihash hash, boolean recursive) throws IOException { return retrieveMap("resolve?arg=/" + scheme+"/"+hash +"&r="+recursive); } public String dns(String domain) throws IOException { Map res = retrieveMap("dns?arg=" + domain); return (String)res.get("Path"); } public Map mount(java.io.File ipfsRoot, java.io.File ipnsRoot) throws IOException { if (ipfsRoot != null && !ipfsRoot.exists()) ipfsRoot.mkdirs(); if (ipnsRoot != null && !ipnsRoot.exists()) ipnsRoot.mkdirs(); return (Map)retrieveAndParse("mount?arg=" + (ipfsRoot != null ? ipfsRoot.getPath() : "/ipfs" ) + "&arg=" + (ipnsRoot != null ? ipnsRoot.getPath() : "/ipns" )); } // level 2 commands public class Refs { public List<Multihash> local() throws IOException { String jsonStream = new String(retrieve("refs/local")); return JSONParser.parseStream(jsonStream).stream() .map(m -> (String) (((Map) m).get("Ref"))) .map(Cid::decode) .collect(Collectors.toList()); } } /* Pinning an object ensures a local copy of it is kept. */ public class Pin { public List<Multihash> add(Multihash hash) throws IOException { return ((List<Object>)((Map)retrieveAndParse("pin/add?stream-channels=true&arg=" + hash)).get("Pins")) .stream() .map(x -> Cid.decode((String)x)) .collect(Collectors.toList()); } public Map<Multihash, Object> ls() throws IOException { return ls(PinType.direct); } public Map<Multihash, Object> ls(PinType type) throws IOException { return ((Map<String, Object>)(((Map)retrieveAndParse("pin/ls?stream-channels=true&t="+type.name())).get("Keys"))).entrySet() .stream() .collect(Collectors.toMap(x -> Cid.decode(x.getKey()), x-> x.getValue())); } public List<Multihash> rm(Multihash hash) throws IOException { return rm(hash, true); } public List<Multihash> rm(Multihash hash, boolean recursive) throws IOException { Map json = retrieveMap("pin/rm?stream-channels=true&r=" + recursive + "&arg=" + hash); return ((List<Object>) json.get("Pins")).stream().map(x -> Cid.decode((String) x)).collect(Collectors.toList()); } public List<Multihash> update(Multihash existing, Multihash modified, boolean unpin) throws IOException { return ((List<Object>)((Map)retrieveAndParse("pin/update?stream-channels=true&arg=" + existing + "&arg=" + modified + "&unpin=" + unpin)).get("Pins")) .stream() .map(x -> Cid.decode((String) x)) .collect(Collectors.toList()); } } /* 'ipfs repo' is a plumbing command used to manipulate the repo. */ public class Repo { public Object gc() throws IOException { return retrieveAndParse("repo/gc"); } } /* 'ipfs block' is a plumbing command used to manipulate raw ipfs blocks. */ public class Block { public byte[] get(Multihash hash) throws IOException { return retrieve("block/get?stream-channels=true&arg=" + hash); } public byte[] rm(Multihash hash) throws IOException { return retrieve("block/rm?stream-channels=true&arg=" + hash); } public List<MerkleNode> put(List<byte[]> data) throws IOException { return put(data, Optional.empty()); } public List<MerkleNode> put(List<byte[]> data, Optional<String> format) throws IOException { for (byte[] block : data) { if (block.length > ContentAddressedStorage.MAX_BLOCK_SIZE) throw new IllegalStateException("Invalid block size: " + block.length + ", blocks must be smaller than 2MiB!"); } String fmt = format.map(f -> "&format=" + f).orElse(""); Multipart m = new Multipart("http://" + host + ":" + port + version+"block/put?stream-channels=true" + fmt, "UTF-8"); for (byte[] f : data) m.addFilePart("file", new NamedStreamable.ByteArrayWrapper(f)); String res = m.finish(); return JSONParser.parseStream(res).stream().map(x -> MerkleNode.fromJSON((Map<String, Object>) x)).collect(Collectors.toList()); } public Map stat(Multihash hash) throws IOException { return retrieveMap("block/stat?stream-channels=true&arg=" + hash); } } /* 'ipfs object' is a plumbing command used to manipulate DAG objects directly. {Object} is a subset of {Block} */ public class IPFSObject { public List<MerkleNode> put(List<byte[]> data) throws IOException { Multipart m = new Multipart("http://" + host + ":" + port + version+"object/put?stream-channels=true", "UTF-8"); for (byte[] f : data) m.addFilePart("file", new NamedStreamable.ByteArrayWrapper(f)); String res = m.finish(); return JSONParser.parseStream(res).stream().map(x -> MerkleNode.fromJSON((Map<String, Object>) x)).collect(Collectors.toList()); } public List<MerkleNode> put(String encoding, List<byte[]> data) throws IOException { if (!"json".equals(encoding) && !"protobuf".equals(encoding)) throw new IllegalArgumentException("Encoding must be json or protobuf"); Multipart m = new Multipart("http://" + host + ":" + port + version+"object/put?stream-channels=true&encoding="+encoding, "UTF-8"); for (byte[] f : data) m.addFilePart("file", new NamedStreamable.ByteArrayWrapper(f)); String res = m.finish(); return JSONParser.parseStream(res).stream().map(x -> MerkleNode.fromJSON((Map<String, Object>) x)).collect(Collectors.toList()); } public MerkleNode get(Multihash hash) throws IOException { Map json = retrieveMap("object/get?stream-channels=true&arg=" + hash); json.put("Hash", hash.toString()); return MerkleNode.fromJSON(json); } public MerkleNode links(Multihash hash) throws IOException { Map json = retrieveMap("object/links?stream-channels=true&arg=" + hash); return MerkleNode.fromJSON(json); } public Map<String, Object> stat(Multihash hash) throws IOException { return retrieveMap("object/stat?stream-channels=true&arg=" + hash); } public byte[] data(Multihash hash) throws IOException { return retrieve("object/data?stream-channels=true&arg=" + hash); } public MerkleNode _new(Optional<String> template) throws IOException { if (template.isPresent() && !ObjectTemplates.contains(template.get())) throw new IllegalStateException("Unrecognised template: "+template.get()); Map json = retrieveMap("object/new?stream-channels=true"+(template.isPresent() ? "&arg=" + template.get() : "")); return MerkleNode.fromJSON(json); } public MerkleNode patch(Multihash base, String command, Optional<byte[]> data, Optional<String> name, Optional<Multihash> target) throws IOException { if (!ObjectPatchTypes.contains(command)) throw new IllegalStateException("Illegal Object.patch command type: "+command); String targetPath = "object/patch/"+command+"?arg=" + base.toBase58(); if (name.isPresent()) targetPath += "&arg=" + name.get(); if (target.isPresent()) targetPath += "&arg=" + target.get().toBase58(); switch (command) { case "add-link": if (!target.isPresent()) throw new IllegalStateException("add-link requires name and target!"); case "rm-link": if (!name.isPresent()) throw new IllegalStateException("link name is required!"); return MerkleNode.fromJSON(retrieveMap(targetPath)); case "set-data": case "append-data": if (!data.isPresent()) throw new IllegalStateException("set-data requires data!"); Multipart m = new Multipart("http://" + host + ":" + port + version+"object/patch/"+command+"?arg="+base.toBase58()+"&stream-channels=true", "UTF-8"); m.addFilePart("file", new NamedStreamable.ByteArrayWrapper(data.get())); String res = m.finish(); return MerkleNode.fromJSON(JSONParser.parse(res)); default: throw new IllegalStateException("Unimplemented"); } } } public class Name { public Map publish(Multihash hash) throws IOException { return publish(Optional.empty(), hash); } public Map publish(Optional<String> id, Multihash hash) throws IOException { return retrieveMap("name/publish?arg=" + (id.isPresent() ? id+"&arg=" : "") + "/ipfs/"+hash); } public String resolve(Multihash hash) throws IOException { Map res = (Map) retrieveAndParse("name/resolve?arg=" + hash); return (String)res.get("Path"); } } public class DHT { public Map findprovs(Multihash hash) throws IOException { return retrieveMap("dht/findprovs?arg=" + hash); } public Map query(MultiAddress addr) throws IOException { return retrieveMap("dht/query?arg=" + addr.toString()); } public Map findpeer(MultiAddress addr) throws IOException { return retrieveMap("dht/findpeer?arg=" + addr.toString()); } public Map get(Multihash hash) throws IOException { return retrieveMap("dht/get?arg=" + hash); } public Map put(String key, String value) throws IOException { return retrieveMap("dht/put?arg=" + key + "&arg="+value); } } public class File { public Map ls(Multihash path) throws IOException { return retrieveMap("file/ls?arg=" + path); } } // Network commands public List<MultiAddress> bootstrap() throws IOException { return ((List<String>)retrieveMap("bootstrap/").get("Peers")).stream().map(x -> new MultiAddress(x)).collect(Collectors.toList()); } public class Bootstrap { public List<MultiAddress> list() throws IOException { return bootstrap(); } public List<MultiAddress> add(MultiAddress addr) throws IOException { return ((List<String>)retrieveMap("bootstrap/add?arg="+addr).get("Peers")).stream().map(x -> new MultiAddress(x)).collect(Collectors.toList()); } public List<MultiAddress> rm(MultiAddress addr) throws IOException { return rm(addr, false); } public List<MultiAddress> rm(MultiAddress addr, boolean all) throws IOException { return ((List<String>)retrieveMap("bootstrap/rm?"+(all ? "all=true&":"")+"arg="+addr).get("Peers")).stream().map(x -> new MultiAddress(x)).collect(Collectors.toList()); } } /* ipfs swarm is a tool to manipulate the network swarm. The swarm is the component that opens, listens for, and maintains connections to other ipfs peers in the internet. */ public class Swarm { public List<Peer> peers() throws IOException { Map m = retrieveMap("swarm/peers?stream-channels=true"); return ((List<Object>)m.get("Peers")).stream().map(Peer::fromJSON).collect(Collectors.toList()); } public Map addrs() throws IOException { Map m = retrieveMap("swarm/addrs?stream-channels=true"); return (Map<String, Object>)m.get("Addrs"); } public Map connect(String multiAddr) throws IOException { Map m = retrieveMap("swarm/connect?arg="+multiAddr); return m; } public Map disconnect(String multiAddr) throws IOException { Map m = retrieveMap("swarm/disconnect?arg="+multiAddr); return m; } } public class Dag { public byte[] get(Cid cid) throws IOException { return retrieve("block/get?stream-channels=true&arg=" + cid); } public MerkleNode put(byte[] object) throws IOException { return put("json", object, "cbor"); } public MerkleNode put(String inputFormat, byte[] object) throws IOException { return put(inputFormat, object, "cbor"); } public MerkleNode put(byte[] object, String outputFormat) throws IOException { return put("json", object, outputFormat); } public MerkleNode put(String inputFormat, byte[] object, String outputFormat) throws IOException { block.put(Collections.singletonList(object)); String prefix = "http://" + host + ":" + port + version; Multipart m = new Multipart(prefix + "block/put/?stream-channels=true&input-enc=" + inputFormat + "&f=" + outputFormat, "UTF-8"); m.addFilePart("file", new NamedStreamable.ByteArrayWrapper(object)); String res = m.finish(); return MerkleNode.fromJSON(JSONParser.parse(res)); } } public class Diag { public String net() throws IOException { return new String(retrieve("diag/net?stream-channels=true")); } } public Map ping(String target) throws IOException { return retrieveMap("ping/" + target.toString()); } public Map id() throws IOException { return retrieveMap("id"); } public class Stats { public Map bw() throws IOException { return retrieveMap("stats/bw"); } } // Tools public String version() throws IOException { Map m = (Map)retrieveAndParse("version"); return (String)m.get("Version"); } public Map commands() throws IOException { return retrieveMap("commands"); } public Map log() throws IOException { return retrieveMap("log/tail"); } public class Config { public Map show() throws IOException { return (Map)retrieveAndParse("config/show"); } public void replace(NamedStreamable file) throws IOException { Multipart m = new Multipart("http://" + host + ":" + port + version+"config/replace?stream-channels=true", "UTF-8"); m.addFilePart("file", file); String res = m.finish(); } public String get(String key) throws IOException { Map m = (Map)retrieveAndParse("config?arg="+key); return (String)m.get("Value"); } public Map set(String key, String value) throws IOException { return retrieveMap("config?arg=" + key + "&arg=" + value); } } public Object update() throws IOException { return retrieveAndParse("update"); } public class Update { public Object check() throws IOException { return retrieveAndParse("update/check"); } public Object log() throws IOException { return retrieveAndParse("update/log"); } } private Map retrieveMap(String path) throws IOException { return (Map)retrieveAndParse(path); } private Object retrieveAndParse(String path) throws IOException { byte[] res = retrieve(path); return JSONParser.parse(new String(res)); } private byte[] retrieve(String path) throws IOException { URL target = new URL("http", host, port, version + path); return IPFS.get(target); } private static byte[] get(URL target) throws IOException { HttpURLConnection conn = (HttpURLConnection) target.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setConnectTimeout(10_000); conn.setReadTimeout(60_000); try { OutputStream out = conn.getOutputStream(); out.write(new byte[0]); out.flush(); out.close(); InputStream in = conn.getInputStream(); ByteArrayOutputStream resp = new ByteArrayOutputStream(); byte[] buf = new byte[4096]; int r; while ((r = in.read(buf)) >= 0) resp.write(buf, 0, r); return resp.toByteArray(); } catch (ConnectException e) { throw new RuntimeException("Couldn't connect to IPFS daemon at "+target+"\n Is IPFS running?"); } catch (IOException e) { InputStream errorStream = conn.getErrorStream(); String err = errorStream == null ? e.getMessage() : readFully(errorStream); throw new RuntimeException("IOException contacting IPFS daemon.\n"+err+"\nTrailer: " + conn.getHeaderFields().get("Trailer"), e); } } private static String readFully(InputStream in) throws IOException { return new String(Serialize.readFully(in)); } private InputStream retrieveStream(String path) throws IOException { URL target = new URL("http", host, port, version + path); return IPFS.getStream(target); } private static InputStream getStream(URL target) throws IOException { HttpURLConnection conn = (HttpURLConnection) target.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Content-Type", "application/json"); return conn.getInputStream(); } private Map postMap(String path, byte[] body, Map<String, String> headers) throws IOException { URL target = new URL("http", host, port, version + path); return (Map) JSONParser.parse(new String(post(target, body, headers))); } private static byte[] post(URL target, byte[] body, Map<String, String> headers) throws IOException { HttpURLConnection conn = (HttpURLConnection) target.openConnection(); for (String key: headers.keySet()) conn.setRequestProperty(key, headers.get(key)); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); OutputStream out = conn.getOutputStream(); out.write(body); out.flush(); out.close(); InputStream in = conn.getInputStream(); ByteArrayOutputStream resp = new ByteArrayOutputStream(); byte[] buf = new byte[4096]; int r; while ((r=in.read(buf)) >= 0) resp.write(buf, 0, r); return resp.toByteArray(); } }
package org.core; import static org.junit.Assert.*; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import org.core.BlobDirectory; import org.core.BlobDirectoryFS; import org.core.BlobFileFS; import org.core.cache.DummyCache; import org.junit.Test; import org.junit.experimental.theories.DataPoints; import org.junit.experimental.theories.Theories; import org.junit.experimental.theories.Theory; import org.junit.runner.RunWith; @RunWith(Theories.class) public class TestBlobFileFS { @Theory public void testBlobFileFS(String fileName) throws IOException { BlobDirectory dir = new BlobDirectoryFS("test_files/blobFileFS", null); BlobFileFS f = new BlobFileFS(dir, fileName, new DummyCache()); assertEquals("Size should be equal", f.length, new File("test_files/blobFileFS/" + fileName).length()); assertEquals("We should be at the begining of the document", 0, f.position); if (fileName == "nonExistant") { f.delete(); } f.close(); } private void testWriteMain(byte[] data, long offset, File file) throws IOException { /*BlobDirectory dir = new BlobDirectoryFS("test_files/blobFileFS", null); BlobFileFS f = new BlobFileFS(dir, "write", new DummyCache()); f.write(data, 0, data.length); f.close();*/ } /* @Theory public void testWrite(byte[] data) throws IOException { testWriteMain(data, 0, file); File file = new File("test_files/blobFileFS/write"); RandomAccessFile raf = new RandomAccessFile(file, null); assertTrue("Files are different", file); file.delete(); file = new File("test_files/blobFileFS/writeExist"); testWriteMain(data, file.length(), file); file. } */ @Test public void testSeek() { //fail("Not yet implemented"); } @Test public void testRead() { //fail("Not yet implemented"); } @Test public void testEquals() { //fail("Not yet implemented"); } public static @DataPoints String[] fileNames = {"construct", "empty"}; public static @DataPoints byte[] datas = { 1, 2};//"construct", "empty", "nonExistant"}; }
package org.deeplearning4j.parallelism; import lombok.NonNull; import org.deeplearning4j.datasets.iterator.AsyncDataSetIterator; import org.deeplearning4j.datasets.iterator.impl.ListDataSetIterator; import org.deeplearning4j.nn.api.Model; import org.deeplearning4j.nn.api.Updater; import org.deeplearning4j.nn.conf.MultiLayerConfiguration; import org.deeplearning4j.nn.graph.ComputationGraph; import org.deeplearning4j.nn.multilayer.MultiLayerNetwork; import org.deeplearning4j.nn.updater.graph.ComputationGraphUpdater; import org.deeplearning4j.optimize.api.IterationListener; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.api.ops.executioner.GridExecutioner; import org.nd4j.linalg.dataset.api.DataSet; import org.nd4j.linalg.dataset.api.iterator.DataSetIterator; import org.nd4j.linalg.factory.Nd4j; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; /** * This is simple data-parallel wrapper suitable for multi-cpu/multi-gpu environments. * * @author raver119@gmail.com */ public class ParallelWrapper implements AutoCloseable { private static Logger logger = LoggerFactory.getLogger(ParallelWrapper.class); private Model model; private int workers = 2; private int prefetchSize = 2; private int averagingFrequency = 1; private Trainer zoo[]; private AtomicLong iterationsCounter = new AtomicLong(0); private boolean reportScore = false; private boolean averageUpdaters = true; private boolean legacyAveraging = false; protected ParallelWrapper(Model model, int workers, int prefetchSize) { this.model = model; this.workers = workers; this.prefetchSize = prefetchSize; if (this.model instanceof MultiLayerNetwork) { ((MultiLayerNetwork) this.model).getUpdater(); } else if (this.model instanceof ComputationGraph) { ((ComputationGraph) this.model).getUpdater(); } zoo = new Trainer[workers]; for (int cnt = 0; cnt < workers; cnt++) { zoo[cnt] = new Trainer(cnt, model); zoo[cnt].start(); } } @Override public void close() throws Exception { if (zoo != null) { for (int i = 0; i < zoo.length; i++) { if (zoo[i] != null) zoo[i].shutdown(); } zoo = null; } } /** * This method causes all threads used for parallel training to stop */ public synchronized void shutdown() { try { close(); } catch (Exception e) { throw new RuntimeException(e); } } /** * This method takes DataSetIterator, and starts training over it by scheduling DataSets to different executors * * @param source */ public synchronized void fit(@NonNull DataSetIterator source) { if (zoo == null) { zoo = new Trainer[workers]; for (int cnt = 0; cnt < workers; cnt++) { zoo[cnt] = new Trainer(cnt, model); zoo[cnt].start(); } } source.reset(); DataSetIterator iterator; if (prefetchSize > 0 && (!(source instanceof AsyncDataSetIterator) && !(source instanceof ListDataSetIterator))) { iterator = new AsyncDataSetIterator(source, prefetchSize); } else iterator = source; AtomicInteger locker = new AtomicInteger(0); while (iterator.hasNext()) { DataSet dataSet = iterator.next(); /* now dataSet should be dispatched to next free workers, until all workers are busy. And then we should block till all finished. */ int pos = locker.getAndIncrement(); zoo[pos].feedDataSet(dataSet); /* if all workers are dispatched now, join till all are finished */ if (pos + 1 == workers || !iterator.hasNext()) { iterationsCounter.incrementAndGet(); for (int cnt = 0; cnt < workers && cnt < locker.get(); cnt ++) { try { zoo[cnt].waitTillRunning(); } catch (Exception e) { throw new RuntimeException(e); } } /* average model, and propagate it to whole */ if (iterationsCounter.get() % averagingFrequency == 0 && pos + 1 == workers) { double score = 0.0; if (!legacyAveraging) { List<INDArray> params = new ArrayList<>(); for (int cnt = 0; cnt < workers && cnt < locker.get(); cnt++) { params.add(zoo[cnt].getModel().params()); score += zoo[cnt].getModel().score(); } Nd4j.averageAndPropagate(model.params(), params); } else { INDArray params = Nd4j.zeros(model.params().shape()); int cnt = 0; for (; cnt < workers && cnt < locker.get(); cnt++) { params.addi(zoo[cnt].getModel().params()); score += zoo[cnt].getModel().score(); } params.divi(workers); model.setParams(params); } score /= Math.min(workers, locker.get()); // TODO: improve this if (reportScore) logger.info("Averaged score: " + score); // averaging updaters state if (model instanceof MultiLayerNetwork) { if (averageUpdaters) { Updater updater = ((MultiLayerNetwork) model).getUpdater(); if (updater != null && updater.getStateViewArray() != null) { if (!legacyAveraging) { List<INDArray> updaters = new ArrayList<>(); for (int cnt = 0; cnt < workers && cnt < locker.get(); cnt++) { updaters.add(((MultiLayerNetwork) zoo[cnt].getModel()).getUpdater().getStateViewArray()); } Nd4j.averageAndPropagate(updater.getStateViewArray(), updaters); } else { INDArray state = Nd4j.zeros(updater.getStateViewArray().shape()); int cnt = 0; for (; cnt < workers && cnt < locker.get(); cnt++) { state.addi(((MultiLayerNetwork) zoo[cnt].getModel()).getUpdater().getStateViewArray().dup()); } state.divi(cnt); updater.setStateViewArray((MultiLayerNetwork) model, state, false); } } } ((MultiLayerNetwork) model).setScore(score); } else if (model instanceof ComputationGraph) { if (averageUpdaters) { ComputationGraphUpdater updater = ((ComputationGraph) model).getUpdater(); if (updater != null && updater.getStateViewArray() != null) { if (!legacyAveraging) { List<INDArray> updaters = new ArrayList<>(); for (int cnt = 0; cnt < workers && cnt < locker.get(); cnt++) { updaters.add(((ComputationGraph) zoo[cnt].getModel()).getUpdater().getStateViewArray()); } Nd4j.averageAndPropagate(updater.getStateViewArray(), updaters); } else { INDArray state = Nd4j.zeros(updater.getStateViewArray().shape()); int cnt = 0; for (; cnt < workers && cnt < locker.get(); cnt++) { state.addi(((ComputationGraph) zoo[cnt].getModel()).getUpdater().getStateViewArray()); } state.divi(cnt); updater.setStateViewArray(state); } } } ((ComputationGraph) model).setScore(score); } if (legacyAveraging) { for (int cnt = 0; cnt < workers; cnt++) { zoo[cnt].updateModel(model); } } } locker.set(0); } } logger.debug("Iterations passed: {}", iterationsCounter.get()); iterationsCounter.set(0); } public static class Builder { private Model model; private int workers = 2; private int prefetchSize = 16; private int averagingFrequency = 1; private boolean reportScore = false; private boolean averageUpdaters = true; private boolean legacyAveraging = true; /** * Build ParallelWrapper for MultiLayerNetwork * * @param mln */ public Builder(@NonNull MultiLayerNetwork mln) { model = mln; } /** * Build ParallelWrapper for ComputationGraph * * @param graph */ public Builder(@NonNull ComputationGraph graph) { model = graph; } /** * This method allows to configure number of workers that'll be used for parallel training * * @param num * @return */ public Builder workers(int num) { if (num < 2) throw new RuntimeException("Number of workers can't be lower then 2!"); this.workers = num; return this; } /** * Model averaging frequency. * * @param freq number of iterations between averagin * @return */ public Builder averagingFrequency(int freq) { this.averagingFrequency = freq; return this; } /** * This method enables/disables updaters averaging. * * Default value: TRUE * * PLEASE NOTE: This method is suitable for debugging purposes mostly. So don't change default value, unless you're sure why you need it. * * @param reallyAverage * @return */ public Builder averageUpdaters(boolean reallyAverage) { this.averageUpdaters = reallyAverage; return this; } /** * Size of prefetch buffer that will be used for background data prefetching. * Usually it's better to keep this value equal to the number of workers. * * Default value: 2 * * @param size 0 to disable prefetching, any positive number * @return */ public Builder prefetchBuffer(int size) { if (size < 0) size = 0; this.prefetchSize = size; return this; } /** * If set to true, legacy averaging method is used. This might be used as fallback on multi-gpu systems without P2P access available. * * Default value: false * * @param reallyUse * @return */ public Builder useLegacyAveraging(boolean reallyUse) { this.legacyAveraging = reallyUse; return this; } /** * This method enables/disables averaged model score reporting * * @param reallyReport * @return */ public Builder reportScoreAfterAveraging(boolean reallyReport) { this.reportScore = reallyReport; return this; } /** * This method returns ParallelWrapper instance * * @return */ public ParallelWrapper build() { ParallelWrapper wrapper = new ParallelWrapper(model, workers, prefetchSize); wrapper.averagingFrequency = this.averagingFrequency; wrapper.reportScore = this.reportScore; wrapper.averageUpdaters = this.averageUpdaters; wrapper.legacyAveraging = this.legacyAveraging; return wrapper; } } private static class Trainer extends Thread implements Runnable { private Model originalModel; private Model replicatedModel; private LinkedBlockingQueue<DataSet> queue = new LinkedBlockingQueue<>(); private AtomicInteger running = new AtomicInteger(0); private int threadId; private AtomicBoolean shouldUpdate = new AtomicBoolean(false); private AtomicBoolean shouldStop = new AtomicBoolean(false); private Exception thrownException; public Trainer(int threadId, Model model) { this.threadId = threadId; this.setDaemon(true); this.setName("ParallelWrapper trainer " + threadId); this.originalModel = model; if (model instanceof MultiLayerNetwork) { // if (threadId != 0) // ((MultiLayerNetwork)this.replicatedModel).setListeners(new ArrayList<IterationListener>()); } else if (model instanceof ComputationGraph) { this.replicatedModel = ((ComputationGraph) model).clone(); if (threadId != 0) ((ComputationGraph)this.replicatedModel).setListeners(new ArrayList<IterationListener>()); } } public void feedDataSet(@NonNull DataSet dataSet) { running.incrementAndGet(); queue.add(dataSet); } public Model getModel() { return replicatedModel; } public void updateModel(@NonNull Model model) { this.shouldUpdate.set(true); if (replicatedModel instanceof MultiLayerNetwork) { replicatedModel.setParams(model.params().dup()); Updater updater = ((MultiLayerNetwork) originalModel).getUpdater(); INDArray view = updater.getStateViewArray(); updater = ((MultiLayerNetwork) replicatedModel).getUpdater(); updater.setStateViewArray((MultiLayerNetwork) replicatedModel, view.dup(), false); } else if (replicatedModel instanceof ComputationGraph) { replicatedModel.setParams(model.params().dup()); ComputationGraphUpdater updater = ((ComputationGraph) originalModel).getUpdater(); INDArray view = updater.getStateViewArray(); updater = ((ComputationGraph) replicatedModel).getUpdater(); updater.setStateViewArray(view.dup()); } if (Nd4j.getExecutioner() instanceof GridExecutioner) ((GridExecutioner) Nd4j.getExecutioner()).flushQueueBlocking(); } public boolean isRunning(){ // if Trainer thread got exception during training - rethrow it here if (thrownException != null) throw new RuntimeException(thrownException); return running.get() == 0; } public void shutdown() { shouldStop.set(true); } @Override public void run() { try { // however, we don't need clone or anything here if (originalModel instanceof MultiLayerNetwork) { MultiLayerConfiguration conf = ((MultiLayerNetwork) originalModel).getLayerWiseConfigurations().clone(); this.replicatedModel = new MultiLayerNetwork(conf); ((MultiLayerNetwork) replicatedModel).init(); } else if (originalModel instanceof ComputationGraph) { this.replicatedModel = new ComputationGraph(((ComputationGraph) originalModel).getConfiguration().clone()); ((ComputationGraph) this.replicatedModel).init(); } while (!shouldStop.get()) { DataSet dataSet = queue.poll(100, TimeUnit.MILLISECONDS); if (dataSet != null) { if (replicatedModel instanceof MultiLayerNetwork) { ((MultiLayerNetwork) replicatedModel).fit(dataSet); } else if (replicatedModel instanceof ComputationGraph) { ((ComputationGraph) replicatedModel).fit(dataSet); } if (Nd4j.getExecutioner() instanceof GridExecutioner) ((GridExecutioner) Nd4j.getExecutioner()).flushQueueBlocking(); running.decrementAndGet(); } } } catch (Exception e) { this.thrownException = e; } } public void waitTillRunning() { while (running.get() != 0) { // if Trainer thread got exception during training - rethrow it here if (thrownException != null) throw new RuntimeException(thrownException); try { Thread.sleep(10); } catch (Exception e) { ; } } } } }
package action; import static org.jboss.arquillian.graphene.Graphene.guardHttp; import static org.junit.Assert.assertTrue; import java.io.File; import java.net.URL; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.drone.api.annotation.Drone; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.Filters; import org.jboss.shrinkwrap.api.GenericArchive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.importer.ExplodedImporter; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.Test; import org.junit.runner.RunWith; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import data.MemberList; import data.MemberValidator; import model.Member; import mock.MockMemberListProducer; @RunWith(Arquillian.class) public class LoginActionTest { public static final String TEST_USERNAME = "test"; public static final String TEST_PASSWORD = "xecret"; public static final String TEST_FIRSTNAME = "Tapfoot"; @Drone private WebDriver driver; // These injected WebElements are proxied, so elements don't have to exist until test accesses them @FindBy(id="loginForm:userName") private WebElement userNameTF; @FindBy(id="loginForm:password") private WebElement passwordTF; @FindBy(id="loginForm:login") private WebElement loginButton; @FindBy(id="menu.loggedInName") private WebElement loggedInName; @ArquillianResource private URL deploymentUrl; @Deployment() public static WebArchive createDeployment() { String DSD = "org.apache.deltaspike.modules:deltaspike-data-module-api:1.3.0"; String DSAPI = "com.darwinsys:darwinsys-api:1.0.5"; String MOCKITO = "org.powermock:powermock-api-mockito:1.6.2"; File[] files = Maven.resolver().resolve(DSD, MOCKITO, DSAPI).withTransitivity().asFile(); final WebArchive archive = ShrinkWrap.create(WebArchive.class, "clubtesting.war") .addPackage(LoginAction.class.getPackage()) // action .addPackage(Member.class.getPackage()) // model .addPackage(MockMemberListProducer.class.getPackage()) // mock .addPackage(WebDriver.class.getPackage()) .addClasses( // MemberHome.class, // exclude MemberList.class, MemberValidator.class ) .addAsLibraries(files) .merge(ShrinkWrap.create(GenericArchive.class).as(ExplodedImporter.class) .importDirectory("src/main/webapp").as(GenericArchive.class), "/", Filters.include(".*\\.xhtml$")) .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") // Yes, this is src/main/resources, not src/test/resources .addAsResource(new File("src/main/resources" + "/META-INF/persistence.xml"), "META-INF/persistence.xml") // Mistakes such as missing leading "/" may cause silent failures .addAsResource(new File("src/main/resources" + "/config-sample.properties"), "config.properties") .addAsWebInfResource(new File("src/test/web.xml"), "WEB-INF/web.xml") .addAsWebInfResource( new StringAsset("<faces-config version=\"2.1\"/>"), "faces-config.xml") ; return archive; } @RunAsClient @Test public void testLoginSuccessfully() { final String target = deploymentUrl.toExternalForm() + "login.jsf"; System.out.println("LoginActionTest.testLoginSuccessfully(): URL = " + target); driver.get(target); //System.out.println(driver.getPageSource()); userNameTF.sendKeys(TEST_USERNAME); passwordTF.sendKeys(TEST_PASSWORD); guardHttp(loginButton).click(); //System.out.println(driver.getPageSource()); assertTrue(driver.getPageSource().contains("Welcome " + TEST_FIRSTNAME)); } // @Test public void testLogout() { // XXX fail("Not yet implemented"); } }
package org.javarosa.cases.model; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.Date; import java.util.Enumeration; import java.util.Hashtable; import java.util.Vector; import org.javarosa.core.model.Constants; import org.javarosa.core.model.data.IAnswerData; import org.javarosa.core.model.data.SelectMultiData; import org.javarosa.core.model.instance.DataModelTree; import org.javarosa.core.model.instance.TreeElement; import org.javarosa.core.model.instance.TreeReference; import org.javarosa.core.model.util.restorable.Restorable; import org.javarosa.core.model.util.restorable.RestoreUtils; import org.javarosa.core.services.storage.utilities.IDRecordable; import org.javarosa.core.util.externalizable.DeserializationException; import org.javarosa.core.util.externalizable.ExtUtil; import org.javarosa.core.util.externalizable.ExtWrapMapPoly; import org.javarosa.core.util.externalizable.ExtWrapNullable; import org.javarosa.core.util.externalizable.Externalizable; import org.javarosa.core.util.externalizable.PrototypeFactory; import org.javarosa.xform.util.XFormAnswerDataParser; /** * NOTE: All new fields should be added to the case class using the "data" class, * as it demonstrated by the "userid" field. This prevents problems with datatype * representation across versions. * * @author Clayton Sims * @date Mar 19, 2009 * */ public class Case implements Externalizable, IDRecordable, Restorable { private String typeId; private String id; private String name; private boolean closed = false; private Date dateOpened; int recordId; Hashtable data = new Hashtable(); /** * NOTE: This constructor is for serialization only. */ public Case() { dateOpened = new Date(); } public Case(String name, String typeId) { this.name = name; this.typeId = typeId; dateOpened = new Date(); } /** * @return the typeId */ public String getTypeId() { return typeId; } /** * @param typeId the typeId to set */ public void setTypeId(String typeId) { this.typeId = typeId; } /** * @return The name of this case */ public String getName() { return name; } /** * @param The name of this case */ public void setName(String name) { this.name = name; } /** * @return True if this case is closed, false otherwise. */ public boolean isClosed() { return closed; } /** * @param Whether or not this case should be recorded as closed */ public void setClosed(boolean closed) { this.closed = closed; } /** * @return the recordId */ public int getRecordId() { return recordId; } /** * @return the id */ public String getId() { return id; } public int getUserId() { Integer id = (Integer)data.get(org.javarosa.core.api.Constants.USER_ID_KEY); if(id == null) { return -1; } else { return id.intValue(); } } public void setUserId(int id) { data.put(org.javarosa.core.api.Constants.USER_ID_KEY, new Integer(id)); } /** * @param id the id to set */ public void setId(String id) { this.id = id; } /** * @return the dateOpened */ public Date getDateOpened() { return dateOpened; } /** * @param dateOpened the dateOpened to set */ public void setDateOpened(Date dateOpened) { this.dateOpened = dateOpened; } /* (non-Javadoc) * @see org.javarosa.core.util.externalizable.Externalizable#readExternal(java.io.DataInputStream, org.javarosa.core.util.externalizable.PrototypeFactory) */ public void readExternal(DataInputStream in, PrototypeFactory pf) throws IOException, DeserializationException { typeId = in.readUTF(); id = (String)ExtUtil.read(in, new ExtWrapNullable(String.class)); name =in.readUTF(); closed = in.readBoolean(); dateOpened = new Date(in.readLong()); recordId = in.readInt(); data = (Hashtable)ExtUtil.read(in, new ExtWrapMapPoly(String.class, true)); } /* (non-Javadoc) * @see org.javarosa.core.util.externalizable.Externalizable#writeExternal(java.io.DataOutputStream) */ public void writeExternal(DataOutputStream out) throws IOException { out.writeUTF(typeId); ExtUtil.write(out, new ExtWrapNullable(id)); out.writeUTF(name); out.writeBoolean(closed); out.writeLong(dateOpened.getTime()); out.writeInt(recordId); ExtUtil.write(out, new ExtWrapMapPoly(data)); } public void setRecordId(int recordId) { this.recordId = recordId; } public void setProperty(String key, Object value) { this.data.put(key, value); } public Object getProperty(String key) { return data.get(key); } public DataModelTree exportData() { DataModelTree dm = RestoreUtils.createDataModel(this); RestoreUtils.addData(dm, "case-id", id); RestoreUtils.addData(dm, "case-type-id", typeId); RestoreUtils.addData(dm, "name", name); RestoreUtils.addData(dm, "dateopened", dateOpened); RestoreUtils.addData(dm, "closed", new Boolean(closed)); for (Enumeration e = data.keys(); e.hasMoreElements(); ) { String key = (String)e.nextElement(); RestoreUtils.addData(dm, "other/" + key + "/type", new Integer(RestoreUtils.getDataType(data.get(key)))); RestoreUtils.addData(dm, "other/" + key + "/data", data.get(key)); } return dm; } public String getRestorableType() { return "case"; } public void importData(DataModelTree dm) { id = (String)RestoreUtils.getValue("case-id", dm); typeId = (String)RestoreUtils.getValue("case-type-id", dm); name = (String)RestoreUtils.getValue("name", dm); dateOpened = (Date)RestoreUtils.getValue("dateopened", dm); closed = RestoreUtils.getBoolean(RestoreUtils.getValue("closed", dm)); // Clayton Sims - Apr 14, 2009 : NOTE: this is unfortunate, but we need // to be able to unparse. //XFormAnswerDataSerializer s = new XFormAnswerDataSerializer(); TreeElement e = dm.resolveReference(RestoreUtils.absRef("other", dm)); for (int i = 0; i < e.getNumChildren(); i++) { TreeElement child = (TreeElement)e.getChildren().elementAt(i); String name = child.getName(); int dataType = ((Integer)RestoreUtils.getValue("other/"+name+"/type", dm)).intValue(); String flatval = (String)RestoreUtils.getValue("other/"+ name+"/data", dm); if(flatval == null) { flatval = ""; } IAnswerData interpreted = XFormAnswerDataParser.getAnswerData(flatval, dataType); if(interpreted != null) { Object value = interpreted.getValue(); if(dataType == Constants.DATATYPE_CHOICE_LIST) { value = new SelectMultiData((Vector)value); } data.put(name, value); } } } public void templateData(DataModelTree dm, TreeReference parentRef) { RestoreUtils.applyDataType(dm, "case-id", parentRef, String.class); RestoreUtils.applyDataType(dm, "case-type-id", parentRef, String.class); RestoreUtils.applyDataType(dm, "name", parentRef, String.class); RestoreUtils.applyDataType(dm, "dateopened", parentRef, Date.class); RestoreUtils.applyDataType(dm, "closed", parentRef, Boolean.class); RestoreUtils.applyDataType(dm, "other/*/type", parentRef, Integer.class);
package org.opendaylight.netvirt.natservice.internal; import com.google.common.base.Strings; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import javax.inject.Inject; import javax.inject.Singleton; import org.opendaylight.controller.md.sal.binding.api.DataBroker; import org.opendaylight.genius.mdsalutil.ActionInfo; import org.opendaylight.genius.mdsalutil.BucketInfo; import org.opendaylight.genius.mdsalutil.GroupEntity; import org.opendaylight.genius.mdsalutil.MDSALUtil; import org.opendaylight.genius.mdsalutil.actions.ActionDrop; import org.opendaylight.genius.mdsalutil.actions.ActionSetFieldEthernetDestination; import org.opendaylight.genius.mdsalutil.interfaces.IMdsalApiManager; import org.opendaylight.infrautils.jobcoordinator.JobCoordinator; import org.opendaylight.netvirt.elanmanager.api.IElanService; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.MacAddress; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid; import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.idmanager.rev160406.IdManagerService; import org.opendaylight.yang.gen.v1.urn.opendaylight.genius.interfacemanager.rpcs.rev160406.OdlInterfaceRpcService; import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupTypes; import org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.neutronvpn.rev150602.subnetmaps.Subnetmap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Singleton public class ExternalNetworkGroupInstaller { private static final Logger LOG = LoggerFactory.getLogger(ExternalNetworkGroupInstaller.class); private final DataBroker broker; private final IMdsalApiManager mdsalManager; private final IElanService elanService; private final IdManagerService idManager; private final OdlInterfaceRpcService interfaceManager; private final JobCoordinator coordinator; @Inject public ExternalNetworkGroupInstaller(final DataBroker broker, final IMdsalApiManager mdsalManager, final IElanService elanService, final IdManagerService idManager, final OdlInterfaceRpcService interfaceManager, final JobCoordinator coordinator) { this.broker = broker; this.mdsalManager = mdsalManager; this.elanService = elanService; this.idManager = idManager; this.interfaceManager = interfaceManager; this.coordinator = coordinator; } public void installExtNetGroupEntries(Subnetmap subnetMap) { if (subnetMap == null) { LOG.error("installExtNetGroupEntries : Subnetmap is null"); return; } if (NatUtil.isIPv6Subnet(subnetMap.getSubnetIp())) { LOG.debug("installExtNetGroupEntries : Subnet id {} is not an IPv4 subnet, hence skipping.", subnetMap.getId()); return; } Uuid networkId = subnetMap.getNetworkId(); Uuid subnetId = subnetMap.getId(); if (networkId == null) { LOG.error("installExtNetGroupEntries : No network associated subnet id {}", subnetId.getValue()); return; } String macAddress = NatUtil.getSubnetGwMac(broker, subnetId, networkId.getValue()); installExtNetGroupEntries(subnetMap, macAddress); } public void installExtNetGroupEntries(Uuid subnetId, String macAddress) { Subnetmap subnetMap = NatUtil.getSubnetMap(broker, subnetId); if (subnetMap == null) { LOG.error("installExtNetGroupEntries : Subnetmap is null"); return; } if (NatUtil.isIPv6Subnet(subnetMap.getSubnetIp())) { LOG.debug("installExtNetGroupEntries : Subnet-id {} is not an IPv4 subnet, hence skipping.", subnetMap.getId()); return; } installExtNetGroupEntries(subnetMap, macAddress); } public void installExtNetGroupEntries(Uuid networkId, BigInteger dpnId) { if (networkId == null) { return; } List<Uuid> subnetIds = NatUtil.getSubnetIdsFromNetworkId(broker, networkId); if (subnetIds.isEmpty()) { LOG.error("installExtNetGroupEntries : No subnet ids associated network id {}", networkId.getValue()); return; } for (Uuid subnetId : subnetIds) { String macAddress = NatUtil.getSubnetGwMac(broker, subnetId, networkId.getValue()); installExtNetGroupEntry(networkId, subnetId, dpnId, macAddress); } } private void installExtNetGroupEntries(Subnetmap subnetMap, String macAddress) { String subnetName = subnetMap.getId().getValue(); Uuid networkId = subnetMap.getNetworkId(); if (networkId == null) { LOG.error("installExtNetGroupEntries : No network associated subnet id {}", subnetName); return; } Collection<String> extInterfaces = elanService.getExternalElanInterfaces(networkId.getValue()); if (extInterfaces == null || extInterfaces.isEmpty()) { LOG.trace("installExtNetGroupEntries : No external ELAN interfaces attached to network:{},subnet {}", networkId, subnetName); return; } long groupId = NatUtil.createGroupId(NatUtil.getGroupIdKey(subnetName), idManager); LOG.info("installExtNetGroupEntries : Installing ext-net group {} entry for subnet {} with macAddress {} " + "(extInterfaces: {})", groupId, subnetName, macAddress, Arrays.toString(extInterfaces.toArray())); for (String extInterface : extInterfaces) { BigInteger dpId = NatUtil.getDpnForInterface(interfaceManager, extInterface); if (BigInteger.ZERO.equals(dpId)) { LOG.info("installExtNetGroupEntries: No DPN for interface {}. NAT ext-net flow will not be installed " + "for subnet {}", extInterface, subnetName); return; } installExtNetGroupEntry(groupId, subnetName, extInterface, macAddress, dpId); } } public void installExtNetGroupEntry(Uuid networkId, Uuid subnetId, BigInteger dpnId, String macAddress) { String subnetName = subnetId.getValue(); String extInterface = elanService.getExternalElanInterface(networkId.getValue(), dpnId); if (extInterface == null) { LOG.warn("installExtNetGroupEntry : No external ELAN interface attached to network {} subnet {} DPN id {}", networkId, subnetName, dpnId); //return; } long groupId = NatUtil.createGroupId(NatUtil.getGroupIdKey(subnetName), idManager); LOG.info("installExtNetGroupEntry : Installing ext-net group {} entry for subnet {} with macAddress {} " + "(extInterface: {})", groupId, subnetName, macAddress, extInterface); installExtNetGroupEntry(groupId, subnetName, extInterface, macAddress, dpnId); } private void installExtNetGroupEntry(long groupId, String subnetName, String extInterface, String macAddress, BigInteger dpnId) { coordinator.enqueueJob(NatConstants.NAT_DJC_PREFIX + subnetName + extInterface, () -> { GroupEntity groupEntity = buildExtNetGroupEntity(macAddress, subnetName, groupId, extInterface, dpnId); if (groupEntity != null) { mdsalManager.syncInstallGroup(groupEntity); } return Collections.emptyList(); }); } public void removeExtNetGroupEntries(Subnetmap subnetMap) { if (subnetMap == null) { return; } String subnetName = subnetMap.getId().getValue(); Uuid networkId = subnetMap.getNetworkId(); if (networkId == null) { LOG.error("removeExtNetGroupEntries : No external network associated subnet id {}", subnetName); return; } Collection<String> extInterfaces = elanService.getExternalElanInterfaces(networkId.getValue()); if (extInterfaces == null || extInterfaces.isEmpty()) { LOG.debug("removeExtNetGroupEntries : No external ELAN interfaces attached to network {} subnet {}", networkId, subnetName); return; } long groupId = NatUtil.createGroupId(NatUtil.getGroupIdKey(subnetName), idManager); for (String extInterface : extInterfaces) { GroupEntity groupEntity = buildEmptyExtNetGroupEntity(subnetName, groupId, extInterface); if (groupEntity != null) { LOG.info("removeExtNetGroupEntries : Remove ext-net Group: id {}, subnet id {}", groupId, subnetName); NatServiceCounters.remove_external_network_group.inc(); mdsalManager.syncRemoveGroup(groupEntity); } } } private GroupEntity buildExtNetGroupEntity(String macAddress, String subnetName, long groupId, String extInterface, BigInteger dpnId) { List<ActionInfo> actionList = new ArrayList<>(); final int setFieldEthDestActionPos = 0; List<ActionInfo> egressActionList = new ArrayList<>(); if (extInterface != null) { egressActionList = NatUtil.getEgressActionsForInterface(interfaceManager, extInterface, null, setFieldEthDestActionPos + 1); } if (Strings.isNullOrEmpty(macAddress) || egressActionList.isEmpty()) { if (Strings.isNullOrEmpty(macAddress)) { LOG.trace("buildExtNetGroupEntity : Building ext-net group {} entry with drop action since " + "GW mac has not been resolved for subnet {} extInterface {}", groupId, subnetName, extInterface); } else { LOG.warn("buildExtNetGroupEntity : Building ext-net group {} entry with drop action since " + "no egress actions were found for subnet {} extInterface {}", groupId, subnetName, extInterface); } actionList.add(new ActionDrop()); } else { LOG.trace("Building ext-net group {} entry for subnet {} extInterface {} macAddress {}", groupId, subnetName, extInterface, macAddress); actionList.add(new ActionSetFieldEthernetDestination(setFieldEthDestActionPos, new MacAddress(macAddress))); actionList.addAll(egressActionList); } List<BucketInfo> listBucketInfo = new ArrayList<>(); listBucketInfo.add(new BucketInfo(actionList)); return MDSALUtil.buildGroupEntity(dpnId, groupId, subnetName, GroupTypes.GroupAll, listBucketInfo); } private GroupEntity buildEmptyExtNetGroupEntity(String subnetName, long groupId, String extInterface) { BigInteger dpId = NatUtil.getDpnForInterface(interfaceManager, extInterface); if (BigInteger.ZERO.equals(dpId)) { LOG.error("buildEmptyExtNetGroupEntity: No DPN for interface {}. NAT ext-net flow will not be installed " + "for subnet {}", extInterface, subnetName); return null; } return MDSALUtil.buildGroupEntity(dpId, groupId, subnetName, GroupTypes.GroupAll, new ArrayList<>()); } }
package etomica; import java.util.Collections; import java.util.EventObject; import java.util.Iterator; import java.util.LinkedList; import etomica.atom.iterator.AtomIteratorListSimple; import etomica.data.meter.MeterPotentialEnergy; import etomica.space.Vector; import etomica.units.Dimension; import etomica.utility.Arrays; import etomica.utility.NameMaker; /** * Integrator is used to define the algorithm used to move the atoms around and * generate new configurations in one or more phases. All integrator methods, * such as molecular dynamics or Monte Carlo are implemented via subclasses of * this Integrator class. The Integrator's activities are managed via the * actions of the governing Controller. * * @author David Kofke */ /* * History * * 07/10/03 (DAK) made Agent interface public 08/25/03 (DAK) changed default for * doSleep to <false> 01/27/04 (DAK) initialized iieCount to inverval (instead * of interval+1) in run method; changed setInterval do disallow non-positive * interval 04/13/04 (DAK) modified reset such that doReset is called if running * is false */ public abstract class Integrator implements java.io.Serializable { protected final PotentialMaster potential; protected Phase firstPhase; protected Phase[] phase; protected boolean equilibrating = false; protected boolean initialized = false; public int phaseCountMax = 1; protected int sleepPeriod = 10; private final LinkedList intervalListeners = new LinkedList(); private ListenerWrapper[] listenerWrapperArray = new ListenerWrapper[0]; int integrationCount = 0; protected double temperature = Default.TEMPERATURE; protected boolean isothermal = false; private String name; protected MeterPotentialEnergy meterPE; protected double[] currentPotentialEnergy = new double[0]; public Integrator(PotentialMaster potentialMaster) { setName(NameMaker.makeName(this.getClass())); phase = new Phase[0]; this.potential = potentialMaster; meterPE = new MeterPotentialEnergy(potentialMaster); if (Default.AUTO_REGISTER) { Simulation.getDefault().register(this); } } /** * Accessor method of the name of this phase * * @return The given name of this phase */ public final String getName() {return name;} /** * Method to set the name of this simulation element. The element's name * provides a convenient way to label output data that is associated with * it. This method might be used, for example, to place a heading on a * column of data. Default name is the base class followed by the integer * index of this element. * * @param name The name string to be associated with this element */ public void setName(String name) {this.name = name;} /** * Overrides the Object class toString method to have it return the output of getName * * @return The name given to the phase */ public String toString() {return getName();} /** * Performs the elementary integration step, such as a molecular dynamics * time step, or a Monte Carlo trial. */ public abstract void doStep(); /** * Defines the actions taken by the integrator to reset itself, such as * required if a perturbation is applied to the simulated phase (e.g., * addition or deletion of a molecule). Also invoked when the * integrator is started or initialized. This also recalculates the * potential energy. */ public void reset() { if(!initialized) return; meterPE.setPhase(phase); currentPotentialEnergy = meterPE.getData(); for (int i=0; i<phase.length; i++) { if (currentPotentialEnergy[i] == Double.POSITIVE_INFINITY) { if (Default.FIX_OVERLAP) { System.out.println("overlap in "+phase[i]); } else { throw new RuntimeException("overlap in "+phase[i]); } } } } /** * Perform any action necessary when neighbor lists are updated */ public void neighborsUpdated() {} /** ;* Returns a new instance of an agent of this integrator for placement in * the given atom in the ia (IntegratorAgent) field. */ public abstract Object makeAgent(Atom a); /** * Initializes the integrator, performing the following steps: (1) deploys * agents in all atoms; (2) call reset method; (3) fires an event * indicating to registered listeners indicating that initialization has * been performed (i.e. fires IntervalEvent of type field set to * INITIALIZE). */ public void initialize() { deployAgents(); initialized = true; reset(); } //how do agents get placed in atoms made during the simulation? protected void deployAgents() { //puts an Agent of this integrator in each // atom of all phases AtomIteratorListSimple iterator = new AtomIteratorListSimple(); for (int i = 0; i < phase.length; i++) { Phase p = phase[i]; iterator.setList(p.speciesMaster.atomList); iterator.reset(); while (iterator.hasNext()) {//does only leaf atoms; do atom groups // need agents? Atom a = iterator.nextAtom(); a.setIntegratorAgent(makeAgent(a)); } } } /** * sets the temperature for this integrator */ public void setTemperature(double t) { temperature = t; } /** * @return the integrator's temperature */ //XXX redundant with temperature(). one of these needs to go public final double getTemperature() { return temperature; } /** * @return the integrator's temperature */ //XXX redundant with getTemperature(). one of these needs to go public final double temperature() { return temperature; } /** * @return the dimenension of temperature (TEMPERATURE) */ public final Dimension getTemperatureDimension() { return Dimension.TEMPERATURE; } /** * @return the potential energy of each phase handled by this integrator */ public double[] getPotentialEnergy() { return currentPotentialEnergy; } //Other introspected properties public void setIsothermal(boolean b) { isothermal = b; } public boolean isIsothermal() { return isothermal; } /** * @return Returns flag indicating whether integrator is in equilibration mode. */ public boolean isEquilibrating() { return equilibrating; } /** * @param equilibrating * Sets equilibration mode of integrator. */ public void setEquilibrating(boolean equilibrating) { this.equilibrating = equilibrating; } /** * @return true if integrator can perform integration of another phase, * false if the integrator has all the phases it was built to handle */ public boolean wantsPhase() { return phase.length < phaseCountMax; } /** * Performs activities needed to set up integrator to work on given phase. * This method should not be called directly; instead it is invoked by the * phase in its setIntegrator method. * * @return true if the phase was successfully added to the integrator; false * otherwise */ //perhaps should throw an exception rather than returning a boolean "false" public boolean addPhase(Phase p) { for (int i = 0; i < phase.length; i++) { if (phase[i] == p) return false; } //check that phase is not already registered if (!this.wantsPhase()) { return false; } //if another phase not wanted, return false phase = (Phase[])Arrays.addOjbect(phase,p); firstPhase = phase[0]; if (Debug.ON && p.index == Debug.PHASE_INDEX) { Debug.setAtoms(p); } return true; } /** * Performs activities needed to disconnect integrator from given phase. * This method should not be called directly; instead it is invoked by the * phase in its setIntegrator method */ public void removePhase(Phase p) { for (int i = 0; i < phase.length; i++) { if (phase[i] == p) {//phase found; remove it phase = (Phase[])Arrays.removeObject(phase,p); if (phaseCount > 0) { firstPhase = phase[0]; } break; } } } public Phase[] getPhase() { return phase; } /** * Arranges listeners registered with this iterator in order such that * those with the smallest (closer to zero) priority value are performed * before those with a larger priority value. This is invoked automatically * whenever a listener is added or removed. It should be invoked explicitly if * the priority setting of a registered listener is changed. */ public synchronized void sortListeners() { //sort using linked list, but put into array afterwards //for rapid looping (avoid repeated construction of iterator) Collections.sort(intervalListeners); listenerWrapperArray = (ListenerWrapper[])intervalListeners.toArray(new ListenerWrapper[0]); } /** * Adds the given listener to those that receive interval events fired by * this integrator. If listener has already been added to integrator, it is * not added again. If listener is null, NullPointerException is thrown. */ public synchronized void addIntervalListener(IntervalListener iil) { if(iil == null) throw new NullPointerException("Cannot add null as a listener to Integrator"); ListenerWrapper wrapper = findWrapper(iil); if(wrapper == null) { //listener not already in list, so OK to add it now intervalListeners.add(new ListenerWrapper(iil)); sortListeners(); } } /** * Removes all interval listeners. */ public synchronized void clearIntervalListeners() { intervalListeners.clear(); } /** * Finds and returns the ListenerWrapper used to put the given listener in the list. * Returns null if listener is not in list. */ private ListenerWrapper findWrapper(IntervalListener iil) { Iterator iterator = intervalListeners.iterator(); while(iterator.hasNext()) { ListenerWrapper wrapper = (ListenerWrapper)iterator.next(); if(wrapper.listener == iil) return wrapper;//found it } return null;//didn't find it in list } /** * Removes given listener from those notified of interval events fired * by this integrator. No action results if given listener is null or is not registered * with this integrator. */ public synchronized void removeIntervalListener(IntervalListener iil) { ListenerWrapper wrapper = findWrapper(iil); intervalListeners.remove(wrapper); sortListeners(); } /** * Notifies registered listeners that an interval has passed. Not * synchronized, so unpredictable behavior if listeners are added while * notification is in process (this should be rare). */ public void fireIntervalEvent(IntervalEvent iie) { for(int i=0; i<listenerWrapperArray.length; i++) { listenerWrapperArray[i].listener.intervalAction(iie); } } /** * Registers with the given integrator all listeners currently registered * with this integrator. Removes all listeners from this integrator. */ public synchronized void transferListenersTo(Integrator anotherIntegrator) { if (anotherIntegrator == this) return; synchronized(anotherIntegrator) { for(int i=0; i<listenerWrapperArray.length; i++) { anotherIntegrator.intervalListeners.add(listenerWrapperArray[i]); } } anotherIntegrator.sortListeners(); intervalListeners.clear(); sortListeners(); } /** * Integrator agent that holds a force vector. Used to indicate that an atom * could be under the influence of a force. */ public interface Forcible { public Vector force(); } public static class IntervalEvent extends EventObject { // Typed constants used to indicate the type of event integrator is // announcing public static final Type START = new Type("Start"); //simulation is starting public static final Type INTERVAL = new Type("Interval"); //routine interval event public static final Type DONE = new Type("Done"); //simulation is finished public static final Type INITIALIZE = new Type("Initialize"); //integrator is initializing private final Type type; private int interval; public IntervalEvent(Integrator source, Type t) { super(source); type = t; } public IntervalEvent(Integrator source, int interval) { this(source, INTERVAL); this.interval = interval; } public int getInterval() { return interval; } public Type type() { return type; } //class used to mark the different types of interval events public final static class Type extends Constants.TypedConstant { private Type(String label) { super(label); } public static final Constants.TypedConstant[] choices = new Constants.TypedConstant[] { START, INTERVAL, DONE, INITIALIZE }; public final Constants.TypedConstant[] choices() { return choices; } } } public interface IntervalListener extends java.util.EventListener { /** * Action performed by the listener when integrator fires its interval event. */ public void intervalAction(IntervalEvent evt); /** * Priority assigned to the listener. A small value will cause the * listener's action to be performed earlier, before another listener having * a larger priority value (e.g., priority 100 action is performed before * one having a priority of 200). Listeners that cause periodic boundaries * to be applied are given priorities in the range 100-199. Ordering * is performed only when a listener is added to the integrator, or when * the sortListeners method of integrator is called. */ public int getPriority(); } /** * This class has a natural ordering that is inconsistent with equals. */ private static class ListenerWrapper implements Comparable { private final IntervalListener listener; private ListenerWrapper(IntervalListener listener) { this.listener = listener; } public int compareTo(Object obj) { int priority = listener.getPriority(); int objPriority = ((ListenerWrapper)obj).listener.getPriority(); //we do explicit comparison of values (rather than returning //their difference) to avoid potential problems with large integers. if(priority < objPriority) return -1; if(priority == objPriority) return 0; return +1; } } }
package org.op4j; import java.io.Serializable; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import junit.framework.TestCase; import org.apache.commons.lang.StringUtils; import org.javaruntype.type.Type; import org.javaruntype.type.Types; import org.junit.Before; import org.junit.Test; import org.op4j.exceptions.ExecutionException; import org.op4j.functions.Call; import org.op4j.functions.ExecCtx; import org.op4j.functions.Fn; import org.op4j.functions.FnArray; import org.op4j.functions.FnBigDecimal; import org.op4j.functions.FnBoolean; import org.op4j.functions.FnDouble; import org.op4j.functions.FnInteger; import org.op4j.functions.FnLong; import org.op4j.functions.FnNumber; import org.op4j.functions.FnShort; import org.op4j.functions.FnString; import org.op4j.functions.Function; import org.op4j.functions.IFunction; import org.op4j.functions.FnString.AsciifyMode; import org.op4j.test.auto.TestOperation; public class AssortedTests extends TestCase { private AssortedTestsData testUtils; @Override @Before public void setUp() throws Exception { this.testUtils = new AssortedTestsData(); } @Test public void test1() { List<String> data = this.testUtils.getStringList(8); List<String> result = Op.onList(data) .forEach().exec(new IFunction<String, String>() { public String execute(String input, ExecCtx ctx) throws Exception { return ctx.getIndex() + " - " + input; } public Type<? extends String> getResultType( Type<? extends String> targetType) { return Types.STRING; } }).get(); assertEquals(data.size(), result.size()); for (int index = 0; index < data.size(); index++) { assertEquals(index + " - " + data.get(index), result.get(index)); } } @Test public void test2() { List<String> data1 = this.testUtils.getStringList(8); List<String> data2 = this.testUtils.getStringList(10); List<String> result = Op.onList(data1) .addAll(data2).removeAllNullOrFalse(new IFunction<String, Boolean>() { public Boolean execute(String input, ExecCtx ctx) throws Exception { return Boolean.valueOf(StringUtils.contains("a", input)); } public Type<? extends Boolean> getResultType( Type<? extends String> targetType) { return Types.BOOLEAN; } }).get(); List<String> aResult = new ArrayList<String>(); data1.addAll(data2); for (String string : data1) { if (!StringUtils.contains("a", string)) { aResult.add(string); } } assertEquals(aResult.size(), result.size()); for (int index = 0; index < aResult.size(); index++) { assertEquals(aResult.get(index), result.get(index)); } } @Test public void test8() { Map<Integer, String> data = this.testUtils.getMapOfIntegerString(5); Map<Integer, String> result = Op.onMap(data) .forEachEntry() .onValue() .replaceWith("abc") .get(); assertEquals(data.size(), result.size()); for (Map.Entry<Integer, String> entry : result.entrySet()) { assertEquals( "abc", entry.getValue()); } } @Test public void test14() { List<Integer> expectedListInt1 = Arrays.asList(new Integer[] { 234,12,231 }); List<Integer> expectedListInt2 = Arrays.asList(new Integer[] { 234,10 }); List<Integer> listInt1 = Op.onListFor(234,12,231).get(); List<Integer> listInt2 = Op.onListFor(234).addAll(10).get(); assertEquals(expectedListInt1, listInt1); assertEquals(expectedListInt2, listInt2); } @Test public void test16() { final Serializable[] expSerArray = new Serializable[] {"one", "two", "three", Integer.valueOf(3) }; final Serializable[] serArray = new String[] {"one", "two", "three" }; Serializable[] newArray = Op.onArrayOf(Types.SERIALIZABLE, serArray).add(Integer.valueOf(3)).get(); assertEquals(Serializable[].class, newArray.getClass()); assertEquals(Arrays.asList(expSerArray), Arrays.asList(newArray)); } @Test public void test17() { final Serializable[] expSerArray = new Serializable[] {"one", "two", "three", Integer.valueOf(3) }; final Serializable[] serArray = new String[] {"one", "two", "three" }; Serializable[] newArray = Op.onArrayOf(Types.SERIALIZABLE, serArray).ifNotNull(). execAsArray( new IFunction<Serializable[],Serializable[]>() { public Type<? extends Serializable[]> getResultType(Type<? extends Serializable[]> targetType) { return targetType; } public Serializable[] execute(final Serializable[] input, final ExecCtx ctx) throws Exception { final String[] result = new String[input.length]; for (int i = 0; i < input.length; i++) { result[i] = (String) input[i]; } return result; } }).endIf().add(Integer.valueOf(3)).get(); assertEquals(Serializable[].class, newArray.getClass()); assertEquals(Arrays.asList(expSerArray), Arrays.asList(newArray)); } @Test public void test18() { final Serializable[] expSerArray = new Serializable[] {"one", "two", "three", Integer.valueOf(3) }; final Serializable[] serArray = new String[] {"one", "two", "three" }; Serializable[] newArray = Op.onArrayOf(Types.SERIALIZABLE, serArray).replaceWith(serArray).add(Integer.valueOf(3)).get(); assertEquals(Serializable[].class, newArray.getClass()); assertEquals(Arrays.asList(expSerArray), Arrays.asList(newArray)); } @Test public void test19 () { final Serializable[] expSerArray = new Serializable[] {"one", "two", "three", Integer.valueOf(3) }; final Serializable[] serArray = new String[] {"one", "two", "three" }; Serializable[] newArray = Op.on(serArray).of(Types.SERIALIZABLE).add(Integer.valueOf(3)).get(); assertEquals(Serializable[].class, newArray.getClass()); assertEquals(Arrays.asList(expSerArray), Arrays.asList(newArray)); } @Test public void test20() { final List<String> stringList = this.testUtils.getStringList(10); try { Op.onList(stringList).forEach().exec(Call.methodForInteger("toUpperCase")).endFor().toArrayOf(Types.INTEGER).get(); } catch (ExecutionException e) { assertTrue(e.getCause().getMessage().startsWith("Result of calling method")); } } @Test public void test21() { final List<String> stringList = Arrays.asList(new String[] {"one", "two", "three"}); final List<String> stringUpperList = Arrays.asList(new String[] {"ONE", "TWO", "THREE"}); final List<String> result = Op.onList(stringList).map(FnString.toUpperCase()).get(); assertEquals(stringUpperList, result); } // @Test // @SuppressWarnings("unchecked") // public void test22() { // final List<List<String>> stringListOfList = Arrays.asList( // Arrays.asList(new String[] {"one", "two", "three", "four"}), // Arrays.asList(new String[] {"un", "dous", "tres", "catro"}) // final List<List<String>> stringUpperListOfList = Arrays.asList( // Arrays.asList(new String[] {"ONE", "TWO", "THREE", "FOUR"}), // Arrays.asList(new String[] {"UN", "DOUS", "TRES", "CATRO"}) // final List<List<String>> result = // Op.onListOfList(stringListOfList).mapMap(StringFuncs.toUpperCase()).get(); // assertEquals(stringUpperListOfList, result); @Test public void test24() { final List<String> stringList = Arrays.asList(new String[] {"one", "two", "three", null}); final List<String> stringUpperList = Arrays.asList(new String[] {"ONE", "TWO", "THREE", null}); final List<String> result = Op.onList(stringList).forEach().execIfNotNull(FnString.toUpperCase()).get(); assertEquals(stringUpperList, result); } @Test public void test25() { final List<String> stringList = Arrays.asList(new String[] {"one", "two", "three", null}); final List<String> stringUpperList = Arrays.asList(new String[] {"ONE", "TWO", "THREE", null}); final List<String> result = Op.onList(stringList).mapIfNotNull(FnString.toUpperCase()).get(); assertEquals(stringUpperList, result); } @Test public void test26() { final String[] stringArr = new String[] {"one", "two", "three", "three", null, null}; final String[] stringArrDist = new String[] {"one", "two", "three", null, "four"}; final String[] result = Op.onArrayOf(Types.STRING, stringArr). exec(FnArray.ofString().distinct()). exec(FnArray.ofString().add("four")). get(); assertEquals(String[].class, result.getClass()); assertEquals(Arrays.asList(stringArrDist), Arrays.asList(result)); } @SuppressWarnings("unchecked") @Test public void test27() { final List<Integer> integerList = Arrays.asList(new Integer[]{null, 23, 34, null, -34}); List<TestOperation> testOperations = new ArrayList<TestOperation>(); testOperations.add(new TestOperation("add", new Object[] {Integer.valueOf(2)})); testOperations.add(new TestOperation("forEach")); testOperations.add(new TestOperation("ifNotNull")); testOperations.add(new TestOperation("replaceWith", new Object[]{null})); testOperations.add(new TestOperation("endIf")); testOperations.add(new TestOperation("exec", new Object[]{FnNumber.toStr()})); testOperations.add(new TestOperation("get")); final List<Integer> listResult = (List<Integer>)org.op4j.test.auto.Test.testOnList(integerList, testOperations); assertEquals(Arrays.asList(new Integer[]{null, null, null, null, null, null}), listResult); // System.out.println("test27. Result testOnList: " + listResult); final Integer[] arrayResult = (Integer[])org.op4j.test.auto.Test.testOnArrayOf(Types.INTEGER, integerList.toArray(new Integer[]{}), testOperations); assertEquals(Arrays.asList(new Integer[]{null, null, null, null, null, null}), Arrays.asList(arrayResult)); // System.out.println("test27. Result testOnArray: " + ArrayUtils.toString(arrayResult)); } @Test public void test28() { final Integer[] integerArr = new Integer[]{null, 23, 34, null, -34}; final List<Integer> integerList = Arrays.asList(integerArr); final List<Integer> result = Op.on(integerArr).toList().get(); assertEquals(integerList, result); } @Test public void test30() throws Exception { final List<String> stringList = Arrays.asList(new String[] {"one", "two", "three", null}); final List<String> stringUpperList = Arrays.asList(new String[] {"ONE", "TWO", "THREE", null}); final Function<List<String>,List<String>> fn = Fn.onListOf(Types.STRING).map(FnString.toUpperCase()).get(); final List<String> result = fn.execute(stringList); assertEquals(stringUpperList, result); final List<String> result2 = Op.on(stringList).exec(fn).get(); assertEquals(stringUpperList, result2); } @Test public void test31() throws Exception { assertEquals(Integer.valueOf(4), Op.on(10).exec(FnInteger.divideBy(3,RoundingMode.CEILING)).get()); } @Test public void test34() { final List<Integer> integerList = Arrays.asList(new Integer[]{null, 23, 34, null, -34}); assertEquals(Arrays.asList(null, 27, 38, null, -30), Op.on(integerList).forEach().exec(FnInteger.add(4)).get()); } @Test public void test35() { final List<BigDecimal> list = Arrays.asList(new BigDecimal[]{null, BigDecimal.valueOf(23), BigDecimal.valueOf(34), null, BigDecimal.valueOf(-34)}); assertEquals(Arrays.asList(null, BigDecimal.valueOf(23).add(BigDecimal.valueOf(4)), BigDecimal.valueOf(34).add(BigDecimal.valueOf(4)), null, BigDecimal.valueOf(-34).add(BigDecimal.valueOf(4))), Op.on(list).forEach().exec(FnBigDecimal.add(BigDecimal.valueOf(4))).get()); } @Test public void test36() throws Exception { final List<Long> result = Arrays.asList(new Long[] { 53L, 430L }); List<Long> values = Arrays.asList(new Long[] { 6641L, 53L, 430L, 1245L }); { values = Op.on(values).removeAllTrue(FnLong.greaterThan(500)).get(); assertEquals(result, values); } } @Test public void test37() throws Exception { final Long[] values = new Long[] { 53L, 430L }; String[] keys = new String[] { "A", "A" }; { Map<String,Long[]> groupedMap = Op.on(keys).zipAndGroupValuesFrom(Types.LONG, values).get(); assertEquals(1, groupedMap.size()); assertEquals(Long[].class, groupedMap.get("A").getClass()); assertEquals(Arrays.asList(values), Arrays.asList(groupedMap.get("A"))); } } @Test public void test38() throws Exception { final String str = "Earth"; Boolean matches = Op.on(str).exec(FnString.matches("a")).get(); assertEquals(Boolean.FALSE, matches); matches = Op.on(str).exec(FnString.matches(".a.*h")).get(); assertEquals(Boolean.TRUE, matches); } @Test public void test39() throws Exception { final String str = "Earth"; Boolean matches = Op.on(str).exec(FnString.contains("a")).get(); assertEquals(Boolean.TRUE, matches); matches = Op.on(str).exec(FnString.contains("b")).get(); assertEquals(Boolean.FALSE, matches); matches = Op.on(str).exec(FnString.contains(".a.*h")).get(); assertEquals(Boolean.TRUE, matches); } @Test public void test40() throws Exception { final String str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " + "Fusce a lacus lectus, quis tristique nibh. Aenean sit amet dolor justo. " + "Morbi nibh urna, ornare non congue non, dignissim at nibh. Nulla euismod, " + "dui id consequat tempus, lacus velit sodales metus, non luctus ipsum " + "purus id neque. Ut eleifend vestibulum rutrum. Praesent quis dui urna, " + "quis cursus arcu. Aliquam interdum quam quis erat condimentum ullamcorper. " + "Nam eget massa eu tellus pulvinar blandit sed quis libero. Proin ut quam " + "nunc, id rutrum mi. Vestibulum ante ipsum primis in faucibus orci luctus " + "et ultrices posuere cubilia Curae;"; assertEquals(11, Op.on(str).exec(FnString.extractAll("qu..")).get().size()); assertEquals("quis", Op.on(str).exec(FnString.extractFirst("qu..")).get()); assertEquals("quam", Op.on(str).exec(FnString.extractLast("qu..")).get()); assertEquals("eleif", Op.on(str).exec(FnString.matchAndExtract("(.*?)(ele..)(.*?)", 2)).get()); assertEquals(Arrays.asList(new String[] {"eleif", "liq"}), Op.on(str).exec(FnString.matchAndExtractAll("(.*?)(ele..)(.*?)(li.)(.*?)", 2, 4)).get()); } @Test public void test41() throws Exception { String[] arr1 = new String[] { "one", "two", "three" }; String[] arr2 = new String[] { "one", "two", "three", "four" }; String[] arr3 = new String[] { "one", "two" }; String[] arr4 = new String[] { "one" }; String[] arr5 = new String[] { }; String[] arr1Res = new String[] { "three", "two", "one" }; String[] arr2Res = new String[] { "four", "three", "two", "one" }; String[] arr3Res = new String[] { "two", "one" }; String[] arr4Res = new String[] { "one" }; String[] arr5Res = new String[] { }; arr1 = Op.on(arr1).reverse().get(); arr2 = Op.on(arr2).reverse().get(); arr3 = Op.on(arr3).reverse().get(); arr4 = Op.on(arr4).reverse().get(); arr5 = Op.on(arr5).reverse().get(); assertEquals(Arrays.asList(arr1Res), Arrays.asList(arr1)); assertEquals(Arrays.asList(arr2Res), Arrays.asList(arr2)); assertEquals(Arrays.asList(arr3Res), Arrays.asList(arr3)); assertEquals(Arrays.asList(arr4Res), Arrays.asList(arr4)); assertEquals(Arrays.asList(arr5Res), Arrays.asList(arr5)); } @Test public void test42() throws Exception { List<String> list1 = Arrays.asList(new String[] { "one", "two", "three" }); List<String> list2 = Arrays.asList(new String[] { "one", "two", "three", "four" }); List<String> list3 = Arrays.asList(new String[] { "one", "two" }); List<String> list4 = Arrays.asList(new String[] { "one" }); List<String> list5 = Arrays.asList(new String[] { }); List<String> list1Res = Arrays.asList(new String[] { "three", "two", "one" }); List<String> list2Res = Arrays.asList(new String[] { "four", "three", "two", "one" }); List<String> list3Res = Arrays.asList(new String[] { "two", "one" }); List<String> list4Res = Arrays.asList(new String[] { "one" }); List<String> list5Res = Arrays.asList(new String[] { }); list1 = Op.on(list1).reverse().get(); list2 = Op.on(list2).reverse().get(); list3 = Op.on(list3).reverse().get(); list4 = Op.on(list4).reverse().get(); list5 = Op.on(list5).reverse().get(); assertEquals(list1Res, list1); assertEquals(list2Res, list2); assertEquals(list3Res, list3); assertEquals(list4Res, list4); assertEquals(list5Res, list5); } @Test public void test43() throws Exception { Set<String> set1 = new LinkedHashSet<String>(Arrays.asList(new String[] { "one", "two", "three" })); Set<String> set2 = new LinkedHashSet<String>(Arrays.asList(new String[] { "one", "two", "three", "four" })); Set<String> set3 = new LinkedHashSet<String>(Arrays.asList(new String[] { "one", "two" })); Set<String> set4 = new LinkedHashSet<String>(Arrays.asList(new String[] { "one" })); Set<String> set5 = new LinkedHashSet<String>(Arrays.asList(new String[] { })); Set<String> set1Res = new LinkedHashSet<String>(Arrays.asList(new String[] { "three", "two", "one" })); Set<String> set2Res = new LinkedHashSet<String>(Arrays.asList(new String[] { "four", "three", "two", "one" })); Set<String> set3Res = new LinkedHashSet<String>(Arrays.asList(new String[] { "two", "one" })); Set<String> set4Res = new LinkedHashSet<String>(Arrays.asList(new String[] { "one" })); Set<String> set5Res = new LinkedHashSet<String>(Arrays.asList(new String[] { })); set1 = Op.on(set1).reverse().get(); set2 = Op.on(set2).reverse().get(); set3 = Op.on(set3).reverse().get(); set4 = Op.on(set4).reverse().get(); set5 = Op.on(set5).reverse().get(); assertEquals(set1Res, set1); assertEquals(set2Res, set2); assertEquals(set3Res, set3); assertEquals(set4Res, set4); assertEquals(set5Res, set5); } @Test public void test44() throws Exception { Map<Integer, String> map0 = new LinkedHashMap<Integer, String>(); Map<Integer, String> map1 = new LinkedHashMap<Integer, String>(map0); map1.put(1, "one"); Map<Integer, String> map2 = new LinkedHashMap<Integer, String>(map1); map2.put(2, "two"); Map<Integer, String> map3 = new LinkedHashMap<Integer, String>(map2); map3.put(3, "three"); Map<Integer, String> map4 = new LinkedHashMap<Integer, String>(map3); map4.put(4, "four"); Map<Integer, String> map0Res = new LinkedHashMap<Integer, String>(); Map<Integer, String> map1Res = new LinkedHashMap<Integer, String>(); map1Res.put(1, "one"); Map<Integer, String> map2Res = new LinkedHashMap<Integer, String>(); map2Res.put(2, "two"); map2Res.put(1, "one"); Map<Integer, String> map3Res = new LinkedHashMap<Integer, String>(); map3Res.put(3, "three"); map3Res.put(2, "two"); map3Res.put(1, "one"); Map<Integer, String> map4Res = new LinkedHashMap<Integer, String>(); map4Res.put(4, "four"); map4Res.put(3, "three"); map4Res.put(2, "two"); map4Res.put(1, "one"); map0 = Op.on(map0).reverse().get(); map1 = Op.on(map1).reverse().get(); map2 = Op.on(map2).reverse().get(); map3 = Op.on(map3).reverse().get(); map4 = Op.on(map4).reverse().get(); assertEquals(map0Res, map0); assertEquals(map1Res, map1); assertEquals(map2Res, map2); assertEquals(map3Res, map3); assertEquals(map4Res, map4); } @Test public void test45() throws Exception { List<Boolean> result = Op.onListFor(BigDecimal.valueOf(34), Double.valueOf(34), BigDecimal.valueOf(34).setScale(4)) .forEach().exec(FnNumber.eqValue(BigDecimal.valueOf(34))).get(); assertTrue("BigDecimal.valueOf(34) equals to BigDecimal.valueOf(34)", result.get(0)); assertTrue("Double.valueOf(34) equals to BigDecimal.valueOf(34)", result.get(1)); assertTrue("BigDecimal.valueOf(34).setScale(4) equals to BigDecimal.valueOf(34)", result.get(2)); } @Test public void test46() throws Exception { List<Boolean> result = Op.onListFor(BigDecimal.valueOf(34), Double.valueOf(34), BigDecimal.valueOf(34).setScale(4)) .forEach().exec(FnNumber.notEqValue(BigDecimal.valueOf(34))).get(); assertFalse("BigDecimal.valueOf(34) notequals to BigDecimal.valueOf(34)", result.get(0)); assertFalse("Double.valueOf(34) notequals to BigDecimal.valueOf(34)", result.get(1)); assertFalse("BigDecimal.valueOf(34).setScale(4) notequals to BigDecimal.valueOf(34)", result.get(2)); } @Test public void test47() throws Exception { Boolean result = Op.on(Types.BIG_DECIMAL, null) .exec(FnNumber.notEq(null)).get(); assertFalse("null notequals to null", result); result = Op.on(Types.BIG_DECIMAL, null) .exec(FnNumber.eq(null)).get(); assertTrue("null equals to null", result); } @Test public void test48() throws Exception { Boolean result = Op.on(Types.BIG_DECIMAL, null) .exec(FnBigDecimal.notEq(null)).get(); assertFalse("null notequals to null", result); result = Op.on(Types.BIG_DECIMAL, null) .exec(FnBigDecimal.eq(null)).get(); assertTrue("null equals to null", result); } @Test public void test49() throws Exception { List<Boolean> result = Op.onListFor(BigDecimal.valueOf(34), BigDecimal.valueOf(34).setScale(10), BigDecimal.valueOf(34).setScale(4)) .forEach().exec(FnBigDecimal.eqValue(BigDecimal.valueOf(34))).get(); assertTrue("BigDecimal.valueOf(34) equals to BigDecimal.valueOf(34)", result.get(0)); assertTrue("BigDecimal.valueOf(34).setScale(10) equals to BigDecimal.valueOf(34)", result.get(1)); assertTrue("BigDecimal.valueOf(34).setScale(4) equals to BigDecimal.valueOf(34)", result.get(2)); } @Test public void test50() throws Exception { List<Boolean> result = Op.onListFor(BigDecimal.valueOf(34), BigDecimal.valueOf(34).setScale(10), BigDecimal.valueOf(34).setScale(4)) .forEach().exec(FnBigDecimal.notEqValue(BigDecimal.valueOf(34))).get(); assertFalse("BigDecimal.valueOf(34) notequals to BigDecimal.valueOf(34)", result.get(0)); assertFalse("BigDecimal.valueOf(34).setScale(10) notequals to BigDecimal.valueOf(34)", result.get(1)); assertFalse("BigDecimal.valueOf(34).setScale(4) notequals to BigDecimal.valueOf(34)", result.get(2)); } @Test public void test51() throws Exception { Boolean result = Op.on(Types.DOUBLE, null) .exec(FnDouble.notEq(null)).get(); assertFalse("null notequals to null", result); result = Op.on(Types.DOUBLE, null) .exec(FnDouble.eq(null)).get(); assertTrue("null equals to null", result); } @Test public void test52() throws Exception { List<Boolean> result = Op.onListFor(Double.valueOf(34), null) .forEach().exec(FnDouble.notEq(Double.valueOf(34))).get(); assertFalse("Double.valueOf(34) notequals to Double.valueOf(34)", result.get(0)); assertTrue("null notequals to Double.valueOf(34)", result.get(1)); Function<Double,Boolean> fn = FnBoolean.or(FnNumber.isNull(), FnDouble.isNull()); Op.on(13434d).exec(fn).get(); Op.on(13434d).exec(FnBoolean.or(FnNumber.isNull(), FnDouble.isNull())).get(); Function<Double,Boolean> fn1 = FnBoolean.or(FnDouble.isNull(), FnNumber.isNull()); Op.on(13434d).exec(fn1).get(); Op.on(13434d).exec(FnBoolean.or(FnDouble.isNull(), FnNumber.isNull())).get(); } @Test public void test53() throws Exception { assertTrue("Op.on(Double.valueOf(4)).exec(FnNumber.eqValue(4))", Op.on(Double.valueOf(4)) .exec(FnNumber.eqValue(4)).get()); assertTrue("Op.on(Double.valueOf(4)).exec(FnNumber.notEq(null))", Op.on(Double.valueOf(4)) .exec(FnNumber.notEq(null)).get()); assertTrue("Op.on(Double.valueOf(4)).exec(FnNumber.eqValue(BigDecimal.valueOf(4).setScale(6)))", Op.on(Double.valueOf(4)).exec(FnNumber.eqValue(BigDecimal.valueOf(4).setScale(6))).get()); assertFalse("Op.on(Double.valueOf(4)).exec(FnNumber.notEqValue(BigDecimal.valueOf(4).setScale(6)))", Op.on(Double.valueOf(4)).exec(FnNumber.notEqValue(BigDecimal.valueOf(4).setScale(6))).get()); assertFalse("Op.on(BigDecimal.valueOf(4)).exec(FnNumber.notEqValue(BigDecimal.valueOf(4).setScale(6)))", Op.on(BigDecimal.valueOf(4)).exec(FnNumber.notEqValue(BigDecimal.valueOf(4).setScale(6))).get()); assertFalse("Op.on(Integer.valueOf(4)).exec(FnNumber.notEqValue(BigDecimal.valueOf(4).setScale(6)))", Op.on(Integer.valueOf(4)).exec(FnNumber.notEqValue(BigDecimal.valueOf(4).setScale(6))).get()); assertTrue("Op.on(Integer.valueOf(4)).exec(FnNumber.eqValue(BigDecimal.valueOf(4).setScale(6)))", Op.on(Integer.valueOf(4)).exec(FnNumber.eqValue(BigDecimal.valueOf(4).setScale(6))).get()); assertTrue("Op.on(Integer.valueOf(4)).exec(FnNumber.notEqValue(BigDecimal.valueOf(4).setScale(6)))", Op.on(Double.valueOf(4.1)).exec(FnNumber.notEqValue(BigDecimal.valueOf(4).setScale(6))).get()); assertTrue("Op.on(Integer.valueOf(4)).exec(FnNumber.notEqValue(BigDecimal.valueOf(4.1).setScale(6)))", Op.on(Double.valueOf(4)).exec(FnNumber.notEqValue(BigDecimal.valueOf(4.1).setScale(6))).get()); assertTrue("Op.on(Short.valueOf((short)4)).exec(FnNumber.eqValue(BigDecimal.valueOf(4).setScale(6)))", Op.on(Short.valueOf((short)4)).exec(FnNumber.eqValue(BigDecimal.valueOf(4).setScale(6))).get()); assertFalse("Op.on(Long.valueOf(4)).exec(FnNumber.notEqValue(BigDecimal.valueOf(4).setScale(6)))", Op.on(Long.valueOf(4)).exec(FnNumber.notEqValue(BigDecimal.valueOf(4).setScale(6))).get()); assertTrue("Op.on(Double.valueOf(4)).exec(FnNumber.eq(4))", Op.on(Double.valueOf(4)) .exec(FnNumber.eq((double)4)).get()); assertFalse("Op.on(Double.valueOf(4)).exec(FnNumber.eq(Integer.valueOf(4)))", Op.on(Double.valueOf(4)) .exec(FnNumber.eq(Integer.valueOf(4))).get()); assertFalse("Op.on(Double.valueOf(4)).exec(FnNumber.eq(BigDecimal.valueOf(4).setScale(6)))", Op.on(Double.valueOf(4)) .exec(FnNumber.eq(BigDecimal.valueOf(4).setScale(6))).get()); assertTrue("Op.on(BigDecimal.valueOf(4)).exec(FnNumber.notEq(BigDecimal.valueOf(4).setScale(6)))", Op.on(BigDecimal.valueOf(4)).exec(FnNumber.notEq(BigDecimal.valueOf(4).setScale(6))).get()); } @Test public void test54() throws Exception { assertEquals( Op.on(new Object[] {4.5, "hello", BigDecimal.valueOf(45.78)}) .exec(FnString.joinArray(",")).get(), "4.5,hello,45.78"); assertEquals( Op.on(new Object[] {4.5, "hello", BigDecimal.valueOf(45.78)}) .exec(FnString.joinArray("*")).get(), "4.5*hello*45.78"); assertEquals(Op.on("Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday") .exec(FnString.split(",")).castToListOf(Types.STRING).forEach().exec(FnString.trim()).get(), Op.onListFor("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday").get()); } @Test public void test55() throws Exception { Calendar cal1 = Calendar.getInstance(); assertEquals( Op.on(new Object[] {4.5, "hello", cal1}) .exec(FnString.joinArray(",")).get(), "4.5,hello," + cal1.toString()); assertEquals( Op.on(new Object[] {4.5, "hello", cal1}) .exec(FnString.joinArray()).get(), "4.5hello" + cal1.toString()); assertEquals( Op.on("hello*goodbye") .exec(FnString.splitAsArray("*")).castToArrayOf(Types.STRING).toList().get(), Op.onArrayFor("hello", "goodbye").toList().get()); assertNull( Op.on(Types.ARRAY_OF_STRING, null) .exec(FnString.joinArray(",")).get()); assertNull( Op.on(Types.STRING, null) .exec(FnString.split()).get()); } @Test public void test56() throws Exception { final String testStr1 = "\u00DF\u00DF \u00DF\u00DF a \u00DF\u00DF nu\u00DF NU\u00DF nu\u00DF\u00DF NU\u00DF\u00DF \u00DF\u00DF"; final String testStr2 = "\u00DF\u00DF"; final String testStr3 = "LO E \u00C7\u00C0 I\u00D1\u00C6 N\u00DC\u00DF \u00DEOR! a\u00F1e\u00E7\u00E1\u00ED\u00E9\u00F3\u00FA \u00E4\u00EB\u00EF\u00F6\u00FC\u00C4\u00CB\u00CF\u00D6\u00DC"; final String testStr4 = "LO E \u00C7\u00C0 I\u00D1\u00C6 N\u00DC\u00DF\u00DF"; final String testStr5 = "LO E \u00C7\u00C0 I\u00D1\u00C6 N\u00DC\u00DF\u00DF "; final String testStr6 = "LO E \u00C7\u00C0 I\u00D1\u00C6 N\u00DC\u00DF\u00DF \u00DF"; final String testStr7 = "LO E \u00C7\u00C0 I\u00D1\u00C6 Nu\u00DF\u00DF \u00DF"; final String testStr8 = "LO E \u00C7\u00C0 I\u00D1\u00C6 N\u00DC\u00DF\u00DF a"; final String testStr9 = "M\u00DCNCHEN"; final String testStr10 = "M\u00DCNCHEN \u00E4\u00EB\u00EF\u00F6\u00FC\u00C4\u00CB\u00CF\u00D6\u00DC"; assertEquals("SSSS SSSS a ssss nuss NUSS nussss NUSSSS SSSS", Op.on(testStr1).exec(FnString.asciify()).get()); assertEquals("SSSS", Op.on(testStr2).exec(FnString.asciify()).get()); assertEquals("LO E CA INAE NUSS THOR! anecaieou aeiouAEIOU", Op.on(testStr3).exec(FnString.asciify()).get()); assertEquals("LO E CA INAE NUSSSS", Op.on(testStr4).exec(FnString.asciify()).get()); assertEquals("LO E CA INAE NUSSSS ", Op.on(testStr5).exec(FnString.asciify()).get()); assertEquals("LO E CA INAE NUSSSS SS", Op.on(testStr6).exec(FnString.asciify()).get()); assertEquals("LO E CA INAE Nussss ss", Op.on(testStr7).exec(FnString.asciify()).get()); assertEquals("LO E CA INAE NUSSSS a", Op.on(testStr8).exec(FnString.asciify()).get()); assertEquals("MUENCHEN", Op.on(testStr9).exec(FnString.asciify(AsciifyMode.UMLAUT_E)).get()); assertEquals("MUENCHEN aeeioeueAEEIOEUE", Op.on(testStr10).exec(FnString.asciify(AsciifyMode.UMLAUT_E)).get()); } @Test public void test57() throws Exception { Short b = Short.valueOf((short)10); Short c = Short.valueOf((short)-3); assertEquals(Op.on(c).exec(FnShort.module(b.intValue())).get(), Short.valueOf(BigInteger.valueOf(c.longValue()) .mod(BigInteger.valueOf(b.longValue())).shortValue())); assertEquals(Op.on(c).exec(FnShort.remainder(b.intValue())).get(), Short.valueOf(BigInteger.valueOf(c.longValue()) .remainder(BigInteger.valueOf(b.longValue())).shortValue())); assertNotSame(Op.on(c).exec(FnShort.remainder(b.intValue())).get(), Short.valueOf(BigInteger.valueOf(c.longValue()) .mod(BigInteger.valueOf(b.longValue())).shortValue())); } @Test public void test58() throws Exception { Long b = Long.valueOf(56756710); Long c = Long.valueOf(-38799); assertEquals(Op.on(c).exec(FnLong.module(b.intValue())).get(), Long.valueOf(BigInteger.valueOf(c.longValue()) .mod(BigInteger.valueOf(b.longValue())).longValue())); assertEquals(Op.on(c).exec(FnLong.remainder(b.intValue())).get(), Long.valueOf(BigInteger.valueOf(c.longValue()) .remainder(BigInteger.valueOf(b.longValue())).longValue())); assertNotSame(Op.on(c).exec(FnLong.remainder(b.intValue())).get(), Long.valueOf(BigInteger.valueOf(c.longValue()) .mod(BigInteger.valueOf(b.longValue())).longValue())); } @Test public void test59() throws Exception { Integer b = Integer.valueOf(56756710); Integer c = Integer.valueOf(-38799); assertEquals(Op.on(c).exec(FnInteger.module(b.intValue())).get(), Integer.valueOf(BigInteger.valueOf(c.longValue()) .mod(BigInteger.valueOf(b.longValue())).intValue())); assertEquals(Op.on(c).exec(FnInteger.remainder(b.intValue())).get(), Integer.valueOf(BigInteger.valueOf(c.longValue()) .remainder(BigInteger.valueOf(b.longValue())).intValue())); assertNotSame(Op.on(c).exec(FnInteger.remainder(b.intValue())).get(), Integer.valueOf(BigInteger.valueOf(c.longValue()) .mod(BigInteger.valueOf(b.longValue())).intValue())); } }
package org.nd4j.nativeblas; import java.util.List; import org.bytedeco.javacpp.ClassProperties; import org.bytedeco.javacpp.LoadEnabled; import org.bytedeco.javacpp.Loader; import org.bytedeco.javacpp.annotation.Platform; import org.bytedeco.javacpp.annotation.Properties; import org.bytedeco.javacpp.tools.Info; import org.bytedeco.javacpp.tools.InfoMap; import org.bytedeco.javacpp.tools.InfoMapper; /** * * @author saudet */ @Properties(target = "org.nd4j.nativeblas.Nd4jCuda", helper = "org.nd4j.nativeblas.Nd4jCudaHelper", value = {@Platform(define = "LIBND4J_ALL_OPS", include = { "array/DataType.h", "array/DataBuffer.h", "array/PointerDeallocator.h", "array/PointerWrapper.h", "array/ConstantDescriptor.h", "array/ConstantDataBuffer.h", "array/ConstantShapeBuffer.h", "array/ConstantOffsetsBuffer.h", "array/TadPack.h", "execution/ErrorReference.h", "execution/Engine.h", "execution/ExecutionMode.h", "memory/MemoryType.h", "system/Environment.h", "types/utf8string.h", "legacy/NativeOps.h", "memory/ExternalWorkspace.h", "memory/Workspace.h", "indexing/NDIndex.h", "indexing/IndicesList.h", "array/DataType.h", "graph/VariableType.h", "graph/ArgumentsList.h", "types/pair.h", "types/pair.h", "array/NDArray.h", "array/NDArrayList.h", "array/ResultSet.h", "graph/RandomGenerator.h", "graph/Variable.h", "graph/VariablesSet.h", "graph/FlowPath.h", "graph/Intervals.h", "graph/Stash.h", "graph/GraphState.h", "graph/VariableSpace.h", "helpers/helper_generator.h", "graph/profiling/GraphProfile.h", "graph/profiling/NodeProfile.h", "graph/Context.h", "graph/ContextPrototype.h", "graph/ResultWrapper.h", "helpers/shape.h", "array/ShapeList.h", //"system/op_boilerplate.h", "ops/InputType.h", "ops/declarable/OpDescriptor.h", "ops/declarable/PlatformHelper.h", "ops/declarable/BroadcastableOp.h", "ops/declarable/BroadcastableBoolOp.h", "helpers/OpArgsHolder.h", "ops/declarable/DeclarableOp.h", "ops/declarable/DeclarableListOp.h", "ops/declarable/DeclarableReductionOp.h", "ops/declarable/DeclarableCustomOp.h", "ops/declarable/BooleanOp.h", "ops/declarable/LogicOp.h", "ops/declarable/OpRegistrator.h", "execution/ContextBuffers.h", "execution/LaunchContext.h", "array/ShapeDescriptor.h", "array/TadDescriptor.h", "array/TadPack.h", "helpers/DebugInfo.h", "ops/declarable/CustomOperations.h", "build_info.h", }, exclude = {"ops/declarable/headers/activations.h", "ops/declarable/headers/boolean.h", "ops/declarable/headers/broadcastable.h", "ops/declarable/headers/convo.h", "ops/declarable/headers/list.h", "ops/declarable/headers/recurrent.h", "ops/declarable/headers/transforms.h", "ops/declarable/headers/parity_ops.h", "ops/declarable/headers/shape.h", "ops/declarable/headers/random.h", "ops/declarable/headers/nn.h", "ops/declarable/headers/blas.h", "ops/declarable/headers/bitwise.h", "ops/declarable/headers/tests.h", "ops/declarable/headers/loss.h", "ops/declarable/headers/datatypes.h", "ops/declarable/headers/third_party.h", "cnpy/cnpy.h" }, compiler = {"cpp11", "nowarnings"}, library = "jnind4jcuda", link = "nd4jcuda", preload = "libnd4jcuda"), @Platform(value = "linux", preload = "gomp@.1", preloadpath = {"/lib64/", "/lib/", "/usr/lib64/", "/usr/lib/"}), @Platform(value = "linux-armhf", preloadpath = {"/usr/arm-linux-gnueabihf/lib/", "/usr/lib/arm-linux-gnueabihf/"}), @Platform(value = "linux-arm64", preloadpath = {"/usr/aarch64-linux-gnu/lib/", "/usr/lib/aarch64-linux-gnu/"}), @Platform(value = "linux-ppc64", preloadpath = {"/usr/powerpc64-linux-gnu/lib/", "/usr/powerpc64le-linux-gnu/lib/", "/usr/lib/powerpc64-linux-gnu/", "/usr/lib/powerpc64le-linux-gnu/"}), @Platform(value = "windows", preload = {"libwinpthread-1", "libgcc_s_seh-1", "libgomp-1", "libstdc++-6", "libnd4jcpu"}) }) public class Nd4jCudaPresets implements LoadEnabled, InfoMapper { @Override public void init(ClassProperties properties) { String platform = properties.getProperty("platform"); List<String> preloads = properties.get("platform.preload"); List<String> resources = properties.get("platform.preloadresource"); // Only apply this at load time since we don't want to copy the CUDA libraries here if (!Loader.isLoadLibraries()) { return; } int i = 0; String[] libs = {"cudart", "cublasLt", "cublas", "curand", "cusolver", "cusparse", "cudnn", "cudnn_ops_infer", "cudnn_ops_train", "cudnn_adv_infer", "cudnn_adv_train", "cudnn_cnn_infer", "cudnn_cnn_train"}; for (String lib : libs) { if (platform.startsWith("linux")) { lib += lib.startsWith("cudnn") ? "@.8" : lib.equals("curand") ? "@.10" : lib.equals("cudart") ? "@.11.0" : "@.11"; } else if (platform.startsWith("windows")) { lib += lib.startsWith("cudnn") ? "64_8" : lib.equals("curand") ? "64_10" : lib.equals("cudart") ? "64_110" : "64_11"; } else { continue; // no CUDA } if (!preloads.contains(lib)) { preloads.add(i++, lib); } } if (i > 0) { resources.add("/org/bytedeco/cuda/"); } } @Override public void map(InfoMap infoMap) { infoMap.put(new Info("thread_local", "ND4J_EXPORT", "INLINEDEF", "CUBLASWINAPI", "FORCEINLINE", "_CUDA_H", "_CUDA_D", "_CUDA_G", "_CUDA_HD", "LIBND4J_ALL_OPS", "NOT_EXCLUDED").cppTypes().annotations()) .put(new Info("NativeOps.h", "build_info.h").objectify()) .put(new Info("OpaqueTadPack").pointerTypes("OpaqueTadPack")) .put(new Info("OpaqueResultWrapper").pointerTypes("OpaqueResultWrapper")) .put(new Info("OpaqueShapeList").pointerTypes("OpaqueShapeList")) .put(new Info("OpaqueVariablesSet").pointerTypes("OpaqueVariablesSet")) .put(new Info("OpaqueVariable").pointerTypes("OpaqueVariable")) .put(new Info("OpaqueConstantDataBuffer").pointerTypes("OpaqueConstantDataBuffer")) .put(new Info("OpaqueConstantShapeBuffer").pointerTypes("OpaqueConstantShapeBuffer")) .put(new Info("OpaqueConstantOffsetsBuffer").pointerTypes("OpaqueConstantOffsetsBuffer")) .put(new Info("OpaqueContext").pointerTypes("OpaqueContext")) .put(new Info("OpaqueRandomGenerator").pointerTypes("OpaqueRandomGenerator")) .put(new Info("OpaqueLaunchContext").pointerTypes("OpaqueLaunchContext")) .put(new Info("OpaqueDataBuffer").pointerTypes("OpaqueDataBuffer")) .put(new Info("const char").valueTypes("byte").pointerTypes("@Cast(\"char*\") String", "@Cast(\"char*\") BytePointer")) .put(new Info("char").valueTypes("char").pointerTypes("@Cast(\"char*\") BytePointer", "@Cast(\"char*\") String")) .put(new Info("Nd4jPointer").cast().valueTypes("Pointer").pointerTypes("PointerPointer")) .put(new Info("Nd4jLong").cast().valueTypes("long").pointerTypes("LongPointer", "LongBuffer", "long[]")) .put(new Info("Nd4jStatus").cast().valueTypes("int").pointerTypes("IntPointer", "IntBuffer", "int[]")) .put(new Info("float16").cast().valueTypes("short").pointerTypes("ShortPointer", "ShortBuffer", "short[]")) .put(new Info("bfloat16").cast().valueTypes("short").pointerTypes("ShortPointer", "ShortBuffer", "short[]")); infoMap.put(new Info("__CUDACC__", "MAX_UINT", "HAVE_MKLDNN").define(false)) .put(new Info("__JAVACPP_HACK__", "LIBND4J_ALL_OPS","__CUDABLAS__").define(true)) .put(new Info("std::initializer_list", "cnpy::NpyArray", "sd::NDArray::applyLambda", "sd::NDArray::applyPairwiseLambda", "sd::graph::FlatResult", "sd::graph::FlatVariable", "sd::NDArray::subarray", "std::shared_ptr", "sd::PointerWrapper", "sd::PointerDeallocator").skip()) .put(new Info("std::string").annotations("@StdString").valueTypes("BytePointer", "String") .pointerTypes("@Cast({\"char*\", \"std::string*\"}) BytePointer")) .put(new Info("std::pair<int,int>").pointerTypes("IntIntPair").define()) .put(new Info("std::vector<std::vector<int> >").pointerTypes("IntVectorVector").define()) .put(new Info("std::vector<std::vector<Nd4jLong> >").pointerTypes("LongVectorVector").define()) .put(new Info("std::vector<sd::NDArray*>").pointerTypes("NDArrayVector").define()) .put(new Info("std::vector<const sd::NDArray*>").pointerTypes("ConstNDArrayVector").define()) .put(new Info("bool").cast().valueTypes("boolean").pointerTypes("BooleanPointer", "boolean[]")) .put(new Info("sd::graph::ResultWrapper").base("org.nd4j.nativeblas.ResultWrapperAbstraction").define()) .put(new Info("sd::IndicesList").purify()); /* String classTemplates[] = { "sd::NDArray", "sd::NDArrayList", "sd::ResultSet", "sd::OpArgsHolder", "sd::graph::GraphState", "sd::graph::Variable", "sd::graph::VariablesSet", "sd::graph::Stash", "sd::graph::VariableSpace", "sd::graph::Context", "sd::graph::ContextPrototype", "sd::ops::DeclarableOp", "sd::ops::DeclarableListOp", "sd::ops::DeclarableReductionOp", "sd::ops::DeclarableCustomOp", "sd::ops::BooleanOp", "sd::ops::BroadcastableOp", "sd::ops::LogicOp"}; for (String t : classTemplates) { String s = t.substring(t.lastIndexOf(':') + 1); infoMap.put(new Info(t + "<float>").pointerTypes("Float" + s)) .put(new Info(t + "<float16>").pointerTypes("Half" + s)) .put(new Info(t + "<double>").pointerTypes("Double" + s)); } */ infoMap.put(new Info("sd::ops::OpRegistrator::updateMSVC").skip()); } }
/* Equips is a java class that makes */ import java.util.ArrayList; public class Equips { public static final String[] equip_desc = {"Savage", "Smart","Forntunate","Fast"} public static final String[] equip_type = {"Power", "Intelligence", "Luck", "Speed"}; public static final String[] typeList = {"Helm", "Armor", "Boots", "Amulet", "Ring"}; private int[] effects = new int[4]; private String name; private String type; private int strength = 0; private int intelligence = 0; private int dexterity = 0; private int luck = 0; private int level; public Equip(int level) { this.level = level; type = typeList[(int)(Math.random(4))]; int num = (int)(Math.random(3)); addStat(num,level); name = equip_desc[num] + " " + type + " of "; num = (int)(Math.random(3)); addStat(num,level); name += equip_type[num]; } public void addStat(int input, int level) { if (input == 0) { strength += 2*level; } if (input == 1) { intelligence += 2 * level; } if (input == 2) { luck += 2 * level; } else dexterity += 2 * level; } }
package nl.tudelft.ewi.dea.jaxrs.account; import static com.google.common.base.Preconditions.checkArgument; import static org.apache.commons.lang3.StringUtils.isNotEmpty; import java.net.URI; import javax.inject.Inject; import javax.inject.Provider; import javax.inject.Singleton; import javax.persistence.NoResultException; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import nl.tudelft.ewi.dea.dao.RegistrationTokenDao; import nl.tudelft.ewi.dea.jaxrs.utils.Renderer; import nl.tudelft.ewi.dea.model.RegistrationToken; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Lists; @Singleton @Path("account") public class AccountResource { private static final Logger LOG = LoggerFactory.getLogger(AccountResource.class); private final Provider<Renderer> renderers; private final RegistrationTokenDao registrationTokenDao; @Inject public AccountResource(final Provider<Renderer> renderers, final RegistrationTokenDao registrationTokenDao) { this.renderers = renderers; this.registrationTokenDao = registrationTokenDao; } @GET @Path("activate/{token}") @Produces(MediaType.TEXT_HTML) public String servePage(@PathParam("token") final String token) { LOG.trace("Serving activation page for token: {}", token); checkArgument(isNotEmpty(token)); final RegistrationToken registrationToken; try { registrationToken = registrationTokenDao.findByToken(token); } catch (final NoResultException e) { LOG.trace("Token not found in database, so not active: {}", token, e); // TODO: Handle missing token. } // TODO: Render page with account input form. return renderers.get() .setValue("scripts", Lists.newArrayList("activate.js")) .render("activate.tpl"); } @POST @Path("activate/{token}") @Consumes(MediaType.APPLICATION_JSON) public Response processActivation(@PathParam("token") final String token, final ActivationRequest request) { // TODO: check if token is still valid, and account doesn't exist yet. // TODO: delete token from database, and create account from request (in // single transaction). // TODO: automatically log user in, and send a confirmation email. final long accountId = 0; return Response.seeOther(URI.create("/account/" + accountId)).build(); } @GET @Path("email/{email}") @Produces(MediaType.APPLICATION_JSON) public Response findByEmail(@PathParam("email") final String email) { // TODO: Return a list of users with a matching email address. return Response.serverError().build(); } @POST @Path("{id}/promote") public Response promoteUserToTeacher(@PathParam("id") final long id) { // TODO: Promote user to teacher status. return Response.serverError().build(); } }
package io.digdag.standards.command; import java.util.List; import java.util.Set; import java.util.HashSet; import java.util.Map; import java.util.UUID; import java.util.regex.Pattern; import java.util.regex.Matcher; import java.util.stream.Collectors; import java.io.File; import java.io.OutputStreamWriter; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.BufferedWriter; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.Files; import com.google.inject.Inject; import com.google.common.base.Optional; import com.google.common.base.Throwables; import com.google.common.hash.Hashing; import com.google.common.collect.ImmutableList; import com.google.common.io.ByteStreams; import io.digdag.spi.CommandExecutor; import io.digdag.spi.TaskRequest; import io.digdag.client.config.Config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static java.util.Locale.ENGLISH; import static java.nio.charset.StandardCharsets.UTF_8; public class DockerCommandExecutor implements CommandExecutor { private final SimpleCommandExecutor simple; private static Logger logger = LoggerFactory.getLogger(DockerCommandExecutor.class); @Inject public DockerCommandExecutor(SimpleCommandExecutor simple) { this.simple = simple; } public Process start(Path projectPath, TaskRequest request, ProcessBuilder pb) throws IOException { // TODO set TZ environment variable Config config = request.getConfig(); if (config.has("docker")) { return startWithDocker(projectPath, request, pb); } else { return simple.start(projectPath.toAbsolutePath(), request, pb); } } private Process startWithDocker(Path projectPath, TaskRequest request, ProcessBuilder pb) { Config dockerConfig = request.getConfig().getNestedOrGetEmpty("docker"); String baseImageName = dockerConfig.get("image", String.class); String imageName; if (dockerConfig.has("build")) { List<String> buildCommands = dockerConfig.getList("build", String.class); imageName = uniqueImageName(request, baseImageName, buildCommands); buildImage(imageName, projectPath, baseImageName, buildCommands); } else { imageName = baseImageName; } ImmutableList.Builder<String> command = ImmutableList.builder(); command.add("docker").add("run"); try { // misc command.add("-i"); // enable stdin command.add("--rm"); // remove container when exits // mount command.add("-v").add(String.format(ENGLISH, "%s:%s:rw", projectPath, projectPath)); // use projectPath to keep pb.directory() valid // workdir Path workdir = (pb.directory() == null) ? Paths.get("") : pb.directory().toPath(); command.add("-w").add(workdir.normalize().toAbsolutePath().toString()); logger.debug("Running in docker: {} {}", command.build().stream().collect(Collectors.joining(" ")), imageName); // env var // TODO deleting temp file right after start() causes "no such file or directory." error // because command execution is asynchronous. but using command-line is insecure. //Path envFile = Files.createTempFile("docker-env-", ".list"); //tempFiles.add(envFile); //try (BufferedWriter out = Files.newBufferedWriter(envFile)) { // for (Map.Entry<String, String> pair : pb.environment().entrySet()) { // out.write(pair.getKey()); // out.write("="); // out.write(pair.getValue()); // out.newLine(); //command.add("--env-file").add(envFile.toAbsolutePath().toString()); for (Map.Entry<String, String> pair : pb.environment().entrySet()) { command.add("-e").add(pair.getKey() + "=" + pair.getValue()); } // image name command.add(imageName); // command and args command.addAll(pb.command()); ProcessBuilder docker = new ProcessBuilder(command.build()); docker.redirectError(pb.redirectError()); docker.redirectErrorStream(pb.redirectErrorStream()); docker.redirectInput(pb.redirectInput()); docker.redirectOutput(pb.redirectOutput()); docker.directory(projectPath.toFile()); return docker.start(); } catch (IOException ex) { throw Throwables.propagate(ex); } } private static String uniqueImageName(TaskRequest request, String baseImageName, List<String> buildCommands) { // Name should include project "id" for security reason because // conflicting SHA1 hash means that attacker can reuse an image // built by someone else. String name = "digdag-project-" + Integer.toString(request.getProjectId()); Config config = request.getConfig().getFactory().create(); config.set("image", baseImageName); config.set("build", buildCommands); config.set("revision", request.getRevision().or(UUID.randomUUID().toString())); String tag = Hashing.sha1().hashString(config.toString(), UTF_8).toString(); return name + ':' + tag; } private void buildImage(String imageName, Path projectPath, String baseImageName, List<String> buildCommands) { try { String[] nameTag = imageName.split(":", 2); Pattern pattern; if (nameTag.length > 1) { pattern = Pattern.compile("\n" + Pattern.quote(nameTag[0]) + " +" + Pattern.quote(nameTag[1])); } else { pattern = Pattern.compile("\n" + Pattern.quote(imageName) + " "); } int ecode; String message; try (ByteArrayOutputStream buffer = new ByteArrayOutputStream()) { ProcessBuilder pb = new ProcessBuilder("docker", "images"); pb.redirectErrorStream(true); Process p = pb.start(); // read stdout to buffer try (InputStream stdout = p.getInputStream()) { ByteStreams.copy(stdout, buffer); } ecode = p.waitFor(); message = buffer.toString(); } Matcher m = pattern.matcher(message); if (m.find()) { // image is already available logger.debug("Reusing docker image {}", imageName); return; } } catch (IOException | InterruptedException ex) { throw new RuntimeException(ex); } logger.info("Building docker image {}", imageName); try { // create Dockerfile Path tmpPath = projectPath.resolve(".digdag/tmp/docker"); // TODO this should be configurable Files.createDirectories(tmpPath); Path dockerFilePath = tmpPath.resolve("Dockerfile." + imageName.replaceAll(":", ".")); try (BufferedWriter out = Files.newBufferedWriter(dockerFilePath)) { out.write("FROM "); out.write(baseImageName.replace("\n", "")); out.write("\n"); // Here shouldn't use 'ADD' because it spoils caching. Using the same base image // and build commands should share pre-build revisions. Using revision name // as the unique key is not good enough for local mode because revision name // is automatically generated based on execution time. for (String command : buildCommands) { for (String line : command.split("\n")) { out.write("RUN "); out.write(line); out.write("\n"); } } } ImmutableList.Builder<String> command = ImmutableList.builder(); command.add("docker").add("build"); command.add("-f").add(dockerFilePath.toString()); command.add("--force-rm"); command.add("-t").add(imageName); command.add(projectPath.toString()); ProcessBuilder docker = new ProcessBuilder(command.build()); docker.redirectError(ProcessBuilder.Redirect.INHERIT); docker.redirectOutput(ProcessBuilder.Redirect.INHERIT); docker.directory(projectPath.toFile()); Process p = docker.start(); int ecode = p.waitFor(); if (ecode != 0) { throw new RuntimeException("Docker build failed"); } } catch (IOException | InterruptedException ex) { throw new RuntimeException(ex); } } }
package org.folio.rest.tools.utils; import io.vertx.core.json.JsonObject; import java.util.Iterator; import java.util.Map; public enum Envs { INSTANCE; public static final String DB_HOST = "db.host"; public static final String DB_PORT = "db.port"; public static final String DB_USER = "db.username"; public static final String DB_PASSWORD = "db.password"; public static final String DB_DATABASE = "db.database"; public static final String DB_TIMEOUT = "db.queryTimeout"; public static final String DB_CHARSET = "db.charset"; public static final String DB_MAXPOOL = "db.maxPoolSize"; private static Map<String, String> envs = null; static { envs = System.getenv(); } public static String getEnv(String key){ return envs.get(key); } public static JsonObject allDBConfs(){ JsonObject obj = new JsonObject(); Iterator<Map.Entry<String, String>> iter = envs.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<String, String> entry = iter.next(); String key = entry.getKey(); if(key.startsWith("db.")){ String value = entry.getValue(); if(value != null){ if(key.equals(DB_PORT) || key.equals(DB_TIMEOUT) || key.equals(DB_MAXPOOL)){ obj.put(key.substring(3), Integer.valueOf(value).intValue()); } else { obj.put(key.substring(3), value); } } } } return obj; } }
// -*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: // @homepage@ package example; import java.awt.*; import java.awt.event.HierarchyEvent; import java.awt.font.FontRenderContext; import java.awt.font.TextLayout; import java.awt.geom.AffineTransform; import java.awt.geom.Rectangle2D; import javax.swing.*; public final class MainPanel extends JPanel { private MainPanel() { super(new BorderLayout()); add(new FontRotateAnimation("A")); setPreferredSize(new Dimension(320, 240)); } public static void main(String[] args) { EventQueue.invokeLater(MainPanel::createAndShowGui); } private static void createAndShowGui() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); Toolkit.getDefaultToolkit().beep(); } JFrame frame = new JFrame("@title@"); // frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } class FontRotateAnimation extends JComponent { private int rotate; private transient Shape shape; private final Timer animator = new Timer(10, null); protected FontRotateAnimation(String str) { super(); addHierarchyListener(e -> { if ((e.getChangeFlags() & HierarchyEvent.DISPLAYABILITY_CHANGED) != 0 && !e.getComponent().isDisplayable()) { animator.stop(); } }); Font font = new Font(Font.SERIF, Font.PLAIN, 200); FontRenderContext frc = new FontRenderContext(null, true, true); Shape outline = new TextLayout(str, font, frc).getOutline(null); shape = outline; animator.addActionListener(e -> { repaint(shape.getBounds()); // clear prev Rectangle2D b = outline.getBounds2D(); double ax = b.getCenterX(); double ay = b.getCenterY(); AffineTransform at = AffineTransform.getRotateInstance(Math.toRadians(rotate), ax, ay); double cx = getWidth() / 2d - ax; double cy = getHeight() / 2d - ay; AffineTransform toCenterAtf = AffineTransform.getTranslateInstance(cx, cy); Shape s1 = at.createTransformedShape(outline); shape = toCenterAtf.createTransformedShape(s1); repaint(shape.getBounds()); // rotate = rotate >= 360 ? 0 : rotate + 2; rotate = (rotate + 2) % 360; }); animator.start(); } @Override protected void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g.create(); // g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setPaint(Color.BLACK); g2.fill(shape); g2.dispose(); } }
package edu.wpi.first.wpilibj.networktables; import edu.wpi.first.wpilibj.tables.*; import java.io.File; import java.io.InputStream; import java.io.OutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; public class NetworkTablesJNI { static boolean libraryLoaded = false; static File jniLibrary = null; static { if (!libraryLoaded) { try { System.loadLibrary("ntcore"); } catch (UnsatisfiedLinkError e) { try { String osname = System.getProperty("os.name"); String resname; if (osname.startsWith("Windows")) resname = "/Windows/" + System.getProperty("os.arch") + "/"; else resname = "/" + osname + "/" + System.getProperty("os.arch") + "/"; System.out.println("platform: " + resname); if (osname.startsWith("Windows")) resname += "ntcore.dll"; else if (osname.startsWith("Mac")) resname += "libntcore.dylib"; else resname += "libntcore.so"; InputStream is = NetworkTablesJNI.class.getResourceAsStream(resname); if (is != null) { // create temporary file if (System.getProperty("os.name").startsWith("Windows")) jniLibrary = File.createTempFile("NetworkTablesJNI", ".dll"); else if (System.getProperty("os.name").startsWith("Mac")) jniLibrary = File.createTempFile("libNetworkTablesJNI", ".dylib"); else jniLibrary = File.createTempFile("libNetworkTablesJNI", ".so"); // flag for delete on exit jniLibrary.deleteOnExit(); OutputStream os = new FileOutputStream(jniLibrary); byte[] buffer = new byte[1024]; int readBytes; try { while ((readBytes = is.read(buffer)) != -1) { os.write(buffer, 0, readBytes); } } finally { os.close(); is.close(); } System.load(jniLibrary.getAbsolutePath()); } else { System.loadLibrary("ntcore"); } } catch (IOException ex) { ex.printStackTrace(); System.exit(1); } } libraryLoaded = true; } } public static native boolean containsKey(String key); public static native int getType(String key); public static native boolean putBoolean(String key, boolean value); public static native boolean putDouble(String key, double value); public static native boolean putString(String key, String value); public static native boolean putRaw(String key, byte[] value); public static native boolean putRaw(String key, ByteBuffer value, int len); public static native boolean putBooleanArray(String key, boolean[] value); public static native boolean putDoubleArray(String key, double[] value); public static native boolean putStringArray(String key, String[] value); public static native void forcePutBoolean(String key, boolean value); public static native void forcePutDouble(String key, double value); public static native void forcePutString(String key, String value); public static native void forcePutRaw(String key, byte[] value); public static native void forcePutRaw(String key, ByteBuffer value, int len); public static native void forcePutBooleanArray(String key, boolean[] value); public static native void forcePutDoubleArray(String key, double[] value); public static native void forcePutStringArray(String key, String[] value); public static native Object getValue(String key) throws TableKeyNotDefinedException; public static native boolean getBoolean(String key) throws TableKeyNotDefinedException; public static native double getDouble(String key) throws TableKeyNotDefinedException; public static native String getString(String key) throws TableKeyNotDefinedException; public static native byte[] getRaw(String key) throws TableKeyNotDefinedException; public static native boolean[] getBooleanArray(String key) throws TableKeyNotDefinedException; public static native double[] getDoubleArray(String key) throws TableKeyNotDefinedException; public static native String[] getStringArray(String key) throws TableKeyNotDefinedException; public static native Object getValue(String key, Object defaultValue); public static native boolean getBoolean(String key, boolean defaultValue); public static native double getDouble(String key, double defaultValue); public static native String getString(String key, String defaultValue); public static native byte[] getRaw(String key, byte[] defaultValue); public static native boolean[] getBooleanArray(String key, boolean[] defaultValue); public static native double[] getDoubleArray(String key, double[] defaultValue); public static native String[] getStringArray(String key, String[] defaultValue); public static native boolean setDefaultBoolean(String key, boolean defaultValue); public static native boolean setDefaultDouble(String key, double defaultValue); public static native boolean setDefaultString(String key, String defaultValue); public static native boolean setDefaultRaw(String key, byte[] defaultValue); public static native boolean setDefaultBooleanArray(String key, boolean[] defaultValue); public static native boolean setDefaultDoubleArray(String key, double[] defaultValue); public static native boolean setDefaultStringArray(String key, String[] defaultValue); public static native void setEntryFlags(String key, int flags); public static native int getEntryFlags(String key); public static native void deleteEntry(String key); public static native void deleteAllEntries(); public static native EntryInfo[] getEntries(String prefix, int types); public static native void flush(); public interface EntryListenerFunction { void apply(int uid, String key, Object value, int flags); } public static native int addEntryListener(String prefix, EntryListenerFunction listener, int flags); public static native void removeEntryListener(int entryListenerUid); public interface ConnectionListenerFunction { void apply(int uid, boolean connected, ConnectionInfo conn); } public static native int addConnectionListener(ConnectionListenerFunction listener, boolean immediateNotify); public static native void removeConnectionListener(int connListenerUid); // public static native void createRpc(String key, byte[] def, IRpc rpc); // public static native void createRpc(String key, ByteBuffer def, int def_len, IRpc rpc); public static native byte[] getRpc(String key) throws TableKeyNotDefinedException; public static native byte[] getRpc(String key, byte[] defaultValue); public static native int callRpc(String key, byte[] params); public static native int callRpc(String key, ByteBuffer params, int params_len); // public static native byte[] getRpcResultBlocking(int callUid); // public static native byte[] getRpcResultNonblocking(int callUid) throws RpcNoResponseException; public static native void setNetworkIdentity(String name); public static native void startServer(String persistFilename, String listenAddress, int port); public static native void stopServer(); public static native void startClient(String serverName, int port); public static native void startClient(String[] serverNames, int[] ports); public static native void stopClient(); public static native void setUpdateRate(double interval); public static native ConnectionInfo[] getConnections(); public static native void savePersistent(String filename) throws PersistentException; public static native String[] loadPersistent(String filename) throws PersistentException; // returns warnings public static native long now(); public interface LoggerFunction { void apply(int level, String file, int line, String msg); } public static native void setLogger(LoggerFunction func, int minLevel); }
package com.datatorrent.stram.plan.logical; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.*; import java.util.Map.Entry; import javax.validation.ValidationException; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.commons.beanutils.BeanMap; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; import org.apache.commons.lang3.StringUtils; import org.apache.hadoop.conf.Configuration; import com.datatorrent.api.*; import com.datatorrent.api.Attribute.AttributeMap.AttributeInitializer; import com.datatorrent.api.Context.OperatorContext; import com.datatorrent.api.Context.PortContext; import com.datatorrent.api.annotation.ApplicationAnnotation; import com.datatorrent.stram.StramUtils; import com.datatorrent.stram.client.StramClientUtils; import com.datatorrent.stram.plan.logical.LogicalPlan.InputPortMeta; import com.datatorrent.stram.plan.logical.LogicalPlan.OperatorMeta; import com.datatorrent.stram.plan.logical.LogicalPlan.OutputPortMeta; import com.datatorrent.stram.plan.logical.LogicalPlan.StreamMeta; import com.datatorrent.stram.util.ObjectMapperFactory; /** * * Builder for the DAG logical representation of operators and streams from properties.<p> * <br> * Supports reading as name-value pairs from Hadoop {@link Configuration} or opProps file. * <br> * * @since 0.3.2 */ public class LogicalPlanConfiguration { private static final Logger LOG = LoggerFactory.getLogger(LogicalPlanConfiguration.class); public static final String GATEWAY_PREFIX = StreamingApplication.DT_PREFIX + "gateway."; public static final String GATEWAY_LISTEN_ADDRESS_PROP = "listenAddress"; public static final String GATEWAY_LISTEN_ADDRESS = GATEWAY_PREFIX + GATEWAY_LISTEN_ADDRESS_PROP; public static final String GATEWAY_STATIC_RESOURCE_DIRECTORY = GATEWAY_PREFIX + "staticResourceDirectory"; public static final String GATEWAY_ALLOW_CROSS_ORIGIN = GATEWAY_PREFIX + "allowCrossOrigin"; public static final String STREAM_PREFIX = StreamingApplication.DT_PREFIX + "stream."; public static final String STREAM_SOURCE = "source"; public static final String STREAM_SINKS = "sinks"; public static final String STREAM_TEMPLATE = "template"; public static final String STREAM_LOCALITY = "locality"; public static final String OPERATOR_PREFIX = StreamingApplication.DT_PREFIX + "operator."; public static final String OPERATOR_CLASSNAME = "classname"; public static final String OPERATOR_TEMPLATE = "template"; public static final String TEMPLATE_idRegExp = "matchIdRegExp"; public static final String TEMPLATE_appNameRegExp = "matchAppNameRegExp"; public static final String TEMPLATE_classNameRegExp = "matchClassNameRegExp"; public static final String CLASS = "class"; private static final String CLASS_SUFFIX = "." + CLASS; private static final String WILDCARD = "*"; private static final String WILDCARD_PATTERN = ".*"; static { Object serial[] = new Object[] {Context.DAGContext.serialVersionUID, OperatorContext.serialVersionUID, PortContext.serialVersionUID}; LOG.debug("Initialized attributes {}", serial); } private enum StramElement { APPLICATION("application"), GATEWAY("gateway"), TEMPLATE("template"), OPERATOR("operator"),STREAM("stream"), PORT("port"), INPUT_PORT("inputport"),OUTPUT_PORT("outputport"), ATTR("attr"), PROP("prop"),CLASS("class"),PATH("path"); private final String value; StramElement(String value) { this.value = value; } public String getValue() { return value; } public static StramElement fromValue(String value) { StramElement velement = null; for (StramElement element : StramElement.values()) { if (element.getValue().equals(value)) { velement = element; break; } } return velement; } } public class JSONObject2String implements StringCodec<Object>, Serializable { private static final long serialVersionUID = -664977453308585878L; @Override public Object fromString(String jsonObj) { ObjectMapper mapper = ObjectMapperFactory.getOperatorValueDeserializer(); try { return mapper.readValue(jsonObj, Object.class); } catch (Exception e) { throw new RuntimeException("Error parsing json content", e); } } @Override public String toString(Object pojo) { ObjectMapper mapper = ObjectMapperFactory.getOperatorValueDeserializer(); try { return mapper.writeValueAsString(pojo); } catch (Exception e) { throw new RuntimeException("Error writing object as json", e); } } } private static abstract class Conf { protected Conf parentConf = null; protected final Map<Attribute<Object>, String> attributes = Maps.newHashMap(); protected final PropertiesWithModifiableDefaults properties = new PropertiesWithModifiableDefaults(); protected Map<StramElement, Map<String, ? extends Conf>> children = Maps.newHashMap(); protected String id; public void setId(String id) { this.id = id; } public String getId() { return id; } public void setParentConf(Conf parentConf) { this.parentConf = parentConf; } @SuppressWarnings("unchecked") public <T extends Conf> T getParentConf() { return (T)parentConf; } @SuppressWarnings("unchecked") public <T extends Conf> T getAncestorConf(StramElement ancestorElement) { if (getElement() == ancestorElement) { return (T)this; } if (parentConf == null) { return null; } else { return parentConf.getAncestorConf(ancestorElement); } } public <T extends Conf> T getOrAddChild(String id, StramElement childType, Class<T> clazz) { @SuppressWarnings("unchecked") Map<String, T> elChildren = (Map<String, T>)children.get(childType); if (elChildren == null) { elChildren = Maps.newHashMap(); children.put(childType, elChildren); } T conf = getOrAddConf(elChildren, id, clazz); if (conf != null) { conf.setParentConf(this); } return conf; } public void setAttribute(Attribute<Object> attr, String value) { attributes.put(attr, value); } public void setProperty(String name, String value) { properties.setProperty(name, value); } public void setDefaultProperties(Properties defaults) { properties.setDefaultProperties(defaults); } public <T extends Conf> List<T> getMatchingChildConf(String name, StramElement childType) { List<T> childConfs = new ArrayList<T>(); Map<String, T> elChildren = getChildren(childType); for (Map.Entry<String, T> entry : elChildren.entrySet()) { String key = entry.getKey(); boolean match = false; boolean exact = false; // Match WILDCARD to null if (name == null) { if (key == null) { match = true; exact = true; } else if (key.equals(WILDCARD)) { match = true; } } else { // Also treat WILDCARD as match any character string when running regular express match if (key.equals(WILDCARD)) { key = WILDCARD_PATTERN; } if (name.matches(key)) { match = true; } if (name.equals(key)) { exact = true; } } // There will be a better match preference order if (match) { if (!exact) { childConfs.add(entry.getValue()); } else { childConfs.add(0, entry.getValue()); } } } return childConfs; } protected <T extends Conf> T getOrAddConf(Map<String, T> map, String id, Class<T> clazz) { T conf = map.get(id); if (conf == null) { try { Constructor<T> declaredConstructor = clazz.getDeclaredConstructor(new Class<?>[] {}); conf = declaredConstructor.newInstance(new Object[] {}); conf.setId(id); map.put(id, conf); } catch (Exception e) { LOG.error("Error instantiating configuration", e); } } return conf; } //public abstract Conf getChild(String id, StramElement childType); public <T extends Conf> T getChild(String id, StramElement childType) { T conf = null; @SuppressWarnings("unchecked") Map<String, T> elChildren = (Map<String, T>)children.get(childType); if (elChildren != null) { conf = elChildren.get(id); } return conf; } @SuppressWarnings("unchecked") public <T extends Conf> Map<String, T> getChildren(StramElement childType) { // Always return non null so caller will not have to do extra check as expected Map<String, T> elChildren = (Map<String, T>)children.get(childType); if (elChildren == null) { elChildren = new HashMap<String, T>(); children.put(childType, elChildren); } return elChildren; } // Override for parsing of custom elements other than attributes and opProps // Make this config parse element as the entry point for parsing in future instead of the generic method in parent class public void parseElement(StramElement element, String[] keys, int index, String propertyValue) { } public Class<? extends Context> getAttributeContextClass() { return null; } public boolean isAllowedChild(StramElement childType) { StramElement[] childElements = getChildElements(); if (childElements != null) { for (StramElement childElement : childElements) { if (childType == childElement) { return true; } } } return false; } public StramElement getDefaultChildElement() { if ((getAttributeContextClass() == null) && isAllowedChild(StramElement.PROP)) { return StramElement.PROP; } return null; } public boolean ignoreUnknownChildren() { return getDefaultChildElement() == null; } public abstract StramElement[] getChildElements(); public abstract StramElement getElement(); } private static class StramConf extends Conf { private final Map<String, String> appAliases = Maps.newHashMap(); private static final StramElement[] CHILD_ELEMENTS = new StramElement[]{StramElement.APPLICATION, StramElement.GATEWAY, StramElement.TEMPLATE, StramElement.OPERATOR, StramElement.PORT, StramElement.INPUT_PORT, StramElement.OUTPUT_PORT, StramElement.STREAM, StramElement.TEMPLATE, StramElement.ATTR}; StramConf() { } @Override public StramElement getElement() { return null; } @Override public StramElement[] getChildElements() { return CHILD_ELEMENTS; } } /** * App configuration */ private static class AppConf extends Conf { private static final StramElement[] CHILD_ELEMENTS = new StramElement[]{StramElement.GATEWAY, StramElement.OPERATOR, StramElement.PORT, StramElement.INPUT_PORT, StramElement.OUTPUT_PORT, StramElement.STREAM, StramElement.ATTR, StramElement.CLASS, StramElement.PATH, StramElement.PROP}; @SuppressWarnings("unused") AppConf() { } @Override public StramElement getElement() { return StramElement.APPLICATION; } @Override public void parseElement(StramElement element, String[] keys, int index, String propertyValue) { if ((element == StramElement.CLASS) || (element == StramElement.PATH)) { StramConf stramConf = getParentConf(); stramConf.appAliases.put(propertyValue, getId()); } } @Override public StramElement[] getChildElements() { return CHILD_ELEMENTS; } @Override public Class<? extends Context> getAttributeContextClass() { return Context.DAGContext.class; } @Override public StramElement getDefaultChildElement() { return StramElement.PROP; } } private static class GatewayConf extends Conf { private static final StramElement[] CHILD_ELEMENTS = new StramElement[] {StramElement.PROP}; @SuppressWarnings("unused") GatewayConf() { } @Override public StramElement[] getChildElements() { return CHILD_ELEMENTS; } @Override public StramElement getElement() { return StramElement.GATEWAY; } } /** * Named set of opProps that can be used to instantiate streams or operators * with common settings. */ private static class TemplateConf extends Conf { private static final StramElement[] CHILD_ELEMENTS = new StramElement[] {StramElement.PROP}; @SuppressWarnings("unused") TemplateConf() { } @Override public StramElement[] getChildElements() { return CHILD_ELEMENTS; } @Override public StramElement getElement() { return StramElement.TEMPLATE; } @Override public void setProperty(String name, String value) { if (name.equals(TEMPLATE_appNameRegExp)) { appNameRegExp = value; } else if (name.equals(TEMPLATE_idRegExp)) { idRegExp = value; } else if (name.equals(TEMPLATE_classNameRegExp)) { classNameRegExp = value; } else { super.setProperty(name, value); } } private String idRegExp; private String appNameRegExp; private String classNameRegExp; } private static class StreamConf extends Conf { private static final StramElement[] CHILD_ELEMENTS = new StramElement[] {StramElement.TEMPLATE, StramElement.PROP}; private OperatorConf sourceNode; private final Set<OperatorConf> targetNodes = new HashSet<OperatorConf>(); @SuppressWarnings("unused") StreamConf() { } @Override public StramElement getElement() { return StramElement.STREAM; } /** * Locality for adjacent operators. * @return boolean */ public DAG.Locality getLocality() { String v = properties.getProperty(STREAM_LOCALITY, null); return (v != null) ? DAG.Locality.valueOf(v) : null; } /** * Set source on stream to the node output port. * @param portName * @param node */ public StreamConf setSource(String portName, OperatorConf node) { if (this.sourceNode != null) { throw new IllegalArgumentException(String.format("Stream already receives input from %s", sourceNode)); } node.outputs.put(portName, this); this.sourceNode = node; return this; } public StreamConf addSink(String portName, OperatorConf targetNode) { if (targetNode.inputs.containsKey(portName)) { throw new IllegalArgumentException(String.format("Port %s already connected to stream %s", portName, targetNode.inputs.get(portName))); } //LOG.debug("Adding {} to {}", targetNode, this); targetNode.inputs.put(portName, this); targetNodes.add(targetNode); return this; } @Override public void setProperty(String name, String value) { AppConf appConf = getParentConf(); if (STREAM_SOURCE.equals(name)) { if (sourceNode != null) { // multiple sources not allowed throw new IllegalArgumentException("Duplicate " + name); } String[] parts = getNodeAndPortId(value); //setSource(parts[1], getOrAddOperator(appConf, parts[0])); setSource(parts[1], appConf.getOrAddChild(parts[0], StramElement.OPERATOR, OperatorConf.class)); } else if (STREAM_SINKS.equals(name)) { String[] targetPorts = value.split(","); for (String nodeAndPort : targetPorts) { String[] parts = getNodeAndPortId(nodeAndPort.trim()); addSink(parts[1], appConf.getOrAddChild(parts[0], StramElement.OPERATOR, OperatorConf.class)); } } else if (STREAM_TEMPLATE.equals(name)) { StramConf stramConf = getAncestorConf(null); TemplateConf templateConf = (TemplateConf)stramConf.getOrAddChild(value, StramElement.TEMPLATE, elementMaps.get(StramElement.TEMPLATE)); setDefaultProperties(templateConf.properties); } else { super.setProperty(name, value); } } private String[] getNodeAndPortId(String s) { String[] parts = s.split("\\."); if (parts.length != 2) { throw new IllegalArgumentException("Invalid node.port reference: " + s); } return parts; } @Override public StramElement[] getChildElements() { return CHILD_ELEMENTS; } @Override public String toString() { return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE). append("id", this.id). toString(); } } private static class PropertiesWithModifiableDefaults extends Properties { private static final long serialVersionUID = -4675421720308249982L; /** * @param defaults */ void setDefaultProperties(Properties defaults) { super.defaults = defaults; } } /** * Operator configuration */ private static class OperatorConf extends Conf { private static final StramElement[] CHILD_ELEMENTS = new StramElement[]{StramElement.PORT, StramElement.INPUT_PORT, StramElement.OUTPUT_PORT, StramElement.ATTR, StramElement.PROP}; @SuppressWarnings("unused") OperatorConf() { } private final Map<String, StreamConf> inputs = new HashMap<String, StreamConf>(); private final Map<String, StreamConf> outputs = new HashMap<String, StreamConf>(); private String templateRef; @Override public StramElement getElement() { return StramElement.OPERATOR; } @Override public void setProperty(String name, String value) { if (OPERATOR_TEMPLATE.equals(name)) { templateRef = value; // Setting opProps from the template as default opProps as before // Revisit this StramConf stramConf = getAncestorConf(null); TemplateConf templateConf = (TemplateConf)stramConf.getOrAddChild(value, StramElement.TEMPLATE, elementMaps.get(StramElement.TEMPLATE)); setDefaultProperties(templateConf.properties); } else { super.setProperty(name, value); } } private String getClassNameReqd() { String className = properties.getProperty(OPERATOR_CLASSNAME); if (className == null) { throw new IllegalArgumentException(String.format("Operator '%s' is missing property '%s'", getId(), LogicalPlanConfiguration.OPERATOR_CLASSNAME)); } return className; } /** * Properties for the node. Template values (if set) become property defaults. * @return Map<String,String> */ private Map<String, String> getProperties() { return Maps.fromProperties(properties); } @Override public StramElement[] getChildElements() { return CHILD_ELEMENTS; } @Override public StramElement getDefaultChildElement() { return StramElement.PROP; } @Override public Class<? extends Context> getAttributeContextClass() { return OperatorContext.class; } /** * * @return String */ @Override public String toString() { return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE). append("id", this.id). toString(); } } /** * Port configuration */ private static class PortConf extends Conf { private static final StramElement[] CHILD_ELEMENTS = new StramElement[] {StramElement.ATTR}; @SuppressWarnings("unused") PortConf() { } @Override public StramElement getElement() { return StramElement.PORT; } @Override public StramElement[] getChildElements() { return CHILD_ELEMENTS; } @Override public Class<? extends Context> getAttributeContextClass() { return PortContext.class; } } private static final Map<StramElement, Class<? extends Conf>> elementMaps = Maps.newHashMap(); static { elementMaps.put(null, StramConf.class); elementMaps.put(StramElement.APPLICATION, AppConf.class); elementMaps.put(StramElement.GATEWAY, GatewayConf.class); elementMaps.put(StramElement.TEMPLATE, TemplateConf.class); elementMaps.put(StramElement.OPERATOR, OperatorConf.class); elementMaps.put(StramElement.STREAM, StreamConf.class); elementMaps.put(StramElement.PORT, PortConf.class); elementMaps.put(StramElement.INPUT_PORT, PortConf.class); elementMaps.put(StramElement.OUTPUT_PORT, PortConf.class); } private Conf getConf(StramElement element, Conf ancestorConf) { if (element == ancestorConf.getElement()) { return ancestorConf; } // If top most element is reached and didnt match ancestor conf // then terminate search if (element == null) { return null; } StramElement parentElement = getAllowedParentElement(element, ancestorConf); Conf parentConf = getConf(parentElement, ancestorConf); return parentConf.getOrAddChild(WILDCARD, element, elementMaps.get(element)); } private Conf addConf(StramElement element, String name, Conf ancestorConf) { StramElement parentElement = getAllowedParentElement(element, ancestorConf); Conf conf1 = null; Conf parentConf = getConf(parentElement, ancestorConf); if (parentConf != null) { conf1 = parentConf.getOrAddChild(name, element, elementMaps.get(element)); } return conf1; } private StramElement getAllowedParentElement(StramElement element, Conf ancestorConf) { StramElement parentElement = null; if ((element == StramElement.APPLICATION)) { parentElement = null; } else if ((element == StramElement.GATEWAY) || (element == StramElement.OPERATOR) || (element == StramElement.STREAM)) { parentElement = StramElement.APPLICATION; } else if ((element == StramElement.PORT) || (element == StramElement.INPUT_PORT) || (element == StramElement.OUTPUT_PORT)) { parentElement = StramElement.OPERATOR; } else if (element == StramElement.TEMPLATE) { parentElement = null; } return parentElement; } /* private boolean isApplicationTypeConf(Conf conf) { return (conf.getElement() == null) || (conf.getElement() == StramElement.APPLICATION); } */ private <T extends Conf> List<T> getMatchingChildConf(List<? extends Conf> confs, String name, StramElement childType) { List<T> childConfs = new ArrayList<T>(); for (Conf conf1 : confs) { List<T> matchingConfs = conf1.getMatchingChildConf(name, childType); childConfs.addAll(matchingConfs); } return childConfs; } private final Properties properties = new Properties(); public final Configuration conf; private final StramConf stramConf = new StramConf(); public LogicalPlanConfiguration(Configuration conf) { this.conf = conf; this.addFromConfiguration(conf); } /** * Add operators from flattened name value pairs in configuration object. * @param conf */ public final void addFromConfiguration(Configuration conf) { addFromProperties(toProperties(conf, StreamingApplication.DT_PREFIX), null); } public static Properties toProperties(Configuration conf, String prefix) { Iterator<Entry<String, String>> it = conf.iterator(); Properties props = new Properties(); while (it.hasNext()) { Entry<String, String> e = it.next(); // filter relevant entries if (e.getKey().startsWith(prefix)) { props.put(e.getKey(), e.getValue()); } } return props; } /** * Get the application alias name for an application class if one is available. * The path for the application class is specified as a parameter. If an alias was specified * in the configuration file or configuration opProps for the application class it is returned * otherwise null is returned. * * @param appPath The path of the application class in the jar * @return The alias name if one is available, null otherwise */ public String getAppAlias(String appPath) { String appAlias; if (appPath.endsWith(CLASS_SUFFIX)) { appPath = appPath.replace("/", ".").substring(0, appPath.length() - CLASS_SUFFIX.length()); } appAlias = stramConf.appAliases.get(appPath); if (appAlias == null) { try { ApplicationAnnotation an = Thread.currentThread().getContextClassLoader().loadClass(appPath).getAnnotation(ApplicationAnnotation.class); if (an != null && StringUtils.isNotBlank(an.name())) { appAlias = an.name(); } } catch (ClassNotFoundException e) { // ignore } } return appAlias; } public LogicalPlanConfiguration addFromJson(JSONObject json, Configuration conf) throws JSONException { Properties prop = new Properties(); JSONArray operatorArray = json.getJSONArray("operators"); for (int i = 0; i < operatorArray.length(); i++) { JSONObject operator = operatorArray.getJSONObject(i); String operatorPrefix = StreamingApplication.DT_PREFIX + StramElement.OPERATOR.getValue() + "." + operator.getString("name") + "."; prop.setProperty(operatorPrefix + "classname", operator.getString("class")); JSONObject operatorProperties = operator.optJSONObject("properties"); if (operatorProperties != null) { String propertiesPrefix = operatorPrefix + StramElement.PROP.getValue() + "."; @SuppressWarnings("unchecked") Iterator<String> iter = operatorProperties.keys(); while (iter.hasNext()) { String key = iter.next(); prop.setProperty(propertiesPrefix + key, operatorProperties.get(key).toString()); } } JSONObject operatorAttributes = operator.optJSONObject("attributes"); if (operatorAttributes != null) { String attributesPrefix = operatorPrefix + StramElement.ATTR.getValue() + "."; @SuppressWarnings("unchecked") Iterator<String> iter = operatorAttributes.keys(); while (iter.hasNext()) { String key = iter.next(); prop.setProperty(attributesPrefix + key, operatorAttributes.getString(key)); } } JSONArray portArray = operator.optJSONArray("ports"); if (portArray != null) { String portsPrefix = operatorPrefix + StramElement.PORT.getValue() + "."; for (int j = 0; j < portArray.length(); j++) { JSONObject port = portArray.getJSONObject(j); JSONObject portAttributes = port.optJSONObject("attributes"); if (portAttributes != null) { String portAttributePrefix = portsPrefix + port.getString("name") + "." + StramElement.ATTR.getValue() + "."; @SuppressWarnings("unchecked") Iterator<String> iter = portAttributes.keys(); while (iter.hasNext()) { String key = iter.next(); prop.setProperty(portAttributePrefix + key, portAttributes.getString(key)); } } } } } JSONObject appAttributes = json.optJSONObject("attributes"); if (appAttributes != null) { String attributesPrefix = StreamingApplication.DT_PREFIX + StramElement.ATTR.getValue() + "."; @SuppressWarnings("unchecked") Iterator<String> iter = appAttributes.keys(); while (iter.hasNext()) { String key = iter.next(); prop.setProperty(attributesPrefix + key, appAttributes.getString(key)); } } JSONArray streamArray = json.getJSONArray("streams"); for (int i = 0; i < streamArray.length(); i++) { JSONObject stream = streamArray.getJSONObject(i); String name = stream.optString("name", "stream-" + i); String streamPrefix = StreamingApplication.DT_PREFIX + StramElement.STREAM.getValue() + "." + name + "."; JSONObject source = stream.getJSONObject("source"); prop.setProperty(streamPrefix + STREAM_SOURCE, source.getString("operatorName") + "." + source.getString("portName")); JSONArray sinks = stream.getJSONArray("sinks"); StringBuilder sinkPropertyValue = new StringBuilder(); for (int j = 0; j < sinks.length(); j++) { if (sinkPropertyValue.length() > 0) { sinkPropertyValue.append(","); } JSONObject sink = sinks.getJSONObject(j); sinkPropertyValue.append(sink.getString("operatorName")).append(".").append(sink.getString("portName")); } prop.setProperty(streamPrefix + STREAM_SINKS, sinkPropertyValue.toString()); String locality = stream.optString("locality", null); if (locality != null) { prop.setProperty(streamPrefix + STREAM_LOCALITY, locality); } } return addFromProperties(prop, conf); } /** * Read node configurations from opProps. The opProps can be in any * random order, as long as they represent a consistent configuration in their * entirety. * * @param props * @param conf configuration for variable substitution and evaluation * @return Logical plan configuration. */ public LogicalPlanConfiguration addFromProperties(Properties props, Configuration conf) { if (conf != null) { StramClientUtils.evalProperties(props, conf); } for (final String propertyName : props.stringPropertyNames()) { String propertyValue = props.getProperty(propertyName); this.properties.setProperty(propertyName, propertyValue); if (propertyName.startsWith(StreamingApplication.DT_PREFIX)) { String[] keyComps = propertyName.split("\\."); parseStramPropertyTokens(keyComps, 1, propertyName, propertyValue, stramConf); } } return this; } private void parseStramPropertyTokens(String[] keys, int index, String propertyName, String propertyValue, Conf conf) { if (index < keys.length) { String key = keys[index]; StramElement element = getElement(key, conf); if ((element == null) && conf.ignoreUnknownChildren()) { return; } if ((element == StramElement.APPLICATION) || (element == StramElement.OPERATOR) || (element == StramElement.STREAM) || (element == StramElement.PORT) || (element == StramElement.INPUT_PORT) || (element == StramElement.OUTPUT_PORT) || (element == StramElement.TEMPLATE)) { if ((index + 1) < keys.length) { String name = keys[index+1]; Conf elConf = addConf(element, name, conf); if (elConf != null) { parseStramPropertyTokens(keys, index + 2, propertyName, propertyValue, elConf); } else { LOG.error("Invalid configuration key: {}", propertyName); } } else { LOG.warn("Invalid configuration key: {}", propertyName); } } else if ((element == StramElement.GATEWAY)) { Conf elConf = addConf(element, null, conf); if (elConf != null) { parseStramPropertyTokens(keys, index+1, propertyName, propertyValue, elConf); } else { LOG.error("Invalid configuration key: {}", propertyName); } } else if ((element == StramElement.ATTR) || ((element == null) && (conf.getDefaultChildElement() == StramElement.ATTR))) { if (conf.getElement() == null) { conf = addConf(StramElement.APPLICATION, WILDCARD, conf); } if (conf != null) { // Supporting current implementation where attribute can be directly specified under stram // Re-composing complete key for nested keys which are used in templates // Implement it better way to not pre-tokenize the property string and parse progressively parseAttribute(conf, keys, index, element, propertyValue); } else { LOG.error("Invalid configuration key: {}", propertyName); } } else if ((element == StramElement.PROP) || ((element == null) && (conf.getDefaultChildElement() == StramElement.PROP))) { // Currently opProps are only supported on operators and streams // Supporting current implementation where property can be directly specified under operator String prop; if (element == StramElement.PROP) { prop = getCompleteKey(keys, index+1); } else { prop = getCompleteKey(keys, index); /* if (conf.getAttributeContextClass() != null) { LOG.warn("Please specify the property {} using the {} keyword as {}", prop, StramElement.PROP.getValue(), getCompleteKey(keys, 0, index) + "." + StramElement.PROP.getValue() + "." + getCompleteKey(keys, index)); } */ } if (prop != null) { conf.setProperty(prop, propertyValue); } else { LOG.warn("Invalid property specification, no property name specified for {}", propertyName); } } else if (element != null) { conf.parseElement(element, keys, index, propertyValue); } } } private StramElement getElement(String value, Conf conf) { StramElement element = null; try { element = StramElement.fromValue(value); } catch (IllegalArgumentException ie) { } // If element is not allowed treat it as text if ((element != null) && !conf.isAllowedChild(element)) { element = null; } return element; } private String getCompleteKey(String[] keys, int start) { return getCompleteKey(keys, start, keys.length); } private String getCompleteKey(String[] keys, int start, int end) { StringBuilder sb = new StringBuilder(1024); for (int i = start; i < end; ++i) { if (i > start) { sb.append("."); } sb.append(keys[i]); } return sb.toString(); } /** * Return all opProps set on the builder. * Can be serialized to property file and used to read back into builder. * @return Properties */ public Properties getProperties() { return this.properties; } public Map<String, String> getAppAliases() { return Collections.unmodifiableMap(this.stramConf.appAliases); } public LogicalPlan createFromProperties(Properties props, String appName) throws IOException { // build DAG from properties LogicalPlanConfiguration tb = new LogicalPlanConfiguration(new Configuration(false)); tb.addFromProperties(props, conf); LogicalPlan dag = new LogicalPlan(); tb.populateDAG(dag); // configure with embedded settings tb.prepareDAG(dag, null, appName); // configure with external settings prepareDAG(dag, null, appName); return dag; } public LogicalPlan createFromJson(JSONObject json, String appName) throws Exception { // build DAG from properties LogicalPlanConfiguration tb = new LogicalPlanConfiguration(new Configuration(false)); tb.addFromJson(json, conf); LogicalPlan dag = new LogicalPlan(); tb.populateDAG(dag); // configure with embedded settings tb.prepareDAG(dag, null, appName); // configure with external settings prepareDAG(dag, null, appName); return dag; } /** * Populate the logical plan structure from properties. * @param dag */ public void populateDAG(LogicalPlan dag) { Configuration pconf = new Configuration(conf); for (final String propertyName : this.properties.stringPropertyNames()) { String propertyValue = this.properties.getProperty(propertyName); pconf.setIfUnset(propertyName, propertyValue); } AppConf appConf = this.stramConf.getChild(WILDCARD, StramElement.APPLICATION); if (appConf == null) { LOG.warn("Application configuration not found. Probably an empty app."); return; } Map<String, OperatorConf> operators = appConf.getChildren(StramElement.OPERATOR); Map<OperatorConf, Operator> nodeMap = new HashMap<OperatorConf, Operator>(operators.size()); // add all operators first for (Map.Entry<String, OperatorConf> nodeConfEntry : operators.entrySet()) { OperatorConf nodeConf = nodeConfEntry.getValue(); if (!WILDCARD.equals(nodeConf.id)) { Class<? extends Operator> nodeClass = StramUtils.classForName(nodeConf.getClassNameReqd(), Operator.class); String optJson = nodeConf.getProperties().get(nodeClass.getName()); Operator nd = null; try { if (optJson != null) { // if there is a special key which is the class name, it means the operator is serialized in json format ObjectMapper mapper = ObjectMapperFactory.getOperatorValueDeserializer(); nd = mapper.readValue("{\"" + nodeClass.getName() + "\":" + optJson + "}", nodeClass); dag.addOperator(nodeConfEntry.getKey(), nd); } else { nd = dag.addOperator(nodeConfEntry.getKey(), nodeClass); } setOperatorProperties(nd, nodeConf.getProperties()); } catch (Exception e) { throw new IllegalArgumentException("Error setting operator properties " + e.getMessage(), e); } nodeMap.put(nodeConf, nd); } } Map<String, StreamConf> streams = appConf.getChildren(StramElement.STREAM); // wire operators for (Map.Entry<String, StreamConf> streamConfEntry : streams.entrySet()) { StreamConf streamConf = streamConfEntry.getValue(); DAG.StreamMeta sd = dag.addStream(streamConfEntry.getKey()); sd.setLocality(streamConf.getLocality()); if (streamConf.sourceNode != null) { String portName = null; for (Map.Entry<String, StreamConf> e : streamConf.sourceNode.outputs.entrySet()) { if (e.getValue() == streamConf) { portName = e.getKey(); } } Operator sourceDecl = nodeMap.get(streamConf.sourceNode); Operators.PortMappingDescriptor sourcePortMap = new Operators.PortMappingDescriptor(); Operators.describe(sourceDecl, sourcePortMap); sd.setSource(sourcePortMap.outputPorts.get(portName).component); } for (OperatorConf targetNode : streamConf.targetNodes) { String portName = null; for (Map.Entry<String, StreamConf> e : targetNode.inputs.entrySet()) { if (e.getValue() == streamConf) { portName = e.getKey(); } } Operator targetDecl = nodeMap.get(targetNode); Operators.PortMappingDescriptor targetPortMap = new Operators.PortMappingDescriptor(); Operators.describe(targetDecl, targetPortMap); sd.addSink(targetPortMap.inputPorts.get(portName).component); } } } /** * Populate the logical plan from the streaming application definition and configuration. * Configuration is resolved based on application alias, if any. * @param app * @param dag * @param name */ public void prepareDAG(LogicalPlan dag, StreamingApplication app, String name) { // EVENTUALLY to be replaced by variable enabled configuration in the demo where the attt below is used -- david, pramod, chetan String connectAddress = conf.get(StreamingApplication.DT_PREFIX + Context.DAGContext.GATEWAY_CONNECT_ADDRESS.getName()); dag.setAttribute(Context.DAGContext.GATEWAY_CONNECT_ADDRESS, connectAddress == null? conf.get(GATEWAY_LISTEN_ADDRESS): connectAddress); if (app != null) { app.populateDAG(dag, conf); } String appAlias = getAppAlias(name); String appName = appAlias == null ? name : appAlias; List<AppConf> appConfs = stramConf.getMatchingChildConf(appName, StramElement.APPLICATION); setApplicationConfiguration(dag, appConfs, app); if (dag.getAttributes().get(Context.DAGContext.APPLICATION_NAME) == null) { dag.setAttribute(Context.DAGContext.APPLICATION_NAME, appName); } // inject external operator configuration setOperatorConfiguration(dag, appConfs, appName); setStreamConfiguration(dag, appConfs, appName); } public static Properties readProperties(String filePath) throws IOException { InputStream is = new FileInputStream(filePath); Properties props = new Properties(System.getProperties()); props.load(is); is.close(); return props; } private String getSimpleName(Attribute<?> attribute) { return attribute.name.substring(attribute.name.lastIndexOf('.')+1); } /** * Get the configuration opProps for the given operator. * These can be operator specific settings or settings from matching templates. * @param ow * @param appName * @return */ public Map<String, String> getProperties(OperatorMeta ow, String appName) { List<AppConf> appConfs = stramConf.getMatchingChildConf(appName, StramElement.APPLICATION); List<OperatorConf> opConfs = getMatchingChildConf(appConfs, ow.getName(), StramElement.OPERATOR); return getProperties(ow, opConfs, appName); } private Map<String,String> getApplicationProperties(List<AppConf> appConfs){ Map<String, String> appProps = new HashMap<String, String>(); // Apply the configurations in reverse order since the higher priority ones are at the beginning for(int i = appConfs.size()-1; i >= 0; i AppConf conf1 = appConfs.get(i); appProps.putAll(Maps.fromProperties(conf1.properties)); } return appProps; } /** * Get the configuration opProps for the given operator. * These can be operator specific settings or settings from matching templates. * @param ow * @param opConfs * @param appName */ private Map<String, String> getProperties(OperatorMeta ow, List<OperatorConf> opConfs, String appName) { Map<String, String> opProps = new HashMap<String, String>(); Map<String, TemplateConf> templates = stramConf.getChildren(StramElement.TEMPLATE); // list of all templates that match operator, ordered by priority if (!templates.isEmpty()) { TreeMap<Integer, TemplateConf> matchingTemplates = getMatchingTemplates(ow, appName, templates); if (matchingTemplates != null && !matchingTemplates.isEmpty()) { // combined map of prioritized template settings for (TemplateConf t : matchingTemplates.descendingMap().values()) { opProps.putAll(Maps.fromProperties(t.properties)); } } List<TemplateConf> refTemplates = getDirectTemplates(opConfs, templates); for (TemplateConf t : refTemplates) { opProps.putAll(Maps.fromProperties(t.properties)); } } // direct settings // Apply the configurations in reverse order since the higher priority ones are at the beginning for (int i = opConfs.size()-1; i >= 0; i Conf conf1 = opConfs.get(i); opProps.putAll(Maps.fromProperties(conf1.properties)); } //properties.remove(OPERATOR_CLASSNAME); return opProps; } private List<TemplateConf> getDirectTemplates(List<OperatorConf> opConfs, Map<String, TemplateConf> templates) { List<TemplateConf> refTemplates = new ArrayList<TemplateConf>(); for (TemplateConf t : templates.values()) { for (OperatorConf opConf : opConfs) { if (t.id.equals(opConf.templateRef)) { refTemplates.add(t); } } } return refTemplates; } /** * Produce the collections of templates that apply for the given id. * @param ow * @param appName * @param templates * @return TreeMap<Integer, TemplateConf> */ private TreeMap<Integer, TemplateConf> getMatchingTemplates(OperatorMeta ow, String appName, Map<String, TemplateConf> templates) { TreeMap<Integer, TemplateConf> tm = new TreeMap<Integer, TemplateConf>(); for (TemplateConf t : templates.values()) { /*if (t.id == nodeConf.templateRef) { // directly assigned applies last tm.put(1, t); continue; } else*/ if ((t.idRegExp != null && ow.getName().matches(t.idRegExp))) { tm.put(1, t); } else if (appName != null && t.appNameRegExp != null && appName.matches(t.appNameRegExp)) { tm.put(2, t); } else if (t.classNameRegExp != null && ow.getOperator().getClass().getName().matches(t.classNameRegExp)) { tm.put(3, t); } } return tm; } /** * Inject the configuration opProps into the operator instance. * @param operator * @param properties * @return Operator */ public static Operator setOperatorProperties(Operator operator, Map<String, String> properties) { try { // populate custom opProps BeanUtils.populate(operator, properties); return operator; } catch (IllegalAccessException e) { throw new IllegalArgumentException("Error setting operator properties", e); } catch (InvocationTargetException e) { throw new IllegalArgumentException("Error setting operator properties", e); } } public static StreamingApplication setApplicationProperties(StreamingApplication application, Map<String, String> properties) { try { BeanUtils.populate(application, properties); return application; } catch (IllegalAccessException e) { throw new IllegalArgumentException("Error setting application properties", e); } catch (InvocationTargetException e) { throw new IllegalArgumentException("Error setting application properties", e); } } public static BeanMap getOperatorProperties(Operator operator) { return new BeanMap(operator); } /** * Set any opProps from configuration on the operators in the DAG. This * method may throw unchecked exception if the configuration contains * opProps that are invalid for an operator. * * @param dag * @param applicationName */ public void setOperatorProperties(LogicalPlan dag, String applicationName) { List<AppConf> appConfs = stramConf.getMatchingChildConf(applicationName, StramElement.APPLICATION); for (OperatorMeta ow : dag.getAllOperators()) { List<OperatorConf> opConfs = getMatchingChildConf(appConfs, ow.getName(), StramElement.OPERATOR); Map<String, String> opProps = getProperties(ow, opConfs, applicationName); setOperatorProperties(ow.getOperator(), opProps); } } /* private static final Map<String, Attribute<?>> legacyKeyMap = Maps.newHashMap(); static { legacyKeyMap.put("appName", Context.DAGContext.APPLICATION_NAME); legacyKeyMap.put("libjars", Context.DAGContext.LIBRARY_JARS); legacyKeyMap.put("maxContainers", Context.DAGContext.CONTAINERS_MAX_COUNT); legacyKeyMap.put("containerMemoryMB", Context.DAGContext.CONTAINER_MEMORY_MB); legacyKeyMap.put("containerJvmOpts", Context.DAGContext.CONTAINER_JVM_OPTIONS); legacyKeyMap.put("masterMemoryMB", Context.DAGContext.MASTER_MEMORY_MB); legacyKeyMap.put("windowSizeMillis", Context.DAGContext.STREAMING_WINDOW_SIZE_MILLIS); legacyKeyMap.put("appPath", Context.DAGContext.APPLICATION_PATH); legacyKeyMap.put("allocateResourceTimeoutMillis", Context.DAGContext.RESOURCE_ALLOCATION_TIMEOUT_MILLIS); } */ /** * Set the application configuration. * @param dag * @param appName * @param app */ public void setApplicationConfiguration(final LogicalPlan dag, String appName, StreamingApplication app) { List<AppConf> appConfs = stramConf.getMatchingChildConf(appName, StramElement.APPLICATION); setApplicationConfiguration(dag, appConfs,app); } private void setApplicationConfiguration(final LogicalPlan dag, List<AppConf> appConfs,StreamingApplication app) { // Make the gateway address available as an application attribute // for (Conf appConf : appConfs) { // Conf gwConf = appConf.getChild(null, StramElement.GATEWAY); // if (gwConf != null) { // String gatewayAddress = gwConf.properties.getProperty(GATEWAY_LISTEN_ADDRESS_PROP); // if (gatewayAddress != null) { // dag.setAttribute(DAGContext.GATEWAY_CONNECT_ADDRESS, gatewayAddress); // break; setAttributes(Context.DAGContext.class, appConfs, dag.getAttributes()); if (app != null) { Map<String, String> appProps = getApplicationProperties(appConfs); setApplicationProperties(app, appProps); } } private void setOperatorConfiguration(final LogicalPlan dag, List<AppConf> appConfs, String appName) { for (final OperatorMeta ow : dag.getAllOperators()) { List<OperatorConf> opConfs = getMatchingChildConf(appConfs, ow.getName(), StramElement.OPERATOR); // Set the operator attributes setAttributes(OperatorContext.class, opConfs, ow.getAttributes()); // Set the operator opProps Map<String, String> opProps = getProperties(ow, opConfs, appName); setOperatorProperties(ow.getOperator(), opProps); // Set the port attributes for (Entry<LogicalPlan.InputPortMeta, LogicalPlan.StreamMeta> entry : ow.getInputStreams().entrySet()) { final InputPortMeta im = entry.getKey(); List<PortConf> inPortConfs = getMatchingChildConf(opConfs, im.getPortName(), StramElement.INPUT_PORT); // Add the generic port attributes as well List<PortConf> portConfs = getMatchingChildConf(opConfs, im.getPortName(), StramElement.PORT); inPortConfs.addAll(portConfs); setAttributes(PortContext.class, inPortConfs, im.getAttributes()); } for (Entry<LogicalPlan.OutputPortMeta, LogicalPlan.StreamMeta> entry : ow.getOutputStreams().entrySet()) { final OutputPortMeta om = entry.getKey(); List<PortConf> outPortConfs = getMatchingChildConf(opConfs, om.getPortName(), StramElement.OUTPUT_PORT); // Add the generic port attributes as well List<PortConf> portConfs = getMatchingChildConf(opConfs, om.getPortName(), StramElement.PORT); outPortConfs.addAll(portConfs); setAttributes(PortContext.class, outPortConfs, om.getAttributes()); } } } private void setStreamConfiguration(LogicalPlan dag, List<AppConf> appConfs, String appAlias) { for (StreamMeta sm : dag.getAllStreams()) { List<StreamConf> smConfs = getMatchingChildConf(appConfs, sm.getName(), StramElement.STREAM); for (StreamConf smConf : smConfs) { DAG.Locality locality = smConf.getLocality(); if (locality != null) { sm.setLocality(locality); break; } } } } private final Map<Class<? extends Context>, Map<String, Attribute<Object>>> attributeMap = Maps.newHashMap(); private void parseAttribute(Conf conf, String[] keys, int index, StramElement element, String attrValue) { String configKey = (element == StramElement.ATTR) ? getCompleteKey(keys, index + 1) : getCompleteKey(keys, index); boolean isDeprecated = false; Class<? extends Context> clazz = conf.getAttributeContextClass(); Map<String, Attribute<Object>> m = attributeMap.get(clazz); if (!attributeMap.containsKey(clazz)) { Set<Attribute<Object>> attributes = AttributeInitializer.getAttributes(clazz); m = Maps.newHashMapWithExpectedSize(attributes.size()); for (Attribute<Object> attr : attributes) { m.put(getSimpleName(attr), attr); } attributeMap.put(clazz, m); } Attribute<Object> attr = m.get(configKey); if (attr == null) { throw new ValidationException("Invalid attribute reference: " + getCompleteKey(keys, 0)); } if (element != StramElement.ATTR || isDeprecated) { String expName = getCompleteKey(keys, 0, index) + "." + StramElement.ATTR.getValue() + "." + getSimpleName(attr); LOG.warn("Referencing the attribute as {} instead of {} is deprecated!", getCompleteKey(keys, 0), expName); } conf.setAttribute(attr, attrValue); } private void setAttributes(Class<?> clazz, List<? extends Conf> confs, Attribute.AttributeMap attributeMap) { Set<Attribute<Object>> processedAttributes = Sets.newHashSet(); //json object codec for complex attributes JSONObject2String jsonCodec = new JSONObject2String(); if (confs.size() > 0) { for (Conf conf1 : confs) { for (Map.Entry<Attribute<Object>, String> e : conf1.attributes.entrySet()) { Attribute<Object> attribute = e.getKey(); if (attribute.codec == null) { String msg = String.format("Attribute does not support property configuration: %s %s", attribute.name, e.getValue()); throw new UnsupportedOperationException(msg); } else { if (processedAttributes.add(attribute)) { String val = e.getValue(); if (val.trim().charAt(0) == '{') { // complex attribute in json attributeMap.put(attribute, jsonCodec.fromString(val)); } else { attributeMap.put(attribute, attribute.codec.fromString(val)); } } } } } } } }
package org.ccnx.ccn.test.io.content; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InvalidObjectException; import java.util.logging.Level; import org.bouncycastle.util.Arrays; import org.ccnx.ccn.CCNHandle; import org.ccnx.ccn.impl.CCNFlowServer; import org.ccnx.ccn.impl.CCNFlowControl.SaveType; import org.ccnx.ccn.impl.security.crypto.util.DigestHelper; import org.ccnx.ccn.impl.support.Log; import org.ccnx.ccn.io.CCNVersionedInputStream; import org.ccnx.ccn.io.content.CCNNetworkObject; import org.ccnx.ccn.io.content.CCNStringObject; import org.ccnx.ccn.io.content.Collection; import org.ccnx.ccn.io.content.Link; import org.ccnx.ccn.io.content.LinkAuthenticator; import org.ccnx.ccn.io.content.UpdateListener; import org.ccnx.ccn.io.content.Collection.CollectionObject; import org.ccnx.ccn.profiles.SegmentationProfile; import org.ccnx.ccn.profiles.VersioningProfile; import org.ccnx.ccn.protocol.CCNTime; import org.ccnx.ccn.protocol.ContentName; import org.ccnx.ccn.protocol.ContentObject; import org.ccnx.ccn.protocol.PublisherID; import org.ccnx.ccn.protocol.SignedInfo; import org.ccnx.ccn.protocol.PublisherID.PublisherType; import org.ccnx.ccn.test.CCNTestHelper; import org.ccnx.ccn.test.Flosser; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; /** * Test basic network object functionality, writing objects to a Flosser. * Much slower than it needs to be -- seems to hit some kind of ordering * bug which requires waiting for interest reexpression before it can go * forward (shows up as mysterious 4-second delays in the log). The corresponding * repo-backed test, CCNNetorkObjectTestRepo runs much faster to do exactly * the same work. * TODO track down slowness */ public class CCNNetworkObjectTest { /** * Handle naming for the test */ static CCNTestHelper testHelper = new CCNTestHelper(CCNNetworkObjectTest.class); static String stringObjName = "StringObject"; static String collectionObjName = "CollectionObject"; static String prefix = "CollectionObject-"; static ContentName [] ns = null; static public byte [] contenthash1 = new byte[32]; static public byte [] contenthash2 = new byte[32]; static public byte [] publisherid1 = new byte[32]; static public byte [] publisherid2 = new byte[32]; static PublisherID pubID1 = null; static PublisherID pubID2 = null; static int NUM_LINKS = 15; static LinkAuthenticator [] las = new LinkAuthenticator[NUM_LINKS]; static Link [] lrs = null; static Collection small1; static Collection small2; static Collection empty; static Collection big; static CCNHandle handle; static String [] numbers = new String[]{"ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE", "TEN"}; static Level oldLevel; static Flosser flosser = null; static void setupNamespace(ContentName name) throws IOException { flosser.handleNamespace(name); } static void removeNamespace(ContentName name) throws IOException { flosser.stopMonitoringNamespace(name); } @AfterClass public static void tearDownAfterClass() throws Exception { try { Log.info("Tearing down CCNNetworkObjectTest, prefix {0}", testHelper.getClassNamespace()); Log.flush(); Log.setDefaultLevel(oldLevel); if (flosser != null) { flosser.stop(); flosser = null; } Log.info("Finished tearing down CCNNetworkObjectTest, prefix {0}", testHelper.getClassNamespace()); Log.flush(); } catch (Exception e) { Log.severe("Exception in tearDownAfterClass: type {0} msg {0}", e.getClass().getName(), e.getMessage()); Log.warningStackTrace(e); } } @BeforeClass public static void setUpBeforeClass() throws Exception { Log.info("Setting up CCNNetworkObjectTest, prefix {0}", testHelper.getClassNamespace()); oldLevel = Log.getLevel(); Log.setDefaultLevel(Level.INFO); handle = CCNHandle.open(); ns = new ContentName[NUM_LINKS]; for (int i=0; i < NUM_LINKS; ++i) { ns[i] = ContentName.fromNative(testHelper.getClassNamespace(), "Links", prefix+Integer.toString(i)); } Arrays.fill(publisherid1, (byte)6); Arrays.fill(publisherid2, (byte)3); pubID1 = new PublisherID(publisherid1, PublisherType.KEY); pubID2 = new PublisherID(publisherid2, PublisherType.ISSUER_KEY); las[0] = new LinkAuthenticator(pubID1); las[1] = null; las[2] = new LinkAuthenticator(pubID2, null, null, SignedInfo.ContentType.DATA, contenthash1); las[3] = new LinkAuthenticator(pubID1, null, CCNTime.now(), null, contenthash1); for (int j=4; j < NUM_LINKS; ++j) { las[j] = new LinkAuthenticator(pubID2, null, CCNTime.now(), null, null); } lrs = new Link[NUM_LINKS]; for (int i=0; i < lrs.length; ++i) { lrs[i] = new Link(ns[i],las[i]); } empty = new Collection(); small1 = new Collection(); small2 = new Collection(); for (int i=0; i < 5; ++i) { small1.add(lrs[i]); small2.add(lrs[i+5]); } big = new Collection(); for (int i=0; i < NUM_LINKS; ++i) { big.add(lrs[i]); } flosser = new Flosser(); Log.info("Finished setting up CCNNetworkObjectTest, prefix is: {0}.", testHelper.getClassNamespace()); } @AfterClass public static void cleanupAfterClass() { handle.close(); } @Test public void testVersioning() throws Exception { // Testing problem of disappearing versions, inability to get latest. Use simpler // object than a collection. CCNHandle lput = CCNHandle.open(); CCNHandle lget = CCNHandle.open(); ContentName testName = ContentName.fromNative(testHelper.getTestNamespace("testVersioning"), stringObjName); try { CCNStringObject so = new CCNStringObject(testName, "First value", SaveType.RAW, lput); setupNamespace(testName); CCNStringObject ro = null; CCNStringObject ro2 = null; CCNStringObject ro3, ro4; // make each time, to get a new handle. CCNTime soTime, srTime, sr2Time, sr3Time, sr4Time, so2Time; for (int i=0; i < numbers.length; ++i) { soTime = saveAndLog(numbers[i], so, null, numbers[i]); if (null == ro) { ro = new CCNStringObject(testName, lget); srTime = waitForDataAndLog(numbers[i], ro); } else { srTime = updateAndLog(numbers[i], ro, null); } if (null == ro2) { ro2 = new CCNStringObject(testName, null); sr2Time = waitForDataAndLog(numbers[i], ro2); } else { sr2Time = updateAndLog(numbers[i], ro2, null); } ro3 = new CCNStringObject(ro.getVersionedName(), null); // read specific version sr3Time = waitForDataAndLog("UpdateToROVersion", ro3); // Save a new version and pull old so2Time = saveAndLog(numbers[i] + "-Update", so, null, numbers[i] + "-Update"); ro4 = new CCNStringObject(ro.getVersionedName(), null); // read specific version sr4Time = waitForDataAndLog("UpdateAnotherToROVersion", ro4); System.out.println("Update " + i + ": Times: " + soTime + " " + srTime + " " + sr2Time + " " + sr3Time + " different: " + so2Time); Assert.assertEquals("SaveTime doesn't match first read", soTime, srTime); Assert.assertEquals("SaveTime doesn't match second read", soTime, sr2Time); Assert.assertEquals("SaveTime doesn't match specific version read", soTime, sr3Time); Assert.assertFalse("UpdateTime isn't newer than read time", soTime.equals(so2Time)); Assert.assertEquals("SaveTime doesn't match specific version read", soTime, sr4Time); } } finally { removeNamespace(testName); lput.close(); lget.close(); } } @Test public void testSaveToVersion() throws Exception { // Testing problem of disappearing versions, inability to get latest. Use simpler // object than a collection. CCNHandle lput = CCNHandle.open(); CCNHandle lget = CCNHandle.open(); ContentName testName = ContentName.fromNative(testHelper.getTestNamespace("testSaveToVersion"), stringObjName); try { CCNTime desiredVersion = CCNTime.now(); CCNStringObject so = new CCNStringObject(testName, "First value", SaveType.RAW, lput); setupNamespace(testName); saveAndLog("SpecifiedVersion", so, desiredVersion, "Time: " + desiredVersion); Assert.assertEquals("Didn't write correct version", desiredVersion, so.getVersion()); CCNStringObject ro = new CCNStringObject(testName, lget); ro.waitForData(); Assert.assertEquals("Didn't read correct version", desiredVersion, ro.getVersion()); ContentName versionName = ro.getVersionedName(); saveAndLog("UpdatedVersion", so, null, "ReplacementData"); updateAndLog("UpdatedData", ro, null); Assert.assertTrue("New version " + so.getVersion() + " should be later than old version " + desiredVersion, (desiredVersion.before(so.getVersion()))); Assert.assertEquals("Didn't read correct version", so.getVersion(), ro.getVersion()); CCNStringObject ro2 = new CCNStringObject(versionName, null); ro2.waitForData(); Assert.assertEquals("Didn't read correct version", desiredVersion, ro2.getVersion()); } finally { removeNamespace(testName); lput.close(); lget.close(); } } @Test public void testEmptySave() throws Exception { boolean caught = false; ContentName testName = ContentName.fromNative(testHelper.getTestNamespace("testEmptySave"), collectionObjName); try { CollectionObject emptycoll = new CollectionObject(testName, (Collection)null, SaveType.RAW, handle); setupNamespace(testName); try { emptycoll.setData(small1); // set temporarily to non-null saveAndLog("Empty", emptycoll, null, null); } catch (InvalidObjectException iox) { // this is what we expect to happen caught = true; } Assert.assertTrue("Failed to produce expected exception.", caught); } finally { removeNamespace(testName); } } @Test public void testStreamUpdate() throws Exception { ContentName testName = ContentName.fromNative(testHelper.getTestNamespace("testStreamUpdate"), collectionObjName); CCNHandle tHandle = CCNHandle.open(); try { CollectionObject testCollectionObject = new CollectionObject(testName, small1, SaveType.RAW, tHandle); setupNamespace(testName); saveAndLog("testStreamUpdate", testCollectionObject, null, small1); System.out.println("testCollectionObject name: " + testCollectionObject.getVersionedName()); CCNVersionedInputStream vis = new CCNVersionedInputStream(testCollectionObject.getVersionedName()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte [] buf = new byte[128]; // Will incur a timeout while (!vis.eof()) { int read = vis.read(buf); if (read > 0) baos.write(buf, 0, read); } System.out.println("Read " + baos.toByteArray().length + " bytes, digest: " + DigestHelper.printBytes(DigestHelper.digest(baos.toByteArray()), 16)); Collection decodedData = new Collection(); decodedData.decode(baos.toByteArray()); System.out.println("Decoded collection data: " + decodedData); Assert.assertEquals("Decoding via stream fails to give expected result!", decodedData, small1); CCNVersionedInputStream vis2 = new CCNVersionedInputStream(testCollectionObject.getVersionedName()); ByteArrayOutputStream baos2 = new ByteArrayOutputStream(); // Will incur a timeout while (!vis2.eof()) { int val = vis2.read(); if (val < 0) break; baos2.write((byte)val); } System.out.println("Read " + baos2.toByteArray().length + " bytes, digest: " + DigestHelper.printBytes(DigestHelper.digest(baos2.toByteArray()), 16)); Assert.assertArrayEquals("Reading same object twice gets different results!", baos.toByteArray(), baos2.toByteArray()); Collection decodedData2 = new Collection(); decodedData2.decode(baos2.toByteArray()); Assert.assertEquals("Decoding via stream byte read fails to give expected result!", decodedData2, small1); CCNVersionedInputStream vis3 = new CCNVersionedInputStream(testCollectionObject.getVersionedName()); Collection decodedData3 = new Collection(); decodedData3.decode(vis3); Assert.assertEquals("Decoding via stream full read fails to give expected result!", decodedData3, small1); } finally { removeNamespace(testName); tHandle.close(); } } @Test public void testVersionOrdering() throws Exception { ContentName testName = ContentName.fromNative(testHelper.getTestNamespace("testVersionOrdering"), collectionObjName, "name1"); ContentName testName2 = ContentName.fromNative(testHelper.getTestNamespace("testVersionOrdering"), collectionObjName, "name2"); CCNHandle tHandle = CCNHandle.open(); try { CollectionObject c0 = new CollectionObject(testName, empty, SaveType.RAW, handle); setupNamespace(testName); CCNTime t0 = saveAndLog("Empty", c0, null, empty); CollectionObject c1 = new CollectionObject(testName2, small1, SaveType.RAW, tHandle); CollectionObject c2 = new CollectionObject(testName2, small1, SaveType.RAW, null); setupNamespace(testName2); CCNTime t1 = saveAndLog("Small", c1, null, small1); Assert.assertTrue("First version should come before second", t0.before(t1)); CCNTime t2 = saveAndLog("Small2ndWrite", c2, null, small1); Assert.assertTrue("Third version should come after second", t1.before(t2)); Assert.assertTrue(c2.contentEquals(c1)); Assert.assertFalse(c2.equals(c1)); Assert.assertTrue(VersioningProfile.isLaterVersionOf(c2.getVersionedName(), c1.getVersionedName())); } finally { removeNamespace(testName); removeNamespace(testName2); tHandle.close(); } } @Test public void testUpdateOtherName() throws Exception { CCNHandle tHandle = CCNHandle.open(); ContentName testName = ContentName.fromNative(testHelper.getTestNamespace("testUpdateOtherName"), collectionObjName, "name1"); ContentName testName2 = ContentName.fromNative(testHelper.getTestNamespace("testUpdateOtherName"), collectionObjName, "name2"); try { CollectionObject c0 = new CollectionObject(testName, empty, SaveType.RAW, handle); setupNamespace(testName); CCNTime t0 = saveAndLog("Empty", c0, null, empty); CollectionObject c1 = new CollectionObject(testName2, small1, SaveType.RAW, tHandle); // Cheat a little, make this one before the setupNamespace... CollectionObject c2 = new CollectionObject(testName2, small1, SaveType.RAW, null); setupNamespace(testName2); CCNTime t1 = saveAndLog("Small", c1, null, small1); Assert.assertTrue("First version should come before second", t0.before(t1)); CCNTime t2 = saveAndLog("Small2ndWrite", c2, null, small1); Assert.assertTrue("Third version should come after second", t1.before(t2)); Assert.assertTrue(c2.contentEquals(c1)); Assert.assertFalse(c2.equals(c1)); CCNTime t3 = updateAndLog(c0.getVersionedName().toString(), c0, testName2); Assert.assertTrue(VersioningProfile.isVersionOf(c0.getVersionedName(), testName2)); Assert.assertEquals(t3, t2); Assert.assertTrue(c0.contentEquals(c2)); t3 = updateAndLog(c0.getVersionedName().toString(), c0, c1.getVersionedName()); Assert.assertTrue(VersioningProfile.isVersionOf(c0.getVersionedName(), testName2)); Assert.assertEquals(t3, t1); Assert.assertTrue(c0.contentEquals(c1)); } finally { removeNamespace(testName); removeNamespace(testName2); tHandle.close(); } } @Test public void testUpdateInBackground() throws Exception { CCNHandle tHandle = CCNHandle.open(); CCNHandle tHandle2 = CCNHandle.open(); CCNHandle tHandle3 = CCNHandle.open(); ContentName testName = ContentName.fromNative(testHelper.getTestNamespace("testUpdateInBackground"), stringObjName, "name1"); try { CCNStringObject c0 = new CCNStringObject(testName, (String)null, SaveType.RAW, tHandle); c0.updateInBackground(); CCNStringObject c1 = new CCNStringObject(testName, (String)null, SaveType.RAW, tHandle2); c1.updateInBackground(true); Assert.assertFalse(c0.available()); Assert.assertFalse(c0.isSaved()); Assert.assertFalse(c1.available()); Assert.assertFalse(c1.isSaved()); CCNStringObject c2 = new CCNStringObject(testName, (String)null, SaveType.RAW, tHandle3); CCNTime t1 = saveAndLog("First string", c2, null, "Here is the first string."); Log.info("Saved c2: " + c2.getVersionedName() + " c0 available? " + c0.available() + " c1 available? " + c1.available()); c0.waitForData(); Assert.assertEquals("c0 update", c0.getVersion(), c2.getVersion()); c1.waitForData(); Assert.assertEquals("c1 update", c1.getVersion(), c2.getVersion()); CCNTime t2 = saveAndLog("Second string", c2, null, "Here is the second string."); synchronized (c1) { if (!c1.getVersion().equals(t2)) { c1.wait(5000); } } Assert.assertEquals("c1 update 2", c1.getVersion(), c2.getVersion()); Assert.assertEquals("c0 unchanged", c0.getVersion(), t1); } finally { removeNamespace(testName); tHandle.close(); tHandle2.close(); tHandle3.close(); } } @Test public void testBackgroundVerifier() throws Exception { ContentName testName = ContentName.fromNative(testHelper.getTestNamespace("testBackgroundVerifier"), stringObjName, "name1"); try { CCNStringObject c0 = new CCNStringObject(testName, (String)null, SaveType.RAW, CCNHandle.open()); c0.updateInBackground(true); CCNStringObject c1 = new CCNStringObject(testName, (String)null, SaveType.RAW, CCNHandle.open()); c1.updateInBackground(true); CCNTime t1 = saveAndLog("First string", c0, null, "Here is the first string."); c0.waitForData(); c1.waitForData(); CCNTime c1Version = c1.getVersion(); Assert.assertTrue(c0.available()); Assert.assertTrue(c0.isSaved()); Assert.assertTrue(c1.available()); Assert.assertTrue(c1.isSaved()); Assert.assertEquals(t1, c1Version); // Test background ability to throw away bogus data. // change the version so a) it's later, and b) the signature won't verify ContentName laterName = SegmentationProfile.segmentName(VersioningProfile.updateVersion(c1.getVersionedName()), SegmentationProfile.baseSegment()); CCNFlowServer server = new CCNFlowServer(testName, null, false, CCNHandle.open()); server.addNameSpace(laterName); ContentObject bogon = new ContentObject(laterName, c0.getFirstSegment().signedInfo(), c0.getFirstSegment().content(), c0.getFirstSegment().signature()); Log.info("Writing bogon: {0}", bogon.fullName()); server.put(bogon); Thread.sleep(300); // Should be no update Assert.assertEquals(c0.getVersion(), c1Version); Assert.assertEquals(c1.getVersion(), c1Version); // Now write a newer one CCNStringObject c2 = new CCNStringObject(testName, (String)null, SaveType.RAW, CCNHandle.open()); CCNTime t2 = saveAndLog("Second string", c2, null, "Here is the second string."); Log.info("Saved c2: " + c2.getVersionedName() + " c0 available? " + c0.available() + " c1 available? " + c1.available()); synchronized (c0) { if (!c0.getVersion().equals(t2)) { c0.wait(5000); } } Assert.assertEquals("c0 update", c0.getVersion(), c2.getVersion()); synchronized (c1) { if (!c1.getVersion().equals(t2)) { c1.wait(5000); } } Assert.assertEquals("c1 update", c1.getVersion(), c2.getVersion()); Assert.assertFalse(c1Version.equals(c1.getVersion())); } finally { removeNamespace(testName); } } @Test public void testSaveAsGone() throws Exception { ContentName testName = ContentName.fromNative(testHelper.getTestNamespace("testSaveAsGone"), collectionObjName); CCNHandle tHandle = CCNHandle.open(); CCNHandle tHandle2 = CCNHandle.open(); try { Log.info("TSAG: Entering testSaveAsGone"); CollectionObject c0 = new CollectionObject(testName, empty, SaveType.RAW, handle); setupNamespace(testName); // this sends the interest, doing it after the object gives it // a chance to catch it. CCNTime t0 = saveAsGoneAndLog("FirstGoneSave", c0); Assert.assertTrue("Should be gone", c0.isGone()); ContentName goneVersionName = c0.getVersionedName(); Log.info("T1"); CCNTime t1 = saveAndLog("NotGone", c0, null, small1); Assert.assertFalse("Should not be gone", c0.isGone()); Assert.assertTrue(t1.after(t0)); Log.info("T2"); CollectionObject c1 = new CollectionObject(testName, tHandle); CCNTime t2 = waitForDataAndLog(testName.toString(), c1); Assert.assertFalse("Read back should not be gone", c1.isGone()); Assert.assertEquals(t2, t1); Log.info("T3"); CCNTime t3 = updateAndLog(goneVersionName.toString(), c1, goneVersionName); Assert.assertTrue(VersioningProfile.isVersionOf(c1.getVersionedName(), testName)); Assert.assertEquals(t3, t0); Assert.assertTrue("Read back should be gone.", c1.isGone()); Log.info("T4"); t0 = saveAsGoneAndLog("GoneAgain", c0); Assert.assertTrue("Should be gone", c0.isGone()); Log.info("TSAG: Updating new object: {0}", testName); CollectionObject c2 = new CollectionObject(testName, tHandle2); Log.info("TSAG: Waiting for: {0}", testName); CCNTime t4 = waitForDataAndLog(testName.toString(), c2); Log.info("TSAG: Waited for: {0}", c2.getVersionedName()); Assert.assertTrue("Read back of " + c0.getVersionedName() + " should be gone, got " + c2.getVersionedName(), c2.isGone()); Assert.assertEquals(t4, t0); Log.info("TSAG: Leaving testSaveAsGone."); } finally { removeNamespace(testName); tHandle.close(); tHandle2.close(); } } @Test public void testUpdateDoesNotExist() throws Exception { ContentName testName = ContentName.fromNative(testHelper.getTestNamespace("testUpdateDoesNotExist"), collectionObjName); CCNHandle tHandle = CCNHandle.open(); try { Log.info("CCNNetworkObjectTest: Entering testUpdateDoesNotExist"); CCNStringObject so = new CCNStringObject(testName, handle); // so should catch exception thrown by underlying stream when it times out. Assert.assertFalse(so.available()); // try to pick up anything that happens to appear so.updateInBackground(); CCNStringObject sowrite = new CCNStringObject(testName, "Now we write something.", SaveType.RAW, tHandle); setupNamespace(testName); saveAndLog("testUpdateDoesNotExist: Delayed write", sowrite, null, "Now we write something."); Log.flush(); so.waitForData(); Assert.assertTrue(so.available()); Assert.assertEquals(so.string(), sowrite.string()); Assert.assertEquals(so.getVersionedName(), sowrite.getVersionedName()); Log.info("CCNNetworkObjectTest: Leaving testUpdateDoesNotExist"); Log.flush(); } finally { removeNamespace(testName); tHandle.close(); } } @Test public void testFirstSegmentInfo() throws Exception { // Testing for matching info about first segment. CCNHandle lput = CCNHandle.open(); CCNHandle lget = CCNHandle.open(); ContentName testName = ContentName.fromNative(testHelper.getTestNamespace("testFirstSegmentInfo"), stringObjName); try { CCNTime desiredVersion = CCNTime.now(); CCNStringObject so = new CCNStringObject(testName, "First value", SaveType.RAW, lput); setupNamespace(testName); saveAndLog("SpecifiedVersion", so, desiredVersion, "Time: " + desiredVersion); Assert.assertEquals("Didn't write correct version", desiredVersion, so.getVersion()); CCNStringObject ro = new CCNStringObject(testName, lget); ro.waitForData(); Assert.assertEquals("Didn't read correct version", desiredVersion, ro.getVersion()); Assert.assertEquals("Didn't match first segment number", so.firstSegmentNumber(), ro.firstSegmentNumber()); Assert.assertArrayEquals("Didn't match first segment digest", so.getFirstDigest(), ro.getFirstDigest()); } finally { removeNamespace(testName); lput.close(); lget.close(); } } static class CounterListener implements UpdateListener { protected Integer _callbackCounter = 0; public int getCounter() { return _callbackCounter; } public void newVersionAvailable(CCNNetworkObject<?> newVersion, boolean wasSave) { synchronized (_callbackCounter) { _callbackCounter++; if (Log.isLoggable(Level.INFO)) { Log.info("UPDATE CALLBACK: counter is " + _callbackCounter + " was save? " + wasSave); } } } } @Test public void testUpdateListener() throws Exception { SaveType saveType = SaveType.RAW; CCNHandle writeHandle = CCNHandle.open(); CCNHandle readHandle = CCNHandle.open(); ContentName testName = ContentName.fromNative(testHelper.getTestNamespace("testUpdateListener"), stringObjName); CounterListener ourListener = new CounterListener(); CCNStringObject readObject = new CCNStringObject(testName, null, null, readHandle); readObject.addListener(ourListener); setupNamespace(testName); CCNStringObject writeObject = new CCNStringObject(testName, "Something to listen to.", saveType, writeHandle); writeObject.save(); boolean result = readObject.update(); Assert.assertTrue(result); Assert.assertTrue(ourListener.getCounter() == 1); readObject.updateInBackground(); writeObject.save("New stuff! New stuff!"); synchronized(readObject) { if (ourListener.getCounter() == 1) readObject.wait(); } // For some reason, we're getting two updates on our updateInBackground... Assert.assertTrue(ourListener.getCounter() > 1); writeHandle.close(); readHandle.close(); } @Test public void testVeryLast() throws Exception { Log.info("CCNNetworkObjectTest: Entering testVeryLast -- dummy test to help track down blowup. Prefix {0}", testHelper.getClassNamespace()); Thread.sleep(1000); Log.info("CCNNetworkObjectTest: Leaving testVeryLast -- dummy test to help track down blowup. Prefix {0}", testHelper.getClassNamespace()); } public <T> CCNTime saveAndLog(String name, CCNNetworkObject<T> ecd, CCNTime version, T data) throws IOException { CCNTime oldVersion = ecd.getVersion(); ecd.save(version, data); Log.info("SAL: Saved " + name + ": " + ecd.getVersionedName() + " (" + ecd.getVersion() + ", updated from " + oldVersion + ")" + " gone? " + ecd.isGone() + " data: " + ecd); return ecd.getVersion(); } public <T> CCNTime saveAsGoneAndLog(String name, CCNNetworkObject<T> ecd) throws IOException { CCNTime oldVersion = ecd.getVersion(); ecd.saveAsGone(); Log.info("SAGAL Saved " + name + ": " + ecd.getVersionedName() + " (" + ecd.getVersion() + ", updated from " + oldVersion + ")" + " gone? " + ecd.isGone() + " data: " + ecd); return ecd.getVersion(); } public CCNTime waitForDataAndLog(String name, CCNNetworkObject<?> ecd) throws IOException { ecd.waitForData(); Log.info("WFDAL: Initial read " + name + ", name: " + ecd.getVersionedName() + " (" + ecd.getVersion() +")" + " gone? " + ecd.isGone() + " data: " + ecd); return ecd.getVersion(); } public CCNTime updateAndLog(String name, CCNNetworkObject<?> ecd, ContentName updateName) throws IOException { if ((null == updateName) ? ecd.update() : ecd.update(updateName, null)) Log.info("Updated " + name + ", to name: " + ecd.getVersionedName() + " (" + ecd.getVersion() +")" + " gone? " + ecd.isGone() + " data: " + ecd); else Log.info("UAL: No update found for " + name + ((null != updateName) ? (" at name " + updateName) : "") + ", still: " + ecd.getVersionedName() + " (" + ecd.getVersion() +")" + " gone? " + ecd.isGone() + " data: " + ecd); return ecd.getVersion(); } }
package org.jbehave.core.embedder; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Properties; import java.util.concurrent.*; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; import org.jbehave.core.ConfigurableEmbedder; import org.jbehave.core.Embeddable; import org.jbehave.core.configuration.Configuration; import org.jbehave.core.configuration.MostUsefulConfiguration; import org.jbehave.core.failures.BatchFailures; import org.jbehave.core.junit.AnnotatedEmbedderRunner; import org.jbehave.core.model.Story; import org.jbehave.core.model.StoryMaps; import org.jbehave.core.reporters.CrossReference; import org.jbehave.core.reporters.ReportsCount; import org.jbehave.core.reporters.StepdocReporter; import org.jbehave.core.reporters.StoryReporterBuilder; import org.jbehave.core.reporters.ViewGenerator; import org.jbehave.core.steps.CandidateSteps; import org.jbehave.core.steps.StepCollector.Stage; import org.jbehave.core.steps.StepFinder; import org.jbehave.core.steps.Stepdoc; /** * Represents an entry point to all of JBehave's functionality that is * embeddable into other launchers, such as IDEs or CLIs. */ public class Embedder { private Configuration configuration = new MostUsefulConfiguration(); private List<CandidateSteps> candidateSteps = new ArrayList<CandidateSteps>(); private EmbedderClassLoader classLoader = new EmbedderClassLoader(this.getClass().getClassLoader()); private EmbedderControls embedderControls = new EmbedderControls(); private List<String> metaFilters = Arrays.asList(); private Properties systemProperties = new Properties(); private StoryMapper storyMapper; private StoryRunner storyRunner; private EmbedderMonitor embedderMonitor; private ExecutorService executorService = createExecutorService(); public Embedder() { this(new StoryMapper(), new StoryRunner(), new PrintStreamEmbedderMonitor()); } public Embedder(StoryMapper storyMapper, StoryRunner storyRunner, EmbedderMonitor embedderMonitor) { this.storyMapper = storyMapper; this.storyRunner = storyRunner; this.embedderMonitor = embedderMonitor; } public void mapStoriesAsPaths(List<String> storyPaths) { EmbedderControls embedderControls = embedderControls(); if (embedderControls.skip()) { embedderMonitor.storiesSkipped(storyPaths); return; } processSystemProperties(); for (String storyPath : storyPaths) { Story story = storyRunner.storyOfPath(configuration, storyPath); embedderMonitor.mappingStory(storyPath, metaFilters); storyMapper.map(story, new MetaFilter("")); for (String filter : metaFilters) { storyMapper.map(story, new MetaFilter(filter)); } } generateMapsView(storyMapper.getStoryMaps()); } private void generateMapsView(StoryMaps storyMaps) { StoryReporterBuilder builder = configuration().storyReporterBuilder(); File outputDirectory = builder.outputDirectory(); Properties viewResources = builder.viewResources(); ViewGenerator viewGenerator = configuration().viewGenerator(); try { embedderMonitor.generatingMapsView(outputDirectory, storyMaps, viewResources); viewGenerator.generateMapsView(outputDirectory, storyMaps, viewResources); } catch (RuntimeException e) { embedderMonitor.mapsViewGenerationFailed(outputDirectory, storyMaps, viewResources, e); throw new ViewGenerationFailed(outputDirectory, storyMaps, viewResources, e); } } public void runAsEmbeddables(List<String> classNames) { EmbedderControls embedderControls = embedderControls(); if (embedderControls.skip()) { embedderMonitor.embeddablesSkipped(classNames); return; } BatchFailures batchFailures = new BatchFailures(); for (Embeddable embeddable : embeddables(classNames, classLoader())) { String name = embeddable.getClass().getName(); try { embedderMonitor.runningEmbeddable(name); embeddable.useEmbedder(this); embeddable.run(); } catch (Throwable e) { if (embedderControls.batch()) { // collect and postpone decision to throw exception batchFailures.put(name, e); } else { if (embedderControls.ignoreFailureInStories()) { embedderMonitor.embeddableFailed(name, e); } else { throw new RunningEmbeddablesFailed(name, e); } } } } if (embedderControls.batch() && batchFailures.size() > 0) { if (embedderControls.ignoreFailureInStories()) { embedderMonitor.batchFailed(batchFailures); } else { throw new RunningEmbeddablesFailed(batchFailures); } } } private List<Embeddable> embeddables(List<String> classNames, EmbedderClassLoader classLoader) { List<Embeddable> embeddables = new ArrayList<Embeddable>(); for (String className : classNames) { if (!classLoader.isAbstract(className)) { embeddables.add(classLoader.newInstance(Embeddable.class, className)); } } return embeddables; } public void runStoriesWithAnnotatedEmbedderRunner(String runnerClass, List<String> classNames) { List<AnnotatedEmbedderRunner> runners = annotatedEmbedderRunners(runnerClass, classNames, classLoader()); for (AnnotatedEmbedderRunner runner : runners) { try { Object annotatedInstance = runner.createTest(); if (annotatedInstance instanceof Embeddable) { ((Embeddable) annotatedInstance).run(); } else { embedderMonitor.annotatedInstanceNotOfType(annotatedInstance, Embeddable.class); } } catch (Throwable e) { throw new AnnotatedEmbedderRunFailed(runner, e); } } } private List<AnnotatedEmbedderRunner> annotatedEmbedderRunners(String runnerClassName, List<String> classNames, EmbedderClassLoader classLoader) { Class<?> runnerClass = loadClass(runnerClassName, classLoader); List<AnnotatedEmbedderRunner> runners = new ArrayList<AnnotatedEmbedderRunner>(); for (String annotatedClassName : classNames) { runners.add(newAnnotatedEmbedderRunner(runnerClass, annotatedClassName, classLoader)); } return runners; } private AnnotatedEmbedderRunner newAnnotatedEmbedderRunner(Class<?> runnerClass, String annotatedClassName, EmbedderClassLoader classLoader) { try { Class<?> annotatedClass = loadClass(annotatedClassName, classLoader); return (AnnotatedEmbedderRunner) runnerClass.getConstructor(Class.class).newInstance(annotatedClass); } catch (Exception e) { throw new AnnotatedEmbedderRunnerInstantiationFailed(runnerClass, annotatedClassName, classLoader, e); } } private Class<?> loadClass(String className, EmbedderClassLoader classLoader) { try { return classLoader.loadClass(className); } catch (ClassNotFoundException e) { throw new ClassLoadingFailed(className, classLoader, e); } } public void runStoriesAsPaths(List<String> storyPaths) { processSystemProperties(); final EmbedderControls embedderControls = embedderControls(); if (embedderControls.skip()) { embedderMonitor.storiesSkipped(storyPaths); return; } final Configuration configuration = configuration(); final List<CandidateSteps> candidateSteps = candidateSteps(); storyRunner.runBeforeOrAfterStories(configuration, candidateSteps, Stage.BEFORE); final BatchFailures batchFailures = new BatchFailures(); configureReporterBuilder(configuration); final MetaFilter filter = new MetaFilter(StringUtils.join(metaFilters, " "), embedderMonitor); List<Future<Throwable>> futures = new ArrayList<Future<Throwable>>(); for (final String storyPath : storyPaths) { enqueueStory(embedderControls, configuration, candidateSteps, batchFailures, filter, futures, storyPath, storyRunner.storyOfPath(configuration, storyPath)); } waitUntilAllDone(futures); checkForFailures(futures); storyRunner.runBeforeOrAfterStories(configuration, candidateSteps, Stage.AFTER); if (embedderControls.batch() && batchFailures.size() > 0) { if (embedderControls.ignoreFailureInStories()) { embedderMonitor.batchFailed(batchFailures); } else { throw new RunningStoriesFailed(batchFailures); } } if (embedderControls.generateViewAfterStories()) { generateReportsView(); } } /** * Enqueue a story to run * * @param embedderControls the embedder controls to use * @param configuration the configuration to use * @param candidateSteps the candidate steps to use * @param batchFailures where to put batch failures * @param filter meta filter (if appl) * @param futures the list of futures if tracking is needed * @param storyPath the path for the story * @param story the parsed story itself * @return a future<throwable> for the story (null if not failing). */ public Future<Throwable> enqueueStory(EmbedderControls embedderControls, Configuration configuration, List<CandidateSteps> candidateSteps, BatchFailures batchFailures, MetaFilter filter, List<Future<Throwable>> futures, String storyPath, Story story) { EnqueuedStory enqueuedStory = makeEnqueuedStory(embedderControls, configuration, candidateSteps, batchFailures, filter, storyPath, story); return submit(futures, enqueuedStory); } public Future<Throwable> enqueueStory(BatchFailures batchFailures, MetaFilter filter, List<Future<Throwable>> futures, String storyPath, Story story) { EnqueuedStory enqueuedStory = makeEnqueuedStory(embedderControls, configuration, candidateSteps, batchFailures, filter, storyPath, story); return submit(futures, enqueuedStory); } private Future<Throwable> submit(List<Future<Throwable>> futures, EnqueuedStory enqueuedStory) { Future<Throwable> submit = executorService.submit(enqueuedStory); futures.add(submit); return submit; } protected EnqueuedStory makeEnqueuedStory(EmbedderControls embedderControls, Configuration configuration, List<CandidateSteps> candidateSteps, BatchFailures batchFailures, MetaFilter filter, String storyPath, Story story) { return new EnqueuedStory(storyPath, configuration, candidateSteps, story, filter, embedderControls, batchFailures, embedderMonitor, storyRunner); } /** * Creates a {@link ThreadPoolExecutor} using the number of threads defined * in the {@link EmbedderControls#threads()} * * @return An ExecutorService */ protected ExecutorService createExecutorService() { int threads = embedderControls.threads(); if (threads == 1) { // this is necessary for situations where people use the // PerStoriesWebDriverSteps class. return new NonThreadingExecutorService(); } else { return Executors.newFixedThreadPool(threads); } } private void waitUntilAllDone(List<Future<Throwable>> futures) { boolean allDone = false; while (!allDone) { allDone = true; for (Future<Throwable> future : futures) { if (!future.isDone()) { allDone = false; try { Thread.sleep(100); } catch (InterruptedException e) { } break; } } } } private void checkForFailures(List<Future<Throwable>> futures) { try { BatchFailures failures = new BatchFailures(); for (Future<Throwable> future : futures) { Throwable failure = future.get(); if (failure != null) { failures.put(future.toString(), failure); } } if (failures.size() > 0) { throw new RunningStoriesFailed(failures); } } catch (InterruptedException e) { throw new RuntimeException(e); } catch (ExecutionException e) { throw new RuntimeException(e); } } private void configureReporterBuilder(Configuration configuration) { StoryReporterBuilder reporterBuilder = configuration.storyReporterBuilder(); reporterBuilder.withMultiThreading(embedderControls.threads() > 1); configuration.useStoryReporterBuilder(reporterBuilder); } public void generateReportsView() { StoryReporterBuilder builder = configuration().storyReporterBuilder(); File outputDirectory = builder.outputDirectory(); List<String> formatNames = builder.formatNames(true); generateReportsView(outputDirectory, formatNames, builder.viewResources()); } public void generateReportsView(File outputDirectory, List<String> formats, Properties viewResources) { EmbedderControls embedderControls = embedderControls(); if (embedderControls.skip()) { embedderMonitor.reportsViewNotGenerated(); return; } ViewGenerator viewGenerator = configuration().viewGenerator(); try { embedderMonitor.generatingReportsView(outputDirectory, formats, viewResources); viewGenerator.generateReportsView(outputDirectory, formats, viewResources); } catch (RuntimeException e) { embedderMonitor.reportsViewGenerationFailed(outputDirectory, formats, viewResources, e); throw new ViewGenerationFailed(outputDirectory, formats, viewResources, e); } ReportsCount count = viewGenerator.getReportsCount(); embedderMonitor.reportsViewGenerated(count); if (!embedderControls.ignoreFailureInView() && count.getScenariosFailed() > 0) { throw new RunningStoriesFailed(count.getStories(), count.getScenarios(), count.getScenariosFailed()); } } public void generateCrossReference() { StoryReporterBuilder builder = configuration().storyReporterBuilder(); CrossReference crossReference = builder.crossReference(); if (crossReference != null) { crossReference.outputToFiles(builder); } } public void reportStepdocs() { reportStepdocs(configuration(), candidateSteps()); } public void reportStepdocsAsEmbeddables(List<String> classNames) { EmbedderControls embedderControls = embedderControls(); if (embedderControls.skip()) { embedderMonitor.embeddablesSkipped(classNames); return; } for (Embeddable embeddable : embeddables(classNames, classLoader())) { if (embeddable instanceof ConfigurableEmbedder) { ConfigurableEmbedder configurableEmbedder = (ConfigurableEmbedder) embeddable; reportStepdocs(configurableEmbedder.configuration(), configurableEmbedder.candidateSteps()); } else { embedderMonitor.embeddableNotConfigurable(embeddable.getClass().getName()); } } } public void reportStepdocs(Configuration configuration, List<CandidateSteps> candidateSteps) { StepFinder finder = configuration.stepFinder(); StepdocReporter reporter = configuration.stepdocReporter(); List<Object> stepsInstances = finder.stepsInstances(candidateSteps); reporter.stepdocs(finder.stepdocs(candidateSteps), stepsInstances); } public void reportMatchingStepdocs(String stepAsString) { Configuration configuration = configuration(); List<CandidateSteps> candidateSteps = candidateSteps(); StepFinder finder = configuration.stepFinder(); StepdocReporter reporter = configuration.stepdocReporter(); List<Stepdoc> matching = finder.findMatching(stepAsString, candidateSteps); List<Object> stepsInstances = finder.stepsInstances(candidateSteps); reporter.stepdocsMatching(stepAsString, matching, stepsInstances); } public void processSystemProperties() { Properties properties = systemProperties(); embedderMonitor.processingSystemProperties(properties); if (!properties.isEmpty()) { for (Object key : properties.keySet()) { String name = (String) key; String value = properties.getProperty(name); System.setProperty(name, value); embedderMonitor.systemPropertySet(name, value); } } } public EmbedderClassLoader classLoader() { return classLoader; } public Configuration configuration() { return configuration; } public List<CandidateSteps> candidateSteps() { return candidateSteps; } public EmbedderControls embedderControls() { return embedderControls; } public EmbedderMonitor embedderMonitor() { return embedderMonitor; } public List<String> metaFilters() { return metaFilters; } public StoryRunner storyRunner() { return storyRunner; } public Properties systemProperties() { return systemProperties; } public void useClassLoader(EmbedderClassLoader classLoader) { this.classLoader = classLoader; } public void useConfiguration(Configuration configuration) { this.configuration = configuration; } public void useCandidateSteps(List<CandidateSteps> candidateSteps) { this.candidateSteps = candidateSteps; } public void useEmbedderControls(EmbedderControls embedderControls) { this.embedderControls = embedderControls; } public void useEmbedderMonitor(EmbedderMonitor embedderMonitor) { this.embedderMonitor = embedderMonitor; } public void useMetaFilters(List<String> metaFilters) { this.metaFilters = metaFilters; } public void useStoryRunner(StoryRunner storyRunner) { this.storyRunner = storyRunner; } public void useSystemProperties(Properties systemProperties) { this.systemProperties = systemProperties; } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); } @SuppressWarnings("serial") public static class ClassLoadingFailed extends RuntimeException { public ClassLoadingFailed(String className, EmbedderClassLoader classLoader, Throwable cause) { super("Failed to load class " + className + " with classLoader " + classLoader, cause); } } @SuppressWarnings("serial") public static class AnnotatedEmbedderRunnerInstantiationFailed extends RuntimeException { public AnnotatedEmbedderRunnerInstantiationFailed(Class<?> runnerClass, String annotatedClassName, EmbedderClassLoader classLoader, Throwable cause) { super("Failed to instantiate annotated embedder runner " + runnerClass + " with annotatedClassName " + annotatedClassName + " and classLoader " + classLoader, cause); } } @SuppressWarnings("serial") public static class AnnotatedEmbedderRunFailed extends RuntimeException { public AnnotatedEmbedderRunFailed(AnnotatedEmbedderRunner runner, Throwable cause) { super("Annotated embedder run failed with runner " + runner.toString(), cause); } } @SuppressWarnings("serial") public static class RunningEmbeddablesFailed extends RuntimeException { public RunningEmbeddablesFailed(String name, Throwable cause) { super("Failures in running embeddable " + name, cause); } public RunningEmbeddablesFailed(BatchFailures batchFailures) { super("Failures in running embeddables in batch: " + batchFailures); } } @SuppressWarnings("serial") public static class RunningStoriesFailed extends RuntimeException { public RunningStoriesFailed(int stories, int scenarios, int failedScenarios) { super("Failures in running " + stories + " stories containing " + scenarios + " scenarios (of which " + failedScenarios + " failed)"); } public RunningStoriesFailed(BatchFailures failures) { super("Failures in running stories in batch: " + failures); } public RunningStoriesFailed(String name, Throwable cause) { super("Failures in running stories " + name, cause); } } @SuppressWarnings("serial") public static class ViewGenerationFailed extends RuntimeException { public ViewGenerationFailed(File outputDirectory, List<String> formats, Properties viewResources, RuntimeException cause) { super("View generation failed to " + outputDirectory + " for formats " + formats + " and resources " + viewResources, cause); } public ViewGenerationFailed(File outputDirectory, StoryMaps storyMaps, Properties viewResources, RuntimeException cause) { super("View generation failed to " + outputDirectory + " for story maps " + storyMaps + " for resources " + viewResources, cause); } public ViewGenerationFailed(File outputDirectory, Properties viewResources, RuntimeException e) { // TODO Auto-generated constructor stub } } /** * Non-threading ExecutorService for situations where thread count = 1 */ public static class NonThreadingExecutorService implements ExecutorService { public void shutdown() { throw new UnsupportedOperationException(); } public List<Runnable> shutdownNow() { throw new UnsupportedOperationException(); } public boolean isShutdown() { throw new UnsupportedOperationException(); } public boolean isTerminated() { throw new UnsupportedOperationException(); } public boolean awaitTermination(long l, TimeUnit timeUnit) throws InterruptedException { throw new UnsupportedOperationException(); } public <T> Future<T> submit(Callable<T> tCallable) { final Object[] rc = new Object[1]; try { rc[0] = tCallable.call(); } catch (Exception e) { rc[0] = e; } return new Future<T>() { public boolean cancel(boolean b) { throw new UnsupportedOperationException(); } public boolean isCancelled() { throw new UnsupportedOperationException(); } public boolean isDone() { return true; } public T get() throws InterruptedException, ExecutionException { return (T) rc[0]; } public T get(long l, TimeUnit timeUnit) throws InterruptedException, ExecutionException, TimeoutException { return get(); } }; } public <T> Future<T> submit(Runnable runnable, T t) { throw new UnsupportedOperationException(); } public Future<?> submit(Runnable runnable) { throw new UnsupportedOperationException(); } public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> callables) throws InterruptedException { throw new UnsupportedOperationException(); } public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> callables, long l, TimeUnit timeUnit) throws InterruptedException { throw new UnsupportedOperationException(); } public <T> T invokeAny(Collection<? extends Callable<T>> callables) throws InterruptedException, ExecutionException { throw new UnsupportedOperationException(); } public <T> T invokeAny(Collection<? extends Callable<T>> callables, long l, TimeUnit timeUnit) throws InterruptedException, ExecutionException, TimeoutException { throw new UnsupportedOperationException(); } public void execute(Runnable runnable) { throw new UnsupportedOperationException(); } } public static class EnqueuedStory implements Callable<Throwable> { private final String storyPath; private final Configuration configuration; private final List<CandidateSteps> candidateSteps; private final Story story; private final MetaFilter filter; private final EmbedderControls embedderControls; private final BatchFailures batchFailures; private final EmbedderMonitor embedderMonitor; private final StoryRunner storyRunner; public EnqueuedStory(String storyPath, Configuration configuration, List<CandidateSteps> candidateSteps, Story story, MetaFilter filter, EmbedderControls embedderControls, BatchFailures batchFailures, EmbedderMonitor embedderMonitor, StoryRunner storyRunner) { this.storyPath = storyPath; this.configuration = configuration; this.candidateSteps = candidateSteps; this.story = story; this.filter = filter; this.embedderControls = embedderControls; this.batchFailures = batchFailures; this.embedderMonitor = embedderMonitor; this.storyRunner = storyRunner; } public Throwable call() throws Exception { try { embedderMonitor.runningStory(storyPath); storyRunner.run(configuration, candidateSteps, story, filter); } catch (Throwable e) { if (embedderControls.batch()) { // collect and postpone decision to throw exception batchFailures.put(storyPath, e); } else { if (embedderControls.ignoreFailureInStories()) { embedderMonitor.storyFailed(storyPath, e); } else { return new RunningStoriesFailed(storyPath, e); } } } return null; } } }
package org.eclipse.jetty.util; import java.util.Locale; import java.util.TimeZone; import java.util.concurrent.TimeUnit; import org.eclipse.jetty.toolchain.test.AdvancedRunner; import org.eclipse.jetty.toolchain.test.annotation.Slow; import org.hamcrest.Matchers; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; /** * Util meta Tests. */ @RunWith(AdvancedRunner.class) public class DateCacheTest { @Test @Slow public void testDateCache() throws Exception { //@WAS: Test t = new Test("org.eclipse.jetty.util.DateCache"); // 012345678901234567890123456789 DateCache dc = new DateCache("EEE, dd MMM yyyy HH:mm:ss zzz ZZZ",Locale.US); dc.setTimeZone(TimeZone.getTimeZone("GMT")); Thread.sleep(2000); long now=System.currentTimeMillis(); long end=now+3000; String f=dc.format(now); String last=f; int hits=0; int misses=0; while (now<end) { last=f; f=dc.format(now); // System.err.printf("%s %s%n",f,last==f); if (last==f) hits++; else misses++; TimeUnit.MILLISECONDS.sleep(100); now=System.currentTimeMillis(); } Assert.assertThat(hits,Matchers.greaterThan(misses)); } }
package org.accada.epcis.repository; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.text.ParseException; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.accada.epcis.soapapi.ActionType; import org.accada.epcis.soapapi.AggregationEventType; import org.accada.epcis.soapapi.ArrayOfString; import org.accada.epcis.soapapi.BusinessLocationType; import org.accada.epcis.soapapi.BusinessTransactionType; import org.accada.epcis.soapapi.DuplicateSubscriptionException; import org.accada.epcis.soapapi.EPC; import org.accada.epcis.soapapi.EPCISServicePortType; import org.accada.epcis.soapapi.EmptyParms; import org.accada.epcis.soapapi.EventListType; import org.accada.epcis.soapapi.GetSubscriptionIDs; import org.accada.epcis.soapapi.ImplementationException; import org.accada.epcis.soapapi.ImplementationExceptionSeverity; import org.accada.epcis.soapapi.InvalidURIException; import org.accada.epcis.soapapi.NoSuchNameException; import org.accada.epcis.soapapi.NoSuchSubscriptionException; import org.accada.epcis.soapapi.ObjectEventType; import org.accada.epcis.soapapi.Poll; import org.accada.epcis.soapapi.QuantityEventType; import org.accada.epcis.soapapi.QueryParam; import org.accada.epcis.soapapi.QueryParameterException; import org.accada.epcis.soapapi.QueryResults; import org.accada.epcis.soapapi.QueryResultsBody; import org.accada.epcis.soapapi.QueryTooLargeException; import org.accada.epcis.soapapi.ReadPointType; import org.accada.epcis.soapapi.Subscribe; import org.accada.epcis.soapapi.SubscribeNotPermittedException; import org.accada.epcis.soapapi.SubscriptionControls; import org.accada.epcis.soapapi.SubscriptionControlsException; import org.accada.epcis.soapapi.TransactionEventType; import org.accada.epcis.soapapi.Unsubscribe; import org.accada.epcis.soapapi.ValidationException; import org.accada.epcis.soapapi.VoidHolder; import org.accada.epcis.utils.TimeParser; import org.apache.axis.MessageContext; import org.apache.axis.message.MessageElement; import org.apache.axis.types.URI; import org.apache.log4j.Logger; /** * EPCIS Query Interface implementation. Converts the invocations by axis to SQL * queries and returns the results to axis. Implementation is highly specific to * the database schema, so beware. The responses generated by the server stubs * are EPCIS standard compliant. However, the results will always be ordered * according to type, not in random order as the standard would allow. Our * *client*, however, will only work with our server, because it relies on the * fact that the answers are ordered. Using it with servers that do not order * the results may lead to arbitrary behaviour of our client (most likely lost * results). * * @author David Gubler * @author Alain Remund * @author Arthur van Dorp * @author Marco Steybe */ public class EpcisQueryInterface implements EPCISServicePortType { private static final Logger LOG = Logger.getLogger(EpcisQueryInterface.class); /** * The version of the standard that this service is implementing. */ private static final String STD_VERSION = "1.0"; /** * The version of this service implementation. */ private static final String VDR_VERSION = "http: /** * The connection to the database. */ private Connection dbconnection = null; /** * The database dependent identifier quotation sign. */ private String delimiter; /** * Before returning the Results of the query, it checks if the set is too * large. This value can be set by Query-Parameters. */ private int maxEventCount; /** * The names of all the implemented queries. */ private final Set<String> queryNames = new HashSet<String>() { private static final long serialVersionUID = -3868728341409854448L; { // TODO: add SimpleMasterDataQuery once implemented. add("SimpleEventQuery"); } }; /** * Basic SQL query string for object events. */ private String objectEventQueryBase = "SELECT DISTINCT " + "`event_ObjectEvent`.id, eventTime, recordTime, " + "eventTimeZoneOffset, action, " + "`voc_BizStep`.uri AS bizStep, " + "`voc_Disposition`.uri AS disposition, " + "`voc_ReadPoint`.uri AS readPoint, " + "`voc_BizLoc`.uri AS bizLocation " + "FROM `event_ObjectEvent` " + "LEFT JOIN `voc_BizStep` ON `event_ObjectEvent`.bizStep = `voc_BizStep`.id " + "LEFT JOIN `voc_Disposition` ON `event_ObjectEvent`.disposition = `voc_Disposition`.id " + "LEFT JOIN `voc_ReadPoint` ON `event_ObjectEvent`.readPoint = `voc_ReadPoint`.id " + "LEFT JOIN `voc_BizLoc` ON `event_ObjectEvent`.bizLocation = `voc_BizLoc`.id " + "LEFT JOIN `event_ObjectEvent_extensions` ON `event_ObjectEvent`.id = `event_ObjectEvent_extensions`.event_id " + "WHERE 1"; /** * Basic SQL query string for aggregation events. */ // TODO marco: query as for objectevent (extensions)! private String aggregationEventQueryBase = "SELECT DISTINCT " + "`event_AggregationEvent`.id, eventTime, recordTime, " + "eventTimeZoneOffset, parentID, action, " + "`voc_BizStep`.uri AS bizStep, " + "`voc_Disposition`.uri AS disposition, " + "`voc_ReadPoint`.uri AS readPoint, " + "`voc_BizLoc`.uri AS bizLocation " + "FROM `event_AggregationEvent` " + "LEFT JOIN `voc_BizStep` ON `event_AggregationEvent`.bizStep = `voc_BizStep`.id " + "LEFT JOIN `voc_Disposition` ON `event_AggregationEvent`.disposition = `voc_Disposition`.id " + "LEFT JOIN `voc_ReadPoint` ON `event_AggregationEvent`.readPoint = `voc_ReadPoint`.id " + "LEFT JOIN `voc_BizLoc` ON `event_AggregationEvent`.bizLocation = `voc_BizLoc`.id " + "WHERE 1 "; /** * Basic SQL query string for quantity events. */ // TODO marco: query as for objectevent (extensions)! private String quantityEventQueryBase = "SELECT DISTINCT " + "`event_QuantityEvent`.id, eventTime, recordTime, eventTimeZoneOffset, " + "`voc_EPCClass`.uri AS epcClass, quantity, " + "`voc_BizStep`.uri AS bizStep, " + "`voc_Disposition`.uri AS disposition, " + "`voc_ReadPoint`.uri AS readPoint, " + "`voc_BizLoc`.uri AS bizLocation " + "FROM `event_QuantityEvent` " + "LEFT JOIN `voc_BizStep` ON `event_QuantityEvent`.bizStep = `voc_BizStep`.id " + "LEFT JOIN `voc_Disposition` ON `event_QuantityEvent`.disposition = `voc_Disposition`.id " + "LEFT JOIN `voc_ReadPoint` ON `event_QuantityEvent`.readPoint = `voc_ReadPoint`.id " + "LEFT JOIN `voc_BizLoc` ON `event_QuantityEvent`.bizLocation = `voc_BizLoc`.id " + "LEFT JOIN `voc_EPCClass` ON `event_QuantityEvent`.epcClass = `voc_EPCClass`.id " + "WHERE 1 "; /** * Basic SQL query string for transaction events. */ // TODO marco: query as for objectevent (extensions)! private String transactionEventQueryBase = "SELECT DISTINCT " + "`event_TransactionEvent`.id, eventTime, recordTime, " + "eventTimeZoneOffset, action, parentID, " + "`voc_BizStep`.uri AS bizStep, " + "`voc_Disposition`.uri AS disposition, " + "`voc_ReadPoint`.uri AS readPoint, " + "`voc_BizLoc`.uri AS bizLocation " + "FROM `event_TransactionEvent` " + "LEFT JOIN `voc_BizStep` ON `event_TransactionEvent`.bizStep = `voc_BizStep`.id " + "LEFT JOIN `voc_Disposition` ON `event_TransactionEvent`.disposition = `voc_Disposition`.id " + "LEFT JOIN `voc_ReadPoint` ON `event_TransactionEvent`.readPoint = `voc_ReadPoint`.id " + "LEFT JOIN `voc_BizLoc` ON `event_TransactionEvent`.bizLocation = `voc_BizLoc`.id " + "WHERE 1 "; public EpcisQueryInterface() { LOG.info("EpcisQueryInterface invoked."); MessageContext msgContext = MessageContext.getCurrentContext(); delimiter = (String) msgContext.getProperty("delimiter"); dbconnection = (Connection) msgContext.getProperty("dbconnection"); } /** * Returns whether subscriptionID already exists in DB. * * @param subscrId * The id to be looked up. * @return <code>true</code> if subscriptionID already exists in DB, * <code>false</code> otherwise. * @throws SQLException * If a problem with the database occured. * @throws ImplementationException * If a problem with the EPCIS implementation occured. */ private boolean fetchExistsSubscriptionId(final String subscrId) throws SQLException, ImplementationException { String query = "SELECT EXISTS(SELECT subscriptionid FROM subscription WHERE subscriptionid = (?))"; PreparedStatement pstmt = dbconnection.prepareStatement(query); pstmt.setString(1, subscrId); LOG.debug("QUERY: " + query); LOG.debug(" query param 1: " + subscrId); ResultSet rs = pstmt.executeQuery(); rs.first(); Boolean result = rs.getBoolean(1); rs.close(); return result.booleanValue(); } /** * Returns all EPCs associated to a certain event_id. * * @param tableName * The SQL name of the table to be searched * @param eventId * is typically an 64bit integer. We use string here to avoid * java vs. SQL type problems. * @return EPCs beloning to event_id * @throws SQLException * If an error with the database occured. */ private EPC[] fetchEPCs(final String tableName, final int eventId) throws SQLException { String query = "SELECT DISTINCT epc FROM " + delimiter + tableName + delimiter + " WHERE " + delimiter + "event_id" + delimiter + " = " + eventId; LOG.debug("QUERY: " + query); Statement stmt = dbconnection.createStatement(); ResultSet rs = stmt.executeQuery(query); List<EPC> epcList = new ArrayList<EPC>(); while (rs.next()) { EPC epc = new EPC(rs.getString("epc")); epcList.add(epc); } EPC[] epcs = new EPC[epcList.size()]; epcs = epcList.toArray(epcs); return epcs; } /** * Retreives all MessageElement, i.e. all fieldname extensions for the given * event. * * @param tableName * The name of the table with the field extensions of the event. * @param eventId * The ID of the event * @return All MessageElement (fieldname extensions) associated with the * given eventId. * @throws SQLException * If an error with the database occured. */ private MessageElement[] fetchMessageElements(final String tableName, final int eventId) throws SQLException { String query = "SELECT * FROM " + delimiter + tableName + delimiter + " WHERE " + delimiter + "event_id" + delimiter + " = " + eventId; LOG.debug("QUERY: " + query); Statement stmt = dbconnection.createStatement(); ResultSet rs = stmt.executeQuery(query); List<MessageElement> meList = new ArrayList<MessageElement>(); while (rs.next()) { String fieldname = rs.getString("fieldname"); String[] parts = fieldname.split(" if (parts.length != 2) { throw new SQLException("Column 'fieldname' in table '" + tableName + "' has invalid format: " + fieldname); } String namespace = parts[0]; String localPart = parts[1]; String prefix = rs.getString("prefix"); String value = rs.getString("intValue"); if (value == null) { value = rs.getString("floatValue"); } if (value == null) { value = rs.getString("strValue"); } if (value == null) { value = rs.getString("dateValue"); } if (value == null) { throw new SQLException("All value columns in '" + tableName + "' are null."); } MessageElement me = new MessageElement(localPart, prefix, namespace); me.setValue(value); LOG.debug("message element resolved to " + me.toString()); meList.add(me); } MessageElement[] any = new MessageElement[meList.size()]; any = meList.toArray(any); return any; } /** * Returns all bizTransactions associated to a certain event_id. * * @param tableName * The SQL name of the table to be searched. * @param eventId * Typically an 64bit integer to identify the event. * @return bizTransactions associated to event_id * @throws SQLException * DB problem. * @throws ImplementationException * Several problems get matched to this exception. */ private BusinessTransactionType[] fetchBizTransactions( final String tableName, final int eventId) throws SQLException, ImplementationException { String query = "SELECT DISTINCT " + "`voc_BizTrans`.uri, `voc_BizTransType`.uri AS `typeuri`" + "FROM ((`BizTransaction` JOIN `" + tableName + "` ON `BizTransaction`.id = `" + tableName + "`.`bizTrans_id`)" + "JOIN `voc_BizTrans` ON `BizTransaction`.`bizTrans` = `voc_BizTrans`.id)" + " LEFT OUTER JOIN `voc_BizTransType` ON `BizTransaction`.`type` = `voc_BizTransType`.id" + " WHERE `" + tableName + "`.event_id = " + eventId; LOG.debug("QUERY: " + query); Statement stmt = dbconnection.createStatement(); ResultSet rs = stmt.executeQuery(query.replaceAll("`", delimiter)); List<BusinessTransactionType> bizTransList = new ArrayList<BusinessTransactionType>(); while (rs.next()) { String uriString = null; uriString = rs.getString("uri"); URI uri = stringToUri(uriString); BusinessTransactionType btrans = new BusinessTransactionType(uri); uriString = rs.getString("typeuri"); if (uriString != null) { uri = stringToUri(uriString); btrans.setType(uri); } bizTransList.add(btrans); } BusinessTransactionType[] bizTrans = new BusinessTransactionType[bizTransList.size()]; bizTrans = bizTransList.toArray(bizTrans); return bizTrans; } /** * Convert a string to a URI. Exceptions are caught and a meaningful * ImplementationException is thrown instead. This method works on axis * URIs, not Java URIs. Make sure you have the right imports. * * @param uriString * String to convert to URI * @return URI * @throws ImplementationException * Thrown when string not in URI format. */ private URI stringToUri(final String uriString) throws ImplementationException { try { if (uriString == null) { return null; } URI uri = new URI(uriString); return uri; } catch (URI.MalformedURIException e) { String msg = "Malformed URI value: " + uriString; LOG.error(msg, e); ImplementationException iex = new ImplementationException(); iex.setReason(msg); iex.setStackTrace(e.getStackTrace()); iex.setSeverity(ImplementationExceptionSeverity.ERROR); throw iex; } } private ObjectEventType[] runObjectEventQuery( final PreparedStatement objectEventQuery) throws SQLException, ImplementationException { if (objectEventQuery == null) { return null; } // Calendar needed for converting timestamps Calendar cal = Calendar.getInstance(); // run the query and get all ObjectEvents ResultSet rs = objectEventQuery.executeQuery(); List<ObjectEventType> objectEventList = new ArrayList<ObjectEventType>(); while (rs.next()) { ObjectEventType objectEvent = new ObjectEventType(); int eventId = rs.getInt("id"); // set EventTime, RecordTime, and EventTimezoneOffset cal.setTime(rs.getTimestamp("eventTime")); objectEvent.setEventTime((Calendar) cal.clone()); cal.setTime(rs.getTimestamp("recordTime")); objectEvent.setRecordTime((Calendar) cal.clone()); objectEvent.setEventTimeZoneOffset(rs.getString("eventTimeZoneOffset")); // set action ActionType action = ActionType.fromString(rs.getString("action")); objectEvent.setAction(action); // set all URIs objectEvent.setBizStep(stringToUri(rs.getString("bizStep"))); objectEvent.setDisposition(stringToUri(rs.getString("disposition"))); if (rs.getString("readPoint") != null) { ReadPointType rp = new ReadPointType(); rp.setId(stringToUri(rs.getString("readPoint"))); objectEvent.setReadPoint(rp); } if (rs.getString("bizLocation") != null) { BusinessLocationType blt = new BusinessLocationType(); blt.setId(stringToUri(rs.getString("bizLocation"))); objectEvent.setBizLocation(blt); } // set business transactions BusinessTransactionType[] btt = fetchBizTransactions( "event_ObjectEvent_bizTrans", eventId); objectEvent.setBizTransactionList(btt); // set EPCs EPC[] epcs = fetchEPCs("event_ObjectEvent_EPCs", eventId); objectEvent.setEpcList(epcs); // set field extensions MessageElement[] any = fetchMessageElements( "event_ObjectEvent_extensions", eventId); objectEvent.set_any(any); objectEventList.add(objectEvent); } rs.close(); ObjectEventType[] objectEvents = {}; objectEvents = objectEventList.toArray(objectEvents); return objectEvents; } private AggregationEventType[] runAggregationEventQuery( final PreparedStatement aggregationEventQuery) throws SQLException, ImplementationException { if (aggregationEventQuery == null) { return null; } // Calendar needed for converting timestamps Calendar cal = Calendar.getInstance(); // run the query and get all AggregationEvents ResultSet rs = aggregationEventQuery.executeQuery(); List<AggregationEventType> aggrEventList = new ArrayList<AggregationEventType>(); while (rs.next()) { AggregationEventType aggrEvent = new AggregationEventType(); int eventId = rs.getInt("id"); // set EventTime, RecordTime, and EventTimezoneOffset cal.setTime(rs.getTimestamp("eventTime")); aggrEvent.setEventTime((Calendar) cal.clone()); cal.setTime(rs.getTimestamp("recordTime")); aggrEvent.setRecordTime((Calendar) cal.clone()); aggrEvent.setEventTimeZoneOffset(rs.getString("eventTimeZoneOffset")); // set action ActionType action = ActionType.fromString(rs.getString("action")); aggrEvent.setAction(action); // set all URIs aggrEvent.setParentID(stringToUri(rs.getString("parentID"))); aggrEvent.setBizStep(stringToUri(rs.getString("bizStep"))); aggrEvent.setDisposition(stringToUri(rs.getString("disposition"))); if (rs.getString("readPoint") != null) { ReadPointType rpt = new ReadPointType(); rpt.setId(stringToUri(rs.getString("readPoint"))); aggrEvent.setReadPoint(rpt); } if (rs.getString("bizLocation") != null) { BusinessLocationType blt = new BusinessLocationType(); blt.setId(stringToUri(rs.getString("bizLocation"))); aggrEvent.setBizLocation(blt); } // set business transactions BusinessTransactionType[] bizTrans = fetchBizTransactions( "event_AggregationEvent_bizTrans", eventId); aggrEvent.setBizTransactionList(bizTrans); // set associated EPCs EPC[] epcs = fetchEPCs("event_AggregationEvent_EPCs", eventId); aggrEvent.setChildEPCs(epcs); // TODO: marco: fetchMessageElements() aggrEventList.add(aggrEvent); } rs.close(); AggregationEventType[] aggrEvents = new AggregationEventType[aggrEventList.size()]; aggrEvents = aggrEventList.toArray(aggrEvents); return aggrEvents; } private QuantityEventType[] runQuantityEventQuery( final PreparedStatement quantityEventQuery) throws SQLException, ImplementationException { if (quantityEventQuery == null) { return null; } // Calendar needed for converting timestamps Calendar cal = Calendar.getInstance(); // run the query and get all QuantityEvents ResultSet rs = quantityEventQuery.executeQuery(); List<QuantityEventType> quantEventList = new ArrayList<QuantityEventType>(); while (rs.next()) { QuantityEventType quantEvent = new QuantityEventType(); int eventId = rs.getInt("id"); // set EventTime, RecordTime, and EventTimezoneOffset cal.setTime(rs.getTimestamp("eventTime")); quantEvent.setEventTime((Calendar) cal.clone()); cal.setTime(rs.getTimestamp("recordTime")); quantEvent.setRecordTime((Calendar) cal.clone()); quantEvent.setEventTimeZoneOffset(rs.getString("eventTimeZoneOffset")); // set EPCClass quantEvent.setEpcClass(stringToUri(rs.getString("epcClass"))); // set quantity quantEvent.setQuantity(rs.getInt("quantity")); // set all URIs quantEvent.setBizStep(stringToUri(rs.getString("bizStep"))); quantEvent.setDisposition(stringToUri(rs.getString("disposition"))); if (rs.getString("readPoint") != null) { ReadPointType rpt = new ReadPointType(); rpt.setId(stringToUri(rs.getString("readPoint"))); quantEvent.setReadPoint(rpt); } if (rs.getString("bizLocation") != null) { BusinessLocationType blt = new BusinessLocationType(); blt.setId(stringToUri(rs.getString("bizLocation"))); quantEvent.setBizLocation(blt); } // set business transactions BusinessTransactionType[] bizTrans = fetchBizTransactions( "event_QuantityEvent_bizTrans", eventId); quantEvent.setBizTransactionList(bizTrans); quantEventList.add(quantEvent); } rs.close(); QuantityEventType[] quantEvents = new QuantityEventType[quantEventList.size()]; quantEvents = quantEventList.toArray(quantEvents); return quantEvents; } private TransactionEventType[] runTransactionEventQuery( final PreparedStatement transactionEventQuery) throws SQLException, ImplementationException { if (transactionEventQuery == null) { return null; } // Calendar needed for converting timestamps Calendar cal = Calendar.getInstance(); // run the query and get all TransactionEvents ResultSet rs = transactionEventQuery.executeQuery(); List<TransactionEventType> transEventList = new ArrayList<TransactionEventType>(); while (rs.next()) { TransactionEventType transEvent = new TransactionEventType(); int eventId = rs.getInt("id"); // set EventTime, RecordTime, and EventTimezoneOffset cal.setTime(rs.getTimestamp("eventTime")); transEvent.setEventTime((Calendar) cal.clone()); cal.setTime(rs.getTimestamp("recordTime")); transEvent.setRecordTime((Calendar) cal.clone()); transEvent.setEventTimeZoneOffset(rs.getString("eventTimeZoneOffset")); // set action ActionType action = ActionType.fromString(rs.getString("action")); transEvent.setAction(action); // set all URIs transEvent.setParentID(stringToUri(rs.getString("parentID"))); transEvent.setBizStep(stringToUri(rs.getString("bizStep"))); transEvent.setDisposition(stringToUri(rs.getString("disposition"))); if (rs.getString("readPoint") != null) { ReadPointType rpt = new ReadPointType(); rpt.setId(stringToUri(rs.getString("readPoint"))); transEvent.setReadPoint(rpt); } if (rs.getString("bizLocation") != null) { BusinessLocationType blt = new BusinessLocationType(); blt.setId(stringToUri(rs.getString("bizLocation"))); transEvent.setBizLocation(blt); } // set business transactions BusinessTransactionType[] bizTrans = fetchBizTransactions( "event_TransactionEvent_bizTrans", eventId); transEvent.setBizTransactionList(bizTrans); // set associated EPCs EPC[] epcs = fetchEPCs("event_TransactionEvent_EPCs", eventId); transEvent.setEpcList(epcs); transEventList.add(transEvent); } rs.close(); TransactionEventType[] transEvents = new TransactionEventType[transEventList.size()]; transEvents = transEventList.toArray(transEvents); return transEvents; } /** * Transforms an array of strings into sql IN (...) notation. Takes the * string array, the query string and the argument vector This function is * designed to be used with PreparedStatement * * @param strings * Array of strings to be added to sql IN (...) expression. * @param query * The query which will be appended with the appropriate amounts * of question marks for the parameters. * @param queryArgs * The queryArgs vector which will take the additional query * parameters specified in 'strings'. */ private void stringArrayToSQL(final String[] strings, final StringBuffer query, final List<String> queryArgs) { int j = 0; while (j < strings.length - 1) { query.append("?,"); queryArgs.add(strings[j]); j++; } if (strings.length > 0) { query.append("?"); queryArgs.add(strings[j]); } } /** * Create an SQL query string from a list of Query Parameters. * * @param queryParams * The query parameters. * @param eventType * Has to be one of the four basic event types "ObjectEvent", * "AggregationEvent", "QuantityEvent", "TransactionEvent". * @return The prepared sql statement. * @throws SQLException * Whenever something goes wrong when querying the db. * @throws QueryParameterException * If one of the given QueryParam is invalid. * @throws ImplementationException */ private PreparedStatement createEventQuery(final QueryParam[] queryParams, final String eventType) throws SQLException, QueryParameterException, ImplementationException { StringBuffer query; if (eventType.equals("ObjectEvent")) { query = new StringBuffer(objectEventQueryBase); } else if (eventType.equals("AggregationEvent")) { query = new StringBuffer(aggregationEventQueryBase); } else if (eventType.equals("QuantityEvent")) { query = new StringBuffer(quantityEventQueryBase); } else if (eventType.equals("TransactionEvent")) { query = new StringBuffer(transactionEventQueryBase); } else { ImplementationException iex = new ImplementationException(); String msg = "Invalid event type encountered: " + eventType; LOG.error(msg); iex.setReason(msg); iex.setSeverity(ImplementationExceptionSeverity.ERROR); throw iex; } String orderBy = ""; String orderDirection = ""; int limit = -1; int maxEvent = -1; List<String> params = new LinkedList<String>(); List<String> queryArgs = new ArrayList<String>(); for (int i = 0; i < queryParams.length; i++) { String paramName = queryParams[i].getName(); Object paramValue = queryParams[i].getValue(); // check parameter value if (paramValue.toString().equals("")) { LOG.info("USER ERROR: empty parameter value provided for parameter " + paramName); // we do not throw an exception // just ignore this parameter continue; } // check if this parameter has already been provided if (params.contains(paramName)) { String msg = "Two or more inputs are provided for the same parameter " + paramName; LOG.error(msg); throw new QueryParameterException(msg); } else { params.add(paramName); } try { if (paramName.equals("eventType")) { // search for the eventType in the list of arguments. // If it does not appear, this eventType is not asked for // and we return null as the query string String[] arglist = ((ArrayOfString) paramValue).getString(); int j = 0; while (arglist != null && (j < arglist.length) && (!arglist[j].equals(eventType))) { j++; } if (arglist != null && arglist.length > 0 && j == arglist.length) { return null; } } else if (paramName.equals("GE_eventTime")) { query.append(" AND (eventTime >= ?) "); Calendar cal = (Calendar) paramValue; Timestamp ts = new Timestamp(cal.getTimeInMillis()); queryArgs.add(ts.toString()); } else if (paramName.equals("LT_eventTime")) { query.append(" AND (eventTime < ?) "); Calendar cal = (Calendar) paramValue; Timestamp ts = new Timestamp(cal.getTimeInMillis()); queryArgs.add(ts.toString()); } else if (paramName.equals("GE_recordTime")) { query.append(" AND (recordTime >= ?) "); Calendar cal = (Calendar) paramValue; Timestamp ts = new Timestamp(cal.getTimeInMillis()); queryArgs.add(ts.toString()); } else if (paramName.equals("LT_recordTime")) { query.append(" AND (recordTime < ?) "); Calendar cal = (Calendar) paramValue; Timestamp ts = new Timestamp(cal.getTimeInMillis()); queryArgs.add(ts.toString()); } else if (paramName.equals("EQ_action")) { // TODO: check input values for action if (!eventType.equals("QuantityEvent")) { query.append(" AND (action IN ("); stringArrayToSQL( ((ArrayOfString) paramValue).getString(), query, queryArgs); query.append(")) "); } else { query.append(" AND 0 "); } } else if (paramName.equals("EQ_bizStep")) { query.append(" AND (`voc_BizStep`.uri IN ("); stringArrayToSQL(((ArrayOfString) paramValue).getString(), query, queryArgs); query.append(")) "); } else if (paramName.equals("EQ_disposition")) { query.append(" AND (`voc_Disposition`.uri IN ("); stringArrayToSQL(((ArrayOfString) paramValue).getString(), query, queryArgs); query.append(")) "); } else if (paramName.equals("EQ_readPoint")) { query.append(" AND (`voc_ReadPoint`.uri IN ("); stringArrayToSQL(((ArrayOfString) paramValue).getString(), query, queryArgs); query.append(")) "); } else if (paramName.equals("WD_readPoint")) { // the % allows any possible ending, which should implement // the semantics of "With Descendant" String[] readPoints = ((ArrayOfString) paramValue).getString(); query.append(" AND `voc_ReadPoint`.uri IS NOT NULL AND ("); int j = 0; while (j < readPoints.length - 1) { query.append("`voc_ReadPoint`.uri LIKE ? OR "); queryArgs.add(readPoints[j] + "%"); j++; } if (readPoints.length > 0) { query.append("`voc_ReadPoint`.uri LIKE ?"); queryArgs.add(readPoints[j] + "%"); } query.append(") "); } else if (paramName.equals("EQ_bizLocation")) { query.append(" AND (`voc_BizLoc`.uri IN ("); stringArrayToSQL(((ArrayOfString) paramValue).getString(), query, queryArgs); query.append(")) "); } else if (paramName.equals("WD_bizLocation")) { String[] bizLocations = null; try { bizLocations = ((ArrayOfString) paramValue).getString(); } catch (ClassCastException e) { // we have the URI directly (no ArrayOfString wrapper) bizLocations = new String[1]; bizLocations[0] = paramValue.toString(); } for (int j = 0; j < bizLocations.length; j++) { bizLocations[j] = bizLocations[j] + "%"; } query.append(" AND ("); int j = 0; while (j < bizLocations.length - 1) { query.append("`voc_BizLoc`.uri LIKE ? OR "); queryArgs.add(bizLocations[j]); j++; } if (bizLocations.length > 0) { query.append("`voc_BizLoc`.uri LIKE ?"); queryArgs.add(bizLocations[j]); } query.append(") "); } else if (paramName.startsWith("EQ_bizTransaction_")) { // this query is subdivided into several subqueries // subquery for selecting IDs from voc_BizTransType // type extracted from parameter name String type = paramName.substring(18); String vocBizTransTypeId = "SELECT id FROM `voc_BizTransType` WHERE uri=\"" + type + "\""; // subquery for selecting IDs from voc_BizTrans StringBuffer temp = new StringBuffer(); temp.append("(SELECT id AS vocBizTransId FROM `voc_BizTrans` WHERE `voc_BizTrans`.uri IN ("); String[] strings = ((ArrayOfString) paramValue).getString(); int j = 0; while (j < strings.length - 1) { temp.append("\"" + strings[j] + "\","); j++; } if (strings.length > 0) { temp.append("\"" + strings[j] + "\""); } temp.append(")) AS SelectedVocBizTrans"); String vocBizTransIds = temp.toString(); // subquery for selecting IDs from BizTransaction String selectedBizTrans = "(SELECT id AS bizTransId, bizTrans FROM `BizTransaction` bt WHERE bt.type=(" + vocBizTransTypeId + ")) AS SelectedBizTrans"; String bizTransId = "SELECT bizTransId FROM " + vocBizTransIds + " INNER JOIN " + selectedBizTrans + " ON SelectedBizTrans.bizTrans=SelectedVocBizTrans.vocBizTransId"; query.append(" AND (`event_" + eventType + "`.id IN ("); query.append("SELECT event_id AS id "); query.append("FROM `event_" + eventType + "_bizTrans` "); query.append("INNER JOIN ("); query.append(bizTransId); query.append(") AS BizTransIds "); query.append("ON BizTransIds.bizTransId=`event_" + eventType + "_bizTrans`.bizTrans_id"); query.append("))"); } else if (paramName.equals("MATCH_epc")) { // FIXME: marco: this does not work correctly // see test SE21 if (eventType.equals("ObjectEvent")) { query.append(" AND (`event_ObjectEvent`.id IN ("); query.append("SELECT event_id FROM `event_ObjectEvent_EPCs` WHERE epc IN ("); stringArrayToSQL( ((ArrayOfString) paramValue).getString(), query, queryArgs); query.append(")))"); } else if (eventType.equals("TransactionEvent")) { query.append(" AND (`event_TransactionEvent`.id IN ("); query.append("SELECT event_id FROM `event_TransactionEvent_EPCs` WHERE epc IN ("); stringArrayToSQL( ((ArrayOfString) paramValue).getString(), query, queryArgs); query.append(")))"); } else { query.append(" AND 0 "); } } else if (paramName.equals("MATCH_parentID")) { if (eventType.equals("AggregationEvent") || eventType.equals("TransactionEvent")) { query.append(" AND (parentID IN ("); stringArrayToSQL( ((ArrayOfString) paramValue).getString(), query, queryArgs); query.append("))"); } else { query.append(" AND 0 "); } } else if (paramName.equals("MATCH_childEPC")) { if (eventType.equals("AggregationEvent")) { query.append(" AND (`event_AggregationEvent`.id IN ("); query.append("SELECT event_id FROM `event_AggregationEvent_EPCs` WHERE epc IN ("); stringArrayToSQL( ((ArrayOfString) paramValue).getString(), query, queryArgs); query.append(")))"); } else { query.append(" AND 0 "); } } else if (paramName.equals("MATCH_epcClass")) { if (eventType.equals("QuantityEvent")) { query.append(" AND (epcClass IN ("); query.append("SELECT id FROM `voc_EPCClass` WHERE uri IN ("); stringArrayToSQL( ((ArrayOfString) paramValue).getString(), query, queryArgs); query.append(")))"); } else { query.append(" AND 0 "); } } else if (paramName.equals("EQ_quantity")) { if (eventType.equals("QuantityEvent")) { query.append(" AND (quantity = ?) "); queryArgs.add(((Integer) paramValue).toString()); } else { query.append(" AND 0 "); } } else if (paramName.equals("GT_quantity")) { if (eventType.equals("QuantityEvent")) { query.append(" AND (quantity > ?) "); queryArgs.add(((Integer) paramValue).toString()); } else { query.append(" AND 0 "); } } else if (paramName.equals("GE_quantity")) { if (eventType.equals("QuantityEvent")) { query.append(" AND (quantity >= ?) "); queryArgs.add(((Integer) paramValue).toString()); } else { query.append(" AND 0 "); } } else if (paramName.equals("LT_quantity")) { if (eventType.equals("QuantityEvent")) { query.append(" AND (quantity < ?) "); queryArgs.add(((Integer) paramValue).toString()); } else { query.append(" AND 0 "); } } else if (paramName.equals("LE_quantity")) { if (eventType.equals("QuantityEvent")) { query.append(" AND (quantity <= ?) "); queryArgs.add(((Integer) paramValue).toString()); } else { query.append(" AND 0 "); } } else if (paramName.startsWith("GT_") || paramName.startsWith("GE_") || paramName.startsWith("EQ_") || paramName.startsWith("LE_") || paramName.startsWith("LT_")) { String op = "="; if (paramName.startsWith("GT_")) { op = ">"; } else if (paramName.startsWith("GE_")) { op = ">="; } else if (paramName.startsWith("LE_")) { op = "<="; } else if (paramName.startsWith("LT_")) { op = "<"; } String where; Object val = paramValue; try { Integer intVal = (Integer) paramValue; where = "intValue" + op + intVal; } catch (ClassCastException e1) { try { Float floatVal = (Float) paramValue; where = "floatValue" + op + floatVal; } catch (ClassCastException e2) { try { Calendar cal = TimeParser.parseAsCalendar(val.toString()); Timestamp ts = new Timestamp( cal.getTimeInMillis()); where = "dateValue" + op + "\"" + ts.toString() + "\""; } catch (ParseException e) { String strVal = val.toString(); where = "strValue" + op + "\"" + strVal + "\""; } } } String fieldname = paramName.substring(3); // FIXME: marco: if db ready -> do this for all events if (eventType.equals("ObjectEvent")) { query.append(" AND `event_ObjectEvent_extensions`."); query.append(where); query.append(" AND `event_ObjectEvent_extensions`.fieldname=\""); query.append(fieldname); query.append("\""); } else { query.append(" AND 0"); } } else if (paramName.startsWith("EXISTS_")) { String type = paramName.substring(7); if (type.equals("childEPCs")) { if (eventType.equals("AggregationEvent")) { query.append(" AND (`event_AggregationEvent`.id IN ("); query.append("SELECT event_id FROM `event_AggregationEvent_EPCs`"); query.append("))"); } else { query.append(" AND 0"); } } else if (type.equals("epcList")) { query.append(" AND (`event_" + eventType + "`.id IN ("); query.append("SELECT event_id FROM `event_" + eventType + "_EPCs`"); query.append("))"); } else if (type.equals("bizTransactionList")) { query.append(" AND (`event_" + eventType + ".id IN ("); query.append("SELECT event_id FROM `event_" + eventType + "_bizTrans`"); query.append("))"); } else { // lets see if we have an extension fieldname String[] parts = type.split(" if (parts.length != 2) { // nope, no extension fieldname, just check if // the given type exists query.append(" AND (?) "); queryArgs.add(type); } else { // yep, extension fieldname: check extension table // FIXME: marco: if db ready -> do this for all // events // just remove the if-else if (eventType.equals("ObjectEvent")) { query.append(" AND (`event_" + eventType + "`.id IN ("); query.append("SELECT event_id FROM `event_" + eventType + "_extensions` "); query.append("WHERE fieldname=\"" + type + "\""); query.append("))"); } else { query.append(" AND 0"); } } } } else if (paramName.startsWith("HASATTR_")) { // TODO: String msg = "HASATTR_fieldname is not implemented."; LOG.info("USER ERROR: " + msg); throw new UnsupportedOperationException(msg); } else if (paramName.startsWith("EQATTR_")) { // TODO: String msg = "EQATTR_fieldname_attrname is not implemented."; LOG.info("USER ERROR: " + msg); throw new UnsupportedOperationException(msg); } else if (paramName.equals("orderBy")) { // Does only work correct if we choose only one Event-Type // to query. Otherwise, the Results are ordered by // Event-Types and second according to the orderBy-Parameter orderBy = (String) paramValue; } else if (paramName.equals("orderDirection")) { // Does only work correct if we choose only one Event-Type // to query. Otherwise, the Results are ordered by // Event-Types and second according to the orderBy-Parameter orderDirection = (String) paramValue; } else if (paramName.equals("eventCountLimit")) { // Does only work properly if we choose only one type to // query. limit = (Integer) paramValue; } else if (paramName.equals("maxEventCount")) { maxEventCount = ((Integer) paramValue).intValue(); } else { String msg = "The parameter " + paramName + " cannot be recognised."; LOG.info("USER ERROR: " + msg); throw new QueryParameterException(msg); } } catch (ClassCastException e) { String msg = "The input value for parameter " + paramName + " of eventType " + eventType + " is not of the type required."; LOG.info("USER ERROR: " + msg); throw new QueryParameterException(msg); } } if (maxEvent > -1 && limit > -1) { String msg = "The maxEventCount and the eventCountLimit are mutually exclusive."; LOG.info("USER ERROR: " + msg); throw new QueryParameterException(msg); } if (orderBy.equals("") && limit > -1) { String msg = "eventCountLimit may only be used when orderBy is specified."; LOG.info("USER ERROR: " + msg); throw new QueryParameterException(msg); } if (!orderBy.equals("")) { query.append(" ORDER BY (?)"); queryArgs.add(orderBy); if (orderDirection.equals("ASC")) { query.append(" ASC"); } else { query.append(" DESC"); } } if (limit > -1) { query.append(" LIMIT " + ((Integer) limit).toString()); } String q = query.toString(); String qs = q.replaceAll("`", delimiter); LOG.debug("QUERY: " + qs); PreparedStatement ps = dbconnection.prepareStatement(qs); for (int i = 0; i < queryArgs.size(); i++) { ps.setString(i + 1, (String) queryArgs.get(i)); LOG.debug(" query param " + (i + 1) + ": " + queryArgs.get(i)); } return ps; } /** * @see org.accada.epcis.soapapi.EPCISServicePortType#getQueryNames(org.accada.epcis.soapapi.EmptyParms) * @param parms * An empty parameter. * @return An ArrayOfString containing the names of all implemented queries. */ public ArrayOfString getQueryNames(final EmptyParms parms) { ArrayOfString qNames = new ArrayOfString(); String[] qNamesArray = new String[queryNames.size()]; qNamesArray = queryNames.toArray(qNamesArray); qNames.setString(qNamesArray); return qNames; } /** * Subscribes a query. * * @see org.accada.epcis.soapapi.EPCISServicePortType#subscribe(org.accada.epcis.soapapi.Subscribe) * @param parms * A Subscribe object containing the query to be subscribed.. * @return Nothing. * @throws ImplementationException * If a problem with the EPCIS implementation occured. * @throws InvalidURIException * If an invalid URI where the query results should be posted is * provided. * @throws SubscribeNotPermittedException * If a SimpleMasterDataQuery is provided which is only valid * for polling. * @throws SubscriptionControlsException * If one of the SubscriptionControls parameters is not set. * @throws ValidationException * If the query is not valid. * @throws DuplicateSubscriptionException * If a query with the given ID is already subscribed. * @throws NoSuchNameException * If a query name is not implemented yet. */ public VoidHolder subscribe(final Subscribe parms) throws ImplementationException, InvalidURIException, SubscribeNotPermittedException, SubscriptionControlsException, ValidationException, DuplicateSubscriptionException, NoSuchNameException { QueryParam[] qParams = parms.getParams(); URI dest = parms.getDest(); String subscrId = parms.getSubscriptionID(); SubscriptionControls controls = parms.getControls(); String queryName = parms.getQueryName(); GregorianCalendar initialRecordTime = (GregorianCalendar) parms.getControls().getInitialRecordTime(); if (initialRecordTime == null) { initialRecordTime = new GregorianCalendar(); } try { // A few input sanity checks // dest may be null or empty. But we don't support pre-arranged // destinations and throw an InvalidURIException according to the // standard. if (dest == null || dest.toString().equals("")) { String msg = "Destination URI is empty. This implementation doesn't support pre-arranged destinations."; LOG.info("USER ERROR: " + msg); throw new InvalidURIException(msg); } // check query name if (!queryNames.contains(queryName)) { String msg = "Illegal query name '" + queryName + "'."; LOG.info("USER ERROR: " + msg); throw new NoSuchNameException(msg); } // SimpleMasterDataQuery only valid for polling if (queryName.equals("SimpleMasterDataQuery")) { String msg = "SimpleMasterDataQuery not permitted for use with subscribe, only with poll."; LOG.info("USER ERROR: " + msg); throw new SubscribeNotPermittedException(msg); } // subscriptionID mustn't be empty. if (subscrId == null || subscrId.equals("")) { String msg = "SubscriptionID is empty. Choose a valid subscriptionID."; LOG.info(msg); throw new ValidationException(msg); } // subscriptionID mustn't exist yet. if (fetchExistsSubscriptionId(subscrId)) { String msg = "SubscriptionID '" + subscrId + "' already exists. Choose a different subscriptionID."; LOG.info("USER ERROR: " + msg); throw new DuplicateSubscriptionException(msg); } // trigger and schedule may no be used together, but one of them // must be set if (controls.getSchedule() != null && controls.getTrigger() != null) { String msg = "Schedule and trigger mustn't be used together."; LOG.info("USER ERROR: " + msg); throw new SubscriptionControlsException(msg); } if (controls.getSchedule() == null && controls.getTrigger() == null) { String msg = "Either schedule or trigger has to be set."; LOG.info("USER ERROR: " + msg); throw new SubscriptionControlsException(msg); } if (controls.getSchedule() == null && controls.getTrigger() != null) { String msg = "Triggers are not supported."; LOG.info("USER ERROR: " + msg); throw new SubscriptionControlsException(msg); } // parse schedule Schedule schedule = new Schedule(controls.getSchedule()); // load subscriptions Map<String, SubscriptionScheduled> subscribedMap = loadSubscriptions(); SubscriptionScheduled newSubscription = new SubscriptionScheduled( subscrId, qParams, dest, controls.isReportIfEmpty(), initialRecordTime, initialRecordTime, schedule, queryName); // store the Query to the database String insert = "INSERT INTO subscription (subscriptionid, " + "params, dest, sched, trigg, initialrecordingtime, " + "exportifempty, queryname, lastexecuted) VALUES " + "((?), (?), (?), (?), (?), (?), (?), (?), (?))"; PreparedStatement stmt = dbconnection.prepareStatement(insert); LOG.debug("QUERY: " + insert); try { stmt.setString(1, subscrId); LOG.debug(" query param 1: " + subscrId); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(outStream); out.writeObject(qParams); ByteArrayInputStream inStream = new ByteArrayInputStream( outStream.toByteArray()); stmt.setBinaryStream(2, inStream, inStream.available()); LOG.debug(" query param 2: [" + inStream.available() + " bytes]"); stmt.setString(3, dest.toString()); LOG.debug(" query param 3: " + dest.toString()); outStream = new ByteArrayOutputStream(); out = new ObjectOutputStream(outStream); out.writeObject(schedule); inStream = new ByteArrayInputStream(outStream.toByteArray()); stmt.setBinaryStream(4, inStream, inStream.available()); LOG.debug(" query param 4: [" + inStream.available() + " bytes]"); stmt.setString(5, ""); LOG.debug(" query param 5: "); Calendar cal = newSubscription.getInitialRecordTime(); Timestamp ts = new Timestamp(cal.getTimeInMillis()); String time = ts.toString(); stmt.setString(6, time); LOG.debug(" query param 6: " + time); stmt.setBoolean(7, controls.isReportIfEmpty()); LOG.debug(" query param 7: " + controls.isReportIfEmpty()); stmt.setString(8, queryName); LOG.debug(" query param 8: " + time); stmt.setString(9, time); LOG.debug(" query param 9: " + time); stmt.executeUpdate(); } catch (IOException e) { String msg = "Unable to store the subscription to the database: " + e.getMessage(); LOG.error(msg); ImplementationException iex = new ImplementationException(); iex.setReason(msg); iex.setStackTrace(e.getStackTrace()); iex.setSeverity(ImplementationExceptionSeverity.ERROR); throw iex; } // store the new Query to the HashMap subscribedMap.put(subscrId, newSubscription); saveSubscriptions(subscribedMap); return new VoidHolder(); } catch (SQLException e) { String msg = "SQL error during query execution: " + e.getMessage(); LOG.error(msg, e); ImplementationException iex = new ImplementationException(); iex.setReason(msg); iex.setStackTrace(e.getStackTrace()); iex.setSeverity(ImplementationExceptionSeverity.ERROR); throw iex; } } /** * This method loads all the stored queries from the database, starts them * again and stores everything in a HasMap. * * @return A Map mapping query names to scheduled query subscriptions. * @throws SQLException * If a problem with the database occured. * @throws ImplementationException * If a problem with the EPCIS implementation occured. */ private Map<String, SubscriptionScheduled> fetchSubscriptions() throws SQLException, ImplementationException { String query = "SELECT * FROM subscription"; LOG.debug("QUERY: " + query); Statement stmt = dbconnection.createStatement(); GregorianCalendar initrectime = new GregorianCalendar(); ResultSet rs = stmt.executeQuery(query); Map<String, SubscriptionScheduled> subscribedMap = new HashMap<String, SubscriptionScheduled>(); while (rs.next()) { try { String subscrId = rs.getString("subscriptionid"); ObjectInput in = new ObjectInputStream( rs.getBinaryStream("params")); QueryParam[] params = (QueryParam[]) in.readObject(); URI dest = stringToUri(rs.getString("dest")); in = new ObjectInputStream(rs.getBinaryStream("sched")); Schedule sched = (Schedule) in.readObject(); initrectime.setTime(rs.getTimestamp("initialrecordingtime")); boolean exportifempty = rs.getBoolean("exportifempty"); String queryName = rs.getString("queryname"); SubscriptionScheduled newSubscription = new SubscriptionScheduled( subscrId, params, dest, exportifempty, initrectime, new GregorianCalendar(), sched, queryName); subscribedMap.put(subscrId, newSubscription); } catch (SQLException e) { // sql exceptions are passed on throw e; } catch (Exception e) { // all other exceptions are caught String msg = "Unable to restore subscribed queries from the database."; LOG.error(msg, e); ImplementationException iex = new ImplementationException(); iex.setReason(msg); iex.setStackTrace(e.getStackTrace()); iex.setSeverity(ImplementationExceptionSeverity.SEVERE); throw iex; } } rs.close(); return subscribedMap; } /** * Stops a subscribed query from further invocations. * * @see org.accada.epcis.soapapi.EPCISServicePortType#unsubscribe(org.accada.epcis.soapapi.Unsubscribe) * @param parms * An Unsubscribe object containing the ID of the query to be * unsubscribed. * @return Nothing. * @throws ImplementationException * If a problem with the EPCIS implementation occured. */ public VoidHolder unsubscribe(final Unsubscribe parms) throws ImplementationException, NoSuchSubscriptionException { try { Map<String, SubscriptionScheduled> subscribedMap = loadSubscriptions(); String subscrId = parms.getSubscriptionID(); if (subscribedMap.containsKey(subscrId)) { // remove subscription from local hash map SubscriptionScheduled toDelete = subscribedMap.get(subscrId); toDelete.stopSubscription(); subscribedMap.remove(subscrId); saveSubscriptions(subscribedMap); // delete subscription from database String delete = "DELETE FROM subscription WHERE " + "subscriptionid = (?)"; PreparedStatement stmt = dbconnection.prepareStatement(delete); stmt.setString(1, subscrId); LOG.debug("QUERY: " + delete); LOG.debug(" query param 1: " + subscrId); stmt.executeUpdate(); return new VoidHolder(); } else { String msg = "A subscription with ID '" + subscrId + "' does not exist."; LOG.info("USER ERROR: " + msg); throw new NoSuchSubscriptionException(msg); } } catch (SQLException e) { ImplementationException iex = new ImplementationException(); String msg = "SQL error during query execution: " + e.getMessage(); LOG.error(msg, e); iex.setReason(msg); iex.setStackTrace(e.getStackTrace()); iex.setSeverity(ImplementationExceptionSeverity.ERROR); throw iex; } } /** * Saves the map with the subscriptions to the message context. * * @param subscribedMap * The map with the subscriptions. */ private void saveSubscriptions( final Map<String, SubscriptionScheduled> subscribedMap) { MessageContext msgContext = MessageContext.getCurrentContext(); msgContext.setProperty("subscribedMap", subscribedMap); } /** * Retrieves the map with the subscriptions from the servlet context. * * @return The map with the subscriptions. * @throws ImplementationException * If the map could not be reloaded. */ private Map<String, SubscriptionScheduled> loadSubscriptions() throws ImplementationException, SQLException { MessageContext msgContext = MessageContext.getCurrentContext(); Map<String, SubscriptionScheduled> subscribedMap = (HashMap<String, SubscriptionScheduled>) msgContext.getProperty("subscribedMap"); if (subscribedMap == null) { subscribedMap = fetchSubscriptions(); } return subscribedMap; } /** * Returns an ArrayOfString containing IDs of all subscribed queries. * * @see org.accada.epcis.soapapi.EPCISServicePortType#getSubscriptionIDs(org.accada.epcis.soapapi.GetSubscriptionIDs) * @param parms * An empty parameter. * @return An ArrayOfString containing IDs of all subscribed queries. * @throws ImplementationException * If a problem with the EPCIS implementation occured. */ public ArrayOfString getSubscriptionIDs(final GetSubscriptionIDs parms) throws ImplementationException { try { Map<String, SubscriptionScheduled> subscribedMap = loadSubscriptions(); String[] temp = {}; temp = subscribedMap.keySet().toArray(temp); ArrayOfString arrOfStr = new ArrayOfString(); arrOfStr.setString(temp); return arrOfStr; } catch (SQLException e) { ImplementationException iex = new ImplementationException(); String msg = "SQL error during query execution: " + e.getMessage(); LOG.error(msg, e); iex.setReason(msg); iex.setStackTrace(e.getStackTrace()); iex.setSeverity(ImplementationExceptionSeverity.ERROR); throw iex; } } /** * Runs (polls) a query. * * @see org.accada.epcis.soapapi.EPCISServicePortType#poll(org.accada.epcis.soapapi.Poll) * @param parms * The query to poll. * @return A QueryResults object containing the result of the query. * @throws ImplementationException * If a problem with the EPCIS implementation occured. * @throws QueryTooLargeException * If the query is too large. * @throws QueryParameterException * If one of the query parameters is invalid. * @throws NoSuchNameException * If an invalid query type was provided. */ public QueryResults poll(final Poll parms) throws ImplementationException, QueryTooLargeException, QueryParameterException, NoSuchNameException { // query type must be implemented. if (!queryNames.contains(parms.getQueryName())) { String msg = "Invalid query name '" + parms.getQueryName() + "' provided."; LOG.info("USER ERROR: " + msg); throw new NoSuchNameException(msg); } String queryName = parms.getQueryName(); if (queryName.equals("SimpleEventQuery")) { try { int actEventCount = 0; maxEventCount = -1; QueryParam[] queryParams = parms.getParams(); String event = "ObjectEvent"; PreparedStatement ps = createEventQuery(queryParams, event); ObjectEventType[] tempObjectEvent = runObjectEventQuery(ps); if (tempObjectEvent != null) { actEventCount += tempObjectEvent.length; } event = "AggregationEvent"; ps = createEventQuery(queryParams, event); AggregationEventType[] tempAggrEvent = runAggregationEventQuery(ps); if (tempAggrEvent != null) { actEventCount += tempAggrEvent.length; } event = "QuantityEvent"; ps = createEventQuery(queryParams, event); QuantityEventType[] tempQuantityEvent = runQuantityEventQuery(ps); if (tempQuantityEvent != null) { actEventCount += tempQuantityEvent.length; } event = "TransactionEvent"; ps = createEventQuery(queryParams, event); TransactionEventType[] tempTransEvent = runTransactionEventQuery(ps); if (tempTransEvent != null) { actEventCount += tempTransEvent.length; } if (maxEventCount > -1 && actEventCount > maxEventCount) { String msg = "The actual result set (" + actEventCount + ") is larger than the specified maxEventCount (" + maxEventCount + ")."; LOG.info("USER ERROR: " + msg); throw new QueryTooLargeException(msg, queryName, null); } // construct QueryResults EventListType eventList = new EventListType(); eventList.setObjectEvent(tempObjectEvent); eventList.setAggregationEvent(tempAggrEvent); eventList.setQuantityEvent(tempQuantityEvent); eventList.setTransactionEvent(tempTransEvent); QueryResultsBody resultsBody = new QueryResultsBody(); resultsBody.setEventList(eventList); QueryResults results = new QueryResults(); results.setResultsBody(resultsBody); results.setQueryName(queryName); LOG.info("poll request for '" + queryName + "' succeeded"); return results; } catch (SQLException e) { ImplementationException iex = new ImplementationException(); String msg = "SQL error during query execution: " + e.getMessage(); LOG.error(msg, e); iex.setReason(msg); iex.setStackTrace(e.getStackTrace()); iex.setSeverity(ImplementationExceptionSeverity.ERROR); throw iex; } } else if (queryName.equals("SimpleMasterDataQuery")) { // FIXME: implement SimpleMasterDataQuery here. return null; } else { String msg = "Invalid query name '" + parms.getQueryName() + "' provided."; LOG.info("USER ERROR: " + msg); throw new NoSuchNameException(msg); } } /** * Returns the standard version. * * @see org.accada.epcis.soapapi.EPCISServicePortType#getStandardVersion(org.accada.epcis.soapapi.EmptyParms) * @param parms * An empty parameter. * @return The standard version. */ public String getStandardVersion(final EmptyParms parms) { return STD_VERSION; } /** * Returns the vendor version. * * @see org.accada.epcis.soapapi.EPCISServicePortType#getVendorVersion(org.accada.epcis.soapapi.EmptyParms) * @param parms * An empty parameter. * @return The vendor version. */ public String getVendorVersion(final EmptyParms parms) { return VDR_VERSION; } }
package org.jgrapht.demo; import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.HashMap; import java.util.Map; import java.util.Random; import org.jgrapht.VertexFactory; import org.jgrapht.ext.ComponentAttributeProvider; import org.jgrapht.ext.ExportException; import org.jgrapht.ext.GraphMLExporter; import org.jgrapht.ext.VertexNameProvider; import org.jgrapht.ext.GraphMLExporter.AttributeCategory; import org.jgrapht.ext.GraphMLExporter.AttributeType; import org.jgrapht.ext.IntegerEdgeNameProvider; import org.jgrapht.generate.CompleteGraphGenerator; import org.jgrapht.graph.DefaultWeightedEdge; import org.jgrapht.graph.DirectedPseudograph; /** * This class demonstrates exporting a graph with custom vertex and * edge attributes as GraphML. Vertices of the graph have an attribute * called "color" and a "name" attribute. Edges have a "weight" attribute * as well as a "name" attribute. */ public final class GraphMLExportDemo { // Number of vertices private static final int size = 6; private static Random generator = new Random(17); enum Color { BLACK("black"), WHITE("white"); private final String value; private Color(String value) { this.value = value; } public String toString() { return value; } } static class GraphVertex { private String id; private Color color; public GraphVertex(String id) { this(id, null); } public GraphVertex(String id, Color color) { this.id = id; this.color = color; } @Override public int hashCode() { return (id == null) ? 0 : id.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; GraphVertex other = (GraphVertex) obj; if (id == null) { return other.id == null; } else { return id.equals(other.id); } } public Color getColor() { return color; } public void setColor(Color color) { this.color = color; } public String getId() { return id; } public void setId(String id) { this.id = id; } @Override public String toString() { return id; } } public static void main(String[] args) { /* * Generate complete graph. * * Vertices have random colors and edges have random edge weights. */ DirectedPseudograph<GraphVertex, DefaultWeightedEdge> g = new DirectedPseudograph<>( DefaultWeightedEdge.class); CompleteGraphGenerator<GraphVertex, DefaultWeightedEdge> completeGenerator = new CompleteGraphGenerator<>( size); VertexFactory<GraphVertex> vFactory = new VertexFactory<GraphVertex>() { private int id = 0; @Override public GraphVertex createVertex() { GraphVertex v = new GraphVertex(String.valueOf(id++)); if (generator.nextBoolean()) { v.setColor(Color.BLACK); } else { v.setColor(Color.WHITE); } return v; } }; completeGenerator.generateGraph(g, vFactory, null); // assign random weights for (DefaultWeightedEdge e : g.edgeSet()) { g.setEdgeWeight(e, generator.nextInt(100)); } // create GraphML exporter GraphMLExporter<GraphVertex, DefaultWeightedEdge> exporter = new GraphMLExporter<>( new VertexNameProvider<GraphVertex>() { @Override public String getVertexName(GraphVertex v) { return v.id; } }, null, new IntegerEdgeNameProvider<>(), null); // set to export the internal edge weights exporter.setExportEdgeWeights(true); // register additional color attribute for vertices exporter.registerAttribute( "color", AttributeCategory.NODE, AttributeType.STRING); // register additional name attribute for vertices and edges exporter.registerAttribute( "name", AttributeCategory.ALL, AttributeType.STRING); // create provider of vertex attributes ComponentAttributeProvider<GraphVertex> vertexAttributeProvider = new ComponentAttributeProvider<GraphVertex>() { @Override public Map<String, String> getComponentAttributes(GraphVertex v) { Map<String, String> m = new HashMap<String, String>(); if (v.getColor() != null) { m.put("color", v.getColor().toString()); } m.put("name", "node-" + v.id); return m; } }; exporter.setVertexAttributeProvider(vertexAttributeProvider); // create provider of edge attributes ComponentAttributeProvider<DefaultWeightedEdge> edgeAttributeProvider = new ComponentAttributeProvider<DefaultWeightedEdge>() { @Override public Map<String, String> getComponentAttributes( DefaultWeightedEdge e) { Map<String, String> m = new HashMap<String, String>(); m.put("name", e.toString()); return m; } }; exporter.setEdgeAttributeProvider(edgeAttributeProvider); // export try { Writer writer = new BufferedWriter( new OutputStreamWriter(System.out)); exporter.export(writer, g); writer.flush(); } catch (ExportException | IOException e) { System.err.println("Error: " + e.getMessage()); System.exit(-1); } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package de.charite.compbio.exomiser.core.model; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Objects; /** * Represents a phenotype term from a phenotype ontology - e.g. the HPO, MPO, ZPO... * @author Jules Jacobsen <jules.jacobsen@sanger.ac.uk> */ public class PhenotypeTerm { private final String id; private final String term; private final double ic; public PhenotypeTerm(String id, String term, double ic) { this.id = id; this.term = term; this.ic = ic; } public String getId() { return id; } @JsonProperty("label") public String getTerm() { return term; } @JsonProperty("IC") public double getIc() { return ic; } @Override public int hashCode() { int hash = 5; hash = 97 * hash + Objects.hashCode(this.id); hash = 97 * hash + Objects.hashCode(this.term); hash = 97 * hash + (int) (Double.doubleToLongBits(this.ic) ^ (Double.doubleToLongBits(this.ic) >>> 32)); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final PhenotypeTerm other = (PhenotypeTerm) obj; if (!Objects.equals(this.id, other.id)) { return false; } if (!Objects.equals(this.term, other.term)) { return false; } return Double.doubleToLongBits(this.ic) == Double.doubleToLongBits(other.ic); } @Override public String toString() { return "PhenotypeTerm{" + "id=" + id + ", term=" + term + ", ic=" + ic + '}'; } }
package org.jfree.data.time.junit; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; import java.util.TimeZone; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.jfree.data.time.Day; import org.jfree.data.time.MonthConstants; /** * Tests for the {@link Day} class. */ public class DayTests extends TestCase { /** * Returns the tests as a test suite. * * @return The test suite. */ public static Test suite() { return new TestSuite(DayTests.class); } /** * Constructs a new set of tests. * * @param name the name of the tests. */ public DayTests(String name) { super(name); } /** * Common test setup. */ protected void setUp() { // no setup required } /** * Check that a Day instance is equal to itself. * * SourceForge Bug ID: 558850. */ public void testEqualsSelf() { Day day = new Day(); assertTrue(day.equals(day)); } /** * Tests the equals method. */ public void testEquals() { Day day1 = new Day(29, MonthConstants.MARCH, 2002); Day day2 = new Day(29, MonthConstants.MARCH, 2002); assertTrue(day1.equals(day2)); } /** * In GMT, the end of 29 Feb 2004 is java.util.Date(1,078,099,199,999L). * Use this to check the day constructor. */ public void testDateConstructor1() { TimeZone zone = TimeZone.getTimeZone("GMT"); Calendar c = new GregorianCalendar(zone); Day d1 = new Day(new Date(1078099199999L), zone); Day d2 = new Day(new Date(1078099200000L), zone); assertEquals(MonthConstants.FEBRUARY, d1.getMonth()); assertEquals(1078099199999L, d1.getLastMillisecond(c)); assertEquals(MonthConstants.MARCH, d2.getMonth()); assertEquals(1078099200000L, d2.getFirstMillisecond(c)); } /** * In Helsinki, the end of 29 Feb 2004 is * java.util.Date(1,078,091,999,999L). Use this to check the Day * constructor. */ public void testDateConstructor2() { TimeZone zone = TimeZone.getTimeZone("Europe/Helsinki"); Calendar c = new GregorianCalendar(zone); Day d1 = new Day(new Date(1078091999999L), zone); Day d2 = new Day(new Date(1078092000000L), zone); assertEquals(MonthConstants.FEBRUARY, d1.getMonth()); assertEquals(1078091999999L, d1.getLastMillisecond(c)); assertEquals(MonthConstants.MARCH, d2.getMonth()); assertEquals(1078092000000L, d2.getFirstMillisecond(c)); } /** * Set up a day equal to 1 January 1900. Request the previous day, it * should be null. */ public void test1Jan1900Previous() { Day jan1st1900 = new Day(1, MonthConstants.JANUARY, 1900); Day previous = (Day) jan1st1900.previous(); assertNull(previous); } /** * Set up a day equal to 1 January 1900. Request the next day, it should * be 2 January 1900. */ public void test1Jan1900Next() { Day jan1st1900 = new Day(1, MonthConstants.JANUARY, 1900); Day next = (Day) jan1st1900.next(); assertEquals(2, next.getDayOfMonth()); } /** * Set up a day equal to 31 December 9999. Request the previous day, it * should be 30 December 9999. */ public void test31Dec9999Previous() { Day dec31st9999 = new Day(31, MonthConstants.DECEMBER, 9999); Day previous = (Day) dec31st9999.previous(); assertEquals(30, previous.getDayOfMonth()); } /** * Set up a day equal to 31 December 9999. Request the next day, it should * be null. */ public void test31Dec9999Next() { Day dec31st9999 = new Day(31, MonthConstants.DECEMBER, 9999); Day next = (Day) dec31st9999.next(); assertNull(next); } /** * Problem for date parsing. * <p> * This test works only correct if the short pattern of the date * format is "dd/MM/yyyy". If not, this test will result in a * false negative. * * @throws ParseException on parsing errors. */ public void testParseDay() throws ParseException { GregorianCalendar gc = new GregorianCalendar(2001, 12, 31); SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy"); Date reference = format.parse("31/12/2001"); if (reference.equals(gc.getTime())) { // test 1... Day d = Day.parseDay("31/12/2001"); assertEquals(37256, d.getSerialDate().toSerial()); } // test 2... Day d = Day.parseDay("2001-12-31"); assertEquals(37256, d.getSerialDate().toSerial()); } /** * Serialize an instance, restore it, and check for equality. */ public void testSerialization() { Day d1 = new Day(15, 4, 2000); Day d2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(d1); out.close(); ObjectInput in = new ObjectInputStream( new ByteArrayInputStream(buffer.toByteArray()) ); d2 = (Day) in.readObject(); in.close(); } catch (Exception e) { System.out.println(e.toString()); } assertEquals(d1, d2); } /** * Two objects that are equal are required to return the same hashCode. */ public void testHashcode() { Day d1 = new Day(1, 2, 2003); Day d2 = new Day(1, 2, 2003); assertTrue(d1.equals(d2)); int h1 = d1.hashCode(); int h2 = d2.hashCode(); assertEquals(h1, h2); } /** * The {@link Day} class is immutable, so should not be {@link Cloneable}. */ public void testNotCloneable() { Day d = new Day(1, 2, 2003); assertFalse(d instanceof Cloneable); } /** * Some checks for the getSerialIndex() method. */ public void testGetSerialIndex() { Day d = new Day(1, 1, 1900); assertEquals(2, d.getSerialIndex()); d = new Day(15, 4, 2000); assertEquals(36631, d.getSerialIndex()); } /** * Some checks for the getFirstMillisecond() method. */ public void testGetFirstMillisecond() { Locale saved = Locale.getDefault(); Locale.setDefault(Locale.UK); TimeZone savedZone = TimeZone.getDefault(); TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")); Day d = new Day(1, 3, 1970); assertEquals(5094000000L, d.getFirstMillisecond()); Locale.setDefault(saved); TimeZone.setDefault(savedZone); } /** * Some checks for the getFirstMillisecond(TimeZone) method. */ public void testGetFirstMillisecondWithTimeZone() { Day d = new Day(26, 4, 1950); TimeZone zone = TimeZone.getTimeZone("America/Los_Angeles"); Calendar c = new GregorianCalendar(zone); assertEquals(-621187200000L, d.getFirstMillisecond(c)); // try null calendar boolean pass = false; try { d.getFirstMillisecond((Calendar) null); } catch (NullPointerException e) { pass = true; } assertTrue(pass); } /** * Some checks for the getFirstMillisecond(TimeZone) method. */ public void testGetFirstMillisecondWithCalendar() { Day d = new Day(1, 12, 2001); GregorianCalendar calendar = new GregorianCalendar(Locale.GERMANY); calendar.setTimeZone(TimeZone.getTimeZone("Europe/Frankfurt")); assertEquals(1007164800000L, d.getFirstMillisecond(calendar)); // try null calendar boolean pass = false; try { d.getFirstMillisecond((Calendar) null); } catch (NullPointerException e) { pass = true; } assertTrue(pass); } /** * Some checks for the getLastMillisecond() method. */ public void testGetLastMillisecond() { Locale saved = Locale.getDefault(); Locale.setDefault(Locale.UK); TimeZone savedZone = TimeZone.getDefault(); TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")); Day d = new Day(1, 1, 1970); assertEquals(82799999L, d.getLastMillisecond()); Locale.setDefault(saved); TimeZone.setDefault(savedZone); } /** * Some checks for the getLastMillisecond(TimeZone) method. */ public void testGetLastMillisecondWithTimeZone() { Day d = new Day(1, 2, 1950); TimeZone zone = TimeZone.getTimeZone("America/Los_Angeles"); Calendar c = new GregorianCalendar(zone); assertEquals(-628358400001L, d.getLastMillisecond(c)); // try null calendar boolean pass = false; try { d.getLastMillisecond((Calendar) null); } catch (NullPointerException e) { pass = true; } assertTrue(pass); } /** * Some checks for the getLastMillisecond(TimeZone) method. */ public void testGetLastMillisecondWithCalendar() { Day d = new Day(4, 5, 2001); Calendar calendar = Calendar.getInstance( TimeZone.getTimeZone("Europe/London"), Locale.UK); assertEquals(989017199999L, d.getLastMillisecond(calendar)); // try null calendar boolean pass = false; try { d.getLastMillisecond((Calendar) null); } catch (NullPointerException e) { pass = true; } assertTrue(pass); } /** * Some checks for the testNext() method. */ public void testNext() { Day d = new Day(25, 12, 2000); d = (Day) d.next(); assertEquals(2000, d.getYear()); assertEquals(12, d.getMonth()); assertEquals(26, d.getDayOfMonth()); d = new Day(31, 12, 9999); assertNull(d.next()); } /** * Some checks for the getStart() method. */ public void testGetStart() { Locale saved = Locale.getDefault(); Locale.setDefault(Locale.ITALY); Calendar cal = Calendar.getInstance(Locale.ITALY); cal.set(2006, Calendar.NOVEMBER, 3, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); Day d = new Day(3, 11, 2006); assertEquals(cal.getTime(), d.getStart()); Locale.setDefault(saved); } /** * Some checks for the getEnd() method. */ public void testGetEnd() { Locale saved = Locale.getDefault(); Locale.setDefault(Locale.ITALY); Calendar cal = Calendar.getInstance(Locale.ITALY); cal.set(1900, Calendar.JANUARY, 1, 23, 59, 59); cal.set(Calendar.MILLISECOND, 999); Day d = new Day(1, 1, 1900); assertEquals(cal.getTime(), d.getEnd()); Locale.setDefault(saved); } }
// $Id: LargeState.java,v 1.12 2005/10/28 15:53:29 belaban Exp $ package org.jgroups.tests; import org.jgroups.*; /** * Tests transfer of large states. Start first instance with -provider flag and -size flag (default = 1MB). * The start second instance without these flags: it should acquire the state from the first instance. Possibly * tracing should be turned on for FRAG to see the fragmentation taking place, e.g.: * <pre> * trace1=FRAG DEBUG STDOUT * </pre><br> * Note that because fragmentation might generate a lot of small fragments at basically the same time (e.g. size1MB, * FRAG.frag-size=4096 generates a lot of fragments), the send buffer of the unicast socket in UDP might be overloaded, * causing it to drop some packets (default size is 8096 bytes). Therefore the send (and receive) buffers for the unicast * socket have been increased (see ucast_send_buf_size and ucast_recv_buf_size below).<p> * If we didn't do this, we would have some retransmission, slowing the state transfer down. * * @author Bela Ban Dec 13 2001 */ public class LargeState { Channel channel; byte[] state=null; Thread getter=null; boolean rc=false; String props; long start, stop; boolean provider=true; public void start(boolean provider, long size, String props) throws Exception { this.provider=provider; channel=new JChannel(props); channel.setOpt(Channel.GET_STATE_EVENTS, Boolean.TRUE); channel.connect("TestChannel"); System.out.println("-- connected to channel"); if(provider) { System.out.println("Creating state of " + size + " bytes"); state=createLargeState(size); System.out.println("Done. Waiting for other members to join and fetch large state"); } else { System.out.println("Getting state"); start=System.currentTimeMillis(); rc=channel.getState(null, 30000); System.out.println("getState(), rc=" + rc); if(rc == false) { channel.close(); return; } } mainLoop(); channel.close(); } public void mainLoop() { Object ret; try { while(true) { ret=channel.receive(0); if(ret instanceof Message) { System.out.println("-- received msg " + ((Message)ret).getObject() + " from " + ((Message)ret).getSrc()); } else if(ret instanceof GetStateEvent) { System.out.println("--> returned state: " + ret); channel.returnState(state); } else if(ret instanceof SetStateEvent) { stop=System.currentTimeMillis(); byte[] new_state=((SetStateEvent)ret).getArg(); if(new_state != null) { state=new_state; System.out.println("<-- Received state, size =" + state.length + " (took " + (stop-start) + "ms)"); } if(!provider) break; } } } catch(Exception e) { } } byte[] createLargeState(long size) { StringBuffer ret=new StringBuffer(); for(int i=0; i < size; i++) ret.append('.'); return ret.toString().getBytes(); } public static void main(String[] args) { boolean provider=false; long size=1024 * 1024; String props="UDP(mcast_addr=239.255.0.35;mcast_port=7500;ip_ttl=2;" + "mcast_send_buf_size=150000;mcast_recv_buf_size=80000;" + "ucast_send_buf_size=80000;ucast_recv_buf_size=150000):" + "PING(timeout=2000;num_initial_members=3):" + "MERGE2(min_interval=5000;max_interval=10000):" + "FD_SOCK:" + "VERIFY_SUSPECT(timeout=1500):" + "pbcast.NAKACK(gc_lag=50;retransmit_timeout=300,600,1200,2400,4800):" + "UNICAST(timeout=300,600,900,1200,2400):" + "pbcast.STABLE(desired_avg_gossip=20000):" + "FRAG(frag_size=60000;down_thread=false;up_thread=false):" + "pbcast.GMS(join_timeout=5000;join_retry_timeout=2000;" + "shun=false;print_local_addr=true):" + "pbcast.STATE_TRANSFER"; for(int i=0; i < args.length; i++) { if("-help".equals(args[i])) { help(); return; } if("-provider".equals(args[i])) { provider=true; continue; } if("-size".equals(args[i])) { size=Long.parseLong(args[++i]); continue; } if("-props".equals(args[i])) { props=args[++i]; } } try { new LargeState().start(provider, size, props); } catch(Exception e) { System.err.println(e); } } static void help() { System.out.println("LargeState [-help] [-size <size of state in bytes] [-provider] [-props <properties>]"); } }
package it.unibz.krdb.obda.owlrefplatform.core.resultset; import it.unibz.krdb.obda.model.BNode; import it.unibz.krdb.obda.model.Constant; import it.unibz.krdb.obda.model.OBDADataFactory; import it.unibz.krdb.obda.model.OBDAException; import it.unibz.krdb.obda.model.OBDAResultSet; import it.unibz.krdb.obda.model.OBDAStatement; import it.unibz.krdb.obda.model.ValueConstant; import it.unibz.krdb.obda.model.Predicate.COL_TYPE; import it.unibz.krdb.obda.model.impl.OBDADataFactoryImpl; import java.net.URI; import java.net.URISyntaxException; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Vector; import com.hp.hpl.jena.iri.IRI; import com.hp.hpl.jena.iri.IRIFactory; public class QuestResultset implements OBDAResultSet { private ResultSet set = null; private OBDAStatement st; private Vector<String> signature; private HashMap<String, Integer> columnMap = new HashMap<String, Integer>(); private HashMap<String, String> bnodeMap = new HashMap<String, String>(); private int bnodeCounter = 0; private OBDADataFactory fac = OBDADataFactoryImpl.getInstance(); /*** * Constructs an OBDA statement from an SQL statement, a signature described * by terms and a statement. The statement is maintained only as a reference * for closing operations. * * @param set * @param signature * A list of terms that determines the type of the columns of * this results set. * @param st * @throws OBDAException */ public QuestResultset(ResultSet set, List<String> signature, OBDAStatement st) throws OBDAException { this.set = set; this.st = st; this.signature = new Vector<String>(signature); for (int j = 1; j <= signature.size(); j++) { columnMap.put(signature.get(j - 1), j - 1); } } public double getDouble(int column) throws OBDAException { try { return set.getDouble(signature.get(column - 1)); } catch (SQLException e) { throw new OBDAException(e.getMessage()); } } public int getInt(int column) throws OBDAException { try { return set.getInt(signature.get(column - 1)); } catch (SQLException e) { throw new OBDAException(e.getMessage()); } } public Object getObject(int column) throws OBDAException { try { return set.getObject(signature.get(column - 1)); } catch (SQLException e) { throw new OBDAException(e.getMessage()); } } public String getString(int column) throws OBDAException { try { return set.getString(signature.get(column - 1)); } catch (SQLException e) { throw new OBDAException(e.getMessage()); } } public URI getURI(int column) throws OBDAException { return getURI(signature.get(column - 1)); } public IRI getIRI(int column) throws OBDAException { return getIRI(signature.get(column - 1)); } public int getColumCount() throws OBDAException { return signature.size(); } public int getFetchSize() throws OBDAException { try { return set.getFetchSize(); } catch (SQLException e) { throw new OBDAException(e.getMessage()); } } public List<String> getSignature() throws OBDAException { return signature; } public boolean nextRow() throws OBDAException { try { return set.next(); } catch (SQLException e) { throw new OBDAException(e); } } public void close() throws OBDAException { try { set.close(); } catch (SQLException e) { throw new OBDAException(e); } } @Override public OBDAStatement getStatement() { return st; } @Override public Constant getConstant(int column) throws OBDAException { return getConstant(signature.get(column - 1)); } @Override public ValueConstant getLiteral(int column) throws OBDAException { return getLiteral(signature.get(column - 1)); } @Override public BNode getBNode(int column) throws OBDAException { return getBNode(signature.get(column - 1)); } @Override public Constant getConstant(String name) throws OBDAException { Constant result = null; try { COL_TYPE type = getQuestType((byte) set.getInt(name + "QuestType")); String realValue = set.getString(name); if (type == null || realValue == null) { return null; } else { if (type == COL_TYPE.OBJECT) { // URI value = getURI(name); IRI irivalue = getIRI(name); // result = fac.getURIConstant(value); result = fac.getURIConstant(irivalue); } else if (type == COL_TYPE.BNODE) { String rawLabel = set.getString(name); String scopedLabel = this.bnodeMap.get(rawLabel); if (scopedLabel == null) { scopedLabel = "b" + bnodeCounter; bnodeCounter += 1; bnodeMap.put(rawLabel, scopedLabel); } result = fac.getBNodeConstant(scopedLabel); } else { /* * The constant is a literal, we need to find if its * rdfs:Literal or a normal literal and construct it properly. */ if (type == COL_TYPE.LITERAL) { String value = set.getString(name); String language = set.getString(name + "Lang"); if (language == null || language.trim().equals("")) { result = fac.getValueConstant(value); } else { result = fac.getValueConstant(value, language); } } else if (type == COL_TYPE.BOOLEAN) { boolean value = set.getBoolean(name); if (value) { result = fac.getValueConstant("true", type); } else { result = fac.getValueConstant("false", type); } } else if (type == COL_TYPE.DOUBLE) { double d = set.getDouble(name); //format name into correct double representation DecimalFormat formatter = new DecimalFormat("0.0 DecimalFormatSymbols symbol = DecimalFormatSymbols.getInstance(); symbol.setDecimalSeparator('.'); formatter.setDecimalFormatSymbols(symbol); String s = formatter.format(d); result = fac.getValueConstant(s, type); } else if (type == COL_TYPE.DATETIME) { Timestamp value = set.getTimestamp(name); result = fac.getValueConstant( value.toString().replace(' ', 'T'), type); } else { result = fac.getValueConstant(realValue, type); } } } } catch (IllegalArgumentException e) { Throwable cause = e.getCause(); if (cause instanceof URISyntaxException) { OBDAException ex = new OBDAException( "Error creating an object's URI. This is often due to mapping with URI templates that refer to columns in which illegal values may appear, e.g., white spaces and special characters. To avoid this error do not use these columns for URI templates in your mappings, or process them using SQL functions (e.g., string replacement) in the SQL queries of your mappings. Note that this last option can be bad for performance, future versions of Quest will allow to string manipulation functions in URI templates to avoid these performance problems." + "\n\nDetailed message: " + cause.getMessage()); ex.setStackTrace(e.getStackTrace()); throw ex; } throw e; } catch (SQLException e) { throw new OBDAException(e); } return result; } private COL_TYPE getQuestType(byte sqltype) { if (sqltype == 1) { return COL_TYPE.OBJECT; } else if (sqltype == 2) { return COL_TYPE.BNODE; } else if (sqltype == 3) { return COL_TYPE.LITERAL; } else if (sqltype == 4) { return COL_TYPE.INTEGER; } else if (sqltype == 5) { return COL_TYPE.DECIMAL; } else if (sqltype == 6) { return COL_TYPE.DOUBLE; } else if (sqltype == 7) { return COL_TYPE.STRING; } else if (sqltype == 8) { return COL_TYPE.DATETIME; } else if (sqltype == 9) { return COL_TYPE.BOOLEAN; }else if (sqltype == 0) { return null; } else { throw new RuntimeException("COLTYPE unknown: " + sqltype); } } @Override public URI getURI(String name) throws OBDAException { String result = ""; try { result = set.getString(name); return URI.create(result);//.replace(' ', '_')); } catch (SQLException e) { throw new OBDAException(e); } } @Override public IRI getIRI(String name) throws OBDAException { String result = ""; try { result = set.getString(name); IRIFactory irif = new IRIFactory(); IRI iri = irif.create(result); return iri; } catch (SQLException e) { throw new OBDAException(e); } } @Override public ValueConstant getLiteral(String name) throws OBDAException { Constant result; result = getConstant(name); return (ValueConstant) result; } @Override public BNode getBNode(String name) throws OBDAException { Constant result; result = getConstant(name); return (BNode) result; } }
package org.springframework.ui.format.jodatime; import static org.junit.Assert.assertEquals; import java.util.Calendar; import java.util.Date; import java.util.Locale; import org.joda.time.DateTime; import org.joda.time.LocalDate; import org.joda.time.LocalDateTime; import org.joda.time.LocalTime; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.springframework.beans.MutablePropertyValues; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.ui.format.jodatime.DateTimeFormat.Style; import org.springframework.ui.format.support.FormattingConversionService; import org.springframework.validation.DataBinder; public class JodaTimeFormattingTests { private FormattingConversionService conversionService = new FormattingConversionService(); private DataBinder binder; @Before public void setUp() { JodaTimeFormattingConfigurer configurer = new JodaTimeFormattingConfigurer(); configurer.installJodaTimeFormatting(conversionService); binder = new DataBinder(new JodaTimeBean()); binder.setConversionService(conversionService); LocaleContextHolder.setLocale(Locale.US); } @After public void tearDown() { LocaleContextHolder.setLocale(null); } @Test public void testBindLocalDate() { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.addPropertyValue("localDate", "10/31/09"); binder.bind(propertyValues); assertEquals(0, binder.getBindingResult().getErrorCount()); assertEquals("10/31/09", binder.getBindingResult().getFieldValue("localDate")); } @Test public void testBindLocalDateArray() { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.addPropertyValue("localDate", new String[] { "10/31/09" }); binder.bind(propertyValues); assertEquals(0, binder.getBindingResult().getErrorCount()); } @Test public void testBindLocalDateAnnotated() { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.addPropertyValue("localDateAnnotated", "Oct 31, 2009"); binder.bind(propertyValues); assertEquals(0, binder.getBindingResult().getErrorCount()); assertEquals("Oct 31, 2009", binder.getBindingResult().getFieldValue("localDateAnnotated")); } @Test public void testBindLocalTime() { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.addPropertyValue("localTime", "12:00 PM"); binder.bind(propertyValues); assertEquals(0, binder.getBindingResult().getErrorCount()); assertEquals("12:00 PM", binder.getBindingResult().getFieldValue("localTime")); } @Test public void testBindLocalTimeAnnotated() { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.addPropertyValue("localTimeAnnotated", "12:00:00 PM"); binder.bind(propertyValues); assertEquals(0, binder.getBindingResult().getErrorCount()); assertEquals("12:00:00 PM", binder.getBindingResult().getFieldValue("localTimeAnnotated")); } @Test public void testBindLocalDateTime() { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.addPropertyValue("localDateTime", "10/31/09 12:00 PM"); binder.bind(propertyValues); assertEquals(0, binder.getBindingResult().getErrorCount()); assertEquals("10/31/09 12:00 PM", binder.getBindingResult().getFieldValue("localDateTime")); } @Test public void testBindLocalDateTimeAnnotated() { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.addPropertyValue("localDateTimeAnnotated", "Saturday, October 31, 2009 12:00:00 PM "); binder.bind(propertyValues); assertEquals(0, binder.getBindingResult().getErrorCount()); assertEquals("Saturday, October 31, 2009 12:00:00 PM ", binder.getBindingResult().getFieldValue("localDateTimeAnnotated")); } @Test @Ignore public void testBindDateTime() { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.addPropertyValue("dateTime", "10/31/09 12:00 PM"); // this doesn't work because the String->ReadableInstant converter doesn't match due to String->@DateTimeFormat DateTime Matchable taking precedence binder.bind(propertyValues); System.out.println(binder.getBindingResult()); assertEquals(0, binder.getBindingResult().getErrorCount()); assertEquals("10/31/09 12:00 PM", binder.getBindingResult().getFieldValue("dateTime")); } @Test public void testBindDateTimeAnnotated() { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.addPropertyValue("dateTimeAnnotated", "Oct 31, 2009 12:00 PM"); binder.bind(propertyValues); System.out.println(binder.getBindingResult()); assertEquals(0, binder.getBindingResult().getErrorCount()); assertEquals("Oct 31, 2009 12:00 PM", binder.getBindingResult().getFieldValue("dateTimeAnnotated")); } @Test public void testBindDate() { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.addPropertyValue("date", "10/31/09 12:00 PM"); binder.bind(propertyValues); assertEquals(0, binder.getBindingResult().getErrorCount()); assertEquals("10/31/09 12:00 PM", binder.getBindingResult().getFieldValue("date")); } @Test public void testBindDateAnnotated() { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.addPropertyValue("dateAnnotated", "10/31/09"); binder.bind(propertyValues); assertEquals(0, binder.getBindingResult().getErrorCount()); assertEquals("10/31/09", binder.getBindingResult().getFieldValue("dateAnnotated")); } @Test public void testBindCalendar() { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.addPropertyValue("calendar", "10/31/09 12:00 PM"); binder.bind(propertyValues); assertEquals(0, binder.getBindingResult().getErrorCount()); assertEquals("10/31/09 12:00 PM", binder.getBindingResult().getFieldValue("calendar")); } @Test public void testBindCalendarAnnotated() { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.addPropertyValue("calendarAnnotated", "10/31/09"); binder.bind(propertyValues); assertEquals(0, binder.getBindingResult().getErrorCount()); assertEquals("10/31/09", binder.getBindingResult().getFieldValue("calendarAnnotated")); } @Test public void testBindLong() { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.addPropertyValue("millis", "1256961600"); binder.bind(propertyValues); assertEquals(0, binder.getBindingResult().getErrorCount()); assertEquals("1256961600", binder.getBindingResult().getFieldValue("millis")); } @Test public void testBindLongAnnotated() { MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.addPropertyValue("millisAnnotated", "10/31/09"); binder.bind(propertyValues); assertEquals(0, binder.getBindingResult().getErrorCount()); assertEquals("10/31/09", binder.getBindingResult().getFieldValue("millisAnnotated")); } public static class JodaTimeBean { private LocalDate localDate; @DateTimeFormat(dateStyle = Style.MEDIUM) private LocalDate localDateAnnotated; private LocalTime localTime; @DateTimeFormat(timeStyle = Style.MEDIUM) private LocalTime localTimeAnnotated; private LocalDateTime localDateTime; @DateTimeFormat(dateStyle = Style.FULL, timeStyle = Style.FULL) private LocalDateTime localDateTimeAnnotated; private DateTime dateTime; @DateTimeFormat(dateStyle = Style.MEDIUM, timeStyle = Style.SHORT) private DateTime dateTimeAnnotated; private Date date; @DateTimeFormat(dateStyle = Style.SHORT) private Date dateAnnotated; private Calendar calendar; @DateTimeFormat(dateStyle = Style.SHORT) private Calendar calendarAnnotated; private Long millis; @DateTimeFormat(dateStyle = Style.SHORT) private Long millisAnnotated; public LocalDate getLocalDate() { return localDate; } public void setLocalDate(LocalDate localDate) { this.localDate = localDate; } public LocalDate getLocalDateAnnotated() { return localDateAnnotated; } public void setLocalDateAnnotated(LocalDate localDateAnnotated) { this.localDateAnnotated = localDateAnnotated; } public LocalTime getLocalTime() { return localTime; } public void setLocalTime(LocalTime localTime) { this.localTime = localTime; } public LocalTime getLocalTimeAnnotated() { return localTimeAnnotated; } public void setLocalTimeAnnotated(LocalTime localTimeAnnotated) { this.localTimeAnnotated = localTimeAnnotated; } public LocalDateTime getLocalDateTime() { return localDateTime; } public void setLocalDateTime(LocalDateTime localDateTime) { this.localDateTime = localDateTime; } public LocalDateTime getLocalDateTimeAnnotated() { return localDateTimeAnnotated; } public void setLocalDateTimeAnnotated(LocalDateTime localDateTimeAnnotated) { this.localDateTimeAnnotated = localDateTimeAnnotated; } public DateTime getDateTime() { return dateTime; } public void setDateTime(DateTime dateTime) { this.dateTime = dateTime; } public DateTime getDateTimeAnnotated() { return dateTimeAnnotated; } public void setDateTimeAnnotated(DateTime dateTimeAnnotated) { this.dateTimeAnnotated = dateTimeAnnotated; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public Date getDateAnnotated() { return dateAnnotated; } public void setDateAnnotated(Date dateAnnotated) { this.dateAnnotated = dateAnnotated; } public Calendar getCalendar() { return calendar; } public void setCalendar(Calendar calendar) { this.calendar = calendar; } public Calendar getCalendarAnnotated() { return calendarAnnotated; } public void setCalendarAnnotated(Calendar calendarAnnotated) { this.calendarAnnotated = calendarAnnotated; } public Long getMillis() { return millis; } public void setMillis(Long millis) { this.millis = millis; } public Long getMillisAnnotated() { return millisAnnotated; } public void setMillisAnnotated(Long millisAnnotated) { this.millisAnnotated = millisAnnotated; } } }
package org.postgresql.test; import org.postgresql.PGConnection; import org.postgresql.PGProperty; import org.postgresql.core.BaseConnection; import org.postgresql.core.ServerVersion; import org.postgresql.core.TransactionState; import org.postgresql.core.Version; import org.postgresql.jdbc.GSSEncMode; import org.postgresql.jdbc.PgConnection; import org.postgresql.util.PSQLException; import org.checkerframework.checker.nullness.qual.Nullable; import org.junit.Assert; import java.io.Closeable; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * Utility class for JDBC tests. */ public class TestUtil { /* * The case is as follows: * 1. Typically the database and hostname are taken from System.properties or build.properties or build.local.properties * That enables to override test DB via system property * 2. There are tests where different DBs should be used (e.g. SSL tests), so we can't just use DB name from system property * That is why _test_ properties exist: they overpower System.properties and build.properties */ public static final String SERVER_HOST_PORT_PROP = "_test_hostport"; public static final String DATABASE_PROP = "_test_database"; /* * Returns the Test database JDBC URL */ public static String getURL() { return getURL(getServer(), + getPort()); } public static String getURL(String server, int port) { return getURL(server + ":" + port, getDatabase()); } public static String getURL(String hostport, String database) { String logLevel = ""; if (getLogLevel() != null && !getLogLevel().equals("")) { logLevel = "&loggerLevel=" + getLogLevel(); } String logFile = ""; if (getLogFile() != null && !getLogFile().equals("")) { logFile = "&loggerFile=" + getLogFile(); } String protocolVersion = ""; if (getProtocolVersion() != 0) { protocolVersion = "&protocolVersion=" + getProtocolVersion(); } String options = ""; if (getOptions() != null) { options = "&options=" + getOptions(); } String binaryTransfer = ""; if (getBinaryTransfer() != null && !getBinaryTransfer().equals("")) { binaryTransfer = "&binaryTransfer=" + getBinaryTransfer(); } String receiveBufferSize = ""; if (getReceiveBufferSize() != -1) { receiveBufferSize = "&receiveBufferSize=" + getReceiveBufferSize(); } String sendBufferSize = ""; if (getSendBufferSize() != -1) { sendBufferSize = "&sendBufferSize=" + getSendBufferSize(); } String ssl = ""; if (getSSL() != null) { ssl = "&ssl=" + getSSL(); } return "jdbc:postgresql: + hostport + "/" + database + "?ApplicationName=Driver Tests" + logLevel + logFile + protocolVersion + options + binaryTransfer + receiveBufferSize + sendBufferSize + ssl; } /* * Returns the Test server */ public static String getServer() { return System.getProperty("server", "localhost"); } /* * Returns the Test port */ public static int getPort() { return Integer.parseInt(System.getProperty("port", System.getProperty("def_pgport"))); } /* * Returns the server side prepared statement threshold. */ public static int getPrepareThreshold() { return Integer.parseInt(System.getProperty("preparethreshold", "5")); } public static int getProtocolVersion() { return Integer.parseInt(System.getProperty("protocolVersion", "0")); } public static String getOptions() { return System.getProperty("options"); } /* * Returns the Test database */ public static String getDatabase() { return System.getProperty("database"); } /* * Returns the Postgresql username */ public static String getUser() { return System.getProperty("username"); } /* * Returns the user's password */ public static String getPassword() { return System.getProperty("password"); } /* * Returns password for default callbackhandler */ public static String getSslPassword() { return System.getProperty(PGProperty.SSL_PASSWORD.getName()); } /* * Return the GSSEncMode for the tests */ public static GSSEncMode getGSSEncMode() throws PSQLException { return GSSEncMode.of(System.getProperties()); } /* * Returns the user for SSPI authentication tests */ public static String getSSPIUser() { return System.getProperty("sspiusername"); } /* * postgres like user */ public static String getPrivilegedUser() { return System.getProperty("privilegedUser"); } public static String getPrivilegedPassword() { return System.getProperty("privilegedPassword"); } /* * Returns the log level to use */ public static String getLogLevel() { return System.getProperty("loggerLevel"); } /* * Returns the log file to use */ public static String getLogFile() { return System.getProperty("loggerFile"); } /* * Returns the binary transfer mode to use */ public static String getBinaryTransfer() { return System.getProperty("binaryTransfer"); } public static int getSendBufferSize() { return Integer.parseInt(System.getProperty("sendBufferSize", "-1")); } public static int getReceiveBufferSize() { return Integer.parseInt(System.getProperty("receiveBufferSize", "-1")); } public static String getSSL() { return System.getProperty("ssl"); } static { try { initDriver(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException("Unable to initialize driver", e); } } private static boolean initialized = false; public static Properties loadPropertyFiles(String... names) { Properties p = new Properties(); for (String name : names) { for (int i = 0; i < 2; i++) { // load x.properties, then x.local.properties if (i == 1 && name.endsWith(".properties") && !name.endsWith(".local.properties")) { name = name.replaceAll("\\.properties$", ".local.properties"); } File f = getFile(name); if (!f.exists()) { System.out.println("Configuration file " + f.getAbsolutePath() + " does not exist. Consider adding it to specify test db host and login"); continue; } try { p.load(new FileInputStream(f)); } catch (IOException ex) { // ignore } } } return p; } public static void initDriver() { synchronized (TestUtil.class) { if (initialized) { return; } Properties p = loadPropertyFiles("build.properties"); p.putAll(System.getProperties()); System.getProperties().putAll(p); initialized = true; } } /** * Resolves file path with account of {@code build.properties.relative.path}. This is a bit tricky * since during maven release, maven does a temporary checkout to {@code core/target/checkout} * folder, so that script should somehow get {@code build.local.properties} * * @param name original name of the file, as if it was in the root pgjdbc folder * @return actual location of the file */ public static File getFile(String name) { if (name == null) { throw new IllegalArgumentException("null file name is not expected"); } if (name.startsWith("/")) { return new File(name); } return new File(System.getProperty("build.properties.relative.path", "../"), name); } /** * Get a connection using a privileged user mostly for tests that the ability to load C functions * now as of 4/14. * * @return connection using a privileged user mostly for tests that the ability to load C * functions now as of 4/14 */ public static Connection openPrivilegedDB() throws SQLException { initDriver(); Properties properties = new Properties(); PGProperty.GSS_ENC_MODE.set(properties,getGSSEncMode().value); properties.setProperty("user", getPrivilegedUser()); properties.setProperty("password", getPrivilegedPassword()); properties.setProperty("options", "-c synchronous_commit=on"); return DriverManager.getConnection(getURL(), properties); } public static Connection openReplicationConnection() throws Exception { Properties properties = new Properties(); PGProperty.ASSUME_MIN_SERVER_VERSION.set(properties, "9.4"); PGProperty.PROTOCOL_VERSION.set(properties, "3"); PGProperty.REPLICATION.set(properties, "database"); //Only simple query protocol available for replication connection PGProperty.PREFER_QUERY_MODE.set(properties, "simple"); properties.setProperty("username", TestUtil.getPrivilegedUser()); properties.setProperty("password", TestUtil.getPrivilegedPassword()); properties.setProperty("options", "-c synchronous_commit=on"); return TestUtil.openDB(properties); } /** * Helper - opens a connection. * * @return connection */ public static Connection openDB() throws SQLException { return openDB(new Properties()); } /* * Helper - opens a connection with the allowance for passing additional parameters, like * "compatible". */ public static Connection openDB(Properties props) throws SQLException { initDriver(); // Allow properties to override the user name. String user = props.getProperty("username"); if (user == null) { user = getUser(); } if (user == null) { throw new IllegalArgumentException( "user name is not specified. Please specify 'username' property via -D or build.properties"); } props.setProperty("user", user); // Allow properties to override the password. String password = props.getProperty("password"); if (password == null) { password = getPassword() != null ? getPassword() : ""; } props.setProperty("password", password); String sslPassword = getSslPassword(); if (sslPassword != null) { PGProperty.SSL_PASSWORD.set(props, sslPassword); } if (!props.containsKey(PGProperty.PREPARE_THRESHOLD.getName())) { PGProperty.PREPARE_THRESHOLD.set(props, getPrepareThreshold()); } if (!props.containsKey(PGProperty.PREFER_QUERY_MODE.getName())) { String value = System.getProperty(PGProperty.PREFER_QUERY_MODE.getName()); if (value != null) { props.put(PGProperty.PREFER_QUERY_MODE.getName(), value); } } // Enable Base4 tests to override host,port,database String hostport = props.getProperty(SERVER_HOST_PORT_PROP, getServer() + ":" + getPort()); String database = props.getProperty(DATABASE_PROP, getDatabase()); // Set GSSEncMode for tests only in the case the property is already missing if (PGProperty.GSS_ENC_MODE.getSetString(props) == null) { PGProperty.GSS_ENC_MODE.set(props, getGSSEncMode().value); } return DriverManager.getConnection(getURL(hostport, database), props); } /* * Helper - closes an open connection. */ public static void closeDB(@Nullable Connection con) throws SQLException { if (con != null) { con.close(); } } /* * Helper - creates a test schema for use by a test */ public static void createSchema(Connection con, String schema) throws SQLException { Statement st = con.createStatement(); try { // Drop the schema dropSchema(con, schema); // Now create the schema String sql = "CREATE SCHEMA " + schema; st.executeUpdate(sql); } finally { closeQuietly(st); } } /* * Helper - drops a schema */ public static void dropSchema(Connection con, String schema) throws SQLException { dropObject(con, "SCHEMA", schema); } /* * Helper - creates a test table for use by a test */ public static void createTable(Connection con, String table, String columns) throws SQLException { Statement st = con.createStatement(); try { // Drop the table dropTable(con, table); // Now create the table String sql = "CREATE TABLE " + table + " (" + columns + ")"; st.executeUpdate(sql); } finally { closeQuietly(st); } } /** * Helper creates a temporary table. * * @param con Connection * @param table String * @param columns String */ public static void createTempTable(Connection con, String table, String columns) throws SQLException { Statement st = con.createStatement(); try { // Drop the table dropTable(con, table); // Now create the table st.executeUpdate("create temp table " + table + " (" + columns + ")"); } finally { closeQuietly(st); } } /* * Helper - creates a unlogged table for use by a test. * Unlogged tables works from PostgreSQL 9.1+ */ public static void createUnloggedTable(Connection con, String table, String columns) throws SQLException { Statement st = con.createStatement(); try { // Drop the table dropTable(con, table); String unlogged = haveMinimumServerVersion(con, ServerVersion.v9_1) ? "UNLOGGED" : ""; // Now create the table st.executeUpdate("CREATE " + unlogged + " TABLE " + table + " (" + columns + ")"); } finally { closeQuietly(st); } } /* * Helper - creates a view */ public static void createView(Connection con, String viewName, String query) throws SQLException { Statement st = con.createStatement(); try { // Drop the view dropView(con, viewName); String sql = "CREATE VIEW " + viewName + " AS " + query; st.executeUpdate(sql); } finally { closeQuietly(st); } } /** * Helper creates an enum type. * * @param con Connection * @param name String * @param values String */ public static void createEnumType(Connection con, String name, String values) throws SQLException { Statement st = con.createStatement(); try { dropType(con, name); // Now create the table st.executeUpdate("create type " + name + " as enum (" + values + ")"); } finally { closeQuietly(st); } } /** * Helper creates an composite type. * * @param con Connection * @param name String * @param values String */ public static void createCompositeType(Connection con, String name, String values) throws SQLException { createCompositeType(con, name, values, true); } /** * Helper creates an composite type. * * @param con Connection * @param name String * @param values String */ public static void createCompositeType(Connection con, String name, String values, boolean shouldDrop) throws SQLException { Statement st = con.createStatement(); try { if (shouldDrop) { dropType(con, name); } // Now create the type st.executeUpdate("CREATE TYPE " + name + " AS (" + values + ")"); } finally { closeQuietly(st); } } /** * Drops a domain. * * @param con Connection * @param domain String */ public static void dropDomain(Connection con, String domain) throws SQLException { dropObject(con, "DOMAIN", domain); } /** * Helper creates a domain. * * @param con Connection * @param name String * @param values String */ public static void createDomain(Connection con, String name, String values) throws SQLException { Statement st = con.createStatement(); try { dropDomain(con, name); // Now create the table st.executeUpdate("create domain " + name + " as " + values); } finally { closeQuietly(st); } } /* * drop a sequence because older versions don't have dependency information for serials */ public static void dropSequence(Connection con, String sequence) throws SQLException { dropObject(con, "SEQUENCE", sequence); } /* * Helper - drops a table */ public static void dropTable(Connection con, String table) throws SQLException { dropObject(con, "TABLE", table); } /* * Helper - drops a view */ public static void dropView(Connection con, String view) throws SQLException { dropObject(con, "VIEW", view); } /* * Helper - drops a type */ public static void dropType(Connection con, String type) throws SQLException { dropObject(con, "TYPE", type); } private static void dropObject(Connection con, String type, String name) throws SQLException { Statement stmt = con.createStatement(); try { if (con.getAutoCommit()) { // Not in a transaction so ignore error for missing object stmt.executeUpdate("DROP " + type + " IF EXISTS " + name + " CASCADE"); } else { // In a transaction so do not ignore errors for missing object stmt.executeUpdate("DROP " + type + " " + name + " CASCADE"); } } finally { closeQuietly(stmt); } } public static void assertNumberOfRows(Connection con, String tableName, int expectedRows, String message) throws SQLException { PreparedStatement ps = null; ResultSet rs = null; try { ps = con.prepareStatement("select count(*) from " + tableName + " as t"); rs = ps.executeQuery(); rs.next(); Assert.assertEquals(message, expectedRows, rs.getInt(1)); } finally { closeQuietly(rs); closeQuietly(ps); } } public static void assertTransactionState(String message, Connection con, TransactionState expected) { TransactionState actual = TestUtil.getTransactionState(con); Assert.assertEquals(message, expected, actual); } /* * Helper - generates INSERT SQL - very simple */ public static String insertSQL(String table, String values) { return insertSQL(table, null, values); } public static String insertSQL(String table, String columns, String values) { String s = "INSERT INTO " + table; if (columns != null) { s = s + " (" + columns + ")"; } return s + " VALUES (" + values + ")"; } /* * Helper - generates SELECT SQL - very simple */ public static String selectSQL(String table, String columns) { return selectSQL(table, columns, null, null); } public static String selectSQL(String table, String columns, String where) { return selectSQL(table, columns, where, null); } public static String selectSQL(String table, String columns, String where, String other) { String s = "SELECT " + columns + " FROM " + table; if (where != null) { s = s + " WHERE " + where; } if (other != null) { s = s + " " + other; } return s; } /* * Helper to prefix a number with leading zeros - ugly but it works... * * @param v value to prefix * * @param l number of digits (0-10) */ public static String fix(int v, int l) { String s = "0000000000".substring(0, l) + Integer.toString(v); return s.substring(s.length() - l); } public static String escapeString(Connection con, String value) throws SQLException { if (con == null) { throw new NullPointerException("Connection is null"); } if (con instanceof PgConnection) { return ((PgConnection) con).escapeString(value); } return value; } public static boolean getStandardConformingStrings(Connection con) { if (con == null) { throw new NullPointerException("Connection is null"); } if (con instanceof PgConnection) { return ((PgConnection) con).getStandardConformingStrings(); } return false; } /** * Determine if the given connection is connected to a server with a version of at least the given * version. This is convenient because we are working with a java.sql.Connection, not an Postgres * connection. */ public static boolean haveMinimumServerVersion(Connection con, int version) throws SQLException { if (con == null) { throw new NullPointerException("Connection is null"); } if (con instanceof PgConnection) { return ((PgConnection) con).haveMinimumServerVersion(version); } return false; } public static boolean haveMinimumServerVersion(Connection con, Version version) throws SQLException { if (con == null) { throw new NullPointerException("Connection is null"); } if (con instanceof PgConnection) { return ((PgConnection) con).haveMinimumServerVersion(version); } return false; } public static boolean haveMinimumJVMVersion(String version) { String jvm = java.lang.System.getProperty("java.version"); return (jvm.compareTo(version) >= 0); } public static boolean haveIntegerDateTimes(Connection con) { if (con == null) { throw new NullPointerException("Connection is null"); } if (con instanceof PgConnection) { return ((PgConnection) con).getQueryExecutor().getIntegerDateTimes(); } return false; } /** * Print a ResultSet to System.out. This is useful for debugging tests. */ public static void printResultSet(ResultSet rs) throws SQLException { ResultSetMetaData rsmd = rs.getMetaData(); for (int i = 1; i <= rsmd.getColumnCount(); i++) { if (i != 1) { System.out.print(", "); } System.out.print(rsmd.getColumnName(i)); } System.out.println(); while (rs.next()) { for (int i = 1; i <= rsmd.getColumnCount(); i++) { if (i != 1) { System.out.print(", "); } System.out.print(rs.getString(i)); } System.out.println(); } } public static List<String> resultSetToLines(ResultSet rs) throws SQLException { List<String> res = new ArrayList<String>(); ResultSetMetaData rsmd = rs.getMetaData(); StringBuilder sb = new StringBuilder(); while (rs.next()) { sb.setLength(0); for (int i = 1; i <= rsmd.getColumnCount(); i++) { if (i != 1) { sb.append(','); } sb.append(rs.getString(i)); } res.add(sb.toString()); } return res; } public static String join(List<String> list) { StringBuilder sb = new StringBuilder(); for (String s : list) { if (sb.length() > 0) { sb.append('\n'); } sb.append(s); } return sb.toString(); } /* * Find the column for the given label. Only SQLExceptions for system or set-up problems are * thrown. The PSQLState.UNDEFINED_COLUMN type exception is consumed to allow cleanup. Relying on * the caller to detect if the column lookup was successful. */ public static int findColumn(PreparedStatement query, String label) throws SQLException { int returnValue = 0; ResultSet rs = query.executeQuery(); if (rs.next()) { try { returnValue = rs.findColumn(label); } catch (SQLException sqle) { } // consume exception to allow cleanup of resource. } rs.close(); return returnValue; } /** * Close a resource and ignore any errors during closing. */ public static void closeQuietly(@Nullable Closeable resource) { if (resource != null) { try { resource.close(); } catch (Exception ignore) { } } } /** * Close a Connection and ignore any errors during closing. */ public static void closeQuietly(@Nullable Connection conn) { if (conn != null) { try { conn.close(); } catch (SQLException ignore) { } } } /** * Close a Statement and ignore any errors during closing. */ public static void closeQuietly(@Nullable Statement stmt) { if (stmt != null) { try { stmt.close(); } catch (SQLException ignore) { } } } /** * Close a ResultSet and ignore any errors during closing. */ public static void closeQuietly(@Nullable ResultSet rs) { if (rs != null) { try { rs.close(); } catch (SQLException ignore) { } } } public static void recreateLogicalReplicationSlot(Connection connection, String slotName, String outputPlugin) throws SQLException, InterruptedException, TimeoutException { //drop previous slot dropReplicationSlot(connection, slotName); PreparedStatement stm = null; try { stm = connection.prepareStatement("SELECT * FROM pg_create_logical_replication_slot(?, ?)"); stm.setString(1, slotName); stm.setString(2, outputPlugin); stm.execute(); } finally { closeQuietly(stm); } } public static void recreatePhysicalReplicationSlot(Connection connection, String slotName) throws SQLException, InterruptedException, TimeoutException { //drop previous slot dropReplicationSlot(connection, slotName); PreparedStatement stm = null; try { stm = connection.prepareStatement("SELECT * FROM pg_create_physical_replication_slot(?)"); stm.setString(1, slotName); stm.execute(); } finally { closeQuietly(stm); } } public static void dropReplicationSlot(Connection connection, String slotName) throws SQLException, InterruptedException, TimeoutException { if (haveMinimumServerVersion(connection, ServerVersion.v9_5)) { PreparedStatement stm = null; try { stm = connection.prepareStatement( "select pg_terminate_backend(active_pid) from pg_replication_slots " + "where active = true and slot_name = ?"); stm.setString(1, slotName); stm.execute(); } finally { closeQuietly(stm); } } waitStopReplicationSlot(connection, slotName); PreparedStatement stm = null; try { stm = connection.prepareStatement( "select pg_drop_replication_slot(slot_name) " + "from pg_replication_slots where slot_name = ?"); stm.setString(1, slotName); stm.execute(); } finally { closeQuietly(stm); } } public static boolean isReplicationSlotActive(Connection connection, String slotName) throws SQLException { PreparedStatement stm = null; ResultSet rs = null; try { stm = connection.prepareStatement("select active from pg_replication_slots where slot_name = ?"); stm.setString(1, slotName); rs = stm.executeQuery(); return rs.next() && rs.getBoolean(1); } finally { closeQuietly(rs); closeQuietly(stm); } } /** * Execute a SQL query with a given connection and return whether any rows were * returned. No column data is fetched. */ public static boolean executeQuery(Connection conn, String sql) throws SQLException { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql); boolean hasNext = rs.next(); rs.close(); stmt.close(); return hasNext; } /** * Execute a SQL query with a given connection, fetch the first row, and return its * string value. */ public static String queryForString(Connection conn, String sql) throws SQLException { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql); Assert.assertTrue("Query should have returned exactly one row but none was found: " + sql, rs.next()); String value = rs.getString(1); Assert.assertFalse("Query should have returned exactly one row but more than one found: " + sql, rs.next()); rs.close(); stmt.close(); return value; } /** * Retrieve the backend process id for a given connection. */ public static int getBackendPid(Connection conn) throws SQLException { PGConnection pgConn = conn.unwrap(PGConnection.class); return pgConn.getBackendPID(); } public static boolean isPidAlive(Connection conn, int pid) throws SQLException { String sql = haveMinimumServerVersion(conn, ServerVersion.v9_2) ? "SELECT EXISTS (SELECT * FROM pg_stat_activity WHERE pid = ?)" // 9.2+ use pid column : "SELECT EXISTS (SELECT * FROM pg_stat_activity WHERE procpid = ?)"; // Use older procpid try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setInt(1, pid); try (ResultSet rs = stmt.executeQuery()) { rs.next(); return rs.getBoolean(1); } } } public static boolean waitForBackendTermination(Connection conn, int pid) throws SQLException, InterruptedException { return waitForBackendTermination(conn, pid, Duration.ofSeconds(30), Duration.ofMillis(10)); } /** * Wait for a backend process to terminate and return whether it actual terminated within the maximum wait time. */ public static boolean waitForBackendTermination(Connection conn, int pid, Duration timeout, Duration sleepDelay) throws SQLException, InterruptedException { long started = System.currentTimeMillis(); do { if (!isPidAlive(conn, pid)) { return true; } Thread.sleep(sleepDelay.toMillis()); } while ((System.currentTimeMillis() - started) < timeout.toMillis()); return !isPidAlive(conn, pid); } /** * Create a new connection to the same database as the supplied connection but with the privileged credentials. */ private static Connection createPrivilegedConnection(Connection conn) throws SQLException { String url = conn.getMetaData().getURL(); Properties props = new Properties(conn.getClientInfo()); props.setProperty("user", getPrivilegedUser()); props.setProperty("password", getPrivilegedPassword()); return DriverManager.getConnection(url, props); } /** * Executed pg_terminate_backend(...) to terminate the server process for * a given process id with the given connection. * This method does not wait for the backend process to exit. */ private static boolean pgTerminateBackend(Connection privConn, int backendPid) throws SQLException { try (PreparedStatement stmt = privConn.prepareStatement("SELECT pg_terminate_backend(?)")) { stmt.setInt(1, backendPid); try (ResultSet rs = stmt.executeQuery()) { rs.next(); return rs.getBoolean(1); } } } /** * Open a new privileged connection to the same database as connection and use it to ask to terminate the connection. * If the connection is terminated, wait for its process to actual terminate. */ public static boolean terminateBackend(Connection conn) throws SQLException, InterruptedException { try (Connection privConn = createPrivilegedConnection(conn)) { int pid = getBackendPid(conn); if (!pgTerminateBackend(privConn, pid)) { return false; } return waitForBackendTermination(privConn, pid); } } /** * Open a new privileged connection to the same database as connection and use it to ask to terminate the connection. * NOTE: This function does not wait for the process to terminate. */ public static boolean terminateBackendNoWait(Connection conn) throws SQLException { try (Connection privConn = createPrivilegedConnection(conn)) { int pid = getBackendPid(conn); return pgTerminateBackend(privConn, pid); } } public static TransactionState getTransactionState(Connection conn) { return ((BaseConnection) conn).getTransactionState(); } private static void waitStopReplicationSlot(Connection connection, String slotName) throws InterruptedException, TimeoutException, SQLException { long startWaitTime = System.currentTimeMillis(); boolean stillActive; long timeInWait = 0; do { stillActive = isReplicationSlotActive(connection, slotName); if (stillActive) { TimeUnit.MILLISECONDS.sleep(100L); timeInWait = System.currentTimeMillis() - startWaitTime; } } while (stillActive && timeInWait <= 30000); if (stillActive) { throw new TimeoutException("Wait stop replication slot " + timeInWait + " timeout occurs"); } } public static void execute(String sql, Connection connection) throws SQLException { try (Statement stmt = connection.createStatement()) { stmt.execute(sql); } } }
package com.redhat.ceylon.eclipse.code.quickfix; import static com.redhat.ceylon.eclipse.code.outline.CeylonLabelProvider.CHANGE; import java.util.Collection; import org.eclipse.core.resources.IFile; import org.eclipse.imp.editor.quickfix.ChangeCorrectionProposal; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.contentassist.ICompletionProposal; import org.eclipse.ltk.core.refactoring.DocumentChange; import org.eclipse.ltk.core.refactoring.TextChange; import org.eclipse.text.edits.ReplaceEdit; import com.redhat.ceylon.compiler.typechecker.model.ProducedType; import com.redhat.ceylon.compiler.typechecker.tree.CustomTree; import com.redhat.ceylon.compiler.typechecker.tree.Node; import com.redhat.ceylon.compiler.typechecker.tree.Tree; import com.redhat.ceylon.compiler.typechecker.tree.Tree.AssignOp; import com.redhat.ceylon.compiler.typechecker.tree.Tree.BaseMemberExpression; import com.redhat.ceylon.compiler.typechecker.tree.Tree.Expression; import com.redhat.ceylon.compiler.typechecker.tree.Tree.InvocationExpression; import com.redhat.ceylon.compiler.typechecker.tree.Tree.QualifiedMemberExpression; import com.redhat.ceylon.compiler.typechecker.tree.Tree.Return; import com.redhat.ceylon.compiler.typechecker.tree.Tree.SpecifierExpression; import com.redhat.ceylon.compiler.typechecker.tree.Tree.SpecifierOrInitializerExpression; import com.redhat.ceylon.compiler.typechecker.tree.Tree.Statement; import com.redhat.ceylon.compiler.typechecker.tree.Tree.Term; import com.redhat.ceylon.compiler.typechecker.tree.Tree.ThenOp; import com.redhat.ceylon.compiler.typechecker.tree.Tree.ValueModifier; import com.redhat.ceylon.eclipse.code.editor.CeylonAutoEditStrategy; import com.redhat.ceylon.eclipse.code.editor.Util; class ConvertThenElseToIfElse extends ChangeCorrectionProposal { final int offset; final IFile file; ConvertThenElseToIfElse(int offset, IFile file, TextChange change) { super("Convert to if-else", change, 10, CHANGE); this.offset=offset; this.file=file; } @Override public void apply(IDocument document) { super.apply(document); Util.gotoLocation(file, offset); } static void addConvertToGetterProposal(IDocument doc, Collection<ICompletionProposal> proposals, IFile file, Statement statement) { try { String action; String declaration = null; Node operation; if (statement instanceof Tree.Return) { Tree.Return returnOp = (Return) statement; action = "return "; if (returnOp.getExpression() == null || returnOp.getExpression().getTerm() == null) { return; } operation = returnOp.getExpression().getTerm(); } else if (statement instanceof Tree.ExpressionStatement) { Tree.ExpressionStatement expressionStmt = (Tree.ExpressionStatement) statement; if (expressionStmt.getExpression() == null) { return; } Tree.Expression expression = expressionStmt.getExpression(); if (expression.getChildren().isEmpty()) { return; } if (! (expression.getChildren().get(0) instanceof Tree.AssignOp)) { return; } Tree.AssignOp assignOp = (Tree.AssignOp) expression.getChildren().get(0); action = getTerm(doc, assignOp.getLeftTerm()) + " := "; operation = assignOp.getRightTerm(); } else if (statement instanceof CustomTree.AttributeDeclaration) { CustomTree.AttributeDeclaration attrDecl = (CustomTree.AttributeDeclaration) statement; String identifier = getTerm(doc, attrDecl.getIdentifier()); String annotations = ""; if (!attrDecl.getAnnotationList().getAnnotations().isEmpty()) { annotations = getTerm(doc, attrDecl.getAnnotationList()) + " "; } String type; if (attrDecl.getType() instanceof ValueModifier) { ValueModifier valueModifier = (ValueModifier) attrDecl.getType(); ProducedType typeModel = valueModifier.getTypeModel(); type = typeModel.getProducedTypeName(); } else { type = getTerm(doc, attrDecl.getType()); } declaration = annotations + type + " " + identifier + ";"; SpecifierOrInitializerExpression sie = attrDecl.getSpecifierOrInitializerExpression(); if (sie==null) return; action = identifier + " " + getToken(sie) + " "; operation = sie.getExpression().getTerm(); } else { return; } String test; String elseTerm; String thenTerm; while (operation instanceof Expression) { //If Operation is enclosed in parenthesis we need to get down through them: return (test then x else y); operation = ((Expression) operation).getTerm(); } if (operation instanceof Tree.DefaultOp) { Tree.DefaultOp defaultOp = (Tree.DefaultOp) operation; if (defaultOp.getLeftTerm() instanceof Tree.ThenOp) { Tree.ThenOp thenOp = (ThenOp) defaultOp.getLeftTerm(); thenTerm = getTerm(doc, thenOp.getRightTerm()); test = getTerm(doc, thenOp.getLeftTerm()); } else { Term leftTerm = defaultOp.getLeftTerm(); String leftTermStr = getTerm(doc, leftTerm); if (leftTerm instanceof BaseMemberExpression) { thenTerm = leftTermStr; test = "exists " + leftTermStr; } else { if (leftTerm instanceof InvocationExpression) { InvocationExpression expr = (InvocationExpression) leftTerm; if (expr.getPrimary() instanceof QualifiedMemberExpression) { leftTerm = expr.getPrimary(); } } if (leftTerm instanceof QualifiedMemberExpression) { QualifiedMemberExpression qMemberExp = (QualifiedMemberExpression) leftTerm; String id = getTerm(doc, qMemberExp.getIdentifier()); test = "exists " + id + " = " + leftTermStr; thenTerm = id; } else { test = "exists tmp_var = " + leftTermStr; thenTerm = "tmp_var"; } } } elseTerm = getTerm(doc, defaultOp.getRightTerm()); } else if (operation instanceof Tree.ThenOp) { Tree.ThenOp thenOp = (ThenOp) operation; thenTerm = getTerm(doc, thenOp.getRightTerm()); test = getTerm(doc, thenOp.getLeftTerm()); elseTerm = "null"; } else { return; } String baseIndent = CeylonQuickFixAssistant.getIndent(statement, doc); String indent = CeylonAutoEditStrategy.getDefaultIndent(); test = removeEnclosingParentesis(test); StringBuilder replace = new StringBuilder(); if (declaration != null) { replace.append(declaration).append("\n").append(baseIndent); } replace.append("if (").append(test).append(") {\n") .append(baseIndent).append(indent).append(action).append(thenTerm).append(";\n") .append(baseIndent).append("}\n") .append(baseIndent).append("else {\n") .append(baseIndent).append(indent).append(action).append(elseTerm).append(";\n") .append(baseIndent).append("}"); TextChange change = new DocumentChange("Convert To if-else", doc); change.setEdit(new ReplaceEdit(statement.getStartIndex(), statement.getStopIndex() - statement.getStartIndex() + 1, replace.toString())); proposals.add(new ConvertThenElseToIfElse(statement.getStartIndex(), file, change)); } catch (BadLocationException e) { e.printStackTrace(); } } private static String getToken( SpecifierOrInitializerExpression token) { if (token instanceof SpecifierExpression) { return "="; } else { return ":="; } } private static String removeEnclosingParentesis(String s) { if (s.charAt(0) == '(' && s.charAt(s.length() - 1) == ')') { return s.substring(1, s.length() - 1); } return s; } private static String getTerm(IDocument doc, Node node) throws BadLocationException { return doc.get(node.getStartIndex(), node.getStopIndex() - node.getStartIndex() + 1); } }
package com.redhat.ceylon.eclipse.imp.hover; import static com.redhat.ceylon.eclipse.imp.outline.CeylonLabelProvider.getPackageLabel; import java.util.List; import org.eclipse.imp.parser.IParseController; import org.eclipse.imp.services.IDocumentationProvider; import com.redhat.ceylon.compiler.typechecker.model.Class; import com.redhat.ceylon.compiler.typechecker.model.Declaration; import com.redhat.ceylon.compiler.typechecker.model.ProducedType; import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration; import com.redhat.ceylon.compiler.typechecker.tree.Tree; import com.redhat.ceylon.compiler.typechecker.tree.Tree.BaseMemberExpression; import com.redhat.ceylon.eclipse.imp.outline.CeylonLabelProvider; import com.redhat.ceylon.eclipse.imp.proposals.CeylonContentProposer; public class CeylonDocumentationProvider implements IDocumentationProvider { public String getDocumentation(Object entity, IParseController ctlr) { if (entity instanceof Tree.Declaration) { return getDocumentation((Tree.Declaration) entity); } else { return null; } } public static String getDocumentation(Tree.Declaration decl) { StringBuilder documentation = new StringBuilder(); if (decl!=null) { appendDescription(decl, documentation); Declaration model = decl.getDeclarationModel(); if (model!=null) { appendInheritance(documentation, model); appendDeclaringType(documentation, model); appendContainingPackage(documentation, model); } appendDocAnnotationContent(decl, documentation); } return documentation.toString(); } private static void appendDescription(Tree.Declaration decl, StringBuilder documentation) { documentation.append("<p><b>") .append(sanitize(CeylonLabelProvider.getLabelFor(decl))) .append("</b></p>"); } private static void appendContainingPackage(StringBuilder documentation, Declaration model) { if (model.isToplevel()) { documentation.append("<ul><li>in ").append(getPackageLabel(model)) .append("</li><ul>"); } } private static void appendDeclaringType(StringBuilder documentation, Declaration model) { if (model.isClassOrInterfaceMember()) { TypeDeclaration declaring = (TypeDeclaration) model.getContainer(); documentation.append("<ul><li>declared by ").append(declaring.getName()) //.append(" - ").append(getPackageLabel(declaring)) .append("</li>"); if (model.isActual()) { documentation.append("<li>"); appendRefinement(documentation, model.getRefinedDeclaration()); documentation.append("</li>"); } documentation.append("</ul>"); } } private static void appendRefinement(StringBuilder documentation, Declaration refined) { TypeDeclaration supertype = (TypeDeclaration) refined.getContainer(); String spkg = supertype.getUnit().getPackage().getQualifiedNameString(); if (spkg.isEmpty()) spkg="default package"; documentation.append("refines '").append(CeylonContentProposer.getDescriptionFor(refined)) .append("' declared by ").append(supertype.getName()); //.append(" - ").append(getPackageLabel(refined)); } private static void appendInheritance(StringBuilder documentation, Declaration model) { if (model instanceof Class) { ProducedType extended = ((Class) model).getExtendedType(); if (extended!=null) { documentation.append("<ul><li>extends ") .append(sanitize(extended.getProducedTypeName())); //.append(" - ").append(getPackageLabel(extended.getDeclaration())).append("</li></ul>"); } } if (model instanceof TypeDeclaration) { List<ProducedType> types = ((TypeDeclaration) model).getSatisfiedTypes(); if (!types.isEmpty()) { documentation.append("<ul>"); for (ProducedType satisfied : types) { documentation.append("<li>satisfies ") .append(sanitize(satisfied.getProducedTypeName())); //.append(" - ").append(getPackageLabel(satisfied.getDeclaration())).append("</li>"); } documentation.append("</ul>"); } } } private static void appendDocAnnotationContent(Tree.Declaration decl, StringBuilder documentation) { Tree.AnnotationList annotationList = decl.getAnnotationList(); if (annotationList != null) { for (Tree.Annotation annotation : annotationList.getAnnotations()) { Tree.Primary annotPrim = annotation.getPrimary(); if (annotPrim instanceof BaseMemberExpression) { String name = ((BaseMemberExpression) annotPrim).getIdentifier().getText(); if ("doc".equals(name)) { Tree.PositionalArgumentList argList = annotation.getPositionalArgumentList(); List<Tree.PositionalArgument> args = argList.getPositionalArguments(); if (!args.isEmpty()) { String docLine = args.get(0).getExpression().getTerm().getText(); documentation.append("<br/><p>" + docLine + "</p>"); } } } } } } private static String sanitize(String s) { return s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;"); } static String getRefinementDocumentation(Declaration refined) { StringBuilder result = new StringBuilder(); appendRefinement(result, refined); return result.toString(); } }
package net.time4j.tz; import net.time4j.base.GregorianDate; import net.time4j.base.UnixTime; import net.time4j.base.WallTime; import java.io.IOException; import java.io.Serializable; import java.lang.ref.ReferenceQueue; import java.lang.ref.SoftReference; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.ServiceLoader; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * <p>Loads and keeps timezone data including the rules. </p> * * <p>Timezones are identified by keys which have canonical forms as * documented in {@link TZID}. If the keys don't specify any provider * (no char &quot;~&quot;) then the timezone data and rules will be * looked up using the default {@code ZoneProvider}. This default provider * is loaded by {@code java.util.ServiceLoader} if its name is equal * to &quot;TZDB&quot; and its version string is not empty but of * the highest value (lexicographically). If no such provider can be * found then Time4J uses the platform provider based on the public * API of {@code java.util.TimeZone} which does not expose its * transition history however. </p> * * <p>Note: The concept of timezones is strongly based on the idea to * avoid any unrounded amounts of seconds or subseconds. Timezones were * historically first introduced by british railway companies to * guarantee fixed departure timetables. Consequently ISO-8601 only * knows timezone offsets in full minutes. The widely used TZDB-repository * of IANA knows in extreme case offsets in full seconds which is also * allowed by Time4J. Although the Time4J-library recognizes * {@link ZonalOffset#atLongitude(java.math.BigDecimal) fractional offsets} * based on the geographical longitude, its {@code Timezone}-API will * always ignore any fractional parts. </p> * * @author Meno Hochschild * @serial exclude * @concurrency All static methods are thread-safe while this class is * immutable as long as the underlying timezone data are. */ /*[deutsch] * <p>L&auml;dt und h&auml;lt Zeitzonendaten mitsamt ihren Regeln. </p> * * <p>Zeitzonen werden durch Schl&uuml;ssel identifiziert, welche eine * kanonische Form wie in {@link TZID} dokumentiert haben. Wenn die * Schl&uuml;ssel nicht einen spezifischen {@code ZoneProvider} festlegen * (fehlende Tilde &quot;~&quot;), dann werden Zeitzonendaten und Regeln * vom Standard-Provider abgefragt. Dieser wird &uuml;ber einen * {@code java.util.ServiceLoader} geladen, wenn sein Name gleich * &quot;TZDB&quot; ist und seine Version lexikalisch die h&ouml;chste * und nicht-leer ist. Kann kein solcher {@code ZoneProvider} gefunden * werden, dann verwendet Time4J ersatzweise das &ouml;ffentliche API von * {@code java.util.TimeZone} (welches allerdings keine Historie * exponiert). </p> * * <p>Hinweis: Das Zeitzonenkonzept fu&szlig;t stark auf der Idee, * irgendwelche nicht-runden Sekunden- oder Subsekundenbetr&auml;ge * zu vermeiden. Historisch wurden Zeitzonen zuerst von britischen * Eisenbahngesellschaften mit der Motivation eingef&uuml;hrt, landesweit * feste Fahrpl&auml;ne zu erm&ouml;glichen. Konsequenterweise kennt * ISO-8601 nur Zeitzonen-Offsets (Verschiebungen) in vollen Minuten. * Die weit verbreitete Zeitzonendatenbank TZDB von IANA kennt in * Extremf&auml;llen auch Offsets in vollen Sekunden, was von Time4J * akzeptiert wird. Obwohl die Time4J-Bibliothek * {@link ZonalOffset#atLongitude(java.math.BigDecimal) fraktionale Offsets} * basierend auf der geographischen L&auml;nge kennt, wird das * {@code Timezone}-API immer fraktionale Subsekunden ignorieren. </p> * * @author Meno Hochschild * @serial exclude * @concurrency All static methods are thread-safe while this class is * immutable as long as the underlying timezone data are. */ public abstract class Timezone implements Serializable { private static final String NEW_LINE = System.getProperty("line.separator"); private static final String REPOSITORY_VERSION = System.getProperty("net.time4j.tz.repository.version"); private static final Comparator<TZID> ID_COMPARATOR = new Comparator<TZID>() { @Override public int compare( TZID o1, TZID o2 ) { String c1 = o1.canonical(); int i1 = c1.indexOf('~'); String c2 = o2.canonical(); int i2 = c2.indexOf('~'); if (i1 >= 0) { return ((i2 == -1) ? 1 : c1.compareTo(c2)); } else if (i2 >= 0) { return -1; } else { return c1.compareTo(c2); } } }; /** * <p>This standard strategy which is also used by the JDK-class * {@code java.util.GregorianCalendar} subtracts the next defined * offset from any local timestamp in order to calculate the global * time while pushing forward an invalid local time. </p> * * <p>Equivalent to * {@code GapResolver.PUSH_FORWARD.and(OverlapResolver.LATER_OFFSET)}. </p> * * @see #getOffset(GregorianDate,WallTime) */ /*[deutsch] * <p>Diese auch von der JDK-Klasse {@code java.util.GregorianCalendar} * verwendete Standardstrategie zieht von einem beliebigen lokalen * Zeitstempel den jeweils n&auml;chstdefinierten Offset ab, um die * globale Zeit zu erhalten, wobei eine ung&uuml;ltige lokale Zeit * um die L&auml;nge einer Offset-Verschiebung vorgeschoben wird. </p> * * <p>&Auml;quivalent zu: * {@code GapResolver.PUSH_FORWARD.and(OverlapResolver.LATER_OFFSET)}. </p> * * @see #getOffset(GregorianDate,WallTime) */ public static final TransitionStrategy DEFAULT_CONFLICT_STRATEGY = GapResolver.PUSH_FORWARD.and(OverlapResolver.LATER_OFFSET); /** * <p>In addition to the {@link #DEFAULT_CONFLICT_STRATEGY * standard strategy}, this strategy ensures the use of valid local * timestamps. </p> * * <p>Equivalent to * {@code GapResolver.ABORT.and(OverlapResolver.LATER_OFFSET)}. </p> */ /*[deutsch] * <p>Legt bei Transformationen von lokalen Zeitstempeln zu UTC fest, * da&szlig; nur in der Zeitzone g&uuml;ltige Zeitstempel zugelassen * werden. </p> * * <p>Ansonsten wird die {@link #DEFAULT_CONFLICT_STRATEGY * Standardstrategie} verwendet. &Auml;quivalent zu: * {@code GapResolver.ABORT.and(OverlapResolver.LATER_OFFSET)}. </p> */ public static final TransitionStrategy STRICT_MODE = GapResolver.ABORT.and(OverlapResolver.LATER_OFFSET); private static final boolean ALLOW_SYSTEM_TZ_OVERRIDE = Boolean.getBoolean("net.time4j.allow.system.tz.override"); private static volatile ZonalKeys zonalKeys = null; private static volatile Timezone currentSystemTZ = null; private static volatile boolean cacheActive = true; private static int softLimit = 11; private static final String NAME_JUT = "java.util.TimeZone"; private static final String NAME_TZDB = "TZDB"; private static final String NAME_ZONENAMES = "#STD_ZONE_NAMES"; private static final String NAME_DEFAULT = "DEFAULT"; private static final Map<String, TZID> PREDEFINED; private static final ZoneProvider PLATFORM_PROVIDER; private static final ZoneProvider DEFAULT_PROVIDER; private static final ConcurrentMap<String, NamedReference> CACHE; private static final ReferenceQueue<Timezone> QUEUE; private static final LinkedList<Timezone> LAST_USED; private static final ConcurrentMap<String, ZoneProvider> PROVIDERS; private static final ZoneProvider ZONENAME_PROVIDER; private static final Timezone SYSTEM_TZ_ORIGINAL; static { CACHE = new ConcurrentHashMap<String, NamedReference>(); PROVIDERS = new ConcurrentHashMap<String, ZoneProvider>(); QUEUE = new ReferenceQueue<Timezone>(); LAST_USED = new LinkedList<Timezone>(); // strong references ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl == null) { cl = Timezone.class.getClassLoader(); } List<Class<? extends TZID>> areas; try { areas = loadPredefined( cl, "AFRICA", "AMERICA", "AMERICA$ARGENTINA", "AMERICA$INDIANA", "AMERICA$KENTUCKY", "AMERICA$NORTH_DAKOTA", "ANTARCTICA", "ASIA", "ATLANTIC", "AUSTRALIA", "EUROPE", "INDIAN", "PACIFIC"); } catch (ClassNotFoundException cnfe) { // olson-package not available areas = Collections.emptyList(); } Map<String, TZID> temp1 = new HashMap<String, TZID>(); temp1.put("Z", ZonalOffset.UTC); temp1.put("UT", ZonalOffset.UTC); temp1.put("UTC", ZonalOffset.UTC); temp1.put("GMT", ZonalOffset.UTC); temp1.put("UTC0", ZonalOffset.UTC); temp1.put("GMT0", ZonalOffset.UTC); for (Class<? extends TZID> area : areas) { for (TZID tzid : area.getEnumConstants()) { temp1.put(tzid.canonical(), tzid); } } PREDEFINED = Collections.unmodifiableMap(temp1); ServiceLoader<ZoneProvider> sl = ServiceLoader.load(ZoneProvider.class, cl); ZoneProvider zp = null; ZoneProvider np = null; for (ZoneProvider provider : sl) { String name = provider.getName(); if (name.equals(NAME_TZDB)) { String v = provider.getVersion(); if (!v.isEmpty()) { if (v.equals(REPOSITORY_VERSION)) { zp = provider; } else if ( (REPOSITORY_VERSION == null) && ((zp == null) || (v.compareTo(zp.getVersion()) > 0)) ) { zp = provider; } } } else if (name.equals(NAME_ZONENAMES)) { np = provider; } else if ( !name.isEmpty() && !name.equals(NAME_DEFAULT) ) { PROVIDERS.put(name, provider); } } ZONENAME_PROVIDER = np; PLATFORM_PROVIDER = new PlatformTZProvider(); PROVIDERS.put(NAME_JUT, PLATFORM_PROVIDER); if (zp == null) { DEFAULT_PROVIDER = PLATFORM_PROVIDER; } else { PROVIDERS.put(NAME_TZDB, zp); DEFAULT_PROVIDER = zp; } Timezone systemTZ = null; try { String zoneID = System.getProperty("user.timezone"); if ( "Z".equals(zoneID) || "UTC".equals(zoneID) ) { systemTZ = ZonalOffset.UTC.getModel(); } else if (zoneID != null) { systemTZ = Timezone.getTZ(resolve(zoneID), zoneID, false); } } catch (SecurityException se) { // OK, dann Zugriff auf j.u.TimeZone.getDefault() } if (systemTZ == null) { SYSTEM_TZ_ORIGINAL = Timezone.getDefaultTZ(); } else { SYSTEM_TZ_ORIGINAL = systemTZ; } if (ALLOW_SYSTEM_TZ_OVERRIDE) { currentSystemTZ = SYSTEM_TZ_ORIGINAL; } zonalKeys = new ZonalKeys(); } /** * <p>Nur zur paket-privaten Verwendung. </p> */ Timezone() { super(); } /** * <p>Gets all available timezone IDs. </p> * * @return unmodifiable list of available timezone ids in ascending order */ /*[deutsch] * <p>Liefert alle verf&uuml;gbaren Zeitzonenkennungen. </p> * * @return unmodifiable list of available timezone ids in ascending order */ public static List<TZID> getAvailableIDs() { return zonalKeys.availables; } public static List<TZID> getAvailableIDs(String provider) { ZoneProvider zp = getProvider(provider); if (zp == null) { return Collections.emptyList(); } List<TZID> result = new ArrayList<TZID>(); for (String id : zp.getAvailableIDs()) { result.add(resolve(id)); } Collections.sort(result, ID_COMPARATOR); return Collections.unmodifiableList(result); } /** * <p>Equivalent to {@code getPreferredIDs(locale, false, "DEFAULT")}. </p> * * @param locale ISO-3166-alpha-2-country to be evaluated * @return unmodifiable set of preferred timezone ids * @see #getPreferredIDs(Locale, boolean, String) * @deprecated For clarity, use the 3-parameter-method instead (will * be removed in next major release) */ /*[deutsch] * <p>&Auml;quivalent zu * {@code getPreferredIDs(locale, false, "DEFAULT")}. </p> * * @param locale ISO-3166-alpha-2-country to be evaluated * @return unmodifiable set of preferred timezone ids * @see #getPreferredIDs(Locale, boolean, String) * @deprecated For clarity, use the 3-parameter-method instead (will * be removed in next major release) */ @Deprecated public static Set<TZID> getPreferredIDs(Locale locale) { return getPreferredIDs(locale, false, NAME_DEFAULT); } public static Set<TZID> getPreferredIDs( Locale locale, boolean smart, String provider ) { ZoneProvider zp = getProvider(provider); if (zp == null) { return Collections.emptySet(); } Set<TZID> p = new HashSet<TZID>(); for (String id : zp.getPreferredIDs(locale, smart)) { p.add(resolve(id)); } return Collections.unmodifiableSet(p); } /** * <p>Gets the system timezone. </p> * * <p>The underlying algorithm to determine the system timezone is * primarily based on the system property &quot;user.timezone&quot; * then on the method {@code java.util.TimeZone.getDefault()}. If * the system property &quot;net.time4j.allow.system.tz.override&quot; * is set to &quot;true&quot; then the system timezone can be changed * by a combined approach of {@code java.util.TimeZone.setDefault()} * and the method {@link Cache#refresh()}. Otherwise this class * will determine the system timezone only for one time while being * loaded. </p> * * <p>Note: If the system timezone cannot be determined (for example * due to a wrong property value for &quot;user.timezone&quot;) then * this method will fall back to UTC timezone.. </p> * * @return default timezone data of system * @see java.util.TimeZone#getDefault() * java.util.TimeZone.getDefault() */ /*[deutsch] * <p>Liefert die Standard-Zeitzone des Systems. </p> * * <p>Der verwendete Algorithmus basiert vorrangig auf der * System-Property &quot;user.timezone&quot;, dann erst auf der * Methode {@code java.util.TimeZone.getDefault()}. Ist zus&auml;tzlich * die Property &quot;net.time4j.allow.system.tz.override&quot; auf den * Wert &quot;true&quot; gesetzt, dann kann nach einer Kombination aus * {@code java.util.TimeZone.setDefault()} und der Methode * {@link Cache#refresh()} in dieser Klasse die Standard-Zeitzone * auch ge&auml;ndert werden, sonst wird sie einmalig beim Laden * dieser Klasse gesetzt. </p> * * <p>Zu beachten: Kann die Standard-Zeitzone zum Beispiel wegen eines * falschen Property-Werts in &quot;user.timezone&quot; nicht interpretiert * werden, f&auml;llt diese Methode auf die UTC-Zeitzone zur&uuml;ck. </p> * * @return default timezone data of system * @see java.util.TimeZone#getDefault() * java.util.TimeZone.getDefault() */ public static Timezone ofSystem() { if (ALLOW_SYSTEM_TZ_OVERRIDE && (currentSystemTZ != null)) { return currentSystemTZ; } else { // detect premature class initialization assert (SYSTEM_TZ_ORIGINAL != null); return SYSTEM_TZ_ORIGINAL; } } public static Timezone of(TZID tzid) { return Timezone.getTZ(tzid, true); } public static Timezone of(String tzid) { return Timezone.getTZ(null, tzid, true); } /** * <p>Tries to load the timezone with the first given identifer else * with given alternative identifier. </p> * * <p>If the timezone cannot be loaded with first identifier then * this method will load the timezone using the alternative. In case * of failure, this method will finally load the system timezone. * In contrast to {@link #of(TZID)}, this method never throws any * exception. </p> * * <p>Queries the underlying {@code ZoneProvider}. </p> * * @param tzid preferred timezone id * @param fallback alternative timezone id * @return timezone data */ /*[deutsch] * <p>Versucht bevorzugt, die Zeitzone mit der angegebenen ID zu laden, * sonst eine Alternative. </p> * * <p>Ist die Zeitzone zur ID nicht ladbar, dann wird als zweiter Versuch * die Zeitzone passend zum zweiten Argument geladen. Schl&auml;gt auch * das fehl, wird schlie&szlig;lich die Standard-Zeitzone der JVM geladen. * Im Gegensatz zu {@link #of(TZID)} wirft diese Methode niemals eine * Ausnahme. </p> * * <p>Fragt den zugrundeliegenden {@code ZoneProvider} ab. </p> * * @param tzid preferred timezone id * @param fallback alternative timezone id * @return timezone data */ public static Timezone of( String tzid, TZID fallback ) { Timezone ret = Timezone.getTZ(null, tzid, false); if (ret == null) { ret = Timezone.getTZ(fallback, false); if (ret == null) { ret = Timezone.ofSystem(); } } return ret; } public static Timezone of( String tzid, TransitionHistory history ) { return new HistorizedTimezone(resolve(tzid), history); } /** * <p>Gets the associated timezone identifier. </p> * * @return timezone id * @see java.util.TimeZone#getID() java.util.TimeZone.getID() */ /*[deutsch] * <p>Liefert die Zeitzonen-ID. </p> * * @return timezone id * @see java.util.TimeZone#getID() java.util.TimeZone.getID() */ public abstract TZID getID(); /** * <p>Calculates the offset for given global timestamp. </p> * * <p>Note: The returned offset has never any subsecond part, normally * not even seconds but full minutes or hours. </p> * * @param ut unix time * @return shift in seconds which yields local time if added to unix time * @see java.util.TimeZone#getOffset(long) * java.util.TimeZone.getOffset(long) */ /*[deutsch] * <p>Ermittelt die Zeitzonenverschiebung zum angegebenen Zeitpunkt auf * der UT-Weltzeitlinie in Sekunden. </p> * * <p>Hinweis: Die zur&uuml;ckgegebene Verschiebung hat niemals * Subsekundenteile, normalerweise auch nicht Sekundenteile, sondern * nur volle Minuten oder Stunden. </p> * * @param ut unix time * @return shift in seconds which yields local time if added to unix time * @see java.util.TimeZone#getOffset(long) * java.util.TimeZone.getOffset(long) */ public abstract ZonalOffset getOffset(UnixTime ut); /** * <p>Calculates the offset for given local timestamp. </p> * * <p>In case of gaps or overlaps, this method uses the * {@link #DEFAULT_CONFLICT_STRATEGY standard strategy} * to get the next defined offset. This behaviour is conform to the * JDK-class {@code java.util.GregorianCalendar}. </p> * * <p>Note: The returned offset has never any subsecond part, normally * not even seconds but full minutes or hours. </p> * * @param localDate local date in timezone * @param localTime local wall time in timezone * @return shift in seconds which yields unix time if subtracted * from local time choosing later offset at gaps or overlaps * @see java.util.TimeZone#getOffset(int, int, int, int, int, int) * java.util.TimeZone.getOffset(int, int, int, int, int, int) */ /*[deutsch] * <p>Ermittelt die Zeitzonenverschiebung zum angegebenen lokalen * Zeitpunkt in Sekunden. </p> * * <p>Als Konfliktstrategie f&uuml;r L&uuml;cken oder &Uuml;berlappungen * auf dem lokalen Zeitstrahl wird die {@link #DEFAULT_CONFLICT_STRATEGY * Standardstrategie} verwendet, den n&auml;chstdefinierten Offset zu * ermitteln. Dieses Verhalten ist zur JDK-Klasse * {@code java.util.GregorianCalendar} konform. </p> * * <p>Hinweis: Die zur&uuml;ckgegebene Verschiebung hat niemals * Subsekundenteile, normalerweise auch nicht Sekundenteile, sondern * nur volle Minuten oder Stunden. </p> * * @param localDate local date in timezone * @param localTime local wall time in timezone * @return shift in seconds which yields unix time if subtracted * from local time choosing later offset at gaps or overlaps * @see java.util.TimeZone#getOffset(int, int, int, int, int, int) * java.util.TimeZone.getOffset(int, int, int, int, int, int) */ public abstract ZonalOffset getOffset( GregorianDate localDate, WallTime localTime ); /** * <p>Evaluates if given local timestamp is invalid due to a gap * on the local timeline. </p> * * <p>A typical example is the transition from standard to daylight * saving time because the clock will be manually adjusted such * that the clock is moved forward by usually one hour. </p> * * @param localDate local date in timezone * @param localTime local wall time in timezone * @return {@code true} if the local time is not defined due to * transition gaps else {@code false} */ /*[deutsch] * <p>Bestimmt, ob der angegebene lokale Zeitpunkt in eine L&uuml;cke * f&auml;llt. </p> * * <p>Das klassiche Beispiel liegt vor, wenn wegen eines &Uuml;bergangs * von der Winter- zur Sommerzeit eine bestimmte Uhrzeit nicht existiert, * weil die Uhr vorgestellt wurde. </p> * * @param localDate local date in timezone * @param localTime local wall time in timezone * @return {@code true} if the local time is not defined due to * transition gaps else {@code false} */ public abstract boolean isInvalid( GregorianDate localDate, WallTime localTime ); /** * <p>Queries if given global timestamp matches daylight saving time * in this timezone? </p> * * <p>The DST correction can be obtained as difference between total * offset and raw offset if the raw offset has not changed yet. * As alternative the DST correction can be obtained by evaluating * the transition offset history. </p> * * @param ut unix time * @return {@code true} if the argument represents summer time * else {@code false} * @see java.util.TimeZone#inDaylightTime(java.util.Date) * java.util.TimeZone.inDaylightTime(java.util.Date) */ /*[deutsch] * <p>Herrscht zum angegebenen Zeitpunkt Sommerzeit in der Zeitzone? </p> * * <p>Die DST-Korrektur selbst kann als Differenz zwischen dem Gesamt-Offset * und dem Standard-Offset erhalten werden, wenn sich der Standard-Offset * historisch nicht ge&auml;ndert hat. Alternativ und genauer kann die * DST-Korrektur &uuml;ber die Offset-Historie ermittelt werden. </p> * * @param ut unix time * @return {@code true} if the argument represents summer time * else {@code false} * @see java.util.TimeZone#inDaylightTime(java.util.Date) * java.util.TimeZone.inDaylightTime(java.util.Date) */ public abstract boolean isDaylightSaving(UnixTime ut); /** * <p>Determines if this timezone has no offset transitions and always * uses a fixed offset. </p> * * @return {@code true} if there is no transition else {@code false} * @since 1.2.1 */ /*[deutsch] * <p>Legt fest, ob diese Zeitzone keine &Uuml;berg&auml;nge kennt und * nur einen festen Offset benutzt. </p> * * @return {@code true} if there is no transition else {@code false} * @since 1.2.1 */ public abstract boolean isFixed(); /** * <p>Gets the underlying offset transitions and rules if available. </p> * * @return {@code TransitionHistory} or {@code null} if there is no * better {@code Provider} than {@code java.util.TimeZone} */ /*[deutsch] * <p>Liefert die zugrundeliegenden &Uuml;berg&auml;nge und Regeln, * falls vorhanden. </p> * * @return {@code TransitionHistory} or {@code null} if there is no * better {@code Provider} than {@code java.util.TimeZone} */ public abstract TransitionHistory getHistory(); /** * <p>Describes all registered {@code ZoneProvider}-instances with * name and optionally location and version. </p> * * @return String */ /*[deutsch] * <p>Beschreibt alle registrierten {@code ZoneProvider}-Instanzen * mit Namen und optional Ort und Version. </p> * * @return String */ public static String getProviderInfo() { StringBuilder sb = new StringBuilder(128); sb.append(Timezone.class.getName()); sb.append(":[default-provider="); sb.append(DEFAULT_PROVIDER.getName()); sb.append(", registered={"); for (String key : PROVIDERS.keySet()) { ZoneProvider provider = PROVIDERS.get(key); if (provider != null) { // defensive against parallel threads sb.append("(name="); sb.append(provider.getName()); String location = provider.getLocation(); if (!location.isEmpty()) { sb.append(",location="); sb.append(location); } String version = provider.getVersion(); if (!version.isEmpty()) { sb.append(",version="); sb.append(version); } sb.append(')'); } } sb.append("}]"); return sb.toString(); } public static String getVersion(String provider) { ZoneProvider zp = getProvider(provider); return ((zp == null) ? "" : zp.getVersion()); } /** * <p>Yields the names of all registered * {@code ZoneProvider}-instances. </p> * * @return unmodifiable list of provider names * @since 2.2 * @see ZoneProvider#getName() */ /*[deutsch] * <p>Liefert die Namen aller registrierten * {@code ZoneProvider}-Instanzen. </p> * * @return unmodifiable list of provider names * @since 2.2 * @see ZoneProvider#getName() */ public static Set<String> getRegisteredProviders() { return Collections.unmodifiableSet(PROVIDERS.keySet()); } /** * <p>Gets the strategy for resolving local timestamps. </p> * * @return transition strategy for resolving local timestamps * @see #with(TransitionStrategy) */ /*[deutsch] * <p>Ermittelt die Strategie zur Aufl&ouml;sung von lokalen * Zeitstempeln. </p> * * @return transition strategy for resolving local timestamps * @see #with(TransitionStrategy) */ public abstract TransitionStrategy getStrategy(); /** * <p>Creates a copy of this timezone which uses given strategy for * resolving local timestamps. </p> * * <p>If this timezone has a fixed offset then the strategy will be * ignored because in this case there can never be a conflict. * Otherwise if there is no public offset transition history then * the only supported strategies are {@link #DEFAULT_CONFLICT_STRATEGY} * and {@link #STRICT_MODE}. </p> * * @param strategy transition strategy for resolving local timestamps * @return copy of this timezone with given strategy * @throws UnsupportedOperationException if given strategy requires * a transition history and this timezone does not have one */ /*[deutsch] * <p>Erzeugt eine Kopie dieser Zeitzone, die zur Aufl&ouml;sung von * lokalen Zeitstempeln die angegebene Strategie nutzt. </p> * * <p>Hat diese Zeitzone einen festen Offset, wird die Strategie * ignoriert, da hier nie eine Konfliktsituation auftreten kann. * Wenn andererseits eine Zeitzone keine &ouml;ffentliche Historie * kennt, dann werden nur {@link #DEFAULT_CONFLICT_STRATEGY} und * {@link #STRICT_MODE} unterst&uuml;tzt. </p> * * @param strategy transition strategy for resolving local timestamps * @return copy of this timezone with given strategy * @throws UnsupportedOperationException if given strategy requires * a transition history and this timezone does not have one */ public abstract Timezone with(TransitionStrategy strategy); /** * <p>Returns the name of this timezone suitable for presentation to * users in given style and locale. </p> * * <p>If the name is not available then this method will yield the * ID of this timezone. </p> * * @param style name style * @param locale language setting * @return localized timezone name for display purposes * @see java.util.TimeZone#getDisplayName(boolean,int,Locale) * java.util.TimeZone.getDisplayName(boolean,int,Locale) * @see Locale#getDefault() * @see #getID() */ /*[deutsch] * <p>Liefert den anzuzeigenden Zeitzonennamen. </p> * * <p>Ist der Zeitzonenname nicht ermittelbar, wird die ID der Zeitzone * geliefert. </p> * * @param style name style * @param locale language setting * @return localized timezone name for display purposes * @see java.util.TimeZone#getDisplayName(boolean,int,Locale) * java.util.TimeZone.getDisplayName(boolean,int,Locale) * @see Locale#getDefault() * @see #getID() */ public String getDisplayName( NameStyle style, Locale locale ) { String tzid = this.getID().canonical(); int index = tzid.indexOf('~'); ZoneProvider provider = DEFAULT_PROVIDER; String zoneID = tzid; if (index >= 0) { String pname = tzid.substring(0, index); if (!pname.equals(NAME_DEFAULT)) { provider = PROVIDERS.get(pname); } zoneID = tzid.substring(index + 1); } String name = provider.getDisplayName(zoneID, style, locale); if ( name.isEmpty() && (provider != PLATFORM_PROVIDER) ) { // platform provider never returns empty name unless zoneID is empty return PLATFORM_PROVIDER.getDisplayName(zoneID, style, locale); } return name; } public static boolean registerProvider(ZoneProvider provider) { String name = provider.getName(); if (name.isEmpty()) { throw new IllegalArgumentException( "Missing name of zone provider."); } else if (name.equals(NAME_TZDB)) { throw new IllegalArgumentException( "TZDB provider cannot be registered after startup."); } else if (name.equals(NAME_JUT)) { throw new IllegalArgumentException( "Platform provider cannot be replaced."); } else if (name.equals(NAME_DEFAULT)) { throw new IllegalArgumentException( "Default zone provider cannot be overridden."); } else if (name.equals(NAME_ZONENAMES)) { throw new IllegalArgumentException( "Reserved zone name provider cannot be replaced."); } boolean inserted = (PROVIDERS.putIfAbsent(name, provider) == null); if (inserted) { zonalKeys = new ZonalKeys(); } return inserted; } /** * <p>Creates a dump of this timezone and writes it to the given * buffer. </p> * * @param buffer buffer to write the dump to * @throws IOException in any case of I/O-errors * @since 2.2 */ /*[deutsch] * <p>Erzeugt eine Textzusammenfassung dieser Instanz und schreibt sie * in den angegebenen Puffer. </p> * * @param buffer buffer to write the dump to * @throws IOException in any case of I/O-errors * @since 2.2 */ public void dump(Appendable buffer) throws IOException { StringBuilder sb = new StringBuilder(4096); sb.append("Start Of Dump =>").append(NEW_LINE); sb.append("*** Timezone-ID:").append(NEW_LINE); sb.append(">>> ").append(this.getID().canonical()).append(NEW_LINE); if (this.isFixed()) { sb.append("*** Fixed offset:").append(NEW_LINE).append(">>> "); sb.append(this.getHistory().getInitialOffset()).append(NEW_LINE); } else { sb.append("*** Strategy:").append(NEW_LINE); sb.append(">>> ").append(this.getStrategy()).append(NEW_LINE); TransitionHistory history = this.getHistory(); sb.append("*** History:").append(NEW_LINE); if (history == null) { sb.append(">>> Not public!").append(NEW_LINE); } else { history.dump(sb); } } sb.append("<= End Of Dump").append(NEW_LINE); buffer.append(sb.toString()); } private static Timezone getDefaultTZ() { String zoneID = java.util.TimeZone.getDefault().getID(); return Timezone.of(zoneID, ZonalOffset.UTC); } private static Timezone getTZ( TZID tzid, boolean wantsException ) { // Liegt eine feste Verschiebung vor? if (tzid instanceof ZonalOffset) { return ((ZonalOffset) tzid).getModel(); } return Timezone.getTZ(tzid, tzid.canonical(), wantsException); } private static Timezone getTZ( TZID tzid, // optional String zoneID, boolean wantsException ) { // Suche im Cache Timezone tz = null; NamedReference sref = CACHE.get(zoneID); if (sref != null) { tz = sref.get(); if (tz == null) { CACHE.remove(sref.tzid); } } if (tz != null) { return tz; } String providerName = ""; String zoneKey = zoneID; for (int i = 0, n = zoneID.length(); i < n; i++) { if (zoneID.charAt(i) == '~') { providerName = zoneID.substring(0, i); zoneKey = zoneID.substring(i + 1); // maybe empty string break; } } if (zoneKey.isEmpty()) { if (wantsException) { throw new IllegalArgumentException("Timezone key is empty."); } else { return null; } } ZoneProvider provider = DEFAULT_PROVIDER; boolean useDefault = ( providerName.isEmpty() || providerName.equals(NAME_DEFAULT)); if (!useDefault) { provider = PROVIDERS.get(providerName); if (provider == null) { if (wantsException) { String msg; if (providerName.equals(NAME_TZDB)) { msg = "TZDB provider not available: "; } else { msg = "Timezone provider not registered: "; } throw new IllegalArgumentException(msg + zoneID); } else { return null; } } } // enums bevorzugen TZID resolved = tzid; if (resolved == null) { if (useDefault) { TZID result = resolve(zoneKey); if (result instanceof ZonalOffset) { return ((ZonalOffset) result).getModel(); } else { resolved = result; } } else { resolved = new NamedID(zoneID); } } if (provider == PLATFORM_PROVIDER) { PlatformTimezone test = new PlatformTimezone(resolved, zoneKey); if ( test.isGMT() && !zoneKey.equals("GMT") && !zoneKey.startsWith("UT") && !zoneKey.equals("Z") ) { // JDK-Fallback verhindern => tz == null } else { tz = test; } } else { // exakte Suche in Historie TransitionHistory history = provider.load(zoneKey); if (history == null) { // Alias-Suche + Fallback-Option tz = Timezone.getZoneByAlias(provider, resolved, zoneKey); } else { tz = new HistorizedTimezone(resolved, history); } } if (tz == null) { if (wantsException) { throw new IllegalArgumentException( "Unknown timezone: " + zoneID); } else { return null; } } // bei Bedarf im Cache speichern if (cacheActive) { NamedReference oldRef = CACHE.putIfAbsent( zoneID, new NamedReference(tz, QUEUE) ); if (oldRef == null) { synchronized (Timezone.class) { LAST_USED.addFirst(tz); while (LAST_USED.size() >= softLimit) { LAST_USED.removeLast(); } } } else { Timezone oldZone = oldRef.get(); if (oldZone != null) { tz = oldZone; } } } return tz; } private static Timezone getZoneByAlias( ZoneProvider provider, TZID tzid, String zoneKey ) { TransitionHistory history = null; String alias = zoneKey; Map<String, String> aliases = provider.getAliases(); while ( (history == null) && ((alias = aliases.get(alias)) != null) ) { history = provider.load(alias); } if (history == null) { String fallback = provider.getFallback(); if (fallback.isEmpty()) { return null; } else if (fallback.equals(provider.getName())) { throw new IllegalArgumentException( "Circular zone provider fallback: " + provider.getName()); } else { return new FallbackTimezone( tzid, Timezone.of(fallback + "~" + zoneKey)); } } else { return new HistorizedTimezone(tzid, history); } } private static TZID resolve(String zoneKey) { // enums bevorzugen TZID resolved = PREDEFINED.get(zoneKey); if (resolved == null) { if (zoneKey.startsWith("GMT")) { zoneKey = "UTC" + zoneKey.substring(3); } resolved = ZonalOffset.parse(zoneKey, false); if (resolved == null) { resolved = new NamedID(zoneKey); } } return resolved; } @SuppressWarnings("unchecked") private static List<Class<? extends TZID>> loadPredefined( ClassLoader loader, String... names ) throws ClassNotFoundException { List<Class<? extends TZID>> classes = new ArrayList<Class<? extends TZID>>(); for (String name : names) { Class<?> clazz = Class.forName("net.time4j.tz.olson." + name, true, loader); if (TZID.class.isAssignableFrom(clazz)) { classes.add((Class<? extends TZID>) clazz); } } return Collections.unmodifiableList(classes); } private static ZoneProvider getProvider(String provider) { if (provider.isEmpty()) { throw new IllegalArgumentException("Missing zone provider."); } return ( provider.equals(NAME_DEFAULT) ? DEFAULT_PROVIDER : PROVIDERS.get(provider)); } /** * <p>Offers some static methods for the configuration of the * timezone cache. </p> */ /*[deutsch] * <p>Bietet statische Methoden zum Konfigurieren des * Zeitzonendatenpuffers. </p> */ public static class Cache { private Cache() { // no instantiation } /** * <p>Can refresh the timezone cache in case of a dynamic * update of the underlying timezone repository. </p> * * <p>First the internal cache will be cleared. Furthermore, * if needed the system timezone will be determined again. </p> */ /*[deutsch] * <p>Erlaubt eine Aktualisierung, wenn sich die Zeitzonendatenbank * ge&auml;ndert hat (<i>dynamic update</i>). </p> * * <p>Der interne Cache wird entleert. Auch wird bei Bedarf die * Standard-Zeitzone neu ermittelt. </p> */ public static void refresh() { synchronized (Timezone.class) { while (QUEUE.poll() != null) {} LAST_USED.clear(); } zonalKeys = new ZonalKeys(); CACHE.clear(); if (ALLOW_SYSTEM_TZ_OVERRIDE) { currentSystemTZ = Timezone.getDefaultTZ(); } } /** * <p>Aktivates or deactivates the internal cache. </p> * * <p>The timezone cache is active by default. Switching off the cache can * make the performance worse especially if the underlying {@code Provider} * itself has no cache. </p> * * @param active {@code true} if chache shall be active * else {@code false} */ /*[deutsch] * <p>Aktiviert oder deaktiviert den internen Cache. </p> * * <p>Standardm&auml;&szlig;ig ist der Cache aktiv. Ein Abschalten des * Cache kann die Performance insbesondere dann verschlechtern, wenn der * zugrundeliegende {@code Provider} selbst keinen Cache hat. </p> * * @param active {@code true} if chache shall be active * else {@code false} */ public static void setCacheActive(boolean active) { cacheActive = active; if (!active) { CACHE.clear(); } } public static void setMinimumCacheSize(int minimumCacheSize) { if (minimumCacheSize < 0) { throw new IllegalArgumentException( "Negative timezone cache size: " + minimumCacheSize); } NamedReference ref; while ((ref = (NamedReference) QUEUE.poll()) != null) { CACHE.remove(ref.tzid); } synchronized (Timezone.class) { softLimit = minimumCacheSize + 1; int n = LAST_USED.size() - minimumCacheSize; for (int i = 0; i < n; i++) { LAST_USED.removeLast(); } } } } private static class NamedReference extends SoftReference<Timezone> { private final String tzid; NamedReference( Timezone tz, ReferenceQueue<Timezone> queue ) { super(tz, queue); this.tzid = tz.getID().canonical(); } } private static class NamedID implements TZID, Serializable { private static final long serialVersionUID = -4889632013137688471L; /** * @serial timezone id */ private final String tzid; NamedID(String tzid) { super(); this.tzid = tzid; } @Override public String canonical() { return this.tzid; } @Override public boolean equals(Object obj) { if (obj instanceof NamedID) { NamedID that = (NamedID) obj; return this.tzid.equals(that.tzid); } else { return false; } } @Override public int hashCode() { return this.tzid.hashCode(); } @Override public String toString() { return this.getClass().getName() + "@" + this.tzid; } } private static class ZonalKeys { private final List<TZID> availables; ZonalKeys() { super(); List<TZID> list = new ArrayList<TZID>(1024); list.add(ZonalOffset.UTC); for (Map.Entry<String, ZoneProvider> e : PROVIDERS.entrySet()) { ZoneProvider zp = e.getValue(); if ( (zp == PLATFORM_PROVIDER) && (DEFAULT_PROVIDER != PLATFORM_PROVIDER) ) { continue; } for (String id : zp.getAvailableIDs()) { TZID tzid = resolve(id); if (!list.contains(tzid)) { list.add(tzid); } } } Collections.sort(list, ID_COMPARATOR); this.availables = Collections.unmodifiableList(list); } } private static class PlatformTZProvider implements ZoneProvider { @Override public Set<String> getAvailableIDs() { Set<String> ret = new HashSet<String>(); String[] temp = java.util.TimeZone.getAvailableIDs(); ret.addAll(Arrays.asList(temp)); return ret; } @Override public Set<String> getPreferredIDs( Locale locale, boolean smart ) { ZoneProvider zp = ZONENAME_PROVIDER; if (zp == null) { return Collections.emptySet(); } return zp.getPreferredIDs(locale, smart); } @Override public Map<String, String> getAliases() { return Collections.emptyMap(); // JDK hat eingebaute Alias-Suche! } @Override public String getFallback() { return ""; } @Override public String getName() { return "java.util.TimeZone"; } @Override public String getLocation() { return ""; } @Override public String getVersion() { return ""; } @Override public TransitionHistory load(String zoneID) { return null; } @Override public String getDisplayName( String tzid, NameStyle style, Locale locale ) { if (locale == null) { throw new NullPointerException("Missing locale."); } else if (tzid.isEmpty()) { return ""; } java.util.TimeZone tz = PlatformTimezone.findZone(tzid); if (tz.getID().equals(tzid)) { return tz.getDisplayName( style.isDaylightSaving(), style.isAbbreviation() ? java.util.TimeZone.SHORT : java.util.TimeZone.LONG, locale ); } return tzid; } } }
package org.opencps.dossiermgt.portlet; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import javax.portlet.ActionRequest; import javax.portlet.ActionResponse; import javax.portlet.PortletException; import javax.portlet.RenderRequest; import javax.portlet.RenderResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.opencps.accountmgt.NoSuchAccountException; import org.opencps.accountmgt.NoSuchAccountFolderException; import org.opencps.accountmgt.NoSuchAccountOwnOrgIdException; import org.opencps.accountmgt.NoSuchAccountOwnUserIdException; import org.opencps.accountmgt.NoSuchAccountTypeException; import org.opencps.accountmgt.model.Business; import org.opencps.accountmgt.model.Citizen; import org.opencps.backend.message.UserActionMsg; import org.opencps.datamgt.model.DictCollection; import org.opencps.datamgt.model.DictItem; import org.opencps.datamgt.service.DictCollectionLocalServiceUtil; import org.opencps.datamgt.service.DictItemLocalServiceUtil; import org.opencps.dossiermgt.CreateDossierFolderException; import org.opencps.dossiermgt.DuplicateFileGroupException; import org.opencps.dossiermgt.EmptyDossierAddressException; import org.opencps.dossiermgt.EmptyDossierCityCodeException; import org.opencps.dossiermgt.EmptyDossierContactNameException; import org.opencps.dossiermgt.EmptyDossierDistrictCodeException; import org.opencps.dossiermgt.EmptyDossierFileException; import org.opencps.dossiermgt.EmptyDossierSubjectIdException; import org.opencps.dossiermgt.EmptyDossierSubjectNameException; import org.opencps.dossiermgt.EmptyDossierWardCodeException; import org.opencps.dossiermgt.EmptyFileGroupException; import org.opencps.dossiermgt.InvalidDossierObjectException; import org.opencps.dossiermgt.NoSuchDossierException; import org.opencps.dossiermgt.NoSuchDossierFileException; import org.opencps.dossiermgt.NoSuchDossierPartException; import org.opencps.dossiermgt.NoSuchDossierTemplateException; import org.opencps.dossiermgt.OutOfLengthDossierAddressException; import org.opencps.dossiermgt.OutOfLengthDossierContactEmailException; import org.opencps.dossiermgt.OutOfLengthDossierContactNameException; import org.opencps.dossiermgt.OutOfLengthDossierContactTelNoException; import org.opencps.dossiermgt.OutOfLengthDossierSubjectIdException; import org.opencps.dossiermgt.OutOfLengthDossierSubjectNameException; import org.opencps.dossiermgt.PermissionDossierException; import org.opencps.dossiermgt.RequiredDossierPartException; import org.opencps.dossiermgt.bean.AccountBean; import org.opencps.dossiermgt.model.Dossier; import org.opencps.dossiermgt.model.DossierFile; import org.opencps.dossiermgt.model.DossierPart; import org.opencps.dossiermgt.model.DossierTemplate; import org.opencps.dossiermgt.model.ServiceConfig; import org.opencps.dossiermgt.search.DossierDisplayTerms; import org.opencps.dossiermgt.search.DossierFileDisplayTerms; import org.opencps.dossiermgt.service.DossierFileLocalServiceUtil; import org.opencps.dossiermgt.service.DossierLocalServiceUtil; import org.opencps.dossiermgt.service.DossierPartLocalServiceUtil; import org.opencps.dossiermgt.service.DossierTemplateLocalServiceUtil; import org.opencps.dossiermgt.service.FileGroupLocalServiceUtil; import org.opencps.dossiermgt.service.ServiceConfigLocalServiceUtil; import org.opencps.dossiermgt.util.DossierMgtUtil; import org.opencps.jasperreport.util.JRReportUtil; import org.opencps.jms.context.JMSContext; import org.opencps.jms.message.SubmitDossierMessage; import org.opencps.jms.util.JMSMessageUtil; import org.opencps.processmgt.model.ProcessOrder; import org.opencps.processmgt.service.ProcessOrderLocalServiceUtil; import org.opencps.servicemgt.model.ServiceInfo; import org.opencps.servicemgt.service.ServiceInfoLocalServiceUtil; import org.opencps.util.AccountUtil; import org.opencps.util.DLFileEntryUtil; import org.opencps.util.DLFolderUtil; import org.opencps.util.DateTimeUtil; import org.opencps.util.MessageKeys; import org.opencps.util.PortletConstants; import org.opencps.util.PortletPropsValues; import org.opencps.util.PortletUtil; import org.opencps.util.WebKeys; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.exception.SystemException; import com.liferay.portal.kernel.json.JSONFactoryUtil; import com.liferay.portal.kernel.json.JSONObject; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.messaging.Message; import com.liferay.portal.kernel.messaging.MessageBusUtil; import com.liferay.portal.kernel.repository.model.FileEntry; import com.liferay.portal.kernel.servlet.SessionErrors; import com.liferay.portal.kernel.servlet.SessionMessages; import com.liferay.portal.kernel.upload.UploadPortletRequest; import com.liferay.portal.kernel.util.GetterUtil; import com.liferay.portal.kernel.util.MimeTypesUtil; import com.liferay.portal.kernel.util.ParamUtil; import com.liferay.portal.kernel.util.StreamUtil; import com.liferay.portal.kernel.util.StringPool; import com.liferay.portal.kernel.util.StringUtil; import com.liferay.portal.kernel.util.Validator; import com.liferay.portal.service.ServiceContext; import com.liferay.portal.service.ServiceContextFactory; import com.liferay.portal.theme.ThemeDisplay; import com.liferay.portal.util.PortalUtil; import com.liferay.portlet.documentlibrary.DuplicateFileException; import com.liferay.portlet.documentlibrary.DuplicateFolderNameException; import com.liferay.portlet.documentlibrary.FileSizeException; import com.liferay.portlet.documentlibrary.NoSuchFileEntryException; import com.liferay.portlet.documentlibrary.model.DLFolder; import com.liferay.portlet.documentlibrary.service.DLAppServiceUtil; import com.liferay.util.bridges.mvc.MVCPortlet; /** * @author trungnt */ public class DossierMgtFrontOfficePortlet extends MVCPortlet { private Log _log = LogFactoryUtil.getLog(DossierMgtFrontOfficePortlet.class.getName()); /** * @param actionRequest * @param actionResponse * @throws IOException */ public void addAttachmentFile( ActionRequest actionRequest, ActionResponse actionResponse) throws IOException { AccountBean accountBean = AccountUtil.getAccountBean(actionRequest); UploadPortletRequest uploadPortletRequest = PortalUtil.getUploadPortletRequest(actionRequest); Dossier dossier = null; DossierFile dossierFile = null; DossierPart dossierPart = null; boolean updated = false; long dossierId = ParamUtil.getLong(uploadPortletRequest, DossierDisplayTerms.DOSSIER_ID); long dossierFileId = ParamUtil.getLong(uploadPortletRequest, DossierFileDisplayTerms.DOSSIER_FILE_ID); long dossierPartId = ParamUtil.getLong(uploadPortletRequest, DossierFileDisplayTerms.DOSSIER_PART_ID); long groupDossierPartId = ParamUtil.getLong(uploadPortletRequest, "groupDossierPartId"); long fileGroupId = ParamUtil.getLong(uploadPortletRequest, DossierDisplayTerms.FILE_GROUP_ID); long size = uploadPortletRequest.getSize(DossierFileDisplayTerms.DOSSIER_FILE_UPLOAD); int dossierFileType = ParamUtil.getInteger(uploadPortletRequest, DossierFileDisplayTerms.DOSSIER_FILE_TYPE); int dossierFileOriginal = ParamUtil.getInteger(uploadPortletRequest, DossierFileDisplayTerms.DOSSIER_FILE_ORIGINAL); String groupName = ParamUtil.getString(uploadPortletRequest, DossierFileDisplayTerms.GROUP_NAME); String displayName = ParamUtil.getString(uploadPortletRequest, DossierFileDisplayTerms.DISPLAY_NAME); String dossierFileNo = ParamUtil.getString(uploadPortletRequest, DossierFileDisplayTerms.DOSSIER_FILE_NO); String dossierFileDate = ParamUtil.getString(uploadPortletRequest, DossierFileDisplayTerms.DOSSIER_FILE_DATE); String sourceFileName = uploadPortletRequest.getFileName(DossierFileDisplayTerms.DOSSIER_FILE_UPLOAD); /* * sourceFileName = sourceFileName * .concat(PortletConstants.TEMP_RANDOM_SUFFIX).concat(StringUtil * .randomString()); */ String redirectURL = ParamUtil.getString(uploadPortletRequest, "redirectURL"); InputStream inputStream = null; Date fileDate = null; if (Validator.isNotNull(dossierFileDate)) { fileDate = DateTimeUtil.convertStringToDate(dossierFileDate); } try { inputStream = uploadPortletRequest.getFileAsStream(DossierFileDisplayTerms.DOSSIER_FILE_UPLOAD); validateAddAttachDossierFile(dossierId, dossierPartId, dossierFileId, displayName, size, sourceFileName, inputStream, accountBean); ServiceContext serviceContext = ServiceContextFactory.getInstance(uploadPortletRequest); serviceContext.setAddGroupPermissions(true); serviceContext.setAddGuestPermissions(true); dossier = DossierLocalServiceUtil.getDossier(dossierId); if (dossierFileId > 0) { dossierFile = DossierFileLocalServiceUtil.getDossierFile(dossierFileId); } dossierPart = DossierPartLocalServiceUtil.getDossierPart(dossierPartId); String contentType = uploadPortletRequest.getContentType(DossierFileDisplayTerms.DOSSIER_FILE_UPLOAD); DLFolder accountFolder = accountBean.getAccountFolder(); DLFolder dossierFolder = DLFolderUtil.addFolder(serviceContext.getUserId(), serviceContext.getScopeGroupId(), serviceContext.getScopeGroupId(), false, accountFolder.getFolderId(), String.valueOf(dossier.getCounter()), StringPool.BLANK, false, serviceContext); DossierFileLocalServiceUtil.addDossierFile( serviceContext.getUserId(), dossierId, dossierPartId, dossierPart.getTemplateFileNo(), groupName, fileGroupId, groupDossierPartId, accountBean.getOwnerUserId(), accountBean.getOwnerOrganizationId(), displayName, StringPool.BLANK, dossierFile != null ? dossierFile.getFileEntryId() : 0, PortletConstants.DOSSIER_FILE_MARK_UNKNOW, dossierFileType, dossierFileNo, fileDate, dossierFileOriginal, PortletConstants.DOSSIER_FILE_SYNC_STATUS_NOSYNC, dossierFolder.getFolderId(), sourceFileName, contentType, displayName, StringPool.BLANK, StringPool.BLANK, inputStream, size, serviceContext); updated = true; } catch (Exception e) { updated = false; if (e instanceof DuplicateFileException) { SessionErrors.add(actionRequest, DuplicateFileException.class); } else if (e instanceof NoSuchDossierException) { SessionErrors.add(actionRequest, NoSuchDossierException.class); } else if (e instanceof NoSuchDossierPartException) { SessionErrors.add(actionRequest, NoSuchDossierPartException.class); } else if (e instanceof NoSuchAccountException) { SessionErrors.add(actionRequest, NoSuchAccountException.class); } else if (e instanceof NoSuchAccountTypeException) { SessionErrors.add(actionRequest, NoSuchAccountTypeException.class); } else if (e instanceof NoSuchAccountFolderException) { SessionErrors.add(actionRequest, NoSuchAccountFolderException.class); } else if (e instanceof NoSuchAccountOwnUserIdException) { SessionErrors.add(actionRequest, NoSuchAccountOwnUserIdException.class); } else if (e instanceof NoSuchAccountOwnOrgIdException) { SessionErrors.add(actionRequest, NoSuchAccountOwnOrgIdException.class); } else if (e instanceof PermissionDossierException) { SessionErrors.add(actionRequest, PermissionDossierException.class); } else if (e instanceof FileSizeException) { SessionErrors.add(actionRequest, FileSizeException.class); } else { SessionErrors.add(actionRequest, "upload-error"); } _log.error(e); } finally { if (updated) { if (Validator.isNotNull(redirectURL)) { actionResponse.sendRedirect(redirectURL); } } else { actionResponse.setRenderParameter("redirectURL", redirectURL); actionResponse.setRenderParameter("content", "upload-file"); actionResponse.setRenderParameter("jspPage", "/html/portlets/dossiermgt/frontoffice/modal_dialog.jsp"); } } } /** * @param actionRequest * @param actionResponse * @throws IOException */ public void addIndividualPartGroup( ActionRequest actionRequest, ActionResponse actionResponse) throws IOException { boolean updated = false; long dossierId = ParamUtil.getLong(actionRequest, DossierDisplayTerms.DOSSIER_ID); long dossierPartId = ParamUtil.getLong(actionRequest, DossierFileDisplayTerms.DOSSIER_PART_ID); String partName = ParamUtil.getString(actionRequest, DossierFileDisplayTerms.PART_NAME); String redirectURL = ParamUtil.getString(actionRequest, "redirectURL"); try { ServiceContext serviceContext = ServiceContextFactory.getInstance(actionRequest); valiadateFileGroup(dossierId, partName); FileGroupLocalServiceUtil.addFileGroup(serviceContext.getUserId(), dossierId, dossierPartId, partName, PortletConstants.DOSSIER_FILE_SYNC_STATUS_NOSYNC, serviceContext); } catch (Exception e) { updated = false; if (e instanceof NoSuchDossierException) { SessionErrors.add(actionRequest, NoSuchDossierException.class); } else if (e instanceof EmptyFileGroupException) { SessionErrors.add(actionRequest, EmptyFileGroupException.class); } else if (e instanceof DuplicateFileGroupException) { SessionErrors.add(actionRequest, DuplicateFileGroupException.class); } else { SessionErrors.add(actionRequest, MessageKeys.DOSSIER_SYSTEM_EXCEPTION_OCCURRED); } _log.error(e); } finally { if (updated) { if (Validator.isNotNull(redirectURL)) { actionResponse.sendRedirect(redirectURL); } } else { actionResponse.setRenderParameter("redirectURL", redirectURL); actionResponse.setRenderParameter("content", "individual"); actionResponse.setRenderParameter("jspPage", "/html/portlets/dossiermgt/frontoffice/modal_dialog.jsp"); } } } /** * @param actionRequest * @param actionResponse */ public void addTempFile( ActionRequest actionRequest, ActionResponse actionResponse) { UploadPortletRequest uploadPortletRequest = PortalUtil.getUploadPortletRequest(actionRequest); long folderId = ParamUtil.getLong(uploadPortletRequest, DossierFileDisplayTerms.FOLDE_ID); long dossierPartId = ParamUtil.getLong(uploadPortletRequest, DossierFileDisplayTerms.DOSSIER_PART_ID); int index = ParamUtil.getInteger(uploadPortletRequest, DossierFileDisplayTerms.INDEX); int level = ParamUtil.getInteger(uploadPortletRequest, DossierFileDisplayTerms.LEVEL); String groupName = ParamUtil.getString(uploadPortletRequest, DossierFileDisplayTerms.GROUP_NAME); String templateFileNo = ParamUtil.getString(uploadPortletRequest, DossierDisplayTerms.TEMPLATE_FILE_NO); String fileName = ParamUtil.getString(uploadPortletRequest, DossierFileDisplayTerms.FILE_NAME); String partType = ParamUtil.getString(uploadPortletRequest, DossierFileDisplayTerms.PART_TYPE); String tempFolderName = ParamUtil.getString(uploadPortletRequest, DossierFileDisplayTerms.TEMP_FOLDER_NAME); ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY); String redirectURL = ParamUtil.getString(uploadPortletRequest, "redirectURL"); String displayName = ParamUtil.getString(uploadPortletRequest, DossierFileDisplayTerms.DISPLAY_NAME); String dossierFileNo = ParamUtil.getString(uploadPortletRequest, DossierFileDisplayTerms.DOSSIER_FILE_NO); String dossierFileDate = ParamUtil.getString(uploadPortletRequest, DossierFileDisplayTerms.DOSSIER_FILE_DATE); String sourceFileName = uploadPortletRequest.getFileName(DossierFileDisplayTerms.DOSSIER_FILE_UPLOAD); sourceFileName = sourceFileName.concat(PortletConstants.TEMP_RANDOM_SUFFIX).concat( StringUtil.randomString()); InputStream inputStream = null; JSONObject jsonObject = JSONFactoryUtil.createJSONObject(); try { inputStream = uploadPortletRequest.getFileAsStream(DossierFileDisplayTerms.DOSSIER_FILE_UPLOAD); String contentType = uploadPortletRequest.getContentType(DossierFileDisplayTerms.DOSSIER_FILE_UPLOAD); FileEntry fileEntry = DLAppServiceUtil.addTempFileEntry( themeDisplay.getScopeGroupId(), folderId, sourceFileName, tempFolderName, inputStream, contentType); jsonObject.put(DossierFileDisplayTerms.DOSSIER_FILE_NO, dossierFileNo); jsonObject.put(DossierFileDisplayTerms.DISPLAY_NAME, displayName); jsonObject.put(DossierFileDisplayTerms.DOSSIER_FILE_DATE, dossierFileDate); jsonObject.put(DossierFileDisplayTerms.FILE_TITLE, fileEntry.getTitle()); jsonObject.put(DossierFileDisplayTerms.MIME_TYPE, fileEntry.getMimeType()); jsonObject.put(DossierFileDisplayTerms.FILE_NAME, fileName); jsonObject.put(DossierFileDisplayTerms.FILE_ENTRY_ID, fileEntry.getFileEntryId()); jsonObject.put(DossierFileDisplayTerms.FOLDE_ID, fileEntry.getFolderId()); jsonObject.put(DossierFileDisplayTerms.DOSSIER_PART_ID, dossierPartId); jsonObject.put(DossierFileDisplayTerms.INDEX, index); jsonObject.put(DossierFileDisplayTerms.LEVEL, level); jsonObject.put(DossierFileDisplayTerms.PART_TYPE, partType); jsonObject.put(DossierFileDisplayTerms.GROUP_NAME, groupName); jsonObject.put(DossierFileDisplayTerms.DOSSIER_FILE_ORIGINAL, PortletConstants.DOSSIER_FILE_ORIGINAL); jsonObject.put(DossierFileDisplayTerms.DOSSIER_FILE_TYPE, PortletConstants.DOSSIER_FILE_TYPE_INPUT); jsonObject.put(DossierDisplayTerms.TEMPLATE_FILE_NO, templateFileNo); } catch (Exception e) { _log.error(e); SessionErrors.add(actionRequest, "upload-error"); } finally { StreamUtil.cleanUp(inputStream); HttpServletRequest request = PortalUtil.getHttpServletRequest(actionRequest); request.setAttribute(WebKeys.RESPONSE_UPLOAD_TEMP_DOSSIER_FILE, jsonObject); if (Validator.isNotNull(redirectURL)) { actionResponse.setRenderParameter("jspPage", "/html/portlets/dossiermgt/frontoffice/upload_dossier_file.jsp"); } } } /** * @param actionRequest * @param actionResponse * @throws IOException */ public void cloneDossierFile( ActionRequest actionRequest, ActionResponse actionResponse) throws IOException { Dossier dossier = null; DossierFile dossierFile = null; DossierPart dossierPart = null; boolean updated = false; long cloneDossierFileId = ParamUtil.getLong(actionRequest, "cloneDossierFileId"); long dossierId = ParamUtil.getLong(actionRequest, DossierDisplayTerms.DOSSIER_ID); long dossierPartId = ParamUtil.getLong(actionRequest, DossierFileDisplayTerms.DOSSIER_PART_ID); long groupDossierPartId = ParamUtil.getLong(actionRequest, "groupDossierPartId"); long fileGroupId = ParamUtil.getLong(actionRequest, DossierDisplayTerms.FILE_GROUP_ID); String groupName = ParamUtil.getString(actionRequest, DossierFileDisplayTerms.GROUP_NAME); String redirectURL = ParamUtil.getString(actionRequest, "redirectURL"); try { ServiceContext serviceContext = ServiceContextFactory.getInstance(actionRequest); serviceContext.setAddGroupPermissions(true); serviceContext.setAddGuestPermissions(true); dossier = DossierLocalServiceUtil.getDossier(dossierId); AccountBean accountBean = AccountUtil.getAccountBean(dossier.getUserId(), serviceContext.getScopeGroupId(), serviceContext); validateCloneDossierFile(dossierId, dossierPartId, cloneDossierFileId, accountBean); dossierFile = DossierFileLocalServiceUtil.getDossierFile(cloneDossierFileId); long fileEntryId = dossierFile.getFileEntryId(); FileEntry fileEntry = DLAppServiceUtil.getFileEntry(fileEntryId); dossierPart = DossierPartLocalServiceUtil.getDossierPart(dossierPartId); DLFolder accountFolder = accountBean.getAccountFolder(); DLFolder dossierFolder = DLFolderUtil.addFolder(serviceContext.getUserId(), serviceContext.getScopeGroupId(), serviceContext.getScopeGroupId(), false, accountFolder.getFolderId(), String.valueOf(dossier.getCounter()), StringPool.BLANK, false, serviceContext); DossierFileLocalServiceUtil.addDossierFile( serviceContext.getUserId(), dossierId, dossierPartId, dossierPart.getTemplateFileNo(), groupName, fileGroupId, groupDossierPartId, accountBean.getOwnerUserId(), accountBean.getOwnerOrganizationId(), dossierFile.getDisplayName(), StringPool.BLANK, dossierFile != null ? dossierFile.getFileEntryId() : 0, PortletConstants.DOSSIER_FILE_MARK_UNKNOW, dossierFile.getDossierFileType(), dossierFile.getDossierFileNo(), dossierFile.getDossierFileDate(), dossierFile.getOriginal(), PortletConstants.DOSSIER_FILE_SYNC_STATUS_NOSYNC, dossierFolder.getFolderId(), fileEntry.getTitle() + StringPool.PERIOD + fileEntry.getExtension(), fileEntry.getMimeType(), fileEntry.getTitle(), StringPool.BLANK, StringPool.BLANK, fileEntry.getContentStream(), fileEntry.getSize(), serviceContext); updated = true; } catch (Exception e) { updated = false; if (e instanceof DuplicateFileException) { SessionErrors.add(actionRequest, DuplicateFileException.class); } else if (e instanceof NoSuchDossierException) { SessionErrors.add(actionRequest, NoSuchDossierException.class); } else if (e instanceof NoSuchDossierPartException) { SessionErrors.add(actionRequest, NoSuchDossierPartException.class); } else if (e instanceof NoSuchAccountException) { SessionErrors.add(actionRequest, NoSuchAccountException.class); } else if (e instanceof NoSuchAccountTypeException) { SessionErrors.add(actionRequest, NoSuchAccountTypeException.class); } else if (e instanceof NoSuchAccountFolderException) { SessionErrors.add(actionRequest, NoSuchAccountFolderException.class); } else if (e instanceof NoSuchAccountOwnUserIdException) { SessionErrors.add(actionRequest, NoSuchAccountOwnUserIdException.class); } else if (e instanceof NoSuchAccountOwnOrgIdException) { SessionErrors.add(actionRequest, NoSuchAccountOwnOrgIdException.class); } else if (e instanceof PermissionDossierException) { SessionErrors.add(actionRequest, PermissionDossierException.class); } else if (e instanceof NoSuchFileEntryException) { SessionErrors.add(actionRequest, NoSuchFileEntryException.class); } else { SessionErrors.add(actionRequest, "upload-error"); } _log.error(e); } finally { if (updated) { if (Validator.isNotNull(redirectURL)) { actionResponse.sendRedirect(redirectURL); } } else { actionResponse.setRenderParameter("redirectURL", redirectURL); actionResponse.setRenderParameter("content", "upload-file"); actionResponse.setRenderParameter("tab1", "select-file"); actionResponse.setRenderParameter("jspPage", "/html/portlets/dossiermgt/frontoffice/modal_dialog.jsp"); } } } /** * @param actionRequest * @param actionResponse * @throws IOException */ public void createReport( ActionRequest actionRequest, ActionResponse actionResponse) throws IOException { ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY); AccountBean accountBean = AccountUtil.getAccountBean(actionRequest); long dossierFileId = ParamUtil.getLong(actionRequest, DossierFileDisplayTerms.DOSSIER_FILE_ID); String sourceFileName = StringPool.BLANK; InputStream inputStream = null; File file = null; JSONObject responseJSON = JSONFactoryUtil.createJSONObject(); String fileExportDir = StringPool.BLANK; try { validateCreateDynamicForm(dossierFileId, accountBean); ServiceContext serviceContext = ServiceContextFactory.getInstance(actionRequest); serviceContext.setAddGroupPermissions(true); serviceContext.setAddGuestPermissions(true); // Get dossier file DossierFile dossierFile = DossierFileLocalServiceUtil.getDossierFile(dossierFileId); // Get dossier part DossierPart dossierPart = DossierPartLocalServiceUtil.getDossierPart(dossierFile.getDossierPartId()); Dossier dossier = DossierLocalServiceUtil.getDossier(dossierFile.getDossierId()); // Get account folder DLFolder accountForlder = accountBean.getAccountFolder(); // Get dossier folder DLFolder dosserFolder = DLFolderUtil.addFolder(themeDisplay.getUserId(), themeDisplay.getScopeGroupId(), themeDisplay.getScopeGroupId(), false, accountForlder.getFolderId(), String.valueOf(dossier.getCounter()), StringPool.BLANK, false, serviceContext); String formData = dossierFile.getFormData(); String jrxmlTemplate = dossierPart.getFormReport(); // Validate json string JSONFactoryUtil.createJSONObject(formData); String outputDestination = PortletPropsValues.OPENCPS_FILE_SYSTEM_TEMP_DIR; String fileName = System.currentTimeMillis() + StringPool.DASH + dossierFileId + StringPool.DASH + dossierPart.getDossierpartId() + ".pdf"; fileExportDir = exportToPDFFile(jrxmlTemplate, formData, null, outputDestination, fileName); if (Validator.isNotNull(fileExportDir)) { file = new File(fileExportDir); inputStream = new FileInputStream(file); if (inputStream != null) { sourceFileName = fileExportDir.substring( fileExportDir.lastIndexOf(StringPool.SLASH) + 1, fileExportDir.length()); String mimeType = MimeTypesUtil.getContentType(file); // Add new version if (dossierFile.getFileEntryId() > 0) { DossierFileLocalServiceUtil.addDossierFile( dossierFile.getDossierFileId(), dosserFolder.getFolderId(), sourceFileName, mimeType, dossierFile.getDisplayName(), StringPool.BLANK, StringPool.BLANK, inputStream, file.length(), serviceContext); } else { // Update version 1 DossierFileLocalServiceUtil.updateDossierFile( dossierFileId, dosserFolder.getFolderId(), sourceFileName, mimeType, dossierFile.getDisplayName(), StringPool.BLANK, StringPool.BLANK, inputStream, file.length(), serviceContext); } } } } catch (Exception e) { if (e instanceof NoSuchDossierFileException) { SessionErrors.add(actionRequest, NoSuchDossierFileException.class); } else if (e instanceof NoSuchAccountException) { SessionErrors.add(actionRequest, NoSuchAccountException.class); } else if (e instanceof NoSuchAccountTypeException) { SessionErrors.add(actionRequest, NoSuchAccountTypeException.class); } else if (e instanceof NoSuchAccountFolderException) { SessionErrors.add(actionRequest, NoSuchAccountFolderException.class); } else if (e instanceof NoSuchAccountOwnUserIdException) { SessionErrors.add(actionRequest, NoSuchAccountOwnUserIdException.class); } else if (e instanceof NoSuchAccountOwnOrgIdException) { SessionErrors.add(actionRequest, NoSuchAccountOwnOrgIdException.class); } else if (e instanceof PermissionDossierException) { SessionErrors.add(actionRequest, PermissionDossierException.class); } else if (e instanceof DuplicateFileException) { SessionErrors.add(actionRequest, DuplicateFileException.class); } else { SessionErrors.add(actionRequest, PortalException.class); } _log.error(e); } finally { responseJSON.put("fileExportDir", fileExportDir); PortletUtil.writeJSON(actionRequest, actionResponse, responseJSON); if (inputStream != null) { inputStream.close(); } if (file.exists()) { file.delete(); } } } /** * @param actionRequest * @param actionResponse * @throws IOException */ public void deleteAttachmentFile( ActionRequest actionRequest, ActionResponse actionResponse) throws IOException { long dossierFileId = ParamUtil.getLong(actionRequest, DossierFileDisplayTerms.DOSSIER_FILE_ID); DossierFile dossierFile = null; JSONObject jsonObject = null; try { if (dossierFileId > 0) { jsonObject = JSONFactoryUtil.createJSONObject(); dossierFile = DossierFileLocalServiceUtil.getDossierFile(dossierFileId); long fileEntryId = dossierFile.getFileEntryId(); DossierFileLocalServiceUtil.deleteDossierFile(dossierFileId, fileEntryId); jsonObject.put("deleted", Boolean.TRUE); } } catch (Exception e) { jsonObject.put("deleted", Boolean.FALSE); _log.error(e); } finally { PortletUtil.writeJSON(actionRequest, actionResponse, jsonObject); } } /** * @param actionRequest * @param actionResponse * @throws IOException */ public void deleteDossier( ActionRequest actionRequest, ActionResponse actionResponse) throws IOException { long dossierId = ParamUtil.getLong(actionRequest, DossierDisplayTerms.DOSSIER_ID); String dossierStatus = ParamUtil.getString(actionRequest, DossierDisplayTerms.DOSSIER_STATUS); String redirectURL = ParamUtil.getString(actionRequest, "redirectURL"); AccountBean accountBean = AccountUtil.getAccountBean(actionRequest); try { if (dossierStatus.equals(PortletConstants.DOSSIER_STATUS_NEW)) { validateDeleteDossier(dossierId, accountBean); DLFolder accountFolder = accountBean.getAccountFolder(); DossierLocalServiceUtil.deleteDossierByDossierId(dossierId, accountFolder); } } catch (Exception e) { if (e instanceof NoSuchDossierException) { SessionErrors.add(actionRequest, NoSuchDossierException.class); } else if (e instanceof NoSuchAccountException) { SessionErrors.add(actionRequest, NoSuchAccountException.class); } else if (e instanceof NoSuchAccountTypeException) { SessionErrors.add(actionRequest, NoSuchAccountTypeException.class); } else if (e instanceof NoSuchAccountFolderException) { SessionErrors.add(actionRequest, NoSuchAccountFolderException.class); } else if (e instanceof NoSuchAccountOwnUserIdException) { SessionErrors.add(actionRequest, NoSuchAccountOwnUserIdException.class); } else if (e instanceof NoSuchAccountOwnOrgIdException) { SessionErrors.add(actionRequest, NoSuchAccountOwnOrgIdException.class); } else if (e instanceof PermissionDossierException) { SessionErrors.add(actionRequest, PermissionDossierException.class); } else { SessionErrors.add(actionRequest, PortalException.class); } _log.error(e); } finally { if (Validator.isNotNull(redirectURL)) { actionResponse.sendRedirect(redirectURL); } } } /** * @param actionRequest * @param actionResponse * @throws IOException */ public void deleteDossierFile( ActionRequest actionRequest, ActionResponse actionResponse) throws IOException { long dossierFileId = ParamUtil.getLong(actionRequest, DossierFileDisplayTerms.DOSSIER_FILE_ID); if (dossierFileId > 0) { DossierFile dossierFile = null; JSONObject jsonObject = JSONFactoryUtil.createJSONObject(); try { dossierFile = DossierFileLocalServiceUtil.getDossierFile(dossierFileId); if (dossierFile != null) { long fileEntryId = dossierFile.getFileEntryId(); try { if (fileEntryId > 0) { DLAppServiceUtil.deleteFileEntry(fileEntryId); } } catch (Exception e) { // nothing to do } DossierFileLocalServiceUtil.deleteDossierFile(dossierFile); jsonObject.put("deleted", Boolean.TRUE); } } catch (Exception e) { _log.error(e); jsonObject.put("deleted", Boolean.FALSE); } writeJSON(actionRequest, actionResponse, jsonObject); } } /** * @param actionRequest * @param actionResponse * @throws IOException */ public void deleteTempFile( ActionRequest actionRequest, ActionResponse actionResponse) throws IOException { ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY); long fileEntryId = ParamUtil.getLong(actionRequest, "fileEntryId"); JSONObject jsonObject = JSONFactoryUtil.createJSONObject(); try { DLAppServiceUtil.deleteFileEntry(fileEntryId); jsonObject.put("deleted", Boolean.TRUE); } catch (Exception e) { String errorMessage = themeDisplay.translate("an-unexpected-error-occurred-while-deleting-the-file"); jsonObject.put("deleted", Boolean.FALSE); jsonObject.put("errorMessage", errorMessage); } writeJSON(actionRequest, actionResponse, jsonObject); } /** * @param groupId * @param folderId * @param tempFolderName * @param fileName * @throws Exception */ protected void deleteTempFile( long groupId, long folderId, String tempFolderName, String fileName) throws Exception { try { DLAppServiceUtil.deleteTempFileEntry(groupId, folderId, fileName, tempFolderName); } catch (Exception e) { _log.error(e); } } public void deleteTempFiles( ActionRequest actionRequest, ActionResponse actionResponse) { String strFileEntryIds = ParamUtil.getString(actionRequest, "fileEntryIds"); if (Validator.isNotNull(strFileEntryIds)) { long[] fileEntryIds = StringUtil.split(strFileEntryIds, 0L); if (fileEntryIds != null) { for (int i = 0; i < fileEntryIds.length; i++) { try { DLAppServiceUtil.deleteFileEntry(fileEntryIds[i]); } catch (Exception e) { continue; } } } } } /** * @param jrxmlTemplate * @param formData * @param map * @param outputDestination * @param fileName * @return */ protected String exportToPDFFile( String jrxmlTemplate, String formData, Map<String, Object> map, String outputDestination, String fileName) { return JRReportUtil.createReportPDFfFile(jrxmlTemplate, formData, map, outputDestination, fileName); } /** * @param object * @param dictCollection * @return */ protected String getSelectedItems( Object object, DictCollection dictCollection) { String selectedItems = StringPool.BLANK; String cityCode = StringPool.BLANK; String districtCode = StringPool.BLANK; String wardCode = StringPool.BLANK; if (object instanceof Citizen) { Citizen citizen = (Citizen) object; cityCode = citizen.getCityCode(); districtCode = citizen.getDistrictCode(); wardCode = citizen.getWardCode(); } else if (object instanceof Business) { Business business = (Business) object; cityCode = business.getCityCode(); districtCode = business.getDistrictCode(); wardCode = business.getWardCode(); } else if (object instanceof Dossier) { Dossier dossier = (Dossier) object; cityCode = dossier.getCityCode(); districtCode = dossier.getDistrictCode(); wardCode = dossier.getWardCode(); } try { DictItem city = DictItemLocalServiceUtil.getDictItemInuseByItemCode( dictCollection.getDictCollectionId(), cityCode); DictItem district = DictItemLocalServiceUtil.getDictItemInuseByItemCode( dictCollection.getDictCollectionId(), districtCode); DictItem ward = DictItemLocalServiceUtil.getDictItemInuseByItemCode( dictCollection.getDictCollectionId(), wardCode); String[] dictItemIds = new String[3]; dictItemIds[0] = city != null ? String.valueOf(city.getDictItemId()) : StringPool.BLANK; dictItemIds[1] = district != null ? String.valueOf(district.getDictItemId()) : StringPool.BLANK; dictItemIds[2] = ward != null ? String.valueOf(ward.getDictItemId()) : StringPool.BLANK; selectedItems = StringUtil.merge(dictItemIds); } catch (Exception e) { // Nothing todo } return selectedItems; } /** * @param actionRequest * @param actionResponse */ public void previewAttachmentFile( ActionRequest actionRequest, ActionResponse actionResponse) { long dossierFileId = ParamUtil.getLong(actionRequest, DossierFileDisplayTerms.DOSSIER_FILE_ID); ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY); String url = DLFileEntryUtil.getDossierFileAttachmentURL(dossierFileId, themeDisplay); JSONObject jsonObject = JSONFactoryUtil.createJSONObject(); jsonObject.put("url", url); try { PortletUtil.writeJSON(actionRequest, actionResponse, jsonObject); } catch (IOException e) { _log.error(e); } } /** * @param actionRequest * @param actionResponse * @throws IOException */ public void previewDynamicForm( ActionRequest actionRequest, ActionResponse actionResponse) throws IOException { long dossierFileId = ParamUtil.getLong(actionRequest, DossierFileDisplayTerms.DOSSIER_FILE_ID); String redirectURL = ParamUtil.getString(actionRequest, "redirectURL"); HttpServletResponse response = PortalUtil.getHttpServletResponse(actionResponse); response.setContentType("text/html"); PrintWriter writer = null; try { writer = response.getWriter(); // Get dossier file DossierFile dossierFile = DossierFileLocalServiceUtil.getDossierFile(dossierFileId); // Get dossier part DossierPart dossierPart = DossierPartLocalServiceUtil.getDossierPart(dossierFile.getDossierPartId()); String formData = dossierFile.getFormData(); String jrxmlTemplate = dossierPart.getFormReport(); // Validate json string JSONFactoryUtil.createJSONObject(formData); JRReportUtil.renderReportHTMLStream(response, writer, jrxmlTemplate, formData, null); } catch (Exception e) { _log.error(e); } finally { if (Validator.isNotNull(redirectURL)) { response.sendRedirect(redirectURL); } } } /** * @param actionRequest * @param actionResponse * @throws IOException */ public void removeAttachmentFile( ActionRequest actionRequest, ActionResponse actionResponse) throws IOException { long dossierFileId = ParamUtil.getLong(actionRequest, DossierFileDisplayTerms.DOSSIER_FILE_ID); JSONObject jsonObject = null; try { DossierFile dossierFile = DossierFileLocalServiceUtil.getDossierFile(dossierFileId); DossierPart dossierPart = DossierPartLocalServiceUtil.getDossierPart(dossierFile.getDossierPartId()); jsonObject = JSONFactoryUtil.createJSONObject(); if (dossierFileId > 0 && dossierPart.getPartType() != PortletConstants.DOSSIER_PART_TYPE_OTHER) { DossierFileLocalServiceUtil.removeDossierFile(dossierFileId); } else { DossierFileLocalServiceUtil.deleteDossierFile(dossierFileId, dossierFile.getFileEntryId()); } jsonObject.put("deleted", Boolean.TRUE); } catch (Exception e) { jsonObject.put("deleted", Boolean.FALSE); _log.error(e); } finally { PortletUtil.writeJSON(actionRequest, actionResponse, jsonObject); } } /** * @param actionRequest * @param actionResponse * @throws IOException */ public void removeIndividualGroup( ActionRequest actionRequest, ActionResponse actionResponse) throws IOException { long fileGroupId = ParamUtil.getLong(actionRequest, DossierDisplayTerms.FILE_GROUP_ID); long dossierId = ParamUtil.getLong(actionRequest, DossierDisplayTerms.DOSSIER_ID); long dossierPartId = ParamUtil.getLong(actionRequest, DossierFileDisplayTerms.DOSSIER_PART_ID); JSONObject jsonObject = null; try { if (fileGroupId > 0) { jsonObject = JSONFactoryUtil.createJSONObject(); FileGroupLocalServiceUtil.deleteFileGroup(dossierId, dossierPartId, fileGroupId); jsonObject.put("deleted", Boolean.TRUE); } } catch (Exception e) { jsonObject.put("deleted", Boolean.FALSE); _log.error(e); } finally { PortletUtil.writeJSON(actionRequest, actionResponse, jsonObject); } } /** * @param renderRequest * @param renderResponse * @throws PortletException * @throws IOException */ @Override public void render( RenderRequest renderRequest, RenderResponse renderResponse) throws PortletException, IOException { ThemeDisplay themeDisplay = (ThemeDisplay) renderRequest.getAttribute(WebKeys.THEME_DISPLAY); Dossier dossier = (Dossier) renderRequest.getAttribute(WebKeys.DOSSIER_ENTRY); DictCollection dictCollection = null; long dossierId = ParamUtil.getLong(renderRequest, DossierDisplayTerms.DOSSIER_ID); long dossierFileId = ParamUtil.getLong(renderRequest, DossierFileDisplayTerms.DOSSIER_FILE_ID); long dossierPartId = ParamUtil.getLong(renderRequest, DossierFileDisplayTerms.DOSSIER_PART_ID); long serviceConfigId = ParamUtil.getLong(renderRequest, DossierDisplayTerms.SERVICE_CONFIG_ID); HttpServletRequest request = PortalUtil.getHttpServletRequest(renderRequest); HttpSession session = request.getSession(); String accountType = GetterUtil.getString(session.getAttribute(WebKeys.ACCOUNT_TYPE)); String selectedItems = StringPool.BLANK; try { if (dossierId > 0) { dossier = DossierLocalServiceUtil.getDossier(dossierId); } dictCollection = DictCollectionLocalServiceUtil.getDictCollection( themeDisplay.getScopeGroupId(), PortletPropsValues.DATAMGT_MASTERDATA_ADMINISTRATIVE_REGION); if (dossier != null) { renderRequest.setAttribute(WebKeys.DOSSIER_ENTRY, dossier); serviceConfigId = dossier.getServiceConfigId(); selectedItems = getSelectedItems(dossier, dictCollection); } else { if (accountType.equals(PortletPropsValues.USERMGT_USERGROUP_NAME_CITIZEN)) { Citizen citizen = (Citizen) session.getAttribute(WebKeys.CITIZEN_ENTRY); selectedItems = getSelectedItems(citizen, dictCollection); } else if (accountType.equals(PortletPropsValues.USERMGT_USERGROUP_NAME_BUSINESS)) { Business business = (Business) session.getAttribute(WebKeys.BUSINESS_ENTRY); selectedItems = getSelectedItems(business, dictCollection); } } renderRequest.setAttribute(WebKeys.DICT_ITEM_SELECTED, selectedItems); if (serviceConfigId > 0) { ServiceConfig serviceConfig = ServiceConfigLocalServiceUtil.getServiceConfig(serviceConfigId); renderRequest.setAttribute(WebKeys.SERVICE_CONFIG_ENTRY, serviceConfig); if (serviceConfig != null && serviceConfig.getServiceInfoId() > 0) { ServiceInfo serviceInfo = ServiceInfoLocalServiceUtil.getServiceInfo(serviceConfig.getServiceInfoId()); renderRequest.setAttribute(WebKeys.SERVICE_INFO_ENTRY, serviceInfo); DossierTemplate dossierTemplate = DossierTemplateLocalServiceUtil.getDossierTemplate(serviceConfig.getDossierTemplateId()); renderRequest.setAttribute(WebKeys.DOSSIER_TEMPLATE_ENTRY, dossierTemplate); } } if (dossierFileId > 0) { DossierFile dossierFile = DossierFileLocalServiceUtil.getDossierFile(dossierFileId); renderRequest.setAttribute(WebKeys.DOSSIER_FILE_ENTRY, dossierFile); } if (dossierPartId > 0) { DossierPart dossierPart = DossierPartLocalServiceUtil.getDossierPart(dossierPartId); renderRequest.setAttribute(WebKeys.DOSSIER_PART_ENTRY, dossierPart); } } catch (Exception e) { _log.error(e); } super.render(renderRequest, renderResponse); } /** * @param actionRequest * @param actionResponse * @throws IOException */ public void updateDossier( ActionRequest actionRequest, ActionResponse actionResponse) throws IOException { ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY); HttpServletRequest request = PortalUtil.getHttpServletRequest(actionRequest); HttpSession session = request.getSession(); String accountType = GetterUtil.getString(session.getAttribute(WebKeys.ACCOUNT_TYPE)); Dossier dossier = null; long dossierId = ParamUtil.getLong(actionRequest, DossierDisplayTerms.DOSSIER_ID); long dossierTemplateId = ParamUtil.getLong(actionRequest, DossierDisplayTerms.DOSSIER_TEMPLATE_ID); long serviceInfoId = ParamUtil.getLong(actionRequest, DossierDisplayTerms.SERVICE_INFO_ID); long cityId = ParamUtil.getLong(actionRequest, DossierDisplayTerms.CITY_ID); long districtId = ParamUtil.getLong(actionRequest, DossierDisplayTerms.DISTRICT_ID); long wardId = ParamUtil.getLong(actionRequest, DossierDisplayTerms.WARD_ID); long serviceConfigId = ParamUtil.getLong(actionRequest, DossierDisplayTerms.SERVICE_CONFIG_ID); long govAgencyOrganizationId = ParamUtil.getLong(actionRequest, DossierDisplayTerms.GOVAGENCY_ORGANIZATION_ID); long ownerUserId = GetterUtil.getLong(session.getAttribute(WebKeys.ACCOUNT_OWNERUSERID)); long ownerOrganizationId = GetterUtil.getLong(session.getAttribute(WebKeys.ACCOUNT_OWNERORGANIZATIONID)); int serviceMode = ParamUtil.getInteger(actionRequest, DossierDisplayTerms.SERVICE_MODE); String serviceDomainIndex = ParamUtil.getString(actionRequest, DossierDisplayTerms.SERVICE_DOMAIN_INDEX); String govAgencyCode = ParamUtil.getString(actionRequest, DossierDisplayTerms.GOVAGENCY_CODE); String govAgencyName = ParamUtil.getString(actionRequest, DossierDisplayTerms.GOVAGENCY_NAME); String serviceAdministrationIndex = ParamUtil.getString(actionRequest, DossierDisplayTerms.SERVICE_ADMINISTRATION_INDEX); String templateFileNo = ParamUtil.getString(actionRequest, DossierDisplayTerms.TEMPLATE_FILE_NO); String subjectName = ParamUtil.getString(actionRequest, DossierDisplayTerms.SUBJECT_NAME); String subjectId = ParamUtil.getString(actionRequest, DossierDisplayTerms.SUBJECT_ID); String address = ParamUtil.getString(actionRequest, DossierDisplayTerms.ADDRESS); String contactName = ParamUtil.getString(actionRequest, DossierDisplayTerms.CONTACT_NAME); String contactTelNo = ParamUtil.getString(actionRequest, DossierDisplayTerms.CONTACT_TEL_NO); String contactEmail = ParamUtil.getString(actionRequest, DossierDisplayTerms.CONTACT_EMAIL); String note = ParamUtil.getString(actionRequest, DossierDisplayTerms.NOTE); String backURL = ParamUtil.getString(actionRequest, "backURL"); String redirectURL = ParamUtil.getString(actionRequest, "redirectURL"); String redirectPaymentURL = ParamUtil.getString(request, DossierDisplayTerms.REDIRECT_PAYMENT_URL); boolean isEditDossier = ParamUtil.getBoolean(request, "isEditDossier"); boolean update = false; try { ServiceContext serviceContext = ServiceContextFactory.getInstance(actionRequest); serviceContext.setAddGroupPermissions(true); serviceContext.setAddGuestPermissions(true); if (dossierId > 0) { dossier = DossierLocalServiceUtil.getDossier(dossierId); } String dossierDestinationFolder = StringPool.BLANK; if (accountType.equals(PortletPropsValues.USERMGT_USERGROUP_NAME_CITIZEN)) { dossierDestinationFolder = PortletUtil.getCitizenDossierDestinationFolder( serviceContext.getScopeGroupId(), ownerUserId); } else if (accountType.equals(PortletPropsValues.USERMGT_USERGROUP_NAME_BUSINESS)) { dossierDestinationFolder = PortletUtil.getBusinessDossierDestinationFolder( serviceContext.getScopeGroupId(), ownerOrganizationId); } if (dossier != null) { dossierDestinationFolder += StringPool.SLASH + dossier.getCounter(); } validateDossier(cityId, districtId, wardId, accountType, dossierDestinationFolder, subjectName, subjectId, address, contactName, contactTelNo, contactEmail); String cityCode = StringPool.BLANK; String districtCode = StringPool.BLANK; String wardCode = StringPool.BLANK; String cityName = StringPool.BLANK; String districtName = StringPool.BLANK; String wardName = StringPool.BLANK; DictItem city = DictItemLocalServiceUtil.getDictItem(cityId); DictItem district = DictItemLocalServiceUtil.getDictItem(districtId); DictItem ward = DictItemLocalServiceUtil.getDictItem(wardId); if (city != null) { cityCode = city.getItemCode(); cityName = city.getItemName(themeDisplay.getLocale()); } if (district != null) { districtCode = district.getItemCode(); districtName = district.getItemName(themeDisplay.getLocale()); } if (ward != null) { wardCode = ward.getItemCode(); wardName = ward.getItemName(themeDisplay.getLocale()); } DLFolder dossierFolder = DLFolderUtil.getTargetFolder(serviceContext.getUserId(), serviceContext.getScopeGroupId(), serviceContext.getScopeGroupId(), false, 0, dossierDestinationFolder, StringPool.BLANK, false, serviceContext); if (dossierId == 0) { dossier = DossierLocalServiceUtil.addDossier( serviceContext.getUserId(), ownerOrganizationId, dossierTemplateId, templateFileNo, serviceConfigId, serviceInfoId, serviceDomainIndex, govAgencyOrganizationId, govAgencyCode, govAgencyName, serviceMode, serviceAdministrationIndex, cityCode, cityName, districtCode, districtName, wardName, wardCode, subjectName, subjectId, address, contactName, contactTelNo, contactEmail, note, PortletConstants.DOSSIER_SOURCE_DIRECT, PortletConstants.DOSSIER_STATUS_NEW, dossierFolder.getFolderId(), redirectPaymentURL, serviceContext); } else { dossier = DossierLocalServiceUtil.updateDossier(dossierId, serviceContext.getUserId(), ownerOrganizationId, dossierTemplateId, templateFileNo, serviceConfigId, serviceInfoId, serviceDomainIndex, govAgencyOrganizationId, govAgencyCode, govAgencyName, serviceMode, serviceAdministrationIndex, cityCode, cityName, districtCode, districtName, wardName, wardCode, subjectName, subjectId, address, contactName, contactTelNo, contactEmail, note, dossierFolder.getFolderId(), serviceContext); } SessionMessages.add(actionRequest, MessageKeys.DOSSIER_UPDATE_SUCCESS); update = true; } catch (Exception e) { update = false; if (e instanceof EmptyDossierCityCodeException || e instanceof EmptyDossierDistrictCodeException || e instanceof EmptyDossierWardCodeException || e instanceof InvalidDossierObjectException || e instanceof CreateDossierFolderException || e instanceof EmptyDossierSubjectNameException || e instanceof OutOfLengthDossierSubjectNameException || e instanceof EmptyDossierSubjectIdException || e instanceof OutOfLengthDossierSubjectIdException || e instanceof EmptyDossierAddressException || e instanceof OutOfLengthDossierContactEmailException || e instanceof OutOfLengthDossierContactNameException || e instanceof OutOfLengthDossierContactTelNoException || e instanceof EmptyDossierContactNameException || e instanceof OutOfLengthDossierAddressException || e instanceof EmptyDossierFileException || e instanceof DuplicateFolderNameException) { SessionErrors.add(actionRequest, e.getClass()); } else { SessionErrors.add(actionRequest, MessageKeys.DOSSIER_SYSTEM_EXCEPTION_OCCURRED); } _log.error(e); } finally { /* * actionRequest .setAttribute(WebKeys.DOSSIER_ENTRY, dossier); */ if (update) { if (Validator.isNotNull(redirectURL)) { actionResponse.sendRedirect(redirectURL + "&_" + WebKeys.DOSSIER_MGT_PORTLET + "_dossierId=" + dossier.getDossierId()); } } else { actionResponse.setRenderParameter("backURL", backURL); actionResponse.setRenderParameter( DossierDisplayTerms.SERVICE_CONFIG_ID, String.valueOf(serviceConfigId)); actionResponse.setRenderParameter( DossierDisplayTerms.DOSSIER_ID, String.valueOf(dossier != null ? dossier.getDossierId() : 0)); actionResponse.setRenderParameter("isEditDossier", String.valueOf(isEditDossier)); actionResponse.setRenderParameter("mvcPath", "/html/portlets/dossiermgt/frontoffice/edit_dossier.jsp"); } } } /** * @param actionRequest * @param actionResponse */ public void updateDossierFile( ActionRequest actionRequest, ActionResponse actionResponse) { UploadPortletRequest uploadPortletRequest = PortalUtil.getUploadPortletRequest(actionRequest); long dossierFileId = ParamUtil.getLong(uploadPortletRequest, DossierFileDisplayTerms.DOSSIER_FILE_ID); long dossierPartId = ParamUtil.getLong(uploadPortletRequest, DossierFileDisplayTerms.DOSSIER_PART_ID); int index = ParamUtil.getInteger(uploadPortletRequest, DossierFileDisplayTerms.INDEX); String groupName = ParamUtil.getString(uploadPortletRequest, DossierFileDisplayTerms.GROUP_NAME); String templateFileNo = ParamUtil.getString(uploadPortletRequest, DossierDisplayTerms.TEMPLATE_FILE_NO); String fileName = ParamUtil.getString(uploadPortletRequest, DossierFileDisplayTerms.FILE_NAME); String redirectURL = ParamUtil.getString(uploadPortletRequest, "redirectURL"); String displayName = ParamUtil.getString(uploadPortletRequest, DossierFileDisplayTerms.DISPLAY_NAME); String dossierFileNo = ParamUtil.getString(uploadPortletRequest, DossierFileDisplayTerms.DOSSIER_FILE_NO); String dossierFileDate = ParamUtil.getString(uploadPortletRequest, DossierFileDisplayTerms.DOSSIER_FILE_DATE); String sourceFileName = uploadPortletRequest.getFileName(DossierFileDisplayTerms.DOSSIER_FILE_UPLOAD); sourceFileName = sourceFileName.concat(PortletConstants.TEMP_RANDOM_SUFFIX).concat( StringUtil.randomString()); String accountType = ParamUtil.getString(uploadPortletRequest, WebKeys.ACCOUNT_TYPE); InputStream inputStream = null; JSONObject jsonObject = JSONFactoryUtil.createJSONObject(); ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY); try { ServiceContext serviceContext = ServiceContextFactory.getInstance(uploadPortletRequest); DossierFile dossierFile = DossierFileLocalServiceUtil.getDossierFile(dossierFileId); long storeFolderId = 0; if (dossierFile != null) { long fileEntryId = dossierFile.getFileEntryId(); if (fileEntryId > 0) { FileEntry fileEntry = DLAppServiceUtil.getFileEntry(fileEntryId); storeFolderId = fileEntry.getFolderId(); } else { long dossierId = dossierFile.getDossierId(); Dossier dossier = DossierLocalServiceUtil.getDossier(dossierId); int dossierNo = dossier.getCounter(); String destination = StringPool.BLANK; if (accountType.equals(PortletPropsValues.USERMGT_USERGROUP_NAME_CITIZEN)) { destination = PortletUtil.getCitizenDossierDestinationFolder( dossier.getGroupId(), themeDisplay.getUserId()) + StringPool.SLASH + String.valueOf(dossierNo); } else if (accountType.equals(PortletPropsValues.USERMGT_USERGROUP_NAME_BUSINESS)) { destination = PortletUtil.getBusinessDossierDestinationFolder( dossier.getGroupId(), dossier.getOwnerOrganizationId()) + StringPool.SLASH + String.valueOf(dossierNo); } DLFolder storeFolder = DLFolderUtil.getTargetFolder(themeDisplay.getUserId(), themeDisplay.getScopeGroupId(), themeDisplay.getScopeGroupId(), false, 0, destination, StringPool.BLANK, false, serviceContext); storeFolderId = storeFolder.getFolderId(); } } inputStream = uploadPortletRequest.getFileAsStream(DossierFileDisplayTerms.DOSSIER_FILE_UPLOAD); long size = uploadPortletRequest.getSize(DossierFileDisplayTerms.DOSSIER_FILE_UPLOAD); String contentType = uploadPortletRequest.getContentType(DossierFileDisplayTerms.DOSSIER_FILE_UPLOAD); String mimeType = Validator.isNotNull(contentType) ? MimeTypesUtil.getContentType(contentType) : StringPool.BLANK; FileEntry fileEntry = DLAppServiceUtil.addFileEntry(serviceContext.getScopeGroupId(), storeFolderId, sourceFileName, mimeType, displayName, StringPool.BLANK, StringPool.BLANK, inputStream, size, serviceContext); jsonObject.put(DossierFileDisplayTerms.DOSSIER_FILE_NO, dossierFileNo); jsonObject.put(DossierFileDisplayTerms.DISPLAY_NAME, displayName); jsonObject.put(DossierFileDisplayTerms.DOSSIER_FILE_DATE, dossierFileDate); jsonObject.put(DossierFileDisplayTerms.FILE_TITLE, fileEntry.getTitle()); jsonObject.put(DossierFileDisplayTerms.MIME_TYPE, fileEntry.getMimeType()); jsonObject.put(DossierFileDisplayTerms.FILE_NAME, fileName); jsonObject.put(DossierFileDisplayTerms.FILE_ENTRY_ID, fileEntry.getFileEntryId()); jsonObject.put(DossierFileDisplayTerms.FOLDE_ID, fileEntry.getFolderId()); jsonObject.put(DossierFileDisplayTerms.DOSSIER_PART_ID, dossierPartId); jsonObject.put(DossierFileDisplayTerms.INDEX, index); jsonObject.put(DossierFileDisplayTerms.GROUP_NAME, groupName); jsonObject.put(DossierFileDisplayTerms.DOSSIER_FILE_ORIGINAL, PortletConstants.DOSSIER_FILE_ORIGINAL); jsonObject.put(DossierFileDisplayTerms.DOSSIER_FILE_TYPE, PortletConstants.DOSSIER_FILE_TYPE_INPUT); jsonObject.put(DossierDisplayTerms.TEMPLATE_FILE_NO, templateFileNo); } catch (Exception e) { _log.error(e); SessionErrors.add(actionRequest, "upload-error"); } finally { StreamUtil.cleanUp(inputStream); HttpServletRequest request = PortalUtil.getHttpServletRequest(actionRequest); request.setAttribute(WebKeys.RESPONSE_UPLOAD_TEMP_DOSSIER_FILE, jsonObject); if (Validator.isNotNull(redirectURL)) { actionResponse.setRenderParameter("jspPage", "/html/portlets/dossiermgt/frontoffice/upload_dossier_file.jsp"); } } } /** * @param actionRequest * @param actionResponse * @throws IOException * @throws SystemException * @throws PortalException */ public void updateDossierStatus( ActionRequest actionRequest, ActionResponse actionResponse) throws IOException, PortalException, SystemException { long dossierId = ParamUtil.getLong(actionRequest, DossierDisplayTerms.DOSSIER_ID); long fileGroupId = ParamUtil.getLong(actionRequest, DossierFileDisplayTerms.DOSSIER_FILE_DATE); /* * long govAgencyOrganizationId = ParamUtil.getLong(actionRequest, * DossierDisplayTerms.GOVAGENCY_ORGANIZATION_ID); */ String dossierStatus = ParamUtil.getString(actionRequest, DossierDisplayTerms.DOSSIER_STATUS); String redirectURL = ParamUtil.getString(actionRequest, "redirectURL"); // Dossier dossier = DossierLocalServiceUtil.getDossier(dossierId); try { ServiceContext serviceContext = ServiceContextFactory.getInstance(actionRequest); UserActionMsg actionMsg = new UserActionMsg(); Message message = new Message(); switch (dossierStatus) { case PortletConstants.DOSSIER_STATUS_WAITING: actionMsg.setAction(WebKeys.ACTION_RESUBMIT_VALUE); actionMsg.setDossierId(dossierId); actionMsg.setFileGroupId(fileGroupId); actionMsg.setLocale(serviceContext.getLocale()); actionMsg.setUserId(serviceContext.getUserId()); actionMsg.setGroupId(serviceContext.getScopeGroupId()); ProcessOrder processOrder = ProcessOrderLocalServiceUtil.getProcessOrder(dossierId, fileGroupId); actionMsg.setProcessOrderId(processOrder.getProcessOrderId()); message.put("msgToEngine", actionMsg); break; case PortletConstants.DOSSIER_STATUS_NEW: validateSubmitDossier(dossierId); actionMsg.setAction(WebKeys.ACTION_SUBMIT_VALUE); actionMsg.setDossierId(dossierId); actionMsg.setFileGroupId(fileGroupId); actionMsg.setLocale(serviceContext.getLocale()); actionMsg.setUserId(serviceContext.getUserId()); actionMsg.setGroupId(serviceContext.getScopeGroupId()); message.put("msgToEngine", actionMsg); break; default: break; } /* * JMSContext context = * JMSMessageUtil.createProducer(serviceContext.getCompanyId(), * dossier.getGovAgencyCode(), true, "submitDossier"); * SubmitDossierMessage submitDossierMessage = new * SubmitDossierMessage(context); * submitDossierMessage.sendMessage(dossierId); */ MessageBusUtil.sendMessage("opencps/frontoffice/out/destination", message); } catch (Exception e) { if (e instanceof NoSuchDossierException || e instanceof NoSuchDossierTemplateException || e instanceof RequiredDossierPartException) { SessionErrors.add(actionRequest, e.getClass()); } else { SessionErrors.add(actionRequest, MessageKeys.DOSSIER_SYSTEM_EXCEPTION_OCCURRED); } _log.error(e); } finally { if (Validator.isNotNull(redirectURL)) { actionResponse.sendRedirect(redirectURL); } } } /** * @param actionRequest * @param actionResponse * @throws IOException */ public void updateDynamicFormData( ActionRequest actionRequest, ActionResponse actionResponse) throws IOException { AccountBean accountBean = AccountUtil.getAccountBean(actionRequest); DossierFile dossierFile = null; long dossierId = ParamUtil.getLong(actionRequest, DossierDisplayTerms.DOSSIER_ID); long dossierPartId = ParamUtil.getLong(actionRequest, DossierFileDisplayTerms.DOSSIER_PART_ID); long dossierFileId = ParamUtil.getLong(actionRequest, DossierFileDisplayTerms.DOSSIER_FILE_ID); long fileGroupId = ParamUtil.getLong(actionRequest, DossierDisplayTerms.FILE_GROUP_ID); long groupDossierPartId = ParamUtil.getLong(actionRequest, "groupDossierPartId"); long fileEntryId = 0; // Default value int dossierFileMark = PortletConstants.DOSSIER_FILE_MARK_UNKNOW; int dossierFileType = PortletConstants.DOSSIER_FILE_TYPE_INPUT; int syncStatus = PortletConstants.DOSSIER_FILE_SYNC_STATUS_NOSYNC; int original = PortletConstants.DOSSIER_FILE_ORIGINAL; String formData = ParamUtil.getString(actionRequest, DossierFileDisplayTerms.FORM_DATA); // Default value String dossierFileNo = StringPool.BLANK; String templateFileNo = StringPool.BLANK; String displayName = StringPool.BLANK; String groupName = ParamUtil.getString(actionRequest, DossierFileDisplayTerms.GROUP_NAME); Date dossierFileDate = null; try { validateDynamicFormData(dossierId, dossierPartId, accountBean); ServiceContext serviceContext = ServiceContextFactory.getInstance(actionRequest); DossierPart dossierPart = DossierPartLocalServiceUtil.getDossierPart(dossierPartId); if (Validator.isNotNull(dossierPart.getTemplateFileNo())) { templateFileNo = dossierPart.getTemplateFileNo(); } if (Validator.isNotNull(dossierPart.getPartName())) { displayName = dossierPart.getPartName(); } if (dossierFileId == 0) { dossierFile = DossierFileLocalServiceUtil.addDossierFile( serviceContext.getUserId(), dossierId, dossierPartId, templateFileNo, groupName, fileGroupId, groupDossierPartId, accountBean.getOwnerUserId(), accountBean.getOwnerOrganizationId(), displayName, formData, fileEntryId, dossierFileMark, dossierFileType, dossierFileNo, dossierFileDate, original, syncStatus, serviceContext); } else { dossierFile = DossierFileLocalServiceUtil.getDossierFile(dossierFileId); dossierFileMark = dossierFile.getDossierFileMark(); dossierFileType = dossierFile.getDossierFileType(); syncStatus = dossierFile.getSyncStatus(); original = dossierFile.getOriginal(); dossierFileNo = Validator.isNotNull(dossierFile.getDossierFileNo()) ? dossierFile.getDossierFileNo() : StringPool.BLANK; templateFileNo = Validator.isNotNull(dossierFile.getTemplateFileNo()) ? dossierFile.getTemplateFileNo() : StringPool.BLANK; displayName = Validator.isNotNull(dossierFile.getDisplayName()) ? dossierFile.getDisplayName() : StringPool.BLANK; dossierFile = DossierFileLocalServiceUtil.updateDossierFile( dossierFileId, serviceContext.getUserId(), dossierId, dossierPartId, templateFileNo, fileGroupId, accountBean.getOwnerUserId(), accountBean.getOwnerOrganizationId(), displayName, formData, fileEntryId, dossierFileMark, dossierFileType, dossierFileNo, dossierFileDate, original, syncStatus, serviceContext); } } catch (Exception e) { if (e instanceof NoSuchDossierException) { SessionErrors.add(actionRequest, NoSuchDossierException.class); } else if (e instanceof NoSuchDossierPartException) { SessionErrors.add(actionRequest, NoSuchDossierPartException.class); } else if (e instanceof NoSuchAccountException) { SessionErrors.add(actionRequest, NoSuchAccountException.class); } else if (e instanceof NoSuchAccountTypeException) { SessionErrors.add(actionRequest, NoSuchAccountTypeException.class); } else if (e instanceof NoSuchAccountFolderException) { SessionErrors.add(actionRequest, NoSuchAccountFolderException.class); } else if (e instanceof NoSuchAccountOwnUserIdException) { SessionErrors.add(actionRequest, NoSuchAccountOwnUserIdException.class); } else if (e instanceof NoSuchAccountOwnOrgIdException) { SessionErrors.add(actionRequest, NoSuchAccountOwnOrgIdException.class); } else if (e instanceof PermissionDossierException) { SessionErrors.add(actionRequest, PermissionDossierException.class); } else { SessionErrors.add(actionRequest, PortalException.class); } _log.error(e); } finally { actionResponse.setRenderParameter("primaryKey", String.valueOf(dossierFile != null ? dossierFile.getDossierFileId() : 0)); actionResponse.setRenderParameter("content", "declaration-online"); actionResponse.setRenderParameter("jspPage", "/html/portlets/dossiermgt/frontoffice/modal_dialog.jsp"); } } /** * @param actionRequest * @param actionResponse * @throws IOException */ public void updateTempDynamicFormData( ActionRequest actionRequest, ActionResponse actionResponse) throws IOException { long dossierPartId = ParamUtil.getLong(actionRequest, DossierFileDisplayTerms.DOSSIER_PART_ID); int index = ParamUtil.getInteger(actionRequest, DossierFileDisplayTerms.INDEX); String formData = ParamUtil.getString(actionRequest, DossierFileDisplayTerms.FORM_DATA); HttpServletRequest request = PortalUtil.getHttpServletRequest(actionRequest); request.setAttribute(WebKeys.FORM_DATA + String.valueOf(dossierPartId) + StringPool.DASH + String.valueOf(index), formData); HttpSession session = request.getSession(); session.setAttribute(WebKeys.FORM_DATA + String.valueOf(dossierPartId) + StringPool.DASH + String.valueOf(index), formData); actionResponse.setRenderParameter("mvcPath", "/html/portlets/dossiermgt/frontoffice/dynamic_form.jsp"); } /** * @param accountBean * @throws NoSuchAccountTypeException * @throws NoSuchAccountException * @throws NoSuchAccountFolderException * @throws NoSuchAccountOwnUserIdException * @throws NoSuchAccountOwnOrgIdException */ private void validateAccount(AccountBean accountBean) throws NoSuchAccountTypeException, NoSuchAccountException, NoSuchAccountFolderException, NoSuchAccountOwnUserIdException, NoSuchAccountOwnOrgIdException { if (accountBean == null) { throw new NoSuchAccountException(); } else if (Validator.isNull(accountBean.getAccountType())) { throw new NoSuchAccountTypeException(); } else if (accountBean.getAccountFolder() == null) { throw new NoSuchAccountFolderException(); } else if (accountBean.isCitizen() && accountBean.getOwnerUserId() == 0) { throw new NoSuchAccountOwnUserIdException(); } else if (accountBean.isBusiness() && accountBean.getOwnerOrganizationId() == 0) { throw new NoSuchAccountOwnOrgIdException(); } } private void validateDynamicFormData( long dossierId, long dossierPartId, AccountBean accountBean) throws NoSuchAccountTypeException, NoSuchAccountException, NoSuchAccountFolderException, NoSuchAccountOwnUserIdException, NoSuchAccountOwnOrgIdException, NoSuchDossierException, NoSuchDossierPartException, PermissionDossierException { validateAccount(accountBean); if (dossierId <= 0) { throw new NoSuchDossierException(); } if (dossierPartId < 0) { throw new NoSuchDossierPartException(); } Dossier dossier = null; try { dossier = DossierLocalServiceUtil.getDossier(dossierId); } catch (Exception e) { throw new NoSuchDossierPartException(); } if (accountBean.isBusiness()) { if (dossier.getOwnerOrganizationId() != accountBean.getOwnerOrganizationId()) { throw new PermissionDossierException(); } } else if (accountBean.isCitizen()) { if (dossier.getUserId() != accountBean.getOwnerUserId()) { throw new PermissionDossierException(); } } try { DossierPartLocalServiceUtil.getDossierPart(dossierPartId); } catch (Exception e) { throw new NoSuchDossierPartException(); } } /** * @param dossierFileId * @param accountBean * @throws NoSuchAccountTypeException * @throws NoSuchAccountException * @throws NoSuchAccountFolderException * @throws NoSuchAccountOwnUserIdException * @throws NoSuchAccountOwnOrgIdException * @throws NoSuchDossierFileException */ private void validateCreateDynamicForm( long dossierFileId, AccountBean accountBean) throws NoSuchAccountTypeException, NoSuchAccountException, NoSuchAccountFolderException, NoSuchAccountOwnUserIdException, NoSuchAccountOwnOrgIdException, NoSuchDossierFileException { validateAccount(accountBean); if (dossierFileId < 0) { throw new NoSuchDossierFileException(); } DossierFile dossierFile = null; try { dossierFile = DossierFileLocalServiceUtil.getDossierFile(dossierFileId); } catch (Exception e) { // TODO: handle exception } if (dossierFile == null) { throw new NoSuchDossierFileException(); } } /** * @param dossierId * @param accountBean * @throws NoSuchAccountTypeException * @throws NoSuchAccountException * @throws NoSuchAccountFolderException * @throws NoSuchAccountOwnUserIdException * @throws NoSuchAccountOwnOrgIdException * @throws NoSuchDossierException */ private void validateDeleteDossier(long dossierId, AccountBean accountBean) throws NoSuchAccountTypeException, NoSuchAccountException, NoSuchAccountFolderException, NoSuchAccountOwnUserIdException, NoSuchAccountOwnOrgIdException, NoSuchDossierException { validateAccount(accountBean); if (dossierId <= 0) { throw new NoSuchDossierException(); } if (dossierId > 0) { Dossier dossier = null; try { dossier = DossierLocalServiceUtil.getDossier(dossierId); } catch (Exception e) { } if (dossier == null) { throw new NoSuchDossierException(); } } } /** * @param dossierId * @param partName * @throws NoSuchDossierException * @throws EmptyFileGroupException * @throws DuplicateFileGroupException */ private void valiadateFileGroup(long dossierId, String partName) throws NoSuchDossierException, EmptyFileGroupException, DuplicateFileGroupException { if (dossierId <= 0) { throw new NoSuchDossierException(); } else if (Validator.isNull(partName.trim())) { throw new EmptyFileGroupException(); } int count = 0; try { count = FileGroupLocalServiceUtil.countByD_DN(dossierId, partName.trim()); } catch (Exception e) { } if (count > 0) { throw new DuplicateFileGroupException(); } } private void validateAddAttachDossierFile( long dossierId, long dossierPartId, long dossierFileId, String displayName, long size, String sourceFileName, InputStream inputStream, AccountBean accountBean) throws NoSuchDossierException, NoSuchDossierPartException, NoSuchAccountException, NoSuchAccountTypeException, NoSuchAccountFolderException, NoSuchAccountOwnUserIdException, NoSuchAccountOwnOrgIdException, PermissionDossierException, FileSizeException { validateAccount(accountBean); if (dossierId <= 0) { throw new NoSuchDossierException(); } if (dossierPartId < 0) { throw new NoSuchDossierPartException(); } Dossier dossier = null; try { dossier = DossierLocalServiceUtil.getDossier(dossierId); } catch (Exception e) { throw new NoSuchDossierPartException(); } if (accountBean.isBusiness()) { if (dossier.getOwnerOrganizationId() != accountBean.getOwnerOrganizationId()) { throw new PermissionDossierException(); } } else if (accountBean.isCitizen()) { if (dossier.getUserId() != accountBean.getOwnerUserId()) { throw new PermissionDossierException(); } } try { DossierPartLocalServiceUtil.getDossierPart(dossierPartId); } catch (Exception e) { throw new NoSuchDossierPartException(); } if (size == 0) { throw new FileSizeException(); } else if (size > 300000000) { throw new FileSizeException(); } } private void validateCloneDossierFile( long dossierId, long dossierPartId, long dossierFileId, AccountBean accountBean) throws NoSuchDossierException, NoSuchDossierPartException, NoSuchAccountException, NoSuchAccountTypeException, NoSuchAccountFolderException, NoSuchAccountOwnUserIdException, NoSuchAccountOwnOrgIdException, PermissionDossierException, NoSuchDossierFileException, NoSuchFileEntryException { validateAccount(accountBean); if (dossierFileId <= 0) { throw new NoSuchDossierFileException(); } DossierFile dossierFile = null; try { dossierFile = DossierFileLocalServiceUtil.getDossierFile(dossierFileId); } catch (Exception e) { } if (dossierFile == null) { throw new NoSuchDossierFileException(); } if (dossierFile.getFileEntryId() <= 0) { throw new NoSuchFileEntryException(); } if (dossierId <= 0) { throw new NoSuchDossierException(); } if (dossierPartId < 0) { throw new NoSuchDossierPartException(); } Dossier dossier = null; try { dossier = DossierLocalServiceUtil.getDossier(dossierId); } catch (Exception e) { throw new NoSuchDossierPartException(); } if (accountBean.isBusiness()) { if (dossier.getOwnerOrganizationId() != accountBean.getOwnerOrganizationId()) { throw new PermissionDossierException(); } } else if (accountBean.isCitizen()) { if (dossier.getUserId() != accountBean.getOwnerUserId()) { throw new PermissionDossierException(); } } try { DossierPartLocalServiceUtil.getDossierPart(dossierPartId); } catch (Exception e) { throw new NoSuchDossierPartException(); } } /** * @param dossierId * @throws NoSuchDossierException * @throws NoSuchDossierTemplateException * @throws RequiredDossierPartException */ public void validateSubmitDossier(long dossierId) throws NoSuchDossierException, NoSuchDossierTemplateException, RequiredDossierPartException { if (dossierId <= 0) { throw new NoSuchDossierException(); } Dossier dossier = null; try { dossier = DossierLocalServiceUtil.getDossier(dossierId); } catch (Exception e) { } if (dossier == null) { throw new NoSuchDossierException(); } DossierTemplate dossierTemplate = null; try { dossierTemplate = DossierTemplateLocalServiceUtil.getDossierTemplate(dossier.getDossierTemplateId()); } catch (Exception e) { } if (dossierTemplate == null) { throw new NoSuchDossierTemplateException(); } List<DossierPart> dossierPartsLevel1 = new ArrayList<DossierPart>(); try { dossierPartsLevel1 = DossierPartLocalServiceUtil.getDossierPartsByT_P( dossierTemplate.getDossierTemplateId(), 0); } catch (Exception e) { } boolean requiredFlag = false; if (dossierPartsLevel1 != null) { for (DossierPart dossierPartLevel1 : dossierPartsLevel1) { List<DossierPart> dossierParts = DossierMgtUtil.getTreeDossierPart(dossierPartLevel1.getDossierpartId()); if (requiredFlag) { break; } for (DossierPart dossierPart : dossierParts) { if (dossierPart.getPartType() != PortletConstants.DOSSIER_PART_TYPE_RESULT && dossierPart.getPartType() != PortletConstants.DOSSIER_PART_TYPE_MULTIPLE_RESULT && dossierPart.getRequired()) { DossierFile dossierFile = null; try { dossierFile = DossierFileLocalServiceUtil.getDossierFileInUse( dossierId, dossierPart.getDossierpartId()); } catch (Exception e) { // TODO: handle exception } if (dossierFile == null) { requiredFlag = true; break; } } } } } if (requiredFlag) { throw new RequiredDossierPartException(); } } /** * @param cityId * @param districtId * @param wardId * @param accountType * @param dossierDestinationFolder * @param subjectName * @param subjectId * @param address * @param contactName * @param contactTelNo * @param contactEmail * @throws EmptyDossierCityCodeException * @throws EmptyDossierDistrictCodeException * @throws EmptyDossierWardCodeException * @throws InvalidDossierObjectException * @throws CreateDossierFolderException * @throws EmptyDossierSubjectNameException * @throws OutOfLengthDossierSubjectNameException * @throws EmptyDossierSubjectIdException * @throws OutOfLengthDossierSubjectIdException * @throws EmptyDossierAddressException * @throws OutOfLengthDossierContactEmailException * @throws OutOfLengthDossierContactNameException * @throws OutOfLengthDossierContactTelNoException * @throws EmptyDossierContactNameException * @throws OutOfLengthDossierAddressException * @throws InvalidDossierObjectException * @throws EmptyDossierFileException */ private void validateDossier( long cityId, long districtId, long wardId, String accountType, String dossierDestinationFolder, String subjectName, String subjectId, String address, String contactName, String contactTelNo, String contactEmail) throws EmptyDossierCityCodeException, EmptyDossierDistrictCodeException, EmptyDossierWardCodeException, InvalidDossierObjectException, CreateDossierFolderException, EmptyDossierSubjectNameException, OutOfLengthDossierSubjectNameException, EmptyDossierSubjectIdException, OutOfLengthDossierSubjectIdException, EmptyDossierAddressException, OutOfLengthDossierContactEmailException, OutOfLengthDossierContactNameException, OutOfLengthDossierContactTelNoException, EmptyDossierContactNameException, OutOfLengthDossierAddressException, InvalidDossierObjectException, EmptyDossierFileException { if (cityId <= 0) { throw new EmptyDossierCityCodeException(); } if (districtId <= 0) { throw new EmptyDossierDistrictCodeException(); } if (wardId <= 0) { throw new EmptyDossierWardCodeException(); } if (Validator.isNull(accountType)) { throw new InvalidDossierObjectException(); } if (Validator.isNull(dossierDestinationFolder)) { throw new CreateDossierFolderException(); } if (Validator.isNull(subjectName)) { throw new EmptyDossierSubjectNameException(); } if (subjectName.trim().length() > PortletPropsValues.DOSSIERMGT_DOSSIER_SUBJECT_NAME_LENGTH) { throw new OutOfLengthDossierSubjectNameException(); } if (Validator.isNull(subjectId)) { throw new EmptyDossierSubjectIdException(); } if (subjectId.trim().length() > PortletPropsValues.DOSSIERMGT_DOSSIER_SUBJECT_ID_LENGTH) { throw new OutOfLengthDossierSubjectIdException(); } if (Validator.isNull(address)) { throw new EmptyDossierAddressException(); } if (address.trim().length() > PortletPropsValues.DOSSIERMGT_DOSSIER_ADDRESS_LENGTH) { throw new OutOfLengthDossierAddressException(); } if (Validator.isNull(contactName)) { throw new EmptyDossierContactNameException(); } if (contactName.trim().length() > PortletPropsValues.DOSSIERMGT_DOSSIER_CONTACT_NAME_LENGTH) { throw new OutOfLengthDossierContactNameException(); } if (contactTelNo.trim().length() > PortletPropsValues.DOSSIERMGT_DOSSIER_CONTACT_TEL_NO_LENGTH) { throw new OutOfLengthDossierContactTelNoException(); } if (contactEmail.trim().length() > PortletPropsValues.DOSSIERMGT_DOSSIER_CONTACT_EMAIL_LENGTH) { throw new OutOfLengthDossierContactEmailException(); } } public void TestConsumer( ActionRequest actionRequest, ActionResponse actionResponse) { try { ServiceContext serviceContext = ServiceContextFactory.getInstance(actionRequest); JMSContext context = JMSMessageUtil.createConsumer(serviceContext.getCompanyId(), "111", true, "submitDossier"); SubmitDossierMessage submitDossierMessage = new SubmitDossierMessage(context); submitDossierMessage.receiveMessage(); } catch (Exception e) { _log.error(e); } } }
package com.axellience.vuegwt.processors.component.template.parser; import com.axellience.vuegwt.processors.component.template.parser.context.TemplateParserContext; import net.htmlparser.jericho.Element; import net.htmlparser.jericho.Logger; import javax.annotation.processing.Messager; import javax.tools.Diagnostic.Kind; public class TemplateParserLogger implements Logger { private final TemplateParserContext context; private final Messager messager; TemplateParserLogger(TemplateParserContext context, Messager messager) { this.context = context; this.messager = messager; } void error(String message, String expression) { error(message + " In expression: " + expression); } @Override public void error(String message) { // Filter errors about invalid first attribute character // The @ sign is not recognized as valid when its valid in Vue GWT // A cleaner way would be to fork Jericho to add the support for @ // But this filter should do for now. if (message.contains("contains attribute name with invalid first character")) return; printMessage(Kind.ERROR, message); } @Override public void warn(String message) { printMessage(Kind.WARNING, message); } @Override public void info(String message) { printMessage(Kind.NOTE, message); } @Override public void debug(String message) { printMessage(Kind.OTHER, message); } public void printMessage(Kind kind, String message) { messager.printMessage(kind, "In " + context.getTemplateName() + getElementDebugInfo(context.getCurrentElement()) + ": " + message, context.getComponentTypeElement()); } private String getElementDebugInfo(Element element) { if (element == null) return ""; return " at line " + element.getSource().getRow(element.getBegin()); } @Override public boolean isErrorEnabled() { return true; } @Override public boolean isWarnEnabled() { return true; } @Override public boolean isInfoEnabled() { return true; } @Override public boolean isDebugEnabled() { return true; } }
package edu.cs4460.msd.visual.main; import java.util.ArrayList; import processing.core.PConstants; import ch.randelshofer.gui.ProgressTracker; import ch.randelshofer.tree.circlemap.CirclemapModel; import ch.randelshofer.tree.circlemap.CirclemapTree; import controlP5.ControlEvent; import controlP5.ControlP5; import edu.cs4460.msd.backend.database.DatabaseConnection; import edu.cs4460.msd.backend.database.SongList; import edu.cs4460.msd.backend.genre.BaseFilteredGenreNodeInfo; import edu.cs4460.msd.backend.genre.GenreBase; import edu.cs4460.msd.backend.genre.GenreFilter; import edu.cs4460.msd.backend.genre.GenreNode; import edu.cs4460.msd.backend.genre.GenreNodeInfo; import edu.cs4460.msd.backend.maps_works.ContinentData; import edu.cs4460.msd.backend.utilities.FontHelper; import edu.cs4460.msd.backend.visual_abstract.AbstractVizBase; import edu.cs4460.msd.visual.circles.CircleVis; import edu.cs4460.msd.visual.controls.ControlVisBase; import edu.cs4460.msd.visual.controls.FilterVisBase; import edu.cs4460.msd.visual.maps.ArtistLocationMap; import edu.cs4460.msd.visual.maps.GenreLocationMap; /** * Base PApplet and controller for the visualization * @author tbowling3 * */ public class VisBase extends AbstractVizBase { public static final int WIDTH = 1200, HEIGHT = 800; public static final int DEFAULT_X = 25, DEFAULT_Y = 35, DEFAULT_WIDTH = 700, DEFAULT_HEIGHT = 500; public static final int SPACING = 25; private int backgroundColor; private ControlP5 cp5; private FontHelper fh; private DatabaseConnection dc; private SongList sl; private GenreBase gb; private ContinentData cd; private String mapTabName = "Map"; private String circleTabName = "Circles Only"; private String mapArtistsName = "Artist Map"; private int activeTabId; private int mapTabId = 1245, circleTabId = 32155, mapArtistsId = 43254; private GenreLocationMap glm; private ArtistLocationMap alm; private FilterVisBase fvb; private ControlVisBase cvb; private CircleVis cv; private GenreFilter filter; private static final long serialVersionUID = -4819693994329829461L; public void setup() { size(WIDTH, HEIGHT); cp5 = new ControlP5(this); fh = new FontHelper(this); dc = new DatabaseConnection(); cd = new ContinentData(); boolean connectToDB = true; if(connectToDB) { buildGenreBase(); buildCVTree(); buildGMTree(); } int mapX = DEFAULT_X, mapY = DEFAULT_Y, mapWidth = DEFAULT_HEIGHT, mapHeight = DEFAULT_HEIGHT; int filterX = DEFAULT_X + DEFAULT_WIDTH + SPACING, filterY = 10, filterWidth = 400, filterHeight = 500; int controlX = DEFAULT_X, controlY = DEFAULT_HEIGHT + SPACING, controlWidth = DEFAULT_WIDTH, controlHeight = 100; backgroundColor = color(164); // Change Font cp5.setFont(fh.tabFont()); // Create Tabs cp5.getTab("default") .activateEvent(true) .setLabel(circleTabName) .setId(circleTabId) .setColorBackground(backgroundColor) .setHeight(25) ; cp5.addTab(mapTabName) .setColorBackground(backgroundColor) .setHeight(25) ; cp5.getTab(mapTabName) .activateEvent(true) .setId(mapTabId) ; cp5.addTab(mapArtistsName) .setColorBackground(backgroundColor) .setHeight(25) ; cp5.getTab(mapArtistsName) .activateEvent(true) .setId(mapArtistsId) ; activeTabId = circleTabId; fvb = new FilterVisBase(this, filterX, filterY, filterWidth, filterHeight); alm = new ArtistLocationMap(this, sl, mapX, mapY, mapWidth, mapHeight); cvb = new ControlVisBase(this, controlX, controlY, controlWidth, controlHeight); filter = new GenreFilter(); // yearsFiltered = false; // countriesFiltered = false; // continentsFiltered = false; // continents = new ArrayList<String>(); // countries = new ArrayList<String>(); } public void draw() { background(backgroundColor); fvb.draw(); cvb.draw(); if(activeTabId == mapTabId) { glm.draw(); } else if(activeTabId == circleTabId){ cv.draw(filter); noStroke(); fill(backgroundColor); rectMode(PConstants.CORNER); rect(0,0, WIDTH, DEFAULT_Y); rect(0, DEFAULT_Y, DEFAULT_X, HEIGHT); rect(DEFAULT_X + DEFAULT_WIDTH, DEFAULT_Y, WIDTH, HEIGHT); rect(0, DEFAULT_Y + DEFAULT_HEIGHT, WIDTH, HEIGHT); } else if(activeTabId == mapArtistsId) { alm.draw(); } } public void mouseMoved() { if(activeTabId == circleTabId) { cv.mouseMoved(mouseX, mouseY); } else if(activeTabId == mapArtistsId) { alm.mouseMoved(mouseX, mouseY); } } public void mouseClicked() { if(activeTabId == circleTabId) { cv.mouseClicked(mouseX, mouseY); } } public void filterYears(int lower, int upper) { if(lower == 1926 && upper == 2010){ filter.setYearsFiltered(false); } else { filter.setYearsFiltered(true); filter.setMinYear(lower); filter.setMaxYear(upper); } filterChanged(); } public void filterCountries(boolean[] checked) { String[] allCountries = cd.findCountriesISOInDatabase(); filter.getCountries().clear(); for(int i = 0; i < checked.length; i++){ if(checked[i]){ filter.getCountries().add(allCountries[i]); } } if(filter.getCountries().size() > 0){ filter.setCountriesFiltered(true); } else { filter.setCountriesFiltered(false); } filterChanged(); } public void filterContinents(boolean[] checked) { if (activeTabId != mapTabId) { String[] allCONTINENTS = ContinentData.getContinents(); filter.getContinents().clear(); for(int i = 0; i < checked.length; i++){ if(checked[i]){ filter.getContinents().add(allCONTINENTS[i]); } } if (filter.getContinents().size() >0){ filter.setContinentsFiltered(true); } else{ filter.setContinentsFiltered(false); } filterChanged(); } else { for (int i = 0; i < 6; i++) { if (checked[i]) glm.flipDrawContinent(i); } } } public void filterSongs(int count) { buildGenreBase(count); } private void filterChanged() { cv.filterChanged(filter); alm.updateFilter(filter); glm.updateFilter(filter); } public void controlEvent(ControlEvent theEvent) { if(theEvent.isTab()) { activeTabId = theEvent.getTab().getId(); } else { fvb.controlEvent(theEvent); cvb.controlEvent(theEvent); } } private void buildGenreBase() { buildGenreBase(-1); } private void buildGenreBase(int limit) { if(limit < 1) { dc.setQueryLimit(""); } else { dc.setQueryLimit(limit); } sl = dc.getArtistTerms(); gb = new GenreBase(sl, 10); } private void buildCVTree() { GenreNode root = gb.getNodeTree(); ProgressTracker p = new ProgressTracker("",""); CirclemapModel model = new CirclemapModel(root, new GenreNodeInfo(), p); cv = model.getView(); cv.setDimensions(DEFAULT_X, DEFAULT_Y, DEFAULT_WIDTH, DEFAULT_HEIGHT); cv.setP(this); } private void buildGMTree() { GenreNode root = gb.getNodeTree(); ProgressTracker p = new ProgressTracker("", ""); CirclemapModel[] models = new CirclemapModel[6]; CirclemapTree[] trees = new CirclemapTree[6]; String[] continents = {"Africa", "Asia", "Europe", "North America", "Oceania", "South America"}; for (int i = 0; i < 6; i++) { GenreFilter baseFilter = new GenreFilter(); baseFilter.setContinentsFiltered(true); ArrayList<String> continent = new ArrayList<String>(); continent.add(continents[i]); baseFilter.setContinents(continent); models[i] = new CirclemapModel(root, new BaseFilteredGenreNodeInfo(baseFilter), p); trees[i] = models[i].getTree(); } int mapX = DEFAULT_X, mapY = DEFAULT_Y, mapWidth = DEFAULT_HEIGHT, mapHeight = DEFAULT_HEIGHT; glm = new GenreLocationMap(this, mapX, mapY, mapWidth, mapHeight, trees); } }
package org.cache2k.impl; import org.cache2k.CacheEntry; import org.cache2k.impl.operation.ExaminationEntry; import org.cache2k.storage.StorageEntry; /** * The cache entry. This is a combined hashtable entry with hashCode and * and collision list (other field) and it contains a double linked list * (next and previous) for the eviction algorithm. * * @author Jens Wilke */ @SuppressWarnings("unchecked") public class Entry<K, T> implements CacheEntry<K,T>, StorageEntry, ExaminationEntry<K, T> { static final int FETCHED_STATE = 16; static final int REFRESH_STATE = FETCHED_STATE + 1; static final int REPUT_STATE = FETCHED_STATE + 3; static final int FETCH_IN_PROGRESS_VALID = FETCHED_STATE + 4; /** * Cache.remove() operation received. Needs to be send to storage. */ static final int REMOVE_PENDING = 11; /** * Entry was created for locking purposes of an atomic operation. */ static final int ATOMIC_OP_NON_VALID = 10; static final int LOADED_NON_VALID_AND_PUT = 9; static final int FETCH_ABORT = 8; static final int FETCH_IN_PROGRESS_NON_VALID = 7; /** Storage was checked, no data available */ static final int LOADED_NON_VALID_AND_FETCH = 6; /** Storage was checked, no data available */ static final int READ_NON_VALID = 5; static final int EXPIRED_STATE = 4; /** Logically the same as immediately expired */ static final int FETCH_NEXT_TIME_STATE = 3; static private final int GONE_STATE = 2; static private final int FETCH_IN_PROGRESS_VIRGIN = 1; static final int VIRGIN_STATE = 0; static final int EXPIRY_TIME_MIN = 32; static private final StaleMarker STALE_MARKER_KEY = new StaleMarker(); final static InitialValueInEntryNeverReturned INITIAL_VALUE = new InitialValueInEntryNeverReturned(); public BaseCache.MyTimerTask task; /** * Hit counter for clock pro. Not used by every eviction algorithm. */ long hitCnt; /** * Time the entry was last updated by put or by fetching it from the cache source. * The time is the time in millis times 2. A set bit 1 means the entry is fetched from * the storage and not modified since then. */ private volatile long fetchedTime; /** * Contains the next time a refresh has to occur, or if no background refresh is configured, when the entry * is expired. Low values have a special meaning, see defined constants. * Negative values means that we need to check against the wall clock. * * Whenever processing is done on the entry, e.g. a refresh or update, the field is used to reflect * the processing state. This means that, during processing the expiry time is lost. This has no negative * impact on the visibility of the entry. For example if the entry is refreshed, it is expired, but since * background refresh is enabled, the expired entry is still returned by the cache. */ public volatile long nextRefreshTime; public K key; public volatile T value = (T) INITIAL_VALUE; /** * Hash implementation: the calculated, modified hash code, retrieved from the key when the entry is * inserted in the cache * * @see BaseCache#modifiedHash(int) */ public int hashCode; /** * Hash implementation: Link to another entry in the same hash table slot when the hash code collides. */ public Entry<K, T> another; /** Lru list: pointer to next element or list head */ public Entry next; /** Lru list: pointer to previous element or list head */ public Entry prev; private static final int MODIFICATION_TIME_BITS = 44; private static final long MODIFICATION_TIME_BASE = 0; private static final int MODIFICATION_TIME_SHIFT = 1; /** including dirty */ private static final long MODIFICATION_TIME_MASK = (1L << MODIFICATION_TIME_BITS) - 1; private static final int DIRTY = 0; private static final int CLEAN = 1; /** * Set modification time and marks entry. We use {@value MODIFICATION_TIME_BITS} bit to store * the time, including 1 bit for the dirty state. Since everything is stored in a long field, * we have bits left that we can use for other purposes. * * @param _clean 1 means not modified */ void setLastModification(long t, int _clean) { fetchedTime = fetchedTime & ~MODIFICATION_TIME_MASK | ((((t - MODIFICATION_TIME_BASE) << MODIFICATION_TIME_SHIFT) + _clean) & MODIFICATION_TIME_MASK); } /** * Set modification time and marks entry as dirty. */ public void setLastModification(long t) { setLastModification(t, DIRTY); } /** * Memory entry needs to be send to the storage. */ public boolean isDirty() { return (fetchedTime & MODIFICATION_TIME_SHIFT) == DIRTY; } public void setLastModificationFromStorage(long t) { setLastModification(t, CLEAN); } public void resetDirty() { fetchedTime = fetchedTime | 1; } @Override public long getLastModification() { return (fetchedTime & MODIFICATION_TIME_MASK) >> MODIFICATION_TIME_SHIFT; } /** * Different possible processing states. The code only uses fetch now, rest is preparation. */ enum ProcessingState { DONE, READ, READ_COMPLETE, MUTATE, LOAD, LOAD_COMPLETE, FETCH, REFRESH, EXPIRY, EXPIRY_COMPLETE, WRITE, WRITE_COMPLETE, STORE, STORE_COMPLETE, NOTIFY, PINNED, EVICT, LAST } private static final int PS_BITS = 5; private static final int PS_MASK = (1 << PS_BITS) - 1; private static final int PS_POS = MODIFICATION_TIME_BITS; public ProcessingState getProcessingState() { return ProcessingState.values()[(int) ((fetchedTime >> PS_POS) & PS_MASK)]; } public void setProcessingState(ProcessingState ps) { fetchedTime = fetchedTime & ~((long) PS_MASK << PS_POS) | ((long) ps.ordinal() << PS_POS); } /** * Starts long operation on entry. Pins the entry in the cache. */ public long startFetch() { setProcessingState(ProcessingState.FETCH); return nextRefreshTime; } public void startFetch(ProcessingState ps) { setProcessingState(ps); } public void nextProcessingStep(ProcessingState ps) { setProcessingState(ps); } public void processingDone() { setProcessingState(ProcessingState.DONE); } /** * If fetch is not stopped, abort and make entry invalid. * This is a safety measure, since during entry processing an * exceptions may happen. This can happen regularly e.g. if storage * is set to read only and a cache put is made. */ public void ensureFetchAbort(boolean _finished) { if (_finished) { return; } synchronized (Entry.this) { if (isFetchInProgress()) { notifyAll(); } } } public void ensureFetchAbort(boolean _finished, long _previousNextRefreshTime) { if (_finished) { return; } synchronized (Entry.this) { if (isVirgin()) { nextRefreshTime = FETCH_ABORT; } if (isFetchInProgress()) { setProcessingState(ProcessingState.DONE); notifyAll(); } } } /** * Entry is not allowed to be evicted */ public boolean isPinned() { return isFetchInProgress(); } public boolean isFetchInProgress() { return getProcessingState() != ProcessingState.DONE; } public void waitForFetch() { if (!isFetchInProgress()) { return; } boolean _interrupt = false; do { try { wait(); } catch (InterruptedException ignore) { _interrupt = true; } } while (isFetchInProgress()); if (_interrupt) { Thread.currentThread().interrupt(); } } public void setGettingRefresh() { setProcessingState(ProcessingState.REFRESH); } public boolean isGettingRefresh() { return getProcessingState() == ProcessingState.REFRESH; } /** Reset next as a marker for {@link #isRemovedFromReplacementList()} */ public final void removedFromList() { next = null; } /** Check that this entry is removed from the list, may be used in assertions. */ public boolean isRemovedFromReplacementList() { return isStale () || next == null; } public Entry shortCircuit() { return next = prev = this; } public final boolean isVirgin() { return nextRefreshTime == VIRGIN_STATE || nextRefreshTime == FETCH_IN_PROGRESS_VIRGIN; } public final boolean isFetchNextTimeState() { return nextRefreshTime == FETCH_NEXT_TIME_STATE; } /** * The entry value was fetched and is valid, which means it can be * returned by the cache. If a valid entry gets removed from the * cache the data is still valid. This is because a concurrent get needs to * return the data. There is also the chance that an entry is removed by eviction, * or is never inserted to the cache, before the get returns it. * * <p/>Even if this is true, the data may be expired. Use hasFreshData() to * make sure to get not expired data. */ public final boolean isDataValidState() { return isDataValidState(nextRefreshTime); } public static boolean isDataValidState(long _nextRefreshTime) { return _nextRefreshTime >= FETCHED_STATE || _nextRefreshTime < 0; } public boolean hasData() { return !isVirgin() && !isGone(); } /** * Returns true if the entry has a valid value and is fresh / not expired. */ public final boolean hasFreshData() { if (nextRefreshTime >= FETCHED_STATE) { return true; } if (needsTimeCheck()) { long now = System.currentTimeMillis(); return now < -nextRefreshTime; } return false; } /** * Same as {@link #hasFreshData}, optimization if current time is known. */ public final boolean hasFreshData(long now) { if (nextRefreshTime >= FETCHED_STATE) { return true; } if (needsTimeCheck()) { return now < -nextRefreshTime; } return false; } public final boolean hasFreshData(long now, long _nextRefreshTime) { if (_nextRefreshTime >= FETCHED_STATE) { return true; } if (_nextRefreshTime < 0) { return now < -_nextRefreshTime; } return false; } public boolean isLoadedNonValid() { return nextRefreshTime == READ_NON_VALID; } public void setLoadedNonValidAndFetch() { nextRefreshTime = LOADED_NON_VALID_AND_FETCH; } public boolean isLoadedNonValidAndFetch() { return nextRefreshTime == LOADED_NON_VALID_AND_FETCH; } /** Entry is kept in the cache but has expired */ public void setExpiredState() { nextRefreshTime = EXPIRED_STATE; } /** * The entry expired, but still in the cache. This may happen if * {@link BaseCache#hasKeepAfterExpired()} is true. */ public boolean isExpiredState() { return isExpiredState(nextRefreshTime); } public static boolean isExpiredState(long _nextRefreshTime) { return _nextRefreshTime == EXPIRED_STATE; } public void setGone() { nextRefreshTime = GONE_STATE; } /** * The entry is not present in the heap any more and was evicted, expired or removed. * Usually we should never grab an entry from the hash table that has this state, but, * after the synchronize goes through somebody else might have evicted it. */ public boolean isGone() { return nextRefreshTime == GONE_STATE; } public boolean isBeeingReput() { return nextRefreshTime == REPUT_STATE; } public boolean needsTimeCheck() { return nextRefreshTime < 0; } public boolean isStale() { return STALE_MARKER_KEY == key; } public void setStale() { key = (K) STALE_MARKER_KEY; } public boolean hasException() { return value instanceof ExceptionWrapper; } public Throwable getException() { if (value instanceof ExceptionWrapper) { return ((ExceptionWrapper) value).getException(); } return null; } public void setException(Throwable exception) { value = (T) new ExceptionWrapper(exception); } public boolean equalsValue(T v) { if (value == null) { return v == value; } return value.equals(v); } public T getValue() { if (value instanceof ExceptionWrapper) { return null; } return value; } @Override public K getKey() { return key; } /** * Expiry time or 0. */ public long getValueExpiryTime() { if (nextRefreshTime < 0) { return -nextRefreshTime; } else if (nextRefreshTime > EXPIRY_TIME_MIN) { return nextRefreshTime; } return 0; } /** * Used for the storage interface. * * @see org.cache2k.storage.StorageEntry */ @Override public T getValueOrException() { return value; } /** * Used for the storage interface. * * @see org.cache2k.storage.StorageEntry */ @Override public long getCreatedOrUpdated() { return getLastModification(); } /** * Used for the storage interface. * * @see org.cache2k.storage.StorageEntry * @deprectated Always returns 0, only to fulfill the {@link org.cache2k.storage.StorageEntry} interface */ @Override public long getEntryExpiryTime() { return 0; } @Override public String toString() { return "Entry{" + "key=" + key + ", lock=" + getProcessingState() + ", createdOrUpdate=" + getCreatedOrUpdated() + ", nextRefreshTime=" + nextRefreshTime + ", valueExpiryTime=" + getValueExpiryTime() + ", entryExpiryTime=" + getEntryExpiryTime() + ", mHC=" + hashCode + ", value=" + value + ", dirty=" + isDirty() + '}'; } /** * Cache entries always have the object identity as equals method. */ @Override public final boolean equals(Object obj) { return this == obj; } /* check entry states */ static { Entry e = new Entry(); e.nextRefreshTime = FETCHED_STATE; synchronized (e) { e.setGettingRefresh(); e = new Entry(); e.setLoadedNonValidAndFetch(); e.setExpiredState(); } } static class InitialValueInEntryNeverReturned extends Object { } static class StaleMarker { @Override public boolean equals(Object o) { return false; } } }
package com.googlecode.jslint4java.cli; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Field; import java.nio.charset.Charset; import java.util.List; import com.beust.jcommander.JCommander; import com.beust.jcommander.ParameterDescription; import com.beust.jcommander.ParameterException; import com.googlecode.jslint4java.Issue; import com.googlecode.jslint4java.JSLint; import com.googlecode.jslint4java.JSLintBuilder; import com.googlecode.jslint4java.JSLintResult; import com.googlecode.jslint4java.Option; import com.googlecode.jslint4java.UnicodeBomInputStream; import com.googlecode.jslint4java.formatter.CheckstyleXmlFormatter; import com.googlecode.jslint4java.formatter.JSLintResultFormatter; import com.googlecode.jslint4java.formatter.JSLintXmlFormatter; import com.googlecode.jslint4java.formatter.JUnitXmlFormatter; import com.googlecode.jslint4java.formatter.PlainFormatter; import com.googlecode.jslint4java.formatter.ReportFormatter; /** * A command line interface to {@link JSLint}. * * @author dom */ class Main { /** * The default command line output. */ private static final class DefaultFormatter implements JSLintResultFormatter { public String format(JSLintResult result) { if (result.getIssues().isEmpty()) { return ""; } String nl = System.getProperty("line.separator"); StringBuilder sb = new StringBuilder(); for (Issue issue : result.getIssues()) { sb.append(PROGNAME); sb.append(':'); sb.append(issue.toString()); sb.append(nl); } // Strip trailing newline if present. The interface is wrong; we should return // a list of lines, not a String. sb.delete(sb.length() - nl.length(), sb.length()); return sb.toString(); } public String footer() { return null; } public String header() { return null; } } @SuppressWarnings("serial") private static class DieException extends RuntimeException { private final int code; public DieException(String message, int code) { super(message); this.code = code; } public int getCode() { return code; } } private static final String PROGNAME = "jslint"; /** * The main entry point. Try passing in "--help" for more details. * * @param args * One or more JavaScript files. * @throws IOException */ public static void main(String[] args) throws IOException { try { System.exit(new Main().run(args)); } catch (DieException e) { if (e.getMessage() != null) { System.err.println(PROGNAME + ": " + e.getMessage()); } System.exit(e.getCode()); } } // @VisibleForTesting. int run(String[] args) throws IOException { List<String> files = processOptions(args); if (formatter.header() != null) { info(formatter.header()); } for (String file : files) { lintFile(file); } if (formatter.footer() != null) { info(formatter.footer()); } return isErrored() ? 1 : 0; } private Charset encoding = Charset.defaultCharset(); private boolean errored = false; private JSLintResultFormatter formatter; private JSLint lint; private final JSLintBuilder lintBuilder = new JSLintBuilder(); private void die(String message) { throw new DieException(message, 1); } /** * Fetch the named {@link Option}, or null if there is no matching one. */ private Option getOption(String optName) { try { return Option.valueOf(optName); } catch (IllegalArgumentException e) { return null; } } private void info(String message) { System.out.println(message); } private boolean isErrored() { return errored; } private void lintFile(String file) throws IOException { BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(new UnicodeBomInputStream( new FileInputStream(file)).skipBOM(), encoding)); JSLintResult result = lint.lint(file, reader); String msg = formatter.format(result); if (msg.length() > 0) { info(msg); } if (!result.getIssues().isEmpty()) { setErrored(true); } } catch (FileNotFoundException e) { die(file + ": No such file or directory."); } finally { if (reader != null) { reader.close(); } } } private JSLint makeLint(Flags flags) { try { if (flags.timeout > 0) { lintBuilder.timeout(flags.timeout); } if (flags.jslint != null) { return lintBuilder.fromFile(new File(flags.jslint)); } else { return lintBuilder.fromDefault(); } } catch (IOException e) { die(e.getMessage()); } return null; } private List<String> processOptions(String[] args) { JSLintFlags jslintFlags = new JSLintFlags(); Flags flags = new Flags(); JCommander jc = new JCommander(new Object[] { flags , jslintFlags }); jc.setProgramName("jslint4java"); try { jc.parse(args); } catch (ParameterException e) { info(e.getMessage()); usage(jc); } if (flags.version) { version(); } if (flags.help) { usage(jc); } if (flags.encoding != null) { encoding = flags.encoding; } lint = makeLint(flags); setResultFormatter(flags.report); for (ParameterDescription pd : jc.getParameters()) { Field field = pd.getField(); // Is it declared on JSLintFlags? if (!field.getDeclaringClass().isAssignableFrom(JSLintFlags.class)) { continue; } try { // Need to get Option. Option o = getOption(field.getName()); // Need to get value. Object val = field.get(jslintFlags); if (val == null) { continue; } Class<?> type = field.getType(); if (type.isAssignableFrom(Boolean.class)) { lint.addOption(o); } // In theory, everything else should be a String for later parsing. else if (type.isAssignableFrom(String.class)) { lint.addOption(o, (String) val); } else { die("unknown type \"" + type + "\" (for " + field.getName() + ")"); } } catch (IllegalArgumentException e) { die(e.getMessage()); } catch (IllegalAccessException e) { die(e.getMessage()); } } if (flags.files.isEmpty()) { usage(jc); return null; // can never happen } else { return flags.files; } } private void setErrored(boolean errored) { this.errored = errored; } private void setResultFormatter(String reportType) { if (reportType == null || reportType.equals("")) { // The original CLI behaviour: one-per-line, with prefix. formatter = new DefaultFormatter(); } else if (reportType.equals("plain")) { formatter = new PlainFormatter(); } else if (reportType.equals("xml")) { formatter = new JSLintXmlFormatter(); } else if (reportType.equals("junit")) { formatter = new JUnitXmlFormatter(); } else if (reportType.equals("report")) { formatter = new ReportFormatter(); } else if (reportType.equals("checkstyle")) { formatter = new CheckstyleXmlFormatter(); } else { die("unknown report type '" + reportType + "'"); } } private void usage(JCommander jc) { jc.usage(); version(); } private void version() { // TODO: display jslint4java version as well. if (lint == null) { lint = lintBuilder.fromDefault(); } info("using jslint version " + lint.getEdition()); throw new DieException(null, 0); } }
package org.junit.gen5.engine; import static org.junit.gen5.api.Assertions.assertEquals; import java.util.Optional; import org.junit.gen5.api.Assertions; import org.junit.gen5.api.Nested; import org.junit.gen5.api.Test; import org.junit.gen5.engine.UniqueId.Segment; /** * Microtests for class {@link UniqueId} * * @since 5.0 */ class UniqueIdTests { static final String ENGINE_ID = "junit5"; @Nested class Creation { @Test void uniqueIdCanBeCreatedFromEngineId() { UniqueId uniqueId = UniqueId.forEngine(ENGINE_ID); assertEquals("[engine:junit5]", uniqueId.getUniqueString()); assertSegment(uniqueId.getSegments().get(0), "engine", "junit5"); } @Test void retrievingOptionalEngineId() { UniqueId uniqueIdWithEngine = UniqueId.forEngine(ENGINE_ID); assertEquals("junit5", uniqueIdWithEngine.getEngineId().get()); UniqueId uniqueIdWithoutEngine = UniqueId.root("root", "avalue"); assertEquals(Optional.empty(), uniqueIdWithoutEngine.getEngineId()); } @Test void uniqueIdCanBeCreatedFromTypeAndValue() { UniqueId uniqueId = UniqueId.root("aType", "aValue"); assertEquals("[aType:aValue]", uniqueId.getUniqueString()); assertSegment(uniqueId.getSegments().get(0), "aType", "aValue"); } @Test void rootSegmentCanBeRetrieved() { UniqueId uniqueId = UniqueId.root("aType", "aValue"); assertEquals(new Segment("aType", "aValue"), uniqueId.getRoot().get()); } @Test void appendingOneSegment() { UniqueId engineId = UniqueId.root("engine", ENGINE_ID); UniqueId classId = engineId.append("class", "org.junit.MyClass"); assertEquals(2, classId.getSegments().size()); assertSegment(classId.getSegments().get(0), "engine", ENGINE_ID); assertSegment(classId.getSegments().get(1), "class", "org.junit.MyClass"); } @Test void appendingSegmentLeavesOriginalUnchanged() { UniqueId uniqueId = UniqueId.root("engine", ENGINE_ID); uniqueId.append("class", "org.junit.MyClass"); assertEquals(1, uniqueId.getSegments().size()); assertSegment(uniqueId.getSegments().get(0), "engine", ENGINE_ID); } @Test void appendingSeveralSegments() { UniqueId engineId = UniqueId.root("engine", ENGINE_ID); UniqueId uniqueId = engineId.append("t1", "v1").append("t2", "v2").append("t3", "v3"); assertEquals(4, uniqueId.getSegments().size()); assertSegment(uniqueId.getSegments().get(0), "engine", ENGINE_ID); assertSegment(uniqueId.getSegments().get(1), "t1", "v1"); assertSegment(uniqueId.getSegments().get(2), "t2", "v2"); assertSegment(uniqueId.getSegments().get(3), "t3", "v3"); } } @Nested class ParsingAndFormatting { private final String uniqueIdString = "[engine:junit5]/[class:MyClass]/[method:myMethod]"; @Test void ensureDefaultUniqueIdFormatIsUsedForParsing() { UniqueId parsedDirectly = UniqueId.parse(uniqueIdString); UniqueId parsedViaFormat = UniqueIdFormat.getDefault().parse(uniqueIdString); assertEquals(parsedViaFormat, parsedDirectly); } @Test void ensureDefaultUniqueIdFormatIsUsedForFormatting() { UniqueId parsedDirectly = UniqueId.parse("[engine:junit5]/[class:MyClass]/[method:myMethod]"); assertEquals("[engine:junit5]/[class:MyClass]/[method:myMethod]", parsedDirectly.getUniqueString()); } } @Nested class EqualsContract { @Test void sameEnginesAreEqual() { UniqueId id1 = UniqueId.root("engine", "junit5"); UniqueId id2 = UniqueId.root("engine", "junit5"); Assertions.assertTrue(id1.equals(id2)); Assertions.assertTrue(id2.equals(id1)); assertEquals(id1.hashCode(), id2.hashCode()); } @Test void differentEnginesAreNotEqual() { UniqueId id1 = UniqueId.root("engine", "junit4"); UniqueId id2 = UniqueId.root("engine", "junit5"); Assertions.assertFalse(id1.equals(id2)); Assertions.assertFalse(id2.equals(id1)); } @Test void uniqueIdWithSameSegmentsAreEqual() { UniqueId id1 = UniqueId.root("engine", "junit5").append("t1", "v1").append("t2", "v2"); UniqueId id2 = UniqueId.root("engine", "junit5").append("t1", "v1").append("t2", "v2"); Assertions.assertTrue(id1.equals(id2)); Assertions.assertTrue(id2.equals(id1)); assertEquals(id1.hashCode(), id2.hashCode()); } @Test void differentOrderOfSegmentsAreNotEqual() { UniqueId id1 = UniqueId.root("engine", "junit5").append("t2", "v2").append("t1", "v1"); UniqueId id2 = UniqueId.root("engine", "junit5").append("t1", "v1").append("t2", "v2"); Assertions.assertFalse(id1.equals(id2)); Assertions.assertFalse(id2.equals(id1)); } @Test void additionalSegmentMakesItNotEqual() { UniqueId id1 = UniqueId.root("engine", "junit5").append("t1", "v1"); UniqueId id2 = id1.append("t2", "v2"); Assertions.assertFalse(id1.equals(id2)); Assertions.assertFalse(id2.equals(id1)); } } private void assertSegment(Segment segment, String expectedType, String expectedValue) { assertEquals(expectedType, segment.getType(), "segment type"); assertEquals(expectedValue, segment.getValue(), "segment value"); } }
package org.broadinstitute.sting.gatk.walkers.recalibration; import org.broadinstitute.sting.WalkerTest; import org.broadinstitute.sting.utils.exceptions.UserException; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.io.File; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; public class RecalibrationWalkersIntegrationTest extends WalkerTest { static HashMap<String, String> paramsFiles = new HashMap<String, String>(); static HashMap<String, String> paramsFilesSolidIndels = new HashMap<String, String>(); private static final class CCTest extends TestDataProvider { String file, md5; private CCTest(final String file, final String md5) { super(CCTest.class); this.file = file; this.md5 = md5; } public String toString() { return "CCTest: " + file; } } @DataProvider(name = "cctestdata") public Object[][] createCCTestData() { new CCTest( validationDataLocation + "NA12892.SLX.SRP000031.2009_06.selected.bam", "ab4940a16ab990181bd8368c76b23853" ); new CCTest( validationDataLocation + "NA19240.chr1.BFAST.SOLID.bam", "17d4b8001c982a70185e344929cf3941"); new CCTest( validationDataLocation + "NA12873.454.SRP000031.2009_06.chr1.10_20mb.bam", "36c0c467b6245c2c6c4e9c956443a154" ); new CCTest( validationDataLocation + "NA12878.1kg.p2.chr1_10mb_11_mb.allTechs.bam", "955a8fa2ddb2b04c406766ccd9ac45cc" ); return CCTest.getTests(CCTest.class); } @Test(dataProvider = "cctestdata") public void testCountCovariates1(CCTest test) { testCC(test, ""); } @Test(dataProvider = "cctestdata") public void testCountCovariates4(CCTest test) { testCC(test, " -nt 4"); } private final void testCC(CCTest test, String parallelism) { String bam = test.file; String md5 = test.md5; WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec( "-R " + b36KGReference + " -knownSites " + b36dbSNP129 + " -T CountCovariates" + " -I " + bam + ( bam.equals( validationDataLocation + "NA12878.1kg.p2.chr1_10mb_11_mb.allTechs.bam" ) ? " -L 1:10,800,000-10,810,000" : " -L 1:10,000,000-10,200,000" ) + " -cov ReadGroupCovariate" + " -cov QualityScoreCovariate" + " -cov CycleCovariate" + " -cov DinucCovariate" + " --solid_recal_mode SET_Q_ZERO" + " -recalFile %s" + parallelism, 1, // just one output file Arrays.asList(md5)); List<File> result = executeTest("testCountCovariates1" + parallelism, spec).getFirst(); paramsFiles.put(bam, result.get(0).getAbsolutePath()); } private static final class TRTest extends TestDataProvider { String file, md5; private TRTest(final String file, final String md5) { super(TRTest.class); this.file = file; this.md5 = md5; } public String toString() { return "TRTest: " + file; } } @DataProvider(name = "trtestdata") public Object[][] createTRTestData() { new TRTest( validationDataLocation + "NA12892.SLX.SRP000031.2009_06.selected.bam", "0b7123ae9f4155484b68e4a4f96c5504" ); new TRTest( validationDataLocation + "NA19240.chr1.BFAST.SOLID.bam", "d04cf1f6df486e45226ebfbf93a188a5"); new TRTest( validationDataLocation + "NA12873.454.SRP000031.2009_06.chr1.10_20mb.bam", "b2f4757bc47cf23bd9a09f756c250787" ); new TRTest( validationDataLocation + "NA12878.1kg.p2.chr1_10mb_11_mb.allTechs.bam", "502c7df4d4923c4d078b014bf78bed34" ); return TRTest.getTests(TRTest.class); } @Test(dataProvider = "trtestdata", dependsOnMethods = "testCountCovariates1") public void testTableRecalibrator1(TRTest test) { String bam = test.file; String md5 = test.md5; String paramsFile = paramsFiles.get(bam); System.out.printf("PARAMS FOR %s is %s%n", bam, paramsFile); if ( paramsFile != null ) { WalkerTestSpec spec = new WalkerTestSpec( "-R " + b36KGReference + " -T TableRecalibration" + " -I " + bam + ( bam.equals( validationDataLocation + "NA12878.1kg.p2.chr1_10mb_11_mb.allTechs.bam" ) ? " -L 1:10,800,000-10,810,000" : " -L 1:10,100,000-10,300,000" ) + " -o %s" + " --no_pg_tag" + " --solid_recal_mode SET_Q_ZERO" + " -recalFile " + paramsFile, 1, // just one output file Arrays.asList(md5)); executeTest("testTableRecalibrator1", spec); } else { throw new IllegalStateException("testTableRecalibrator1: paramsFile was null"); } } @Test public void testCountCovariatesUseOriginalQuals() { HashMap<String, String> e = new HashMap<String, String>(); e.put( validationDataLocation + "originalQuals.1kg.chr1.1-1K.bam", "0b88d0e8c97e83bdeee2064b6730abff"); for ( Map.Entry<String, String> entry : e.entrySet() ) { String bam = entry.getKey(); String md5 = entry.getValue(); WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec( "-R " + b36KGReference + " -T CountCovariates" + " -I " + bam + " -L 1:1-1,000" + " -standard" + " -OQ" + " -recalFile %s" + " -knownSites " + b36dbSNP129, 1, // just one output file Arrays.asList(md5)); executeTest("testCountCovariatesUseOriginalQuals", spec); } } @Test(dependsOnMethods = "testCountCovariates1") public void testTableRecalibratorMaxQ70() { HashMap<String, String> e = new HashMap<String, String>(); e.put( validationDataLocation + "NA12892.SLX.SRP000031.2009_06.selected.bam", "0b7123ae9f4155484b68e4a4f96c5504" ); for ( Map.Entry<String, String> entry : e.entrySet() ) { String bam = entry.getKey(); String md5 = entry.getValue(); String paramsFile = paramsFiles.get(bam); System.out.printf("PARAMS FOR %s is %s%n", bam, paramsFile); if ( paramsFile != null ) { WalkerTestSpec spec = new WalkerTestSpec( "-R " + b36KGReference + " -T TableRecalibration" + " -I " + bam + ( bam.equals( validationDataLocation + "NA12878.1kg.p2.chr1_10mb_11_mb.allTechs.bam" ) ? " -L 1:10,800,000-10,810,000" : " -L 1:10,100,000-10,300,000" ) + " -o %s" + " --no_pg_tag" + " -maxQ 70" + " --solid_recal_mode SET_Q_ZERO" + " -recalFile " + paramsFile, 1, // just one output file Arrays.asList(md5)); executeTest("testTableRecalibratorMaxQ70", spec); } else { throw new IllegalStateException("testTableRecalibratorMaxQ70: paramsFile was null"); } } } @Test public void testCountCovariatesSolidIndelsRemoveRefBias() { HashMap<String, String> e = new HashMap<String, String>(); e.put( validationDataLocation + "NA19240.chr1.BFAST.SOLID.bam", "8379f24cf5312587a1f92c162ecc220f" ); for ( Map.Entry<String, String> entry : e.entrySet() ) { String bam = entry.getKey(); String md5 = entry.getValue(); WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec( "-R " + b36KGReference + " -knownSites " + b36dbSNP129 + " -T CountCovariates" + " -I " + bam + " -standard" + " -U" + " -L 1:10,000,000-20,000,000" + " --solid_recal_mode REMOVE_REF_BIAS" + " -recalFile %s", 1, // just one output file Arrays.asList(md5)); List<File> result = executeTest("testCountCovariatesSolidIndelsRemoveRefBias", spec).getFirst(); paramsFilesSolidIndels.put(bam, result.get(0).getAbsolutePath()); } } @Test(dependsOnMethods = "testCountCovariatesSolidIndelsRemoveRefBias") public void testTableRecalibratorSolidIndelsRemoveRefBias() { HashMap<String, String> e = new HashMap<String, String>(); e.put( validationDataLocation + "NA19240.chr1.BFAST.SOLID.bam", "2ad4c17ac3ed380071137e4e53a398a5" ); for ( Map.Entry<String, String> entry : e.entrySet() ) { String bam = entry.getKey(); String md5 = entry.getValue(); String paramsFile = paramsFilesSolidIndels.get(bam); System.out.printf("PARAMS FOR %s is %s%n", bam, paramsFile); if ( paramsFile != null ) { WalkerTestSpec spec = new WalkerTestSpec( "-R " + b36KGReference + " -T TableRecalibration" + " -I " + bam + " -o %s" + " --no_pg_tag" + " -U" + " -L 1:10,000,000-20,000,000" + " --solid_recal_mode REMOVE_REF_BIAS" + " -recalFile " + paramsFile, 1, // just one output file Arrays.asList(md5)); executeTest("testTableRecalibratorSolidIndelsRemoveRefBias", spec); } else { throw new IllegalStateException("testTableRecalibratorSolidIndelsRemoveRefBias: paramsFile was null"); } } } @Test public void testCountCovariatesBED() { HashMap<String, String> e = new HashMap<String, String>(); e.put( validationDataLocation + "NA12892.SLX.SRP000031.2009_06.selected.bam", "7e973328751d233653530245d404a64d"); for ( Map.Entry<String, String> entry : e.entrySet() ) { String bam = entry.getKey(); String md5 = entry.getValue(); WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec( "-R " + b36KGReference + " -knownSites:bed " + validationDataLocation + "recalibrationTest.bed" + " -T CountCovariates" + " -I " + bam + " -L 1:10,000,000-10,200,000" + " -standard" + " --solid_recal_mode SET_Q_ZERO" + " -recalFile %s", 1, // just one output file Arrays.asList(md5)); executeTest("testCountCovariatesBED", spec); } } @Test public void testCountCovariatesVCFPlusDBsnp() { HashMap<String, String> e = new HashMap<String, String>(); e.put( validationDataLocation + "NA12892.SLX.SRP000031.2009_06.selected.bam", "fd9e37879069aa6d84436c25e472b9e9"); for ( Map.Entry<String, String> entry : e.entrySet() ) { String bam = entry.getKey(); String md5 = entry.getValue(); WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec( "-R " + b36KGReference + " -knownSites:anyNameABCD,VCF3 " + validationDataLocation + "vcfexample3.vcf" + " -T CountCovariates" + " -I " + bam + " -knownSites " + b36dbSNP129 + " -L 1:10,000,000-10,200,000" + " -cov ReadGroupCovariate" + " -cov QualityScoreCovariate" + " -cov CycleCovariate" + " -cov DinucCovariate" + " --solid_recal_mode SET_Q_ZERO" + " -recalFile %s", 1, // just one output file Arrays.asList(md5)); executeTest("testCountCovariatesVCFPlusDBsnp", spec); } } @Test public void testCountCovariatesNoIndex() { HashMap<String, String> e = new HashMap<String, String>(); e.put( validationDataLocation + "NA12878.1kg.p2.chr1_10mb_11_mb.allTechs.noindex.bam", "828d247c6e8ef5ebdf3603dc0ce79f61" ); for ( Map.Entry<String, String> entry : e.entrySet() ) { String bam = entry.getKey(); String md5 = entry.getValue(); WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec( "-R " + b36KGReference + " -knownSites " + b36dbSNP129 + " -T CountCovariates" + " -I " + bam + " -cov ReadGroupCovariate" + " -cov QualityScoreCovariate" + " --solid_recal_mode DO_NOTHING" + " -recalFile %s" + " -U", 1, // just one output file Arrays.asList(md5)); List<File> result = executeTest("testCountCovariatesNoIndex", spec).getFirst(); paramsFiles.put(bam, result.get(0).getAbsolutePath()); } } @Test(dependsOnMethods = "testCountCovariatesNoIndex") public void testTableRecalibratorNoIndex() { HashMap<String, String> e = new HashMap<String, String>(); e.put( validationDataLocation + "NA12878.1kg.p2.chr1_10mb_11_mb.allTechs.noindex.bam", "991f093a0e610df235d28ada418ebf33" ); for ( Map.Entry<String, String> entry : e.entrySet() ) { String bam = entry.getKey(); String md5 = entry.getValue(); String paramsFile = paramsFiles.get(bam); System.out.printf("PARAMS FOR %s is %s%n", bam, paramsFile); if ( paramsFile != null ) { WalkerTestSpec spec = new WalkerTestSpec( "-R " + b36KGReference + " -T TableRecalibration" + " -I " + bam + " -o %s" + " --no_pg_tag" + " --solid_recal_mode DO_NOTHING" + " -recalFile " + paramsFile + " -U", 1, // just one output file Arrays.asList(md5)); executeTest("testTableRecalibratorNoIndex", spec); } else { throw new IllegalStateException("testTableRecalibratorNoIndex: paramsFile was null"); } } } @Test public void testCountCovariatesFailWithoutDBSNP() { HashMap<String, String> e = new HashMap<String, String>(); e.put( validationDataLocation + "NA12892.SLX.SRP000031.2009_06.selected.bam", ""); for ( Map.Entry<String, String> entry : e.entrySet() ) { String bam = entry.getKey(); WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec( "-R " + b36KGReference + " -T CountCovariates" + " -I " + bam + " -L 1:10,000,000-10,200,000" + " -standard" + " --solid_recal_mode SET_Q_ZERO" + " -recalFile %s", 1, // just one output file UserException.CommandLineException.class); executeTest("testCountCovariatesFailWithoutDBSNP", spec); } } }
// Triple Play - utilities for use in PlayN-based games package tripleplay.ui; import pythagoras.f.Dimension; import pythagoras.f.IPoint; import pythagoras.f.IRectangle; import pythagoras.f.Point; import pythagoras.f.Rectangle; import playn.core.Connection; import playn.core.Events; import playn.core.GroupLayer; import playn.core.Layer; import playn.core.Pointer; import react.Slot; import tripleplay.ui.Style.HAlign; import tripleplay.ui.Style.VAlign; import static playn.core.PlayN.graphics; /** * Provides a context for popping up a menu. */ public class MenuHost { /** The root layer that will contain all menus that pop up. It should normally be close to the * top of the hierarchy so that it draws on top of everything. */ public final GroupLayer rootLayer; /** The interface we use to create the menu's root and do animation. */ public final Interface iface; /** * An event type for triggering a menu popup. Also acts as a menu constraint so the integrated * host layout can make sure the whole menu is on screen and near to the triggering event * position or element. */ public static class Pop extends Layout.Constraint { /** The element that triggered the popup. {@link #position} is relative to this. */ public final Element<?> trigger; /** The menu to show. */ public final Menu menu; /** The position where the menu should pop up, e.g. a touch event position. Relative to * {@link #trigger}. */ public IPoint position; /** The bounds to confine the menu, in screen coordinates; usually the whole screen. */ public IRectangle bounds; /** Creates a new event and initializes {@link #trigger} and {@link #menu}. */ public Pop (Element<?> trigger, Menu menu) { this.menu = menu; this.trigger = trigger; position = new Point(0, 0); } /** * Causes the menu to handle further events on the given layer. This is usually the layer * handling a pointer start that caused the popup. A listener will be added to the layer * and the menu notified of pointer drag and end events. */ public Pop relayEvents (Layer layer) { _relayTarget = layer; return this; } /** * Positions the menu popup at the given positional event. */ public Pop atEventPos (Events.Position pos) { return atScreenPos(pos.x(), pos.y()); } /** * Positions the menu popup at the given screen position. */ public Pop atScreenPos (float x, float y) { position = new Point(x, y); return this; } /** * Positions the menu horizontally relative to the given layer, with an offset. The * vertical position remains unchanged. */ public Pop atLayerX (Layer layer, float x) { return atScreenPos(Layer.Util.layerToScreen(layer, x, 0).x, position.y()); } /** * Positions the menu vertically relative to the given layer, with an offset. The * horizontal position remains unchanged. */ public Pop atLayerY (Layer layer, float y) { return atScreenPos(position.x(), Layer.Util.layerToScreen(layer, 0, y).y); } /** * Sets the menu's horizontal alignment. */ public Pop halign (HAlign halign) { _halign = halign; return this; } /** * Sets the menu's vertical alignment. */ public Pop valign (VAlign valign) { _valign = valign; return this; } /** * Positions the menu horizontally relative to the left edge of the trigger. */ public Pop toLeft (float x) { return atLayerX(trigger.layer, x).halign(HAlign.RIGHT); } /** * Positions the menu horizontally relative to the right edge of the trigger. */ public Pop toRight (float x) { return atLayerX(trigger.layer, trigger.size().width() + x).halign(HAlign.LEFT); } /** * Positions the menu vertically relative to the top edge of the trigger. */ public Pop toTop (float y) { return atLayerY(trigger.layer, y).valign(VAlign.TOP); } /** * Positions the menu vertically relative to the bottom edge of the trigger. */ public Pop toBottom (float y) { return atLayerY(trigger.layer, trigger.size().height() + y).valign(VAlign.BOTTOM); } /** * Flags this {@code Pop} event so that the menu will not be destroyed automatically when * it is deactivated. Returns this instance for chaining. */ public Pop retainMenu () { _retain = true; return this; } /** * Optionally confines the menu area to the given screen area. By default the menu is * confined by the size of the application (see {@link playn.core.Graphics}). */ public Pop inScreenArea (IRectangle area) { bounds = new Rectangle(area); return this; } /** * Optionally confines the menu area to the given element. By default the menu is confined * by the size of the application area (see {@link playn.core.Graphics}). */ public Pop inElement (Element<?> elem) { Point tl = Layer.Util.layerToScreen(elem.layer, 0, 0); Point br = Layer.Util.layerToScreen(elem.layer, elem.size().width(), elem.size().height()); bounds = new Rectangle(tl.x(), tl.y(), br.x() - tl.x(), br.y() - tl.y()); return this; } /** * Returns the x position for the menu, adjusted for our specified alignment. */ public float alignedX (float width) { switch (_halign) { case LEFT: return position.x(); case CENTER: return position.x() - width / 2; case RIGHT: return position.x() - width; } // Unreachable assert(false); return position.x(); } /** * Returns the y position for the menu, adjusted for our specified alignment. */ public float alignedY (float height) { switch (_valign) { case TOP: return position.y(); case CENTER: return position.y() - height / 2; case BOTTOM: return position.y() - height; } // Unreachable assert(false); return position.x(); } /** Whether we should keep the menu around (i.e. not destroy it). */ protected boolean _retain; /** The layer that will be sending pointer drag and end events to us. */ protected Layer _relayTarget; protected HAlign _halign = HAlign.LEFT; protected VAlign _valign = VAlign.TOP; } public static Connection relayEvents (Layer from, final Menu to) { return from.addListener(new Pointer.Adapter() { @Override public void onPointerDrag (Pointer.Event e) { to.onPointerDrag(e); } @Override public void onPointerEnd (Pointer.Event e) { to.onPointerEnd(e); } }); } /** * Creates a menu host using the given values. The root layer is set to the layer of the given * root and the stylesheet to its stylesheet. */ public MenuHost (Interface iface, Elements<?> root) { this(iface, root.layer); _stylesheet = root.stylesheet(); } /** * Creates a new menu host using the given values. The stylesheet is set to an empty * one and can be changed via the {@link #setStylesheet(Stylesheet)} method. */ public MenuHost (Interface iface, GroupLayer rootLayer) { this.iface = iface; this.rootLayer = rootLayer; } /** * Sets the stylesheet for menus popped by this host. */ public MenuHost setStylesheet (Stylesheet sheet) { _stylesheet = sheet; return this; } /** * Directs a menu pop signal to {@link #popup(Pop)}. */ public Slot<Pop> onPopup () { return new Slot<Pop>() { @Override public void onEmit (Pop event) { popup(event); } }; } /** * Displays the menu specified by the given pop, incorporating all the configured attributes * therein. */ public void popup (final Pop pop) { // if there is no explicit constraint area requested, use the graphics if (pop.bounds == null) pop.inScreenArea(new Rectangle( 0, 0, graphics().width(), graphics().height())); // set up the menu root final Root menuRoot = iface.createRoot(new RootLayout(), _stylesheet, rootLayer); menuRoot.layer.setDepth(1); menuRoot.layer.setHitTester(null); // get hits from out of bounds menuRoot.add(pop.menu.setConstraint(pop)); menuRoot.pack(); // position the menu Point loc = Layer.Util.screenToLayer(rootLayer, pop.alignedX(menuRoot.size().width()), pop.alignedY(menuRoot.size().height())); menuRoot.layer.setTranslation(loc.x, loc.y); // set up the activation final Activation activation = new Activation(pop); // connect to deactivation signal and do our cleanup activation.deactivated = pop.menu.deactivated().connect(new Slot<Menu>() { @Override public void onEmit (Menu event) { // check parentage, it's possible the menu has been repopped already if (pop.menu.parent() == menuRoot) { // free the constraint to gc pop.menu.setConstraint(null); // remove or destroy it, depending on the caller's preference if (pop._retain) menuRoot.remove(pop.menu); else menuRoot.destroy(pop.menu); } // clear all connections activation.clear(); // TODO: do we need to stop menu animation here? it should be automatic since // by the time we reach this method, the deactivation animation is complete // always kill off the transient root iface.destroyRoot(menuRoot); // if this was our active menu, clear it if (_active != null && _active.pop.menu == event) _active = null; } }); // close the menu any time the trigger is removed from the hierarchy activation.triggerRemoved = pop.trigger.hierarchyChanged().connect(new Slot<Boolean>() { @Override public void onEmit (Boolean event) { if (!event) pop.menu.deactivate(); } }); // deactivate the old menu if (_active != null) _active.pop.menu.deactivate(); // pass along the animator pop.menu.init(iface.animator()); // activate _active = activation; pop.menu.activate(); } public Menu active () { return _active != null ? _active.pop.menu : null; } /** Simple layout for positioning the menu within the transient {@code Root}. */ protected static class RootLayout extends Layout { @Override public Dimension computeSize (Elements<?> elems, float hintX, float hintY) { return new Dimension(preferredSize(elems.childAt(0), hintX, hintY)); } @Override public void layout (Elements<?> elems, float left, float top, float width, float height) { if (elems.childCount() == 0) return; // get the constraint, it will always be a Pop Pop pop = (Pop)elems.childAt(0).constraint(); // make sure the menu lies inside the requested bounds if the menu doesn't do // that itself if (pop.menu.automaticallyConfine()) { IRectangle bounds = pop.bounds; Point tl = Layer.Util.screenToLayer(elems.layer, bounds.x(), bounds.y()); Point br = Layer.Util.screenToLayer(elems.layer, bounds.x() + bounds.width(), bounds.y() + bounds.height()); // nudge location left = Math.min(Math.max(left, tl.x), br.x - width); top = Math.min(Math.max(top, tl.y), br.y - height); } setBounds(elems.childAt(0), left, top, width, height); } } /** Holds a few variables related to the menu's activation. */ protected static class Activation { /** The configuration of the menu. */ public final Pop pop; /** Connects to the pointer events from the relay. */ public Connection pointerRelay; /** Connection to the trigger's hierarchy change. */ public react.Connection triggerRemoved; /** Connection to the menu's deactivation. */ public react.Connection deactivated; /** Creates a new activation. */ public Activation (Pop pop) { this.pop = pop; // handle pointer events from the relay Layer target = pop._relayTarget; if (target != null) pointerRelay = relayEvents(target, pop.menu); } /** Clears out the connections. */ public void clear () { if (pointerRelay != null) pointerRelay.disconnect(); if (triggerRemoved != null) triggerRemoved.disconnect(); if (deactivated != null) deactivated.disconnect(); pointerRelay = null; triggerRemoved = null; deactivated = null; } } /** The stylesheet used for popped menus. */ protected Stylesheet _stylesheet = Stylesheet.builder().create(); /** Currently active. */ protected Activation _active; }
package org.togglz.junit.vary; import java.util.HashSet; import java.util.Set; import org.togglz.core.Feature; /** * Default implementation of {@link VariationSet} that allows to build the set dynamically. * * @author Christian Kaltepoth * * @param <F> The feature class */ public class VariationSetBuilder<F extends Feature> implements VariationSet<F> { public static <F extends Feature> VariationSetBuilder<F> create(Class<F> featureClass) { return new VariationSetBuilder<F>(featureClass); } private final Class<F> featureClass; private final Set<F> featuresToVary = new HashSet<F>(); private final Set<F> featuresToEnable = new HashSet<F>(); private final Set<F> featuresToDisable = new HashSet<F>(); private VariationSetBuilder(Class<F> featureClass) { this.featureClass = featureClass; } /** * Vary this feature in the variation set. */ public VariationSetBuilder<F> vary(F f) { featuresToVary.add(f); featuresToEnable.remove(f); featuresToDisable.remove(f); return this; } /** * Enable this feature in the variation set. */ public VariationSetBuilder<F> enable(F f) { featuresToVary.remove(f); featuresToEnable.add(f); featuresToDisable.remove(f); return this; } /** * Disable this feature in the variation set. */ public VariationSetBuilder<F> disable(F f) { featuresToVary.remove(f); featuresToEnable.remove(f); featuresToDisable.add(f); return this; } /** * Enable all features in the variation set. */ public VariationSetBuilder<F> enableAll() { for (F f : featureClass.getEnumConstants()) { enable(f); } return this; } /** * Disable all features in the variation set. */ public VariationSetBuilder<F> disableAll() { for (F f : featureClass.getEnumConstants()) { disable(f); } return this; } /* * (non-Javadoc) * * @see org.togglz.junit.vary.VariationSet#getVariants() */ @Override public Set<Set<F>> getVariants() { // start with a single variant with all feature disabled Set<Set<F>> variantSet = new HashSet<Set<F>>(); variantSet.add(new HashSet<F>()); for (F feature : featureClass.getEnumConstants()) { // enable the feature in all variants if (featuresToEnable.contains(feature)) { for (Set<F> variant : variantSet) { variant.add(feature); } } // disable the feature in all variants else if (featuresToDisable.contains(feature)) { for (Set<F> variant : variantSet) { variant.remove(feature); } } // copy the existing variants, enable the feature in the copy, and merge them else if (featuresToVary.contains(feature)) { Set<Set<F>> copy = deepCopy(variantSet); for (Set<F> variant : copy) { variant.add(feature); } variantSet.addAll(copy); } } return variantSet; } private Set<Set<F>> deepCopy(Set<Set<F>> src) { Set<Set<F>> copy = new HashSet<Set<F>>(); for (Set<F> variant : src) { copy.add(new HashSet<F>(variant)); } return copy; } public Class<? extends Feature> getFeatureClass() { return featureClass; } }
// Triple Play - utilities for use in PlayN-based games package tripleplay.ui; import react.Slot; import react.Value; import react.ValueView; /** * Maintains a single selected item among a specified set of <code>Element</code> instances. The * elements may be added individually, or the children of an <code>Elements</code> may be tracked * automatically. * * <p>A click on a tracked element that implements <code>Clickable</code> makes it the selected * item, or <code>selected</code> can be used to manually control the selected item.</p> */ public class Selector { /** The selected item. May be updated to set the selection manually. */ public final Value<Element<?>> selected = Value.create(null); /** Create a selector with a null initial selection. */ public Selector () { selected.connect(new ValueView.Listener<Element<?>> () { @Override public void onChange (Element<?> selected, Element<?> deselected) { setSelected(deselected, false); setSelected(selected, true); } }); } /** Creates a selector containing the children of elements with initialSelection selected. */ public Selector (Elements<?> elements, Element<?> initialSelection) { this(); add(elements); selected.update(initialSelection); } /** * Tracks the children of <code>elements</code> for setting the selection. Children * subsequently added or removed from <code>elements</code> are automatically handled * appropriately. */ public Selector add (Elements<?> elements) { for (Element<?> child : elements) { _addSlot.onEmit(child); } elements.childAdded().connect(_addSlot); elements.childRemoved().connect(_removeSlot); return this; } /** * Stops tracking the children of <code>elements</code> for setting the selection. */ public Selector remove (Elements<?> elements) { for (Element<?> child : elements) { _removeSlot.onEmit(child); } elements.childAdded().disconnect(_addSlot); elements.childRemoved().disconnect(_removeSlot); return this; } /** * Tracks one or more elements. */ public Selector add (Element<?> elem, Element<?>... more) { _addSlot.onEmit(elem); for (Element<?> e : more) { _addSlot.onEmit(e); } return this; } /** * Stops tracking one or more elements. */ public Selector remove (Element<?> elem, Element<?>... more) { _removeSlot.onEmit(elem); for (Element<?> e : more) { _removeSlot.onEmit(e); } return this; } /** * Internal method to update the selection state of an element. */ protected void setSelected (Element<?> elem, boolean state) { if (elem == null) { return; } // TODO: do we need a Selectable interface to better abstract this value update? if (elem instanceof TogglableTextWidget) { ((TogglableTextWidget<?>)elem).selected.update(state); } else { elem.set(Element.Flag.SELECTED, state); elem.invalidate(); } } protected final Slot<Element<?>> _addSlot = new Slot<Element<?>>() { @Override public void onEmit (Element<?> child) { if (child instanceof Clickable<?>) { ((Clickable<?>)child).clicked().connect(_clickSlot); } } }; protected final Slot<Element<?>> _removeSlot = new Slot<Element<?>>() { @Override public void onEmit (Element<?> removed) { if (removed instanceof Clickable<?>) { ((Clickable<?>)removed).clicked().disconnect(_clickSlot); } if (selected.get() == removed) selected.update(null); } }; protected final Slot<Element<?>> _clickSlot = new Slot<Element<?>>() { @Override public void onEmit (Element<?> clicked) { selected.update(clicked.isSelected() ? clicked : null); } }; }
package org.lenskit.knn.item; import org.grouplens.grapht.annotation.DefaultInteger; import org.lenskit.inject.Parameter; import javax.inject.Qualifier; import java.lang.annotation.*; /** * The minimum users two items must have in common in order to be included in the similarity model. * Items with fewer than this many users in common will be ignored, i.e. treated as having no similarity. * A hard threshold allows for performance optimizations. */ @Qualifier @Documented @Parameter(int.class) @DefaultInteger(0) @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.PARAMETER, ElementType.FIELD, ElementType.METHOD}) public @interface MinCommonUsers { }
package org.innovateuk.ifs.user.resource; import com.fasterxml.jackson.annotation.JsonIgnore; public class ProcessRoleResource { private Long id; private Long user; private String userName; private Long applicationId; private ProcessRoleType role; private Long organisationId; private String userEmail; public ProcessRoleResource(){ // no-arg constructor } public ProcessRoleResource(Long id, UserResource user, Long applicationId, ProcessRoleType role, Long organisationId) { this.id = id; this.user = user.getId(); this.userName = user.getName(); this.applicationId = applicationId; this.role = role; this.organisationId = organisationId; } public Long getId(){return id;} public Long getUser() { return user; } public String getUserName() { return userName; } public ProcessRoleType getRole() { return role; } public Long getOrganisationId() { return organisationId; } public Long getApplicationId() { return this.applicationId; } public void setUser(Long user) { this.user = user; } public void setUserName(String userName) { this.userName = userName; } public void setApplicationId(Long applicationId) { this.applicationId = applicationId; } public void setRole(ProcessRoleType role) { this.role = role; } public void setOrganisationId(Long organisationId) { this.organisationId = organisationId; } public void setId(Long id) { this.id = id; } public String getUserEmail() { return userEmail; } public ProcessRoleResource setUserEmail(String userEmail) { this.userEmail = userEmail; return this; } @JsonIgnore public boolean isLeadApplicant() { return this.role == ProcessRoleType.LEADAPPLICANT; } }
package lhpn2sbml.gui; import lhpn2sbml.parser.*; import gcm2sbml.gui.*; import gcm2sbml.gui.Runnable; import biomodelsim.Log; import gcm2sbml.util.GlobalConstants; import gcm2sbml.util.Utility; import java.awt.GridLayout; import java.awt.GridBagLayout; import java.awt.GridBagConstraints; //import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.HashMap; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; //import javax.swing.DefaultListModel; //import javax.swing.JComboBox; import javax.swing.JFrame; //import javax.swing.BoxLayout; //import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; //import javax.swing.Icon; public class TransitionsPanel extends JPanel implements ActionListener { private String selected = ""; // private TransitionsPanel frame; private PropertyList transitionsList, controlList, boolAssignments, varAssignments, intAssignments, rateAssignments, assignments; private JPanel fieldPanel; private String[] options = { "Ok", "Cancel" }; // private Object[] types = { "Boolean", "Continuous", "Integer", "Rate" }; private LHPNFile lhpn; // private Log log; private HashMap<String, PropertyField> fields = null; public TransitionsPanel(String selected, PropertyList transitionsList, PropertyList controlList, LHPNFile lhpn, Log log) { super(new GridBagLayout()); GridBagConstraints constraints = new GridBagConstraints(); this.selected = selected; this.transitionsList = transitionsList; this.controlList = controlList; this.lhpn = lhpn; // this.log = log; fields = new HashMap<String, PropertyField>(); fieldPanel = new JPanel(new GridLayout(5, 2)); // ID field PropertyField field = new PropertyField(GlobalConstants.ID, "", null, null, Utility.ATACSIDstring); // field.setMaximumSize(new Dimension(5, 5)); // field.setPreferredSize(new Dimension(5, 5)); fields.put(GlobalConstants.ID, field); fieldPanel.add(field); // Delay field field = new PropertyField("Delay Lower Bound", "0", null, null, Utility.NAMEstring); fields.put("Delay lower", field); fieldPanel.add(field); field = new PropertyField("Delay Upper Bound", "inf", null, null, Utility.NAMEstring); fields.put("Delay upper", field); fieldPanel.add(field); // Transition Rate Field field = new PropertyField("Transition Rate", "", null, null, Utility.NAMEstring); fields.put("Transition rate", field); fieldPanel.add(field); // Enabling condition field field = new PropertyField("Enabling Condition", "", null, null, Utility.NAMEstring); fields.put("Enabling Condition", field); fieldPanel.add(field); // fieldPanel.setMaximumSize(new Dimension(50,50)); // fieldPanel.setPreferredSize(new Dimension(50,50)); constraints.gridx = 0; constraints.gridy = 0; add(fieldPanel, constraints); // Assignment panel assignments = new PropertyList("Assignment List"); boolAssignments = new PropertyList("Boolean Assignment List"); varAssignments = new PropertyList("Continuous Assignment List"); intAssignments = new PropertyList("Integer Assignment List"); rateAssignments = new PropertyList("Rate Assignment List"); EditButton addAssign = new EditButton("Add Assignment", assignments); RemoveButton removeAssign = new RemoveButton("Remove Assignment", assignments); EditButton editAssign = new EditButton("Edit Assignment", assignments); if (selected != null) { if (lhpn.getBooleanVars(selected) != null) { for (String s : lhpn.getBooleanVars(selected)) { if (s != null && lhpn.getBoolAssign(selected, s) != null) { boolAssignments.addItem(s + ":=" + lhpn.getBoolAssign(selected, s).toString()); assignments.addItem(s + ":=" + lhpn.getBoolAssign(selected, s).toString()); } } } if (lhpn.getContAssignVars(selected) != null) { for (String s : lhpn.getContAssignVars(selected)) { if (s != null) { if (!s.equals(null)) { varAssignments.addItem(s + ":=" + lhpn.getContAssign(selected, s)); assignments.addItem(s + ":=" + lhpn.getContAssign(selected, s)); } } } } if (lhpn.getIntVars(selected) != null) { for (Object obj : lhpn.getIntVars(selected).keySet()) { if (obj != null) { String s = (String) obj; if (!s.equals(null)) { intAssignments.addItem(s + ":=" + lhpn.getIntAssign(selected, s)); assignments.addItem(s + ":=" + lhpn.getIntAssign(selected, s)); } } } } if (lhpn.getRateVars(selected) != null) { for (String s : lhpn.getRateVars(selected)) { // log.addText(selected + " " + s); if (s != null) { if (!s.equals(null) && !lhpn.getRateAssign(selected, s).equals("true") && !lhpn.getRateAssign(selected, s).equals("false")) { rateAssignments.addItem(s + "':=" + lhpn.getRateAssign(selected, s)); assignments.addItem(s + "':=" + lhpn.getRateAssign(selected, s)); } } } } } JPanel assignPanel = Utility.createPanel(this, "Assignments", assignments, addAssign, removeAssign, editAssign); constraints.gridx = 0; constraints.gridy = 1; add(assignPanel, constraints); /* * // Boolean Assignment panel boolAssignments = new * PropertyList("Boolean Assignment List"); EditButton addBoolAssign = * new EditButton("Add Boolean Assignment", boolAssignments); * RemoveButton removeBoolAssign = new RemoveButton("Remove Boolean * Assignment", boolAssignments); EditButton editBoolAssign = new * EditButton("Edit Boolean Assignment", boolAssignments); if (selected != * null) { if (lhpn.getBooleanVars(selected) != null) { for (String s : * lhpn.getBooleanVars(selected)) { boolAssignments.addItem(s + ":=" + * lhpn.getBoolAssign(selected, s)); } } } * * JPanel boolAssignPanel = Utility.createPanel(this, "Boolean * Assignments", boolAssignments, addBoolAssign, removeBoolAssign, * editBoolAssign); constraints.gridx = 0; constraints.gridy = 1; * add(boolAssignPanel, constraints); // Variable Assignment panel * varAssignments = new PropertyList("Variable Assignment List"); * EditButton addVarAssign = new EditButton("Add Variable Assignment", * varAssignments); RemoveButton removeVarAssign = new * RemoveButton("Remove Variable Assignment", varAssignments); * EditButton editVarAssign = new EditButton("Edit Variable Assignment", * varAssignments); if (selected != null) { if * (lhpn.getContAssignVars(selected) != null) { for (String s : * lhpn.getContAssignVars(selected)) { varAssignments.addItem(s + ":=" + * lhpn.getContAssign(selected, s)); } } } * * JPanel varAssignPanel = Utility.createPanel(this, "Variable * Assignments", varAssignments, addVarAssign, removeVarAssign, * editVarAssign); constraints.gridx = 0; constraints.gridy = 2; * add(varAssignPanel, constraints); // Rate Assignment panel * rateAssignments = new PropertyList("Rate Assignment List"); * EditButton addRateAssign = new EditButton("Add Rate Assignment", * rateAssignments); RemoveButton removeRateAssign = new * RemoveButton("Remove Rate Assignment", rateAssignments); EditButton * editRateAssign = new EditButton("Edit Rate Assignment", * rateAssignments); if (selected != null) { if * (lhpn.getRateVars(selected) != null) { for (String s : * lhpn.getRateVars(selected)) { // log.addText(selected + " " + s); * rateAssignments.addItem(s + ":=" + lhpn.getRateAssign(selected, s)); } } } * * JPanel rateAssignPanel = Utility.createPanel(this, "Rate * Assignments", rateAssignments, addRateAssign, removeRateAssign, * editRateAssign); constraints.gridx = 0; constraints.gridy = 3; * constraints.fill = GridBagConstraints.BOTH; add(rateAssignPanel, * constraints); */ String oldName = null; if (selected != null) { oldName = selected; // Properties prop = lhpn.getVariables().get(selected); fields.get(GlobalConstants.ID).setValue(selected); // log.addText(lhpn.getDelay(selected)); String delay = lhpn.getDelay(selected); if (delay != null) { Pattern pattern = Pattern.compile("\\[([\\S^,]+?),([\\S^\\]]+?)\\]"); Matcher matcher = pattern.matcher(delay); if (matcher.find()) { fields.get("Delay lower").setValue(matcher.group(1)); fields.get("Delay upper").setValue(matcher.group(2)); } else { fields.get("Delay lower").setValue(delay); if (delay.equals("")) { fields.get("Delay upper").setValue(""); } } } else if (lhpn.getTransitionRate(selected) != null) { fields.get("Delay lower").setValue(delay); fields.get("Delay upper").setValue(""); } fields.get("Enabling Condition").setValue(lhpn.getEnabling(selected)); fields.get("Transition rate").setValue(lhpn.getTransitionRate(selected)); // log.addText(selected + lhpn.getEnabling(selected)); // loadProperties(prop); } // setType(types[0]); boolean display = false; while (!display) { display = openGui(oldName); } } private boolean checkValues() { for (PropertyField f : fields.values()) { if (!f.isValid()) { return false; } } return true; } private boolean openGui(String oldName) { int value = JOptionPane.showOptionDialog(new JFrame(), this, "Transition Editor", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { if (!checkValues()) { Utility.createErrorMessage("Error", "Illegal values entered."); return false; } String[] allVariables = lhpn.getAllIDs(); if (oldName == null && allVariables != null) { for (int i = 0; i < allVariables.length; i++) { if (allVariables[i] != null) { if (allVariables[i].equals(fields.get(GlobalConstants.ID).getValue())) { Utility.createErrorMessage("Error", "Transition id already exists."); return false; } } } } else if (!oldName.equals(fields.get(GlobalConstants.ID).getValue())) { for (int i = 0; i < allVariables.length; i++) { if (allVariables[i].equals(fields.get(GlobalConstants.ID).getValue())) { Utility.createErrorMessage("Error", "Transition id already exists."); return false; } } } else if (fields.get(GlobalConstants.ID).getValue() == null) { Utility.createErrorMessage("Error", "Enter transition ID."); return false; } String id = fields.get(GlobalConstants.ID).getValue(); // Check to see if we need to add or edit Properties property = new Properties(); for (PropertyField f : fields.values()) { if (f.getState() == null || f.getState().equals(PropertyField.states[1])) { property.put(f.getKey(), f.getValue()); } } if (selected != null && !oldName.equals(id)) { lhpn.changeTransitionName(oldName, id); } else if (selected == null) { lhpn.addTransition(id); } save(id); transitionsList.removeItem(oldName); transitionsList.addItem(id); transitionsList.setSelectedValue(id, true); for (String s : controlList.getItems()) { if (oldName != null) { String[] array = s.split("\\s"); for (String t : array) { if (t.equals(oldName)) { controlList.removeItem(s); s = s.replace(oldName, id); controlList.addItem(s); } } } } } else if (value == JOptionPane.NO_OPTION) { // System.out.println(); return true; } return true; } public void save(String transition) { // log.addText("saving..."); lhpn.removeAllAssign(transition); if (boolAssignments.getItems() != null) { for (String s : boolAssignments.getItems()) { // System.out.println("bool" + s); String[] tempArray = s.split(":="); lhpn.addBoolAssign(transition, tempArray[0], tempArray[1]); } } if (varAssignments.getItems() != null) { for (String s : varAssignments.getItems()) { // System.out.println("var " + s); String[] tempArray = s.split(":="); // System.out.println(transition + " " + tempArray[0] + " " + // tempArray[1]); lhpn.addContAssign(transition, tempArray[0], tempArray[1]); // log.addText("continuous "+ tempArray[0]); } } if (intAssignments.getItems() != null) { for (String s : intAssignments.getItems()) { // System.out.println("int" + s); String[] tempArray = s.split(":="); // System.out.println(transition + " " + tempArray[0] + " " + // tempArray[1]); lhpn.addIntAssign(transition, tempArray[0], tempArray[1]); // log.addText("integer " + tempArray[0]); } } if (rateAssignments.getItems() != null) { for (String s : rateAssignments.getItems()) { // System.out.println("rate " + s); String[] tempArray = s.split("':="); // System.out.println(tempArray[1]); lhpn.addRateAssign(transition, tempArray[0], tempArray[1]); } } String delay; if (!fields.get("Delay upper").getValue().equals("")) { delay = "[" + fields.get("Delay lower").getValue() + "," + fields.get("Delay upper").getValue() + "]"; } else { delay = fields.get("Delay lower").getValue(); } lhpn.changeDelay(transition, delay); lhpn.changeTransitionRate(transition, fields.get("Transition rate").getValue()); lhpn.changeEnabling(transition, fields.get("Enabling Condition").getValue()); } public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("comboBoxChanged")) { } Object o = e.getSource(); if (o instanceof Runnable) { ((Runnable) o).run(); } } public class RemoveButton extends AbstractRunnableNamedButton { public RemoveButton(String name, PropertyList list) { super(name); this.list = list; } public void run() { if (list.getSelectedValue() != null) { String assignment = list.getSelectedValue().toString(); if (isBoolean(assignment)) { list.removeItem(assignment); boolAssignments.removeItem(assignment); lhpn.removeBoolAssign(selected, assignment); } else if (isContinuous(assignment)) { list.removeItem(assignment); varAssignments.removeItem(assignment); lhpn.removeContAssign(selected, assignment); } else if (isRate(assignment)) { list.removeItem(assignment); rateAssignments.removeItem(assignment); lhpn.removeRateAssign(selected, assignment); } else if (isInteger(assignment)) { list.removeItem(assignment); intAssignments.removeItem(assignment); lhpn.removeIntAssign(selected, assignment); } } } private PropertyList list = null; } public class EditButton extends AbstractRunnableNamedButton { public EditButton(String name, PropertyList list) { super(name); this.list = list; } public void run() { new EditCommand(getName(), list).run(); } private PropertyList list = null; } private class EditCommand implements Runnable { public EditCommand(String name, PropertyList list) { this.name = name; this.list = list; } public void run() { if (name == null || name.equals("")) { Utility.createErrorMessage("Error", "Nothing selected to edit"); return; } if (list.getSelectedValue() == null && getName().contains("Edit")) { Utility.createErrorMessage("Error", "Nothing selected to edit"); return; } // String type = "", assignment = ""; String variable = null; if (list.getSelectedValue() != null && getName().contains("Edit")) { variable = list.getSelectedValue().toString(); } if ((lhpn.getContVars().length == 0) && (lhpn.getBooleanVars().length == 0) && (lhpn.getIntVars().length == 0)) { Utility.createErrorMessage("Error", "Add variables first"); } else if (getName().contains("Add") && (list.getItems().length == lhpn.getContVars().length + lhpn.getBooleanVars().length + lhpn.getIntVars().length)) { Utility.createErrorMessage("Error", "All variable have already been assigned in this transition"); } else { // System.out.println("transition " + selected); AssignmentPanel panel = new AssignmentPanel(selected, variable, list, varAssignments, rateAssignments, boolAssignments, intAssignments, lhpn); } /* * if (list.getSelectedValue() == null) { type = (String) * JOptionPane.showInputDialog(fieldPanel, "Which type of variable * assignment do you want to add?", "Assignment Type", * JOptionPane.PLAIN_MESSAGE, null, types, types[0]); } else { * assignment = list.getSelectedValue().toString(); } if * (getName().contains("Boolean") || type.equals("Boolean") || * isBoolean(assignment)) { String variable = null; if * (list.getSelectedValue() != null && getName().contains("Edit")) { * variable = list.getSelectedValue().toString(); } if * (lhpn.getBooleanVars().length == 0) { * Utility.createErrorMessage("Error", "Add boolean variables * first"); } else { BoolAssignPanel panel = new * BoolAssignPanel(selected, variable, list, boolAssignments, lhpn, * log); } } else if (getName().contains("Variable") || * type.equals("Continuous") || isContinuous(assignment)) { String * variable = null; if (list.getSelectedValue() != null && * getName().contains("Edit")) { variable = * list.getSelectedValue().toString(); } if * (lhpn.getContVars().length == 0) { * Utility.createErrorMessage("Error", "Add continuous variables * first"); } else { // System.out.println("transition " + * selected); VarAssignPanel panel = new VarAssignPanel(selected, * variable, list, varAssignments, lhpn); } } else if * (getName().contains("Integer") || type.equals("Integer") || * isInteger(assignment)) { String variable = null; if * (list.getSelectedValue() != null && getName().contains("Edit")) { * variable = list.getSelectedValue().toString(); } if * (lhpn.getIntVars().length == 0) { * Utility.createErrorMessage("Error", "Add integers first"); } else { // * System.out.println("transition " + // lhpn.getIntVars().length); * IntAssignPanel panel = new IntAssignPanel(selected, variable, * list, intAssignments, lhpn); } } else if * (getName().contains("Rate") || type.equals("Rate") || * isRate(assignment)) { String variable = null; if * (list.getSelectedValue() != null && getName().contains("Edit")) { * variable = list.getSelectedValue().toString(); } if * (lhpn.getContVars().length == 0) { * Utility.createErrorMessage("Error", "Add continuous variables * first"); } else { RateAssignPanel panel = new * RateAssignPanel(selected, variable, list, rateAssignments, lhpn, * log); } } */ } public String getName() { return name; } private String name = null; private PropertyList list = null; } private boolean isBoolean(String assignment) { for (String s : boolAssignments.getItems()) { if (s.equals(assignment)) { return true; } } return false; } private boolean isContinuous(String assignment) { for (String s : varAssignments.getItems()) { if (s.equals(assignment)) { return true; } } return false; } private boolean isInteger(String assignment) { for (String s : intAssignments.getItems()) { if (s.equals(assignment)) { return true; } } return false; } private boolean isRate(String assignment) { for (String s : rateAssignments.getItems()) { if (s.equals(assignment)) { return true; } } return false; } private void loadProperties(Properties property) { for (Object o : property.keySet()) { if (fields.containsKey(o.toString())) { fields.get(o.toString()).setValue(property.getProperty(o.toString())); fields.get(o.toString()).setCustom(); } } } }
package verification; import java.io.File; import java.util.ArrayList; import verification.platu.main.Options; import verification.platu.project.Project; import lpn.parser.LhpnFile; /** * This class provides a way to run depth-first search and partial order reduction (in platu package) * without the need for a GUI. * @author Zhen Zhang * */ public class VerificationNoGui { public static void main (String[] args) { if (args.length == 0) { System.err.println("Error: Missing arguments."); System.exit(0); } //System.out.println("Enter the directory of all LPNs: "); //Scanner scanner = new Scanner(System.in); //String directory = scanner.nextLine(); String directory = null; boolean poroff = true; for (int i=0; i<args.length; i++) { if (args[i].equals("-portb")) { Options.setPOR("tb"); Options.setCycleClosingMthd("behavioral"); Options.setCycleClosingAmpleMethd("cctb"); poroff = false; } else if (args[i].equals("-portboff")) { Options.setPOR("tboff"); Options.setCycleClosingMthd("behavioral"); Options.setCycleClosingAmpleMethd("cctboff"); poroff = false; } else if (args[i].contains("-dir=")) { // Directory should be provided as an argument starting with -dir: directory = args[i].trim().substring(5); } else if (args[i].contains("-log=")) { // Runtime, memory usage, and state count etc are written in the log file specified here. Options.setLogName(args[i].trim().substring(5)); } else if (args[i].contains("-memlim=")) { Options.setMemUpperBoundFlag(); String memUpperBound = args[i].trim().replace("-memlim=", ""); if(memUpperBound.contains("G")) { memUpperBound = memUpperBound.replace("G", ""); Options.setMemoryUpperBound((long)(Float.parseFloat(memUpperBound) * 1000000000)); } if(memUpperBound.contains("M")) { memUpperBound = memUpperBound.replace("M", ""); Options.setMemoryUpperBound((long)(Float.parseFloat(memUpperBound) * 1000000)); } } else if (args[i].contains("-disableDeadlockPreserve")) { Options.disablePORdeadlockPreserve(); } else if (args[i].contains("-debugON")) { Options.setDebugMode(true); System.out.println("Debug mode is ON."); } else if (args[i].contains("-depQueue")) { Options.setUseDependentQueue(); System.out.println("Use dependent queue."); } else if (args[i].contains("-disableDisablingError")) { Options.disableDisablingError(); System.out.println("Disabling error was diabled."); } else if (args[i].contains("-generateStateGraph")) { Options.setOutputSgFlag(true); System.out.println("Gererate state graphs."); } } if (directory.trim().equals("") || directory == null) { System.out.println("Direcotry provided is empty. Exit."); System.exit(0); } File dir = new File(directory); if (!dir.exists()) { System.err.println("Invalid direcotry. Exit."); System.exit(0); } Options.setPrjSgPath(directory); // Options for printing the final numbers from search_dfs or search_dfsPOR. Options.setOutputLogFlag(true); //Options.setDebugMode(false); File[] lpns = dir.listFiles(new FileExtentionFilter(".lpn")); ArrayList<LhpnFile> lpnList = new ArrayList<LhpnFile>(); for (int i=0; i < lpns.length; i++) { String curLPNname = lpns[i].getName(); LhpnFile curLPN = new LhpnFile(); curLPN.load(directory + curLPNname); lpnList.add(curLPN); } System.out.println("====== LPN loading order ========"); for (int i=0; i<lpnList.size(); i++) { System.out.println(lpnList.get(i).getLabel()); } Project untimed_dfs = new Project(lpnList); if (poroff) untimed_dfs.search(); else untimed_dfs.search_por_traceback(); } }
package org.javarosa.entity.model.view; import java.util.Vector; import javax.microedition.lcdui.Canvas; import javax.microedition.lcdui.Command; import javax.microedition.lcdui.CommandListener; import javax.microedition.lcdui.Displayable; import javax.microedition.lcdui.Graphics; import org.javarosa.core.api.IView; import org.javarosa.entity.activity.EntitySelectActivity; import de.enough.polish.ui.Container; import de.enough.polish.ui.FramedForm; import de.enough.polish.ui.Item; import de.enough.polish.ui.ItemStateListener; import de.enough.polish.ui.StringItem; import de.enough.polish.ui.TextField; public class EntitySelectView extends FramedForm implements IView, ItemStateListener, CommandListener { //#if javarosa.patientselect.formfactor == nokia-s40 private static final int MAX_ROWS_ON_SCREEN = 5; private static final int SCROLL_INCREMENT = 4; //#else private static final int MAX_ROWS_ON_SCREEN = 10; private static final int SCROLL_INCREMENT = 5; //#endif public static final int NEW_DISALLOWED = 0; public static final int NEW_IN_LIST = 1; public static final int NEW_IN_MENU = 2; private static final int INDEX_NEW = -1; //behavior configuration options public boolean sortByName = true; //if false, sort by ID public boolean wrapAround = false; //TODO: support this public int newMode = NEW_IN_LIST; private EntitySelectActivity controller; public String entityType; private TextField tf; private Command exitCmd; private Command sortCmd; private Command newCmd; private int firstIndex; private int selectedIndex; private Vector rowIDs; //index into data corresponding to current matches public EntitySelectView(EntitySelectActivity controller, String title) { super(title); this.controller = controller; tf = new TextField("Find: ", "", 20, TextField.ANY); tf.setInputMode(TextField.MODE_UPPERCASE); tf.setItemStateListener(this); append(Graphics.BOTTOM, tf); exitCmd = new Command("Cancel", Command.CANCEL, 4); sortCmd = new Command("Sort", Command.SCREEN, 3); addCommand(exitCmd); addCommand(sortCmd); this.setCommandListener(this); rowIDs = new Vector(); this.setScrollYOffset(0, false); } public void init () { selectedIndex = 0; firstIndex = 0; //can't go in constructor, as entityType is not set there yet if (newMode == NEW_IN_MENU) { newCmd = new Command("New " + entityType, Command.SCREEN, 4); addCommand(newCmd); } refresh(); } public void refresh () { refresh(-1); } public void refresh (int selectedEntity) { if (selectedEntity == -1) selectedEntity = getSelectedEntity(); getMatches(tf.getText()); selectEntity(selectedEntity); refreshList(); } public void show () { this.setActiveFrame(Graphics.BOTTOM); controller.setView(this); } public Object getScreenObject() { return this; } private void getMatches (String key) { rowIDs = controller.search(key); sortRows(); if (newMode == NEW_IN_LIST) { rowIDs.addElement(new Integer(INDEX_NEW)); } } private void stepIndex (boolean increment) { selectedIndex += (increment ? 1 : -1); if (selectedIndex < 0) { selectedIndex = 0; } else if (selectedIndex >= rowIDs.size()) { selectedIndex = rowIDs.size() - 1; } if (selectedIndex < firstIndex) { firstIndex -= SCROLL_INCREMENT; if (firstIndex < 0) firstIndex = 0; } else if (selectedIndex >= firstIndex + MAX_ROWS_ON_SCREEN) { firstIndex += SCROLL_INCREMENT; //don't believe i need to do any clipping in this case } } private int getSelectedEntity () { int selectedEntityID = -1; //save off old selected item if (!listIsEmpty()) { int rowID = rowID(selectedIndex); if (rowID != INDEX_NEW) { selectedEntityID = controller.getRecordID(rowID(selectedIndex)); } } return selectedEntityID; } private boolean listIsEmpty () { return rowIDs.size() == 0 || (rowIDs.size() == 1 && newMode == NEW_IN_LIST); } private int rowID (int i) { return ((Integer)rowIDs.elementAt(i)).intValue(); } private int selectedIndexFromScreen (int i) { return firstIndex + i; } private void selectEntity (int entityID) { //if old selected item is in new search result, select it, else select first match selectedIndex = 0; if (entityID != -1) { for (int i = 0; i < rowIDs.size(); i++) { int rowID = rowID(i); if (rowID != INDEX_NEW) { if (controller.getRecordID(rowID) == entityID) { selectedIndex = i; } } } } //position selected item in center of visible list firstIndex = selectedIndex - MAX_ROWS_ON_SCREEN / 2; if (firstIndex < 0) firstIndex = 0; } private void refreshList () { container.clear(); //#style patselTitleRow Container title = new Container(false); String[] titleData = controller.getTitleData(); for (int j = 0; j < titleData.length; j++) { //#style patselCell StringItem str = new StringItem("", titleData[j]); title.add(str); } //#style patselCell StringItem number = new StringItem("","(" + String.valueOf(rowIDs.size()) + ")"); title.add(number); this.append(title); if (listIsEmpty()) { this.append( new StringItem("", "(No matches)")); } for (int i = firstIndex; i < rowIDs.size() && i < firstIndex + MAX_ROWS_ON_SCREEN; i++) { Container row; int rowID = rowID(i); if (i == selectedIndex) { //#style patselSelectedRow row = new Container(false); } else if (i % 2 == 0) { //#style patselEvenRow row = new Container(false); } else { //#style patselOddRow row = new Container(false); } if (rowID == INDEX_NEW) { row.add(new StringItem("", "Add New " + entityType)); } else { String[] rowData = controller.getDataFields(rowID); for (int j = 0; j < rowData.length; j++) { //#style patselCell StringItem str = new StringItem("", rowData[j]); row.add(str); } } append(row); } setActiveFrame(Graphics.BOTTOM); } protected boolean handleKeyPressed(int keyCode, int gameAction) { //Supress these actions, letting the propogates screws up scrolling //on some platforms. if (gameAction == Canvas.UP && keyCode != Canvas.KEY_NUM2) { return true; } else if (gameAction == Canvas.DOWN && keyCode != Canvas.KEY_NUM8) { return true; } return super.handleKeyReleased(keyCode, gameAction); } protected boolean handleKeyReleased(int keyCode, int gameAction) { if (gameAction == Canvas.UP && keyCode != Canvas.KEY_NUM2) { stepIndex(false); refreshList(); return true; } else if (gameAction == Canvas.DOWN && keyCode != Canvas.KEY_NUM8) { stepIndex(true); refreshList(); return true; } else if (gameAction == Canvas.FIRE && keyCode != Canvas.KEY_NUM5) { processSelect(); return true; } return super.handleKeyReleased(keyCode, gameAction); } private void processSelect() { if (rowIDs.size() > 0) { int rowID = rowID(selectedIndex); if (rowID == INDEX_NEW) { controller.newEntity(); } else { controller.itemSelected(rowID); } } } public void itemStateChanged (Item item) { if (item == tf) { refresh(); } } public void changeSort (boolean sortByName) { this.sortByName = sortByName; refresh(); } //can't believe i'm writing a fucking sort function private void sortRows () { for (int i = rowIDs.size() - 1; i > 0; i for (int j = 0; j < i; j++) { int rowA = rowID(j); int rowB = rowID(j + 1); String keyA, keyB; if (sortByName) { keyA = controller.getDataName(rowA); keyB = controller.getDataName(rowB); } else { keyA = controller.getDataID(rowA); keyB = controller.getDataID(rowB); } if (keyA.compareTo(keyB) > 0) { rowIDs.setElementAt(new Integer(rowB), j); rowIDs.setElementAt(new Integer(rowA), j + 1); } } } } public void commandAction(Command cmd, Displayable d) { if (d == this) { if (cmd == exitCmd) { controller.exit(); } else if (cmd == sortCmd) { EntitySelectSortPopup pssw = new EntitySelectSortPopup(this, controller); pssw.show(); } else if (cmd == newCmd) { controller.newEntity(); } } } //#if polish.hasPointerEvents /* (non-Javadoc) * @see de.enough.polish.ui.Container#handlePointerPressed(int, int) */ protected boolean handlePointerPressed(int x, int y) { boolean handled = false; int screenIndex = 0; for (int i = 0; i < this.container.size(); i++) { Item item = this.container.getItems()[i]; if (item instanceof Container) { if (this.container.isInItemArea(x - this.container.getAbsoluteX(), y - this.container.getAbsoluteY(), item)) { selectedIndex = selectedIndexFromScreen(screenIndex); refreshList(); processSelect(); handled = true; break; } screenIndex++; } } if (handled){ return true; } else { return super.handlePointerPressed(x, y); } } //#endif }
package netrank; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; import mark.core.DetectionAgentProfile; import mark.core.Evidence; import mark.core.RawData; import mark.core.ServerInterface; /** * * @author Georgi Nikolov * The Obscurity agent uses the Bing API to execute a search of the domain. * Afterwards we look at the number of results produced and if the quantity is * under a predetermined threshold its considered suspicious as it gives insight * in how obscure the domain is. */ public class Obscurity extends WebsiteParser { private static final String DEFAULT_URL = "https: + " + "&setlang=en-gb"; private static final String DEFAULT_PATTERN = "(.*?) (?i)r"; private static final String DEFAULT_ELEMENT = "span.sb_count"; private static final int OBSCURITY_THRESHOLD = 1000; @Override public final int parse(final String data, final String given_pattern) { int result = 0; //use regex pattern to extract the numbers from the result string. Pattern pattern = Pattern.compile(given_pattern); Matcher matcher = pattern.matcher(data); //if a pattern is found replace the symbols delimiting the numbers //with nothing so we can transform the String numbers to Integer. String matched_string = ""; if (matcher.find()) { if (matcher.group(1).contains("&nbsp;")) { matched_string = matcher.group(1).replaceAll("&nbsp;", ""); } else if (matcher.group(1).contains(",")) { matched_string = matcher.group(1).replaceAll(",", ""); } else { matched_string = matcher.group(1); } result = Integer.parseInt(matched_string); } return result; } @Override public final void analyze( final Link subject, final String actual_trigger_label, final DetectionAgentProfile profile, final ServerInterface datastore) throws Throwable { RawData[] raw_data = datastore.findRawData( actual_trigger_label, subject); String domain_name = subject.getServer(); String number_of_results = ""; String search_url = ""; String element_to_search_for = DEFAULT_ELEMENT; String pattern_to_search_for = DEFAULT_PATTERN; //check if the parameter field in the config file has been filled //if it is adapt the DEFAULT parameters with those from the config file. if (profile.parameters != null) { search_url = profile.parameters.values().toArray()[0].toString() .replace(" element_to_search_for = profile.parameters.values().toArray()[2] .toString(); pattern_to_search_for = profile.parameters.values().toArray()[1] .toString(); } else { search_url = DEFAULT_URL.replace(" } try { number_of_results = connect(search_url, element_to_search_for); } catch (IOException ex) { System.out.println("Could not establish connection to server"); return; } System.out.println("NUMBERS: "+number_of_results); int parsed_results = parse(number_of_results, pattern_to_search_for); if (parsed_results < OBSCURITY_THRESHOLD) { Evidence evidence = new Evidence(); evidence.score = 1; evidence.subject = subject; evidence.label = profile.label; evidence.time = raw_data[raw_data.length - 1].time; evidence.report = "Found a domain:" + " " + domain_name + " that has suspiciosly low Obscurity value." + parsed_results + " references " + "found of " + domain_name + " on search engines."; datastore.addEvidence(evidence); } } }
package soot; import soot.util.*; /** * A class that models Java's array types. ArrayTypes are parametrized by a Type and * and an integer representing the array's dimension count.. * Two ArrayType are 'equal' if they are parametrized equally. * * * */ public class ArrayType extends RefLikeType { /** * baseType can be any type except for an array type, null and void * * What is the base type of the array? That is, for an array of type * A[][][], how do I find out what the A is? The accepted way of * doing this has always been to look at the public field baseType * in ArrayType, ever since the very beginning of Soot. */ public final Type baseType; /** dimension count for the array type*/ public final int numDimensions; private ArrayType(Type baseType, int numDimensions) { if( !( baseType instanceof PrimType || baseType instanceof RefType ) ) throw new RuntimeException( "oops, base type must be PrimType or RefType but not '"+ baseType +"'" ); if( numDimensions < 1 ) throw new RuntimeException( "attempt to create array with "+numDimensions+" dimensions" ); this.baseType = baseType; this.numDimensions = numDimensions; } /** * Creates an ArrayType parametrized by a given Type and dimension count. * @param baseType a Type to parametrize the ArrayType * @param numDimensions the dimension count to parametrize the ArrayType. * @return an ArrayType parametrized accrodingly. */ public static ArrayType v(Type baseType, int numDimensions) { if( numDimensions < 1 ) throw new RuntimeException( "attempt to create array with "+numDimensions+" dimensions" ); ArrayType ret; Type elementType; if( numDimensions == 1 ) { elementType = baseType; } else { elementType = ArrayType.v( baseType, numDimensions-1 ); } ret = elementType.getArrayType(); if( ret == null ) { ret = new ArrayType(baseType, numDimensions); elementType.setArrayType( ret ); } return ret; } /** * Two ArrayType are 'equal' if they are parametrized identically. * (ie have same Type and dimension count. * @param t object to test for equality * @return true if t is an ArrayType and is parametrized identically to this. */ public boolean equals(Object t) { return t == this; /* if(t instanceof ArrayType) { ArrayType arrayType = (ArrayType) t; return this.numDimensions == arrayType.numDimensions && this.baseType.equals(arrayType.baseType); } else return false; */ } public void toString(UnitPrinter up) { up.type( baseType ); for(int i = 0; i < numDimensions; i++) up.literal("[]"); } public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append(baseType.toString()); for(int i = 0; i < numDimensions; i++) buffer.append("[]"); return buffer.toString(); } public int hashCode() { return baseType.hashCode() + 0x432E0341 * numDimensions; } public void apply(Switch sw) { ((TypeSwitch) sw).caseArrayType(this); } /** * If I have a variable x of declared type t, what is a good * declared type for the expression ((Object[]) x)[i]? The * getArrayElementType() method in RefLikeType was introduced to * answer this question for all classes implementing RefLikeType. If * t is an array, then the answer is the same as getElementType(). * But t could also be Object, Serializable, or Cloneable, which can * all hold any array, so then the answer is Object. */ public Type getArrayElementType() { return getElementType(); } /** * If I get an element of the array, what will be its type? That * is, if I have an array a of type A[][][], what is the type of * a[] (it's A[][])? The getElementType() method in ArrayType was * introduced to answer this question. */ public Type getElementType() { if( numDimensions > 1 ) { return ArrayType.v( baseType, numDimensions-1 ); } else { return baseType; } } public ArrayType makeArrayType() { return ArrayType.v( baseType, numDimensions+1 ); } public boolean isAllowedInFinalCode() { return true; } }
package soot; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.ConcurrentModificationException; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import soot.jimple.SpecialInvokeExpr; import soot.util.ArraySet; import soot.util.Chain; /** * Represents the class hierarchy. It is closely linked to a Scene, and must be * recreated if the Scene changes. * * The general convention is that if a method name contains "Including", then it * returns the non-strict result; otherwise, it does a strict query (e.g. strict * superclass). */ public class Hierarchy { // These two maps are not filled in the constructor. private Map<SootClass, List<SootClass>> classToSubclasses; private Map<SootClass, List<SootClass>> interfaceToSubinterfaces; private Map<SootClass, List<SootClass>> interfaceToSuperinterfaces; private Map<SootClass, List<SootClass>> classToDirSubclasses; private Map<SootClass, List<SootClass>> interfaceToDirSubinterfaces; private Map<SootClass, List<SootClass>> interfaceToDirSuperinterfaces; // This holds the direct implementers. private Map<SootClass, List<SootClass>> interfaceToDirImplementers; int state; Scene sc; /** Constructs a hierarchy from the current scene. */ public Hierarchy() { this.sc = Scene.v(); state = sc.getState(); // Well, this used to be describable by 'Duh'. // Construct the subclasses hierarchy and the subinterfaces hierarchy. { Chain<SootClass> allClasses = sc.getClasses(); classToSubclasses = new HashMap<SootClass, List<SootClass>>(allClasses.size() * 2 + 1, 0.7f); interfaceToSubinterfaces = new HashMap<SootClass, List<SootClass>>(allClasses.size() * 2 + 1, 0.7f); interfaceToSuperinterfaces = new HashMap<SootClass, List<SootClass>>(allClasses.size() * 2 + 1, 0.7f); classToDirSubclasses = new HashMap<SootClass, List<SootClass>>(allClasses.size() * 2 + 1, 0.7f); interfaceToDirSubinterfaces = new HashMap<SootClass, List<SootClass>>(allClasses.size() * 2 + 1, 0.7f); interfaceToDirSuperinterfaces = new HashMap<SootClass, List<SootClass>>(allClasses.size() * 2 + 1, 0.7f); interfaceToDirImplementers = new HashMap<SootClass, List<SootClass>>(allClasses.size() * 2 + 1, 0.7f); for (SootClass c : allClasses) { if (c.resolvingLevel() < SootClass.HIERARCHY) continue; if (c.isInterface()) { interfaceToDirSubinterfaces.put(c, new ArrayList<SootClass>()); interfaceToDirSuperinterfaces.put(c, new ArrayList<SootClass>()); interfaceToDirImplementers.put(c, new ArrayList<SootClass>()); } else classToDirSubclasses.put(c, new ArrayList<SootClass>()); } for (SootClass c : allClasses) { if (c.resolvingLevel() < SootClass.HIERARCHY) continue; if (c.hasSuperclass()) { if (c.isInterface()) { List<SootClass> l2 = interfaceToDirSuperinterfaces.get(c); for (SootClass i : c.getInterfaces()) { if (c.resolvingLevel() < SootClass.HIERARCHY) continue; List<SootClass> l = interfaceToDirSubinterfaces.get(i); if (l != null) l.add(c); if (l2 != null) l2.add(i); } } else { List<SootClass> l = classToDirSubclasses.get(c.getSuperclass()); if (l != null) l.add(c); for (SootClass i : c.getInterfaces()) { if (c.resolvingLevel() < SootClass.HIERARCHY) continue; l = interfaceToDirImplementers.get(i); if (l != null) l.add(c); } } } } // Fill the directImplementers lists with subclasses. for (SootClass c : allClasses) { if (c.resolvingLevel() < SootClass.HIERARCHY) continue; if (c.isInterface()) { List<SootClass> imp = interfaceToDirImplementers.get(c); Set<SootClass> s = new ArraySet<SootClass>(); for (SootClass c0 : imp) { if (c.resolvingLevel() < SootClass.HIERARCHY) continue; s.addAll(getSubclassesOfIncluding(c0)); } imp.clear(); imp.addAll(s); } } } } protected void checkState() { if (state != sc.getState()) throw new ConcurrentModificationException("Scene changed for Hierarchy!"); } // This includes c in the list of subclasses. /** Returns a list of subclasses of c, including itself. */ public List<SootClass> getSubclassesOfIncluding(SootClass c) { c.checkLevel(SootClass.HIERARCHY); if (c.isInterface()) throw new RuntimeException("class needed!"); List<SootClass> l = new ArrayList<SootClass>(); l.addAll(getSubclassesOf(c)); l.add(c); return Collections.unmodifiableList(l); } /** Returns a list of subclasses of c, excluding itself. */ public List<SootClass> getSubclassesOf(SootClass c) { c.checkLevel(SootClass.HIERARCHY); if (c.isInterface()) throw new RuntimeException("class needed!"); checkState(); // If already cached, return the value. if (classToSubclasses.get(c) != null) return classToSubclasses.get(c); // Otherwise, build up the hashmap. List<SootClass> l = new ArrayList<SootClass>(); for (SootClass cls : classToDirSubclasses.get(c)) { if (cls.resolvingLevel() < SootClass.HIERARCHY) continue; l.addAll(getSubclassesOfIncluding(cls)); } l = Collections.unmodifiableList(l); classToSubclasses.put(c, l); return l; } /** Returns a list of superclasses of c, including itself. */ public List<SootClass> getSuperclassesOfIncluding(SootClass c) { c.checkLevel(SootClass.HIERARCHY); List<SootClass> l = getSuperclassesOf(c); ArrayList<SootClass> al = new ArrayList<SootClass>(); al.add(c); al.addAll(l); return Collections.unmodifiableList(al); } /** Returns a list of strict superclasses of c, starting with c's parent. */ public List<SootClass> getSuperclassesOf(SootClass c) { c.checkLevel(SootClass.HIERARCHY); if (c.isInterface()) throw new RuntimeException("class needed!"); checkState(); ArrayList<SootClass> l = new ArrayList<SootClass>(); SootClass cl = c; while (cl.hasSuperclass()) { l.add(cl.getSuperclass()); cl = cl.getSuperclass(); } return Collections.unmodifiableList(l); } /** Returns a list of subinterfaces of c, including itself. */ public List<SootClass> getSubinterfacesOfIncluding(SootClass c) { c.checkLevel(SootClass.HIERARCHY); if (!c.isInterface()) throw new RuntimeException("interface needed!"); List<SootClass> l = new ArrayList<SootClass>(); l.addAll(getSubinterfacesOf(c)); l.add(c); return Collections.unmodifiableList(l); } /** Returns a list of subinterfaces of c, excluding itself. */ public List<SootClass> getSubinterfacesOf(SootClass c) { c.checkLevel(SootClass.HIERARCHY); if (!c.isInterface()) throw new RuntimeException("interface needed!"); checkState(); // If already cached, return the value. if (interfaceToSubinterfaces.get(c) != null) return interfaceToSubinterfaces.get(c); // Otherwise, build up the hashmap. List<SootClass> l = new ArrayList<SootClass>(); for (SootClass si : interfaceToDirSubinterfaces.get(c)) { l.addAll(getSubinterfacesOfIncluding(si)); } interfaceToSubinterfaces.put(c, Collections.unmodifiableList(l)); return Collections.unmodifiableList(l); } /** Returns a list of superinterfaces of c, including itself. */ public List<SootClass> getSuperinterfacesOfIncluding(SootClass c) { c.checkLevel(SootClass.HIERARCHY); if (!c.isInterface()) throw new RuntimeException("interface needed!"); List<SootClass> l = new ArrayList<SootClass>(); l.addAll(getSuperinterfacesOf(c)); l.add(c); return Collections.unmodifiableList(l); } /** Returns a list of superinterfaces of c, excluding itself. */ public List<SootClass> getSuperinterfacesOf(SootClass c) { c.checkLevel(SootClass.HIERARCHY); if (!c.isInterface()) throw new RuntimeException("interface needed!"); checkState(); // If already cached, return the value. List<SootClass> cached = interfaceToSuperinterfaces.get(c); if (cached != null) return cached; // Otherwise, build up the hashmap. List<SootClass> l = new ArrayList<SootClass>(); for (SootClass si : interfaceToDirSuperinterfaces.get(c)) { l.addAll(getSuperinterfacesOfIncluding(si)); } interfaceToSuperinterfaces.put(c, Collections.unmodifiableList(l)); return Collections.unmodifiableList(l); } /** Returns a list of direct superclasses of c, excluding c. */ public List<SootClass> getDirectSuperclassesOf(SootClass c) { throw new RuntimeException("Not implemented yet!"); } /** Returns a list of direct subclasses of c, excluding c. */ public List<SootClass> getDirectSubclassesOf(SootClass c) { c.checkLevel(SootClass.HIERARCHY); if (c.isInterface()) throw new RuntimeException("class needed!"); checkState(); return Collections.unmodifiableList(classToDirSubclasses.get(c)); } // This includes c in the list of subclasses. /** Returns a list of direct subclasses of c, including c. */ public List<SootClass> getDirectSubclassesOfIncluding(SootClass c) { c.checkLevel(SootClass.HIERARCHY); if (c.isInterface()) throw new RuntimeException("class needed!"); checkState(); List<SootClass> l = new ArrayList<SootClass>(); l.addAll(classToDirSubclasses.get(c)); l.add(c); return Collections.unmodifiableList(l); } /** Returns a list of direct superinterfaces of c. */ public List<SootClass> getDirectSuperinterfacesOf(SootClass c) { throw new RuntimeException("Not implemented yet!"); } /** Returns a list of direct subinterfaces of c. */ public List<SootClass> getDirectSubinterfacesOf(SootClass c) { c.checkLevel(SootClass.HIERARCHY); if (!c.isInterface()) throw new RuntimeException("interface needed!"); checkState(); return interfaceToDirSubinterfaces.get(c); } /** Returns a list of direct subinterfaces of c, including itself. */ public List<SootClass> getDirectSubinterfacesOfIncluding(SootClass c) { c.checkLevel(SootClass.HIERARCHY); if (!c.isInterface()) throw new RuntimeException("interface needed!"); checkState(); List<SootClass> l = new ArrayList<SootClass>(); l.addAll(interfaceToDirSubinterfaces.get(c)); l.add(c); return Collections.unmodifiableList(l); } /** Returns a list of direct implementers of c, excluding itself. */ public List<SootClass> getDirectImplementersOf(SootClass i) { i.checkLevel(SootClass.HIERARCHY); if (!i.isInterface()) throw new RuntimeException("interface needed; got " + i); checkState(); return Collections.unmodifiableList(interfaceToDirImplementers.get(i)); } /** Returns a list of implementers of c, excluding itself. */ public List<SootClass> getImplementersOf(SootClass i) { i.checkLevel(SootClass.HIERARCHY); if (!i.isInterface()) throw new RuntimeException("interface needed; got " + i); checkState(); ArraySet<SootClass> set = new ArraySet<SootClass>(); for (SootClass c : getSubinterfacesOfIncluding(i)) { set.addAll(getDirectImplementersOf(c)); } ArrayList<SootClass> l = new ArrayList<SootClass>(); l.addAll(set); return Collections.unmodifiableList(l); } /** * Returns true if child is a subclass of possibleParent. If one of the * known parent classes is phantom, we conservatively assume that the * current class might be a child. */ public boolean isClassSubclassOf(SootClass child, SootClass possibleParent) { child.checkLevel(SootClass.HIERARCHY); possibleParent.checkLevel(SootClass.HIERARCHY); List<SootClass> parentClasses = getSuperclassesOf(child); if (parentClasses.contains(possibleParent)) return true; for (SootClass sc : parentClasses) if (sc.isPhantom()) return true; return false; } /** * Returns true if child is, or is a subclass of, possibleParent. If one of * the known parent classes is phantom, we conservatively assume that the * current class might be a child. */ public boolean isClassSubclassOfIncluding(SootClass child, SootClass possibleParent) { child.checkLevel(SootClass.HIERARCHY); possibleParent.checkLevel(SootClass.HIERARCHY); List<SootClass> parentClasses = getSuperclassesOfIncluding(child); if (parentClasses.contains(possibleParent)) return true; for (SootClass sc : parentClasses) if (sc.isPhantom()) return true; return false; } /** Returns true if child is a direct subclass of possibleParent. */ public boolean isClassDirectSubclassOf(SootClass c, SootClass c2) { throw new RuntimeException("Not implemented yet!"); } /** Returns true if child is a superclass of possibleParent. */ public boolean isClassSuperclassOf(SootClass parent, SootClass possibleChild) { parent.checkLevel(SootClass.HIERARCHY); possibleChild.checkLevel(SootClass.HIERARCHY); return getSubclassesOf(parent).contains(possibleChild); } /** Returns true if parent is, or is a superclass of, possibleChild. */ public boolean isClassSuperclassOfIncluding(SootClass parent, SootClass possibleChild) { parent.checkLevel(SootClass.HIERARCHY); possibleChild.checkLevel(SootClass.HIERARCHY); return getSubclassesOfIncluding(parent).contains(possibleChild); } /** Returns true if child is a subinterface of possibleParent. */ public boolean isInterfaceSubinterfaceOf(SootClass child, SootClass possibleParent) { child.checkLevel(SootClass.HIERARCHY); possibleParent.checkLevel(SootClass.HIERARCHY); return getSubinterfacesOf(possibleParent).contains(child); } /** Returns true if child is a direct subinterface of possibleParent. */ public boolean isInterfaceDirectSubinterfaceOf(SootClass child, SootClass possibleParent) { child.checkLevel(SootClass.HIERARCHY); possibleParent.checkLevel(SootClass.HIERARCHY); return getDirectSubinterfacesOf(possibleParent).contains(child); } /** Returns true if parent is a superinterface of possibleChild. */ public boolean isInterfaceSuperinterfaceOf(SootClass parent, SootClass possibleChild) { parent.checkLevel(SootClass.HIERARCHY); possibleChild.checkLevel(SootClass.HIERARCHY); return getSuperinterfacesOf(possibleChild).contains(parent); } /** Returns true if parent is a direct superinterface of possibleChild. */ public boolean isInterfaceDirectSuperinterfaceOf(SootClass parent, SootClass possibleChild) { parent.checkLevel(SootClass.HIERARCHY); possibleChild.checkLevel(SootClass.HIERARCHY); return getDirectSuperinterfacesOf(possibleChild).contains(parent); } /** * Returns the most specific type which is an ancestor of both c1 and c2. */ public SootClass getLeastCommonSuperclassOf(SootClass c1, SootClass c2) { c1.checkLevel(SootClass.HIERARCHY); c2.checkLevel(SootClass.HIERARCHY); throw new RuntimeException("Not implemented yet!"); } // Questions about method invocation. /** * Checks whether check is a visible class in view of the from class. It * assumes that protected and private classes do not exit. If they exist and * check is either protected or private, the check will return false. */ public boolean isVisible(SootClass from, SootClass check) { if (check.isPublic()) return true; if (check.isProtected() || check.isPrivate()) return false; // package visibility return from.getJavaPackageName().equals(check.getJavaPackageName()); } /** * Returns true if the classmember m is visible from code in the class from. */ public boolean isVisible(SootClass from, ClassMember m) { from.checkLevel(SootClass.HIERARCHY); m.getDeclaringClass().checkLevel(SootClass.HIERARCHY); if (!isVisible(from, m.getDeclaringClass())) return false; if (m.isPublic()) return true; if (m.isPrivate()) { return from.equals(m.getDeclaringClass()); } if (m.isProtected()) { return isClassSubclassOfIncluding(from, m.getDeclaringClass()); } // m is package return from.getJavaPackageName().equals(m.getDeclaringClass().getJavaPackageName()); // || isClassSubclassOfIncluding( from, m.getDeclaringClass() ); } /** * Given an object of actual type C (o = new C()), returns the method which * will be called on an o.f() invocation. */ public SootMethod resolveConcreteDispatch(SootClass concreteType, SootMethod m) { concreteType.checkLevel(SootClass.HIERARCHY); m.getDeclaringClass().checkLevel(SootClass.HIERARCHY); checkState(); if (concreteType.isInterface()) throw new RuntimeException("class needed!"); String methodSig = m.getSubSignature(); for (SootClass c : getSuperclassesOfIncluding(concreteType)) { SootMethod sm = c.getMethodUnsafe(methodSig); if (sm != null && isVisible(c, m)) { return sm; } } throw new RuntimeException("could not resolve concrete dispatch!\nType: " + concreteType + "\nMethod: " + m); } /** * Given a set of definite receiver types, returns a list of possible * targets. */ public List<SootMethod> resolveConcreteDispatch(List<Type> classes, SootMethod m) { m.getDeclaringClass().checkLevel(SootClass.HIERARCHY); checkState(); Set<SootMethod> s = new ArraySet<SootMethod>(); for (Type cls : classes) { if (cls instanceof RefType) s.add(resolveConcreteDispatch(((RefType) cls).getSootClass(), m)); else if (cls instanceof ArrayType) { s.add(resolveConcreteDispatch((RefType.v("java.lang.Object")).getSootClass(), m)); } else throw new RuntimeException("Unable to resolve concrete dispatch of type " + cls); } return Collections.unmodifiableList(new ArrayList<SootMethod>(s)); } // what can get called for c & all its subclasses /** * Given an abstract dispatch to an object of type c and a method m, gives a * list of possible receiver methods. */ public List<SootMethod> resolveAbstractDispatch(SootClass c, SootMethod m) { c.checkLevel(SootClass.HIERARCHY); m.getDeclaringClass().checkLevel(SootClass.HIERARCHY); checkState(); Set<SootMethod> s = new ArraySet<SootMethod>(); Collection<SootClass> classesIt; if (c.isInterface()) { Set<SootClass> classes = new HashSet<SootClass>(); for (SootClass sootClass : getImplementersOf(c)) { classes.addAll(getSubclassesOfIncluding(sootClass)); } classesIt = classes; } else classesIt = getSubclassesOfIncluding(c); for (SootClass cl : classesIt) { if (!Modifier.isAbstract(cl.getModifiers())) { s.add(resolveConcreteDispatch(cl, m)); } } return Collections.unmodifiableList(new ArrayList<SootMethod>(s)); } // what can get called if you have a set of possible receiver types /** * Returns a list of possible targets for the given method and set of * receiver types. */ public List<SootMethod> resolveAbstractDispatch(List<SootClass> classes, SootMethod m) { m.getDeclaringClass().checkLevel(SootClass.HIERARCHY); Set<SootMethod> s = new ArraySet<SootMethod>(); for (SootClass sootClass : classes) { s.addAll(resolveAbstractDispatch(sootClass, m)); } return Collections.unmodifiableList(new ArrayList<SootMethod>(s)); } /** Returns the target for the given SpecialInvokeExpr. */ public SootMethod resolveSpecialDispatch(SpecialInvokeExpr ie, SootMethod container) { container.getDeclaringClass().checkLevel(SootClass.HIERARCHY); SootMethod target = ie.getMethod(); target.getDeclaringClass().checkLevel(SootClass.HIERARCHY); /* * This is a bizarre condition! Hopefully the implementation is correct. * See VM Spec, 2nd Edition, Chapter 6, in the definition of * invokespecial. */ if ("<init>".equals(target.getName()) || target.isPrivate()) return target; else if (isClassSubclassOf(target.getDeclaringClass(), container.getDeclaringClass())) return resolveConcreteDispatch(container.getDeclaringClass(), target); else return target; } }
import java.awt.EventQueue; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; import java.net.BindException; import java.net.ServerSocket; import java.net.Socket; import java.net.URL; import java.util.ArrayList; import java.util.List; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JTextArea; import javax.net.ServerSocketFactory; import javax.net.ssl.SSLServerSocketFactory; import javax.swing.JScrollPane; /* * @author Yasiru Dahanayake */ public class Server { private static ArrayList<ServerThread> clients; private static ServerSocket sS; private static final int PORT = 1234; private static JFrame frame; private static boolean serverRunning = true; private static JTextArea textArea; private static JScrollPane scrollPane; private static ObjectOutputStream oos; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { Server window = new Server(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); while (serverRunning){ SetUpConnections(); } } /** * Create the application. */ public Server() { initialize(); } /* * Uses self signed certificate "ca.store" to authenticate a handshake * Server starts up and listens for connections, if an instance of the * server is already running notify and close the current instance. */ private static void SetUpConnections() { try { // using a self singed certificate // password is capita123 //String trustStore = Server.class.getResource("Resources").getPath(); //System.setProperty("javax.net.ssl.keyStore",Server.class.getResourceAsStream("/ca.store")); System.setProperty("javax.net.ssl.keyStore","ca.store"); System.setProperty("javax.net.ssl.keyStorePassword", "capita123"); ServerSocketFactory factory = SSLServerSocketFactory.getDefault(); sS = factory.createServerSocket(PORT); textArea.append("Server running and listening for connections... \n"); while (true) { Socket socket = sS.accept(); ServerThread rc = new ServerThread(socket); // clients.add(rc); Thread tr = new Thread(rc); tr.start(); textArea.append("DEBUG: Client Connected \n"); } } catch (BindException e) { JOptionPane.showMessageDialog(frame, "instance of a server is " + "already running"); System.exit(0); } catch (Exception e) { textArea.append(e.getMessage()+"\n"); e.printStackTrace(); } } /* * Writes an ArrayList of objects to the client through socket */ private static void writeToClient(List<Object> list, Socket socket) throws IOException { oos = new ObjectOutputStream(socket.getOutputStream()); textArea.append("DEBUG: Objects sent to client \n"); oos.writeObject(list); } /* * CLoses the client socket (removes connection) removes this thread from * server thread. */ private static void closeConnection(Socket socket, ServerThread thread) { try { socket.close(); clients.remove(thread); textArea.append("Client Disconnected, thread removed \n "); } catch (NullPointerException E) { } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /* * Runnable class to handle instances of clients that are connected test * method handle requests to for testing with dummy client. * */ private static class ServerThread implements Runnable, Serializable { Socket socket; ServerThread(Socket socket) { this.socket = socket; } @Override public void run() { } } /** * Initialise the contents of the frame. */ private void initialize() { frame = new JFrame(); frame.setBounds(100, 100, 450, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(null); frame.setTitle("Server"); frame.setResizable(false); scrollPane = new JScrollPane(); scrollPane.setBounds(27, 21, 400, 235); frame.getContentPane().add(scrollPane); textArea = new JTextArea(); textArea.setEditable(false); scrollPane.setViewportView(textArea); /* * resume server button */ } }
package addons.eventhandlers; import network.Link; import simulation.Route; import simulation.events.*; import java.io.PrintStream; public class DebugEventHandler implements ImportListener, LearnListener, SelectListener, ExportListener, DetectListener { private PrintStream printStream; // print stream to print debug messages // listen to all events by default private boolean importEventsEnabled; private boolean learnEventsEnabled; private boolean selectEventsEnabled; private boolean detectEventsEnabled; private boolean exportEventsEnabled; /** * Creates a debug event handler that will print to the stdout by default. * * @param enabled sets all events as enabled or disabled. */ public DebugEventHandler(boolean enabled) { this.printStream = System.out; setAllEnabled(enabled); } /** * Creates a debug event handler that will print to the given print stream. * * @param enabled sets all events as enabled or disabled. */ public DebugEventHandler(PrintStream printStream, boolean enabled) { this.printStream = printStream; setAllEnabled(enabled); } public void setAllEnabled(boolean enabled) { importEventsEnabled = enabled; learnEventsEnabled = enabled; selectEventsEnabled = enabled; detectEventsEnabled = enabled; exportEventsEnabled = enabled; } public void setImportEnabled(boolean enable) { importEventsEnabled = enable; } public void setLearnEnabled(boolean enable) { learnEventsEnabled = enable; } public void setSelectEnabled(boolean enable) { selectEventsEnabled = enable; } public void setDetectEnabled(boolean enable) { detectEventsEnabled = enable; } public void setExportEnabled(boolean enable) { exportEventsEnabled = enable; } public void register(SimulationEventGenerator eventGenerator) { eventGenerator.addImportListener(this); eventGenerator.addLearnListener(this); eventGenerator.addSelectListener(this); eventGenerator.addExportListener(this); eventGenerator.addDetectListener(this); } /** * Invoked when a detect event occurs. * * @param event detect event that occurred. */ @Override public void onDetected(DetectEvent event) { if (detectEventsEnabled) { printStream.println("Detect:\t" + event.getDetectingNode() + " detected with " + pretty(event.getLearnedRoute()) + " learned from " + pretty(event.getOutLink()) + " other option was " + pretty(event.getExclRoute())); } } /** * Invoked when a export event occurs. * * @param event export event that occurred. */ @Override public void onExported(ExportEvent event) { if (exportEventsEnabled) { printStream.println("Export:\t" + event.getExportingNode() + " exported to " + event.getLearningNode() + " " + pretty(event.getRoute())); } } /** * Invoked when a import event occurs. * * @param event import event that occurred. */ @Override public void onImported(ImportEvent event) { if (importEventsEnabled) { printStream.println("Import:\t" + event.getImportingNode() + " imported from " + event.getExportingNode() + " " + pretty(event.getRoute())); } } /** * Invoked when a learn event occurs. * * @param event learn event that occurred. */ @Override public void onLearned(LearnEvent event) { if (learnEventsEnabled) { printStream.println("Learn:\t" + event.getLearningNode() + " learned through " + pretty(event.getLink()) + " " + pretty(event.getRoute())); } } /** * Invoked when a select event occurs. * * @param event select event that occurred. */ @Override public void onSelected(SelectEvent event) { if (selectEventsEnabled) { if (event.getPreviousRoute().equals(event.getSelectedRoute())) { printStream.println("Select:\t" + event.getSelectingNode() + " selected same " + pretty(event.getSelectedRoute())); } else { printStream.println("Select:\t" + event.getSelectingNode() + " selected " + pretty(event.getSelectedRoute()) + " over " + pretty(event.getPreviousRoute())); } } } /* Set of methods to print components in a prettier way. */ private static String pretty(Route route) { return String.format("route (%s, %s)", route.getAttribute(), route.getPath()); } private static String pretty(Link link) { return String.format("link (%s->%s, %s)", link.getSource(), link.getDestination(), link.getLabel()); } }
package org.exist.xquery; import java.io.IOException; import junit.framework.TestCase; import junit.textui.TestRunner; import org.exist.EXistException; import org.exist.collections.Collection; import org.exist.collections.IndexInfo; import org.exist.collections.triggers.TriggerException; import org.exist.dom.DocumentImpl; import org.exist.security.PermissionDeniedException; import org.exist.security.SecurityManager; import org.exist.security.xacml.AccessContext; import org.exist.storage.BrokerPool; import org.exist.storage.DBBroker; import org.exist.storage.serializers.Serializer; import org.exist.storage.txn.TransactionException; import org.exist.storage.txn.TransactionManager; import org.exist.storage.txn.Txn; import org.exist.util.Configuration; import org.exist.util.LockException; import org.exist.xmldb.XmldbURI; import org.exist.xquery.value.NodeValue; import org.exist.xquery.value.Sequence; import org.xml.sax.SAXException; public class XQueryUpdateTest extends TestCase { public static void main(String[] args) { TestRunner.run(XQueryUpdateTest.class); } protected static XmldbURI TEST_COLLECTION = XmldbURI.create(DBBroker.ROOT_COLLECTION + "/test"); protected static String TEST_XML = "<?xml version=\"1.0\"?>" + "<products/>"; protected static String UPDATE_XML = "<progress total=\"100\" done=\"0\" failed=\"0\" passed=\"0\"/>"; protected final static int ITEMS_TO_APPEND = 1000; private BrokerPool pool; public void testAppend() { DBBroker broker = null; try { System.out.println("testAppend() ...\n"); broker = pool.get(SecurityManager.SYSTEM_USER); XQuery xquery = broker.getXQueryService(); String query = " declare variable $i external;\n" + " update insert\n" + " <product id='id{$i}' num='{$i}'>\n" + " <description>Description {$i}</description>\n" + " <price>{$i + 1.0}</price>\n" + " <stock>{$i * 10}</stock>\n" + " </product>\n" + " into /products"; XQueryContext context = xquery.newContext(AccessContext.TEST); CompiledXQuery compiled = xquery.compile(context, query); for (int i = 0; i < ITEMS_TO_APPEND; i++) { context.declareVariable("i", new Integer(i)); xquery.execute(compiled, null); } Sequence seq = xquery.execute("/products", null, AccessContext.TEST); assertEquals(seq.getItemCount(), 1); Serializer serializer = broker.getSerializer(); System.out.println(serializer.serialize((NodeValue) seq.itemAt(0))); seq = xquery.execute("//product", null, AccessContext.TEST); assertEquals(ITEMS_TO_APPEND, seq.getItemCount()); seq = xquery.execute("//product[price > 0.0]", null, AccessContext.TEST); assertEquals(ITEMS_TO_APPEND, seq.getItemCount()); System.out.println("testAppend: PASS"); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } finally { pool.release(broker); } } public void testAppendAttributes() { testAppend(); DBBroker broker = null; try { System.out.println("testAppendAttributes() ...\n"); broker = pool.get(SecurityManager.SYSTEM_USER); XQuery xquery = broker.getXQueryService(); String query = " declare variable $i external;\n" + " update insert\n" + " attribute name { concat('n', $i) }\n" + " into //product[@num = $i]"; XQueryContext context = xquery.newContext(AccessContext.TEST); CompiledXQuery compiled = xquery.compile(context, query); for (int i = 0; i < ITEMS_TO_APPEND; i++) { context.declareVariable("i", new Integer(i)); xquery.execute(compiled, null); } Sequence seq = xquery.execute("/products", null, AccessContext.TEST); assertEquals(seq.getItemCount(), 1); Serializer serializer = broker.getSerializer(); System.out.println(serializer.serialize((NodeValue) seq.itemAt(0))); seq = xquery.execute("//product", null, AccessContext.TEST); assertEquals(ITEMS_TO_APPEND, seq.getItemCount()); seq = xquery.execute("//product[@name = 'n20']", null, AccessContext.TEST); assertEquals(1, seq.getItemCount()); store(broker, "attribs.xml", "<test attr1='aaa' attr2='bbb'>ccc</test>"); query = "update insert attribute attr1 { 'eee' } into /test"; System.out.println("testing duplicate attribute ..."); xquery.execute(query, null, AccessContext.TEST); seq = xquery.execute("document('" + TEST_COLLECTION + "/attribs.xml')/test[@attr1 = 'eee']", null, AccessContext.TEST); assertEquals(1, seq.getItemCount()); System.out.println(serializer.serialize((NodeValue) seq.itemAt(0))); System.out.println("testAppendAttributes: PASS"); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } finally { pool.release(broker); } } public void testInsertBefore() { DBBroker broker = null; try { System.out.println("testInsertBefore() ...\n"); broker = pool.get(SecurityManager.SYSTEM_USER); String query = " update insert\n" + " <product id='original'>\n" + " <description>Description</description>\n" + " <price>0</price>\n" + " <stock>10</stock>\n" + " </product>\n" + " into /products"; XQuery xquery = broker.getXQueryService(); xquery.execute(query, null, AccessContext.TEST); query = " declare variable $i external;\n" + " update insert\n" + " <product id='id{$i}'>\n" + " <description>Description {$i}</description>\n" + " <price>{$i + 1.0}</price>\n" + " <stock>{$i * 10}</stock>\n" + " </product>\n" + " preceding /products/product[1]"; XQueryContext context = xquery.newContext(AccessContext.TEST); CompiledXQuery compiled = xquery.compile(context, query); for (int i = 0; i < ITEMS_TO_APPEND; i++) { context.declareVariable("i", new Integer(i)); xquery.execute(compiled, null); } Sequence seq = xquery.execute("/products", null, AccessContext.TEST); assertEquals(seq.getItemCount(), 1); Serializer serializer = broker.getSerializer(); System.out.println(serializer.serialize((NodeValue) seq.itemAt(0))); seq = xquery.execute("//product", null, AccessContext.TEST); assertEquals(ITEMS_TO_APPEND + 1, seq.getItemCount()); seq = xquery.execute("//product[price > 0.0]", null, AccessContext.TEST); assertEquals(ITEMS_TO_APPEND, seq.getItemCount()); System.out.println("testInsertBefore: PASS"); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } finally { pool.release(broker); } } public void testInsertAfter() { DBBroker broker = null; try { System.out.println("testInsertAfter() ...\n"); broker = pool.get(SecurityManager.SYSTEM_USER); String query = " update insert\n" + " <product id='original'>\n" + " <description>Description</description>\n" + " <price>0</price>\n" + " <stock>10</stock>\n" + " </product>\n" + " into /products"; XQuery xquery = broker.getXQueryService(); xquery.execute(query, null, AccessContext.TEST); query = " declare variable $i external;\n" + " update insert\n" + " <product id='id{$i}'>\n" + " <description>Description {$i}</description>\n" + " <price>{$i + 1.0}</price>\n" + " <stock>{$i * 10}</stock>\n" + " </product>\n" + " following /products/product[1]"; XQueryContext context = xquery.newContext(AccessContext.TEST); CompiledXQuery compiled = xquery.compile(context, query); for (int i = 0; i < ITEMS_TO_APPEND; i++) { context.declareVariable("i", new Integer(i)); xquery.execute(compiled, null); } Sequence seq = xquery.execute("/products", null, AccessContext.TEST); assertEquals(seq.getItemCount(), 1); Serializer serializer = broker.getSerializer(); System.out.println(serializer.serialize((NodeValue) seq.itemAt(0))); seq = xquery.execute("//product", null, AccessContext.TEST); assertEquals(ITEMS_TO_APPEND + 1, seq.getItemCount()); seq = xquery.execute("//product[price > 0.0]", null, AccessContext.TEST); assertEquals(ITEMS_TO_APPEND, seq.getItemCount()); System.out.println("testInsertAfter: PASS"); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } finally { pool.release(broker); } } public void testUpdate() { testAppend(); DBBroker broker = null; try { System.out.println("testUpdate() ...\n"); broker = pool.get(SecurityManager.SYSTEM_USER); XQuery xquery = broker.getXQueryService(); String query = "declare option exist:output-size-limit '-1';\n" + "for $prod at $i in //product return\n" + " update value $prod/description\n" + " with concat('Updated Description', $i)"; Sequence seq = xquery.execute(query, null, AccessContext.TEST); seq = xquery.execute("//product[starts-with(description, 'Updated')]", null, AccessContext.TEST); assertEquals(seq.getItemCount(), ITEMS_TO_APPEND); Serializer serializer = broker.getSerializer(); System.out.println(serializer.serialize((NodeValue) seq.itemAt(0))); for (int i = 1; i <= ITEMS_TO_APPEND; i++) { seq = xquery.execute("//product[description &= 'Description" + i + "']", null, AccessContext.TEST); assertEquals(1, seq.getItemCount()); System.out.println(serializer.serialize((NodeValue) seq.itemAt(0))); } seq = xquery.execute("//product[description &= 'Updated']", null, AccessContext.TEST); assertEquals(seq.getItemCount(), ITEMS_TO_APPEND); System.out.println(serializer.serialize((NodeValue) seq.itemAt(0))); query = "declare option exist:output-size-limit '-1';\n" + "for $prod at $count in //product return\n" + " update value $prod/stock/text()\n" + " with (400 + $count)"; seq = xquery.execute(query, null, AccessContext.TEST); seq = xquery.execute("//product[stock > 400]", null, AccessContext.TEST); assertEquals(seq.getItemCount(), ITEMS_TO_APPEND); seq = xquery.execute("//product[stock &= '401']", null, AccessContext.TEST); assertEquals(seq.getItemCount(), 1); System.out.println(serializer.serialize((NodeValue) seq.itemAt(0))); query = "declare option exist:output-size-limit '-1';\n" + "for $prod in //product return\n" + " update value $prod/@num\n" + " with xs:int($prod/@num) * 3"; seq = xquery.execute(query, null, AccessContext.TEST); seq = xquery.execute("/products", null, AccessContext.TEST); assertEquals(seq.getItemCount(), 1); seq = xquery.execute("//product[@num = 3]", null, AccessContext.TEST); assertEquals(seq.getItemCount(), 1); System.out.println(serializer.serialize((NodeValue) seq.itemAt(0))); query = "declare option exist:output-size-limit '-1';\n" + "for $prod in //product return\n" + " update value $prod/stock\n" + " with (<local>10</local>,<external>1</external>)"; seq = xquery.execute(query, null, AccessContext.TEST); seq = xquery.execute("/products", null, AccessContext.TEST); assertEquals(seq.getItemCount(), 1); seq = xquery.execute("//product/stock/external[. = 1]", null, AccessContext.TEST); assertEquals(seq.getItemCount(), ITEMS_TO_APPEND); System.out.println("testUpdate: PASS"); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } finally { pool.release(broker); } } public void testRemove() { testAppend(); DBBroker broker = null; try { broker = pool.get(SecurityManager.SYSTEM_USER); XQuery xquery = broker.getXQueryService(); String query = "for $prod in //product return\n" + " update delete $prod\n"; Sequence seq = xquery.execute(query, null, AccessContext.TEST); seq = xquery.execute("//product", null, AccessContext.TEST); assertEquals(seq.getItemCount(), 0); System.out.println("testRemove: PASS"); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } finally { pool.release(broker); } } public void testRename() { testAppend(); DBBroker broker = null; try { System.out.println("testUpdate() ...\n"); broker = pool.get(SecurityManager.SYSTEM_USER); XQuery xquery = broker.getXQueryService(); String query = "for $prod in //product return\n" + " update rename $prod/description as 'desc'\n"; Sequence seq = xquery.execute(query, null, AccessContext.TEST); seq = xquery.execute("//product/desc", null, AccessContext.TEST); assertEquals(seq.getItemCount(), ITEMS_TO_APPEND); query = "for $prod in //product return\n" + " update rename $prod/@num as 'count'\n"; seq = xquery.execute(query, null, AccessContext.TEST); seq = xquery.execute("//product/@count", null, AccessContext.TEST); assertEquals(seq.getItemCount(), ITEMS_TO_APPEND); System.out.println("testUpdate: PASS"); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } finally { pool.release(broker); } } public void testReplace() { testAppend(); DBBroker broker = null; try { System.out.println("testReplace() ...\n"); broker = pool.get(SecurityManager.SYSTEM_USER); XQuery xquery = broker.getXQueryService(); String query = "for $prod in //product return\n" + " update replace $prod/description with <desc>An updated description.</desc>\n"; Sequence seq = xquery.execute(query, null, AccessContext.TEST); seq = xquery.execute("//product/desc", null, AccessContext.TEST); assertEquals(seq.getItemCount(), ITEMS_TO_APPEND); query = "for $prod in //product return\n" + " update replace $prod/@num with '1'\n"; seq = xquery.execute(query, null, AccessContext.TEST); seq = xquery.execute("//product/@num", null, AccessContext.TEST); assertEquals(seq.getItemCount(), ITEMS_TO_APPEND); query = "for $prod in //product return\n" + " update replace $prod/desc/text() with 'A new update'\n"; seq = xquery.execute(query, null, AccessContext.TEST); seq = xquery.execute("//product[starts-with(desc, 'A new')]", null, AccessContext.TEST); assertEquals(seq.getItemCount(), ITEMS_TO_APPEND); System.out.println("testUpdate: PASS"); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } finally { pool.release(broker); } } public void testAttrUpdate() { DBBroker broker = null; try { System.out.println("testAttrUpdate() ...\n"); broker = pool.get(SecurityManager.SYSTEM_USER); store(broker, "test.xml", UPDATE_XML); String query = "let $progress := /progress\n" + "for $i in 1 to 100\n" + "let $done := $progress/@done\n" + "return (\n" + " update value $done with xs:int($done + 1),\n" + " xs:int(/progress/@done)\n" + ")"; XQuery xquery = broker.getXQueryService(); Sequence result = xquery.execute(query, null, AccessContext.TEST); System.out.println("testAttrUpdate(): PASSED\n"); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } finally { pool.release(broker); } } public void testAppendCDATA() { DBBroker broker = null; try { System.out.println("testAppendCDATA() ...\n"); broker = pool.get(SecurityManager.SYSTEM_USER); XQuery xquery = broker.getXQueryService(); String query = " declare variable $i external;\n" + " update insert\n" + " <product>\n" + " <description><![CDATA[me & you <>]]></description>\n" + " </product>\n" + " into /products"; XQueryContext context = xquery.newContext(AccessContext.TEST); CompiledXQuery compiled = xquery.compile(context, query); for (int i = 0; i < ITEMS_TO_APPEND; i++) { xquery.execute(compiled, null); } Sequence seq = xquery.execute("/products", null, AccessContext.TEST); assertEquals(seq.getItemCount(), 1); Serializer serializer = broker.getSerializer(); System.out.println(serializer.serialize((NodeValue) seq.itemAt(0))); seq = xquery.execute("//product", null, AccessContext.TEST); assertEquals(ITEMS_TO_APPEND, seq.getItemCount()); System.out.println("testAppendCDATA: PASS"); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } finally { pool.release(broker); } } public void bugtestInsertAttribDoc_1730726() { DBBroker broker = null; try { System.out.println(this.getName()+" ...\n"); broker = pool.get(SecurityManager.SYSTEM_USER); String query = "declare namespace xmldb = \"http://exist-db.org/xquery/xmldb\"; "+ "let $uri := xmldb:store(\"/db\", \"insertAttribDoc.xml\", <C/>) "+ "let $node := doc($uri)/element() "+ "let $attrib := <Value f=\"ATTRIB VALUE\"/>/@* "+ "return update insert $attrib into $node"; XQuery xquery = broker.getXQueryService(); Sequence result = xquery.execute(query, null, AccessContext.TEST); System.out.println(this.getName()+"(): PASSED\n"); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } finally { pool.release(broker); } } protected void setUp() throws Exception { this.pool = startDB(); DBBroker broker = null; try { broker = pool.get(SecurityManager.SYSTEM_USER); store(broker, "test.xml", TEST_XML); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } finally { pool.release(broker); } } private void store(DBBroker broker, String docName, String data) throws PermissionDeniedException, EXistException, TriggerException, SAXException, LockException, TransactionException { TransactionManager mgr = pool.getTransactionManager(); Txn transaction = mgr.beginTransaction(); System.out.println("Transaction started ..."); try { Collection root = broker.getOrCreateCollection(transaction, TEST_COLLECTION); broker.saveCollection(transaction, root); IndexInfo info = root.validateXMLResource(transaction, broker, XmldbURI.create(docName), data); //TODO : unlock the collection here ? root.store(transaction, broker, info, data, false); mgr.commit(transaction); DocumentImpl doc = root.getDocument(broker, XmldbURI.create(docName)); broker.getSerializer().serialize(doc); } catch (IOException e) { mgr.abort(transaction); fail(); } } protected BrokerPool startDB() { String home, file = "conf.xml"; home = System.getProperty("exist.home"); if (home == null) home = System.getProperty("user.dir"); try { Configuration config = new Configuration(file, home); BrokerPool.configure(1, 5, config); return BrokerPool.getInstance(); } catch (Exception e) { fail(e.getMessage()); } return null; } protected void tearDown() { pool = null; try { BrokerPool.stopAll(false); } catch (Exception e) { fail(e.getMessage()); } } }
package sk.fiit.dps.team11; import java.util.concurrent.ScheduledExecutorService; import java.util.stream.Stream; import javax.inject.Singleton; import org.apache.activemq.broker.BrokerService; import org.glassfish.hk2.api.InjectionResolver; import org.glassfish.hk2.api.TypeLiteral; import org.glassfish.hk2.utilities.binding.AbstractBinder; import org.glassfish.jersey.server.spi.internal.ValueFactoryProvider; import org.glassfish.jersey.servlet.ServletContainer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.health.HealthCheck; import com.kjetland.dropwizard.activemq.ActiveMQBundle; import io.dropwizard.Application; import io.dropwizard.configuration.EnvironmentVariableSubstitutor; import io.dropwizard.configuration.SubstitutingSourceProvider; import io.dropwizard.setup.Bootstrap; import io.dropwizard.setup.Environment; import sk.fiit.dps.team11.annotations.MQSender; import sk.fiit.dps.team11.config.TopConfiguration; import sk.fiit.dps.team11.core.DatabaseAdapter; import sk.fiit.dps.team11.core.MQ; import sk.fiit.dps.team11.core.RequestStates; import sk.fiit.dps.team11.core.Topology; import sk.fiit.dps.team11.core.VersionResolution; import sk.fiit.dps.team11.providers.ActiveMQSenderFactoryProvider; import sk.fiit.dps.team11.providers.InjectManager; import sk.fiit.dps.team11.providers.RuntimeExceptionMapper; import sk.fiit.dps.team11.resources.CheckConnectivityResource; import sk.fiit.dps.team11.resources.StorageResource; import sk.fiit.dps.team11.workers.DataManipulationWorker; import sk.fiit.dps.team11.workers.ReplicaFinderWorker; import sk.fiit.dps.team11.workers.ReplicationWorker; import sk.fiit.dps.team11.workers.TimeoutCheckWorker; import sk.fiit.dps.team11.workers.WrappedMethodWorker; public class KeyValueStoreService extends Application<TopConfiguration> { private static final Logger LOGGER = LoggerFactory.getLogger(KeyValueStoreService.class); private ActiveMQBundle activeMQBundle; public static void main(String[] args) throws Exception { new KeyValueStoreService().run(args); } @Override public void initialize(Bootstrap<TopConfiguration> bootstrap) { bootstrap.setConfigurationSourceProvider(new SubstitutingSourceProvider( bootstrap.getConfigurationSourceProvider(), new EnvironmentVariableSubstitutor(false))); BrokerService brokerService = new BrokerService(); try { brokerService.addConnector("tcp://localhost:61616"); brokerService.setBrokerName("local-mq"); brokerService.setPersistent(false); brokerService.start(); } catch (Exception e) { LOGGER.error("Couldn't initialize Message queue"); System.exit(1); } this.activeMQBundle = new ActiveMQBundle(); bootstrap.addBundle(activeMQBundle); } @Override public void run(final TopConfiguration configuration, Environment environment) { environment.healthChecks().register("base-app", new HealthCheck() { @Override protected Result check() throws Exception { return Result.healthy(); } }); MetricRegistry metrics = environment.metrics(); InjectManager injectManager = new InjectManager(); environment.lifecycle().addServerLifecycleListener(server -> { injectManager.injectLocator(((ServletContainer) environment.getJerseyServletContainer()) .getApplicationHandler().getServiceLocator()); }); // Core objects DatabaseAdapter db = new DatabaseAdapter(); environment.lifecycle().manage(db); ScheduledExecutorService execService = environment.lifecycle().scheduledExecutorService("sch-thread-pool-%d") .threads(configuration.getParallelism().getNumScheduledThreads()) .build(); // Injections environment.jersey().register(new AbstractBinder() { @Override protected void configure() { bind(configuration).to(TopConfiguration.class); bind(activeMQBundle).to(ActiveMQBundle.class); bind(metrics).to(MetricRegistry.class); bind(db).to(DatabaseAdapter.class); bind(MQ.class).to(MQ.class).in(Singleton.class); bind(RequestStates.class).to(RequestStates.class).in(Singleton.class); bind(execService).to(ScheduledExecutorService.class); bind(Topology.class).to(Topology.class).in(Singleton.class); bind(injectManager).to(InjectManager.class); bind(VersionResolution.class).to(VersionResolution.class).in(Singleton.class); bind(ActiveMQSenderFactoryProvider.class).to(ValueFactoryProvider.class).in(Singleton.class); bind(ActiveMQSenderFactoryProvider.InjectionResolver.class) .to(new TypeLiteral<InjectionResolver<MQSender>>() {}).in(Singleton.class); } }); // Providers, handlers, mappers environment.jersey().register(RuntimeExceptionMapper.class); // Resources environment.jersey().register(StorageResource.class); environment.jersey().register(CheckConnectivityResource.class); // Queue workers Stream<Object> workers = Stream.of(new DataManipulationWorker(), new ReplicaFinderWorker(), new ReplicationWorker(), new TimeoutCheckWorker()); workers .map(worker -> injectManager.register(worker)) .flatMap(worker -> WrappedMethodWorker.scan(worker).stream()) .forEach(wrappedWorker -> wrappedWorker.register(activeMQBundle)); } }
package traffic.model; import static org.junit.Assert.*; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.List; import org.jdom.JDOMException; import org.junit.Test; import traffic.graph.Graph; import traffic.graph.GraphNode; import traffic.strategy.LookaheadShortestPathVehicleStrategy; import traffic.strategy.QuadraticSpeedStrategy; /** * @author Jochen Wuttke - wuttkej@gmail.com * */ public class SimulationXMLReaderTest { @Test (expected=ConfigurationException.class) public void testFileNotFound() throws JDOMException, IOException, ConfigurationException { SimulationXMLReader.buildSimulator( new File("bad config") ); } @Test public void testStart() throws JDOMException, IOException, ConfigurationException { List<Vehicle> cars = (List<Vehicle>)SimulationXMLReader.buildSimulator( new File("resources/test/config.xml" )).getAgents(Vehicle.class); assertEquals(cars.get(0).getCurrentPosition().getID(), 0); assertEquals(cars.get(1).getCurrentPosition().getID(), 4); assertEquals(cars.get(2).getCurrentPosition().getID(), 3); assertEquals(cars.get(3).getCurrentPosition().getID(), 8); assertEquals(cars.get(4).getCurrentPosition().getID(), 3); } @Test public void testVehicleNum() throws JDOMException, IOException, ConfigurationException { List<Vehicle> cars = SimulationXMLReader.buildSimulator( new File("resources/test/config.xml" )).getAgents(Vehicle.class); assertEquals(cars.get(0).getID(), 0); assertEquals(cars.get(1).getID(), 1); assertEquals(cars.get(2).getID(), 2); assertEquals(cars.get(3).getID(), 3); assertEquals(cars.get(4).getID(), 4); } @Test public void invalidVehicleStrategyDefaultsCorrectly() throws JDOMException, IOException, ConfigurationException { List<Vehicle> cars = SimulationXMLReader.buildSimulator( new File("resources/test/invalid-strategy.xml" )).getAgents(Vehicle.class); assertEquals( LookaheadShortestPathVehicleStrategy.class, cars.get(1).getStrategy().getClass() ); } @Test(expected=ConfigurationException.class) public void invalidDefaultVehicleStrategyThrows() throws JDOMException, IOException, ConfigurationException { SimulationXMLReader.buildSimulator( new File("resources/test/illegal-default-car-strategy.xml" )).getAgents(Vehicle.class); fail( "This should throw a meaningful exception to be handled by main()" ); } @Test(expected=ConfigurationException.class) public void noVehicleThrows() throws JDOMException, IOException, ConfigurationException { SimulationXMLReader.buildSimulator( new File("resources/test/no-car.xml" )).getAgents(Vehicle.class); fail( "This should throw a meaningful exception to be handled by main()" ); } @Test(expected=ConfigurationException.class) public void noVehiclesThrows() throws JDOMException, IOException, ConfigurationException { SimulationXMLReader.buildSimulator( new File("resources/test/no-cars.xml" )).getAgents(Vehicle.class); fail( "This should throw a meaningful exception to be handled by main()" ); } @Test public void invalidStartEndIsIgnored() throws JDOMException, IOException, ConfigurationException { List<Vehicle> cars = SimulationXMLReader.buildSimulator( new File("resources/test/invalid-start.xml" )).getAgents(Vehicle.class); assertEquals( 3, cars.size() ); assertEquals( 0, cars.get(0).getID() ); assertEquals( 3, cars.get(1).getID() ); assertEquals( 4, cars.get(2).getID() ); } @Test public void testStrategies() throws FileNotFoundException, ConfigurationException { TrafficSimulator sim = SimulationXMLReader.buildSimulator( new File("resources/test/config.xml" ) ); Graph g = sim.getGraph(); assertEquals(1, g.getNode(6).getCurrentDelay()); g.addVehicleAtNode(sim.getVehicle(0), 6); g.addVehicleAtNode(sim.getVehicle(1), 6); assertEquals(3, g.getNode(6).getCurrentDelay()); //Tests Quadratic Speed Strategy assertEquals(1, g.getNode(1).getCurrentDelay()); g.addVehicleAtNode(sim.getVehicle(2), 1); g.addVehicleAtNode(sim.getVehicle(3), 1); assertEquals(3, g.getNode(1).getCurrentDelay() ); //Tests Linear Speed Strategy } @Test public void testNeighbors() throws FileNotFoundException, ConfigurationException { Graph g = SimulationXMLReader.buildSimulator( new File("resources/test/config.xml")).getGraph(); List<GraphNode> neighbors = g.getNodes().get(2).getNeighbors(); int first = neighbors.get(0).getID(); assertEquals(first, 4); int second = neighbors.get(1).getID(); assertEquals(second, 7); int third = neighbors.get(2).getID(); assertEquals(third, 9); } @Test public void emptyNeighborListIsNotIgnored() throws FileNotFoundException, ConfigurationException { Graph g = SimulationXMLReader.buildSimulator( new File("resources/test/unconnected-node.xml")).getGraph(); assertEquals( g.getNodes().size(), 10); } @Test(expected=ConfigurationException.class) public void noNodesThrows() throws FileNotFoundException, ConfigurationException { SimulationXMLReader.buildSimulator(new File("resources/test/no-nodes.xml")).getGraph(); fail( "This should throw a meaningful exception to be handled by main()" ); } @Test(expected=ConfigurationException.class) public void oneNodesIsOK() throws FileNotFoundException, ConfigurationException { SimulationXMLReader.buildSimulator(new File("resources/test/one-node.xml")).getGraph(); fail( "This should throw a meaningful exception to be handled by main()" ); } @Test(expected=ConfigurationException.class) public void noGraphThrows() throws FileNotFoundException, ConfigurationException { SimulationXMLReader.buildSimulator( new File("resources/test/no-graph.xml" )).getGraph(); fail( "This should throw a meaningful exception to be handled by main()" ); } @Test public void invalidNeighborIsIgnored() throws FileNotFoundException, ConfigurationException { Graph g = SimulationXMLReader.buildSimulator( new File("resources/test/invalid-neighbor.xml")).getGraph(); List<GraphNode> neighbors = g.getNode( 0 ).getNeighbors(); assertEquals(1, neighbors.size() ); assertEquals(4, neighbors.get(0).getID() ); neighbors = g.getNode( 1 ).getNeighbors(); assertTrue( neighbors.isEmpty() ); } @Test public void invalidSpeedStrategyDefaultsCorrectly() throws FileNotFoundException, ConfigurationException { Graph g = SimulationXMLReader.buildSimulator( new File("resources/test/invalid-strategy2.xml")).getGraph(); assertEquals( QuadraticSpeedStrategy.class, g.getNodes().get(1).getSpeedStrategy().getClass() ); } @Test public void loadsAutoGeneratedConfig() throws FileNotFoundException, ConfigurationException { SimulationXMLReader.buildSimulator( new File("resources/test/auto-generated.xml")).getGraph(); //this passes when no unexpected exceptions are thrown } @Test public void setsDelayCorrectly() throws FileNotFoundException, ConfigurationException { Graph g = SimulationXMLReader.buildSimulator( new File("resources/test/config-weights.xml")).getGraph(); assertEquals( 7, g.getNodes().get(1).getDelay() ); } @Test public void setsDelayCorrectly2() throws FileNotFoundException, ConfigurationException { Graph g = SimulationXMLReader.buildSimulator( new File("resources/test/shortest-path-test-weights.xml")).getGraph(); assertEquals( 4, g.getNodes().get(3).getDelay() ); } @Test (expected=ConfigurationException.class) public void invalidDelayDefaults() throws FileNotFoundException, ConfigurationException { SimulationXMLReader.buildSimulator( new File("resources/test/config-weights-invalid.xml")).getGraph(); fail( "This should throw a meaningful exception to be handled by main()" ); } @Test (expected=ConfigurationException.class) public void negativeDelayDefaults() throws FileNotFoundException, ConfigurationException { SimulationXMLReader.buildSimulator( new File("resources/test/config-weights-invalid2.xml")).getGraph(); fail( "This should throw a meaningful exception to be handled by main()" ); } @Test public void nodesHaveAllVehicles() throws FileNotFoundException, ConfigurationException { Graph g = SimulationXMLReader.buildSimulator( new File("resources/test/shortest-path-test-weights.xml")).getGraph(); assertEquals( 3, g.getNode(2).numVehiclesAtNode() ); } }
package com.intellij.openapi.roots.ui.configuration; import com.intellij.ide.util.treeView.AbstractTreeBuilder; import com.intellij.ide.util.treeView.AbstractTreeStructure; import com.intellij.ide.util.treeView.NodeDescriptor; import com.intellij.idea.ActionsBundle; import com.intellij.openapi.actionSystem.DataProvider; import com.intellij.openapi.actionSystem.DefaultActionGroup; import com.intellij.openapi.actionSystem.Presentation; import com.intellij.openapi.actionSystem.ex.CustomComponentAction; import com.intellij.openapi.fileChooser.FileChooserDescriptor; import com.intellij.openapi.fileChooser.FileSystemTree; import com.intellij.openapi.fileChooser.actions.NewFolderAction; import com.intellij.openapi.fileChooser.ex.FileSystemTreeImpl; import com.intellij.openapi.fileChooser.impl.FileTreeBuilder; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectBundle; import com.intellij.openapi.roots.SourceFolder; import com.intellij.openapi.roots.ui.configuration.actions.IconWithTextAction; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.IconLoader; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.ui.ScrollPaneFactory; import com.intellij.ui.TreeSpeedSearch; import com.intellij.ui.TreeToolTipHandler; import com.intellij.ui.roots.ToolbarPanel; import com.intellij.ui.treeStructure.Tree; import com.intellij.util.ui.tree.TreeUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.tree.*; import java.awt.*; import java.io.File; import java.util.Comparator; public abstract class ContentEntryTreeEditor { private final Project myProject; protected Tree myTree; private FileSystemTreeImpl myFileSystemTree; private final JPanel myTreePanel; private final DefaultMutableTreeNode EMPTY_TREE_ROOT = new DefaultMutableTreeNode(ProjectBundle.message("module.paths.empty.node")); protected DefaultActionGroup myEditingActionsGroup; private ContentEntryEditor myContentEntryEditor; private final MyContentEntryEditorListener myContentEntryEditorListener = new MyContentEntryEditorListener(); private final FileChooserDescriptor myDescriptor; public ContentEntryTreeEditor(Project project) { myProject = project; myTree = new Tree(); myTree.setRootVisible(true); myTree.setShowsRootHandles(true); myEditingActionsGroup = new DefaultActionGroup(); TreeToolTipHandler.install(myTree); TreeUtil.installActions(myTree); new TreeSpeedSearch(myTree); myTreePanel = new MyPanel(new BorderLayout()); final JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(myTree); myTreePanel.add(new ToolbarPanel(scrollPane, myEditingActionsGroup), BorderLayout.CENTER); myTreePanel.setVisible(false); myDescriptor = new FileChooserDescriptor(false, true, false, false, false, true); myDescriptor.setShowFileSystemRoots(false); } protected void createEditingActions() { } protected TreeCellRenderer getContentEntryCellRenderer() { return new ContentEntryTreeCellRenderer(this); } /** * @param contentEntryEditor : null means to clear the editor */ public void setContentEntryEditor(ContentEntryEditor contentEntryEditor) { if (myContentEntryEditor != null && myContentEntryEditor.equals(contentEntryEditor)) { return; } if (myFileSystemTree != null) { Disposer.dispose(myFileSystemTree); myFileSystemTree = null; } if (myContentEntryEditor != null) { myContentEntryEditor.removeContentEntryEditorListener(myContentEntryEditorListener); myContentEntryEditor = null; } if (contentEntryEditor == null) { ((DefaultTreeModel)myTree.getModel()).setRoot(EMPTY_TREE_ROOT); myTreePanel.setVisible(false); if (myFileSystemTree != null) { Disposer.dispose(myFileSystemTree); } return; } myTreePanel.setVisible(true); myContentEntryEditor = contentEntryEditor; myContentEntryEditor.addContentEntryEditorListener(myContentEntryEditorListener); final VirtualFile file = contentEntryEditor.getContentEntry().getFile(); myDescriptor.setRoot(file); if (file != null) { myDescriptor.setTitle(file.getPresentableUrl()); } else { final String url = contentEntryEditor.getContentEntry().getUrl(); myDescriptor.setTitle(VirtualFileManager.extractPath(url).replace('/', File.separatorChar)); } final Runnable init = new Runnable() { public void run() { myFileSystemTree.updateTree(); if (file != null) { select(file); } } }; myFileSystemTree = new FileSystemTreeImpl(myProject, myDescriptor, myTree, getContentEntryCellRenderer(), init) { protected AbstractTreeBuilder createTreeBuilder(JTree tree, DefaultTreeModel treeModel, AbstractTreeStructure treeStructure, Comparator<NodeDescriptor> comparator, FileChooserDescriptor descriptor, final Runnable onInitialized) { return new MyFileTreeBuilder(tree, treeModel, treeStructure, comparator, descriptor, onInitialized); } }; myFileSystemTree.showHiddens(true); Disposer.register(myProject, myFileSystemTree); final NewFolderAction newFolderAction = new MyNewFolderAction(); DefaultActionGroup mousePopupGroup = new DefaultActionGroup(); mousePopupGroup.add(myEditingActionsGroup); mousePopupGroup.addSeparator(); mousePopupGroup.add(newFolderAction); myFileSystemTree.registerMouseListener(mousePopupGroup); } public ContentEntryEditor getContentEntryEditor() { return myContentEntryEditor; } public JComponent createComponent() { createEditingActions(); return myTreePanel; } public void select(VirtualFile file) { if (myFileSystemTree != null) { myFileSystemTree.select(file); } } public void requestFocus() { myTree.requestFocus(); } public void update() { if (myFileSystemTree != null) { myFileSystemTree.updateTree(); final DefaultTreeModel model = (DefaultTreeModel)myTree.getModel(); final int visibleRowCount = myTree.getVisibleRowCount(); for (int row = 0; row < visibleRowCount; row++) { final TreePath pathForRow = myTree.getPathForRow(row); if (pathForRow != null) { final TreeNode node = (TreeNode)pathForRow.getLastPathComponent(); if (node != null) { model.nodeChanged(node); } } } } } private class MyContentEntryEditorListener extends ContentEntryEditorListenerAdapter { public void sourceFolderAdded(ContentEntryEditor editor, SourceFolder folder) { update(); } public void sourceFolderRemoved(ContentEntryEditor editor, VirtualFile file, boolean isTestSource) { update(); } public void folderExcluded(ContentEntryEditor editor, VirtualFile file) { update(); } public void folderIncluded(ContentEntryEditor editor, VirtualFile file) { update(); } public void packagePrefixSet(ContentEntryEditor editor, SourceFolder folder) { update(); } } private static class MyNewFolderAction extends NewFolderAction implements CustomComponentAction { private MyNewFolderAction() { super(ActionsBundle.message("action.FileChooser.NewFolder.text"), ActionsBundle.message("action.FileChooser.NewFolder.description"), IconLoader.getIcon("/actions/newFolder.png")); } public JComponent createCustomComponent(Presentation presentation) { return IconWithTextAction.createCustomComponentImpl(this, presentation); } } private static class MyFileTreeBuilder extends FileTreeBuilder { public MyFileTreeBuilder(JTree tree, DefaultTreeModel treeModel, AbstractTreeStructure treeStructure, Comparator<NodeDescriptor> comparator, FileChooserDescriptor descriptor, @Nullable Runnable onInitialized) { super(tree, treeModel, treeStructure, comparator, descriptor, onInitialized); } protected boolean isAlwaysShowPlus(NodeDescriptor nodeDescriptor) { return false; // need this in order to not show plus for empty directories } } private class MyPanel extends JPanel implements DataProvider { private MyPanel(final LayoutManager layout) { super(layout); } @Nullable public Object getData(@NonNls final String dataId) { if (dataId.equals(FileSystemTree.DATA_KEY.getName())) { return myFileSystemTree; } return null; } } }
package org.languagetool.rules.patterns; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.languagetool.Language; import static org.junit.Assert.fail; public final class PatternTestTools { // These characters should not be present in token values as they split tokens in all languages. private static final Pattern TOKEN_SEPARATOR_PATTERN = Pattern.compile("[ .,:;…!?(){}<>«»\"]"); private static final Pattern PROBABLE_PATTERN = Pattern.compile("(\\\\[dDsSwW])|.*([^*]\\*|[.+?{}()|\\[\\]].*|\\\\d).*"); // Polish POS tags use dots, so do not consider the presence of a dot // as indicating a probable regular expression. private static final Pattern PROBABLE_PATTERN_PL_POS = Pattern.compile("(\\\\[dDsSwW])|.*([^*]\\*|[+?{}()|\\[\\]].*|\\\\d).*"); private static final Pattern CHAR_SET_PATTERN = Pattern.compile("\\[^?([^\\]]+)\\]"); private static final Pattern STRICT_CHAR_SET_PATTERN = Pattern.compile("(\\(\\?-i\\))?.*(?<!\\\\)\\[^?([^\\]]+)\\]"); /* * These strings are not be recognized as a regular expression */ private static final Set<String> NO_REGEXP = new HashSet<>(Arrays.asList( "PRP:LOK+TMP+MOD:DAT+AKK" )); private PatternTestTools() { } public static void failIfWhitespaceInToken(List<PatternToken> patternTokens, AbstractPatternRule rule, Language lang) { if (patternTokens != null) { for (PatternToken token : patternTokens) { if (token.getString() != null && token.getString().matches(".*\\s.*")) { fail("Whitespace found in token '" + token.getString() + "' of rule " + rule.getFullId() + " (language " + lang.getShortCodeWithCountryAndVariant() + "): " + "Using whitespace in a token will not work, as text gets split at whitespace. " + "Use a new <token> element instead."); } } } } // TODO: probably this would be more useful for exceptions // instead of adding next methods to PatternRule // we can probably validate using XSD and specify regexes straight there public static void warnIfRegexpSyntaxNotKosher(List<PatternToken> patternTokens, String ruleId, String ruleSubId, Language lang) { if (patternTokens == null) { // for <regexp> return; } int i = 0; for (PatternToken pToken : patternTokens) { i++; if (pToken.isReferenceElement()) { continue; } // Check whether token value is consistent with regexp="..." warnIfElementNotKosher( pToken.getString(), pToken.isRegularExpression(), pToken.isCaseSensitive(), pToken.getNegation(), pToken.isInflected(), false, // not a POS lang, ruleId + "[" + ruleSubId + "]", i); // Check postag="..." is consistent with postag_regexp="..." warnIfElementNotKosher( pToken.getPOStag() == null ? "" : pToken.getPOStag(), pToken.isPOStagRegularExpression(), pToken.isCaseSensitive(), pToken.getPOSNegation(), false, true, // a POS. lang, ruleId + "[" + ruleSubId + "] (POS tag)", i); List<PatternToken> exceptionPatternTokens = new ArrayList<>(); if (pToken.getExceptionList() != null) { for (PatternToken exception: pToken.getExceptionList()) { // Detect useless exception or missing skip="...". I.e. things like this: // <token postag="..."><exception scope="next">foo</exception</token> // We now allow scope="next" without skip="..." if (exception.hasNextException()) continue; // if (exception.hasNextException() && pToken.getSkipNext() == 0) { // System.err.println("The " + lang + " rule: " // + ruleId + "[" + ruleSubId + "]" // + " (exception in token [" + i + "])" // + " has no skip=\"...\" and yet contains scope=\"next\"" // + " so the exception never applies." // + " Did you forget skip=\"...\"?"); // Detect exception that can't possibly be matched. if ( !pToken.getString().isEmpty() && !exception.getString().isEmpty() && !pToken.getNegation() && !pToken.isInflected() && !exception.getNegation() && !exception.isInflected() && pToken.getSkipNext() == 0 && pToken.isCaseSensitive() == exception.isCaseSensitive()) { if (exception.isRegularExpression()) { if (pToken.isRegularExpression()) { // Both exception and token are regexp. In that case, we only // check sanity when exception regexp is a simple disjunction as // in this example: // <token regexp="yes">...some arbitrary regexp... // <exception regexp="yes">foo|bar|xxx</exception> // </token> // All the words foo, bar, xxx should match the token regexp, or else they // are useless. if (exception.getString().indexOf('|') >= 0) { String[] alt = exception.getString().split("\\|"); for (String part : alt) { if (exception.getString().indexOf('(') >= 0) { break; } if (part.matches("[^.*?{}\\[\\]]+")) { if (!part.matches("(?i)" + pToken.getString())) { System.err.println("The " + lang + " rule: " + ruleId + "[" + ruleSubId + "]" + " has exception regexp [" + exception.getString() + "] which contains disjunction part [" + part + "] which seems useless since it does not match " + "the regexp of token word [" + i + "] " + "[" + pToken.getString() + "], or did you forget skip=\"...\" or scope=\"previous\"?"); } } } } } else { // It does not make sense to to have a regexp exception // with a token which is not a regexp!? // Example <token>foo<exception regexp="xxx|yyy"/></token> System.err.println("The " + lang + " rule: " + ruleId + "[" + ruleSubId + "]" + " has exception regexp [" + exception.getString() + "] in token word [" + i +"] [" + pToken.getString() + "] which seems useless, or " + "did you forget skip=\"...\" or scope=\"previous\"?"); } } else { if (pToken.isRegularExpression()) { // An exception that cannot match a token regexp is useless. // Example: <token regexp="yes">foo|bar<exception>xxx</exception></token> // Here exception word xxx cannot possibly match the regexp "foo|bar". if (!exception.getString().matches( (exception.isCaseSensitive() ? "" : "(?i)") + pToken.getString())) { System.err.println("The " + lang + " rule: " + ruleId + "[" + ruleSubId + "] has exception word [" + exception.getString() + "] which cannot match the " + "regexp token [" + i + "] [" + pToken.getString() + "] so exception seems useless, " + "or did you forget skip=\"...\" or scope=\"previous\"?"); } } else { // An exception that cannot match a token string is useless, // Example: <token>foo<exception>bar</exception></token> System.err.println("The " + lang + " rule: " + ruleId + "[" + ruleSubId + "] has exception word [" + exception.getString() + "] in token word [" + i + "] [" + pToken.getString() + "] which seems useless, " + "or did you forget skip=\"...\" or scope=\"previous\"?"); } } } // Check whether exception value is consistent with regexp="..." // Don't check string "." since it is sometimes used as a regexp // and sometimes used as non regexp. if (!exception.getString().equals(".")) { warnIfElementNotKosher( exception.getString(), exception.isRegularExpression(), exception.isCaseSensitive(), exception.getNegation(), exception.isInflected(), false, // not a POS lang, ruleId + "[" + ruleSubId+ "] (exception in token [" + i + "])", i); } // Check postag="..." of exception is consistent with postag_regexp="..." warnIfElementNotKosher( exception.getPOStag() == null ? "" : exception.getPOStag(), exception.isPOStagRegularExpression(), exception.isCaseSensitive(), exception.getPOSNegation(), false, true, // a POS lang, ruleId + "[" + ruleSubId + "] (exception in POS tag of token [" + i + "])", i); // Search for duplicate exceptions (which are useless). // Since there are 2 nested loops on the list of exceptions, // this has thus a O(n^2) complexity, where n is the number // of exceptions in a token. But n is small and it is also // for testing only so that's OK. for (PatternToken otherException: exceptionPatternTokens) { if (equalException(exception, otherException)) { System.err.println("The " + lang + " rule: " + ruleId + "[" + ruleSubId + "]" + " in token [" + i + "]" + " contains duplicate exceptions with" + " string=[" + exception.getString() + "]" + " POS tag=[" + exception.getPOStag() + "]" + " negate=[" + exception.getNegation() + "]" + " POS negate=[" + exception.getPOSNegation() + "]"); break; } } exceptionPatternTokens.add(exception); } } } } /** * Predicate to check whether two exceptions are identical or whether * one exception always implies the other. * * Example #1, useless identical exceptions: * <exception>xx</exception><exception>xx</exception> * * Example #2, first exception implies the second exception: * <exception>xx</exception><exception postag="A">xx</exception> */ private static boolean equalException(PatternToken exception1, PatternToken exception2) { String string1 = exception1.getString() == null ? "" : exception1.getString(); String string2 = exception2.getString() == null ? "" : exception2.getString(); if (!exception1.isCaseSensitive() || !exception2.isCaseSensitive()) { // String comparison is done case insensitive if one or both strings // are case insensitive, because the case insensitive one would imply // the case sensitive one. string1 = string1.toLowerCase(); string2 = string2.toLowerCase(); } if (!string1.isEmpty() && !string2.isEmpty()) { if (!string1.equals(string2)) { return false; } } String posTag1 = exception1.getPOStag() == null ? "" : exception1.getPOStag(); String posTag2 = exception2.getPOStag() == null ? "" : exception2.getPOStag(); if (!posTag1.isEmpty() && !posTag2.isEmpty()) { if (!posTag1.equals(posTag2)) { return false; } } if ( string1.isEmpty() != string2.isEmpty() && posTag1.isEmpty() != posTag2.isEmpty()) { return false; } // We should not need to check for: // - isCaseSensitive() since an exception without isCaseSensitive // imply the one with isCaseSensitive. // - isInflected() since an exception with inflected="yes" // implies the one without inflected="yes" if they have // identical strings. // without inflected="yes". // - isRegularExpression() since a given string is either // a regexp or not. return exception1.getNegation() == exception2.getNegation() && exception1.getPOSNegation() == exception2.getPOSNegation() && exception1.hasNextException() == exception2.hasNextException() && exception1.hasPreviousException() == exception2.hasPreviousException(); } private static void warnIfElementNotKosher( String stringValue, boolean isRegularExpression, boolean isCaseSensitive, boolean isNegated, boolean isInflected, boolean isPos, Language lang, String ruleId, int tokenIndex) { // Check that the string value does not contain token separator. if (!isPos && !isRegularExpression && stringValue.length() > 1) { // Example: <token>foo bar</token> can't be valid because // token value contains a space which is a token separator. if (TOKEN_SEPARATOR_PATTERN.matcher(stringValue).find()) { System.err.println("The " + lang + " rule: " + ruleId + ", token [" + tokenIndex + "], contains " + "\"" + stringValue + "\" that contains token separators, so can't possibly be matched."); } } // Use a different regexp to check for probable regexp in Polish POS tags // since Polish uses dot '.' in POS tags. So a dot does not indicate that // it's a probable regexp for Polish POS tags. Pattern regexPattern = (isPos && lang.getShortCode().equals("pl")) ? PROBABLE_PATTERN_PL_POS // Polish POS tag. : PROBABLE_PATTERN; // something else than Polish POS tag. if (!isRegularExpression && stringValue.length() > 1 && regexPattern.matcher(stringValue).find() && !NO_REGEXP.contains(stringValue)) { System.err.println("The " + lang + " rule: " + ruleId + ", token [" + tokenIndex + "], contains " + "\"" + stringValue + "\" that is not marked as regular expression but probably is one."); } if (isRegularExpression && stringValue.isEmpty()) { System.err.println("The " + lang + " rule: " + ruleId + ", token [" + tokenIndex + "], contains an empty string " + "\"" + stringValue + "\" that is marked as regular expression."); } else if (isRegularExpression && stringValue.length() > 1 && !regexPattern.matcher(stringValue).find()) { System.err.println("The " + lang + " rule: " + ruleId + ", token [" + tokenIndex + "], contains " + "\"" + stringValue + "\" that is marked as regular expression but probably is not one."); } if (isNegated && stringValue.isEmpty()) { System.err.println("The " + lang + " rule: " + ruleId + ", token [" + tokenIndex + "], marked as negated but is " + "empty so the negation is useless. Did you mix up " + "negate=\"yes\" and negate_pos=\"yes\"?"); } if (isInflected && stringValue.isEmpty()) { System.err.println("The " + lang + " rule: " + ruleId + ", token [" + tokenIndex + "], contains " + "\"" + stringValue + "\" that is marked as inflected but is empty, so the attribute is redundant."); } if (isRegularExpression && ".*".equals(stringValue)) { System.err.println("The " + lang + " rule: " + ruleId + ", token [" + tokenIndex + "], marked as regular expression contains " + "regular expression \".*\" which is useless: " + "(use an empty string without regexp=\"yes\" such as <token/>)"); } if (isRegularExpression) { Matcher matcher = CHAR_SET_PATTERN.matcher(stringValue); if (matcher.find()) { Matcher strictMatcher = STRICT_CHAR_SET_PATTERN.matcher(stringValue); // for performance reasons, only now use the strict pattern if (strictMatcher.find()) { // Remove things like \p{Punct} which are irrelevant here. String s = strictMatcher.group(2).replaceAll("\\\\p\\{[^}]*\\}", ""); // case sensitive if pattern contains (?-i). if (s.indexOf('|') >= 0) { if (!(s.indexOf('|') >= 1 && s.charAt(s.indexOf('|') -1) == '\\')){ //don't warn if it's escaped System.err.println("The " + lang + " rule: " + ruleId + ", token [" + tokenIndex + "], contains | (pipe) in " + "regexp bracket expression [" + strictMatcher.group(2) + "] which is unlikely to be correct."); } } /* Disabled case insensitive check for now: it gives several errors * in German which are minor and debatable whether it adds value. boolean caseSensitive = matcher.group(1) != null || isCaseSensitive; if (!caseSensitive) { s = s.toLowerCase(); } */ char[] sorted = s.toCharArray(); // Sort characters in string, so finding duplicate characters can be done by // looking for identical adjacent characters. Arrays.sort(sorted); for (int i = 1; i < sorted.length; ++i) { char c = sorted[i]; if ("&\\-|".indexOf(c) < 0 && sorted[i - 1] == c) { System.err.println("The " + lang + " rule: " + ruleId + ", token [" + tokenIndex + "], contains " + "regexp part [" + strictMatcher.group(2) + "] which contains duplicated char [" + c + "]."); break; } } } } if (stringValue.contains("|")) { if (stringValue.contains("||") || stringValue.charAt(0) == '|' || stringValue.charAt(stringValue.length() - 1) == '|') { // Empty disjunctions in regular expression are most likely not intended. System.err.println("The " + lang + " rule: " + ruleId + ", token [" + tokenIndex + "], contains empty " + "disjunction | within " + "\"" + stringValue + "\"."); } String[] groups = stringValue.split("\\)|\\("); for (String group : groups) { String[] alt = group.split("\\|"); Set<String> partSet = new HashSet<>(); Set<String> partSetNoCase = new HashSet<>(); boolean hasSingleChar = false; boolean hasSingleDot = false; for (String part : alt) { if (part.length() == 1) { // If all alternatives in disjunction have one char, then // a dot . (any char) does not make sense since it would match // other characters. if (part.equals(".")) { hasSingleDot = true; } else { hasSingleChar = true; } } String partNoCase = isCaseSensitive ? part : part.toLowerCase(); if (partSetNoCase.contains(partNoCase)) { if (partSet.contains(part)) { // Duplicate disjunction parts "foo|foo". System.err.println("The " + lang + " rule: " + ruleId + ", token [" + tokenIndex + "], contains " + "duplicated disjunction part (" + part + ") within " + "\"" + stringValue + "\"."); } else { // Duplicate disjunction parts "Foo|foo" since element ignores case. System.err.println("The " + lang + " rule: " + ruleId + ", token [" + tokenIndex + "], contains duplicated " + "non case sensitive disjunction part (" + part + ") within " + "\"" + stringValue + "\". Did you " + "forget case_sensitive=\"yes\"?"); } } partSetNoCase.add(partNoCase); partSet.add(part); } if (hasSingleDot && hasSingleChar) { // This finds errors like this <token regexp="yes">.|;|:</token> // which should be <token regexp="yes">\.|;|:</token> or // even better <token regexp="yes">[.;:]</token> System.err.println("The " + lang + " rule: " + ruleId + ", token [" + tokenIndex + "], contains a single dot (matching any char) " + "so other single char disjunctions are useless within " + "\"" + stringValue + "\". Did you forget forget a backslash before the dot?"); } } } } } }
package org.collectionspace.chain.csp.persistence.services.vocab; import static org.junit.Assert.*; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.io.InputStream; import org.apache.commons.io.IOUtils; import org.collectionspace.bconfigutils.bootstrap.BootstrapConfigController; import org.collectionspace.chain.controller.ChainServlet; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.junit.BeforeClass; import org.junit.Test; import org.mortbay.jetty.HttpHeaders; import org.mortbay.jetty.testing.HttpTester; import org.mortbay.jetty.testing.ServletTester; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TestNameThroughWebapp { private static final Logger log=LoggerFactory.getLogger(TestNameThroughWebapp.class); private static String cookie; // XXX refactor protected InputStream getResource(String name) { String path=getClass().getPackage().getName().replaceAll("\\.","/")+"/"+name; return Thread.currentThread().getContextClassLoader().getResourceAsStream(path); } private static void login(ServletTester tester) throws IOException, Exception { HttpTester out=jettyDo(tester,"GET","/chain/login?userid=test@collectionspace.org&password=testtest",null); assertEquals(303,out.getStatus()); cookie=out.getHeader("Set-Cookie"); log.info("Got cookie "+cookie); } // XXX refactor private static HttpTester jettyDo(ServletTester tester,String method,String path,String data) throws IOException, Exception { HttpTester request = new HttpTester(); HttpTester response = new HttpTester(); request.setMethod(method); request.setHeader("Host","tester"); request.setURI(path); request.setVersion("HTTP/1.0"); if(data!=null) request.setContent(data); if(cookie!=null) request.addHeader(HttpHeaders.COOKIE,cookie); response.parse(tester.getResponses(request.generate())); return response; } // XXX refactor into other copy of this method private static ServletTester setupJetty() throws Exception { BootstrapConfigController config_controller=new BootstrapConfigController(null); config_controller.addSearchSuffix("test-config-loader2.xml"); config_controller.go(); String base=config_controller.getOption("services-url"); ServletTester tester=new ServletTester(); tester.setContextPath("/chain"); /* @Test public void testAuthoritiesList() throws Exception { ServletTester jetty=setupJetty(); HttpTester out=jettyDo(jetty,"GET","/chain/authorities/person",null); assertTrue(out.getStatus()<299); log.info(out.getContent()); JSONArray results=new JSONObject(out.getContent()).getJSONArray("items"); boolean found=false; for(int i=0;i<results.length();i++) { JSONObject entry=results.getJSONObject(i); if(entry.getString("displayName").toLowerCase().contains("achmed abdullah")) found=true; } //might be failing because of pagination assertTrue(found); } */ @Test public void testNamesSearch() throws Exception { ServletTester jetty=setupJetty(); //jettyDo(jetty,"GET","/chain/quick-reset",null); HttpTester out=jettyDo(jetty,"GET","/chain/vocabularies/person/search?query=Achmed+Abdullah",null); assertTrue(out.getStatus()<299); log.info(out.getContent()); JSONArray results=new JSONObject(out.getContent()).getJSONArray("results"); for(int i=0;i<results.length();i++) { JSONObject entry=results.getJSONObject(i); assertTrue(entry.getString("displayName").toLowerCase().contains("achmed abdullah")); assertEquals(entry.getString("number"),entry.getString("displayName")); assertTrue(entry.has("refid")); } } // XXX failing due to pagination - reinsert when pagination works /* @Test public void testNamesList() throws Exception { ServletTester jetty=setupJetty(); HttpTester out=jettyDo(jetty,"GET","/chain/vocabularies/person",null); assertTrue(out.getStatus()<299); log.info(out.getContent()); JSONArray results=new JSONObject(out.getContent()).getJSONArray("items"); boolean found=false; for(int i=0;i<results.length();i++) { JSONObject entry=results.getJSONObject(i); if(entry.getString("displayName").toLowerCase().contains("achmed abdullah")) found=true; } assertTrue(found); } */ @Test public void testNamesGet() throws Exception { ServletTester jetty=setupJetty(); HttpTester out=jettyDo(jetty,"GET","/chain/vocabularies/person/search?query=Achmed+Abdullah",null); assertTrue(out.getStatus()<299); log.info(out.getContent()); // Find candidate JSONArray results=new JSONObject(out.getContent()).getJSONArray("results"); assertEquals(1,results.length()); JSONObject entry=results.getJSONObject(0); String csid=entry.getString("csid"); out=jettyDo(jetty,"GET","/chain/vocabularies/person/"+csid,null); JSONObject fields=new JSONObject(out.getContent()).getJSONObject("fields"); log.info("JSON",fields); assertEquals(csid,fields.getString("csid")); assertEquals("Achmed Abdullah",fields.getString("displayName")); } @Test public void testNamesCreateUpdateDelete() throws Exception { ServletTester jetty=setupJetty(); // Create JSONObject data=new JSONObject("{'fields':{'displayName':'Fred Bloggs'}}"); HttpTester out=jettyDo(jetty,"POST","/chain/vocabularies/person/",data.toString()); assertTrue(out.getStatus()<300); String url=out.getHeader("Location"); // Read out=jettyDo(jetty,"GET","/chain/vocabularies"+url,null); assertTrue(out.getStatus()<299); data=new JSONObject(out.getContent()).getJSONObject("fields"); assertEquals(data.getString("csid"),url.split("/")[2]); assertEquals("Fred Bloggs",data.getString("displayName")); // Update data=new JSONObject("{'fields':{'displayName':'Owain Glyndwr'}}"); out=jettyDo(jetty,"PUT","/chain/vocabularies"+url,data.toString()); assertTrue(out.getStatus()<300); // Read out=jettyDo(jetty,"GET","/chain/vocabularies"+url,null); assertTrue(out.getStatus()<299); data=new JSONObject(out.getContent()).getJSONObject("fields"); assertEquals(data.getString("csid"),url.split("/")[2]); assertEquals("Owain Glyndwr",data.getString("displayName")); // Delete out=jettyDo(jetty,"DELETE","/chain/vocabularies"+url,null); assertTrue(out.getStatus()<299); out=jettyDo(jetty,"GET","/chain/vocabularies"+url,null); assertEquals(400,out.getStatus()); } public void testAutocompleteOfOrganization() throws Exception { ServletTester jetty=setupJetty(); int resultsize =1; int pagenum = 0; String checkpagination = ""; boolean found=false; while(resultsize >0){ HttpTester out=jettyDo(jetty,"GET","/chain/vocabularies/person/autocomplete/group?q=Bing&pageSize=150&pageNum="+pagenum,null); assertTrue(out.getStatus()<299); pagenum++; String[] data=out.getContent().split("\n"); JSONObject test=new JSONObject(data[0]); if(data.length==0 || checkpagination.equals(test.getString("urn"))){ resultsize=0; //testing whether we have actually returned the same page or the next page - all csid returned should be unique } checkpagination = test.getString("urn"); for(int i=0;i<data.length;i++) { JSONObject entry=new JSONObject(data[i]); if(entry.getString("label").toLowerCase().contains("bing crosby ice cream")){ found = true; assertTrue(entry.has("urn")); } } } assertTrue(found); } }
package com.torodb.torod.db.backends.converters.array; import javax.json.JsonString; import org.jooq.tools.json.JSONValue; import com.torodb.torod.core.subdocument.values.ScalarString; import com.torodb.torod.core.subdocument.values.heap.StringScalarString; public class StringToArrayConverter implements ArrayConverter<JsonString, ScalarString> { private static final long serialVersionUID = 1L; @Override public String toJsonLiteral(ScalarString value) { return StringToArrayConverter.toJsonString(value.toString()); } @Override public ScalarString fromJsonValue(JsonString value) { return new StringScalarString(value.getString()); } public static String toJsonString(String text) { return '\"' + JSONValue.escape((String) text) + '\"'; } }
package org.opendaylight.yangtools.yang.data.api.schema.tree; import com.google.common.annotations.Beta; import com.google.common.base.Preconditions; import java.util.Iterator; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier; import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Utility class holding methods useful when dealing with {@link DataTreeCandidate} instances. */ @Beta public final class DataTreeCandidates { private static final Logger LOG = LoggerFactory.getLogger(DataTreeCandidates.class); private DataTreeCandidates() { throw new UnsupportedOperationException(); } public static DataTreeCandidate newDataTreeCandidate(final YangInstanceIdentifier rootPath, final DataTreeCandidateNode rootNode) { return new DefaultDataTreeCandidate(rootPath, rootNode); } public static DataTreeCandidate fromNormalizedNode(final YangInstanceIdentifier rootPath, final NormalizedNode<?, ?> node) { return new DefaultDataTreeCandidate(rootPath, new NormalizedNodeDataTreeCandidateNode(node)); } public static void applyToCursor(final DataTreeModificationCursor cursor, final DataTreeCandidate candidate) { DataTreeCandidateNodes.applyToCursor(cursor, candidate.getRootNode()); } public static void applyToModification(final DataTreeModification modification, final DataTreeCandidate candidate) { if (modification instanceof CursorAwareDataTreeModification) { try (DataTreeModificationCursor cursor = ((CursorAwareDataTreeModification) modification).createCursor(candidate.getRootPath())) { applyToCursor(cursor, candidate); } return; } final DataTreeCandidateNode node = candidate.getRootNode(); final YangInstanceIdentifier path = candidate.getRootPath(); switch (node.getModificationType()) { case DELETE: modification.delete(path); LOG.debug("Modification {} deleted path {}", modification, path); break; case SUBTREE_MODIFIED: LOG.debug("Modification {} modified path {}", modification, path); NodeIterator iterator = new NodeIterator(null, path, node.getChildNodes().iterator()); do { iterator = iterator.next(modification); } while (iterator != null); break; case UNMODIFIED: LOG.debug("Modification {} unmodified path {}", modification, path); // No-op break; case WRITE: modification.write(path, node.getDataAfter().get()); LOG.debug("Modification {} written path {}", modification, path); break; default: throw new IllegalArgumentException("Unsupported modification " + node.getModificationType()); } } private static final class NodeIterator { private final Iterator<DataTreeCandidateNode> iterator; private final YangInstanceIdentifier path; private final NodeIterator parent; public NodeIterator(@Nullable final NodeIterator parent, @Nonnull final YangInstanceIdentifier path, @Nonnull final Iterator<DataTreeCandidateNode> iterator) { this.iterator = Preconditions.checkNotNull(iterator); this.path = Preconditions.checkNotNull(path); this.parent = parent; } NodeIterator next(final DataTreeModification modification) { while (iterator.hasNext()) { final DataTreeCandidateNode node = iterator.next(); final YangInstanceIdentifier child = path.node(node.getIdentifier()); switch (node.getModificationType()) { case DELETE: modification.delete(child); LOG.debug("Modification {} deleted path {}", modification, child); break; case SUBTREE_MODIFIED: LOG.debug("Modification {} modified path {}", modification, child); return new NodeIterator(this, child, node.getChildNodes().iterator()); case UNMODIFIED: LOG.debug("Modification {} unmodified path {}", modification, child); // No-op break; case WRITE: modification.write(child, node.getDataAfter().get()); LOG.debug("Modification {} written path {}", modification, child); break; default: throw new IllegalArgumentException("Unsupported modification " + node.getModificationType()); } } return parent; } } }
package org.eclipse.birt.report.designer.ui.editors; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.birt.report.designer.core.model.SessionHandleAdapter; import org.eclipse.birt.report.designer.core.util.mediator.request.IRequestConvert; import org.eclipse.birt.report.designer.core.util.mediator.request.ReportRequest; import org.eclipse.birt.report.designer.internal.lib.commands.SetCurrentEditModelCommand; import org.eclipse.birt.report.designer.internal.ui.util.ExceptionHandler; import org.eclipse.birt.report.designer.internal.ui.util.UIUtil; import org.eclipse.birt.report.designer.nls.Messages; import org.eclipse.birt.report.designer.ui.editors.pages.ReportLayoutEditorFormPage; import org.eclipse.birt.report.designer.ui.editors.pages.ReportMasterPageEditorFormPage; import org.eclipse.birt.report.model.api.CellHandle; import org.eclipse.birt.report.model.api.ColumnHandle; import org.eclipse.birt.report.model.api.DesignElementHandle; import org.eclipse.birt.report.model.api.LibraryHandle; import org.eclipse.birt.report.model.api.MasterPageHandle; import org.eclipse.birt.report.model.api.ModuleHandle; import org.eclipse.birt.report.model.api.ReportDesignHandle; import org.eclipse.birt.report.model.api.ReportElementHandle; import org.eclipse.birt.report.model.api.ReportItemHandle; import org.eclipse.birt.report.model.api.RowHandle; import org.eclipse.birt.report.model.api.TemplateElementHandle; import org.eclipse.birt.report.model.api.TemplateParameterDefinitionHandle; import org.eclipse.core.resources.IMarker; import org.eclipse.core.runtime.CoreException; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.forms.editor.IFormPage; import org.eclipse.ui.ide.IGotoMarker; /** * BIRTGotoMarker */ class BIRTGotoMarker implements IGotoMarker { protected IDEMultiPageReportEditor editorPart; public BIRTGotoMarker( IDEMultiPageReportEditor editorPart ) { this.editorPart = editorPart; } /* * (non-Javadoc) * * @see org.eclipse.ui.ide.IGotoMarker#gotoMarker(org.eclipse.core.resources.IMarker) */ public void gotoMarker( IMarker marker ) { assert editorPart != null; if ( !marker.exists( ) ) { return; } ModuleHandle moduleHandle = editorPart.getModel( ); ReportElementHandle reportElementHandle = getReportElementHandle( moduleHandle, marker ); if ( reportElementHandle == null || ( reportElementHandle != null && isElementTemplateParameterDefinition( reportElementHandle ) ) ) { gotoXMLSourcePage( marker ); } else { if ( moduleHandle instanceof ReportDesignHandle ) { // go to master page if ( isElementInMasterPage( reportElementHandle ) ) { gotoLayoutPage( ReportMasterPageEditorFormPage.ID, marker, reportElementHandle ); } else // go to Layout Page { gotoLayoutPage( ReportLayoutEditorFormPage.ID, marker, reportElementHandle ); } } else if ( moduleHandle instanceof LibraryHandle ) { // go to master page if ( isElementInMasterPage( reportElementHandle ) ) { gotoLayoutPage( LibraryMasterPageEditorFormPage.ID, marker, reportElementHandle ); } else // go to Layout Page { gotoLibraryLayoutPage( marker, reportElementHandle ); } } } } protected void gotoLibraryLayoutPage( IMarker marker, ReportElementHandle reportElementHandle ) { String pageId = LibraryLayoutEditorFormPage.ID; if ( activatePage( pageId ) == false ) { return; } ModuleHandle moduleHandle = editorPart.getModel( ); reportElementHandle = getReportElementHandle( moduleHandle, marker ); if ( reportElementHandle != null && ( !isElementInMasterPage( reportElementHandle ) ) ) { SetCurrentEditModelCommand command = new SetCurrentEditModelCommand( reportElementHandle ); command.execute( ); } else // can not find it in this editpage { MessageDialog.openError( UIUtil.getDefaultShell( ), Messages.getString( "BIRTGotoMarker.Error.Title" ), //$NON-NLS-1$ Messages.getString( "BIRTGotoMarker.Error.Message" ) ); //$NON-NLS-1$ } } protected void gotoLayoutPage( String pageId, final IMarker marker, final ReportElementHandle reportElementHandle ) { if ( activatePage( pageId ) == false ) { return; } Display.getCurrent( ).asyncExec( new Runnable( ) { public void run( ) { gotoLayoutMarker( marker, reportElementHandle ); } } ); } protected void gotoXMLSourcePage( final IMarker marker ) { if ( activatePage( MultiPageReportEditor.XMLSourcePage_ID ) == false ) { return; } final IReportEditorPage reportXMLSourcePage = (IReportEditorPage) editorPart.getActivePageInstance( ); Display.getCurrent( ).asyncExec( new Runnable( ) { public void run( ) { gotoXMLSourceMarker( reportXMLSourcePage, marker ); } } ); } protected void gotoXMLSourceMarker( IReportEditorPage reportXMLSourcePage, IMarker marker ) { reportXMLSourcePage.selectReveal( marker ); } protected boolean activatePage( String pageId ) { if ( pageId.equals( editorPart.getActivePageInstance( ).getId( ) ) ) { return true; } IFormPage formPage = editorPart.setActivePage( pageId ); if ( formPage != null ) { return true; } return false; } protected ReportElementHandle getReportElementHandle( ModuleHandle moduleHandle, IMarker marker ) { Integer elementId = new Integer( 0 ); try { elementId = (Integer) marker.getAttribute( IDEMultiPageReportEditor.ELEMENT_ID ); } catch ( CoreException e ) { ExceptionHandler.handle( e ); } if ( elementId != null && elementId.intValue( ) > 0 ) { DesignElementHandle elementHandle = moduleHandle.getElementByID( elementId.intValue( ) ); if ( elementHandle == null || !( elementHandle instanceof ReportElementHandle ) ) { return null; } if ( elementHandle instanceof CellHandle || elementHandle instanceof ColumnHandle || elementHandle instanceof MasterPageHandle || elementHandle instanceof ReportItemHandle || elementHandle instanceof RowHandle || elementHandle instanceof TemplateElementHandle ) { return (ReportElementHandle) elementHandle; } } return null; } /** * Select the report element in the layout(including report design and * library) * * @param marker * the marker to go to */ protected void gotoLayoutMarker( IMarker marker, ReportElementHandle reportElementHandle ) { ModuleHandle moduleHandle = editorPart.getModel( ); reportElementHandle = getReportElementHandle( moduleHandle, marker ); if ( reportElementHandle == null ) { MessageDialog.openError( UIUtil.getDefaultShell( ), Messages.getString( "BIRTGotoMarker.Error.Title" ), //$NON-NLS-1$ Messages.getString( "BIRTGotoMarker.Error.Message" ) ); //$NON-NLS-1$ return; } List list = new ArrayList( ); list.add( reportElementHandle ); ReportRequest r = new ReportRequest( ); r.setType( ReportRequest.SELECTION ); r.setRequestConvert( new IRequestConvert( ) { /* * (non-Javadoc) * * @see org.eclipse.birt.report.designer.core.util.mediator.request.IRequestConvert#convertSelectionToModelLisr(java.util.List) */ public List convertSelectionToModelLisr( List list ) { List lst = new ArrayList( ); for ( Iterator itr = list.iterator( ); itr.hasNext( ); ) { Object obj = itr.next( ); // if ( obj instanceof ReportElementModel ) // lst.add( ( (ReportElementModel) obj ).getSlotHandle( ) ); lst.add( obj ); } return lst; } } ); r.setSelectionObject( list ); SessionHandleAdapter.getInstance( ).getMediator( ).notifyRequest( r ); } protected boolean isElementInMasterPage( DesignElementHandle elementHandle ) { ModuleHandle root = elementHandle.getRoot( ); DesignElementHandle container = elementHandle; while ( container != null && container != root ) { if ( container instanceof MasterPageHandle ) { return true; } container = container.getContainer( ); } return false; } protected boolean isElementTemplateParameterDefinition( DesignElementHandle elementHandle ) { ModuleHandle root = elementHandle.getRoot( ); DesignElementHandle container = elementHandle; while ( container != null && container != root ) { if ( container instanceof TemplateParameterDefinitionHandle ) { return true; } container = container.getContainer( ); } return false; } }
package org.splevo.vpm.builder.java2kdmdiff; import org.apache.log4j.Logger; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.compare.diff.metamodel.DiffElement; import org.eclipse.emf.compare.diff.metamodel.DiffModel; import org.eclipse.emf.ecore.EObject; import org.eclipse.gmt.modisco.java.ASTNode; import org.eclipse.gmt.modisco.java.Block; import org.eclipse.gmt.modisco.java.MethodDeclaration; import org.eclipse.gmt.modisco.java.NamedElement; import org.eclipse.modisco.java.composition.javaapplication.JavaApplication; import org.splevo.vpm.variability.VariationPoint; import org.splevo.vpm.variability.VariationPointGroup; import org.splevo.vpm.variability.VariationPointModel; import org.splevo.vpm.variability.variabilityFactory; /** * A builder to generate a Variation Point Model (VPM) based on a java2kdm diff-model, i.e. an * extended EMF Compare diff-model. * * @author benjamin * */ public class Java2KDMVPMBuilder { /** The logger used by this class. */ private Logger logger = Logger.getLogger(Java2KDMVPMBuilder.class); /** The id to set for leading variants. */ private String variantIDLeading = null; /** The id to set for integration variants. */ private String variantIDIntegration = null; /** * Constructor to set the variant ids. * * @param variantIDLeading * The id for the leading variants. * @param variantIDIntegration * The id for the integration variants. */ public Java2KDMVPMBuilder(String variantIDLeading, String variantIDIntegration) { this.variantIDIntegration = variantIDIntegration; this.variantIDLeading = variantIDLeading; } /** * Build a new VariationPointModel based on a DiffModel. * * The provided diff model should be the result of a JavaModel diffing. This will be checked by * the builder and null will be returned if this is not valid. * * @param diffModel * The diff model to interpret. * @return The resulting VariationPointModel or null if the DiffModel is not a about a modisco * JavaModel. * */ public VariationPointModel buildVPM(DiffModel diffModel) { if (!checkDiffModelIsValid(diffModel)) { return null; } VariationPointModel vpm = initVPM(diffModel); // visit the difference tree Java2KDMDiffVisitor java2KDMDiffVisitor = new Java2KDMDiffVisitor(variantIDLeading, variantIDIntegration); for (DiffElement diffElement : diffModel.getDifferences()) { VariationPoint vp = java2KDMDiffVisitor.doSwitch(diffElement); if (vp != null) { VariationPointGroup group = variabilityFactory.eINSTANCE.createVariationPointGroup(); // set the group id to the class of the software entity // except it is a block surrounded by a method String groupID = buildGroupID(vp.getEnclosingSoftwareEntity()); group.setGroupId(groupID); group.getVariationPoints().add(vp); vpm.getVariationPointGroups().add(group); } else { logger.warn("null VariationPoint created: " + diffElement); } } return vpm; } /** * Get the id for variation point group based on the ASTNode specifying the variability * location. * * @param node * The AST node containing the variability. * @return The derived group id. */ private String buildGroupID(ASTNode node) { String groupID = null; // get the containing elements name in case of a block if (node instanceof Block) { EObject parent = node.eContainer(); if (parent instanceof MethodDeclaration) { groupID = ((MethodDeclaration) parent).getName() + "()"; } else if (node instanceof NamedElement) { groupID = ((NamedElement) node).getName(); } } // use the name of named elements if (node instanceof NamedElement) { groupID = ((NamedElement) node).getName(); } // use the meta class name as fall back if (groupID == null) { groupID = node.getClass().getSimpleName(); } return groupID; } /** * Init the instance of the variation point model. * * @param diffModel * The diff model to get the diffed models from. * @return The initialized variation point model. */ private VariationPointModel initVPM(DiffModel diffModel) { JavaApplication leadingModel = selectJavaAppModel(diffModel.getRightRoots()); JavaApplication integrationModel = selectJavaAppModel(diffModel.getLeftRoots()); VariationPointModel vpm = variabilityFactory.eINSTANCE.createVariationPointModel(); vpm.setLeadingModel(leadingModel); vpm.setIntegrationModel(integrationModel); return vpm; } /** * Get a JavaApplication model from a list of model elements. * * @param eObjectList * The list to try to find the JavaApplication element in. * @return The first found JavaApplication or null if none is in the list. */ private JavaApplication selectJavaAppModel(EList<EObject> eObjectList) { for (EObject root : eObjectList) { if (root instanceof JavaApplication) { return (JavaApplication) root; } } return null; } /** * Check that the DiffModel is a valid input. This means, that the diffed models must be modisco * discovered java models and contain a JavaApplication model * * @param diffModel * The diff model to check * @return true/false depending whether the diff model is valid. */ private boolean checkDiffModelIsValid(DiffModel diffModel) { boolean valid = true; if (selectJavaAppModel(diffModel.getLeftRoots()) == null) { logger.warn("Diff model invalid: No valid JavaApplication integration root (left) available"); valid = false; } if (selectJavaAppModel(diffModel.getRightRoots()) == null) { logger.warn("Diff model contains no valid JavaApplication leading root (right) available"); valid = false; } return valid; } }
package io.github.Cnly.WowSuchCleaner.WowSuchCleaner.data.auction; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.UUID; import org.bukkit.Bukkit; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.scheduler.BukkitRunnable; import io.github.Cnly.Crafter.Crafter.framework.configs.CrafterYamlConfigManager; import io.github.Cnly.Crafter.Crafter.framework.locales.CrafterLocaleManager; import io.github.Cnly.WowSuchCleaner.WowSuchCleaner.Main; import io.github.Cnly.WowSuchCleaner.WowSuchCleaner.config.auction.AuctionConfig; import io.github.Cnly.WowSuchCleaner.WowSuchCleaner.config.auction.AuctionableItem; public class AuctionDataManager { private Main main = Main.getInstance(); private AuctionConfig auctionConfig = main.getAuctionConfig(); private CrafterLocaleManager localeManager = main.getLocaleManager(); private CrafterYamlConfigManager data = new CrafterYamlConfigManager(new File(main.getDataFolder(), "auctionData.yml"), false, main) { @Override public CrafterYamlConfigManager save() { AuctionDataManager.this.save(); return super.save(); } }; private ArrayList<Lot> lots = new ArrayList<>(); public AuctionDataManager() { this.load(); data.setAutoSaveInterval(60); new LotMaintainTask().runTaskTimer(main, 20L, 20L); } public void shutdownGracefully() { data.setAutoSaveInterval(0); data.save(); } public Map<UUID, ItemStack> getVaultContents(Player p) { String vaultPath = new StringBuilder(43).append("vaults.").append(p.getUniqueId()).toString(); ConfigurationSection singlePlayerVaultSection = data.getConfigurationSection(vaultPath); HashMap<UUID, ItemStack> result = new HashMap<>(); for(String lotUuidString : singlePlayerVaultSection.getKeys(false)) { if(lotUuidString.length() != 36) continue; // There is an itemCount field result.put(UUID.fromString(lotUuidString), singlePlayerVaultSection.getItemStack(lotUuidString)); } return result; } public boolean removeVaultItem(Player p, UUID lotUuid) { String vaultPath = new StringBuilder(43).append("vaults.").append(p.getUniqueId()).toString(); ConfigurationSection singlePlayerVaultSection = data.getConfigurationSection(vaultPath); String uuidString = lotUuid.toString(); if(singlePlayerVaultSection.isSet(uuidString)) { singlePlayerVaultSection.set(uuidString, null); unoccupyVault(p.getUniqueId()); return true; } else { return false; } } public boolean hasLot(Lot lot) { return lots.contains(lot); } public boolean addLot(ItemStack item) { AuctionableItem ai = auctionConfig.getAuctionableItemConfig(item); if(null == ai) return false; double startingPrice = (((int)(ai.getStartingPrice() * 100)) * item.getAmount()) / 100D; double minimumIncrement = (((int)(ai.getMinimumIncrement() * 100)) * item.getAmount()) / 100D; Lot lot = new Lot(item, false, startingPrice, null, null, -1, minimumIncrement, System.currentTimeMillis() + ai.getPreserveTimeInSeconds() * 1000, ai.getAuctionDurationInSeconds() * 1000); lots.add(lot); return true; } public boolean removeLot(Lot lot) { boolean success = lots.remove(lot); removeFromBackend(lot); return success; } public List<Lot> getLots() { return Collections.unmodifiableList(lots); } private void save() { for(Lot lot : lots) { this.saveToBackend(lot); } } private void saveToBackend(Lot lot) { UUID uuid = lot.getUuid(); String uuidString = uuid.toString(); ItemStack item = lot.getItem(); boolean started = lot.isStarted(); double price = lot.getPrice(); String lastBidPlayerName = lot.getLastBidPlayerName(); UUID lastBidPlayerUuid = lot.getLastBidPlayerUuid(); double lastBidPrice = lot.getLastBidPrice(); double minimumIncrement = lot.getMinimumIncrement(); long preserveTimeExpire = lot.getPreserveTimeExpire(); long auctionDurationExpire = lot.getAuctionDurationExpire(); String sectionPath = "lots." + uuidString; ConfigurationSection singleLotSection = data.getYamlConfig().getConfigurationSection(sectionPath); if(null == singleLotSection) { singleLotSection = data.getYamlConfig().createSection(sectionPath); } singleLotSection.set("item", item); singleLotSection.set("started", started); singleLotSection.set("price", price); singleLotSection.set("lastBidPlayerName", lastBidPlayerName); singleLotSection.set("lastBidPlayerUuid", null == lastBidPlayerUuid ? null : lastBidPlayerUuid.toString()); singleLotSection.set("lastBidPrice", lastBidPrice); singleLotSection.set("minimumIncrement", minimumIncrement); singleLotSection.set("preserveTimeExpire", preserveTimeExpire); singleLotSection.set("auctionDurationExpire", auctionDurationExpire); } private void removeFromBackend(Lot lot) { data.set("lots." + lot.getUuid().toString(), null); } public boolean isVaultAvailable(Player p) { String vaultPath = new StringBuilder(43).append("vaults.").append(p.getUniqueId()).toString(); ConfigurationSection singlePlayerVaultSection = data.getConfigurationSection(vaultPath); return singlePlayerVaultSection.getInt("itemCount", 0) < auctionConfig.getVaultCapacity(); } public boolean occupyVault(Player p) { String vaultPath = new StringBuilder(43).append("vaults.").append(p.getUniqueId()).toString(); ConfigurationSection singlePlayerVaultSection = data.getConfigurationSection(vaultPath); int itemCount = singlePlayerVaultSection.getInt("itemCount", 0); if(itemCount < auctionConfig.getVaultCapacity()) { singlePlayerVaultSection.set("itemCount", ++itemCount); return true; } else { return false; } } public void unoccupyVault(UUID uuid) { String vaultPath = new StringBuilder(43).append("vaults.").append(uuid).toString(); ConfigurationSection singlePlayerVaultSection = data.getConfigurationSection(vaultPath); int itemCount = singlePlayerVaultSection.getInt("itemCount", 0); if(itemCount <= 0) return; singlePlayerVaultSection.set("itemCount", --itemCount); } public void addDeposit(Lot lot, Player p, double deposit) { String depositPath = new StringBuilder(86).append("lots.").append(lot.getUuid()).append(".deposit.").append(p.getUniqueId()).toString(); data.set(depositPath, data.getYamlConfig().getDouble(depositPath, 0) + deposit); } public Map<UUID, Double> getDeposit(Lot lot) { HashMap<UUID, Double> result = new HashMap<>(); String path = new StringBuilder(49).append("lots.").append(lot.getUuid()).append(".deposit").toString(); ConfigurationSection singleLotDepositSection = data.getConfigurationSection(path); for(String uuidString : singleLotDepositSection.getKeys(false)) { UUID uuid = UUID.fromString(uuidString); result.put(uuid, singleLotDepositSection.getDouble(uuidString)); } return result; } public void hammer(Lot lot) { UUID buyerUuid = lot.getLastBidPlayerUuid(); Player buyer = Bukkit.getPlayer(buyerUuid); if(null == buyer || buyer.getInventory().firstEmpty() == -1) { String path = new StringBuilder(80).append("vaults.").append(buyerUuid.toString()).append('.').append(lot.getUuid()).toString(); data.set(path, lot.getItem()); } else { unoccupyVault(buyerUuid); buyer.getInventory().addItem(lot.getItem()); buyer.sendMessage(localeManager.getLocalizedString("ui.hammerBuyer")); } Map<UUID, Double> deposit = getDeposit(lot); deposit.remove(buyerUuid); for(Entry<UUID, Double> e : deposit.entrySet()) { Player p = Bukkit.getPlayer(e.getKey()); if(null != p) { p.sendMessage(localeManager.getLocalizedString("ui.hammerOthers")); } Main.economy.depositPlayer(p != null ? p : Bukkit.getOfflinePlayer(e.getKey()), e.getValue()); unoccupyVault(e.getKey()); } removeLot(lot); } private void load() { ConfigurationSection lotsSection = data.getConfigurationSection("lots"); for(String uuidString : lotsSection.getKeys(false)) { ConfigurationSection singleLotSection = lotsSection.getConfigurationSection(uuidString); ItemStack item = singleLotSection.getItemStack("item"); boolean started = singleLotSection.getBoolean("started"); double price = singleLotSection.getDouble("price"); String lastBidPlayerName = singleLotSection.getString("lastBidPlayerName"); UUID lastBidPlayerUuid = singleLotSection.isSet("lastBidPlayerUuid") ? UUID.fromString(singleLotSection.getString("lastBidPlayerUuid")) : null; double lastBidPrice = singleLotSection.getDouble("lastBidPrice"); double minimumIncrement = singleLotSection.getDouble("minimumIncrement"); long preserveTimeExpire = singleLotSection.getLong("preserveTimeExpire"); long auctionDurationExpire = singleLotSection.getLong("auctionDurationExpire"); Lot lot = new Lot(UUID.fromString(uuidString), item, started, price, lastBidPlayerName, lastBidPlayerUuid, lastBidPrice, minimumIncrement, preserveTimeExpire, auctionDurationExpire); lots.add(lot); } } private class LotMaintainTask extends BukkitRunnable { @Override public void run() { long currentTime = System.currentTimeMillis(); List<Lot> lotsToHammer = null; List<Lot> lotsToRemove = null; for(Lot lot : lots) { if(lot.isStarted()) { if(currentTime > lot.getAuctionDurationExpire()) { if(null == lotsToHammer) { lotsToHammer = new ArrayList<Lot>(); } lotsToHammer.add(lot); } } else { if(currentTime > lot.getPreserveTimeExpire()) { if(null == lotsToRemove) { lotsToRemove = new ArrayList<Lot>(); } lotsToRemove.add(lot); } } } if(lotsToHammer != null) { for(Lot lot : lotsToHammer) { hammer(lot); } } if(lotsToRemove != null) { for(Lot lot : lotsToRemove) { removeLot(lot); } } } } }
package de.factoryfx.data; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Stream; import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.ObjectIdGenerators; import com.google.common.base.Strings; import de.factoryfx.data.attribute.Attribute; import de.factoryfx.data.attribute.AttributeChangeListener; import de.factoryfx.data.merge.MergeResult; import de.factoryfx.data.merge.MergeResultEntry; import de.factoryfx.data.merge.attribute.AttributeMergeHelper; import de.factoryfx.data.validation.AttributeValidation; import de.factoryfx.data.validation.Validation; import de.factoryfx.data.validation.ValidationError; import javafx.beans.property.ReadOnlyStringProperty; import javafx.beans.property.SimpleStringProperty; import javafx.util.Pair; @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") public class Data { private String id; public String getId() { if (id == null) { id = UUID.randomUUID().toString(); } return id; } public void setId(String value) { id = value; } @JsonIgnore private static final Map<Class<?>, Field[]> fields = new ConcurrentHashMap<>(); @JsonIgnore private Field[] instanceFields; @JsonIgnore private Field[] getFields() { if (instanceFields==null) { final List<Field> fieldsOrdered = getFieldsOrdered(getClass()); instanceFields = fieldsOrdered.toArray(new Field[fieldsOrdered.size()]); fields.put(getClass(), instanceFields); } return instanceFields; } private List<Field> getFieldsOrdered(Class<?> clazz) { ArrayList<Field> fields = new ArrayList<>(); Class<?> parent = clazz.getSuperclass(); if (parent!=null){// skip Object fields.addAll(getFieldsOrdered(parent)); } Stream.of(clazz.getDeclaredFields()).filter(f->Modifier.isPublic(f.getModifiers())).filter(f->!Modifier.isStatic(f.getModifiers())).forEach(fields::add); return fields; } @FunctionalInterface interface TriConsumer<A, B, C> { void accept(A a, B b, C c); } private void visitChildFactoriesFlat(Consumer<Data> consumer) { visitAttributesFlat((attributeVariableName, attribute) -> { attribute.internal_visit(consumer); }); } @FunctionalInterface public interface AttributeVisitor{ void accept(String attributeVariableName, Attribute<?> attribute); } private void visitAttributesFlat(AttributeVisitor consumer) { Field[] fields = getFields(); for (Field field : fields) { try { Object fieldValue = field.get(this); if (fieldValue instanceof Attribute) { consumer.accept(field.getName(),(Attribute) fieldValue); } } catch (IllegalAccessException e) { throw new RuntimeException(e); } } } private void visitAttributesFlat(Consumer<Attribute<?>> consumer) { this.visitAttributesFlat((attributeVariableName, attribute) -> consumer.accept(attribute)); } @SuppressWarnings("unchecked") private <A> void visitAttributesDualFlat(Data data, BiConsumer<Attribute<A>, Attribute<A>> consumer) { Field[] fields = getFields(); for (Field field : fields) { try { Object fieldValue = field.get(this); if (fieldValue instanceof Attribute) { consumer.accept((Attribute<A>) field.get(this), (Attribute<A>) field.get(data)); } } catch (IllegalAccessException e) { throw new RuntimeException(e); } } } private void visitAttributesTripleFlat(Optional<?> data1, Optional<?> data2, TriConsumer<Attribute<?>, Optional<Attribute<?>>, Optional<Attribute<?>>> consumer) { Field[] fields = getFields(); for (Field field : fields) { try { // fields[f].setAccessible(true); Object fieldValue = field.get(this); if (fieldValue instanceof Attribute) { Attribute<?> value1 = null; if (data1.isPresent()) { value1 = (Attribute<?>) field.get(data1.get()); } Attribute<?> value2 = null; if (data2.isPresent()) { value2 = (Attribute<?>) field.get(data2.get()); } consumer.accept((Attribute<?>) field.get(this), Optional.ofNullable(value1), Optional.ofNullable(value2)); } } catch (IllegalAccessException e) { throw new RuntimeException(e); } } } private Map<Object,Data> collectChildFactoriesMap() { HashSet<Data> factoryBases = new HashSet<>(); // factoryBases.add(this); TODO required? collectModelEntitiesTo(factoryBases); HashMap<Object, Data> result = new HashMap<>(); for (Data factory: factoryBases){ result.put(factory.getId(),factory); } return result; } @SuppressWarnings("unchecked") private <T extends Data> Set<T> collectChildrenFlat() { HashSet<T> result = new HashSet<>(); this.visitChildFactoriesFlat(factoryBase -> result.add((T)factoryBase)); return result; } /** collect set with all nested children and itself*/ private Set<Data> collectChildrenDeep() { HashSet<Data> factoryBases = new HashSet<>(); collectModelEntitiesTo(factoryBases); return factoryBases; } private void collectModelEntitiesTo(Set<Data> allModelEntities) { if (allModelEntities.add(this)){ visitAttributesFlat(attribute -> attribute.internal_collectChildren(allModelEntities)); } } /** * after deserialization from json only the value is present and metadata are missing * we create a copy which contains the metadata and than copy then transfer the value in the new copy (which is what conveniently copy does) */ private <T extends Data> T reconstructMetadataDeepRoot() { return this.copy(); } private Supplier<Data> newInstanceSupplier= () -> { try { return Data.this.getClass().newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new RuntimeException(e); } }; private void setNewInstanceSupplier(Supplier<Data> newInstanceSupplier){ this.newInstanceSupplier=newInstanceSupplier; } private Data newInstance() { return newInstanceSupplier.get(); } @SuppressWarnings("unchecked") private void fixDuplicateObjects() { Map<Object, Data> idToDataMap = collectChildFactoriesMap(); final Set<Data> all = collectChildrenDeep(); for (Data data: all){ data.visitAttributesFlat(attribute -> attribute.internal_fixDuplicateObjects(idToDataMap)); } } private Supplier<String> displayTextProvider= () -> Data.this.getClass().getSimpleName()+":"+getId(); @JsonIgnore @SuppressWarnings("unchecked") private String getDisplayText(){ return displayTextProvider.get(); } private void setDisplayTextProvider(Supplier<String> displayTextProvider){ this.displayTextProvider=displayTextProvider; } /** validate attributes without visiting child factories*/ @SuppressWarnings("unchecked") private List<ValidationError> validateFlat(){ final ArrayList<ValidationError> result = new ArrayList<>(); final Map<Attribute<?>, List<ValidationError>> attributeListMap = validateFlatMapped(); for (Map.Entry<Attribute<?>, List<ValidationError>> entry: attributeListMap.entrySet()){ result.addAll(entry.getValue()); } return result; } /** validate attributes without visiting child factories */ private Map<Attribute<?>,List<ValidationError>> validateFlatMapped(){ Map<Attribute<?>,List<ValidationError>> result= new HashMap<>(); visitAttributesFlat((attributeVariableName, attribute) -> { final ArrayList<ValidationError> validationErrors = new ArrayList<>(); result.put(attribute, validationErrors); validationErrors.addAll(attribute.internal_validate(this)); }); for (AttributeValidation<?> validation: dataValidations){ final Map<Attribute<?>, List<ValidationError>> validateResult = validation.validate(this); for (Map.Entry<Attribute<?>, List<ValidationError>> entry: validateResult.entrySet()){ result.get(entry.getKey()).addAll(entry.getValue()); } } return result; } final List<AttributeValidation<?>> dataValidations = new ArrayList<>(); private <T> void addValidation(Validation<T> validation, Attribute<?>... dependencies){ for ( Attribute<?> dependency: dependencies){ dataValidations.add(new AttributeValidation<>(validation,dependency)); } } @SuppressWarnings("unchecked") private void merge(Optional<Data> originalValue, Optional<Data> newValue, MergeResult mergeResult) { this.visitAttributesTripleFlat(originalValue, newValue, (currentAttribute, originalAttribute, newAttribute) -> { AttributeMergeHelper<?> attributeMergeHelper = currentAttribute.internal_createMergeHelper(); if (attributeMergeHelper!=null){ boolean hasNoConflict = attributeMergeHelper.hasNoConflict(originalAttribute, newAttribute); if (hasNoConflict) { if (newAttribute.isPresent()) { if (attributeMergeHelper.isMergeable(originalAttribute, newAttribute)) { MergeResultEntry mergeResultEntry = new MergeResultEntry(Data.this, currentAttribute, newAttribute); mergeResult.addMergeExecutions(() -> attributeMergeHelper.merge(originalAttribute, newAttribute.get())); mergeResult.addMergeInfo(mergeResultEntry); } } } else { MergeResultEntry mergeResultEntry = new MergeResultEntry(Data.this, currentAttribute, newAttribute); mergeResult.addConflictInfos(mergeResultEntry); } } }); } private HashMap<Data, Data> getChildToParentMap(Set<Data> allModelEntities) { HashMap<Data, Data> result = new HashMap<>(); for (Data factoryBase : allModelEntities) { factoryBase.visitAttributesFlat(attribute -> { attribute.internal_visit(nestedFactoryBase -> { result.put(nestedFactoryBase, factoryBase); }); }); } return result; } private List<Data> getMassPathTo(HashMap<Data, Data> childToParent, Data target) { List<Data> path = new ArrayList<>(); Optional<Data> pathElement = Optional.ofNullable(childToParent.get(target)); while (pathElement.isPresent()) { path.add(pathElement.get()); pathElement = Optional.ofNullable(childToParent.get(pathElement.get())); } Collections.reverse(path); return path; } @SuppressWarnings("unchecked") private <T extends Data> T copy() { return (T)copyDeep(0,Integer.MAX_VALUE,new HashMap<>()); } @SuppressWarnings("unchecked") private <T extends Data> T semanticCopy() { T result = (T)newInstance(); // result.setId(this.getId()); this.visitAttributesDualFlat(result, (thisAttribute, copyAttribute) -> { thisAttribute.internal_semanticCopyTo(copyAttribute); }); return result; } /**copy including one the references first level of nested references*/ @SuppressWarnings("unchecked") private <T extends Data> T copyOneLevelDeep(){ return (T)copyDeep(0,1,new HashMap<>()); } /**copy without nested references, only value attributes are copied*/ @SuppressWarnings("unchecked") private <T extends Data> T copyZeroLevelDeep(){ return (T)copyDeep(0,0,new HashMap<>()); } private Data copyDeep(final int level, final int maxLevel, HashMap<Object,Data> identityPreserver){ if (level>maxLevel){ return null; } Data result= identityPreserver.get(this.getId()); if (result==null){ result = newInstance(); result.setId(this.getId()); this.visitAttributesDualFlat(result, (thisAttribute, copyAttribute) -> { thisAttribute.internal_copyTo(copyAttribute,(data)->{ if (data==null){ return null; } return data.copyDeep(level + 1, maxLevel, identityPreserver); }); }); identityPreserver.put(this.getId(),result); } return result; } private boolean readyForUsage(){ return root!=null; } @SuppressWarnings("unchecked") private <T extends Data> T endUsage() { for (Data data: collectChildrenDeep()){ data.visitAttributesFlat((attributeVariableName, attribute) -> { attribute.internal_endUsage(); }); } return (T)this; } @SuppressWarnings("unchecked") <T extends Data> T propagateRoot(Data root){ final Set<Data> childrenDeep = collectChildrenDeep(); for (Data data: childrenDeep){ data.root=root; data.visitAttributesFlat((attributeVariableName, attribute) -> { attribute.internal_prepareUsage(root); }); } for (Data data: childrenDeep){ data.visitAttributesFlat((attributeVariableName, attribute) -> { attribute.internal_afterPreparedUsage(root); }); } return (T)this; } private <T extends Data> T prepareUsage() { T result = reconstructMetadataDeepRoot(); return result.propagateRoot(result); } private Data root; private Data getRoot(){ return root; } private Function<List<Attribute<?>>,List<Pair<String,List<Attribute<?>>>>> attributeListGroupedSupplier=(List<Attribute<?>> allAttributes)->{ return Collections.singletonList(new Pair<>("Data", allAttributes)); }; private void setAttributeListGroupedSupplier(Function<List<Attribute<?>>,List<Pair<String,List<Attribute<?>>>>> attributeListGroupedSupplier){ this.attributeListGroupedSupplier=attributeListGroupedSupplier; } private List<Pair<String,List<Attribute<?>>>> attributeListGrouped(){ return attributeListGroupedSupplier.apply(attributeList()); } private List<Attribute<?>> attributeList(){ ArrayList<Attribute<?>> result = new ArrayList<>(); this.visitAttributesFlat((attributeVariableName, attribute) -> { result.add(attribute); }); return result; } private Function<String,Boolean> matchSearchTextFunction=text->{ return Strings.isNullOrEmpty(text) || Strings.nullToEmpty(getDisplayText()).toLowerCase().contains(text.toLowerCase()); }; private void setMatchSearchTextFunction(Function<String,Boolean> matchSearchTextFunction) { this.matchSearchTextFunction=matchSearchTextFunction; } private boolean matchSearchText(String text) { return matchSearchTextFunction.apply(text); } private List<Attribute<?>> displayTextDependencies= Collections.emptyList(); private void setDisplayTextDependencies(List<Attribute<?>> displayTextDependencies) { this.displayTextDependencies = displayTextDependencies; } private SimpleStringProperty simpleStringProperty=null; @JsonIgnore private ReadOnlyStringProperty getDisplayTextObservable() { if (simpleStringProperty==null){ simpleStringProperty = new SimpleStringProperty(); simpleStringProperty.set(getDisplayText()); addDisplayTextListeners(this,(attributeParam, value) -> simpleStringProperty.set(getDisplayText())); } return simpleStringProperty; } @SuppressWarnings("unchecked") private void addDisplayTextListeners(Data data, AttributeChangeListener attributeChangeListener){ for (Attribute<?> attribute: data.displayTextDependencies){ attribute.internal_addListener(attributeChangeListener); attribute.internal_visit(data1 -> addDisplayTextListeners(data1,attributeChangeListener)); } } private final DataUtility dataUtility = new DataUtility(this); /** public utility api */ public DataUtility utility(){ return dataUtility; } public static class DataUtility { private final Data data; public DataUtility(Data data) { this.data = data; } /** semantic copy can be configured on the attributes, unlike internal copy which always create complete copy with same ids*/ public <T extends Data> T semanticCopy(){ return data.semanticCopy(); } } private final DataConfiguration dataConfiguration = new DataConfiguration(this); /** data configurations api */ public DataConfiguration config(){ return dataConfiguration; } public static class DataConfiguration { private final Data data; public DataConfiguration(Data data) { this.data = data; } /** * short readable text describing the factory * */ public void setDisplayTextProvider(Supplier<String> displayTextProvider){ data.setDisplayTextProvider(displayTextProvider); } /** * short readable text describing the factory * @param displayTextProvider * @param dependencies */ public void setDisplayTextProvider(Supplier<String> displayTextProvider, Attribute<?>... dependencies){ data.setDisplayTextProvider(displayTextProvider); data.setDisplayTextDependencies(Arrays.asList(dependencies)); } /** * @see #setDisplayTextDependencies(Attribute[]) * */ public void setDisplayTextDependencies(List<Attribute<?>> attributes){ data.setDisplayTextDependencies(attributes); } /** set the attributes that affect the displaytext<br> * used for live update in gui * */ public void setDisplayTextDependencies(Attribute<?>... attributes){ data.setDisplayTextDependencies(Arrays.asList(attributes)); } /** * grouped iteration over attributes e.g. used in gui editor where each group is a new Tab * */ public void setAttributeListGroupedSupplier(Function<List<Attribute<?>>,List<Pair<String,List<Attribute<?>>>>> attributeListGroupedSupplier){ this.data.setAttributeListGroupedSupplier(attributeListGroupedSupplier); } /** * new Instance configuration default in over reflection over default constructor * used for copies * */ public void setNewInstanceSupplier(Supplier<Data> newInstanceSupplier){ this.data.setNewInstanceSupplier(newInstanceSupplier); } /** * define match logic for freetext search e.g. in tables * */ public void setMatchSearchTextFunction(Function<String,Boolean> matchSearchTextFunction){ data.setMatchSearchTextFunction(matchSearchTextFunction); } /** * data validation * @param validation * @param dependencies * @param <T> */ public <T> void addValidation(Validation<T> validation, Attribute<?>... dependencies){ data.addValidation(validation,dependencies); } } private final Internal internal = new Internal(this); /** <b>internal methods should be only used from the framework.</b> * They may change in the Future. * There is no fitting visibility in java therefore this workaround. */ public Internal internal(){ return internal; } public static class Internal{ private final Data data; public Internal(Data data) { this.data = data; } public boolean matchSearchText(String newValue) { return data.matchSearchText(newValue); } public <T extends Data> T semanticCopy() { return data.semanticCopy(); } public void visitChildFactoriesFlat(Consumer<Data> consumer) { data.visitChildFactoriesFlat(consumer); } public <A> void visitAttributesDualFlat(Data modelBase, BiConsumer<Attribute<A>, Attribute<A>> consumer) { data.visitAttributesDualFlat(modelBase,consumer); } public void visitAttributesFlat(AttributeVisitor consumer) { data.visitAttributesFlat(consumer); } public void visitAttributesFlat(Consumer<Attribute<?>> consumer) { data.visitAttributesFlat(consumer); } public List<Pair<String,List<Attribute<?>>>> attributeListGrouped(){ return data.attributeListGrouped(); } public Map<Object,Data> collectChildFactoriesMap() { return data.collectChildFactoriesMap(); } public <T extends Data> Set<T> collectChildrenFlat() { return data.collectChildrenFlat(); } public Set<Data> collectChildrenDeep() { return data.collectChildrenDeep(); } public void collectModelEntitiesTo(Set<Data> allModelEntities) { data.collectModelEntitiesTo(allModelEntities); } /**fix all factories with same id should be same object * only call on root * */ public void fixDuplicateObjects() { data.fixDuplicateObjects(); } public String getDisplayText(){ return data.getDisplayText(); } public ReadOnlyStringProperty getDisplayTextObservable(){ return data.getDisplayTextObservable(); } public List<ValidationError> validateFlat(){ return data.validateFlat(); } public Map<Attribute<?>,List<ValidationError>> validateFlatMapped(){ return data.validateFlatMapped(); } public void merge(Optional<Data> originalValue, Optional<Data> newValue, MergeResult mergeResult) { data.merge(originalValue,newValue,mergeResult); } public List<Data> getPathFromRoot() { return data.root.getMassPathTo(data.root.getChildToParentMap(data.root.collectChildrenDeep()), data); } public <T extends Data> T copy() { return data.copy(); } public <T extends Data> T copyOneLevelDeep(){ return data.copyOneLevelDeep(); } public <T extends Data> T copyZeroLevelDeep(){ return data.copyZeroLevelDeep(); } /** * after serialisation or programmatically creation this mus be called first before using the object * to: * -fix jackson wrong deserialization (metadata ==null) * -propagate root node to all children (for validation etc) * * unfortunately we must create a copy and can't make the same object usable(which we tried but failed) * * only call on root * return usable copy */ public <T extends Data> T prepareUsableCopy() { return data.prepareUsage(); } /** only call on root*/ public <T extends Data> T endUsage() { return data.endUsage(); } public boolean readyForUsage(){ return data.readyForUsage(); } public <T extends Data> T propagateRoot(Data root){ return data.propagateRoot(root); } public Data getRoot(){ return data.getRoot(); } } }
package elki.visualization.visualizers.scatterplot.cluster; import java.util.Iterator; import org.apache.batik.util.SVGConstants; import org.w3c.dom.Element; import elki.data.Cluster; import elki.data.Clustering; import elki.data.model.Model; import elki.data.model.PrototypeModel; import elki.database.datastore.ObjectNotFoundException; import elki.database.ids.DBIDRef; import elki.visualization.VisualizationTask; import elki.visualization.VisualizationTask.UpdateFlag; import elki.visualization.VisualizationTree; import elki.visualization.VisualizerContext; import elki.visualization.css.CSSClass; import elki.visualization.gui.VisualizationPlot; import elki.visualization.projections.Projection; import elki.visualization.projector.ScatterPlotProjector; import elki.visualization.style.ClusterStylingPolicy; import elki.visualization.style.StyleLibrary; import elki.visualization.style.StylingPolicy; import elki.visualization.style.marker.MarkerLibrary; import elki.visualization.svg.SVGUtil; import elki.visualization.visualizers.VisFactory; import elki.visualization.visualizers.Visualization; import elki.visualization.visualizers.scatterplot.AbstractScatterplotVisualization; /** * Visualize the mean of a KMeans-Clustering * * @author Heidi Kolb * @since 0.7.0 * * @stereotype factory * @navassoc - create - Instance */ public class ClusterMeanVisualization implements VisFactory { /** * A short name characterizing this Visualizer. */ private static final String NAME = "Cluster Means"; /** * Constructor. */ public ClusterMeanVisualization() { super(); } @Override public Visualization makeVisualization(VisualizerContext context, VisualizationTask task, VisualizationPlot plot, double width, double height, Projection proj) { return new Instance(context, task, plot, width, height, proj); } @Override public void processNewResult(final VisualizerContext context, Object start) { VisualizationTree.findVis(context, start).filter(ScatterPlotProjector.class).forEach(p -> { context.addVis(p, new VisualizationTask(this, NAME, p, p.getRelation()) .level(VisualizationTask.LEVEL_DATA + 1).with(UpdateFlag.ON_STYLEPOLICY)); }); } /** * Instance. * * @author Heidi Kolb * * @navhas - visualizes - MeanModel * @navhas - visualizes - MedoidModel */ public class Instance extends AbstractScatterplotVisualization { /** * CSS class name for center of the means */ private static final String CSS_MEAN_CENTER = "mean-center"; /** * CSS class name for center of the means */ private static final String CSS_MEAN = "mean-marker"; /** * Constructor. * * @param context Visualizer context * @param task Visualization task * @param plot Plot to draw to * @param width Embedding width * @param height Embedding height * @param proj Projection */ public Instance(VisualizerContext context, VisualizationTask task, VisualizationPlot plot, double width, double height, Projection proj) { super(context, task, plot, width, height, proj); addListeners(); } @Override public void fullRedraw() { setupCanvas(); final StylingPolicy spol = context.getStylingPolicy(); if(!(spol instanceof ClusterStylingPolicy)) { return; } @SuppressWarnings("unchecked") Clustering<Model> clustering = (Clustering<Model>) ((ClusterStylingPolicy) spol).getClustering(); if(clustering.getAllClusters().size() == 0) { return; } StyleLibrary slib = context.getStyleLibrary(); MarkerLibrary ml = slib.markers(); double marker_size = slib.getSize(StyleLibrary.MARKERPLOT); // Small crosses for mean: if(!svgp.getCSSClassManager().contains(CSS_MEAN_CENTER)) { CSSClass center = new CSSClass(this, CSS_MEAN_CENTER); center.setStatement(SVGConstants.CSS_STROKE_PROPERTY, slib.getTextColor(StyleLibrary.DEFAULT)); center.setStatement(SVGConstants.CSS_STROKE_WIDTH_PROPERTY, slib.getLineWidth(StyleLibrary.AXIS_TICK) * .5); svgp.addCSSClassOrLogError(center); } // Markers for the mean: if(!svgp.getCSSClassManager().contains(CSS_MEAN)) { CSSClass center = new CSSClass(this, CSS_MEAN); center.setStatement(SVGConstants.CSS_OPACITY_PROPERTY, "0.7"); svgp.addCSSClassOrLogError(center); } Iterator<Cluster<Model>> ci = clustering.getAllClusters().iterator(); for(int cnum = 0; ci.hasNext(); cnum++) { Cluster<Model> clus = ci.next(); Model model = clus.getModel(); double[] mean = null; try { if(model instanceof PrototypeModel) { Object prototype = ((PrototypeModel<?>) model).getPrototype(); if(prototype instanceof double[]) { mean = proj.fastProjectDataToRenderSpace((double[]) prototype); } else if(prototype instanceof DBIDRef) { mean = proj.fastProjectDataToRenderSpace(rel.get((DBIDRef) prototype)); } } if(mean == null) { continue; } } catch(ObjectNotFoundException e) { continue; // Element not found. } // add a greater Marker for the mean Element meanMarker = ml.useMarker(svgp, mean[0], mean[1], cnum, marker_size * 3); SVGUtil.addCSSClass(meanMarker, CSS_MEAN); // Add a fine cross to mark the exact location of the mean. Element meanMarkerCenter = svgp.svgLine(mean[0] - .7, mean[1], mean[0] + .7, mean[1]); SVGUtil.setAtt(meanMarkerCenter, SVGConstants.SVG_CLASS_ATTRIBUTE, CSS_MEAN_CENTER); Element meanMarkerCenter2 = svgp.svgLine(mean[0], mean[1] - .7, mean[0], mean[1] + .7); SVGUtil.setAtt(meanMarkerCenter2, SVGConstants.SVG_CLASS_ATTRIBUTE, CSS_MEAN_CENTER); layer.appendChild(meanMarker); layer.appendChild(meanMarkerCenter); layer.appendChild(meanMarkerCenter2); } svgp.updateStyleElement(); } } }
package org.csstudio.alarm.beast.msghist; import org.csstudio.security.ui.PasswordFieldEditor; import org.eclipse.core.runtime.preferences.InstanceScope; import org.eclipse.jface.preference.FieldEditorPreferencePage; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.IntegerFieldEditor; import org.eclipse.jface.preference.StringFieldEditor; import org.eclipse.swt.widgets.Composite; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import org.eclipse.ui.preferences.ScopedPreferenceStore; /** Preference page. * Connected to GUI in plugin.xml * @author Kay Kasemir * @author Xihui Chen */ public class PreferencePage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage { /** Constructor */ public PreferencePage() { // This way, preference changes in the GUI end up in a file under // {workspace}/.metadata/.plugins/org.eclipse.core.runtime/.settings/, // i.e. they are specific to the workspace instance. final IPreferenceStore store = new ScopedPreferenceStore(InstanceScope.INSTANCE, Activator.ID); setPreferenceStore(store); setMessage(Messages.MessageHistory); } /** {@inheritDoc */ @Override public void init(IWorkbench workbench) { /* NOP */ } /** {@inheritDoc */ @Override protected void createFieldEditors() { final Composite parent = getFieldEditorParent(); addField(new StringFieldEditor(Preferences.RDB_URL, Messages.Pref_URL, parent)); addField(new StringFieldEditor(Preferences.RDB_USER, Messages.Pref_User, parent)); addField(new PasswordFieldEditor(Activator.ID, Preferences.RDB_PASSWORD, Messages.Pref_Password, parent)); addField(new StringFieldEditor(Preferences.RDB_SCHEMA, Messages.Pref_Schema, parent)); addField(new StringFieldEditor(Preferences.START, Messages.Pref_Starttime, parent)); final IntegerFieldEditor max_properties = new IntegerFieldEditor(Preferences.MAX_PROPERTIES, Messages.Pref_MaxProperties, parent); max_properties.setValidRange(0, Integer.MAX_VALUE); addField(max_properties); addField(new TableColumnsFieldEditor(parent)); } }
package org.ovirt.engine.core.bll; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.ovirt.engine.core.common.businessentities.storage.DiskImage; import org.ovirt.engine.core.common.queries.IdsQueryParameters; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.dao.DiskImageDao; @RunWith(MockitoJUnitRunner.class) public class GetAncestorImagesByImagesIdsQueryTest extends AbstractUserQueryTest<IdsQueryParameters, GetAncestorImagesByImagesIdsQuery<IdsQueryParameters>> { @Mock private DiskImageDao diskImageDao; private List<Guid> imagesIds; private DiskImage image1; // snapshot 0 (base snapshot) private DiskImage image2; // snapshot 1 private DiskImage image3; // snapshot 2 (active image) @Override @Before public void setUp() throws Exception { super.setUp(); initializeImages(); when(getDbFacadeMockInstance().getDiskImageDao()).thenReturn(diskImageDao); imagesIds = new ArrayList<>(); when(getQueryParameters().getIds()).thenReturn(imagesIds); } @Test public void executeQueryCommandWithEmptyMap() { assertTrue(runQuery().isEmpty()); } @Test public void executeQueryCommandWithBaseSnapshotOnly() { imagesIds.add(image1.getImageId()); Map<Guid, DiskImage> queryReturnValue = runQuery(); assertEquals(1, queryReturnValue.size()); assertEquals(image1, queryReturnValue.get(image1.getImageId())); } @Test public void executeQueryCommandWithSnapshots() { imagesIds.add(image1.getImageId()); imagesIds.add(image2.getImageId()); imagesIds.add(image3.getImageId()); Map<Guid, DiskImage> queryReturnValue = runQuery(); assertEquals(3, queryReturnValue.size()); assertEquals(image1, queryReturnValue.get(image1.getImageId())); assertEquals(image1, queryReturnValue.get(image2.getImageId())); assertEquals(image1, queryReturnValue.get(image3.getImageId())); } private void initializeImages() { image1 = new DiskImage(); image1.setImageId(Guid.newGuid()); mockImageAncestor(image1, image1); image2 = new DiskImage(); image2.setImageId(Guid.newGuid()); mockImageAncestor(image2, image1); image3 = new DiskImage(); image3.setImageId(Guid.newGuid()); mockImageAncestor(image3, image1); } private void mockImageAncestor(DiskImage imageToMock, DiskImage imageAncestor) { when(diskImageDao.getAncestor(imageToMock.getImageId(), getUser().getId(), getQueryParameters().isFiltered())) .thenReturn(imageAncestor); } private Map<Guid, DiskImage> runQuery() { getQuery().executeQueryCommand(); return getQuery().getQueryReturnValue().getReturnValue(); } }
package com.bagri.xdm.cache.hazelcast.impl; import static com.bagri.xdm.client.common.XDMCacheConstants.CN_XDM_DOCUMENT; import static com.bagri.xdm.domain.XDMDocument.dvFirst; import java.util.Set; import java.util.Map.Entry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.bagri.xdm.common.XDMDocumentKey; import com.bagri.xdm.common.XDMFactory; import com.bagri.xdm.domain.XDMDocument; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.IMap; import com.hazelcast.map.EntryBackupProcessor; import com.hazelcast.map.EntryProcessor; import com.hazelcast.query.Predicate; import com.hazelcast.query.Predicates; public class DocumentKeyProcessor implements EntryProcessor<XDMDocumentKey, XDMDocument> { //, IdentifiedDataSerializable { private static final Logger logger = LoggerFactory.getLogger(DocumentKeyProcessor.class); private String uri; private boolean returnNext; private boolean skipClosed; private XDMFactory factory; private HazelcastInstance hzInstance; public DocumentKeyProcessor() { } public DocumentKeyProcessor(String uri, boolean returnNext, boolean skipClosed, XDMFactory factory, HazelcastInstance hzInstance) { this.uri = uri; this.returnNext = returnNext; this.skipClosed = skipClosed; this.factory = factory; this.hzInstance = hzInstance; } @Override public Object process(Entry<XDMDocumentKey, XDMDocument> entry) { if (entry.getValue() == null) { return null; } XDMDocument doc = null; boolean sameUri = false; XDMDocumentKey key = entry.getKey(); XDMDocument lastDoc = entry.getValue(); IMap<XDMDocumentKey, XDMDocument> xddCache = hzInstance.getMap(CN_XDM_DOCUMENT); do { if (lastDoc != null) { doc = lastDoc; sameUri = uri.equals(lastDoc.getUri()); if (sameUri) { key = factory.newXDMDocumentKey(uri, key.getRevision(), key.getVersion() + 1); } else { key = factory.newXDMDocumentKey(uri, key.getRevision() + 1, dvFirst); } lastDoc = xddCache.get(key); } else { break; } } while (true); if (returnNext) { return key; } if (sameUri) { // the txFinish can be > 0, but not committed yet! // should also check if doc's start transaction is committed.. if (doc.getTxFinish() == 0) { return factory.newXDMDocumentKey(doc.getDocumentKey()); } else { if (skipClosed) { return key; } logger.info("process; the latest document version is finished already: {}", doc); } } return null; } @Override public EntryBackupProcessor<XDMDocumentKey, XDMDocument> getBackupProcessor() { return null; } }
package org.jasig.cas.ticket.registry; import org.jasig.cas.authentication.TestUtils; import org.jasig.cas.authentication.principal.DefaultPrincipalFactory; import org.jasig.cas.authentication.principal.Principal; import org.jasig.cas.mock.MockService; import org.jasig.cas.ticket.ExpirationPolicy; import org.jasig.cas.ticket.ServiceTicket; import org.jasig.cas.ticket.Ticket; import org.jasig.cas.ticket.TicketGrantingTicket; import org.jasig.cas.ticket.TicketGrantingTicketImpl; import org.jasig.cas.ticket.UniqueTicketIdGenerator; import org.jasig.cas.ticket.support.HardTimeoutExpirationPolicy; import org.jasig.cas.ticket.support.MultiTimeUseOrTimeoutExpirationPolicy; import org.jasig.cas.util.DefaultUniqueTicketIdGenerator; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import static org.junit.Assert.*; /** * Unit test for {@link JpaTicketRegistry} class. * * @author Marvin S. Addison * @since 3.0.0 */ public class JpaTicketRegistryTests { /** Number of clients contending for operations in concurrent test. */ private static final int CONCURRENT_SIZE = 20; private static final UniqueTicketIdGenerator ID_GENERATOR = new DefaultUniqueTicketIdGenerator(64); private static final ExpirationPolicy EXP_POLICY_TGT = new HardTimeoutExpirationPolicy(1000); private static final ExpirationPolicy EXP_POLICY_ST = new MultiTimeUseOrTimeoutExpirationPolicy(1, 1000); /** Logger instance. */ private final Logger logger = LoggerFactory.getLogger(getClass()); private PlatformTransactionManager txManager; private TicketRegistry jpaTicketRegistry; @Before public void setup() { final ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:/jpaSpringContext.xml"); this.jpaTicketRegistry = ctx.getBean("jpaTicketRegistry", TicketRegistry.class); this.txManager = ctx.getBean("ticketTransactionManager", PlatformTransactionManager.class); } @Test public void verifyTicketCreationAndDeletion() throws Exception { final TicketGrantingTicket newTgt = newTGT(); addTicketInTransaction(newTgt); final TicketGrantingTicket tgtFromDb = (TicketGrantingTicket) getTicketInTransaction(newTgt.getId()); assertNotNull(tgtFromDb); assertEquals(newTgt.getId(), tgtFromDb.getId()); final ServiceTicket newSt = grantServiceTicketInTransaction(tgtFromDb); final ServiceTicket stFromDb = (ServiceTicket) getTicketInTransaction(newSt.getId()); assertNotNull(stFromDb); assertEquals(newSt.getId(), stFromDb.getId()); deleteTicketInTransaction(newTgt.getId()); assertNull(getTicketInTransaction(newTgt.getId())); assertNull(getTicketInTransaction(newSt.getId())); } @Test public void verifyConcurrentServiceTicketGeneration() throws Exception { final TicketGrantingTicket newTgt = newTGT(); addTicketInTransaction(newTgt); final ExecutorService executor = Executors.newFixedThreadPool(CONCURRENT_SIZE); try { final List<ServiceTicketGenerator> generators = new ArrayList<>(CONCURRENT_SIZE); for (int i = 0; i < CONCURRENT_SIZE; i++) { generators.add(new ServiceTicketGenerator(newTgt.getId(), this.jpaTicketRegistry, this.txManager)); } final List<Future<String>> results = executor.invokeAll(generators); for (final Future<String> result : results) { assertNotNull(result.get()); } } catch (final Exception e) { logger.error("testConcurrentServiceTicketGeneration produced an error", e); fail("testConcurrentServiceTicketGeneration failed."); } finally { executor.shutdownNow(); } } static TicketGrantingTicket newTGT() { final Principal principal = new DefaultPrincipalFactory().createPrincipal( "bob", Collections.singletonMap("displayName", (Object) "Bob")); return new TicketGrantingTicketImpl( ID_GENERATOR.getNewTicketId("TGT"), TestUtils.getAuthentication(principal), EXP_POLICY_TGT); } static ServiceTicket newST(final TicketGrantingTicket parent) { return parent.grantServiceTicket( ID_GENERATOR.getNewTicketId("ST"), new MockService("https://service.example.com"), EXP_POLICY_ST, false, true); } void addTicketInTransaction(final Ticket ticket) { new TransactionTemplate(txManager).execute(new TransactionCallback<Object>() { @Override public Void doInTransaction(final TransactionStatus status) { jpaTicketRegistry.addTicket(ticket); return null; } }); } void deleteTicketInTransaction(final String ticketId) { new TransactionTemplate(txManager).execute(new TransactionCallback<Void>() { @Override public Void doInTransaction(final TransactionStatus status) { jpaTicketRegistry.deleteTicket(ticketId); return null; } }); } Ticket getTicketInTransaction(final String ticketId) { return new TransactionTemplate(txManager).execute(new TransactionCallback<Ticket>() { @Override public Ticket doInTransaction(final TransactionStatus status) { return jpaTicketRegistry.getTicket(ticketId); } }); } ServiceTicket grantServiceTicketInTransaction(final TicketGrantingTicket parent) { return new TransactionTemplate(txManager).execute(new TransactionCallback<ServiceTicket>() { @Override public ServiceTicket doInTransaction(final TransactionStatus status) { final ServiceTicket st = newST(parent); jpaTicketRegistry.addTicket(st); return st; } }); } private static class ServiceTicketGenerator implements Callable<String> { private final PlatformTransactionManager txManager; private final String parentTgtId; private final TicketRegistry jpaTicketRegistry; ServiceTicketGenerator(final String tgtId, final TicketRegistry jpaTicketRegistry, final PlatformTransactionManager txManager) { parentTgtId = tgtId; this.jpaTicketRegistry = jpaTicketRegistry; this.txManager = txManager; } @Override public String call() throws Exception { return new TransactionTemplate(txManager).execute(new TransactionCallback<String>() { @Override public String doInTransaction(final TransactionStatus status) { // Querying for the TGT prior to updating it as done in // CentralAuthenticationServiceImpl#grantServiceTicket(String, Service, Credential) final ServiceTicket st = newST((TicketGrantingTicket) jpaTicketRegistry.getTicket(parentTgtId)); jpaTicketRegistry.addTicket(st); return st.getId(); } }); } } }
package edu.duke.cabig.c3pr.domain.scheduler.runtime.job; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.quartz.JobDataMap; import org.quartz.JobExecutionException; import org.springframework.mail.MailException; import edu.duke.cabig.c3pr.constants.EmailNotificationDeliveryStatusEnum; import edu.duke.cabig.c3pr.constants.NotificationEventTypeEnum; import edu.duke.cabig.c3pr.constants.NotificationFrequencyEnum; import edu.duke.cabig.c3pr.constants.RegistrationWorkFlowStatus; import edu.duke.cabig.c3pr.dao.PlannedNotificationDao; import edu.duke.cabig.c3pr.dao.ScheduledNotificationDao; import edu.duke.cabig.c3pr.dao.StudySubjectDao; import edu.duke.cabig.c3pr.dao.query.DataAuditEventQuery; import edu.duke.cabig.c3pr.domain.ContactMechanismBasedRecipient; import edu.duke.cabig.c3pr.domain.PlannedNotification; import edu.duke.cabig.c3pr.domain.RecipientScheduledNotification; import edu.duke.cabig.c3pr.domain.RoleBasedRecipient; import edu.duke.cabig.c3pr.domain.ScheduledNotification; import edu.duke.cabig.c3pr.domain.StudySubject; import edu.duke.cabig.c3pr.domain.UserBasedRecipient; import edu.duke.cabig.c3pr.domain.repository.AuditHistoryRepository; import edu.duke.cabig.c3pr.utils.NotificationEmailService; import gov.nih.nci.cabig.ctms.audit.domain.DataAuditEvent; /** * This class serves as the Email sending job class scheduled by <code>scheduler</code> * component. * @author Vinay Gangoli */ public class ScheduledNotificationJob extends ScheduledJob { protected static final Log logger = LogFactory.getLog(ScheduledNotificationJob.class); private NotificationEmailService notificationEmailService; private AuditHistoryRepository auditHistoryRepository; private StudySubjectDao studySubjectDao; private PlannedNotificationDao plannedNotificationDao; private ScheduledNotificationDao scheduledNotificationDao; public final String NEW_REGISTATION_REPORT_MESSAGE = "This is the list of New Registrations from last "; public static final String WEEK = "Week"; public static final String MONTH = "Month"; public static final String YEAR = "Year"; public ScheduledNotificationJob(){ super(); } /* * @see edu.duke.cabig.c3pr.domain.scheduler.runtime.job.ScheduledJob#processJob(org.quartz.JobDataMap, org.springframework.context.ApplicationContext, * edu.duke.cabig.c3pr.domain.RecipientScheduledNotification) * This is the job for the Study status change notification email delivery. */ @Override public void processJob(JobDataMap jobDataMap, RecipientScheduledNotification recipientScheduledNotification, PlannedNotification plannedNotification) throws JobExecutionException { logger.debug("Executing ScheduledNotification Job"); assert applicationContext != null: "applicationContext cannot be null"; assert plannedNotification != null: "plannedNotification cant be null"; synchronized (this) { try { // init the member variables notificationEmailService = (NotificationEmailService) applicationContext.getBean("notificationEmailService"); setAuditInfo(); if(recipientScheduledNotification == null){ if(plannedNotification.getFrequency() != NotificationFrequencyEnum.IMMEDIATE){ //Generate the REPORT NOTIFICATION and send it ScheduledNotification scheduledNotification = handleReportGeneration(plannedNotification); if(scheduledNotification != null){ for(RecipientScheduledNotification rsn: scheduledNotification.getRecipientScheduledNotification()){ notificationEmailService.sendReportEmail(rsn); } } else { logger.error("Error during report generation job: scheduledNotification is null. " + "Note: only events can have frequencies other than IMMEDIATE."); } } } else if(recipientScheduledNotification.getDeliveryStatus().equals(EmailNotificationDeliveryStatusEnum.PENDING) || recipientScheduledNotification.getDeliveryStatus().equals(EmailNotificationDeliveryStatusEnum.RETRY) ){ if(plannedNotification.getFrequency().equals(NotificationFrequencyEnum.IMMEDIATE)){ if(recipientScheduledNotification.getRecipient() instanceof UserBasedRecipient){ if(((UserBasedRecipient)recipientScheduledNotification.getRecipient()).getResearchStaff() != null){ logger.error("$$$$$$$$$$ Threads id is :" + Thread.currentThread().getId()); logger.error("$$$$$$$$$$ RBN's id is :" + recipientScheduledNotification.getId()); logger.error("$$$$$$$$$$ ResearchStaff's version is :" + ((UserBasedRecipient)recipientScheduledNotification.getRecipient()).getResearchStaff().getVersion() ); } } notificationEmailService.sendEmail(recipientScheduledNotification); } recipientScheduledNotification.setDeliveryStatus(EmailNotificationDeliveryStatusEnum.COMPLETE); } } catch(MailException me){ logger.error("execution of sendMail failed", me); recipientScheduledNotification.setDeliveryStatus(EmailNotificationDeliveryStatusEnum.RETRY); }catch (Exception e){ logger.error("execution of job failed", e); recipientScheduledNotification.setDeliveryStatus(EmailNotificationDeliveryStatusEnum.ERROR); } finally { if(recipientScheduledNotification.getRecipient() instanceof UserBasedRecipient){ if(((UserBasedRecipient)recipientScheduledNotification.getRecipient()).getResearchStaff() != null){ logger.error("$$$$$$$$$$ FINALLY Threads id is :" + Thread.currentThread().getId()); logger.error("$$$$$$$$$$ FINALLY RBN's id is :" + recipientScheduledNotification.getId()); logger.error("$$$$$$$$$$ FINALLY ResearchStaff's version is :" + ((UserBasedRecipient)recipientScheduledNotification.getRecipient()).getResearchStaff().getVersion() ); } } recipientScheduledNotificationDao.saveOrUpdate(recipientScheduledNotification); } } logger.debug("Exiting ScheduledNotification Job"); } public ScheduledNotification handleReportGeneration(PlannedNotification plannedNotification){ plannedNotificationDao = (PlannedNotificationDao) applicationContext.getBean("plannedNotificationDao"); scheduledNotificationDao = (ScheduledNotificationDao) applicationContext.getBean("scheduledNotificationDao"); //if recipientScheduledNotification is null...create and save both scheduledNotification and recipientScheduledNotification. if(plannedNotification.getEventName().equals(NotificationEventTypeEnum.NEW_REGISTRATION_EVENT_REPORT)){ //gov.nih.nci.cabig.ctms.audit.DataAuditInfo.setLocal(new gov.nih.nci.cabig.ctms.audit.domain.DataAuditInfo( //userName, request.getRemoteAddr(), new Date(),httpReq.getRequestURI())); //gov.nih.nci.cabig.ctms.audit.DataAuditInfo.setLocal(new gov.nih.nci.cabig.ctms.audit.domain.DataAuditInfo( //"C3PR Admin", "C3PR Scheduled Notification Job", new Date(), "C3PR Scheduled Notification Job")); String reportText = generateReportFromHistory(plannedNotification); ScheduledNotification scheduledNotification = addScheduledNotification(plannedNotification, reportText); plannedNotificationDao.saveOrUpdate(plannedNotification); return scheduledNotificationDao.getById(scheduledNotification.getId()); } if(plannedNotification.getEventName().equals(NotificationEventTypeEnum.MASTER_SUBJECT_UPDATED_EVENT)){ String reportText = generateReportFromHistory(plannedNotification); ScheduledNotification scheduledNotification = addScheduledNotification(plannedNotification, reportText); plannedNotificationDao.saveOrUpdate(plannedNotification); return scheduledNotificationDao.getById(scheduledNotification.getId()); } return null; } public ScheduledNotification addScheduledNotification(PlannedNotification plannedNotification, String reportText){ ScheduledNotification scheduledNotification = new ScheduledNotification(); plannedNotification.getScheduledNotifications().add(scheduledNotification); scheduledNotification.setDateSent(new Date()); scheduledNotification.setMessage(reportText); scheduledNotification.setTitle(plannedNotification.getEventName().getDisplayName() + " - " + plannedNotification.getFrequency().getDisplayName() + " Report."); RecipientScheduledNotification rsn; for(RoleBasedRecipient rbr: plannedNotification.getRoleBasedRecipient()){ rsn = new RecipientScheduledNotification(); rsn.setRecipient(rbr); rsn.setIsRead(Boolean.FALSE); rsn.setScheduledNotification(scheduledNotification); rsn.setDeliveryStatus(EmailNotificationDeliveryStatusEnum.PENDING); scheduledNotification.getRecipientScheduledNotification().add(rsn); } for(UserBasedRecipient ubr: plannedNotification.getUserBasedRecipient()){ rsn = new RecipientScheduledNotification(); rsn.setRecipient(ubr); rsn.setIsRead(Boolean.FALSE); rsn.setScheduledNotification(scheduledNotification); rsn.setDeliveryStatus(EmailNotificationDeliveryStatusEnum.PENDING); scheduledNotification.getRecipientScheduledNotification().add(rsn); } for(ContactMechanismBasedRecipient cmbr: plannedNotification.getContactMechanismBasedRecipient()){ rsn = new RecipientScheduledNotification(); rsn.setRecipient(cmbr); rsn.setIsRead(Boolean.FALSE); rsn.setScheduledNotification(scheduledNotification); rsn.setDeliveryStatus(EmailNotificationDeliveryStatusEnum.PENDING); scheduledNotification.getRecipientScheduledNotification().add(rsn); } return scheduledNotification; } /* * generate the new registrations report and assign it to the rsn. */ private String generateReportFromHistory(PlannedNotification plannedNotification){ auditHistoryRepository = (AuditHistoryRepository)applicationContext.getBean("auditHistoryRepository"); studySubjectDao = (StudySubjectDao)applicationContext.getBean("studySubjectDao"); List<DataAuditEvent> daeList = getAuditHistory(auditHistoryRepository, plannedNotification); Iterator iter = daeList.iterator(); List <Integer>idList = new ArrayList<Integer>(); DataAuditEvent auditEvent = null; while(iter.hasNext()){ auditEvent = (DataAuditEvent)iter.next(); idList.add(auditEvent.getReference().getId()); } List<StudySubject> ssList = new ArrayList<StudySubject>(); for(int i = 0; i < idList.size(); i++){ ssList.add(studySubjectDao.getById(idList.get(i))); } return composeReport(ssList, plannedNotification); } /* * create the message format with the values to be reported */ private String composeReport(List<StudySubject> ssList, PlannedNotification plannedNotification){ StringBuffer msgBody = new StringBuffer(); String messageText = " "; String messageTerm = " "; switch(plannedNotification.getEventName()){ case NEW_REGISTRATION_EVENT: messageText = NEW_REGISTATION_REPORT_MESSAGE; break; default: break; } switch(plannedNotification.getFrequency()){ case WEEKLY: messageTerm = WEEK; break; case MONTHLY: messageTerm = MONTH; break; case ANNUAL: messageTerm = YEAR; break; default: break; } msgBody.append("<html><body><br/>"); msgBody.append( messageText + messageTerm + "<br/><br/>"); msgBody.append("<table border ='1'>"); msgBody.append("<tr>"); msgBody.append("<th>" + "Subject MRN" + "</th>"); msgBody.append("<th>" + "Registration Status" + "</th>"); msgBody.append("<th>" + "Subject Name" + "</th>"); msgBody.append("</tr>"); StudySubject ss = null; Iterator iter = ssList.iterator(); while(iter.hasNext()){ ss = (StudySubject)iter.next(); msgBody.append("<tr>"); msgBody.append("<td>" + ss.getStudySubjectDemographics().getMasterSubject().getMRN().getValue()+ "</td>"); msgBody.append("<td>" + ss.getRegWorkflowStatus().getDisplayName()+ "</td>"); msgBody.append("<td>" + ss.getStudySubjectDemographics().getMasterSubject().getFirstName() + " " + ss.getStudySubjectDemographics().getMasterSubject().getLastName() + "</td>"); msgBody.append("</tr>"); } msgBody.append("</table>"); msgBody.append("</body></html>"); return msgBody.toString(); } /* * generate the query and run it against the audit repo to get results for report. */ private List<DataAuditEvent> getAuditHistory(AuditHistoryRepository auditHistoryRepository, PlannedNotification plannedNotification){ DataAuditEventQuery dataAuditEventQuery = new DataAuditEventQuery(); Calendar now = Calendar.getInstance(); Calendar prev = (Calendar)now.clone(); if(plannedNotification.getFrequency().equals(NotificationFrequencyEnum.WEEKLY)){ prev.add(Calendar.DATE, -7); } if(plannedNotification.getFrequency().equals(NotificationFrequencyEnum.MONTHLY)){ prev.add(Calendar.MONTH, -1); } if(plannedNotification.getFrequency().equals(NotificationFrequencyEnum.ANNUAL)){ prev.add(Calendar.YEAR, -1); } dataAuditEventQuery.filterByClassName(StudySubject.class.getName()); dataAuditEventQuery.filterByEndDateBefore(now.getTime()); dataAuditEventQuery.filterByStartDateAfter(prev.getTime()); //where the status has changed to REGISTERED dataAuditEventQuery.filterByValue("regWorkflowStatus", null, RegistrationWorkFlowStatus.ENROLLED.toString()); final List<DataAuditEvent> dataAuditEvents = auditHistoryRepository.findDataAuditEvents(dataAuditEventQuery); return dataAuditEvents; } public NotificationEmailService getNotificationEmailService() { return notificationEmailService; } public void setNotificationEmailService(NotificationEmailService notificationEmailService) { this.notificationEmailService = notificationEmailService; } }
package com.zsmartsystems.zigbee.console.main; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.HashSet; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.xml.PrettyPrintWriter; import com.thoughtworks.xstream.io.xml.StaxDriver; import com.zsmartsystems.zigbee.IeeeAddress; import com.zsmartsystems.zigbee.database.ZclAttributeDao; import com.zsmartsystems.zigbee.database.ZclClusterDao; import com.zsmartsystems.zigbee.database.ZigBeeEndpointDao; import com.zsmartsystems.zigbee.database.ZigBeeNetworkDataStore; import com.zsmartsystems.zigbee.database.ZigBeeNodeDao; import com.zsmartsystems.zigbee.security.ZigBeeKey; import com.zsmartsystems.zigbee.zdo.field.BindingTable; import com.zsmartsystems.zigbee.zdo.field.NodeDescriptor.FrequencyBandType; import com.zsmartsystems.zigbee.zdo.field.NodeDescriptor.MacCapabilitiesType; import com.zsmartsystems.zigbee.zdo.field.NodeDescriptor.ServerCapabilitiesType; import com.zsmartsystems.zigbee.zdo.field.PowerDescriptor.PowerSourceType; /** * Serializes and deserializes the ZigBee network state. * * @author Chris Jackson */ public class ZigBeeDataStore implements ZigBeeNetworkDataStore { /** * The logger. */ private final static Logger logger = LoggerFactory.getLogger(ZigBeeDataStore.class); private final String networkId; public ZigBeeDataStore(String networkId) { this.networkId = "database/" + networkId + "/"; File file = new File(this.networkId); if (file.exists()) { return; } if (!file.mkdirs()) { logger.error("Error creating network database folder {}", file); } } private XStream openStream() { try { XStream stream = new XStream(new StaxDriver()); XStream.setupDefaultSecurity(stream); stream.alias("ZigBeeKey", ZigBeeKey.class); stream.alias("ZigBeeNode", ZigBeeNodeDao.class); stream.alias("ZigBeeEndpoint", ZigBeeEndpointDao.class); stream.alias("ZclCluster", ZclClusterDao.class); stream.alias("ZclAttribute", ZclAttributeDao.class); stream.alias("MacCapabilitiesType", MacCapabilitiesType.class); stream.alias("ServerCapabilitiesType", ServerCapabilitiesType.class); stream.alias("PowerSourceType", PowerSourceType.class); stream.alias("FrequencyBandType", FrequencyBandType.class); stream.alias("BindingTable", BindingTable.class); stream.alias("IeeeAddress", IeeeAddress.class); stream.registerConverter(new IeeeAddressConverter()); // stream.registerLocalConverter(ZigBeeKey.class, "key", new KeyArrayConverter()); // stream.registerLocalConverter(ZigBeeKey.class, "address", new IeeeAddressConverter()); // stream.registerLocalConverter(BindingTable.class, "srcAddr", new IeeeAddressConverter()); // stream.registerLocalConverter(BindingTable.class, "dstAddr", new IeeeAddressConverter()); stream.allowTypesByWildcard(new String[] { "com.zsmartsystems.zigbee.**" }); return stream; } catch (Exception e) { logger.debug("Error opening XStream ", e); return null; } } private File getFile(IeeeAddress address) { return new File(networkId + address + ".xml"); } @Override public Set<IeeeAddress> readNetworkNodes() { Set<IeeeAddress> nodes = new HashSet<>(); File dir = new File(networkId); File[] files = dir.listFiles(); if (files == null) { return nodes; } for (File file : files) { if (!file.getName().toLowerCase().endsWith(".xml")) { continue; } try { IeeeAddress address = new IeeeAddress(file.getName().substring(0, 16)); nodes.add(address); } catch (IllegalArgumentException e) { logger.error("Error parsing database filename: {}", file.getName()); } } return nodes; } @Override public ZigBeeNodeDao readNode(IeeeAddress address) { XStream stream = openStream(); File file = getFile(address); ZigBeeNodeDao node = null; try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"))) { node = (ZigBeeNodeDao) stream.fromXML(reader); reader.close(); logger.info("{}: ZigBee reading network state complete.", address); } catch (Exception e) { logger.error("{}: Error reading network state: ", address, e); } return node; } @Override public void writeNode(ZigBeeNodeDao node) { XStream stream = openStream(); File file = getFile(node.getIeeeAddress()); try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"))) { stream.marshal(node, new PrettyPrintWriter(writer)); writer.close(); logger.info("{}: ZigBee saving network state complete.", node.getIeeeAddress()); } catch (Exception e) { logger.error("{}: Error writing network state: ", node.getIeeeAddress(), e); } } @Override public void removeNode(IeeeAddress address) { File file = getFile(address); if (!file.delete()) { logger.error("{}: Error removing network state", address); } } }