answer
stringlengths
17
10.2M
package org.opendaylight.controller.cluster.datastore.node.utils.stream; import static com.google.common.base.Preconditions.checkArgument; import com.google.common.collect.ImmutableMap; import java.util.Map; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument; final class PathArgumentTypes { static final byte AUGMENTATION_IDENTIFIER = 1; static final byte NODE_IDENTIFIER = 2; static final byte NODE_IDENTIFIER_WITH_VALUE = 3; static final byte NODE_IDENTIFIER_WITH_PREDICATES = 4; private PathArgumentTypes() { throw new UnsupportedOperationException("Utility class"); } private static final Map<Class<?>, Byte> CLASS_TO_ENUM_MAP = ImmutableMap.<Class<?>, Byte>builder() .put(AugmentationIdentifier.class, AUGMENTATION_IDENTIFIER) .put(NodeIdentifier.class, NODE_IDENTIFIER) .put(NodeIdentifierWithPredicates.class, NODE_IDENTIFIER_WITH_PREDICATES) .put(NodeWithValue.class, NODE_IDENTIFIER_WITH_VALUE).build(); static byte getSerializablePathArgumentType(final PathArgument pathArgument) { final Byte type = CLASS_TO_ENUM_MAP.get(pathArgument.getClass()); checkArgument(type != null, "Unknown type of PathArgument = %s", pathArgument); return type; } }
package com.yahoo.jdisc.http.server.jetty; import com.yahoo.jdisc.http.ConnectorConfig; import org.eclipse.jetty.server.AcceptRateLimit; import org.eclipse.jetty.server.ConnectionLimit; import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.LowResourceMonitor; import org.eclipse.jetty.util.component.LifeCycle; import java.time.Duration; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Queue; import java.util.concurrent.TimeUnit; import static java.util.Collections.singleton; /** * Throttles new connections using {@link LowResourceMonitor}, {@link AcceptRateLimit} and {@link ConnectionLimit}. * * @author bjorncs */ class ConnectionThrottler { private final Object monitor = new Object(); private final Queue<Runnable> throttleResetters = new ArrayDeque<>(); private final Collection<LifeCycle> beans = new ArrayList<>(); private final Connector connector; private int throttlersCount; ConnectionThrottler(Connector connector, ConnectorConfig.Throttling config) { this.connector = connector; Duration idleTimeout = fromSeconds(config.idleTimeout()); if (config.maxAcceptRate() != -1) { beans.add(new CoordinatedAcceptRateLimit(config.maxAcceptRate(), fromSeconds(config.maxAcceptRatePeriod()))); } if (config.maxConnections() != -1) { beans.add(new CoordinatedConnectionLimit(config.maxConnections(), idleTimeout)); } if (config.maxHeapUtilization() != -1) { beans.add(new CoordinatedLowResourcesLimit(config.maxHeapUtilization(), idleTimeout)); } } void registerBeans() { beans.forEach(bean -> connector.getServer().addBean(bean)); } private static Duration fromSeconds(double seconds) { return Duration.ofMillis((long) (seconds * 1000)); } private void onThrottle(Runnable throttleResetter) { synchronized (monitor) { ++throttlersCount; throttleResetters.offer(throttleResetter); } } private void onReset() { List<Runnable> resetters = new ArrayList<>(); synchronized (monitor) { if (--throttlersCount == 0) { resetters.addAll(throttleResetters); throttleResetters.clear(); } } resetters.forEach(Runnable::run); } private static long toMaxMemoryUsageInBytes(double maxHeapUtilization) { return (long) (maxHeapUtilization * Runtime.getRuntime().maxMemory()); } private class CoordinatedLowResourcesLimit extends LowResourceMonitor { CoordinatedLowResourcesLimit(double maxHeapUtilization, Duration idleTimeout) { super(connector.getServer()); super.setMonitoredConnectors(singleton(connector)); super.setMaxMemory(toMaxMemoryUsageInBytes(maxHeapUtilization)); super.setLowResourcesIdleTimeout((int)idleTimeout.toMillis()); } @Override protected void setLowResources() { super.setLowResources(); ConnectionThrottler.this.onThrottle(() -> super.clearLowResources()); } @Override protected void clearLowResources() { ConnectionThrottler.this.onReset(); } } private class CoordinatedConnectionLimit extends ConnectionLimit { CoordinatedConnectionLimit(int maxConnections, Duration idleTimeout) { super(maxConnections, connector); super.setIdleTimeout(idleTimeout.toMillis()); } @Override protected void limit() { super.limit(); ConnectionThrottler.this.onThrottle(() -> super.unlimit()); } @Override protected void unlimit() { ConnectionThrottler.this.onReset(); } } private class CoordinatedAcceptRateLimit extends AcceptRateLimit { CoordinatedAcceptRateLimit(int limit, Duration period) { super(limit, period.toMillis(), TimeUnit.MILLISECONDS, connector); } @Override protected void limit() { super.limit(); ConnectionThrottler.this.onThrottle(() -> super.unlimit()); } @Override protected void unlimit() { ConnectionThrottler.this.onReset(); } } }
package com.wci.umls.server.jpa.algo.action; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Properties; import java.util.Set; import com.google.common.base.CaseFormat; import com.wci.umls.server.AlgorithmParameter; import com.wci.umls.server.Project; import com.wci.umls.server.ValidationResult; import com.wci.umls.server.algo.action.MolecularActionAlgorithm; import com.wci.umls.server.helpers.ConfigUtility; import com.wci.umls.server.helpers.HasId; import com.wci.umls.server.helpers.HasLastModified; import com.wci.umls.server.helpers.LocalException; import com.wci.umls.server.helpers.TrackingRecordList; import com.wci.umls.server.jpa.actions.MolecularActionJpa; import com.wci.umls.server.jpa.algo.AbstractAlgorithm; import com.wci.umls.server.jpa.content.ConceptJpa; import com.wci.umls.server.jpa.services.helper.IndexUtility; import com.wci.umls.server.model.actions.AtomicAction; import com.wci.umls.server.model.actions.MolecularAction; import com.wci.umls.server.model.content.Atom; import com.wci.umls.server.model.content.AtomRelationship; import com.wci.umls.server.model.content.Concept; import com.wci.umls.server.model.content.ConceptRelationship; import com.wci.umls.server.model.workflow.TrackingRecord; import com.wci.umls.server.model.workflow.WorkflowStatus; /** * Abstract {@link MolecularActionAlgorithm}. */ public abstract class AbstractMolecularAction extends AbstractAlgorithm implements MolecularActionAlgorithm { /** The Constant LOCK. */ private final static String LOCK = "lock"; /** The concept id. */ private Long conceptId; /** The concept id 2. */ private Long conceptId2; /** The concept. */ private Concept concept; /** The concept2. */ private Concept concept2; /** The last modified. */ private Long lastModified; /** The change status flag. */ private boolean changeStatusFlag; /** The override warnings. */ private boolean overrideWarnings; /** The validation checks. */ private List<String> validationChecks = null; /** * Instantiates an empty {@link AbstractMolecularAction}. * * @throws Exception the exception */ public AbstractMolecularAction() throws Exception { super(); } /* see superclass */ @Override public void reset() throws Exception { } /** * Returns the concept id. * * @return the concept id */ public Long getConceptId() { return conceptId; } /** * Sets the concept id. * * @param conceptId the concept id */ public void setConceptId(Long conceptId) { this.conceptId = conceptId; } /** * Returns the concept id 2. * * @return the concept id 2 */ public Long getConceptId2() { return conceptId2; } /** * Sets the concept id 2. * * @param conceptId2 the concept id 2 */ public void setConceptId2(Long conceptId2) { this.conceptId2 = conceptId2; } /* see superclass */ @Override public Concept getConcept() { return concept; } /* see superclass */ @Override public Concept getConcept2() { return concept2; } /** * Sets the concept 2. * * @param concept2 the concept 2 */ public void setConcept2(Concept concept2) { this.concept2 = concept2; } /* see superclass */ @Override public Long getLastModified() { return lastModified; } /** * Sets the last modified. * * @param lastModified the last modified */ public void setLastModified(Long lastModified) { this.lastModified = lastModified; } /* see superclass */ @Override public boolean getChangeStatusFlag() { return changeStatusFlag; } /* see superclass */ @Override public String getName() { String objectName = this.getClass().getSimpleName(); objectName = objectName.replace("MolecularAction", ""); objectName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, objectName); objectName = objectName.toUpperCase(); return objectName; } /* see superclass */ @Override public void setChangeStatusFlag(boolean changeStatusFlag) { this.changeStatusFlag = changeStatusFlag; } /** * Sets the override warnings. * * @param overrideWarnings the override warnings */ public void setOverrideWarnings(boolean overrideWarnings) { this.overrideWarnings = overrideWarnings; } /** * Indicates whether or not override warnings is the case. * * @return <code>true</code> if so, <code>false</code> otherwise */ public boolean isOverrideWarnings() { return overrideWarnings; } /* see superclass */ @Override public ValidationResult checkPreconditions() throws Exception { return validateAction(this); } /* see superclass */ @Override public void initialize(Project project, Long conceptId, Long conceptId2, Long lastModified, boolean molecularActionFlag) throws Exception { setProject(project); this.lastModified = lastModified; // For undo-redo, lastModified can be null. // if (lastModified == null) { // throw new Exception("Unexpected null concept last modified value"); // Global lock to acquire list of concept ids to lock. final List<Long> conceptIdList = new ArrayList<>(); synchronized (LOCK) { // Extract concept ids and sort them final Set<Long> conceptIds = new HashSet<>(); if (conceptId != null) { conceptIds.add(conceptId); } if (conceptId2 != null && !(conceptId2.equals(conceptId))) { conceptIds.add(conceptId2); } // If locking related concepts, add them to the list if (lockRelatedConcepts()) { for (final Long id : new ArrayList<>(conceptIds)) { final Concept concept = getConcept(id); for (final ConceptRelationship rel : concept.getRelationships()) { conceptIds.add(rel.getTo().getId()); } } } conceptIdList.addAll(conceptIds); // Sort in id order for locking Collections.sort(conceptIdList); } // Clear concept references (this is probably unnecessary) this.concept = null; this.concept2 = null; // Iterate for (final Long i : conceptIdList) { Concept tempConcept = null; // Lock on the concept id (in Java) synchronized (i.toString().intern()) { // retrieve the concept tempConcept = getConcept(i); // only lock concepts that exist (because in undo/redo they may not) if (tempConcept == null) { continue; } if (i == conceptId) { concept = new ConceptJpa(tempConcept, true); } if (i == conceptId2) { concept2 = new ConceptJpa(tempConcept, true); } // Fail if already locked - this is secondary protection if (isObjectLocked(tempConcept)) { // unlock concepts and fail rollback(); throw new Exception("Fatal error: concept is locked " + i); } // lock the concept via JPA lockObject(tempConcept); } } // Pick up the terminology/version from concept if (concept != null) { setTerminology(concept.getTerminology()); setVersion(concept.getVersion()); } // In some situations, concept will be null (e.g. undoing a merge). Use // concept2 instead. else if (concept2 != null) { setTerminology(concept2.getTerminology()); setVersion(concept2.getVersion()); } else { rollback(); throw new Exception("Unexpected missing concept for action " + conceptId); } // Prepare the service setMolecularActionFlag(molecularActionFlag); setLastModifiedFlag(true); // construct the molecular action if (molecularActionFlag) { final MolecularAction molecularAction = new MolecularActionJpa(); molecularAction.setTerminology((concept != null ? concept.getTerminology() : concept2.getTerminology())); molecularAction.setComponentId(conceptId); molecularAction.setComponentId2(conceptId2); molecularAction.setVersion( (concept != null ? concept.getVersion() : concept2.getVersion())); molecularAction.setName(getName()); molecularAction.setTimestamp(new Date()); molecularAction.setActivityId(getActivityId()); molecularAction.setWorkId(getWorkId()); // Add the molecular action and pass to the service. // It needs to be added now so that when atomic actions // an identifier. final MolecularAction newMolecularAction = addMolecularAction(molecularAction); setMolecularAction(newMolecularAction); } // // throw exception on terminology mismatch // if (!project.getTerminology().equals((concept != null // ? concept.getTerminology() : concept2.getTerminology()))) { // // unlock concepts and fail // rollback(); // throw new Exception("Project and concept terminologies do not match"); // Concept freshness check - the driving concept of the action // should match the "last modified" value. // NOTE: this fails to do a last modified check when undoing a merge if (concept != null && lastModified != null && concept.getLastModified().getTime() != lastModified.longValue()) { // unlock concepts and fail rollback(); throw new LocalException( "Concept is stale, click 'Refresh' and try again (" + ConfigUtility.DATE_FORMAT4.format(new Date(lastModified)) + (concept != null ? ", " + ConfigUtility.DATE_FORMAT4.format(concept.getLastModified()) : " ") + ")"); } } /** * Find rel to concept containing atom. * * @param fromConcept the from concept * @param toAtom the to atom * @return the concept relationship * @throws Exception the exception */ @SuppressWarnings("static-method") public ConceptRelationship findRelToConceptContainingAtom(Concept fromConcept, Atom toAtom) throws Exception { for (ConceptRelationship rel : fromConcept.getRelationships()) { Concept toConcept = rel.getTo(); for (Atom atom : toConcept.getAtoms()) { if (atom.getId().equals(toAtom.getId())) { return rel; } } } return null; } /** * Find demotion between concepts. * * @param relationship the relationship * @return the atom relationship * @throws Exception the exception */ public List<AtomRelationship> findDemotionsMatchingRelationship( ConceptRelationship relationship) throws Exception { final List<AtomRelationship> rels = new ArrayList<>(); final List<Atom> fromAtoms = getConcept(relationship.getFrom().getId()).getAtoms(); final List<Atom> toAtoms = getConcept(relationship.getTo().getId()).getAtoms(); for (final Atom fromAtom : fromAtoms) { for (final AtomRelationship atomRel : fromAtom.getRelationships()) { for (final Atom toAtom : toAtoms) { if (atomRel.getTo().getId().equals(toAtom.getId()) && atomRel.getWorkflowStatus() == WorkflowStatus.DEMOTION) { rels.add(atomRel); } } } } return rels; } /** * Indicates whether or not delete action is the case. * * @param action the action * @return <code>true</code> if so, <code>false</code> otherwise */ @SuppressWarnings("static-method") public boolean isRemoveAction(AtomicAction action) { return action.getNewValue() == null && action.getField().equals("id"); } /** * Indicates whether or not insert action is the case. * * @param action the action * @return <code>true</code> if so, <code>false</code> otherwise */ @SuppressWarnings("static-method") public boolean isAddAction(AtomicAction action) { return action.getOldValue() == null && action.getField().equals("id"); } /** * Indicates whether or not change action is the case. * * @param action the action * @return <code>true</code> if so, <code>false</code> otherwise */ @SuppressWarnings("static-method") public boolean isChangeAction(AtomicAction action) { return action.getOldValue() != null && action.getNewValue() != null && action.getCollectionClassName() == null; } /** * Indicates whether or not collections action is the case. * * @param action the action * @return <code>true</code> if so, <code>false</code> otherwise */ @SuppressWarnings("static-method") public boolean isCollectionsAction(AtomicAction action) { return action.getCollectionClassName() != null; } /** * Returns the referenced object. * * @param action the action * @return the referenced object * @throws Exception the exception */ public HasLastModified getReferencedObject(AtomicAction action) throws Exception { final Object referencedObject = getObject(action.getObjectId(), Class.forName(action.getClassName())); if (referencedObject == null) { throw new Exception("Unable to find referenced object for " + action.getObjectId() + ", " + action.getClassName()); } return (HasLastModified) referencedObject; } /** * Returns the referenced collection object. * * @param action the action * @return the referenced collection object * @throws Exception the exception */ public HasLastModified getReferencedCollectionObject(AtomicAction action) throws Exception { final String id = action.getOldValue() == null ? action.getNewValue() : action.getOldValue(); final Object referencedObject = getObject(Long.parseLong(id), Class.forName(action.getCollectionClassName())); if (referencedObject == null) { throw new Exception("Unable to find referenced (collection) object for " + id + ", " + action.getCollectionClassName()); } return (HasLastModified) referencedObject; } /** * Returns the collection. * * @param a the a * @param containerObject the referenced object * @return the collection * @throws Exception the exception */ @SuppressWarnings({ "static-method", "rawtypes" }) public Collection getCollection(AtomicAction a, Object containerObject) throws Exception { final List<Method> oneToManyMethods = IndexUtility.getAllCollectionGetMethods(containerObject.getClass()); // Iterate through @OneToMan methods for (final Method m : oneToManyMethods) { if (IndexUtility.getFieldNameFromMethod(m, null).equals(a.getField())) { return (Collection) m.invoke(containerObject, new Object[] {}); } } throw new Exception( "Unable to find collection method for: " + a.getField()); } /** * Returns the column method. * * @param a the a * @return the column method * @throws Exception the exception */ @SuppressWarnings("static-method") public Method getColumnGetMethod(AtomicAction a) throws Exception { final List<Method> oneToManyMethods = IndexUtility.getAllColumnGetMethods(Class.forName(a.getClassName())); // Iterate through @OneToMan methods for (final Method m : oneToManyMethods) { if (IndexUtility.getFieldNameFromMethod(m, null).equals(a.getField())) { return m; } } throw new Exception( "Unable to find column get method for: " + a.getField()); } /** * Returns the column set method. * * @param a the a * @return the column set method * @throws Exception the exception */ @SuppressWarnings("static-method") public Method getColumnSetMethod(AtomicAction a) throws Exception { final List<Method> oneToManyMethods = IndexUtility.getAllColumnSetMethods(Class.forName(a.getClassName())); // Iterate through @OneToMan methods for (final Method m : oneToManyMethods) { if (IndexUtility.getFieldNameFromMethod(m, null).equals(a.getField())) { return m; } } throw new Exception( "Unable to find column set method for: " + a.getField()); } /** * Returns the object for value. * * @param type the type * @param value the value * @return the object for value * @throws Exception the exception */ @SuppressWarnings("static-method") public Object getObjectForValue(Class<?> type, String value) throws Exception { Object setObject = null; if (type == String.class) { setObject = value; } else if (type == Long.class) { setObject = Long.parseLong(value); } else if (type == WorkflowStatus.class) { setObject = WorkflowStatus.valueOf(value); } else if (type == boolean.class) { if (value.equals("true")) { setObject = true; } else if (value.equals("false")) { setObject = false; } else { setObject = null; } } else { throw new Exception( "Unrecognized getter method type for undo operation - " + type); } return setObject; } /* see superclass */ @Override public List<AlgorithmParameter> getParameters() { throw new UnsupportedOperationException( "Individual molecular actions should not " + "be used as configurable algorithms"); } /* see superclass */ @Override public void checkProperties(Properties p) throws Exception { } /* see superclass */ /* see superclass */ @Override public void setProperties(Properties p) throws Exception { throw new UnsupportedOperationException( "Individual molecular actions should not " + "be used as configurable algorithms"); } /* see superclass */ @Override public List<String> getValidationChecks() { return validationChecks; } /* see superclass */ @Override public void setValidationChecks(List<String> validationChecks) { this.validationChecks = validationChecks; } /** * Post action maintenance. * * @throws Exception the exception */ public void postActionMaintenance() throws Exception { final Set<Concept> concepts = new HashSet<>(); if (getConcept() != null) { concepts.add(getConcept(getConcept().getId())); } if (getConcept2() != null) { concepts.add(getConcept(getConcept2().getId())); } // Start a new action that doesn't create molecular/atomic actions beginTransaction(); setMolecularActionFlag(false); // Only concepts that exist and contain atoms will need to go through this // process final Set<Long> recordsSeen = new HashSet<>(); for (final Concept c : concepts) { if (c != null && !c.getAtoms().isEmpty()) { // Recompute tracking record workflow status // Any tracking record that references this concept may potentially be // updated. final TrackingRecordList records = findTrackingRecordsForConcept(getProject(), c, null, null); // Set trackingRecord to READY_FOR_PUBLICATION if all contained // concepts and atoms are all set to READY_FOR_PUBLICATION. if (records != null) { for (final TrackingRecord record : records.getObjects()) { if (!recordsSeen.contains(record.getId())) { final WorkflowStatus status = computeTrackingRecordStatus(record); if (record.getWorkflowStatus() != status) { record.setWorkflowStatus(status); updateTrackingRecord(record); } recordsSeen.add(record.getId()); } } } // Recompute the concept's preferred name c.setName(getComputePreferredNameHandler(c.getTerminology()) .computePreferredName(c.getAtoms(), getPrecedenceList(c.getTerminology(), c.getVersion()))); updateConcept(c); } } commit(); close(); } /* see superclass */ @Override public boolean lockRelatedConcepts() { return false; } /* see superclass */ @Override public String getDescription() { return getName(); } /** * Removes the by id. * * @param list the list * @param id the id */ @SuppressWarnings("static-method") public void removeById(List<? extends HasId> list, Long id) { int index = 0; for (final HasId obj : list) { if (obj.getId().equals(id)) { list.remove(index); break; } index++; } } }
package org.motechproject.nms.language.service.impl; import org.motechproject.nms.language.domain.CircleLanguage; import org.motechproject.nms.language.domain.Language; import org.motechproject.nms.language.repository.CircleLanguageDataService; import org.motechproject.nms.language.repository.LanguageDataService; import org.motechproject.nms.language.service.LanguageService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; /** * Implementation of the {@link LanguageService} interface. */ @Service("languageService") public class LanguageServiceImpl implements LanguageService { @Autowired private LanguageDataService languageDataService; @Autowired private CircleLanguageDataService circleLanguageDataService; /** * Returns the language for a given code * @param code the language code * @return the language object if found */ public Language getLanguageByCode(String code) { return languageDataService.findByCode(code); } /** * Returns the default language for the circle * * @param circle The code for the circle * @return The default language for the circle or null if no languages are found for circle */ @Override public Language getDefaultCircleLanguage(String circle) { Language defaultLanguage = null; List<CircleLanguage> circleLanguages = circleLanguageDataService.findByCircle(circle); //todo #120 revisit when we know what to do with multiple default languages if (circleLanguages.size() > 0) { defaultLanguage = circleLanguages.get(0).getLanguage(); } return defaultLanguage; } /** * Returns all languages for a given circle * * @param circle The code for the circle * @return A list that contains all languages for the circle. If no languages are found an empty list is returned */ @Override public List<Language> getCircleLanguages(String circle) { List<CircleLanguage> circleLanguages = circleLanguageDataService.findByCircle(circle); List<Language> languages = new ArrayList<Language>(); for (CircleLanguage circleLanguage : circleLanguages) { languages.add(circleLanguage.getLanguage()); } return languages; } @Override public Language getLanguage(String code) { return languageDataService.findByCode(code); } }
package org.languagetool.rules.nl; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.ResourceBundle; import org.languagetool.Language; import org.languagetool.rules.AbstractCheckCaseRule; public class CheckCaseRule extends AbstractCheckCaseRule { private static final String FILE_NAME = "/nl/check_case.txt"; private static final Locale NL_LOCALE = new Locale("nl"); public CheckCaseRule(ResourceBundle messages, Language language) { super(messages, language); this.setDefaultTempOff(); } @Override public List<String> getFileNames() { return Arrays.asList(FILE_NAME); } @Override public String getId() { return "NL_CHECKCASE"; } @Override public String getDescription() { return "Controle op hoofd- en kleine letters"; } @Override public String getShort() { return "Schrijfwijze"; } @Override public String getMessage() { return "Aanbevolen schrijfwijze"; } @Override public Locale getLocale() { return NL_LOCALE; } }
package com.matthewtamlin.spyglass.library.use_adapters; import com.matthewtamlin.spyglass.library.use_annotations.UseDouble; import static com.matthewtamlin.java_utilities.checkers.NullChecker.checkNotNull; public class UseDoubleAdapter implements UseAdapter<Double, UseDouble> { @Override public Double getValue(final UseDouble annotation) { checkNotNull(annotation, "Argument 'annotation' cannot be null."); return annotation.value(); } }
package org.libreplan.web.planner.order; import static org.libreplan.web.I18nHelper._; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.lang.Validate; import org.apache.commons.logging.Log; import org.libreplan.business.orders.entities.Order; import org.libreplan.business.planner.entities.TaskElement; import org.libreplan.web.common.ViewSwitcher; import org.libreplan.web.common.components.bandboxsearch.BandboxMultipleSearch; import org.libreplan.web.common.components.finders.FilterPair; import org.libreplan.web.orders.OrderCRUDController; import org.libreplan.web.planner.TaskElementPredicate; import org.libreplan.web.planner.advances.AdvanceAssignmentPlanningController; import org.libreplan.web.planner.calendar.CalendarAllocationController; import org.libreplan.web.planner.consolidations.AdvanceConsolidationController; import org.libreplan.web.planner.taskedition.AdvancedAllocationTaskController; import org.libreplan.web.planner.taskedition.EditTaskController; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import org.zkoss.ganttz.FilterAndParentExpandedPredicates; import org.zkoss.ganttz.Planner; import org.zkoss.ganttz.data.Task; import org.zkoss.ganttz.extensions.ContextWithPlannerTask; import org.zkoss.ganttz.extensions.ICommand; import org.zkoss.ganttz.extensions.IContext; import org.zkoss.ganttz.extensions.IContextWithPlannerTask; import org.zkoss.ganttz.timetracker.zoom.ZoomLevel; import org.zkoss.ganttz.util.LongOperationFeedback; import org.zkoss.ganttz.util.LongOperationFeedback.ILongOperation; import org.zkoss.ganttz.util.ProfilingLogFactory; import org.zkoss.zk.ui.Executions; import org.zkoss.zk.ui.Sessions; import org.zkoss.zk.ui.WrongValueException; import org.zkoss.zk.ui.util.Composer; import org.zkoss.zk.ui.util.GenericForwardComposer; import org.zkoss.zul.Checkbox; import org.zkoss.zul.Constraint; import org.zkoss.zul.Datebox; import org.zkoss.zul.Popup; import org.zkoss.zul.Textbox; import org.zkoss.zul.Vbox; @Component @Scope(BeanDefinition.SCOPE_PROTOTYPE) public class OrderPlanningController implements Composer { private static final Log PROFILING_LOG = ProfilingLogFactory .getLog(OrderPlanningController.class); @Autowired private ViewSwitcher viewSwitcher; private Map<String, String[]> parameters; @Autowired private IOrderPlanningModel model; private Planner planner; @Autowired private CalendarAllocationController calendarAllocationController; @Autowired private EditTaskController editTaskController; @Autowired private AdvancedAllocationTaskController advancedAllocationTaskController; @Autowired private AdvanceConsolidationController advanceConsolidationController; @Autowired private AdvanceAssignmentPlanningController advanceAssignmentPlanningController; @Autowired private OrderCRUDController orderCRUDController; private GenericForwardComposer currentControllerToShow; private Order order; private TaskElement task; private List<ICommand<TaskElement>> additional = new ArrayList<ICommand<TaskElement>>(); private Vbox orderElementFilter; private Datebox filterStartDateOrderElement; private Datebox filterFinishDateOrderElement; private Checkbox labelsWithoutInheritance; private BandboxMultipleSearch bdFiltersOrderElement; private Textbox filterNameOrderElement; private Popup filterOptionsPopup; public OrderPlanningController() { } public List<org.libreplan.business.planner.entities.TaskElement> getCriticalPath() { return planner != null ? planner.getCriticalPath() : null; } public void setOrder(Order order, ICommand<TaskElement>... additionalCommands) { Validate.notNull(additionalCommands); Validate.noNullElements(additionalCommands); this.order = order; this.additional = Arrays.asList(additionalCommands); if (planner != null) { ensureIsInPlanningOrderView(); updateConfiguration(); onApplyFilter(); } } public void setShowedTask(TaskElement task) { this.task = task; } public CalendarAllocationController getCalendarAllocationController() { return calendarAllocationController; } private void ensureIsInPlanningOrderView() { viewSwitcher.goToPlanningOrderView(); } public ViewSwitcher getViewSwitcher() { return viewSwitcher; } @Override public void doAfterCompose(org.zkoss.zk.ui.Component comp) { this.planner = (Planner) comp; String zoomLevelParameter = null; if ((parameters != null) && (parameters.get("zoom") != null) && !(parameters.isEmpty())) { zoomLevelParameter = parameters.get("zoom")[0]; } ZoomLevel sessionZoom = (ZoomLevel) Sessions.getCurrent().getAttribute( "zoomLevel"); // ZoomLevel sessionZoom = (ZoomLevel) // Sessions.getCurrent().getAttribute( // order.getCode() + "zoomLevel"); if (order != null) { System.out.println("expecting to get" + order.getCode() + sessionZoom); } else { System.out.println("expecting to get (null)" + sessionZoom); } if (sessionZoom != null) { zoomLevelParameter = sessionZoom.getInternalName(); } if (zoomLevelParameter != null) { planner.setInitialZoomLevel(ZoomLevel .getFromString(zoomLevelParameter)); } planner.setAreContainersExpandedByDefault(Planner .guessContainersExpandedByDefault(parameters)); planner.setAreShownAdvancesByDefault(Planner .guessShowAdvancesByDefault(parameters)); planner.setAreShownReportedHoursByDefault(Planner .guessShowReportedHoursByDefault(parameters)); planner.setAreShownMoneyCostBarByDefault(Planner .guessShowMoneyCostBarByDefault(parameters)); orderElementFilter = (Vbox) planner.getFellow("orderElementFilter"); // Configuration of the order filter org.zkoss.zk.ui.Component filterComponent = Executions .createComponents("/orders/_orderElementTreeFilter.zul", orderElementFilter, new HashMap<String, String>()); filterComponent.setVariable("treeController", this, true); filterOptionsPopup = (Popup) filterComponent .getFellow("filterOptionsPopup"); filterStartDateOrderElement = (Datebox) filterOptionsPopup .getFellow("filterStartDateOrderElement"); filterFinishDateOrderElement = (Datebox) filterOptionsPopup .getFellow("filterFinishDateOrderElement"); labelsWithoutInheritance = (Checkbox) filterOptionsPopup .getFellow("labelsWithoutInheritance"); bdFiltersOrderElement = (BandboxMultipleSearch) filterComponent .getFellow("bdFiltersOrderElement"); bdFiltersOrderElement.setFinder("taskElementsMultipleFiltersFinder"); filterNameOrderElement = (Textbox) filterComponent .getFellow("filterNameOrderElement"); filterComponent.setVisible(true); updateConfiguration(); } private void updateConfiguration() { if (order != null) { importOrderFiltersFromSession(); long time = System.currentTimeMillis(); model.setConfigurationToPlanner(planner, order, viewSwitcher, editTaskController, advancedAllocationTaskController, advanceAssignmentPlanningController, advanceConsolidationController, calendarAllocationController, additional); PROFILING_LOG.debug("setConfigurationToPlanner took: " + (System.currentTimeMillis() - time) + " ms"); planner.updateSelectedZoomLevel(); showResorceAllocationIfIsNeeded(); } } private void importOrderFiltersFromSession() { filterNameOrderElement.setValue((String) Sessions.getCurrent() .getAttribute(order.getCode() + "-tasknameFilter")); filterStartDateOrderElement.setValue((Date) Sessions.getCurrent() .getAttribute(order.getCode() + "-startDateFilter")); filterFinishDateOrderElement.setValue((Date) Sessions.getCurrent() .getAttribute(order.getCode() + "-endDateFilter")); if (Sessions.getCurrent().getAttribute( order.getCode() + "-inheritanceFilter") != null) { labelsWithoutInheritance.setChecked((Boolean) Sessions.getCurrent() .getAttribute(order.getCode() + "-inheritanceFilter")); } } public EditTaskController getEditTaskController() { return editTaskController; } public AdvancedAllocationTaskController getAdvancedAllocationTaskController() { return advancedAllocationTaskController; } public OrderCRUDController getOrderCRUDController() { return orderCRUDController; } public void setURLParameters(Map<String, String[]> parameters) { this.parameters = parameters; } public Order getOrder() { return model.getOrder(); } public void onApplyFilter() { filterByPredicate(createPredicate()); } private TaskElementPredicate createPredicate() { List<FilterPair> listFilters = (List<FilterPair>) bdFiltersOrderElement .getSelectedElements(); Date startDate = filterStartDateOrderElement.getValue(); Date finishDate = filterFinishDateOrderElement.getValue(); boolean ignoreLabelsInheritance = labelsWithoutInheritance.isChecked(); String name = filterNameOrderElement.getValue(); if (listFilters.isEmpty() && startDate == null && finishDate == null && name == null) { return null; } Sessions.getCurrent().setAttribute(order.getCode() + "-tasknameFilter", name); Sessions.getCurrent().setAttribute( order.getCode() + "-startDateFilter", startDate); Sessions.getCurrent().setAttribute(order.getCode() + "-endDateFilter", finishDate); Sessions.getCurrent() .setAttribute(order.getCode() + "-inheritanceFilter", ignoreLabelsInheritance); Sessions.getCurrent().setAttribute( order.getCode() + "-labelsandcriteriaFilter", listFilters); return new TaskElementPredicate(listFilters, startDate, finishDate, name, ignoreLabelsInheritance); } public Checkbox getLabelsWithoutInheritance() { return labelsWithoutInheritance; } public void setLabelsWithoutInheritance(Checkbox labelsWithoutInheritance) { this.labelsWithoutInheritance = labelsWithoutInheritance; } private void filterByPredicate(final TaskElementPredicate predicate) { LongOperationFeedback.execute(orderElementFilter, new ILongOperation() { @Override public void doAction() { // FIXME remove or change model.forceLoadLabelsAndCriterionRequirements(); final IContext<?> context = planner.getContext(); FilterAndParentExpandedPredicates newPredicate = new FilterAndParentExpandedPredicates( context) { @Override public boolean accpetsFilterPredicate(Task task) { if (predicate == null) { return true; } TaskElement taskElement = (TaskElement) context .getMapper() .findAssociatedDomainObject(task); return predicate.accepts(taskElement); } }; newPredicate.setFilterContainers(planner.getPredicate() .isFilterContainers()); planner.setTaskListPredicate(newPredicate); } @Override public String getName() { return _("filtering"); } }); } public Constraint checkConstraintFinishDate() { return new Constraint() { @Override public void validate(org.zkoss.zk.ui.Component comp, Object value) throws WrongValueException { Date finishDate = (Date) value; if ((finishDate != null) && (filterStartDateOrderElement.getValue() != null) && (finishDate.compareTo(filterStartDateOrderElement .getValue()) < 0)) { filterFinishDateOrderElement.setValue(null); throw new WrongValueException(comp, _("must be after start date")); } } }; } public Constraint checkConstraintStartDate() { return new Constraint() { @Override public void validate(org.zkoss.zk.ui.Component comp, Object value) throws WrongValueException { Date startDate = (Date) value; if ((startDate != null) && (filterFinishDateOrderElement.getValue() != null) && (startDate.compareTo(filterFinishDateOrderElement .getValue()) > 0)) { filterStartDateOrderElement.setValue(null); throw new WrongValueException(comp, _("must be lower than end date")); } } }; } public void showResorceAllocationIfIsNeeded() { if ((task != null) && (planner != null)) { planner.expandAllAlways(); Task foundTask = null; TaskElement foundTaskElement = null; IContext<TaskElement> context = (IContext<TaskElement>) planner .getContext(); Map<TaskElement, Task> map = context.getMapper() .getMapDomainToTask(); for (Entry<TaskElement, Task> entry : map.entrySet()) { if (task.getId().equals(entry.getKey().getId())) { foundTaskElement = entry.getKey(); foundTask = entry.getValue(); } } if ((foundTask != null) && (foundTaskElement != null)) { IContextWithPlannerTask<TaskElement> contextTask = ContextWithPlannerTask .create(context, foundTask); if (this.getCurrentControllerToShow().equals( getEditTaskController())) { this.editTaskController.showEditFormResourceAllocation( contextTask, foundTaskElement, model.getPlanningState()); } else if (this.getCurrentControllerToShow().equals( this.getAdvanceAssignmentPlanningController())) { getAdvanceAssignmentPlanningController().showWindow( contextTask, foundTaskElement, model.getPlanningState()); } } } } public AdvanceConsolidationController getAdvanceConsolidationController() { return advanceConsolidationController; } public AdvanceAssignmentPlanningController getAdvanceAssignmentPlanningController() { return advanceAssignmentPlanningController; } public void setCurrentControllerToShow(GenericForwardComposer currentControllerToShow) { this.currentControllerToShow = currentControllerToShow; } public GenericForwardComposer getCurrentControllerToShow() { return currentControllerToShow; } }
package org.sourcepit.maven.bootstrap.it; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsEqual.equalTo; import static org.junit.Assert.assertThat; import java.io.File; import java.util.Arrays; import java.util.Iterator; import java.util.List; import org.junit.Test; import org.sourcepit.common.maven.testing.ExternalMavenTest; import org.sourcepit.common.testing.Environment; /** * @author Bernd Vogt <bernd.vogt@sourcepit.org> */ public class BuildBootstrapperIT extends ExternalMavenTest { @Override protected boolean isDebug() { return false; } @Override protected Environment newEnvironment() { return Environment.get("env-it.properties"); } @Test public void testSimpleProject() throws Exception { final File projectDir = getResource("simple-project"); final int error = build(projectDir, "-e", "-B", "compile"); assertThat(error, is(0)); Report bootstrapperReport = new Report(new File(projectDir, TestBootstrapper.class.getName() + ".txt")); List<String> lines = bootstrapperReport.readLines(); assertThat(lines.size(), is(4)); Iterator<String> it = lines.iterator(); assertThat(it.next(), equalTo("getModuleDescriptors")); assertThat(it.next(), equalTo("pom.xml")); assertThat(it.next(), equalTo("beforeBootstrapProjects")); assertThat(it.next(), equalTo("afterWrapperProjectsInitialized")); Report participantReport = new Report(new File(projectDir, TestBootstrapParticipant.class.getName() + ".txt")); lines = participantReport.readLines(); assertThat(lines.size(), is(2)); it = lines.iterator(); assertThat(it.next(), equalTo("beforeBuild,org.sourcepit.it,simple-project")); assertThat(it.next(), equalTo("afterBuild,org.sourcepit.it,simple-project")); } @Test public void testReactorProject() throws Exception { final File projectDir = getResource("reactor-project"); final int error = build(projectDir, "-e", "-B", "compile"); assertThat(error, is(0)); Report bootstrapperReport = new Report(new File(projectDir, TestBootstrapper.class.getName() + ".txt")); List<String> lines = bootstrapperReport.readLines(); assertThat(lines.size(), is(4)); Iterator<String> it = lines.iterator(); assertThat(it.next(), equalTo("getModuleDescriptors")); // we musn't rely on module build ordering, it differs from system to system final List<String> poms = Arrays.asList(it.next().split(",")); assertThat(poms.size(), is(3)); assertThat(poms.contains("pom.xml"), is(true)); assertThat(poms.contains("module-project-b/pom.xml"), is(true)); assertThat(poms.contains("module-project-a/pom.xml"), is(true)); assertThat(it.next(), equalTo("beforeBootstrapProjects")); assertThat(it.next(), equalTo("afterWrapperProjectsInitialized")); Report participantReport = new Report(new File(projectDir, TestBootstrapParticipant.class.getName() + ".txt")); lines = participantReport.readLines(); assertThat(lines.size(), is(4)); it = lines.iterator(); assertThat(it.next(), equalTo("beforeBuild,org.sourcepit.it,module-project-b")); assertThat(it.next(), equalTo("beforeBuild,org.sourcepit.it,module-project-a")); assertThat(it.next(), equalTo("afterBuild,org.sourcepit.it,module-project-b")); assertThat(it.next(), equalTo("afterBuild,org.sourcepit.it,module-project-a")); } }
package org.mockserver.maven; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.resolver.ArtifactResolver; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.repository.RepositorySystem; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.concurrent.ExecutionException; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import static org.mockito.MockitoAnnotations.initMocks; /** * @author jamesdbloom */ public class MockServerRunForkedMojoTest { public final String level = "LEVEL"; private final String jarWithDependenciesPath = new File("jarWithDependenciesPath.jar").getAbsolutePath(); private String javaBinaryPath = "java"; @Mock protected RepositorySystem mockRepositorySystem; @Mock protected ArtifactResolver mockArtifactResolver; @Mock private InstanceHolder mockEmbeddedJettyHolder; @Mock private ProcessBuildFactory mockProcessBuildFactory; @InjectMocks private MockServerRunForkedMojo mockServerRunForkedMojo; private ProcessBuilder processBuilder; @Mock private Artifact mockArtifact; @Before public void setupMocks() { processBuilder = new ProcessBuilder("echo", ""); mockServerRunForkedMojo = new MockServerRunForkedMojo(); javaBinaryPath = mockServerRunForkedMojo.getJavaBin(); initMocks(this); when(mockRepositorySystem.createArtifactWithClassifier("org.mock-server", "mockserver-netty", mockServerRunForkedMojo.getVersion(), "jar", "jar-with-dependencies")).thenReturn(mockArtifact); when(mockArtifact.getFile()).thenReturn(new File(jarWithDependenciesPath)); mockServerRunForkedMojo.logLevel = level; } @Test public void shouldRunMockServerAndProxyForkedBothPortsSpecified() throws MojoExecutionException, ExecutionException, InterruptedException { // given mockServerRunForkedMojo.serverPort = 1; mockServerRunForkedMojo.serverSecurePort = 2; mockServerRunForkedMojo.proxyPort = 3; mockServerRunForkedMojo.pipeLogToConsole = true; when(mockProcessBuildFactory.create(anyListOf(String.class))).thenReturn(processBuilder); // when mockServerRunForkedMojo.execute(); // then verify(mockRepositorySystem).createArtifactWithClassifier("org.mock-server", "mockserver-netty", mockServerRunForkedMojo.getVersion(), "jar", "jar-with-dependencies"); verify(mockProcessBuildFactory).create(Arrays.asList( javaBinaryPath, "-Dfile.encoding=UTF-8", "-Dmockserver.logLevel=" + level, "-cp", jarWithDependenciesPath, "org.mockserver.cli.Main", "-serverPort", "1", "-serverSecurePort", "2", "-proxyPort", "3" )); assertEquals(true, processBuilder.redirectErrorStream()); } @Test public void shouldRunMockServerAndProxyForkedOnlyNonSecurePort() throws MojoExecutionException, ExecutionException, InterruptedException { // given mockServerRunForkedMojo.serverPort = 1; mockServerRunForkedMojo.serverSecurePort = -1; mockServerRunForkedMojo.proxyPort = 3; mockServerRunForkedMojo.pipeLogToConsole = true; when(mockProcessBuildFactory.create(anyListOf(String.class))).thenReturn(processBuilder); // when mockServerRunForkedMojo.execute(); // then verify(mockRepositorySystem).createArtifactWithClassifier("org.mock-server", "mockserver-netty", mockServerRunForkedMojo.getVersion(), "jar", "jar-with-dependencies"); verify(mockProcessBuildFactory).create(Arrays.asList( javaBinaryPath, "-Dfile.encoding=UTF-8", "-Dmockserver.logLevel=" + level, "-cp", jarWithDependenciesPath, "org.mockserver.cli.Main", "-serverPort", "1", "-proxyPort", "3" )); assertEquals(true, processBuilder.redirectErrorStream()); } @Test public void shouldRunMockServerAndProxyForkedOnlySecurePort() throws MojoExecutionException, ExecutionException, InterruptedException { // given mockServerRunForkedMojo.serverPort = -1; mockServerRunForkedMojo.serverSecurePort = 2; mockServerRunForkedMojo.proxyPort = -1; mockServerRunForkedMojo.pipeLogToConsole = true; when(mockProcessBuildFactory.create(anyListOf(String.class))).thenReturn(processBuilder); // when mockServerRunForkedMojo.execute(); // then verify(mockRepositorySystem).createArtifactWithClassifier("org.mock-server", "mockserver-netty", mockServerRunForkedMojo.getVersion(), "jar", "jar-with-dependencies"); verify(mockProcessBuildFactory).create(Arrays.asList( javaBinaryPath, "-Dfile.encoding=UTF-8", "-Dmockserver.logLevel=" + level, "-cp", jarWithDependenciesPath, "org.mockserver.cli.Main", "-serverSecurePort", "2" )); assertEquals(true, processBuilder.redirectErrorStream()); } @Test public void shouldRunMockServerOnlyForkedBothPortsSpecified() throws MojoExecutionException, ExecutionException, InterruptedException { // given ExampleInitializationClass.mockServerClient = null; mockServerRunForkedMojo.serverPort = 1; mockServerRunForkedMojo.serverSecurePort = 2; mockServerRunForkedMojo.pipeLogToConsole = true; mockServerRunForkedMojo.initializationClass = "org.mockserver.maven.ExampleInitializationClass"; String classLocation = "org/mockserver/maven/ExampleInitializationClass.class"; mockServerRunForkedMojo.compileClasspath = Arrays.asList(ExampleInitializationClass.class.getClassLoader().getResource(classLocation).getFile().replaceAll(classLocation, "")); mockServerRunForkedMojo.testClasspath = Arrays.asList(); when(mockProcessBuildFactory.create(anyListOf(String.class))).thenReturn(processBuilder); // when mockServerRunForkedMojo.execute(); // then verify(mockProcessBuildFactory).create(Arrays.asList( javaBinaryPath, "-Dfile.encoding=UTF-8", "-Dmockserver.logLevel=" + level, "-cp", jarWithDependenciesPath, "org.mockserver.cli.Main", "-serverPort", "1", "-serverSecurePort", "2" )); assertEquals(true, processBuilder.redirectErrorStream()); assertNotNull(ExampleInitializationClass.mockServerClient); } @Test public void shouldRunMockServerOnlyForkedOnlyNonSecurePort() throws MojoExecutionException, ExecutionException, InterruptedException { // given ExampleInitializationClass.mockServerClient = null; mockServerRunForkedMojo.serverPort = 1; mockServerRunForkedMojo.serverSecurePort = -1; mockServerRunForkedMojo.pipeLogToConsole = true; mockServerRunForkedMojo.initializationClass = "org.mockserver.maven.ExampleInitializationClass"; String classLocation = "org/mockserver/maven/ExampleInitializationClass.class"; mockServerRunForkedMojo.compileClasspath = Arrays.asList(ExampleInitializationClass.class.getClassLoader().getResource(classLocation).getFile().replaceAll(classLocation, "")); mockServerRunForkedMojo.testClasspath = Arrays.asList(); when(mockProcessBuildFactory.create(anyListOf(String.class))).thenReturn(processBuilder); // when mockServerRunForkedMojo.execute(); // then verify(mockRepositorySystem).createArtifactWithClassifier("org.mock-server", "mockserver-netty", mockServerRunForkedMojo.getVersion(), "jar", "jar-with-dependencies"); verify(mockProcessBuildFactory).create(Arrays.asList( javaBinaryPath, "-Dfile.encoding=UTF-8", "-Dmockserver.logLevel=" + level, "-cp", jarWithDependenciesPath, "org.mockserver.cli.Main", "-serverPort", "1" )); assertEquals(true, processBuilder.redirectErrorStream()); assertNotNull(ExampleInitializationClass.mockServerClient); } @Test public void shouldRunMockServerOnlyForkedOnlySecurePort() throws MojoExecutionException, ExecutionException, InterruptedException { // given ExampleInitializationClass.mockServerClient = null; mockServerRunForkedMojo.serverPort = -1; mockServerRunForkedMojo.serverSecurePort = 2; mockServerRunForkedMojo.pipeLogToConsole = true; mockServerRunForkedMojo.initializationClass = "org.mockserver.maven.ExampleInitializationClass"; when(mockProcessBuildFactory.create(anyListOf(String.class))).thenReturn(processBuilder); // when mockServerRunForkedMojo.execute(); // then verify(mockRepositorySystem).createArtifactWithClassifier("org.mock-server", "mockserver-netty", mockServerRunForkedMojo.getVersion(), "jar", "jar-with-dependencies"); verify(mockProcessBuildFactory).create(Arrays.asList( javaBinaryPath, "-Dfile.encoding=UTF-8", "-Dmockserver.logLevel=" + level, "-cp", jarWithDependenciesPath, "org.mockserver.cli.Main", "-serverSecurePort", "2" )); assertEquals(true, processBuilder.redirectErrorStream()); assertNull(ExampleInitializationClass.mockServerClient); } @Test public void shouldRunProxyOnlyForkedBothPortsSpecified() throws MojoExecutionException, ExecutionException, InterruptedException { // given ExampleInitializationClass.mockServerClient = null; mockServerRunForkedMojo.proxyPort = 1; mockServerRunForkedMojo.pipeLogToConsole = true; mockServerRunForkedMojo.initializationClass = "org.mockserver.maven.ExampleInitializationClass"; when(mockProcessBuildFactory.create(anyListOf(String.class))).thenReturn(processBuilder); // when mockServerRunForkedMojo.execute(); // then verify(mockRepositorySystem).createArtifactWithClassifier("org.mock-server", "mockserver-netty", mockServerRunForkedMojo.getVersion(), "jar", "jar-with-dependencies"); verify(mockProcessBuildFactory).create(Arrays.asList( javaBinaryPath, "-Dfile.encoding=UTF-8", "-Dmockserver.logLevel=" + level, "-cp", jarWithDependenciesPath, "org.mockserver.cli.Main", "-proxyPort", "1" )); assertEquals(true, processBuilder.redirectErrorStream()); assertNull(ExampleInitializationClass.mockServerClient); } @Test public void shouldRunProxyOnlyForkedOnlyNonSecurePort() throws MojoExecutionException, ExecutionException, InterruptedException { // given mockServerRunForkedMojo.proxyPort = 1; mockServerRunForkedMojo.pipeLogToConsole = true; when(mockProcessBuildFactory.create(anyListOf(String.class))).thenReturn(processBuilder); // when mockServerRunForkedMojo.execute(); // then verify(mockRepositorySystem).createArtifactWithClassifier("org.mock-server", "mockserver-netty", mockServerRunForkedMojo.getVersion(), "jar", "jar-with-dependencies"); verify(mockProcessBuildFactory).create(Arrays.asList( javaBinaryPath, "-Dfile.encoding=UTF-8", "-Dmockserver.logLevel=" + level, "-cp", jarWithDependenciesPath, "org.mockserver.cli.Main", "-proxyPort", "1" )); assertEquals(true, processBuilder.redirectErrorStream()); } @Test public void shouldHandleProcessException() throws IOException { // given when(mockProcessBuildFactory.create(anyListOf(String.class))).thenReturn(new ProcessBuilder("TEST FAIL")); // when try { mockServerRunForkedMojo.execute(); } catch (Throwable t) { // then fail(); } } @Test public void shouldRunMockServerForkedAndNotPipeToConsole() throws MojoExecutionException, ExecutionException, InterruptedException { // given mockServerRunForkedMojo.pipeLogToConsole = false; when(mockProcessBuildFactory.create(anyListOf(String.class))).thenReturn(processBuilder); // when mockServerRunForkedMojo.execute(); // then verify(mockRepositorySystem).createArtifactWithClassifier("org.mock-server", "mockserver-netty", mockServerRunForkedMojo.getVersion(), "jar", "jar-with-dependencies"); assertEquals(false, processBuilder.redirectErrorStream()); } @Test public void shouldHandleIncorrectInitializationClassName() throws MojoExecutionException { // given mockServerRunForkedMojo.serverPort = 1; mockServerRunForkedMojo.serverSecurePort = 2; mockServerRunForkedMojo.pipeLogToConsole = true; mockServerRunForkedMojo.initializationClass = "org.mockserver.maven.InvalidClassName"; when(mockProcessBuildFactory.create(anyListOf(String.class))).thenReturn(processBuilder); // when mockServerRunForkedMojo.execute(); assertNull(ExampleInitializationClass.mockServerClient); } @Test public void shouldSkipStoppingMockServer() throws MojoExecutionException { // given mockServerRunForkedMojo.skip = true; // when mockServerRunForkedMojo.execute(); // then verify(mockProcessBuildFactory, times(0)).create(anyListOf(String.class)); } }
package com.evolveum.midpoint.model.sync; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.xml.bind.JAXBElement; import javax.xml.namespace.QName; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.Validate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import com.evolveum.midpoint.common.DebugUtil; import com.evolveum.midpoint.common.QueryUtil; import com.evolveum.midpoint.common.patch.PatchXml; import com.evolveum.midpoint.common.result.OperationResult; import com.evolveum.midpoint.common.result.OperationResultStatus; import com.evolveum.midpoint.model.controller.ModelController; import com.evolveum.midpoint.model.expr.ExpressionException; import com.evolveum.midpoint.model.expr.ExpressionHandler; import com.evolveum.midpoint.provisioning.api.ChangeNotificationDispatcher; import com.evolveum.midpoint.provisioning.api.ResourceObjectChangeListener; import com.evolveum.midpoint.schema.XsdTypeConverter; import com.evolveum.midpoint.schema.constants.ObjectTypes; import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.exception.SystemException; import com.evolveum.midpoint.schema.util.JAXBUtil; import com.evolveum.midpoint.util.DOMUtil; import com.evolveum.midpoint.util.logging.LoggingUtils; import com.evolveum.midpoint.util.logging.Trace; import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_1.ExpressionType; import com.evolveum.midpoint.xml.ns._public.common.common_1.ObjectChangeAdditionType; import com.evolveum.midpoint.xml.ns._public.common.common_1.ObjectChangeDeletionType; import com.evolveum.midpoint.xml.ns._public.common.common_1.ObjectChangeModificationType; import com.evolveum.midpoint.xml.ns._public.common.common_1.ObjectChangeType; import com.evolveum.midpoint.xml.ns._public.common.common_1.ObjectFactory; import com.evolveum.midpoint.xml.ns._public.common.common_1.ObjectModificationType; import com.evolveum.midpoint.xml.ns._public.common.common_1.ObjectType; import com.evolveum.midpoint.xml.ns._public.common.common_1.PagingType; import com.evolveum.midpoint.xml.ns._public.common.common_1.QueryType; import com.evolveum.midpoint.xml.ns._public.common.common_1.ResourceObjectShadowChangeDescriptionType; import com.evolveum.midpoint.xml.ns._public.common.common_1.ResourceObjectShadowType; import com.evolveum.midpoint.xml.ns._public.common.common_1.ResourceType; import com.evolveum.midpoint.xml.ns._public.common.common_1.SynchronizationSituationType; import com.evolveum.midpoint.xml.ns._public.common.common_1.SynchronizationType; import com.evolveum.midpoint.xml.ns._public.common.common_1.SynchronizationType.Reaction; import com.evolveum.midpoint.xml.ns._public.common.common_1.UserType; /** * * @author lazyman * */ @Service(value = "synchronizationService") public class SynchronizationService implements ResourceObjectChangeListener { private static final Trace LOGGER = TraceManager.getTrace(SynchronizationService.class); @Autowired(required = true) private ModelController controller; @Autowired(required = true) private ActionManager<Action> actionManager; @Autowired private ExpressionHandler expressionHandler; @Autowired private ChangeNotificationDispatcher notificationManager; @PostConstruct public void registerForResourceObjectChangeNotifications() { notificationManager.registerNotificationListener(this); } @PreDestroy public void unregisterForResourceObjectChangeNotifications() { notificationManager.unregisterNotificationListener(this); } @Override public void notifyChange(ResourceObjectShadowChangeDescriptionType change, OperationResult parentResult) { Validate.notNull(change, "Resource object shadow change description must not be null."); Validate.notNull(change.getObjectChange(), "Object change in change description must not be null."); Validate.notNull(change.getResource(), "Resource in change must not be null."); Validate.notNull(parentResult, "Parent operation result must not be null."); OperationResult subResult = parentResult.createSubresult(NOTIFY_CHANGE); try { ResourceType resource = change.getResource(); if (resource == null) { String message = "Resource definition not found in change."; LOGGER.debug(message); subResult.recordFatalError(message); return; } LOGGER.debug("Resource definition found in change."); if (!isSynchronizationEnabled(resource.getSynchronization())) { String message = "Synchronization is not enabled."; LOGGER.debug(message); subResult.recordStatus(OperationResultStatus.SUCCESS, message); return; } LOGGER.debug("Synchronization is enabled."); ResourceObjectShadowType objectShadow = change.getShadow(); if (objectShadow == null && (change.getObjectChange() instanceof ObjectChangeAdditionType)) { // There may not be a previous shadow in addition. But in that // case we have (almost) everything in the ObjectChangeType - // almost everything except OID. But we can live with that. objectShadow = (ResourceObjectShadowType) ((ObjectChangeAdditionType) change .getObjectChange()).getObject(); } if (objectShadow == null) { throw new IllegalArgumentException("Change doesn't contain ResourceObjectShadow."); } ResourceObjectShadowType objectShadowAfterChange = getObjectAfterChange(objectShadow, change.getObjectChange()); LOGGER.debug("Resource object shadow after change resolved. (Object in log on TRACE level)"); if (LOGGER.isTraceEnabled()) { LOGGER.trace(JAXBUtil.silentMarshalWrap(objectShadowAfterChange)); } SynchronizationSituation situation = checkSituation(change, objectShadowAfterChange, subResult); notifyChange(change, situation, resource, objectShadowAfterChange, subResult); } finally { LOGGER.debug(subResult.dump()); } } /** * Apply the changes to the provided shadow. * * @param objectShadow * shadow with some data * @param change * changes to be applied */ @SuppressWarnings("unchecked") private ResourceObjectShadowType getObjectAfterChange(ResourceObjectShadowType objectShadow, ObjectChangeType change) { LOGGER.debug("Resolving resource object shadow after change."); if (change instanceof ObjectChangeAdditionType) { ObjectChangeAdditionType objectAddition = (ObjectChangeAdditionType) change; ObjectType object = objectAddition.getObject(); if (object instanceof ResourceObjectShadowType) { return (ResourceObjectShadowType) object; } else { throw new IllegalArgumentException("The changed object is not a shadow, it is " + object.getClass().getName()); } } else if (change instanceof ObjectChangeModificationType) { try { ObjectChangeModificationType objectModification = (ObjectChangeModificationType) change; ObjectModificationType modification = objectModification.getObjectModification(); PatchXml patchXml = new PatchXml(); String patchedXml = patchXml.applyDifferences(modification, objectShadow); ResourceObjectShadowType changedResourceShadow = ((JAXBElement<ResourceObjectShadowType>) JAXBUtil .unmarshal(patchedXml)).getValue(); return changedResourceShadow; } catch (Exception ex) { throw new SystemException(ex.getMessage(), ex); } } else if (change instanceof ObjectChangeDeletionType) { // in case of deletion the object has already all that it can have return objectShadow; } else { throw new IllegalArgumentException("Unknown change type " + change.getClass().getName()); } } private boolean isSynchronizationEnabled(SynchronizationType synchronization) { if (synchronization == null || synchronization.isEnabled() == null) { return false; } return synchronization.isEnabled(); } // XXX: in situation when one account belongs to two different idm users // (repository returns only first user). It should be changed because // otherwise we can't check SynchronizationSituationType.CONFLICT situation private SynchronizationSituation checkSituation(ResourceObjectShadowChangeDescriptionType change, ResourceObjectShadowType objectShadowAfterChange, OperationResult result) { OperationResult subResult = result.createSubresult(CHECK_SITUATION); if (change.getShadow() != null) { LOGGER.trace("Determining situation for OID {}.", new Object[] { change.getShadow().getOid() }); } else { LOGGER.trace("Determining situation for new resource object."); } ResourceObjectShadowType resourceShadow = change.getShadow(); ModificationType modification = getModificationType(change.getObjectChange()); SynchronizationSituation situation = null; try { UserType user = null; if (resourceShadow != null && resourceShadow.getOid() != null && !resourceShadow.getOid().isEmpty()) { user = controller.listAccountShadowOwner(resourceShadow.getOid(), subResult); } if (user != null) { LOGGER.trace("Shadow OID {} does have owner: {}", change.getShadow().getOid(), user.getOid()); SynchronizationSituationType state = null; switch (modification) { case ADD: case MODIFY: // if user is found it means account/group is linked to // resource state = SynchronizationSituationType.CONFIRMED; break; case DELETE: state = SynchronizationSituationType.DELETED; } situation = new SynchronizationSituation(user, state); } else { LOGGER.trace("Resource object shadow doesn't have owner."); situation = checkSituationWithCorrelation(change, objectShadowAfterChange, modification, result); } } catch (Exception ex) { LOGGER.error("Error occured during resource object shadow owner lookup."); throw new SystemException("Error occured during resource object shadow owner lookup, reason: " + ex.getMessage(), ex); } finally { subResult.computeStatus(); } LOGGER.trace("checkSituation::end - {}, {}", new Object[] { (situation.getUser() == null ? "null" : situation.getUser().getOid()), situation.getSituation() }); return situation; } /** * account is not linked to user. you have to use correlation and * confirmation rule to be shure user for this account doesn't exists * resourceShadow only contains the data that were in the repository before * the change. But the correlation/confirmation should work on the updated * data. Therefore let's apply the changes before running * correlation/confirmation * * @throws SynchronizationException */ private SynchronizationSituation checkSituationWithCorrelation( ResourceObjectShadowChangeDescriptionType change, ResourceObjectShadowType objectShadowAfterChange, ModificationType modification, OperationResult result) throws SynchronizationException { ResourceObjectShadowType resourceShadow = change.getShadow(); // It is better to get resource from change. The resource object may // have only resourceRef ResourceType resource = change.getResource(); SynchronizationType synchronization = resource.getSynchronization(); UserType user = null; SynchronizationSituationType state = null; LOGGER.debug("CORRELATION: Looking for list of users based on correlation rule."); List<UserType> users = findUsersByCorrelationRule(objectShadowAfterChange, synchronization.getCorrelation(), result); if (synchronization.getConfirmation() == null) { if (resourceShadow != null) { LOGGER.debug("CONFIRMATION: No expression for oid {}, accepting all results of correlation", new Object[] { resourceShadow.getOid() }); } else { LOGGER.debug("CONFIRMATION: No expression for new resource object, accepting all results of correlation"); } } else { LOGGER.debug("CONFIRMATION: Checking users from correlation with confirmation rule."); users = findUserByConfirmationRule(users, objectShadowAfterChange, synchronization.getConfirmation(), result); } if (users == null || users.size() == 0) { state = SynchronizationSituationType.UNMATCHED; } else { switch (users.size()) { case 1: if (ModificationType.ADD.equals(modification)) { state = SynchronizationSituationType.FOUND; } else { state = SynchronizationSituationType.UNASSIGNED; } user = users.get(0); break; default: state = SynchronizationSituationType.DISPUTED; } } return new SynchronizationSituation(user, state); } private ModificationType getModificationType(ObjectChangeType change) { if (change instanceof ObjectChangeAdditionType) { return ModificationType.ADD; } else if (change instanceof ObjectChangeModificationType) { return ModificationType.MODIFY; } else if (change instanceof ObjectChangeDeletionType) { return ModificationType.DELETE; } throw new SystemException("Unknown modification type - change '" + change.getClass() + "'."); } private enum ModificationType { ADD, DELETE, MODIFY; } private void notifyChange(ResourceObjectShadowChangeDescriptionType change, SynchronizationSituation situation, ResourceType resource, ResourceObjectShadowType objectShadowAfterChange, OperationResult parentResult) { SynchronizationType synchronization = resource.getSynchronization(); List<Action> actions = findActionsForReaction(synchronization.getReaction(), situation.getSituation()); if (actions.isEmpty()) { LOGGER.warn("Skipping synchronization on resource: {}. Actions was not found.", new Object[] { resource.getName() }); return; } if (change.getShadow() != null && change.getShadow().getResource() == null) { // This should hold under interface contract, but let's be on the // safe side if (change.getShadow().getResourceRef() != null) { if (!change.getShadow().getResourceRef().getOid().equals(resource.getOid())) { String message = "OID of resource does not match OID in shadow resourceRef"; parentResult.recordFatalError(message); throw new SystemException(message); } } change.getShadow().setResource(resource); } try { LOGGER.trace("Updating user started."); String userOid = situation.getUser() == null ? null : situation.getUser().getOid(); for (Action action : actions) { LOGGER.debug("ACTION: Executing: {}.", new Object[] { action.getClass() }); userOid = action.executeChanges(userOid, change, situation.getSituation(), objectShadowAfterChange, parentResult); } LOGGER.trace("Updating user finished."); } catch (SynchronizationException ex) { LoggingUtils.logException(LOGGER, "### SYNCHRONIZATION # notifyChange(..): Synchronization action failed", ex); parentResult.recordFatalError("Synchronization action failed.", ex); throw new SystemException("Synchronization action failed, reason: " + ex.getMessage(), ex); } catch (Exception ex) { LoggingUtils.logException(LOGGER, "### SYNCHRONIZATION # notifyChange(..): Unexpected " + "error occured, synchronization action failed", ex); parentResult.recordFatalError("Unexpected error occured, synchronization action failed.", ex); throw new SystemException("Unexpected error occured, synchronization action failed, reason: " + ex.getMessage(), ex); } parentResult.recordSuccess(); } private List<Action> findActionsForReaction(List<Reaction> reactions, SynchronizationSituationType situation) { List<Action> actions = new ArrayList<Action>(); if (reactions == null) { return actions; } Reaction reaction = null; for (Reaction react : reactions) { if (react.getSituation() == null) { LOGGER.warn("Reaction ({}) doesn't contain situation element, skipping.", reactions.indexOf(react)); continue; } if (situation.equals(react.getSituation())) { reaction = react; break; } } if (reaction == null) { LOGGER.warn("Reaction on situation {} was not found.", situation); return actions; } List<Reaction.Action> actionList = reaction.getAction(); for (Reaction.Action actionXml : actionList) { if (actionXml == null) { LOGGER.warn("Reaction ({}) doesn't contain action element, skipping.", reactions.indexOf(reaction)); return actions; } if (actionXml.getRef() == null) { LOGGER.warn("Reaction ({}): Action element doesn't contain ref attribute, skipping.", reactions.indexOf(reaction)); return actions; } Action action = actionManager.getActionInstance(actionXml.getRef()); if (action == null) { LOGGER.warn("Couln't create action with uri '{}' for reaction {}, skipping action.", actionXml.getRef(), reactions.indexOf(reaction)); continue; } action.setParameters(actionXml.getAny()); actions.add(action); } return actions; } private List<UserType> findUsersByCorrelationRule(ResourceObjectShadowType resourceShadow, QueryType query, OperationResult result) throws SynchronizationException { if (query == null) { LOGGER.error("Corrrelation rule for resource '{}' doesn't contain query, " + "returning empty list of users.", resourceShadow.getName()); return null; } Element element = query.getFilter(); if (element == null) { LOGGER.error("Corrrelation rule for resource '{}' doesn't contain query, " + "returning empty list of users.", resourceShadow.getName()); return null; } Element filter = updateFilterWithAccountValues(resourceShadow, element, result); if (filter == null) { LOGGER.debug("Couldn't create search filter from correlation rule."); return null; } List<UserType> users = null; try { query = new ObjectFactory().createQueryType(); query.setFilter(filter); LOGGER.debug("CORRELATION: expression for OID {} results in filter {}", resourceShadow.getOid(), DebugUtil.prettyPrint(query)); PagingType paging = new PagingType(); users = controller.searchObjects(UserType.class, query, paging, result); if (users == null) { return null; } } catch (Exception ex) { LoggingUtils.logException(LOGGER, "Couldn't search users in repository, based on filter (simplified)\n{}.", ex, DebugUtil.prettyPrint(filter)); throw new SynchronizationException( "Couldn't search users in repository, based on filter (See logs).", ex); } LOGGER.debug("CORRELATION: expression for OID {} returned {} users.", new Object[] { resourceShadow.getOid(), users.size() }); return users; } private List<UserType> findUserByConfirmationRule(List<UserType> users, ResourceObjectShadowType resourceObjectShadowType, ExpressionType expression, OperationResult result) throws SynchronizationException { List<UserType> list = new ArrayList<UserType>(); if (users == null) { LOGGER.debug("Correlation list is null or empty. Returning empty confirmation list."); return list; } for (UserType user : users) { try { boolean confirmedUser = expressionHandler.evaluateConfirmationExpression(user, resourceObjectShadowType, expression, result); if (user != null && confirmedUser) { list.add(user); } } catch (ExpressionException ex) { LoggingUtils.logException(LOGGER, "Couldn't confirm user {}", ex, user.getName()); throw new SynchronizationException("Couldn't confirm user " + user.getName(), ex); } } LOGGER.debug("CONFIRMATION: expression for OID {} matched {} users.", resourceObjectShadowType.getOid(), list.size()); return list; } private Element updateFilterWithAccountValues(ResourceObjectShadowType resourceObjectShadow, Element filter, OperationResult result) throws SynchronizationException { LOGGER.trace("updateFilterWithAccountValues::begin"); if (filter == null) { return null; } try { LOGGER.trace("Transforming search filter from:\n{}", DOMUtil.printDom(filter.getOwnerDocument())); Document document = DOMUtil.getDocument(); Element and = document.createElementNS(SchemaConstants.NS_C, "and"); document.appendChild(and); and.appendChild(QueryUtil.createTypeFilter(document, ObjectTypes.USER.getObjectTypeUri())); Element equal = null; if (SchemaConstants.NS_C.equals(filter.getNamespaceURI()) && "equal".equals(filter.getLocalName())) { equal = (Element) document.adoptNode(filter.cloneNode(true)); Element path = findChildElement(equal, SchemaConstants.NS_C, "path"); if (path != null) { equal.removeChild(path); } Element valueExpressionElement = findChildElement(equal, SchemaConstants.NS_C, "valueExpression"); if (valueExpressionElement != null) { equal.removeChild(valueExpressionElement); Element refElement = findChildElement(valueExpressionElement, SchemaConstants.NS_C, "ref"); QName ref = DOMUtil.resolveQName(refElement); Element value = document.createElementNS(SchemaConstants.NS_C, "value"); equal.appendChild(value); Element attribute = document.createElementNS(ref.getNamespaceURI(), ref.getLocalPart()); ExpressionType valueExpression = XsdTypeConverter.toJavaValue(valueExpressionElement, ExpressionType.class); String expressionResult = expressionHandler.evaluateExpression(resourceObjectShadow, valueExpression, result); if (StringUtils.isEmpty(expressionResult)) { LOGGER.debug("Expression result from search filter expression was null or empty (trying " + "to create filter with empty name attribute, while transforming search filter)."); return null; } // TODO: log more context LOGGER.debug("Search filter expression in the rule for OID {} evaluated to {}.", new Object[] { resourceObjectShadow.getOid(), expressionResult }); attribute.setTextContent(expressionResult); value.appendChild(attribute); and.appendChild(equal); } else { LOGGER.warn("No valueExpression in rule for OID {}", resourceObjectShadow.getOid()); } } filter = and; LOGGER.trace("Transforming filter to:\n{}", DOMUtil.printDom(filter.getOwnerDocument())); } catch (Exception ex) { LoggingUtils.logException(LOGGER, "Couldn't transform filter.", ex); throw new SynchronizationException("Couldn't transform filter, reason: " + ex.getMessage(), ex); } LOGGER.trace("updateFilterWithAccountValues::end"); return filter; } private Element findChildElement(Element element, String namespace, String name) { NodeList list = element.getChildNodes(); for (int i = 0; i < list.getLength(); i++) { Node node = list.item(i); if (node.getNodeType() == Node.ELEMENT_NODE && namespace.equals(node.getNamespaceURI()) && name.equals(node.getLocalName())) { return (Element) node; } } return null; } }
package com.evolveum.midpoint.model.sync; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.xml.bind.JAXBElement; import org.apache.commons.lang.Validate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import com.evolveum.midpoint.api.logging.LoggingUtils; import com.evolveum.midpoint.api.logging.Trace; import com.evolveum.midpoint.common.DebugUtil; import com.evolveum.midpoint.common.QueryUtil; import com.evolveum.midpoint.common.jaxb.JAXBUtil; import com.evolveum.midpoint.common.patch.PatchXml; import com.evolveum.midpoint.common.result.OperationResult; import com.evolveum.midpoint.common.result.OperationResultStatus; import com.evolveum.midpoint.logging.TraceManager; import com.evolveum.midpoint.model.controller.ModelController; import com.evolveum.midpoint.model.expr.ExpressionException; import com.evolveum.midpoint.model.expr.ExpressionHandler; import com.evolveum.midpoint.provisioning.api.ChangeNotificationDispatcher; import com.evolveum.midpoint.provisioning.api.ResourceObjectChangeListener; import com.evolveum.midpoint.schema.ObjectTypes; import com.evolveum.midpoint.schema.exception.SystemException; import com.evolveum.midpoint.util.DOMUtil; import com.evolveum.midpoint.xml.ns._public.common.common_1.ObjectChangeAdditionType; import com.evolveum.midpoint.xml.ns._public.common.common_1.ObjectChangeDeletionType; import com.evolveum.midpoint.xml.ns._public.common.common_1.ObjectChangeModificationType; import com.evolveum.midpoint.xml.ns._public.common.common_1.ObjectChangeType; import com.evolveum.midpoint.xml.ns._public.common.common_1.ObjectFactory; import com.evolveum.midpoint.xml.ns._public.common.common_1.ObjectListType; import com.evolveum.midpoint.xml.ns._public.common.common_1.ObjectModificationType; import com.evolveum.midpoint.xml.ns._public.common.common_1.ObjectType; import com.evolveum.midpoint.xml.ns._public.common.common_1.PagingType; import com.evolveum.midpoint.xml.ns._public.common.common_1.QueryType; import com.evolveum.midpoint.xml.ns._public.common.common_1.ResourceObjectShadowChangeDescriptionType; import com.evolveum.midpoint.xml.ns._public.common.common_1.ResourceObjectShadowType; import com.evolveum.midpoint.xml.ns._public.common.common_1.ResourceType; import com.evolveum.midpoint.xml.ns._public.common.common_1.SynchronizationSituationType; import com.evolveum.midpoint.xml.ns._public.common.common_1.SynchronizationType; import com.evolveum.midpoint.xml.ns._public.common.common_1.SynchronizationType.Reaction; import com.evolveum.midpoint.xml.ns._public.common.common_1.UserType; import com.evolveum.midpoint.xml.schema.ExpressionHolder; import com.evolveum.midpoint.xml.schema.SchemaConstants; /** * * @author lazyman * */ @Service(value = "synchronizationService") public class SynchronizationService implements ResourceObjectChangeListener { private static final Trace LOGGER = TraceManager.getTrace(SynchronizationService.class); @Autowired(required = true) private ModelController controller; @Autowired(required = true) private ActionManager<Action> actionManager; @Autowired private ExpressionHandler expressionHandler; @Autowired private ChangeNotificationDispatcher notificationManager; @PostConstruct public void registerForResourceObjectChangeNotifications() { notificationManager.registerNotificationListener(this); } @PreDestroy public void unregisterForResourceObjectChangeNotifications() { notificationManager.unregisterNotificationListener(this); } @Override public void notifyChange(ResourceObjectShadowChangeDescriptionType change, OperationResult parentResult) { Validate.notNull(change, "Resource object shadow change description must not be null."); Validate.notNull(change.getObjectChange(), "Object change in change description must not be null."); Validate.notNull(change.getResource(), "Resource in change must not be null."); Validate.notNull(parentResult, "Parent operation result must not be null."); OperationResult subResult = new OperationResult("Notify Change"); parentResult.addSubresult(subResult); try { ResourceType resource = change.getResource(); if (resource == null) { String message = "Resource definition not found in change."; LOGGER.debug(message); subResult.recordFatalError(message); return; } LOGGER.debug("Resource definition found in change."); if (!isSynchronizationEnabled(resource.getSynchronization())) { String message = "Synchronization is not enabled."; LOGGER.debug(message); subResult.recordStatus(OperationResultStatus.SUCCESS, message); return; } LOGGER.debug("Synchronization is enabled."); ResourceObjectShadowType objectShadow = change.getShadow(); if (objectShadow == null && (change.getObjectChange() instanceof ObjectChangeAdditionType)) { // There may not be a previous shadow in addition. But in that // case // we have (almost) everything in the ObjectChangeType - almost // everything except OID. But we can live with that. objectShadow = (ResourceObjectShadowType) ((ObjectChangeAdditionType) change .getObjectChange()).getObject(); } if (objectShadow == null) { throw new IllegalArgumentException("Change doesn't contain ResourceObjectShadow."); } ResourceObjectShadowType objectShadowAfterChange = getObjectAfterChange(objectShadow, change.getObjectChange()); LOGGER.debug("Resource object shadow after change resolved. (Object in log on TRACE level)"); if (LOGGER.isTraceEnabled()) { LOGGER.trace(JAXBUtil.silentMarshalWrap(objectShadowAfterChange)); } SynchronizationSituation situation = checkSituation(change, objectShadowAfterChange, subResult); notifyChange(change, situation, resource, objectShadowAfterChange, subResult); } finally { LOGGER.debug(subResult.dump()); } } /** * Apply the changes to the provided shadow. * * @param objectShadow * shadow with some data * @param change * changes to be applied */ @SuppressWarnings("unchecked") private ResourceObjectShadowType getObjectAfterChange(ResourceObjectShadowType objectShadow, ObjectChangeType change) { LOGGER.debug("Resolving resource object shadow after change."); if (change instanceof ObjectChangeAdditionType) { ObjectChangeAdditionType objectAddition = (ObjectChangeAdditionType) change; ObjectType object = objectAddition.getObject(); if (object instanceof ResourceObjectShadowType) { return (ResourceObjectShadowType) object; } else { throw new IllegalArgumentException("The changed object is not a shadow, it is " + object.getClass().getName()); } } else if (change instanceof ObjectChangeModificationType) { try { ObjectChangeModificationType objectModification = (ObjectChangeModificationType) change; ObjectModificationType modification = objectModification.getObjectModification(); PatchXml patchXml = new PatchXml(); String patchedXml = patchXml.applyDifferences(modification, objectShadow); ResourceObjectShadowType changedResourceShadow = ((JAXBElement<ResourceObjectShadowType>) JAXBUtil .unmarshal(patchedXml)).getValue(); return changedResourceShadow; } catch (Exception ex) { throw new SystemException(ex.getMessage(), ex); } } else if (change instanceof ObjectChangeDeletionType) { // in case of deletion the object has already all that it can have return objectShadow; } else { throw new IllegalArgumentException("Unknown change type " + change.getClass().getName()); } } private boolean isSynchronizationEnabled(SynchronizationType synchronization) { if (synchronization == null || synchronization.isEnabled() == null) { return false; } return synchronization.isEnabled(); } // XXX: in situation when one account belongs to two different idm users // (repository returns only first user). It should be changed because // otherwise we can't check SynchronizationSituationType.CONFLICT situation private SynchronizationSituation checkSituation(ResourceObjectShadowChangeDescriptionType change, ResourceObjectShadowType objectShadowAfterChange, OperationResult result) { OperationResult subResult = new OperationResult("Check Synchronization Situation"); result.addSubresult(subResult); if (change.getShadow() != null) { LOGGER.trace("Determining situation for OID {}.", new Object[] { change.getShadow().getOid() }); } else { LOGGER.trace("Determining situation for new resource object."); } ResourceObjectShadowType resourceShadow = change.getShadow(); ModificationType modification = getModificationType(change.getObjectChange()); SynchronizationSituation situation = null; try { UserType user = null; if (resourceShadow != null && resourceShadow.getOid() != null && !resourceShadow.getOid().isEmpty()) { user = controller.listAccountShadowOwner(resourceShadow.getOid(), subResult); } if (user != null) { LOGGER.trace("Shadow OID {} does have owner: {}", change.getShadow().getOid(), user.getOid()); SynchronizationSituationType state = null; switch (modification) { case ADD: case MODIFY: // if user is found it means account/group is linked to // resource state = SynchronizationSituationType.CONFIRMED; break; case DELETE: state = SynchronizationSituationType.DELETED; } situation = new SynchronizationSituation(user, state); } else { LOGGER.trace("Resource object shadow doesn't have owner."); situation = checkSituationWithCorrelation(change, objectShadowAfterChange, modification, result); } } catch (Exception ex) { LOGGER.error("Error occured during resource object shadow owner lookup."); throw new SystemException("Error occured during resource object shadow owner lookup, reason: " + ex.getMessage(), ex); } LOGGER.trace("checkSituation::end - {}, {}", new Object[] { (situation.getUser() == null ? "null" : situation.getUser().getOid()), situation.getSituation() }); return situation; } /** * account is not linked to user. you have to use correlation and * confirmation rule to be shure user for this account doesn't exists * resourceShadow only contains the data that were in the repository before * the change. But the correlation/confirmation should work on the updated * data. Therefore let's apply the changes before running * correlation/confirmation * * @throws SynchronizationException */ private SynchronizationSituation checkSituationWithCorrelation( ResourceObjectShadowChangeDescriptionType change, ResourceObjectShadowType objectShadowAfterChange, ModificationType modification, OperationResult result) throws SynchronizationException { ResourceObjectShadowType resourceShadow = change.getShadow(); // It is better to get resource from change. The resource object may // have only resourceRef ResourceType resource = change.getResource(); SynchronizationType synchronization = resource.getSynchronization(); UserType user = null; SynchronizationSituationType state = null; LOGGER.debug("CORRELATION: Looking for list of users based on correlation rule."); List<UserType> users = findUsersByCorrelationRule(objectShadowAfterChange, synchronization.getCorrelation(), result); if (synchronization.getConfirmation() == null) { if (resourceShadow != null) { LOGGER.debug("CONFIRMATION: No expression for oid {}, accepting all results of correlation", new Object[] { resourceShadow.getOid() }); } else { LOGGER.debug("CONFIRMATION: No expression for new resource object, accepting all results of correlation"); } } else { LOGGER.debug("CONFIRMATION: Checking users from correlation with confirmation rule."); users = findUserByConfirmationRule(users, objectShadowAfterChange, new ExpressionHolder( synchronization.getConfirmation()), result); } switch (users.size()) { case 0: state = SynchronizationSituationType.UNMATCHED; break; case 1: if (ModificationType.ADD.equals(modification)) { state = SynchronizationSituationType.FOUND; } else { state = SynchronizationSituationType.UNASSIGNED; } user = users.get(0); break; default: state = SynchronizationSituationType.DISPUTED; } return new SynchronizationSituation(user, state); } private ModificationType getModificationType(ObjectChangeType change) { if (change instanceof ObjectChangeAdditionType) { return ModificationType.ADD; } else if (change instanceof ObjectChangeModificationType) { return ModificationType.MODIFY; } else if (change instanceof ObjectChangeDeletionType) { return ModificationType.DELETE; } throw new SystemException("Unknown modification type - change '" + change.getClass() + "'."); } private enum ModificationType { ADD, DELETE, MODIFY; } private void notifyChange(ResourceObjectShadowChangeDescriptionType change, SynchronizationSituation situation, ResourceType resource, ResourceObjectShadowType objectShadowAfterChange, OperationResult parentResult) { SynchronizationType synchronization = resource.getSynchronization(); List<Action> actions = findActionsForReaction(synchronization.getReaction(), situation.getSituation()); if (actions.isEmpty()) { LOGGER.warn("Skipping synchronization on resource: {}. Actions was not found.", new Object[] { resource.getName() }); return; } if (change.getShadow() != null && change.getShadow().getResource() == null) { // This should hold under interface contract, but let's be on the // safe side if (change.getShadow().getResourceRef() != null) { if (!change.getShadow().getResourceRef().getOid().equals(resource.getOid())) { String message = "OID of resource does not match OID in shadow resourceRef"; parentResult.recordFatalError(message); throw new SystemException(message); } } change.getShadow().setResource(resource); } try { LOGGER.trace("Updating user started."); String userOid = situation.getUser() == null ? null : situation.getUser().getOid(); for (Action action : actions) { LOGGER.debug("ACTION: Executing: {}.", new Object[] { action.getClass() }); // TODO: fix operation result type userOid = action.executeChanges(userOid, change, situation.getSituation(), objectShadowAfterChange, new OperationResult("Resource Object Change Service")); } LOGGER.trace("Updating user finished."); } catch (SynchronizationException ex) { LoggingUtils.logException(LOGGER, "### SYNCHRONIZATION # notifyChange(..): Synchronization action failed", ex); parentResult.recordFatalError("Synchronization action failed.", ex); throw new SystemException("Synchronization action failed, reason: " + ex.getMessage(), ex); } catch (Exception ex) { LoggingUtils.logException(LOGGER, "### SYNCHRONIZATION # notifyChange(..): Unexpected " + "error occured, synchronization action failed", ex); parentResult.recordFatalError("Unexpected error occured, synchronization action failed.", ex); throw new SystemException("Unexpected error occured, synchronization action failed, reason: " + ex.getMessage(), ex); } parentResult.recordSuccess(); } private List<Action> findActionsForReaction(List<Reaction> reactions, SynchronizationSituationType situation) { List<Action> actions = new ArrayList<Action>(); if (reactions == null) { return actions; } Reaction reaction = null; for (Reaction react : reactions) { if (react.getSituation() == null) { LOGGER.warn("Reaction ({}) doesn't contain situation element, skipping.", reactions.indexOf(react)); continue; } if (situation.equals(react.getSituation())) { reaction = react; break; } } if (reaction == null) { LOGGER.warn("Reaction on situation {} was not found.", situation); return actions; } List<Reaction.Action> actionList = reaction.getAction(); for (Reaction.Action actionXml : actionList) { if (actionXml == null) { LOGGER.warn("Reaction ({}) doesn't contain action element, skipping.", reactions.indexOf(reaction)); return actions; } if (actionXml.getRef() == null) { LOGGER.warn("Reaction ({}): Action element doesn't contain ref attribute, skipping.", reactions.indexOf(reaction)); return actions; } Action action = actionManager.getActionInstance(actionXml.getRef()); if (action == null) { LOGGER.warn("Couln't create action with uri '{}' for reaction {}, skipping action.", actionXml.getRef(), reactions.indexOf(reaction)); continue; } action.setParameters(actionXml.getAny()); actions.add(action); } return actions; } private List<UserType> findUsersByCorrelationRule(ResourceObjectShadowType resourceShadow, QueryType query, OperationResult result) throws SynchronizationException { List<UserType> users = new ArrayList<UserType>(); if (query == null) { LOGGER.error("Corrrelation rule for resource '{}' doesn't contain query, " + "returning empty list of users.", resourceShadow.getName()); return users; } Element element = query.getFilter(); if (element == null) { LOGGER.error("Corrrelation rule for resource '{}' doesn't contain query, " + "returning empty list of users.", resourceShadow.getName()); return users; } Element filter = updateFilterWithAccountValues(resourceShadow, element, result); try { query = new ObjectFactory().createQueryType(); query.setFilter(filter); LOGGER.debug("CORRELATION: expression for OID {} results in filter {}", resourceShadow.getOid(), DebugUtil.prettyPrint(query)); PagingType paging = new PagingType(); ObjectListType container = controller.searchObjectsInRepository(query, paging, result); if (container == null) { return users; } List<ObjectType> objects = container.getObject(); for (ObjectType object : objects) { if (object instanceof UserType) { users.add((UserType) object); } } } catch (Exception ex) { LoggingUtils.logException(LOGGER, "Couldn't search users in repository, based on filter (simplified)\n{}.", ex, DebugUtil.prettyPrint(filter)); throw new SynchronizationException( "Couldn't search users in repository, based on filter (See logs).", ex); } LOGGER.debug("CORRELATION: expression for OID {} returned {} users.", new Object[] { resourceShadow.getOid(), users.size() }); return users; } private List<UserType> findUserByConfirmationRule(List<UserType> users, ResourceObjectShadowType resourceObjectShadowType, ExpressionHolder expression, OperationResult result) throws SynchronizationException { List<UserType> list = new ArrayList<UserType>(); for (UserType user : users) { try { boolean confirmedUser = getExpressionHandler().evaluateConfirmationExpression(user, resourceObjectShadowType, expression, result); if (user != null && confirmedUser) { list.add(user); } } catch (ExpressionException ex) { LoggingUtils.logException(LOGGER, "Couldn't confirm user {}", ex, user.getName()); throw new SynchronizationException("Couldn't confirm user " + user.getName(), ex); } } LOGGER.debug("CONFIRMATION: expression for OID {} matched {} users.", resourceObjectShadowType.getOid(), list.size()); return list; } private Element updateFilterWithAccountValues(ResourceObjectShadowType resourceObjectShadow, Element filter, OperationResult result) throws SynchronizationException { LOGGER.trace("updateFilterWithAccountValues::begin"); if (filter == null) { return null; } try { LOGGER.trace("Transforming search filter from:\n{}", DOMUtil.printDom(filter.getOwnerDocument())); Document document = DOMUtil.getDocument(); Element and = document.createElementNS(SchemaConstants.NS_C, "and"); document.appendChild(and); and.appendChild(QueryUtil.createTypeFilter(document, ObjectTypes.USER.getObjectTypeUri())); Element equal = null; if (SchemaConstants.NS_C.equals(filter.getNamespaceURI()) && "equal".equals(filter.getLocalName())) { equal = (Element) document.adoptNode(filter.cloneNode(true)); Element path = findChildElement(equal, SchemaConstants.NS_C, "path"); if (path != null) { equal.removeChild(path); } Element valueExpression = findChildElement(equal, SchemaConstants.NS_C, "valueExpression"); if (valueExpression != null) { equal.removeChild(valueExpression); String ref = valueExpression.getAttribute("ref"); String namespace = filter.getOwnerDocument().getNamespaceURI(); if (ref.contains(":")) { String pref = ref.substring(0, ref.indexOf(":")); namespace = filter.lookupNamespaceURI(pref); } Element value = document.createElementNS(SchemaConstants.NS_C, "value"); equal.appendChild(value); Element attribute = document.createElementNS(namespace, ref); String expressionResult = getExpressionHandler().evaluateExpression(resourceObjectShadow, new ExpressionHolder(valueExpression), result); // TODO: log more context LOGGER.debug("Search filter expression in the rule for OID {} evaluated to {}.", new Object[] { resourceObjectShadow.getOid(), expressionResult }); attribute.setTextContent(expressionResult); value.appendChild(attribute); } else { LOGGER.warn("No valueExpression in rule for OID {}", resourceObjectShadow.getOid()); } } filter = and; LOGGER.trace("Transforming filter to:\n{}", DOMUtil.printDom(filter.getOwnerDocument())); } catch (Exception ex) { LoggingUtils.logException(LOGGER, "Couldn't update filter.", ex); throw new SynchronizationException("Couldn't update filter, reason: " + ex.getMessage(), ex); } LOGGER.trace("updateFilterWithAccountValues::end"); return filter; } private Element findChildElement(Element element, String namespace, String name) { NodeList list = element.getChildNodes(); for (int i = 0; i < list.getLength(); i++) { Node node = list.item(i); if (node.getNodeType() == Node.ELEMENT_NODE && namespace.equals(node.getNamespaceURI()) && name.equals(node.getLocalName())) { return (Element) node; } } return null; } private ExpressionHandler getExpressionHandler() { expressionHandler.setModel(controller); return expressionHandler; } }
package de.lmu.ifi.dbs.elki.math; import java.math.BigInteger; import java.util.Random; import de.lmu.ifi.dbs.elki.data.NumberVector; import de.lmu.ifi.dbs.elki.math.linearalgebra.Matrix; import de.lmu.ifi.dbs.elki.math.linearalgebra.Vector; /** * A collection of math related utility functions. * * @author Arthur Zimekt * @author Erich Schubert * * @apiviz.landmark */ public final class MathUtil { /** * Two times Pi. */ public static final double TWOPI = 2 * Math.PI; /** * Squre root of two times Pi. */ public static final double SQRTTWOPI = Math.sqrt(TWOPI); /** * Square root of 2. */ public static final double SQRT2 = Math.sqrt(2); /** * Square root of 5 */ public static final double SQRT5 = Math.sqrt(5); /** * Square root of 0.5 == 1 / Sqrt(2) */ public static final double SQRTHALF = Math.sqrt(.5); /** * Precomputed value of 1 / sqrt(pi) */ public static final double ONE_BY_SQRTPI = 1 / Math.sqrt(Math.PI); /** * Logarithm of 2 to the basis e, for logarithm conversion. */ public static final double LOG2 = Math.log(2); /** * Math.log(Math.PI) */ public static final double LOGPI = Math.log(Math.PI); /** * Math.log(Math.PI) / 2 */ public static final double LOGPIHALF = LOGPI / 2.; /** * Math.log(Math.sqrt(2*Math.PI)) */ public static final double LOGSQRTTWOPI = Math.log(SQRTTWOPI); /** * Fake constructor for static class. */ private MathUtil() { // Static methods only - do not instantiate! } /** * Computes the square root of the sum of the squared arguments without under * or overflow. * * Note: this code is <em>not</em> redundant to {@link Math#hypot}, since the * latter is significantly slower (but maybe has a higher precision). * * @param a first cathetus * @param b second cathetus * @return {@code sqrt(a<sup>2</sup> + b<sup>2</sup>)} */ public static double fastHypot(double a, double b) { if(a < 0) { a = -a; } if(b < 0) { b = -b; } if(a > b) { final double r = b / a; return a * Math.sqrt(1 + r * r); } else if(b != 0) { final double r = a / b; return b * Math.sqrt(1 + r * r); } else { return 0.0; } } /** * Computes the square root of the sum of the squared arguments without under * or overflow. * * Note: this code is <em>not</em> redundant to {@link Math#hypot}, since the * latter is significantly slower (but has a higher precision). * * @param a first cathetus * @param b second cathetus * @param c second cathetus * @return {@code sqrt(a<sup>2</sup> + b<sup>2</sup> + c<sup>2</sup>)} */ public static double fastHypot3(double a, double b, double c) { if(a < 0) { a = -a; } if(b < 0) { b = -b; } if(c < 0) { c = -c; } double m = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c); if(m <= 0) { return 0.0; } a = a / m; b = b / m; c = c / m; return m * Math.sqrt(a * a + b * b + c * c); } /** * Compute the Mahalanobis distance using the given weight matrix * * @param weightMatrix Weight Matrix * @param o1_minus_o2 Delta vector * @return Mahalanobis distance */ public static double mahalanobisDistance(Matrix weightMatrix, Vector o1_minus_o2) { double sqrDist = o1_minus_o2.transposeTimesTimes(weightMatrix, o1_minus_o2); if(sqrDist < 0 && Math.abs(sqrDist) < 0.000000001) { sqrDist = Math.abs(sqrDist); } return Math.sqrt(sqrDist); } /** * <p> * Provides the Pearson product-moment correlation coefficient for two * FeatureVectors. * </p> * * @param x first FeatureVector * @param y second FeatureVector * @return the Pearson product-moment correlation coefficient for x and y */ public static double pearsonCorrelationCoefficient(NumberVector<?, ?> x, NumberVector<?, ?> y) { final int xdim = x.getDimensionality(); final int ydim = y.getDimensionality(); if(xdim != ydim) { throw new IllegalArgumentException("Invalid arguments: feature vectors differ in dimensionality."); } if(xdim <= 0) { throw new IllegalArgumentException("Invalid arguments: dimensionality not positive."); } PearsonCorrelation pc = new PearsonCorrelation(); for(int i = 0; i < xdim; i++) { pc.put(x.doubleValue(i + 1), y.doubleValue(i + 1), 1.0); } return pc.getCorrelation(); } /** * <p> * Provides the Pearson product-moment correlation coefficient for two * FeatureVectors. * </p> * * @param x first FeatureVector * @param y second FeatureVector * @return the Pearson product-moment correlation coefficient for x and y */ public static double weightedPearsonCorrelationCoefficient(NumberVector<?, ?> x, NumberVector<?, ?> y, double[] weights) { final int xdim = x.getDimensionality(); final int ydim = y.getDimensionality(); if(xdim != ydim) { throw new IllegalArgumentException("Invalid arguments: feature vectors differ in dimensionality."); } if(xdim != weights.length) { throw new IllegalArgumentException("Dimensionality doesn't agree to weights."); } PearsonCorrelation pc = new PearsonCorrelation(); for(int i = 0; i < xdim; i++) { pc.put(x.doubleValue(i + 1), y.doubleValue(i + 1), weights[i]); } return pc.getCorrelation(); } /** * <p> * Provides the Pearson product-moment correlation coefficient for two * FeatureVectors. * </p> * * @param x first FeatureVector * @param y second FeatureVector * @return the Pearson product-moment correlation coefficient for x and y */ public static double weightedPearsonCorrelationCoefficient(NumberVector<?, ?> x, NumberVector<?, ?> y, NumberVector<?, ?> weights) { final int xdim = x.getDimensionality(); final int ydim = y.getDimensionality(); if(xdim != ydim) { throw new IllegalArgumentException("Invalid arguments: feature vectors differ in dimensionality."); } if(xdim != weights.getDimensionality()) { throw new IllegalArgumentException("Dimensionality doesn't agree to weights."); } PearsonCorrelation pc = new PearsonCorrelation(); for(int i = 0; i < xdim; i++) { pc.put(x.doubleValue(i + 1), y.doubleValue(i + 1), weights.doubleValue(i + 1)); } return pc.getCorrelation(); } /** * <p> * Provides the Pearson product-moment correlation coefficient for two * FeatureVectors. * </p> * * @param x first FeatureVector * @param y second FeatureVector * @return the Pearson product-moment correlation coefficient for x and y */ public static double pearsonCorrelationCoefficient(double[] x, double[] y) { final int xdim = x.length; final int ydim = y.length; if(xdim != ydim) { throw new IllegalArgumentException("Invalid arguments: feature vectors differ in dimensionality."); } PearsonCorrelation pc = new PearsonCorrelation(); for(int i = 0; i < xdim; i++) { pc.put(x[i], y[i], 1.0); } return pc.getCorrelation(); } /** * <p> * Provides the Pearson product-moment correlation coefficient for two * FeatureVectors. * </p> * * @param x first FeatureVector * @param y second FeatureVector * @return the Pearson product-moment correlation coefficient for x and y */ public static double weightedPearsonCorrelationCoefficient(double[] x, double[] y, double[] weights) { final int xdim = x.length; final int ydim = y.length; if(xdim != ydim) { throw new IllegalArgumentException("Invalid arguments: feature vectors differ in dimensionality."); } if(xdim != weights.length) { throw new IllegalArgumentException("Dimensionality doesn't agree to weights."); } PearsonCorrelation pc = new PearsonCorrelation(); for(int i = 0; i < xdim; i++) { pc.put(x[i], y[i], weights[i]); } return pc.getCorrelation(); } /** * Compute the Factorial of n, often written as <code>c!</code> in * mathematics.</p> * <p> * Use this method if for large values of <code>n</code>. * </p> * * @param n Note: n &gt;= 0. This {@link BigInteger} <code>n</code> will be 0 * after this method finishes. * @return n * (n-1) * (n-2) * ... * 1 */ public static BigInteger factorial(BigInteger n) { BigInteger nFac = BigInteger.valueOf(1); while(n.compareTo(BigInteger.valueOf(1)) > 0) { nFac = nFac.multiply(n); n = n.subtract(BigInteger.valueOf(1)); } return nFac; } /** * Compute the Factorial of n, often written as <code>c!</code> in * mathematics. * * @param n Note: n &gt;= 0 * @return n * (n-1) * (n-2) * ... * 1 */ public static long factorial(int n) { long nFac = 1; for(long i = n; i > 0; i nFac *= i; } return nFac; } /** * <p> * Binomial coefficient, also known as "n choose k". * </p> * * @param n Total number of samples. n &gt; 0 * @param k Number of elements to choose. <code>n &gt;= k</code>, * <code>k &gt;= 0</code> * @return n! / (k! * (n-k)!) */ public static long binomialCoefficient(long n, long k) { final long m = Math.max(k, n - k); double temp = 1; for(long i = n, j = 1; i > m; i temp = temp * i / j; } return (long) temp; } /** * Compute the Factorial of n, often written as <code>c!</code> in * mathematics. * * @param n Note: n &gt;= 0 * @return n * (n-1) * (n-2) * ... * 1 */ public static double approximateFactorial(int n) { double nFac = 1.0; for(int i = n; i > 0; i nFac *= i; } return nFac; } /** * <p> * Binomial coefficent, also known as "n choose k") * </p> * * @param n Total number of samples. n &gt; 0 * @param k Number of elements to choose. <code>n &gt;= k</code>, * <code>k &gt;= 0</code> * @return n! / (k! * (n-k)!) */ public static double approximateBinomialCoefficient(int n, int k) { final int m = Math.max(k, n - k); long temp = 1; for(int i = n, j = 1; i > m; i temp = temp * i / j; } return temp; } /** * Compute the sum of the i first integers. * * @param i maximum summand * @return Sum */ public static long sumFirstIntegers(final long i) { return ((i - 1L) * i) / 2; } /** * Produce an array of random numbers in [0:1] * * @param len Length * @return Array */ public static double[] randomDoubleArray(int len) { return randomDoubleArray(len, new Random()); } /** * Produce an array of random numbers in [0:1] * * @param len Length * @param r Random generator * @return Array */ public static double[] randomDoubleArray(int len, Random r) { final double[] ret = new double[len]; for(int i = 0; i < len; i++) { ret[i] = r.nextDouble(); } return ret; } /** * Convert Degree to Radians * * @param deg Degree value * @return Radian value */ public static double deg2rad(double deg) { return deg * Math.PI / 180.0; } /** * Radians to Degree * * @param rad Radians value * @return Degree value */ public static double rad2deg(double rad) { return rad * 180 / Math.PI; } /** * Compute the approximate on-earth-surface distance of two points. * * @param lat1 Latitude of first point in degree * @param lon1 Longitude of first point in degree * @param lat2 Latitude of second point in degree * @param lon2 Longitude of second point in degree * @return Distance in km (approximately) */ public static double latlngDistance(double lat1, double lon1, double lat2, double lon2) { final double EARTH_RADIUS = 6371; // Work in radians lat1 = MathUtil.deg2rad(lat1); lat2 = MathUtil.deg2rad(lat2); lon1 = MathUtil.deg2rad(lon1); lon2 = MathUtil.deg2rad(lon2); // Delta final double dlat = lat1 - lat2; final double dlon = lon1 - lon2; // Spherical Law of Cosines // NOTE: there seems to be a signedness issue in this code! // double dist = Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * // Math.cos(lat2) * Math.cos(dlon); // return EARTH_RADIUS * Math.atan(dist); // Alternative: Havestine formula, higher precision at < 1 meters: final double a = Math.sin(dlat / 2) * Math.sin(dlat / 2) + Math.sin(dlon / 2) * Math.sin(dlon / 2) * Math.cos(lat1) * Math.cos(lat2); final double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); return EARTH_RADIUS * c; } /** * Compute the angle between two vectors. * * @param v1 first vector * @param v2 second vector * @return Angle */ public static double angle(Vector v1, Vector v2) { return angle(v1.getArrayRef(), v2.getArrayRef()); } /** * Compute the angle between two vectors. * * @param v1 first vector * @param v2 second vector * @return Angle */ public static double angle(double[] v1, double[] v2) { // Essentially, we want to compute this: // v1.transposeTimes(v2) / (v1.euclideanLength() * v2.euclideanLength()); // We can just compute all three in parallel. double s = 0, e1 = 0, e2 = 0; for(int k = 0; k < v1.length; k++) { final double r1 = v1[k]; final double r2 = v2[k]; s += r1 * r2; e1 += r1 * r1; e2 += r2 * r2; } return Math.sqrt((s / e1) * (s / e2)); } /** * Compute the angle between two vectors. * * @param v1 first vector * @param v2 second vector * @param o Origin * @return Angle */ public static double angle(Vector v1, Vector v2, Vector o) { return angle(v1.getArrayRef(), v2.getArrayRef(), o.getArrayRef()); } /** * Compute the angle between two vectors. * * @param v1 first vector * @param v2 second vector * @param o Origin * @return Angle */ public static double angle(double[] v1, double[] v2, double[] o) { // Essentially, we want to compute this: // v1' = v1 - o, v2' = v2 - o // v1'.transposeTimes(v2') / (v1'.euclideanLength()*v2'.euclideanLength()); // We can just compute all three in parallel. double s = 0, e1 = 0, e2 = 0; for(int k = 0; k < v1.length; k++) { final double r1 = v1[k] - o[k]; final double r2 = v2[k] - o[k]; s += r1 * r2; e1 += r1 * r1; e2 += r2 * r2; } return Math.sqrt((s / e1) * (s / e2)); } /** * Find the next power of 2. * * Classic bit operation, for signed 32-bit. Valid for positive integers only * (0 otherwise). * * @param x original integer * @return Next power of 2 */ public static int nextPow2Int(int x) { --x; x |= x >>> 1; x |= x >>> 2; x |= x >>> 4; x |= x >>> 8; x |= x >>> 16; return ++x; } /** * Find the next power of 2. * * Classic bit operation, for signed 64-bit. Valid for positive integers only * (0 otherwise). * * @param x original long integer * @return Next power of 2 */ public static long nextPow2Long(long x) { --x; x |= x >>> 1; x |= x >>> 2; x |= x >>> 4; x |= x >>> 16; x |= x >>> 32; return ++x; } /** * Find the next larger number with all ones. * * Classic bit operation, for signed 32-bit. Valid for positive integers only * (-1 otherwise). * * @param x original integer * @return Next number with all bits set */ public static int nextAllOnesInt(int x) { x |= x >>> 1; x |= x >>> 2; x |= x >>> 4; x |= x >>> 8; x |= x >>> 16; return x; } /** * Find the next larger number with all ones. * * Classic bit operation, for signed 64-bit. Valid for positive integers only * (-1 otherwise). * * @param x original long integer * @return Next number with all bits set */ public static long nextAllOnesLong(long x) { x |= x >>> 1; x |= x >>> 2; x |= x >>> 4; x |= x >>> 16; x |= x >>> 32; return x; } /** * Return the largest double that rounds down to this float. * * Note: Probably not always correct - subnormal values are quite tricky. So * some of the bounds might not be tight. * * @param f Float value * @return Double value */ public static double floatToDoubleUpper(float f) { if(Float.isNaN(f)) { return Double.NaN; } if(Float.isInfinite(f)) { if(f > 0) { return Double.POSITIVE_INFINITY; } else { return Double.longBitsToDouble(0xc7efffffffffffffl); } } long bits = Double.doubleToRawLongBits((double) f); if((bits & 0x8000000000000000l) == 0) { // Positive if(bits == 0l) { return Double.longBitsToDouble(0x3690000000000000l); } if(f == Float.MIN_VALUE) { // bits += 0x7_ffff_ffff_ffffl; return Double.longBitsToDouble(0x36a7ffffffffffffl); } if(Float.MIN_NORMAL > f && f >= Double.MIN_NORMAL) { // The most tricky case: // a denormalized float, but a normalized double final long bits2 = Double.doubleToRawLongBits((double) Math.nextUp(f)); bits = (bits >>> 1) + (bits2 >>> 1) - 1l; } else { bits += 0xfffffffl; // 28 extra bits } return Double.longBitsToDouble(bits); } else { if(bits == 0x8000000000000000l) { return -0.0d; } if(f == -Float.MIN_VALUE) { // bits -= 0xf_ffff_ffff_ffffl; return Double.longBitsToDouble(0xb690000000000001l); } if(-Float.MIN_NORMAL < f && f <= -Double.MIN_NORMAL) { // The most tricky case: // a denormalized float, but a normalized double final long bits2 = Double.doubleToRawLongBits((double) Math.nextUp(f)); bits = (bits >>> 1) + (bits2 >>> 1) + 1l; } else { bits -= 0xfffffffl; // 28 extra bits } return Double.longBitsToDouble(bits); } } /** * Return the largest double that rounds up to this float. * * Note: Probably not always correct - subnormal values are quite tricky. So * some of the bounds might not be tight. * * @param f Float value * @return Double value */ public static double floatToDoubleLower(float f) { if(Float.isNaN(f)) { return Double.NaN; } if(Float.isInfinite(f)) { if(f < 0) { return Double.NEGATIVE_INFINITY; } else { return Double.longBitsToDouble(0x47efffffffffffffl); } } long bits = Double.doubleToRawLongBits((double) f); if((bits & 0x8000000000000000l) == 0) { // Positive if(bits == 0l) { return +0.0d; } if(f == Float.MIN_VALUE) { // bits -= 0xf_ffff_ffff_ffffl; return Double.longBitsToDouble(0x3690000000000001l); } if(Float.MIN_NORMAL > f /* && f >= Double.MIN_NORMAL */) { // The most tricky case: // a denormalized float, but a normalized double final long bits2 = Double.doubleToRawLongBits((double) -Math.nextUp(-f)); bits = (bits >>> 1) + (bits2 >>> 1) + 1l; // + (0xfff_ffffl << 18); } else { bits -= 0xfffffffl; // 28 extra bits } return Double.longBitsToDouble(bits); } else { if(bits == 0x8000000000000000l) { return Double.longBitsToDouble(0xb690000000000000l); } if(f == -Float.MIN_VALUE) { // bits += 0x7_ffff_ffff_ffffl; return Double.longBitsToDouble(0xb6a7ffffffffffffl); } if(-Float.MIN_NORMAL < f /* && f <= -Double.MIN_NORMAL */) { // The most tricky case: // a denormalized float, but a normalized double final long bits2 = Double.doubleToRawLongBits((double) -Math.nextUp(-f)); bits = (bits >>> 1) + (bits2 >>> 1) - 1l; } else { bits += 0xfffffffl; // 28 extra bits } return Double.longBitsToDouble(bits); } } }
package project.architecture.logger.java; public class Main { public static void main(String[] args) { System.out.println("Hello team"); } }
package org.modeshape.graph.property.basic; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.StringTokenizer; import org.modeshape.common.annotation.Immutable; import org.modeshape.common.util.CheckArg; import org.modeshape.graph.property.Name; import org.modeshape.graph.property.Path; import org.modeshape.graph.property.Property; import org.modeshape.graph.property.PropertyFactory; import org.modeshape.graph.property.PropertyType; import org.modeshape.graph.property.ValueFactories; import org.modeshape.graph.property.ValueFactory; /** * <p> * An implementation of {@link PropertyFactory} which provides the feature for * substituting special decorated variables (i.e., ${variable}) with a system * property. This will support the following decorated syntax options: * <li>${variable}</li> * <li>${variable [,variable,..] }</li> * <li>${variable [:defaultvalue] }</li> * </p> * <p> * Where the <i>variable</i> represents a value to be looked up in the System * properties and <i>defaultvalue</i> indicates what to use when the System * property is not found. * </p> * Notice that the syntax supports multiple <i>variables</i>. The logic will * process the <i>variables</i> from let to right, until a System property is * found. And at that point, it will stop and will not attempt to find values * for the other <i>variables</i>. * <p> */ @Immutable public class SystemPropertyFactory extends BasicPropertyFactory { private final ValueFactories factories; public SystemPropertyFactory( ValueFactories valueFactories ) { super(valueFactories); this.factories = valueFactories; } /** * {@inheritDoc} */ public Property create( Name name, PropertyType desiredType, Object... values ) { CheckArg.isNotNull(name, "name"); if (values == null || values.length == 0) { return new BasicEmptyProperty(name); } final int len = values.length; if (desiredType == null) desiredType = PropertyType.OBJECT; final ValueFactory<?> factory = factories.getValueFactory(desiredType); if (values.length == 1) { Object value = values[0]; // Check whether the sole value was a collection ... if (value instanceof Path) { value = factory.create(value); return new BasicSingleValueProperty(name, value); } if (value instanceof Collection<?>) { // The single value is a collection, so create property with the collection's contents ... return create(name, desiredType, (Iterable<?>)value); } if (value instanceof Iterator<?>) { // The single value is an iterator over a collection, so create property with the iterator's contents ... return create(name, desiredType, (Iterator<?>)value); } if (value instanceof Object[]) { // The single value is an object array, so create the property with the array as the value(s)... return create(name, desiredType, (Object[])value); } if (value instanceof String) { value = factory.create(getSubstitutedProperty((String)value)); return new BasicSingleValueProperty(name, value); } value = factory.create(value); return new BasicSingleValueProperty(name, value); } List<Object> valueList = new ArrayList<Object>(len); for (int i = 0; i != len; ++i) { Object value = factory.create(values[i]); valueList.add(value); } return new BasicMultiValueProperty(name, valueList); } /** * {@inheritDoc} */ @SuppressWarnings( "unchecked" ) public Property create( Name name, PropertyType desiredType, Iterable<?> values ) { CheckArg.isNotNull(name, "name"); List<Object> valueList = null; if (values instanceof Collection) { Collection<Object> originalValues = (Collection<Object>)values; if (originalValues.isEmpty()) { return new BasicEmptyProperty(name); } valueList = new ArrayList<Object>(originalValues.size()); } else { // We don't know the size valueList = new ArrayList<Object>(); } // Copy the values, ensuring that the values are the correct type ... if (desiredType == null) desiredType = PropertyType.OBJECT; final ValueFactory<?> factory = factories.getValueFactory(desiredType); for (Object value : values) { valueList.add(factory.create(value)); } if (valueList.isEmpty()) { // may not have been a collection earlier return new BasicEmptyProperty(name); } if (valueList.size() == 1) { Object o = valueList.get(0); if (o instanceof String) { o = getSubstitutedProperty( (String) o); } return new BasicSingleValueProperty(name, o); } return new BasicMultiValueProperty(name, valueList); } /** * {@inheritDoc} */ public Property create( Name name, PropertyType desiredType, Iterator<?> values ) { CheckArg.isNotNull(name, "name"); final List<Object> valueList = new ArrayList<Object>(); if (desiredType == null) desiredType = PropertyType.OBJECT; final ValueFactory<?> factory = factories.getValueFactory(desiredType); while (values.hasNext()) { Object value = values.next(); value = factory.create(value); valueList.add(value); } if (valueList.isEmpty()) { return new BasicEmptyProperty(name); } if (valueList.size() == 1) { Object o = valueList.get(0); if (o instanceof String) { o = getSubstitutedProperty( (String) o); } return new BasicSingleValueProperty(name, o); } return new BasicMultiValueProperty(name, valueList); } private static final String CURLY_PREFIX = "${"; private static final String CURLY_SUFFIX = "}"; private static final String VAR_DELIM = ","; private static final String DEFAULT_DELIM = ":"; /** * getSubstitutedProperty is called to perform the property substitution on * the value. * @param value * @return String */ protected String getSubstitutedProperty(String value) { if (value == null || value.trim().length() == 0) return null; StringBuffer sb = null; sb = new StringBuffer(value); // Get the index of the first constant, if any int startName = sb.indexOf(CURLY_PREFIX); if (startName == -1) return value; // process as many different variable groupings that are defined, where one group will resolve to one property substitution while (startName != -1) { String defaultValue = null; int endName = sb.indexOf(CURLY_SUFFIX, startName); if (endName == -1) { // if no suffix can be found, then this variable was probably defined incorrectly // but return what there is at this point return sb.toString(); } String varString = sb.substring(startName + 2, endName); if (varString.indexOf(DEFAULT_DELIM) > -1) { List<String> defaults = split(varString, DEFAULT_DELIM); // get the property(s) variables that are defined left of the default delimiter. varString = defaults.get(0); // if the default is defined, then capture in case none of the other properties are found if (defaults.size() == 2 ) { defaultValue = defaults.get(1); } } String constValue = null; // split the property(s) based VAR_DELIM, when multiple property options are defined List<String> vars = split(varString, VAR_DELIM); for (String var : vars) { constValue = System.getenv(var); if (constValue == null) { constValue = System.getProperty(var); } // the first found property is the value to be substituted if (constValue != null) { break; } } // if no property is found to substitute, then use the default value, if defined if (constValue == null && defaultValue != null) { constValue = defaultValue; } if (constValue != null) { sb = sb.replace(startName, endName + 1, constValue); // Checking for another constants startName = sb.indexOf(CURLY_PREFIX); } else { // continue to try to substitute for other properties so that all defined variables // are tried to be substituted for startName = sb.indexOf(CURLY_PREFIX, endName); } } return sb.toString(); } /** * Split a string into pieces based on delimiters. Similar to the perl function of * the same name. The delimiters are not included in the returned strings. * * @param str Full string * @param splitter Characters to split on * @return List of String pieces from full string */ private static List<String> split(String str, String splitter) { StringTokenizer tokens = new StringTokenizer(str, splitter); ArrayList<String> l = new ArrayList<String>(tokens.countTokens()); while(tokens.hasMoreTokens()) { l.add(tokens.nextToken()); } return l; } }
package com.elasticgrid.amazon.boot; import com.elasticgrid.model.ClusterException; import com.elasticgrid.model.NodeProfile; import com.elasticgrid.model.ec2.EC2Node; import com.elasticgrid.config.EC2Configuration; import com.elasticgrid.platforms.ec2.discovery.EC2ClusterLocator; import com.xerox.amazonws.ec2.EC2Exception; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.InetAddress; import java.util.Map; import java.util.Properties; import java.util.Set; /** * Bootstrapper in charge of fetching the EC2 launch parameters and generating the EG configuration files. * The launch parameters are available in the <tt>/tmp/user-data</tt> file. * * @author Jerome Bernard */ public class Bootstrapper { public static final String LAUNCH_PARAMETER_CLUSTER_NAME = "CLUSTER_NAME"; public static final String LAUNCH_PARAMETER_DROP_BUCKET = "DROP_BUCKET"; public static final String LAUNCH_PARAMETER_OVERRIDES_URL = "OVERRIDES_URL"; public static final String LAUNCH_PARAMETER_YUM_PACKAGES = "YUM_PACKAGES"; public static final String LAUNCH_PARAMETER_ACCESS_ID = "AWS_ACCESS_ID"; public static final String LAUNCH_PARAMETER_SECRET_KEY = "AWS_SECRET_KEY"; public static final String LAUNCH_PARAMETER_EC2_SECURED = "AWS_EC2_SECURED"; public static final String LAUNCH_PARAMETER_SQS_SECURED = "AWS_SQS_SECURED"; public static final String LAUNCH_PARAMETER_EC2_KEYPAIR = "AWS_EC2_KEYPAIR"; public static final String LAUNCH_PARAMETER_EC2_AMI32 = "AWS_EC2_AMI32"; public static final String LAUNCH_PARAMETER_EC2_AMI64 = "AWS_EC2_AMI64"; public static final String LAUNCH_PARAMETERS_FILE = "/tmp/user-data"; public static final String ELASTIC_GRID_CONFIGURATION_FILE = "config/eg.properties"; private String egHome = System.getProperty("EG_HOME"); public Bootstrapper() throws IOException, EC2Exception { // retreive EC2 launch parameters Properties launchParameters = fetchLaunchParameters(); Properties egParameters = translateProperties(launchParameters); // save configuration into an Elastic Grid configuration file File file = saveConfiguration(egParameters); System.out.printf("Elastic Grid configuration file generated in '%s'\n", file.getAbsolutePath()); // start Spring context ApplicationContext ctx = new ClassPathXmlApplicationContext("/com/elasticgrid/amazon/boot/applicationContext.xml"); // locate monitor node and write the location of the found monitor into $EG_HOME/config/monitor-host EC2ClusterLocator locator = (EC2ClusterLocator) ctx.getBean("clusterLocator", EC2ClusterLocator.class); String clusterName = launchParameters.getProperty(LAUNCH_PARAMETER_CLUSTER_NAME); try { EC2Node monitor = locator.findMonitor(clusterName); InetAddress monitorHost = monitor.getAddress(); String monitorHostAddress = monitorHost.getHostAddress(); if (monitorHostAddress.equals(InetAddress.getLocalHost().getHostAddress())) { System.out.println("This host is going to be the new monitor!"); } else { System.out.printf("Using monitor host: %s\n", monitorHost.getHostName()); egParameters.put(EC2Configuration.EG_MONITOR_HOST, monitorHost.getHostName()); } FileUtils.writeStringToFile(new File(egHome + File.separator + "config", "monitor-host"), monitorHost.getHostName()); // get the currently running node Set<EC2Node> nodes = locator.findNodes(clusterName); EC2Node thisNode = null; for (EC2Node node : nodes) { if (node.getAddress().equals(InetAddress.getLocalHost())) thisNode = node; } String profile = null; switch (thisNode.getProfile()) { case AGENT: profile = "agent"; break; case MONITOR: profile = "monitor"; break; case MONITOR_AND_AGENT: profile = "monitor-and-agent"; break; } FileUtils.writeStringToFile(new File("/tmp/eg-node-to-start"), profile); System.out.printf("Local machine is morphed into a %s\n", profile); String overridesURL = ""; if (launchParameters.containsKey(LAUNCH_PARAMETER_OVERRIDES_URL)) overridesURL = launchParameters.getProperty(LAUNCH_PARAMETER_OVERRIDES_URL); FileUtils.writeStringToFile(new File("/tmp/overrides"), overridesURL); } catch (ClusterException e) { System.err.println("Could not find monitor host!"); System.exit(-1); } } /** * At boot time, a file is generated into {@link #LAUNCH_PARAMETERS_FILE}. * This method retreive the content of the file and parse it as if it was a Java configuration file. * @return the {@link Properties} object * @throws IOException if the file generated at boot time can't be found or read */ private Properties fetchLaunchParameters() throws IOException { Properties launchProperties = new Properties(); InputStream launchFile = null; try { launchFile = new FileInputStream(new File(LAUNCH_PARAMETERS_FILE)); launchProperties.load(launchFile); return launchProperties; } finally { IOUtils.closeQuietly(launchFile); } } /** * This method translate EC2 lauch parameters into {@link Properties} which can be used through * all Elastic Grid code. * @param launchParameters the EC2 launch paraameters * @return the Elastic Grid parameters * @throws IOException if the metadata can't be fetched */ private Properties translateProperties(Properties launchParameters) throws IOException { // translate properties Properties egParameters = new Properties(); for (Map.Entry property : launchParameters.entrySet()) { String key = (String) property.getKey(); if (LAUNCH_PARAMETER_ACCESS_ID.equals(key)) egParameters.put(EC2Configuration.AWS_ACCESS_ID, property.getValue()); if (LAUNCH_PARAMETER_SECRET_KEY.equals(key)) egParameters.put(EC2Configuration.AWS_SECRET_KEY, property.getValue()); if (LAUNCH_PARAMETER_CLUSTER_NAME.equals(key)) egParameters.put(EC2Configuration.EG_CLUSTER_NAME, property.getValue()); if (LAUNCH_PARAMETER_DROP_BUCKET.equals(key)) egParameters.put(EC2Configuration.EG_DROP_BUCKET, property.getValue()); if (LAUNCH_PARAMETER_OVERRIDES_URL.equals(key)) egParameters.put(EC2Configuration.EG_OVERRIDES_URL, property.getValue()); if (LAUNCH_PARAMETER_EC2_SECURED.equals(key)) egParameters.put(EC2Configuration.AWS_EC2_SECURED, property.getValue()); else egParameters.put(EC2Configuration.AWS_EC2_SECURED, Boolean.TRUE.toString()); if (LAUNCH_PARAMETER_SQS_SECURED.equals(key)) egParameters.put(EC2Configuration.AWS_SQS_SECURED, property.getValue()); if (LAUNCH_PARAMETER_EC2_KEYPAIR.equals(key)) egParameters.put(EC2Configuration.AWS_EC2_KEYPAIR, property.getValue()); /* else egParameters.put(EC2Configuration.AWS_EC2_KEYPAIR, EC2Utils.getInstanceMetadata("keypair")); // todo: check the value of the metadata property */ if (LAUNCH_PARAMETER_EC2_AMI32.equals(key)) egParameters.put(EC2Configuration.AWS_EC2_AMI32, property.getValue()); if (LAUNCH_PARAMETER_EC2_AMI64.equals(key)) egParameters.put(EC2Configuration.AWS_EC2_AMI64, property.getValue()); if (LAUNCH_PARAMETER_YUM_PACKAGES.equals(key)) egParameters.put(EC2Configuration.REDHAT_YUM_PACKAGES, property.getValue()); } return egParameters; } /** * Dump Elastic Grid properties into a configuration file. * @param egParameters the properties to dump in a file * @return the file where the properties have been dumped into. * @throws IOException if there is an error when generating the configuration file */ private File saveConfiguration(Properties egParameters) throws IOException { // write EG configuration if (egHome == null) { System.err.println("Could not find EG_HOME environment variable. Please fix this."); System.exit(-1); } File config = new File(egHome, ELASTIC_GRID_CONFIGURATION_FILE); FileOutputStream stream = null; try { stream = new FileOutputStream(config); egParameters.store(stream, "Elastic Grid Configuration File - Generated file, please do NOT edit!"); } finally { IOUtils.closeQuietly(stream); } return config; } public static void main(String[] args) throws IOException, EC2Exception { System.out.printf("Preparing Elastic Grid environment...\n"); new Bootstrapper(); } }
/* @java.file.header */ package org.gridgain.grid.kernal.processors.cache; import org.gridgain.grid.*; import org.gridgain.grid.cache.*; import org.gridgain.grid.kernal.managers.deployment.*; import org.gridgain.grid.kernal.processors.cache.distributed.dht.*; import org.gridgain.grid.kernal.processors.cache.extras.*; import org.gridgain.grid.kernal.processors.cache.query.*; import org.gridgain.grid.kernal.processors.dr.*; import org.gridgain.grid.lang.*; import org.gridgain.grid.logger.*; import org.gridgain.grid.util.*; import org.gridgain.grid.util.lang.*; import org.gridgain.grid.util.offheap.unsafe.*; import org.gridgain.grid.util.tostring.*; import org.gridgain.grid.util.typedef.*; import org.gridgain.grid.util.typedef.internal.*; import org.jetbrains.annotations.*; import sun.misc.*; import java.io.*; import java.nio.*; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.*; import static org.gridgain.grid.cache.GridCacheFlag.*; import static org.gridgain.grid.cache.GridCacheTxState.*; import static org.gridgain.grid.events.GridEventType.*; import static org.gridgain.grid.kernal.processors.cache.GridCacheOperation.*; import static org.gridgain.grid.kernal.processors.dr.GridDrType.*; /** * Adapter for cache entry. */ @SuppressWarnings({ "NonPrivateFieldAccessedInSynchronizedContext", "TooBroadScope", "FieldAccessedSynchronizedAndUnsynchronized"}) public abstract class GridCacheMapEntry<K, V> implements GridCacheEntryEx<K, V> { private static final long serialVersionUID = 0L; private static final Unsafe UNSAFE = GridUnsafe.unsafe(); private static final byte IS_REFRESHING_MASK = 0x01; private static final byte IS_DELETED_MASK = 0x02; private static final byte IS_UNSWAPPED_MASK = 0x04; private static final Comparator<GridCacheVersion> ATOMIC_VER_COMPARATOR = new GridCacheAtomicVersionComparator(); private static final int SIZE_OVERHEAD = 87 /*entry*/ + 32 /* version */; /** Static logger to avoid re-creation. Made static for test purpose. */ protected static final AtomicReference<GridLogger> logRef = new AtomicReference<>(); /** Logger. */ protected static volatile GridLogger log; /** Cache registry. */ @GridToStringExclude protected final GridCacheContext<K, V> cctx; /** Key. */ @GridToStringInclude protected final K key; /** Value. */ @GridToStringInclude protected V val; /** Start version. */ @GridToStringInclude protected final long startVer; /** Version. */ @GridToStringInclude protected GridCacheVersion ver; /** Next entry in the linked list. */ @GridToStringExclude private volatile GridCacheMapEntry<K, V> next0; /** Next entry in the linked list. */ @GridToStringExclude private volatile GridCacheMapEntry<K, V> next1; /** Key hash code. */ @GridToStringInclude private final int hash; /** Key bytes. */ @GridToStringExclude private volatile byte[] keyBytes; /** Value bytes. */ @GridToStringExclude protected byte[] valBytes; /** Off-heap value pointer. */ private long valPtr; /** Extras */ @GridToStringInclude private GridCacheEntryExtras<K> extras; /** * Flags: * <ul> * <li>Refreshing flag - mask {@link #IS_REFRESHING_MASK}</li> * <li>Deleted flag - mask {@link #IS_DELETED_MASK}</li> * </ul> */ @GridToStringInclude protected byte flags; /** * @param cctx Cache context. * @param key Cache key. * @param hash Key hash value. * @param val Entry value. * @param next Next entry in the linked list. * @param ttl Time to live. * @param hdrId Header id. */ protected GridCacheMapEntry(GridCacheContext<K, V> cctx, K key, int hash, V val, GridCacheMapEntry<K, V> next, long ttl, int hdrId) { log = U.logger(cctx.kernalContext(), logRef, this); if (cctx.portableEnabled()) key = (K)cctx.kernalContext().portable().detachPortable(key); this.key = key; this.hash = hash; this.cctx = cctx; ttlAndExpireTimeExtras(ttl, toExpireTime(ttl)); if (cctx.portableEnabled()) val = (V)cctx.kernalContext().portable().detachPortable(val); synchronized (this) { value(val, null); } next(hdrId, next); ver = cctx.versions().next(); startVer = ver.order(); } /** {@inheritDoc} */ @Override public long startVersion() { return startVer; } /** * Sets entry value. If off-heap value storage is enabled, will serialize value to off-heap. * * @param val Value to store. * @param valBytes Value bytes to store. */ protected void value(@Nullable V val, @Nullable byte[] valBytes) { assert Thread.holdsLock(this); // In case we deal with GGFS cache, count updated data if (cctx.cache().isGgfsDataCache() && cctx.kernalContext().ggfsHelper().isGgfsBlockKey(key())) { int newSize = valueLength((byte[])val, valBytes != null ? GridCacheValueBytes.marshaled(valBytes) : GridCacheValueBytes.nil()); int oldSize = valueLength((byte[])this.val, this.val == null ? valueBytesUnlocked() : GridCacheValueBytes.nil()); int delta = newSize - oldSize; if (delta != 0 && !cctx.isNear()) cctx.cache().onGgfsDataSizeChanged(delta); } if (!isOffHeapValuesOnly()) { this.val = val; this.valBytes = isStoreValueBytes() ? valBytes : null; } else { try { if (cctx.kernalContext().config().isPeerClassLoadingEnabled()) { if (val != null || valBytes != null) { if (val == null) val = cctx.marshaller().unmarshal(valBytes, cctx.deploy().globalLoader()); if (val != null) cctx.gridDeploy().deploy(val.getClass(), val.getClass().getClassLoader()); } if (U.p2pLoader(val)) { cctx.deploy().addDeploymentContext( new GridDeploymentInfoBean((GridDeploymentInfo)val.getClass().getClassLoader())); } } GridUnsafeMemory mem = cctx.unsafeMemory(); assert mem != null; if (val != null || valBytes != null) { boolean valIsByteArr = val != null && val instanceof byte[]; if (valBytes == null && !valIsByteArr) valBytes = CU.marshal(cctx, val); valPtr = mem.putOffHeap(valPtr, valIsByteArr ? (byte[])val : valBytes, valIsByteArr); } else { mem.removeOffHeap(valPtr); valPtr = 0; } } catch (GridException e) { U.error(log, "Failed to deserialize value [entry=" + this + ", val=" + val + ']'); throw new GridRuntimeException(e); } } } /** * Isolated method to get length of GGFS block. * * @param val Value. * @param valBytes Value bytes. * @return Length of value. */ private int valueLength(@Nullable byte[] val, GridCacheValueBytes valBytes) { assert valBytes != null; return val != null ? val.length : valBytes.isNull() ? 0 : valBytes.get().length - (valBytes.isPlain() ? 0 : 6); } /** * @return Value bytes. */ protected GridCacheValueBytes valueBytesUnlocked() { assert Thread.holdsLock(this); if (!isOffHeapValuesOnly()) { if (valBytes != null) return GridCacheValueBytes.marshaled(valBytes); } else { if (valPtr != 0) { GridUnsafeMemory mem = cctx.unsafeMemory(); assert mem != null; return mem.getOffHeap(valPtr); } } return GridCacheValueBytes.nil(); } /** {@inheritDoc} */ @Override public int memorySize() throws GridException { byte[] kb; GridCacheValueBytes vb; V v; int extrasSize; synchronized (this) { kb = keyBytes; vb = valueBytesUnlocked(); v = val; extrasSize = extrasSize(); } if (kb == null || (vb.isNull() && v != null)) { if (kb == null) kb = CU.marshal(cctx, key); if (vb.isNull()) vb = (v != null && v instanceof byte[]) ? GridCacheValueBytes.plain(v) : GridCacheValueBytes.marshaled(CU.marshal(cctx, v)); synchronized (this) { if (keyBytes == null) keyBytes = kb; // If value didn't change. if (!isOffHeapValuesOnly() && valBytes == null && val == v) valBytes = vb.isPlain() ? null : vb.get(); } } return SIZE_OVERHEAD + extrasSize + kb.length + (vb.isNull() ? 0 : vb.get().length); } /** {@inheritDoc} */ @Override public boolean isInternal() { return key instanceof GridCacheInternal; } /** {@inheritDoc} */ @Override public boolean isDht() { return false; } /** {@inheritDoc} */ @Override public boolean isLocal() { return false; } /** {@inheritDoc} */ @Override public boolean isNear() { return false; } /** {@inheritDoc} */ @Override public boolean isReplicated() { return false; } /** {@inheritDoc} */ @Override public boolean detached() { return false; } /** {@inheritDoc} */ @Override public GridCacheContext<K, V> context() { return cctx; } /** {@inheritDoc} */ @Override public boolean isNew() throws GridCacheEntryRemovedException { assert Thread.holdsLock(this); checkObsolete(); return isStartVersion(); } /** {@inheritDoc} */ @Override public synchronized boolean isNewLocked() throws GridCacheEntryRemovedException { checkObsolete(); return isStartVersion(); } /** * @return {@code True} if start version. */ public boolean isStartVersion() { return ver.nodeOrder() == cctx.localNode().order() && ver.order() == startVer; } /** {@inheritDoc} */ @Override public boolean valid(long topVer) { return true; } /** {@inheritDoc} */ @Override public int partition() { return 0; } /** {@inheritDoc} */ @Override public boolean partitionValid() { return true; } /** {@inheritDoc} */ @Nullable @Override public GridCacheEntryInfo<K, V> info() { GridCacheEntryInfo<K, V> info = null; long time = U.currentTimeMillis(); try { synchronized (this) { if (!obsolete()) { info = new GridCacheEntryInfo<>(); info.key(key); long expireTime = expireTimeExtras(); boolean expired = expireTime != 0 && expireTime <= time; info.keyBytes(keyBytes); info.ttl(ttlExtras()); info.expireTime(expireTime); info.version(ver); info.setNew(isStartVersion()); info.setDeleted(deletedUnlocked()); if (!expired) { info.value(cctx.kernalContext().config().isPeerClassLoadingEnabled() ? rawGetOrUnmarshalUnlocked(false) : val); GridCacheValueBytes valBytes = valueBytesUnlocked(); if (!valBytes.isNull()) { if (valBytes.isPlain()) info.value((V)valBytes.get()); else info.valueBytes(valBytes.get()); } } } } } catch (GridException e) { throw new GridRuntimeException("Failed to unmarshal object while creating entry info: " + this, e); } return info; } /** {@inheritDoc} */ @Override public V unswap() throws GridException { return unswap(false, true); } /** * Unswaps an entry. * * @param ignoreFlags Whether to ignore swap flags. * @param needVal If {@code false} then do not to deserialize value during unswap. * @return Value. * @throws GridException If failed. */ @Nullable @Override public V unswap(boolean ignoreFlags, boolean needVal) throws GridException { boolean swapEnabled = cctx.swap().swapEnabled() && (ignoreFlags || !cctx.hasFlag(SKIP_SWAP)); if (!swapEnabled && !cctx.isOffHeapEnabled()) return null; synchronized (this) { if (isStartVersion() && ((flags & IS_UNSWAPPED_MASK) == 0)) { GridCacheSwapEntry<V> e; if (cctx.offheapTiered()) { e = cctx.swap().readOffheapPointer(this); if (e != null) { if (e.offheapPointer() > 0) { valPtr = e.offheapPointer(); if (needVal) { V val = unmarshalOffheap(false); e.value(val); } } else { // Read from swap. valPtr = 0; if (cctx.portableEnabled() && !e.valueIsByteArray()) e.valueBytes(null); // Clear bytes marshalled with portable marshaller. } } } else e = detached() ? cctx.swap().read(this, true) : cctx.swap().readAndRemove(this); if (log.isDebugEnabled()) log.debug("Read swap entry [swapEntry=" + e + ", cacheEntry=" + this + ']'); flags |= IS_UNSWAPPED_MASK; // If there is a value. if (e != null) { long delta = e.expireTime() == 0 ? 0 : e.expireTime() - U.currentTimeMillis(); if (delta >= 0) { V val = e.value(); if (cctx.portableEnabled()) val = (V)cctx.kernalContext().portable().detachPortable(val); // Set unswapped value. update(val, e.valueBytes(), e.expireTime(), e.ttl(), e.version()); return val; } else clearIndex(e.value()); } } } return null; } /** * @throws GridException If failed. */ private void swap() throws GridException { if (cctx.isSwapOrOffheapEnabled() && !deletedUnlocked() && hasValueUnlocked()) { assert Thread.holdsLock(this); long expireTime = expireTimeExtras(); if (expireTime > 0 && U.currentTimeMillis() >= expireTime) { // Don't swap entry if it's expired. if (cctx.offheapTiered() && valPtr > 0) { boolean rmv = cctx.swap().removeOffheap(key, getOrMarshalKeyBytes()); assert rmv; valPtr = 0; } return; } if (val == null && cctx.offheapTiered() && valPtr != 0) { if (log.isDebugEnabled()) log.debug("Value did not change, skip write swap entry: " + this); if (cctx.swap().offheapEvictionEnabled()) cctx.swap().enableOffheapEviction(key(), getOrMarshalKeyBytes()); return; } boolean plain = val instanceof byte[]; GridUuid valClsLdrId = null; if (val != null) valClsLdrId = cctx.deploy().getClassLoaderId(val.getClass().getClassLoader()); cctx.swap().write(key(), getOrMarshalKeyBytes(), plain ? ByteBuffer.wrap((byte[])val) : swapValueBytes(), plain, ver, ttlExtras(), expireTime, cctx.deploy().getClassLoaderId(U.detectObjectClassLoader(key)), valClsLdrId); if (log.isDebugEnabled()) log.debug("Wrote swap entry: " + this); } } /** * @throws GridException If failed. */ protected final void releaseSwap() throws GridException { if (cctx.isSwapOrOffheapEnabled()) { synchronized (this){ cctx.swap().remove(key(), getOrMarshalKeyBytes()); } if (log.isDebugEnabled()) log.debug("Removed swap entry [entry=" + this + ']'); } } /** * @param key Key. * @param matchVer Version to match. */ protected void refreshAhead(final K key, final GridCacheVersion matchVer) { if (log.isDebugEnabled()) log.debug("Scheduling asynchronous refresh for entry: " + this); // Asynchronous execution (we don't check filter here). cctx.closures().runLocalSafe(new GPR() { @SuppressWarnings({"unchecked"}) @Override public void run() { if (log.isDebugEnabled()) log.debug("Refreshing-ahead entry: " + GridCacheMapEntry.this); synchronized (GridCacheMapEntry.this){ // If there is a point to refresh. if (!matchVer.equals(ver)) { refreshingLocked(false); if (log.isDebugEnabled()) log.debug("Will not refresh value as entry has been recently updated: " + GridCacheMapEntry.this); return; } } V val = null; try { val = cctx.store().loadFromStore(null, key); } catch (GridException e) { U.error(log, "Failed to refresh-ahead entry: " + GridCacheMapEntry.this, e); } finally { synchronized (GridCacheMapEntry.this) { refreshingLocked(false); // If version matched, set value. Note that we don't update // swap here, as asynchronous refresh happens only if // value is already in memory. if (val != null && matchVer.equals(ver)) { try { V prev = rawGetOrUnmarshalUnlocked(false); long ttl = ttlExtras(); long expTime = toExpireTime(ttl); // Detach value before index update. if (cctx.portableEnabled()) val = (V)cctx.kernalContext().portable().detachPortable(val); updateIndex(val, null, expTime, ver, prev); // Don't change version for read-through. update(val, null, expTime, ttl, ver); } catch (GridException e) { U.error(log, "Failed to update cache index: " + GridCacheMapEntry.this, e); } } } } } }, true); } /** * @param tx Transaction. * @param key Key. * @param reload flag. * @param filter Filter. * @param subjId Subject ID. * @param taskName Task name. * @return Read value. * @throws GridException If failed. */ @SuppressWarnings({"RedundantTypeArguments"}) @Nullable protected V readThrough(@Nullable GridCacheTxEx<K, V> tx, K key, boolean reload, GridPredicate<GridCacheEntry<K, V>>[] filter, UUID subjId, String taskName) throws GridException { return cctx.store().loadFromStore(tx, key); } /** {@inheritDoc} */ @Nullable @Override public final V innerGet(@Nullable GridCacheTxEx<K, V> tx, boolean readSwap, boolean readThrough, boolean failFast, boolean unmarshal, boolean updateMetrics, boolean evt, boolean tmp, UUID subjId, Object transformClo, String taskName, GridPredicate<GridCacheEntry<K, V>>[] filter) throws GridException, GridCacheEntryRemovedException, GridCacheFilterFailedException { cctx.denyOnFlag(LOCAL); return innerGet0(tx, readSwap, readThrough, evt, failFast, unmarshal, updateMetrics, tmp, subjId, transformClo, taskName, filter); } /** {@inheritDoc} */ @SuppressWarnings({"unchecked", "RedundantTypeArguments", "TooBroadScope"}) private V innerGet0(GridCacheTxEx<K, V> tx, boolean readSwap, boolean readThrough, boolean evt, boolean failFast, boolean unmarshal, boolean updateMetrics, boolean tmp, UUID subjId, Object transformClo, String taskName, GridPredicate<GridCacheEntry<K, V>>[] filter) throws GridException, GridCacheEntryRemovedException, GridCacheFilterFailedException { // Disable read-through if there is no store. if (readThrough && !cctx.isStoreEnabled()) readThrough = false; GridCacheMvccCandidate<K> owner; V old; V ret = null; if (!F.isEmptyOrNulls(filter) && !cctx.isAll( (new GridCacheFilterEvaluationEntry<>(key, rawGetOrUnmarshal(true), this, true)), filter)) return CU.<V>failed(failFast); boolean asyncRefresh = false; GridCacheVersion startVer; boolean expired = false; V expiredVal = null; boolean hasOldBytes; synchronized (this) { checkObsolete(); // Cache version for optimistic check. startVer = ver; GridCacheMvcc<K> mvcc = mvccExtras(); owner = mvcc == null ? null : mvcc.anyOwner(); double delta = Double.MAX_VALUE; long expireTime = expireTimeExtras(); if (expireTime > 0) { delta = expireTime - U.currentTimeMillis(); if (log.isDebugEnabled()) log.debug("Checked expiration time for entry [timeLeft=" + delta + ", entry=" + this + ']'); if (delta <= 0) expired = true; } V val = this.val; hasOldBytes = valBytes != null || valPtr != 0; if ((unmarshal || isOffHeapValuesOnly()) && !expired && val == null && hasOldBytes) val = rawGetOrUnmarshalUnlocked(tmp); boolean valid = valid(tx != null ? tx.topologyVersion() : cctx.affinity().affinityTopologyVersion()); // Attempt to load from swap. if (val == null && !hasOldBytes && readSwap) { // Only promote when loading initial state. if (isNew() || !valid) { // If this entry is already expired (expiration time was too low), // we simply remove from swap and clear index. if (expired) { releaseSwap(); // Previous value is guaranteed to be null clearIndex(null); } else { // Read and remove swap entry. if (tmp) { unswap(false, false); val = rawGetOrUnmarshalUnlocked(true); } else val = unswap(); // Recalculate expiration after swap read. if (expireTime > 0) { delta = expireTime - U.currentTimeMillis(); if (log.isDebugEnabled()) log.debug("Checked expiration time for entry [timeLeft=" + delta + ", entry=" + this + ']'); if (delta <= 0) expired = true; } } } } // Only calculate asynchronous refresh-ahead, if there is no other // one in progress and if not expired. if (delta > 0 && expireTime > 0 && !refreshingUnlocked()) { double refreshRatio = cctx.config().getRefreshAheadRatio(); if (1 - delta / ttlExtras() >= refreshRatio) asyncRefresh = true; } old = expired || !valid ? null : val; if (expired) { expiredVal = val; value(null, null); } if (old == null && !hasOldBytes) { asyncRefresh = false; if (updateMetrics) cctx.cache().metrics0().onRead(false); } else { if (updateMetrics) cctx.cache().metrics0().onRead(true); // Set retVal here for event notification. ret = old; // Mark this entry as refreshing, so other threads won't schedule // asynchronous refresh while this one is in progress. if (asyncRefresh || readThrough) refreshingLocked(true); } if (evt && expired && cctx.events().isRecordable(EVT_CACHE_OBJECT_EXPIRED)) { cctx.events().addEvent(partition(), key, tx, owner, EVT_CACHE_OBJECT_EXPIRED, null, false, expiredVal, expiredVal != null || hasOldBytes, subjId, null, taskName); // No more notifications. evt = false; } if (evt && !expired && cctx.events().isRecordable(EVT_CACHE_OBJECT_READ)) { cctx.events().addEvent(partition(), key, tx, owner, EVT_CACHE_OBJECT_READ, ret, ret != null, old, hasOldBytes || old != null, subjId, transformClo != null ? transformClo.getClass().getName() : null, taskName); // No more notifications. evt = false; } } if (asyncRefresh && !readThrough && cctx.isStoreEnabled()) { assert ret != null; refreshAhead(key, startVer); } // Check before load. if (!cctx.isAll(this, filter)) return CU.<V>failed(failFast, ret); if (ret != null) { // If return value is consistent, then done. if (F.isEmptyOrNulls(filter) || version().equals(startVer)) return ret; // Try again (recursion). return innerGet0(tx, readSwap, readThrough, false, failFast, unmarshal, updateMetrics, tmp, subjId, transformClo, taskName, filter); } boolean loadedFromStore = false; if (ret == null && readThrough) { GridCacheTxEx tx0 = null; if (tx != null && tx.local()) { if (cctx.isReplicated() || cctx.isColocated() || tx.near()) tx0 = tx; else if (tx.dht()) { GridCacheVersion ver = ((GridDhtTxLocalAdapter)tx).nearXidVersion(); tx0 = cctx.dht().near().context().tm().tx(ver); } } ret = readThrough(tx0, key, false, filter, subjId, taskName); loadedFromStore = true; } boolean match = false; synchronized (this) { long ttl = ttlExtras(); // If version matched, set value. if (startVer.equals(ver)) { match = true; if (ret != null) { // Detach value before index update. if (cctx.portableEnabled()) ret = (V)cctx.kernalContext().portable().detachPortable(ret); GridCacheVersion nextVer = nextVersion(); V prevVal = rawGetOrUnmarshalUnlocked(false); long expTime = toExpireTime(ttl); if (loadedFromStore) // Update indexes before actual write to entry. updateIndex(ret, null, expTime, nextVer, prevVal); // Don't change version for read-through. update(ret, null, expTime, ttl, nextVer); if (cctx.deferredDelete() && deletedUnlocked() && !isInternal() && !detached()) deletedUnlocked(false); } if (evt && cctx.events().isRecordable(EVT_CACHE_OBJECT_READ)) cctx.events().addEvent(partition(), key, tx, owner, EVT_CACHE_OBJECT_READ, ret, ret != null, old, hasOldBytes, subjId, transformClo != null ? transformClo.getClass().getName() : null, taskName); } } if (F.isEmptyOrNulls(filter) || match) return ret; // Try again (recursion). return innerGet0(tx, readSwap, readThrough, false, failFast, unmarshal, updateMetrics, tmp, subjId, transformClo, taskName, filter); } /** {@inheritDoc} */ @SuppressWarnings({"unchecked", "TooBroadScope"}) @Nullable @Override public final V innerReload(GridPredicate<GridCacheEntry<K, V>>[] filter) throws GridException, GridCacheEntryRemovedException { cctx.denyOnFlag(GridCacheFlag.READ); CU.checkStore(cctx); GridCacheVersion startVer; boolean wasNew; synchronized (this) { checkObsolete(); // Cache version for optimistic check. startVer = ver; wasNew = isNew(); } String taskName = cctx.kernalContext().job().currentTaskName(); // Check before load. if (cctx.isAll(this, filter)) { V ret = readThrough(null, key, true, filter, cctx.localNodeId(), taskName); boolean touch = false; try { synchronized (this) { long ttl = ttlExtras(); // Generate new version. GridCacheVersion nextVer = cctx.versions().nextForLoad(ver); // If entry was loaded during read step. if (wasNew && !isNew()) // Map size was updated on entry creation. return ret; // If version matched, set value. if (startVer.equals(ver)) { releaseSwap(); V old = rawGetOrUnmarshalUnlocked(false); long expTime = toExpireTime(ttl); // Detach value before index update. if (cctx.portableEnabled()) ret = (V)cctx.kernalContext().portable().detachPortable(ret); // Update indexes. if (ret != null) { updateIndex(ret, null, expTime, nextVer, old); if (cctx.deferredDelete() && !isInternal() && !detached() && deletedUnlocked()) deletedUnlocked(false); } else { clearIndex(old); if (cctx.deferredDelete() && !isInternal() && !detached() && !deletedUnlocked()) deletedUnlocked(true); } update(ret, null, expTime, ttl, nextVer); touch = true; // If value was set - return, otherwise try again. return ret; } } if (F.isEmptyOrNulls(filter)) { touch = true; return ret; } } finally { if (touch) cctx.evicts().touch(this, cctx.affinity().affinityTopologyVersion()); } // Recursion. return innerReload(filter); } // If filter didn't pass. return null; } /** * @param nodeId Node ID. */ protected void recordNodeId(UUID nodeId) { // No-op. } /** {@inheritDoc} */ @Override public final GridCacheUpdateTxResult<V> innerSet( @Nullable GridCacheTxEx<K, V> tx, UUID evtNodeId, UUID affNodeId, V val, @Nullable byte[] valBytes, boolean writeThrough, boolean retval, long ttl, boolean evt, boolean metrics, long topVer, GridPredicate<GridCacheEntry<K, V>>[] filter, GridDrType drType, long drExpireTime, @Nullable GridCacheVersion explicitVer, @Nullable UUID subjId, String taskName ) throws GridException, GridCacheEntryRemovedException { V old; boolean valid = valid(tx != null ? tx.topologyVersion() : topVer); // Lock should be held by now. if (!cctx.isAll(this, filter)) return new GridCacheUpdateTxResult<>(false, null); final GridCacheVersion newVer; boolean intercept = cctx.config().getInterceptor() != null; synchronized (this) { checkObsolete(); if (cctx.kernalContext().config().isCacheSanityCheckEnabled()) { if (tx != null && tx.groupLock()) groupLockSanityCheck(tx); else assert tx == null || (!tx.local() && tx.onePhaseCommit()) || tx.ownsLock(this) : "Transaction does not own lock for update [entry=" + this + ", tx=" + tx + ']'; } // Load and remove from swap if it is new. boolean startVer = isStartVersion(); if (startVer) unswap(true, retval); newVer = explicitVer != null ? explicitVer : tx == null ? nextVersion() : tx.writeVersion(); assert newVer != null : "Failed to get write version for tx: " + tx; if (tx != null && !tx.local() && tx.onePhaseCommit() && explicitVer == null) { if (!(isNew() || !valid) && ver.compareTo(newVer) > 0) { if (log.isDebugEnabled()) log.debug("Skipping entry update for one-phase commit since current entry version is " + "greater than write version [entry=" + this + ", newVer=" + newVer + ']'); return new GridCacheUpdateTxResult<>(false, null); } } old = (retval || intercept) ? rawGetOrUnmarshalUnlocked(!retval) : this.val; GridCacheValueBytes oldBytes = valueBytesUnlocked(); if (intercept) { V interceptorVal = (V)cctx.config().getInterceptor().onBeforePut(key, old, val); if (interceptorVal == null) return new GridCacheUpdateTxResult<>(false, cctx.<V>unwrapTemporary(old)); else if (interceptorVal != val) { val = cctx.unwrapTemporary(interceptorVal); valBytes = null; } } // Determine new ttl and expire time. if (ttl < 0) ttl = ttlExtras(); assert ttl >= 0; long expireTime = drExpireTime < 0L ? toExpireTime(ttl) : drExpireTime; // Detach value before index update. if (cctx.portableEnabled()) val = (V)cctx.kernalContext().portable().detachPortable(val); // Update index inside synchronization since it can be updated // in load methods without actually holding entry lock. if (val != null || valBytes != null) { updateIndex(val, valBytes, expireTime, newVer, old); if (cctx.deferredDelete() && deletedUnlocked() && !isInternal() && !detached()) deletedUnlocked(false); } update(val, valBytes, expireTime, ttl, newVer); drReplicate(drType, val, valBytes, newVer); recordNodeId(affNodeId); if (metrics) cctx.cache().metrics0().onWrite(); if (evt && newVer != null && cctx.events().isRecordable(EVT_CACHE_OBJECT_PUT)) { V evtOld = cctx.unwrapTemporary(old); cctx.events().addEvent(partition(), key, evtNodeId, tx == null ? null : tx.xid(), newVer, EVT_CACHE_OBJECT_PUT, val, val != null, evtOld, evtOld != null || hasValueUnlocked(), subjId, null, taskName); } GridCacheMode mode = cctx.config().getCacheMode(); if (mode == GridCacheMode.LOCAL || mode == GridCacheMode.REPLICATED || (tx != null && (tx.dht() || tx.colocated()) && tx.local())) cctx.continuousQueries().onEntryUpdate(this, key, val, valueBytesUnlocked(), old, oldBytes); cctx.dataStructures().onEntryUpdated(key, false); } if (log.isDebugEnabled()) log.debug("Updated cache entry [val=" + val + ", old=" + old + ", entry=" + this + ']'); // Persist outside of synchronization. The correctness of the // value will be handled by current transaction. if (writeThrough) cctx.store().putToStore(tx, key, val, newVer); if (intercept) cctx.config().getInterceptor().onAfterPut(key, val); return valid ? new GridCacheUpdateTxResult<>(true, retval ? old : null) : new GridCacheUpdateTxResult<V>(false, null); } /** {@inheritDoc} */ @Override public final GridCacheUpdateTxResult<V> innerRemove( @Nullable GridCacheTxEx<K, V> tx, UUID evtNodeId, UUID affNodeId, boolean writeThrough, boolean retval, boolean evt, boolean metrics, long topVer, GridPredicate<GridCacheEntry<K, V>>[] filter, GridDrType drType, @Nullable GridCacheVersion explicitVer, @Nullable UUID subjId, String taskName ) throws GridException, GridCacheEntryRemovedException { assert cctx.transactional(); V old; GridCacheVersion newVer; boolean valid = valid(tx != null ? tx.topologyVersion() : topVer); // Lock should be held by now. if (!cctx.isAll(this, filter)) return new GridCacheUpdateTxResult<>(false, null); GridCacheVersion obsoleteVer = null; GridCacheVersion enqueueVer = null; boolean intercept = cctx.config().getInterceptor() != null; GridBiTuple<Boolean, V> interceptRes = null; try { synchronized (this) { checkObsolete(); if (tx != null && tx.groupLock() && cctx.kernalContext().config().isCacheSanityCheckEnabled()) groupLockSanityCheck(tx); else assert tx == null || (!tx.local() && tx.onePhaseCommit()) || tx.ownsLock(this) : "Transaction does not own lock for remove[entry=" + this + ", tx=" + tx + ']'; boolean startVer = isStartVersion(); if (startVer) { if (tx != null && !tx.local() && tx.onePhaseCommit()) // Must promote to check version for one-phase commit tx. unswap(true, retval); else // Release swap. releaseSwap(); } newVer = explicitVer != null ? explicitVer : tx == null ? nextVersion() : tx.writeVersion(); if (tx != null && !tx.local() && tx.onePhaseCommit() && explicitVer == null) { if (!startVer && ver.compareTo(newVer) > 0) { if (log.isDebugEnabled()) log.debug("Skipping entry removal for one-phase commit since current entry version is " + "greater than write version [entry=" + this + ", newVer=" + newVer + ']'); return new GridCacheUpdateTxResult<>(false, null); } if (!detached()) enqueueVer = newVer; } old = (retval || intercept) ? rawGetOrUnmarshalUnlocked(!retval) : val; if (intercept) { interceptRes = cctx.config().<K, V>getInterceptor().onBeforeRemove(key, old); if (cctx.cancelRemove(interceptRes)) return new GridCacheUpdateTxResult<>(false, cctx.<V>unwrapTemporary(interceptRes.get2())); } GridCacheValueBytes oldBytes = valueBytesUnlocked(); if (old == null) old = saveValueForIndexUnlocked(); // Clear indexes inside of synchronization since indexes // can be updated without actually holding entry lock. clearIndex(old); update(null, null, 0, 0, newVer); if (cctx.offheapTiered() && valPtr > 0) { boolean rmv = cctx.swap().removeOffheap(key, getOrMarshalKeyBytes()); assert rmv; valPtr = 0; } if (cctx.deferredDelete() && !detached() && !isInternal()) { if (!deletedUnlocked()) deletedUnlocked(true); enqueueVer = newVer; } drReplicate(drType, null, null, newVer); if (metrics) cctx.cache().metrics0().onWrite(); if (tx == null) obsoleteVer = newVer; else { // Only delete entry if the lock is not explicit. if (tx.groupLock() || lockedBy(tx.xidVersion())) obsoleteVer = tx.xidVersion(); else if (log.isDebugEnabled()) log.debug("Obsolete version was not set because lock was explicit: " + this); } if (evt && newVer != null && cctx.events().isRecordable(EVT_CACHE_OBJECT_REMOVED)) { V evtOld = cctx.unwrapTemporary(old); cctx.events().addEvent(partition(), key, evtNodeId, tx == null ? null : tx.xid(), newVer, EVT_CACHE_OBJECT_REMOVED, null, false, evtOld, evtOld != null || hasValueUnlocked(), subjId, null, taskName); } GridCacheMode mode = cctx.config().getCacheMode(); if (mode == GridCacheMode.LOCAL || mode == GridCacheMode.REPLICATED || (tx != null && (tx.dht() || tx.colocated()) && tx.local())) cctx.continuousQueries().onEntryUpdate(this, key, null, null, old, oldBytes); cctx.dataStructures().onEntryUpdated(key, true); } } finally { if (enqueueVer != null) { assert cctx.deferredDelete(); cctx.onDeferredDelete(this, enqueueVer); } } // Persist outside of synchronization. The correctness of the // value will be handled by current transaction. if (writeThrough) cctx.store().removeFromStore(tx, key); if (!cctx.deferredDelete()) { boolean marked = false; synchronized (this) { // If entry is still removed. if (newVer == ver) { if (obsoleteVer == null || !(marked = markObsolete0(obsoleteVer, true))) { if (log.isDebugEnabled()) log.debug("Entry could not be marked obsolete (it is still used): " + this); } else { recordNodeId(affNodeId); // If entry was not marked obsolete, then removed lock // will be registered whenever removeLock is called. cctx.mvcc().addRemoved(obsoleteVer); if (log.isDebugEnabled()) log.debug("Entry was marked obsolete: " + this); } } } if (marked) onMarkedObsolete(); } if (intercept) cctx.config().getInterceptor().onAfterRemove(key, old); return valid ? new GridCacheUpdateTxResult<>(true, cctx.<V>unwrapTemporary(interceptRes != null ? interceptRes.get2() : old)) : new GridCacheUpdateTxResult<V>(false, null); } /** {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public GridBiTuple<Boolean, V> innerUpdateLocal( GridCacheVersion ver, GridCacheOperation op, @Nullable Object writeObj, boolean writeThrough, boolean retval, long ttl, boolean evt, boolean metrics, @Nullable GridPredicate<GridCacheEntry<K, V>>[] filter, boolean intercept, @Nullable UUID subjId, String taskName ) throws GridException, GridCacheEntryRemovedException { assert cctx.isLocal() && cctx.atomic(); V old; boolean res = true; GridBiTuple<Boolean, ?> interceptorRes = null; synchronized (this) { boolean needVal = retval || intercept || op == GridCacheOperation.TRANSFORM || !F.isEmpty(filter); checkObsolete(); // Load and remove from swap if it is new. if (isNew()) unswap(true, retval); long newTtl = ttl; if (newTtl < 0) newTtl = ttlExtras(); long newExpireTime = toExpireTime(newTtl); // Possibly get old value form store. old = needVal ? rawGetOrUnmarshalUnlocked(!retval) : val; GridCacheValueBytes oldBytes = valueBytesUnlocked(); if (needVal && old == null) { old = readThrough(null, key, false, CU.<K, V>empty(), subjId, taskName); // Detach value before index update. if (cctx.portableEnabled()) old = (V)cctx.kernalContext().portable().detachPortable(old); if (old != null) updateIndex(old, null, expireTime(), ver, null); else clearIndex(null); update(old, null, 0, 0, ver); } // Check filter inside of synchronization. if (!F.isEmpty(filter)) { boolean pass = cctx.isAll(wrapFilterLocked(), filter); if (!pass) return new GridBiTuple<>(false, retval ? old : null); } // Apply metrics. if (metrics && needVal) cctx.cache().metrics0().onRead(old != null); String transformCloClsName = null; V updated; // Calculate new value. if (op == GridCacheOperation.TRANSFORM) { transformCloClsName = writeObj.getClass().getName(); GridClosure<V, V> transform = (GridClosure<V, V>)writeObj; assert transform != null; updated = cctx.unwrapTemporary(transform.apply(old)); } else updated = (V)writeObj; op = updated == null ? GridCacheOperation.DELETE : GridCacheOperation.UPDATE; if (intercept) { if (op == GridCacheOperation.UPDATE) { updated = (V)cctx.config().getInterceptor().onBeforePut(key, old, updated); if (updated == null) return new GridBiTuple<>(false, cctx.<V>unwrapTemporary(old)); } else { interceptorRes = cctx.config().getInterceptor().onBeforeRemove(key, old); if (cctx.cancelRemove(interceptorRes)) return new GridBiTuple<>(false, cctx.<V>unwrapTemporary(interceptorRes.get2())); } } boolean hadVal = hasValueUnlocked(); // Try write-through. if (op == GridCacheOperation.UPDATE) { // Detach value before index update. if (cctx.portableEnabled()) updated = (V)cctx.kernalContext().portable().detachPortable(updated); if (writeThrough) // Must persist inside synchronization in non-tx mode. cctx.store().putToStore(null, key, updated, ver); // Update index inside synchronization since it can be updated // in load methods without actually holding entry lock. updateIndex(updated, null, newExpireTime, ver, old); update(updated, null, newExpireTime, newTtl, ver); if (evt) { V evtOld = null; if (transformCloClsName != null && cctx.events().isRecordable(EVT_CACHE_OBJECT_READ)) { evtOld = cctx.unwrapTemporary(old); cctx.events().addEvent(partition(), key, cctx.localNodeId(), null, (GridCacheVersion)null, EVT_CACHE_OBJECT_READ, evtOld, evtOld != null || hadVal, evtOld, evtOld != null || hadVal, subjId, transformCloClsName, taskName); } if (cctx.events().isRecordable(EVT_CACHE_OBJECT_PUT)) { if (evtOld == null) evtOld = cctx.unwrapTemporary(old); cctx.events().addEvent(partition(), key, cctx.localNodeId(), null, (GridCacheVersion)null, EVT_CACHE_OBJECT_PUT, updated, updated != null, evtOld, evtOld != null || hadVal, subjId, null, taskName); } } } else { if (writeThrough) // Must persist inside synchronization in non-tx mode. cctx.store().removeFromStore(null, key); // Update index inside synchronization since it can be updated // in load methods without actually holding entry lock. clearIndex(old); update(null, null, 0, 0, ver); if (evt) { V evtOld = null; if (transformCloClsName != null && cctx.events().isRecordable(EVT_CACHE_OBJECT_READ)) cctx.events().addEvent(partition(), key, cctx.localNodeId(), null, (GridCacheVersion)null, EVT_CACHE_OBJECT_READ, evtOld, evtOld != null || hadVal, evtOld, evtOld != null || hadVal, subjId, transformCloClsName, taskName); if (cctx.events().isRecordable(EVT_CACHE_OBJECT_REMOVED)) { if (evtOld == null) evtOld = cctx.unwrapTemporary(old); cctx.events().addEvent(partition(), key, cctx.localNodeId(), null, (GridCacheVersion) null, EVT_CACHE_OBJECT_REMOVED, null, false, evtOld, evtOld != null || hadVal, subjId, null, taskName); } } res = hadVal; } if (metrics) cctx.cache().metrics0().onWrite(); cctx.continuousQueries().onEntryUpdate(this, key, val, valueBytesUnlocked(), old, oldBytes); cctx.dataStructures().onEntryUpdated(key, op == DELETE); if (intercept) { if (op == UPDATE) cctx.config().getInterceptor().onAfterPut(key, val); else cctx.config().getInterceptor().onAfterRemove(key, old); } } return new GridBiTuple<>(res, cctx.<V>unwrapTemporary(interceptorRes != null ? interceptorRes.get2() : old)); } /** {@inheritDoc} */ @Override public GridCacheUpdateAtomicResult<K, V> innerUpdate( GridCacheVersion newVer, UUID evtNodeId, UUID affNodeId, GridCacheOperation op, @Nullable Object writeObj, @Nullable byte[] valBytes, boolean writeThrough, boolean retval, long ttl, boolean evt, boolean metrics, boolean primary, boolean verCheck, @Nullable GridPredicate<GridCacheEntry<K, V>>[] filter, GridDrType drType, long drTtl, long drExpireTime, @Nullable GridCacheVersion drVer, boolean drResolve, boolean intercept, @Nullable UUID subjId, String taskName ) throws GridException, GridCacheEntryRemovedException, GridClosureException { assert cctx.atomic(); V old; boolean res = true; V updated; GridCacheVersion enqueueVer = null; GridDrResolveResult<V> drRes = null; long newTtl = 0L; long newExpireTime = 0L; long newDrExpireTime = -1L; // Explicit DR expire time which possibly will be sent to DHT node. synchronized (this) { boolean needVal = intercept || retval || op == GridCacheOperation.TRANSFORM || !F.isEmptyOrNulls(filter); checkObsolete(); // Load and remove from swap if it is new. if (isNew()) unswap(true, retval); Object transformClo = null; if (drResolve) { drRes = cctx.dr().resolveAtomic(this, op, writeObj, valBytes, ttl, drTtl, drExpireTime, drVer); if (drRes != null) { if (drRes.isUseOld()) { old = retval ? rawGetOrUnmarshalUnlocked(false) : val; return new GridCacheUpdateAtomicResult<>(false, old, null, 0L, -1L, null, null, false); } newTtl = drRes.newTtl(); newExpireTime = drRes.newExpireTime(); newDrExpireTime = drRes.newDrExpireTime(); op = drRes.operation(); writeObj = drRes.value(); valBytes = drRes.valueBytes(); if (drRes.isMerge()) drVer = null; // Update will be considered as local. } else drVer = null; } if (drRes == null) { // Perform version check only in case there will be no explicit conflict resolution. if (verCheck) { if (!isNew() && ATOMIC_VER_COMPARATOR.compare(ver, newVer) >= 0) { if (ATOMIC_VER_COMPARATOR.compare(ver, newVer) == 0 && cctx.isStoreEnabled() && primary) { if (log.isDebugEnabled()) log.debug("Received entry update with same version as current (will update store) " + "[entry=" + this + ", newVer=" + newVer + ']'); V val = rawGetOrUnmarshalUnlocked(false); if (val == null) { assert deletedUnlocked(); cctx.store().removeFromStore(null, key()); } else cctx.store().putToStore(null, key(), val, ver); } else { if (log.isDebugEnabled()) log.debug("Received entry update with smaller version than current (will ignore) " + "[entry=" + this + ", newVer=" + newVer + ']'); } old = retval ? rawGetOrUnmarshalUnlocked(false) : val; return new GridCacheUpdateAtomicResult<>(false, old, null, 0L, -1L, null, null, false); } } else assert isNew() || ATOMIC_VER_COMPARATOR.compare(ver, newVer) <= 0 : "Invalid version for inner update [entry=" + this + ", newVer=" + newVer + ']'; } if (drRes == null) { // Calculate TTL and expire time for local update. if (drTtl >= 0L) { assert drExpireTime >= 0L; newTtl = drTtl; newExpireTime = drExpireTime; } else { assert drExpireTime == -1L; newTtl = ttl; if (newTtl < 0) newTtl = ttlExtras(); newExpireTime = toExpireTime(newTtl); } } // Possibly get old value form store. old = needVal ? rawGetOrUnmarshalUnlocked(!retval) : val; GridCacheValueBytes oldBytes = valueBytesUnlocked(); if (needVal && old == null) { old = readThrough(null, key, false, CU.<K, V>empty(), subjId, taskName); // Detach value before index update. if (cctx.portableEnabled()) old = (V)cctx.kernalContext().portable().detachPortable(old); if (old != null) updateIndex(old, null, expireTime(), ver, null); else clearIndex(null); update(old, null, 0, 0, ver); if (deletedUnlocked() && old != null && !isInternal()) deletedUnlocked(false); } // Check filter inside of synchronization. if (!F.isEmptyOrNulls(filter)) { boolean pass = cctx.isAll(wrapFilterLocked(), filter); if (!pass) return new GridCacheUpdateAtomicResult<>(false, retval ? old : null, null, 0L, -1L, null, null, false); } // Apply metrics. if (metrics && needVal) cctx.cache().metrics0().onRead(old != null); // Calculate new value. if (op == GridCacheOperation.TRANSFORM) { transformClo = writeObj; GridClosure<V, V> transform = (GridClosure<V, V>)writeObj; updated = cctx.unwrapTemporary(transform.apply(old)); valBytes = null; } else updated = (V)writeObj; op = updated == null ? GridCacheOperation.DELETE : GridCacheOperation.UPDATE; assert op == GridCacheOperation.UPDATE || (op == GridCacheOperation.DELETE && updated == null); boolean hadVal = hasValueUnlocked(); // Incorporate DR version into new version if needed. if (drVer != null && drVer != newVer) newVer = new GridCacheVersionEx(newVer.topologyVersion(), newVer.globalTime(), newVer.order(), newVer.nodeOrder(), newVer.dataCenterId(), drVer); GridBiTuple<Boolean, V> interceptRes = null; if (op == GridCacheOperation.UPDATE) { if (intercept) { V interceptorVal = (V)cctx.config().getInterceptor().onBeforePut(key, old, updated); if (interceptorVal == null) return new GridCacheUpdateAtomicResult<>(false, retval ? old : null, null, 0L, -1L, null, null, false); else if (interceptorVal != updated) { updated = cctx.unwrapTemporary(interceptorVal); valBytes = null; } } // Try write-through. if (writeThrough) // Must persist inside synchronization in non-tx mode. cctx.store().putToStore(null, key, updated, newVer); if (!hadVal) { boolean new0 = isNew(); assert deletedUnlocked() || new0 || isInternal(): "Invalid entry [entry=" + this + ", locNodeId=" + cctx.localNodeId() + ']'; if (!new0 && !isInternal()) deletedUnlocked(false); } else { assert !deletedUnlocked() : "Invalid entry [entry=" + this + ", locNodeId=" + cctx.localNodeId() + ']'; // Do not change size; } if (cctx.portableEnabled()) updated = (V)cctx.kernalContext().portable().detachPortable(updated); // Update index inside synchronization since it can be updated // in load methods without actually holding entry lock. updateIndex(updated, valBytes, newExpireTime, newVer, old); update(updated, valBytes, newExpireTime, newTtl, newVer); drReplicate(drType, updated, valBytes, newVer); recordNodeId(affNodeId); if (evt) { V evtOld = null; if (transformClo != null && cctx.events().isRecordable(EVT_CACHE_OBJECT_READ)) { evtOld = cctx.unwrapTemporary(old); cctx.events().addEvent(partition(), key, evtNodeId, null, newVer, EVT_CACHE_OBJECT_READ, evtOld, evtOld != null || hadVal, evtOld, evtOld != null || hadVal, subjId, transformClo.getClass().getName(), taskName); } if (newVer != null && cctx.events().isRecordable(EVT_CACHE_OBJECT_PUT)) { if (evtOld == null) evtOld = cctx.unwrapTemporary(old); cctx.events().addEvent(partition(), key, evtNodeId, null, newVer, EVT_CACHE_OBJECT_PUT, updated, updated != null, evtOld, evtOld != null || hadVal, subjId, null, taskName); } } } else { if (intercept) { interceptRes = cctx.config().<K, V>getInterceptor().onBeforeRemove(key, old); if (cctx.cancelRemove(interceptRes)) return new GridCacheUpdateAtomicResult<>(false, cctx.<V>unwrapTemporary(interceptRes.get2()), null, 0L, -1L, null, null, false); } if (writeThrough) // Must persist inside synchronization in non-tx mode. cctx.store().removeFromStore(null, key); // Update index inside synchronization since it can be updated // in load methods without actually holding entry lock. clearIndex(old); if (hadVal) { assert !deletedUnlocked(); if (!isInternal()) deletedUnlocked(true); } else { boolean new0 = isNew(); assert deletedUnlocked() || new0 || isInternal() : "Invalid entry [entry=" + this + ", locNodeId=" + cctx.localNodeId() + ']'; if (new0) { if (!isInternal()) deletedUnlocked(true); } } enqueueVer = newVer; // Clear value on backup. Entry will be removed from cache when it got evicted from queue. update(null, null, 0, 0, newVer); if (cctx.offheapTiered() && valPtr != 0) { boolean rmv = cctx.swap().removeOffheap(key, getOrMarshalKeyBytes()); assert rmv; valPtr = 0; } clearReaders(); recordNodeId(affNodeId); drReplicate(drType, null, null, newVer); if (evt) { V evtOld = null; if (transformClo != null && cctx.events().isRecordable(EVT_CACHE_OBJECT_READ)) { evtOld = cctx.unwrapTemporary(old); cctx.events().addEvent(partition(), key, evtNodeId, null, newVer, EVT_CACHE_OBJECT_READ, evtOld, evtOld != null || hadVal, evtOld, evtOld != null || hadVal, subjId, transformClo.getClass().getName(), taskName); } if (newVer != null && cctx.events().isRecordable(EVT_CACHE_OBJECT_REMOVED)) { if (evtOld == null) evtOld = cctx.unwrapTemporary(old); cctx.events().addEvent(partition(), key, evtNodeId, null, newVer, EVT_CACHE_OBJECT_REMOVED, null, false, evtOld, evtOld != null || hadVal, subjId, null, taskName); } } res = hadVal; // Do not propagate zeroed TTL and expire time. newTtl = 0L; newDrExpireTime = -1L; } if (metrics) cctx.cache().metrics0().onWrite(); if (primary || cctx.isReplicated()) cctx.continuousQueries().onEntryUpdate(this, key, val, valueBytesUnlocked(), old, oldBytes); cctx.dataStructures().onEntryUpdated(key, op == DELETE); if (intercept) { if (op == UPDATE) cctx.config().getInterceptor().onAfterPut(key, val); else cctx.config().getInterceptor().onAfterRemove(key, old); if (interceptRes != null) old = cctx.unwrapTemporary(interceptRes.get2()); } } if (log.isDebugEnabled()) log.debug("Updated cache entry [val=" + val + ", old=" + old + ", entry=" + this + ']'); return new GridCacheUpdateAtomicResult<>(res, old, updated, newTtl, newDrExpireTime, enqueueVer, drRes, true); } /** * Perform DR if needed. * * @param drType DR type. * @param val Value. * @param valBytes Value bytes. * @param ver Version. * @throws GridException In case of exception. */ private void drReplicate(GridDrType drType, @Nullable V val, @Nullable byte[] valBytes, GridCacheVersion ver) throws GridException { if (cctx.isDrEnabled() && drType != DR_NONE && !isInternal()) cctx.dr().replicate(key, keyBytes, val, valBytes, rawTtl(), rawExpireTime(), ver.drVersion(), drType); } /** * @return {@code true} if entry has readers. It makes sense only for dht entry. * @throws GridCacheEntryRemovedException If removed. */ protected boolean hasReaders() throws GridCacheEntryRemovedException { return false; } protected void clearReaders() { // No-op. } /** {@inheritDoc} */ @Override public boolean clear(GridCacheVersion ver, boolean readers, @Nullable GridPredicate<GridCacheEntry<K, V>>[] filter) throws GridException { cctx.denyOnFlag(GridCacheFlag.READ); boolean ret; boolean rmv; boolean marked; while (true) { ret = false; rmv = false; marked = false; // For optimistic check. GridCacheVersion startVer = null; if (!F.isEmptyOrNulls(filter)) { synchronized (this) { startVer = this.ver; } if (!cctx.isAll(this, filter)) return false; } synchronized (this) { if (startVer != null && !startVer.equals(this.ver)) // Version has changed since filter checking. continue; V val = saveValueForIndexUnlocked(); try { if ((!hasReaders() || readers)) { // markObsolete will clear the value. if (!(marked = markObsolete0(ver, true))) { if (log.isDebugEnabled()) log.debug("Entry could not be marked obsolete (it is still used): " + this); break; } clearReaders(); } else { if (log.isDebugEnabled()) log.debug("Entry could not be marked obsolete (it still has readers): " + this); break; } } catch (GridCacheEntryRemovedException ignore) { if (log.isDebugEnabled()) log.debug("Got removed entry when clearing (will simply return): " + this); ret = true; break; } if (log.isDebugEnabled()) log.debug("Entry has been marked obsolete: " + this); clearIndex(val); releaseSwap(); ret = true; rmv = true; break; } } if (marked) onMarkedObsolete(); if (rmv) cctx.cache().removeEntry(this); // Clear cache. return ret; } /** {@inheritDoc} */ @Override public synchronized GridCacheVersion obsoleteVersion() { return obsoleteVersionExtras(); } /** {@inheritDoc} */ @Override public boolean markObsolete(GridCacheVersion ver) { boolean obsolete; synchronized (this) { obsolete = markObsolete0(ver, true); } if (obsolete) onMarkedObsolete(); return obsolete; } /** {@inheritDoc} */ @Override public boolean markObsoleteIfEmpty(@Nullable GridCacheVersion ver) throws GridException { boolean obsolete = false; boolean deferred = false; try { synchronized (this) { if (obsoleteVersionExtras() != null) return false; if (!hasValueUnlocked() || checkExpired()) { if (ver == null) ver = nextVersion(); if (cctx.deferredDelete() && !isStartVersion() && !detached() && !isInternal()) { if (!deletedUnlocked()) { update(null, null, 0L, 0L, ver); deletedUnlocked(true); deferred = true; } } else obsolete = markObsolete0(ver, true); } } } finally { if (obsolete) onMarkedObsolete(); if (deferred) cctx.onDeferredDelete(this, ver); } return obsolete; } /** {@inheritDoc} */ @Override public boolean markObsoleteVersion(GridCacheVersion ver) { assert cctx.deferredDelete(); boolean marked; synchronized (this) { if (obsoleteVersionExtras() != null) return true; if (!this.ver.equals(ver)) return false; marked = markObsolete0(ver, true); } if (marked) onMarkedObsolete(); return marked; } /** * <p> * Note that {@link #onMarkedObsolete()} should always be called after this method * returns {@code true}. * * @param ver Version. * @param clear {@code True} to clear. * @return {@code True} if entry is obsolete, {@code false} if entry is still used by other threads or nodes. */ protected final boolean markObsolete0(GridCacheVersion ver, boolean clear) { assert Thread.holdsLock(this); GridCacheVersion obsoleteVer = obsoleteVersionExtras(); if (ver != null) { // If already obsolete, then do nothing. if (obsoleteVer != null) return true; GridCacheMvcc<K> mvcc = mvccExtras(); if (mvcc == null || mvcc.isEmpty(ver)) { obsoleteVer = ver; obsoleteVersionExtras(obsoleteVer); if (clear) value(null, null); } return obsoleteVer != null; } else return obsoleteVer != null; } /** {@inheritDoc} */ @Override public void onMarkedObsolete() { // No-op. } /** {@inheritDoc} */ @Override public final synchronized boolean obsolete() { return obsoleteVersionExtras() != null; } /** {@inheritDoc} */ @Override public final synchronized boolean obsolete(GridCacheVersion exclude) { GridCacheVersion obsoleteVer = obsoleteVersionExtras(); return obsoleteVer != null && !obsoleteVer.equals(exclude); } /** {@inheritDoc} */ @Override public synchronized boolean invalidate(@Nullable GridCacheVersion curVer, GridCacheVersion newVer) throws GridException { assert newVer != null; if (curVer == null || ver.equals(curVer)) { V val = saveValueForIndexUnlocked(); value(null, null); ver = newVer; releaseSwap(); clearIndex(val); onInvalidate(); } return obsoleteVersionExtras() != null; } /** * Called when entry invalidated. */ protected void onInvalidate() { // No-op. } /** {@inheritDoc} */ @Override public boolean invalidate(@Nullable GridPredicate<GridCacheEntry<K, V>>[] filter) throws GridCacheEntryRemovedException, GridException { if (F.isEmptyOrNulls(filter)) { synchronized (this) { checkObsolete(); invalidate(null, nextVersion()); return true; } } else { // For optimistic checking. GridCacheVersion startVer; synchronized (this){ checkObsolete(); startVer = ver; } if (!cctx.isAll(this, filter)) return false; synchronized (this) { checkObsolete(); if (startVer.equals(ver)) { invalidate(null, nextVersion()); return true; } } // If version has changed then repeat the process. return invalidate(filter); } } /** {@inheritDoc} */ @Override public boolean compact(@Nullable GridPredicate<GridCacheEntry<K, V>>[] filter) throws GridCacheEntryRemovedException, GridException { // For optimistic checking. GridCacheVersion startVer; synchronized (this) { checkObsolete(); startVer = ver; } if (!cctx.isAll(this, filter)) return false; synchronized (this) { checkObsolete(); if (deletedUnlocked()) return false; // Cannot compact soft-deleted entries. if (startVer.equals(ver)) { if (hasValueUnlocked() && !checkExpired()) { if (!isOffHeapValuesOnly()) { if (val != null) valBytes = null; } return false; } else return clear(nextVersion(), false, filter); } } // If version has changed do it again. return compact(filter); } /** * * @param val New value. * @param valBytes New value bytes. * @param expireTime Expiration time. * @param ttl Time to live. * @param ver Update version. */ protected final void update(@Nullable V val, @Nullable byte[] valBytes, long expireTime, long ttl, GridCacheVersion ver) { assert ver != null; assert Thread.holdsLock(this); long oldExpireTime = expireTimeExtras(); if (oldExpireTime != 0 && expireTime != oldExpireTime && cctx.config().isEagerTtl()) cctx.ttl().removeTrackedEntry(this); value(val, valBytes); ttlAndExpireTimeExtras(ttl, expireTime); if (expireTime != 0 && expireTime != oldExpireTime && cctx.config().isEagerTtl()) cctx.ttl().addTrackedEntry(this); this.ver = ver; } /** * @return {@code true} If value bytes should be stored. */ protected boolean isStoreValueBytes() { return cctx.config().isStoreValueBytes(); } /** * @return {@code True} if values should be stored off-heap. */ protected boolean isOffHeapValuesOnly() { return cctx.config().getMemoryMode() == GridCacheMemoryMode.OFFHEAP_VALUES; } /** * @param ttl Time to live. * @return Expiration time. */ protected long toExpireTime(long ttl) { long expireTime = ttl == 0 ? 0 : U.currentTimeMillis() + ttl; // Account for overflow. if (expireTime < 0) expireTime = 0; return expireTime; } /** * @throws GridCacheEntryRemovedException If entry is obsolete. */ protected void checkObsolete() throws GridCacheEntryRemovedException { assert Thread.holdsLock(this); if (obsoleteVersionExtras() != null) throw new GridCacheEntryRemovedException(); } /** {@inheritDoc} */ @Override public K key() { return key; } /** {@inheritDoc} */ @Override public synchronized GridCacheVersion version() throws GridCacheEntryRemovedException { checkObsolete(); return ver; } /** * Gets hash value for the entry key. * * @return Hash value. */ int hash() { return hash; } /** * Gets next entry in bucket linked list within a hash map segment. * * @param segId Segment ID. * @return Next entry. */ GridCacheMapEntry<K, V> next(int segId) { return segId % 2 == 0 ? next0 : next1; } /** * Sets next entry in bucket linked list within a hash map segment. * * @param segId Segment ID. * @param next Next entry. */ void next(int segId, @Nullable GridCacheMapEntry<K, V> next) { if (segId % 2 == 0) next0 = next; else next1 = next; } /** {@inheritDoc} */ @Nullable @Override public V peek(GridCachePeekMode mode, GridPredicate<GridCacheEntry<K, V>>[] filter) throws GridCacheEntryRemovedException { try { GridTuple<V> peek = peek0(false, mode, filter, cctx.tm().localTxx()); return peek != null ? peek.get() : null; } catch (GridCacheFilterFailedException ignore) { assert false; return null; } catch (GridException e) { throw new GridRuntimeException("Unable to perform entry peek() operation.", e); } } /** {@inheritDoc} */ @Override public V peek(Collection<GridCachePeekMode> modes, GridPredicate<GridCacheEntry<K, V>>[] filter) throws GridCacheEntryRemovedException { assert modes != null; for (GridCachePeekMode mode : modes) { try { GridTuple<V> val = peek0(false, mode, filter, cctx.tm().localTxx()); if (val != null) return val.get(); } catch (GridCacheFilterFailedException ignored) { assert false; return null; } catch (GridException e) { throw new GridRuntimeException("Unable to perform entry peek() operation.", e); } } return null; } /** {@inheritDoc} */ @Nullable @Override public V peekFailFast(GridCachePeekMode mode, GridPredicate<GridCacheEntry<K, V>>[] filter) throws GridCacheEntryRemovedException, GridCacheFilterFailedException { try { GridTuple<V> peek = peek0(true, mode, filter, cctx.tm().localTxx()); return peek != null ? peek.get() : null; } catch (GridException e) { throw new GridRuntimeException("Unable to perform entry peek() operation.", e); } } /** * @param failFast Fail-fast flag. * @param mode Peek mode. * @param filter Filter. * @param tx Transaction to peek value at (if mode is TX value). * @return Peeked value. * @throws GridException In case of error. * @throws GridCacheEntryRemovedException If removed. * @throws GridCacheFilterFailedException If filter failed. */ @SuppressWarnings({"RedundantTypeArguments"}) @Nullable @Override public GridTuple<V> peek0(boolean failFast, GridCachePeekMode mode, GridPredicate<GridCacheEntry<K, V>>[] filter, @Nullable GridCacheTxEx<K, V> tx) throws GridCacheEntryRemovedException, GridCacheFilterFailedException, GridException { assert tx == null || tx.local(); long topVer = tx != null ? tx.topologyVersion() : cctx.affinity().affinityTopologyVersion(); switch (mode) { case TX: return peekTx(failFast, filter, tx); case GLOBAL: return peekGlobal(failFast, topVer, filter); case NEAR_ONLY: return peekGlobal(failFast, topVer, filter); case PARTITIONED_ONLY: return peekGlobal(failFast, topVer, filter); case SMART: /* * If there is no ongoing transaction, or transaction is NOT in ACTIVE state, * which means that it is either rolling back, preparing to commit, or committing, * then we only check the global cache storage because value has already been * validated against filter and enlisted into transaction and, therefore, second * validation against the same enlisted value will be invalid (it will always be false). * * However, in ACTIVE state, we must also validate against other values that * may have enlisted into the same transaction and that's why we pass 'true' * to 'e.peek(true)' method in this case. */ return tx == null || tx.state() != ACTIVE ? peekGlobal(failFast, topVer, filter) : peekTxThenGlobal(failFast, filter, tx); case SWAP: return peekSwap(failFast, filter); case DB: return F.t(peekDb(failFast, filter)); default: // Should never be reached. assert false; return null; } } /** {@inheritDoc} */ @Override public V poke(V val) throws GridCacheEntryRemovedException, GridException { assert val != null; V old; synchronized (this) { checkObsolete(); if (isNew() || !valid(-1)) unswap(true, true); if (deletedUnlocked()) return null; old = rawGetOrUnmarshalUnlocked(false); GridCacheVersion nextVer = nextVersion(); // Update index inside synchronization since it can be updated // in load methods without actually holding entry lock. long expireTime = expireTimeExtras(); if (cctx.portableEnabled()) val = (V)cctx.kernalContext().portable().detachPortable(val); updateIndex(val, null, expireTime, nextVer, old); update(val, null, expireTime, ttlExtras(), nextVer); } if (log.isDebugEnabled()) log.debug("Poked cache entry [newVal=" + val + ", oldVal=" + old + ", entry=" + this + ']'); return old; } /** * Checks that entries in group locks transactions are not locked during commit. * * @param tx Transaction to check. * @throws GridCacheEntryRemovedException If entry is obsolete. * @throws GridException If entry was externally locked. */ private void groupLockSanityCheck(GridCacheTxEx<K, V> tx) throws GridCacheEntryRemovedException, GridException { assert tx.groupLock(); GridCacheTxEntry<K, V> txEntry = tx.entry(key); if (txEntry.groupLockEntry()) { if (lockedByAny()) throw new GridException("Failed to update cache entry (entry was externally locked while " + "accessing entry within group lock transaction) [entry=" + this + ", tx=" + tx + ']'); } } /** * @param failFast Fail fast flag. * @param filter Filter. * @param tx Transaction to peek value at (if mode is TX value). * @return Peeked value. * @throws GridCacheFilterFailedException If filter failed. * @throws GridCacheEntryRemovedException If entry got removed. * @throws GridException If unexpected cache failure occurred. */ @Nullable private GridTuple<V> peekTxThenGlobal(boolean failFast, GridPredicate<GridCacheEntry<K, V>>[] filter, GridCacheTxEx<K, V> tx) throws GridCacheFilterFailedException, GridCacheEntryRemovedException, GridException { GridTuple<V> peek = peekTx(failFast, filter, tx); // If transaction has value (possibly null, which means value is to be deleted). if (peek != null) return peek; long topVer = tx == null ? cctx.affinity().affinityTopologyVersion() : tx.topologyVersion(); return peekGlobal(failFast, topVer, filter); } /** * @param failFast Fail fast flag. * @param filter Filter. * @param tx Transaction to peek value at (if mode is TX value). * @return Peeked value. * @throws GridCacheFilterFailedException If filter failed. */ @Nullable private GridTuple<V> peekTx(boolean failFast, GridPredicate<GridCacheEntry<K, V>>[] filter, @Nullable GridCacheTxEx<K, V> tx) throws GridCacheFilterFailedException { return tx == null ? null : tx.peek(failFast, key, filter); } /** * @param failFast Fail fast flag. * @param topVer Topology version. * @param filter Filter. * @return Peeked value. * @throws GridCacheFilterFailedException If filter failed. * @throws GridCacheEntryRemovedException If entry got removed. * @throws GridException If unexpected cache failure occurred. */ @SuppressWarnings({"RedundantTypeArguments"}) @Nullable private GridTuple<V> peekGlobal(boolean failFast, long topVer, GridPredicate<GridCacheEntry<K, V>>[] filter) throws GridCacheEntryRemovedException, GridCacheFilterFailedException, GridException { if (!valid(topVer)) return null; boolean rmv = false; try { while (true) { GridCacheVersion ver; V val; synchronized (this) { if (checkExpired()) { rmv = markObsolete0(cctx.versions().next(this.ver), true); return null; } checkObsolete(); ver = this.ver; val = rawGetOrUnmarshalUnlocked(false); } if (!cctx.isAll(wrap(false), filter)) return F.t(CU.<V>failed(failFast)); if (F.isEmptyOrNulls(filter) || ver.equals(version())) return F.t(val); } } finally { if (rmv) { onMarkedObsolete(); cctx.cache().map().removeEntry(this); } } } /** * @param failFast Fail fast flag. * @param filter Filter. * @return Value from swap storage. * @throws GridException In case of any errors. * @throws GridCacheFilterFailedException If filter failed. */ @SuppressWarnings({"unchecked"}) @Nullable private GridTuple<V> peekSwap(boolean failFast, GridPredicate<GridCacheEntry<K, V>>[] filter) throws GridException, GridCacheFilterFailedException { if (!cctx.isAll(wrap(false), filter)) return F.t((V)CU.failed(failFast)); synchronized (this) { if (checkExpired()) return null; } GridCacheSwapEntry<V> e = cctx.swap().read(this, false); return e != null ? F.t(e.value()) : null; } /** * @param failFast Fail fast flag. * @param filter Filter. * @return Value from persistent store. * @throws GridException In case of any errors. * @throws GridCacheFilterFailedException If filter failed. */ @SuppressWarnings({"unchecked"}) @Nullable private V peekDb(boolean failFast, GridPredicate<GridCacheEntry<K, V>>[] filter) throws GridException, GridCacheFilterFailedException { if (!cctx.isAll(wrap(false), filter)) return CU.failed(failFast); synchronized (this) { if (checkExpired()) return null; } return cctx.store().loadFromStore(cctx.tm().localTxx(), key); } /** * TODO: GG-4009: do we need to generate event and invalidate value? * * @return {@code true} if expired. * @throws GridException In case of failure. */ private boolean checkExpired() throws GridException { assert Thread.holdsLock(this); long expireTime = expireTimeExtras(); if (expireTime > 0) { long delta = expireTime - U.currentTimeMillis(); if (log.isDebugEnabled()) log.debug("Checked expiration time for entry [timeLeft=" + delta + ", entry=" + this + ']'); if (delta <= 0) { releaseSwap(); clearIndex(saveValueForIndexUnlocked()); return true; } } return false; } /** * @return Value. */ @Override public synchronized V rawGet() { return val; } /** {@inheritDoc} */ @Nullable @Override public synchronized V rawGetOrUnmarshal(boolean tmp) throws GridException { return rawGetOrUnmarshalUnlocked(tmp); } /** * @param tmp If {@code true} can return temporary instance. * @return Value (unmarshalled if needed). * @throws GridException If failed. */ @Nullable public V rawGetOrUnmarshalUnlocked(boolean tmp) throws GridException { assert Thread.holdsLock(this); V val = this.val; if (val != null) return val; GridCacheValueBytes valBytes = valueBytesUnlocked(); if (!valBytes.isNull()) val = valBytes.isPlain() ? (V)valBytes.get() : cctx.marshaller().<V>unmarshal(valBytes.get(), cctx.deploy().globalLoader()); if (val == null && cctx.offheapTiered() && valPtr != 0) val = unmarshalOffheap(tmp); return val; } /** {@inheritDoc} */ @Override public synchronized boolean hasValue() { return hasValueUnlocked(); } /** * @return {@code True} if this entry has value. */ protected boolean hasValueUnlocked() { assert Thread.holdsLock(this); return val != null || valBytes != null || valPtr != 0; } /** {@inheritDoc} */ /* @Override public synchronized GridDrEntry<K, V> drEntry() throws GridException { return new GridDrPlainEntry<>(key, isStartVersion() ? unswap(true, true) : rawGetOrUnmarshalUnlocked(false), ttlExtras(), expireTimeExtras(), ver.drVersion()); } */ /** {@inheritDoc} */ @Override public synchronized V rawPut(V val, long ttl) { V old = this.val; update(val, null, toExpireTime(ttl), ttl, nextVersion()); return old; } /** {@inheritDoc} */ @SuppressWarnings({"RedundantTypeArguments"}) @Override public boolean initialValue(V val, byte[] valBytes, GridCacheVersion ver, long ttl, long expireTime, boolean preload, long topVer, GridDrType drType) throws GridException, GridCacheEntryRemovedException { if (cctx.isUnmarshalValues() && valBytes != null && val == null && isNewLocked()) val = cctx.marshaller().<V>unmarshal(valBytes, cctx.deploy().globalLoader()); synchronized (this) { checkObsolete(); if (isNew() || (!preload && deletedUnlocked())) { long expTime = expireTime < 0 ? toExpireTime(ttl) : expireTime; if (cctx.portableEnabled()) val = (V)cctx.kernalContext().portable().detachPortable(val); if (val != null || valBytes != null) updateIndex(val, valBytes, expTime, ver, null); // Version does not change for load ops. update(val, valBytes, expTime, ttl, ver); boolean skipQryNtf = false; if (val == null && valBytes == null) { skipQryNtf = true; if (cctx.deferredDelete() && !isInternal()) { assert !deletedUnlocked(); deletedUnlocked(true); } } else if (deletedUnlocked()) deletedUnlocked(false); drReplicate(drType, val, valBytes, ver); if (!skipQryNtf) { if (cctx.affinity().primary(cctx.localNode(), key, topVer) || cctx.isReplicated()) cctx.continuousQueries().onEntryUpdate(this, key, val, valueBytesUnlocked(), null, null); cctx.dataStructures().onEntryUpdated(key, false); } return true; } return false; } } /** {@inheritDoc} */ @Override public synchronized boolean initialValue(K key, GridCacheSwapEntry <V> unswapped) throws GridException, GridCacheEntryRemovedException { checkObsolete(); if (isNew()) { V val = unswapped.value(); if (cctx.portableEnabled()) { val = (V)cctx.kernalContext().portable().detachPortable(val); if (cctx.offheapTiered() && !unswapped.valueIsByteArray()) unswapped.valueBytes(cctx.convertPortableBytes(unswapped.valueBytes())); } // Version does not change for load ops. update(val, unswapped.valueBytes(), unswapped.expireTime(), unswapped.ttl(), unswapped.version() ); return true; } return false; } /** {@inheritDoc} */ @Override public synchronized boolean versionedValue(V val, GridCacheVersion curVer, GridCacheVersion newVer) throws GridException, GridCacheEntryRemovedException { checkObsolete(); if (curVer == null || curVer.equals(ver)) { if (val != this.val) { if (newVer == null) newVer = nextVersion(); V old = rawGetOrUnmarshalUnlocked(false); long ttl = ttlExtras(); long expTime = toExpireTime(ttl); // Detach value before index update. if (cctx.portableEnabled()) val = (V)cctx.kernalContext().portable().detachPortable(val); if (val != null) { updateIndex(val, null, expTime, newVer, old); if (deletedUnlocked()) deletedUnlocked(false); } // Version does not change for load ops. update(val, null, expTime, ttl, newVer); } return true; } return false; } /** * Gets next version for this cache entry. * * @return Next version. */ private GridCacheVersion nextVersion() { // Do not change topology version when generating next version. return cctx.versions().next(ver); } /** {@inheritDoc} */ @Override public synchronized boolean hasLockCandidate(GridCacheVersion ver) throws GridCacheEntryRemovedException { checkObsolete(); GridCacheMvcc<K> mvcc = mvccExtras(); return mvcc != null && mvcc.hasCandidate(ver); } /** {@inheritDoc} */ @Override public synchronized boolean hasLockCandidate(long threadId) throws GridCacheEntryRemovedException { checkObsolete(); GridCacheMvcc<K> mvcc = mvccExtras(); return mvcc != null && mvcc.localCandidate(threadId) != null; } /** {@inheritDoc} */ @Override public synchronized boolean lockedByAny(GridCacheVersion... exclude) throws GridCacheEntryRemovedException { checkObsolete(); GridCacheMvcc<K> mvcc = mvccExtras(); return mvcc != null && !mvcc.isEmpty(exclude); } /** {@inheritDoc} */ @Override public boolean lockedByThread() throws GridCacheEntryRemovedException { return lockedByThread(Thread.currentThread().getId()); } /** {@inheritDoc} */ @Override public synchronized boolean lockedLocally(GridCacheVersion lockVer) throws GridCacheEntryRemovedException { checkObsolete(); GridCacheMvcc<K> mvcc = mvccExtras(); return mvcc != null && mvcc.isLocallyOwned(lockVer); } /** {@inheritDoc} */ @Override public synchronized boolean lockedByThread(long threadId, GridCacheVersion exclude) throws GridCacheEntryRemovedException { checkObsolete(); GridCacheMvcc<K> mvcc = mvccExtras(); return mvcc != null && mvcc.isLocallyOwnedByThread(threadId, false, exclude); } /** {@inheritDoc} */ @Override public synchronized boolean lockedLocallyByIdOrThread(GridCacheVersion lockVer, long threadId) throws GridCacheEntryRemovedException { GridCacheMvcc<K> mvcc = mvccExtras(); return mvcc != null && mvcc.isLocallyOwnedByIdOrThread(lockVer, threadId); } /** {@inheritDoc} */ @Override public synchronized boolean lockedByThread(long threadId) throws GridCacheEntryRemovedException { checkObsolete(); GridCacheMvcc<K> mvcc = mvccExtras(); return mvcc != null && mvcc.isLocallyOwnedByThread(threadId, true); } /** {@inheritDoc} */ @Override public synchronized boolean lockedBy(GridCacheVersion ver) throws GridCacheEntryRemovedException { checkObsolete(); GridCacheMvcc<K> mvcc = mvccExtras(); return mvcc != null && mvcc.isOwnedBy(ver); } /** {@inheritDoc} */ @Override public synchronized boolean lockedByThreadUnsafe(long threadId) { GridCacheMvcc<K> mvcc = mvccExtras(); return mvcc != null && mvcc.isLocallyOwnedByThread(threadId, true); } /** {@inheritDoc} */ @Override public synchronized boolean lockedByUnsafe(GridCacheVersion ver) { GridCacheMvcc<K> mvcc = mvccExtras(); return mvcc != null && mvcc.isOwnedBy(ver); } /** {@inheritDoc} */ @Override public synchronized boolean lockedLocallyUnsafe(GridCacheVersion lockVer) { GridCacheMvcc<K> mvcc = mvccExtras(); return mvcc != null && mvcc.isLocallyOwned(lockVer); } /** {@inheritDoc} */ @Override public synchronized boolean hasLockCandidateUnsafe(GridCacheVersion ver) { GridCacheMvcc<K> mvcc = mvccExtras(); return mvcc != null && mvcc.hasCandidate(ver); } /** {@inheritDoc} */ @Override public synchronized Collection<GridCacheMvccCandidate<K>> localCandidates(GridCacheVersion... exclude) throws GridCacheEntryRemovedException { checkObsolete(); GridCacheMvcc<K> mvcc = mvccExtras(); return mvcc == null ? Collections.<GridCacheMvccCandidate<K>>emptyList() : mvcc.localCandidates(exclude); } /** {@inheritDoc} */ @Override public Collection<GridCacheMvccCandidate<K>> remoteMvccSnapshot(GridCacheVersion... exclude) { return Collections.emptyList(); } /** {@inheritDoc} */ @Nullable @Override public synchronized GridCacheMvccCandidate<K> candidate(GridCacheVersion ver) throws GridCacheEntryRemovedException { checkObsolete(); GridCacheMvcc<K> mvcc = mvccExtras(); return mvcc == null ? null : mvcc.candidate(ver); } /** {@inheritDoc} */ @Override public synchronized GridCacheMvccCandidate<K> localCandidate(long threadId) throws GridCacheEntryRemovedException { checkObsolete(); GridCacheMvcc<K> mvcc = mvccExtras(); return mvcc == null ? null : mvcc.localCandidate(threadId); } /** {@inheritDoc} */ @Override public GridCacheMvccCandidate<K> candidate(UUID nodeId, long threadId) throws GridCacheEntryRemovedException { boolean loc = cctx.nodeId().equals(nodeId); synchronized (this) { checkObsolete(); GridCacheMvcc<K> mvcc = mvccExtras(); return mvcc == null ? null : loc ? mvcc.localCandidate(threadId) : mvcc.remoteCandidate(nodeId, threadId); } } /** {@inheritDoc} */ @Override public synchronized GridCacheMvccCandidate<K> localOwner() throws GridCacheEntryRemovedException { checkObsolete(); GridCacheMvcc<K> mvcc = mvccExtras(); return mvcc == null ? null : mvcc.localOwner(); } /** {@inheritDoc} */ @Override public synchronized long rawExpireTime() { return expireTimeExtras(); } /** {@inheritDoc} */ @SuppressWarnings({"IfMayBeConditional"}) @Override public long expireTime() throws GridCacheEntryRemovedException { GridCacheTxLocalAdapter<K, V> tx; if (cctx.isDht()) tx = cctx.dht().near().context().tm().localTx(); else tx = cctx.tm().localTx(); if (tx != null) { long time = tx.entryExpireTime(key); if (time > 0) return time; } synchronized (this) { checkObsolete(); return expireTimeExtras(); } } /** {@inheritDoc} */ @Override public long expireTimeUnlocked() { assert Thread.holdsLock(this); return expireTimeExtras(); } /** {@inheritDoc} */ @Override public boolean onTtlExpired(GridCacheVersion obsoleteVer) { boolean obsolete = false; boolean deferred = false; try { synchronized (this) { V expiredVal = val; boolean hasOldBytes = valBytes != null || valPtr != 0; boolean expired = checkExpired(); if (expired) { if (cctx.deferredDelete() && !detached() && !isInternal()) { if (!deletedUnlocked()) { update(null, null, 0L, 0L, ver); deletedUnlocked(true); deferred = true; } } else { if (markObsolete0(obsoleteVer, true)) obsolete = true; // Success, will return "true". } if (cctx.events().isRecordable(EVT_CACHE_OBJECT_EXPIRED)) cctx.events().addEvent(partition(), key, cctx.localNodeId(), null, EVT_CACHE_OBJECT_EXPIRED, null, false, expiredVal, expiredVal != null || hasOldBytes, null, null, null); } } } catch (GridException e) { U.error(log, "Failed to clean up expired cache entry: " + this, e); } finally { if (obsolete) onMarkedObsolete(); if (deferred) cctx.onDeferredDelete(this, obsoleteVer); } return obsolete; } /** {@inheritDoc} */ @Override public synchronized long rawTtl() { return ttlExtras(); } /** {@inheritDoc} */ @SuppressWarnings({"IfMayBeConditional"}) @Override public long ttl() throws GridCacheEntryRemovedException { GridCacheTxLocalAdapter<K, V> tx; if (cctx.isDht()) tx = cctx.dht().near().context().tm().localTx(); else tx = cctx.tm().localTx(); if (tx != null) { long entryTtl = tx.entryTtl(key); if (entryTtl > 0) return entryTtl; } synchronized (this) { checkObsolete(); return ttlExtras(); } } /** {@inheritDoc} */ @Override public synchronized void keyBytes(byte[] keyBytes) throws GridCacheEntryRemovedException { checkObsolete(); if (keyBytes != null) this.keyBytes = keyBytes; } /** {@inheritDoc} */ @Override public synchronized byte[] keyBytes() { return keyBytes; } /** {@inheritDoc} */ @Override public byte[] getOrMarshalKeyBytes() throws GridException { byte[] bytes = keyBytes(); if (bytes != null) return bytes; bytes = CU.marshal(cctx, key); synchronized (this) { keyBytes = bytes; } return bytes; } /** {@inheritDoc} */ @Override public synchronized GridCacheValueBytes valueBytes() throws GridCacheEntryRemovedException { checkObsolete(); return valueBytesUnlocked(); } /** {@inheritDoc} */ @Nullable @Override public GridCacheValueBytes valueBytes(@Nullable GridCacheVersion ver) throws GridException, GridCacheEntryRemovedException { V val = null; GridCacheValueBytes valBytes = GridCacheValueBytes.nil(); synchronized (this) { checkObsolete(); if (ver == null || this.ver.equals(ver)) { val = this.val; ver = this.ver; valBytes = valueBytesUnlocked(); if (valBytes.isNull() && cctx.offheapTiered() && valPtr != 0) valBytes = offheapValueBytes(); } else ver = null; } if (valBytes.isNull()) { if (val != null) valBytes = (val instanceof byte[]) ? GridCacheValueBytes.plain(val) : GridCacheValueBytes.marshaled(CU.marshal(cctx, val)); if (ver != null && !isOffHeapValuesOnly()) { synchronized (this) { checkObsolete(); if (this.val == val) this.valBytes = isStoreValueBytes() ? valBytes.getIfMarshaled() : null; } } } return valBytes; } /** * Updates cache index. * * @param val Value. * @param valBytes Value bytes. * @param expireTime Expire time. * @param ver New entry version. * @param prevVal Previous value. * @throws GridException If update failed. */ protected void updateIndex(@Nullable V val, @Nullable byte[] valBytes, long expireTime, GridCacheVersion ver, @Nullable V prevVal) throws GridException { assert Thread.holdsLock(this); assert val != null || valBytes != null : "null values in update index for key: " + key; try { GridCacheQueryManager<K, V> qryMgr = cctx.queries(); if (qryMgr != null) qryMgr.store(key, keyBytes, val, valBytes, ver, expireTime); } catch (GridException e) { throw new GridCacheIndexUpdateException(e); } } /** * Clears index. * * @param prevVal Previous value (if needed for index update). * @throws GridException If failed. */ protected void clearIndex(@Nullable V prevVal) throws GridException { assert Thread.holdsLock(this); try { GridCacheQueryManager<K, V> qryMgr = cctx.queries(); if (qryMgr != null) qryMgr.remove(key(), keyBytes()); } catch (GridException e) { throw new GridCacheIndexUpdateException(e); } } /** * This method will return current value only if clearIndex(V) will require previous value (this is the case * for Mongo caches). If previous value is not required, this method will return {@code null}. * * @return Previous value or {@code null}. * @throws GridException If failed to retrieve previous value. */ protected V saveValueForIndexUnlocked() throws GridException { assert Thread.holdsLock(this); if (!cctx.cache().isMongoDataCache() && !cctx.cache().isMongoMetaCache()) return null; return rawGetOrUnmarshalUnlocked(false); } /** * Wraps this map entry into cache entry. * * @param prjAware {@code true} if entry should inherit projection properties. * @return Wrapped entry. */ @Override public GridCacheEntry<K, V> wrap(boolean prjAware) { GridCacheProjectionImpl<K, V> prjPerCall = null; if (prjAware) prjPerCall = cctx.projectionPerCall(); return new GridCacheEntryImpl<>(prjPerCall, cctx, key, this); } /** {@inheritDoc} */ @Override public GridCacheEntry<K, V> wrapFilterLocked() throws GridException { return null; } /** {@inheritDoc} */ @Override public GridCacheEntry<K, V> evictWrap() { return new GridCacheEvictionEntry<>(this); } /** {@inheritDoc} */ @Override public boolean evictInternal(boolean swap, GridCacheVersion obsoleteVer, @Nullable GridPredicate<GridCacheEntry<K, V>>[] filter) throws GridException { boolean marked = false; try { if (F.isEmptyOrNulls(filter)) { synchronized (this) { V prev = saveValueForIndexUnlocked(); if (!hasReaders() && markObsolete0(obsoleteVer, false)) { if (swap) { if (!isStartVersion()) { try { // Write to swap. swap(); } catch (GridException e) { U.error(log, "Failed to write entry to swap storage: " + this, e); } } } else clearIndex(prev); // Nullify value after swap. value(null, null); marked = true; return true; } } } else { // For optimistic check. while (true) { GridCacheVersion v; synchronized (this) { v = ver; } if (!cctx.isAll(this, filter)) return false; synchronized (this) { if (!v.equals(ver)) // Version has changed since entry passed the filter. Do it again. continue; V prevVal = saveValueForIndexUnlocked(); if (!hasReaders() && markObsolete0(obsoleteVer, false)) { if (swap) { if (!isStartVersion()) { try { // Write to swap. swap(); } catch (GridException e) { U.error(log, "Failed to write entry to swap storage: " + this, e); } } } else clearIndex(prevVal); // Nullify value after swap. value(null, null); marked = true; return true; } else return false; } } } } catch (GridCacheEntryRemovedException ignore) { if (log.isDebugEnabled()) log.debug("Got removed entry when evicting (will simply return): " + this); return true; } finally { if (marked) onMarkedObsolete(); } return false; } /** {@inheritDoc} */ @Override public GridCacheBatchSwapEntry<K, V> evictInBatchInternal(GridCacheVersion obsoleteVer) throws GridException { assert Thread.holdsLock(this); assert cctx.isSwapOrOffheapEnabled(); GridCacheBatchSwapEntry<K, V> ret = null; try { if (!hasReaders() && markObsolete0(obsoleteVer, false)) { if (!isStartVersion()) { boolean plain = val instanceof byte[]; GridUuid valClsLdrId = null; if (val != null) valClsLdrId = cctx.deploy().getClassLoaderId(U.detectObjectClassLoader(val)); ret = new GridCacheBatchSwapEntry<>(key(), getOrMarshalKeyBytes(), partition(), plain ? ByteBuffer.wrap((byte[])val) : swapValueBytes(), plain, ver, ttlExtras(), expireTimeExtras(), cctx.deploy().getClassLoaderId(U.detectObjectClassLoader(key)), valClsLdrId); } value(null, null); } } catch (GridCacheEntryRemovedException ignored) { if (log.isDebugEnabled()) log.debug("Got removed entry when evicting (will simply return): " + this); } return ret; } /** * Create value bytes wrapper from the given object. * * @return Value bytes wrapper. * @throws GridException If failed. */ private ByteBuffer swapValueBytes() throws GridException { assert val != null || valBytes != null || valPtr != 0; if (cctx.offheapTiered() && cctx.portableEnabled()) { if (val != null) return cctx.portable().marshal(val, false); V val0 = cctx.marshaller().unmarshal(valBytes, U.gridClassLoader()); return cctx.portable().marshal(val0, false); } else { GridCacheValueBytes res = valueBytesUnlocked(); if (res.isNull()) res = GridCacheValueBytes.marshaled(CU.marshal(cctx, val)); assert res.get() != null; return ByteBuffer.wrap(res.get()); } } /** * @param filter Entry filter. * @return {@code True} if entry is visitable. */ public boolean visitable(GridPredicate<GridCacheEntry<K, V>>[] filter) { try { if (obsoleteOrDeleted() || (filter != CU.<K, V>empty() && !cctx.isAll(wrap(false), filter))) return false; } catch (GridException e) { U.error(log, "An exception was thrown while filter checking.", e); RuntimeException ex = e.getCause(RuntimeException.class); if (ex != null) throw ex; Error err = e.getCause(Error.class); if (err != null) throw err; return false; } GridCacheTxEx<K, V> tx = cctx.tm().localTxx(); return tx == null || !tx.removed(key); } /** * Ensures that internal data storage is created. * * @param size Amount of data to ensure. * @return {@code true} if data storage was created. */ private boolean ensureData(int size) { if (attributeDataExtras() == null) { attributeDataExtras(new GridLeanMap<String, Object>(size)); return true; } else return false; } /** {@inheritDoc} */ @Override public void copyMeta(GridMetadataAware from) { A.notNull(from, "from"); synchronized (this) { Map m = from.allMeta(); ensureData(m.size()); attributeDataExtras().putAll(from.allMeta()); } } /** {@inheritDoc} */ @Override public void copyMeta(Map<String, ?> attrData) { A.notNull(attrData, "data"); synchronized (this) { ensureData(attrData.size()); attributeDataExtras().putAll(attrData); } } /** {@inheritDoc} */ @SuppressWarnings({"unchecked"}) @Nullable @Override public <V1> V1 addMeta(String name, V1 val) { A.notNull(name, "name", val, "val"); synchronized (this) { ensureData(1); return (V1)attributeDataExtras().put(name, val); } } /** {@inheritDoc} */ @SuppressWarnings({"unchecked"}) @Nullable @Override public <V1> V1 meta(String name) { A.notNull(name, "name"); synchronized (this) { GridLeanMap<String, Object> attrData = attributeDataExtras(); return attrData == null ? null : (V1)attrData.get(name); } } /** {@inheritDoc} */ @SuppressWarnings({"unchecked"}) @Nullable @Override public <V1> V1 removeMeta(String name) { A.notNull(name, "name"); synchronized (this) { GridLeanMap<String, Object> attrData = attributeDataExtras(); if (attrData == null) return null; V1 old = (V1)attrData.remove(name); if (attrData.isEmpty()) attributeDataExtras(null); return old; } } /** {@inheritDoc} */ @SuppressWarnings({"unchecked"}) @Override public <V1> boolean removeMeta(String name, V1 val) { A.notNull(name, "name", val, "val"); synchronized (this) { GridLeanMap<String, Object> attrData = attributeDataExtras(); if (attrData == null) return false; V1 old = (V1)attrData.get(name); if (old != null && old.equals(val)) { attrData.remove(name); if (attrData.isEmpty()) attributeDataExtras(null); return true; } return false; } } /** {@inheritDoc} */ @SuppressWarnings( {"unchecked", "RedundantCast"}) @Override public synchronized <V1> Map<String, V1> allMeta() { GridLeanMap<String, Object> attrData = attributeDataExtras(); if (attrData == null) return Collections.emptyMap(); if (attrData.size() <= 5) // This is a singleton unmodifiable map. return (Map<String, V1>)attrData; // Return a copy. return new HashMap<>((Map<String, V1>)attrData); } /** {@inheritDoc} */ @Override public boolean hasMeta(String name) { return meta(name) != null; } /** {@inheritDoc} */ @Override public <V1> boolean hasMeta(String name, V1 val) { A.notNull(name, "name"); Object v = meta(name); return v != null && v.equals(val); } /** {@inheritDoc} */ @SuppressWarnings({"unchecked"}) @Nullable @Override public <V1> V1 putMetaIfAbsent(String name, V1 val) { A.notNull(name, "name", val, "val"); synchronized (this) { V1 v = meta(name); if (v == null) return addMeta(name, val); return v; } } /** {@inheritDoc} */ @SuppressWarnings({"unchecked", "ClassReferencesSubclass"}) @Nullable @Override public <V1> V1 putMetaIfAbsent(String name, Callable<V1> c) { A.notNull(name, "name", c, "c"); synchronized (this) { V1 v = meta(name); if (v == null) try { return addMeta(name, c.call()); } catch (Exception e) { throw F.wrap(e); } return v; } } /** {@inheritDoc} */ @SuppressWarnings({"unchecked"}) @Override public <V1> V1 addMetaIfAbsent(String name, V1 val) { A.notNull(name, "name", val, "val"); synchronized (this) { V1 v = meta(name); if (v == null) addMeta(name, v = val); return v; } } /** {@inheritDoc} */ @SuppressWarnings({"unchecked"}) @Nullable @Override public <V1> V1 addMetaIfAbsent(String name, @Nullable Callable<V1> c) { A.notNull(name, "name", c, "c"); synchronized (this) { V1 v = meta(name); if (v == null && c != null) try { addMeta(name, v = c.call()); } catch (Exception e) { throw F.wrap(e); } return v; } } /** {@inheritDoc} */ @SuppressWarnings({"RedundantTypeArguments"}) @Override public <V1> boolean replaceMeta(String name, V1 curVal, V1 newVal) { A.notNull(name, "name", newVal, "newVal", curVal, "curVal"); synchronized (this) { if (hasMeta(name)) { V1 val = this.<V1>meta(name); if (val != null && val.equals(curVal)) { addMeta(name, newVal); return true; } } return false; } } /** * Convenience way for super-classes which implement {@link Externalizable} to * serialize metadata. Super-classes must call this method explicitly from * within {@link Externalizable#writeExternal(ObjectOutput)} methods implementation. * * @param out Output to write to. * @throws IOException If I/O error occurred. */ @SuppressWarnings({"TooBroadScope"}) protected void writeExternalMeta(ObjectOutput out) throws IOException { Map<String, Object> cp; // Avoid code warning (suppressing is bad here, because we need this warning for other places). synchronized (this) { cp = new GridLeanMap<>(attributeDataExtras()); } out.writeObject(cp); } /** * Convenience way for super-classes which implement {@link Externalizable} to * serialize metadata. Super-classes must call this method explicitly from * within {@link Externalizable#readExternal(ObjectInput)} methods implementation. * * @param in Input to read from. * @throws IOException If I/O error occurred. * @throws ClassNotFoundException If some class could not be found. */ @SuppressWarnings({"unchecked"}) protected void readExternalMeta(ObjectInput in) throws IOException, ClassNotFoundException { GridLeanMap<String, Object> cp = (GridLeanMap<String, Object>)in.readObject(); synchronized (this) { attributeDataExtras(cp); } } /** {@inheritDoc} */ @Override public boolean deleted() { if (!cctx.deferredDelete()) return false; synchronized (this) { return deletedUnlocked(); } } /** {@inheritDoc} */ @Override public synchronized boolean obsoleteOrDeleted() { return obsoleteVersionExtras() != null || (cctx.deferredDelete() && (deletedUnlocked() || !hasValueUnlocked())); } /** * @return {@code True} if deleted. */ @SuppressWarnings("SimplifiableIfStatement") protected boolean deletedUnlocked() { assert Thread.holdsLock(this); if (!cctx.deferredDelete()) return false; return (flags & IS_DELETED_MASK) != 0; } /** * @param deleted {@code True} if deleted. */ protected void deletedUnlocked(boolean deleted) { assert Thread.holdsLock(this); assert cctx.deferredDelete(); if (deleted) { assert !deletedUnlocked(); flags |= IS_DELETED_MASK; cctx.decrementPublicSize(this); } else { assert deletedUnlocked(); flags &= ~IS_DELETED_MASK; cctx.incrementPublicSize(this); } } /** * @return {@code True} if refreshing. */ protected boolean refreshingUnlocked() { assert Thread.holdsLock(this); return (flags & IS_REFRESHING_MASK) != 0; } /** * @param refreshing {@code True} if refreshing. */ protected void refreshingLocked(boolean refreshing) { assert Thread.holdsLock(this); if (refreshing) flags |= IS_REFRESHING_MASK; else flags &= ~IS_REFRESHING_MASK; } /** * @return Attribute data. */ @Nullable private GridLeanMap<String, Object> attributeDataExtras() { return extras != null ? extras.attributesData() : null; } /** * @param attrData Attribute data. */ private void attributeDataExtras(@Nullable GridLeanMap<String, Object> attrData) { extras = (extras != null) ? extras.attributesData(attrData) : attrData != null ? new GridCacheAttributesEntryExtras<K>(attrData) : null; } /** * @return MVCC. */ @Nullable protected GridCacheMvcc<K> mvccExtras() { return extras != null ? extras.mvcc() : null; } /** * @param mvcc MVCC. */ protected void mvccExtras(@Nullable GridCacheMvcc<K> mvcc) { extras = (extras != null) ? extras.mvcc(mvcc) : mvcc != null ? new GridCacheMvccEntryExtras<>(mvcc) : null; } /** * @return Obsolete version. */ @Nullable protected GridCacheVersion obsoleteVersionExtras() { return extras != null ? extras.obsoleteVersion() : null; } /** * @param obsoleteVer Obsolete version. */ protected void obsoleteVersionExtras(@Nullable GridCacheVersion obsoleteVer) { extras = (extras != null) ? extras.obsoleteVersion(obsoleteVer) : obsoleteVer != null ? new GridCacheObsoleteEntryExtras<K>(obsoleteVer) : null; } /** * @return TTL. */ public long ttlExtras() { return extras != null ? extras.ttl() : 0; } /** * @return Expire time. */ public long expireTimeExtras() { return extras != null ? extras.expireTime() : 0L; } /** * @param ttl TTL. * @param expireTime Expire time. */ protected void ttlAndExpireTimeExtras(long ttl, long expireTime) { extras = (extras != null) ? extras.ttlAndExpireTime(ttl, expireTime) : ttl != 0 ? new GridCacheTtlEntryExtras<K>(ttl, expireTime) : null; } /** * @return Size of extras object. */ private int extrasSize() { return extras != null ? extras.size() : 0; } /** * @return Value bytes read from offheap. * @throws GridException If failed. */ private GridCacheValueBytes offheapValueBytes() throws GridException { assert cctx.offheapTiered() && valPtr != 0; long ptr = valPtr; boolean plainByteArr = UNSAFE.getByte(ptr++) != 0; if (plainByteArr || !cctx.portableEnabled()) { int size = UNSAFE.getInt(ptr); byte[] bytes = U.copyMemory(ptr + 4, size); return plainByteArr ? GridCacheValueBytes.plain(bytes) : GridCacheValueBytes.marshaled(bytes); } assert cctx.portableEnabled(); return GridCacheValueBytes.marshaled(CU.marshal(cctx, cctx.portable().unmarshal(valPtr, true))); } /** * @param tmp If {@code true} can return temporary object. * @return Unmarshalled value. * @throws GridException If unmarshalling failed. */ private V unmarshalOffheap(boolean tmp) throws GridException { assert cctx.offheapTiered() && valPtr != 0; if (cctx.portableEnabled()) return (V)cctx.portable().unmarshal(valPtr, !tmp); long ptr = valPtr; boolean plainByteArr = UNSAFE.getByte(ptr++) != 0; int size = UNSAFE.getInt(ptr); byte[] res = U.copyMemory(ptr + 4, size); if (plainByteArr) return (V)res; GridUuid valClsLdrId = U.readGridUuid(ptr + 4 + size); ClassLoader ldr = valClsLdrId != null ? cctx.deploy().getClassLoader(valClsLdrId) : cctx.deploy().localLoader(); return cctx.marshaller().unmarshal(res, ldr); } /** {@inheritDoc} */ @Override public boolean equals(Object o) { // Identity comparison left on purpose. return o == this; } /** {@inheritDoc} */ @Override public int hashCode() { return hash; } /** {@inheritDoc} */ @Override public synchronized String toString() { return S.toString(GridCacheMapEntry.class, this); } }
package org.geotools.coverage.processing.operation; import javax.media.jai.operator.WarpDescriptor; import org.geotools.coverage.processing.BaseScaleOperationJAI; /** * This operation is simply a wrapper for the JAI Warp operation * * @source $URL$ * @version $Id$ * @author Simone Giannecchini * @since 9.0 * * @see WarpDescriptor */ public class Warp extends BaseScaleOperationJAI { /** serialVersionUID */ private static final long serialVersionUID = -9077795909705065389L; /** * Default constructor. */ public Warp() { super("Warp"); } }
package robowars.server.controller; import java.io.BufferedReader; import java.io.IOException; import java.io.ObjectInputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Vector; import org.apache.log4j.Logger; import robowars.shared.model.CommandType; import robowars.shared.model.GameRobot; import robowars.shared.model.RobotCommand; import lejos.pc.comm.NXTComm; import lejos.pc.comm.NXTCommException; import lejos.pc.comm.NXTCommFactory; import lejos.pc.comm.NXTInfo; /** * Manages communications with a single connected NXT robot. */ public class RobotProxy { /** The logger used by this class */ private static Logger log = Logger.getLogger(RobotProxy.class); /** The NXTComm object to use to initiate communication with the robot. */ NXTComm nxtComm; /** Stream for robot output */ private OutputStream outputStream; /** Stream for robot input (needs a separate thread to continually read) */ private ObjectInputStream inputStream; /** The server lobby that the robot should register with. */ private ServerLobby lobby; /** * The GameController object managing the game this proxy is * participating in (null if no game is in progress). */ private GameController controller; /** * The GameRobot instance that stores details on the robot managed * by this proxy. */ private GameRobot robot; /** * Generates a new robot proxy * @param identifier A string identifier for this robot */ public RobotProxy(ServerLobby lobby, NXTInfo nxtInfo) { this.lobby = lobby; // Use test sizes for now, actual dimensions should probably be sent // by the robot robot = new GameRobot(50, 50, nxtInfo.name); controller = null; nxtComm = null; outputStream = null; openConnection(nxtInfo); } /** * Opens a connection to the remote robot using the provided NXTInfo * object. * @param nxtInfo An NXTInfo object defining the robot to be connected * to (usually from a call to search on an NXTComm object) */ public void openConnection(NXTInfo nxtInfo) { try { nxtComm = NXTCommFactory.createNXTComm(NXTCommFactory.BLUETOOTH); nxtComm.open(nxtInfo); } catch (NXTCommException e) { // TODO Auto-generated catch block e.printStackTrace(); } outputStream = nxtComm.getOutputStream(); try { inputStream = new ObjectInputStream(nxtComm.getInputStream()); // Once input stream is open, generate new thread to continually // read input new Thread(new Runnable(){ @Override public void run() { // TODO: Read incoming Pose information here } }).start(); } catch (IOException e) { log.error("Error creating input stream for robot: " + getIdentifier()); } lobby.registerRobot(this); } /** * @return The lobby that the RobotProxy is associated with. */ public ServerLobby getServerLobby() { return lobby; } /** * Sets the instance of GameController that this UserProxy should pass * input commands to. * @param controller The GameController instance to pass inputs to. */ public void setGameController(GameController controller) { if(controller != null) { this.controller = controller; } } /** * Clears all references to a GameController for the proxy. */ public void clearGameController() { controller = null; } /** * @return The identifier of the robot (either the "friendly" NXT * name or the MAC address of the robot. */ public String getIdentifier() { return robot.getRobotId(); } /** * Sends a serialized RobotCommand to the connected robot through Bluetooth * @param command The RobotCommand to send */ public void sendCommand(RobotCommand command) { if(outputStream != null) { synchronized(outputStream) { try { switch(command.getType()) { case MOVE_CONTINUOUS: outputStream.write(1); outputStream.flush(); break; case TURN_RIGHT_ANGLE_LEFT: outputStream.write(3); outputStream.flush(); break; case TURN_RIGHT_ANGLE_RIGHT: outputStream.write(4); outputStream.flush(); break; case STOP: outputStream.write(2); outputStream.flush(); break; } } catch (IOException e) { log.error("Could not write to robot output stream."); } } } } }
package ast.visitors; import ast.*; import ast.utils.ASTUtils; import environment.EnvironmentStack; import symbols.value.*; import symbols.utils.Symbol; import dataStructures.*; import interpreter.parser.parser; import interpreter.lexer.lexer; import libraryFunctions.LibraryFunction_t; import java.util.ArrayList; import java.util.HashMap; import java.util.Objects; import java.util.logging.Level; import java.util.logging.Logger; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.nio.charset.StandardCharsets; import static utils.Constants.*; public class ExecutionASTVisitor implements ASTVisitor { private final EnvironmentStack _envStack; private int _scope; private int _inFunction; private int _inLoop; private boolean _inMeta; private Value _program; private void enterScopeSpace() { //System.out.println("EnterScopeSpace"); _scope++; _envStack.enterBlock(_scope); } private void exitScopeSpace() { //System.out.println("ExitScopeSpace"); _envStack.exitBlock(); _scope } private void enterFunctionSpace() { //System.out.println("EnterFunctionSpace"); _scope = FUNCTION_ENV_INIT_SCOPE; _inFunction++; _envStack.enterFunction(); } private Value exitFunctionSpace() { //System.out.println("ExitFunctionSpace"); _inFunction Value value = _envStack.exitFunction(); _scope = _envStack.topEnvScope(); return value; } private void enterLoopSpace() { //System.out.println("EnterLoopSpace"); _inLoop++; } private void exitLoopSpace() { //System.out.println("ExitLoopSpace"); _inLoop } private void enterMetaSpace() { _inMeta = true; } private void exitMetaSpace() { _inMeta = false; } private void setNodeIsLValueIfMember(ASTNode node) { //System.out.print("SetNodeIsLValueIfMember: "); if (node instanceof Member) { ((Member) node).setIsLValue(); //System.out.println("TRUE"); } else { //System.out.println("FALSE"); } } private Symbol toSymbol(IdentifierExpression idExpr) { return new Symbol(idExpr); } private Symbol toSymbol(String id) { return new Symbol(new IdentifierExpression(id)); } public ExecutionASTVisitor(Program program) { _envStack = new EnvironmentStack(); _scope = 0; _inFunction = 0; _inLoop = 0; _inMeta = false; _program = new StaticVal(Value_t.AST, program); _program = new DynamicVal(_program, "PROGRAM"); _envStack.insertSymbol(toSymbol("PROGRAM"), (DynamicVal) _program); } @Override public Value visit(Program node) throws ASTVisitorException { //System.out.println("-Program"); for (Statement stmt : node.getStatements()) { if (stmt != null) { stmt.accept(this); } } // //System.out.println(_envStack.toString()); return null; } @Override public Value visit(ExpressionStatement node) throws ASTVisitorException { //System.out.println("-ExpressionStatement"); Value retVal = NULL; //It is 'null' when we have semicolon with out expression if (node.getExpression() != null) { retVal = node.getExpression().accept(this); } return retVal; } @Override public Value visit(AssignmentExpression node) throws ASTVisitorException { //System.out.println("-AssignmentExpression"); setNodeIsLValueIfMember(node.getLvalue()); Value left = node.getLvalue().accept(this); setNodeIsLValueIfMember(node.getExpression()); Value right = node.getExpression().accept(this); _envStack.setValue((DynamicVal) left, right); // System.out.println(_envStack.toString()); return left; } @Override public Value visit(BinaryExpression node) throws ASTVisitorException { //System.out.println("-BinaryExpression"); Value result = null; Value left = node.getExpression1().accept(this); Value right = node.getExpression2().accept(this); Operator op = node.getOperator(); // Handle possible meta operands if (left.isAST() && right.isAST()) { BinaryExpression binAST; if (left.isAST() && !right.isAST()) { binAST = new BinaryExpression(op, ((Expression) left.getData()), node.getExpression2()); } else if (!left.isAST() && right.isAST()) { binAST = new BinaryExpression(op, node.getExpression1(), (Expression) right.getData()); } else { binAST = new BinaryExpression(op, (Expression) left.getData(), (Expression) right.getData()); } result = new StaticVal<>(Value_t.AST, binAST); return result; } String leftInfo = (left instanceof DynamicVal) ? ((DynamicVal) left).getErrorInfo() + "(" + left.getType() + ")" : left.getData() + "(" + left.getType() + ")"; leftInfo = "'" + left.getData() + "' (" + left.getType() + ")"; String rightInfo = (right instanceof DynamicVal) ? ((DynamicVal) right).getErrorInfo() + "(" + right.getType() + ")" : right.getData() + "(" + right.getType() + ")"; rightInfo = "'" + right.getData() + "' (" + right.getType() + ")"; if (op.isLogical() && !left.getType().toString().equals(right.getType().toString())) { result = new StaticVal<>(Value_t.BOOLEAN, Boolean.FALSE); if (op.equals(Operator.NOT_EQUAL)) { result = new StaticVal<>(Value_t.BOOLEAN, Boolean.TRUE); } if (!left.isNumeric() && !right.isNumeric()) { return result; } } //Handle error cases. String typeError = "Incompatible operand types for '" + node.getOperator() + "': " + leftInfo + " and " + rightInfo; if (left.isUndefined() || right.isUndefined()) { ASTUtils.error(node, typeError); } else if (left.isNull() || right.isNull()) { if (!Objects.equals(left, right)) { ASTUtils.error(node, typeError); } } else if ((!left.isNumeric() || !right.isNumeric()) && (!left.isBoolean() || !right.isBoolean())) { if ((left.isString() || right.isString())) { if (op.equals(Operator.PLUS)) { result = new StaticVal(Value_t.STRING, (String) left.getData().toString() + (String) right.getData().toString()); } else if (op.equals(Operator.CMP_EQUAL)) { result = new StaticVal(Value_t.BOOLEAN, left.getData().toString().equals(right.getData().toString())); } else if (op.equals(Operator.NOT_EQUAL)) { result = new StaticVal(Value_t.BOOLEAN, !left.getData().toString().equals(right.getData().toString())); } else { ASTUtils.error(node, typeError); } return result; } else { ASTUtils.error(node, typeError); } } //Compute operation result if (left.isNumeric()) { Double leftVal = (left.isReal()) ? (Double) left.getData() : ((Integer) left.getData()).doubleValue(); Double rightVal = (right.isReal()) ? (Double) right.getData() : ((Integer) right.getData()).doubleValue(); Double resultVal; boolean realResult; if (op.isLogical()) { if (op.equals(Operator.CMP_EQUAL)) { result = new StaticVal<>(Value_t.BOOLEAN, (Double.compare(leftVal, rightVal) == 0)); } else if (op.equals(Operator.NOT_EQUAL)) { result = new StaticVal<>(Value_t.BOOLEAN, (Double.compare(leftVal, rightVal) != 0)); } else if (op.equals(Operator.GREATER_OR_EQUAL)) { result = new StaticVal<>(Value_t.BOOLEAN, (leftVal >= rightVal)); } else if (op.equals(Operator.GREATER)) { result = new StaticVal<>(Value_t.BOOLEAN, (leftVal > rightVal)); } else if (op.equals(Operator.LESS_OR_EQUAL)) { result = new StaticVal<>(Value_t.BOOLEAN, (leftVal <= rightVal)); } else if (op.equals(Operator.LESS)) { result = new StaticVal<>(Value_t.BOOLEAN, (leftVal < rightVal)); } else { ASTUtils.error(node, typeError); } } else { realResult = (left.isReal() || right.isReal()); if (op.equals(Operator.PLUS)) { result = (realResult) ? new StaticVal<>(Value_t.REAL, leftVal + rightVal) : new StaticVal<>(Value_t.INTEGER, (Integer) ((Double) (leftVal + rightVal)).intValue()); } else if (op.equals(Operator.MINUS)) { result = (realResult) ? new StaticVal<>(Value_t.REAL, leftVal - rightVal) : new StaticVal<>(Value_t.INTEGER, (Integer) ((Double) (leftVal - rightVal)).intValue()); } else if (op.equals(Operator.MUL)) { result = (realResult) ? new StaticVal<>(Value_t.REAL, leftVal * rightVal) : new StaticVal<>(Value_t.INTEGER, (Integer) ((Double) (leftVal * rightVal)).intValue()); } else if (op.equals(Operator.DIV)) { result = (realResult) ? new StaticVal<>(Value_t.REAL, leftVal / rightVal) : new StaticVal<>(Value_t.INTEGER, (Integer) ((Double) (leftVal / rightVal)).intValue()); } else if (op.equals(Operator.MOD)) { result = (realResult) ? new StaticVal<>(Value_t.REAL, leftVal % rightVal) : new StaticVal<>(Value_t.INTEGER, (Integer) ((Double) (leftVal % rightVal)).intValue()); } } } else if (left.isBoolean()) { // Boolean values Boolean leftVal = (Boolean) left.getData(); Boolean rightVal = (Boolean) right.getData(); if (op.equals(Operator.LOGIC_AND)) { result = new StaticVal<>(Value_t.BOOLEAN, (leftVal && rightVal)); } else if (op.equals(Operator.LOGIC_OR)) { result = new StaticVal<>(Value_t.BOOLEAN, (leftVal || rightVal)); } else if (op.equals(Operator.CMP_EQUAL)) { result = new StaticVal<>(Value_t.BOOLEAN, (Objects.equals(leftVal, rightVal))); } else if (op.equals(Operator.NOT_EQUAL)) { result = new StaticVal<>(Value_t.BOOLEAN, (!Objects.equals(leftVal, rightVal))); } else { ASTUtils.error(node, typeError); } } else if (left.isNull()) { if (op.equals(Operator.LOGIC_AND)) { result = new StaticVal<>(Value_t.BOOLEAN, Boolean.FALSE); } else if (op.equals(Operator.LOGIC_OR)) { result = new StaticVal<>(Value_t.BOOLEAN, Boolean.FALSE); } else if (op.equals(Operator.CMP_EQUAL)) { result = new StaticVal<>(Value_t.BOOLEAN, (Objects.equals(left, right))); } else if (op.equals(Operator.NOT_EQUAL)) { result = new StaticVal<>(Value_t.BOOLEAN, (!Objects.equals(left, right))); } else { ASTUtils.error(node, typeError); } } else { //fatal error. } // //System.out.println("RESULT: "+result.getData()); return result; } @Override public Value visit(ParenthesisExpression node) throws ASTVisitorException { //System.out.println("-ParenthesisExpression"); Value result = node.getExpression().accept(this); return result; } @Override public Value visit(UnaryExpression node) throws ASTVisitorException { //System.out.println("-UnaryExpression"); Operator op = node.getOperator(); Value returnVal = new StaticVal(); if (node.getExpression() != null) { setNodeIsLValueIfMember(node.getExpression()); Value value = node.getExpression().accept(this); if (op.equals(Operator.MINUS)) { if (value.isInteger()) { returnVal = new StaticVal(value.getType(), -(int) value.getData()); } else if (value.isReal()) { returnVal = new StaticVal(value.getType(), -(double) value.getData()); } else { String msg = "Symbol '" + ((DynamicVal) value).getErrorInfo() + "' should be numeric type for operation '" + op.toString() + "'."; ASTUtils.error(node, msg); } } else if (op.equals(Operator.LOGIC_NOT)) { if (value.isBoolean()) { returnVal = new StaticVal(Value_t.BOOLEAN, !(boolean) value.getData()); } else if (value.isInteger() || value.isReal() || value.isString() || value.isUserFunction() || value.isLibraryFunction() || value.isTable() || value.isObject() || value.isAST()) { returnVal = new StaticVal(Value_t.BOOLEAN, Boolean.FALSE); } else if (value.isNull() || value.isUndefined()) { returnVal = new StaticVal(Value_t.BOOLEAN, Boolean.TRUE); } else { String msg = "Symbol '" + ((DynamicVal) value).getErrorInfo() + "' cannot be converted to boolean type."; ASTUtils.error(node, msg); } } } else { setNodeIsLValueIfMember(node.getLvalue()); Value value = node.getLvalue().accept(this); StaticVal assignVal = null; if (value.isInteger()) { int data = op.equals(Operator.PLUS_PLUS) ? (int) value.getData() + 1 : (int) value.getData() - 1; assignVal = new StaticVal(value.getType(), data); } else if (value.isReal()) { double data = op.equals(Operator.PLUS_PLUS) ? (double) value.getData() + 1 : (double) value.getData() - 1; assignVal = new StaticVal(value.getType(), data); } else { String msg = "Symbol '" + ((DynamicVal) value).getErrorInfo() + "' should be numeric type for operation '" + op.toString() + "'."; ASTUtils.error(node, msg); } _envStack.setValue((DynamicVal) value, assignVal); } return returnVal; } @Override public Value visit(IdentifierExpression node) throws ASTVisitorException { //System.out.println("-IdentifierExpression"); Symbol symbol = toSymbol(node); Value symbolInfo; symbolInfo = _envStack.lookupAll(symbol); if (symbolInfo == null) { _envStack.insertSymbol(symbol); symbolInfo = _envStack.lookupCurrentScope(symbol); // Retrieve newly added symbol } return symbolInfo; } @Override public Value visit(IdentifierExpressionLocal node) throws ASTVisitorException { //System.out.println("-IdentifierExpressionLocal"); Symbol symbol = toSymbol(node); Value symbolInfo; symbolInfo = _envStack.lookupCurrentScope(symbol); if (symbolInfo == null) { _envStack.insertSymbol(symbol); symbolInfo = _envStack.lookupCurrentScope(symbol); // Retrieve newly added symbol } return symbolInfo; } @Override public Value visit(IdentifierExpressionGlobal node) throws ASTVisitorException { //System.out.println("-IdentifierExpressionGlobal"); Symbol symbol = toSymbol(node); Value symbolInfo; symbolInfo = _envStack.lookupGlobalScope(symbol); if (symbolInfo == null) { String msg = "Global variable: " + symbol.getName() + " doesn't exist"; ASTUtils.error(node, msg); } return symbolInfo; } @Override public Value visit(Member node) throws ASTVisitorException { //System.out.println("-Member"); Value lvalue = null; Value key = null; Value retVal; String id = node.getIdentifier(); if ((node.getLvalue() != null) && (id != null)) { // lvalue.id lvalue = node.getLvalue().accept(this); if (!lvalue.isObject()) { String msg = "'" + ((DynamicVal) lvalue).getErrorInfo() + "' is not Object type to get member '" + id + "'."; ASTUtils.error(node, msg); } // key = _envStack.lookupAll(node.getIdentifier()); key = new StaticVal(Value_t.STRING, node.getIdentifier()); } else if ((node.getLvalue() != null) && (node.getExpression() != null)) { // lvalue [exp] lvalue = node.getLvalue().accept(this); if (!lvalue.isObject() && !lvalue.isTable()) { String msg = "'" + ((DynamicVal) lvalue).getErrorInfo() + "' is not Object or Array type to get member '" + id + "'."; ASTUtils.error(node, msg); } key = node.getExpression().accept(this); if (key.getData() != null && lvalue.isObject()) { key = new StaticVal(Value_t.STRING, node.getExpression().accept(this).getData().toString()); } else { key = node.getExpression().accept(this); } } else if ((id != null) && (node.getCall() != null)) { // call.id lvalue = node.getCall().accept(this); if (!lvalue.isObject()) { //Cast error Think about this add all other cases of downcasts of the ExecutionASTVisitor. what to do? //String msg = "'" + ((DynamicVal) lvalue).getErrorInfo() + "' it's not Object type to get member '" + id + "'."; String msg = "Return value is not Object type to get member '" + id + "'."; ASTUtils.error(node, msg); } Symbol symbol = toSymbol(node.getIdentifierExpr()); key = _envStack.lookupAll(symbol); } else if ((node.getCall() != null) && (node.getExpression() != null)) { // call (expr) lvalue = node.getCall().accept(this); if (!lvalue.isObject() && !lvalue.isTable()) { //Cast error Think about this add all other cases of downcasts of the ExecutionASTVisitor. what to do? //String msg = "'" + ((DynamicVal) lvalue).getErrorInfo() + "' it's not Object or Array type to get member '" + id + "'."; String msg = "Return value is not Object or Array type to get member '" + id + "'."; ASTUtils.error(node, msg); } key = node.getExpression().accept(this); } else { //fatal error Think how to manage this errors. } Value value = (lvalue.isObject()) ? ((FoxObject) lvalue.getData()).get(key) : ((FoxArray) lvalue.getData()).get(key); if (value == NULL) { if (node.isLValue()) { String errorInfo = "Object." + "id."; retVal = new DynamicVal(errorInfo); if (lvalue.isObject()) { ((FoxObject) lvalue.getData()).put(key, retVal); } else { ((FoxArray) lvalue.getData()).put(key, retVal); } // lvalue.put(key, retVal); } else { retVal = NULL; } } else { retVal = value; } return retVal; } @Override public Value visit(ExtendedCall node) throws ASTVisitorException { //System.out.println("-ExtendedCall"); Value retVal = NULL; Value function = node.getCall().accept(this); if (function.isUserFunction()) { String functionName = ((FunctionDef) function.getData()).getFuncName(); node.setLvalueCall(functionName, node.getNormCall()); retVal = node.getLvalueCall().accept(this); } else { String errorCode = "ExtendedCall"; ASTUtils.fatalError(node, errorCode); } return retVal; } @Override public Value visit(LvalueCall node) throws ASTVisitorException { //System.out.println("-LvalueCall"); Value lvalue = node.getLvalue().accept(this); //System.out.println(lvalue); if (node.getCallSuffix() instanceof NormCall) { if (!lvalue.isUserFunction() && !lvalue.isLibraryFunction()) { String msg = "Function call: Symbol '" + ((DynamicVal) lvalue).getErrorInfo() + "' is not Type-Function, BUT Type-" + lvalue.getType() + "."; ASTUtils.error(node, msg); } } else if (node.getCallSuffix() instanceof MethodCall) { if (!lvalue.isObject()) { String msg = "Function call using lvalue..id(elist): Symbol-" + ((DynamicVal) lvalue).getErrorInfo() + " is not Type-Object, but Type-" + lvalue.getType() + "."; ASTUtils.error(node, msg); } } if (lvalue.isUserFunction()) { //Get Actual Arguments Value parameters = node.getCallSuffix().accept(this); HashMap<Integer, Value> actualArguments = (HashMap<Integer, Value>) parameters.getData(); enterFunctionSpace(); int count = 0; ArrayList<IdentifierExpression> arguments = ((FunctionDef) lvalue.getData()).getArguments(); if (actualArguments.size() < arguments.size()) { String msg = "Call to '" + ((DynamicVal) lvalue).getErrorInfo() + "' requires " + arguments.size() + " arguments" + ": " + actualArguments.size() + " found."; ASTUtils.error(node, msg); } //Add Arguments field Symbol symbol = toSymbol("arguments"); String errorInfo = "arguments"; FoxArray argumentsArray = new FoxArray(); DynamicVal argumentInfo = new DynamicVal(Value_t.TABLE, argumentsArray, errorInfo); _envStack.insertSymbol(symbol, argumentInfo); //Map user function arguments with actual arguments(given args). for (IdentifierExpression argument : arguments) { symbol = toSymbol(argument); //System.out.println(name); errorInfo = symbol.getName(); argumentInfo = new DynamicVal(actualArguments.get(count), errorInfo); _envStack.insertSymbol(symbol, argumentInfo); Value key = new StaticVal(Value_t.INTEGER, count); argumentsArray.put(key, argumentInfo); count++; } //Add the extra given arguments. for (int i = count; i < actualArguments.size(); i++) { symbol = toSymbol("arg errorInfo = "arg argumentInfo = new DynamicVal(actualArguments.get(i), errorInfo); _envStack.insertSymbol(symbol, argumentInfo); Value key = new StaticVal(Value_t.INTEGER, i); argumentsArray.put(key, argumentInfo); } ((FunctionDef) lvalue.getData()).getBody().accept(this); } else if (lvalue.isLibraryFunction()) { //Get Actual Arguments Value parameters = node.getCallSuffix().accept(this); HashMap<Integer, Value> actualArguments = (HashMap<Integer, Value>) parameters.getData(); enterFunctionSpace(); for (int i = 0; i < actualArguments.size(); i++) { Symbol symbol = toSymbol(LIBRARY_FUNC_ARG + i); String errorInfo = LIBRARY_FUNC_ARG + i; DynamicVal argumentInfo = new DynamicVal(actualArguments.get(i), errorInfo); _envStack.insertSymbol(symbol, argumentInfo); } try { Method method = (Method) lvalue.getData(); method.invoke(null, _envStack.getFunctionEnv()); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { Logger.getLogger(ExecutionASTVisitor.class.getName()).log(Level.SEVERE, null, ex); } } else if (lvalue.isObject()) { //Get lvalue FoxObject fobject = (FoxObject) lvalue.getData(); //Get ..id String id = ((MethodCall) node.getCallSuffix()).getIdentifier(); Value key = new StaticVal(Value_t.STRING, id); // Value function = objectData.get(key); Value function = fobject.get(key); if (!function.isUserFunction() && !function.isLibraryFunction()) { String msg = "Function call using lvalue..id(elist): Symbmol- 'lvalue." + id + "' is not Type-Function, but Type-" + lvalue.getType() + "."; ASTUtils.error(node, msg); } //Get Actual Arguments Value parameters = node.getCallSuffix().accept(this); HashMap<Integer, Value> actualArguments = (HashMap<Integer, Value>) parameters.getData(); ArrayList<IdentifierExpression> arguments = ((FunctionDef) function.getData()).getArguments(); enterFunctionSpace(); if (arguments.size() != (actualArguments.size() + 1)) { String msg = "Call to '" + ((DynamicVal) lvalue).getErrorInfo() + "' requires " + arguments.size() + " arguments" + ": " + actualArguments.size() + " found."; ASTUtils.error(node, msg); } int count = 0; Symbol symbol = toSymbol(arguments.get(count)); String errorInfo = symbol.getName(); DynamicVal argumentInfo = new DynamicVal(lvalue, errorInfo); _envStack.insertSymbol(symbol, argumentInfo); for (count = 1; count < arguments.size(); count++) { symbol = toSymbol(arguments.get(count)); //System.out.println(name); errorInfo = symbol.getName(); argumentInfo = new DynamicVal(actualArguments.get(count - 1), errorInfo); _envStack.insertSymbol(symbol, argumentInfo); count++; } Value bodyRet = ((FunctionDef) function.getData()).getBody().accept(this); } Value ret = exitFunctionSpace(); if (ret.getType().equals(Value_t.ERROR)) { String msg = "Error during Function Execution @'" + ((DynamicVal) lvalue).getErrorInfo() + "' - " + ret.getData(); ASTUtils.error(node, msg); } else if (ret == null) { ret = NULL; } //System.out.println(_envStack.toString()); return ret; } @Override public Value visit(AnonymousFunctionCall node) throws ASTVisitorException { //System.out.println("-AnonymousFunctionCall"); Value function = node.getFunctionDef().accept(this); Value returnValue = node.getLvalueCall().accept(this); return returnValue; } @Override public Value visit(NormCall node) throws ASTVisitorException { //System.out.println("-NormCall"); HashMap<Integer, Value> arguments = new HashMap<>(); int count = 0; for (Expression expression : node.getExpressionList()) { Value argValue; if (expression instanceof MetaSyntax && _inMeta) { argValue = new StaticVal<>(Value_t.AST, expression); } else { argValue = expression.accept(this); } arguments.put(count, argValue); //System.out.println(argValue); count++; } //Change to fox Table. return new StaticVal(Value_t.UNDEFINED, arguments); } @Override public Value visit(MethodCall node) throws ASTVisitorException { //System.out.println("-MethodCall"); Value arguments = node.getNormCall().accept(this); return arguments; } @Override public Value visit(ObjectDefinition node) throws ASTVisitorException { //System.out.println("-ObjectDefinition"); HashMap<Value, Value> objectData = new HashMap<>(); if (!node.getIndexedElementList().isEmpty()) { for (IndexedElement indexed : node.getIndexedElementList()) { ArrayList<Value> data = (ArrayList<Value>) indexed.accept(this).getData(); String errorInfo = "Object.(" + data.get(0) + ")"; Value value = new DynamicVal(data.get(1), errorInfo); Value name = new StaticVal(Value_t.STRING, data.get(0).getData().toString()); objectData.put(name, value); // objectData.put(data.get(0), value); } } FoxObject fobject = new FoxObject(objectData); return new StaticVal(Value_t.OBJECT, fobject); } @Override public Value visit(IndexedElement node) throws ASTVisitorException { //System.out.println("-IndexedElement"); ArrayList<Value> objectData = new ArrayList<>(); if (node.getExpression1() instanceof IdentifierExpression) { objectData.add(new StaticVal(Value_t.STRING, ((IdentifierExpression) node.getExpression1()).getIdentifier())); } else { objectData.add(node.getExpression1().accept(this)); } Value value = node.isValueExpression() ? node.getExpression2().accept(this) : node.getFunctionDef().accept(this); objectData.add(value); return new StaticVal(Value_t.UNDEFINED, objectData); } @Override public Value visit(ArrayDef node) throws ASTVisitorException { //System.out.println("-ArrayDef"); HashMap<Value, Value> arrayData = new HashMap<>(); int count = 0; if (node.getExpressionList() != null) { for (Expression expression : node.getExpressionList()) { Value index = new StaticVal(Value_t.INTEGER, count); Value value = expression.accept(this); String errorInfo = "Object.(" + count + ")"; Value element = new DynamicVal(value, errorInfo); arrayData.put(index, element); count++; } } FoxArray farray = new FoxArray(arrayData); return new StaticVal(Value_t.TABLE, farray); } @Override public Value visit(Block node) throws ASTVisitorException { //System.out.println("-Block"); Value retVal = NULL; enterScopeSpace(); for (Statement stmt : node.getStatementList()) { retVal = stmt.accept(this); if (retVal != NULL && retVal != null) { if (retVal.getData().equals(BREAK) || retVal.getData().equals(CONTINUE) || retVal.getData().equals(RETURN)) { return retVal; } } } exitScopeSpace(); return retVal; } @Override public Value visit(FunctionDefExpression node) throws ASTVisitorException { //System.out.println("-FunctionDefExpression"); Value retVal = node.getFunctionDef().accept(this); return retVal; } @Override public Value visit(FunctionDef node) throws ASTVisitorException { //System.out.println("-FunctionDef"); /*Function Name*/ Symbol symbol = toSymbol(node.getFuncNameIdentifierExpr()); String name = symbol.getName(); DynamicVal funcInfo = _envStack.lookupCurrentScope(symbol); boolean isLibraryFunction = LibraryFunction_t.isLibraryFunction(name); if (funcInfo != null) { boolean isUserFunction = funcInfo.getType() == Value_t.USER_FUNCTION; String msg; if (isUserFunction) { msg = "Redeclaration of User-Function: " + name + "."; } else if (isLibraryFunction) { msg = "User-Function shadows Library-Function: " + name + "."; } else { //Think to remove this else statment. msg = "User-Function already declared as Variable: " + name + "."; } ASTUtils.error(node, msg); } else { if (isLibraryFunction) { String msg = "User-Function Shadows Library-Function: " + name + "."; ASTUtils.error(node, msg); } } String errorInfo = name; funcInfo = new DynamicVal(Value_t.USER_FUNCTION, node, errorInfo); _envStack.insertSymbol(symbol, funcInfo); /*Function ONLY Check Arguments*/ enterScopeSpace(); for (IdentifierExpression argument : node.getArguments()) { symbol = toSymbol(argument); Value argInfo = _envStack.lookupCurrentScope(symbol); if (argInfo != null) { String msg = "Redeclaration of Formal-Argument: " + name + "."; ASTUtils.error(node, msg); } if (LibraryFunction_t.isLibraryFunction(name)) { String msg = "Formal-Argument shadows Library-Function: " + name + "."; ASTUtils.error(node, msg); } _envStack.insertSymbol(symbol); } exitScopeSpace(); return funcInfo; } @Override public Value visit(IntegerLiteral node) throws ASTVisitorException { //System.out.println("-IntegerLiteral"); return new StaticVal(Value_t.INTEGER, node.getLiteral()); } @Override public Value visit(DoubleLiteral node) throws ASTVisitorException { //System.out.println("-DoubleLiteral"); return new StaticVal(Value_t.REAL, node.getLiteral()); } @Override public Value visit(StringLiteral node) throws ASTVisitorException { //System.out.println("-StringLiteral"); return new StaticVal(Value_t.STRING, node.getLiteral()); } @Override public Value visit(NullLiteral node) throws ASTVisitorException { //System.out.println("-NullLiteral"); return NULL; } @Override public Value visit(TrueLiteral node) throws ASTVisitorException { //System.out.println("-TrueLiteral"); return new StaticVal(Value_t.BOOLEAN, Boolean.TRUE); } @Override public Value visit(FalseLiteral node) throws ASTVisitorException { //System.out.println("-FalseLiteral"); return new StaticVal(Value_t.BOOLEAN, Boolean.FALSE); } @Override public Value visit(IfStatement node) throws ASTVisitorException { //System.out.println("-IfStatement"); Value val = node.getExpression().accept(this); Value ret = NULL; Boolean enter; if (val.isNull() || val.isUndefined()) { // ASTUtils.error(node, "If expression must be boolean: " + val.getType() + " given"); enter = false; } else if (val.isNumeric()) { int s = (val.getData() instanceof Double) ? ((Double) val.getData()).intValue() : (Integer) val.getData(); enter = s != 0; } else if (val.isBoolean()) { enter = (Boolean) val.getData(); } else { enter = true; } if (enter) { ret = node.getStatement().accept(this); if (ret != null) { if (ret.getData().equals(BREAK) || ret.getData().equals(CONTINUE) || ret.getData().equals(RETURN)) { return ret; } } } else { if (node.getElseStatement() != null) { ret = node.getElseStatement().accept(this); if (ret != null) { if (ret.getData().equals(BREAK) || ret.getData().equals(CONTINUE) || ret.getData().equals(RETURN)) { return ret; } } } } return ret; } @Override public Value visit(WhileStatement node) throws ASTVisitorException { //System.out.println("-WhileStatement"); Value val = node.getExpression().accept(this); Value ret; if (!val.isBoolean()) { ASTUtils.error(node, "While expression must be boolean: " + val.getType() + " given"); } enterLoopSpace(); while ((Boolean) ((Value) node.getExpression().accept(this)).getData()) { ret = node.getStatement().accept(this); if (ret != null) { if (ret.getData().equals(BREAK)) { break; } else if (ret.getData().equals(CONTINUE)) { continue; } else if (ret.getData().equals(RETURN)) { exitLoopSpace(); return ret; } } } exitLoopSpace(); return null; } @Override public Value visit(ForStatement node) throws ASTVisitorException { //System.out.println("-ForStatement"); Value ret; enterLoopSpace(); for (Expression expression : node.getExpressionList1()) { expression.accept(this); } Value val = node.getExpression().accept(this); if (!val.isBoolean()) { ASTUtils.error(node, "For expression must be boolean: " + val.getType() + " given"); } while ((Boolean) ((Value) node.getExpression().accept(this)).getData()) { ret = node.getStatement().accept(this); if (ret != null) { if (ret.getData().equals(BREAK)) { break; } else if (ret.getData().equals(CONTINUE)) { for (Expression expression : node.getExpressionList2()) { expression.accept(this); } continue; } else if (ret.getData().equals(RETURN)) { return ret; } } for (Expression expression : node.getExpressionList2()) { expression.accept(this); } } exitLoopSpace(); return null; } @Override public Value visit(BreakStatement node) throws ASTVisitorException { //System.out.println("-BreakStatement"); if (_inLoop == 0) { ASTUtils.error(node, "Use of 'break' while not in a loop."); } return new StaticVal(Value_t.STRING, BREAK); } @Override public Value visit(ContinueStatement node) throws ASTVisitorException { //System.out.println("-ContinueStatement"); if (_inLoop == 0) { ASTUtils.error(node, "Use of 'continue' while not in a loop."); } return new StaticVal(Value_t.STRING, CONTINUE); } @Override public Value visit(ReturnStatement node) throws ASTVisitorException { //System.out.println("-ReturnStatement"); Value ret; if (_inFunction == 0) { ASTUtils.error(node, "Use of 'return' while not in a function."); } if (node.getExpression() != null) { ret = node.getExpression().accept(this); _envStack.setReturnValue(ret); } return new StaticVal(Value_t.STRING, RETURN); } @Override public Value visit(MetaSyntax node) throws ASTVisitorException { if (node.getExpression() != null) { if (_inMeta) { return node.getExpression().accept(this); } else { return new StaticVal<>(Value_t.AST, node.getExpression()); } } else { if (_inMeta) { for (Statement stmt : node.getStatementList()) { stmt.accept(this); } } else { if (node.getStatementList().size() == 1) { return new StaticVal<>(Value_t.AST, node.getStatementList().get(0)); } else { return new StaticVal<>(Value_t.AST, node.getStatementList()); } } } return new StaticVal(); } @Override public Value visit(MetaEscape node) throws ASTVisitorException { Value exprVal = node.getExpression().accept(this); if (!exprVal.isAST()) { String msg = ".~ requires an identifier holding an AST: " + exprVal.getType() + " found"; ASTUtils.error(node, msg); } return exprVal; } @Override public Value visit(MetaExecute node) throws ASTVisitorException { Value ret = new StaticVal(); // If the following expression is a function call, enter meta space beforehand, so possible produced // ASTs get executed correctly if (node.getExpression() instanceof LvalueCall) { enterMetaSpace(); } Value exprVal = node.getExpression().accept(this); enterMetaSpace(); if (!exprVal.isAST()) { String msg = "'.!' requires an AST: " + exprVal.getType() + " found"; ASTUtils.error(node, msg); } if (exprVal.getData() instanceof Expression) { Expression astExpr = (Expression) exprVal.getData(); ret = astExpr.accept(this); while (ret.isAST()) { ret = ((Expression) ret.getData()).accept(this); } } else { for (Statement stmt : (ArrayList<Statement>) exprVal.getData()) { stmt.accept(this); } } exitMetaSpace(); return ret; } @Override public Value visit(MetaRun node) throws ASTVisitorException { Value exprVal = node.getExpression().accept(this); Value retVal; if (!exprVal.isString()) { String msg = "'.@' requires a StringLiteral: " + exprVal.getType() + " found"; ASTUtils.error(node, msg); } InputStream stream = new ByteArrayInputStream(((String) exprVal.getData()).getBytes(StandardCharsets.UTF_8)); parser p = new parser(new lexer(stream)); ASTNode program = null; try { program = (ASTNode) p.parse().value; } catch (Exception e) { String msg = "'.@' StringLiteral is NOT a valid statment."; ASTUtils.error(node, msg); } retVal = new StaticVal<>(Value_t.AST, ((Program) program).getStatements()); return retVal; } @Override public Value visit(MetaEval node) throws ASTVisitorException { Value retVal = node.getEvalNode().accept(this); return retVal; } @Override public Value visit(MetaToText node) throws ASTVisitorException { if (node.getExpression() == null) { return new StaticVal<>(Value_t.STRING, ""); } Expression expr = (Expression) node.getExpression(); ASTVisitor astVisitor = new ToStringASTVisitor(); expr.accept(astVisitor); String data = astVisitor.toString(); return new StaticVal<>(Value_t.STRING, data); } }
package com.yahoo.vespa.hosted.node.admin.integration; import com.yahoo.config.provision.DockerImage; import com.yahoo.config.provision.HostName; import com.yahoo.config.provision.NodeType; import com.yahoo.vespa.flags.InMemoryFlagSource; import com.yahoo.vespa.hosted.node.admin.configserver.noderepository.NodeSpec; import com.yahoo.vespa.hosted.node.admin.configserver.orchestrator.Orchestrator; import com.yahoo.vespa.hosted.node.admin.container.CGroupV2; import com.yahoo.vespa.hosted.node.admin.container.ContainerEngineMock; import com.yahoo.vespa.hosted.node.admin.container.ContainerName; import com.yahoo.vespa.hosted.node.admin.container.ContainerOperations; import com.yahoo.vespa.hosted.node.admin.container.RegistryCredentials; import com.yahoo.vespa.hosted.node.admin.container.metrics.Metrics; import com.yahoo.vespa.hosted.node.admin.maintenance.StorageMaintainer; import com.yahoo.vespa.hosted.node.admin.maintenance.servicedump.VespaServiceDumper; import com.yahoo.vespa.hosted.node.admin.nodeadmin.NodeAdminImpl; import com.yahoo.vespa.hosted.node.admin.nodeadmin.NodeAdminStateUpdater; import com.yahoo.vespa.hosted.node.admin.nodeagent.NodeAgentContext; import com.yahoo.vespa.hosted.node.admin.nodeagent.NodeAgentContextFactory; import com.yahoo.vespa.hosted.node.admin.nodeagent.NodeAgentContextImpl; import com.yahoo.vespa.hosted.node.admin.nodeagent.NodeAgentFactory; import com.yahoo.vespa.hosted.node.admin.nodeagent.NodeAgentImpl; import com.yahoo.vespa.hosted.node.admin.task.util.network.IPAddressesMock; import com.yahoo.vespa.test.file.TestFileSystem; import org.mockito.InOrder; import org.mockito.Mockito; import java.nio.file.FileSystem; import java.time.Clock; import java.time.Duration; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.logging.Logger; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.when; /** * @author musum */ // Need to deconstruct nodeAdminStateUpdater public class ContainerTester implements AutoCloseable { private static final Logger log = Logger.getLogger(ContainerTester.class.getName()); private static final Duration INTERVAL = Duration.ofMillis(10); static final HostName HOST_HOSTNAME = HostName.from("host.test.yahoo.com"); private final Thread loopThread; private final ContainerEngineMock containerEngine = new ContainerEngineMock(); private final FileSystem fileSystem = TestFileSystem.create(); final ContainerOperations containerOperations = spy(new ContainerOperations(containerEngine, new CGroupV2(fileSystem), fileSystem)); final NodeRepoMock nodeRepository = spy(new NodeRepoMock()); final Orchestrator orchestrator = mock(Orchestrator.class); final StorageMaintainer storageMaintainer = mock(StorageMaintainer.class); final InOrder inOrder = Mockito.inOrder(containerOperations, nodeRepository, orchestrator, storageMaintainer); final InMemoryFlagSource flagSource = new InMemoryFlagSource(); final NodeAdminStateUpdater nodeAdminStateUpdater; final NodeAdminImpl nodeAdmin; private boolean terminated = false; private volatile NodeAdminStateUpdater.State wantedState = NodeAdminStateUpdater.State.RESUMED; ContainerTester(List<DockerImage> images) { images.forEach(image -> containerEngine.pullImage(null, image, RegistryCredentials.none)); when(storageMaintainer.diskUsageFor(any())).thenReturn(Optional.empty()); IPAddressesMock ipAddresses = new IPAddressesMock(); ipAddresses.addAddress(HOST_HOSTNAME.value(), "1.1.1.1"); ipAddresses.addAddress(HOST_HOSTNAME.value(), "f000::"); for (int i = 1; i < 4; i++) ipAddresses.addAddress("host" + i + ".test.yahoo.com", "f000::" + i); NodeSpec hostSpec = NodeSpec.Builder.testSpec(HOST_HOSTNAME.value()).type(NodeType.host).build(); nodeRepository.updateNodeSpec(hostSpec); Clock clock = Clock.systemUTC(); Metrics metrics = new Metrics(); FileSystem fileSystem = TestFileSystem.create(); NodeAgentFactory nodeAgentFactory = (contextSupplier, nodeContext) -> new NodeAgentImpl( contextSupplier, nodeRepository, orchestrator, containerOperations, () -> RegistryCredentials.none, storageMaintainer, flagSource, Collections.emptyList(), Optional.empty(), Optional.empty(), clock, Duration.ofSeconds(-1), VespaServiceDumper.DUMMY_INSTANCE); nodeAdmin = new NodeAdminImpl(nodeAgentFactory, metrics, clock, Duration.ofMillis(10), Duration.ZERO); NodeAgentContextFactory nodeAgentContextFactory = (nodeSpec, acl) -> NodeAgentContextImpl.builder(nodeSpec).acl(acl).fileSystem(fileSystem).build(); nodeAdminStateUpdater = new NodeAdminStateUpdater(nodeAgentContextFactory, nodeRepository, orchestrator, nodeAdmin, HOST_HOSTNAME); loopThread = new Thread(() -> { nodeAdminStateUpdater.start(); while (! terminated) { try { nodeAdminStateUpdater.converge(wantedState); } catch (RuntimeException e) { log.info(e.getMessage()); } try { Thread.sleep(INTERVAL.toMillis()); } catch (InterruptedException e) { e.printStackTrace(); } } }); loopThread.start(); } /** Adds a node to node-repository mock that is running on this host */ void addChildNodeRepositoryNode(NodeSpec nodeSpec) { if (nodeSpec.wantedDockerImage().isPresent()) { if (!containerEngine.hasImage(null, nodeSpec.wantedDockerImage().get())) { throw new IllegalArgumentException("Want to use image " + nodeSpec.wantedDockerImage().get() + ", but that image does not exist in the container engine"); } } nodeRepository.updateNodeSpec(new NodeSpec.Builder(nodeSpec) .parentHostname(HOST_HOSTNAME.value()) .build()); } void setWantedState(NodeAdminStateUpdater.State wantedState) { this.wantedState = wantedState; } <T> T inOrder(T t) { // Should probably wait for one NodeAdminStateUpdater tick & one node agent tick // instead of waiting up to a timeout, but there are currently no guarantees on the node // agent ticks. return inOrder.verify(t, timeout(60000)); } public static NodeAgentContext containerMatcher(ContainerName containerName) { return argThat((ctx) -> ctx.containerName().equals(containerName)); } @Override public void close() { // First, stop NodeAdmin and all the NodeAgents nodeAdminStateUpdater.stop(); terminated = true; do { try { loopThread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } while (loopThread.isAlive()); } }
package com.x.base.core.project.config; import java.io.File; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.BooleanUtils; import com.x.base.core.project.annotation.FieldDescribe; import com.x.base.core.project.gson.XGsonBuilder; import com.x.base.core.project.tools.BaseTools; import com.x.base.core.project.tools.DefaultCharset; import com.x.base.core.project.tools.NumberTools; public class Organization extends ConfigObject { private static final long serialVersionUID = -2193428649985413384L; public static final Integer DEFAULT_UNITLEVELORDERNUMBERDIGITS = 10; public static final Boolean DEFAULT_PICKPERSONWITHNAME = true; public static final Boolean DEFAULT_PICKIDENTITYWITHNAME = true; public static Organization defaultInstance() { return new Organization(); } @FieldDescribe("unitunitLevelOrderNumber,<=0.") private Integer unitLevelOrderNumberDigits = DEFAULT_UNITLEVELORDERNUMBERDIGITS; @FieldDescribe("zhangsan@123@P distinguishedName unique .") private Boolean pickPersonWithName = DEFAULT_PICKPERSONWITHNAME; @FieldDescribe("zhangsan@456@I distinguishedName unique .") private Boolean pickIdentityWithName = DEFAULT_PICKIDENTITYWITHNAME; public Integer getUnitLevelOrderNumberDigits() { return NumberTools.nullOrLessThan(this.unitLevelOrderNumberDigits, 1) ? DEFAULT_UNITLEVELORDERNUMBERDIGITS : this.unitLevelOrderNumberDigits; } public Boolean getPickPersonWithName() { return BooleanUtils.isTrue(this.pickPersonWithName); } public Boolean getPickIdentityWithName() { return BooleanUtils.isTrue(this.pickIdentityWithName); } public void save() throws Exception { File file = new File(Config.base(), Config.PATH_CONFIG_ORGANIZATION); FileUtils.write(file, XGsonBuilder.toJson(this), DefaultCharset.charset); BaseTools.executeSyncFile(Config.PATH_CONFIG_ORGANIZATION); } }
package org.opennms.netmgt.dao.db; import java.io.ByteArrayOutputStream; import java.io.PrintStream; public class PopulatedTemporaryDatabaseTestCase extends TemporaryDatabaseTestCase { private InstallerDb m_installerDb; private ByteArrayOutputStream m_outputStream; protected void setUp() throws Exception { super.setUp(); initializeDatabase(); } protected void initializeDatabase() throws Exception { if (!isEnabled()) { return; } m_installerDb = new InstallerDb(); // Create a ByteArrayOutputSteam to effectively throw away output. resetOutputStream(); m_installerDb.setDatabaseName(getTestDatabase()); m_installerDb.setDataSource(getDataSource()); m_installerDb.setCreateSqlLocation( "../opennms-daemon/src/main/filtered/etc/create.sql"); m_installerDb.setStoredProcedureDirectory( "../opennms-daemon/src/main/filtered/etc"); //installerDb.setDebug(true); m_installerDb.readTables(); m_installerDb.createSequences(); m_installerDb.updatePlPgsql(); m_installerDb.addStoredProcedures(); m_installerDb.createTables(); m_installerDb.closeConnection(); } public ByteArrayOutputStream getOutputStream() { return m_outputStream; } public void resetOutputStream() { m_outputStream = new ByteArrayOutputStream(); m_installerDb.setOutputStream(new PrintStream(m_outputStream)); } }
package org.caleydo.view.heatmap.heatmap.template; import org.caleydo.view.heatmap.heatmap.renderer.ContentCaptionRenderer; import org.caleydo.view.heatmap.heatmap.renderer.ContentSelectionRenderer; import org.caleydo.view.heatmap.heatmap.renderer.HeatMapRenderer; import org.caleydo.view.heatmap.heatmap.renderer.StorageSelectionRenderer; public class DefaultTemplate extends ATemplate { @Override public void setParameters() { templateRenderer.clearRenderers(); Row row = new Row(); row.sizeY = 1; // heat map RenderParameters heatMapLayout = new RenderParameters(); heatMapLayout.sizeX = 0.715f; heatMapLayout.sizeY = 0.84f; heatMapLayout.renderer = new HeatMapRenderer(templateRenderer.heatMap); templateRenderer.addRenderer(heatMapLayout); RenderParameters contentSelectionLayout = new RenderParameters(); contentSelectionLayout.isBackground = true; contentSelectionLayout.sizeX = 0.72f; contentSelectionLayout.renderer = new ContentSelectionRenderer( templateRenderer.heatMap); templateRenderer.addRenderer(contentSelectionLayout); RenderParameters storageSelectionLayout = new RenderParameters(); storageSelectionLayout.isBackground = true; // contentSelectionLayout.sizeX = 1; storageSelectionLayout.sizeY = 0.84f; storageSelectionLayout.renderer = new StorageSelectionRenderer( templateRenderer.heatMap); templateRenderer.addRenderer(storageSelectionLayout); row.appendElement(contentSelectionLayout); row.appendElement(storageSelectionLayout); row.appendElement(heatMapLayout); RenderParameters spacing = new RenderParameters(); spacing.sizeX = 0.01f; row.appendElement(spacing); // content captions RenderParameters contentCaptionLayout = new RenderParameters(); contentCaptionLayout.sizeX = 0.29f; contentCaptionLayout.sizeY = 0.84f; // heatMapLayout.grabY = true; contentCaptionLayout.transformX = 0.7f + templateRenderer.SPACING; contentCaptionLayout.renderer = new ContentCaptionRenderer( templateRenderer.heatMap); templateRenderer.addRenderer(contentCaptionLayout); row.appendElement(contentCaptionLayout); add(row); spacing = new RenderParameters(); spacing.sizeY = 0.16f; add(spacing); } }
package org.osgi.test.support.compatibility; import java.net.URL; import junit.framework.TestCase; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleException; import org.osgi.framework.ServiceReference; public abstract class DefaultTestBundleControl extends TestCase { /* @GuardedBy("this") */ private BundleContext context; /** * THis method is called by the JUnit runner for OSGi, and gives us a Bundle * Context. */ public synchronized void setBundleContext(BundleContext context) { this.context = context; } /** * Returns the current Bundle Context */ public synchronized BundleContext getContext() { if (context == null) fail("No valid Bundle context said, are you running in OSGi Test mode?"); return context; } /** * This returned a web server but we will just now, it is mostly used in * installBundle and there we get the bundle from our resources. */ public String getWebServer() { return "/www/"; } /** * Uninstall a bundle. * * @param bundle * @throws BundleException */ public void uninstallBundle(Bundle bundle) throws BundleException { bundle.uninstall(); } /** * Install a bundle. * * @param bundle * @throws BundleException */ public Bundle installBundle(String url) throws BundleException { URL resource = getClass().getResource(url); if ( resource == null ) fail("Can not load bundle " + url); return getContext().installBundle(resource.toString()); } /** * Convenience getService method */ public Object getService(Class clazz ) { BundleContext c = getContext(); ServiceReference ref = c.getServiceReference(clazz.getName()); if ( ref == null ) return null; return c.getService(ref); } public void failException(String message, Class expectedExceptionClass) { fail(message + " expected:[" + expectedExceptionClass.getName() + "] and got nothing"); } public void pass(String passMessage) { //nothing to do here } public void log(String logMessage) { //log messages are currently skipped } }
package org.spoofax.jsglr2.parser.observing; import java.util.HashMap; import java.util.Queue; import java.util.function.Consumer; import org.metaborg.parsetable.actions.IAction; import org.metaborg.parsetable.actions.IReduce; import org.metaborg.parsetable.characterclasses.CharacterClassFactory; import org.metaborg.parsetable.productions.IProduction; import org.spoofax.jsglr2.JSGLR2Logging; import org.spoofax.jsglr2.JSGLR2Request; import org.spoofax.jsglr2.elkhound.AbstractElkhoundStackNode; import org.spoofax.jsglr2.incremental.parseforest.IncrementalParseForest; import org.spoofax.jsglr2.inputstack.incremental.IIncrementalInputStack; import org.spoofax.jsglr2.parseforest.IDerivation; import org.spoofax.jsglr2.parseforest.IParseForest; import org.spoofax.jsglr2.parseforest.IParseNode; import org.spoofax.jsglr2.parser.AbstractParseState; import org.spoofax.jsglr2.parser.ForShifterElement; import org.spoofax.jsglr2.parser.result.ParseFailure; import org.spoofax.jsglr2.parser.result.ParseSuccess; import org.spoofax.jsglr2.recovery.IRecoveryParseState; import org.spoofax.jsglr2.stack.IStackNode; import org.spoofax.jsglr2.stack.StackLink; import org.spoofax.jsglr2.stack.collections.IForActorStacks; public class LogParserObserver //@formatter:off <ParseForest extends IParseForest, Derivation extends IDerivation<ParseForest>, ParseNode extends IParseNode<ParseForest, Derivation>, StackNode extends IStackNode, ParseState extends AbstractParseState<?, StackNode>> //@formatter:on extends RegisteringParserObserver<ParseForest, Derivation, ParseNode, StackNode, ParseState> { final private Consumer<String> logger; final private JSGLR2Logging[] scopes; final private HashMap<JSGLR2Request, Long> startTimes; public LogParserObserver(Consumer<String> logger, JSGLR2Logging... scopes) { this.logger = logger; this.scopes = scopes; this.startTimes = new HashMap<>(); } public LogParserObserver(Consumer<String> logger) { this(logger, JSGLR2Logging.All); } public LogParserObserver(JSGLR2Logging... scopes) { this(System.out::println, scopes); } @Override public void parseStart(ParseState parseState) { super.parseStart(parseState); log("Starting parse" + (parseState.request.isCompletion() ? (" for completion at offset " + parseState.request.completionCursorOffset.get()) : ""), JSGLR2Logging.Parsing, JSGLR2Logging.Minimal); startTimes.put(parseState.request, System.currentTimeMillis()); } @Override public void parseRound(ParseState parseState, Iterable<StackNode> activeStacks) { if(parseState.inputStack instanceof IIncrementalInputStack) { IncrementalParseForest node = ((IIncrementalInputStack) parseState.inputStack).getNode(); @SuppressWarnings("unchecked") int id = id((ParseForest) node); String activeStacksText = " (active stacks: " + stackQueueToString(activeStacks) + ")"; String message = node.isTerminal() ? "Process character node " + id + " " + node.toString() + activeStacksText : "Process parse node " + id + activeStacksText + ":\n " + node.toString().replaceAll("\n", "\n "); log(message, JSGLR2Logging.Parsing); } else log("Parse character '" + characterToString(parseState.inputStack.getChar()) + "' (active stacks: " + stackQueueToString(activeStacks) + ")", JSGLR2Logging.Parsing, JSGLR2Logging.Recovery); } @Override public void createStackNode(StackNode stack) { super.createStackNode(stack); log(" Create stack " + stackNodeString(stack), JSGLR2Logging.Parsing); } @Override public void createStackLink(StackLink<ParseForest, StackNode> link) { super.createStackLink(link); log(" Create link " + stackNodeString(link.to) + " < JSGLR2Logging.Parsing); } @Override public void resetDeterministicDepth(AbstractElkhoundStackNode<ParseForest> stack) { log(" Reset deterministic depth for stack " + stackNodeString((StackNode) stack), JSGLR2Logging.Parsing); } @Override public void rejectStackLink(StackLink<ParseForest, StackNode> link) { log("Reject link " + id(link), JSGLR2Logging.Parsing); } @Override public void forActorStacks(IForActorStacks<StackNode> forActorStacks) { log("For actor stacks: " + stackQueueToString(forActorStacks), JSGLR2Logging.Parsing); } @Override public void actor(StackNode stack, ParseState parseState, Iterable<IAction> applicableActions) { log(" Actor for stack " + stackNodeString(stack) + " (applicable actions: " + applicableActionsToString(applicableActions) + ")", JSGLR2Logging.Parsing); } @Override public void skipRejectedStack(StackNode stack) { log(" Skipping stack " + stackNodeString(stack) + " since all links to it are rejected", JSGLR2Logging.Parsing); } @Override public void breakDown(IIncrementalInputStack inputStack, BreakdownReason reason) { @SuppressWarnings("unchecked") ParseForest forest = (ParseForest) inputStack.getNode(); log(" Breaking down parse node " + id(forest) + ", reason: " + reason.message, JSGLR2Logging.Parsing); @SuppressWarnings("unchecked") ParseNode node = (ParseNode) forest; for(Derivation derivation : node.getDerivations()) { for(ParseForest parseForest : derivation.parseForests()) { id(parseForest); // Register the children of the broken-down parse node } } } @Override public void addForShifter(ForShifterElement<StackNode> forShifterElement) { log(" Add for shifter " + forShifterElementToString(forShifterElement), JSGLR2Logging.Parsing); } @Override public void doLimitedReductions(ParseState parseState, StackNode stack, IReduce reduce, StackLink<ParseForest, StackNode> link) { } @Override public void reducer(ParseState parseState, StackNode activeStack, StackNode originStack, IReduce reduce, ParseForest[] parseNodes, StackNode gotoStack) { log(" Reduce by production [" + reduce.production().descriptor() + "] (" + reduce.productionType().toString() + ") with parse nodes " + parseForestsToString(parseNodes) + ", target stack: " + stackNodeString(gotoStack), JSGLR2Logging.Parsing, conditional(JSGLR2Logging.Recovery, reduce.production().isRecovery())); } @Override public void reducerElkhound(StackNode stack, IReduce reduce, ParseForest[] parseNodes) { log(" Reduce (Elkhound) by production [" + reduce.production().descriptor() + "] (" + reduce.productionType().toString() + ") with parse nodes " + parseForestsToString(parseNodes), JSGLR2Logging.Parsing, conditional(JSGLR2Logging.Recovery, reduce.production().isRecovery())); } @Override public void directLinkFound(ParseState parseState, StackLink<ParseForest, StackNode> directLink) { log(" Direct link " + (directLink != null ? id(directLink) : "not") + " found", JSGLR2Logging.Parsing); } @Override public void accept(StackNode acceptingStack) { log(" Accept stack " + stackNodeString(acceptingStack), JSGLR2Logging.Parsing); } @Override public void createParseNode(ParseNode parseNode, IProduction production) { super.createParseNode(parseNode, production); log(" Create parse node " + id((ParseForest) parseNode) + " for production " + (production == null ? null : production.id()), JSGLR2Logging.Parsing); } @Override public void createDerivation(Derivation derivation, IProduction production, ParseForest[] parseNodes) { super.createDerivation(derivation, production, parseNodes); log(" Create derivation with parse nodes " + parseForestsToString(parseNodes), JSGLR2Logging.Parsing); } @Override public void createCharacterNode(ParseForest characterNode, int character) { super.createCharacterNode(characterNode, character); log(" Create character node " + id(characterNode) + " for character '" + characterToString(character) + "'", JSGLR2Logging.Parsing); } @Override public void addDerivation(ParseNode parseNode, Derivation derivation) { log(" Add derivation " + id(derivation) + " to parse node " + id((ParseForest) parseNode), JSGLR2Logging.Parsing); } @Override public void shifter(ParseForest termNode, Queue<ForShifterElement<StackNode>> forShifter) { log(" Shifter for elements " + forShifterQueueToString(forShifter) + " with character node " + id(termNode), JSGLR2Logging.Parsing); } @Override public void startRecovery(ParseState parseState) { log(" Recovery started at offset " + parseState.inputStack.offset(), JSGLR2Logging.Recovery); } @Override public void recoveryIteration(ParseState parseState) { log(" Recovery iteration " + ((IRecoveryParseState) parseState).recoveryJob().iteration, JSGLR2Logging.Recovery); } @Override public void endRecovery(ParseState parseState) { log(" Recovery ended at offset " + parseState.inputStack.offset(), JSGLR2Logging.Recovery); } @Override public void remark(String remark) { log(remark, JSGLR2Logging.All); } @Override public void success(ParseSuccess<ParseForest> success) { log("Parsing succeeded " + timing(success.parseState.request), JSGLR2Logging.Parsing, JSGLR2Logging.Minimal); } @Override public void failure(ParseFailure<ParseForest> failure) { log("Parsing failed " + timing(failure.parseState.request), JSGLR2Logging.Parsing, JSGLR2Logging.Minimal); } private String timing(JSGLR2Request request) { return "(in " + (System.currentTimeMillis() - startTimes.get(request)) + "ms)"; } private String characterToString(int character) { return CharacterClassFactory.intToString(character).replace("\n", "\\n").replace("\r", "\\r").replace("\t", "\\t"); } private JSGLR2Logging conditional(JSGLR2Logging scope, boolean condition) { if(condition) return scope; else return JSGLR2Logging.None; } private void log(String message, JSGLR2Logging... eventJSGLR2Loggings) { for(JSGLR2Logging scope : scopes) { if(scope == JSGLR2Logging.All) { logger.accept(message); return; } for(JSGLR2Logging eventJSGLR2Logging : eventJSGLR2Loggings) { if(scope == eventJSGLR2Logging || eventJSGLR2Logging == JSGLR2Logging.Minimal) { logger.accept(message); return; } } } } }
package info.justaway.view; import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Matrix; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.util.FloatMath; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.widget.ImageView; public class ScaleImageView extends ImageView implements OnTouchListener { private Activity mActivity; private Context mContext; private float MAX_SCALE = 10f; private Matrix mMatrix; private final float[] mMatrixValues = new float[9]; // display width height. private int mWidth; private int mHeight; private int mIntrinsicWidth; private int mIntrinsicHeight; private float mScale; private float mMinScale; private float mPrevDistance; private boolean mIsScaling; private boolean mIsInitializedScaling; private int mPrevMoveX; private int mPrevMoveY; private GestureDetector mDetector; public ScaleImageView(Context context, AttributeSet attr) { super(context, attr); this.mContext = context; initialize(); } public void setActivity(Activity activity) { this.mActivity = activity; } public ScaleImageView(Context context) { super(context); this.mContext = context; initialize(); } @Override public void setImageBitmap(Bitmap bm) { super.setImageBitmap(bm); this.initialize(); } @Override public void setImageDrawable(Drawable drawable) { super.setImageDrawable(drawable); this.initialize(); } @Override public void setImageResource(int resId) { super.setImageResource(resId); this.initialize(); } private void initialize() { this.setScaleType(ScaleType.MATRIX); this.mMatrix = new Matrix(); Drawable d = getDrawable(); if (d != null) { mIntrinsicWidth = d.getIntrinsicWidth(); mIntrinsicHeight = d.getIntrinsicHeight(); setOnTouchListener(this); } mDetector = new GestureDetector(mContext, new GestureDetector.SimpleOnGestureListener() { @Override public boolean onDoubleTap(MotionEvent e) { maxZoomTo((int) e.getX(), (int) e.getY()); cutting(); return super.onDoubleTap(e); } @Override public void onLongPress(MotionEvent e) { if (mActivity != null) { mActivity.openOptionsMenu(); } super.onLongPress(e); } }); } @Override protected boolean setFrame(int l, int t, int r, int b) { mWidth = r - l; mHeight = b - t; mMatrix.reset(); int r_norm = r - l; mScale = (float) r_norm / (float) mIntrinsicWidth; int paddingHeight; int paddingWidth; // scaling vertical if (mScale * mIntrinsicHeight > mHeight) { mScale = (float) mHeight / (float) mIntrinsicHeight; mMatrix.postScale(mScale, mScale); paddingWidth = (r - mWidth) / 2; paddingHeight = 0; // scaling horizontal } else { mMatrix.postScale(mScale, mScale); paddingHeight = (b - mHeight) / 2; paddingWidth = 0; } mMatrix.postTranslate(paddingWidth, paddingHeight); setImageMatrix(mMatrix); if (!mIsInitializedScaling) { mIsInitializedScaling = true; zoomTo(mScale, mWidth / 2, mHeight / 2); } cutting(); Boolean isChanges = super.setFrame(l, t, r, b); if (mMinScale != mScale) { mMinScale = mScale; isChanges = true; } return isChanges; } protected float getValue(Matrix matrix, int whichValue) { matrix.getValues(mMatrixValues); return mMatrixValues[whichValue]; } protected float getScale() { return getValue(mMatrix, Matrix.MSCALE_X); } public float getTranslateX() { return getValue(mMatrix, Matrix.MTRANS_X); } protected float getTranslateY() { return getValue(mMatrix, Matrix.MTRANS_Y); } protected void maxZoomTo(int x, int y) { if (mMinScale != getScale() && (getScale() - mMinScale) > 0.1f) { // threshold 0.1f float scale = mMinScale / getScale(); zoomTo(scale, x, y); } else { float scale = 2f / getScale(); zoomTo(scale, x, y); } } public void zoomTo(float scale, int x, int y) { if (getScale() * scale < mMinScale) { return; } if (scale >= 1 && getScale() * scale > MAX_SCALE) { return; } mMatrix.postScale(scale, scale); // move to center mMatrix.postTranslate(-(mWidth * scale - mWidth) / 2, -(mHeight * scale - mHeight) / 2); // move x and y distance mMatrix.postTranslate(-(x - (mWidth / 2)) * scale, 0); mMatrix.postTranslate(0, -(y - (mHeight / 2)) * scale); setImageMatrix(mMatrix); } public void cutting() { int width = (int) (mIntrinsicWidth * getScale()); int height = (int) (mIntrinsicHeight * getScale()); if (getTranslateX() < -(width - mWidth)) { mMatrix.postTranslate(-(getTranslateX() + width - mWidth), 0); } if (getTranslateX() > 0) { mMatrix.postTranslate(-getTranslateX(), 0); } if (getTranslateY() < -(height - mHeight)) { mMatrix.postTranslate(0, -(getTranslateY() + height - mHeight)); } if (getTranslateY() > 0) { mMatrix.postTranslate(0, -getTranslateY()); } if (width < mWidth) { mMatrix.postTranslate((mWidth - width) / 2, 0); } if (height < mHeight) { mMatrix.postTranslate(0, (mHeight - height) / 2); } setImageMatrix(mMatrix); } private float distance(float x0, float x1, float y0, float y1) { float x = x0 - x1; float y = y0 - y1; return FloatMath.sqrt(x * x + y * y); } private float displayDistance() { return FloatMath.sqrt(mWidth * mWidth + mHeight * mHeight); } @Override public boolean onTouchEvent(MotionEvent event) { if (mDetector.onTouchEvent(event)) { return true; } int touchCount = event.getPointerCount(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_POINTER_1_DOWN: case MotionEvent.ACTION_POINTER_2_DOWN: if (touchCount >= 2) { float distance = distance(event.getX(0), event.getX(1), event.getY(0), event.getY(1)); mPrevDistance = distance; mIsScaling = true; } else { mPrevMoveX = (int) event.getX(); mPrevMoveY = (int) event.getY(); } case MotionEvent.ACTION_MOVE: if (touchCount >= 2 && mIsScaling) { float dist = distance(event.getX(0), event.getX(1), event.getY(0), event.getY(1)); float scale = (dist - mPrevDistance) / displayDistance(); mPrevDistance = dist; scale += 1; scale = scale * scale; zoomTo(scale, mWidth / 2, mHeight / 2); cutting(); } else if (!mIsScaling) { int distanceX = mPrevMoveX - (int) event.getX(); int distanceY = mPrevMoveY - (int) event.getY(); mPrevMoveX = (int) event.getX(); mPrevMoveY = (int) event.getY(); mMatrix.postTranslate(-distanceX, -distanceY); cutting(); } break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: case MotionEvent.ACTION_POINTER_2_UP: if (event.getPointerCount() <= 1) { mIsScaling = false; } break; } return true; } @Override public boolean onTouch(View v, MotionEvent event) { return super.onTouchEvent(event); } }
package edu.kit.informatik.kachelung; import sun.reflect.generics.reflectiveObjects.NotImplementedException; public class Tile { /** * Represents the size of the codification array for the tiles used in the game */ public static final int NUMBER_ELEMENTS = 6; /** * Represents the codification of the connection lines in the tile */ private LineType[] lineTypes; public void setLineTypes(LineType[] lineTypes) { this.lineTypes = lineTypes; } //region A.2 //A.2.1 /** * Initializes a new instance of {@linkplain Tile} using a specific codification of connection lines * @param lineTypes The codification of the connection lines to use. * {@code LineTypes.length} is {@linkplain #NUMBER_ELEMENTS} */ public Tile(LineType[] lineTypes) { this.lineTypes = lineTypes; } //A.2.2 /** * Initializes a new instance of {@linkplain Tile} that doesn't contains any connection lines */ public Tile() { lineTypes = new LineType[NUMBER_ELEMENTS]; for (int i = 0; i < NUMBER_ELEMENTS; i++) { lineTypes[i] = LineType.NONE; } } /** * * @param index A number between {@code 0} and {@linkplain #NUMBER_ELEMENTS}{@code -1} * @return The value of {@link #lineTypes} at the given index */ public LineType getLineTypeAtIndex(int index) { return lineTypes[index]; } //A.2.4 /** * Counts the different colors of the connection lines in the tile * @return A number between 0 and 3 */ public int getNumberOfColors() { return getColors().length; } private LineType[] getColors() { LineType[] colors = new LineType[2]; throw new NotImplementedException(); // return colors; } //A.2.5 /** * * @param otherTile * @return */ public boolean isExactlyEqualTo(Tile otherTile) { boolean isEqual = true; for (int i = 0; i < NUMBER_ELEMENTS; i++) { if (this.lineTypes[i] != otherTile.getLineTypeAtIndex(i)) { isEqual = false; break; } } return isEqual; } //A.2.6 /** * * @return */ public Tile copy() { LineType[] copyArray = new LineType[NUMBER_ELEMENTS]; for (int i = 0; i < NUMBER_ELEMENTS; i++) { copyArray[i] = lineTypes[i]; } return new Tile(copyArray); } //A.2.7 public void rotateClockwise() { LineType lastElement = lineTypes[NUMBER_ELEMENTS - 1]; for (int i = NUMBER_ELEMENTS - 1; i > 0; i //copy the content in the "i"-cell to the previous one lineTypes[i] = lineTypes[i - 1]; } lineTypes[0] = lastElement; } //A.2.8 public void rotateCounterClockwise() { LineType firstElement = lineTypes[0]; for (int i = 0; i <= NUMBER_ELEMENTS - 2; i++) { lineTypes[i] = lineTypes[i + 1]; } lineTypes[NUMBER_ELEMENTS - 1] = firstElement; } //A.2.9 /** * * @return {@code True} if the object contains no connection lines. {@code False} otherwise */ public boolean isEmpty() { boolean isEmpty = true; for (int i = 0; i < NUMBER_ELEMENTS; i++) { if (this.lineTypes[i] != LineType.NONE) { isEmpty = false; break; } } return isEmpty; } //A.2.10 /** * * @param otherTile * @return */ public boolean isRotationEqualTo(Tile otherTile) { Tile clone = this.copy(); boolean rotationIsEqualToOther = false; for (int i = 0; i <= NUMBER_ELEMENTS - 2; i++) { if (clone.isExactlyEqualTo(otherTile)) { rotationIsEqualToOther = true; break; } } return rotationIsEqualToOther; } //A.2.11 public boolean canBeRecoloredTo(Tile otherTile) { throw new NotImplementedException(); } //A.2.12 public boolean dominates(Tile otherTile) { throw new NotImplementedException(); } //A.2.13 public boolean hasSameColorsAs(Tile otherTile) { throw new NotImplementedException(); } //A.2.14 public String toString() { StringBuilder builder = new StringBuilder(); for (LineType element : lineTypes) { builder.append(element.getAbbreviation()); } return builder.toString(); } //endregion A.2 //region A.3 //A.3.1 /** * * @param otherTile * @param position A value between {@code 0} and {@linkplain #NUMBER_ELEMENTS}{@code -1} * @return */ public boolean fitsTo(Tile otherTile, int position) { int reflectedPosition = reflectPosition(position); return lineTypes[position].fitsTo(otherTile.getLineTypeAtIndex(reflectedPosition)); } /** * Calculates a mirrored position inside a tile. * Support method for {@linkplain Tile#fitsTo(Tile, int)}. * @param position A value between {@code 0} and {@linkplain #NUMBER_ELEMENTS}{@code -1} * @return The mirrored position in relation to the given value */ private int reflectPosition(int position) { return (position + NUMBER_ELEMENTS / 2 ) % NUMBER_ELEMENTS; } //endregion A.3 }
package com.chiralbehaviors.CoRE.phantasm.graphql; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import org.junit.Before; import org.junit.Test; import com.chiralbehaviors.CoRE.jooq.enums.ExistentialDomain; import com.chiralbehaviors.CoRE.meta.models.AbstractModelTest; import com.chiralbehaviors.CoRE.meta.workspace.WorkspaceAccessor; import com.chiralbehaviors.CoRE.meta.workspace.WorkspaceScope; import com.chiralbehaviors.CoRE.meta.workspace.dsl.WorkspaceImporter; import com.chiralbehaviors.CoRE.phantasm.resource.test.location.MavenArtifact; import com.chiralbehaviors.CoRE.phantasm.resource.test.product.Thing1; import com.chiralbehaviors.CoRE.phantasm.resource.test.product.Thing2; import com.chiralbehaviors.CoRE.phantasm.resource.test.product.Thing3; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import graphql.ExecutionResult; import graphql.schema.GraphQLSchema; /** * @author hhildebrand * */ public class FacetTypeTest extends AbstractModelTest { @Before public void initializeScope() throws IOException { WorkspaceImporter.manifest(FacetTypeTest.class.getResourceAsStream("/thing.wsp"), model); } @SuppressWarnings("unchecked") @Test public void testCreateAndMutate() throws Exception { String[] newAliases = new String[] { "jones", "smith" }; String newUri = "new iri"; MavenArtifact artifact1 = model.construct(MavenArtifact.class, ExistentialDomain.Location, "core", "core artifact"); artifact1.setArtifactID("com.chiralbehaviors.CoRE"); artifact1.setArtifactID("core"); artifact1.setVersion("0.0.2-SNAPSHOT"); artifact1.setType("jar"); MavenArtifact artifact2 = model.construct(MavenArtifact.class, ExistentialDomain.Location, "animations", "animations artifact"); artifact2.setArtifactID("com.chiralbehaviors.CoRE"); artifact2.setArtifactID("animations"); artifact2.setVersion("0.0.2-SNAPSHOT"); artifact2.setType("jar"); WorkspaceScope scope = model.getWorkspaceModel() .getScoped(WorkspaceAccessor.uuidOf(THING_URI)); GraphQLSchema schema = new WorkspaceSchema().build(scope.getWorkspace(), model); Map<String, Object> variables = new HashMap<>(); variables.put("artifact", artifact1.getRuleform() .getId() .toString()); variables.put("name", "hello"); variables.put("description", "goodbye"); QueryRequest request = new QueryRequest("mutation m ($name: String!, $description: String, $artifact: String) { createThing1(state: { setName: $name, setDescription: $description, setDerivedFrom: $artifact}) { id name description } }", variables); ExecutionResult execute = new WorkspaceContext(model, scope.getWorkspace() .getDefiningProduct()).execute(schema, request.getQuery(), request.getVariables()); assertTrue(execute.getErrors() .toString(), execute.getErrors() .isEmpty()); Map<String, Object> result = (Map<String, Object>) execute.getData(); Map<String, Object> thing1Result = (Map<String, Object>) result.get("createThing1"); assertNotNull(thing1Result); assertEquals("hello", thing1Result.get("name")); Thing1 thing1 = model.wrap(Thing1.class, model.records() .resolve(UUID.fromString((String) thing1Result.get("id")))); assertNotNull(thing1); assertEquals(artifact1, thing1.getDerivedFrom()); variables = new HashMap<>(); variables.put("id", thing1.getRuleform() .getId() .toString()); variables.put("artifact", artifact2.getRuleform() .getId() .toString()); variables.put("aliases", Arrays.asList(newAliases)); variables.put("name", "hello"); variables.put("uri", newUri); request = new QueryRequest("mutation m($id: String!, $name: String!, $artifact: String, $aliases: [String], $uri: String) { updateThing1(state: { id: $id, setName: $name, setDerivedFrom: $artifact, setAliases: $aliases, setURI: $uri}) { id name } }", variables); execute = new WorkspaceContext(model, scope.getWorkspace() .getDefiningProduct()).execute(schema, request.getQuery(), request.getVariables()); assertTrue(execute.getErrors() .toString(), execute.getErrors() .isEmpty()); result = (Map<String, Object>) execute.getData(); thing1Result = (Map<String, Object>) result.get("updateThing1"); assertNotNull(thing1Result); assertEquals("hello", thing1Result.get("name")); thing1 = model.wrap(Thing1.class, model.records() .resolve(UUID.fromString((String) thing1Result.get("id")))); assertNotNull(thing1); assertEquals(artifact2, thing1.getDerivedFrom()); assertArrayEquals(newAliases, thing1.getAliases()); assertEquals(newUri, thing1.getURI()); variables = new HashMap<>(); variables.put("thing1", thing1.getRuleform() .getId() .toString()); variables.put("artifact", artifact2.getRuleform() .getId() .toString()); variables.put("name", "hello"); request = new QueryRequest("mutation m($name: String!, $artifact: String, $thing1: String!) { \n" + "createThing2(state: {setName: $name, \n" + "addDerivedFrom: $artifact, \n" + "setThing1: $thing1}) { id name } }", variables); execute = new WorkspaceContext(model, scope.getWorkspace() .getDefiningProduct()).execute(schema, request.getQuery(), request.getVariables()); assertTrue(execute.getErrors() .toString(), execute.getErrors() .isEmpty()); result = (Map<String, Object>) execute.getData(); } @Test public void testIntrospection() throws Exception { Thing1 thing1 = model.construct(Thing1.class, ExistentialDomain.Product, "test", "testy"); GraphQLSchema schema = new WorkspaceSchema().build(thing1.getScope() .getWorkspace(), model); String query = getIntrospectionQuery(); ExecutionResult execute = new WorkspaceContext(model, thing1.getScope() .getWorkspace() .getDefiningProduct()).execute(schema, query); assertTrue(execute.getErrors() .toString(), execute.getErrors() .isEmpty()); JsonNode result = new ObjectMapper().convertValue(execute.getData(), JsonNode.class); assertNotNull(result); } @Test public void testMutation() throws Exception { String[] newAliases = new String[] { "jones", "smith" }; String newUri = "new iri"; Thing1 thing1 = model.construct(Thing1.class, ExistentialDomain.Product, "test", "testy"); Thing2 thing2 = model.construct(Thing2.class, ExistentialDomain.Product, "tester", "testier"); Thing3 thing3 = model.construct(Thing3.class, ExistentialDomain.Product, "Thingy", "a favorite thing"); MavenArtifact artifact = model.construct(MavenArtifact.class, ExistentialDomain.Location, "model", "model artifact"); artifact.setArtifactID("com.chiralbehaviors.CoRE"); artifact.setArtifactID("model"); artifact.setVersion("0.0.2-SNAPSHOT"); artifact.setType("jar"); MavenArtifact artifact2 = model.construct(MavenArtifact.class, ExistentialDomain.Location, "animations", "animations artifact"); artifact2.setArtifactID("com.chiralbehaviors.CoRE"); artifact2.setArtifactID("animations"); artifact2.setVersion("0.0.2-SNAPSHOT"); artifact2.setType("jar"); thing1.setAliases(new String[] { "smith", "jones" }); String uri = "http://example.com"; thing1.setURI(uri); thing1.setDerivedFrom(artifact); thing1.setThing2(thing2); thing2.addThing3(thing3); thing3.addDerivedFrom(artifact); thing3.addDerivedFrom(artifact2); WorkspaceScope scope = model.getWorkspaceModel() .getScoped(WorkspaceAccessor.uuidOf(THING_URI)); GraphQLSchema schema = new WorkspaceSchema().build(scope.getWorkspace(), model); Map<String, Object> variables = new HashMap<>(); variables.put("id", thing1.getRuleform() .getId() .toString()); variables.put("artifact", artifact2.getRuleform() .getId() .toString()); variables.put("aliases", Arrays.asList(newAliases)); variables.put("name", "hello"); variables.put("uri", newUri); QueryRequest request = new QueryRequest("mutation m($id: String!, $name: String!, $artifact: String!, $aliases: [String], $uri: String) { updateThing1(state: { id: $id, setName: $name, setDerivedFrom: $artifact, setAliases: $aliases, setURI: $uri}) { name } }", variables); ExecutionResult execute = new WorkspaceContext(model, scope.getWorkspace() .getDefiningProduct()).execute(schema, request.getQuery(), request.getVariables()); assertTrue(execute.getErrors() .toString(), execute.getErrors() .isEmpty()); @SuppressWarnings("unchecked") Map<String, Object> result = (Map<String, Object>) execute.getData(); thing1.getRuleform() .refresh(); assertEquals("hello", thing1.getName()); @SuppressWarnings("unchecked") Map<String, Object> thing1Result = (Map<String, Object>) result.get("updateThing1"); assertNotNull(thing1Result); assertEquals(thing1.getName(), thing1Result.get("name")); assertEquals(artifact2, thing1.getDerivedFrom()); assertArrayEquals(newAliases, thing1.getAliases()); assertEquals(newUri, thing1.getURI()); } @SuppressWarnings("unchecked") @Test public void testWorkspaceSchema() throws Exception { Thing1 thing1 = model.construct(Thing1.class, ExistentialDomain.Product, "test", "testy"); Thing2 thing2 = model.construct(Thing2.class, ExistentialDomain.Product, "tester", "testier"); Thing3 thing3 = model.construct(Thing3.class, ExistentialDomain.Product, "Thingy", "a favorite thing"); MavenArtifact artifact = model.construct(MavenArtifact.class, ExistentialDomain.Location, "model", "model artifact"); artifact.setArtifactID("com.chiralbehaviors.CoRE"); artifact.setArtifactID("model"); artifact.setVersion("0.0.2-SNAPSHOT"); artifact.setType("jar"); MavenArtifact artifact2 = model.construct(MavenArtifact.class, ExistentialDomain.Location, "animations", "animations artifact"); artifact2.setArtifactID("com.chiralbehaviors.CoRE"); artifact2.setArtifactID("animations"); artifact2.setVersion("0.0.2-SNAPSHOT"); artifact2.setType("jar"); thing1.setAliases(new String[] { "smith", "jones" }); String uri = "http://example.com"; thing1.setURI(uri); thing1.setDerivedFrom(artifact); thing1.setThing2(thing2); thing2.addThing3(thing3); thing3.addDerivedFrom(artifact); thing3.addDerivedFrom(artifact2); GraphQLSchema schema = new WorkspaceSchema().build(thing1.getScope() .getWorkspace(), model); Map<String, Object> variables = new HashMap<>(); variables.put("id", thing1.getRuleform() .getId() .toString()); String query = "query it($id: String!) { thing1(id: $id) {id name thing2 {id name thing3s {id name derivedFroms {id name}}} derivedFrom {id name}}}"; ExecutionResult execute = new WorkspaceContext(model, thing1.getScope() .getWorkspace() .getDefiningProduct()).execute(schema, query, variables); assertTrue(execute.getErrors() .toString(), execute.getErrors() .isEmpty()); Map<String, Object> result = (Map<String, Object>) execute.getData(); assertNotNull(result); Map<String, Object> thing1Result = (Map<String, Object>) result.get("thing1"); assertNotNull(thing1Result); assertEquals(thing1.getName(), thing1Result.get("name")); assertEquals(thing1.getRuleform() .getId() .toString(), thing1Result.get("id")); Map<String, Object> thing2Result = (Map<String, Object>) thing1Result.get("thing2"); assertNotNull(thing2Result); assertEquals(thing2.getName(), thing2Result.get("name")); assertEquals(thing2.getRuleform() .getId() .toString(), thing2Result.get("id")); List<Map<String, Object>> thing3s = (List<Map<String, Object>>) thing2Result.get("thing3s"); assertNotNull(thing3s); assertEquals(1, thing3s.size()); Map<String, Object> thing3Result = thing3s.get(0); assertEquals(thing3.getName(), thing3Result.get("name")); assertEquals(thing3.getRuleform() .getId() .toString(), thing3Result.get("id")); List<Map<String, Object>> thing3DerivedFroms = (List<Map<String, Object>>) thing3Result.get("derivedFroms"); assertNotNull(thing3DerivedFroms); assertEquals(2, thing3DerivedFroms.size()); String q = "{ thing1s {id name URI}}"; result = (Map<String, Object>) new WorkspaceContext(model, thing1.getScope() .getWorkspace() .getDefiningProduct()).execute(schema, q) .getData(); List<Map<String, Object>> instances = (List<Map<String, Object>>) result.get("thing1s"); assertEquals(1, instances.size()); Map<String, Object> instance = instances.get(0); assertEquals(thing1.getName(), instance.get("name")); assertEquals(thing1.getRuleform() .getId() .toString(), instance.get("id")); assertEquals(uri, instance.get("URI")); } @Test public void testCreate() throws Exception { Thing2 thing2 = model.construct(Thing2.class, ExistentialDomain.Product, "tester", "testier"); Thing3 thing3 = model.construct(Thing3.class, ExistentialDomain.Product, "Thingy", "a favorite thing"); MavenArtifact artifact = model.construct(MavenArtifact.class, ExistentialDomain.Location, "model", "model artifact"); artifact.setArtifactID("com.chiralbehaviors.CoRE"); artifact.setArtifactID("model"); artifact.setVersion("0.0.2-SNAPSHOT"); artifact.setType("jar"); MavenArtifact artifact2 = model.construct(MavenArtifact.class, ExistentialDomain.Location, "animations", "animations artifact"); artifact2.setArtifactID("com.chiralbehaviors.CoRE"); artifact2.setArtifactID("animations"); artifact2.setVersion("0.0.2-SNAPSHOT"); artifact2.setType("jar"); thing2.addThing3(thing3); thing3.addDerivedFrom(artifact); thing3.addDerivedFrom(artifact2); WorkspaceScope scope = model.getWorkspaceModel() .getScoped(WorkspaceAccessor.uuidOf(THING_URI)); GraphQLSchema schema = new WorkspaceSchema().build(scope.getWorkspace(), model); Map<String, Object> variables = new HashMap<>(); variables.put("artifact", artifact2.getRuleform() .getId() .toString()); variables.put("name", "hello"); variables.put("description", "goodbye"); QueryRequest request = new QueryRequest("mutation m ($name: String!, $description: String, $artifact: String) { createThing1(state: { setName: $name, setDescription: $description, setDerivedFrom: $artifact}) { id name } }", variables); ExecutionResult execute = new WorkspaceContext(model, scope.getWorkspace() .getDefiningProduct()).execute(schema, request.getQuery(), request.getVariables()); assertTrue(execute.getErrors() .toString(), execute.getErrors() .isEmpty()); @SuppressWarnings("unchecked") Map<String, Object> result = (Map<String, Object>) execute.getData(); @SuppressWarnings("unchecked") Map<String, Object> thing1Result = (Map<String, Object>) result.get("createThing1"); assertNotNull(thing1Result); assertEquals("hello", thing1Result.get("name")); } @Test public void testCasting() throws Exception { Thing1 thing1 = model.construct(Thing1.class, ExistentialDomain.Product, "test", "testy"); Thing2 thing2 = model.construct(Thing2.class, ExistentialDomain.Product, "tester", "testier"); Thing3 thing3 = model.construct(Thing3.class, ExistentialDomain.Product, "Thingy", "a favorite thing"); thing1.setThing2(thing2); thing2.addThing3(thing3); WorkspaceScope scope = model.getWorkspaceModel() .getScoped(WorkspaceAccessor.uuidOf(THING_URI)); GraphQLSchema schema = new WorkspaceSchema().build(scope.getWorkspace(), model); Map<String, Object> variables = new HashMap<>(); variables.put("id", thing1.getRuleform() .getId() .toString()); variables.put("thing3", thing3.getRuleform() .getId() .toString()); QueryRequest request = new QueryRequest("mutation m($id: String!, $thing3: String!) { updateThing1(state: { id: $id, setThing2: $thing3}) { name } }", variables); ExecutionResult execute = new WorkspaceContext(model, scope.getWorkspace() .getDefiningProduct()).execute(schema, request.getQuery(), request.getVariables()); assertEquals(execute.getErrors() .toString(), 1, execute.getErrors() .size()); assertTrue(execute.getErrors() .get(0) .getMessage() .contains("ClassCastException")); } private String getIntrospectionQuery() throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[16 * 4096]; try (InputStream in = getClass().getResourceAsStream("/introspection-query")) { for (int read = in.read(buf); read != -1; read = in.read(buf)) { baos.write(buf, 0, read); } } return baos.toString(); } }
package io.flutter.logging.tree; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import com.intellij.execution.filters.Filter; import com.intellij.execution.filters.HyperlinkInfo; import com.intellij.openapi.project.Project; import com.intellij.ui.components.panels.NonOpaquePanel; import com.intellij.ui.tree.BaseTreeModel; import com.intellij.util.EventDispatcher; import com.intellij.util.ui.JBUI; import io.flutter.inspector.DiagnosticLevel; import io.flutter.inspector.DiagnosticsNode; import io.flutter.inspector.DiagnosticsTreeStyle; import io.flutter.logging.FlutterLogEntry; import io.flutter.logging.FlutterLogEntryParser.LineHandler; import io.flutter.logging.text.StyledText; import io.flutter.utils.JsonUtils; import io.flutter.view.InspectorColoredTreeCellRenderer; import org.jetbrains.annotations.NotNull; import javax.swing.*; import javax.swing.event.HyperlinkEvent; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.text.html.HTMLEditorKit; import javax.swing.tree.TreeCellRenderer; import javax.swing.tree.TreePath; import java.awt.*; import java.awt.event.*; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.EventListener; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import static com.intellij.ui.SimpleTextAttributes.REGULAR_ATTRIBUTES; import static io.flutter.utils.HtmlBuilder.*; @SuppressWarnings("ALL") public class DataPanel extends JPanel { public static interface ContentListener extends EventListener { void hasContent(boolean hasContent); } /* * Swing's support for CSS is limited and doesn't allow for multiple classes so we cons * together css styling as a single style attribute. * * These values are loosely derived from devtools/inspector.css. * * TODO(pq): add theme-awareness. */ private static class CssStyle { static String forNode(DiagnosticsNode node) { return attr("style", forLevel(node.getLevel()) + forStyle(node.getStyle())); } static String forLevel(DiagnosticLevel level) { switch (level) { case info: return "padding-left: 16px; "; case error: return "color: rgb(244, 67, 54); padding-left: 16px; "; case hint: return "background-color: #fafad2; padding: 8px 8px 8px 24px; margin: 5px 0; "; default: return ""; } } static String forStyle(DiagnosticsTreeStyle style) { switch (style) { case error: return "background-color: #f97c7c; padding: 12px; margin:5px 0; "; default: return ""; } } } class NodeRenderer extends InspectorColoredTreeCellRenderer { private final List<Filter> filters; public NodeRenderer(List<Filter> filters) { super(); this.filters = filters; } @Override public void customizeCellRenderer(@NotNull JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { if (value instanceof String) { appendStyledText(value.toString()); } else if (value instanceof DiagnosticsNode) { final DiagnosticsNode node = (DiagnosticsNode)value; if (!node.isProperty()) { final Icon icon = node.getIcon(); if (icon != null) { setIcon(icon); } } appendStyledText(value.toString()); } } void appendStyledText(@NotNull String line) { final LineHandler lineHandler = new LineHandler(filters, null); final List<StyledText> styledTexts = lineHandler.parseLineStyle(line); for (StyledText styledText : styledTexts) { append(styledText.getText(), styledText.getStyle() != null ? styledText.getStyle() : REGULAR_ATTRIBUTES, styledText.getTag()); } } } // TODO(pq): consider a model shared w/ the inspector tree. class NodeModel extends BaseTreeModel<Object> { private final DiagnosticsNode node; private final String rootContent; public NodeModel(DiagnosticsNode node, String rootContent) { this.node = node; this.rootContent = rootContent; } @Override public List<? extends Object> getChildren(Object parent) { if (parent instanceof DiagnosticsNode) { return DataPanel.getChildren((DiagnosticsNode)parent); } if (parent == rootContent) { return DataPanel.getChildren(node); } return null; } @Override public Object getRoot() { return rootContent; } } static class MouseHandler extends MouseAdapter implements MouseMotionListener { @NotNull private final JTree tree; @NotNull private final Project project; MouseHandler(@NotNull JTree tree, @NotNull Project project) { this.tree = tree; this.project = project; } @Override public void mouseMoved(MouseEvent e) { final Cursor cursor = getTagForPosition(e) instanceof HyperlinkInfo ? Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) : Cursor.getDefaultCursor(); tree.setCursor(cursor); } @Override public void mouseClicked(MouseEvent e) { final Object tag = getTagForPosition(e); if (tag instanceof HyperlinkInfo) { ((HyperlinkInfo)tag).navigate(project); } } private Object getTagForPosition(MouseEvent e) { final JTree tree = (JTree)e.getSource(); final TreeCellRenderer cellRenderer = tree.getCellRenderer(); if (cellRenderer instanceof InspectorColoredTreeCellRenderer) { final InspectorColoredTreeCellRenderer renderer = (InspectorColoredTreeCellRenderer)cellRenderer; final TreePath treePath = tree.getPathForLocation(e.getX(), e.getY()); final Rectangle pathBounds = tree.getPathBounds(treePath); if (pathBounds != null) { final int x = e.getX() - pathBounds.x; return renderer.getFragmentTagAt(x); } } return null; } } private final Gson gsonHelper = new GsonBuilder().setPrettyPrinting().create(); private final HTMLEditorKit editorKit; private final EventDispatcher<ContentListener> dispatcher = EventDispatcher.create(ContentListener.class); private final Project project; private FlutterLogEntry entry; private DataPanel(Project project) { this.project = project; setBorder(JBUI.Borders.empty()); editorKit = new HTMLEditorKit(); } public static DataPanel create(@NotNull Project project) { final DataPanel panel = new DataPanel(project); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); return panel; } public void onUpdate(@NotNull ContentListener listener) { dispatcher.addListener(listener); } private void linkSelected(URL url) { // TODO(pq): handle html links } public void update(@NotNull FlutterLogEntry entry) { // Avoid unneeded updates. if (entry == this.entry) { return; } this.entry = entry; final Object data = entry.getData(); // Remove stale content. for (Component c : getComponents()) { remove(c); } boolean showDataPane = false; if (data instanceof DiagnosticsNode) { showDataPane = updateNodeData((DiagnosticsNode)data); } else if (data instanceof String && JsonUtils.hasJsonData((String)data)) { showDataPane = updateJsonTextData((String)data); } showPane(showDataPane); } private void showPane(boolean show) { setVisible(show); if (show) { repaint(); revalidate(); } dispatcher.getMulticaster().hasContent(show); // TODO(pq): set caret position // Scroll to start. // setCaretPosition(0); } private boolean updateJsonTextData(String data) { @SuppressWarnings("ConstantConditions") final JsonElement jsonElement = new JsonParser().parse((String)data); final String text = gsonHelper.toJson(jsonElement); if (text.isEmpty()) { return false; } final JEditorPane editorPane = createEditorPane(); editorPane.setText(html(pre(text))); add(editorPane); return true; } private boolean updateNodeData(DiagnosticsNode data) { // Header. addText(data.toString(), data); // Body. final List<DiagnosticsNode> properties = data.getInlineProperties(); for (DiagnosticsNode node : properties) { // TODO(pq): refactor to handle edge cases and consider parsing into a list of StyledTexts. String contents = ""; if (node.getName() != null) { contents += node.getName(); } final List<DiagnosticsNode> children = getChildren(node); if (!children.isEmpty() || node.getDescription() != null) { if (!contents.isEmpty()) { contents += ": "; } if (node.getDescription() != null) { contents += node.getDescription(); } } if (children.isEmpty()) { addText(contents, node); } else { addTree(contents, node); } } return true; } private void addText(String contents, DiagnosticsNode node) { final JEditorPane editorPane = createEditorPane(); editorPane.setText(html( div( CssStyle.forNode(node), span(contents) ))); add(editorPane); } private void addTree(String rootLabel, DiagnosticsNode node) { final JTree tree = new JTree(); tree.setModel(new NodeModel(node, rootLabel)); tree.setCellRenderer(new NodeRenderer(entry.getFilters())); tree.setShowsRootHandles(true); tree.collapseRow(0); tree.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { tree.clearSelection(); } }); tree.addTreeSelectionListener(new TreeSelectionListener() { @Override public void valueChanged(TreeSelectionEvent e) { selectionChanged(tree); } }); final MouseHandler mouseHandler = new MouseHandler(tree, project); tree.addMouseListener(mouseHandler); tree.addMouseMotionListener(mouseHandler); final NonOpaquePanel panel = new NonOpaquePanel(); panel.add(tree); add(panel); } private void selectionChanged(@NotNull JTree tree) { final Object pathComponent = tree.getLastSelectedPathComponent(); if (pathComponent instanceof DiagnosticsNode) { final DiagnosticsNode diagnostics = (DiagnosticsNode)pathComponent; diagnostics.setSelection(diagnostics.getValueRef(), false); } } private JEditorPane createEditorPane() { final JEditorPane editorPane = new JEditorPane(); editorPane.setEditable(false); editorPane.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, true); editorPane.setEditorKit(editorKit); editorPane.addHyperlinkListener(e -> { if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { linkSelected(e.getURL()); } }); return editorPane; } private static List<DiagnosticsNode> getChildren(DiagnosticsNode node) { final ArrayList<DiagnosticsNode> children = node.getChildren().getNow(new ArrayList<>()); return Stream.of(children, node.getInlineProperties()).flatMap(Collection::stream).collect(Collectors.toList()); } }
package edu.miamioh.cse283.htw; import java.io.IOException; import java.net.*; import java.util.*; import java.util.regex.*; /** * The CaveServer class takes the following command-line parameters: * <p/> * <Hostname of CaveSystemServer> <port number of CaveSystemServer> <port number of this CaveServer> * <p/> * E.g., "localhost 1234 2000" */ public class CaveServer { /** * Port base for this cave server. */ protected int portBase; /** * Socket for accepting connections from players. */ protected ServerSocket clientSocket; /** * Proxy to the CaveSystemServer. */ protected CaveSystemServerProxy caveSystem; /** * Random number generator (used to pick caves for players). */ protected Random rng; /** * Rooms in this CaveServer. */ protected ArrayList<Room> rooms; /** * Constructor. */ public CaveServer(CaveSystemServerProxy caveSystem, int portBase) { this.caveSystem = caveSystem; this.portBase = portBase; this.rng = new Random(); // locations for hazards int[] hazards = Utils.nRand(7, 20); // construct the rooms: rooms = new ArrayList<Room>(); for (int i = 0; i < 20; ++i) { int contents = Room.EMPTY; if (i == hazards[0]) { contents = Room.WUMPUS; } else if (i == hazards[1]) { contents = Room.HOLE; } else if (i == hazards[2]) { contents = Room.BATS; } else if (i == hazards[3]) { contents = Room.GOLD; } else if (i == hazards[4]) { contents = Room.GOLD; } else if (i == hazards[5]) { contents = Room.ARROWS; } else if (i == hazards[6]) { contents = Room.ARROWS; } rooms.add(new Room(contents, this)); } // connect them to each other: for (int i = 0; i < 20; ++i) { rooms.get(i).connectRoom(rooms.get((i + 1) % 20)); rooms.get(i).connectRoom(rooms.get((i + 2) % 20)); } // and give them random ids: HashSet<Integer> ids = new HashSet<Integer>(); for (int i = 0; i < 20; ++i) { int r = rng.nextInt(100); while (ids.contains(r)) { r = rng.nextInt(100); } rooms.get(i).setIdNumber(r); } } public Room randomRoom() { int index = rng.nextInt(rooms.size()); return rooms.get(index); } /** * Returns the port number to use for accepting client connections. */ public int getClientPort() { return portBase; } /** * Returns an initial room for a client. */ public synchronized Room getInitialRoom() { return rooms.get(rng.nextInt(rooms.size())); } /** * This is the thread that handles a single client connection. */ public class ClientThread implements Runnable { /** * This is our "client" (actually, a proxy to the network-connected client). */ protected ClientProxy client; /** * Notification messages. */ protected ArrayList<String> notifications; /** * Constructor. */ public ClientThread(ClientProxy client) { this.client = client; this.notifications = new ArrayList<String>(); } /** * Returns true if there are notifications that should be sent to this client. */ public synchronized boolean hasNotifications() { return !notifications.isEmpty(); } /** * Returns and resets notification messages. */ public synchronized ArrayList<String> getNotifications() { ArrayList<String> t = notifications; notifications = new ArrayList<String>(); return t; } /** * Play the game with this client. */ public void run() { try { // the first time a player connects, send a welcome message: ArrayList<String> welcome = new ArrayList<String>(); welcome.add("Welcome!"); client.sendNotifications(welcome); // Put the player in an initial room and send them their initial // sensory information: Room r = getInitialRoom(); client.changeRoom(r); // while the player is alive, listen for commands from the player // and for activities elsewhere in the cave: try { while (true) { // poll, waiting for input from client or other notifications: while (!client.ready() && !hasNotifications() && client.isAlive()) { try { Thread.sleep(50); } catch (InterruptedException ex) { } } // if there are notifications, send them: if (hasNotifications()) { client.sendNotifications(getNotifications()); } // if the player is dead, send the DIED message and break: if (!client.isAlive()) { break; } // if the player did something, respond to it: if (client.ready()) { String line = client.nextLine().trim(); try { dispatch(line); } catch (ClientQuitException e) { break; } } } } finally { // make sure the client leaves whichever room they're in, // and close the client's socket: client.close(); } } catch (Exception ex) { // If an exception is thrown, we can't fix it here -- Crash. ex.printStackTrace(); System.exit(1); } } private void dispatch(String line) throws ClientQuitException { Matcher action = Protocol.ACTION_PATTERN.matcher(line); if (action.matches()) { int actionNumber = Integer.parseInt(action.group(1)); int roomNumber; Room tempRoom; switch (actionNumber) { case Protocol.MOVE: // move the player: split out the room number, move the player, etc. // client has to leave the room: r.leaveRoom(client) // and enter the new room: newRoom.enterRoom(client) // send the client new senses here: client.sendSenses(r.getSensed()); roomNumber = Integer.parseInt(action.group(2)); tempRoom = client.getCurrentRoom().getRoom(roomNumber); if (tempRoom != null) { client.changeRoom(tempRoom); } else { notifications.add("Invalid room number."); } break; case Protocol.CLIMB: // climb the ladder, if the player is in a room with a ladder. // send a notification telling the player his score // and some kind of congratulations, and then kill // the player to end the game -- call kill(), above. break; case Protocol.SHOOT: // shoot an arrow: split out the room number into which the arrow // is to be shot, and then send an arrow into the right series of // rooms. roomNumber = Integer.parseInt(action.group(2)); tempRoom = client.getCurrentRoom().getRoom(roomNumber); tempRoom.shoot(client); break; case Protocol.PICKUP: // pickup gold / arrows. tempRoom = client.getCurrentRoom(); tempRoom.pickup(client); break; } } else if (line.startsWith(Protocol.QUIT)) { // no response: drop gold and arrows, and break. throw new ClientQuitException(); } else { // invalid response; send the client some kind of error message // (as a notificiation). } } } /** * Runs the CaveSystemServer. */ public void run() { try { // first thing we need to do is register this CaveServer // with the CaveSystemServer: clientSocket = new ServerSocket(getClientPort()); caveSystem.register(clientSocket); System.out.println("CaveServer registered"); // then, loop forever accepting Client connections: while (true) { ClientProxy client = new ClientProxy(clientSocket.accept()); System.out.println("Client connected"); (new Thread(new ClientThread(client))).start(); } } catch (Exception ex) { ex.printStackTrace(); System.exit(1); } } /** * Main method (run the CaveServer). */ public static void main(String[] args) { try { InetAddress addr = InetAddress.getByName("localhost"); int cssPortBase = 1234; int cavePortBase = 2000; if (args.length > 0) { addr = InetAddress.getByName(args[0]); cssPortBase = Integer.parseInt(args[1]); cavePortBase = Integer.parseInt(args[2]); } // first, we need our proxy object to the CaveSystemServer: CaveSystemServerProxy caveSystem = new CaveSystemServerProxy(new Socket(addr, cssPortBase + 1)); // now construct this cave server, and run it: CaveServer cs = new CaveServer(caveSystem, cavePortBase); cs.run(); } catch (IOException ex) { ex.printStackTrace(); } } /** * Returns the Room with the given ID number, or NULL if one doesn't exist * * @param index the ID number to search for * @return Room with the given ID number, or NULL if one doesn't exist */ private Room getRoomByNumber(int index) { for (int i = 0; i < rooms.size(); i++) { Room r = rooms.get(i); if (r.getIdNumber() == index) { return r; } } return null; } }
package sk.henrichg.phoneprofiles; import android.app.Activity; import android.app.KeyguardManager; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.media.Ringtone; import android.media.RingtoneManager; import android.net.Uri; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.Preference.OnPreferenceChangeListener; import android.preference.PreferenceManager; import android.preference.PreferenceScreen; import android.telephony.TelephonyManager; import android.text.Spannable; import android.text.SpannableString; import android.text.style.CharacterStyle; import android.text.style.StyleSpan; import android.text.style.UnderlineSpan; import com.fnp.materialpreferences.PreferenceFragment; public class ProfilePreferencesNestedFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener { protected PreferenceManager prefMng; protected SharedPreferences preferences; private Context context; static final String PREFS_NAME_ACTIVITY = "profile_preferences_activity"; static final String PREFS_NAME_FRAGMENT = "profile_preferences_fragment"; static final String PREFS_NAME_DEFAULT_PROFILE = GlobalData.DEFAULT_PROFILE_PREFS_NAME; static final String PREF_NOTIFICATION_ACCESS = "prf_pref_volumeNotificationsAccessSettings"; static final int RESULT_NOTIFICATION_ACCESS_SETTINGS = 1980; static final String PREF_UNLINK_VOLUMES_APP_PREFERENCES = "prf_pref_volumeUnlinkVolumesAppSettings"; @Override public int addPreferencesFromResource() { return -1; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // this is really important in order to save the state across screen // configuration changes for example setRetainInstance(false); context = getActivity().getBaseContext(); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); String PREFS_NAME; if (ProfilePreferencesFragment.startupSource == GlobalData.PREFERENCES_STARTUP_SOURCE_ACTIVITY) PREFS_NAME = PREFS_NAME_ACTIVITY; else if (ProfilePreferencesFragment.startupSource == GlobalData.PREFERENCES_STARTUP_SOURCE_FRAGMENT) PREFS_NAME = PREFS_NAME_FRAGMENT; else if (ProfilePreferencesFragment.startupSource == GlobalData.PREFERENCES_STARTUP_SOURCE_DEFAUT_PROFILE) PREFS_NAME = PREFS_NAME_DEFAULT_PROFILE; else PREFS_NAME = PREFS_NAME_FRAGMENT; prefMng = getPreferenceManager(); prefMng.setSharedPreferencesName(PREFS_NAME); prefMng.setSharedPreferencesMode(Activity.MODE_PRIVATE); preferences = prefMng.getSharedPreferences(); preferences.registerOnSharedPreferenceChangeListener(this); if (android.os.Build.VERSION.SDK_INT >= 21) { ListPreference ringerModePreference = (ListPreference) prefMng.findPreference(GlobalData.PREF_PROFILE_VOLUME_RINGER_MODE); /* // add zen mode option to preference Ringer mode if (ringerModePreference.findIndexOfValue("5") < 0) { CharSequence[] entries = ringerModePreference.getEntries(); CharSequence[] entryValues = ringerModePreference.getEntryValues(); CharSequence[] newEntries = new CharSequence[entries.length + 1]; CharSequence[] newEntryValues = new CharSequence[entries.length + 1]; for (int i = 0; i < entries.length; i++) { newEntries[i] = entries[i]; newEntryValues[i] = entryValues[i]; } newEntries[entries.length] = context.getString(R.string.array_pref_ringerModeArray_ZenMode); newEntryValues[entries.length] = "5"; ringerModePreference.setEntries(newEntries); ringerModePreference.setEntryValues(newEntryValues); ringerModePreference.setValue(Integer.toString(profile._volumeRingerMode)); setSummary(GlobalData.PREF_PROFILE_VOLUME_RINGER_MODE, profile._volumeRingerMode); } */ /*final boolean canEnableZenMode = (PPNotificationListenerService.isNotificationListenerServiceEnabled(context.getApplicationContext()) || (GlobalData.isRooted(false) && GlobalData.settingsBinaryExists()) );*/ final boolean canEnableZenMode = GlobalData.canChangeZenMode(context.getApplicationContext(), true); Preference zenModePreference = prefMng.findPreference(GlobalData.PREF_PROFILE_VOLUME_ZEN_MODE); if (zenModePreference != null) { String value = preferences.getString(GlobalData.PREF_PROFILE_VOLUME_RINGER_MODE, ""); zenModePreference.setEnabled((value.equals("5")) && canEnableZenMode); } Preference notificationAccessPreference = prefMng.findPreference(PREF_NOTIFICATION_ACCESS); if (notificationAccessPreference != null) { if (android.os.Build.VERSION.SDK_INT >= 24) { PreferenceScreen preferenceCategory = (PreferenceScreen) findPreference("prf_pref_soundProfileCategory"); preferenceCategory.removePreference(notificationAccessPreference); } else { //notificationAccessPreference.setWidgetLayoutResource(R.layout.start_activity_preference); notificationAccessPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { Intent intent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"); startActivityForResult(intent, RESULT_NOTIFICATION_ACCESS_SETTINGS); return false; } }); } } Preference volumeUnlinkPreference = prefMng.findPreference(PREF_UNLINK_VOLUMES_APP_PREFERENCES); //volumeUnlinkPreference.setWidgetLayoutResource(R.layout.start_activity_preference); if (ringerModePreference != null) { ringerModePreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { String sNewValue = (String) newValue; int iNewValue; if (sNewValue.isEmpty()) iNewValue = 0; else iNewValue = Integer.parseInt(sNewValue); /*final boolean canEnableZenMode = (PPNotificationListenerService.isNotificationListenerServiceEnabled(context.getApplicationContext()) || (GlobalData.isRooted(false) && GlobalData.settingsBinaryExists()) );*/ final boolean canEnableZenMode = GlobalData.canChangeZenMode(context.getApplicationContext(), true); Preference zenModePreference = prefMng.findPreference(GlobalData.PREF_PROFILE_VOLUME_ZEN_MODE); zenModePreference.setEnabled((iNewValue == 5) && canEnableZenMode); setTitleStyle(zenModePreference, false, false); return true; } }); } } else { // remove zen mode preferences from preferences screen // for Android version < 5.0 this is not supported Preference preference = prefMng.findPreference(GlobalData.PREF_PROFILE_VOLUME_ZEN_MODE); if (preference != null) { PreferenceScreen preferenceCategory = (PreferenceScreen) findPreference("prf_pref_soundProfileCategory"); preferenceCategory.removePreference(preference); } preference = prefMng.findPreference(PREF_NOTIFICATION_ACCESS); if (preference != null) { PreferenceScreen preferenceCategory = (PreferenceScreen) findPreference("prf_pref_soundProfileCategory"); preferenceCategory.removePreference(preference); } preference = prefMng.findPreference(GlobalData.PREF_PROFILE_VIBRATE_WHEN_RINGING); if (preference != null) { PreferenceScreen preferenceCategory = (PreferenceScreen) findPreference("prf_pref_soundProfileCategory"); preferenceCategory.removePreference(preference); } } if (android.os.Build.VERSION.SDK_INT < 23) { Preference preference = (Preference) prefMng.findPreference("prf_pref_volumeVibrateWhenRingingRootInfo"); if (preference != null) { PreferenceScreen preferenceCategory = (PreferenceScreen) findPreference("prf_pref_soundProfileCategory"); preferenceCategory.removePreference(preference); } } else { Preference preference = prefMng.findPreference(GlobalData.PREF_PROFILE_VIBRATE_WHEN_RINGING); if (preference != null) { preference.setTitle("(R) " + getString(R.string.profile_preferences_vibrateWhenRinging)); String value = preferences.getString(GlobalData.PREF_PROFILE_VIBRATE_WHEN_RINGING, ""); setSummary(GlobalData.PREF_PROFILE_VIBRATE_WHEN_RINGING, value); } } if (android.os.Build.VERSION.SDK_INT < 24) { Preference preference = (Preference) prefMng.findPreference(GlobalData.PREF_PROFILE_DEVICE_WALLPAPER_FOR); if (preference != null) { PreferenceScreen preferenceCategory = (PreferenceScreen) findPreference("prf_pref_othersCategory"); preferenceCategory.removePreference(preference); } } if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) { ListPreference networkTypePreference = (ListPreference) prefMng.findPreference(GlobalData.PREF_PROFILE_DEVICE_NETWORK_TYPE); if (networkTypePreference != null) { final TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); final int phoneType = telephonyManager.getPhoneType(); if (phoneType == TelephonyManager.PHONE_TYPE_GSM) { if (ProfilePreferencesFragment.startupSource == GlobalData.PREFERENCES_STARTUP_SOURCE_DEFAUT_PROFILE) { networkTypePreference.setEntries(context.getResources().getStringArray(R.array.networkTypeGSMDPArray)); networkTypePreference.setEntryValues(context.getResources().getStringArray(R.array.networkTypeGSMDPValues)); } else { networkTypePreference.setEntries(context.getResources().getStringArray(R.array.networkTypeGSMArray)); networkTypePreference.setEntryValues(context.getResources().getStringArray(R.array.networkTypeGSMValues)); } String value = preferences.getString(GlobalData.PREF_PROFILE_DEVICE_NETWORK_TYPE, ""); networkTypePreference.setValue(value); setSummary(GlobalData.PREF_PROFILE_DEVICE_NETWORK_TYPE, value); } if (phoneType == TelephonyManager.PHONE_TYPE_CDMA) { if (ProfilePreferencesFragment.startupSource == GlobalData.PREFERENCES_STARTUP_SOURCE_DEFAUT_PROFILE) { networkTypePreference.setEntries(context.getResources().getStringArray(R.array.networkTypeCDMADPArray)); networkTypePreference.setEntryValues(context.getResources().getStringArray(R.array.networkTypeCDMADPValues)); } else { networkTypePreference.setEntries(context.getResources().getStringArray(R.array.networkTypeCDMAArray)); networkTypePreference.setEntryValues(context.getResources().getStringArray(R.array.networkTypeCDMAValues)); } String value = preferences.getString(GlobalData.PREF_PROFILE_DEVICE_NETWORK_TYPE, ""); networkTypePreference.setValue(value); setSummary(GlobalData.PREF_PROFILE_DEVICE_NETWORK_TYPE, value); } } } } @Override public void onDestroy() { preferences.unregisterOnSharedPreferenceChangeListener(this); super.onDestroy(); } public void doOnActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == ImageViewPreference.RESULT_LOAD_IMAGE && resultCode == Activity.RESULT_OK && data != null) { Uri selectedImage = data.getData(); String picturePath = ImageViewPreference.getPath(context, selectedImage); if (ProfilePreferencesFragment.changedImageViewPreference != null) // nastavime image identifikatoru na ziskanu cestu ku obrazku ProfilePreferencesFragment.changedImageViewPreference.setImageIdentifierAndType(picturePath, false); } if (requestCode == ProfileIconPreference.RESULT_LOAD_IMAGE && resultCode == Activity.RESULT_OK && data != null) { Uri selectedImage = data.getData(); String picturePath = ImageViewPreference.getPath(context, selectedImage); if (ProfilePreferencesFragment.changedProfileIconPreference != null) // nastavime image identifikatoru na ziskanu cestu ku obrazku ProfilePreferencesFragment.changedProfileIconPreference.setImageIdentifierAndType(picturePath, false, true); } if (requestCode == RESULT_NOTIFICATION_ACCESS_SETTINGS) { /*final boolean canEnableZenMode = (PPNotificationListenerService.isNotificationListenerServiceEnabled(context.getApplicationContext()) || (GlobalData.isRooted(false) && GlobalData.settingsBinaryExists()) );*/ final String sZenModeType = preferences.getString(GlobalData.PREF_PROFILE_VOLUME_ZEN_MODE, ""); setSummary(GlobalData.PREF_PROFILE_VOLUME_ZEN_MODE, sZenModeType); } if (requestCode == ApplicationsDialogPreference.RESULT_APPLICATIONS_EDITOR && resultCode == Activity.RESULT_OK && data != null) { if (ProfilePreferencesFragment.applicationsDialogPreference != null) { ProfilePreferencesFragment.applicationsDialogPreference.updateShortcut( (Intent)data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT), data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME), (Bitmap)data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON), data.getIntExtra(LaunchShortcutActivity.EXTRA_DIALOG_PREFERENCE_POSITION, -1)); } } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); doOnActivityResult(requestCode, resultCode, data); } private void setTitleStyle(Preference preference, boolean bold, boolean underline) { CharSequence title = preference.getTitle(); Spannable sbt = new SpannableString(title); Object spansToRemove[] = sbt.getSpans(0, title.length(), Object.class); for(Object span: spansToRemove){ if(span instanceof CharacterStyle) sbt.removeSpan(span); } if (bold || underline) { if (bold) sbt.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, title.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); if (underline) sbt.setSpan(new UnderlineSpan(), 0, title.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); preference.setTitle(sbt); } else { preference.setTitle(sbt); } } private String getTitleWhenPreferenceChanged(String key) { Preference preference = prefMng.findPreference(key); String title = ""; if ((preference != null) && (preference.isEnabled())) { if (key.equals(GlobalData.PREF_PROFILE_ASK_FOR_DURATION)) { boolean defaultValue = getResources().getBoolean( GlobalData.getResourceId(preference.getKey(), "bool", context)); if (preferences.getBoolean(key, defaultValue) != defaultValue) title = preference.getTitle().toString(); } else { String defaultValue = getResources().getString( GlobalData.getResourceId(preference.getKey(), "string", context)); if (preference instanceof VolumeDialogPreference) { if (VolumeDialogPreference.changeEnabled(preferences.getString(preference.getKey(), defaultValue))) title = preference.getTitle().toString(); } else if (preference instanceof BrightnessDialogPreference) { if (BrightnessDialogPreference.changeEnabled(preferences.getString(preference.getKey(), defaultValue))) title = preference.getTitle().toString(); } else { if (!preferences.getString(preference.getKey(), defaultValue).equals(defaultValue)) title = preference.getTitle().toString(); } } return title; } else return title; } private void setCategorySummary(Preference preference, boolean bold) { String key = preference.getKey(); boolean _bold = bold; Preference preferenceScreen = null; String summary = ""; if (key.equals(GlobalData.PREF_PROFILE_DURATION) || key.equals(GlobalData.PREF_PROFILE_AFTER_DURATION_DO) || key.equals(GlobalData.PREF_PROFILE_ASK_FOR_DURATION)) { String title = getTitleWhenPreferenceChanged(GlobalData.PREF_PROFILE_DURATION); String afterDurationDoTitle = getTitleWhenPreferenceChanged(GlobalData.PREF_PROFILE_AFTER_DURATION_DO); if ((!afterDurationDoTitle.isEmpty()) && (!title.isEmpty())) { _bold = true; summary = summary + title + " • "; summary = summary + afterDurationDoTitle; } title = getTitleWhenPreferenceChanged(GlobalData.PREF_PROFILE_ASK_FOR_DURATION); if (!title.isEmpty()) { _bold = true; if (!summary.isEmpty()) summary = summary +" • "; summary = summary + title; } preferenceScreen = prefMng.findPreference("prf_pref_activationDurationCategory"); } if (key.equals(GlobalData.PREF_PROFILE_VOLUME_RINGER_MODE) || key.equals(GlobalData.PREF_PROFILE_VOLUME_ZEN_MODE) || key.equals(GlobalData.PREF_PROFILE_VIBRATION_ON_TOUCH) || key.equals(GlobalData.PREF_PROFILE_VIBRATE_WHEN_RINGING)) { String title = getTitleWhenPreferenceChanged(GlobalData.PREF_PROFILE_VOLUME_RINGER_MODE); if (!title.isEmpty()) { _bold = true; summary = summary + title; } title = getTitleWhenPreferenceChanged(GlobalData.PREF_PROFILE_VOLUME_ZEN_MODE); if (!title.isEmpty()) { _bold = true; if (!summary.isEmpty()) summary = summary +" • "; summary = summary + title; } title = getTitleWhenPreferenceChanged(GlobalData.PREF_PROFILE_VIBRATE_WHEN_RINGING); if (!title.isEmpty()) { _bold = true; if (!summary.isEmpty()) summary = summary +" • "; summary = summary + title; } title = getTitleWhenPreferenceChanged(GlobalData.PREF_PROFILE_VIBRATION_ON_TOUCH); if (!title.isEmpty()) { _bold = true; if (!summary.isEmpty()) summary = summary +" • "; summary = summary + title; } preferenceScreen = prefMng.findPreference("prf_pref_soundProfileCategory"); } if (key.equals(GlobalData.PREF_PROFILE_VOLUME_RINGTONE) || key.equals(GlobalData.PREF_PROFILE_VOLUME_NOTIFICATION) || key.equals(GlobalData.PREF_PROFILE_VOLUME_MEDIA) || key.equals(GlobalData.PREF_PROFILE_VOLUME_ALARM) || key.equals(GlobalData.PREF_PROFILE_VOLUME_SYSTEM) || key.equals(GlobalData.PREF_PROFILE_VOLUME_VOICE) || key.equals(GlobalData.PREF_PROFILE_VOLUME_SPEAKER_PHONE)) { String title = getTitleWhenPreferenceChanged(GlobalData.PREF_PROFILE_VOLUME_RINGTONE); if (!title.isEmpty()) { _bold = true; summary = summary + title; } title = getTitleWhenPreferenceChanged(GlobalData.PREF_PROFILE_VOLUME_NOTIFICATION); if (!title.isEmpty()) { _bold = true; if (!summary.isEmpty()) summary = summary +" • "; summary = summary + title; } title = getTitleWhenPreferenceChanged(GlobalData.PREF_PROFILE_VOLUME_MEDIA); if (!title.isEmpty()) { _bold = true; if (!summary.isEmpty()) summary = summary +" • "; summary = summary + title; } title = getTitleWhenPreferenceChanged(GlobalData.PREF_PROFILE_VOLUME_ALARM); if (!title.isEmpty()) { _bold = true; if (!summary.isEmpty()) summary = summary +" • "; summary = summary + title; } title = getTitleWhenPreferenceChanged(GlobalData.PREF_PROFILE_VOLUME_SYSTEM); if (!title.isEmpty()) { _bold = true; if (!summary.isEmpty()) summary = summary +" • "; summary = summary + title; } title = getTitleWhenPreferenceChanged(GlobalData.PREF_PROFILE_VOLUME_VOICE); if (!title.isEmpty()) { _bold = true; if (!summary.isEmpty()) summary = summary +" • "; summary = summary + title; } title = getTitleWhenPreferenceChanged(GlobalData.PREF_PROFILE_VOLUME_SPEAKER_PHONE); if (!title.isEmpty()) { _bold = true; if (!summary.isEmpty()) summary = summary +" • "; summary = summary + title; } preferenceScreen = prefMng.findPreference("prf_pref_volumeCategory"); } if (key.equals(GlobalData.PREF_PROFILE_SOUND_RINGTONE_CHANGE) || //key.equals(GlobalData.PREF_PROFILE_SOUND_RINGTONE) || key.equals(GlobalData.PREF_PROFILE_SOUND_NOTIFICATION_CHANGE) || //key.equals(GlobalData.PREF_PROFILE_SOUND_NOTIFICATION) || key.equals(GlobalData.PREF_PROFILE_SOUND_ALARM_CHANGE)) { //key.equals(GlobalData.PREF_PROFILE_SOUND_ALARM)) { String title = getTitleWhenPreferenceChanged(GlobalData.PREF_PROFILE_SOUND_RINGTONE_CHANGE); if (!title.isEmpty()) { _bold = true; summary = summary + title; } //_bold = _bold || isBold(GlobalData.PREF_PROFILE_SOUND_RINGTONE); title = getTitleWhenPreferenceChanged(GlobalData.PREF_PROFILE_SOUND_NOTIFICATION_CHANGE); if (!title.isEmpty()) { _bold = true; if (!summary.isEmpty()) summary = summary +" • "; summary = summary + title; } //_bold = _bold || isBold(GlobalData.PREF_PROFILE_SOUND_NOTIFICATION); title = getTitleWhenPreferenceChanged(GlobalData.PREF_PROFILE_SOUND_ALARM_CHANGE); if (!title.isEmpty()) { _bold = true; if (!summary.isEmpty()) summary = summary +" • "; summary = summary + title; } //_bold = _bold || isBold(GlobalData.PREF_PROFILE_SOUND_ALARM); preferenceScreen = prefMng.findPreference("prf_pref_soundsCategory"); } if (key.equals(GlobalData.PREF_PROFILE_DEVICE_AIRPLANE_MODE) || key.equals(GlobalData.PREF_PROFILE_DEVICE_AUTOSYNC) || key.equals(GlobalData.PREF_PROFILE_DEVICE_MOBILE_DATA) || key.equals(GlobalData.PREF_PROFILE_DEVICE_MOBILE_DATA_PREFS) || key.equals(GlobalData.PREF_PROFILE_DEVICE_WIFI) || key.equals(GlobalData.PREF_PROFILE_DEVICE_WIFI_AP) || key.equals(GlobalData.PREF_PROFILE_DEVICE_BLUETOOTH) || key.equals(GlobalData.PREF_PROFILE_DEVICE_GPS) || key.equals(GlobalData.PREF_PROFILE_DEVICE_LOCATION_SERVICE_PREFS) || key.equals(GlobalData.PREF_PROFILE_DEVICE_NFC) || key.equals(GlobalData.PREF_PROFILE_DEVICE_NETWORK_TYPE)) { String title = getTitleWhenPreferenceChanged(GlobalData.PREF_PROFILE_DEVICE_AIRPLANE_MODE); if (!title.isEmpty()) { _bold = true; summary = summary + title; } title = getTitleWhenPreferenceChanged(GlobalData.PREF_PROFILE_DEVICE_AUTOSYNC); if (!title.isEmpty()) { _bold = true; if (!summary.isEmpty()) summary = summary +" • "; summary = summary + title; } title = getTitleWhenPreferenceChanged(GlobalData.PREF_PROFILE_DEVICE_NETWORK_TYPE); if (!title.isEmpty()) { _bold = true; if (!summary.isEmpty()) summary = summary +" • "; summary = summary + title; } title = getTitleWhenPreferenceChanged(GlobalData.PREF_PROFILE_DEVICE_MOBILE_DATA); if (!title.isEmpty()) { _bold = true; if (!summary.isEmpty()) summary = summary +" • "; summary = summary + title; } title = getTitleWhenPreferenceChanged(GlobalData.PREF_PROFILE_DEVICE_MOBILE_DATA_PREFS); if (!title.isEmpty()) { _bold = true; if (!summary.isEmpty()) summary = summary +" • "; summary = summary + title; } title = getTitleWhenPreferenceChanged(GlobalData.PREF_PROFILE_DEVICE_WIFI); if (!title.isEmpty()) { _bold = true; if (!summary.isEmpty()) summary = summary +" • "; summary = summary + title; } title = getTitleWhenPreferenceChanged(GlobalData.PREF_PROFILE_DEVICE_WIFI_AP); if (!title.isEmpty()) { _bold = true; if (!summary.isEmpty()) summary = summary +" • "; summary = summary + title; } title = getTitleWhenPreferenceChanged(GlobalData.PREF_PROFILE_DEVICE_BLUETOOTH); if (!title.isEmpty()) { _bold = true; if (!summary.isEmpty()) summary = summary +" • "; summary = summary + title; } title = getTitleWhenPreferenceChanged(GlobalData.PREF_PROFILE_DEVICE_GPS); if (!title.isEmpty()) { _bold = true; if (!summary.isEmpty()) summary = summary +" • "; summary = summary + title; } title = getTitleWhenPreferenceChanged(GlobalData.PREF_PROFILE_DEVICE_LOCATION_SERVICE_PREFS); if (!title.isEmpty()) { _bold = true; if (!summary.isEmpty()) summary = summary +" • "; summary = summary + title; } title = getTitleWhenPreferenceChanged(GlobalData.PREF_PROFILE_DEVICE_NFC); if (!title.isEmpty()) { _bold = true; if (!summary.isEmpty()) summary = summary +" • "; summary = summary + title; } preferenceScreen = prefMng.findPreference("prf_pref_radiosCategory"); } if (key.equals(GlobalData.PREF_PROFILE_DEVICE_SCREEN_TIMEOUT) || key.equals(GlobalData.PREF_PROFILE_DEVICE_KEYGUARD) || key.equals(GlobalData.PREF_PROFILE_DEVICE_BRIGHTNESS) || key.equals(GlobalData.PREF_PROFILE_DEVICE_AUTOROTATE) || key.equals(GlobalData.PREF_PROFILE_NOTIFICATION_LED)) { String title = getTitleWhenPreferenceChanged(GlobalData.PREF_PROFILE_DEVICE_SCREEN_TIMEOUT); if (!title.isEmpty()) { _bold = true; summary = summary + title; } title = getTitleWhenPreferenceChanged(GlobalData.PREF_PROFILE_DEVICE_KEYGUARD); if (!title.isEmpty()) { _bold = true; if (!summary.isEmpty()) summary = summary +" • "; summary = summary + title; } title = getTitleWhenPreferenceChanged(GlobalData.PREF_PROFILE_DEVICE_BRIGHTNESS); if (!title.isEmpty()) { _bold = true; if (!summary.isEmpty()) summary = summary +" • "; summary = summary + title; } title = getTitleWhenPreferenceChanged(GlobalData.PREF_PROFILE_DEVICE_AUTOROTATE); if (!title.isEmpty()) { _bold = true; if (!summary.isEmpty()) summary = summary +" • "; summary = summary + title; } title = getTitleWhenPreferenceChanged(GlobalData.PREF_PROFILE_NOTIFICATION_LED); if (!title.isEmpty()) { _bold = true; if (!summary.isEmpty()) summary = summary +" • "; summary = summary + title; } preferenceScreen = prefMng.findPreference("prf_pref_screenCategory"); } if (key.equals(GlobalData.PREF_PROFILE_DEVICE_POWER_SAVE_MODE) || key.equals(GlobalData.PREF_PROFILE_DEVICE_RUN_APPLICATION_CHANGE) || //key.equals(GlobalData.PREF_PROFILE_DEVICE_RUN_APPLICATION_PACKAGE_NAME) || key.equals(GlobalData.PREF_PROFILE_DEVICE_WALLPAPER_CHANGE)) { //key.equals(GlobalData.PREF_PROFILE_DEVICE_WALLPAPER)) { String title = getTitleWhenPreferenceChanged(GlobalData.PREF_PROFILE_DEVICE_POWER_SAVE_MODE); if (!title.isEmpty()) { _bold = true; summary = summary + title; } title = getTitleWhenPreferenceChanged(GlobalData.PREF_PROFILE_DEVICE_RUN_APPLICATION_CHANGE); if (!title.isEmpty()) { _bold = true; if (!summary.isEmpty()) summary = summary +" • "; summary = summary + title; } //_bold = _bold || isBold(GlobalData.PREF_PROFILE_DEVICE_RUN_APPLICATION_PACKAGE_NAME); title = getTitleWhenPreferenceChanged(GlobalData.PREF_PROFILE_DEVICE_WALLPAPER_CHANGE); if (!title.isEmpty()) { _bold = true; if (!summary.isEmpty()) summary = summary +" • "; summary = summary + title; } //_bold = _bold || isBold(GlobalData.PREF_PROFILE_DEVICE_WALLPAPER); preferenceScreen = prefMng.findPreference("prf_pref_othersCategory"); } if (preferenceScreen != null) { setTitleStyle(preferenceScreen, _bold, false); if (_bold) preferenceScreen.setSummary(summary); else preferenceScreen.setSummary(""); } } private void setSummary(String key, Object value) { if (key.equals(GlobalData.PREF_PROFILE_VOLUME_UNLINK_VOLUMES_APP_SETTINGS)) { Preference preference = prefMng.findPreference(key); if (preference != null) { preference.setSummary(context.getResources().getString(R.string.menu_settings) + ": " + context.getResources().getString(R.string.phone_profiles_pref_applicationUnlinkRingerNotificationVolumes)); } } if (key.equals(GlobalData.PREF_PROFILE_NAME)) { Preference preference = prefMng.findPreference(key); if (preference != null) { preference.setSummary(value.toString()); setTitleStyle(preference, false, true); } } if (key.equals(GlobalData.PREF_PROFILE_VOLUME_RINGER_MODE)) { String sValue = value.toString(); ListPreference listPreference = (ListPreference)prefMng.findPreference(key); if (listPreference != null) { int index = listPreference.findIndexOfValue(sValue); CharSequence summary = (index >= 0) ? listPreference.getEntries()[index] : null; listPreference.setSummary(summary); setTitleStyle(listPreference, index > 0, false); setCategorySummary(listPreference, index > 0); } } if (key.equals(GlobalData.PREF_PROFILE_VOLUME_ZEN_MODE)) { if (android.os.Build.VERSION.SDK_INT >= 21) { /*final boolean canEnableZenMode = (PPNotificationListenerService.isNotificationListenerServiceEnabled(context.getApplicationContext()) || (GlobalData.isRooted(false) && GlobalData.settingsBinaryExists()) );*/ final boolean canEnableZenMode = GlobalData.canChangeZenMode(context.getApplicationContext(), true); if (!canEnableZenMode) { ListPreference listPreference = (ListPreference)prefMng.findPreference(key); if (listPreference != null) { listPreference.setEnabled(false); listPreference.setSummary(getResources().getString(R.string.profile_preferences_device_not_allowed)+ ": "+getResources().getString(R.string.preference_not_allowed_reason_not_supported)); setTitleStyle(listPreference, false, false); setCategorySummary(listPreference, false); } } else { String sValue = value.toString(); ListPreference listPreference = (ListPreference)prefMng.findPreference(key); if (listPreference != null) { int iValue = Integer.parseInt(sValue); int index = listPreference.findIndexOfValue(sValue); CharSequence summary = (index >= 0) ? listPreference.getEntries()[index] : null; if ((iValue != 0) && (iValue != 99)) { if (!((iValue == 6) && (android.os.Build.VERSION.SDK_INT < 23))) { String[] summaryArray = getResources().getStringArray(R.array.zenModeSummaryArray); summary = summary + " - " + summaryArray[iValue - 1]; } } listPreference.setSummary(summary); final String sRingerMode = preferences.getString(GlobalData.PREF_PROFILE_VOLUME_RINGER_MODE, ""); int iRingerMode; if (sRingerMode.isEmpty()) iRingerMode = 0; else iRingerMode = Integer.parseInt(sRingerMode); if (iRingerMode == 5) { setTitleStyle(listPreference, index > 0, false); setCategorySummary(listPreference, index > 0); } listPreference.setEnabled(iRingerMode == 5); } } } } if (key.equals(GlobalData.PREF_PROFILE_SOUND_RINGTONE_CHANGE) || key.equals(GlobalData.PREF_PROFILE_SOUND_NOTIFICATION_CHANGE) || key.equals(GlobalData.PREF_PROFILE_SOUND_ALARM_CHANGE)) { String sValue = value.toString(); ListPreference listPreference = (ListPreference)prefMng.findPreference(key); if (listPreference != null) { int index = listPreference.findIndexOfValue(sValue); CharSequence summary = (index >= 0) ? listPreference.getEntries()[index] : null; listPreference.setSummary(summary); setTitleStyle(listPreference, index > 0, false); setCategorySummary(listPreference, index > 0); } } if (key.equals(GlobalData.PREF_PROFILE_SOUND_RINGTONE) || key.equals(GlobalData.PREF_PROFILE_SOUND_NOTIFICATION) || key.equals(GlobalData.PREF_PROFILE_SOUND_ALARM)) { String ringtoneUri = value.toString(); Preference preference = prefMng.findPreference(key); if (preference != null) { if (ringtoneUri.isEmpty()) preference.setSummary(R.string.preferences_notificationSound_None); else { Uri uri = Uri.parse(ringtoneUri); Ringtone ringtone = RingtoneManager.getRingtone(context, uri); String ringtoneName; if (ringtone == null) ringtoneName = ""; else ringtoneName = ringtone.getTitle(context); preference.setSummary(ringtoneName); } } } if (key.equals(GlobalData.PREF_PROFILE_DEVICE_AIRPLANE_MODE) || key.equals(GlobalData.PREF_PROFILE_DEVICE_AUTOSYNC) || key.equals(GlobalData.PREF_PROFILE_DEVICE_WIFI) || key.equals(GlobalData.PREF_PROFILE_DEVICE_BLUETOOTH) || key.equals(GlobalData.PREF_PROFILE_DEVICE_MOBILE_DATA) || key.equals(GlobalData.PREF_PROFILE_DEVICE_MOBILE_DATA_PREFS) || key.equals(GlobalData.PREF_PROFILE_DEVICE_GPS) || key.equals(GlobalData.PREF_PROFILE_DEVICE_NFC) || key.equals(GlobalData.PREF_PROFILE_DEVICE_WIFI_AP) || key.equals(GlobalData.PREF_PROFILE_DEVICE_POWER_SAVE_MODE) || key.equals(GlobalData.PREF_PROFILE_DEVICE_NETWORK_TYPE)) { if (key.equals(GlobalData.PREF_PROFILE_DEVICE_MOBILE_DATA)) { // set mobile data preference title Preference mobileDataPreference = prefMng.findPreference(GlobalData.PREF_PROFILE_DEVICE_MOBILE_DATA); if (mobileDataPreference != null) { if (android.os.Build.VERSION.SDK_INT >= 21) { mobileDataPreference.setTitle(R.string.profile_preferences_deviceMobileData_21); } else { mobileDataPreference.setTitle(R.string.profile_preferences_deviceMobileData); } } } int canChange = GlobalData.isProfilePreferenceAllowed(key, context); if (canChange != GlobalData.PREFERENCE_ALLOWED) { ListPreference listPreference = (ListPreference)prefMng.findPreference(key); if (listPreference != null) { listPreference.setEnabled(false); if (canChange == GlobalData.PREFERENCE_NOT_ALLOWED) listPreference.setSummary(getResources().getString(R.string.profile_preferences_device_not_allowed)+ ": "+getResources().getString(GlobalData.getNotAllowedPreferenceReasonString())); setTitleStyle(listPreference, false, false); setCategorySummary(listPreference, false); } } else { String sValue = value.toString(); ListPreference listPreference = (ListPreference)prefMng.findPreference(key); if (listPreference != null) { int index = listPreference.findIndexOfValue(sValue); CharSequence summary = (index >= 0) ? listPreference.getEntries()[index] : null; listPreference.setSummary(summary); setTitleStyle(listPreference, index > 0, false); setCategorySummary(listPreference, index > 0); } } } if (key.equals(GlobalData.PREF_PROFILE_DEVICE_KEYGUARD)) { ListPreference listPreference = (ListPreference)prefMng.findPreference(key); if (listPreference != null) { boolean secureKeyguard; KeyguardManager keyguardManager = (KeyguardManager) context.getSystemService(Activity.KEYGUARD_SERVICE); if (android.os.Build.VERSION.SDK_INT >= 16) secureKeyguard = keyguardManager.isKeyguardSecure(); else secureKeyguard = keyguardManager.inKeyguardRestrictedInputMode(); listPreference.setEnabled(!secureKeyguard); if (secureKeyguard) { setTitleStyle(listPreference, false, false); setCategorySummary(listPreference, false); listPreference.setSummary(getResources().getString(R.string.profile_preferences_device_not_allowed)+ ": "+getResources().getString(R.string.preference_not_allowed_reason_not_supported)); } else { String sValue = value.toString(); int index = listPreference.findIndexOfValue(sValue); CharSequence summary = (index >= 0) ? listPreference.getEntries()[index] : null; listPreference.setSummary(summary); setTitleStyle(listPreference, index > 0, false); setCategorySummary(listPreference, index > 0); } } } if (key.equals(GlobalData.PREF_PROFILE_DEVICE_SCREEN_TIMEOUT)) { String sValue = value.toString(); ListPreference listPreference = (ListPreference)prefMng.findPreference(key); if (listPreference != null) { int index = listPreference.findIndexOfValue(sValue); CharSequence summary = (index >= 0) ? listPreference.getEntries()[index] : null; listPreference.setSummary(summary); setTitleStyle(listPreference, index > 0, false); setCategorySummary(listPreference, index > 0); } } if (key.equals(GlobalData.PREF_PROFILE_DEVICE_AUTOROTATE)) { String sValue = value.toString(); ListPreference listPreference = (ListPreference)prefMng.findPreference(key); if (listPreference != null) { int index = listPreference.findIndexOfValue(sValue); CharSequence summary = (index >= 0) ? listPreference.getEntries()[index] : null; listPreference.setSummary(summary); setTitleStyle(listPreference, index > 0, false); setCategorySummary(listPreference, index > 0); } } if (key.equals(GlobalData.PREF_PROFILE_DEVICE_WALLPAPER_CHANGE) || key.equals(GlobalData.PREF_PROFILE_DEVICE_MOBILE_DATA_PREFS) || key.equals(GlobalData.PREF_PROFILE_DEVICE_RUN_APPLICATION_CHANGE) || key.equals(GlobalData.PREF_PROFILE_DEVICE_LOCATION_SERVICE_PREFS) || key.equals(GlobalData.PREF_PROFILE_VOLUME_SPEAKER_PHONE) || key.equals(GlobalData.PREF_PROFILE_VIBRATION_ON_TOUCH) || key.equals(GlobalData.PREF_PROFILE_VIBRATE_WHEN_RINGING) || key.equals(GlobalData.PREF_PROFILE_DEVICE_WALLPAPER_FOR)) { String sValue = value.toString(); ListPreference listPreference = (ListPreference)prefMng.findPreference(key); if (listPreference != null) { int index = listPreference.findIndexOfValue(sValue); CharSequence summary = (index >= 0) ? listPreference.getEntries()[index] : null; listPreference.setSummary(summary); setTitleStyle(listPreference, index > 0, false); setCategorySummary(listPreference, index > 0); } } if (key.equals(GlobalData.PREF_PROFILE_NOTIFICATION_LED)) { ListPreference listPreference = (ListPreference) prefMng.findPreference(key); if (listPreference != null) { if (android.os.Build.VERSION.SDK_INT >= 23) { listPreference.setTitle(R.string.profile_preferences_notificationLed_23); } else { listPreference.setTitle(R.string.profile_preferences_notificationLed); } int canChange = GlobalData.isProfilePreferenceAllowed(key, context); if (canChange != GlobalData.PREFERENCE_ALLOWED) { listPreference.setEnabled(false); if (canChange == GlobalData.PREFERENCE_NOT_ALLOWED) listPreference.setSummary(getResources().getString(R.string.profile_preferences_device_not_allowed)+ ": "+getResources().getString(GlobalData.getNotAllowedPreferenceReasonString())); setTitleStyle(listPreference, false, false); setCategorySummary(listPreference, false); } else { String sValue = value.toString(); int index = listPreference.findIndexOfValue(sValue); CharSequence summary = (index >= 0) ? listPreference.getEntries()[index] : null; listPreference.setSummary(summary); setTitleStyle(listPreference, index > 0, false); setCategorySummary(listPreference, index > 0); } } } if (key.equals(GlobalData.PREF_PROFILE_DURATION)) { Preference preference = prefMng.findPreference(key); if (preference != null) { String sValue = value.toString(); int iValue = 0; if (!sValue.isEmpty()) iValue = Integer.valueOf(sValue); //preference.setSummary(sValue); setTitleStyle(preference, iValue > 0, false); setCategorySummary(preference, iValue > 0); } } if (key.equals(GlobalData.PREF_PROFILE_AFTER_DURATION_DO)) { String sValue = value.toString(); ListPreference listPreference = (ListPreference)prefMng.findPreference(key); if (listPreference != null) { int index = listPreference.findIndexOfValue(sValue); CharSequence summary = (index >= 0) ? listPreference.getEntries()[index] : null; listPreference.setSummary(summary); setTitleStyle(listPreference, index > 0, false); setCategorySummary(listPreference, index > 0); } } if (key.equals(GlobalData.PREF_PROFILE_ASK_FOR_DURATION)) { String sValue = value.toString(); CheckBoxPreference checkBoxPreference = (CheckBoxPreference)prefMng.findPreference(key); if (checkBoxPreference != null) { boolean show = sValue.equals("true"); setTitleStyle(checkBoxPreference, show, false); setCategorySummary(checkBoxPreference, show); } } if (key.equals(GlobalData.PREF_PROFILE_VOLUME_RINGTONE) || key.equals(GlobalData.PREF_PROFILE_VOLUME_NOTIFICATION) || key.equals(GlobalData.PREF_PROFILE_VOLUME_MEDIA) || key.equals(GlobalData.PREF_PROFILE_VOLUME_ALARM) || key.equals(GlobalData.PREF_PROFILE_VOLUME_SYSTEM) || key.equals(GlobalData.PREF_PROFILE_VOLUME_VOICE)) { Preference preference = prefMng.findPreference(key); if (preference != null) { String sValue = value.toString(); boolean change = VolumeDialogPreference.changeEnabled(sValue); setTitleStyle(preference, change, false); setCategorySummary(preference, change); } } if (key.equals(GlobalData.PREF_PROFILE_DEVICE_BRIGHTNESS)) { Preference preference = prefMng.findPreference(key); if (preference != null) { String sValue = value.toString(); boolean change = BrightnessDialogPreference.changeEnabled(sValue); setTitleStyle(preference, change, false); setCategorySummary(preference, change); } } } public void setSummary(String key) { String value; if (key.equals(GlobalData.PREF_PROFILE_ASK_FOR_DURATION)) { boolean b = preferences.getBoolean(key, false); value = Boolean.toString(b); } else value = preferences.getString(key, ""); setSummary(key, value); } private void disableDependedPref(String key, Object value) { String sValue = value.toString(); final String NO_CHANGE = "0"; final String DEFAULT_PROFILE = "99"; final String ON = "1"; if (key.equals(GlobalData.PREF_PROFILE_SOUND_RINGTONE_CHANGE)) { boolean enabled = !(sValue.equals(DEFAULT_PROFILE) || sValue.equals(NO_CHANGE)); prefMng.findPreference(GlobalData.PREF_PROFILE_SOUND_RINGTONE).setEnabled(enabled); } if (key.equals(GlobalData.PREF_PROFILE_SOUND_NOTIFICATION_CHANGE)) { boolean enabled = !(sValue.equals(DEFAULT_PROFILE) || sValue.equals(NO_CHANGE)); prefMng.findPreference(GlobalData.PREF_PROFILE_SOUND_NOTIFICATION).setEnabled(enabled); } if (key.equals(GlobalData.PREF_PROFILE_SOUND_ALARM_CHANGE)) { boolean enabled = !(sValue.equals(DEFAULT_PROFILE) || sValue.equals(NO_CHANGE)); prefMng.findPreference(GlobalData.PREF_PROFILE_SOUND_ALARM).setEnabled(enabled); } if (key.equals(GlobalData.PREF_PROFILE_DEVICE_WALLPAPER_CHANGE)) { boolean enabled = !(sValue.equals(DEFAULT_PROFILE) || sValue.equals(NO_CHANGE)); Preference preference = prefMng.findPreference(GlobalData.PREF_PROFILE_DEVICE_WALLPAPER); if (preference != null) preference.setEnabled(enabled); preference = prefMng.findPreference(GlobalData.PREF_PROFILE_DEVICE_WALLPAPER_FOR); if (preference != null) preference.setEnabled(enabled); } if (key.equals(GlobalData.PREF_PROFILE_DEVICE_RUN_APPLICATION_CHANGE)) { boolean enabled = !(sValue.equals(DEFAULT_PROFILE) || sValue.equals(NO_CHANGE)); prefMng.findPreference(GlobalData.PREF_PROFILE_DEVICE_RUN_APPLICATION_PACKAGE_NAME).setEnabled(enabled); } if (key.equals(GlobalData.PREF_PROFILE_DEVICE_WIFI_AP)) { boolean enabled = !sValue.equals(ON); ListPreference preference = (ListPreference) prefMng.findPreference(GlobalData.PREF_PROFILE_DEVICE_WIFI); if (preference != null) { if (!enabled) preference.setValue(NO_CHANGE); preference.setEnabled(enabled); } } if (key.equals(GlobalData.PREF_PROFILE_VOLUME_RINGER_MODE) || key.equals(GlobalData.PREF_PROFILE_VOLUME_ZEN_MODE)) { if (android.os.Build.VERSION.SDK_INT >= 21) { String ringerMode = preferences.getString(GlobalData.PREF_PROFILE_VOLUME_RINGER_MODE, "0"); String zenMode = preferences.getString(GlobalData.PREF_PROFILE_VOLUME_ZEN_MODE, "0"); boolean enabled = false; if (ringerMode.equals("5")) { if (zenMode.equals("1") || zenMode.equals("2")) enabled = true; } ListPreference preference = (ListPreference) prefMng.findPreference(GlobalData.PREF_PROFILE_VIBRATE_WHEN_RINGING); if (preference != null) { if (!enabled) preference.setValue(NO_CHANGE); preference.setEnabled(enabled); } } } } public void disableDependedPref(String key) { String value = preferences.getString(key, ""); disableDependedPref(key, value); } public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { String value; if (key.equals(GlobalData.PREF_PROFILE_ASK_FOR_DURATION)) { boolean bValue = sharedPreferences.getBoolean(key, false); value = Boolean.toString(bValue); } else value = sharedPreferences.getString(key, ""); setSummary(key, value); // disable depended preferences disableDependedPref(key, value); //Activity activity = getActivity(); //boolean canShow = (EditorProfilesActivity.mTwoPane) && (activity instanceof EditorProfilesActivity); //canShow = canShow || ((!EditorProfilesActivity.mTwoPane) && (activity instanceof ProfilePreferencesFragmentActivity)); //if (canShow) // showActionMode(); ProfilePreferencesFragmentActivity activity = (ProfilePreferencesFragmentActivity)getActivity(); ProfilePreferencesFragmentActivity.showSaveMenu = true; activity.invalidateOptionsMenu(); } }
package it.unimi.dsi.sux4j.util; import it.unimi.dsi.Util; import it.unimi.dsi.bits.BitVector; import it.unimi.dsi.bits.Fast; import it.unimi.dsi.bits.LongArrayBitVector; import it.unimi.dsi.bits.TransformationStrategies; import it.unimi.dsi.bits.TransformationStrategy; import it.unimi.dsi.fastutil.booleans.BooleanArrayList; import it.unimi.dsi.fastutil.ints.IntArrayList; import it.unimi.dsi.fastutil.ints.IntIterator; import it.unimi.dsi.fastutil.ints.IntOpenHashSet; import it.unimi.dsi.fastutil.io.BinIO; import it.unimi.dsi.fastutil.longs.LongOpenHashSet; import it.unimi.dsi.fastutil.objects.AbstractObjectBidirectionalIterator; import it.unimi.dsi.fastutil.objects.AbstractObjectIterator; import it.unimi.dsi.fastutil.objects.AbstractObjectSet; import it.unimi.dsi.fastutil.objects.AbstractObjectSortedSet; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import it.unimi.dsi.fastutil.objects.ObjectBidirectionalIterator; import it.unimi.dsi.fastutil.objects.ObjectIterator; import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; import it.unimi.dsi.fastutil.objects.ObjectSet; import it.unimi.dsi.fastutil.objects.ObjectSortedSet; import it.unimi.dsi.io.FastBufferedReader; import it.unimi.dsi.io.FileLinesCollection; import it.unimi.dsi.io.LineIterator; import it.unimi.dsi.lang.MutableString; import it.unimi.dsi.logging.ProgressLogger; import it.unimi.dsi.sux4j.mph.Hashes; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.nio.charset.Charset; import java.util.Comparator; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.zip.GZIPInputStream; import org.apache.log4j.Logger; import com.martiansoftware.jsap.FlaggedOption; import com.martiansoftware.jsap.JSAP; import com.martiansoftware.jsap.JSAPException; import com.martiansoftware.jsap.JSAPResult; import com.martiansoftware.jsap.Parameter; import com.martiansoftware.jsap.SimpleJSAP; import com.martiansoftware.jsap.Switch; import com.martiansoftware.jsap.UnflaggedOption; import com.martiansoftware.jsap.stringparsers.ForNameStringParser; /** A z-fast trie, that is, a predecessor/successor data structure using low linear (in the number of keys) additional space and * answering to the query string * <var>x</var> in time |<var>x</var>|/<var>w</var> + log(max{|<var>x</var>|, |<var>x</var><sup>-</sup>|, |<var>x</var><sup>+</sup>|}) with high probability, * where <var>w</var> is the machine word size, and <var>x</var><sup>-</sup>/<var>x</var><sup>+</sup> are the predecessor/successor of <var>x</var> in the currently stored set, respectively. * * <p>In rough terms, the z-fast trie uses time |<var>x</var>|/<var>w</var> (which is optimal) to actually look at the string content, * and log(max{|<var>x</var>|, |<var>x</var><sup>-</sup>|, |<var>x</var><sup>+</sup>|}) to perform the search. This is known to be (essentially) optimal. * String lengths are up to {@link Integer#MAX_VALUE}, and not limited to be a constant multiple of <var>w</var> for the bounds to hold. * * <p>The linear overhead of a z-fast trie is very low. For <var>n</var> keys we allocate 2<var>n</var> &minus; 1 nodes containing six references and * two longs, plus a dictionary containing <var>n</var> &minus; 1 nodes (thus using around 2<var>n</var> references and 2<var>n</var> longs). * */ public class ZFastTrie<T> extends AbstractObjectSortedSet<T> implements Serializable { public static final long serialVersionUID = 1L; private static final Logger LOGGER = Util.getLogger( ZFastTrie.class ); private static final boolean ASSERTS = false; private static final boolean DEBUG = false; private static final boolean DDEBUG = DEBUG; private static final boolean DDDEBUG = false; /** If true, signatures are restricted to two bits, generating lots of false positives. */ private static final boolean SHORT_SIGNATURES = false; /** The number of elements in the trie. */ private int size; /** The root node. */ private transient Node<T> root; /** The transformation strategy. */ private final TransformationStrategy<? super T> transform; /** A dictionary mapping handles to the corresponding internal nodes. */ public transient Handle2NodeMap<T> handle2Node; /** The head of the doubly linked list of leaves. */ private transient Leaf<T> head; /** The tail of the doubly linked list of leaves. */ private transient Leaf<T> tail; /** A linear-probing hash map that compares keys using signatures as a first try. */ protected final static class Handle2NodeMap<U> { private static final long serialVersionUID = 1L; private static final int INITIAL_LENGTH = 64; /** The transformation strategy. */ protected final TransformationStrategy<? super U> transform; /** The node table. */ protected InternalNode<U>[] node; /** The signature of the handle of the corresponding entry {@link #node}. */ protected long[] signature; /** If true, there are more copies of the signature along the search path. */ private boolean dup[]; /** The number of elements in the table. */ protected int size; /** The number of slots in the table (always a power of two). */ protected int length; /** {@link #length} &minus; 1. */ protected int mask; protected void assertTable() { for( int i = signature.length; i-- != 0; ) if ( node[ i ] != null ) assert get( node[ i ].handle( transform ), true ) == node[ i ]; if ( size == 0 ) return; final IntOpenHashSet overallHashes = new IntOpenHashSet(); int start = 0; int first = -1; while( node[ start ] != null ) start = ( start + 1 ) & mask; // We are on an empty entry for( ;; ) { while( node[ start ] == null ) start = ( start + 1 ) & mask; // We are on a nonempty entry if ( first == -1 ) first = start; else if ( first == start ) break; int end = start; while( node[ end ] != null ) end = ( end + 1 ) & mask; // [start..end) is a maximal nonempty subsequence IntOpenHashSet hashesSeen = new IntOpenHashSet(); LongOpenHashSet signaturesSeen = new LongOpenHashSet(); for( int pos = end; pos != start; ) { pos = ( pos - 1 ) & mask; assert signaturesSeen.add( signature[ pos ] ) ^ dup[ pos ]; hashesSeen.add( hash( signature[ pos ] ) ); } // Hashes in each maximal nonempty subsequence must be disjoint for( IntIterator iterator = hashesSeen.iterator(); iterator.hasNext(); ) assert overallHashes.add( iterator.nextInt() ); start = end; } } /** Creates a new handle-to-node map using a given transformation strategy and expected number of elements. * * @param size the expected number of elements. * @param transform the transformation strategy used for this map. */ @SuppressWarnings("unchecked") public Handle2NodeMap( final int size, TransformationStrategy<? super U> transform ) { this.transform = transform; length = Math.max( INITIAL_LENGTH, 1 << Fast.ceilLog2( 1 + ( 3L * size / 2 ) ) ); mask = length - 1; signature = new long[ length ]; node = new InternalNode[ length ]; dup = new boolean[ length ]; } /** Creates a new handle-to-node map using a given transformation strategy. * * @param transform the transformation strategy used for this map. */ @SuppressWarnings("unchecked") public Handle2NodeMap( TransformationStrategy<? super U> transform ) { this.transform = transform; length = INITIAL_LENGTH; mask = length - 1; signature = new long[ length ]; node = new InternalNode[ length ]; dup = new boolean[ length ]; } /** Generates a hash table position starting from a signature. * * @param s a signature. */ protected int hash( final long s ) { return (int)( s ^ s >>> 32 ) & mask; } /** Find the position in the table of a given handle using signatures. * * <p>Note that this function just compares signatures (except for duplicates, which are * checked explicitly). Thus, it might return false positives when queried with * keys that are not handles. Nonetheless, it will always return a correct result on a handle. * * @param v a bit vector. * @param handleLength the length of the prefix of <code>v</code> that will be used as a handle. * @param s the signature of the prefix of <code>v</code> of <code>handleLength</code> bits. * * @return the position in the table where the specified handle can be found, or a position containing <code>null</code>. */ protected int findPos( final BitVector v, final long handleLength, final long s ) { int pos = hash( s ); while( node[ pos ] != null && // Position is not empty ( signature[ pos ] != s || // Different signature ( dup[ pos ] && ( handleLength != node[ pos ].handleLength() || // Different handle length (it's a duplicate) ! v.equals( node[ pos ].reference.key( transform ), 0, handleLength ) ) ) ) ) // Different handle pos = ( pos + 1 ) & mask; return pos; } /** Find the position in the table of a given handle using handles. * * <p>Note that this function compares handles. Thus, it always returns a correct value. * @param v a bit vector. * @param handleLength the length of the prefix of <code>v</code> that will be used as a handle. * @param s the signature of the prefix of <code>v</code> of <code>handleLength</code> bits. * * @return the position in the table where the specified handle can be found, or a position containing <code>null</code>. */ protected int findExactPos( final BitVector v, final long handleLength, final long s ) { int pos = hash( s ); while( node[ pos ] != null && // Position is not empty ( signature[ pos ] != s || // Different signature handleLength != node[ pos ].handleLength() || // Different handle length ! v.equals( node[ pos ].reference.key( transform ), 0, handleLength ) ) ) // Different handle pos = ( pos + 1 ) & mask; return pos; } @SuppressWarnings("unchecked") public void clear() { length = INITIAL_LENGTH; mask = length - 1; size = 0; signature = new long[ length ]; node = new InternalNode[ length ]; dup = new boolean[ length ]; } public ObjectSet<LongArrayBitVector> keySet() { return new AbstractObjectSet<LongArrayBitVector>() { @Override public ObjectIterator<LongArrayBitVector> iterator() { return new AbstractObjectIterator<LongArrayBitVector>() { private int i = 0; private int pos = -1; @Override public boolean hasNext() { return i < size; } @Override public LongArrayBitVector next() { if ( ! hasNext() ) throw new NoSuchElementException(); while( node[ ++pos ] == null ); i++; return LongArrayBitVector.copy( node[ pos ].handle( transform ) ); } }; } @Override public boolean contains( Object o ) { BitVector v = (BitVector)o; return get( v, true ) != null; } @Override public int size() { return size; } }; } public ObjectSet<Node<U>> values() { return new AbstractObjectSet<Node<U>>() { @Override public ObjectIterator<Node<U>> iterator() { return new AbstractObjectIterator<Node<U>>() { private int i = 0; private int pos = -1; @Override public boolean hasNext() { return i < size; } @Override public Node<U> next() { if ( ! hasNext() ) throw new NoSuchElementException(); while( node[ ++pos ] == null ); i++; return node[ pos ]; } }; } @Override public boolean contains( Object o ) { @SuppressWarnings("unchecked") final Node<U> node = (Node<U>)o; return get( node.handle( transform ), true ) != null; } @Override public int size() { return size; } }; } /** Replaces an entry with a given node. * * @param oldNode a node appearing in the table. * @param newNode a node with the same handle as <code>oldNode</code>. * @param s the signature of the handle of <code>oldNode</code> and <code>newNode</code>. */ public void replaceExisting( final InternalNode<U> oldNode, final InternalNode<U> newNode, long s ) { if ( SHORT_SIGNATURES ) s &= 0x3; int pos = hash( s ); while( node[ pos ] != oldNode ) pos = ( pos + 1 ) & mask; if ( node[ pos ] == null ) throw new IllegalStateException(); if ( ASSERTS ) assert node[ pos ].handle( transform ).equals( newNode.handle( transform ) ) : node[ pos ].handle( transform ) + " != " + newNode.handle( transform ); node[ pos ] = newNode; if ( ASSERTS ) assertTable(); } public void removeExisting( final InternalNode<U> n, long s ) { if ( DEBUG ) System.err.println( "Map.remove(" + n + ", " + s + ")" ); if ( SHORT_SIGNATURES ) s &= 0x3; int pos = hash( s ); int lastDup = -1; // Keeps track of the last duplicate entry with the same signature. while ( node[ pos ] != n ) { if ( signature[ pos ] == s ) lastDup = pos; pos = ( pos + 1 ) & mask; } if ( node[ pos ] == null ) throw new IllegalStateException(); if ( ! dup[ pos ] && lastDup != -1 ) dup[ lastDup ] = false; // We are removing the only non-duplicate entry. // Move entries, compatibly with their hash code, to fill the hole. int candidateHole, h; do { candidateHole = pos; // Find candidate for a move (possibly empty). do { pos = ( pos + 1 ) & mask; if ( node[ pos ] == null ) break; h = hash( signature[ pos ] ); /* The hash h must lie cyclically between candidateHole and pos: more precisely, h must be after candidateHole * but before the first free entry in the table (which is equivalent to the previous statement). */ } while( candidateHole <= pos ? candidateHole < h && h <= pos : candidateHole < h || h <= pos ); node[ candidateHole ] = node[ pos ]; signature[ candidateHole ] = signature[ pos ]; dup[ candidateHole ] = dup[ pos ]; } while( node[ pos ] != null ); size if ( ASSERTS ) assertTable(); } /** Adds a new entry to the table. * * @param v a node. * * @see #addNew(InternalNode, long) */ public void addNew( final InternalNode<U> v ) { addNew( v, v.handleHash( transform ) ); } /** Adds a new entry to the table. * * <p>Note that as long as the handle of the given node is not in the * table this function will always perform correctly. Otherwise, * the table will end up containing two copies of the same key (i.e., handle). * * @param n a node. * @param s the signature of the handle of <code>n</code>. */ public void addNew( final InternalNode<U> n, long s ) { if ( SHORT_SIGNATURES ) s &= 0x3; if ( DEBUG ) System.err.println( "Map.addNew(" + n + ", " + s + ")" ); int pos = hash( s ); // Finds a free position, marking all keys with the same signature along the search path as duplicates. while( node[ pos ] != null ) { if ( signature[ pos ] == s ) dup[ pos ] = true; pos = ( pos + 1 ) & mask; } size++; signature[ pos ] = s; node[ pos ] = n; if ( 3L * size > 2L * length ) { // Rehash. length *= 2; mask = length - 1; final long newKey[] = new long[ length ]; @SuppressWarnings("unchecked") final InternalNode<U>[] newValue = new InternalNode[ length ]; final boolean[] newDup = new boolean[ length ]; final long[] key = this.signature; final InternalNode<U>[] value = this.node; for( int i = key.length; i if ( value[ i ] != null ) { s = key[ i ]; pos = hash( s ); while( newValue[ pos ] != null ) { if ( newKey[ pos ] == s ) newDup[ pos ] = true; pos = ( pos + 1 ) & mask; } newKey[ pos ] = key[ i ]; newValue[ pos ] = value[ i ]; } } this.signature = newKey; this.node = newValue; this.dup = newDup; } if ( ASSERTS ) assertTable(); } public int size() { return size; } /** Retrieves a node given its handle. * * @param v a bit vector. * @param handleLength the prefix of <code>v</code> that must be used as a handle. * @param s the signature of the specified handle. * @param exact whether the search should be exact; if false, and the given handle does not * appear in the table, it is possible that an unpredictable internal node is returned. * * @return the node with given handle, or <code>null</code> if there is no such node (if * <code>exact</code> is false, a false positive might be returned). */ public InternalNode<U> get( final BitVector v, final long handleLength, final long s, final boolean exact ) { if ( SHORT_SIGNATURES ) return node[ exact ? findExactPos( v, handleLength, s & 0x3 ) : findPos( v, handleLength, s & 0x3 ) ]; else return node[ exact ? findExactPos( v, handleLength, s ) : findPos( v, handleLength, s ) ]; } /** Retrieves a node given its handle. * * @param handle a handle. * @param exact whether the search should be exact; if false, and the given handle does not * appear in the table, it is possible that an unpredictable internal node is returned. * * @return the node with given handle, or <code>null</code> if there is no such node (if * <code>exact</code> is false, a false positive might be returned). * * @see #get(BitVector, long, long, boolean) */ public InternalNode<U> get( final BitVector handle, final boolean exact ) { return get( handle, handle.length(), Hashes.murmur( handle, 0 ), exact ); } public String toString() { StringBuilder s = new StringBuilder(); s.append( '{' ); for( LongArrayBitVector v: keySet() ) s.append( v ).append( " => " ).append( get( v, true ) ).append( ", " ); if ( s.length() > 1 ) s.setLength( s.length() - 2 ); s.append( '}' ); return s.toString(); } } /** A node of the trie. */ protected abstract static class Node<U> { /** The length of the extent of the parent node, or 0 for the root. */ protected long parentExtentLength; public boolean isLeaf() { return this instanceof Leaf; } public boolean isInternal() { return this instanceof InternalNode; } public long nameLength() { return parentExtentLength == 0 ? 0 : parentExtentLength + 1; } public long handleLength( TransformationStrategy<? super U> transform ) { return twoFattest( parentExtentLength, extentLength( transform ) ); } public abstract BitVector key( TransformationStrategy<? super U> transform ); public abstract BitVector handle( TransformationStrategy<? super U> transform ); public abstract long extentLength( TransformationStrategy<? super U> transform ); public abstract BitVector extent( TransformationStrategy<? super U> transform ); public abstract boolean intercepts( final long h ); public long handleHash( TransformationStrategy<? super U> transform ) { if ( SHORT_SIGNATURES ) return Hashes.murmur( handle( transform ), 0 ) & 0x3; else return Hashes.murmur( handle( transform ), 0 ); } /** Returns true if this node is the exit node of a string. * * @param v the string. * @param transform the transformation strategy used to build the trie this node belongs to. * @return true if the string exits at this node. */ public boolean isExitNodeOf( final LongArrayBitVector v, TransformationStrategy<? super U> transform ) { return isExitNodeOf( v.length(), v.longestCommonPrefixLength( extent( transform ) ), transform ); } /** Returns true if this node is the exit node of a string given its length and the length of the longest * common prefix with the node extent. * * @param length the length of a string. * @param lcpLength the length of the longest common prefix between the string and the extent of this node. * @return true if the string exits at this node. */ public boolean isExitNodeOf( final long length, final long lcpLength, TransformationStrategy<? super U> transform ) { return parentExtentLength < lcpLength && ( lcpLength < extentLength( transform ) || lcpLength == length ); } @SuppressWarnings({"rawtypes","unchecked"}) public String toString() { final TransformationStrategy transform = TransformationStrategies.prefixFreeIso(); final long extentLength = extentLength( transform ); return ( isLeaf() ? "[" : "(" ) + Integer.toHexString( hashCode() & 0xFFFF ) + ( key( transform ) == null ? "" : " " + ( extentLength > 16 ? key( transform ).subVector( 0, 8 ) + "..." + key( transform ).subVector( extentLength - 8, extentLength ): key( transform ).subVector( 0, extentLength ) ) ) + " (" + parentExtentLength + ".." + extentLength + "], " + handleLength( transform ) + "->" + // TODO jumpLength() + ( isLeaf() ? "]" : ")" ); } } /** A internal node. */ protected final static class InternalNode<U> extends Node<U> { /** The length of the extent (for leaves, this is equal to the length of the transformed {@link #key}, which * is returned by {@link #extentLength(TransformationStrategy)}). */ protected long extentLength; /** The left subtrie. */ protected Node<U> left; /** The right subtrie. */ protected Node<U> right; /** The left jump pointer. */ protected Node<U> jumpLeft; /** The right jump pointer. */ protected Node<U> jumpRight; /** The leaf whose key this node refers to. */ protected Leaf<U> reference; public long handleLength() { return twoFattest( parentExtentLength, extentLength ); } public long jumpLength() { final long handleLength = handleLength(); return handleLength + ( handleLength & -handleLength ); } public boolean isLeaf() { return false; } public boolean isInternal() { return true; } public boolean intercepts( final long h ) { return h > parentExtentLength && h <= extentLength; } public BitVector extent( TransformationStrategy<? super U> transform ) { return reference.key( transform ).subVector( 0, extentLength ); } public long extentLength( final TransformationStrategy<? super U> transform ) { return extentLength; } @Override public BitVector key( TransformationStrategy<? super U> transform ) { return reference.key( transform ); } public BitVector handle( TransformationStrategy<? super U> transform ) { return reference.key( transform ).subVector( 0, handleLength() ); } } /** An external node, a.k.a. leaf. */ protected final static class Leaf<U> extends Node<U> { /** The previous leaf. */ protected Leaf<U> prev; /** The next leaf. */ protected Leaf<U> next; /** The key associated to this leaf. */ protected U key; /** The internal node that refers to the key of this leaf, if any. It will be <code>null</code> for exactly one leaf. */ protected InternalNode<U> reference; public BitVector handle( TransformationStrategy<? super U> transform ) { return reference.key( transform ).subVector( 0, handleLength( transform ) ); } public boolean isLeaf() { return true; } public boolean isInternal() { return false; } public boolean intercepts( final long h ) { return h > parentExtentLength; } public BitVector extent( final TransformationStrategy<? super U> transform ) { return key( transform ); } public long extentLength( final TransformationStrategy<? super U> transform ) { return transform.length( key ); } @Override public BitVector key( final TransformationStrategy<? super U> transform ) { return transform.toBitVector( key ); } } /** Creates a new z-fast trie using the given transformation strategy. * * @param transform a transformation strategy that must turn distinct elements into distinct, prefix-free bit vectors. */ public ZFastTrie( final TransformationStrategy<? super T> transform ) { this.transform = transform; this.handle2Node = new Handle2NodeMap<T>( transform ); initHeadTail(); } private void initHeadTail() { head = new Leaf<T>(); tail = new Leaf<T>(); head.next = tail; tail.prev = head; } /** Creates a new z-fast trie using the given elements and transformation strategy. * * @param elements an iterator returning the elements to be inserted in the trie. * @param transform a transformation strategy that must turn distinct elements into distinct, prefix-free bit vectors. */ public ZFastTrie( final Iterator<? extends T> elements, final TransformationStrategy<? super T> transform ) { this( transform ); while( elements.hasNext() ) add( elements.next() ); } /** Creates a new z-fast trie using the given elements and transformation strategy. * * @param elements an iterator returning the elements to be inserted in the trie. * @param transform a transformation strategy that must turn distinct elements into distinct, prefix-free bit vectors. */ public ZFastTrie( final Iterable<? extends T> elements, final TransformationStrategy<? super T> transform ) { this( elements.iterator(), transform ); } public int size() { return size > Integer.MAX_VALUE ? -1 : (int)size; } /** Returns the 2-fattest number in an interval. * * <p>Note that to get the length of the handle of a node you must * call this function passing the length of the extent of the parent (one less * than the node name) and the length of the extent of the node. * * @param a left extreme (excluded). * @param b right extreme (included). * @return the 2-fattest number in (<code>a</code>..<code>b</code>]. */ public final static long twoFattest( final long a, final long b ) { return ( -1L << Fast.mostSignificantBit( a ^ b ) & b ); } private static <U> void removeLeaf( final Leaf<U> node ) { node.next.prev = node.prev; node.prev.next = node.next; } private static <U> void addAfter( final Leaf<U> pred, final Leaf<U> node ) { node.next = pred.next; node.prev = pred; pred.next.prev = node; pred.next = node; } private static <U> void addBefore( final Leaf<U> succ, final Leaf<U> node ) { node.prev = succ.prev; node.next = succ; succ.prev.next = node; succ.prev = node; } private void assertTrie() { /* Shortest key */ LongArrayBitVector root = null; /* Keeps track of which nodes in map are reachable using the handle-2-node * map first, and then left/right pointer from the root. */ ObjectOpenHashSet<Node<T>> nodes = new ObjectOpenHashSet<Node<T>>(); /* Keeps track of leaves. */ ObjectOpenHashSet<Leaf<T>> leaves = new ObjectOpenHashSet<Leaf<T>>(); /* Keeps track of reference to leaf keys in internal nodes. */ ObjectOpenHashSet<T> references = new ObjectOpenHashSet<T>(); assert size == 0 && handle2Node.size() == 0 || size == handle2Node.size() + 1; /* Search for the root (shortest handle) and check that nodes and handles do match. */ for( LongArrayBitVector v : handle2Node.keySet() ) { final long vHandleLength = handle2Node.get( v, true ).handleLength(); if ( root == null || handle2Node.get( root, true ).handleLength() > vHandleLength ) root = v; final InternalNode<T> node = handle2Node.get( v, true ); nodes.add( node ); assert node.reference.reference == node : node + " -> " + node.reference + " -> " + node.reference.reference; } assert nodes.size() == handle2Node.size() : nodes.size() + " != " + handle2Node.size(); assert size < 2 || this.root == handle2Node.get( root, true ); if ( size > 1 ) { /* Verify doubly linked list of leaves. */ Leaf<T> toRight = head.next, toLeft = tail.prev; for( int i = 1; i < size; i++ ) { assert new MutableString( (CharSequence)toRight.key ).compareTo( (CharSequence)toRight.next.key ) < 0 : toRight.key + " >= " + toRight.next.key + " " + toRight + " " + toRight.next; assert new MutableString( (CharSequence)toLeft.key ).compareTo( (CharSequence)toLeft.prev.key ) > 0 : toLeft.key + " >= " + toLeft.prev.key + " " + toLeft + " " + toLeft.prev; toRight = toRight.next; toLeft = toLeft.prev; } final int numNodes = visit( handle2Node.get( root, true ), null, 0, 0, nodes, leaves, references ); assert numNodes == 2 * size - 1 : numNodes + " != " + ( 2 * size - 1 ); assert leaves.size() == size; int c = 0; for( Leaf<T> leaf: leaves ) if ( references.contains( leaf.key ) ) c++; assert c == size - 1 : c + " != " + ( size - 1 ); } else if ( size == 1 ) { assert head.next == this.root; assert tail.prev == this.root; } assert nodes.isEmpty(); } private int visit( final Node<T> n, final Node<T> parent, final long parentExtentLength, final int depth, ObjectOpenHashSet<Node<T>> nodes, ObjectOpenHashSet<Leaf<T>> leaves, ObjectOpenHashSet<T> references ) { if ( n == null ) return 0; if ( DEBUG ) { for( int i = depth; i-- != 0; ) System.err.print( '\t' ); System.err.println( "Node " + n + " (parent extent length: " + parentExtentLength + ")" + ( n.isInternal() ? " Jump left: " + ((InternalNode<T>)n).jumpLeft + " Jump right: " + ((InternalNode<T>)n).jumpRight : "" ) ); } assert parent == null || parent.extent( transform ).equals( n.extent( transform ).subVector( 0, ((InternalNode<T>)parent).extentLength ) ); assert parentExtentLength < n.extentLength( transform ); assert n.parentExtentLength == parentExtentLength : n.parentExtentLength + " != " + parentExtentLength + " " + n; if ( n.isInternal() ) { assert references.add( ((InternalNode<T>)n).reference.key ); assert nodes.remove( n ) : n; assert handle2Node.keySet().contains( n.handle( transform ) ) : n; /* Check that jumps are correct. */ final long jumpLength = ((InternalNode<T>)n).jumpLength(); Node<T> jumpLeft = ((InternalNode<T>)n).left; while( jumpLeft.isInternal() && jumpLength > ((InternalNode<T>)jumpLeft).extentLength ) jumpLeft = ((InternalNode<T>)jumpLeft).left; assert jumpLeft == ((InternalNode<T>)n).jumpLeft : jumpLeft + " != " + ((InternalNode<T>)n).jumpLeft + " (node: " + n + ")"; Node<T> jumpRight = ((InternalNode<T>)n).right; while( jumpRight.isInternal() && jumpLength > ((InternalNode<T>)jumpRight).extentLength ) jumpRight = ((InternalNode<T>)jumpRight).right; assert jumpRight == ((InternalNode<T>)n).jumpRight : jumpRight + " != " + ((InternalNode<T>)n).jumpRight + " (node: " + n + ")"; return 1 + visit( ((InternalNode<T>)n).left, n, ((InternalNode<T>)n).extentLength, depth + 1, nodes, leaves, references ) + visit( ((InternalNode<T>)n).right, n, n.extentLength( transform ), depth + 1, nodes, leaves, references ); } else { assert leaves.add( (Leaf<T>)n ); assert n.extentLength( transform ) == n.key( transform ).length(); return 1; } } /** Sets the jump pointers of a node by searching exhaustively for * handles that are jumps of the node handle length. * * @param node the node whose jump pointers must be set. */ private static <U> void setJumps( final InternalNode<U> node ) { if ( DEBUG ) System.err.println( "setJumps(" + node + ")" ); final long jumpLength = node.jumpLength(); Node<U> jump; for( jump = node.left; jump.isInternal() && jumpLength > ((InternalNode<U>)jump).extentLength; ) jump = ((InternalNode<U>)jump).jumpLeft; if ( ASSERTS ) assert jump.intercepts( jumpLength ) : jumpLength + " not in " + "(" + jump.parentExtentLength + ".." + ((InternalNode<U>)jump).extentLength + "] " + jump; node.jumpLeft = jump; for( jump = node.right; jump.isInternal() && jumpLength > ((InternalNode<U>)jump).extentLength; ) jump = ((InternalNode<U>)jump).jumpRight; if ( ASSERTS ) assert jump.intercepts( jumpLength ) : jumpLength + " not in " + "(" + jump.parentExtentLength + ".." + ((InternalNode<U>)jump).extentLength + "] " + jump; node.jumpRight = jump; } /** Fixes the right jumps of the ancestors of a node after an insertion. * * @param internal the new internal node. * @param exitNode the exit node. * @param rightChild whether the exit node is a right child. * @param leaf the new leaf. * @param stack a stack containing the 2-fat ancestors of the parent of the exit node. */ private static <U> void fixRightJumpsAfterInsertion( final InternalNode<U> internal, Node<U> exitNode, boolean rightChild, Leaf<U> leaf, final ObjectArrayList<InternalNode<U>> stack ) { if ( DEBUG ) System.err.println( "fixRightJumpsAfterInsertion(" + internal + ", " + exitNode + ", " + rightChild + ", " + leaf + ", " + stack ); final long lcp = leaf.parentExtentLength; InternalNode<U> toBeFixed = null; long jumpLength = -1; if ( ! rightChild ) { /* Nodes jumping to the left into the exit node but above the lcp must point to internal. */ while( ! stack.isEmpty() ) { toBeFixed = stack.pop(); jumpLength = toBeFixed.jumpLength(); if ( toBeFixed.jumpLeft != exitNode ) break; if ( jumpLength <= lcp ) toBeFixed.jumpLeft = internal; } } else { while( ! stack.isEmpty() ) { toBeFixed = stack.top(); jumpLength = toBeFixed.jumpLength(); if ( toBeFixed.jumpRight != exitNode || jumpLength > lcp ) break; toBeFixed.jumpRight = internal; stack.pop(); } while( ! stack.isEmpty() ) { toBeFixed = stack.pop(); jumpLength = toBeFixed.jumpLength(); while( exitNode.isInternal() && toBeFixed.jumpRight != exitNode ) exitNode = ((InternalNode<U>)exitNode).jumpRight; if ( toBeFixed.jumpRight != exitNode ) return; toBeFixed.jumpRight = leaf; } } } /** Fixes the left jumps of the ancestors of a node after an insertion. * * @param internal the new internal node. * @param exitNode the exit node. * @param rightChild whether the exit node is a right child. * @param leaf the new leaf. * @param stack a stack containing the 2-fat ancestors of the parent of the exit node. */ private static <U> void fixLeftJumpsAfterInsertion( final InternalNode<U> internal, Node<U> exitNode, boolean rightChild, Leaf<U> leaf, final ObjectArrayList<InternalNode<U>> stack ) { if ( DEBUG ) System.err.println( "fixLeftJumpsAfterInsertion(" + internal + ", " + exitNode + ", " + rightChild + ", " + leaf + ", " + stack ); final long lcp = leaf.parentExtentLength; InternalNode<U> toBeFixed = null; long jumpLength = -1; if ( rightChild ) { /* Nodes jumping to the right into the exit node but above the lcp must point to internal. */ while( ! stack.isEmpty() ) { toBeFixed = stack.pop(); jumpLength = toBeFixed.jumpLength(); if ( toBeFixed.jumpRight != exitNode ) break; if ( jumpLength <= lcp ) toBeFixed.jumpRight = internal; } } else { while( ! stack.isEmpty() ) { toBeFixed = stack.top(); jumpLength = toBeFixed.jumpLength(); if ( toBeFixed.jumpLeft != exitNode || jumpLength > lcp ) break; toBeFixed.jumpLeft = internal; stack.pop(); } while( ! stack.isEmpty() ) { toBeFixed = stack.pop(); jumpLength = toBeFixed.jumpLength(); while( exitNode.isInternal() && toBeFixed.jumpLeft != exitNode ) exitNode = ((InternalNode<U>)exitNode).jumpLeft; if ( toBeFixed.jumpLeft != exitNode ) return; toBeFixed.jumpLeft = leaf; } } } /** Fixes the right jumps of the ancestors of a node after a deletion. * * @param parentExitNode the parent of the exit node. * @param exitNode the exit node. * @param otherNode the other child of the parent of the exit node. * @param rightChild whether the parent of the exit node is a right child. * @param stack a stack containing the 2-fat ancestors of the grandparent of the exit node. */ private static <U> void fixRightJumpsAfterDeletion( InternalNode<U> parentExitNode, Leaf<U> exitNode, Node<U> otherNode, boolean rightChild, final ObjectArrayList<InternalNode<U>> stack ) { if ( DEBUG ) System.err.println( "fixRightJumpsAfterDeletion(" + parentExitNode + ", " + exitNode + ", " + otherNode + ", " + rightChild + ", " + stack ); InternalNode<U> toBeFixed = null; long jumpLength = -1; if ( ! rightChild ) { /* Nodes jumping to the left into the exit node but above the lcp must point to internal. */ while( ! stack.isEmpty() ) { toBeFixed = stack.pop(); jumpLength = toBeFixed.jumpLength(); if ( toBeFixed.jumpLeft != parentExitNode ) break; toBeFixed.jumpLeft = otherNode; } } else { while( ! stack.isEmpty() ) { toBeFixed = stack.top(); jumpLength = toBeFixed.jumpLength(); if ( toBeFixed.jumpRight != parentExitNode ) break; toBeFixed.jumpRight = otherNode; stack.pop(); } while( ! stack.isEmpty() ) { toBeFixed = stack.pop(); if ( toBeFixed.jumpRight != exitNode ) break; jumpLength = toBeFixed.jumpLength(); while( ! otherNode.intercepts( jumpLength ) ) otherNode = ((InternalNode<U>)otherNode).jumpRight; toBeFixed.jumpRight = otherNode; } } } /** Fixes the left jumps of the ancestors of a node after a deletion. * * @param parentExitNode the parent of the exit node. * @param exitNode the exit node. * @param otherNode the other child of the parent of the exit node. * @param rightChild whether the parent of the exit node is a right child. * @param stack a stack containing the 2-fat ancestors of the grandparent of the exit node. */ private static <U> void fixLeftJumpsAfterDeletion( InternalNode<U> parentExitNode, Leaf<U> exitNode, Node<U> otherNode, boolean rightChild, final ObjectArrayList<InternalNode<U>> stack ) { if ( DEBUG ) System.err.println( "fixLeftJumpsAfterDeletion(" + parentExitNode + ", " + exitNode + ", " + otherNode + ", " + rightChild + ", " + stack ); InternalNode<U> toBeFixed = null; long jumpLength = -1; if ( rightChild ) { /* Nodes jumping to the left into the exit node but above the lcp must point to internal. */ while( ! stack.isEmpty() ) { toBeFixed = stack.pop(); jumpLength = toBeFixed.jumpLength(); if ( toBeFixed.jumpRight != parentExitNode ) break; toBeFixed.jumpRight = otherNode; } } else { while( ! stack.isEmpty() ) { toBeFixed = stack.top(); jumpLength = toBeFixed.jumpLength(); if ( toBeFixed.jumpLeft != parentExitNode ) break; toBeFixed.jumpLeft = otherNode; stack.pop(); } while( ! stack.isEmpty() ) { toBeFixed = stack.pop(); if ( toBeFixed.jumpLeft != exitNode ) break; jumpLength = toBeFixed.jumpLength(); while( ! otherNode.intercepts( jumpLength ) ) otherNode = ((InternalNode<U>)otherNode).jumpLeft; toBeFixed.jumpLeft = otherNode; } } } @SuppressWarnings("unchecked") public boolean remove( final Object k ) { if ( DEBUG ) System.err.println( "remove(" + k + ")" ); final LongArrayBitVector v = LongArrayBitVector.copy( transform.toBitVector( (T)k ) ); if ( size == 0 ) return false; if ( size == 1 ) { if ( ! ((Leaf<T>)root).key.equals( k ) ) return false; removeLeaf( (Leaf<T>)root ); root = null; size = 0; if ( ASSERTS ) assertTrie(); return true; } final ObjectArrayList<InternalNode<T>> stack = new ObjectArrayList<InternalNode<T>>( 64 ); InternalNode<T> parentExitNode; boolean rightLeaf, rightChild = false; Node<T> exitNode; long lcp; final long[] state = Hashes.preprocessMurmur( v, 0 ); ParexData<T> parexData = getParentExitNode( v, state, stack ); if ( ASSERTS ) assertParent( v, parexData, stack ); parentExitNode = parexData.parexNode; exitNode = parexData.exitNode; lcp = parexData.lcp; rightLeaf = parentExitNode != null && parentExitNode.right == exitNode; if ( DDEBUG ) System.err.println( "Parex node: " + parentExitNode + " Exit node: " + exitNode + " LCP: " + lcp ); if ( ! ( exitNode.isLeaf() && ((Leaf<T>)exitNode).key.equals( k ) ) ) return false; // Not found final Node<T> otherNode = rightLeaf ? parentExitNode.left : parentExitNode.right; final boolean otherNodeIsInternal = otherNode.isInternal(); if ( parentExitNode != null && parentExitNode != root ) { // Let us fix grandpa's child pointer and update the stack. final InternalNode<T> grandParentExitNode = getGrandParentExitNode( v, state, stack ); if ( DDEBUG ) System.err.println( "Grandparex node: " + grandParentExitNode ); if ( rightChild = ( grandParentExitNode.right == parentExitNode ) ) grandParentExitNode.right = otherNode; else grandParentExitNode.left = otherNode; } final long parentExitNodehandleLength = parentExitNode.handleLength(); final long otherNodeHandleLength = otherNode.handleLength( transform ); final long t = parentExitNodehandleLength | otherNodeHandleLength; final boolean cutLow = ( t & -t & otherNodeHandleLength ) != 0; if ( parentExitNode == root ) root = otherNode; // Fix leaf reference if not null final InternalNode<T> refersToExitNode = ((Leaf<T>)exitNode).reference; if ( refersToExitNode == null ) parentExitNode.reference.reference = null; else { refersToExitNode.reference = parentExitNode.reference; refersToExitNode.reference.reference = refersToExitNode; } // Fix doubly-linked list removeLeaf( (Leaf<T>)exitNode ); if ( DDEBUG ) System.err.println( "Cut " + ( cutLow ? "low" : "high") + "; leaf on the " + ( rightLeaf ? "right" : "left") + "; other node is " + ( otherNodeIsInternal ? "internal" : "a leaf") ); if ( rightLeaf ) fixRightJumpsAfterDeletion( parentExitNode, (Leaf<T>)exitNode, otherNode, rightChild, stack ); else fixLeftJumpsAfterDeletion( parentExitNode, (Leaf<T>)exitNode, otherNode, rightChild, stack ); if ( cutLow && otherNodeIsInternal ) { handle2Node.removeExisting( (InternalNode<T>)otherNode, Hashes.murmur( otherNode.key( transform ), otherNodeHandleLength, state, parentExitNode.extentLength ) ); otherNode.parentExtentLength = parentExitNode.parentExtentLength; handle2Node.replaceExisting( parentExitNode, (InternalNode<T>)otherNode, Hashes.murmur( v, parentExitNodehandleLength, state ) ); setJumps( (InternalNode<T>)otherNode ); } else { otherNode.parentExtentLength = parentExitNode.parentExtentLength; handle2Node.removeExisting( parentExitNode, Hashes.murmur( v, parentExitNodehandleLength, state ) ); } size if ( ASSERTS ) { assertTrie(); assert ! contains( k ); } return true; } @Override public boolean add( final T k ) { if ( DEBUG ) System.err.println( "add(" + k + ")" ); final LongArrayBitVector v = LongArrayBitVector.copy( transform.toBitVector( k ) ); if ( DEBUG ) System.err.println( "add(" + v + ")" ); if ( size == 0 ) { final Leaf<T> leaf = new Leaf<T>(); leaf.key = k; leaf.parentExtentLength = 0; leaf.reference = null; addAfter( head, leaf ); root = leaf; size++; if ( ASSERTS ) assertTrie(); return true; } final ObjectArrayList<InternalNode<T>> stack = new ObjectArrayList<InternalNode<T>>( 64 ); InternalNode<T> parentExitNode; boolean rightChild; Node<T> exitNode; long lcp; final long[] state = Hashes.preprocessMurmur( v, 0 ); ParexData<T> parexData = getParentExitNode( v, state, stack ); if ( ASSERTS ) assertParent( v, parexData, stack ); parentExitNode = parexData.parexNode; exitNode = parexData.exitNode; lcp = parexData.lcp; rightChild = parentExitNode != null && parentExitNode.right == exitNode; if ( DDEBUG ) System.err.println( "Parex node: " + parentExitNode + " Exit node: " + exitNode + " LCP: " + lcp ); if ( exitNode.isLeaf() && ((Leaf<T>)exitNode).key.equals( k ) ) return false; // Already there final boolean exitDirection = v.getBoolean( lcp ); final long exitNodeHandleLength = exitNode.handleLength( transform ); final boolean cutLow = lcp >= exitNodeHandleLength; Leaf<T> leaf = new Leaf<T>(); InternalNode<T> internal = new InternalNode<T>(); final boolean exitNodeIsInternal = exitNode.isInternal(); leaf.key = k; leaf.parentExtentLength = lcp; leaf.reference = internal; internal.reference = leaf; internal.parentExtentLength = exitNode.parentExtentLength; internal.extentLength = lcp; if ( exitDirection ) { internal.jumpRight = internal.right = leaf; internal.left = exitNode; internal.jumpLeft = cutLow && exitNodeIsInternal ? ((InternalNode<T>)exitNode).jumpLeft : exitNode; } else { internal.jumpLeft = internal.left = leaf; internal.right = exitNode; internal.jumpRight = cutLow && exitNodeIsInternal ? ((InternalNode<T>)exitNode).jumpRight : exitNode; } if ( exitNode == root ) root = internal; // Update root else { if ( rightChild ) parentExitNode.right = internal; else parentExitNode.left = internal; } if ( DDEBUG ) System.err.println( "Cut " + ( cutLow ? "low" : "high") + "; exit to the " + ( exitDirection ? "right" : "left") ); if ( exitDirection ) fixRightJumpsAfterInsertion( internal, exitNode, rightChild, leaf, stack ); else fixLeftJumpsAfterInsertion( internal, exitNode, rightChild, leaf, stack ); if ( cutLow && exitNodeIsInternal ) { handle2Node.replaceExisting( (InternalNode<T>)exitNode, internal, Hashes.murmur( v, exitNodeHandleLength, state ) ); exitNode.parentExtentLength = lcp; handle2Node.addNew( (InternalNode<T>)exitNode, Hashes.murmur( exitNode.key( transform ), exitNode.handleLength( transform ), state, lcp ) ); setJumps( (InternalNode<T>)exitNode ); } else { exitNode.parentExtentLength = lcp; handle2Node.addNew( internal, Hashes.murmur( v, internal.handleLength(), state ) ); } if ( DEBUG ) System.err.println( "After insertion, map: " + handle2Node + " root: " + root ); size++; /* We find a predecessor or successor to insert the new leaf in the doubly linked list. */ if ( exitDirection ) { while( exitNode.isInternal() ) exitNode = ((InternalNode<T>)exitNode).jumpRight; addAfter( (Leaf<T>)exitNode, leaf ); } else { while( exitNode.isInternal() ) exitNode = ((InternalNode<T>)exitNode).jumpLeft; addBefore( (Leaf<T>)exitNode, leaf ); } if ( ASSERTS ) assertTrie(); if ( ASSERTS ) assert contains( k ); return true; } /** Returns the exit node of a given bit vector. * * @param v a bit vector. * @param state the hash state of <code>v</code> precomputed by {@link Hashes#preprocessMurmur(BitVector, long)}. * @return the exit node of <code>v</code>. */ private Node<T> getExitNode( final LongArrayBitVector v, final long[] state ) { if ( size == 0 ) throw new IllegalStateException(); if ( size == 1 ) return root; if ( DDEBUG ) System.err.println( "getExitNode(" + v + ")" ); final long length = v.length(); // This can be the exit node of v, the parex node of v, or something completely wrong. InternalNode<T> parexOrExitNode = fatBinarySearch( v, state, null, false, 0, length ); // This will contain the exit node if parexOrExitNode contains the correct parex node. Node<T> candidateExitNode; if ( parexOrExitNode == null ) candidateExitNode = root; else candidateExitNode = parexOrExitNode.extentLength < length && v.getBoolean( parexOrExitNode.extentLength ) ? parexOrExitNode.right : parexOrExitNode.left; /* This lcp length makes it possible to compute the length of the lcp between v and * parexOrExitNode by minimisation with the extent length, as necessarily the extent of * candidateExitNode is an extension of the extent of parexOrExitNode. */ final long lcpLength = v.longestCommonPrefixLength( candidateExitNode.extent( transform ) ); // In this case the fat binary search gave us the correct parex node. if ( candidateExitNode.isExitNodeOf( length, lcpLength, transform ) ) return candidateExitNode; // In this case the fat binary search gave us the correct exit node. if ( parexOrExitNode.isExitNodeOf( length, Math.min( parexOrExitNode.extentLength, lcpLength ), transform ) ) return parexOrExitNode; // Otherwise, something went horribly wrong. We restart in exact mode. parexOrExitNode = fatBinarySearch( v, state, null, true, 0, length ); if ( parexOrExitNode == null ) return root; return parexOrExitNode.extent( transform ).isProperPrefix( v ) ? parexOrExitNode.extentLength < length && v.getBoolean( parexOrExitNode.extentLength ) ? parexOrExitNode.right : parexOrExitNode.left : parexOrExitNode; } protected final static class ParexData<U> { protected final long lcp; protected final InternalNode<U> parexNode; protected final Node<U> exitNode; protected ParexData( final InternalNode<U> parexNode, final Node<U> exitNode, final long lcp ) { this.lcp = lcp; this.parexNode = parexNode; this.exitNode = exitNode; } } /** Returns the parent of the exit node of a given bit vector. * * @param v a bit vector. * @param state the hash state of <code>v</code> precomputed by {@link Hashes#preprocessMurmur(BitVector, long)}. * @param stack if not <code>null</code>, a stack that will be filled with the <em>fat nodes</em> along the path to the parent of the exit node. * @return the parent of the exit node of <code>v</code>, or <code>null</code> if the exit node is the root. */ public ParexData<T> getParentExitNode( final LongArrayBitVector v, final long[] state, final ObjectArrayList<InternalNode<T>> stack ) { if ( DDEBUG ) System.err.println( "getParentExitNode(" + v + ")" ); if ( size == 0 ) throw new IllegalStateException(); if ( size == 1 ) return new ParexData<T>( null, root, v.longestCommonPrefixLength( root.extent( transform ) ) ); final long length = v.length(); // This can be the exit node of v, the parex node of v, or something completely wrong. InternalNode<T> parexOrExitNode = fatBinarySearch( v, state, stack, false, 0, length ); // This will contain the exit node if parexOrExitNode contains the correct parex node. Node<T> candidateExitNode; if ( parexOrExitNode == null ) candidateExitNode = root; else candidateExitNode = parexOrExitNode.extentLength < length && v.getBoolean( parexOrExitNode.extentLength ) ? parexOrExitNode.right : parexOrExitNode.left; /* This lcp length makes it possible to compute the length of the lcp between v and * parexOrExitNode by minimisation with the extent length, as necessarily the extent of * candidateExitNode is an extension of the extent of parexOrExitNode. */ long lcpLength = v.longestCommonPrefixLength( candidateExitNode.extent( transform ) ); // In this case the fat binary search gave us the correct parex node, and we have all the data we need. if ( candidateExitNode.isExitNodeOf( length, lcpLength, transform ) ) return new ParexData<T>( parexOrExitNode, candidateExitNode, lcpLength ); // Now this is the length of the longest common prefix between v and the extent of parexOrExitNode. lcpLength = Math.min( parexOrExitNode.extentLength, lcpLength ); if ( ASSERTS ) assert lcpLength == v.longestCommonPrefixLength( parexOrExitNode.extent( transform ) ); if ( parexOrExitNode.isExitNodeOf( length, lcpLength, transform ) ) { // In this case the fat binary search gave us the correct *exit* node. We must pop it from the stack and maybe restart the search. stack.pop(); final long startingPoint = stack.isEmpty() ? 0 : stack.top().extentLength; // We're lucky: the second element on the stack is the parex node. if ( startingPoint == parexOrExitNode.parentExtentLength ) return new ParexData<T>( stack.isEmpty() ? null : stack.top(), parexOrExitNode, lcpLength ); final int stackSize = stack.size(); // Unless there are mistakes, this is really the parex node. final InternalNode<T> parexNode = fatBinarySearch( v, state, stack, false, startingPoint, parexOrExitNode.parentExtentLength ); if ( parexNode.left == parexOrExitNode || parexNode.right == parexOrExitNode ) return new ParexData<T>( parexNode, parexOrExitNode, lcpLength ); // Something went wrong with the last search. We can just, at this point, restart in exact mode. stack.size( stackSize ); return new ParexData<T>( fatBinarySearch( v, state, stack, true, startingPoint, parexOrExitNode.parentExtentLength ), parexOrExitNode, lcpLength ); } // The search failed. This even is so rare that we can afford to handle it inefficiently. stack.clear(); parexOrExitNode = fatBinarySearch( v, state, stack, true, 0, length ); if ( parexOrExitNode == null ) candidateExitNode = root; else candidateExitNode = parexOrExitNode.extentLength < length && v.getBoolean( parexOrExitNode.extentLength ) ? parexOrExitNode.right : parexOrExitNode.left; lcpLength = v.longestCommonPrefixLength( candidateExitNode.extent( transform ) ); // In this case the fat binary search gave us the correct parex node, and we have all the data we need. if ( candidateExitNode.isExitNodeOf( length, lcpLength, transform ) ) return new ParexData<T>( parexOrExitNode, candidateExitNode, lcpLength ); // In this case the fat binary search gave us the correct *exit* node. We must pop it from the stack and maybe restart the search. stack.pop(); final long startingPoint = stack.isEmpty() ? 0 : stack.top().extentLength; // We're lucky: the second element on the stack is the parex node. if ( startingPoint == parexOrExitNode.parentExtentLength ) return new ParexData<T>( stack.isEmpty() ? null : stack.top(), parexOrExitNode, lcpLength ); // The fat binary search will certainly return the parex node. return new ParexData<T>( fatBinarySearch( v, state, stack, true, startingPoint, parexOrExitNode.parentExtentLength ), parexOrExitNode, lcpLength ); } private void assertParent( LongArrayBitVector v, ParexData<T> parexData, ObjectArrayList<InternalNode<T>> stack ) { assert ( parexData.parexNode == null ) == stack.isEmpty() : ( parexData.parexNode == null ) + " != " + stack.isEmpty(); assert parexData.parexNode != null || parexData.exitNode == root; assert parexData.parexNode == null || parexData.parexNode.left == parexData.exitNode || parexData.parexNode.right == parexData.exitNode; for( InternalNode<T> node : stack ) { assert v.equals( node.extent( transform ), node.parentExtentLength, node.extentLength ); } } /** Returns the grandparent of the exit node of a given bit vector. * * @param v a bit vector. * @param stack as filled by {@link #getParentExitNode(LongArrayBitVector, long[], ObjectArrayList)}. */ public InternalNode<T> getGrandParentExitNode( final LongArrayBitVector v, final long[] state, final ObjectArrayList<InternalNode<T>> stack ) { final InternalNode<T> parentExitNode = stack.pop(); final long startingPoint = stack.isEmpty() ? 0 : stack.top().extentLength; // We're lucky: the second element on the stack is the grandparent of the exit node. if ( startingPoint == parentExitNode.parentExtentLength ) return stack.isEmpty() ? null : stack.top(); final int stackSize = stack.size(); // Unless there are mistakes, this is really the grandparent of the exit node. final InternalNode<T> grandParentExitNode = fatBinarySearch( v, state, stack, false, startingPoint, parentExitNode.parentExtentLength ); if ( grandParentExitNode.left == parentExitNode || grandParentExitNode.right == parentExitNode ) return grandParentExitNode; // Something went wrong with the last search. We can just, at this point, restart in exact mode. stack.size( stackSize ); return fatBinarySearch( v, state, stack, true, startingPoint, parentExitNode.parentExtentLength ); } private InternalNode<T> fatBinarySearch( final LongArrayBitVector v, final long[] state, final ObjectArrayList<InternalNode<T>> stack, final boolean exact, long a, long b ) { if ( DDDEBUG ) System.err.println( "fatBinarySearch(" + v + ", " + stack + ", " + exact + ", (" + a + ".." + b +"])" ); if ( ASSERTS ) assert a < b : a + " >= " + b; InternalNode<T> node = null, top = stack == null || stack.isEmpty() ? null : stack.top(); long topExtentLength = 0; long checkMask = -1L << Fast.ceilLog2( b - a ); while( b - a > 0 ) { if ( ASSERTS ) assert checkMask != 0; if ( DDDEBUG ) System.err.println( "(" + a + ".." + b + "] (check mask: " + Long.toBinaryString( checkMask ) ); final long f = b & checkMask; if ( ( a & checkMask ) != f ) { if ( DDDEBUG ) System.err.println( "Inquiring with key " + v.subVector( 0, f ) + " (" + f + ")" ); node = handle2Node.get( v, f, Hashes.murmur( v, f, state ), exact ); final long g; /* The second test is just to catch false positives. The third test is necessary to * guarantee that if the exit node is correct the whole stack is correct. */ if ( node == null || ( g = node.extentLength ) < f || ( node.parentExtentLength < topExtentLength ) ) { if ( DDDEBUG ) System.err.println( "Missing" ); b = f - 1; } else { if ( DDDEBUG ) System.err.println( "Found extent of length " + g ); if ( stack != null ) stack.push( node ); topExtentLength = ( top = node ).extentLength; a = g; } } checkMask >>= 1; } if ( DDDEBUG ) System.err.println( "Final interval: (" + a + ".." + b + "]; top: " + top + "; stack: " + stack ); return top; } @SuppressWarnings("unchecked") public boolean contains( final Object o ) { if ( DEBUG ) System.err.println( "contains(" + o + ")" ); if ( DDEBUG ) System.err.println( "Map: " + handle2Node + " root: " + root ); if ( size == 0 ) return false; final LongArrayBitVector v = LongArrayBitVector.copy( transform.toBitVector( (T)o ) ); final long[] state = Hashes.preprocessMurmur( v, 0 ); final Node<T> exitNode = getExitNode( v, state ); return exitNode.isLeaf() && ((Leaf<T>)exitNode).key.equals( o ); } private Leaf<T> predNode( final T k ) { final LongArrayBitVector v = LongArrayBitVector.copy( transform.toBitVector( k ) ); final long[] state = Hashes.preprocessMurmur( v, 0 ); Node<T> exitNode = getExitNode( v, state ); if ( v.compareTo( exitNode.extent( transform ) ) <= 0 ) { while( exitNode.isInternal() && ((InternalNode<T>)exitNode).jumpRight != null ) exitNode = ((InternalNode<T>)exitNode).jumpRight; return (Leaf<T>)exitNode; } else { while( exitNode.isInternal() && ((InternalNode<T>)exitNode).jumpLeft != null ) exitNode = ((InternalNode<T>)exitNode).jumpLeft; return ((Leaf<T>)exitNode).prev; } } @SuppressWarnings("unchecked") public T pred( final Object o ) { if ( size == 0 ) return null; return predNode( (T)o ).key; } private Leaf<T> succNode( final T k ) { final LongArrayBitVector v = LongArrayBitVector.copy( transform.toBitVector( k ) ); final long[] state = Hashes.preprocessMurmur( v, 0 ); Node<T> exitNode = getExitNode( v, state ); if ( v.compareTo( exitNode.extent( transform ) ) <= 0 ) { while( exitNode.isInternal() && ((InternalNode<T>)exitNode).jumpLeft != null ) exitNode = ((InternalNode<T>)exitNode).jumpLeft; return (Leaf<T>)exitNode; } else { while( exitNode.isInternal() && ((InternalNode<T>)exitNode).jumpRight != null ) exitNode = ((InternalNode<T>)exitNode).jumpRight; return ((Leaf<T>)exitNode).next; } } @SuppressWarnings("unchecked") public T succ( final Object o ) { if ( size == 0 ) return null; return succNode( (T)o ).key; } @Override public ObjectBidirectionalIterator<T> iterator() { return iteratorFromLeaf( head.next ); } @Override public ObjectBidirectionalIterator<T> iterator( final T from ) { return size == 0 ? iteratorFromLeaf( tail ) : iteratorFromLeaf( succNode( from ) ); } private ObjectBidirectionalIterator<T> iteratorFromLeaf( final Leaf<T> from ) { return new AbstractObjectBidirectionalIterator<T>() { private Leaf<T> curr = from; @Override public boolean hasNext() { return curr != tail; } @Override public T next() { if ( ! hasNext() ) throw new NoSuchElementException(); final T result = curr.key; curr = curr.next; return result; } @Override public boolean hasPrevious() { return curr.prev != head; } @Override public T previous() { if ( ! hasPrevious() ) throw new NoSuchElementException(); curr = curr.prev; return curr.key; } }; } @Override public Comparator<? super T> comparator() { return null; } @Override public T first() { return head.next.key; } @Override public T last() { return tail.prev.key; } @Override public ObjectSortedSet<T> headSet( T arg0 ) { throw new UnsupportedOperationException(); } @Override public ObjectSortedSet<T> subSet( T arg0, T arg1 ) { throw new UnsupportedOperationException(); } @Override public ObjectSortedSet<T> tailSet( T arg0 ) { throw new UnsupportedOperationException(); } private void writeObject( final ObjectOutputStream s ) throws IOException { s.defaultWriteObject(); if ( size > 0 ) writeNode( root, transform, s ); } private static <U >void writeNode( final Node<U> node, final TransformationStrategy<? super U> transform, final ObjectOutputStream s ) throws IOException { s.writeBoolean( node.isInternal() ); if ( node.isInternal() ) { final InternalNode<U> internalNode = (InternalNode<U>)node; s.writeLong( internalNode.extentLength - internalNode.parentExtentLength ); writeNode( internalNode.left, transform, s ); writeNode( internalNode.right, transform, s ); } else s.writeObject( ((Leaf<U>)node).key ); } private void readObject( final ObjectInputStream s ) throws IOException, ClassNotFoundException { s.defaultReadObject(); initHeadTail(); handle2Node = new Handle2NodeMap<T>( size, transform ); if ( size > 0 ) root = readNode( s, 0, 0, handle2Node, new ObjectArrayList<Leaf<T>>(), new ObjectArrayList<InternalNode<T>>(), new IntArrayList(), new IntArrayList(), new BooleanArrayList() ); if ( ASSERTS ) assertTrie(); } /** Reads recursively a node of the trie. * * @param s the object input stream. * @param depth the depth of the node to be read. * @param parentExtentLength the length of the extent of the parent node. * @param map the map representing the trie. * @param leafStack a stack that cumulates leaves as they are found: internal nodes extract references from this stack when their visit is completed. * @param jumpStack a stack that cumulates nodes that need jump pointer fixes. * @param depthStack a stack parallel to <code>jumpStack</code>, providing the depth of the corresponding node. * @param segmentStack a stack of integers representing the length of maximal constant subsequences of the string of directions taken up to the current node; for instance, if we reached the current node by 1/1/0/0/0/1/0/0, the stack will contain 2,3,1,2. * @param dirStack a stack parallel to <code>segmentStack</code>: for each element, whether it counts left or right turns. * @return the subtree rooted at the next node in the stream. */ @SuppressWarnings("unchecked") private Node<T> readNode( final ObjectInputStream s, final int depth, final long parentExtentLength, final Handle2NodeMap<T> map, final ObjectArrayList<Leaf<T>> leafStack, final ObjectArrayList<InternalNode<T>> jumpStack, final IntArrayList depthStack, final IntArrayList segmentStack, final BooleanArrayList dirStack ) throws IOException, ClassNotFoundException { final boolean isInternal = s.readBoolean(); // The two following variables are identical when non-null. final InternalNode<T> internalNode = isInternal ? new InternalNode<T>() : null; final Node<T> node = isInternal ? internalNode : new Leaf<T>(); node.parentExtentLength = parentExtentLength; if ( isInternal ) internalNode.extentLength = parentExtentLength + s.readLong(); if ( ! dirStack.isEmpty() ) { /* We cannot fix the jumps of nodes that are more than this number of levels up in the tree. */ final int maxDepthDelta = segmentStack.topInt(); final boolean dir = dirStack.topBoolean(); InternalNode<T> anc; int d; long jumpLength; do { jumpLength = ( anc = jumpStack.top() ).jumpLength(); d = depthStack.topInt(); /* To be fixable, a node must be within the depth limit, and we must intercept its jump length (note that * we cannot use .intercept() as the state of node is not yet consistent). If a node cannot be fixed, no * node higher in the stack can. */ if ( depth - d <= maxDepthDelta && jumpLength > parentExtentLength && ( ! isInternal || jumpLength <= internalNode.extentLength ) ) { //if ( DDEBUG ) System.err.println( "Setting " + ( dir ? "right" : "left" ) + " jump pointer of " + anc + " to " + node ); if ( dir ) anc.jumpRight = node; else anc.jumpLeft = node; jumpStack.pop(); depthStack.popInt(); } else break; } while( ! jumpStack.isEmpty() ); } if ( isInternal ) { if ( dirStack.isEmpty() || dirStack.topBoolean() != false ) { segmentStack.push( 1 ); dirStack.push( false ); } else segmentStack.push( segmentStack.popInt() + 1 ); jumpStack.push( internalNode ); depthStack.push( depth ); if ( DEBUG ) System.err.println( "Recursing into left node... " ); internalNode.left = readNode( s, depth + 1, internalNode.extentLength, map, leafStack, jumpStack, depthStack, segmentStack, dirStack ); int top = segmentStack.popInt(); if ( top != 1 ) segmentStack.push( top - 1 ); else dirStack.popBoolean(); if ( dirStack.isEmpty() || dirStack.topBoolean() != true ) { segmentStack.push( 1 ); dirStack.push( true ); } else segmentStack.push( segmentStack.popInt() + 1 ); jumpStack.push( internalNode ); depthStack.push( depth ); if ( DEBUG ) System.err.println( "Recursing into right node... " ); internalNode.right = readNode( s, depth + 1, internalNode.extentLength, map, leafStack, jumpStack, depthStack, segmentStack, dirStack ); top = segmentStack.popInt(); if ( top != 1 ) segmentStack.push( top - 1 ); else dirStack.popBoolean(); /* We assign the reference leaf, and store the associated key. */ final Leaf<T> referenceLeaf = leafStack.pop(); internalNode.reference = referenceLeaf; referenceLeaf.reference = internalNode; map.addNew( internalNode ); if ( ASSERTS ) { // Check jump pointers. Node<T> t; t = internalNode.left; while( t.isInternal() && ! t.intercepts( internalNode.jumpLength() ) ) t = ((InternalNode<T>)t).left; assert internalNode.jumpLeft == t : internalNode.jumpLeft + " != " + t + " (" + node + ")"; t = internalNode.right; while( t.isInternal() && ! t.intercepts( internalNode.jumpLength() ) ) t = ((InternalNode<T>)t).right; assert internalNode.jumpRight == t : internalNode.jumpRight + " != " + t + " (" + node + ")"; } } else { final Leaf<T> leaf = (Leaf<T>)node; leaf.key = (T)s.readObject(); leafStack.push( leaf ); addBefore( tail, leaf ); } return node; } public static void main( final String[] arg ) throws NoSuchMethodException, IOException, JSAPException { final SimpleJSAP jsap = new SimpleJSAP( ZFastTrie.class.getName(), "Builds an PaCo trie-based monotone minimal perfect hash function reading a newline-separated list of strings.", new Parameter[] { new FlaggedOption( "encoding", ForNameStringParser.getParser( Charset.class ), "UTF-8", JSAP.NOT_REQUIRED, 'e', "encoding", "The string file encoding." ), new Switch( "loadAll", 'l', "load-all", "Load all strings into memory before building the trie." ), new Switch( "iso", 'i', "iso", "Use ISO-8859-1 coding internally (i.e., just use the lower eight bits of each character)." ), new Switch( "bitVector", 'b', "bit-vector", "Build a trie of bit vectors, rather than a trie of strings." ), new Switch( "zipped", 'z', "zipped", "The string list is compressed in gzip format." ), new UnflaggedOption( "trie", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED, JSAP.NOT_GREEDY, "The filename for the serialised z-fast trie." ), new UnflaggedOption( "stringFile", JSAP.STRING_PARSER, "-", JSAP.NOT_REQUIRED, JSAP.NOT_GREEDY, "The name of a file containing a newline-separated list of strings, or - for standard input." ), }); JSAPResult jsapResult = jsap.parse( arg ); if ( jsap.messagePrinted() ) return; final String functionName = jsapResult.getString( "trie" ); final String stringFile = jsapResult.getString( "stringFile" ); final Charset encoding = (Charset)jsapResult.getObject( "encoding" ); final boolean zipped = jsapResult.getBoolean( "zipped" ); final boolean iso = jsapResult.getBoolean( "iso" ); final boolean bitVector = jsapResult.getBoolean( "bitVector" ); final InputStream inputStream = "-".equals( stringFile ) ? System.in : new FileInputStream( stringFile ); Iterator<MutableString> lineIterator = new LineIterator( new FastBufferedReader( new InputStreamReader( zipped ? new GZIPInputStream( inputStream ) : inputStream, encoding ) ) ); if ( jsapResult.userSpecified( "loadAll" ) ) lineIterator = ((LineIterator)lineIterator).allLines().iterator(); final TransformationStrategy<CharSequence> transformationStrategy = iso ? TransformationStrategies.prefixFreeIso() : TransformationStrategies.prefixFreeUtf16(); ProgressLogger pl = new ProgressLogger(); pl.itemsName = "keys"; pl.displayFreeMemory = true; pl.start( "Adding keys..." ); if ( bitVector ) { ZFastTrie<LongArrayBitVector> zFastTrie = new ZFastTrie<LongArrayBitVector>( TransformationStrategies.identity() ); while( lineIterator.hasNext() ) { zFastTrie.add( LongArrayBitVector.copy( transformationStrategy.toBitVector( lineIterator.next().copy() ) ) ); pl.lightUpdate(); } pl.done(); BinIO.storeObject( zFastTrie, functionName ); } else { ZFastTrie<CharSequence> zFastTrie = new ZFastTrie<CharSequence>( transformationStrategy ); while( lineIterator.hasNext() ) { zFastTrie.add( lineIterator.next().copy() ); pl.lightUpdate(); } pl.done(); BinIO.storeObject( zFastTrie, functionName ); } LOGGER.info( "Completed." ); } }
package edu.wpi.first.wpilibj.team2903; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.buttons.Button; import edu.wpi.first.wpilibj.buttons.DigitalIOButton; /** * This class is the glue that binds the controls on the physical operator * interface to the commands and command groups that allow control of the robot. */ public class OI { //// CREATING BUTTONS // One type of button is a joystick button which is any button on a joystick. // You create one by telling it which joystick it's on and which button // number it is. public static Joystick leftStick = new Joystick(1); public static Joystick rightStick = new Joystick(2); public static Joystick controlStick = new Joystick(3); // Button button = new JoystickButton(stick, buttonNumber); // Button MaxShooter = new JoystickButton(rightStick,4); // Another type of button you can create is a DigitalIOButton, which is // a button or switch hooked up to the cypress module. These are useful if // you want to build a customized operator interface. // Button button = new DigitalIOButton(1); // There are a few additional built in buttons you can use. Additionally, // by subclassing Button you can create custom triggers and bind those to // commands the same as any other Button. //// TRIGGERING COMMANDS WITH BUTTONS // Once you have a button, it's trivial to bind it to a button in one of // three ways: // Start the command when the button is pressed and let it run the command // until it is finished as determined by it's isFinished method. // button.whenPressed(new ExampleCommand()); // Run the command while the button is being held down and interrupt it once // the button is released. // button.whileHeld(new ExampleCommand()); // Start the command when the button is released and let it run the command // until it is finished as determined by it's isFinished method. // button.whenReleased(new ExampleCommand()); }
package org.eclipse.che.api.core.util; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; /** * Container for system command arguments. * * @author <a href="mailto:andrew00x@gmail.com">Andrey Parfonov</a> */ public class CommandLine { private final List<String> line; public CommandLine(CommandLine other) { line = new ArrayList<>(other.line); } public CommandLine(String... args) { line = new ArrayList<>(); if (args != null && args.length > 0) { Collections.addAll(line, args); } } public CommandLine() { line = new ArrayList<>(); } /** * Adds list of arguments in command line. * * @param args * arguments * @return this {@code CommandLine} */ public CommandLine add(String... args) { if (args != null && args.length > 0) { Collections.addAll(line, args); } return this; } /** * Adds list of arguments in command line. * * @param args * arguments * @return this {@code CommandLine} */ public CommandLine add(List<String> args) { if (args != null && !args.isEmpty()) { line.addAll(args); } return this; } /** * Adds set of options in command line. * * @param options * options * @return this {@code CommandLine} * @see #addPair(String, String) */ public CommandLine add(Map<String, String> options) { if (options != null && !options.isEmpty()) { for (Map.Entry<String, String> entry : options.entrySet()) { addPair(entry.getKey(), entry.getValue()); } } return this; } /** * Adds option in command line. If {@code value != null} then adds {@code name=value} in command line. If {@code value} is {@code null} * adds only {@code name} in command line. * * @param name * option's name * @param value * option's value * @return this {@code CommandLine} */ public CommandLine addPair(String name, String value) { if (name != null) { if (value != null) { line.add(name + '=' + value); } else { line.add(name); } } return this; } /** * Removes all command line arguments. * * @return this {@code CommandLine} */ public CommandLine clear() { line.clear(); return this; } public String[] asArray() { return line.toArray(new String[line.size()]); } /** Create shell command. */ public String[] toShellCommand() { return ShellFactory.getShell().createShellCommand(this); } @Override public String toString() { final String[] str = asArray(); final StringBuilder sb = new StringBuilder(); // sb.append('\''); for (String s : str) { if (sb.length() > 1) { sb.append(' '); } sb.append(s); } // sb.append('\''); return sb.toString(); } }
package jamaica.core.functions; import java.io.*; import java.util.*; import jamaica.core.exceptions.*; import jamaica.core.types.*; import org.testng.annotations.*; import static jamaica.core.functions.collections.*; import static jamaica.core.functions.testing.*; import static org.testng.Assert.*; public class exceptions { // add_tuple @Test public void add_tuple__creates_and_adds_a_tuple_to_an_exception_tuples_list_from_the_given_params() { ExceptionTuples errors = new ExceptionTuples(); add_tuple(errors, new NumberFormatException(), 10); assert_that(errors.list.size() == 1); assert_that(errors.list.get(0).one instanceof NumberFormatException); assert_that(errors.list.get(0).two == 10); } public static Tuple<Exception, Integer> add_tuple(ExceptionTuples errors, Exception one, Integer two) { Tuple<Exception, Integer> tuple = new Tuple<>(one, two); errors.list.add(tuple); return tuple; } // get_root_cause @Test public void get_root_cause__returns_the_cause_used_to_instantiate_an_exception() { Throwable a = new Throwable(); assertEquals(get_root_cause(new Throwable(a)), a); } public static Throwable get_root_cause(Throwable t) { Throwable result = t; while (result.getCause() != null) { result = result.getCause(); } return result; } // reduce_exception @Test public void reduce_exception__groups_exceptions_by_class() { ReducedExceptions result = new ReducedExceptions(); result = reduce_exception(result, new IllegalArgumentException(), 1); result = reduce_exception(result, new IllegalArgumentException(), 2); result = reduce_exception(result, new IllegalArgumentException(), 3); assert result.getLocationMap().size() == 1 : "expected one exception type in the map"; assert result.getLocationMap().containsKey(IllegalArgumentException.class); } @Test public void reduce_exception__retains_the_location_of_the_original_exceptions() { ReducedExceptions result = new ReducedExceptions(); result = reduce_exception(result, new IllegalArgumentException(), 1); result = reduce_exception(result, new IllegalArgumentException(), 2); result = reduce_exception(result, new IllegalArgumentException(), 3); assert elements_match(result.getLocationMap().get(IllegalArgumentException.class), as_list(1, 2, 3)) : "expected the locations for the IllegalArgumentException to equal [1, 2, 3]"; } public static ReducedExceptions reduce_exception(ReducedExceptions map, Exception cause, int location) { Class type = cause.getClass(); Map<Class, List<Integer>> locations = map.getLocationMap(); if (!locations.containsKey(type)) { locations.put(type, new LinkedList()); } locations.get(type).add(location); return map; } // throw_checked @Test(expectedExceptions=IOException.class) public void throw__checked_throws_a_checked_exception_without_being_declared_in_the_method_body() { throw_checked(new IOException()); } public static void throw_checked(Exception e) { exceptions.<RuntimeException>throw_checked_hack(e); } private static <E extends Exception> void throw_checked_hack(Exception e) throws E { throw (E) e; } }
package ua.com.fielden.platform.entity.proxy; import static javassist.util.proxy.ProxyFactory.isProxyClass; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.fetch; import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.fetchAll; import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.fetchOnly; import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.from; import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.select; import java.math.BigDecimal; import java.util.List; import org.junit.Test; import ua.com.fielden.platform.entity.AbstractEntity; import ua.com.fielden.platform.entity.meta.MetaProperty; import ua.com.fielden.platform.entity.query.model.EntityResultQueryModel; import ua.com.fielden.platform.reflection.Reflector; import ua.com.fielden.platform.sample.domain.ITgBogie; import ua.com.fielden.platform.sample.domain.ITgVehicle; import ua.com.fielden.platform.sample.domain.TgAuthor; import ua.com.fielden.platform.sample.domain.TgBogie; import ua.com.fielden.platform.sample.domain.TgBogieLocation; import ua.com.fielden.platform.sample.domain.TgFuelType; import ua.com.fielden.platform.sample.domain.TgFuelUsage; import ua.com.fielden.platform.sample.domain.TgOrgUnit1; import ua.com.fielden.platform.sample.domain.TgOrgUnit2; import ua.com.fielden.platform.sample.domain.TgOrgUnit3; import ua.com.fielden.platform.sample.domain.TgOrgUnit4; import ua.com.fielden.platform.sample.domain.TgOrgUnit5; import ua.com.fielden.platform.sample.domain.TgPersonName; import ua.com.fielden.platform.sample.domain.TgTimesheet; import ua.com.fielden.platform.sample.domain.TgVehicle; import ua.com.fielden.platform.sample.domain.TgVehicleFinDetails; import ua.com.fielden.platform.sample.domain.TgVehicleMake; import ua.com.fielden.platform.sample.domain.TgVehicleModel; import ua.com.fielden.platform.sample.domain.TgWagon; import ua.com.fielden.platform.sample.domain.TgWagonSlot; import ua.com.fielden.platform.sample.domain.TgWorkshop; import ua.com.fielden.platform.security.user.User; import ua.com.fielden.platform.security.user.UserAndRoleAssociation; import ua.com.fielden.platform.security.user.UserRole; import ua.com.fielden.platform.test.AbstractDomainDrivenTestCase; import ua.com.fielden.platform.test.PlatformTestDomainTypes; import ua.com.fielden.platform.types.Money; public class EntityProxyLoadingTest extends AbstractDomainDrivenTestCase { private final ITgBogie coBogie = getInstance(ITgBogie.class); private final ITgVehicle coVehicle = getInstance(ITgVehicle.class); private static void shouldNotBeProxy(Class<? extends AbstractEntity<?>> entityClass) { assertFalse("Should not be proxy", isProxyClass(entityClass)); } private static void shouldBeProxy(final AbstractEntity<?> entity, final String propName) { assertTrue("Should be proxy", Reflector.isPropertyProxied(entity, propName)); } private static void shouldNotBeProxy(final AbstractEntity<?> entity, final String propName) { assertFalse("Should not be proxy", Reflector.isPropertyProxied(entity, propName)); } ///////////////////////////// primitive prop ////////////////////////////// @Test public void not_null_primitive_property_outside_fetch_model_should_be_proxied() { final EntityResultQueryModel<TgVehicle> model = select(TgVehicle.class).where().prop("key").eq().val("CAR2").model(); final TgVehicle vehicle = coVehicle.getEntity(from(model).with(fetch(TgVehicle.class).without("desc")).model()); shouldBeProxy(vehicle, "desc"); } @Test public void not_null_calc_property_outside_fetch_model_should_be_proxied() { final EntityResultQueryModel<TgVehicle> model = select(TgVehicle.class).where().prop("key").eq().val("CAR2").model(); final TgVehicle vehicle = coVehicle.getEntity(from(model).model()); shouldBeProxy(vehicle, "constValueProp"); } ///////////////////////////// usual entity prop ////////////////////////////// @Test public void not_null_entity_property_outside_fetch_model_should_be_proxied() { final EntityResultQueryModel<TgVehicle> model = select(TgVehicle.class).where().prop("key").eq().val("CAR2").model(); final TgVehicle vehicle = coVehicle.getEntity(from(model).model()); shouldBeProxy(vehicle, "replacedBy"); } @Test public void null_entity_property_outside_fetch_model_should_be_also_proxied() { final EntityResultQueryModel<TgVehicle> model = select(TgVehicle.class).where().prop("key").eq().val("CAR1").model(); final TgVehicle vehicle = coVehicle.getEntity(from(model).model()); shouldBeProxy(vehicle, "replacedBy"); } @Test public void null_entity_property_within_fetch_model_should_not_be_proxied() { final EntityResultQueryModel<TgVehicle> model = select(TgVehicle.class).where().prop("key").eq().val("CAR1").model(); final TgVehicle vehicle = coVehicle.getEntity(from(model).with(fetch(TgVehicle.class).with("replacedBy")).model()); shouldNotBeProxy(vehicle, "replacedBy"); assertNull(vehicle.getReplacedBy()); } @Test public void not_null_entity_property_within_fetch_model_should_not_be_proxied() { final EntityResultQueryModel<TgVehicle> model = select(TgVehicle.class).where().prop("key").eq().val("CAR2").model(); final TgVehicle vehicle = coVehicle.getEntity(from(model).with(fetch(TgVehicle.class).with("replacedBy")).model()); shouldNotBeProxy(vehicle.getReplacedBy().getClass()); shouldNotBeProxy(vehicle, "replacedBy"); assertNotNull(vehicle.getReplacedBy()); } ///////////////////////////// 1-2-1 entity prop (implicitly calculated prop) ////////////////////////////// @Test public void not_null_121_property_outside_fetch_model_should_be_proxied() { final EntityResultQueryModel<TgVehicle> model = select(TgVehicle.class).where().prop("key").eq().val("CAR1").model(); final TgVehicle vehicle = coVehicle.getEntity(from(model).model()); shouldBeProxy(vehicle, "finDetails"); } @Test public void null_121_property_outside_fetch_model_should_also_be_proxied() { final EntityResultQueryModel<TgVehicle> model = select(TgVehicle.class).where().prop("key").eq().val("CAR2").model(); final TgVehicle vehicle = coVehicle.getEntity(from(model).model()); shouldBeProxy(vehicle, "finDetails"); } @Test public void not_null_121_property_within_fetch_model_should_not_be_proxied() { final EntityResultQueryModel<TgVehicle> model = select(TgVehicle.class).where().prop("key").eq().val("CAR1").model(); final TgVehicle vehicle = coVehicle.getEntity(from(model).with(fetch(TgVehicle.class).with("finDetails")).model()); shouldNotBeProxy(vehicle, "finDetails"); shouldNotBeProxy(vehicle.getFinDetails().getClass()); assertNotNull(vehicle.getFinDetails()); } @Test public void null_121_property_within_fetch_model_should_not_be_proxied() { final EntityResultQueryModel<TgVehicle> model = select(TgVehicle.class).where().prop("key").eq().val("CAR2").model(); final TgVehicle vehicle = coVehicle.getEntity(from(model).with(fetch(TgVehicle.class).with("finDetails")).model()); shouldNotBeProxy(vehicle, "finDetails"); assertNull(vehicle.getFinDetails()); } ///////////////////////////// calculated entity prop (explicitly calculated prop) ////////////////////////////// @Test public void not_null_calculated_property_outside_fetch_model_should_be_proxied() { final EntityResultQueryModel<TgVehicle> model = select(TgVehicle.class).where().prop("key").eq().val("CAR2").model(); final TgVehicle vehicle = coVehicle.getEntity(from(model).with(fetch(TgVehicle.class).with("finDetails")).model()); shouldBeProxy(vehicle, "lastFuelUsage"); } @Test public void not_null_calculated_property_within_fetch_model_should_not_be_proxied() { final EntityResultQueryModel<TgVehicle> model = select(TgVehicle.class).where().prop("key").eq().val("CAR2").model(); final TgVehicle vehicle = coVehicle.getEntity(from(model).with(fetch(TgVehicle.class).with("lastFuelUsage")).model()); shouldNotBeProxy(vehicle, "lastFuelUsage"); assertNotNull(vehicle.getLastFuelUsage().getId()); } ///////////////////////////// other ////////////////////////////// @Test public void test_fetch_all_with_calc_prop() { final EntityResultQueryModel<TgVehicle> qry = select(TgVehicle.class).where().prop("key").eq().val("CAR2").model(); final TgVehicle veh = coVehicle.getEntity(from(qry).with(fetchAll(TgVehicle.class).with("lastFuelUsage")).model()); shouldNotBeProxy(veh, "replacedBy"); shouldNotBeProxy(veh, "lastFuelUsage"); shouldNotBeProxy(veh.getLastFuelUsage(), "vehicle"); shouldNotBeProxy(veh.getLastFuelUsage().getVehicle(), "replacedBy"); } @Test public void test_fetch_all_with_121_prop() { final EntityResultQueryModel<TgVehicle> qry = select(TgVehicle.class).where().prop("key").eq().val("CAR2").model(); final TgVehicle veh = coVehicle.getEntity(from(qry).with(fetchAll(TgVehicle.class).with("finDetails", fetch(TgVehicleFinDetails.class))).model()); shouldNotBeProxy(veh, "replacedBy"); shouldNotBeProxy(veh, "finDetails"); } @Test public void test_fetch_of_one_to_one_master_entity_model() { final EntityResultQueryModel<TgVehicle> qry = select(TgVehicle.class).where().prop("key").eq().val("CAR1").model(); final TgVehicle veh = coVehicle.getEntity(from(qry).with(fetchAll(TgVehicle.class).with("finDetails", fetch(TgVehicleFinDetails.class))).model()); shouldNotBeProxy(veh, "model"); shouldNotBeProxy(veh, "finDetails"); shouldNotBeProxy(veh.getFinDetails(), "key"); shouldNotBeProxy(veh.getFinDetails().getKey(), "model"); } @Test public void test_query_with_union_property_being_null() { final EntityResultQueryModel<TgBogie> qry = select(TgBogie.class).where().prop("key").eq().val("BOGIE2").model(); TgBogie bogie = coBogie.getEntity(from(qry).with(fetch(TgBogie.class).with("location", fetch(TgBogieLocation.class).with("wagonSlot").with("workshop"))).model()); shouldNotBeProxy(bogie, "location"); assertNull(bogie.getLocation()); } @Test public void test_query_for_correct_fetching_adjustment() { final EntityResultQueryModel<TgVehicle> qry = select(TgVehicle.class). where().prop("key").eq().val("CAR2"). yield().prop("key").as("key"). yield().prop("desc").as("desc"). yield().prop("model").as("model"). yield().prop("model.make").as("model.make"). yield().prop("model.make.key").as("model.make.key"). modelAsEntity(TgVehicle.class); final TgVehicle vehicle1 = coVehicle.getEntity(from(qry).with(fetch(TgVehicle.class). with("key"). with("desc"). with("model", fetchOnly(TgVehicleModel.class). with("key"). with("make", fetchOnly(TgVehicleMake.class). with("key")))).model()); assertNotNull(vehicle1.getModel().getMake().getKey()); assertTrue(vehicle1.getProperty("replacedBy").isProxy()); } @Override protected void populateDomain() { final TgFuelType unleadedFuelType = save(new_(TgFuelType.class, "U", "Unleaded")); final TgFuelType petrolFuelType = save(new_(TgFuelType.class, "P", "Petrol")); final TgWorkshop workshop1 = save(new_(TgWorkshop.class, "WSHOP1", "Workshop 1")); final TgWorkshop workshop2 = save(new_(TgWorkshop.class, "WSHOP2", "Workshop 2")); final TgBogieLocation location = config.getEntityFactory().newEntity(TgBogieLocation.class); location.setWorkshop(workshop1); final TgBogie bogie1 = save(new_(TgBogie.class, "BOGIE1", "Bogie 1").setLocation(location)); final TgBogie bogie2 = save(new_(TgBogie.class, "BOGIE2", "Bogie 2")); final TgBogie bogie3 = save(new_(TgBogie.class, "BOGIE3", "Bogie 3")); final TgBogie bogie4 = save(new_(TgBogie.class, "BOGIE4", "Bogie 4")); final TgBogie bogie5 = save(new_(TgBogie.class, "BOGIE5", "Bogie 5")); final TgBogie bogie6 = save(new_(TgBogie.class, "BOGIE6", "Bogie 6")); final TgBogie bogie7 = save(new_(TgBogie.class, "BOGIE7", "Bogie 7")); final TgWagon wagon1 = save(new_(TgWagon.class, "WAGON1", "Wagon 1")); final TgWagon wagon2 = save(new_(TgWagon.class, "WAGON2", "Wagon 2")); save(new_composite(TgWagonSlot.class, wagon1, 5)); save(new_composite(TgWagonSlot.class, wagon1, 6)); save(new_composite(TgWagonSlot.class, wagon1, 7)); save(new_composite(TgWagonSlot.class, wagon1, 8)); save(new_composite(TgWagonSlot.class, wagon1, 4).setBogie(bogie1)); save(new_composite(TgWagonSlot.class, wagon1, 3).setBogie(bogie2)); save(new_composite(TgWagonSlot.class, wagon1, 2).setBogie(bogie3)); save(new_composite(TgWagonSlot.class, wagon1, 1).setBogie(bogie4)); save(new_composite(TgWagonSlot.class, wagon2, 1).setBogie(bogie5)); save(new_composite(TgWagonSlot.class, wagon2, 2).setBogie(bogie6)); save(new_composite(TgWagonSlot.class, wagon2, 3).setBogie(bogie7)); final TgOrgUnit1 orgUnit1 = save(new_(TgOrgUnit1.class, "orgunit1", "desc orgunit1")); final TgOrgUnit2 orgUnit2 = save(new_composite(TgOrgUnit2.class, orgUnit1, "orgunit2")); final TgOrgUnit3 orgUnit3 = save(new_composite(TgOrgUnit3.class, orgUnit2, "orgunit3")); final TgOrgUnit4 orgUnit4 = save(new_composite(TgOrgUnit4.class, orgUnit3, "orgunit4")); final TgOrgUnit5 orgUnit5 = save(new_composite(TgOrgUnit5.class, orgUnit4, "orgunit5")); final TgVehicleMake merc = save(new_(TgVehicleMake.class, "MERC", "Mercedes")); final TgVehicleMake audi = save(new_(TgVehicleMake.class, "AUDI", "Audi")); final TgVehicleMake bmw = save(new_(TgVehicleMake.class, "BMW", "BMW")); final TgVehicleMake subaro = save(new_(TgVehicleMake.class, "SUBARO", "Subaro")); final TgVehicleModel m316 = save(new_(TgVehicleModel.class, "316", "316").setMake(merc)); final TgVehicleModel m317 = save(new_(TgVehicleModel.class, "317", "317").setMake(audi)); final TgVehicleModel m318 = save(new_(TgVehicleModel.class, "318", "318").setMake(audi)); final TgVehicleModel m319 = save(new_(TgVehicleModel.class, "319", "319").setMake(bmw)); final TgVehicleModel m320 = save(new_(TgVehicleModel.class, "320", "320").setMake(bmw)); final TgVehicleModel m321 = save(new_(TgVehicleModel.class, "321", "321").setMake(bmw)); final TgVehicleModel m322 = save(new_(TgVehicleModel.class, "322", "322").setMake(bmw)); final TgVehicle car1 = save(new_(TgVehicle.class, "CAR1", "CAR1 DESC").setInitDate(date("2001-01-01 00:00:00")).setModel(m318).setPrice(new Money("20")).setPurchasePrice(new Money("10")).setActive(true).setLeased(false)); final TgVehicle car2 = save(new_(TgVehicle.class, "CAR2", "CAR2 DESC").setInitDate(date("2007-01-01 00:00:00")).setModel(m316).setPrice(new Money("200")).setPurchasePrice(new Money("100")).setActive(false).setLeased(true).setLastMeterReading(new BigDecimal("105")).setStation(orgUnit5).setReplacedBy(car1)); save(new_(TgVehicleFinDetails.class, car1).setCapitalWorksNo("CAP_NO1")); save(new_composite(TgFuelUsage.class, car2, date("2006-02-09 00:00:00")).setQty(new BigDecimal("100")).setFuelType(unleadedFuelType)); save(new_composite(TgFuelUsage.class, car2, date("2008-02-10 00:00:00")).setQty(new BigDecimal("120")).setFuelType(petrolFuelType)); save(new_composite(TgTimesheet.class, "USER1", date("2011-11-01 13:00:00")).setFinishDate(date("2011-11-01 15:00:00")).setIncident("002")); final UserRole managerRole = save(new_(UserRole.class, "MANAGER", "Managerial role")); final UserRole dataEntryRole = save(new_(UserRole.class, "DATAENTRY", "Data entry role")); final UserRole analyticRole = save(new_(UserRole.class, "ANALYTIC", "Analytic role")); final UserRole fleetOperatorRole = save(new_(UserRole.class, "FLEET_OPERATOR", "Fleet operator role")); final UserRole workshopOperatorRole = save(new_(UserRole.class, "WORKSHOP_OPERATOR", "Workshop operator role")); final UserRole warehouseOperatorRole = save(new_(UserRole.class, "WAREHOUSE_OPERATOR", "Warehouse operator role")); final User baseUser1 = save(new_(User.class, "base_user1", "base user1").setBase(true).setPassword("password1")); final User user1 = save(new_(User.class, "user1", "user1 desc").setBase(false).setBasedOnUser(baseUser1).setPassword("password1")); final User user2 = save(new_(User.class, "user2", "user2 desc").setBase(false).setBasedOnUser(baseUser1).setPassword("password1")); final User user3 = save(new_(User.class, "user3", "user3 desc").setBase(false).setBasedOnUser(baseUser1).setPassword("password1")); save(new_composite(UserAndRoleAssociation.class, user1, managerRole)); save(new_composite(UserAndRoleAssociation.class, user1, analyticRole)); save(new_composite(UserAndRoleAssociation.class, user2, dataEntryRole)); save(new_composite(UserAndRoleAssociation.class, user2, fleetOperatorRole)); save(new_composite(UserAndRoleAssociation.class, user2, warehouseOperatorRole)); save(new_composite(UserAndRoleAssociation.class, user3, dataEntryRole)); save(new_composite(UserAndRoleAssociation.class, user3, fleetOperatorRole)); save(new_composite(UserAndRoleAssociation.class, user3, warehouseOperatorRole)); final TgPersonName chris = save(new_(TgPersonName.class, "Chris", "Chris")); save(new_composite(TgAuthor.class, chris, "Date", null)); final TgPersonName yurij = save(new_(TgPersonName.class, "Yurij", "Yurij")); save(new_composite(TgAuthor.class, yurij, "Shcherbyna", "Mykolajovych")); System.out.println("\n\n\n\n\n\n\n\n\n ===== DATA POPULATED SUCCESSFULLY =====\n\n\n\n\n\n\n\n\n"); } @Override protected List<Class<? extends AbstractEntity<?>>> domainEntityTypes() { return PlatformTestDomainTypes.entityTypes; } }
package org.httpkit; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; /** * No synchronization, better toString */ public class BytesInputStream extends InputStream { private final byte[] buf; private final int count; private int mark = 0; private int pos; public BytesInputStream(byte[] data, int length) { this.buf = data; this.count = length; this.pos = 0; } /** * get the underlying bytes, copied * * @return */ public byte[] bytes() { return Arrays.copyOf(buf, count); } public int read() throws IOException { return (pos < count) ? (buf[pos++] & 0xff) : -1; } public int read(byte[] b) throws IOException { return read(b, 0, b.length); } public int read(byte[] b, int off, int len) throws IOException { if (pos >= count) { return -1; } int avail = count - pos; if (len > avail) { len = avail; } System.arraycopy(buf, pos, b, off, len); pos += len; return len; } public String toString() { return "BytesInputStream[len=" + count + "]"; } public long skip(long n) throws IOException { long k = count - pos; if (n < k) { k = n < 0 ? 0 : n; } pos += k; return k; } public int available() { return count - pos; } public boolean markSupported() { return true; } public void mark(int readAheadLimit) { mark = pos; } public void reset() { pos = mark; } public int getCount() { return count; } }
package org.jsimpledb.kv.mvcc; import com.google.common.base.Converter; import com.google.common.base.Preconditions; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.List; import java.util.Map; import java.util.NavigableMap; import java.util.TreeMap; import org.jsimpledb.kv.KVStore; import org.jsimpledb.kv.KeyRange; import org.jsimpledb.kv.KeyRanges; import org.jsimpledb.kv.util.KeyListEncoder; import org.jsimpledb.util.ByteUtil; import org.jsimpledb.util.ConvertedNavigableMap; import org.jsimpledb.util.LongEncoder; import org.jsimpledb.util.SizeEstimating; import org.jsimpledb.util.SizeEstimator; import org.jsimpledb.util.UnsignedIntEncoder; /** * Holds a set of writes to a {@link KVStore}. * * <p> * Each mutation is either a key/value put, the removal of a key range (possibly containing only a single key), * or a counter adjustment. * * <p> * Instances are not thread safe. * </p> */ public class Writes implements Cloneable, Mutations, SizeEstimating { private KeyRanges removes = KeyRanges.EMPTY; private /*final*/ TreeMap<byte[], byte[]> puts = new TreeMap<>(ByteUtil.COMPARATOR); private /*final*/ TreeMap<byte[], Long> adjusts = new TreeMap<>(ByteUtil.COMPARATOR); // Accessors /** * Get the key ranges removals contained by this instance. * * @return key ranges removed */ public KeyRanges getRemoves() { return this.removes; } public void setRemoves(KeyRanges removes) { Preconditions.checkArgument(removes != null, "null removes"); this.removes = removes; } /** * Get the written key/value pairs contained by this instance. * * <p> * The caller must not modify any of the returned {@code byte[]} arrays. * </p> * * @return mutable mapping from key to corresponding value */ public NavigableMap<byte[], byte[]> getPuts() { return this.puts; } /** * Get the set of counter adjustments contained by this instance. * * <p> * The caller must not modify any of the returned {@code byte[]} arrays. * </p> * * @return mutable mapping from key to corresponding counter adjustment */ public NavigableMap<byte[], Long> getAdjusts() { return this.adjusts; } /** * Determine whether this instance is empty, i.e., contains zero mutations. * * @return true if this instance contains zero mutations, otherwise false */ public boolean isEmpty() { return this.removes.isEmpty() && this.puts.isEmpty() && this.adjusts.isEmpty(); } /** * Clear all mutations. */ public void clear() { this.removes = KeyRanges.EMPTY; this.puts.clear(); this.adjusts.clear(); } // Mutations @Override public List<KeyRange> getRemoveRanges() { return this.removes.asList(); } @Override public Iterable<Map.Entry<byte[], byte[]>> getPutPairs() { return this.puts.entrySet(); } @Override public Iterable<Map.Entry<byte[], Long>> getAdjustPairs() { return this.adjusts.entrySet(); } // Application public void applyTo(KVStore target) { Writes.apply(this, target); } public static void apply(Mutations mutations, KVStore target) { Preconditions.checkArgument(mutations != null, "null mutations"); Preconditions.checkArgument(target != null, "null target"); for (KeyRange remove : mutations.getRemoveRanges()) target.removeRange(remove.getMin(), remove.getMax()); for (Map.Entry<byte[], byte[]> entry : mutations.getPutPairs()) target.put(entry.getKey(), entry.getValue()); for (Map.Entry<byte[], Long> entry : mutations.getAdjustPairs()) target.adjustCounter(entry.getKey(), entry.getValue()); } // Serialization /** * Serialize this instance. * * @param out output * @throws IOException if an error occurs */ public void serialize(OutputStream out) throws IOException { // Removes this.removes.serialize(out); // Puts UnsignedIntEncoder.write(out, this.puts.size()); byte[] prev = null; for (Map.Entry<byte[], byte[]> entry : this.puts.entrySet()) { final byte[] key = entry.getKey(); final byte[] value = entry.getValue(); KeyListEncoder.write(out, key, prev); KeyListEncoder.write(out, value, null); prev = key; } // Adjusts UnsignedIntEncoder.write(out, this.adjusts.size()); prev = null; for (Map.Entry<byte[], Long> entry : this.adjusts.entrySet()) { final byte[] key = entry.getKey(); final long value = entry.getValue(); KeyListEncoder.write(out, key, prev); LongEncoder.write(out, value); prev = key; } } /** * Calculate the number of bytes required to serialize this instance via {@link #serialize serialize()}. * * @return number of serialized bytes */ public long serializedLength() { // Removes long total = this.removes.serializedLength(); // Puts total += UnsignedIntEncoder.encodeLength(this.puts.size()); byte[] prev = null; for (Map.Entry<byte[], byte[]> entry : this.puts.entrySet()) { final byte[] key = entry.getKey(); final byte[] value = entry.getValue(); total += KeyListEncoder.writeLength(key, prev); total += KeyListEncoder.writeLength(value, null); prev = key; } // Adjusts total += UnsignedIntEncoder.encodeLength(this.adjusts.size()); prev = null; for (Map.Entry<byte[], Long> entry : this.adjusts.entrySet()) { final byte[] key = entry.getKey(); final long value = entry.getValue(); total += KeyListEncoder.writeLength(key, prev); total += LongEncoder.encodeLength(value); prev = key; } // Done return total; } public static Writes deserialize(InputStream input) throws IOException { Preconditions.checkArgument(input != null, "null input"); // Create new instance final Writes writes = new Writes(); // Populate removes writes.removes = KeyRanges.deserialize(input); // Populate puts int count = UnsignedIntEncoder.read(input); byte[] prev = null; for (int i = 0; i < count; i++) { final byte[] key = KeyListEncoder.read(input, prev); final byte[] value = KeyListEncoder.read(input, null); writes.puts.put(key, value); prev = key; } // Populate adjusts count = UnsignedIntEncoder.read(input); prev = null; for (int i = 0; i < count; i++) { final byte[] key = KeyListEncoder.read(input, prev); final long value = LongEncoder.read(input); writes.adjusts.put(key, value); prev = key; } // Done return writes; } // SizeEstimating @Override public void addTo(SizeEstimator estimator) { estimator .addObjectOverhead() .addField(this.removes) .addTreeMapField(this.puts) .addTreeMapField(this.adjusts); for (Map.Entry<byte[], byte[]> entry : this.puts.entrySet()) { estimator .add(entry.getKey()) .add(entry.getValue()); } for (Map.Entry<byte[], Long> entry : this.adjusts.entrySet()) { estimator .add(entry.getKey()) .addObjectOverhead() .addLongField(); } } // Cloneable @Override @SuppressWarnings("unchecked") public Writes clone() { final Writes clone; try { clone = (Writes)super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } clone.puts = (TreeMap<byte[], byte[]>)this.puts.clone(); clone.adjusts = (TreeMap<byte[], Long>)this.adjusts.clone(); return clone; } // Object @Override public String toString() { final Converter<String, byte[]> byteConverter = ByteUtil.STRING_CONVERTER.reverse(); final ConvertedNavigableMap<String, String, byte[], byte[]> putsView = new ConvertedNavigableMap<>(this.puts, byteConverter, byteConverter); final ConvertedNavigableMap<String, Long, byte[], Long> adjustsView = new ConvertedNavigableMap<>(this.adjusts, byteConverter, Converter.<Long>identity()); return this.getClass().getSimpleName() + "[removes=" + this.removes + ",puts=" + putsView + (!this.adjusts.isEmpty() ? ",adjusts=" + adjustsView : "") + "]"; } }
package com.intellij.codeInsight.editorActions; import com.intellij.codeInsight.CodeInsightSettings; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.RangeMarker; import com.intellij.openapi.editor.actions.EditorActionUtil; import com.intellij.openapi.editor.impl.DocumentImpl; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.CharFilter; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; import com.intellij.psi.codeStyle.CodeStyleSettingsManager; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.io.IOException; /** * @author yole */ public class CopyPasteIndentProcessor implements CopyPastePostProcessor<IndentTransferableData> { @Override public IndentTransferableData collectTransferableData(PsiFile file, Editor editor, int[] startOffsets, int[] endOffsets) { if (!acceptFileType(file.getFileType())) { return null; } return new IndentTransferableData(editor.getCaretModel().getOffset()); } private static boolean acceptFileType(FileType fileType) { for(PreserveIndentOnPasteBean bean: Extensions.getExtensions(PreserveIndentOnPasteBean.EP_NAME)) { if (fileType.getName().equals(bean.fileType)) { return true; } } return false; } @Override public IndentTransferableData extractTransferableData(Transferable content) { IndentTransferableData indentData = new IndentTransferableData(-1); try { final DataFlavor flavor = IndentTransferableData.getDataFlavorStatic(); if (flavor != null) { final Object transferData = content.getTransferData(flavor); if (transferData instanceof IndentTransferableData) { indentData = (IndentTransferableData)transferData; } } } catch (UnsupportedFlavorException e) { // do nothing } catch (IOException e) { // do nothing } return indentData; } @Override public void processTransferableData(final Project project, final Editor editor, final RangeMarker bounds, final int caretOffset, final Ref<Boolean> indented, final IndentTransferableData value) { if (!CodeInsightSettings.getInstance().INDENT_TO_CARET_ON_PASTE) { return; } if (value.getOffset() == caretOffset) return; final Document document = editor.getDocument(); final PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document); if (psiFile == null || !acceptFileType(psiFile.getFileType())) { return; } ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override public void run() { final boolean useTabs = CodeStyleSettingsManager.getSettings(project).useTabCharacter(psiFile.getFileType()); CharFilter NOT_INDENT_FILTER = new CharFilter() { public boolean accept(char ch) { return useTabs? ch != '\t' : !Character.isWhitespace(ch); } }; String pastedText = document.getText(TextRange.create(bounds)); int startLine = document.getLineNumber(bounds.getStartOffset()); int endLine = document.getLineNumber(bounds.getEndOffset()); //calculate from indent int fromIndent = StringUtil.findFirst(pastedText, NOT_INDENT_FILTER); if (fromIndent < 0) fromIndent = 0; //calculate to indent String initialText = document.getText(TextRange.create(0, bounds.getStartOffset())) + document.getText(TextRange.create(bounds.getEndOffset(), document.getTextLength())); int toIndent = 0; if (initialText.length() > 0) { final DocumentImpl initialDocument = new DocumentImpl(initialText); int lineNumber = initialDocument.getTextLength() > caretOffset? initialDocument.getLineNumber(caretOffset) : initialDocument.getLineCount() - 1; final int offset = getLineStartSafeOffset(initialDocument, lineNumber); if (bounds.getStartOffset() == offset) { String toString = initialDocument.getText(TextRange.create(offset, initialDocument.getLineEndOffset(lineNumber))); toIndent = StringUtil.findFirst(toString, NOT_INDENT_FILTER); if (toIndent < 0 && StringUtil.isEmptyOrSpaces(toString)) { toIndent = toString.length(); } else if ((toIndent < 0 || toString.startsWith("\n")) && initialText.length() >= caretOffset) { toIndent = caretOffset - offset; } } else if (isNotApplicable(initialDocument, offset)) return; else { // selection startLine += 1; toIndent = Math.abs(bounds.getStartOffset() - offset); } } // actual difference in indentation level int indent = toIndent - fromIndent; if (useTabs) // indent is counted in tab units indent *= CodeStyleSettingsManager.getSettings(project).getTabSize(psiFile.getFileType()); // don't indent single-line text if (!StringUtil.startsWithWhitespace(pastedText) && !StringUtil.endsWithLineBreak(pastedText) && !(StringUtil.splitByLines(pastedText).length > 1)) return; if (pastedText.endsWith("\n")) endLine -= 1; for (int i = startLine; i <= endLine; i++) { EditorActionUtil.indentLine(project, editor, i, indent); } indented.set(Boolean.TRUE); } private boolean isNotApplicable(DocumentImpl initialDocument, int offset) { return caretOffset < initialDocument.getTextLength() && !StringUtil .isEmptyOrSpaces(initialDocument.getText(TextRange.create(offset, caretOffset))); } }); } private static int getLineStartSafeOffset(final Document document, int line) { if (line >= document.getLineCount()) return document.getTextLength(); return document.getLineStartOffset(line); } }
package jse8_impatient.chapter2; import java.util.stream.IntStream; import java.util.stream.Stream; public class Exercise6 { public static void main(String [] args) throws Exception { System.out.println("Chapter2 - Exercise6"); characterStream("blah chapter 2 exercise 6").forEach(System.out::println); } public static Stream<Character> characterStream(String s) { return IntStream.range(0, s.length()).mapToObj(s::charAt); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package erp.mod.hrs.view; import erp.cfd.SCfdConsts; import erp.client.SClientInterface; import erp.data.SDataConstants; import erp.data.SDataConstantsSys; import erp.data.SDataUtilities; import erp.lib.SLibConstants; import erp.mhrs.data.SDataFormerPayroll; import erp.mhrs.data.SDataPayrollReceiptIssue; import erp.mod.SModConsts; import erp.mod.SModSysConsts; import erp.mod.hrs.db.SHrsFormerPayroll; import erp.mod.hrs.db.SHrsFormerUtils; import erp.mod.hrs.db.SHrsPayrollAnnul; import erp.mod.hrs.db.SHrsUtils; import erp.mod.hrs.form.SDialogFormerPayrollDate; import erp.mod.hrs.form.SDialogPrintOrderPayroll; import erp.mtrn.data.SCfdUtils; import erp.mtrn.data.SDataCfd; import erp.mtrn.form.SDialogAnnulCfdi; import java.awt.Cursor; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JOptionPane; import sa.lib.SLibConsts; import sa.lib.SLibTimeUtils; import sa.lib.SLibUtils; import sa.lib.db.SDbConsts; import sa.lib.grid.SGridColumnView; import sa.lib.grid.SGridConsts; import sa.lib.grid.SGridFilterDatePeriod; import sa.lib.grid.SGridPaneSettings; import sa.lib.grid.SGridPaneView; import sa.lib.grid.SGridRow; import sa.lib.grid.SGridRowView; import sa.lib.grid.SGridUtils; import sa.lib.gui.SGuiClient; import sa.lib.gui.SGuiConsts; import sa.lib.gui.SGuiDate; import sa.lib.gui.SGuiParams; /** * * @author Juan Barajas */ public class SViewCfdiPayroll extends SGridPaneView implements ActionListener { private SGridFilterDatePeriod moFilterDatePeriod; private JButton jbReemit; private JButton jbSignPayroll; private JButton jbAnnulPayroll; private JButton jbGetXml; private JButton jbGetAcknowledgmentCancellation; private JButton jbPrint; private JButton jbPrintAcknowledgmentCancellation; private JButton jbSendMail; private JButton jbVerifyCfdi; private JButton jbRestoreSignedXml; private JButton jbRestoreAcknowledgmentCancellation; private JButton jbDeactivateControlFlags; private SDialogAnnulCfdi moDialogAnnulCfdi; private SDialogFormerPayrollDate moDialogFormerPayrollDate; public SViewCfdiPayroll(SGuiClient client, int subType, String title, SGuiParams params) { super(client, SGridConsts.GRID_PANE_VIEW, SModConsts.HRS_SIE_PAY, subType, title, params); setRowButtonsEnabled(false, false, false, false, mnGridSubtype == SModConsts.VIEW_SC_SUM); jtbFilterDeleted.setEnabled(false); initComponetsCustom(); } private void initComponetsCustom() { moFilterDatePeriod = new SGridFilterDatePeriod(miClient, this, SGuiConsts.DATE_PICKER_DATE_PERIOD); moFilterDatePeriod.initFilter(new SGuiDate(SGuiConsts.GUI_DATE_MONTH, miClient.getSession().getCurrentDate().getTime())); jbReemit = SGridUtils.createButton(miClient.getImageIcon(SLibConstants.ICON_DOC_IMPORT), "Regenerar CFDI", this); jbSignPayroll = SGridUtils.createButton(miClient.getImageIcon(SLibConstants.ICON_DOC_XML_SIGN), "Timbrar CFDI", this); jbAnnulPayroll = SGridUtils.createButton(miClient.getImageIcon(SLibConstants.ICON_ANNUL), "Anular " + (mnGridSubtype == SModConsts.VIEW_SC_SUM ? "" : "recibo ") + "nómina", this); jbGetXml = SGridUtils.createButton(miClient.getImageIcon(SLibConstants.ICON_DOC_XML), "Obtener XML del comprobante", this); jbGetAcknowledgmentCancellation = SGridUtils.createButton(miClient.getImageIcon(SLibConstants.ICON_DOC_XML_CANCEL), "Obtener XML del acuse de cancelación del CFDI", this); jbPrint = SGridUtils.createButton(miClient.getImageIcon(SLibConstants.ICON_PRINT), "Imprimir " + (mnGridSubtype == SModConsts.VIEW_SC_SUM ? "" : "recibo ") + "nómina", this); jbPrintAcknowledgmentCancellation = SGridUtils.createButton(miClient.getImageIcon(SLibConstants.ICON_PRINT_ACK_CAN), "Imprimir acuse de cancelación", this); jbSendMail = SGridUtils.createButton(new ImageIcon(getClass().getResource("/erp/img/icon_std_mail.gif")), "Enviar " + (mnGridSubtype == SModConsts.VIEW_SC_SUM ? "" : "recibo ") + "nómina", this); jbVerifyCfdi = SGridUtils.createButton(new ImageIcon(getClass().getResource("/erp/img/icon_std_ok.gif")), "Verificar timbrado o cancelación " + (mnGridSubtype == SModConsts.VIEW_SC_SUM ? "de los " : "del ") + "CFDI", this); jbRestoreSignedXml = SGridUtils.createButton(new ImageIcon(getClass().getResource("/erp/img/icon_std_insert.gif")), "Insertar XML timbrado del CFDI", this); jbRestoreAcknowledgmentCancellation = SGridUtils.createButton(new ImageIcon(getClass().getResource("/erp/img/icon_std_insert.gif")), "Insertar PDF del acuse de cancelación del CFDI", this); jbDeactivateControlFlags = SGridUtils.createButton(new ImageIcon(getClass().getResource("/erp/img/icon_std_action.gif")), "Limpiar inconsistencias del timbrado o cancelación del CFDI", this); moDialogAnnulCfdi = new SDialogAnnulCfdi((SClientInterface) miClient, true); moDialogFormerPayrollDate = new SDialogFormerPayrollDate(miClient, SModConsts.HRSX_DATE, "Fecha de pago"); switch (mnGridSubtype) { case SModConsts.VIEW_SC_SUM: jbReemit.setEnabled(isCfdiPayrollVersionOld()); jbSignPayroll.setEnabled(true); jbAnnulPayroll.setEnabled(true); jbGetXml.setEnabled(false); jbGetAcknowledgmentCancellation.setEnabled(false); jbPrint.setEnabled(true); jbPrintAcknowledgmentCancellation.setEnabled(true); jbSendMail.setEnabled(true); jbVerifyCfdi.setEnabled(true); jbRestoreSignedXml.setEnabled(false); jbRestoreAcknowledgmentCancellation.setEnabled(false); jbDeactivateControlFlags.setEnabled(false); break; case SModConsts.VIEW_SC_DET: jbReemit.setEnabled(false); jbSignPayroll.setEnabled(true); jbAnnulPayroll.setEnabled(true); jbGetXml.setEnabled(true); jbGetAcknowledgmentCancellation.setEnabled(true); jbPrint.setEnabled(true); jbPrintAcknowledgmentCancellation.setEnabled(true); jbSendMail.setEnabled(true); jbVerifyCfdi.setEnabled(true); jbRestoreSignedXml.setEnabled(true); jbRestoreAcknowledgmentCancellation.setEnabled(true); jbDeactivateControlFlags.setEnabled(true); break; default: miClient.showMsgBoxError(SLibConsts.ERR_MSG_OPTION_UNKNOWN); } getPanelCommandsSys(SGuiConsts.PANEL_CENTER).add(moFilterDatePeriod); getPanelCommandsSys(SGuiConsts.PANEL_CENTER).add(jbReemit); getPanelCommandsSys(SGuiConsts.PANEL_CENTER).add(jbSignPayroll); getPanelCommandsSys(SGuiConsts.PANEL_CENTER).add(jbAnnulPayroll); getPanelCommandsSys(SGuiConsts.PANEL_CENTER).add(jbGetXml); getPanelCommandsSys(SGuiConsts.PANEL_CENTER).add(jbGetAcknowledgmentCancellation); getPanelCommandsSys(SGuiConsts.PANEL_CENTER).add(jbPrint); getPanelCommandsSys(SGuiConsts.PANEL_CENTER).add(jbPrintAcknowledgmentCancellation); getPanelCommandsSys(SGuiConsts.PANEL_CENTER).add(jbSendMail); getPanelCommandsSys(SGuiConsts.PANEL_CENTER).add(jbVerifyCfdi); getPanelCommandsSys(SGuiConsts.PANEL_CENTER).add(jbRestoreSignedXml); getPanelCommandsSys(SGuiConsts.PANEL_CENTER).add(jbRestoreAcknowledgmentCancellation); getPanelCommandsSys(SGuiConsts.PANEL_CENTER).add(jbDeactivateControlFlags); } private void actionReemitPayroll() { SDataFormerPayroll oFormerPayroll = null; SHrsFormerPayroll payroll = null; if (jbReemit.isEnabled()) { if (jtTable.getSelectedRowCount() != 1) { miClient.showMsgBoxInformation(SGridConsts.MSG_SELECT_ROW); } else { SGridRowView gridRow = (SGridRowView) getSelectedGridRow(); if (gridRow.getRowType() != SGridConsts.ROW_TYPE_DATA) { miClient.showMsgBoxWarning(SGridConsts.ERR_MSG_ROW_TYPE_DATA); } else if (gridRow.isRowSystem()) { miClient.showMsgBoxWarning(SDbConsts.MSG_REG_ + gridRow.getRowName() + SDbConsts.MSG_REG_IS_SYSTEM); } else if (!gridRow.isUpdatable()) { miClient.showMsgBoxWarning(SDbConsts.MSG_REG_ + gridRow.getRowName() + SDbConsts.MSG_REG_NON_UPDATABLE); } else { try { moDialogFormerPayrollDate.setFormReset(); moDialogFormerPayrollDate.setVisible(true); if (moDialogFormerPayrollDate.getFormResult() == SGuiConsts.FORM_RESULT_OK) { payroll = SHrsFormerUtils.readFormerPayroll((SClientInterface) miClient, miClient.getSession().getStatement(), ((int []) gridRow.getRowPrimaryKey())[0], miClient.getSession().getConfigCompany().getCompanyId(), moDialogFormerPayrollDate.getDateEmission(), moDialogFormerPayrollDate.getDatePayment()); SCfdUtils.computeCfdiPayroll((SClientInterface) miClient, payroll, moDialogFormerPayrollDate.isRegenerateOnlyNonStampedCfdi()); // Update date of payment: oFormerPayroll = new SDataFormerPayroll(); oFormerPayroll.read(new int[] { ((int []) gridRow.getRowPrimaryKey())[0] }, miClient.getSession().getStatement()); if (oFormerPayroll != null) { oFormerPayroll.setFkUserEditId(miClient.getSession().getUser().getPkUserId()); oFormerPayroll.setDatePayment(moDialogFormerPayrollDate.getDatePayment()); if (oFormerPayroll.saveField((miClient.getSession().getDatabase().getConnection()), new int[] { ((int []) gridRow.getRowPrimaryKey())[0] }) != SLibConstants.DB_ACTION_SAVE_OK) { throw new Exception(SLibConstants.MSG_ERR_DB_REG_SAVE + "\n- No se pudo actualizar la fecha de pago."); } } miClient.getSession().notifySuscriptors(mnGridType); } } catch (Exception e) { miClient.getFrame().setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); SLibUtils.showException(this, e); } } } } } private boolean isCfdiPayrollVersionOld() { return mnGridMode == SCfdConsts.CFDI_PAYROLL_VER_OLD; } private void actionSignPayroll() { boolean sign = true; boolean needUpdate = false; SDataCfd cfd = null; SDataPayrollReceiptIssue receiptIssue = null; if (jbSignPayroll.isEnabled()) { if (jtTable.getSelectedRowCount() != 1) { miClient.showMsgBoxInformation(SGridConsts.MSG_SELECT_ROW); } else { SGridRowView gridRow = (SGridRowView) getSelectedGridRow(); if (gridRow.getRowType() != SGridConsts.ROW_TYPE_DATA) { miClient.showMsgBoxWarning(SGridConsts.ERR_MSG_ROW_TYPE_DATA); } else if (gridRow.isRowSystem()) { miClient.showMsgBoxWarning(SDbConsts.MSG_REG_ + gridRow.getRowName() + SDbConsts.MSG_REG_IS_SYSTEM); } else if (!gridRow.isUpdatable()) { miClient.showMsgBoxWarning(SDbConsts.MSG_REG_ + gridRow.getRowName() + SDbConsts.MSG_REG_NON_UPDATABLE); } else { try { if (mnGridSubtype == SModConsts.VIEW_SC_SUM) { // Stamp all payroll receipts: needUpdate = SCfdUtils.signCfdi((SClientInterface) miClient, SCfdUtils.getPayrollCfds((SClientInterface) miClient, (isCfdiPayrollVersionOld() ? SCfdConsts.CFDI_PAYROLL_VER_OLD : SCfdConsts.CFDI_PAYROLL_VER_CUR), gridRow.getRowPrimaryKey()), (isCfdiPayrollVersionOld() ? SCfdConsts.CFDI_PAYROLL_VER_OLD : SCfdConsts.CFDI_PAYROLL_VER_CUR)); } else { // Stamp current payroll receipt: cfd = (SDataCfd) SDataUtilities.readRegistry((SClientInterface) miClient, SDataConstants.TRN_CFD, gridRow.getRowPrimaryKey(), SLibConstants.EXEC_MODE_SILENT); if (!isCfdiPayrollVersionOld()) { receiptIssue = new SDataPayrollReceiptIssue(); if (receiptIssue.read(new int[] { cfd.getFkPayrollReceiptPayrollId_n(), cfd.getFkPayrollReceiptEmployeeId_n(), cfd.getFkPayrollReceiptIssueId_n() }, miClient.getSession().getStatement()) != SLibConstants.DB_ACTION_READ_OK) { throw new Exception(SLibConstants.MSG_ERR_DB_REG_READ_DEP + "\n El recibo no ha sido emitido."); } if (receiptIssue.isDeleted()) { sign = false; miClient.showMsgBoxWarning("El recibo '" + receiptIssue.getIssueNumber() + "' está eliminado."); } else if (receiptIssue.getFkReceiptStatusId() == SDataConstantsSys.TRNS_ST_DPS_ANNULED) { sign = false; miClient.showMsgBoxWarning("El recibo '" + receiptIssue.getIssueNumber() + "' está anulado."); } else if (!SDataUtilities.isPeriodOpen((SClientInterface) miClient, receiptIssue.getDateIssue())) { sign = false; miClient.showMsgBoxWarning(SLibConstants.MSG_ERR_GUI_PER_CLOSE); } } if (sign) { needUpdate = SCfdUtils.signCfdi((SClientInterface) miClient, cfd, (isCfdiPayrollVersionOld() ? SCfdConsts.CFDI_PAYROLL_VER_OLD : SCfdConsts.CFDI_PAYROLL_VER_CUR)); } } if (needUpdate) { miClient.getSession().notifySuscriptors(mnGridType); } } catch (Exception e) { SLibUtils.showException(this, e); } } } } } private void actionAnnulPayroll() { boolean needUpdate = false; SDataCfd cfd = null; ArrayList<SDataCfd> cfds = null; SHrsPayrollAnnul payrollAnnul = null; ArrayList<SDataPayrollReceiptIssue> receiptIssues = null; SDataPayrollReceiptIssue receiptIssue = null; if (jbAnnulPayroll.isEnabled()) { if (jtTable.getSelectedRowCount() != 1) { miClient.showMsgBoxInformation(SGridConsts.MSG_SELECT_ROW); } else { SGridRowView gridRow = (SGridRowView) getSelectedGridRow(); if (gridRow.getRowType() != SGridConsts.ROW_TYPE_DATA) { miClient.showMsgBoxWarning(SGridConsts.ERR_MSG_ROW_TYPE_DATA); } else if (gridRow.isRowSystem()) { miClient.showMsgBoxWarning(SDbConsts.MSG_REG_ + gridRow.getRowName() + SDbConsts.MSG_REG_IS_SYSTEM); } else if (!gridRow.isUpdatable()) { miClient.showMsgBoxWarning(SDbConsts.MSG_REG_ + gridRow.getRowName() + SDbConsts.MSG_REG_NON_UPDATABLE); } else { try { receiptIssues = new ArrayList<SDataPayrollReceiptIssue>(); if (mnGridSubtype == SModConsts.VIEW_SC_SUM) { cfds = SCfdUtils.getPayrollCfds((SClientInterface) miClient, (isCfdiPayrollVersionOld() ? SCfdConsts.CFDI_PAYROLL_VER_OLD : SCfdConsts.CFDI_PAYROLL_VER_CUR), gridRow.getRowPrimaryKey()); if (!isCfdiPayrollVersionOld()) { receiptIssues = SHrsUtils.getPayrollReceiptIssues(miClient.getSession(), gridRow.getRowPrimaryKey()); } } else { cfds = new ArrayList<SDataCfd>(); cfd = (SDataCfd) SDataUtilities.readRegistry((SClientInterface) miClient, SDataConstants.TRN_CFD, gridRow.getRowPrimaryKey(), SLibConstants.EXEC_MODE_SILENT); if (cfd != null) { cfds.add(cfd); } if (!isCfdiPayrollVersionOld()) { receiptIssue = new SDataPayrollReceiptIssue(); if (receiptIssue.read(new int[] { cfd.getFkPayrollReceiptPayrollId_n(), cfd.getFkPayrollReceiptEmployeeId_n(), cfd.getFkPayrollReceiptIssueId_n() }, miClient.getSession().getStatement()) != SLibConstants.DB_ACTION_READ_OK) { throw new Exception(SLibConstants.MSG_ERR_DB_REG_READ_DEP); } receiptIssues.add(receiptIssue); } } moDialogAnnulCfdi.formReset(); moDialogAnnulCfdi.formRefreshCatalogues(); moDialogAnnulCfdi.setValue(SGuiConsts.PARAM_DATE, (cfds == null || cfds.isEmpty() ? miClient.getSession().getCurrentDate() : cfds.get(0).getTimestamp())); moDialogAnnulCfdi.setVisible(true); if (moDialogAnnulCfdi.getFormResult() == SLibConstants.FORM_RESULT_OK) { payrollAnnul = new SHrsPayrollAnnul((SClientInterface) miClient, cfds, receiptIssues, (isCfdiPayrollVersionOld() ? SCfdConsts.CFDI_PAYROLL_VER_OLD : SCfdConsts.CFDI_PAYROLL_VER_CUR), mnGridSubtype == SModConsts.VIEW_SC_SUM, moDialogAnnulCfdi.getDate(), moDialogAnnulCfdi.getAnnulSat()); needUpdate = payrollAnnul.annulPayroll(); } if (needUpdate) { miClient.getSession().notifySuscriptors(mnGridType); } } catch (Exception e) { SLibUtils.showException(this, e); } } } } } private void actionGetXml() { if (jbGetXml.isEnabled()) { if (jtTable.getSelectedRowCount() != 1) { miClient.showMsgBoxInformation(SGridConsts.MSG_SELECT_ROW); } else { SGridRowView gridRow = (SGridRowView) getSelectedGridRow(); if (gridRow.getRowType() != SGridConsts.ROW_TYPE_DATA) { miClient.showMsgBoxWarning(SGridConsts.ERR_MSG_ROW_TYPE_DATA); } else if (gridRow.isRowSystem()) { miClient.showMsgBoxWarning(SDbConsts.MSG_REG_ + gridRow.getRowName() + SDbConsts.MSG_REG_IS_SYSTEM); } else if (!gridRow.isUpdatable()) { miClient.showMsgBoxWarning(SDbConsts.MSG_REG_ + gridRow.getRowName() + SDbConsts.MSG_REG_NON_UPDATABLE); } else { try { if (mnGridSubtype == SModConsts.VIEW_SC_DET) { SCfdUtils.getXmlCfd((SClientInterface) miClient, (SDataCfd) SDataUtilities.readRegistry((SClientInterface) miClient, SDataConstants.TRN_CFD, gridRow.getRowPrimaryKey(), SLibConstants.EXEC_MODE_SILENT)); } } catch (Exception e) { SLibUtils.showException(this, e); } } } } } private void actionGetAcknowledgmentCancellation() { if (jbGetAcknowledgmentCancellation.isEnabled()) { if (jtTable.getSelectedRowCount() != 1) { miClient.showMsgBoxInformation(SGridConsts.MSG_SELECT_ROW); } else { SGridRowView gridRow = (SGridRowView) getSelectedGridRow(); if (gridRow.getRowType() != SGridConsts.ROW_TYPE_DATA) { miClient.showMsgBoxWarning(SGridConsts.ERR_MSG_ROW_TYPE_DATA); } else if (gridRow.isRowSystem()) { miClient.showMsgBoxWarning(SDbConsts.MSG_REG_ + gridRow.getRowName() + SDbConsts.MSG_REG_IS_SYSTEM); } else if (!gridRow.isUpdatable()) { miClient.showMsgBoxWarning(SDbConsts.MSG_REG_ + gridRow.getRowName() + SDbConsts.MSG_REG_NON_UPDATABLE); } else { try { if (mnGridSubtype == SModConsts.VIEW_SC_DET) { SCfdUtils.getAcknowledgmentCancellationCfd((SClientInterface) miClient, (SDataCfd) SDataUtilities.readRegistry((SClientInterface) miClient, SDataConstants.TRN_CFD, gridRow.getRowPrimaryKey(), SLibConstants.EXEC_MODE_SILENT)); } } catch (Exception e) { SLibUtils.showException(this, e); } } } } } private void actionPrint() { SDialogPrintOrderPayroll dialogPrintOrderPayroll = null; ArrayList<SDataCfd> cfdAux = null; ArrayList<SDataCfd> cfds = null; int orderBy = 0; int copiesNum = 0; if (jbPrint.isEnabled()) { if (jtTable.getSelectedRowCount() != 1) { miClient.showMsgBoxInformation(SGridConsts.MSG_SELECT_ROW); } else { SGridRowView gridRow = (SGridRowView) getSelectedGridRow(); if (gridRow.getRowType() != SGridConsts.ROW_TYPE_DATA) { miClient.showMsgBoxWarning(SGridConsts.ERR_MSG_ROW_TYPE_DATA); } else if (gridRow.isRowSystem()) { miClient.showMsgBoxWarning(SDbConsts.MSG_REG_ + gridRow.getRowName() + SDbConsts.MSG_REG_IS_SYSTEM); } else if (!gridRow.isUpdatable()) { miClient.showMsgBoxWarning(SDbConsts.MSG_REG_ + gridRow.getRowName() + SDbConsts.MSG_REG_NON_UPDATABLE); } else { try { if (mnGridSubtype == SModConsts.VIEW_SC_SUM) { dialogPrintOrderPayroll = new SDialogPrintOrderPayroll(miClient, "Ordenamiento de impresión"); dialogPrintOrderPayroll.setVisible(true); cfdAux = new ArrayList<SDataCfd>(); cfds = new ArrayList<SDataCfd>(); if (dialogPrintOrderPayroll.getFormResult() == SLibConstants.FORM_RESULT_OK) { orderBy = (int) dialogPrintOrderPayroll.getValue(SGuiConsts.PARAM_KEY); copiesNum = (int) dialogPrintOrderPayroll.getValue(SLibConsts.UNDEFINED); cfdAux = SCfdUtils.getPayrollCfds((SClientInterface) miClient, (isCfdiPayrollVersionOld() ? SCfdConsts.CFDI_PAYROLL_VER_OLD : SCfdConsts.CFDI_PAYROLL_VER_CUR), gridRow.getRowPrimaryKey(), orderBy); for(SDataCfd cfd : cfdAux) { if (cfd.getFkXmlStatusId() == SDataConstantsSys.TRNS_ST_DPS_EMITED) { cfds.add(cfd); } } SCfdUtils.printCfd((SClientInterface) miClient, cfds, copiesNum, (isCfdiPayrollVersionOld() ? SCfdConsts.CFDI_PAYROLL_VER_OLD : SCfdConsts.CFDI_PAYROLL_VER_CUR)); } } else { SCfdUtils.printCfd((SClientInterface) miClient, SCfdConsts.CFD_TYPE_PAYROLL, (SDataCfd) SDataUtilities.readRegistry((SClientInterface) miClient, SDataConstants.TRN_CFD, gridRow.getRowPrimaryKey(), SLibConstants.EXEC_MODE_SILENT), (isCfdiPayrollVersionOld() ? SCfdConsts.CFDI_PAYROLL_VER_OLD : SCfdConsts.CFDI_PAYROLL_VER_CUR)); } } catch (Exception e) { SLibUtils.showException(this, e); } } } } } private void actionPrintAcknowledgmentCancellation() { ArrayList<SDataCfd> cfdAux = null; ArrayList<SDataCfd> cfds = null; if (jbPrintAcknowledgmentCancellation.isEnabled()) { if (jtTable.getSelectedRowCount() != 1) { miClient.showMsgBoxInformation(SGridConsts.MSG_SELECT_ROW); } else { SGridRowView gridRow = (SGridRowView) getSelectedGridRow(); if (gridRow.getRowType() != SGridConsts.ROW_TYPE_DATA) { miClient.showMsgBoxWarning(SGridConsts.ERR_MSG_ROW_TYPE_DATA); } else if (gridRow.isRowSystem()) { miClient.showMsgBoxWarning(SDbConsts.MSG_REG_ + gridRow.getRowName() + SDbConsts.MSG_REG_IS_SYSTEM); } else if (!gridRow.isUpdatable()) { miClient.showMsgBoxWarning(SDbConsts.MSG_REG_ + gridRow.getRowName() + SDbConsts.MSG_REG_NON_UPDATABLE); } else { try { if (mnGridSubtype == SModConsts.VIEW_SC_SUM) { cfdAux = new ArrayList<SDataCfd>(); cfds = new ArrayList<SDataCfd>(); cfdAux = SCfdUtils.getPayrollCfds((SClientInterface) miClient, (isCfdiPayrollVersionOld() ? SCfdConsts.CFDI_PAYROLL_VER_OLD : SCfdConsts.CFDI_PAYROLL_VER_CUR), gridRow.getRowPrimaryKey()); for(SDataCfd cfd : cfdAux) { if (cfd.getFkXmlStatusId() == SDataConstantsSys.TRNS_ST_DPS_ANNULED) { cfds.add(cfd); } } SCfdUtils.printAcknowledgmentCancellationCfd((SClientInterface) miClient, cfds, (isCfdiPayrollVersionOld() ? SCfdConsts.CFDI_PAYROLL_VER_OLD : SCfdConsts.CFDI_PAYROLL_VER_CUR)); } else { SCfdUtils.printAcknowledgmentCancellationCfd((SClientInterface) miClient, (SDataCfd) SDataUtilities.readRegistry((SClientInterface) miClient, SDataConstants.TRN_CFD, gridRow.getRowPrimaryKey(), SLibConstants.EXEC_MODE_SILENT), (isCfdiPayrollVersionOld() ? SCfdConsts.CFDI_PAYROLL_VER_OLD : SCfdConsts.CFDI_PAYROLL_VER_CUR)); } } catch (Exception e) { SLibUtils.showException(this, e); } } } } } private void actionSendMail() { if (jbSendMail.isEnabled()) { if (jtTable.getSelectedRowCount() != 1) { miClient.showMsgBoxInformation(SGridConsts.MSG_SELECT_ROW); } else { SGridRowView gridRow = (SGridRowView) getSelectedGridRow(); if (gridRow.getRowType() != SGridConsts.ROW_TYPE_DATA) { miClient.showMsgBoxWarning(SGridConsts.ERR_MSG_ROW_TYPE_DATA); } else if (gridRow.isRowSystem()) { miClient.showMsgBoxWarning(SDbConsts.MSG_REG_ + gridRow.getRowName() + SDbConsts.MSG_REG_IS_SYSTEM); } else if (!gridRow.isUpdatable()) { miClient.showMsgBoxWarning(SDbConsts.MSG_REG_ + gridRow.getRowName() + SDbConsts.MSG_REG_NON_UPDATABLE); } else { try { if (mnGridSubtype == SModConsts.VIEW_SC_SUM) { SCfdUtils.sendCfd((SClientInterface) miClient, SCfdUtils.getPayrollCfds((SClientInterface) miClient, (isCfdiPayrollVersionOld() ? SCfdConsts.CFDI_PAYROLL_VER_OLD : SCfdConsts.CFDI_PAYROLL_VER_CUR), gridRow.getRowPrimaryKey()), (isCfdiPayrollVersionOld() ? SCfdConsts.CFDI_PAYROLL_VER_OLD : SCfdConsts.CFDI_PAYROLL_VER_CUR)); } else { SCfdUtils.sendCfd((SClientInterface) miClient, SCfdConsts.CFD_TYPE_PAYROLL, (SDataCfd) SDataUtilities.readRegistry((SClientInterface) miClient, SDataConstants.TRN_CFD, gridRow.getRowPrimaryKey(), SLibConstants.EXEC_MODE_SILENT), (isCfdiPayrollVersionOld() ? SCfdConsts.CFDI_PAYROLL_VER_OLD : SCfdConsts.CFDI_PAYROLL_VER_CUR)); } } catch (Exception e) { SLibUtils.showException(this, e); } } } } } private void actionVerifyCfdi() { boolean needUpdate = false; if (jbVerifyCfdi.isEnabled()) { if (jtTable.getSelectedRowCount() != 1) { miClient.showMsgBoxInformation(SGridConsts.MSG_SELECT_ROW); } else { SGridRowView gridRow = (SGridRowView) getSelectedGridRow(); if (gridRow.getRowType() != SGridConsts.ROW_TYPE_DATA) { miClient.showMsgBoxWarning(SGridConsts.ERR_MSG_ROW_TYPE_DATA); } else if (gridRow.isRowSystem()) { miClient.showMsgBoxWarning(SDbConsts.MSG_REG_ + gridRow.getRowName() + SDbConsts.MSG_REG_IS_SYSTEM); } else if (!gridRow.isUpdatable()) { miClient.showMsgBoxWarning(SDbConsts.MSG_REG_ + gridRow.getRowName() + SDbConsts.MSG_REG_NON_UPDATABLE); } else { try { if (mnGridSubtype == SModConsts.VIEW_SC_SUM) { needUpdate = SCfdUtils.verifyCfdi((SClientInterface) miClient, SCfdUtils.getPayrollCfds((SClientInterface) miClient, (isCfdiPayrollVersionOld() ? SCfdConsts.CFDI_PAYROLL_VER_OLD : SCfdConsts.CFDI_PAYROLL_VER_CUR), gridRow.getRowPrimaryKey()), (isCfdiPayrollVersionOld() ? SCfdConsts.CFDI_PAYROLL_VER_OLD : SCfdConsts.CFDI_PAYROLL_VER_CUR)); } else { needUpdate = SCfdUtils.verifyCfdi((SClientInterface) miClient, (SDataCfd) SDataUtilities.readRegistry((SClientInterface) miClient, SDataConstants.TRN_CFD, gridRow.getRowPrimaryKey(), SLibConstants.EXEC_MODE_SILENT), (isCfdiPayrollVersionOld() ? SCfdConsts.CFDI_PAYROLL_VER_OLD : SCfdConsts.CFDI_PAYROLL_VER_CUR)); } if (needUpdate) { miClient.getSession().notifySuscriptors(mnGridType); } } catch (Exception e) { miClient.getFrame().setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); SLibUtils.showException(this, e); } } } } } private void actionRestoreSignedXml() { boolean restore = true; boolean needUpdate = true; SDataCfd cfd = null; SDataPayrollReceiptIssue receiptIssue = null; if (jbRestoreSignedXml.isEnabled()) { if (jtTable.getSelectedRowCount() != 1) { miClient.showMsgBoxInformation(SGridConsts.MSG_SELECT_ROW); } else { SGridRowView gridRow = (SGridRowView) getSelectedGridRow(); if (gridRow.getRowType() != SGridConsts.ROW_TYPE_DATA) { miClient.showMsgBoxWarning(SGridConsts.ERR_MSG_ROW_TYPE_DATA); } else if (gridRow.isRowSystem()) { miClient.showMsgBoxWarning(SDbConsts.MSG_REG_ + gridRow.getRowName() + SDbConsts.MSG_REG_IS_SYSTEM); } else if (!gridRow.isUpdatable()) { miClient.showMsgBoxWarning(SDbConsts.MSG_REG_ + gridRow.getRowName() + SDbConsts.MSG_REG_NON_UPDATABLE); } else { try { cfd = (SDataCfd) SDataUtilities.readRegistry((SClientInterface) miClient, SDataConstants.TRN_CFD, gridRow.getRowPrimaryKey(), SLibConstants.EXEC_MODE_SILENT); if (!isCfdiPayrollVersionOld()) { receiptIssue = new SDataPayrollReceiptIssue(); if (receiptIssue.read(new int[] { cfd.getFkPayrollReceiptPayrollId_n(), cfd.getFkPayrollReceiptEmployeeId_n(), cfd.getFkPayrollReceiptIssueId_n() }, miClient.getSession().getStatement()) != SLibConstants.DB_ACTION_READ_OK) { restore = false; throw new Exception(SLibConstants.MSG_ERR_DB_REG_READ_DEP); } if (receiptIssue.isDeleted()) { restore = false; miClient.showMsgBoxWarning("El documento '" + receiptIssue.getIssueNumber() + "' está eliminado."); } } if (restore) { needUpdate = SCfdUtils.restoreSignXml((SClientInterface) miClient, (receiptIssue == null ? cfd : receiptIssue.getDbmsDataCfd()), true, SLibConstants.UNDEFINED); if (needUpdate) { miClient.getSession().notifySuscriptors(mnGridType); } } } catch (Exception e) { miClient.getFrame().setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); SLibUtils.showException(this, e); } } } } } private void actionRestoreAcknowledgmentCancellation() { boolean restore = true; boolean needUpdate = true; SDataCfd cfd = null; SDataPayrollReceiptIssue receiptIssue = null; if (jbRestoreAcknowledgmentCancellation.isEnabled()) { if (jtTable.getSelectedRowCount() != 1) { miClient.showMsgBoxInformation(SGridConsts.MSG_SELECT_ROW); } else { SGridRowView gridRow = (SGridRowView) getSelectedGridRow(); if (gridRow.getRowType() != SGridConsts.ROW_TYPE_DATA) { miClient.showMsgBoxWarning(SGridConsts.ERR_MSG_ROW_TYPE_DATA); } else if (gridRow.isRowSystem()) { miClient.showMsgBoxWarning(SDbConsts.MSG_REG_ + gridRow.getRowName() + SDbConsts.MSG_REG_IS_SYSTEM); } else if (!gridRow.isUpdatable()) { miClient.showMsgBoxWarning(SDbConsts.MSG_REG_ + gridRow.getRowName() + SDbConsts.MSG_REG_NON_UPDATABLE); } else { try { cfd = (SDataCfd) SDataUtilities.readRegistry((SClientInterface) miClient, SDataConstants.TRN_CFD, gridRow.getRowPrimaryKey(), SLibConstants.EXEC_MODE_SILENT); if (!isCfdiPayrollVersionOld()) { receiptIssue = new SDataPayrollReceiptIssue(); if (receiptIssue.read(new int[] { cfd.getFkPayrollReceiptPayrollId_n(), cfd.getFkPayrollReceiptEmployeeId_n(), cfd.getFkPayrollReceiptIssueId_n() }, miClient.getSession().getStatement()) != SLibConstants.DB_ACTION_READ_OK) { restore = false; throw new Exception(SLibConstants.MSG_ERR_DB_REG_READ_DEP); } if (receiptIssue.isDeleted()) { restore = false; miClient.showMsgBoxWarning("El documento '" + receiptIssue.getIssueNumber() + "' está eliminado."); } } if (restore) { needUpdate = SCfdUtils.restoreAcknowledgmentCancellation((SClientInterface) miClient, (receiptIssue == null ? cfd : receiptIssue.getDbmsDataCfd()), true, SLibConstants.UNDEFINED); if (needUpdate) { miClient.getSession().notifySuscriptors(mnGridType); } } } catch (Exception e) { miClient.getFrame().setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); SLibUtils.showException(this, e); } } } } } private void actionDeactivateControlFlags() { if (jbDeactivateControlFlags.isEnabled()) { if (jtTable.getSelectedRowCount() != 1) { miClient.showMsgBoxInformation(SGridConsts.MSG_SELECT_ROW); } else { SGridRowView gridRow = (SGridRowView) getSelectedGridRow(); if (gridRow.getRowType() != SGridConsts.ROW_TYPE_DATA) { miClient.showMsgBoxWarning(SGridConsts.ERR_MSG_ROW_TYPE_DATA); } else if (gridRow.isRowSystem()) { miClient.showMsgBoxWarning(SDbConsts.MSG_REG_ + gridRow.getRowName() + SDbConsts.MSG_REG_IS_SYSTEM); } else if (!gridRow.isUpdatable()) { miClient.showMsgBoxWarning(SDbConsts.MSG_REG_ + gridRow.getRowName() + SDbConsts.MSG_REG_NON_UPDATABLE); } else { try { SCfdUtils.resetCfdiDiactivateFlags((SClientInterface) miClient, (SDataCfd) SDataUtilities.readRegistry((SClientInterface) miClient, SDataConstants.TRN_CFD, gridRow.getRowPrimaryKey(), SLibConstants.EXEC_MODE_SILENT)); miClient.getSession().notifySuscriptors(mnGridType); } catch (Exception e) { SLibUtils.showException(this, e); } } } } } @Override public void prepareSqlQuery() { String sql = ""; Object filter = null; int[] date = null; int sqlLenght = 0; moPaneSettings = new SGridPaneSettings(1); jbRowDisable.setEnabled(false); filter = (SGuiDate) moFiltersMap.get(SGridConsts.FILTER_DATE_PERIOD).getValue(); if (filter != null){ switch (((SGuiDate) filter).getGuiType()) { case SGuiConsts.GUI_DATE_DATE: sql += (sql.length() == 0 ? "" : "AND ") + "dt_end = '" + SLibUtils.DbmsDateFormatDate.format((SGuiDate) filter) + "' "; break; case SGuiConsts.GUI_DATE_MONTH: date = SLibTimeUtils.digestMonth((SGuiDate) filter); if (isCfdiPayrollVersionOld()) { sql += (sql.length() == 0 ? "" : "AND ") + "pay_year = " + date[0] + " AND pay_per = " + date[1] + " "; } else { sql += (sql.length() == 0 ? "" : "AND ") + "per_year = " + date[0] + " AND per = " + date[1] + " "; } break; case SGuiConsts.GUI_DATE_YEAR: date = SLibTimeUtils.digestYear((SGuiDate) filter); if (isCfdiPayrollVersionOld()) { sql += (sql.length() == 0 ? "" : "AND ") + "pay_year = " + date[0] + " "; } else { sql += (sql.length() == 0 ? "" : "AND ") + "per_year = " + date[0] + " "; } break; default: } } sqlLenght = mnGridSubtype == SModConsts.VIEW_SC_DET ? 2 : 1; msSql = ""; for (int i = 0; i < sqlLenght; i++) { msSql += "SELECT " + (mnGridSubtype == SModConsts.VIEW_SC_DET ? "COALESCE(id_cfd, 0) AS " : "f_id_pay AS ") + SDbConsts.FIELD_ID + "1, " + "pay_num AS " + SDbConsts.FIELD_CODE + ", " + "pay_num AS " + SDbConsts.FIELD_NAME + ", " + "pay_year AS f_pay_year, " + "pay_per AS f_pay_per, " + "pay_type AS f_pay_type, " + "dt_beg, " + "dt_end, " + "f_debit, " + "f_credit, " + "f_balance, " + "f_tot, "; if (mnGridSubtype == SModConsts.VIEW_SC_DET) { msSql += "b.bp AS f_bp, num_ser, f_rcp_num, f_id_pay, b.id_bp AS f_id_bp, " + "f_dt_iss, f_dt_pay, f_tp_pay_sys, "; } if (mnGridSubtype == SModConsts.VIEW_SC_DET) { msSql += "CONCAT(num_ser, IF(LENGTH(num_ser) = 0, '', '-'), erp.lib_fix_int(f_rcp_num, " + SDataConstantsSys.NUM_LEN_DPS + ")) AS f_num, " + "IF(" + (isCfdiPayrollVersionOld() ? "c.fid_st_xml = " : "fk_st_rcp = ") + SDataConstantsSys.TRNS_ST_DPS_ANNULED + ", " + SGridConsts.ICON_ANNUL + ", " + SGridConsts.ICON_NULL + ") AS f_ico, " + "IF(c.fid_st_xml IS NULL, " + SGridConsts.ICON_NULL + ", " /* not have CFDI associated */ + "IF(c.fid_st_xml = " + SDataConstantsSys.TRNS_ST_DPS_NEW + " OR LENGTH(c.uuid) = 0, " + SGridConsts.ICON_XML_PEND + ", " /* CFDI pending sign */ + "IF(LENGTH(c.ack_can_xml) = 0 AND c.ack_can_pdf_n IS NULL, " + SGridConsts.ICON_XML_ISSU + ", " /* CFDI signed, canceled only SIIE */ + "IF(LENGTH(c.ack_can_xml) != 0, " + SGridConsts.ICON_XML_ANNUL_XML + ", " /* CFDI canceled with cancellation acknowledgment in XML format */ + "IF(c.ack_can_pdf_n IS NOT NULL, " + SGridConsts.ICON_XML_ANNUL_PDF + ", " /* CFDI canceled with cancellation acknowledgment in PDF format */ + SGridConsts.ICON_XML_ISSU + " " /* CFDI signed, canceled only SIIE */ + "))))) AS f_ico_xml, " + "!c.b_con AS f_con, c.b_prc_ws, c.b_prc_sto_xml, c.b_prc_sto_pdf "; } else { msSql += "(SELECT COUNT(*) FROM " + SModConsts.TablesMap.get(SModConsts.TRN_CFD) + " AS c1 " + (isCfdiPayrollVersionOld() ? "" : "INNER JOIN " + SModConsts.TablesMap.get(SModConsts.HRS_PAY_RCP_ISS) + " AS pei ON " + "c1.fid_pay_rcp_pay_n = pei.id_pay AND c1.fid_pay_rcp_emp_n = pei.id_emp AND c1.fid_pay_rcp_iss_n = pei.id_iss AND pei.b_del = 0 AND pei.fk_st_rcp = " + SModSysConsts.TRNS_ST_DPS_EMITED + " ") + "WHERE b_con = 1 AND " + (isCfdiPayrollVersionOld() ? "fid_pay_pay_n = c.fid_pay_pay_n" : "fid_pay_rcp_pay_n = c.fid_pay_rcp_pay_n") + " AND fid_st_xml = " + SModSysConsts.TRNS_ST_DPS_EMITED + ") AS f_sign, " + "(SELECT COUNT(*) FROM " + SModConsts.TablesMap.get(SModConsts.TRN_CFD) + " AS c1 " + (isCfdiPayrollVersionOld() ? "" : "INNER JOIN " + SModConsts.TablesMap.get(SModConsts.HRS_PAY_RCP_ISS) + " AS pei ON " + "c1.fid_pay_rcp_pay_n = pei.id_pay AND c1.fid_pay_rcp_emp_n = pei.id_emp AND c1.fid_pay_rcp_iss_n = pei.id_iss AND pei.b_del = 0 AND pei.fk_st_rcp <> " + SModSysConsts.TRNS_ST_DPS_ANNULED + " ") + "WHERE b_con = 1 AND " + (isCfdiPayrollVersionOld() ? "fid_pay_pay_n = c.fid_pay_pay_n" : "fid_pay_rcp_pay_n = c.fid_pay_rcp_pay_n") + " AND fid_st_xml = " + SModSysConsts.TRNS_ST_DPS_NEW + ") AS f_new, " + "(SELECT COUNT(*) FROM " + SModConsts.TablesMap.get(SModConsts.TRN_CFD) + " AS c1 " + (isCfdiPayrollVersionOld() ? "" : "INNER JOIN " + SModConsts.TablesMap.get(SModConsts.HRS_PAY_RCP_ISS) + " AS pei ON " + "c1.fid_pay_rcp_pay_n = pei.id_pay AND c1.fid_pay_rcp_emp_n = pei.id_emp AND c1.fid_pay_rcp_iss_n = pei.id_iss AND pei.b_del = 0 AND pei.fk_st_rcp = " + SModSysConsts.TRNS_ST_DPS_EMITED + " ") + "WHERE b_con = 0 AND " + (isCfdiPayrollVersionOld() ? "fid_pay_pay_n = c.fid_pay_pay_n" : "fid_pay_rcp_pay_n = c.fid_pay_rcp_pay_n") + " AND fid_st_xml = " + SModSysConsts.TRNS_ST_DPS_EMITED + ") AS f_incon, " + "(SELECT COUNT(*) FROM " + SModConsts.TablesMap.get(SModConsts.TRN_CFD) + " AS c1 " + (isCfdiPayrollVersionOld() ? "" : "INNER JOIN " + SModConsts.TablesMap.get(SModConsts.HRS_PAY_RCP_ISS) + " AS pei ON " + "c1.fid_pay_rcp_pay_n = pei.id_pay AND c1.fid_pay_rcp_emp_n = pei.id_emp AND c1.fid_pay_rcp_iss_n = pei.id_iss AND pei.b_del = 0 ") + "WHERE b_prc_ws = 1 AND " + (isCfdiPayrollVersionOld() ? "fid_pay_pay_n = c.fid_pay_pay_n" : "fid_pay_rcp_pay_n = c.fid_pay_rcp_pay_n") + ") AS f_prc_ws, " + "(SELECT COUNT(*) FROM " + SModConsts.TablesMap.get(SModConsts.TRN_CFD) + " AS c1 " + (isCfdiPayrollVersionOld() ? "" : "INNER JOIN " + SModConsts.TablesMap.get(SModConsts.HRS_PAY_RCP_ISS) + " AS pei ON " + "c1.fid_pay_rcp_pay_n = pei.id_pay AND c1.fid_pay_rcp_emp_n = pei.id_emp AND c1.fid_pay_rcp_iss_n = pei.id_iss AND pei.b_del = 0 ") + "WHERE b_prc_sto_xml = 1 AND " + (isCfdiPayrollVersionOld() ? "fid_pay_pay_n = c.fid_pay_pay_n" : "fid_pay_rcp_pay_n = c.fid_pay_rcp_pay_n") + ") AS f_prc_sto_xml, " + "(SELECT COUNT(*) FROM " + SModConsts.TablesMap.get(SModConsts.TRN_CFD) + " AS c1 " + (isCfdiPayrollVersionOld() ? "" : "INNER JOIN " + SModConsts.TablesMap.get(SModConsts.HRS_PAY_RCP_ISS) + " AS pei ON " + "c1.fid_pay_rcp_pay_n = pei.id_pay AND c1.fid_pay_rcp_emp_n = pei.id_emp AND c1.fid_pay_rcp_iss_n = pei.id_iss AND pei.b_del = 0 ") + "WHERE b_prc_sto_pdf = 1 AND " + (isCfdiPayrollVersionOld() ? "fid_pay_pay_n = c.fid_pay_pay_n" : "fid_pay_rcp_pay_n = c.fid_pay_rcp_pay_n") + ") AS f_prc_sto_pdf "; } if (isCfdiPayrollVersionOld()) { msSql += "FROM( " + "SELECT v.id_pay AS f_id_pay, v.pay_num, v.pay_num AS f_name, v.pay_year, v.pay_per, v.pay_type AS pay_type, v.dt_beg, v.dt_end, fid_bpr_n, pe.id_emp, pe.num_ser, pe.num AS f_rcp_num, " + "'' AS f_dt_iss, " + "'' AS f_dt_pay, " + "'' AS f_tp_pay_sys, " + "SUM(pe.debit) AS f_debit, " + "SUM(pe.credit) AS f_credit, " + "SUM(pe.debit - pe.credit) AS f_balance, " + "(SELECT COUNT(*) FROM hrs_sie_pay_emp WHERE b_del = 0 AND id_pay = v.id_pay GROUP BY id_pay ) AS f_tot " + "FROM " + SModConsts.TablesMap.get(SModConsts.HRS_SIE_PAY) + " AS v " + "INNER JOIN " + SModConsts.TablesMap.get(SModConsts.HRS_SIE_PAY_EMP) + " AS pe ON " + "v.id_pay = pe.id_pay AND pe.b_del = FALSE " + "WHERE " + (sqlLenght == 2 && i == 0 ? "pe.b_del = 0 " : "") + (sql.isEmpty() ? "" : (sqlLenght == 2 && i == 0 ? "AND " : "") + sql) + "GROUP BY v.id_pay, v.pay_year, v.pay_per, v.pay_num, v.pay_type, v.dt_beg, v.dt_end " + (mnGridSubtype == SModConsts.VIEW_SC_DET ? ", pe.id_emp, pe.fid_bpr_n " : "") + "ORDER BY v.pay_year, v.pay_per, v.pay_type, v.pay_num, v.id_pay " + (mnGridSubtype == SModConsts.VIEW_SC_DET ? ", pe.id_emp, pe.fid_bpr_n " : "") + ") AS t "; } else { msSql += "FROM( " + "SELECT v.id_pay AS f_id_pay, v.num AS pay_num, v.num AS f_name, v.per_year AS pay_year, v.per AS pay_per, v.dt_sta AS dt_beg, v.dt_end, pe.id_emp, pei.id_iss, pei.fk_st_rcp, pei.num_ser, pei.num AS f_rcp_num, " + "pei.dt_iss AS f_dt_iss, " + "pei.dt_pay AS f_dt_pay, " + "(SELECT tp_pay_sys FROM " + SModConsts.TablesMap.get(SModConsts.TRNU_TP_PAY_SYS) + " WHERE id_tp_pay_sys = pei.fk_tp_pay_sys) AS f_tp_pay_sys, " + "SUM(pei.ear_r) AS f_debit, " + "SUM(pei.ded_r) AS f_credit, " + "SUM(pei.pay_r) AS f_balance, " + "(SELECT t.name FROM " + SModConsts.TablesMap.get(SModConsts.HRSS_TP_PAY) + " AS t WHERE v.fk_tp_pay = t.id_tp_pay) AS pay_type, " + "(SELECT COUNT(*) FROM " + SModConsts.TablesMap.get(SModConsts.HRS_PAY_RCP) + " WHERE b_del = 0 AND id_pay = v.id_pay GROUP BY id_pay ) AS f_tot " + "FROM " + SModConsts.TablesMap.get(SModConsts.HRS_PAY) + " AS v " + "INNER JOIN " + SModConsts.TablesMap.get(SModConsts.HRS_PAY_RCP) + " AS pe ON " + "v.id_pay = pe.id_pay AND pe.b_del = 0 " + "INNER JOIN " + SModConsts.TablesMap.get(SModConsts.HRS_PAY_RCP_ISS) + " AS pei ON " + "pe.id_pay = pei.id_pay AND pe.id_emp = pei.id_emp AND pei.b_del = 0 " + (mnGridSubtype == SModConsts.VIEW_SC_DET ? "" : " AND pei.fk_st_rcp <> " + SModSysConsts.TRNS_ST_DPS_ANNULED + " ") + "WHERE v.b_del = 0 " + (sql.isEmpty() ? "" : "AND " + sql) + "GROUP BY v.id_pay, v.per_year, v.per, v.num, pay_type, v.dt_sta, v.dt_end " + (mnGridSubtype == SModConsts.VIEW_SC_DET ? ", pe.id_emp, pei.id_iss " : "") + "ORDER BY v.per_year, v.per, pay_type ,v.num, v.id_pay " + (mnGridSubtype == SModConsts.VIEW_SC_DET ? ", pe.id_emp, pei.id_iss " : "") + ") AS t "; } msSql += (mnGridSubtype == SModConsts.VIEW_SC_DET ? "INNER JOIN " : "LEFT OUTER JOIN ") + SModConsts.TablesMap.get(SModConsts.TRN_CFD) + " AS c ON " + (isCfdiPayrollVersionOld() ? "t.f_id_pay = c.fid_pay_pay_n AND t.id_emp = c.fid_pay_emp_n " : "t.f_id_pay = c.fid_pay_rcp_pay_n AND t.id_emp = c.fid_pay_rcp_emp_n AND t.id_iss = c.fid_pay_rcp_iss_n ") + "AND NOT (c.fid_st_xml = " + SDataConstantsSys.TRNS_ST_DPS_NEW + " AND c.b_con = 0) "; /* + (mnGridSubtype == SModConsts.VIEW_SC_DET ? "INNER JOIN " : "LEFT OUTER JOIN ") + SModConsts.TablesMap.get(SModConsts.TRNS_ST_DPS) + " AS st ON " + "c.fid_st_xml = st.id_st_dps ";*/ if (mnGridSubtype == SModConsts.VIEW_SC_DET) { msSql += "INNER JOIN " + SModConsts.TablesMap.get(SModConsts.BPSU_BP) + " AS b ON " + (isCfdiPayrollVersionOld() ? "t.fid_bpr_n = b.id_bp " : "t.id_emp = b.id_bp "); } if (sqlLenght == 2 && i == 0) { msSql += " UNION "; } } msSql += "GROUP BY f_id_pay, f_pay_year, f_pay_per, t.f_name, f_pay_type, t.dt_beg, t.dt_end " + (mnGridSubtype == SModConsts.VIEW_SC_DET ? ", t.id_emp, f_id_bp, c.id_cfd " : "") + "ORDER BY f_pay_year, f_pay_per, f_pay_type, f_name, f_id_pay " + (mnGridSubtype == SModConsts.VIEW_SC_DET ? ", f_num, f_bp, f_id_bp " : ""); } @Override public ArrayList<SGridColumnView> createGridColumns() { ArrayList<SGridColumnView> gridColumnsViews = new ArrayList<>(); gridColumnsViews.add(new SGridColumnView(SGridConsts.COL_TYPE_INT_CAL_YEAR, "f_pay_year", "Ejercicio", 50)); gridColumnsViews.add(new SGridColumnView(SGridConsts.COL_TYPE_INT_CAL_MONTH, "f_pay_per", "Período", 50)); gridColumnsViews.add(new SGridColumnView(SGridConsts.COL_TYPE_TEXT_NAME_CAT_M, "f_pay_type", "Tipo nómina", 75)); gridColumnsViews.add(new SGridColumnView(SGridConsts.COL_TYPE_TEXT_NAME_CAT_S, SDbConsts.FIELD_NAME, "No. nómina", 50)); gridColumnsViews.add(new SGridColumnView(SGridConsts.COL_TYPE_DATE, "dt_beg", "F. inicial")); gridColumnsViews.add(new SGridColumnView(SGridConsts.COL_TYPE_DATE, "dt_end", "F. final")); if (mnGridSubtype == SModConsts.VIEW_SC_DET) { gridColumnsViews.add(new SGridColumnView(SGridConsts.COL_TYPE_INT_ICON, "f_ico", "Estatus")); gridColumnsViews.add(new SGridColumnView(SGridConsts.COL_TYPE_INT_ICON, "f_ico_xml", "CFD")); gridColumnsViews.add(new SGridColumnView(SGridConsts.COL_TYPE_TEXT, "f_num", "Folio recibo", 75)); gridColumnsViews.add(new SGridColumnView(SGridConsts.COL_TYPE_TEXT_NAME_BPR_L, "f_bp", "Empleado")); } gridColumnsViews.add(new SGridColumnView(SGridConsts.COL_TYPE_DEC_AMT, "f_debit", "Percepciones $")); gridColumnsViews.add(new SGridColumnView(SGridConsts.COL_TYPE_DEC_AMT, "f_credit", "Deducciones $")); gridColumnsViews.add(new SGridColumnView(SGridConsts.COL_TYPE_DEC_AMT, "f_balance", "Alcance neto $")); if (mnGridSubtype == SModConsts.VIEW_SC_DET) { if (!isCfdiPayrollVersionOld()) { gridColumnsViews.add(new SGridColumnView(SGridConsts.COL_TYPE_DATE, "f_dt_iss", "F emisión")); gridColumnsViews.add(new SGridColumnView(SGridConsts.COL_TYPE_DATE, "f_dt_pay", "F pago")); gridColumnsViews.add(new SGridColumnView(SGridConsts.COL_TYPE_TEXT_NAME_CAT_S, "f_tp_pay_sys", "Método pago")); } gridColumnsViews.add(new SGridColumnView(SGridConsts.COL_TYPE_BOOL_M, "f_con", "Iconsistente")); gridColumnsViews.add(new SGridColumnView(SGridConsts.COL_TYPE_BOOL_M, "b_prc_ws", "Incorrecto PAC")); gridColumnsViews.add(new SGridColumnView(SGridConsts.COL_TYPE_BOOL_M, "b_prc_sto_xml", "Incorrecto XML disco")); gridColumnsViews.add(new SGridColumnView(SGridConsts.COL_TYPE_BOOL_M, "b_prc_sto_pdf", "Incorrecto PDF disco")); } else { gridColumnsViews.add(new SGridColumnView(SGridConsts.COL_TYPE_DEC_0D, "f_tot", "Recibos totales", 100)); gridColumnsViews.add(new SGridColumnView(SGridConsts.COL_TYPE_DEC_0D, "f_sign", "CFDI timbrados", 100)); gridColumnsViews.add(new SGridColumnView(SGridConsts.COL_TYPE_DEC_0D, "f_new", "CFDI x timbrar", 100)); gridColumnsViews.add(new SGridColumnView(SGridConsts.COL_TYPE_DEC_0D, "f_incon", "CFDI inconsistentes", 100)); gridColumnsViews.add(new SGridColumnView(SGridConsts.COL_TYPE_DEC_0D, "f_prc_ws", "CFDI incorrectos PAC", 100)); gridColumnsViews.add(new SGridColumnView(SGridConsts.COL_TYPE_DEC_0D, "f_prc_sto_xml", "CFDI incorrectos XML disco", 100)); gridColumnsViews.add(new SGridColumnView(SGridConsts.COL_TYPE_DEC_0D, "f_prc_sto_pdf", "CFDI incorrectos PDF disco", 100)); } return gridColumnsViews; } @Override public void defineSuscriptions() { moSuscriptionsSet.add(mnGridType); moSuscriptionsSet.add(SModConsts.TRN_CFD); moSuscriptionsSet.add(SModConsts.HRS_PAY); moSuscriptionsSet.add(SModConsts.HRS_PAY_RCP); moSuscriptionsSet.add(SModConsts.HRS_SIE_PAY); moSuscriptionsSet.add(SModConsts.BPSU_BP); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() instanceof JButton) { JButton button = (JButton) e.getSource(); if (button == jbReemit) { actionReemitPayroll(); } else if (button == jbSignPayroll) { actionSignPayroll(); } else if (button == jbAnnulPayroll) { actionAnnulPayroll(); } else if (button == jbGetXml) { actionGetXml(); } else if (button == jbGetAcknowledgmentCancellation) { actionGetAcknowledgmentCancellation(); } else if (button == jbPrint) { actionPrint(); } else if (button == jbPrintAcknowledgmentCancellation) { actionPrintAcknowledgmentCancellation(); } else if (button == jbSendMail) { actionSendMail(); } else if (button == jbVerifyCfdi) { actionVerifyCfdi(); } else if (button == jbRestoreSignedXml) { actionRestoreSignedXml(); } else if (button == jbRestoreAcknowledgmentCancellation) { actionRestoreAcknowledgmentCancellation(); } else if (button == jbDeactivateControlFlags) { actionDeactivateControlFlags(); } } } @Override public void actionRowDelete() { if (jbRowDelete.isEnabled()) { if (jtTable.getSelectedRowCount() == 0) { miClient.showMsgBoxInformation(SGridConsts.MSG_SELECT_ROWS); } else if (miClient.showMsgBoxConfirm(SGridConsts.MSG_CONFIRM_REG_DEL) == JOptionPane.YES_OPTION) { boolean updates = false; SGridRow[] gridRows = getSelectedGridRows(); for (SGridRow gridRow : gridRows) { if (((SGridRowView) gridRow).getRowType() != SGridConsts.ROW_TYPE_DATA) { miClient.showMsgBoxWarning(SGridConsts.ERR_MSG_ROW_TYPE_DATA); } else if (((SGridRowView) gridRow).isRowSystem()) { miClient.showMsgBoxWarning(SDbConsts.MSG_REG_ + gridRow.getRowName() + SDbConsts.MSG_REG_IS_SYSTEM); } else if (!((SGridRowView) gridRow).isDeletable()) { miClient.showMsgBoxWarning(SDbConsts.MSG_REG_ + gridRow.getRowName() + SDbConsts.MSG_REG_NON_DELETABLE); } else { try { if (SCfdUtils.deletePayroll((SClientInterface) miClient, gridRow.getRowPrimaryKey()[0])) { updates = true; } } catch (Exception e) { SLibUtils.showException(this, e); } } } if (updates) { miClient.getSession().notifySuscriptors(mnGridType); } } } } }
package com.kloudless; import com.fasterxml.jackson.databind.JsonNode; import com.kloudless.exception.*; import com.kloudless.model.*; import com.kloudless.net.KloudlessResponse; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import static com.kloudless.StaticImporter.TestInfo; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.filter; public class KloudlessTest extends KloudlessBaseTest { static List<String> testAccounts; @BeforeClass public static void setUp() { Kloudless.apiKey = TestInfo.getApiKey(); testAccounts = TestInfo.getTestAccounts(); Kloudless.overrideApiBase(TestInfo.getApiBasedUrl()); // Insert Custom Headers HashMap<String, String> customHeaders = new HashMap<String, String>(); // USER IMPERSONATION // customHeaders.put("X-Kloudless-As-User", "INSERT USER ID HERE"); Kloudless.addCustomHeaders(customHeaders); } // Begin Account Tests @Test public void testAccountAll() throws KloudlessException { AccountCollection accounts = Account.all(null); List<Account> list = accounts.objects.stream().filter(x -> testAccounts .contains(x.id)).collect(Collectors.toList()); assertThat(list.size()).isGreaterThan(0); } @Test public void testAccountRetrieve() throws KloudlessException { for (String testAccount : testAccounts) { Account account = Account.retrieve(testAccount, null); String jsonTree = TestInfo.getOneTestAccountJson(); try { JsonNode root = mapper.readTree(jsonTree); int id = root.at("/id").asInt(); assertThat(Integer.parseInt(account.id)).isEqualTo(id); String acnt = root.at("/account").asText(); assertThat(account.account).isEqualTo(acnt); String service = root.at("/service").asText(); assertThat(account.service).isEqualTo(service); } catch (IOException e) { e.printStackTrace(); } } } @Test public void testAccountSearch() throws KloudlessException { final String folderName = "new test fold\u00e9r"; for (String testAccount : testAccounts) { createTestFolder(folderName, getRootFolderId(testAccount), testAccount); Map<String, Object> params = new HashMap<>(); params.put("q", folderName); MetadataCollection results = Account.search(testAccount, params); if (results.count > 0) { results.objects.stream().forEach(x -> { assertThat(x.name).isEqualTo(folderName); }); } } } @Test public void testAccountRecent() throws KloudlessException, IOException { java.io.File file1 = new java.io.File(TestInfo.getPathUploadingFile()); final String fileName = file1.getName(); for (String testAccount : testAccounts) { createTestFile(fileName, file1, getRootFolderId(testAccount), testAccount); FileCollection results = Account.recent(testAccount, null); List<Metadata> list = results.objects.stream().filter(x -> x.name.equals(fileName)) .collect(Collectors.toList()); assertThat(list.size()).isGreaterThan(0); } } @Test @Ignore public void testAccountEvents() throws KloudlessException { HashMap<String, Object> params = new HashMap<>(); //params.put("cursor", "after-auth"); for (String testAccount : testAccounts) { EventCollection events = Account.events(testAccount, null); if (events.count > 0) { //TODO: add asserts later if the event retrieval works } events = Account.events(testAccount, params); if (events.count > 0) { //TODO: add asserts later if the event retrieval works } } } // Begin Folder Tests @Test public void testFolderContents() throws KloudlessException { final String fileName = "test folder content"; for (String testAccount : testAccounts) { createTestFolder(fileName, getRootFolderId(testAccount), testAccount); MetadataCollection contents = Folder.contents(getRootFolderId(testAccount) , testAccount, null); List<Metadata> list = contents.objects.stream().filter(x -> x.name.equals(fileName)) .collect(Collectors.toList()); // greater one is for fear of the duplication assertThat(list.size() >= 1); } } @Test public void testFolderRetrieve() throws KloudlessException { final String folderName = "test folder retrieve"; for (String testAccount : testAccounts) { Folder createdFolder = createTestFolder(folderName, getRootFolderId(testAccount), testAccount); Folder retrieved = Folder.retrieve(createdFolder.id, testAccount, null); assertThat(createdFolder.name).isEqualTo(retrieved.name); assertThat(createdFolder.id).isEqualTo(retrieved.id); } } @Test public void testFolderSave() throws KloudlessException { final String folderName = "test folder save"; final String folderNameChanged = "test folder saf\u009e"; for(String testAccount : testAccounts) { Folder createdFolder = createTestFolder(folderName, getRootFolderId(testAccount), testAccount); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } createdFolder.name = folderNameChanged; Map<String,Object> metadata = new HashMap<>(); metadata.put("parent_id",getRootFolderId(testAccount)); metadata.put("name",folderNameChanged); Folder folderNamedChanged = Folder.save(createdFolder.id, testAccount, metadata); Folder retrieved = Folder.retrieve(folderNamedChanged.id, testAccount, null); assertThat(retrieved.name).isEqualTo(folderNameChanged); } } @Test public void testFolderCreate() throws KloudlessException { final String folderName = "test create a folder"; for (String testAccount : testAccounts) { Folder newFolder = createTestFolder(folderName, getRootFolderId(testAccount), testAccount); assertThat(folderName).isEqualTo(newFolder.name); } } @Test public void testFolderDelete() throws KloudlessException { final String folderName = "test folder deletion"; for (String account : testAccounts) { Folder newFolder = createTestFolder(folderName, getRootFolderId(account), account); int code = deleteTestFolder(newFolder.id, account, false, true); assertThat(code).isEqualTo(204); } } // Begin File Tests @Test public void testFileContents() throws KloudlessException, IOException { // Binary file java.io.File file1 = new java.io.File(TestInfo.getPathUploadingFile()); long expectedSize = file1.length(); for (String account : testAccounts) { File fileCreated = createTestFile("test file content by checking the size", file1, getRootFolderId(account), account); KloudlessResponse response = File.contents(fileCreated.id, account, null); long actualSize = response.getResponseStream().size(); assertThat(actualSize).isEqualTo(expectedSize); } //TODO: text file } @Test public void testFileRetrieve() throws KloudlessException { final String fileName = "test retrieving file"; for (String account : testAccounts) { File createdFile = null; java.io.File file = new java.io.File(TestInfo.getPathUploadingFile()); try { createdFile = createTestFile(fileName, file, getRootFolderId(account), account); } catch (IOException e) { e.printStackTrace(); } File retrievedFile = File.retrieve(createdFile.id, account, null); assertThat(retrievedFile.name).isEqualTo(fileName); } } @Test public void testFileSave() throws KloudlessException, IOException { final String fileName = "test update a file"; final String fileNameChanged = "file name is changed"; java.io.File file = new java.io.File(TestInfo.getPathUploadingFile()); for (String account : testAccounts) { File fileCreated = createTestFile(fileName, file, getRootFolderId(account), account); Map<String, Object> params = new HashMap<>(); params.put("name", fileNameChanged); params.put("parent_id", getRootFolderId(account)); params.put("account", account); File.save(fileCreated.id, account, params); File updatedFile = File.retrieve(fileCreated.id, account, null); assertThat(updatedFile.name).isEqualTo(fileNameChanged); } } @Test public void testFileCreate() throws KloudlessException, IOException { java.io.File file1 = new java.io.File(TestInfo.getPathUploadingFile()); final String fileName = file1.getName(); final long size = file1.length(); for (String account : testAccounts) { File fileCreated = createTestFile(fileName, file1, getRootFolderId(account), account); File fileRetrieved = File.retrieve(fileCreated.id, account, null); assertThat(fileName).isEqualTo(fileRetrieved.name); assertThat(fileRetrieved.size).isEqualTo(size); } } @Test public void testFileDelete() throws KloudlessException, IOException { final String fileName = "test file deletion"; java.io.File file1 = new java.io.File(TestInfo.getPathUploadingFile()); for (String account : testAccounts) { File fileCreated = createTestFile(fileName, file1, getRootFolderId(account), account); KloudlessResponse response = File.delete(fileCreated.id, account, null); int code = response.getResponseCode(); assertThat(code).isEqualTo(204); } } @Test public void testMultipartUpload() throws APIException, AuthenticationException, InvalidRequestException, APIConnectionException { java.io.File file = new java.io.File(TestInfo.getPathUploadingFile()); HashMap<String, Object> params = new HashMap<>(); HashMap<String, String> keys = new HashMap<>(); for (String account : testAccounts) { params.clear(); keys.clear(); params.put("name", file.getName()); params.put("parent_id", getRootFolderId(account)); params.put("size", file.length()); keys.put("overwrite", "true"); File.Multipart multipart = File.initializeMultipartUpload(account, params, keys); assertThat(multipart.getId() > 0); assertThat(multipart.getAccount()).isEqualTo(account); assertThat(multipart.getPartSize()).isGreaterThan(0); assertThat(multipart.getPartCount()).isEqualTo( (int) Math.ceil((double) multipart.getOriginalFileSize() / multipart.getPartSize())); assertThat(multipart.getPartCount()).isGreaterThanOrEqualTo(1); assertThat(multipart.getPartCount()).isLessThanOrEqualTo(10000); for (int part_number = 1; part_number <= multipart.getPartCount(); part_number++) { params.clear(); keys.clear(); params.put("session_id", String.valueOf(multipart.getId())); params.put("file", file); params.put("part_number", part_number); params.put("part_size", multipart.getPartSize()); keys.put("part_number", String.valueOf(part_number)); KloudlessResponse response = File.multipartUpload(account, params, keys); assertThat(response.getResponseCode()).isEqualTo(200); if (part_number == 1) { // test retrieve multipart upload status File.Multipart multipartStatus = File.retrieveMultipartUploadInfo(account, params); assertThat(multipartStatus.getId()).isEqualTo(multipart.getId()); assertThat(multipartStatus.getAccount()).isEqualTo(multipart.getAccount()); } } File mergedFile = File.finalizeMultipartUpload(account, params); assertThat(mergedFile.name).isEqualTo(file.getName()); assertThat(mergedFile.size).isEqualTo(file.length()); } } @Test public void testAbortMultipartUplad() throws APIException, InvalidRequestException, AuthenticationException, APIConnectionException { java.io.File file = new java.io.File(TestInfo.getPathUploadingFile()); HashMap<String, Object> params = new HashMap<>(); HashMap<String, String> keys = new HashMap<>(); for (String account : testAccounts) { params.clear(); keys.clear(); params.put("name", file.getName()); params.put("parent_id", getRootFolderId(account)); params.put("size", file.length()); keys.put("overwrite", "true"); File.Multipart multipart = File.initializeMultipartUpload(account, params, keys); assertThat(multipart.getId() > 0); assertThat(multipart.getAccount()).isEqualTo(account); assertThat(multipart.getPartSize()).isGreaterThan(0); assertThat(multipart.getPartCount()).isEqualTo( (int) Math.ceil((double) multipart.getOriginalFileSize() / multipart.getPartSize())); assertThat(multipart.getPartCount()).isGreaterThanOrEqualTo(1); assertThat(multipart.getPartCount()).isLessThanOrEqualTo(10000); params.clear(); params.put("session_id", multipart.getId()); KloudlessResponse response = File.abortMultipartUpload(account, params); assertThat(response.getResponseCode()).isEqualTo(204); } } // Begin Link Tests @Test @Ignore public void testLinkAll() throws KloudlessException { for (String testAccount : testAccounts) { LinkCollection links = Link.all(testAccount, null); System.out.println(links); } } @Test @Ignore public void testLinkRetrieve() throws KloudlessException { // TODO: figure out how to test retrieve a created link } @Test @Ignore public void testLinkSave() throws KloudlessException { // TODO: figure out how to test save a created link } @Test @Ignore public void testLinkCreate() throws KloudlessException { // TODO: figure out how to test create a link } @Test @Ignore public void testLinkDelete() throws KloudlessException { // TODO: figure out how to test delete a file } @Test @Ignore public void testPermissionAll() throws KloudlessException { // for (String testAccount : testAccounts) { // testAccount, "folder", null); // testAccount, "file", null); } @Test @Ignore public void testPermissionUpdate() throws KloudlessException { // HashMap<String, Object> params = new HashMap<String, Object>(); // params.put("EMAIL", "ROLE"); // for (String testAccount : testAccounts) { // testAccount, "folder", params); // testAccount, "file", params); } @Test @Ignore public void testPermissionSave() throws KloudlessException { // HashMap<String, Object> params = new HashMap<String, Object>(); // params.put("EMAIL", "ROLE"); // for (String testAccount : testAccounts) { // testAccount, "folder", params); // testAccount, "file", params); } // Begin Properties Tests @Test @Ignore public void testPropertiesAll() throws KloudlessException { for (String testAccount : testAccounts) { PropertyCollection properties = Property.all("FILE ID", testAccount, null); System.out.println(properties); } } // TODO: include updating properties test @Test @Ignore public void testPropertiesDelete() throws KloudlessException { // for (String testAccount : testAccounts) { // KloudlessResponse response = Property.delete("FILE ID", // testAccount, null); // System.out.println(response); } //Begin Team Endpoint Tests, Admin Account Required @Test @Ignore public void testUserAll() throws KloudlessException { // UserCollection users = User.all("ADMIN ACCOUNT ID", null); // System.out.println(users); } @Test @Ignore public void testUserRetrieve() throws KloudlessException { // User user = User.retrieve("USER ID", "ADMIN ACCOUNT ID", null); // System.out.println(user); } @Test @Ignore public void testUserGroups() throws KloudlessException { // GroupCollection groups = User.groups("USER ID", "ADMIN ACCOUNT ID", null); // System.out.println(groups); } @Test @Ignore public void testGroupAll() throws KloudlessException { // GroupCollection groups = Group.all("ADMIN ACCOUNT ID", null); // System.out.println(groups); } @Test @Ignore public void testGroupRetrieve() throws KloudlessException { // Group group = Group.retrieve("GROUP ID", "ADMIN ACCOUNT ID", null); // System.out.println(group); } @Test @Ignore public void testGroupUsers() throws KloudlessException { // UserCollection users = Group.users("GROUP ID", "ADMIN ACCOUNT ID", null); // System.out.println(users); } }
package com.intellij.structuralsearch.plugin.ui; import com.intellij.icons.AllIcons; import com.intellij.openapi.fileTypes.LanguageFileType; import com.intellij.openapi.util.JDOMExternalizable; import com.intellij.openapi.util.NlsSafe; import com.intellij.openapi.util.text.StringUtil; import com.intellij.structuralsearch.MatchOptions; import com.intellij.structuralsearch.NamedScriptableDefinition; import com.intellij.structuralsearch.SSRBundle; import com.intellij.structuralsearch.plugin.replace.ReplaceOptions; import org.jdom.Attribute; import org.jdom.DataConversionException; import org.jdom.Element; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.nio.charset.StandardCharsets; import java.util.Objects; import java.util.UUID; public abstract class Configuration implements JDOMExternalizable { @NonNls public static final String CONTEXT_VAR_NAME = "__context__"; public static final Configuration[] EMPTY_ARRAY = {}; @NonNls protected static final String NAME_ATTRIBUTE_NAME = "name"; @NonNls private static final String CREATED_ATTRIBUTE_NAME = "created"; @NonNls private static final String UUID_ATTRIBUTE_NAME = "uuid"; @NonNls private static final String DESCRIPTION_ATTRIBUTE_NAME = "description"; @NonNls private static final String SUPPRESS_ID_ATTRIBUTE_NAME = "suppressId"; @NonNls private static final String PROBLEM_DESCRIPTOR_ATTRIBUTE_NAME = "problemDescriptor"; @NonNls private static final String ORDER_ATTRIBUTE_NAME = "order"; private @NotNull @Nls(capitalization = Nls.Capitalization.Sentence) String name; private String category; private boolean predefined; private long created; private UUID uuid; private String description; private String suppressId; private String problemDescriptor; private int order; private @NonNls String refName; private transient String myCurrentVariableName; public Configuration() { name = ""; category = ""; created = -1L; } public Configuration(@NotNull @Nls String name, @NotNull String category) { this.name = name; this.category = category; created = -1L; } protected Configuration(@NotNull Configuration configuration) { name = configuration.name; category = configuration.category; created = -1L; // receives timestamp when added to history predefined = false; // copy is never predefined uuid = configuration.uuid; description = configuration.description; suppressId = configuration.suppressId; problemDescriptor = configuration.problemDescriptor; order = configuration.order; refName = configuration.refName; } @NotNull public abstract Configuration copy(); @NotNull @Nls public String getName() { return name; } public void setName(@NotNull String value) { if (uuid == null) { uuid = UUID.nameUUIDFromBytes(name.getBytes(StandardCharsets.UTF_8)); } name = value; } @NotNull @Nls public String getTypeText() { final LanguageFileType type = getFileType(); return isPredefined() ? SSRBundle.message("predefined.configuration.type.text", type.getLanguage().getDisplayName()) : SSRBundle.message("predefined.configuration.type.text.user.defined", type.getLanguage().getDisplayName()); } @NotNull public String getCategory() { return category; } public void setCategory(@NotNull String category) { this.category = category; } public long getCreated() { return created; } public void setCreated(long created) { if (predefined) { throw new AssertionError(); } this.created = created; } @NotNull public UUID getUuid() { return uuid == null ? (uuid = UUID.nameUUIDFromBytes(name.getBytes(StandardCharsets.UTF_8))) : uuid; } public void setUuid(@Nullable UUID uuid) { this.uuid = uuid; } public @NlsSafe @Nullable String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public @NlsSafe @Nullable String getSuppressId() { return suppressId; } public void setSuppressId(String suppressId) { this.suppressId = suppressId; } public @NlsSafe @Nullable String getProblemDescriptor() { return this.problemDescriptor; } public void setProblemDescriptor(String problemDescriptor) { this.problemDescriptor = problemDescriptor; } public int getOrder() { return order; } public void setOrder(int order) { if (order < 0) throw new IllegalArgumentException(); this.order = order; } @Override public void readExternal(Element element) { name = element.getAttributeValue(NAME_ATTRIBUTE_NAME); final Attribute createdAttribute = element.getAttribute(CREATED_ATTRIBUTE_NAME); if (createdAttribute != null) { try { created = createdAttribute.getLongValue(); } catch (DataConversionException ignore) {} } final Attribute uuidAttribute = element.getAttribute(UUID_ATTRIBUTE_NAME); if (uuidAttribute != null) { try { uuid = UUID.fromString(uuidAttribute.getValue()); } catch (IllegalArgumentException ignore) {} } final Attribute descriptionAttribute = element.getAttribute(DESCRIPTION_ATTRIBUTE_NAME); if (descriptionAttribute != null) { description = descriptionAttribute.getValue(); } final Attribute suppressIdAttribute = element.getAttribute(SUPPRESS_ID_ATTRIBUTE_NAME); if (suppressIdAttribute != null) { suppressId = suppressIdAttribute.getValue(); } final Attribute problemDescriptorAttribute = element.getAttribute(PROBLEM_DESCRIPTOR_ATTRIBUTE_NAME); if (problemDescriptorAttribute != null) { problemDescriptor = problemDescriptorAttribute.getValue(); } final Attribute mainAttribute = element.getAttribute(ORDER_ATTRIBUTE_NAME); if (mainAttribute != null) { try { order = Math.max(0, mainAttribute.getIntValue()); } catch (DataConversionException ignore) {} } } @Override public void writeExternal(Element element) { element.setAttribute(NAME_ATTRIBUTE_NAME,name); if (created > 0) { element.setAttribute(CREATED_ATTRIBUTE_NAME, String.valueOf(created)); } if (uuid != null && !uuid.equals(UUID.nameUUIDFromBytes(name.getBytes(StandardCharsets.UTF_8)))) { element.setAttribute(UUID_ATTRIBUTE_NAME, uuid.toString()); } if (!StringUtil.isEmpty(description)) { element.setAttribute(DESCRIPTION_ATTRIBUTE_NAME, description); } if (!StringUtil.isEmpty(suppressId)) { element.setAttribute(SUPPRESS_ID_ATTRIBUTE_NAME, suppressId); } if (!StringUtil.isEmpty(problemDescriptor)) { element.setAttribute(PROBLEM_DESCRIPTOR_ATTRIBUTE_NAME, problemDescriptor); } if (order != 0) { element.setAttribute(ORDER_ATTRIBUTE_NAME, String.valueOf(order)); } } public boolean isPredefined() { return predefined; } public void setPredefined(boolean predefined) { this.predefined = predefined; } @NotNull public abstract MatchOptions getMatchOptions(); @NotNull public abstract ReplaceOptions getReplaceOptions(); public abstract NamedScriptableDefinition findVariable(@NotNull String name); public abstract void removeUnusedVariables(); public String getCurrentVariableName() { return myCurrentVariableName; } public void setCurrentVariableName(String variableName) { myCurrentVariableName = variableName; } public boolean equals(Object configuration) { if (!(configuration instanceof Configuration)) return false; final Configuration other = (Configuration)configuration; return Objects.equals(category, other.category) && name.equals(other.name); } @Override public int hashCode() { return 31 * name.hashCode() + (category != null ? category.hashCode() : 0); } @NotNull public Icon getIcon() { final LanguageFileType type = getFileType(); return (type == null || type.getIcon() == null) ? AllIcons.FileTypes.Any_type : type.getIcon(); } public LanguageFileType getFileType() { return null; } @NotNull @NonNls public String getRefName() { return refName == null ? name : refName; } public void setRefName(String refName) { if (isPredefined()) this.refName = refName; } }
package com.pg85.otg.forge.gui.screens; import java.util.List; import java.util.function.Consumer; import javax.annotation.Nullable; import com.mojang.blaze3d.matrix.MatrixStack; import com.pg85.otg.config.dimensions.DimensionConfig; import com.pg85.otg.config.dimensions.DimensionConfig.OTGDimension; import com.pg85.otg.config.dimensions.DimensionConfig.OTGOverWorld; import net.minecraft.client.gui.DialogTexts; import net.minecraft.client.gui.screen.CreateWorldScreen; import net.minecraft.client.gui.screen.Screen; import net.minecraft.client.gui.widget.button.Button; import net.minecraft.client.gui.widget.list.ExtendedList; import net.minecraft.client.resources.I18n; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.StringTextComponent; import net.minecraft.util.text.TextComponent; import net.minecraft.util.text.TranslationTextComponent; import net.minecraft.world.gen.settings.DimensionGeneratorSettings; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; @OnlyIn(Dist.CLIENT) public class CreateOTGDimensionsScreen extends Screen { public final CreateWorldScreen parent; public DimensionGeneratorSettings dimGenSettings; private final Consumer<OTGDimensionSettingsContainer> dimensionConfigConsumer; private ITextComponent columnType; private ITextComponent columnHeight; private CreateOTGDimensionsScreen.DetailsList list; private final DimensionConfig currentSelection; private Button addDimButton; private Button removeDimButton; private Button editDimButton; private boolean uiLocked = false; private static DimensionConfig modpackConfig; public CreateOTGDimensionsScreen(CreateWorldScreen parent, Consumer<OTGDimensionSettingsContainer> dimensionConfigConsumer) { super(setTitle()); this.parent = parent; this.dimensionConfigConsumer = dimensionConfigConsumer; if(modpackConfig == null) { this.currentSelection = new DimensionConfig(); this.currentSelection.Overworld = new OTGOverWorld(null, -1, null, null); this.currentSelection.Nether = new OTGDimension(null, -1); this.currentSelection.End = new OTGDimension(null, -1); } else { this.currentSelection = modpackConfig; this.uiLocked = true; } } private static TextComponent setTitle() { // If there is a dimensionconfig for the generatorsettings, use that. Otherwise find a preset by name. modpackConfig = DimensionConfig.fromDisk("Modpack"); if(modpackConfig == null || modpackConfig.ModpackName == null) { return new TranslationTextComponent("otg.createDimensions.customize.title"); } else { return new StringTextComponent(modpackConfig.ModpackName); } } protected void init() { this.columnType = new TranslationTextComponent("otg.createDimensions.customize.dimension"); this.columnHeight = new TranslationTextComponent("otg.createDimensions.customize.preset"); this.list = new CreateOTGDimensionsScreen.DetailsList(); this.children.add(this.list); if(!this.uiLocked) { this.addDimButton = this.addButton(new Button(this.width / 2 - 155, this.height - 52, 95, 20, new TranslationTextComponent("otg.createDimensions.customize.dimension.addDimension"), (p_213007_1_) -> { this.currentSelection.Dimensions.add(new OTGDimension(null, -1l)); this.list.resetRows(); this.updateButtonValidity(); })); this.removeDimButton = this.addButton(new Button(this.width / 2 - 50, this.height - 52, 95, 20, new TranslationTextComponent("otg.createDimensions.customize.dimension.removeDimension"), (p_213007_1_) -> { if (this.hasValidSelection() && this.currentSelection.Dimensions.size() > this.list.getSelected().dimId - 3) { this.currentSelection.Dimensions.remove(this.list.getSelected().dimId - 3); this.list.resetRows(); this.updateButtonValidity(); } })); this.editDimButton = this.addButton(new Button(this.width / 2 + 53, this.height - 52, 95, 20, new TranslationTextComponent("otg.createDimensions.customize.dimension.editDimension"), (p_213007_1_) -> { if (this.hasValidSelection()) { this.minecraft.setScreen(new SelectOTGPresetScreen(CreateOTGDimensionsScreen.this, CreateOTGDimensionsScreen.this.currentSelection, this.list.getSelected().dimId)); } })); } // Done this.addButton(new Button(this.width / 2 - 155, this.height - 28, 150, 20, DialogTexts.GUI_DONE, (p_213010_1_) -> { if(!(this.parent instanceof ModpackCreateWorldScreen)) { this.dimensionConfigConsumer.accept(new OTGDimensionSettingsContainer(this.currentSelection, this.dimGenSettings)); } this.minecraft.setScreen(this.parent); } )); // Cancel this.addButton(new Button(this.width / 2 + 5, this.height - 28, 150, 20, DialogTexts.GUI_CANCEL, (p_213009_1_) -> { this.minecraft.setScreen(this.parent); })); this.updateButtonValidity(); } private void updateButtonValidity() { if(!this.uiLocked) { this.removeDimButton.active = this.hasValidSelection(); this.editDimButton.active = this.hasValidSelection(); this.addDimButton.active = this.list.children().size() <= 13; } } private boolean hasValidSelection() { return this.list.getSelected() != null; } public void onClose() { this.minecraft.setScreen(this.parent); } public void render(MatrixStack p_230430_1_, int p_230430_2_, int p_230430_3_, float p_230430_4_) { this.renderBackground(p_230430_1_); this.list.render(p_230430_1_, p_230430_2_, p_230430_3_, p_230430_4_); drawCenteredString(p_230430_1_, this.font, this.title, this.width / 2, 8, 16777215); int i = this.width / 2 - 92 - 16; drawString(p_230430_1_, this.font, this.columnType, i, 32, 16777215); drawString(p_230430_1_, this.font, this.columnHeight, i + 2 + 213 - this.font.width(this.columnHeight), 32, 16777215); super.render(p_230430_1_, p_230430_2_, p_230430_3_, p_230430_4_); } @OnlyIn(Dist.CLIENT) class DetailsList extends ExtendedList<CreateOTGDimensionsScreen.DetailsList.LayerEntry> { public DetailsList() { super(CreateOTGDimensionsScreen.this.minecraft, CreateOTGDimensionsScreen.this.width, CreateOTGDimensionsScreen.this.height, 43, CreateOTGDimensionsScreen.this.height - 60, 24); this.addEntry(new CreateOTGDimensionsScreen.DetailsList.LayerEntry("Overworld", CreateOTGDimensionsScreen.this.currentSelection.Overworld.PresetFolderName == null ? CreateOTGDimensionsScreen.this.currentSelection.Overworld.NonOTGWorldType != null ? CreateOTGDimensionsScreen.this.currentSelection.Overworld.NonOTGWorldType : "Non-OTG": CreateOTGDimensionsScreen.this.currentSelection.Overworld.PresetFolderName, 0)); this.addEntry(new CreateOTGDimensionsScreen.DetailsList.LayerEntry("Nether", CreateOTGDimensionsScreen.this.currentSelection.Nether.PresetFolderName == null ? "Vanilla" : CreateOTGDimensionsScreen.this.currentSelection.Nether.PresetFolderName, 1)); this.addEntry(new CreateOTGDimensionsScreen.DetailsList.LayerEntry("End", CreateOTGDimensionsScreen.this.currentSelection.End.PresetFolderName == null ? "Vanilla" : CreateOTGDimensionsScreen.this.currentSelection.End.PresetFolderName, 2)); int dimId = 3; for(OTGDimension dim : currentSelection.Dimensions) { this.addEntry(new CreateOTGDimensionsScreen.DetailsList.LayerEntry("OTG " + (dimId - 2), dim.PresetFolderName == null ? "None" : dim.PresetFolderName, dimId)); dimId++; } } public void setSelected(@Nullable CreateOTGDimensionsScreen.DetailsList.LayerEntry p_241215_1_) { super.setSelected(p_241215_1_); CreateOTGDimensionsScreen.this.updateButtonValidity(); } protected boolean isFocused() { return CreateOTGDimensionsScreen.this.getFocused() == this; } protected int getScrollbarPosition() { return this.width - 70; } public void resetRows() { int i = this.children().indexOf(this.getSelected()); this.clearEntries(); this.addEntry(new CreateOTGDimensionsScreen.DetailsList.LayerEntry("Overworld", currentSelection.Overworld.PresetFolderName == null ? currentSelection.Overworld.NonOTGWorldType != null ? currentSelection.Overworld.NonOTGWorldType : "Non-OTG" : currentSelection.Overworld.PresetFolderName, 0)); this.addEntry(new CreateOTGDimensionsScreen.DetailsList.LayerEntry("Nether", currentSelection.Nether.PresetFolderName == null ? "Vanilla" : currentSelection.Nether.PresetFolderName, 1)); this.addEntry(new CreateOTGDimensionsScreen.DetailsList.LayerEntry("End", currentSelection.End.PresetFolderName == null ? "Vanilla" : currentSelection.End.PresetFolderName, 2)); int dimId = 3; for(OTGDimension dim : currentSelection.Dimensions) { this.addEntry(new CreateOTGDimensionsScreen.DetailsList.LayerEntry("OTG " + (dimId - 2), dim.PresetFolderName == null ? "None" : dim.PresetFolderName, dimId)); dimId++; } List<CreateOTGDimensionsScreen.DetailsList.LayerEntry> list = this.children(); if (i >= 0 && i < list.size()) { this.setSelected(list.get(i)); } } @OnlyIn(Dist.CLIENT) class LayerEntry extends ExtendedList.AbstractListEntry<CreateOTGDimensionsScreen.DetailsList.LayerEntry> { private final String dimensionName; private String presetFolderName; private int dimId; private LayerEntry(String dimensionName, String presetFolderName, int dimId) { this.dimensionName = dimensionName; this.presetFolderName = presetFolderName; this.dimId = dimId; } public void render(MatrixStack p_230432_1_, int p_230432_2_, int p_230432_3_, int p_230432_4_, int p_230432_5_, int p_230432_6_, int p_230432_7_, int p_230432_8_, boolean p_230432_9_, float p_230432_10_) { String s = I18n.get(this.dimensionName, 32); CreateOTGDimensionsScreen.this.font.draw(p_230432_1_, s, (float)(p_230432_4_), (float)(p_230432_3_ + 3), 16777215); String s1 = I18n.get(this.presetFolderName, 32); CreateOTGDimensionsScreen.this.font.draw(p_230432_1_, s1, (float)(p_230432_4_ + 2 + 213 - CreateOTGDimensionsScreen.this.font.width(s1)), (float)(p_230432_3_ + 3), 16777215); } public boolean mouseClicked(double p_231044_1_, double p_231044_3_, int p_231044_5_) { if (p_231044_5_ == 0 && !CreateOTGDimensionsScreen.this.uiLocked) { DetailsList.this.setSelected(this); if(this.dimId <= 2) // We need to be able to select custom dims, so we can delete them. { DetailsList.this.minecraft.setScreen(new SelectOTGPresetScreen(CreateOTGDimensionsScreen.this, CreateOTGDimensionsScreen.this.currentSelection, this.dimId)); } return true; } else { return false; } } } } }
package javaslang; import static javaslang.Assertions.assertThat; import static javaslang.Serializables.deserialize; import static javaslang.Serializables.serialize; import static org.fest.assertions.api.Assertions.assertThat; import java.io.IOException; import java.io.ObjectOutputStream; import org.junit.Test; public class SerializablesTest { private static final String MAGIC_NUMBER = "0xCAFEBABE"; @Test public void shouldNotInstantiable() { assertThat(Serializables.class).isNotInstantiable(); } @Test public void shouldSerializeDeserialize() { assertThat(deserialize(serialize(MAGIC_NUMBER))).isEqualTo(MAGIC_NUMBER); } @Test public void shouldThrowIllegalStateExceptionOnSerializationError() { final Object o = new Object() { private void writeObject(ObjectOutputStream o) throws IOException { throw new IOException(); } }; assertThat(() -> serialize(o)).isThrowing(IllegalStateException.class, "Error serializing object"); } }
package network.aika; import network.aika.debugger.AIKADebugger; import network.aika.neuron.activation.text.TokenActivation; import network.aika.neuron.conjunctive.*; import network.aika.neuron.conjunctive.text.TokenNeuron; import network.aika.neuron.conjunctive.text.TokenPositionRelationNeuron; import network.aika.neuron.disjunctive.*; import network.aika.text.Document; import org.graphstream.ui.view.camera.Camera; import org.junit.jupiter.api.Test; import java.util.List; import java.util.Map; import java.util.TreeMap; import static network.aika.TestUtils.*; import static network.aika.neuron.disjunctive.InhibSynType.INPUT; public class MetaNeuronTest { public Map<Integer, double[]> getActCoordinateMap() { Map<Integer, double[]> coords = new TreeMap<>(); coords.put(0, new double[]{0.0, 0.0}); coords.put(1, new double[]{1.082, 0.004}); coords.put(2, new double[]{-0.001, 0.298}); coords.put(3, new double[]{0.002, 0.623}); coords.put(4, new double[]{0.244, 0.826}); coords.put(5, new double[]{0.047, 0.926}); coords.put(6, new double[]{0.507, 1.03}); coords.put(7, new double[]{1.082, 0.296}); coords.put(8, new double[]{1.061, 0.574}); coords.put(9, new double[]{1.243, 0.813}); coords.put(10, new double[]{0.632, 0.83}); coords.put(11, new double[]{0.472, 0.009}); coords.put(12, new double[]{0.998, 1.147}); coords.put(13, new double[]{1.243, 1.013}); coords.put(14, new double[]{0.272, 0.287}); coords.put(15, new double[]{0.272, 0.487}); coords.put(16, new double[]{0.664, 0.289}); coords.put(17, new double[]{0.655, 0.513}); coords.put(18, new double[]{0.44, 0.525}); coords.put(19, new double[]{0.44, 0.725}); return coords; } public Map<Long, double[]> getNeuronCoordinateMap() { Map<Long, double[]> coords = new TreeMap<>(); coords.put(1l, new double[]{0.077, -15.728}); coords.put(2l, new double[]{-3.301, 6.852}); coords.put(3l, new double[]{-3.236, 12.599}); coords.put(4l, new double[]{9.227, 38.369}); coords.put(5l, new double[]{-5.69, 38.367}); coords.put(6l, new double[]{2.188, 12.729}); coords.put(7l, new double[]{-15.7, 8.66}); coords.put(8l, new double[]{-7.929, 21.224}); coords.put(9l, new double[]{14.846, 7.498}); coords.put(10l, new double[]{14.858, 21.224}); coords.put(11l, new double[]{-11.775, -16.114}); coords.put(12l, new double[]{11.394, -15.651}); coords.put(13l, new double[]{-12.148, -3.61}); coords.put(14l, new double[]{14.523, -3.094}); coords.put(15l, new double[]{2.156, 6.443}); return coords; } @Test public void testMetaNeuron() { AIKADebugger debugger = AIKADebugger.createAndShowGUI(); debugger.addBreakpoints( ); debugger.setCurrentTestCase(() -> setupMetaNeuronTest(debugger) ); debugger.run(); } private BindingNeuron createInitialSyllableBindingNeuron( Model m, TokenNeuron letterPN, InhibitoryNeuron inhib, PatternNeuron syllablePN ) { CategoryNeuron sylBeginCategory = new BindingCategoryNeuron() .init(m, "Syl. Cat. Pos-0"); BindingNeuron sylBeginBN = new BindingNeuron() .init(m, "Abstract Syl. Pos-0"); new InhibitorySynapse(INPUT) .init(sylBeginBN, inhib, 1.0); new NegativeFeedbackSynapse() .init(inhib, sylBeginBN, -20.0) .adjustBias(); new PatternSynapse() .init(sylBeginBN, syllablePN, 10.0) .adjustBias(); new PositiveFeedbackSynapse() .init(syllablePN, sylBeginBN, 10.0); new InputPatternSynapse() .init(letterPN, sylBeginBN, 10.0) .adjustBias(); new BindingCategoryInputSynapse() .init(sylBeginCategory, sylBeginBN, 1.0); return sylBeginBN; } private BindingNeuron createContinueRightBindingNeuron( Model m, int pos, TokenNeuron letterPN, LatentRelationNeuron relPT, BindingNeuron lastBN, InhibitoryNeuron inhib, PatternNeuron syllablePN ) { CategoryNeuron sylContinueRightCategory = new BindingCategoryNeuron() .init(m, "Syl. Cat. Pos-R" + pos); BindingNeuron sylContinueRightBN = new BindingNeuron() .init(m, "Abstract Syl. Pos-R" + pos); new InhibitorySynapse(INPUT) .init(sylContinueRightBN, inhib, 1.0); new NegativeFeedbackSynapse() .init(inhib, sylContinueRightBN, -20.0) .adjustBias(); new RelationInputSynapse() .init(relPT, sylContinueRightBN, 5.0) .adjustBias(); new SamePatternSynapse() .init(lastBN, sylContinueRightBN, 10.0) .adjustBias(); new PatternSynapse() .init(sylContinueRightBN, syllablePN, 6.0) .adjustBias(); new PositiveFeedbackSynapse() .init(syllablePN, sylContinueRightBN, 10.0); new InputPatternSynapse() .init(letterPN, sylContinueRightBN, 10.0) .adjustBias(); new BindingCategoryInputSynapse() .init(sylContinueRightCategory, sylContinueRightBN, 1.0); sylContinueRightBN.updateBias(3.0); return sylContinueRightBN; } public void setupMetaNeuronTest(AIKADebugger debugger) { Model m = new Model(); LatentRelationNeuron relPT = TokenPositionRelationNeuron.lookupRelation(m, -1, -1); // Abstract CategoryNeuron letterCategory = new PatternCategoryNeuron() .init(m, "PC-letter"); TokenNeuron letterPN = new TokenNeuron() .init(m, "Abstract Letter"); PatternNeuron syllablePN = new PatternNeuron() .init(m, "Syllable"); InhibitoryNeuron inhib =new InhibitoryNeuron() .init(m, "I"); new PatternCategoryInputSynapse() .init(letterCategory, letterPN, 1.0); CategoryNeuron syllableCategory = new PatternCategoryNeuron() .init(m, "Syllable Category"); BindingNeuron sylBeginBN = createInitialSyllableBindingNeuron( m, letterPN, inhib, syllablePN ); BindingNeuron sylRightPos1BN = createContinueRightBindingNeuron( m, 1, letterPN, relPT, sylBeginBN, inhib, syllablePN ); new PatternCategoryInputSynapse() .init(syllableCategory, syllablePN, 1.0); // Concrete TokenNeuron letterS = letterPN.instantiateTemplate(true) .init(m, "L-s", true); TokenNeuron letterC = letterPN.instantiateTemplate(true) .init(m, "L-c", true); letterPN.updateBias(3.0); sylBeginBN.updateBias(3.0); syllablePN.updateBias(3.0); Document doc = new Document(m, "s c h"); debugger.setDocument(doc); debugger.setModel(m); Config c = getConfig() .setAlpha(0.99) .setLearnRate(-0.011) .setInductionThreshold(0.1) .setTrainingEnabled(true); doc.setConfig(c); Map<Integer, double[]> actCoords = getActCoordinateMap(); Map<Long, double[]> neuronCoords = getNeuronCoordinateMap(); debugger.getActivationViewManager().setCoordinateListener(act -> actCoords.get(act.getId())); Camera camera = debugger.getActivationViewManager().getCamera(); camera.setViewPercent(1.65); camera.setViewCenter(0.557, 0.473, 0); debugger.getNeuronViewManager().setCoordinateListener(n -> neuronCoords.get(n.getId())); camera = debugger.getNeuronViewManager().getCamera(); camera.setViewPercent(1.1); camera.setViewCenter(-0.782, 10.985, 0); TokenActivation letterSAct = doc.addToken(letterS, 0, 0, 2); TokenActivation letterCAct = doc.addToken(letterC, 1, 2, 4); process(doc, List.of(letterSAct, letterCAct)); doc.postProcessing(); doc.updateModel(); } }
package org.deft.web; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.apache.http.HttpResponse; import org.apache.http.ProtocolVersion; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpParams; import org.deft.example.AsyncDbHandler; import org.deft.web.handler.RequestHandler; import org.junit.BeforeClass; import org.junit.Test; public class DeftSystemTest { private static final int PORT = 8081; public static final String expectedPayload = "hello test"; private static class ExampleRequestHandler extends RequestHandler { @Override public void get(org.deft.web.protocol.HttpRequest request, org.deft.web.protocol.HttpResponse response) { response.write(expectedPayload); } } private static class WRequestHandler extends RequestHandler { @Override public void get(org.deft.web.protocol.HttpRequest request, org.deft.web.protocol.HttpResponse response) { response.write("1"); } } private static class WWRequestHandler extends RequestHandler { @Override public void get(org.deft.web.protocol.HttpRequest request, org.deft.web.protocol.HttpResponse response) { response.write("1"); response.write("2"); } } private static class WWFWRequestHandler extends RequestHandler { @Override public void get(org.deft.web.protocol.HttpRequest request, org.deft.web.protocol.HttpResponse response) { response.write("1"); response.write("2"); response.flush(); response.write("3"); } } private static class WFWFRequestHandler extends RequestHandler { @Override public void get(org.deft.web.protocol.HttpRequest request, org.deft.web.protocol.HttpResponse response) { response.write("1"); response.flush(); response.write("2"); response.flush(); } } @BeforeClass public static void setup() { Map<String, RequestHandler> reqHandlers = new HashMap<String, RequestHandler>(); reqHandlers.put("/", new ExampleRequestHandler()); reqHandlers.put("/mySql", new AsyncDbHandler()); reqHandlers.put("/w", new WRequestHandler()); reqHandlers.put("/ww", new WWRequestHandler()); reqHandlers.put("/wwfw", new WWFWRequestHandler()); reqHandlers.put("/wfwf", new WFWFRequestHandler()); final Application application = new Application(reqHandlers); // start deft instance from a new thread because the start invocation is blocking // (invoking thread will be I/O loop thread) new Thread(new Runnable() { @Override public void run() { new HttpServer(application).listen(PORT).getIOLoop().start(); } }).start(); } @Test public void simpleGetRequestTest() throws ClientProtocolException, IOException { doSimpleGetRequest(); } private void doSimpleGetRequest() throws ClientProtocolException, IOException { HttpParams params = new BasicHttpParams(); params.setParameter(" Connection", "Close"); HttpClient httpclient = new DefaultHttpClient(params); HttpGet httpget = new HttpGet("http://localhost:" + PORT + "/"); HttpResponse response = httpclient.execute(httpget); List<String> expectedHeaders = Arrays.asList(new String[] {"Server", "Date"}); assertEquals(200, response.getStatusLine().getStatusCode()); assertEquals(new ProtocolVersion("HTTP", 1, 1), response.getStatusLine().getProtocolVersion()); assertEquals("OK", response.getStatusLine().getReasonPhrase()); assertEquals(expectedHeaders.size(), response.getAllHeaders().length); for (String header : expectedHeaders) { assertTrue(response.getFirstHeader(header) != null); } assertEquals(expectedPayload, convertStreamToString(response.getEntity().getContent()).trim()); } /** * Test a RH that does a single write * @throws ClientProtocolException * @throws IOException */ @Test public void wTest() throws ClientProtocolException, IOException { HttpParams params = new BasicHttpParams(); params.setParameter(" Connection", "Close"); HttpClient httpclient = new DefaultHttpClient(params); HttpGet httpget = new HttpGet("http://localhost:" + PORT + "/w"); HttpResponse response = httpclient.execute(httpget); assertNotNull(response); assertEquals(200, response.getStatusLine().getStatusCode()); assertEquals(new ProtocolVersion("HTTP", 1, 1), response.getStatusLine().getProtocolVersion()); assertEquals("OK", response.getStatusLine().getReasonPhrase()); String payLoad = convertStreamToString(response.getEntity().getContent()).trim(); assertEquals("1", payLoad); } @Test public void wwTest() throws ClientProtocolException, IOException { HttpParams params = new BasicHttpParams(); params.setParameter(" Connection", "Close"); HttpClient httpclient = new DefaultHttpClient(params); HttpGet httpget = new HttpGet("http://localhost:" + PORT + "/ww"); HttpResponse response = httpclient.execute(httpget); assertNotNull(response); assertEquals(200, response.getStatusLine().getStatusCode()); assertEquals(new ProtocolVersion("HTTP", 1, 1), response.getStatusLine().getProtocolVersion()); assertEquals("OK", response.getStatusLine().getReasonPhrase()); String payLoad = convertStreamToString(response.getEntity().getContent()).trim(); assertEquals("12", payLoad); } @Test public void wwfwTest() throws ClientProtocolException, IOException { HttpParams params = new BasicHttpParams(); params.setParameter(" Connection", "Close"); HttpClient httpclient = new DefaultHttpClient(params); HttpGet httpget = new HttpGet("http://localhost:" + PORT + "/wwfw"); HttpResponse response = httpclient.execute(httpget); assertNotNull(response); assertEquals(200, response.getStatusLine().getStatusCode()); assertEquals(new ProtocolVersion("HTTP", 1, 1), response.getStatusLine().getProtocolVersion()); assertEquals("OK", response.getStatusLine().getReasonPhrase()); String payLoad = convertStreamToString(response.getEntity().getContent()).trim(); assertEquals("123", payLoad); } @Test public void wfwfTest() throws ClientProtocolException, IOException { HttpParams params = new BasicHttpParams(); params.setParameter(" Connection", "Close"); HttpClient httpclient = new DefaultHttpClient(params); HttpGet httpget = new HttpGet("http://localhost:" + PORT + "/wfwf"); HttpResponse response = httpclient.execute(httpget); assertNotNull(response); assertEquals(200, response.getStatusLine().getStatusCode()); assertEquals(new ProtocolVersion("HTTP", 1, 1), response.getStatusLine().getProtocolVersion()); assertEquals("OK", response.getStatusLine().getReasonPhrase()); String payLoad = convertStreamToString(response.getEntity().getContent()).trim(); assertEquals("12", payLoad); } @Test public void simpleConcurrentGetRequestTest() { int nThreads = 8; int nRequests = 2048; final CountDownLatch latch = new CountDownLatch(nRequests); ExecutorService executor = Executors.newFixedThreadPool(nThreads); for (int i = 1; i <= nRequests; i++) { executor.submit(new Runnable() { @Override public void run() { try { doSimpleGetRequest(); latch.countDown(); } catch (Exception e) { e.printStackTrace(); } } }); } try { latch.await(15 * 1000, TimeUnit.MILLISECONDS); // max wait time } catch (InterruptedException e) { e.printStackTrace(); } if (latch.getCount() != 0) { assertTrue("Did not finish " + nRequests + " # of requests", false); } } public String convertStreamToString(InputStream is) throws IOException { if (is != null) { StringBuilder sb = new StringBuilder(); String line; try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); while ((line = reader.readLine()) != null) { sb.append(line).append("\n"); } } finally { is.close(); } return sb.toString(); } else { return ""; } } }
package org.takes.tk; import java.io.IOException; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Test; import org.takes.rs.RsPrint; /** * Test case for {@link TkMeasured}. * @author Dmitry Molotchko (dima.molotchko@gmail.com) * @version $Id$ * @since 0.9.1 */ public final class TkMeasuredTest { /** * TkMeasured can create a response with HTTP header "X-Takes-Millis". * @throws IOException If some problem inside */ @Test public void createsMeasuredResponse() throws IOException { final String tkMeasuredHeader = "X-Takes-Millis"; MatcherAssert.assertThat( new RsPrint( new TkMeasured(new TkText("default header response")).act() ).print(), Matchers.containsString(tkMeasuredHeader) ); } /** * TkMeasured can create a response with custom HTTP header. * @throws IOException If some problem occurs */ @Test public void createsMeasuredResponseWithCustomHeader() throws IOException { final String customHeader = "X-Custom-Takes-Millis"; MatcherAssert.assertThat( new RsPrint( new TkMeasured( new TkText("custom header response"), customHeader ).act() ).print(), Matchers.containsString(customHeader) ); } }
package org.jpmml.evaluator.association; import java.io.Serializable; import java.util.ArrayList; import java.util.BitSet; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import com.google.common.collect.BiMap; import com.google.common.collect.ImmutableBiMap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import org.dmg.pmml.DataType; import org.dmg.pmml.Field; import org.dmg.pmml.FieldName; import org.dmg.pmml.MiningField; import org.dmg.pmml.PMML; import org.dmg.pmml.Target; import org.dmg.pmml.Targets; import org.dmg.pmml.association.AssociationModel; import org.dmg.pmml.association.AssociationRule; import org.dmg.pmml.association.Item; import org.dmg.pmml.association.ItemRef; import org.dmg.pmml.association.Itemset; import org.dmg.pmml.association.PMMLAttributes; import org.jpmml.evaluator.EntityUtil; import org.jpmml.evaluator.EvaluationContext; import org.jpmml.evaluator.EvaluationException; import org.jpmml.evaluator.Evaluator; import org.jpmml.evaluator.FieldValue; import org.jpmml.evaluator.FieldValueUtil; import org.jpmml.evaluator.FieldValues; import org.jpmml.evaluator.HasEntityRegistry; import org.jpmml.evaluator.HasGroupFields; import org.jpmml.evaluator.IndexableUtil; import org.jpmml.evaluator.InputField; import org.jpmml.evaluator.InvalidAttributeException; import org.jpmml.evaluator.MisplacedElementException; import org.jpmml.evaluator.MissingAttributeException; import org.jpmml.evaluator.MissingValueException; import org.jpmml.evaluator.ModelEvaluator; import org.jpmml.evaluator.PMMLException; import org.jpmml.evaluator.PMMLUtil; import org.jpmml.evaluator.TargetField; import org.jpmml.evaluator.TypeInfos; import org.jpmml.evaluator.ValueFactory; public class AssociationModelEvaluator extends ModelEvaluator<AssociationModel> implements HasGroupFields, HasEntityRegistry<AssociationRule> { private List<InputField> groupInputFields = null; private BiMap<String, AssociationRule> entityRegistry = ImmutableBiMap.of(); private Map<String, Item> items = Collections.emptyMap(); private Map<String, Itemset> itemsets = Collections.emptyMap(); private List<ItemValue> itemValues = null; private AssociationModelEvaluator(){ } public AssociationModelEvaluator(PMML pmml){ this(pmml, PMMLUtil.findModel(pmml, AssociationModel.class)); } public AssociationModelEvaluator(PMML pmml, AssociationModel associationModel){ super(pmml, associationModel); Targets targets = associationModel.getTargets(); if(targets != null){ throw new MisplacedElementException(targets); } // End if if(associationModel.hasAssociationRules()){ this.entityRegistry = ImmutableBiMap.copyOf(EntityUtil.buildBiMap(associationModel.getAssociationRules())); } // End if if(associationModel.hasItems()){ this.items = ImmutableMap.copyOf(IndexableUtil.buildMap(associationModel.getItems(), PMMLAttributes.ITEM_ID)); } // End if if(associationModel.hasItemsets()){ this.itemsets = ImmutableMap.copyOf(IndexableUtil.buildMap(associationModel.getItemsets(), PMMLAttributes.ITEMSET_ID)); } } @Override public String getSummary(){ return "Association rules"; } @Override public List<InputField> getGroupFields(){ if(this.groupInputFields == null){ this.groupInputFields = createInputFields(MiningField.UsageType.GROUP); } return this.groupInputFields; } /** * @return <code>null</code> Always. */ @Override public Target getTarget(FieldName name){ return null; } @Override public FieldName getTargetName(){ return Evaluator.DEFAULT_TARGET_NAME; } @Override public BiMap<String, AssociationRule> getEntityRegistry(){ return this.entityRegistry; } @Override protected List<TargetField> createTargetFields(){ List<TargetField> targetFields = super.createTargetFields(); if(!targetFields.isEmpty()){ throw createMiningSchemaException("Expected 0 target fields, got " + targetFields.size() + " target fields"); } return targetFields; } @Override protected <V extends Number> Map<FieldName, Association> evaluateAssociationRules(ValueFactory<V> valueFactory, EvaluationContext context){ AssociationModel associationModel = getModel(); Set<String> activeItems = getActiveItemIds(context); Map<String, Boolean> flags = new HashMap<>(); List<Itemset> itemsets = associationModel.getItemsets(); for(Itemset itemset : itemsets){ flags.put(itemset.getId(), isSubset(activeItems, itemset)); } List<AssociationRule> associationRules = associationModel.getAssociationRules(); BitSet antecedentFlags = new BitSet(associationRules.size()); BitSet consequentFlags = new BitSet(associationRules.size()); for(int i = 0; i < associationRules.size(); i++){ AssociationRule associationRule = associationRules.get(i); String antecedent = associationRule.getAntecedent(); if(antecedent == null){ throw new MissingAttributeException(associationRule, PMMLAttributes.ASSOCIATIONRULE_ANTECEDENT); } Boolean antecedentFlag = flags.get(antecedent); if(antecedentFlag == null){ throw new InvalidAttributeException(associationRule, PMMLAttributes.ASSOCIATIONRULE_ANTECEDENT, antecedent); } antecedentFlags.set(i, antecedentFlag); String consequent = associationRule.getConsequent(); if(consequent == null){ throw new MissingAttributeException(associationRule, PMMLAttributes.ASSOCIATIONRULE_CONSEQUENT); } Boolean consequentFlag = flags.get(consequent); if(consequentFlag == null){ throw new InvalidAttributeException(associationRule, PMMLAttributes.ASSOCIATIONRULE_CONSEQUENT, consequent); } consequentFlags.set(i, consequentFlag); } Association association = new Association(associationRules, antecedentFlags, consequentFlags){ @Override public Map<String, Item> getItems(){ return AssociationModelEvaluator.this.getItems(); } @Override public Map<String, Itemset> getItemsets(){ return AssociationModelEvaluator.this.getItemsets(); } @Override public BiMap<String, AssociationRule> getEntityRegistry(){ return AssociationModelEvaluator.this.getEntityRegistry(); } }; return Collections.singletonMap(getTargetName(), association); } /** * @return A set of {@link Item#getId() Item identifiers}. */ Set<String> getActiveItemIds(EvaluationContext context){ AssociationModel associationModel = getModel(); List<InputField> activeFields = getActiveFields(); List<InputField> groupFields = getGroupFields(); Set<String> result = new HashSet<>(); Map<FieldName, Set<FieldValue>> explodedValues = null; List<ItemValue> itemValues = getItemValues(); for(ItemValue itemValue : itemValues){ String id = itemValue.getId(); FieldName name = itemValue.getField(); String category = itemValue.getCategory(); FieldValue value = context.evaluate(name); if(groupFields.isEmpty()){ if(FieldValueUtil.isMissing(value)){ continue; } // End if // "The item values are based on field names when the field has only true/false values" if(category == null){ DataType dataType = value.getDataType(); switch(dataType){ case STRING: if((AssociationModelEvaluator.STRING_TRUE).equalsValue(value)){ result.add(id); break; } else if((AssociationModelEvaluator.STRING_FALSE).equalsValue(value)){ break; } // Falls through default: if((AssociationModelEvaluator.BOOLEAN_TRUE).equalsValue(value)){ result.add(id); break; } else if((AssociationModelEvaluator.BOOLEAN_FALSE).equalsValue(value)){ break; } throw new EvaluationException("Expected " + PMMLException.formatValue(AssociationModelEvaluator.BOOLEAN_FALSE) + " or " + PMMLException.formatValue(AssociationModelEvaluator.BOOLEAN_TRUE) + ", got " + PMMLException.formatValue(value)); } } else { if(value.equalsValue(category)){ result.add(id); } } } else if(groupFields.size() == 1){ if(FieldValueUtil.isMissing(value)){ throw new MissingValueException(name); } // End if if(explodedValues == null){ explodedValues = new HashMap<>(); } Set<FieldValue> explodedValue = explodedValues.get(name); if(explodedValue == null){ explodedValue = new HashSet<>(); Collection<?> objects = value.asCollection(); for(Object object : objects){ explodedValue.add(FieldValueUtil.create(value, object)); } } // End if if(category == null){ throw new IllegalStateException(); } else { FieldValue categoryValue = FieldValueUtil.create(value, category); if(explodedValue.contains(categoryValue)){ result.add(id); } } } else { throw createMiningSchemaException("Expected 0 or 1 group field(s), got " + groupFields.size() + " group fields"); } } return result; } static private boolean isSubset(Set<String> items, Itemset itemset){ boolean result = true; List<ItemRef> itemRefs = itemset.getItemRefs(); for(ItemRef itemRef : itemRefs){ result &= items.contains(itemRef.getItemRef()); if(!result){ return false; } } return result; } private Map<String, Item> getItems(){ return this.items; } private Map<String, Itemset> getItemsets(){ return this.itemsets; } private List<ItemValue> getItemValues(){ if(this.itemValues == null){ this.itemValues = ImmutableList.copyOf(parseItemValues(this)); } return this.itemValues; } static private List<ItemValue> parseItemValues(AssociationModelEvaluator modelEvaluator){ AssociationModel associationModel = modelEvaluator.getModel(); List<InputField> activeFields = modelEvaluator.getActiveFields(); List<InputField> groupFields = modelEvaluator.getGroupFields(); List<ItemValue> result = new ArrayList<>(); List<Item> items = associationModel.getItems(); for(Item item : items){ String id = item.getId(); if(id == null){ throw new MissingAttributeException(item, PMMLAttributes.ITEM_ID); } String value = item.getValue(); if(value == null){ throw new MissingAttributeException(item, PMMLAttributes.ITEM_VALUE); } FieldName name = item.getField(); String category = item.getCategory(); parser: if(name == null){ // Categorical data style: no group fields, one or more active fields if(groupFields.isEmpty()){ if(activeFields.isEmpty()){ throw modelEvaluator.createMiningSchemaException("Expected 1 or more active field(s), got " + activeFields.size() + " active fields"); } name = FieldName.create(value); category = null; Field<?> field = modelEvaluator.resolveField(name); if(field != null){ break parser; } int index = value.indexOf('='); if(index > -1){ name = FieldName.create(value.substring(0, index)); category = value.substring(index + 1); field = modelEvaluator.resolveField(name); if(field != null){ break parser; } } throw new InvalidAttributeException(item, PMMLAttributes.ITEM_VALUE, value); } else // Transactional data style: one group field, one active field if(groupFields.size() == 1){ if(activeFields.size() != 1){ throw modelEvaluator.createMiningSchemaException("Expected 1 active field, got " + activeFields.size() + " active fields"); } InputField activeField = activeFields.get(0); name = activeField.getFieldName(); category = value; } else { throw modelEvaluator.createMiningSchemaException("Expected 0 or 1 group field(s), got " + groupFields.size() + " group fields"); } } else { if(groupFields.size() == 1){ if(category != null){ break parser; } } // End if if(category == null){ throw new MissingAttributeException(item, PMMLAttributes.ITEM_CATEGORY); } } ItemValue itemValue = new ItemValue(id, name, category); result.add(itemValue); } return result; } static private class ItemValue implements Serializable { private String id = null; private FieldName field = null; private String category = null; private ItemValue(){ } private ItemValue(String id, FieldName field, String category){ setId(id); setField(field); setCategory(category); } private String getId(){ return this.id; } private void setId(String id){ this.id = id; } private FieldName getField(){ return this.field; } private void setField(FieldName field){ this.field = field; } private String getCategory(){ return this.category; } private void setCategory(String category){ this.category = category; } } // IBM SPSS-style schema private static final FieldValue STRING_TRUE = FieldValueUtil.create(TypeInfos.CATEGORICAL_STRING, "T"); private static final FieldValue STRING_FALSE = FieldValueUtil.create(TypeInfos.CATEGORICAL_STRING, "F"); private static final FieldValue BOOLEAN_TRUE = FieldValues.CATEGORICAL_BOOLEAN_TRUE; private static final FieldValue BOOLEAN_FALSE = FieldValues.CATEGORICAL_BOOLEAN_FALSE; }
import java.awt.geom.*; import java.util.*; public class PrioritySearchTree { PSTNode[] heap; public PrioritySearchTree(ArrayList<PSTPoint> points) { if(points == null) return; Collections.sort(points); // Sort by y-coordinate in increasing order this.heap = new PSTNode[heapSize(treeHeight(points.size()))]; buildTree(0,points); } private void buildTree(int rootIndex, ArrayList<PSTPoint> points) { if(points == null || points.size() < 1) return; // Since points are ordered by y increasing, smallest is first PSTPoint rootPoint = points.get(0); // Find median X value // - uses average X value of non-root points double sumX = 0.0d; for(PSTPoint p : points) { sumX += p.getX(); } sumX -= rootPoint.getX(); double medianX = sumX/(points.size()-1); // Set the root node heap[rootIndex] = new PSTNode(rootPoint,medianX); // Bisect the non-root points into two arrays above and below the median ArrayList<PSTPoint> upperPoints = new ArrayList<PSTPoint>(); ArrayList<PSTPoint> lowerPoints = new ArrayList<PSTPoint>(); for(PSTPoint p : points) { if(p == rootPoint) continue; // note: if p.x is equal to median, it will be added to left child else if(p.getX() <= medianX) lowerPoints.add(p); else upperPoints.add(p); } if(lowerPoints.size() > 0) buildTree(indexOfLeftChild(rootIndex),lowerPoints); if(upperPoints.size() > 0) buildTree(indexOfRightChild(rootIndex),upperPoints); } public ArrayList<PSTPoint> findAllPointsWithin(double x1, double x2, double y2) { return findAllPointsWithin(x1,x2,y2,new ArrayList<PSTPoint>(),0); } public ArrayList<PSTPoint> findAllPointsWithin(double x1, double y1, double x2, double y2) { return findAllPointsWithin(x1,y1,x2,y2,new ArrayList<PSTPoint>(),0); } public ArrayList<PSTPoint> findAllPointsWithin(double x1, double y1, double x2, double y2, ArrayList<PSTPoint> list, int rootIndex) { PSTNode node = heap[rootIndex]; if(node == null) return list; double nodeY = node.getY(); double nodeX = node.getX(); double nodeR = node.getMedianX(); if(nodeY < y1) { // nodeR >= points in left tree >= x1 if(nodeR >= x1) findAllPointsWithin(x1,y1,x2,y2,list,indexOfLeftChild(rootIndex)); // nodeR < points in right tree <= x2 if(nodeR < x2) findAllPointsWithin(x1,y1,x2,y2,list,indexOfRightChild(rootIndex)); } else { // Now that nodeY >= y1, we can do a 3 bounded search findAllPointsWithin(x1,x2,y2,list,rootIndex); } return list; } // Note that as y2 and x2 approach positive infinity and // x1 approaches negative infinity, this search visits more nodes. // In the worst case, all nodes are visited. public ArrayList<PSTPoint> findAllPointsWithin(double x1, double x2, double y2, ArrayList<PSTPoint> list, int rootIndex) { PSTNode node = heap[rootIndex]; if(node == null) return list; double nodeX = node.getX(); double nodeY = node.getY(); double nodeR = node.getMedianX(); if(nodeY <= y2) { if(nodeX >= x1 && nodeX <= x2) { list.add(node.getPoint()); } // nodeR >= points in left tree >= x1 if(nodeR >= x1) findAllPointsWithin(x1,x2,y2,list,indexOfLeftChild(rootIndex)); // nodeR < points in right tree <= x2 if(nodeR < x2) findAllPointsWithin(x1,x2,y2,list,indexOfRightChild(rootIndex)); } return list; } public double minY() throws EmptyTreeException { if(heap[0] == null) throw new EmptyTreeException(); return heap[0].getY(); } public double minX() throws EmptyTreeException { int index = 0; if(heap[index] == null) throw new EmptyTreeException(); double min = heap[index].getX(); while(indexOfLeftChild(index) < heap.length && heap[indexOfLeftChild(index)] != null) { index = indexOfLeftChild(index); if(heap[index].getX() < min) min = heap[index].getX(); } return min; } public double maxX() throws EmptyTreeException { int index = 0; if(heap[index] == null) throw new EmptyTreeException(); double max = heap[index].getX(); while(indexOfRightChild(index) < heap.length && heap[indexOfRightChild(index)] != null) { index = indexOfRightChild(index); if(heap[index].getX() > max) max = heap[index].getX(); } return max; } // Determine the height of a balanced tree with n elements private static int treeHeight(int n) { return doubleToInt(Math.ceil(Math.log(n+1)/Math.log(2))-1); } // Determine the max number of heap nodes in a tree of given height private static int heapSize(int height) { return doubleToInt(Math.pow(2, height + 1)-1); } private static int indexOfLeftChild(int rootIndex) { return (2*rootIndex)+1; } private static int indexOfRightChild(int rootIndex) { return (2*rootIndex)+2; } private static int doubleToInt(double d) { return (new Double(d)).intValue(); } private static void printList(ArrayList<PSTPoint> points) { for(PSTPoint p : points) System.out.print(p + " "); System.out.println(); } public static void main(String[] args) throws EmptyTreeException { // Test construction new PrioritySearchTree(null); ArrayList<PSTPoint> testPoints = new ArrayList<PSTPoint>(); testPoints.add(new PSTPoint(1.0d,1.0d)); testPoints.add(new PSTPoint(2.0d,5.0d)); testPoints.add(new PSTPoint(3.0d,3.0d)); testPoints.add(new PSTPoint(-3.0d,0.0d)); testPoints.add(new PSTPoint(-2.0d,4.0d)); testPoints.add(new PSTPoint(-1.0d,2.0d)); testPoints.add(new PSTPoint(4.0d,-1.0d)); testPoints.add(new PSTPoint(5.0d,-2.0d)); testPoints.add(new PSTPoint(6.0d,-3.0d)); testPoints.add(new PSTPoint(7.0d,22.0d)); testPoints.add(new PSTPoint(8.0d,42.0d)); testPoints.add(new PSTPoint(0.0d,-30.0d)); PrioritySearchTree pst = new PrioritySearchTree(testPoints); // Test query System.out.print("All points within 4 bounds: "); printList(pst.findAllPointsWithin(-3.0d,-3.0d,3.0d,3.0d)); System.out.print("All points within 3 bounds: "); printList(pst.findAllPointsWithin(-3.0d,3.0d,3.0d)); System.out.println("MinY: " + pst.minY()); System.out.println("MinX: " + pst.minX()); System.out.println("MaxX: " + pst.maxX()); // Test with more data testPoints = new ArrayList<PSTPoint>(); for(double i = 1.0d; i < 10000; i++) { testPoints.add(new PSTPoint(i,i)); testPoints.add(new PSTPoint(-i,-i)); } pst = new PrioritySearchTree(testPoints); System.out.print("All points (larger data set) within 4 bounds: "); printList(pst.findAllPointsWithin(-3.0d,-3.0d,3.0d,3.0d)); System.out.print("All points (larger data set) within 3 bounds: "); printList(pst.findAllPointsWithin(-3.0d,3.0d,3.0d)); System.out.println("MinY: " + pst.minY()); System.out.println("MinX: " + pst.minX()); System.out.println("MaxX: " + pst.maxX()); } public class EmptyTreeException extends Exception { public EmptyTreeException() { super("Tree is empty"); } } }
package org.jdesktop.test; import java.util.Collections; import java.util.LinkedList; import java.util.List; import javax.swing.ListModel; import javax.swing.event.ListDataEvent; import javax.swing.event.ListDataListener; /** * A <code>ListDataListener</code> that stores the received * <code>ListDataEvents</code>. * */ public class ListDataReport implements ListDataListener { /** * Holds a list of all canceled events. */ protected List<ListDataEvent> changedEvents = Collections.synchronizedList(new LinkedList<ListDataEvent>()); protected List<ListDataEvent> addedEvents = Collections.synchronizedList(new LinkedList<ListDataEvent>()); protected List<ListDataEvent> removedEvents = Collections.synchronizedList(new LinkedList<ListDataEvent>()); protected List<ListDataEvent> allEvents = Collections.synchronizedList(new LinkedList<ListDataEvent>()); /** * Instantiates a ListDataReport. */ public ListDataReport() { this(null); } /** * Instantiates a ListDataReport and registers as listener to the given ListModel. */ public ListDataReport(ListModel model) { if (model != null) { model.addListDataListener(this); } } public void contentsChanged(ListDataEvent e) { changedEvents.add(0, e); allEvents.add(0, e); } public void intervalAdded(ListDataEvent e) { addedEvents.add(e); allEvents.add(0, e); } public void intervalRemoved(ListDataEvent e) { removedEvents.add(e); allEvents.add(0, e); } public void clear() { changedEvents.clear(); addedEvents.clear(); removedEvents.clear(); allEvents.clear(); } public int getEventCount() { return allEvents.size(); } public boolean hasEvents() { return !allEvents.isEmpty(); } public ListDataEvent getLastEvent() { return allEvents.isEmpty() ? null : allEvents.get(0); } public int getChangedEventCount() { return changedEvents.size(); } public boolean hasChangedEvents() { return !changedEvents.isEmpty(); } public ListDataEvent getLastChangedEvent() { return changedEvents.isEmpty() ? null : changedEvents.get(0); } public int getAddedEventCount() { return addedEvents.size(); } public boolean hasAddedEvents() { return !addedEvents.isEmpty(); } public ListDataEvent getLastAddedEvent() { return addedEvents.isEmpty() ? null : addedEvents.get(0); } public int getRemovedEventCount() { return removedEvents.size(); } public boolean hasRemovedEvents() { return !removedEvents.isEmpty(); } public ListDataEvent getLastRemovedEvent() { return removedEvents.isEmpty() ? null : removedEvents.get(0); } }
package org.csstudio.sns.product; import org.csstudio.platform.ui.workspace.WorkspaceSwitchHelper; import org.eclipse.core.runtime.IPlatformRunnable; import org.eclipse.core.runtime.Platform; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.osgi.service.datalocation.Location; import org.eclipse.osgi.util.NLS; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.PlatformUI; /** This class controls all aspects of the application's execution * @author Kay Kasemir */ public class Application implements IPlatformRunnable { /** {@inheritDoc} */ @SuppressWarnings("nls") //$NON-NLS-1$ public Object run(Object args) throws Exception { Display display = PlatformUI.createDisplay(); try { PluginActivator.logInfo("CSS Application started"); //$NON-NLS-1$ int returnCode = 0; // Select the workspace Location workspace_location = null; try { boolean need_workspace = true; while (need_workspace) { // Query for workpace final String workspace = WorkspaceSwitchHelper.promptForWorkspace(null, true); // Nothing selected if (workspace == null) { PluginActivator.logInfo("CSS Application Canceled"); //$NON-NLS-1$ return IPlatformRunnable.EXIT_OK; } // Does this require a restart? if (WorkspaceSwitchHelper.prepareWorkspaceSwitch(null, workspace)) { MessageDialog.openInformation(null, Messages.Application_RestartTitle, NLS.bind(Messages.Application_RestartMessage, workspace)); PluginActivator.logInfo("CSS Application Relaunch"); //$NON-NLS-1$ return IPlatformRunnable.EXIT_RELAUNCH; } // Lock the workspace workspace_location = Platform.getInstanceLocation(); PluginActivator.logInfo("CSS Workspace: " + workspace_location); //$NON-NLS-1$ if (workspace_location.lock()) need_workspace = false; else { workspace_location = null; // Cannot lock the workspace. // Give message, then query again MessageDialog.openError(null, Messages.Application_WorkspaceInUseError, NLS.bind(Messages.Application_WorkspaceInUseInfo, workspace)); } } PluginActivator.logInfo("CSS Application Running"); //$NON-NLS-1$ returnCode = PlatformUI.createAndRunWorkbench(display, new ApplicationWorkbenchAdvisor()); } finally { if (workspace_location != null && workspace_location.isSet()) workspace_location.release(); } if (returnCode == PlatformUI.RETURN_RESTART) { // Something called IWorkbench.restart(). // Is this supposed to be a RESTART or RELAUNCH? final Integer exit_code = Integer.getInteger(RelaunchConstants.PROP_EXIT_CODE); if (IPlatformRunnable.EXIT_RELAUNCH.equals(exit_code)) { // RELAUCH with new command line PluginActivator.logInfo("RELAUNCH, command line:"); //$NON-NLS-1$ PluginActivator.logInfo( System.getProperty(RelaunchConstants.PROP_EXIT_DATA)); return IPlatformRunnable.EXIT_RELAUNCH; } // RESTART without changes return IPlatformRunnable.EXIT_RESTART; } // Plain exit from IWorkbench.close() return IPlatformRunnable.EXIT_OK; } finally { display.dispose(); } } }
package carelender.controller; import carelender.controller.callbacks.OnConfirmedCallback; import carelender.controller.states.AppState; import carelender.controller.states.BlockingStateController; import carelender.controller.states.StateManager; import carelender.model.AppSettings; import carelender.model.AppSettings.SettingName; import carelender.model.data.*; import carelender.model.strings.FirstStartMessages; import carelender.view.gui.UserInterfaceController; import carelender.view.parser.DateTimeParser; import carelender.view.parser.InputParser; import java.util.*; /** * Does all the logic of the application */ public class Controller { private static UserInterfaceController userInterfaceController = null; private static StateManager stateManager; private static BlockingStateController blockingStateController; //Stores the messages to the user //private static ArrayList<String> messageList; //Stores the user's inputs private static ArrayList<String> commandList; private static int currentCommand; private static String incompleteInput; //Application state private static String userName; private static QueryList currentListQuery; private static TimerTask reminder; private static Timer timer; public static void initialize() throws Exception { //messageList = new ArrayList<>(); commandList = new ArrayList<>(); stateManager = new StateManager(); blockingStateController = new BlockingStateController(); //Initialize timer for reminder TimerTask reminder = new ReminderCaller(); Timer timer = new Timer(); timer.scheduleAtFixedRate(reminder,5000,5000); userName = null; if(AppSettings.getInstance().getStringSetting(SettingName.USERNAME) != null){ userName = AppSettings.getInstance().getStringSetting(SettingName.USERNAME); System.out.println("Username: " + userName); } currentCommand = 0; } public static void stopTimer() { timer.cancel(); } public static void initUserInterfaceController(UserInterfaceController userInterfaceController) { Controller.userInterfaceController = userInterfaceController; //Controller.userInterfaceController.setMessageList(messageList); /*canvasRenderer = new MonthViewRenderer(); Controller.userInterfaceController.setCanvasRenderer(canvasRenderer);*/ } /** * Called by UI when up key is pressed */ public static void processUpPress() { if (currentCommand < commandList.size() - 1){ currentCommand++; } showPreviousCommand(); } /** * Called by UI when down key is pressed */ public static void processDownPress() { if ( currentCommand >= 0 ) { currentCommand } showPreviousCommand(); } /** * Called by UI when page down key is pressed */ public static void processPageDownPress() { userInterfaceController.processPageDownPress(); } /** * Called by UI when page up key is pressed */ public static void processPageUpPress() { userInterfaceController.processPageUpPress(); } /** * Shows any previous command based on the currentCommand variable */ private static void showPreviousCommand() { if ( currentCommand == -1 ) { //Index -1 is an empty command userInterfaceController.setUserInput(incompleteInput); } else { int commandIndex = commandList.size() - currentCommand - 1; if (commandIndex < 0 || commandIndex >= commandList.size()) { return; } userInterfaceController.setUserInput(commandList.get(commandIndex)); } } /** * Saves the user's command. Removes duplicates and empty commands * @param userInput User input to save */ private static void saveUserCommand ( String userInput ) { if ( userInput.length() > 0 ) { int index = commandList.indexOf(userInput); if ( index >= 0 ) commandList.remove(index); commandList.add(userInput); currentCommand = -1; } } /** * Called by UI while user is typing * @param userInput the incomplete user input */ public static void processIncompleteInput(String userInput) { incompleteInput = userInput; if ( stateManager.getAppState() == AppState.DEFAULT && !blockingStateController.isBlocked() ) { StringBuilder stringBuilder = new StringBuilder(); String [] autocompleteOptions = InputParser.getInstance().getAutocompleteOptions(userInput, stringBuilder); if ( autocompleteOptions != null ) { //System.out.println("Autocomplete size: " + autocompleteOptions.length); } else { //System.out.println("No match"); } userInterfaceController.setAutocompleteOptions(autocompleteOptions, stringBuilder.toString()); } else { userInterfaceController.setAutocompleteOptions(null, null); } } /** * Processes the user input. * Called by the UserInterfaceController class * @param userInput The user input string */ public static void processCompleteInput(String userInput) { userInterfaceController.setAutocompleteOptions(null, null); userInput = userInput.trim(); saveUserCommand(userInput); boolean blocked = blockingStateController.processBlockingState(userInput); if ( !blocked ) { switch ( stateManager.getAppState() ) { case FIRSTSTART: stateFirstStart(userInput); break; default: stateDefault(userInput); break; } } } private static void stateFirstStart ( String userInput ) { final OnConfirmedCallback confirmNameCallback = new OnConfirmedCallback() { @Override public void onConfirmed(boolean confirmed) { System.out.println("Confirmed: " + confirmed); if ( confirmed ) { displayMessage(FirstStartMessages.confirmed(userName)); stateManager.changeState(AppState.DEFAULT); AppSettings.getInstance().setStringSetting(SettingName.USERNAME, userInput); refreshDisplay(); } else { displayMessage(FirstStartMessages.askForNameAgain()); userName = null; } } }; userName = userInput; blockingStateController.startConfirmation(FirstStartMessages.confirmation(userName), confirmNameCallback); } private static void stateDefault(String userInput) { if ( userInput.length() == 0 ) { return; } QueryBase query = InputParser.getInstance().parseCompleteInput(userInput); query.userInput = userInput; switch (query.getQueryType()) { case DATETEST: DateRange[] dateRanges = DateTimeParser.parseDateTime(userInput); displayMessage( "User input: [" + userInput + "]" ); displayMessage("Matched " + dateRanges.length + " dates"); for(DateRange range:dateRanges) { displayMessage(" " + range.toString()); } break; case DEV1: //canvasRenderer.increment(); break; case DEV2: break; case LIST: currentListQuery = (QueryList)query; break; case EXIT: System.exit(0); break; default: query.controllerExecute(); break; } refreshDisplay(); } /** * Converts an add query to an event object * @param queryAdd * @return */ public static Event queryAddToEventObject(QueryAdd queryAdd) { Event eventObj = new Event(0, queryAdd.getName(), queryAdd.getDateRange(), queryAdd.getCategory()); return eventObj; } public static void showHelp() { //userInterfaceController.displayMessage("Available Commands:"); //userInterfaceController.displayMessage(InputParser.getInstance().showCommandList()); blockingStateController.startPopup(InputParser.getInstance().showCommandList()); } public static void printWelcomeMessage() { if ( stateManager.isState(AppState.FIRSTSTART) && userName == null ) { userInterfaceController.setAnnouncementMessage("CareLender: Maybe the best task manager in the world.\n" + FirstStartMessages.askForName()); } else { userInterfaceController.setAnnouncementMessage("Welcome back, " + userName); stateManager.changeState(AppState.DEFAULT); } } /** * Refreshes the list of events. * It is called after every query the user inputs */ public static void refreshDisplay () { if ( currentListQuery == null) { currentListQuery = new QueryList(); currentListQuery.addSearchParam(QueryList.SearchParam.DATE_START, DateTimeParser.getDate(0)); } currentListQuery.controllerExecute(); userInterfaceController.refreshOutputField(); } /** * Prints a message to screen * @param message message to be displayed */ public static void displayMessage ( String message ) { userInterfaceController.displayMessage(message); } public static void displayAnnouncement ( String message ) { userInterfaceController.setAnnouncementMessage(message); } public static void displayTasks (EventList events) { userInterfaceController.setTaskList(events); } public static void clearMessages () { userInterfaceController.clearMessageLog(); } public static void setDisplayedList(EventList displayedList) { InputParser.getInstance().setDisplayedList(displayedList); userInterfaceController.setWeekEventList(displayedList); } public static BlockingStateController getBlockingStateController() { return blockingStateController; } public static UserInterfaceController getGUI() { return userInterfaceController; } public static void processTabPress() { userInterfaceController.processTabPress(); } }
package com.jetbrains.python.codeInsight.intentions; import com.intellij.codeInsight.CodeInsightUtilBase; import com.intellij.codeInsight.intention.IntentionAction; import com.intellij.codeInsight.template.*; import com.intellij.lang.ASTNode; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.fileEditor.OpenFileDescriptor; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiReference; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.IncorrectOperationException; import com.jetbrains.python.PyBundle; import com.jetbrains.python.PyNames; import com.jetbrains.python.PyTokenTypes; import com.jetbrains.python.documentation.PyDocumentationSettings; import com.jetbrains.python.documentation.PythonDocumentationProvider; import com.jetbrains.python.psi.*; import com.jetbrains.python.psi.resolve.PyResolveContext; import com.jetbrains.python.psi.types.PyReturnTypeReference; import com.jetbrains.python.psi.types.PyType; import com.jetbrains.python.psi.types.TypeEvalContext; import org.jetbrains.annotations.NotNull; /** * User: ktisha * * Helps to specify type */ public class SpecifyTypeInDocstringIntention implements IntentionAction { private String myText = PyBundle.message("INTN.specify.type"); public SpecifyTypeInDocstringIntention() { } @NotNull public String getText() { return myText; } @NotNull public String getFamilyName() { return PyBundle.message("INTN.specify.type"); } public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) { PsiElement elementAt = file.findElementAt(editor.getCaretModel().getOffset() - 1); if (elementAt != null && !(elementAt.getNode().getElementType() == PyTokenTypes.IDENTIFIER)) elementAt = file.findElementAt(editor.getCaretModel().getOffset()); PyCallExpression callExpression = PsiTreeUtil.getParentOfType(elementAt, PyCallExpression.class); if (callExpression != null ) { PyAssignmentStatement assignmentStatement = PsiTreeUtil.getParentOfType(elementAt, PyAssignmentStatement.class); if (assignmentStatement != null) { PyType type = assignmentStatement.getAssignedValue().getType(TypeEvalContext.slow()); if (type == null || type instanceof PyReturnTypeReference) { myText = PyBundle.message("INTN.specify.return.type"); return true; } } } else { PyFunction parentFunction = PsiTreeUtil.getParentOfType(elementAt, PyFunction.class); if (parentFunction != null) { final ASTNode nameNode = parentFunction.getNameNode(); if (nameNode != null && nameNode.getPsi() == elementAt) { myText = PyBundle.message("INTN.specify.return.type"); return true; } } } PyExpression problemElement = PyUtil.findProblemElement(editor, file, PyNamedParameter.class, PyQualifiedExpression.class); if (problemElement == null) return false; if (problemElement instanceof PyQualifiedExpression) { final PyExpression qualifier = ((PyQualifiedExpression)problemElement).getQualifier(); if (qualifier != null && !qualifier.getText().equals(PyNames.CANONICAL_SELF)) { problemElement = qualifier; } } if (problemElement.getParent() instanceof PyCallExpression || PsiTreeUtil.getParentOfType(problemElement, PyLambdaExpression.class) != null) { return false; } final PyType type = problemElement.getType(TypeEvalContext.slow()); if (type == null || type instanceof PyReturnTypeReference) { PyFunction pyFunction = PsiTreeUtil.getParentOfType(problemElement, PyFunction.class); PsiReference reference = problemElement.getReference(); if (problemElement instanceof PyQualifiedExpression) { final PyExpression qualifier = ((PyQualifiedExpression)problemElement).getQualifier(); if (qualifier != null && !qualifier.getText().equals(PyNames.CANONICAL_SELF)) reference = qualifier.getReference(); } if (pyFunction != null && (problemElement instanceof PyParameter || reference != null && reference.resolve() instanceof PyParameter)) { final String docstring = pyFunction.getDocStringValue(); if (docstring != null) { String name = problemElement.getName(); if (problemElement instanceof PyQualifiedExpression) { final PyExpression qualifier = ((PyQualifiedExpression)problemElement).getQualifier(); if (qualifier != null) name = qualifier.getText(); } if (docstring.contains("type " + name + ":")) return false; } return true; } } return false; } public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException { PsiElement elementAt = file.findElementAt(editor.getCaretModel().getOffset() - 1); if (elementAt != null && !(elementAt.getNode().getElementType() == PyTokenTypes.IDENTIFIER)) elementAt = file.findElementAt(editor.getCaretModel().getOffset()); String type = "type"; String name = ""; PyCallExpression callExpression = PsiTreeUtil.getParentOfType(elementAt, PyCallExpression.class); PyFunction pyFunction = PsiTreeUtil.getParentOfType(elementAt, PyFunction.class); PyExpression problemElement = PyUtil.findProblemElement(editor, file, PyNamedParameter.class, PyQualifiedExpression.class); if (callExpression != null ) { PyAssignmentStatement assignmentStatement = PsiTreeUtil.getParentOfType(elementAt, PyAssignmentStatement.class); if (assignmentStatement != null) { PyType pyType = assignmentStatement.getAssignedValue().getType(TypeEvalContext.slow()); if (pyType == null || pyType instanceof PyReturnTypeReference) { pyFunction = (PyFunction)callExpression.resolveCalleeFunction(PyResolveContext.defaultContext()); problemElement = null; type = "rtype"; } } } if (pyFunction != null) { final ASTNode nameNode = pyFunction.getNameNode(); if (nameNode != null && nameNode.getPsi() == elementAt) { type = "rtype"; } } PyDocumentationSettings documentationSettings = PyDocumentationSettings.getInstance(project); String prefix = ":"; if (documentationSettings.isEpydocFormat(file)) { prefix = "@"; } PsiReference reference = null; PyElementGenerator elementGenerator = PyElementGenerator.getInstance(project); if (problemElement != null) { name = problemElement.getName(); reference = problemElement.getReference(); if (problemElement instanceof PyQualifiedExpression) { final PyExpression qualifier = ((PyQualifiedExpression)problemElement).getQualifier(); if (qualifier != null) { reference = qualifier.getReference(); name = qualifier.getText(); } } pyFunction = PsiTreeUtil.getParentOfType(problemElement, PyFunction.class); } final ASTNode nameNode = pyFunction.getNameNode(); if ((pyFunction != null && (problemElement instanceof PyParameter || reference != null && reference.resolve() instanceof PyParameter)) || elementAt == nameNode.getPsi() || callExpression != null) { PyStringLiteralExpression docStringExpression = pyFunction.getDocStringExpression(); int startOffset; int endOffset; final Pair<String, Integer> replacementToOffset = PythonDocumentationProvider.addParamToDocstring(pyFunction, type, name, prefix); if (docStringExpression != null) { final String typePattern = type + " " + name + ":"; final int index = docStringExpression.getText().indexOf(typePattern); if (index == -1) { PyExpression str = elementGenerator.createDocstring(replacementToOffset.getFirst()).getExpression(); docStringExpression.replace(str); startOffset = replacementToOffset.getSecond(); endOffset = startOffset; } else { startOffset = index + typePattern.length() + 1; endOffset = docStringExpression.getText().indexOf("\n", startOffset); if (endOffset == -1) endOffset = startOffset; } pyFunction = CodeInsightUtilBase.forcePsiPostprocessAndRestoreElement(pyFunction); docStringExpression = pyFunction.getDocStringExpression(); } else { final PyStatementList list = pyFunction.getStatementList(); final Document document = editor.getDocument(); startOffset = replacementToOffset.getSecond(); if (list != null && list.getStatements().length != 0) { if (document.getLineNumber(list.getTextOffset()) == document.getLineNumber(pyFunction.getTextOffset())) { PyFunction func = elementGenerator.createFromText(LanguageLevel.forElement(pyFunction), PyFunction.class, "def " + pyFunction.getName() + pyFunction.getParameterList().getText() +":\n\t"+replacementToOffset.getFirst() + "\n\t" + list.getText()); pyFunction = (PyFunction)pyFunction.replace(func); startOffset = replacementToOffset.getSecond() + 2; } else { PyExpressionStatement str = elementGenerator.createDocstring(replacementToOffset.getFirst()); list.addBefore(str, list.getStatements()[0]); } } pyFunction = CodeInsightUtilBase.forcePsiPostprocessAndRestoreElement(pyFunction); docStringExpression = pyFunction.getDocStringExpression(); endOffset = startOffset; } assert docStringExpression != null; int textOffSet = docStringExpression.getTextOffset(); final TemplateBuilder builder = TemplateBuilderFactory.getInstance().createTemplateBuilder(docStringExpression); builder.replaceRange(TextRange.create(startOffset, endOffset), PyNames.OBJECT); Template template = ((TemplateBuilderImpl)builder).buildInlineTemplate(); OpenFileDescriptor descriptor = new OpenFileDescriptor( project, pyFunction.getContainingFile().getVirtualFile(), pyFunction.getTextOffset() + pyFunction.getTextLength() ); Editor targetEditor = FileEditorManager.getInstance(project).openTextEditor(descriptor, true); if (targetEditor != null) { targetEditor.getCaretModel().moveToOffset(textOffSet); TemplateManager.getInstance(project).startTemplate(targetEditor, template); } } } public boolean startInWriteAction() { return true; } }
package com.carrotsearch.randomizedtesting; import junit.framework.Assert; import org.junit.After; import org.junit.Test; import org.junit.runner.JUnitCore; import org.junit.runner.Result; import com.carrotsearch.randomizedtesting.annotations.Timeout; /** * Test global timeout override (-Dtests.timeout=1000!). */ public class TestTimeoutOverride extends WithNestedTestClass { public static class Nested extends RandomizedTest { @Test @Timeout(millis = 5000) public void testMethod1() { assumeRunningNested(); sleep(10000); } } public static class Nested2 extends RandomizedTest { @Test @Timeout(millis = 100) public void testMethod1() { assumeRunningNested(); sleep(1000); } } @Test public void testTimeoutOverride() { System.setProperty(SysGlobals.SYSPROP_TIMEOUT(), "200!"); long start = System.currentTimeMillis(); Result result = JUnitCore.runClasses(Nested.class); long end = System.currentTimeMillis(); Assert.assertEquals(1, result.getFailureCount()); Assert.assertTrue(end - start < 3000); } @Test public void testDisableTimeout() { System.setProperty(SysGlobals.SYSPROP_TIMEOUT(), "0!"); long start = System.currentTimeMillis(); Result result = JUnitCore.runClasses(Nested2.class); long end = System.currentTimeMillis(); Assert.assertEquals(0, result.getFailureCount()); Assert.assertTrue(end - start > 900); } @After public void cleanup() { System.clearProperty(SysGlobals.SYSPROP_TIMEOUT()); } }
package com.intellij.refactoring.encapsulateFields; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.*; import com.intellij.psi.codeStyle.CodeStyleManager; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.PsiSearchHelper; import com.intellij.psi.tree.IElementType; import com.intellij.psi.util.PsiFormatUtil; import com.intellij.psi.util.PsiUtil; import com.intellij.refactoring.BaseRefactoringProcessor; import com.intellij.refactoring.HelpID; import com.intellij.refactoring.RefactoringBundle; import com.intellij.refactoring.ui.ConflictsDialog; import com.intellij.refactoring.util.*; import com.intellij.usageView.UsageInfo; import com.intellij.usageView.UsageViewDescriptor; import com.intellij.usageView.UsageViewUtil; import com.intellij.util.IncorrectOperationException; import com.intellij.util.containers.HashMap; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; import java.util.Map; public class EncapsulateFieldsProcessor extends BaseRefactoringProcessor { private static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.encapsulateFields.EncapsulateFieldsProcessor"); private PsiClass myClass; private EncapsulateFieldsDialog myDialog; private PsiField[] myFields; private HashMap<String,PsiMethod> myNameToGetter; private HashMap<String,PsiMethod> myNameToSetter; public EncapsulateFieldsProcessor(Project project, EncapsulateFieldsDialog dialog) { super(project); myDialog = dialog; } protected UsageViewDescriptor createUsageViewDescriptor(UsageInfo[] usages) { PsiField[] fields = new PsiField[myFields.length]; for (int idx = 0; idx < myFields.length; idx++) { fields[idx] = myFields[idx]; } return new EncapsulateFieldsViewDescriptor(fields); } protected String getCommandName() { return RefactoringBundle.message("encapsulate.fields.command.name", UsageViewUtil.getDescriptiveName(myClass)); } public void doRun() { myFields = myDialog.getSelectedFields(); if (myFields.length == 0){ String message = RefactoringBundle.message("encapsulate.fields.no.fields.selected"); CommonRefactoringUtil.showErrorMessage(EncapsulateFieldsHandler.REFACTORING_NAME, message, HelpID.ENCAPSULATE_FIELDS, myProject); return; } myClass = myFields[0].getContainingClass(); super.doRun(); } protected boolean preprocessUsages(Ref<UsageInfo[]> refUsages) { ArrayList<String> conflicts = new ArrayList<String>(); if (myDialog != null) { checkExistingMethods(myDialog.getGetterPrototypes(), conflicts, true); checkExistingMethods(myDialog.getSetterPrototypes(), conflicts, false); if(conflicts.size() > 0) { ConflictsDialog dialog = new ConflictsDialog(myProject, conflicts); dialog.show(); if(!dialog.isOK()) return false; } } prepareSuccessful(); return true; } private void checkExistingMethods(PsiMethod[] prototypes, ArrayList<String> conflicts, boolean isGetter) { if(prototypes == null) return; for (PsiMethod prototype : prototypes) { final PsiType prototypeReturnType = prototype.getReturnType(); PsiMethod existing = myClass.findMethodBySignature(prototype, true); if (existing != null) { final PsiType returnType = existing.getReturnType(); if (!RefactoringUtil.equivalentTypes(prototypeReturnType, returnType, myClass.getManager())) { final String descr = PsiFormatUtil.formatMethod(existing, PsiSubstitutor.EMPTY, PsiFormatUtil.SHOW_NAME | PsiFormatUtil.SHOW_PARAMETERS | PsiFormatUtil.SHOW_TYPE, PsiFormatUtil.SHOW_TYPE ); String message = isGetter ? RefactoringBundle.message("encapsulate.fields.getter.exists", CommonRefactoringUtil.htmlEmphasize(descr), CommonRefactoringUtil.htmlEmphasize(prototype.getName())) : RefactoringBundle.message("encapsulate.fields.setter.exists", CommonRefactoringUtil.htmlEmphasize(descr), CommonRefactoringUtil.htmlEmphasize(prototype.getName())); conflicts.add(message); } } } } @NotNull protected UsageInfo[] findUsages() { boolean findGet = myDialog.isToEncapsulateGet(); boolean findSet = myDialog.isToEncapsulateSet(); PsiModifierList newModifierList = null; if (!myDialog.isToUseAccessorsWhenAccessible()){ PsiElementFactory factory = PsiManager.getInstance(myProject).getElementFactory(); try{ PsiField field = factory.createField("a", PsiType.INT); setNewFieldVisibility(field); newModifierList = field.getModifierList(); } catch(IncorrectOperationException e){ LOG.error(e); } } PsiMethod[] getterPrototypes = myDialog.getGetterPrototypes(); PsiMethod[] setterPrototypes = myDialog.getSetterPrototypes(); ArrayList<UsageInfo> array = new ArrayList<UsageInfo>(); PsiField[] fields = myFields; for(int i = 0; i < fields.length; i++){ PsiField field = fields[i]; PsiSearchHelper helper = field.getManager().getSearchHelper(); PsiReference[] refs = helper.findReferences(field, GlobalSearchScope.projectScope(myProject), true); for (final PsiReference reference : refs) { if (!(reference instanceof PsiReferenceExpression)) continue; PsiReferenceExpression ref = (PsiReferenceExpression)reference; // [Jeka] to avoid recursion in the field's accessors if (findGet && isUsedInExistingAccessor(getterPrototypes[i], ref)) continue; if (findSet && isUsedInExistingAccessor(setterPrototypes[i], ref)) continue; if (!findGet) { if (!PsiUtil.isAccessedForWriting(ref)) continue; } if (!findSet || field.hasModifierProperty(PsiModifier.FINAL)) { if (!PsiUtil.isAccessedForReading(ref)) continue; } if (!myDialog.isToUseAccessorsWhenAccessible()) { PsiClass accessObjectClass = null; PsiExpression qualifier = ref.getQualifierExpression(); if (qualifier != null) { accessObjectClass = (PsiClass)PsiUtil.getAccessObjectClass(qualifier).getElement(); } if (PsiManager.getInstance(myProject).getResolveHelper() .isAccessible(field, newModifierList, ref, accessObjectClass, null)) { continue; } } UsageInfo usageInfo = new MyUsageInfo(ref, i); array.add(usageInfo); } } MyUsageInfo[] usageInfos = array.toArray(new MyUsageInfo[array.size()]); return UsageViewUtil.removeDuplicatedUsages(usageInfos); } protected void refreshElements(PsiElement[] elements) { LOG.assertTrue(elements.length == myFields.length); for (int idx = 0; idx < elements.length; idx++) { PsiElement element = elements[idx]; LOG.assertTrue(element instanceof PsiField); myFields[idx] = (PsiField)element; } myClass = myFields[0].getContainingClass(); } protected void performRefactoring(UsageInfo[] usages) { // change visibility of fields if (myDialog.getFieldsVisibility() != null){ // "as is" for (PsiField field : myFields) { setNewFieldVisibility(field); } } // generate accessors myNameToGetter = new com.intellij.util.containers.HashMap<String, PsiMethod>(); myNameToSetter = new com.intellij.util.containers.HashMap<String, PsiMethod>(); for(int i = 0; i < myFields.length; i++){ PsiField field = myFields[i]; if (myDialog.isToEncapsulateGet()){ PsiMethod[] prototypes = myDialog.getGetterPrototypes(); addOrChangeAccessor(prototypes[i], myNameToGetter); } if (myDialog.isToEncapsulateSet() && !field.hasModifierProperty(PsiModifier.FINAL)){ PsiMethod[] prototypes = myDialog.getSetterPrototypes(); addOrChangeAccessor(prototypes[i], myNameToSetter); } } Map<PsiFile, List<MyUsageInfo>> usagesInFiles = new HashMap<PsiFile, List<MyUsageInfo>>(); for (UsageInfo usage : usages) { PsiElement element = usage.getElement(); if (element == null) continue; final PsiFile file = element.getContainingFile(); List<MyUsageInfo> usagesInFile = usagesInFiles.get(file); if (usagesInFile == null) { usagesInFile = new ArrayList<MyUsageInfo>(); usagesInFiles.put(file, usagesInFile); } usagesInFile.add(((MyUsageInfo)usage)); } for (List<MyUsageInfo> usageInfos : usagesInFiles.values()) { //this is to avoid elements to become invalid as a result of processUsage RefactoringUtil.sortDepthFirstRightLeftOrder(usages); for (MyUsageInfo info : usageInfos) { processUsage(info); } } } private void setNewFieldVisibility(PsiField field) { try{ if (myDialog.getFieldsVisibility() != null){ field.normalizeDeclaration(); field.getModifierList().setModifierProperty(myDialog.getFieldsVisibility(), true); } } catch(IncorrectOperationException e){ LOG.error(e); } } private void addOrChangeAccessor(PsiMethod prototype, HashMap<String,PsiMethod> nameToAncestor) { PsiMethod existing = myClass.findMethodBySignature(prototype, false); PsiMethod result = existing; try{ if (existing == null){ prototype.getModifierList().setModifierProperty(myDialog.getAccessorsVisibility(), true); result = (PsiMethod) myClass.add(prototype); } else{ //TODO : change visibility } nameToAncestor.put(prototype.getName(), result); } catch(IncorrectOperationException e){ LOG.error(e); } } private boolean isUsedInExistingAccessor(PsiMethod prototype, PsiElement element) { PsiMethod existingAccessor = myClass.findMethodBySignature(prototype, false); if (existingAccessor != null) { PsiElement parent = element; while (parent != null) { if (existingAccessor.equals(parent)) return true; parent = parent.getParent(); } } return false; } private void processUsage(MyUsageInfo usage) { PsiField field = myFields[usage.fieldIndex]; boolean processGet = myDialog.isToEncapsulateGet(); boolean processSet = myDialog.isToEncapsulateSet() && !field.hasModifierProperty(PsiModifier.FINAL); if (!processGet && !processSet) return; PsiElementFactory factory = PsiManager.getInstance(myProject).getElementFactory(); try{ final PsiReferenceExpression expr = (PsiReferenceExpression)usage.getElement(); if (expr == null) return; final PsiElement parent = expr.getParent(); if (parent instanceof PsiAssignmentExpression && expr.equals(((PsiAssignmentExpression)parent).getLExpression())){ PsiAssignmentExpression assignment = (PsiAssignmentExpression)parent; if (assignment.getRExpression() == null) return; PsiJavaToken opSign = assignment.getOperationSign(); IElementType opType = opSign.getTokenType(); if (opType == JavaTokenType.EQ) { { if (!processSet) return; final int fieldIndex = usage.fieldIndex; final PsiExpression setterArgument = assignment.getRExpression(); PsiMethodCallExpression methodCall = createSetterCall(fieldIndex, setterArgument, expr); if (methodCall != null) { assignment.replace(methodCall); } //TODO: check if value is used!!! } } else if (opType == JavaTokenType.ASTERISKEQ || opType == JavaTokenType.DIVEQ || opType == JavaTokenType.PERCEQ || opType == JavaTokenType.PLUSEQ || opType == JavaTokenType.MINUSEQ || opType == JavaTokenType.LTLTEQ || opType == JavaTokenType.GTGTEQ || opType == JavaTokenType.GTGTGTEQ || opType == JavaTokenType.ANDEQ || opType == JavaTokenType.OREQ || opType == JavaTokenType.XOREQ) { { // Q: side effects of qualifier??! String opName = opSign.getText(); LOG.assertTrue(StringUtil.endsWithChar(opName, '=')); opName = opName.substring(0, opName.length() - 1); PsiExpression getExpr = expr; if (processGet) { final int fieldIndex = usage.fieldIndex; final PsiMethodCallExpression getterCall = createGetterCall(fieldIndex, expr); if (getterCall != null) { getExpr = getterCall; } } @NonNls String text = "a" + opName + "b"; PsiBinaryExpression binExpr = (PsiBinaryExpression)factory.createExpressionFromText(text, expr); binExpr = (PsiBinaryExpression)CodeStyleManager.getInstance(myProject).reformat(binExpr); binExpr.getLOperand().replace(getExpr); binExpr.getROperand().replace(assignment.getRExpression()); PsiExpression setExpr; if (processSet) { setExpr = createSetterCall(usage.fieldIndex, binExpr, expr); } else { text = "a = b"; PsiAssignmentExpression assignment1 = (PsiAssignmentExpression)factory.createExpressionFromText(text, null); assignment1 = (PsiAssignmentExpression)CodeStyleManager.getInstance(myProject).reformat(assignment1); assignment1.getLExpression().replace(expr); assignment1.getRExpression().replace(binExpr); setExpr = assignment1; } assignment.replace(setExpr); //TODO: check if value is used!!! } } } else if (isPlusPlusOrMinusMinus(parent)){ PsiJavaToken sign; if (parent instanceof PsiPrefixExpression){ sign = ((PsiPrefixExpression)parent).getOperationSign(); } else{ sign = ((PsiPostfixExpression)parent).getOperationSign(); } IElementType tokenType = sign.getTokenType(); PsiExpression getExpr = expr; if (processGet){ final int fieldIndex = usage.fieldIndex; final PsiMethodCallExpression getterCall = createGetterCall(fieldIndex, expr); if(getterCall != null) { getExpr = getterCall; } } @NonNls String text; if (tokenType == JavaTokenType.PLUSPLUS){ text = "a+1"; } else{ text = "a-1"; } PsiBinaryExpression binExpr = (PsiBinaryExpression)factory.createExpressionFromText(text, null); binExpr = (PsiBinaryExpression)CodeStyleManager.getInstance(myProject).reformat(binExpr); binExpr.getLOperand().replace(getExpr); PsiExpression setExpr; if (processSet){ final int fieldIndex = usage.fieldIndex; setExpr = createSetterCall(fieldIndex, binExpr, expr); } else{ text = "a = b"; PsiAssignmentExpression assignment = (PsiAssignmentExpression)factory.createExpressionFromText(text, null); assignment = (PsiAssignmentExpression)CodeStyleManager.getInstance(myProject).reformat(assignment); assignment.getLExpression().replace(expr); assignment.getRExpression().replace(binExpr); setExpr = assignment; } parent.replace(setExpr); } else{ if (!processGet) return; PsiMethodCallExpression methodCall = createGetterCall(usage.fieldIndex, expr); if (methodCall != null) { expr.replace(methodCall); } } } catch(IncorrectOperationException e){ LOG.error(e); } } private PsiMethodCallExpression createSetterCall(final int fieldIndex, final PsiExpression setterArgument, PsiReferenceExpression expr) throws IncorrectOperationException { String[] setterNames = myDialog.getSetterNames(); PsiElementFactory factory = expr.getManager().getElementFactory(); final String setterName = setterNames[fieldIndex]; @NonNls String text = setterName + "(a)"; PsiExpression qualifier = expr.getQualifierExpression(); if (qualifier != null){ text = "q." + text; } PsiMethodCallExpression methodCall = (PsiMethodCallExpression)factory.createExpressionFromText(text, expr); methodCall = (PsiMethodCallExpression)CodeStyleManager.getInstance(myProject).reformat(methodCall); methodCall.getArgumentList().getExpressions()[0].replace(setterArgument); if (qualifier != null){ methodCall.getMethodExpression().getQualifierExpression().replace(qualifier); } final PsiMethod targetMethod = myNameToSetter.get(setterName); methodCall = checkMethodResolvable(methodCall, targetMethod, expr); if (methodCall == null) { VisibilityUtil.escalateVisibility(myFields[fieldIndex], expr); } return methodCall; } private PsiMethodCallExpression createGetterCall(final int fieldIndex, PsiReferenceExpression expr) throws IncorrectOperationException { String[] getterNames = myDialog.getGetterNames(); PsiElementFactory factory = expr.getManager().getElementFactory(); final String getterName = getterNames[fieldIndex]; @NonNls String text = getterName + "()"; PsiExpression qualifier = expr.getQualifierExpression(); if (qualifier != null){ text = "q." + text; } PsiMethodCallExpression methodCall = (PsiMethodCallExpression)factory.createExpressionFromText(text, expr); methodCall = (PsiMethodCallExpression)CodeStyleManager.getInstance(myProject).reformat(methodCall); if (qualifier != null){ methodCall.getMethodExpression().getQualifierExpression().replace(qualifier); } final PsiMethod targetMethod = myNameToGetter.get(getterName); methodCall = checkMethodResolvable(methodCall, targetMethod, expr); if(methodCall == null) { VisibilityUtil.escalateVisibility(myFields[fieldIndex], expr); } return methodCall; } private PsiMethodCallExpression checkMethodResolvable(PsiMethodCallExpression methodCall, final PsiMethod targetMethod, PsiReferenceExpression context) throws IncorrectOperationException { PsiElementFactory factory = targetMethod.getManager().getElementFactory(); final PsiElement resolved = methodCall.getMethodExpression().resolve(); if (resolved != targetMethod) { PsiClass containingClass; if (resolved instanceof PsiMethod) { containingClass = ((PsiMethod) resolved).getContainingClass(); } else { LOG.assertTrue(resolved instanceof PsiClass); containingClass = (PsiClass)resolved; } if(containingClass.isInheritor(myClass, false)) { final PsiExpression newMethodExpression = factory.createExpressionFromText("super." + targetMethod.getName(), context); methodCall.getMethodExpression().replace(newMethodExpression); } else { methodCall = null; } } return methodCall; } private boolean isPlusPlusOrMinusMinus(PsiElement expression) { if (expression instanceof PsiPrefixExpression){ PsiPrefixExpression prefixExpression = (PsiPrefixExpression)expression; PsiJavaToken sign = prefixExpression.getOperationSign(); IElementType tokenType = sign.getTokenType(); return tokenType == JavaTokenType.PLUSPLUS || tokenType == JavaTokenType.MINUSMINUS; } if (expression instanceof PsiPostfixExpression){ PsiPostfixExpression postfixExpression = (PsiPostfixExpression)expression; PsiJavaToken sign = postfixExpression.getOperationSign(); IElementType tokenType = sign.getTokenType(); return tokenType == JavaTokenType.PLUSPLUS || tokenType == JavaTokenType.MINUSMINUS; } return false; } private static class MyUsageInfo extends UsageInfo { public final int fieldIndex; public MyUsageInfo(PsiJavaCodeReferenceElement ref, int fieldIndex) { super(ref); this.fieldIndex = fieldIndex; } } }
package com.evolveum.midpoint.repo.xml; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.Transformer; import org.apache.commons.lang.StringUtils; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xmldb.api.base.Collection; import org.xmldb.api.base.Resource; import org.xmldb.api.base.ResourceIterator; import org.xmldb.api.base.ResourceSet; import org.xmldb.api.base.XMLDBException; import org.xmldb.api.modules.XPathQueryService; import com.evolveum.midpoint.api.logging.Trace; import com.evolveum.midpoint.common.jaxb.JAXBUtil; import com.evolveum.midpoint.common.patch.PatchXml; import com.evolveum.midpoint.common.result.OperationResult; import com.evolveum.midpoint.logging.TraceManager; import com.evolveum.midpoint.repo.api.RepositoryService; import com.evolveum.midpoint.schema.ObjectTypes; import com.evolveum.midpoint.schema.exception.ObjectAlreadyExistsException; import com.evolveum.midpoint.schema.exception.ObjectNotFoundException; import com.evolveum.midpoint.schema.exception.SchemaException; import com.evolveum.midpoint.schema.exception.SystemException; import com.evolveum.midpoint.util.DOMUtil; import com.evolveum.midpoint.util.patch.PatchException; import com.evolveum.midpoint.xml.ns._public.common.common_1.ObjectContainerType; import com.evolveum.midpoint.xml.ns._public.common.common_1.ObjectListType; import com.evolveum.midpoint.xml.ns._public.common.common_1.ObjectModificationType; import com.evolveum.midpoint.xml.ns._public.common.common_1.ObjectType; import com.evolveum.midpoint.xml.ns._public.common.common_1.PagingType; import com.evolveum.midpoint.xml.ns._public.common.common_1.PropertyAvailableValuesListType; import com.evolveum.midpoint.xml.ns._public.common.common_1.PropertyReferenceListType; import com.evolveum.midpoint.xml.ns._public.common.common_1.QueryType; import com.evolveum.midpoint.xml.ns._public.common.common_1.ResourceObjectShadowType; import com.evolveum.midpoint.xml.ns._public.common.common_1.UserType; import com.evolveum.midpoint.xml.schema.SchemaConstants; import com.evolveum.midpoint.xml.schema.XPathType; public class XmlRepositoryService implements RepositoryService { private static final Trace TRACE = TraceManager.getTrace(XmlRepositoryService.class); private Collection collection; XmlRepositoryService(Collection collection) { super(); this.collection = collection; } @Override public String addObject(ObjectType object, OperationResult parentResult) throws ObjectAlreadyExistsException, SchemaException { String oid = null; try { checkAndFailIfObjectAlreadyExists(object.getOid()); // generate new oid, if necessary oid = (null != object.getOid() ? object.getOid() : UUID.randomUUID().toString()); object.setOid(oid); Map<String, Object> properties = new HashMap<String, Object>(); properties.put(Marshaller.JAXB_FRAGMENT, Boolean.TRUE); String serializedObject = JAXBUtil.marshalWrap(properties, object, SchemaConstants.C_OBJECT); // FIXME: try to find another solution how to escape XQuery special // characters in XMLs serializedObject = StringUtils.replace(serializedObject, "{", "{{"); serializedObject = StringUtils.replace(serializedObject, "}", "}}"); // Receive the XPath query service. XPathQueryService service = (XPathQueryService) collection.getService("XPathQueryService", "1.0"); StringBuilder query = new StringBuilder( "declare namespace c='http://midpoint.evolveum.com/xml/ns/public/common/common-1.xsd';\n") .append("let $x := ").append(serializedObject).append("\n") .append("return insert node $x into //c:objects"); TRACE.trace("generated query: " + query); service.query(query.toString()); return oid; } catch (JAXBException ex) { TRACE.error("Failed to (un)marshal object", ex); throw new IllegalArgumentException("Failed to (un)marshal object", ex); } catch (XMLDBException ex) { TRACE.error("Reported error by XML Database", ex); throw new SystemException("Reported error by XML Database", ex); } } @Override public ObjectType getObject(String oid, PropertyReferenceListType resolve, OperationResult parentResult) throws ObjectNotFoundException, SchemaException { validateOid(oid); ByteArrayInputStream in = null; ObjectType object = null; try { XPathQueryService service = (XPathQueryService) collection.getService("XPathQueryService", "1.0"); StringBuilder query = new StringBuilder( "declare namespace c='http://midpoint.evolveum.com/xml/ns/public/common/common-1.xsd';\n"); query.append("for $x in //c:object where $x/@oid=\"").append(oid).append("\" return $x"); TRACE.trace("generated query: " + query); ResourceSet set = service.query(query.toString()); ResourceIterator iter = set.getIterator(); // Loop through all result items. while (iter.hasMoreResources()) { Resource res = iter.nextResource(); if (null != object) { TRACE.error("More than one object with oid {} found", oid); throw new SystemException("More than one object with oid " + oid + " found"); } Object c = res.getContent(); if (c instanceof String) { in = new ByteArrayInputStream(((String) c).getBytes("UTF-8")); JAXBElement<ObjectType> o = (JAXBElement<ObjectType>) JAXBUtil.unmarshal(in); if (o != null) { object = o.getValue(); } } } } catch (UnsupportedEncodingException ex) { TRACE.error("UTF-8 is unsupported encoding", ex); throw new SystemException("UTF-8 is unsupported encoding", ex); } catch (JAXBException ex) { TRACE.error("Failed to (un)marshal object", ex); throw new IllegalArgumentException("Failed to (un)marshal object", ex); } catch (XMLDBException ex) { TRACE.error("Reported error by XML Database", ex); throw new SystemException("Reported error by XML Database", ex); } finally { try { if (null != in) { in.close(); } } catch (IOException ex) { } } if (object == null) { throw new ObjectNotFoundException("Object not found. OID: " + oid); } return object; } @Override public ObjectListType listObjects(Class objectType, PagingType paging, OperationResult parentResult) { if (null == objectType) { TRACE.error("objectType is null"); throw new IllegalArgumentException("objectType is null"); } //validation if object type is supported ObjectTypes objType = ObjectTypes.getObjectType(objectType); String oType = objType.getValue(); return searchObjects(oType, paging, null); } @Override public ObjectListType searchObjects(QueryType query, PagingType paging, OperationResult parentResult) throws SchemaException { validateQuery(query); NodeList children = query.getFilter().getChildNodes(); String objectType = null; Map<String, String> filters = new HashMap<String, String>(); for (int index = 0; index < children.getLength(); index++) { Node child = children.item(index); if (child.getNodeType() != Node.ELEMENT_NODE) { // Skipping all non-element nodes continue; } if (!StringUtils.equals(SchemaConstants.NS_C, child.getNamespaceURI())) { TRACE.warn("Found query's filter element from unsupported namespace. Ignoring filter {}", child); continue; } if (validateFilterElement(SchemaConstants.NS_C, "type", child)) { objectType = child.getAttributes().getNamedItem("uri").getTextContent(); } else if (validateFilterElement(SchemaConstants.NS_C, "equal", child)) { Node criteria = DOMUtil.getFirstChildElement(child); if (validateFilterElement(SchemaConstants.NS_C, "path", criteria)) { XPathType xpathType = new XPathType((Element) criteria); String parentPath = xpathType.getXPath(); Node criteriaValueNode = DOMUtil.getNextSiblingElement(criteria); processValueNode(criteriaValueNode, filters, parentPath); } if (validateFilterElement(SchemaConstants.NS_C, "value", criteria)) { processValueNode(criteria, filters, null); } } } return searchObjects(objectType, paging, filters); } @Override public void modifyObject(ObjectModificationType objectChange, OperationResult parentResult) throws ObjectNotFoundException, SchemaException { validateObjectChange(objectChange); try { // get object from repo // FIXME: possible problems with resolving property reference before // xml patching ObjectType objectType = this.getObject(objectChange.getOid(), new PropertyReferenceListType(), null); // modify the object PatchXml xmlPatchTool = new PatchXml(); String serializedObject = xmlPatchTool.applyDifferences(objectChange, objectType); // HACK: serializedObject = serializedObject.substring(38); // store modified object in repo // Receive the XPath query service. XPathQueryService service = (XPathQueryService) collection.getService("XPathQueryService", "1.0"); StringBuilder query = new StringBuilder( "declare namespace c='http://midpoint.evolveum.com/xml/ns/public/common/common-1.xsd';\n") .append("replace node //c:object[@oid=\"").append(objectChange.getOid()) .append("\"] with ").append(serializedObject); TRACE.trace("generated query: " + query); service.query(query.toString()); } catch (PatchException ex) { TRACE.error("Failed to modify object", ex); throw new SystemException("Failed to modify object", ex); } catch (XMLDBException ex) { TRACE.error("Reported error by XML Database", ex); throw new SystemException("Reported error by XML Database", ex); } } @Override public void deleteObject(String oid, OperationResult parentResult) throws ObjectNotFoundException { validateOid(oid); try { ObjectType retrievedObject = getObject(oid, null, null); } catch (SchemaException ex) { TRACE.error("Schema validation problem occured while checking existence of the object before its deletion", ex); throw new SystemException("Schema validation problem occured while checking existence of the object before its deletion", ex); } ByteArrayInputStream in = null; ObjectContainerType out = null; try { // Receive the XPath query service. XPathQueryService service = (XPathQueryService) collection.getService("XPathQueryService", "1.0"); StringBuilder QUERY = new StringBuilder( "declare namespace c='http://midpoint.evolveum.com/xml/ns/public/common/common-1.xsd';\n"); QUERY.append("delete nodes //c:object[@oid=\"").append(oid).append("\"]"); service.query(QUERY.toString()); } catch (XMLDBException ex) { TRACE.error("Reported error by XML Database", ex); throw new SystemException("Reported error by XML Database"); } finally { try { if (null != in) { in.close(); } } catch (IOException ex) { } } } @Override public PropertyAvailableValuesListType getPropertyAvailableValues(String oid, PropertyReferenceListType properties, OperationResult parentResult) throws ObjectNotFoundException { throw new UnsupportedOperationException("Not implemented yet."); } @Override public UserType listAccountShadowOwner(String accountOid, OperationResult parentResult) throws ObjectNotFoundException { Map<String, String> filters = new HashMap<String, String>(); // FIXME: hardcoded prefix c: filters.put("c:accountRef", accountOid); ObjectListType retrievedObjects = searchObjects(ObjectTypes.USER.getObjectTypeUri(), null, filters); List<ObjectType> objects = retrievedObjects.getObject(); if (null == retrievedObjects || objects == null || objects.size() == 0) { return null; } if (objects.size() > 1) { throw new SystemException("Found incorrect number of objects " + objects.size()); } UserType userType = (UserType) objects.get(0); return userType; } @Override public List<ResourceObjectShadowType> listResourceObjectShadows(String resourceOid, Class resourceObjectShadowType, OperationResult parentResult) throws ObjectNotFoundException { Map<String, String> filters = new HashMap<String, String>(); // FIXME: hardcoded prefix c: filters.put("c:resourceRef", resourceOid); ObjectListType retrievedObjects = searchObjects(ObjectTypes.ACCOUNT.getObjectTypeUri(), null, filters); @SuppressWarnings("unchecked") List<ResourceObjectShadowType> objects = (List<ResourceObjectShadowType>) CollectionUtils.collect( retrievedObjects.getObject(), new Transformer() { @Override public Object transform(final Object input) { return (ResourceObjectShadowType) input; } }); List<ResourceObjectShadowType> ros = new ArrayList<ResourceObjectShadowType>(); ros.addAll(objects); return ros; } private void checkAndFailIfObjectAlreadyExists(String oid) throws ObjectAlreadyExistsException, SchemaException { // check if object with the same oid already exists, if yes, then fail if (StringUtils.isNotEmpty(oid)) { try { ObjectType retrievedObject = getObject(oid, null, null); if (null != retrievedObject) { throw new ObjectAlreadyExistsException("Object with oid " + oid + " already exists"); } } catch (ObjectNotFoundException e) { //ignore } } } private ObjectListType searchObjects(String objectType, PagingType paging, Map<String, String> filters) { ByteArrayInputStream in = null; ObjectListType objectList = new ObjectListType(); // FIXME: objectList.count has to contain all elements that match search // criteria, but not only from paging interval objectList.setCount(0); try { XPathQueryService service = (XPathQueryService) collection.getService("XPathQueryService", "1.0"); StringBuilder query = new StringBuilder( "declare namespace c='http://midpoint.evolveum.com/xml/ns/public/common/common-1.xsd';\n"); // TODO: namespace declaration has to be generated dynamically query.append("declare namespace idmdn='http://midpoint.evolveum.com/xml/ns/public/common/common-1.xsd';\n"); query.append("declare namespace i='http://midpoint.evolveum.com/xml/ns/public/common/common-1.xsd';\n"); query.append("declare namespace dj='http://midpoint.evolveum.com/xml/ns/samples/localhostOpenDJ';\n"); query.append("declare namespace xsi='http: query.append("declare namespace s='http://midpoint.evolveum.com/xml/ns/public/resource/idconnector/resource-schema-1.xsd';\n"); // FIXME: possible problems with object type checking. Now it is // simple string checking, because import schema is not supported query.append("for $x in //c:object where $x/@xsi:type=\"") .append(objectType.substring(objectType.lastIndexOf("#") + 1)).append("\""); if (null != paging && null != paging.getOffset() && null != paging.getMaxSize()) { query.append("[fn:position() = ( ").append(paging.getOffset() * paging.getMaxSize()) .append(" to ").append(((paging.getOffset() + 1) * paging.getMaxSize()) - 1) .append(") ] "); } if (filters != null) { for (Map.Entry<String, String> filterEntry : filters.entrySet()) { // FIXME: now only refs are searched by attributes values if (StringUtils.contains(filterEntry.getKey(), "Ref")) { // search based on attribute value query.append(" and $x/").append(filterEntry.getKey()).append("/@oid='") .append(filterEntry.getValue()).append("'"); } else { // search based on element value query.append(" and $x/").append(filterEntry.getKey()).append("='") .append(filterEntry.getValue()).append("'"); } } } if (null != paging && null != paging.getOrderBy()) { XPathType xpath = new XPathType(paging.getOrderBy().getProperty()); String orderBy = xpath.getXPath(); query.append(" order by $x/").append(orderBy); if (null != paging.getOrderDirection()) { query.append(" "); query.append(StringUtils.lowerCase(paging.getOrderDirection().toString())); } } query.append(" return $x "); TRACE.trace("generated query: " + query); ResourceSet set = service.query(query.toString()); ResourceIterator iter = set.getIterator(); while (iter.hasMoreResources()) { Resource res = iter.nextResource(); Object c = res.getContent(); if (c instanceof String) { in = new ByteArrayInputStream(((String) c).getBytes("UTF-8")); JAXBElement<ObjectType> o = (JAXBElement<ObjectType>) JAXBUtil.unmarshal(in); if (o != null) { objectList.getObject().add(o.getValue()); } } } } catch (UnsupportedEncodingException ex) { TRACE.error("UTF-8 is unsupported encoding", ex); throw new SystemException("UTF-8 is unsupported encoding", ex); } catch (JAXBException ex) { TRACE.error("Failed to (un)marshal object", ex); throw new IllegalArgumentException("Failed to (un)marshal object", ex); } catch (XMLDBException ex) { TRACE.error("Reported error by XML Database", ex); throw new SystemException("Reported error by XML Database", ex); } finally { try { if (null != in) { in.close(); } } catch (IOException ex) { } } return objectList; } private void processValueNode(Node criteriaValueNode, Map<String, String> filters, String parentPath) { if (null == criteriaValueNode) { throw new IllegalArgumentException("Query filter does not contain any values to search by"); } if (validateFilterElement(SchemaConstants.NS_C, "value", criteriaValueNode)) { Node firstChild = DOMUtil.getFirstChildElement(criteriaValueNode); if (null == firstChild) { throw new IllegalArgumentException("Query filter contains empty list of values to search by"); } // FIXME: possible problem with prefixes String lastPathSegment; if (!StringUtils.isEmpty(firstChild.getPrefix())) { lastPathSegment = firstChild.getPrefix() + ":" + firstChild.getLocalName(); } else { lastPathSegment = "c:" + firstChild.getLocalName(); } // some search filters does not contain element's text value, for // these filters the value is stored in attribute String criteriaValue = StringUtils.trim(firstChild.getTextContent()); if (StringUtils.isEmpty(criteriaValue)) { // FIXME: for now it is ok to get value of the first attribute if (firstChild.getAttributes().getLength() == 1) { criteriaValue = StringUtils.trim(firstChild.getAttributes().item(0).getNodeValue()); } else { throw new IllegalArgumentException("Incorrect number of attributes in query filter " + firstChild + ", expected was 1, but actual size was " + criteriaValueNode.getAttributes().getLength()); } } if (StringUtils.isEmpty(criteriaValue)) { throw new IllegalArgumentException("Could not extract filter value from search query filter " + criteriaValueNode); } if (parentPath != null) { filters.put(parentPath + "/" + lastPathSegment, criteriaValue); } else { filters.put(lastPathSegment, criteriaValue); } } else { throw new IllegalArgumentException("Found unexpected element in query filter " + criteriaValueNode); } } private boolean validateFilterElement(String elementNamespace, String elementName, Node criteria) { if (StringUtils.equals(elementName, criteria.getLocalName()) && StringUtils.equalsIgnoreCase(elementNamespace, criteria.getNamespaceURI())) { return true; } return false; } private void validateOid(String oid) { if (StringUtils.isEmpty(oid)) { throw new IllegalArgumentException("Invalid OID"); } try { UUID.fromString(oid); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Invalid OID format " + oid); } } private void validateObjectChange(ObjectModificationType objectChange) { if (null == objectChange) { throw new IllegalArgumentException("Provided null object modifications"); } validateOid(objectChange.getOid()); if (null == objectChange.getPropertyModification() || objectChange.getPropertyModification().size() == 0) { throw new IllegalArgumentException("No property modifications provided"); } } private void validateQuery(QueryType query) { if (null == query) { throw new IllegalArgumentException("Provided null query"); } if (null == query.getFilter()) { throw new IllegalArgumentException("No filter in query"); } } }
package org.fusesource.restygwt.client; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import org.fusesource.restygwt.client.Json.Style; import com.google.gwt.json.client.JSONNull; import com.google.gwt.json.client.JSONValue; public abstract class AbstractNestedJsonEncoderDecoder<E, F, G> extends AbstractJsonEncoderDecoder<E> { protected AbstractJsonEncoderDecoder<F> nested; protected AbstractJsonEncoderDecoder<G> second; protected Style style; AbstractNestedJsonEncoderDecoder( AbstractJsonEncoderDecoder<F> encoder ){ this.nested = encoder; } AbstractNestedJsonEncoderDecoder( AbstractJsonEncoderDecoder<F> encoder, Style style ){ this.nested = encoder; this.style = style; } AbstractNestedJsonEncoderDecoder( AbstractJsonEncoderDecoder<F> keyEncoder, AbstractJsonEncoderDecoder<G> valueEncoder, Style style ){ this.nested = keyEncoder; this.second = valueEncoder; this.style = style; } static public <T> AbstractJsonEncoderDecoder<T[]> arrayEncoderDecoder(AbstractJsonEncoderDecoder<T> encoder){ return new AbstractNestedJsonEncoderDecoder<T[], T, Void>( encoder ) { @Override public JSONValue encode(T[] value) throws EncodingException { return value != null ? toJSON(value, nested) : JSONNull.getInstance(); } @SuppressWarnings("unchecked") @Override public T[] decode(JSONValue value) throws DecodingException { return toArray(value, nested, (T[]) new Object[ asArray( value ).size() ]); } }; } static public <T> AbstractJsonEncoderDecoder<Collection<T>> collectionEncoderDecoder(AbstractJsonEncoderDecoder<T> encoder){ return new AbstractNestedJsonEncoderDecoder<Collection<T>, T, Void>( encoder ) { @SuppressWarnings("unchecked") @Override public JSONValue encode(Collection<T> value) throws EncodingException { return value != null ? toJSON((T[])value.toArray(), nested) : JSONNull.getInstance(); } @Override public Collection<T> decode(JSONValue value) throws DecodingException { return toList(value, nested); } }; } static public <T> AbstractJsonEncoderDecoder<List<T>> listEncoderDecoder(AbstractJsonEncoderDecoder<T> encoder){ return new AbstractNestedJsonEncoderDecoder<List<T>, T, Void>( encoder ) { @SuppressWarnings("unchecked") @Override public JSONValue encode(List<T> value) throws EncodingException { return value != null ? toJSON((T[])value.toArray(), nested) : JSONNull.getInstance(); } @Override public List<T> decode(JSONValue value) throws DecodingException { return toList(value, nested); } }; } static public <T> AbstractJsonEncoderDecoder<Set<T>> setEncoderDecoder(AbstractJsonEncoderDecoder<T> encoder){ return new AbstractNestedJsonEncoderDecoder<Set<T>, T, Void>( encoder ) { @Override public JSONValue encode(Set<T> value) throws EncodingException { return value != null ? toJSON(value, nested) : JSONNull.getInstance(); } @Override public Set<T> decode(JSONValue value) throws DecodingException { return toSet(value, nested); } }; } static public <T> AbstractJsonEncoderDecoder<Map<String, T>> mapEncoderDecoder(AbstractJsonEncoderDecoder<T> encoder, Style style){ return new AbstractNestedJsonEncoderDecoder<Map<String, T>, T, Void>( encoder, style ) { @Override public JSONValue encode(Map<String, T> value) throws EncodingException { return value != null ? toJSON(value, nested, style) : JSONNull.getInstance(); } @Override public Map<String, T> decode(JSONValue value) throws DecodingException { return toMap(value, nested, style ); } }; } static public <T, S> AbstractJsonEncoderDecoder<Map<T, S>> mapEncoderDecoder(AbstractJsonEncoderDecoder<T> keyEncoder, AbstractJsonEncoderDecoder<S> valueEncoder, Style style){ return new AbstractNestedJsonEncoderDecoder<Map<T, S>, T, S>( keyEncoder, valueEncoder, style ) { @Override public JSONValue encode(Map<T, S> value) throws EncodingException { return value != null ? toJSON(value, nested, second, style) : JSONNull.getInstance(); } @Override public Map<T, S> decode(JSONValue value) throws DecodingException { return toMap(value, nested, second, style ); } }; } }
package hudson.scm; import hudson.MarkupText; import hudson.Util; import hudson.model.AbstractBuild; import hudson.model.User; import org.kohsuke.stapler.export.Exported; import org.kohsuke.stapler.export.ExportedBean; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.List; /** * Represents SCM change list. * * <p> * Use the "index" view of this object to render the changeset detail page, * and use the "digest" view of this object to render the summary page. * For the change list at project level, see {@link SCM}. * * <p> * {@link Iterator} is expected to return recent changes first. * * @author Kohsuke Kawaguchi */ @ExportedBean(defaultVisibility=999) public abstract class ChangeLogSet<T extends ChangeLogSet.Entry> implements Iterable<T> { /** * {@link AbstractBuild} whose change log this object represents. */ public final AbstractBuild<?,?> build; protected ChangeLogSet(AbstractBuild<?, ?> build) { this.build = build; } /** * Returns true if there's no change. */ public abstract boolean isEmptySet(); /** * All changes in this change set. */ // method for the remote API. @Exported public final Object[] getItems() { List<T> r = new ArrayList<T>(); for (T t : this) r.add(t); return r.toArray(); } /** * Optional identification of the kind of SCM being used. * @return a short token, such as the SCM's main CLI executable name * @since 1.284 */ @Exported public String getKind() { return null; } /** * Constant instance that represents no changes. */ public static ChangeLogSet<? extends ChangeLogSet.Entry> createEmpty(AbstractBuild build) { return new EmptyChangeLogSet(build); } @ExportedBean(defaultVisibility=999) public static abstract class Entry { private ChangeLogSet parent; public ChangeLogSet getParent() { return parent; } /** * Should be invoked before a {@link ChangeLogSet} is exposed to public. */ protected void setParent(ChangeLogSet parent) { this.parent = parent; } /** * Returns a human readable display name of the commit number, revision number, and such thing * that identifies this entry. * * <p> * This method is primarily intended for visualization of the data. * * @return * null if such a concept doesn't make sense for the implementation. For example, * in CVS there's no single identifier for commits. Each file gets a different revision number. * @since 1.405 */ public String getCommitId() { return null; } /** * Returns the timestamp of this commit in the {@link Date#getTime()} format. * * <p> * This method is primarily intended for visualization of the data. * * @return * -1 if the implementation doesn't support it (for example, in CVS a commit * spreads over time between multiple changes on multiple files, so there's no single timestamp.) * @since 1.405 */ public long getTimestamp() { return -1; } /** * Gets the "commit message". * * <p> * The exact definition depends on the individual SCM implementation. * * @return * Can be empty but never null. */ public abstract String getMsg(); /** * The user who made this change. * * @return * never null. */ public abstract User getAuthor(); /** * Returns a set of paths in the workspace that was * affected by this change. * * <p> * Contains string like 'foo/bar/zot'. No leading/trailing '/', * and separator must be normalized to '/'. * * @return never null. */ public abstract Collection<String> getAffectedPaths(); /** * Returns a set of paths in the workspace that was * affected by this change. * <p> * Noted: since this is a new interface, some of the SCMs may not have * implemented this interface. The default implementation for this * interface is throw UnsupportedOperationException * <p> * It doesn't throw NoSuchMethodException because I rather to throw a * runtime exception * * @return AffectedFile never null. * @since 1.309 */ public Collection<? extends AffectedFile> getAffectedFiles() { String scm = "this SCM"; ChangeLogSet parent = getParent(); if ( null != parent ) { String kind = parent.getKind(); if ( null != kind && kind.trim().length() > 0 ) scm = kind; } throw new UnsupportedOperationException("getAffectedFiles() is not implemented by " + scm); } /** * Gets the text fully marked up by {@link ChangeLogAnnotator}. */ public String getMsgAnnotated() { MarkupText markup = new MarkupText(getMsg()); for (ChangeLogAnnotator a : ChangeLogAnnotator.all()) a.annotate(parent.build,this,markup); return markup.toString(false); } /** * Message escaped for HTML */ public String getMsgEscaped() { return Util.escape(getMsg()); } } /** * Represents a file change. Contains filename, edit type, etc. * * I checked the API names against some some major SCMs and most SCMs * can adapt to this interface with very little changes * * @see ChangeLogSet.Entry#getAffectedFiles() */ public interface AffectedFile { /** * The path in the workspace that was affected * <p> * Contains string like 'foo/bar/zot'. No leading/trailing '/', * and separator must be normalized to '/'. * * @return never null. */ String getPath(); /** * Return whether the file is new/modified/deleted */ EditType getEditType(); } }
package uk.ac.york.minesweeper; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.Point; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.util.ArrayList; import javax.swing.JComponent; import javax.swing.SwingUtilities; /** * A component which can display a minefield graphically and handle various events */ public class MinefieldPanel extends JComponent { private static final long serialVersionUID = 1L; /** Size of all the tiles */ private static final int TILE_SIZE = 32; /** Width of the bevel */ private static final int BEVEL_WIDTH = 2; /** Font vertical offset (from top to BASELINE) */ private static final int FONT_VOFFSET = 24; /** The font to draw numbers with */ private static final Font FONT = new Font(Font.MONOSPACED, Font.BOLD, 24); /** Default background colour */ private static final Color COLOUR_BACKGROUND = new Color(0xC0, 0xC0, 0xC0); /** Light grey for bevels */ private static final Color COLOUR_LIGHT = new Color(0xE0, 0xE0, 0xE0); /** Dark grey for bevels */ private static final Color COLOUR_DARK = new Color(0x80, 0x80, 0x80); /** Colour of question marks */ private static final Color COLOUR_QUESTION = Color.WHITE; /** The colours of the numbers (0 is unused) */ private static final Color[] COLOUR_NUMBERS = new Color[] { null, // 0 = Unused new Color(0x00, 0x00, 0xFF), // 1 = Blue new Color(0x00, 0x7F, 0x00), // 2 = Green new Color(0xFF, 0x00, 0x00), // 3 = Red new Color(0x2F, 0x2F, 0x9F), // 4 = Dark Blue new Color(0xFF, 0x00, 0x00), // 5 = Maroon new Color(0x9F, 0x9F, 0x2F), // 6 = Turquoise new Color(0x00, 0x00, 0x00), // 7 = Black new Color(0x7F, 0x7F, 0x7F), // 8 = Grey }; /** Current minefield */ private Minefield minefield; /** Currently selected tile (null most of the time) */ private Point selectedTile; /** List of state change listeners */ private ArrayList<MinefieldStateChangeListener> listeners = new ArrayList<MinefieldStateChangeListener>(); /** * Initializes a new MinefieldPanel with the given Minefield * * There must always be a minefield to display (you cannot pass null) * * @param minefield minefield to display */ public MinefieldPanel(Minefield minefield) { this.addMouseListener(new MouseEventListener()); this.setBackground(COLOUR_BACKGROUND); this.setOpaque(true); this.setFont(FONT); this.setMinefield(minefield); } /** * Adds a listener to which received game state change events * * @param listener listener to add */ public void addStateChangeListener(MinefieldStateChangeListener listener) { if (!listeners.contains(listener)) listeners.add(listener); } /** * Removes a listener which received game state change events * * @param listener listener to remove */ public void removeStateChangeListener(MinefieldStateChangeListener listener) { listeners.remove(listener); } /** * Fires the state changed event */ private void fireStateChangeEvent() { MinefieldStateChangeEvent event = new MinefieldStateChangeEvent(this); for (MinefieldStateChangeListener listener : listeners) listener.stateChanged(event); } /** * Gets the current minefield * * @return current minefield */ public Minefield getMinefield() { return minefield; } /** * Sets a new minefield for the component * * @param newMinefield the new minefield */ public void setMinefield(Minefield newMinefield) { if (newMinefield == null) throw new IllegalArgumentException("newMinefield cannot be null"); this.minefield = newMinefield; // Reset selected tile this.selectedTile = null; // Update all visuals this.setSize(getPreferredSize()); this.repaint(); // Fire event this.fireStateChangeEvent(); } /** * Draws a character on a tile * * @param g graphics object * @param x x position of top-left of tile * @param y y position of top-left of tile * @param c character to draw */ private static void drawCharacter(Graphics g, int x, int y, char c) { // Get coordinates to draw at int drawX = x + (TILE_SIZE - g.getFontMetrics().charWidth(c)) / 2; int drawY = y + FONT_VOFFSET; // Draw the character g.drawChars(new char[] { c }, 0, 1, drawX, drawY); } /** * Draws an image at the given tile location * * @param g graphics object * @param x x position of top-left of tile * @param y y position of top-left of tile * @param img image to draw */ private static void drawImage(Graphics g, int tileX, int tileY, BufferedImage img) { int xOff = tileX + (TILE_SIZE - img.getWidth()) / 2; int yOff = tileY + (TILE_SIZE - img.getHeight()) / 2; g.drawImage(img, xOff, yOff, null); } @Override public void paintComponent(Graphics g) { // Get selected tile position int selectedX = (selectedTile == null ? -1 : selectedTile.x); int selectedY = (selectedTile == null ? -1 : selectedTile.y); // Draw background if (isOpaque()) { g.setColor(getBackground()); g.fillRect(0, 0, getWidth(), getHeight()); } // Draw all the tiles for (int x = 0; x < minefield.getWidth(); x++) { for (int y = 0; y < minefield.getHeight(); y++) { int graphicsX1 = x * TILE_SIZE; int graphicsY1 = y * TILE_SIZE; // Draw standard background g.setColor(COLOUR_DARK); g.drawLine(graphicsX1, graphicsY1, graphicsX1 + TILE_SIZE, graphicsY1); g.drawLine(graphicsX1, graphicsY1, graphicsX1, graphicsY1 + TILE_SIZE); // Covered or uncovered? if (minefield.getTileState(x, y) == TileState.UNCOVERED) { // Draw the correct symbol int tileValue = minefield.getTileValue(x, y); if (tileValue < 0) { drawImage(g, graphicsX1, graphicsY1, Images.MINE); } else if (tileValue > 0) { g.setColor(COLOUR_NUMBERS[tileValue]); drawCharacter(g, graphicsX1, graphicsY1, (char) ('0' + tileValue)); } } else { // Only draw the bevel background if this is NOT the selected tile if (x != selectedX || y != selectedY) { int bevelX2 = graphicsX1 + TILE_SIZE - BEVEL_WIDTH; int bevelY2 = graphicsY1 + TILE_SIZE - BEVEL_WIDTH; g.setColor(COLOUR_LIGHT); g.fillRect(graphicsX1, graphicsY1, TILE_SIZE, BEVEL_WIDTH); g.fillRect(graphicsX1, graphicsY1, BEVEL_WIDTH, TILE_SIZE); g.setColor(COLOUR_DARK); g.fillRect(graphicsX1, bevelY2, TILE_SIZE, BEVEL_WIDTH); g.fillRect(bevelX2, graphicsY1, BEVEL_WIDTH, TILE_SIZE); } // Draw flag or question mark if needed if (minefield.getTileState(x, y) == TileState.FLAGGED) { drawImage(g, graphicsX1, graphicsY1, Images.FLAG); } else if (minefield.getTileState(x, y) == TileState.QUESTION) { g.setColor(COLOUR_QUESTION); drawCharacter(g, graphicsX1, graphicsY1, '?'); } } } } } @Override public Dimension getPreferredSize() { return new Dimension(TILE_SIZE * minefield.getWidth(), TILE_SIZE * minefield.getHeight()); } @Override public Dimension getMaximumSize() { return getPreferredSize(); } @Override public Dimension getMinimumSize() { return getPreferredSize(); } /** * Handles all mouse events within the game area */ private class MouseEventListener extends MouseAdapter { /** * Calculates the selected tile from a mouse event */ private Point getTileFromEvent(MouseEvent e) { return new Point(e.getX() / TILE_SIZE, e.getY() / TILE_SIZE); } @Override public void mouseExited(MouseEvent e) { // Clear selected tile if (selectedTile != null) { selectedTile = null; repaint(); } } @Override public void mousePressed(MouseEvent e) { // Ignore if finished if (minefield.isFinished()) return; // Get tile position Point tile = getTileFromEvent(e); // Right or left click? if (SwingUtilities.isLeftMouseButton(e)) { // Do not select tiles with flags on if (minefield.getTileState(tile.x, tile.y) == TileState.FLAGGED) return; // Set new selected tile selectedTile = tile; } else if (SwingUtilities.isRightMouseButton(e)) { TileState newState; // Change flagged state switch(minefield.getTileState(tile.x, tile.y)) { case COVERED: newState = TileState.FLAGGED; break; case FLAGGED: newState = TileState.QUESTION; break; default: newState = TileState.COVERED; break; case UNCOVERED: newState = TileState.UNCOVERED; break; } minefield.setTileState(tile.x, tile.y, newState); } repaint(); } @Override public void mouseReleased(MouseEvent e) { // Ignore if finished if (minefield.isFinished()) return; // Ensure there was a tile selected if (selectedTile != null) { // Ensure the tile was the same as the one clicked on if (selectedTile.equals(getTileFromEvent(e))) { // Either chord or uncover depending on the number of clicks GameState state = minefield.getGameState(); if (e.getClickCount() == 2) minefield.chord(selectedTile.x, selectedTile.y); else if (e.getClickCount() == 1) minefield.uncover(selectedTile.x, selectedTile.y); // Fire state changed event if needed if (minefield.getGameState() != state) fireStateChangeEvent(); } // Clear selected tile selectedTile = null; repaint(); } } } }
package io.spine.core; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.RUNTIME; /** * Marks a method as a subscriber for the command output. * * <p>Use it to subscribe to either events, business rejections, or entity state updates. * * <h1>Subscribing to Events</h1> * * <p>An event subscriber method: * <ul> * <li>is annotated with {@link Subscribe}; * <li>is {@code public}; * <li>returns {@code void}; * <li>accepts an event derived from {@link io.spine.base.EventMessage EventMessage} * as the first parameter; * <li>(optional) accepts an {@link io.spine.core.EventContext EventContext} * as the second parameter. * </ul> * * <h1>Subscribing to Rejections</h1> * * <p>A rejection subscriber method: * <ul> * <li>is annotated with {@link Subscribe}; * <li>is {@code public}; * <li>returns {@code void}; * <li>accepts a rejection message derived from {@link io.spine.base.RejectionMessage * RejectionMessage} as the first parameter; * <li>(optional) accepts a command derived from {@link io.spine.base.CommandMessage * CommandMessage} as the second parameter; * <li>(optional) accepts an {@link io.spine.core.CommandContext CommandContext} * as the second or the third parameter. * </ul> * * <p>Therefore, if the subscriber method specifies both the command message and * the command context, it must have the parameters exactly is that order, i.e. * {@code (RejectionMessage, CommandMessage, CommandContext)}. Otherwise, an exception may be thrown * at runtime. * * <p>The type of the command argument, if specified, acts as a filter, i.e. the subscriber receives * the rejection if: * <ul> * <li>the rejection type matches the first argument type; * <li>the command, which processing caused the rejection, has the same type as * the command message argument if it is present; * <li>if the command message argument is absent, any rejection of a matching type is received * by the subscriber. * </ul> * * <h1>Subscribing to entity state updates</h1> * * <p>An entity state subscriber method: * <ul> * <li>is annotated with {@link Subscribe}; * <li>is {@code public}; * <li>returns {@code void}; * <li>accepts an entity state message marked with the {@code (entity)} option as the only * parameter. * </ul> * * <h1>Filtering events by a field value</h1> * <p>If a {@linkplain ByField field filter} is defined, only the events matching this filter are * passed to the subscriber. * * <p>Any combination of {@code external} and {@code filter} is valid, i.e. it is possible * to filter external event subscriptions. Though, it is not possible to filter entity state * updates. * * <p>A single subscribing class may define a number of subscriber methods with different field * filters. Though, all the field filters must target the same field. For example, this event * handling is valid: * <pre> * {@code * \@Subscribe(filter = @ByField(path = "subscription.status", value = "EXPIRED")) * public void onExpired(UserLoggedIn event) { * // Handle expired subscription. * } * * \@Subscribe(filter = @ByField(path = "subscription.status", value = "INACTIVE")) * public void onInactive(UserLoggedIn event) { * // Handle inactive subscription. * } * * \@Subscribe * public void on(UserLoggedIn event) { * // Handle other cases. * } * } * </pre> * <p>And this one is not: * <pre> * {@code * \@Subscribe(filter = @ByField(path = "subscription.status", value = "EXPIRED")) * public void onExpired(UserLoggedIn event) { * } * * \@Subscribe(filter = @ByField(path = "payment_method.status", value = "UNSET")) * public void onUnknownBilling(UserLoggedIn event) { * // Error, different field paths used in the same class for the same event type. * } * } * </pre> * * <p>If the annotation is applied to a method which doesn't satisfy any of these requirements, * this method is not considered as a subscriber and is not registered for the command output * delivery. * * @author Alexander Yevsyukov * @author Alex Tymchenko * @author Dmytro Dashenkov */ @Retention(RUNTIME) @Target(METHOD) @Documented public @interface Subscribe { /** * When {@code true}, the annotated method of receives an event generated from outside of the * Bounded Context to which the annotated method's class belongs. */ boolean external() default false; /** * Filter to apply to all the event messages. * * <p>If an event does not match this filter, it is not passed to the subscriber method. * * <p>If the {@link ByField#path() @ByField.path} if empty, the filter is not * applied. */ ByField filter() default @ByField(path = "", value = ""); }
package us.kbase.typedobj.db; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import java.util.regex.Pattern; import java.util.stream.Collectors; import org.bson.BSONObject; import org.jongo.Jongo; import org.jongo.MongoCollection; import us.kbase.typedobj.exceptions.TypeStorageException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBObject; public class MongoTypeStorage implements TypeStorage { private Jongo jdb; private final DB db; public static final String TABLE_MODULE_REQUEST = "module_request"; public static final String TABLE_MODULE_VERSION = "module_version"; public static final String TABLE_MODULE_OWNER = "module_owner"; public static final String TABLE_MODULE_INFO_HISTORY = "module_info_history"; public static final String TABLE_MODULE_SPEC_HISTORY = "module_spec_history"; public static final String TABLE_MODULE_TYPE_SCHEMA = "module_type_schema"; public static final String TABLE_MODULE_TYPE_PARSE = "module_type_parse"; public static final String TABLE_MODULE_FUNC_PARSE = "module_func_parse"; public static final String TABLE_FUNC_REFS = "func_refs"; public static final String TABLE_TYPE_REFS = "type_refs"; public static final int MAX_REQUESTS_BY_USER = 30; private static final ObjectMapper MAPPER = new ObjectMapper(); private static final Pattern dotSep = Pattern.compile(Pattern.quote(".")); public MongoTypeStorage(DB db) { this.db = db; jdb = new Jongo(db); ensureIndeces(); } private void ensureIndeces() { MongoCollection reqs = jdb.getCollection(TABLE_MODULE_REQUEST); reqs.ensureIndex("{moduleName:1,ownerUserId:1}", "{unique:true}"); reqs.ensureIndex("{ownerUserId:1}", "{unique:false}"); MongoCollection vers = jdb.getCollection(TABLE_MODULE_VERSION); vers.ensureIndex("{moduleName:1}", "{unique:true}"); MongoCollection owns = jdb.getCollection(TABLE_MODULE_OWNER); owns.ensureIndex("{moduleName:1,ownerUserId:1}", "{unique:true}"); owns.ensureIndex("{ownerUserId:1}", "{unique:false}"); MongoCollection infos = jdb.getCollection(TABLE_MODULE_INFO_HISTORY); infos.ensureIndex("{moduleName:1,versionTime:1}", "{unique:true}"); MongoCollection specs = jdb.getCollection(TABLE_MODULE_SPEC_HISTORY); specs.ensureIndex("{moduleName:1,versionTime:1}", "{unique:true}"); MongoCollection tschs = jdb.getCollection(TABLE_MODULE_TYPE_SCHEMA); tschs.ensureIndex("{moduleName:1,typeName:1,version:1}", "{unique:true}"); tschs.ensureIndex("{moduleName:1,moduleVersion:1}", "{unique:false}"); MongoCollection tprs = jdb.getCollection(TABLE_MODULE_TYPE_PARSE); tprs.ensureIndex("{moduleName:1,typeName:1,version:1}", "{unique:true}"); tprs.ensureIndex("{moduleName:1,moduleVersion:1}", "{unique:false}"); MongoCollection fprs = jdb.getCollection(TABLE_MODULE_FUNC_PARSE); fprs.ensureIndex("{moduleName:1,funcName:1,version:1}", "{unique:true}"); fprs.ensureIndex("{moduleName:1,moduleVersion:1}", "{unique:false}"); MongoCollection frefs = jdb.getCollection(TABLE_FUNC_REFS); frefs.ensureIndex("{depModule:1,depName:1,depVersion:1}", "{unique:false}"); frefs.ensureIndex("{refModule:1,refName:1,refVersion:1}", "{unique:false}"); frefs.ensureIndex("{depModule:1,depModuleVersion:1}", "{unique:false}"); MongoCollection trefs = jdb.getCollection(TABLE_TYPE_REFS); trefs.ensureIndex("{depModule:1,depName:1,depVersion:1}", "{unique:false}"); trefs.ensureIndex("{refModule:1,refName:1,refVersion:1}", "{unique:false}"); trefs.ensureIndex("{depModule:1,depModuleVersion:1}", "{unique:false}"); } private Map<String, Object> toMap(final Object obj) { return MAPPER.convertValue(obj, new TypeReference<Map<String, Object>>() {}); } private DBObject toDBObj(final Object obj) { return new BasicDBObject(toMap(obj)); } private <T> T toObj(final DBObject dbo, final Class<T> clazz) { if (dbo == null) { return null; } return MAPPER.convertValue(toMapRec(dbo), clazz); } // Unimplemented error for dbo.toMap() // dbo is read only // can't call convertValue() on dbo since it has a 'size' field outside of the internal map // and just weird shit happens when you do anyway private Map<String, Object> toMapRec(final BSONObject dbo) { return dbo.keySet().stream().filter(k -> !k.equals("_id")).collect(Collectors.toMap( k -> k, // may need lists too? k -> dbo.get(k) instanceof BSONObject ? toMapRec((BSONObject) dbo.get(k)) : dbo.get(k))); } @Override public void addRefs(Set<RefInfo> typeRefs, Set<RefInfo> funcRefs) throws TypeStorageException { try { if (typeRefs.size() > 0) { DBCollection refs = db.getCollection(TABLE_TYPE_REFS); for (RefInfo ref : typeRefs) { if (ref.getDepModuleVersion() == 0) throw new TypeStorageException("Dependent type's module version was not initialized"); refs.insert(toDBObj(ref)); } } if (funcRefs.size() > 0) { DBCollection refs = db.getCollection(TABLE_FUNC_REFS); for (RefInfo ref : funcRefs) { if (ref.getDepModuleVersion() == 0) throw new TypeStorageException("Dependent function's module version was not initialized"); refs.insert(toDBObj(ref)); } } } catch (Exception e) { throw new TypeStorageException(e); } } @Override public long getLastReleasedModuleVersion(String moduleName) throws TypeStorageException { Long ret = getLastModuleVersionOrNull(moduleName); if (ret == null) throw new TypeStorageException("Module " + moduleName + " is not registered"); return ret; } @Override public boolean checkModuleExist(String moduleName) throws TypeStorageException { return getLastModuleVersionOrNull(moduleName) != null; } private Long getLastModuleVersionOrNull(String moduleName) throws TypeStorageException { try { final DBCollection vers = db.getCollection(TABLE_MODULE_VERSION); final ModuleVersion ret = toObj(vers.findOne( new BasicDBObject("moduleName", moduleName)), ModuleVersion.class); return ret == null ? null : ret.releasedVersionTime; } catch (Exception e) { throw new TypeStorageException(e); } } @Override public boolean checkModuleInfoRecordExist(String moduleName, long version) throws TypeStorageException { return getModuleInfoOrNull(moduleName, version) != null; } @Override public boolean checkModuleSpecRecordExist(String moduleName, long version) throws TypeStorageException { return getModuleSpecOrNull(moduleName, version) != null; } private ModuleInfo getModuleInfoOrNull(String moduleName, long version) throws TypeStorageException { try { final DBCollection infos = db.getCollection(TABLE_MODULE_INFO_HISTORY); final ModuleInfo info = toObj(infos.findOne(new BasicDBObject("moduleName", moduleName) .append("versionTime", version)), ModuleInfo.class); return info; } catch (Exception e) { throw new TypeStorageException(e); } } private String getModuleSpecOrNull(String moduleName, long version) throws TypeStorageException { try { final DBCollection specs = db.getCollection(TABLE_MODULE_SPEC_HISTORY); final ModuleSpec spec = toObj(specs.findOne(new BasicDBObject("moduleName", moduleName) .append("versionTime", version)), ModuleSpec.class); return spec == null ? null : spec.document; } catch (Exception e) { throw new TypeStorageException(e); } } @Override public boolean checkTypeSchemaRecordExists(String moduleName, String typeName, String version) throws TypeStorageException { try { final DBCollection docs = db.getCollection(TABLE_MODULE_TYPE_SCHEMA); return null != docs.findOne(new BasicDBObject("moduleName", moduleName) .append("typeName", typeName) .append("version", version)); } catch (Exception e) { throw new TypeStorageException(e); } } @Override public Set<String> getAllRegisteredModules(boolean withUnsupported) throws TypeStorageException { try { MongoCollection infos = jdb.getCollection(TABLE_MODULE_VERSION); Map<String, Boolean> map = getProjection(infos, "{}", "moduleName", String.class, "supported", Boolean.class); Set<String> ret = new TreeSet<String>(); if (withUnsupported) { ret.addAll(map.keySet()); } else { for (String module : map.keySet()) if (map.get(module)) ret.add(module); } return ret; } catch (Exception e) { throw new TypeStorageException(e); } } @Override public boolean getModuleSupportedState(String moduleName) throws TypeStorageException { try { MongoCollection vers = jdb.getCollection(TABLE_MODULE_VERSION); ModuleVersion ret = vers.findOne("{moduleName:#}", moduleName).as(ModuleVersion.class); if (ret == null) throw new TypeStorageException("Support information is unavailable for module: " + moduleName); return ret.isSupported(); } catch (TypeStorageException e) { throw e; } catch (Exception e) { throw new TypeStorageException(e); } } @SuppressWarnings("unchecked") @Override public String getFuncParseRecord(String moduleName, String funcName, String version) throws TypeStorageException { Map<String, Object> ret; try { MongoCollection docs = jdb.getCollection(TABLE_MODULE_FUNC_PARSE); ret = docs.findOne("{moduleName: moduleName, funcName, version).as(Map.class); } catch (Exception e) { throw new TypeStorageException(e); } if (ret == null) throw new TypeStorageException("Function parse record was not found " + "for " + moduleName + "." + funcName + "." + version); return ret.get("document").toString(); } @Override public Set<RefInfo> getFuncRefsByDep(String depModule, String depFunc, String version) throws TypeStorageException { try { MongoCollection refs = jdb.getCollection(TABLE_FUNC_REFS); return Sets.newTreeSet(refs.find("{depModule: depModule, depFunc, version).as(RefInfo.class)); } catch (Exception e) { throw new TypeStorageException(e); } } @Override public Set<RefInfo> getFuncRefsByRef(String refModule, String refType, String version) throws TypeStorageException { try { MongoCollection refs = jdb.getCollection(TABLE_FUNC_REFS); return Sets.newTreeSet(refs.find("{refModule: refModule, refType, version).as(RefInfo.class)); } catch (Exception e) { throw new TypeStorageException(e); } } @Override public ModuleInfo getModuleInfoRecord(String moduleName, long version) throws TypeStorageException { ModuleInfo ret = getModuleInfoOrNull(moduleName, version); if (ret == null) throw new TypeStorageException("Info-record was not found for module: " + moduleName); return ret; } @Override public String getModuleSpecRecord(String moduleName, long version) throws TypeStorageException { String ret = getModuleSpecOrNull(moduleName, version); if (ret == null) throw new TypeStorageException("Spec-record was not found for module: " + moduleName); return ret; } @Override public TreeMap<Long, Boolean> getAllModuleVersions(String moduleName) throws TypeStorageException { try { MongoCollection infos = jdb.getCollection(TABLE_MODULE_INFO_HISTORY); Map<Long, Boolean> map = getProjection(infos, "{moduleName:#}", "versionTime", Long.class, "released", Boolean.class, moduleName); long releaseVer = getLastReleasedModuleVersion(moduleName); TreeMap<Long, Boolean> ret = new TreeMap<Long, Boolean>(); for (long ver : map.keySet()) ret.put(ver, ver <= releaseVer && map.get(ver)); return ret; } catch (Exception e) { throw new TypeStorageException(e); } } @SuppressWarnings({ "rawtypes", "unchecked" }) protected <KT, VT> Map<KT, VT> getProjection(MongoCollection infos, String whereCondition, String keySelectField, Class<KT> keyType, String valueSelectField, Class<VT> valueType, Object... params) throws TypeStorageException { List<Map> data = Lists.newArrayList(infos.find(whereCondition, params).projection( "{'" + keySelectField + "':1,'" + valueSelectField + "':1}").as(Map.class)); Map<KT, VT> ret = new LinkedHashMap<KT, VT>(); for (Map<?,?> item : data) { Object key = getMongoProp(item, keySelectField); if (key == null || !(keyType.isInstance(key))) throw new TypeStorageException("Key is wrong: " + key); Object value = getMongoProp(item, valueSelectField); if (value == null || !(valueType.isInstance(value))) throw new TypeStorageException("Value is wrong: " + value); ret.put((KT)key, (VT)value); } return ret; } private static Object getMongoProp(Map<?,?> data, String propWithDots) { String[] parts = dotSep.split(propWithDots); Object value = null; for (String part : parts) { if (value != null) { data = (Map<?,?>)value; } value = data.get(part); } return value; } @Override public Map<String, Boolean> getAllTypeVersions(String moduleName, String typeName) throws TypeStorageException { if (typeName.contains("'")) throw new TypeStorageException("Type names with symbol ['] are not supperted"); try { MongoCollection schemas = jdb.getCollection(TABLE_MODULE_INFO_HISTORY); Map<Long, String> typeMap = getProjection(schemas, "{moduleName:#,'types." + typeName + ".typeName':#}", "versionTime", Long.class, "types." + typeName + ".typeVersion", String.class, moduleName, typeName); Map<Long, Boolean> moduleMap = getAllModuleVersions(moduleName); Map<String, Boolean> ret = new LinkedHashMap<String, Boolean>(); for (Map.Entry<Long, String> entry : typeMap.entrySet()) { long moduleVer = entry.getKey(); String typeVer = entry.getValue(); boolean prevTypeRet = ret.containsKey(typeVer) ? ret.get(typeVer) : false; boolean newTypeRet = moduleMap.get(moduleVer); ret.put(typeVer, prevTypeRet || newTypeRet); } return ret; } catch (Exception e) { throw new TypeStorageException(e); } } @Override public Map<String, Boolean> getAllFuncVersions(String moduleName, String funcName) throws TypeStorageException { if (funcName.contains("'")) throw new TypeStorageException("Function names with symbol ['] are not supperted"); try { MongoCollection schemas = jdb.getCollection(TABLE_MODULE_INFO_HISTORY); Map<Long, String> funcMap = getProjection(schemas, "{moduleName:#,'funcs." + funcName + ".funcName':#}", "versionTime", Long.class, "funcs." + funcName + ".funcVersion", String.class, moduleName, funcName); Map<Long, Boolean> moduleMap = getAllModuleVersions(moduleName); Map<String, Boolean> ret = new LinkedHashMap<String, Boolean>(); for (Map.Entry<Long, String> entry : funcMap.entrySet()) { long moduleVer = entry.getKey(); String funcVer = entry.getValue(); boolean prevFuncRet = ret.containsKey(funcVer) ? ret.get(funcVer) : false; boolean newFuncRet = moduleMap.get(moduleVer); ret.put(funcVer, prevFuncRet || newFuncRet); } return ret; } catch (Exception e) { throw new TypeStorageException(e); } } @Override public long generateNewModuleVersion(String moduleName) throws TypeStorageException { long ret = System.currentTimeMillis(); Long value = getLastModuleVersionWithUnreleasedOrNull(moduleName); if (value != null && ret <= value) ret = value + 1; return ret; } @SuppressWarnings("unchecked") @Override public String getTypeParseRecord(String moduleName, String typeName, String version) throws TypeStorageException { Map<String, Object> ret; try { MongoCollection docs = jdb.getCollection(TABLE_MODULE_TYPE_PARSE); ret = docs.findOne("{moduleName: moduleName, typeName, version).as(Map.class); } catch (Exception e) { throw new TypeStorageException(e); } if (ret == null) throw new TypeStorageException("Type parse record was not found " + "for " + moduleName + "." + typeName + "." + version); return ret.get("document").toString(); } @Override public Set<RefInfo> getTypeRefsByDep(String depModule, String depType, String version) throws TypeStorageException { try { MongoCollection refs = jdb.getCollection(TABLE_TYPE_REFS); return Sets.newTreeSet(refs.find("{depModule: depModule, depType, version).as(RefInfo.class)); } catch (Exception e) { throw new TypeStorageException(e); } } @Override public Set<RefInfo> getTypeRefsByRef(String refModule, String refType, String version) throws TypeStorageException { try { MongoCollection refs = jdb.getCollection(TABLE_TYPE_REFS); return Sets.newTreeSet(refs.find("{refModule: refModule, refType, version).as(RefInfo.class)); } catch (Exception e) { throw new TypeStorageException(e); } } @Override public String getTypeSchemaRecord(String moduleName, String typeName, String version) throws TypeStorageException { String query = "{moduleName: Map<String, Object> ret = findTypeRecord(moduleName, typeName, version, query, moduleName, typeName, version); if (ret == null) throw new TypeStorageException("Type schema record was not found " + "for " + moduleName + "." + typeName + "." + version); return ret.get("document").toString(); } @SuppressWarnings("unchecked") private Map<String, Object> findTypeRecord(String moduleName, String typeName, String version, String query, Object... params) throws TypeStorageException { Map<String, Object> ret; try { MongoCollection docs = jdb.getCollection(TABLE_MODULE_TYPE_SCHEMA); ret = docs.findOne(query, params).as(Map.class); } catch (Exception e) { throw new TypeStorageException(e); } return ret; } @Override public String getTypeMd5(String moduleName, String typeName, String version) throws TypeStorageException { String query = "{moduleName: Map<String, Object> ret = findTypeRecord(moduleName, typeName, version, query, moduleName, typeName, version); if (ret == null) throw new TypeStorageException("Type schema record was not found " + "for " + moduleName + "." + typeName + "." + version); return ret.get("md5hash").toString(); } @SuppressWarnings("rawtypes") @Override public List<String> getTypeVersionsByMd5(String moduleName, String typeName, String md5) throws TypeStorageException { try { String query = "{moduleName:#,typeName:#,md5hash:#}"; MongoCollection docs = jdb.getCollection(TABLE_MODULE_TYPE_SCHEMA); List<Map> list = Lists.newArrayList(docs.find(query, moduleName, typeName, md5).as(Map.class)); List<String> ret = new ArrayList<String>(); for (Map<?,?> map : list) ret.add(map.get("version").toString()); return ret; } catch (Exception e) { throw new TypeStorageException(e); } } @Override public void removeAllData() throws TypeStorageException { jdb.getCollection(TABLE_TYPE_REFS).remove(); jdb.getCollection(TABLE_FUNC_REFS).remove(); jdb.getCollection(TABLE_MODULE_TYPE_PARSE).remove(); jdb.getCollection(TABLE_MODULE_TYPE_SCHEMA).remove(); jdb.getCollection(TABLE_MODULE_FUNC_PARSE).remove(); jdb.getCollection(TABLE_MODULE_REQUEST).remove(); jdb.getCollection(TABLE_MODULE_OWNER).remove(); jdb.getCollection(TABLE_MODULE_SPEC_HISTORY).remove(); jdb.getCollection(TABLE_MODULE_INFO_HISTORY).remove(); jdb.getCollection(TABLE_MODULE_VERSION).remove(); } // removed removeModule method after 3ad9e2d. Untested, unused. @Override public void writeFuncParseRecord(String moduleName, String funcName, String version, long moduleVersion, String parseText) throws TypeStorageException { try { MongoCollection recs = jdb.getCollection(TABLE_MODULE_FUNC_PARSE); recs.remove("{moduleName: FuncRecord rec = new FuncRecord(); rec.setModuleName(moduleName); rec.setFuncName(funcName); rec.setVersion(version); rec.setModuleVersion(moduleVersion); rec.setDocument(parseText); recs.save(rec); } catch (Exception e) { throw new TypeStorageException(e); } } private void writeModuleVersion(String moduleName, long version) throws TypeStorageException { try { MongoCollection vers = jdb.getCollection(TABLE_MODULE_VERSION); if (vers.findOne("{moduleName:#}", moduleName).as(ModuleVersion.class) == null) { ModuleVersion ver = new ModuleVersion(); ver.setModuleName(moduleName); ver.setVersionTime(version); ver.setReleasedVersionTime(version); ver.setSupported(true); vers.insert(ver); } else { vers.update("{moduleName:#}", moduleName).with("{$set: {versionTime: #}}", version); } } catch (Exception e) { throw new TypeStorageException(e); } } @Override public void writeModuleRecords(ModuleInfo info, String specDocument, long version) throws TypeStorageException { writeModuleVersion(info.getModuleName(), version); writeModuleInfo(info, version); try { MongoCollection specs = jdb.getCollection(TABLE_MODULE_SPEC_HISTORY); ModuleSpec spec = new ModuleSpec(); spec.setModuleName(info.getModuleName()); spec.setDocument(specDocument); spec.setVersionTime(version); specs.insert(spec); } catch (Exception e) { throw new TypeStorageException(e); } } @Override public void initModuleInfoRecord(ModuleInfo info) throws TypeStorageException { long version = generateNewModuleVersion(info.getModuleName()); writeModuleVersion(info.getModuleName(), version); writeModuleInfo(info, version); } private void writeModuleInfo(ModuleInfo info, long version) throws TypeStorageException { try { MongoCollection infos = jdb.getCollection(TABLE_MODULE_INFO_HISTORY); info.setVersionTime(version); infos.insert(info); } catch (Exception e) { throw new TypeStorageException(e); } } @Override public void writeTypeParseRecord(String moduleName, String typeName, String version, long moduleVersion, String document) throws TypeStorageException { try { MongoCollection recs = jdb.getCollection(TABLE_MODULE_TYPE_PARSE); recs.remove("{moduleName: TypeRecord rec = new TypeRecord(); rec.setModuleName(moduleName); rec.setTypeName(typeName); rec.setVersion(version); rec.setModuleVersion(moduleVersion); rec.setDocument(document); recs.save(rec); } catch (Exception e) { throw new TypeStorageException(e); } } @Override public Map<Long, Boolean> getModuleVersionsForTypeVersion(String moduleName, String typeName, String typeVersion) throws TypeStorageException { if (typeName.contains("'")) throw new TypeStorageException("Type names with symbol ['] are not supperted"); try { MongoCollection infoCol = jdb.getCollection(TABLE_MODULE_INFO_HISTORY); return getProjection(infoCol, "{moduleName:#,'types." + typeName + ".typeVersion':#," + "'types." + typeName + ".supported':#}", "versionTime", Long.class, "released", Boolean.class, moduleName, typeVersion, true); } catch (Exception e) { throw new TypeStorageException(e); } } @Override public Map<Long, Boolean> getModuleVersionsForFuncVersion(String moduleName, String funcName, String funcVersion) throws TypeStorageException { if (funcName.contains("'")) throw new TypeStorageException("Function names with symbol ['] are not supperted"); try { MongoCollection infoCol = jdb.getCollection(TABLE_MODULE_INFO_HISTORY); return getProjection(infoCol, "{moduleName:#,'funcs." + funcName + ".funcVersion':#}", "versionTime", Long.class, "released", Boolean.class, moduleName, funcVersion); } catch (Exception e) { throw new TypeStorageException(e); } } @Override public void writeTypeSchemaRecord(String moduleName, String typeName, String version, long moduleVersion, String document, String md5) throws TypeStorageException { try { MongoCollection recs = jdb.getCollection(TABLE_MODULE_TYPE_SCHEMA); recs.remove("{moduleName: TypeRecord rec = new TypeRecord(); rec.setModuleName(moduleName); rec.setTypeName(typeName); rec.setVersion(version); rec.setModuleVersion(moduleVersion); rec.setDocument(document); rec.setMd5hash(md5); recs.insert(rec); } catch (Exception e) { throw new TypeStorageException(e); } } @Override public void addNewModuleRegistrationRequest(String moduleName, String userId) throws TypeStorageException { try { MongoCollection recs = jdb.getCollection(TABLE_MODULE_REQUEST); int prevCount = Lists.newArrayList(recs.find("{ownerUserId: userId).as(OwnerInfo.class)).size(); if (prevCount >= MAX_REQUESTS_BY_USER) throw new TypeStorageException("User " + userId + " has maximal count " + "of requests: " + MAX_REQUESTS_BY_USER); if (recs.findOne("{moduleName:#}", moduleName).as(OwnerInfo.class) != null) throw new TypeStorageException("Registration of module " + moduleName + " was already requested"); if (checkModuleExist(moduleName)) throw new TypeStorageException("Module " + moduleName + " was already registered"); OwnerInfo rec = new OwnerInfo(); rec.setOwnerUserId(userId); rec.setWithChangeOwnersPrivilege(true); rec.setModuleName(moduleName); recs.insert(rec); } catch (TypeStorageException e) { throw e; } catch (Exception e) { throw new TypeStorageException(e); } } @Override public String getOwnerForNewModuleRegistrationRequest(String moduleName) throws TypeStorageException { OwnerInfo ret; try { MongoCollection recs = jdb.getCollection(TABLE_MODULE_REQUEST); ret = recs.findOne("{moduleName:#}", moduleName).as(OwnerInfo.class); } catch (Exception e) { throw new TypeStorageException(e); } if (ret == null) throw new TypeStorageException("There is no request for module " + moduleName); return ret.getOwnerUserId(); } @Override public void addOwnerToModule(String moduleName, String userId, boolean withChangeOwnersPrivilege) throws TypeStorageException { try { MongoCollection recs = jdb.getCollection(TABLE_MODULE_OWNER); recs.remove("{moduleName:#,ownerUserId:#}", moduleName, userId); OwnerInfo rec = new OwnerInfo(); rec.setOwnerUserId(userId); rec.setWithChangeOwnersPrivilege(withChangeOwnersPrivilege); rec.setModuleName(moduleName); recs.insert(rec); } catch (Exception e) { throw new TypeStorageException(e); } } @Override public List<OwnerInfo> getNewModuleRegistrationRequests() throws TypeStorageException { try { MongoCollection recs = jdb.getCollection(TABLE_MODULE_REQUEST); return Lists.newArrayList(recs.find().as(OwnerInfo.class)); } catch (Exception e) { throw new TypeStorageException(e); } } @Override public Map<String, OwnerInfo> getOwnersForModule(String moduleName) throws TypeStorageException { try { MongoCollection recs = jdb.getCollection(TABLE_MODULE_OWNER); List<OwnerInfo> owners = Lists.newArrayList(recs.find("{moduleName:#}", moduleName).as(OwnerInfo.class)); Map<String, OwnerInfo> ret = new TreeMap<String, OwnerInfo>(); for (OwnerInfo oi : owners) ret.put(oi.getOwnerUserId(), oi); return ret; } catch (Exception e) { throw new TypeStorageException(e); } } @Override public Map<String, OwnerInfo> getModulesForOwner(String userId) throws TypeStorageException { try { MongoCollection recs = jdb.getCollection(TABLE_MODULE_OWNER); List<OwnerInfo> owners = Lists.newArrayList(recs.find("{ownerUserId:#}", userId).as(OwnerInfo.class)); Map<String, OwnerInfo> ret = new TreeMap<String, OwnerInfo>(); for (OwnerInfo oi : owners) ret.put(oi.getModuleName(), oi); return ret; } catch (Exception e) { throw new TypeStorageException(e); } } @Override public void removeNewModuleRegistrationRequest(String moduleName, String userId) throws TypeStorageException { try { MongoCollection recs = jdb.getCollection(TABLE_MODULE_REQUEST); recs.remove("{moduleName:#,ownerUserId:#}", moduleName, userId); } catch (Exception e) { throw new TypeStorageException(e); } } @Override public void removeOwnerFromModule(String moduleName, String userId) throws TypeStorageException { try { MongoCollection recs = jdb.getCollection(TABLE_MODULE_OWNER); recs.remove("{moduleName:#,ownerUserId:#}", moduleName, userId); } catch (Exception e) { throw new TypeStorageException(e); } } @Override public Map<String, Long> listObjects() throws TypeStorageException { String[] tables = { TABLE_FUNC_REFS, TABLE_MODULE_FUNC_PARSE, TABLE_MODULE_INFO_HISTORY, TABLE_MODULE_OWNER, TABLE_MODULE_REQUEST, TABLE_MODULE_SPEC_HISTORY, TABLE_MODULE_TYPE_PARSE, TABLE_MODULE_TYPE_SCHEMA, TABLE_MODULE_VERSION, TABLE_TYPE_REFS }; Map<String, Long> ret = new TreeMap<String, Long>(); for (String table : tables) { MongoCollection recs = jdb.getCollection(table); List<Object> rows = Lists.newArrayList(recs.find().as(Object.class)); ret.put(table, (long)rows.size()); } return ret; } @Override public void removeModuleVersionAndSwitchIfNotCurrent(String moduleName, long versionToDelete, long versionToSwitchTo) throws TypeStorageException { try { jdb.getCollection(TABLE_TYPE_REFS).remove("{depModule: jdb.getCollection(TABLE_FUNC_REFS).remove("{depModule: jdb.getCollection(TABLE_MODULE_TYPE_SCHEMA).remove("{moduleName: jdb.getCollection(TABLE_MODULE_TYPE_PARSE).remove("{moduleName: jdb.getCollection(TABLE_MODULE_FUNC_PARSE).remove("{moduleName: jdb.getCollection(TABLE_MODULE_SPEC_HISTORY).remove("{moduleName:#,versionTime:#}", moduleName, versionToDelete); jdb.getCollection(TABLE_MODULE_INFO_HISTORY).remove("{moduleName:#,versionTime:#}", moduleName, versionToDelete); } catch (Exception e) { throw new TypeStorageException(e); } if (versionToSwitchTo != getLastModuleVersionWithUnreleased(moduleName)) writeModuleVersion(moduleName, versionToSwitchTo); } @Override public long getLastModuleVersionWithUnreleased(String moduleName) throws TypeStorageException { Long ret = getLastModuleVersionWithUnreleasedOrNull(moduleName); if (ret == null) throw new TypeStorageException("Module" + moduleName + " was not registered"); return ret; } private Long getLastModuleVersionWithUnreleasedOrNull(String moduleName) throws TypeStorageException { try { MongoCollection vers = jdb.getCollection(TABLE_MODULE_VERSION); ModuleVersion ret = vers.findOne("{moduleName:#}", moduleName).as(ModuleVersion.class); if (ret == null) return null; return ret.versionTime; } catch (Exception e) { throw new TypeStorageException(e); } } @Override public void setModuleReleaseVersion(String moduleName, long version) throws TypeStorageException { try { MongoCollection vers = jdb.getCollection(TABLE_MODULE_VERSION); if (vers.findOne("{moduleName:#}", moduleName).as(ModuleVersion.class) == null) { throw new TypeStorageException("Module" + moduleName + " was not registered"); } else { MongoCollection infos = jdb.getCollection(TABLE_MODULE_INFO_HISTORY); infos.update("{moduleName:#, versionTime:#}", moduleName, version).with("{$set: {released: #}}", true); vers.update("{moduleName:#}", moduleName).with("{$set: {releasedVersionTime: #}}", version); } } catch (TypeStorageException e) { throw e; } catch (Exception e) { throw new TypeStorageException(e); } } // used to be a method here called copyModuleVersion, removed after commit 3ad9e2d. @Override public void changeModuleSupportedState(String moduleName, boolean supported) throws TypeStorageException { try { MongoCollection vers = jdb.getCollection(TABLE_MODULE_VERSION); if (vers.findOne("{moduleName:#}", moduleName).as(ModuleVersion.class) == null) throw new TypeStorageException("Support information is unavailable for module: " + moduleName); vers.update("{moduleName:#}", moduleName).with("{$set: {supported: #}}", supported); } catch (TypeStorageException e) { throw e; } catch (Exception e) { throw new TypeStorageException(e); } } public static class ModuleSpec { private String moduleName; private String document; private long versionTime; public String getModuleName() { return moduleName; } public void setModuleName(String moduleName) { this.moduleName = moduleName; } public String getDocument() { return document; } public void setDocument(String document) { this.document = document; } public long getVersionTime() { return versionTime; } public void setVersionTime(long versionTime) { this.versionTime = versionTime; } } public static class ModuleVersion { private String moduleName; private long versionTime; private long releasedVersionTime; private boolean supported; public String getModuleName() { return moduleName; } public void setModuleName(String moduleName) { this.moduleName = moduleName; } public long getVersionTime() { return versionTime; } public void setVersionTime(long versionTime) { this.versionTime = versionTime; } public long getReleasedVersionTime() { return releasedVersionTime; } public void setReleasedVersionTime(long releasedVersionTime) { this.releasedVersionTime = releasedVersionTime; } public boolean isSupported() { return supported; } public void setSupported(boolean supported) { this.supported = supported; } } public class TypeRecord { private String moduleName; private String typeName; private String version; private long moduleVersion; private String document; private String md5hash; public TypeRecord() { } public String getModuleName() { return moduleName; } public void setModuleName(String moduleName) { this.moduleName = moduleName; } public String getTypeName() { return typeName; } public void setTypeName(String typeName) { this.typeName = typeName; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public long getModuleVersion() { return moduleVersion; } public void setModuleVersion(long moduleVersion) { this.moduleVersion = moduleVersion; } public String getDocument() { return document; } public void setDocument(String document) { this.document = document; } public String getMd5hash() { return md5hash; } public void setMd5hash(String md5hash) { this.md5hash = md5hash; } } public class FuncRecord { private String moduleName; private String funcName; private String version; private long moduleVersion; private String document; public String getModuleName() { return moduleName; } public void setModuleName(String moduleName) { this.moduleName = moduleName; } public String getFuncName() { return funcName; } public void setFuncName(String funcName) { this.funcName = funcName; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public long getModuleVersion() { return moduleVersion; } public void setModuleVersion(long moduleVersion) { this.moduleVersion = moduleVersion; } public String getDocument() { return document; } public void setDocument(String document) { this.document = document; } } }
package net.time4j; import net.time4j.base.MathUtils; import net.time4j.engine.ChronoDisplay; import net.time4j.engine.ChronoException; import net.time4j.engine.EpochDays; import net.time4j.scale.TimeScale; import net.time4j.tz.Timezone; import net.time4j.tz.ZonalOffset; import net.time4j.tz.olson.ASIA; import java.math.BigDecimal; import java.math.BigInteger; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeConstants; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; /** * <p>Serves as bridge to temporal types of JDK or other date and time * libraries.</p> * * <p>All singleton instances are defined as static constants and are * <i>immutable</i>.</p> * * @param <S> source type in other library * @param <T> target type in Time4J * @author Meno Hochschild * @since 2.0 */ /*[deutsch] * <p>Dient als Br&uuml;cke zu Datums- und Zeittypen aus dem JDK oder anderen * Bibliotheken. </p> * * <p>Alle Singleton-Instanzen sind als statische Konstanten definiert und * unver&auml;nderlich (<i>immutable</i>). </p> * * @param <S> source type in other library * @param <T> target type in Time4J * @author Meno Hochschild * @since 2.0 */ public abstract class TemporalType<S, T> { private static final boolean WITH_SQL_UTC_CONVERSION = Boolean.getBoolean("net.time4j.sql.utc.conversion"); private static final PlainDate UNIX_DATE = PlainDate.of(0, EpochDays.UNIX); private static final int MIO = 1000000; private static final int MRD = 1000000000; private static final BigDecimal MRD_D = BigDecimal.valueOf(MRD); private static final BigInteger MRD_I = BigInteger.valueOf(MRD); /** * <p>Bridge between a traditional Java timestamp of type * {@code java.util.Date} and the class {@code Moment}.</p> * * <p>The conversion does not take into account any UTC-leapseconds. The * supported value range is smaller than in the class {@code Moment}. * Example: </p> * * <pre> * java.util.Date instant = new java.util.Date(86401 * 1000); * Moment ut = TemporalType.JAVA_UTIL_DATE.translate(instant); * System.out.println(ut); * // output: 1970-01-02T00:00:01Z * </pre> * * @since 2.0 */ /*[deutsch] * <p>Br&uuml;cke zwischen einem traditionellen Java-Zeitstempel des Typs * {@code java.util.Date} und der Klasse {@code Moment}. </p> * * <p>Die Konversion ber&uuml;cksichtigt KEINE UTC-Schaltsekunden. * Der unterst&uuml;tzte Wertbereich ist kleiner als in der Klasse * {@code Moment}. Beispiel: </p> * * <pre> * java.util.Date instant = new java.util.Date(86401 * 1000); * Moment ut = TemporalType.JAVA_UTIL_DATE.translate(instant); * System.out.println(ut); * // Ausgabe: 1970-01-02T00:00:01Z * </pre> * * @since 2.0 */ public static final TemporalType<java.util.Date, Moment> JAVA_UTIL_DATE = new JavaUtilDateRule(); /** * <p>Bridge between a traditional Java timestamp as count of milliseconds * since UNIX-epoch and the class {@code Moment}.</p> * * <p>The conversion does not take into account any UTC-leapseconds. * The supported value range is smaller than in the class {@code Moment}. * Example: </p> * * <pre> * long instant = 86401 * 1000L; * Moment ut = TemporalType.MILLIS_SINCE_UNIX.translate(instant); * System.out.println(ut); * // output: 1970-01-02T00:00:01Z * </pre> * * @since 2.0 */ /*[deutsch] * <p>Br&uuml;cke zwischen einem traditionellen Java-Zeitstempel als * Anzahl der Millisekunden seit der UNIX-Epoche und der Klasse * {@code Moment}. </p> * * <p>Die Konversion ber&uuml;cksichtigt KEINE UTC-Schaltsekunden. Der * unterst&uuml;tzte Wertbereich ist etwas kleiner als in der Klasse * {@code Moment}. Beispiel: </p> * * <pre> * long instant = 86401 * 1000L; * Moment ut = TemporalType.MILLIS_SINCE_UNIX.translate(instant); * System.out.println(ut); * // Ausgabe: 1970-01-02T00:00:01Z * </pre> * * @since 2.0 */ public static final TemporalType<Long, Moment> MILLIS_SINCE_UNIX = new MillisSinceUnixRule(); /** * <p>Bridge between a JDBC-Date and the class {@code PlainDate}.</p> * * <p>If the system property &quot;net.time4j.sql.utc.conversion&quot; is * set to the value &quot;true&quot; then the conversion will not take into * account the system timezone anticipating that a SQL-DATE was created * without any timezone calculation on the server side, too. That is more * or less the case if UTC is the default timezone on the application * server. </p> * * <p>Example (UTC as default timezone):</p> * * <pre> * java.sql.Date sqlValue = new java.sql.Date(86400 * 1000); * PlainDate date = TemporalType.SQL_DATE.translate(sqlValue); * System.out.println(date); * // output: 1970-01-02 * </pre> * * <p><strong>Note:</strong> The conversion is only possible if a date has * a year in the range {@code 1900-9999} because else a JDBC-compatible * database cannot store the date per SQL-specification. It is strongly * recommended to interprete a SQL-DATE only as abstract JDBC object * because its text output via {@code java.sql.Date.toString()}-method * is not reliable (dependency on the gregorian-julian cutover day * + possible timezone side effects). The concrete formatting can be * done by Time4J for example via {@code PlainDate.toString()} or a * suitable {@code ChronoFormatter}.</p> * * @since 2.0 */ /*[deutsch] * <p>Br&uuml;cke zwischen einem JDBC-Date und der Klasse * {@code PlainDate}. </p> * * <p>Wenn die System-Property &quot;net.time4j.sql.utc.conversion&quot; * auf den Wert &quot;true&quot; gesetzt ist, dann ber&uuml;cksichtigt die * Konversion NICHT die Standardzeitzone des Systems und setzt somit voraus, * da&szlig; ein SQL-DATE java-seitig ebenfalls ohne Zeitzonenkalkulation * erzeugt wurde. Das ist de facto der Fall, wenn auf dem Application-Server * UTC die Standardzeitzone ist. </p> * * <p>Beispiel (UTC als Standardzeitzone): </p> * * <pre> * java.sql.Date sqlValue = new java.sql.Date(86400 * 1000); * PlainDate date = TemporalType.SQL_DATE.translate(sqlValue); * System.out.println(date); * // Ausgabe: 1970-01-02 * </pre> * * <p><strong>Zu beachten:</strong> Die Konversion ist nur m&ouml;glich, * wenn ein Datum ein Jahr im Bereich {@code 1900-9999} hat, denn sonst * kann eine JDBC-kompatible Datenbank den Datumswert per SQL-Spezifikation * nicht speichern. Es wird dringend empfohlen, ein SQL-DATE nur als * abstraktes JDBC-Objekt zu interpretieren, weil seine Textausgabe via * {@code java.sql.Date.toString()}-Methode nicht zuverl&auml;ssig ist * (Abh&auml;ngigkeit vom gregorianisch-julianischen Umstellungstag * + evtl. Zeitzoneneffekte). Die konkrete Formatierung kann von Time4J * korrekt zum Beispiel via {@code PlainDate.toString()} oder &uuml;ber * einen geeigneten {@code ChronoFormatter} geleistet werden. </p> * * @since 2.0 */ public static final TemporalType<java.sql.Date, PlainDate> SQL_DATE = new SqlDateRule(); // min = new java.sql.Date(-2208988800000L), // 1900-01-01 // max = new java.sql.Date(253402214400000L + 86399999), // 9999-12-31 /** * <p>Bridge between a JDBC-Time and the class {@code PlainTime}.</p> * * <p>If the system property &quot;net.time4j.sql.utc.conversion&quot; is * set to the value &quot;true&quot; then the conversion will NOT take into * account the system timezone anticipating that a SQL-DATE was created * without any timezone calculation on the server side, too. That is more * or less the case if UTC is the default timezone on the application * server. </p> * * <p>Example (UTC as default timezone):</p> * * <pre> * java.sql.Time sqlValue = new java.sql.Time(43200 * 1000); * PlainTime time = TemporalType.SQL_TIME.translate(sqlValue); * System.out.println(time); * // output: T12:00:00 * </pre> * * <p><strong>Note:</strong> The conversion only occurs in millisecond * precision at best not in in nanosecond precision so there is possible * loss of data. Furthermore, the text output via the method * {@code java.sql.Time.toString()} can be misinterpreted by timezone * side effects. Concrete text output should be done by Time4J. </p> * * @since 2.0 */ /*[deutsch] * <p>Br&uuml;cke zwischen einem JDBC-Time und der Klasse * {@code PlainTime}. </p> * * <p>Wenn die System-Property &quot;net.time4j.sql.utc.conversion&quot; * auf den Wert &quot;true&quot; gesetzt ist, dann ber&uuml;cksichtigt * die Konversion NICHT die Standardzeitzone des Systems und setzt somit * voraus, da&szlig; ein SQL-TIME java-seitig ebenfalls ohne * Zeitzonenkalkulation erzeugt wurde. Das ist de facto der Fall, wenn * auf dem Application-Server UTC die Standardzeitzone ist. </p> * * <p>Beispiel (UTC als Standardzeitzone): </p> * * <pre> * java.sql.Time sqlValue = new java.sql.Time(43200 * 1000); * PlainTime time = TemporalType.SQL_TIME.translate(sqlValue); * System.out.println(time); * // Ausgabe: T12:00:00 * </pre> * * <p><strong>Zu beachten:</strong> Die Konversion geschieht nur in * Milli-, nicht in Nanosekundenpr&auml;zision, so da&szlig; eventuell * Informationsverluste auftreten k&ouml;nnen. Auch ist die Textausgabe * mittels {@code java.sql.Time.toString()} durch Zeitzoneneffekte * verf&auml;lscht. Konkrete Textausgaben sollen daher immer durch Time4J * erfolgen. </p> * * @since 2.0 */ public static final TemporalType<java.sql.Time, PlainTime> SQL_TIME = new SqlTimeRule(); /** * <p>Bridge between a JDBC-Timestamp and the class * {@code PlainTimestamp}.</p> * * <p>If the system property &quot;net.time4j.sql.utc.conversion&quot; * is set to the value &quot;true&quot; then the conversion will NOT take * into account the system timezone anticipating that a SQL-DATE was * created without any timezone calculation on the server side, too. * That is more or less the case if UTC is the default timezone on the * application server. </p> * * <p>Example (UTC as default timezone):</p> * * <pre> * java.sql.Timestamp sqlValue = new java.sql.Timestamp(86401 * 1000); * sqlValue.setNanos(1); * PlainTimestamp ts = TemporalType.SQL_TIMESTAMP.translate(sqlValue); * System.out.println(ts); * // output: 1970-01-02T00:00:01,000000001 * </pre> * * @since 2.0 */ /*[deutsch] * <p>Br&uuml;cke zwischen einem JDBC-Timestamp und der Klasse * {@code PlainTimestamp}. </p> * * <p>Wenn die System-Property &quot;net.time4j.sql.utc.conversion&quot; * auf den Wert &quot;true&quot; gesetzt ist, dann ber&uuml;cksichtigt * die Konversion NICHT die Standardzeitzone des Systems und setzt somit * voraus, da&szlig; ein SQL-TIMESTAMP java-seitig auch ohne * Zeitzonenkalkulation erzeugt wurde. Das ist de facto der Fall, wenn * auf dem Application-Server UTC die Standardzeitzone ist. </p> * * <p>Beispiel (UTC als Standardzeitzone): </p> * * <pre> * java.sql.Timestamp sqlValue = new java.sql.Timestamp(86401 * 1000); * sqlValue.setNanos(1); * PlainTimestamp ts = TemporalType.SQL_TIMESTAMP.translate(sqlValue); * System.out.println(ts); * // Ausgabe: 1970-01-02T00:00:01,000000001 * </pre> * * @since 2.0 */ public static final TemporalType<java.sql.Timestamp, PlainTimestamp> SQL_TIMESTAMP = new SqlTimestampRule(); /** * <p>Bridge between a XML-date according to {@code xsd:date} * and the type {@code PlainDate}. </p> * * <p>Example: </p> * * <pre> * XMLGregorianCalendar xmlGregCal = * DatatypeFactory.newInstance().newXMLGregorianCalendarDate( * 2014, 2, 28, 60); // here with optional offset * PlainDate date = TemporalType.XML_DATE.translate(xmlGregCal); * System.out.println(date); * // output: 2014-02-28 * </pre> * * @since 2.0 */ /*[deutsch] * <p>Br&uuml;cke zwischen einem XML-Datum entsprechend * {@code xsd:date} und dem Typ {@code PlainDate}. </p> * * <p>Beispiel: </p> * * <pre> * XMLGregorianCalendar xmlGregCal = * DatatypeFactory.newInstance().newXMLGregorianCalendarDate( * 2014, 2, 28, 60); // hier mit optionalem Offset * PlainDate date = TemporalType.XML_DATE.translate(xmlGregCal); * System.out.println(date); * // Ausgabe: 2014-02-28 * </pre> * * @since 2.0 */ public static final TemporalType<XMLGregorianCalendar, PlainDate> XML_DATE = new XmlDateRule(); /** * <p>Bridge between a XML-time according to {@code xsd:time} * and the type {@code PlainTime}. </p> * * <p>Example: </p> * * <pre> * XMLGregorianCalendar xmlGregCal = * DatatypeFactory.newInstance().newXMLGregorianCalendarTime( * 21, 45, 30, 0, 60); // here with optional offset * PlainTime time = TemporalType.XML_TIME.translate(xmlGregCal); * System.out.println(time); * // output: T21:45:30 * </pre> * * @since 2.0 */ /*[deutsch] * <p>Br&uuml;cke zwischen einer XML-Uhrzeit entsprechend * {@code xsd:time} und dem Typ {@code PlainTime}. </p> * * <p>Beispiel: </p> * * <pre> * XMLGregorianCalendar xmlGregCal = * DatatypeFactory.newInstance().newXMLGregorianCalendarTime( * 21, 45, 30, 0, 60); // here with optional offset * PlainTime time = TemporalType.XML_TIME.translate(xmlGregCal); * System.out.println(time); * // Ausgabe: T21:45:30 * </pre> * * @since 2.0 */ public static final TemporalType<XMLGregorianCalendar, PlainTime> XML_TIME = new XmlTimeRule(); /** * <p>Bridge between a XML-timestamp according to {@code xsd:dateTime} * (without timezone-offset) and the type {@code PlainTimestamp}. </p> * * <p>Example: </p> * * <pre> * XMLGregorianCalendar xmlGregCal = * DatatypeFactory.newInstance().newXMLGregorianCalendar( * 2014, 2, 28, 14, 45, 30, 0, 60); * PlainTimestamp tsp = TemporalType.XML_DATE_TIME.translate(xmlGregCal); * System.out.println(tsp); * // output: 2014-02-28T14:45:30 * </pre> * * @since 2.0 */ /*[deutsch] * <p>Br&uuml;cke zwischen einem XML-Zeitstempel entsprechend * {@code xsd:dateTime} ohne Zeitzonen-Offset und dem Typ * {@code PlainTimestamp}. </p> * * <p>Beispiel: </p> * * <pre> * XMLGregorianCalendar xmlGregCal = * DatatypeFactory.newInstance().newXMLGregorianCalendar( * 2014, 2, 28, 14, 45, 30, 0, 60); * PlainTimestamp tsp = TemporalType.XML_DATE_TIME.translate(xmlGregCal); * System.out.println(tsp); * // Ausgabe: 2014-02-28T14:45:30 * </pre> * * @since 2.0 */ public static final TemporalType<XMLGregorianCalendar, PlainTimestamp> XML_DATE_TIME = new XmlDateTimeRule(); /** * <p>Bridge between a XML-timestamp according to {@code xsd:dateTime} * inclusive timezone-offset and the type {@code ZonalMoment}. </p> * * <p>Example: </p> * * <pre> * XMLGregorianCalendar xmlGregCal = * DatatypeFactory.newInstance().newXMLGregorianCalendar( * 2014, 2, 28, 14, 45, 30, 0, 60); * ZonalMoment zm = TemporalType.XML_DATE_TIME_OFFSET.translate(xmlGregCal); * System.out.println(zm.print(Iso8601Format.EXTENDED_DATE_TIME_OFFSET)); * // output: 2014-02-28T14:45:30+01:00 * </pre> * * @since 2.0 */ /*[deutsch] * <p>Br&uuml;cke zwischen einem XML-Zeitstempel entsprechend * {@code xsd:dateTime} inklusive Zeitzonen-Offset und dem Typ * {@code ZonalMoment}. </p> * * <p>Beispiel: </p> * * <pre> * XMLGregorianCalendar xmlGregCal = * DatatypeFactory.newInstance().newXMLGregorianCalendar( * 2014, 2, 28, 14, 45, 30, 0, 60); * ZonalMoment zm = TemporalType.XML_DATE_TIME_OFFSET.translate(xmlGregCal); * System.out.println(zm.print(Iso8601Format.EXTENDED_DATE_TIME_OFFSET)); * // Ausgabe: 2014-02-28T14:45:30+01:00 * </pre> * * @since 2.0 */ public static final TemporalType<XMLGregorianCalendar, ZonalMoment> XML_DATE_TIME_OFFSET = new XmlDateTimeOffsetRule(); /** * <p>Creates a new instance.</p> */ protected TemporalType() { super(); } /** * <p>Converts the external type to a type in Time4J. </p> * * @param source external object * @return translated Time4J-object * @throws ChronoException if conversion fails * @since 2.0 */ /*[deutsch] * <p>Konvertiert den externen Typ nach Time4J. </p> * * @param source external object * @return translated Time4J-object * @throws ChronoException if conversion fails * @since 2.0 */ public abstract T translate(S source); /** * <p>Converts the Time4J-type to an external type.</p> * * @param time4j Time4J-object * @return translated object of external type * @throws ChronoException if conversion fails * @since 2.0 */ /*[deutsch] * <p>Konvertiert den Time4J-Typ zu einem externen Typ.</p> * * @param time4j Time4J-object * @return translated object of external type * @throws ChronoException if conversion fails * @since 2.0 */ public abstract S from(T time4j); private static DatatypeFactory getXMLFactory() { try { return DatatypeFactory.newInstance(); } catch (DatatypeConfigurationException ex) { throw new ChronoException("XML-conversion not available.", ex); } } private static XMLGregorianCalendar toXML( ChronoDisplay tsp, int tz ) { PlainDate date = tsp.get(PlainDate.COMPONENT); int year = date.getYear(); int month = date.getMonth(); int dom = date.getDayOfMonth(); PlainTime time = tsp.get(PlainTime.COMPONENT); int hour = time.getHour(); int minute = time.getMinute(); int second = tsp.get(PlainTime.SECOND_OF_MINUTE).intValue(); int nano = time.getNanosecond(); DatatypeFactory factory = getXMLFactory(); if ((nano % MIO) == 0) { int millis = nano / MIO; return factory.newXMLGregorianCalendar( year, month, dom, hour, minute, second, millis, tz); } else { BigInteger y = BigInteger.valueOf(year); BigDecimal f = BigDecimal.valueOf(nano).setScale(9).divide(MRD_D); return factory.newXMLGregorianCalendar( y, month, dom, hour, minute, second, f, tz); } } private static class JavaUtilDateRule extends TemporalType<java.util.Date, Moment> { @Override public Moment translate(java.util.Date source) { long millis = source.getTime(); long seconds = MathUtils.floorDivide(millis, 1000); int nanos = MathUtils.floorModulo(millis, 1000) * MIO; return Moment.of(seconds, nanos, TimeScale.POSIX); } @Override public java.util.Date from(Moment target) { long posixTime = target.getPosixTime(); int fraction = target.getNanosecond(); long millis = MathUtils.safeAdd( MathUtils.safeMultiply(posixTime, 1000), fraction / MIO); return new java.util.Date(millis); } } private static class MillisSinceUnixRule extends TemporalType<Long, Moment> { @Override public Moment translate(Long source) { long millis = source.longValue(); long seconds = MathUtils.floorDivide(millis, 1000); int nanos = MathUtils.floorModulo(millis, 1000) * MIO; return Moment.of(seconds, nanos, TimeScale.POSIX); } @Override public Long from(Moment moment) { long posixTime = moment.getPosixTime(); int fraction = moment.getNanosecond(); return Long.valueOf( MathUtils.safeAdd( MathUtils.safeMultiply(posixTime, 1000), fraction / MIO)); } } private static class SqlDateRule extends TemporalType<java.sql.Date, PlainDate> { @Override public PlainDate translate(java.sql.Date source) { long millis = source.getTime(); // UTC zone if (!WITH_SQL_UTC_CONVERSION) { Moment unixTime = Moment.of( MathUtils.floorDivide(millis, 1000), TimeScale.POSIX); ZonalOffset offset = Timezone.ofSystem().getOffset(unixTime); millis += offset.getIntegralAmount() * 1000; } return PlainDate.axis().getCalendarSystem().transform( MathUtils.floorDivide(millis, 86400 * 1000) - 2 * 365 ); } @Override public java.sql.Date from(PlainDate date) { int year = date.getYear(); if ((year < 1900) || (year > 9999)) { throw new ChronoException( "SQL-Date is only defined in year range of 1900-9999."); } long millis = // localMillis MathUtils.safeMultiply( date.getDaysSinceUTC() + 2 * 365, 86400 * 1000); if (!WITH_SQL_UTC_CONVERSION) { ZonalOffset offset = Timezone.ofSystem().getOffset(date, PlainTime.MIN); millis -= offset.getIntegralAmount() * 1000; } return new java.sql.Date(millis); } } private static class SqlTimeRule extends TemporalType<java.sql.Time, PlainTime> { @Override public PlainTime translate(java.sql.Time source) { long millis = source.getTime(); // UTC zone if (!WITH_SQL_UTC_CONVERSION) { Moment unixTime = Moment.of( MathUtils.floorDivide(millis, 1000), TimeScale.POSIX); ZonalOffset offset = Timezone.ofSystem().getOffset(unixTime); millis += offset.getIntegralAmount() * 1000; } return PlainTime.MIN.with( PlainTime.MILLI_OF_DAY, MathUtils.floorModulo(millis, 86400 * 1000) ); } @Override public java.sql.Time from(PlainTime time) { long millis = // local millis time.get(PlainTime.MILLI_OF_DAY).intValue(); if (!WITH_SQL_UTC_CONVERSION) { ZonalOffset offset = Timezone.ofSystem().getOffset(UNIX_DATE, time); millis -= offset.getIntegralAmount() * 1000; } return new java.sql.Time(millis); } } private static class SqlTimestampRule extends TemporalType<java.sql.Timestamp, PlainTimestamp> { @Override public PlainTimestamp translate(java.sql.Timestamp source) { long millis = source.getTime(); // UTC zone if (!WITH_SQL_UTC_CONVERSION) { Moment unixTime = Moment.of( MathUtils.floorDivide(millis, 1000), TimeScale.POSIX); ZonalOffset offset = Timezone.ofSystem().getOffset(unixTime); millis += offset.getIntegralAmount() * 1000; } PlainDate date = PlainDate.of( MathUtils.floorDivide(millis, 86400 * 1000), EpochDays.UNIX); PlainTime time = PlainTime.createFromMillis( MathUtils.floorModulo(millis, 86400 * 1000)); PlainTimestamp ts = PlainTimestamp.of(date, time); return ts.with(PlainTime.NANO_OF_SECOND, source.getNanos()); } @Override public java.sql.Timestamp from(PlainTimestamp tsp) { long dateMillis = // local millis MathUtils.safeMultiply( tsp.getCalendarDate().getDaysSinceUTC() + 2 * 365, 86400 * 1000 ); long timeMillis = // local millis tsp.get(PlainTime.MILLI_OF_DAY).intValue(); if (!WITH_SQL_UTC_CONVERSION) { ZonalOffset offset = Timezone.ofSystem().getOffset(tsp, tsp); timeMillis -= offset.getIntegralAmount() * 1000; } java.sql.Timestamp ret = new java.sql.Timestamp( MathUtils.safeAdd(dateMillis, timeMillis)); ret.setNanos(tsp.get(PlainTime.NANO_OF_SECOND).intValue()); return ret; } } private static class XmlDateRule extends TemporalType<XMLGregorianCalendar, PlainDate> { @Override public PlainDate translate(XMLGregorianCalendar source) { BigInteger eon = source.getEon(); if (eon != null) { BigInteger bi = eon.abs(); if (bi.compareTo(MRD_I) >= 0) { throw new ChronoException( "Out of supported year range: " + source); } } int year = source.getYear(); int month = source.getMonth(); int dom = source.getDay(); if ( (year == DatatypeConstants.FIELD_UNDEFINED) || (month == DatatypeConstants.FIELD_UNDEFINED) || (dom == DatatypeConstants.FIELD_UNDEFINED) ) { throw new ChronoException("Missing date component: " + source); } else { return PlainDate.of(year, month, dom); } } @Override public XMLGregorianCalendar from(PlainDate date) { int year = date.getYear(); int month = date.getMonth(); int dom = date.getDayOfMonth(); DatatypeFactory factory = getXMLFactory(); return factory.newXMLGregorianCalendarDate( year, month, dom, DatatypeConstants.FIELD_UNDEFINED); } } private static class XmlTimeRule extends TemporalType<XMLGregorianCalendar, PlainTime> { @Override public PlainTime translate(XMLGregorianCalendar source) { int hour = source.getHour(); if (hour == DatatypeConstants.FIELD_UNDEFINED) { throw new ChronoException("Missing hour component: " + source); } int minute = source.getMinute(); if (minute == DatatypeConstants.FIELD_UNDEFINED) { minute = 0; } int second = source.getSecond(); if (second == DatatypeConstants.FIELD_UNDEFINED) { second = 0; } int nano = 0; BigDecimal fraction = source.getFractionalSecond(); if (fraction != null) { nano = fraction.movePointRight(9).intValue(); } return PlainTime.of(hour, minute, second, nano); } @Override public XMLGregorianCalendar from(PlainTime time) { int hour = time.getHour(); int minute = time.getMinute(); int second = time.getSecond(); int nano = time.getNanosecond(); DatatypeFactory factory = getXMLFactory(); int noTZ = DatatypeConstants.FIELD_UNDEFINED; if ((nano % MIO) == 0) { int millis = nano / MIO; return factory.newXMLGregorianCalendarTime( hour, minute, second, millis, noTZ); } else { BigDecimal f = BigDecimal.valueOf(nano).setScale(9).divide(MRD_D); return factory.newXMLGregorianCalendarTime( hour, minute, second, f, noTZ); } } } private static class XmlDateTimeRule extends TemporalType<XMLGregorianCalendar, PlainTimestamp> { @Override public PlainTimestamp translate(XMLGregorianCalendar source) { BigInteger eon = source.getEon(); if (eon != null) { BigInteger bi = eon.abs(); if (bi.compareTo(MRD_I) >= 0) { throw new ChronoException( "Out of supported year range: " + source); } } int year = source.getYear(); int month = source.getMonth(); int dom = source.getDay(); if ( (year == DatatypeConstants.FIELD_UNDEFINED) || (month == DatatypeConstants.FIELD_UNDEFINED) || (dom == DatatypeConstants.FIELD_UNDEFINED) ) { throw new ChronoException("Missing date component: " + source); } int hour = source.getHour(); if (hour == DatatypeConstants.FIELD_UNDEFINED) { throw new ChronoException("Missing hour component: " + source); } int minute = source.getMinute(); if (minute == DatatypeConstants.FIELD_UNDEFINED) { minute = 0; } int second = source.getSecond(); if (second == DatatypeConstants.FIELD_UNDEFINED) { second = 0; } int nano = 0; BigDecimal fraction = source.getFractionalSecond(); if (fraction != null) { nano = fraction.movePointRight(9).intValue(); } PlainTimestamp tsp = PlainTimestamp.of(year, month, dom, hour, minute, second); if (nano != 0) { tsp = tsp.with(PlainTime.NANO_OF_SECOND, nano); } return tsp; } @Override public XMLGregorianCalendar from(PlainTimestamp tsp) { return toXML(tsp, DatatypeConstants.FIELD_UNDEFINED); } } private static class XmlDateTimeOffsetRule extends TemporalType<XMLGregorianCalendar, ZonalMoment> { @Override public ZonalMoment translate(XMLGregorianCalendar source) { PlainTimestamp tsp = XML_DATE_TIME.translate(source); int offsetMins = source.getTimezone(); if (offsetMins == DatatypeConstants.FIELD_UNDEFINED) { throw new ChronoException("Missing timezone offset: " + source); } ZonalOffset offset = ZonalOffset.ofTotalSeconds(offsetMins * 60); return ZonalMoment.of(tsp, offset); } @Override public XMLGregorianCalendar from(ZonalMoment zm) { ZonalOffset offset = zm.getOffset(); int tz = offset.getIntegralAmount() / 60; try { return toXML(zm, tz); } catch (IllegalArgumentException iae) { if (zm.isLeapSecond()) { // some XML-implementations are not conform to XML-Schema ZonalMoment pm = zm.toMoment().minus(1, SI.SECONDS).inZonalView(offset); return toXML(pm, tz); } else { throw iae; } } } } }
package net.runelite.client.plugins.itemcharges; import java.awt.Color; import net.runelite.client.config.Config; import net.runelite.client.config.ConfigGroup; import net.runelite.client.config.ConfigItem; import net.runelite.client.config.ConfigSection; @ConfigGroup("itemCharge") public interface ItemChargeConfig extends Config { @ConfigSection( name = "Charge Settings", description = "Configuration for which charges should be displayed", position = 98 ) String chargesSection = "charges"; @ConfigSection( name = "Notification Settings", description = "Configuration for notifications", position = 99 ) String notificationSection = "notifications"; @ConfigItem( keyName = "veryLowWarningColor", name = "Very Low Warning Color", description = "The color of the overlay when charges are very low", position = 1 ) default Color veryLowWarningColor() { return Color.RED; } @ConfigItem( keyName = "lowWarningColor", name = "Low Warning Color", description = "The color of the overlay when charges are low", position = 2 ) default Color lowWarningolor() { return Color.YELLOW; } @ConfigItem( keyName = "veryLowWarning", name = "Very Low Warning", description = "The charge count for the very low warning color", position = 3 ) default int veryLowWarning() { return 1; } @ConfigItem( keyName = "lowWarning", name = "Low Warning", description = "The charge count for the low warning color", position = 4 ) default int lowWarning() { return 2; } @ConfigItem( keyName = "showTeleportCharges", name = "Show Teleport Charges", description = "Show teleport item charge counts", position = 5, section = chargesSection ) default boolean showTeleportCharges() { return true; } @ConfigItem( keyName = "showDodgyCount", name = "Dodgy Necklace Count", description = "Show Dodgy necklace charges", position = 6, section = chargesSection ) default boolean showDodgyCount() { return true; } @ConfigItem( keyName = "dodgyNotification", name = "Dodgy Necklace Notification", description = "Send a notification when a Dodgy necklace breaks", position = 7, section = notificationSection ) default boolean dodgyNotification() { return true; } @ConfigItem( keyName = "dodgyNecklace", name = "", description = "", hidden = true ) default int dodgyNecklace() { return -1; } @ConfigItem( keyName = "dodgyNecklace", name = "", description = "" ) void dodgyNecklace(int dodgyNecklace); @ConfigItem( keyName = "showImpCharges", name = "Show Imp-in-a-box charges", description = "Show Imp-in-a-box item charges", position = 8, section = chargesSection ) default boolean showImpCharges() { return true; } @ConfigItem( keyName = "showFungicideCharges", name = "Show Fungicide Charges", description = "Show Fungicide item charges", position = 9, section = chargesSection ) default boolean showFungicideCharges() { return true; } @ConfigItem( keyName = "showWateringCanCharges", name = "Show Watering Can Charges", description = "Show Watering can item charges", position = 10, section = chargesSection ) default boolean showWateringCanCharges() { return true; } @ConfigItem( keyName = "showWaterskinCharges", name = "Show Waterskin Charges", description = "Show Waterskin dose counts", position = 11, section = chargesSection ) default boolean showWaterskinCharges() { return true; } @ConfigItem( keyName = "showBellowCharges", name = "Show Bellows Charges", description = "Show Ogre bellows item charges", position = 12, section = chargesSection ) default boolean showBellowCharges() { return true; } @ConfigItem( keyName = "showBasketCharges", name = "Show Basket Charges", description = "Show Fruit basket item counts", position = 13, section = chargesSection ) default boolean showBasketCharges() { return true; } @ConfigItem( keyName = "showSackCharges", name = "Show Sack Charges", description = "Show Sack item counts", position = 14, section = chargesSection ) default boolean showSackCharges() { return true; } @ConfigItem( keyName = "showAbyssalBraceletCharges", name = "Show Abyssal Bracelet Charges", description = "Show Abyssal bracelet item charges", position = 15, section = chargesSection ) default boolean showAbyssalBraceletCharges() { return true; } @ConfigItem( keyName = "showAmuletOfChemistryCharges", name = "Show Amulet of Chemistry Charges", description = "Show Amulet of chemistry item charges", position = 16, section = chargesSection ) default boolean showAmuletOfChemistryCharges() { return true; } @ConfigItem( keyName = "amuletOfChemistry", name = "", description = "", hidden = true ) default int amuletOfChemistry() { return -1; } @ConfigItem( keyName = "amuletOfChemistry", name = "", description = "" ) void amuletOfChemistry(int amuletOfChemistry); @ConfigItem( keyName = "showAmuletOfBountyCharges", name = "Show Amulet of Bounty Charges", description = "Show Amulet of bounty item charges", position = 17, section = chargesSection ) default boolean showAmuletOfBountyCharges() { return true; } @ConfigItem( keyName = "amuletOfBounty", name = "", description = "", hidden = true ) default int amuletOfBounty() { return -1; } @ConfigItem( keyName = "amuletOfBounty", name = "", description = "" ) void amuletOfBounty(int amuletOfBounty); @ConfigItem( keyName = "recoilNotification", name = "Ring of Recoil Notification", description = "Send a notification when a Ring of recoil breaks", position = 18, section = notificationSection ) default boolean recoilNotification() { return false; } @ConfigItem( keyName = "showBindingNecklaceCharges", name = "Show Binding Necklace Charges", description = "Show Binding necklace item charges", position = 19, section = chargesSection ) default boolean showBindingNecklaceCharges() { return true; } @ConfigItem( keyName = "bindingNecklace", name = "", description = "", hidden = true ) default int bindingNecklace() { return -1; } @ConfigItem( keyName = "bindingNecklace", name = "", description = "" ) void bindingNecklace(int bindingNecklace); @ConfigItem( keyName = "bindingNotification", name = "Binding Necklace Notification", description = "Send a notification when a Binding necklace breaks", position = 20, section = notificationSection ) default boolean bindingNotification() { return true; } @ConfigItem( keyName = "showExplorerRingCharges", name = "Show Explorer's Ring Alch Charges", description = "Show Explorer's ring alchemy charges", position = 21, section = chargesSection ) default boolean showExplorerRingCharges() { return true; } @ConfigItem( keyName = "explorerRing", name = "", description = "", hidden = true ) default int explorerRing() { return -1; } @ConfigItem( keyName = "explorerRing", name = "", description = "" ) void explorerRing(int explorerRing); @ConfigItem( keyName = "showRingOfForgingCount", name = "Show Ring of Forging Charges", description = "Show Ring of forging item charges", position = 22, section = chargesSection ) default boolean showRingOfForgingCount() { return true; } @ConfigItem( keyName = "ringOfForging", name = "", description = "", hidden = true ) default int ringOfForging() { return -1; } @ConfigItem( keyName = "ringOfForging", name = "", description = "" ) void ringOfForging(int ringOfForging); @ConfigItem( keyName = "ringOfForgingNotification", name = "Ring of Forging Notification", description = "Send a notification when a Ring of forging breaks", position = 23, section = notificationSection ) default boolean ringOfForgingNotification() { return true; } @ConfigItem( keyName = "showInfoboxes", name = "Show Infoboxes", description = "Show an infobox with remaining charges for equipped items", position = 24 ) default boolean showInfoboxes() { return false; } @ConfigItem( keyName = "showPotionDoseCount", name = "Show Potion Doses", description = "Show remaining potion doses", position = 25, section = chargesSection ) default boolean showPotionDoseCount() { return false; } }
package net.runelite.client.plugins.itemcharges; import com.google.common.primitives.Ints; import com.google.inject.Provides; import java.awt.Color; import java.awt.image.BufferedImage; import java.util.EnumMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.inject.Inject; import lombok.extern.slf4j.Slf4j; import net.runelite.api.ChatMessageType; import net.runelite.api.Client; import net.runelite.api.EquipmentInventorySlot; import net.runelite.api.InventoryID; import net.runelite.api.Item; import net.runelite.api.ItemContainer; import net.runelite.api.ItemID; import net.runelite.api.Varbits; import net.runelite.api.events.ChatMessage; import net.runelite.api.events.ItemContainerChanged; import net.runelite.api.events.ScriptCallbackEvent; import net.runelite.api.events.VarbitChanged; import net.runelite.api.events.WidgetLoaded; import net.runelite.api.widgets.Widget; import net.runelite.api.widgets.WidgetID; import net.runelite.api.widgets.WidgetInfo; import net.runelite.client.Notifier; import net.runelite.client.callback.ClientThread; import net.runelite.client.config.ConfigManager; import net.runelite.client.eventbus.Subscribe; import net.runelite.client.events.ConfigChanged; import net.runelite.client.game.ItemManager; import net.runelite.client.plugins.Plugin; import net.runelite.client.plugins.PluginDescriptor; import net.runelite.client.ui.overlay.OverlayManager; import net.runelite.client.ui.overlay.infobox.InfoBoxManager; import net.runelite.client.util.Text; @PluginDescriptor( name = "Item Charges", description = "Show number of item charges remaining", tags = {"inventory", "notifications", "overlay"} ) @Slf4j public class ItemChargePlugin extends Plugin { private static final Pattern DODGY_CHECK_PATTERN = Pattern.compile( "Your dodgy necklace has (\\d+) charges? left\\."); private static final Pattern DODGY_PROTECT_PATTERN = Pattern.compile( "Your dodgy necklace protects you\\..*It has (\\d+) charges? left\\."); private static final Pattern DODGY_BREAK_PATTERN = Pattern.compile( "Your dodgy necklace protects you\\..*It then crumbles to dust\\."); private static final String RING_OF_RECOIL_BREAK_MESSAGE = "Your Ring of Recoil has shattered."; private static final Pattern BINDING_CHECK_PATTERN = Pattern.compile( "You have ([0-9]+|one) charges? left before your Binding necklace disintegrates\\."); private static final Pattern BINDING_USED_PATTERN = Pattern.compile( "You bind the temple's power into (mud|lava|steam|dust|smoke|mist) runes\\."); private static final String BINDING_BREAK_TEXT = "Your Binding necklace has disintegrated."; private static final Pattern RING_OF_FORGING_CHECK_PATTERN = Pattern.compile( "You can smelt ([0-9]+|one) more pieces? of iron ore before a ring melts\\."); private static final String RING_OF_FORGING_USED_TEXT = "You retrieve a bar of iron."; private static final String RING_OF_FORGING_BREAK_TEXT = "Your Ring of Forging has melted."; private static final String RING_OF_FORGING_VARROCK_PLATEBODY = "The Varrock platebody enabled you to smelt your next ore simultaneously."; private static final Pattern AMULET_OF_CHEMISTRY_CHECK_PATTERN = Pattern.compile( "Your amulet of chemistry has (\\d) charges? left\\." ); private static final Pattern AMULET_OF_CHEMISTRY_USED_PATTERN = Pattern.compile( "Your amulet of chemistry helps you create a \\d-dose potion\\. It has (\\d|one) charges? left\\." ); private static final Pattern AMULET_OF_CHEMISTRY_BREAK_PATTERN = Pattern.compile( "Your amulet of chemistry helps you create a \\d-dose potion\\. It then crumbles to dust\\." ); private static final Pattern AMULET_OF_BOUNTY_CHECK_PATTERN = Pattern.compile( "Your amulet of bounty has (\\d+) charges? left\\." ); private static final Pattern AMULET_OF_BOUNTY_USED_PATTERN = Pattern.compile( "Your amulet of bounty saves some seeds for you\\. It has (\\d) charges? left\\." ); private static final String AMULET_OF_BOUNTY_BREAK_TEXT = "Your amulet of bounty saves some seeds for you. It then crumbles to dust."; private static final Pattern CHRONICLE_ADD_PATTERN = Pattern.compile( "You add (?:\\d+|a single) charges? to your book\\. It now has (\\d+|one) charges?\\." ); private static final Pattern CHRONICLE_USE_AND_CHECK_PATTERN = Pattern.compile( "Your book has (\\d+) charges left\\." ); private static final String CHRONICLE_FULL_TEXT = "Your book is fully charged! It has 1,000 charges already."; private static final String CHRONICLE_ONE_CHARGE_TEXT = "You have one charge left in your book."; private static final String CHRONICLE_EMPTY_TEXT = "Your book has run out of charges."; private static final String CHRONICLE_NO_CHARGES_TEXT = "Your book does not have any charges. Purchase some Teleport Cards from Diango."; private static final Pattern BRACELET_OF_SLAUGHTER_ACTIVATE_PATTERN = Pattern.compile( "Your bracelet of slaughter prevents your slayer count from decreasing. (?:(?:It has (\\d{1,2}) charges? left)|(It then crumbles to dust))\\." ); private static final Pattern BRACELET_OF_SLAUGHTER_CHECK_PATTERN = Pattern.compile( "Your bracelet of slaughter has (\\d{1,2}) charges? left\\." ); private static final String BRACELET_OF_SLAUGHTER_BREAK_TEXT = "Your Bracelet of Slaughter has crumbled to dust."; private static final Pattern EXPEDITIOUS_BRACELET_ACTIVATE_PATTERN = Pattern.compile( "Your expeditious bracelet helps you progress your slayer (?:task )?faster. (?:(?:It has (\\d{1,2}) charges? left)|(It then crumbles to dust))\\." ); private static final Pattern EXPEDITIOUS_BRACELET_CHECK_PATTERN = Pattern.compile( "Your expeditious bracelet has (\\d{1,2}) charges? left\\." ); private static final String EXPEDITIOUS_BRACELET_BREAK_TEXT = "Your Expeditious Bracelet has crumbled to dust."; private static final int MAX_DODGY_CHARGES = 10; private static final int MAX_BINDING_CHARGES = 16; private static final int MAX_EXPLORER_RING_CHARGES = 30; private static final int MAX_RING_OF_FORGING_CHARGES = 140; private static final int MAX_AMULET_OF_CHEMISTRY_CHARGES = 5; private static final int MAX_AMULET_OF_BOUNTY_CHARGES = 10; private static final int MAX_SLAYER_BRACELET_CHARGES = 30; private int lastExplorerRingCharge = -1; @Inject private Client client; @Inject private ClientThread clientThread; @Inject private ConfigManager configManager; @Inject private OverlayManager overlayManager; @Inject private ItemChargeOverlay overlay; @Inject private ItemManager itemManager; @Inject private InfoBoxManager infoBoxManager; @Inject private Notifier notifier; @Inject private ItemChargeConfig config; // Limits destroy callback to once per tick private int lastCheckTick; private final Map<EquipmentInventorySlot, ItemChargeInfobox> infoboxes = new EnumMap<>(EquipmentInventorySlot.class); @Provides ItemChargeConfig getConfig(ConfigManager configManager) { return configManager.getConfig(ItemChargeConfig.class); } @Override protected void startUp() { overlayManager.add(overlay); } @Override protected void shutDown() throws Exception { overlayManager.remove(overlay); infoBoxManager.removeIf(ItemChargeInfobox.class::isInstance); infoboxes.clear(); lastCheckTick = -1; } @Subscribe public void onConfigChanged(ConfigChanged event) { if (!event.getGroup().equals(ItemChargeConfig.GROUP)) { return; } clientThread.invoke(this::updateInfoboxes); } @Subscribe public void onChatMessage(ChatMessage event) { if (event.getType() == ChatMessageType.GAMEMESSAGE || event.getType() == ChatMessageType.SPAM) { String message = Text.removeTags(event.getMessage()); Matcher dodgyCheckMatcher = DODGY_CHECK_PATTERN.matcher(message); Matcher dodgyProtectMatcher = DODGY_PROTECT_PATTERN.matcher(message); Matcher dodgyBreakMatcher = DODGY_BREAK_PATTERN.matcher(message); Matcher bindingNecklaceCheckMatcher = BINDING_CHECK_PATTERN.matcher(message); Matcher bindingNecklaceUsedMatcher = BINDING_USED_PATTERN.matcher(message); Matcher ringOfForgingCheckMatcher = RING_OF_FORGING_CHECK_PATTERN.matcher(message); Matcher amuletOfChemistryCheckMatcher = AMULET_OF_CHEMISTRY_CHECK_PATTERN.matcher(message); Matcher amuletOfChemistryUsedMatcher = AMULET_OF_CHEMISTRY_USED_PATTERN.matcher(message); Matcher amuletOfChemistryBreakMatcher = AMULET_OF_CHEMISTRY_BREAK_PATTERN.matcher(message); Matcher amuletOfBountyCheckMatcher = AMULET_OF_BOUNTY_CHECK_PATTERN.matcher(message); Matcher amuletOfBountyUsedMatcher = AMULET_OF_BOUNTY_USED_PATTERN.matcher(message); Matcher chronicleAddMatcher = CHRONICLE_ADD_PATTERN.matcher(message); Matcher chronicleUseAndCheckMatcher = CHRONICLE_USE_AND_CHECK_PATTERN.matcher(message); Matcher slaughterActivateMatcher = BRACELET_OF_SLAUGHTER_ACTIVATE_PATTERN.matcher(message); Matcher slaughterCheckMatcher = BRACELET_OF_SLAUGHTER_CHECK_PATTERN.matcher(message); Matcher expeditiousActivateMatcher = EXPEDITIOUS_BRACELET_ACTIVATE_PATTERN.matcher(message); Matcher expeditiousCheckMatcher = EXPEDITIOUS_BRACELET_CHECK_PATTERN.matcher(message); if (config.recoilNotification() && message.contains(RING_OF_RECOIL_BREAK_MESSAGE)) { notifier.notify("Your Ring of Recoil has shattered"); } else if (dodgyBreakMatcher.find()) { if (config.dodgyNotification()) { notifier.notify("Your dodgy necklace has crumbled to dust."); } updateDodgyNecklaceCharges(MAX_DODGY_CHARGES); } else if (dodgyCheckMatcher.find()) { updateDodgyNecklaceCharges(Integer.parseInt(dodgyCheckMatcher.group(1))); } else if (dodgyProtectMatcher.find()) { updateDodgyNecklaceCharges(Integer.parseInt(dodgyProtectMatcher.group(1))); } else if (amuletOfChemistryCheckMatcher.find()) { updateAmuletOfChemistryCharges(Integer.parseInt(amuletOfChemistryCheckMatcher.group(1))); } else if (amuletOfChemistryUsedMatcher.find()) { final String match = amuletOfChemistryUsedMatcher.group(1); int charges = 1; if (!match.equals("one")) { charges = Integer.parseInt(match); } updateAmuletOfChemistryCharges(charges); } else if (amuletOfChemistryBreakMatcher.find()) { updateAmuletOfChemistryCharges(MAX_AMULET_OF_CHEMISTRY_CHARGES); } else if (amuletOfBountyCheckMatcher.find()) { updateAmuletOfBountyCharges(Integer.parseInt(amuletOfBountyCheckMatcher.group(1))); } else if (amuletOfBountyUsedMatcher.find()) { updateAmuletOfBountyCharges(Integer.parseInt(amuletOfBountyUsedMatcher.group(1))); } else if (message.equals(AMULET_OF_BOUNTY_BREAK_TEXT)) { updateAmuletOfBountyCharges(MAX_AMULET_OF_BOUNTY_CHARGES); } else if (message.contains(BINDING_BREAK_TEXT)) { if (config.bindingNotification()) { notifier.notify(BINDING_BREAK_TEXT); } // This chat message triggers before the used message so add 1 to the max charges to ensure proper sync updateBindingNecklaceCharges(MAX_BINDING_CHARGES + 1); } else if (bindingNecklaceUsedMatcher.find()) { updateBindingNecklaceCharges(getItemCharges(ItemChargeConfig.KEY_BINDING_NECKLACE) - 1); } else if (bindingNecklaceCheckMatcher.find()) { final String match = bindingNecklaceCheckMatcher.group(1); int charges = 1; if (!match.equals("one")) { charges = Integer.parseInt(match); } updateBindingNecklaceCharges(charges); } else if (ringOfForgingCheckMatcher.find()) { final String match = ringOfForgingCheckMatcher.group(1); int charges = 1; if (!match.equals("one")) { charges = Integer.parseInt(match); } updateRingOfForgingCharges(charges); } else if (message.equals(RING_OF_FORGING_USED_TEXT) || message.equals(RING_OF_FORGING_VARROCK_PLATEBODY)) { final ItemContainer inventory = client.getItemContainer(InventoryID.INVENTORY); final ItemContainer equipment = client.getItemContainer(InventoryID.EQUIPMENT); // Determine if the player smelted with a Ring of Forging equipped. if (equipment == null) { return; } if (equipment.contains(ItemID.RING_OF_FORGING) && (message.equals(RING_OF_FORGING_USED_TEXT) || inventory.count(ItemID.IRON_ORE) > 1)) { int charges = Ints.constrainToRange(getItemCharges(ItemChargeConfig.KEY_RING_OF_FORGING) - 1, 0, MAX_RING_OF_FORGING_CHARGES); updateRingOfForgingCharges(charges); } } else if (message.equals(RING_OF_FORGING_BREAK_TEXT)) { if (config.ringOfForgingNotification()) { notifier.notify("Your ring of forging has melted."); } updateRingOfForgingCharges(MAX_RING_OF_FORGING_CHARGES); } else if (chronicleAddMatcher.find()) { final String match = chronicleAddMatcher.group(1); if (match.equals("one")) { setItemCharges(ItemChargeConfig.KEY_CHRONICLE, 1); } else { setItemCharges(ItemChargeConfig.KEY_CHRONICLE, Integer.parseInt(match)); } } else if (chronicleUseAndCheckMatcher.find()) { setItemCharges(ItemChargeConfig.KEY_CHRONICLE, Integer.parseInt(chronicleUseAndCheckMatcher.group(1))); } else if (message.equals(CHRONICLE_ONE_CHARGE_TEXT)) { setItemCharges(ItemChargeConfig.KEY_CHRONICLE, 1); } else if (message.equals(CHRONICLE_EMPTY_TEXT) || message.equals(CHRONICLE_NO_CHARGES_TEXT)) { setItemCharges(ItemChargeConfig.KEY_CHRONICLE, 0); } else if (message.equals(CHRONICLE_FULL_TEXT)) { setItemCharges(ItemChargeConfig.KEY_CHRONICLE, 1000); } else if (slaughterActivateMatcher.find()) { final String found = slaughterActivateMatcher.group(1); if (found == null) { updateBraceletOfSlaughterCharges(MAX_SLAYER_BRACELET_CHARGES); if (config.slaughterNotification()) { notifier.notify(BRACELET_OF_SLAUGHTER_BREAK_TEXT); } } else { updateBraceletOfSlaughterCharges(Integer.parseInt(found)); } } else if (slaughterCheckMatcher.find()) { updateBraceletOfSlaughterCharges(Integer.parseInt(slaughterCheckMatcher.group(1))); } else if (expeditiousActivateMatcher.find()) { final String found = expeditiousActivateMatcher.group(1); if (found == null) { updateExpeditiousBraceletCharges(MAX_SLAYER_BRACELET_CHARGES); if (config.expeditiousNotification()) { notifier.notify(EXPEDITIOUS_BRACELET_BREAK_TEXT); } } else { updateExpeditiousBraceletCharges(Integer.parseInt(found)); } } else if (expeditiousCheckMatcher.find()) { updateExpeditiousBraceletCharges(Integer.parseInt(expeditiousCheckMatcher.group(1))); } } } @Subscribe public void onItemContainerChanged(ItemContainerChanged event) { if (event.getContainerId() != InventoryID.EQUIPMENT.getId()) { return; } updateInfoboxes(); } @Subscribe private void onScriptCallbackEvent(ScriptCallbackEvent event) { if (!"destroyOnOpKey".equals(event.getEventName())) { return; } final int yesOption = client.getIntStack()[client.getIntStackSize() - 1]; if (yesOption == 1) { checkDestroyWidget(); } } @Subscribe private void onVarbitChanged(VarbitChanged event) { int explorerRingCharge = client.getVar(Varbits.EXPLORER_RING_ALCHS); if (lastExplorerRingCharge != explorerRingCharge) { lastExplorerRingCharge = explorerRingCharge; updateExplorerRingCharges(explorerRingCharge); } } @Subscribe public void onWidgetLoaded(WidgetLoaded widgetLoaded) { if (widgetLoaded.getGroupId() == WidgetID.DIALOG_SPRITE_GROUP_ID) { clientThread.invokeLater(() -> { Widget sprite = client.getWidget(WidgetInfo.DIALOG_SPRITE_SPRITE); if (sprite != null) { switch (sprite.getItemId()) { case ItemID.DODGY_NECKLACE: log.debug("Reset dodgy necklace"); updateDodgyNecklaceCharges(MAX_DODGY_CHARGES); break; case ItemID.RING_OF_FORGING: log.debug("Reset ring of forging"); updateRingOfForgingCharges(MAX_RING_OF_FORGING_CHARGES); break; case ItemID.AMULET_OF_CHEMISTRY: log.debug("Reset amulet of chemistry"); updateAmuletOfChemistryCharges(MAX_AMULET_OF_CHEMISTRY_CHARGES); break; case ItemID.BRACELET_OF_SLAUGHTER: log.debug("Reset bracelet of slaughter"); updateBraceletOfSlaughterCharges(MAX_SLAYER_BRACELET_CHARGES); break; case ItemID.EXPEDITIOUS_BRACELET: log.debug("Reset expeditious bracelet"); updateExpeditiousBraceletCharges(MAX_SLAYER_BRACELET_CHARGES); break; } } }); } } private void updateDodgyNecklaceCharges(final int value) { setItemCharges(ItemChargeConfig.KEY_DODGY_NECKLACE, value); updateInfoboxes(); } private void updateAmuletOfChemistryCharges(final int value) { setItemCharges(ItemChargeConfig.KEY_AMULET_OF_CHEMISTRY, value); updateInfoboxes(); } private void updateAmuletOfBountyCharges(final int value) { setItemCharges(ItemChargeConfig.KEY_AMULET_OF_BOUNTY, value); updateInfoboxes(); } private void updateBindingNecklaceCharges(final int value) { setItemCharges(ItemChargeConfig.KEY_BINDING_NECKLACE, value); updateInfoboxes(); } private void updateExplorerRingCharges(final int value) { // Note: Varbit counts upwards. We count down from the maximum charges. setItemCharges(ItemChargeConfig.KEY_EXPLORERS_RING, MAX_EXPLORER_RING_CHARGES - value); updateInfoboxes(); } private void updateRingOfForgingCharges(final int value) { setItemCharges(ItemChargeConfig.KEY_RING_OF_FORGING, value); updateInfoboxes(); } private void updateBraceletOfSlaughterCharges(final int value) { setItemCharges(ItemChargeConfig.KEY_BRACELET_OF_SLAUGHTER, value); updateInfoboxes(); } private void updateExpeditiousBraceletCharges(final int value) { setItemCharges(ItemChargeConfig.KEY_EXPEDITIOUS_BRACELET, value); updateInfoboxes(); } private void checkDestroyWidget() { final int currentTick = client.getTickCount(); if (lastCheckTick == currentTick) { return; } lastCheckTick = currentTick; final Widget widgetDestroyItemName = client.getWidget(WidgetInfo.DESTROY_ITEM_NAME); if (widgetDestroyItemName == null) { return; } if (widgetDestroyItemName.getText().equals("Binding necklace")) { log.debug("Reset binding necklace"); updateBindingNecklaceCharges(MAX_BINDING_CHARGES); } } private void updateInfoboxes() { final ItemContainer itemContainer = client.getItemContainer(InventoryID.EQUIPMENT); if (itemContainer == null) { return; } final Item[] items = itemContainer.getItems(); boolean showInfoboxes = config.showInfoboxes(); for (EquipmentInventorySlot slot : EquipmentInventorySlot.values()) { if (slot.getSlotIdx() >= items.length) { break; } Item i = items[slot.getSlotIdx()]; int id = i.getId(); ItemChargeType type = null; int charges = -1; final ItemWithCharge itemWithCharge = ItemWithCharge.findItem(id); if (itemWithCharge != null) { type = itemWithCharge.getType(); charges = itemWithCharge.getCharges(); } else { final ItemWithConfig itemWithConfig = ItemWithConfig.findItem(id); if (itemWithConfig != null) { type = itemWithConfig.getType(); charges = getItemCharges(itemWithConfig.getConfigKey()); } } boolean enabled = type != null && type.getEnabled().test(config); if (showInfoboxes && enabled && charges > 0) { ItemChargeInfobox infobox = infoboxes.get(slot); if (infobox != null) { if (infobox.getItem() == id) { if (infobox.getCount() == charges) { continue; } log.debug("Updating infobox count for {}", infobox); infobox.setCount(charges); continue; } log.debug("Rebuilding infobox {}", infobox); infoBoxManager.removeInfoBox(infobox); infoboxes.remove(slot); } final String name = itemManager.getItemComposition(id).getName(); final BufferedImage image = itemManager.getImage(id); infobox = new ItemChargeInfobox(this, image, name, charges, id, slot); infoBoxManager.addInfoBox(infobox); infoboxes.put(slot, infobox); } else { ItemChargeInfobox infobox = infoboxes.remove(slot); if (infobox != null) { log.debug("Removing infobox {}", infobox); infoBoxManager.removeInfoBox(infobox); } } } } int getItemCharges(String key) { // Migrate old non-profile configurations Integer i = configManager.getConfiguration(ItemChargeConfig.GROUP, key, Integer.class); if (i != null) { configManager.unsetConfiguration(ItemChargeConfig.GROUP, key); configManager.setRSProfileConfiguration(ItemChargeConfig.GROUP, key, i); return i; } i = configManager.getRSProfileConfiguration(ItemChargeConfig.GROUP, key, Integer.class); return i == null ? -1 : i; } private void setItemCharges(String key, int value) { configManager.setRSProfileConfiguration(ItemChargeConfig.GROUP, key, value); } Color getColor(int charges) { Color color = Color.WHITE; if (charges <= config.veryLowWarning()) { color = config.veryLowWarningColor(); } else if (charges <= config.lowWarning()) { color = config.lowWarningolor(); } return color; } }
package com.audiophile.t2m.text; import java.text.BreakIterator; import java.util.ArrayList; import java.util.Locale; public class Sentence { private SentenceType sentenceType; // Type of the sentence private int wordCount; // Number of words in sentence private float avgWordLength; // Average characters per word private int[] wordLength; // Length of every word private String[] words; // All words in the sentence as array public Sentence(String text) { analyse(text); System.out.println("Sentence: wordCount:" + this.wordCount + "; avgWordLength: " + avgWordLength + "; sentenceType: " + sentenceType); } /** * Analyses the sentence and calculates the meta data of the sentence * * @param text String The sentence as plain text */ private void analyse(String text) { // Breaking sentence into words BreakIterator iterator = BreakIterator.getWordInstance(Locale.GERMAN); iterator.setText(text); ArrayList<String> wordList = new ArrayList<>(text.length() / 6); // Avg word length in german is 5.7 int start = iterator.first(); for (int end = iterator.next(); end != BreakIterator.DONE; start = end, end = iterator.next()) { String word = text.substring(start, end).trim(); if (word.length() > 0) wordList.add(word); } wordList.trimToSize(); // Remove unused indices if initialCapacity is bigger than the actual needed one this.words = new String[wordList.size()]; this.wordLength = new int[wordList.size()]; // Convert ArrayList to array an calculate word lengths this.avgWordLength = 0; for (int i = 0; i < wordList.size(); i++) { this.words[i] = wordList.get(i); this.wordLength[i] = words[i].length(); this.avgWordLength += this.wordLength[i]; } this.wordCount = this.words.length; // Set number of words this.avgWordLength /= (float) this.wordCount; if (wordCount > 0) { // Define the sentence type by last word/character this.sentenceType = mapSentenceType(words[wordCount - 1]); // If mapping failed, try second last word (last word might be a quotation mark) if (sentenceType == null && wordCount > 1) { this.sentenceType = mapSentenceType(words[wordCount - 2]); if (sentenceType == null) this.sentenceType = SentenceType.Statement; } } } private SentenceType mapSentenceType(String character) { switch (character) { case "?": return SentenceType.Question; case "!": return SentenceType.Exclamation; case ".": case ":": case ";": return SentenceType.Statement; default: return null; } } public SentenceType getSentenceType() { return sentenceType; } public int getWordCount() { return wordCount; } public float getAvgWordLength() { return avgWordLength; } public int[] getWordLength() { return wordLength; } public String[] getWords() { return words; } /** * Type of a sentence, defined by its ending character * .|:|; = Statement * ? = Question * ! = Exclamation */ public enum SentenceType { Statement, Question, Exclamation } }
package com.eddysystems.eddy.engine; import com.eddysystems.eddy.EddyPlugin; import com.eddysystems.eddy.PreferencesProvider; import com.intellij.codeInsight.daemon.impl.ShowIntentionsPass; import com.intellij.codeInsight.intention.impl.IntentionHintComponent; import com.intellij.lang.ASTNode; import com.intellij.notification.Notification; import com.intellij.notification.NotificationType; import com.intellij.notification.Notifications; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.Result; import com.intellij.openapi.application.impl.LaterInvocator; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.TextRange; import com.intellij.psi.*; import com.intellij.psi.codeStyle.CodeStyleManager; import com.intellij.psi.impl.source.tree.LeafElement; import com.intellij.psi.impl.source.tree.RecursiveTreeElementVisitor; import com.intellij.psi.impl.source.tree.TreeElement; import com.intellij.util.SmartList; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import scala.Function2; import scala.Unit$; import scala.runtime.AbstractFunction1; import scala.runtime.AbstractFunction2; import scala.runtime.BoxedUnit; import scala.util.Try; import tarski.Environment.Env; import tarski.Memory; import tarski.Scores.Alt; import tarski.Tarski; import tarski.Tarski.ShowStmts; import tarski.Tokens; import tarski.Tokens.ShowFlags; import tarski.Tokens.Token; import tarski.Tokens.WhitespaceTok; import utility.Locations.Loc; import utility.Utility.Unchecked; import java.util.ArrayList; import java.util.List; import static com.eddysystems.eddy.engine.Utility.*; import static tarski.Tokens.abbrevShowFlags; import static tarski.Tokens.fullShowFlags; import static utility.Utility.unchecked; public class Eddy { final private Project project; final private Memory.Info base; final private Editor editor; final private Document document; public Editor getEditor() { return editor; } public PsiFile getFile() { final PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(document); assert file != null; return file; } public static class Input { final TextRange range; final List<Loc<Token>> input; final PsiElement place; final String before_text; Input(final TextRange range, final List<Loc<Token>> input, final PsiElement place, final String before_text) { this.range = range; this.input = input; this.place = place; this.before_text = before_text; } public String getText() { return before_text; } } // The results of the interpretation public static class Output { final private Eddy eddy; final public Input input; final public List<Alt<ShowStmts>> results; // Mutable field: which output we've selected. If we haven't explicitly selected something, offset < 0. private int selected = -1; Output(final Eddy eddy, final Input input, final List<Alt<ShowStmts>> results) { this.eddy = eddy; this.input = input; this.results = results; } static String format(final ShowStmts ss, final ShowFlags f) { return f.abbreviate() ? ss.abbrev() : ss.full(); } public String format(final int i, final ShowFlags f) { return format(results.get(i).x(),f); } public List<String> formats(final ShowFlags f, final boolean probs) { final List<String> fs = new ArrayList<String>(results.size()); for (final Alt<ShowStmts> a : results) fs.add(format(a.x(),f)); if (probs) { for (int i = 0; i < fs.size(); ++i) { fs.set(i, String.format("%f: %s", results.get(i).p(), fs.get(i))); } } return fs; } public String[] getResultSummary() { return formats(new ShowFlags(true,true), true).toArray(new String[results.size()]); } public boolean foundSomething() { return !results.isEmpty(); } // Did we find useful meanings, and are those meanings different from what's already there? public boolean shouldShowHint() { for (final Alt<ShowStmts> r : results) if (r.x().similar(input.input)) return false; // We found what's already there return !results.isEmpty(); } // Is there only one realistic option (or did the user explicitly select one)? public boolean single() { return results.size() == 1 || selected >= 0; } public boolean nextBestResult() { if (shouldShowHint() && results.size()>1) { selected = (Math.max(0,selected)+1)%results.size(); return true; } return false; } public boolean prevBestResult() { if (shouldShowHint() && results.size()>1) { selected = (Math.max(0,selected)+results.size()-1)%results.size(); return true; } return false; } public String bestTextAbbrev() { assert shouldShowHint(); return format(Math.max(0,selected),abbrevShowFlags()); } public void applySelected() { apply(Math.max(0,selected)); } public int autoApply() { // Automatically apply the best found result return rawApply(eddy.document,format(0,abbrevShowFlags())); } public boolean shouldAutoApply() { // check if we're confident enough to apply the best found result automatically double t = PreferencesProvider.getData().getNumericAutoApplyThreshold(); double f = PreferencesProvider.getData().getNumericAutoApplyFactor(); log("confidence based on t = " + t + ", f = " + f + ", " + results.size() + " results."); if (results.size() >= 1 && results.get(0).p() >= t) { if (results.size() == 1) return true; else return results.get(0).p()/results.get(1).p() > f; } return false; } public int rawApply(final @NotNull Document document, final @NotNull String code) { final int offsetDiff = code.length() - input.range.getLength(); document.replaceString(input.range.getStartOffset(), input.range.getEndOffset(), code); Memory.log(Memory.eddyAutoApply(eddy.base,Memory.now(),input.input,results,code)); return offsetDiff; } public void apply(final int index) { final String full = format(results.get(index).x(),fullShowFlags()); ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override public void run() { final Editor editor = eddy.editor; new WriteCommandAction(eddy.project, eddy.getFile()) { @Override public void run(@NotNull Result result) { final int newOffset = input.range.getEndOffset() + rawApply(eddy.document,full); editor.getCaretModel().moveToOffset(newOffset); PsiDocumentManager.getInstance(eddy.project).commitDocument(eddy.document); } }.execute(); } }); Memory.log(Memory.eddyApply(eddy.base,Memory.now(),input.input,results,index)); } public void logSuggestion(final @NotNull String suggestion) { Memory.log(Memory.eddySuggestion(eddy.base, Memory.now(), input.input, results, suggestion)).onComplete(new AbstractFunction1<Try<BoxedUnit>, Void>() { @Override public Void apply(Try<BoxedUnit> v) { final String title, msg; if (v.isSuccess()) { title = "Suggestion processed"; msg = "Thank you! Your suggestion will help improve eddy!"; } else { title = "Suggestion failed to send"; msg = "I'm sorry, your suggestion could not be recorded. Our servers could not be reached."; } Notifications.Bus.notify(new Notification("Eddy", title, msg, NotificationType.INFORMATION), eddy.project); return null; } }, scala.concurrent.ExecutionContext.Implicits$.MODULE$.global()); } } public static interface Take { // return true if we're done absorbing output, false if more is desired public boolean take(Output output); } public Eddy(@NotNull final Project project, final Editor editor) { this.project = project; this.editor = editor; this.document = editor.getDocument(); this.base = Memory.basics(EddyPlugin.installKey(), EddyPlugin.getVersion() + " - " + EddyPlugin.getBuild(), project.getName()); } private static class Skip extends Exception { public Skip(final String s) { super(s); } } public static class PsiStructureException extends RuntimeException { public PsiStructureException(final String s) { super(s); } } // Find the previous or immediately enclosing element (which may be null if there's no parent) private static @Nullable PsiElement previous(final PsiElement e) throws Skip { PsiElement p = e.getPrevSibling(); if (p != null) return p; return e.getParent(); } // Trim a range to not include whitespace private static TextRange trim(final Document doc, final TextRange r) { final int lo = r.getStartOffset(); final String s = doc.getText(r); final String t = s.trim(); final int st = s.indexOf(t); return new TextRange(lo+st,lo+st+t.length()); } private static @NotNull PsiCodeBlock codeBlockAbove(PsiElement e) throws Skip { for (;;) { if (e == null) throw new Skip("No enclosing code block found"); if (e instanceof PsiCodeBlock) return (PsiCodeBlock)e; e = e.getParent(); } } private static @NotNull PsiElement stmtsAbove(PsiElement e) throws Skip { for (;;) { if (e == null) throw new Skip("No enclosing statements found"); if (e instanceof PsiCodeBlock || e instanceof PsiStatement) return e; e = e.getParent(); } } // Find the smallest consecutive sequence of statements and EOL comments that contains the given range. // 1. Starting at elem, go up to find the nearest enclosing code block. // 2. Descend to the smallest child that contains the whole trimmed range. // 3. Go up to the nearest enclosing statement or code block. // 4. If we're at a code block, return the list of children intersecting the line. // 5. Otherwise, return whatever we're at. private static List<PsiElement> elementsContaining(final Document doc, TextRange range, PsiElement e) throws Skip { // Trim whitespace off both ends of range range = trim(doc,range); // Go up to the nearest enclosing code block e = codeBlockAbove(e); // Descend to the smallest child of e that contains the whole (trimmed) range outer: for (;;) { for (final PsiElement kid : e.getChildren()) if (kid.getTextRange().contains(range)) { e = kid; continue outer; } break; } // Go back up to find a statement or code block e = stmtsAbove(e); // Collect results final List<PsiElement> results = new SmartList<PsiElement>(); if (e instanceof PsiCodeBlock) { // We're a code block, so return only those children intersecting the line. // Also ignore the first and last children, which are left and right braces. final PsiElement[] block = e.getChildren(); int lo = 1, hi = block.length-1; while (lo < hi && !block[lo ].getTextRange().intersects(range)) lo++; while (lo < hi && !block[hi-1].getTextRange().intersects(range)) hi for (int i=lo;i<hi;i++) results.add(block[i]); } else { // Otherwise, return a singleton list results.add(e); } return results; } // Should we expand an element or leave it atomic? private static boolean expand(final TreeElement e, final TextRange range, final int cursor) { // Never expand leaves if (e instanceof LeafElement) return false; // Otherwise, expand or not based on psi final @NotNull PsiElement psi = e.getPsi(); final TextRange r = psi.getTextRange(); // Expand blocks if the cursor is strictly inside if (psi instanceof PsiCodeBlock) { // Check if we're strictly inside. Note that r.contains(pos) is wrong here. // |{} - r 0 2, pos 0, not inside // {|} - r 0 2, pos 1, inside // {}| - r 0 2, pos 2, not inside return r.getStartOffset() < cursor && cursor < r.getEndOffset(); } // Expand statements if they overlap our line if (psi instanceof PsiStatement) return r.intersects(range); // Expand everything else return true; } public Input input() throws Skip { log("processing eddy..."); // Determine where we are final int cursor = editor.getCaretModel().getCurrentCaret().getOffset(); final int line = document.getLineNumber(cursor); final TextRange range = TextRange.create(document.getLineStartOffset(line), document.getLineEndOffset(line)); log(" processing line " + line + ": " + document.getText(range)); // Find relevant statements and comments final List<PsiElement> elems = elementsContaining(document,range,getFile().findElementAt(cursor)); if (elems.isEmpty()) throw new Skip("Empty statement list"); final PsiElement place = previous(elems.get(0)); if (place == null) throw new PsiStructureException("previous(" + elems.get(0) + ") == null"); // Walk all relevant elements, collecting leaves and atomic code blocks. // We walk on AST instead of Psi to get down to the token level. final List<Loc<Token>> tokens = new ArrayList<Loc<Token>>(); final RecursiveTreeElementVisitor V = new RecursiveTreeElementVisitor() { @Override protected boolean visitNode(final TreeElement e) { if (expand(e,range,cursor)) return true; tokens.add(Tokenizer.psiToTok(e)); return false; } }; for (final PsiElement elem : elems) { final ASTNode node = elem.getNode(); assert node instanceof TreeElement : "Bad AST node "+node+" for element "+elem; ((TreeElement)node).acceptTree(V); } // Trim whitespace at the ends of the token stream while (!tokens.isEmpty() && tokens.get(0).x() instanceof WhitespaceTok) tokens.remove(0); while (!tokens.isEmpty() && tokens.get(tokens.size()-1).x() instanceof WhitespaceTok) tokens.remove(tokens.size()-1); if (tokens.isEmpty()) throw new Skip("No tokens"); // Compute range to be replaced. We rely on !tokens.isEmpty final TextRange trim = Tokenizer.range(tokens.get(0)).union(Tokenizer.range(tokens.get(tokens.size()-1))); final String before = document.getText(trim); log(" before: " + before.replaceAll("[\n\t ]+", " ")); return new Input(trim,tokens,place,before); } public Env env(final Input input, final int lastEdit) { return EddyPlugin.getInstance(project).getEnv().getLocalEnvironment(input.place, lastEdit); } private void updateIntentions() { if (!ApplicationManager.getApplication().isHeadlessEnvironment()) { LaterInvocator.invokeLater(new Runnable() { @Override public void run() { final PsiFile file = getFile(); ShowIntentionsPass.IntentionsInfo intentions = new ShowIntentionsPass.IntentionsInfo(); ShowIntentionsPass.getActionsToShow(editor, file, intentions, -1); if (!intentions.isEmpty()) { try { IntentionHintComponent.showIntentionHint(project, file, editor, intentions, false); } catch (final NullPointerException e) { // Log and ignore log("updateIntentions: Can't show hint due to NullPointerException"); } } } }, project.getDisposed()); } } public void process(final @NotNull Editor editor, final int lastEdit, final Take takeoutput) { // Use mutable variables so that we log more if an exception is thrown partway through class Helper { final double start = Memory.now(); Input input; List<Alt<ShowStmts>> results; List<Double> delays = new ArrayList<Double>(4); Throwable error; void compute(final Env env) { if (Thread.currentThread().isInterrupted()) throw new ThreadDeath(); final Function2<String,ShowFlags,String> format = new AbstractFunction2<String,ShowFlags,String>() { @Override public String apply(final String sh, final ShowFlags f) { return reformat(input.place,sh,f); } }; final long startTime = System.nanoTime(); final Tarski.Take take = new Tarski.Take() { @Override public boolean take(final List<Alt<ShowStmts>> rs) { results = rs; double delay = (System.nanoTime() - startTime)/1e9; delays.add(delay); Eddy.Output output = new Output(Eddy.this,input,results); if (isDebug()) System.out.println(String.format("output %.3fs: ", delay) + logString(output.formats(abbrevShowFlags(),true))); updateIntentions(); return takeoutput.take(output); } }; Tarski.fixTake(input.input,env,format,take); } void unsafe() { try { input = Eddy.this.input(); compute(env(input,lastEdit)); } catch (Skip s) { // ignore skipped lines log("skipping: " + s.getMessage()); } } void safe() { try { if (isDebug()) // Run outside try so that we can see inside exceptions unchecked(new Unchecked<Unit$>() { @Override public Unit$ apply() { unsafe(); return Unit$.MODULE$; }}); else try { unsafe(); } catch (final Throwable e) { error = e; if (!(e instanceof ThreadDeath)) logError("process()",e); // Log everything except for ThreadDeath, which happens all the time. if (e instanceof Error && !(e instanceof AssertionError)) throw (Error)e; // Rethrow most kinds of Errors } } finally { Memory.log(Memory.eddyProcess(base,start, input==null ? null : input.input, results, delays).error(error)); } } } new Helper().safe(); } // The string should be a single syntactically valid statement private String reformat(final PsiElement place, final @NotNull String show, final ShowFlags f) { final CodeStyleManager csm = CodeStyleManager.getInstance(project); final PsiElementFactory ef = JavaPsiFacade.getElementFactory(project); final String blockText = '{' + show + "\n}"; PsiCodeBlock block = ef.createCodeBlockFromText(blockText,place); block = (PsiCodeBlock)csm.reformat(block,true); // strip whitespace at the beginning and end of the block PsiElement elem = block.getFirstBodyElement(); // skip whitespace at the beginning of the block if (elem instanceof PsiWhiteSpace) elem = elem.getNextSibling(); String result = ""; while (elem != null && elem != block.getRBrace()) { if (elem instanceof PsiWhiteSpace && elem.getNextSibling() == block.getRBrace()) // don't believe IntelliJ, this is important! break; result += elem.getText(); elem = elem.getNextSibling(); } return result; } }
package com.eu.controller; import cn.jiguang.common.ClientConfig; import cn.jpush.api.JPushClient; import cn.jpush.api.push.PushResult; import cn.jpush.api.push.model.Platform; import cn.jpush.api.push.model.PushPayload; import cn.jpush.api.push.model.audience.Audience; import cn.jpush.api.push.model.notification.AndroidNotification; import cn.jpush.api.push.model.notification.IosNotification; import cn.jpush.api.push.model.notification.Notification; import cn.jpush.api.push.model.notification.PlatformNotification; import com.eu.mapper.ActivitynotificationMapper; import com.eu.mapper.CommunityauthorityMapper; import com.eu.mapper.CommunitynotificationMapper; import com.eu.mapper.ParticipateactivityMapper; import com.eu.pojo.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.List; @Controller @RequestMapping("/push") public class PushController { @Autowired private CommunitynotificationMapper communitynotificationMapper; @Autowired private ActivitynotificationMapper activitynotificationMapper; @Autowired private ParticipateactivityMapper participateactivityMapper; @Autowired private CommunityauthorityMapper communityauthorityMapper; private static String masterSecret = "507fa5d70928e7a037ab22cd"; private static String appKey = "7dd9d0f83f93c23e2c295dc0"; /** * * @param alert * @param avid ID * @return */ @RequestMapping("/activitytagpush") @ResponseBody public RequestResult pushNotificationByTag(String alert,int avid,String avname) { JPushClient jpushClient = new JPushClient(masterSecret, appKey, null, ClientConfig.getInstance()); String pushtag = "av" + avid; Notification notification = Notification.newBuilder(). addPlatformNotification(IosNotification.newBuilder() .setAlert(alert) .incrBadge(1) .build() ) .addPlatformNotification(AndroidNotification.alert(alert)).build(); // For push, all you need do is to build PushPayload object. PushPayload payload = PushPayload.newBuilder() .setPlatform(Platform.android_ios()) .setAudience(Audience.tag(pushtag)) .setNotification(notification).build(); try { jpushClient.sendPush(payload); } catch (Exception e) { return new RequestResult(500, e.getMessage(), null); } ParticipateactivityExample example = new ParticipateactivityExample(); ParticipateactivityExample.Criteria criteria = example.createCriteria(); criteria.andAvidEqualTo(avid); List<Participateactivity> participateactivityList = participateactivityMapper.selectByExample(example); Activitynotification activitynotification = new Activitynotification(); activitynotification.setMsg(alert); activitynotification.setSendtime(new Date()); activitynotification.setAvid(avid); activitynotification.setSender(avname); for(Participateactivity participateactivity:participateactivityList){ activitynotification.setUid(participateactivity.getUid()); activitynotificationMapper.insert(activitynotification); } return new RequestResult(200, "OK", null); } /** * * @param alert * @param cmid ID * @return */ @RequestMapping("/communitytagpush") @ResponseBody public RequestResult pushCommunityNotificationByTag(String alert,int cmid,String cmname) { JPushClient jpushClient = new JPushClient(masterSecret, appKey, null, ClientConfig.getInstance()); String pushtag = "cm" + cmid; // For push, all you need do is to build PushPayload object. PushPayload payload = PushPayload.newBuilder() .setPlatform(Platform.android_ios()) .setAudience(Audience.tag(pushtag)) .setNotification(Notification.alert(alert)).build(); try { jpushClient.sendPush(payload); } catch (Exception e) { return new RequestResult(500, e.getMessage(), null); } CommunityauthorityExample example = new CommunityauthorityExample(); CommunityauthorityExample.Criteria criteria = example.createCriteria(); criteria.andCmidEqualTo(cmid); List<Communityauthority> communityauthorities = communityauthorityMapper.selectByExample(example); Communitynotification communitynotification = new Communitynotification(); communitynotification.setMsg(alert); communitynotification.setSendtime(new Date()); communitynotification.setCmid(cmid); communitynotification.setSender(cmname); for(Communityauthority communityauthority:communityauthorities){ communitynotification.setUid(communityauthority.getUid()); communitynotificationMapper.insert(communitynotification); } return new RequestResult(200, "OK", null); } /** * * @param alias ID ID , * @param alert * @param cmid ID * @return */ @RequestMapping("/communityaliaspush") @ResponseBody public RequestResult pushNotificationByAlias(String alias,String alert,int cmid,String cmname){ Collection<String> aliases = new ArrayList<>(); String[] aliasarray = alias.split(","); for (String uid:aliasarray){ aliases.add(uid); } JPushClient jPushClient = new JPushClient(masterSecret,appKey); PushPayload pushPayload = PushPayload.newBuilder() .setPlatform(Platform.android_ios()) .setAudience(Audience.alias(aliases)) .setNotification(Notification.alert(alert)).build(); try { jPushClient.sendPush(pushPayload); }catch (Exception e){ return new RequestResult(500,e.getMessage(),null); } Communitynotification communitynotification = new Communitynotification(); communitynotification.setMsg(alert); communitynotification.setSendtime(new Date()); communitynotification.setCmid(cmid); communitynotification.setSender(cmname); for (String uid:aliases){ communitynotification.setUid(Long.parseLong(uid)); communitynotificationMapper.insert(communitynotification); } return new RequestResult(200,"OK",null); } }
// ModuleDirectory.java package ed.appserver; import java.io.*; import java.util.*; import ed.js.*; import ed.js.engine.*; public class ModuleDirectory extends JSObjectLame implements JSLibrary { public ModuleDirectory( String root , String name , AppContext context , Scope scope ){ this( new File( Module._base , root ) , name , context , scope ); } public ModuleDirectory( File root , String name , AppContext context , Scope scope ){ _root = root; _name = name; _context = context; _scope = scope; if ( ! _root.exists() ){ _root.mkdirs(); if ( ! _root.exists() ) throw new RuntimeException( "modules directory [" + _root + "] does not exist" ); } } public File getRoot(){ return _root; } public synchronized Module getModule( String name ){ Module m = _modules.get( name ); if ( m != null ) return m; final File moddir = new File( _root , name ); m = new Module( moddir , _name + "." + name , true ); _modules.put( name , m ); return m; } public synchronized JSFileLibrary getJSFileLibrary( String name ){ JSFileLibrary lib = _libraries.get( name ); if ( lib != null ) return lib; Module m = getModule( name ); lib = m.getLibrary( getDesiredVersion( name ) , _context , _scope , true ); System.err.println( "created JSFileLibrary : " + name ); _libraries.put( name , lib ); return lib; } public Object get( Object n ){ return getJSFileLibrary( n.toString() ); } public boolean isLoaded( String name ){ return _modules.containsKey( name ); } public String getDesiredVersion( String name ){ if ( _scope != null ) return _getDesiredVersion( _scope , name ); if ( _context != null ) return _getDesiredVersion( _context._scope , name ); // its very important this not call getScope(). that would cause an inf. loop return null; } String _getDesiredVersion( Scope s , String name ){ return AppContext.getVersionForLibrary( s , name ); } public Object getFromPath( String path , boolean evalToFunction ){ while ( path.startsWith( "/" ) ) path = path.substring(1); int idx = path.indexOf( "/" ); final String libName; final String next; if ( idx > 0 ){ libName = path.substring( 0 , idx ); next = path.substring( idx + 1 ); } else { libName = path; next = null; } JSFileLibrary lib = getJSFileLibrary( libName ); if ( next == null ) return lib; return lib.getFromPath( next , evalToFunction ); } final String _name; final File _root; final AppContext _context; final Scope _scope; final Map<String,Module> _modules = new HashMap<String,Module>(); final Map<String,JSFileLibrary> _libraries = new HashMap<String,JSFileLibrary>(); }
package com.fsck.k9.activity; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.EnumMap; import java.util.Iterator; import java.util.List; import java.util.Map; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences.Editor; import android.graphics.Color; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.style.AbsoluteSizeSpan; import android.text.style.ForegroundColorSpan; import android.text.style.StyleSpan; import android.util.Log; import android.util.TypedValue; import android.view.GestureDetector; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.BaseAdapter; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.view.ActionMode; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import com.actionbarsherlock.view.Window; import com.fsck.k9.Account; import com.fsck.k9.Account.SortType; import com.fsck.k9.AccountStats; import com.fsck.k9.FontSizes; import com.fsck.k9.K9; import com.fsck.k9.Preferences; import com.fsck.k9.R; import com.fsck.k9.SearchSpecification; import com.fsck.k9.activity.setup.AccountSettings; import com.fsck.k9.activity.setup.FolderSettings; import com.fsck.k9.activity.setup.Prefs; import com.fsck.k9.controller.MessagingController; import com.fsck.k9.controller.MessagingListener; import com.fsck.k9.helper.MessageHelper; import com.fsck.k9.helper.Utility; import com.fsck.k9.mail.Flag; import com.fsck.k9.mail.Folder; import com.fsck.k9.mail.Message; import com.fsck.k9.mail.store.LocalStore; import com.fsck.k9.mail.store.LocalStore.LocalFolder; import com.fsck.k9.mail.store.LocalStore.LocalMessage; import com.fsck.k9.mail.store.StorageManager; /** * MessageList is the primary user interface for the program. This Activity * shows a list of messages. * From this Activity the user can perform all standard message operations. */ public class MessageList extends K9ListActivity implements OnItemClickListener { /** * Reverses the result of a {@link Comparator}. * * @param <T> */ public static class ReverseComparator<T> implements Comparator<T> { private Comparator<T> mDelegate; /** * @param delegate * Never <code>null</code>. */ public ReverseComparator(final Comparator<T> delegate) { mDelegate = delegate; } @Override public int compare(final T object1, final T object2) { // arg1 & 2 are mixed up, this is done on purpose return mDelegate.compare(object2, object1); } } /** * Chains comparator to find a non-0 result. * * @param <T> */ public static class ComparatorChain<T> implements Comparator<T> { private List<Comparator<T>> mChain; /** * @param chain * Comparator chain. Never <code>null</code>. */ public ComparatorChain(final List<Comparator<T>> chain) { mChain = chain; } @Override public int compare(T object1, T object2) { int result = 0; for (final Comparator<T> comparator : mChain) { result = comparator.compare(object1, object2); if (result != 0) { break; } } return result; } } public static class AttachmentComparator implements Comparator<MessageInfoHolder> { @Override public int compare(MessageInfoHolder object1, MessageInfoHolder object2) { return (object1.message.hasAttachments() ? 0 : 1) - (object2.message.hasAttachments() ? 0 : 1); } } public static class FlaggedComparator implements Comparator<MessageInfoHolder> { @Override public int compare(MessageInfoHolder object1, MessageInfoHolder object2) { return (object1.flagged ? 0 : 1) - (object2.flagged ? 0 : 1); } } public static class UnreadComparator implements Comparator<MessageInfoHolder> { @Override public int compare(MessageInfoHolder object1, MessageInfoHolder object2) { return (object1.read ? 1 : 0) - (object2.read ? 1 : 0); } } public static class SenderComparator implements Comparator<MessageInfoHolder> { @Override public int compare(MessageInfoHolder object1, MessageInfoHolder object2) { return object1.compareCounterparty.toLowerCase().compareTo(object2.compareCounterparty.toLowerCase()); } } public static class DateComparator implements Comparator<MessageInfoHolder> { @Override public int compare(MessageInfoHolder object1, MessageInfoHolder object2) { return object1.compareDate.compareTo(object2.compareDate); } } public static class ArrivalComparator implements Comparator<MessageInfoHolder> { @Override public int compare(MessageInfoHolder object1, MessageInfoHolder object2) { return object1.compareArrival.compareTo(object2.compareArrival); } } public static class SubjectComparator implements Comparator<MessageInfoHolder> { @Override public int compare(MessageInfoHolder arg0, MessageInfoHolder arg1) { // XXX doesn't respect the Comparator contract since it alters the compared object if (arg0.compareSubject == null) { arg0.compareSubject = Utility.stripSubject(arg0.message.getSubject()); } if (arg1.compareSubject == null) { arg1.compareSubject = Utility.stripSubject(arg1.message.getSubject()); } return arg0.compareSubject.compareToIgnoreCase(arg1.compareSubject); } } /** * Immutable empty {@link Message} array */ private static final Message[] EMPTY_MESSAGE_ARRAY = new Message[0]; private static final int DIALOG_MARK_ALL_AS_READ = 1; private static final int ACTIVITY_CHOOSE_FOLDER_MOVE = 1; private static final int ACTIVITY_CHOOSE_FOLDER_COPY = 2; private static final String EXTRA_ACCOUNT = "account"; private static final String EXTRA_FOLDER = "folder"; private static final String EXTRA_QUERY = "query"; private static final String EXTRA_QUERY_FLAGS = "queryFlags"; private static final String EXTRA_FORBIDDEN_FLAGS = "forbiddenFlags"; private static final String EXTRA_INTEGRATE = "integrate"; private static final String EXTRA_ACCOUNT_UUIDS = "accountUuids"; private static final String EXTRA_FOLDER_NAMES = "folderNames"; private static final String EXTRA_TITLE = "title"; private static final String EXTRA_LIST_POSITION = "listPosition"; private static final String EXTRA_RETURN_FROM_MESSAGE_VIEW = "returnFromMessageView"; /** * Maps a {@link SortType} to a {@link Comparator} implementation. */ private static final Map<SortType, Comparator<MessageInfoHolder>> SORT_COMPARATORS; static { // fill the mapping at class time loading final Map<SortType, Comparator<MessageInfoHolder>> map = new EnumMap<SortType, Comparator<MessageInfoHolder>>(SortType.class); map.put(SortType.SORT_ATTACHMENT, new AttachmentComparator()); map.put(SortType.SORT_DATE, new DateComparator()); map.put(SortType.SORT_ARRIVAL, new ArrivalComparator()); map.put(SortType.SORT_FLAGGED, new FlaggedComparator()); map.put(SortType.SORT_SENDER, new SenderComparator()); map.put(SortType.SORT_SUBJECT, new SubjectComparator()); map.put(SortType.SORT_UNREAD, new UnreadComparator()); // make it immutable to prevent accidental alteration (content is immutable already) SORT_COMPARATORS = Collections.unmodifiableMap(map); } private ListView mListView; private int mPreviewLines = 0; private MessageListAdapter mAdapter; private View mFooterView; private FolderInfoHolder mCurrentFolder; private LayoutInflater mInflater; private MessagingController mController; private Account mAccount; private int mUnreadMessageCount = 0; /** * Stores the name of the folder that we want to open as soon as possible * after load. */ private String mFolderName; /** * If we're doing a search, this contains the query string. */ private String mQueryString; private Flag[] mQueryFlags = null; private Flag[] mForbiddenFlags = null; private boolean mIntegrate = false; private String[] mAccountUuids = null; private String[] mFolderNames = null; private String mTitle; private MessageListHandler mHandler = new MessageListHandler(); private SortType mSortType = SortType.SORT_DATE; private boolean mSortAscending = true; private boolean mSortDateAscending = false; private boolean mStars = true; private boolean mCheckboxes = true; private int mSelectedCount = 0; private FontSizes mFontSizes = K9.getFontSizes(); private MenuItem mRefreshMenuItem; private ActionBar mActionBar; private ActionMode mActionMode; private View mActionBarProgressView; private Bundle mState = null; /** * Relevant messages for the current context when we have to remember the * chosen messages between user interactions (eg. Selecting a folder for * move operation) */ private List<MessageInfoHolder> mActiveMessages; private Context context; /* package visibility for faster inner class access */ MessageHelper mMessageHelper = MessageHelper.getInstance(this); private StorageManager.StorageListener mStorageListener = new StorageListenerImplementation(); private TextView mActionBarTitle; private TextView mActionBarSubTitle; private TextView mActionBarUnread; private final class StorageListenerImplementation implements StorageManager.StorageListener { @Override public void onUnmount(String providerId) { if (mAccount != null && providerId.equals(mAccount.getLocalStorageProviderId())) { runOnUiThread(new Runnable() { @Override public void run() { onAccountUnavailable(); } }); } } @Override public void onMount(String providerId) { // no-op } } /** * This class is used to run operations that modify UI elements in the UI thread. * * <p>We are using convenience methods that add a {@link android.os.Message} instance or a * {@link Runnable} to the message queue.</p> * * <p><strong>Note:</strong> If you add a method to this class make sure you don't accidentally * perform the operation in the calling thread.</p> */ class MessageListHandler extends Handler { private static final int ACTION_REMOVE_MESSAGE = 1; private static final int ACTION_RESET_UNREAD_COUNT = 2; private static final int ACTION_SORT_MESSAGES = 3; private static final int ACTION_FOLDER_LOADING = 4; private static final int ACTION_REFRESH_TITLE = 5; private static final int ACTION_PROGRESS = 6; public void removeMessage(MessageReference messageReference) { android.os.Message msg = android.os.Message.obtain(this, ACTION_REMOVE_MESSAGE, messageReference); sendMessage(msg); } public void sortMessages() { android.os.Message msg = android.os.Message.obtain(this, ACTION_SORT_MESSAGES); sendMessage(msg); } public void folderLoading(String folder, boolean loading) { android.os.Message msg = android.os.Message.obtain(this, ACTION_FOLDER_LOADING, (loading) ? 1 : 0, 0, folder); sendMessage(msg); } public void refreshTitle() { android.os.Message msg = android.os.Message.obtain(this, ACTION_REFRESH_TITLE); sendMessage(msg); } public void progress(final boolean progress) { android.os.Message msg = android.os.Message.obtain(this, ACTION_PROGRESS, (progress) ? 1 : 0, 0); sendMessage(msg); } public void changeMessageUid(final MessageReference ref, final String newUid) { // Instead of explicitly creating a container to be able to pass both arguments in a // Message we post a Runnable to the message queue. post(new Runnable() { @Override public void run() { mAdapter.changeMessageUid(ref, newUid); } }); } public void addOrUpdateMessages(final Account account, final String folderName, final List<Message> providedMessages, final boolean verifyAgainstSearch) { final List<Message> messages = new ArrayList<Message>(providedMessages); post(new Runnable() { @Override public void run() { mAdapter.addOrUpdateMessages(account, folderName, messages, verifyAgainstSearch); } }); } @Override public void handleMessage(android.os.Message msg) { switch (msg.what) { case ACTION_REMOVE_MESSAGE: { MessageReference messageReference = (MessageReference) msg.obj; mAdapter.removeMessage(messageReference); break; } case ACTION_RESET_UNREAD_COUNT: { mAdapter.resetUnreadCount(); break; } case ACTION_SORT_MESSAGES: { mAdapter.sortMessages(); break; } case ACTION_FOLDER_LOADING: { String folder = (String) msg.obj; boolean loading = (msg.arg1 == 1); MessageList.this.folderLoading(folder, loading); break; } case ACTION_REFRESH_TITLE: { MessageList.this.refreshTitle(); break; } case ACTION_PROGRESS: { boolean progress = (msg.arg1 == 1); MessageList.this.progress(progress); break; } } } } /** * @return The comparator to use to display messages in an ordered * fashion. Never <code>null</code>. */ protected Comparator<MessageInfoHolder> getComparator() { final List<Comparator<MessageInfoHolder>> chain = new ArrayList<Comparator<MessageInfoHolder>>(2 /* we add 2 comparators at most */); { // add the specified comparator final Comparator<MessageInfoHolder> comparator = SORT_COMPARATORS.get(mSortType); if (mSortAscending) { chain.add(comparator); } else { chain.add(new ReverseComparator<MessageInfoHolder>(comparator)); } } { // add the date comparator if not already specified if (mSortType != SortType.SORT_DATE && mSortType != SortType.SORT_ARRIVAL) { final Comparator<MessageInfoHolder> comparator = SORT_COMPARATORS.get(SortType.SORT_DATE); if (mSortDateAscending) { chain.add(comparator); } else { chain.add(new ReverseComparator<MessageInfoHolder>(comparator)); } } } // build the comparator chain final Comparator<MessageInfoHolder> chainComparator = new ComparatorChain<MessageInfoHolder>(chain); return chainComparator; } private void folderLoading(String folder, boolean loading) { if (mCurrentFolder != null && mCurrentFolder.name.equals(folder)) { mCurrentFolder.loading = loading; } updateFooterView(); } private void refreshTitle() { setWindowTitle(); setWindowProgress(); } private void setWindowProgress() { int level = Window.PROGRESS_END; if (mCurrentFolder != null && mCurrentFolder.loading && mAdapter.mListener.getFolderTotal() > 0) { int divisor = mAdapter.mListener.getFolderTotal(); if (divisor != 0) { level = (Window.PROGRESS_END / divisor) * (mAdapter.mListener.getFolderCompleted()) ; if (level > Window.PROGRESS_END) { level = Window.PROGRESS_END; } } } setSupportProgress(level); } private void setWindowTitle() { // regular folder content display if (mFolderName != null) { String displayName = FolderInfoHolder.getDisplayName(MessageList.this, mAccount, mFolderName); mActionBarTitle.setText(displayName); String operation = mAdapter.mListener.getOperation(MessageList.this, getTimeFormat()).trim(); if (operation.length() < 1) { mActionBarSubTitle.setText(mAccount.getEmail()); } else { mActionBarSubTitle.setText(operation); } } else if (mQueryString != null) { // query result display. This may be for a search folder as opposed to a user-initiated search. if (mTitle != null) { // This was a search folder; the search folder has overridden our title. mActionBarTitle.setText(mTitle); } else { // This is a search result; set it to the default search result line. mActionBarTitle.setText(getString(R.string.search_results)); } } // set unread count if (mUnreadMessageCount == 0) { mActionBarUnread.setVisibility(View.GONE); } else { if (mQueryString != null && mTitle == null) { // This is a search result. The unread message count is easily confused // with total number of messages in the search result, so let's hide it. mActionBarUnread.setVisibility(View.GONE); } else { mActionBarUnread.setText(Integer.toString(mUnreadMessageCount)); mActionBarUnread.setVisibility(View.VISIBLE); } } } private void progress(final boolean progress) { // Make sure we don't try this before the menu is initialized // this could happen while the activity is initialized. if (mRefreshMenuItem == null) { return; } if (progress) { mRefreshMenuItem.setActionView(mActionBarProgressView); } else { mRefreshMenuItem.setActionView(null); } } /** * Show the message list that was used to open the {@link MessageView} for a message. * * <p> * <strong>Note:</strong> * The {@link MessageList} instance should still be around and all we do is bring it back to * the front (see the activity flags).<br> * Out of sheer paranoia we also set the extras that were used to create the original * {@code MessageList} instance. Using those, the activity can be recreated in the unlikely * case of it having been killed by the OS. * </p> * * @param context * The {@link Context} instance to invoke the {@link Context#startActivity(Intent)} * method on. * @param extras * The extras used to create the original {@code MessageList} instance. * * @see MessageView#actionView(Context, MessageReference, ArrayList, Bundle) */ public static void actionHandleFolder(Context context, Bundle extras) { Intent intent = new Intent(context, MessageList.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); intent.putExtras(extras); intent.putExtra(EXTRA_RETURN_FROM_MESSAGE_VIEW, true); context.startActivity(intent); } public static void actionHandleFolder(Context context, Account account, String folder) { Intent intent = new Intent(context, MessageList.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); intent.putExtra(EXTRA_ACCOUNT, account.getUuid()); if (folder != null) { intent.putExtra(EXTRA_FOLDER, folder); } context.startActivity(intent); } public static Intent actionHandleFolderIntent(Context context, Account account, String folder) { Intent intent = new Intent(context, MessageList.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); intent.putExtra(EXTRA_ACCOUNT, account.getUuid()); if (folder != null) { intent.putExtra(EXTRA_FOLDER, folder); } return intent; } public static void actionHandle(Context context, String title, String queryString, boolean integrate, Flag[] flags, Flag[] forbiddenFlags) { Intent intent = new Intent(context, MessageList.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); intent.putExtra(EXTRA_QUERY, queryString); if (flags != null) { intent.putExtra(EXTRA_QUERY_FLAGS, Utility.combine(flags, ',')); } if (forbiddenFlags != null) { intent.putExtra(EXTRA_FORBIDDEN_FLAGS, Utility.combine(forbiddenFlags, ',')); } intent.putExtra(EXTRA_INTEGRATE, integrate); intent.putExtra(EXTRA_TITLE, title); context.startActivity(intent); } /** * Creates and returns an intent that opens Unified Inbox or All Messages screen. */ public static Intent actionHandleAccountIntent(Context context, String title, SearchSpecification searchSpecification) { Intent intent = new Intent(context, MessageList.class); intent.putExtra(EXTRA_QUERY, searchSpecification.getQuery()); if (searchSpecification.getRequiredFlags() != null) { intent.putExtra(EXTRA_QUERY_FLAGS, Utility.combine(searchSpecification.getRequiredFlags(), ',')); } if (searchSpecification.getForbiddenFlags() != null) { intent.putExtra(EXTRA_FORBIDDEN_FLAGS, Utility.combine(searchSpecification.getForbiddenFlags(), ',')); } intent.putExtra(EXTRA_INTEGRATE, searchSpecification.isIntegrate()); intent.putExtra(EXTRA_ACCOUNT_UUIDS, searchSpecification.getAccountUuids()); intent.putExtra(EXTRA_FOLDER_NAMES, searchSpecification.getFolderNames()); intent.putExtra(EXTRA_TITLE, title); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); return intent; } public static void actionHandle(Context context, String title, SearchSpecification searchSpecification) { Intent intent = actionHandleAccountIntent(context, title, searchSpecification); context.startActivity(intent); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (view == mFooterView) { if (mCurrentFolder != null) { mController.loadMoreMessages(mAccount, mFolderName, mAdapter.mListener); } return; } MessageInfoHolder message = (MessageInfoHolder) mAdapter.getItem(position); if (mSelectedCount > 0) { toggleMessageSelect(position); } else { onOpenMessage(message); } } @Override public void onCreate(Bundle savedInstanceState) { context = this; super.onCreate(savedInstanceState); mActionBarProgressView = getLayoutInflater().inflate(R.layout.actionbar_indeterminate_progress_actionview, null); // need this for actionbar initialization mQueryString = getIntent().getStringExtra(EXTRA_QUERY); mInflater = getLayoutInflater(); mActionBar = getSupportActionBar(); initializeActionBar(); initializeLayout(); mPreviewLines = K9.messageListPreviewLines(); initializeMessageList(getIntent(), true); getListView().setVerticalFadingEdgeEnabled(false); // Enable context action bar behaviour getListView().setOnItemLongClickListener(new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { toggleMessageSelect(position); return true; }}); // Correcting for screen rotation when in ActionMode mSelectedCount = getSelectionFromCheckboxes().size(); if (mSelectedCount > 0) { mActionMode = MessageList.this.startActionMode(mActionModeCallback); mActionMode.setTitle(String.format( getString(R.string.actionbar_selected), mSelectedCount)); } } @Override public void onNewIntent(Intent intent) { setIntent(intent); // onNewIntent doesn't autoset our "internal" intent initializeMessageList(intent, false); } private void initializeMessageList(Intent intent, boolean create) { boolean returnFromMessageView = intent.getBooleanExtra( EXTRA_RETURN_FROM_MESSAGE_VIEW, false); if (!create && returnFromMessageView) { // We're returning from the MessageView activity with "Manage back button" enabled. // So just leave the activity in the state it was left in. return; } String accountUuid = intent.getStringExtra(EXTRA_ACCOUNT); mAccount = Preferences.getPreferences(this).getAccount(accountUuid); if (mAccount != null && !mAccount.isAvailable(this)) { Log.i(K9.LOG_TAG, "not opening MessageList of unavailable account"); onAccountUnavailable(); return; } mFolderName = intent.getStringExtra(EXTRA_FOLDER); mQueryString = intent.getStringExtra(EXTRA_QUERY); String queryFlags = intent.getStringExtra(EXTRA_QUERY_FLAGS); if (queryFlags != null) { String[] flagStrings = queryFlags.split(","); mQueryFlags = new Flag[flagStrings.length]; for (int i = 0; i < flagStrings.length; i++) { mQueryFlags[i] = Flag.valueOf(flagStrings[i]); } } String forbiddenFlags = intent.getStringExtra(EXTRA_FORBIDDEN_FLAGS); if (forbiddenFlags != null) { String[] flagStrings = forbiddenFlags.split(","); mForbiddenFlags = new Flag[flagStrings.length]; for (int i = 0; i < flagStrings.length; i++) { mForbiddenFlags[i] = Flag.valueOf(flagStrings[i]); } } mIntegrate = intent.getBooleanExtra(EXTRA_INTEGRATE, false); mAccountUuids = intent.getStringArrayExtra(EXTRA_ACCOUNT_UUIDS); mFolderNames = intent.getStringArrayExtra(EXTRA_FOLDER_NAMES); mTitle = intent.getStringExtra(EXTRA_TITLE); // Take the initial folder into account only if we are *not* restoring // the activity already. if (mFolderName == null && mQueryString == null) { mFolderName = mAccount.getAutoExpandFolderName(); } mAdapter = new MessageListAdapter(); restorePreviousData(); if (mFolderName != null) { mCurrentFolder = mAdapter.getFolder(mFolderName, mAccount); } // Hide "Load up to x more" footer for search views mFooterView.setVisibility((mQueryString != null) ? View.GONE : View.VISIBLE); mController = MessagingController.getInstance(getApplication()); mListView.setAdapter(mAdapter); } private void restorePreviousData() { final ActivityState previousData = getLastNonConfigurationInstance(); if (previousData != null) { mAdapter.restoreMessages(previousData.messages); mActiveMessages = previousData.activeMessages; } } @Override public void onPause() { super.onPause(); mController.removeListener(mAdapter.mListener); saveListState(); StorageManager.getInstance(getApplication()).removeListener(mStorageListener); } public void saveListState() { mState = new Bundle(); mState.putInt(EXTRA_LIST_POSITION, mListView.getSelectedItemPosition()); } public void restoreListState() { if (mState == null) { return; } int pos = mState.getInt(EXTRA_LIST_POSITION, ListView.INVALID_POSITION); if (pos >= mListView.getCount()) { pos = mListView.getCount() - 1; } if (pos == ListView.INVALID_POSITION) { mListView.setSelected(false); } else { mListView.setSelection(pos); } } /** * On resume we refresh messages for the folder that is currently open. * This guarantees that things like unread message count and read status * are updated. */ @Override public void onResume() { super.onResume(); if (mAccount != null && !mAccount.isAvailable(this)) { onAccountUnavailable(); return; } StorageManager.getInstance(getApplication()).addListener(mStorageListener); mStars = K9.messageListStars(); mCheckboxes = K9.messageListCheckboxes(); mController.addListener(mAdapter.mListener); Account[] accountsWithNotification; Preferences prefs = Preferences.getPreferences(getApplicationContext()); Account account = getCurrentAccount(prefs); if (account != null) { accountsWithNotification = new Account[] { account }; mSortType = account.getSortType(); mSortAscending = account.isSortAscending(mSortType); mSortDateAscending = account.isSortAscending(SortType.SORT_DATE); } else { accountsWithNotification = prefs.getAccounts(); mSortType = K9.getSortType(); mSortAscending = K9.isSortAscending(mSortType); mSortDateAscending = K9.isSortAscending(SortType.SORT_DATE); } for (Account accountWithNotification : accountsWithNotification) { mController.notifyAccountCancel(this, accountWithNotification); } if (mAdapter.isEmpty()) { if (mFolderName != null) { mController.listLocalMessages(mAccount, mFolderName, mAdapter.mListener); // Hide the archive button if we don't have an archive folder. if (!mAccount.hasArchiveFolder()) { // mBatchArchiveButton.setVisibility(View.GONE); } } else if (mQueryString != null) { mController.searchLocalMessages(mAccountUuids, mFolderNames, null, mQueryString, mIntegrate, mQueryFlags, mForbiddenFlags, mAdapter.mListener); // Don't show the archive button if this is a search. // mBatchArchiveButton.setVisibility(View.GONE); } } else { // reread the selected date format preference in case it has changed mMessageHelper.refresh(); mAdapter.markAllMessagesAsDirty(); new Thread() { @Override public void run() { if (mFolderName != null) { mController.listLocalMessagesSynchronous(mAccount, mFolderName, mAdapter.mListener); } else if (mQueryString != null) { mController.searchLocalMessagesSynchronous(mAccountUuids, mFolderNames, null, mQueryString, mIntegrate, mQueryFlags, mForbiddenFlags, mAdapter.mListener); } runOnUiThread(new Runnable() { @Override public void run() { mAdapter.pruneDirtyMessages(); mAdapter.notifyDataSetChanged(); restoreListState(); } }); } } .start(); } if (mAccount != null && mFolderName != null) { mController.getFolderUnreadMessageCount(mAccount, mFolderName, mAdapter.mListener); } refreshTitle(); } private void initializeActionBar() { mActionBar.setDisplayShowCustomEnabled(true); mActionBar.setCustomView(R.layout.actionbar_custom); View customView = mActionBar.getCustomView(); mActionBarTitle = (TextView) customView.findViewById(R.id.actionbar_title_first); mActionBarSubTitle = (TextView) customView.findViewById(R.id.actionbar_title_sub); mActionBarUnread = (TextView) customView.findViewById(R.id.actionbar_unread_count); if (mQueryString != null) { mActionBarSubTitle.setVisibility(View.GONE); } mActionBar.setDisplayHomeAsUpEnabled(true); } private void initializeLayout() { mListView = getListView(); mListView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); mListView.setLongClickable(true); mListView.setFastScrollEnabled(true); mListView.setScrollingCacheEnabled(false); mListView.setOnItemClickListener(this); mListView.addFooterView(getFooterView(mListView)); registerForContextMenu(mListView); } /** * Container for values to be kept while the device configuration is * modified at runtime (keyboard, orientation, etc.) and Android restarts * this activity. * * @see MessageList#onRetainNonConfigurationInstance() * @see MessageList#getLastNonConfigurationInstance() */ static class ActivityState { public List<MessageInfoHolder> messages; public List<MessageInfoHolder> activeMessages; } /* (non-Javadoc) * * Method overridden for proper typing within this class (the return type is * more specific than the super implementation) * * @see android.app.Activity#onRetainNonConfigurationInstance() */ @Override public ActivityState onRetainNonConfigurationInstance() { final ActivityState state = new ActivityState(); state.messages = mAdapter.getMessages(); state.activeMessages = mActiveMessages; return state; } /* * (non-Javadoc) * * Method overridden for proper typing within this class (the return type is * more specific than the super implementation) * * @see android.app.Activity#getLastNonConfigurationInstance() */ @Override public ActivityState getLastNonConfigurationInstance() { return (ActivityState) super.getLastNonConfigurationInstance(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // Shortcuts that work no matter what is selected switch (keyCode) { // messagelist is actually a K9Activity, not a K9ListActivity // This saddens me greatly, but to support volume key navigation // in MessageView, we implement this bit of wrapper code case KeyEvent.KEYCODE_VOLUME_UP: { if (K9.useVolumeKeysForListNavigationEnabled()) { int currentPosition = mListView.getSelectedItemPosition(); if (currentPosition == AdapterView.INVALID_POSITION || mListView.isInTouchMode()) { currentPosition = mListView.getFirstVisiblePosition(); } if (currentPosition > 0) { mListView.setSelection(currentPosition - 1); } return true; } return false; } case KeyEvent.KEYCODE_VOLUME_DOWN: { if (K9.useVolumeKeysForListNavigationEnabled()) { int currentPosition = mListView.getSelectedItemPosition(); if (currentPosition == AdapterView.INVALID_POSITION || mListView.isInTouchMode()) { currentPosition = mListView.getFirstVisiblePosition(); } if (currentPosition < mListView.getCount()) { mListView.setSelection(currentPosition + 1); } return true; } return false; } case KeyEvent.KEYCODE_C: { onCompose(); return true; } case KeyEvent.KEYCODE_Q: { onShowFolderList(); return true; } case KeyEvent.KEYCODE_O: { onCycleSort(); return true; } case KeyEvent.KEYCODE_I: { changeSort(mSortType); return true; } case KeyEvent.KEYCODE_H: { Toast toast = Toast.makeText(this, R.string.message_list_help_key, Toast.LENGTH_LONG); toast.show(); return true; } } boolean retval = true; int position = mListView.getSelectedItemPosition(); try { if (position >= 0) { MessageInfoHolder message = (MessageInfoHolder) mAdapter.getItem(position); final List<MessageInfoHolder> selection = getSelectionFromMessage(message); if (message != null) { switch (keyCode) { case KeyEvent.KEYCODE_DEL: { onDelete(selection); return true; } case KeyEvent.KEYCODE_S: { setSelected(selection, !message.selected); return true; } case KeyEvent.KEYCODE_D: { onDelete(selection); return true; } case KeyEvent.KEYCODE_G: { setFlag(selection, Flag.FLAGGED, !message.flagged); return true; } case KeyEvent.KEYCODE_M: { onMove(selection); return true; } case KeyEvent.KEYCODE_V: { onArchive(selection); return true; } case KeyEvent.KEYCODE_Y: { onCopy(selection); return true; } case KeyEvent.KEYCODE_Z: { setFlag(selection, Flag.SEEN, !message.read); return true; } } } } } finally { retval = super.onKeyDown(keyCode, event); } return retval; } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { // Swallow these events too to avoid the audible notification of a volume change if (K9.useVolumeKeysForListNavigationEnabled()) { if ((keyCode == KeyEvent.KEYCODE_VOLUME_UP) || (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "Swallowed key up."); return true; } } return super.onKeyUp(keyCode, event); } private void onOpenMessage(MessageInfoHolder message) { if (message.folder.name.equals(message.message.getFolder().getAccount().getDraftsFolderName())) { MessageCompose.actionEditDraft(this, message.message.getFolder().getAccount(), message.message); } else { // Need to get the list before the sort starts ArrayList<MessageReference> messageRefs = new ArrayList<MessageReference>(); for (MessageInfoHolder holder : mAdapter.getMessages()) { MessageReference ref = holder.message.makeMessageReference(); messageRefs.add(ref); } MessageReference ref = message.message.makeMessageReference(); Log.i(K9.LOG_TAG, "MessageList sending message " + ref); MessageView.actionView(this, ref, messageRefs, getIntent().getExtras()); } /* * We set read=true here for UI performance reasons. The actual value * will get picked up on the refresh when the Activity is resumed but * that may take a second or so and we don't want this to show and * then go away. I've gone back and forth on this, and this gives a * better UI experience, so I am putting it back in. */ if (!message.read) { message.read = true; } } private void onAccounts() { Accounts.listAccounts(this); finish(); } private void onShowFolderList() { FolderList.actionHandleAccount(this, mAccount); finish(); } private void onCompose() { if (mQueryString != null) { /* * If we have a query string, we don't have an account to let * compose start the default action. */ MessageCompose.actionCompose(this, null); } else { MessageCompose.actionCompose(this, mAccount); } } private void onReply(MessageInfoHolder holder) { MessageCompose.actionReply(this, holder.message.getFolder().getAccount(), holder.message, false, null); } private void onReplyAll(MessageInfoHolder holder) { MessageCompose.actionReply(this, holder.message.getFolder().getAccount(), holder.message, true, null); } private void onForward(MessageInfoHolder holder) { MessageCompose.actionForward(this, holder.message.getFolder().getAccount(), holder.message, null); } private void onResendMessage(MessageInfoHolder message) { MessageCompose.actionEditDraft(this, message.message.getFolder().getAccount(), message.message); } private void onEditPrefs() { Prefs.actionPrefs(this); } private void onEditAccount() { AccountSettings.actionSettings(this, mAccount); } private void changeSort(SortType sortType) { Boolean sortAscending = (mSortType == sortType) ? !mSortAscending : null; changeSort(sortType, sortAscending); } /** * Change the sort type and sort order used for the message list. * * @param sortType * Specifies which field to use for sorting the message list. * @param sortAscending * Specifies the sort order. If this argument is {@code null} the default search order * for the sort type is used. */ // FIXME: Don't save the changes in the UI thread private void changeSort(SortType sortType, Boolean sortAscending) { mSortType = sortType; Preferences prefs = Preferences.getPreferences(getApplicationContext()); Account account = getCurrentAccount(prefs); if (account != null) { account.setSortType(mSortType); if (sortAscending == null) { mSortAscending = account.isSortAscending(mSortType); } else { mSortAscending = sortAscending; } account.setSortAscending(mSortType, mSortAscending); mSortDateAscending = account.isSortAscending(SortType.SORT_DATE); account.save(prefs); } else { K9.setSortType(mSortType); if (sortAscending == null) { mSortAscending = K9.isSortAscending(mSortType); } else { mSortAscending = sortAscending; } K9.setSortAscending(mSortType, mSortAscending); mSortDateAscending = K9.isSortAscending(SortType.SORT_DATE); Editor editor = prefs.getPreferences().edit(); K9.save(editor); editor.commit(); } reSort(); } private void reSort() { int toastString = mSortType.getToast(mSortAscending); Toast toast = Toast.makeText(this, toastString, Toast.LENGTH_SHORT); toast.show(); mAdapter.sortMessages(); } private void onCycleSort() { SortType[] sorts = SortType.values(); int curIndex = 0; for (int i = 0; i < sorts.length; i++) { if (sorts[i] == mSortType) { curIndex = i; break; } } curIndex++; if (curIndex == sorts.length) { curIndex = 0; } changeSort(sorts[curIndex]); } /** * @param holders * Never {@code null}. */ private void onDelete(final List<MessageInfoHolder> holders) { final List<Message> messagesToRemove = new ArrayList<Message>(); for (MessageInfoHolder holder : holders) { messagesToRemove.add(holder.message); } mAdapter.removeMessages(holders); mController.deleteMessages(messagesToRemove.toArray(EMPTY_MESSAGE_ARRAY), null); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode != RESULT_OK) { return; } switch (requestCode) { case ACTIVITY_CHOOSE_FOLDER_MOVE: case ACTIVITY_CHOOSE_FOLDER_COPY: { if (data == null) { return; } final String destFolderName = data.getStringExtra(ChooseFolder.EXTRA_NEW_FOLDER); final List<MessageInfoHolder> holders = mActiveMessages; if (destFolderName != null) { mActiveMessages = null; // don't need it any more final Account account = holders.get(0).message.getFolder().getAccount(); account.setLastSelectedFolderName(destFolderName); switch (requestCode) { case ACTIVITY_CHOOSE_FOLDER_MOVE: move(holders, destFolderName); break; case ACTIVITY_CHOOSE_FOLDER_COPY: copy(holders, destFolderName); break; } } break; } } } private void onMarkAllAsRead(final Account account, final String folder) { if (K9.confirmMarkAllAsRead()) { showDialog(DIALOG_MARK_ALL_AS_READ); } else { markAllAsRead(); } } private void markAllAsRead() { try { mController.markAllMessagesRead(mAccount, mCurrentFolder.name); for (MessageInfoHolder holder : mAdapter.getMessages()) { holder.read = true; } mAdapter.sortMessages(); } catch (Exception e) { // Ignore } } private void onExpunge(final Account account, String folderName) { mController.expunge(account, folderName, null); } @Override public Dialog onCreateDialog(int id) { switch (id) { case DIALOG_MARK_ALL_AS_READ: return ConfirmationDialog.create(this, id, R.string.mark_all_as_read_dlg_title, getString(R.string.mark_all_as_read_dlg_instructions_fmt, mCurrentFolder.displayName), R.string.okay_action, R.string.cancel_action, new Runnable() { @Override public void run() { markAllAsRead(); } }); case R.id.dialog_confirm_spam: return ConfirmationDialog.create(this, id, R.string.dialog_confirm_spam_title, "" /* text is refreshed by #onPrepareDialog(int, Dialog) below */, R.string.dialog_confirm_spam_confirm_button, R.string.dialog_confirm_spam_cancel_button, new Runnable() { @Override public void run() { onSpamConfirmed(mActiveMessages); // No further need for this reference mActiveMessages = null; } }, new Runnable() { @Override public void run() { // event for cancel, we don't need this reference any more mActiveMessages = null; } }); } return super.onCreateDialog(id); } /* * (non-Javadoc) * * Android happens to invoke this method even if the given dialog is not * shown (eg. a dismissed dialog) as part of the automatic activity * reloading following a configuration change (orientation, keyboard, * locale, etc.). */ @Override public void onPrepareDialog(final int id, final Dialog dialog) { switch (id) { case DIALOG_MARK_ALL_AS_READ: { if (mCurrentFolder != null) { ((AlertDialog)dialog).setMessage(getString(R.string.mark_all_as_read_dlg_instructions_fmt, mCurrentFolder.displayName)); } break; } case R.id.dialog_confirm_spam: { // mActiveMessages can be null if Android restarts the activity // while this dialog is not actually shown (but was displayed at // least once) if (mActiveMessages != null) { final int selectionSize = mActiveMessages.size(); final String message; message = getResources().getQuantityString(R.plurals.dialog_confirm_spam_message, selectionSize, Integer.valueOf(selectionSize)); ((AlertDialog) dialog).setMessage(message); } break; } default: { super.onPrepareDialog(id, dialog); } } } private void onToggleRead(final List<MessageInfoHolder> holders) { LocalMessage message; Folder folder; Account account; String folderName; int i = 0; for (final Iterator<MessageInfoHolder> iterator = holders.iterator(); iterator.hasNext(); i++) { final MessageInfoHolder messageInfo = iterator.next(); message = messageInfo.message; folder = message.getFolder(); account = folder.getAccount(); folderName = message.getFolder().getName(); mController.setFlag(account, folderName, new Message[]{message}, Flag.SEEN, !messageInfo.read); messageInfo.read = !messageInfo.read; mAdapter.sortMessages(); } } private void onToggleFlag(final List<MessageInfoHolder> holders) { LocalMessage message; Folder folder; Account account; String folderName; int i = 0; for (final Iterator<MessageInfoHolder> iterator = holders.iterator(); iterator.hasNext(); i++) { final MessageInfoHolder messageInfo = iterator.next(); message = messageInfo.message; folder = message.getFolder(); account = folder.getAccount(); folderName = message.getFolder().getName(); mController.setFlag(account, folderName, new Message[]{message}, Flag.FLAGGED, !messageInfo.flagged); messageInfo.flagged = !messageInfo.flagged; mAdapter.sortMessages(); } } private void checkMail(Account account, String folderName) { mController.synchronizeMailbox(account, folderName, mAdapter.mListener, null); mController.sendPendingMessages(account, mAdapter.mListener); } @Override public boolean onOptionsItemSelected(MenuItem item) { int itemId = item.getItemId(); switch (itemId) { case android.R.id.home: { if (mQueryString == null) { onShowFolderList(); } else { onAccounts(); } return true; } case R.id.compose: { onCompose(); return true; } case R.id.check_mail: { checkMail(mAccount, mFolderName); return true; } case R.id.set_sort_date: { changeSort(SortType.SORT_DATE); return true; } case R.id.set_sort_arrival: { changeSort(SortType.SORT_ARRIVAL); return true; } case R.id.set_sort_subject: { changeSort(SortType.SORT_SUBJECT); return true; } case R.id.set_sort_sender: { changeSort(SortType.SORT_SENDER); return true; } case R.id.set_sort_flag: { changeSort(SortType.SORT_FLAGGED); return true; } case R.id.set_sort_unread: { changeSort(SortType.SORT_UNREAD); return true; } case R.id.set_sort_attach: { changeSort(SortType.SORT_ATTACHMENT); return true; } case R.id.select_all: toggleAllSelected(); return true; case R.id.app_settings: { onEditPrefs(); return true; } } if (mQueryString != null) { // None of the options after this point are "safe" for search results //TODO: This is not true for "unread" and "starred" searches in regular folders return false; } switch (itemId) { case R.id.send_messages: { mController.sendPendingMessages(mAccount, mAdapter.mListener); return true; } case R.id.mark_all_as_read: { if (mFolderName != null) { onMarkAllAsRead(mAccount, mFolderName); } return true; } case R.id.folder_settings: { if (mFolderName != null) { FolderSettings.actionSettings(this, mAccount, mFolderName); } return true; } case R.id.account_settings: { onEditAccount(); return true; } case R.id.expunge: { if (mCurrentFolder != null) { onExpunge(mAccount, mCurrentFolder.name); } return true; } default: { return super.onOptionsItemSelected(item); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getSupportMenuInflater().inflate(R.menu.message_list_option, menu); mRefreshMenuItem = menu.findItem(R.id.check_mail); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { if (mQueryString != null) { menu.findItem(R.id.mark_all_as_read).setVisible(false); menu.findItem(R.id.expunge).setVisible(false); menu.findItem(R.id.check_mail).setVisible(false); menu.findItem(R.id.send_messages).setVisible(false); menu.findItem(R.id.folder_settings).setVisible(false); menu.findItem(R.id.account_settings).setVisible(false); } else { if (mCurrentFolder != null && mCurrentFolder.name.equals(mAccount.getOutboxFolderName())) { menu.findItem(R.id.check_mail).setVisible(false); } else { menu.findItem(R.id.send_messages).setVisible(false); } if (mCurrentFolder != null && K9.ERROR_FOLDER_NAME.equals(mCurrentFolder.name)) { menu.findItem(R.id.expunge).setVisible(false); } if (!mController.isMoveCapable(mAccount)) { // FIXME: Really we want to do this for all local-only folders if (mCurrentFolder != null && !mAccount.getInboxFolderName().equals(mCurrentFolder.name)) { menu.findItem(R.id.check_mail).setVisible(false); } menu.findItem(R.id.expunge).setVisible(false); } } return true; } class MessageListAdapter extends BaseAdapter { private final List<MessageInfoHolder> mMessages = Collections.synchronizedList(new ArrayList<MessageInfoHolder>()); private final ActivityListener mListener = new ActivityListener() { @Override public void informUserOfStatus() { mHandler.refreshTitle(); } @Override public void synchronizeMailboxStarted(Account account, String folder) { if (updateForMe(account, folder)) { mHandler.progress(true); mHandler.folderLoading(folder, true); } super.synchronizeMailboxStarted(account, folder); } @Override public void synchronizeMailboxFinished(Account account, String folder, int totalMessagesInMailbox, int numNewMessages) { if (updateForMe(account, folder)) { mHandler.progress(false); mHandler.folderLoading(folder, false); mHandler.sortMessages(); } super.synchronizeMailboxFinished(account, folder, totalMessagesInMailbox, numNewMessages); } @Override public void synchronizeMailboxFailed(Account account, String folder, String message) { if (updateForMe(account, folder)) { mHandler.progress(false); mHandler.folderLoading(folder, false); mHandler.sortMessages(); } super.synchronizeMailboxFailed(account, folder, message); } @Override public void synchronizeMailboxAddOrUpdateMessage(Account account, String folder, Message message) { mHandler.addOrUpdateMessages(account, folder, Collections.singletonList(message), true); } @Override public void synchronizeMailboxRemovedMessage(Account account, String folder, Message message) { mHandler.removeMessage(message.makeMessageReference()); } @Override public void listLocalMessagesStarted(Account account, String folder) { if ((mQueryString != null && folder == null) || (account != null && account.equals(mAccount))) { mHandler.progress(true); if (folder != null) { mHandler.folderLoading(folder, true); } } } @Override public void listLocalMessagesFailed(Account account, String folder, String message) { if ((mQueryString != null && folder == null) || (account != null && account.equals(mAccount))) { mHandler.sortMessages(); mHandler.progress(false); if (folder != null) { mHandler.folderLoading(folder, false); } } } @Override public void listLocalMessagesFinished(Account account, String folder) { if ((mQueryString != null && folder == null) || (account != null && account.equals(mAccount))) { mHandler.sortMessages(); mHandler.progress(false); if (folder != null) { mHandler.folderLoading(folder, false); } } } @Override public void listLocalMessagesRemoveMessage(Account account, String folder, Message message) { mHandler.removeMessage(message.makeMessageReference()); } @Override public void listLocalMessagesAddMessages(Account account, String folder, List<Message> messages) { mHandler.addOrUpdateMessages(account, folder, messages, false); } @Override public void listLocalMessagesUpdateMessage(Account account, String folder, Message message) { mHandler.addOrUpdateMessages(account, folder, Collections.singletonList(message), false); } @Override public void searchStats(AccountStats stats) { mUnreadMessageCount = stats.unreadMessageCount; super.searchStats(stats); } @Override public void folderStatusChanged(Account account, String folder, int unreadMessageCount) { if (updateForMe(account, folder)) { mUnreadMessageCount = unreadMessageCount; } super.folderStatusChanged(account, folder, unreadMessageCount); } @Override public void messageUidChanged(Account account, String folder, String oldUid, String newUid) { MessageReference ref = new MessageReference(); ref.accountUuid = account.getUuid(); ref.folderName = folder; ref.uid = oldUid; mHandler.changeMessageUid(ref, newUid); } }; private boolean updateForMe(Account account, String folder) { if ((account.equals(mAccount) && mFolderName != null && folder.equals(mFolderName))) { return true; } else { return false; } } public List<MessageInfoHolder> getMessages() { return mMessages; } public void restoreMessages(List<MessageInfoHolder> messages) { mMessages.addAll(messages); } private Drawable mAttachmentIcon; private Drawable mForwardedIcon; private Drawable mAnsweredIcon; private Drawable mForwardedAnsweredIcon; MessageListAdapter() { mAttachmentIcon = getResources().getDrawable(R.drawable.ic_email_attachment_small); mAnsweredIcon = getResources().getDrawable(R.drawable.ic_email_answered_small); mForwardedIcon = getResources().getDrawable(R.drawable.ic_email_forwarded_small); mForwardedAnsweredIcon = getResources().getDrawable(R.drawable.ic_email_forwarded_answered_small); } public void markAllMessagesAsDirty() { for (MessageInfoHolder holder : mMessages) { holder.dirty = true; } } public void pruneDirtyMessages() { List<MessageInfoHolder> messagesToRemove = new ArrayList<MessageInfoHolder>(); for (MessageInfoHolder holder : mMessages) { if (holder.dirty) { messagesToRemove.add(holder); } } removeMessages(messagesToRemove); } public void removeMessage(MessageReference messageReference) { MessageInfoHolder holder = getMessage(messageReference); if (holder == null) { Log.w(K9.LOG_TAG, "Got callback to remove non-existent message with UID " + messageReference.uid); } else { removeMessages(Collections.singletonList(holder)); } } public void removeMessages(final List<MessageInfoHolder> messages) { if (messages.isEmpty()) { return; } for (MessageInfoHolder message : messages) { if (message != null && (mFolderName == null || ( message.folder != null && message.folder.name.equals(mFolderName)))) { if (message.selected && mSelectedCount > 0) { mSelectedCount } mMessages.remove(message); } } resetUnreadCount(); notifyDataSetChanged(); } /** * Set the selection state for all messages at once. * @param selected Selection state to set. */ public void setSelectionForAllMesages(final boolean selected) { for (MessageInfoHolder message : mMessages) { message.selected = selected; } notifyDataSetChanged(); } public void addMessages(final List<MessageInfoHolder> messages) { if (messages.isEmpty()) { return; } final boolean wasEmpty = mMessages.isEmpty(); for (final MessageInfoHolder message : messages) { if (mFolderName == null || (message.folder != null && message.folder.name.equals(mFolderName))) { int index = Collections.binarySearch(mMessages, message, getComparator()); if (index < 0) { index = (index * -1) - 1; } mMessages.add(index, message); } } if (wasEmpty) { mListView.setSelection(0); } resetUnreadCount(); notifyDataSetChanged(); } public void changeMessageUid(MessageReference ref, String newUid) { MessageInfoHolder holder = getMessage(ref); if (holder != null) { holder.uid = newUid; holder.message.setUid(newUid); } } public void resetUnreadCount() { if (mQueryString != null) { int unreadCount = 0; for (MessageInfoHolder holder : mMessages) { unreadCount += holder.read ? 0 : 1; } mUnreadMessageCount = unreadCount; refreshTitle(); } } public void sortMessages() { final Comparator<MessageInfoHolder> chainComparator = getComparator(); Collections.sort(mMessages, chainComparator); notifyDataSetChanged(); } public void addOrUpdateMessages(final Account account, final String folderName, final List<Message> messages, final boolean verifyAgainstSearch) { boolean needsSort = false; final List<MessageInfoHolder> messagesToAdd = new ArrayList<MessageInfoHolder>(); List<MessageInfoHolder> messagesToRemove = new ArrayList<MessageInfoHolder>(); List<Message> messagesToSearch = new ArrayList<Message>(); // cache field into local variable for faster access for JVM without JIT final MessageHelper messageHelper = mMessageHelper; for (Message message : messages) { MessageInfoHolder m = getMessage(message); if (message.isSet(Flag.DELETED)) { if (m != null) { messagesToRemove.add(m); } } else { final Folder messageFolder = message.getFolder(); final Account messageAccount = messageFolder.getAccount(); if (m == null) { if (updateForMe(account, folderName)) { m = new MessageInfoHolder(); FolderInfoHolder folderInfoHolder = new FolderInfoHolder( MessageList.this, messageFolder, messageAccount); messageHelper.populate(m, message, folderInfoHolder, messageAccount); messagesToAdd.add(m); } else { if (mQueryString != null) { if (verifyAgainstSearch) { messagesToSearch.add(message); } else { m = new MessageInfoHolder(); FolderInfoHolder folderInfoHolder = new FolderInfoHolder( MessageList.this, messageFolder, messageAccount); messageHelper.populate(m, message, folderInfoHolder, messageAccount); messagesToAdd.add(m); } } } } else { m.dirty = false; // as we reload the message, unset its dirty flag FolderInfoHolder folderInfoHolder = new FolderInfoHolder(MessageList.this, messageFolder, account); messageHelper.populate(m, message, folderInfoHolder, account); needsSort = true; } } } if (!messagesToSearch.isEmpty()) { mController.searchLocalMessages(mAccountUuids, mFolderNames, messagesToSearch.toArray(EMPTY_MESSAGE_ARRAY), mQueryString, mIntegrate, mQueryFlags, mForbiddenFlags, new MessagingListener() { @Override public void listLocalMessagesAddMessages(Account account, String folder, List<Message> messages) { mHandler.addOrUpdateMessages(account, folder, messages, false); } }); } if (!messagesToRemove.isEmpty()) { removeMessages(messagesToRemove); } if (!messagesToAdd.isEmpty()) { addMessages(messagesToAdd); } if (needsSort) { sortMessages(); resetUnreadCount(); } } /** * Find a specific message in the message list. * * <p><strong>Note:</strong> * This method was optimized because it is called a lot. Don't change it unless you know * what you are doing.</p> * * @param message * A {@link Message} instance describing the message to look for. * * @return The corresponding {@link MessageInfoHolder} instance if the message was found in * the message list. {@code null} otherwise. */ private MessageInfoHolder getMessage(Message message) { String uid; Folder folder; for (MessageInfoHolder holder : mMessages) { uid = message.getUid(); if (holder.uid == uid || uid.equals(holder.uid)) { folder = message.getFolder(); if (holder.folder.name.equals(folder.getName()) && holder.account.equals(folder.getAccount().getUuid())) { return holder; } } } return null; } /** * Find a specific message in the message list. * * <p><strong>Note:</strong> * This method was optimized because it is called a lot. Don't change it unless you know * what you are doing.</p> * * @param messageReference * A {@link MessageReference} instance describing the message to look for. * * @return The corresponding {@link MessageInfoHolder} instance if the message was found in * the message list. {@code null} otherwise. */ private MessageInfoHolder getMessage(MessageReference messageReference) { String uid; for (MessageInfoHolder holder : mMessages) { uid = messageReference.uid; if ((holder.uid == uid || uid.equals(holder.uid)) && holder.folder.name.equals(messageReference.folderName) && holder.account.equals(messageReference.accountUuid)) { return holder; } } return null; } public FolderInfoHolder getFolder(String folder, Account account) { LocalFolder local_folder = null; try { LocalStore localStore = account.getLocalStore(); local_folder = localStore.getFolder(folder); return new FolderInfoHolder(context, local_folder, account); } catch (Exception e) { Log.e(K9.LOG_TAG, "getFolder(" + folder + ") goes boom: ", e); return null; } finally { if (local_folder != null) { local_folder.close(); } } } private final OnClickListener flagClickListener = new OnClickListener() { @Override public void onClick(View v) { // Perform action on clicks MessageInfoHolder message = (MessageInfoHolder) getItem((Integer)v.getTag()); onToggleFlag(Arrays.asList(new MessageInfoHolder[]{message})); } }; @Override public int getCount() { return mMessages.size(); } @Override public long getItemId(int position) { try { MessageInfoHolder messageHolder = (MessageInfoHolder) getItem(position); if (messageHolder != null) { return messageHolder.message.getId(); } } catch (Exception e) { Log.i(K9.LOG_TAG, "getItemId(" + position + ") ", e); } return -1; } @Override public Object getItem(int position) { try { if (position < mMessages.size()) { return mMessages.get(position); } } catch (Exception e) { Log.e(K9.LOG_TAG, "getItem(" + position + "), but folder.messages.size() = " + mMessages.size(), e); } return null; } @Override public View getView(int position, View convertView, ViewGroup parent) { MessageInfoHolder message = (MessageInfoHolder) getItem(position); View view; if ((convertView != null) && (convertView.getId() == R.layout.message_list_item)) { view = convertView; } else { view = mInflater.inflate(R.layout.message_list_item, parent, false); view.setId(R.layout.message_list_item); } MessageViewHolder holder = (MessageViewHolder) view.getTag(); if (holder == null) { holder = new MessageViewHolder(); holder.subject = (TextView) view.findViewById(R.id.subject); holder.from = (TextView) view.findViewById(R.id.from); holder.date = (TextView) view.findViewById(R.id.date); holder.chip = view.findViewById(R.id.chip); holder.preview = (TextView) view.findViewById(R.id.preview); holder.selected = (CheckBox) view.findViewById(R.id.selected_checkbox); holder.flagged = (CheckBox) view.findViewById(R.id.flagged); holder.flagged.setOnClickListener(flagClickListener); if (!mStars) { holder.flagged.setVisibility(View.GONE); } if (mCheckboxes) { holder.selected.setVisibility(View.VISIBLE); } if (holder.selected != null) { holder.selected.setOnCheckedChangeListener(holder); } holder.subject.setTextSize(TypedValue.COMPLEX_UNIT_SP, mFontSizes.getMessageListSubject()); holder.date.setTextSize(TypedValue.COMPLEX_UNIT_SP, mFontSizes.getMessageListDate()); holder.preview.setLines(mPreviewLines); holder.preview.setTextSize(TypedValue.COMPLEX_UNIT_SP, mFontSizes.getMessageListPreview()); view.setTag(holder); } if (message != null) { bindView(position, view, holder, message); } else { // This branch code is triggered when the local store // hands us an invalid message holder.chip.getBackground().setAlpha(0); holder.subject.setText(getString(R.string.general_no_subject)); holder.subject.setTypeface(null, Typeface.NORMAL); String noSender = getString(R.string.general_no_sender); if (holder.preview != null) { holder.preview.setText(noSender, TextView.BufferType.SPANNABLE); Spannable str = (Spannable) holder.preview.getText(); str.setSpan(new StyleSpan(Typeface.NORMAL), 0, noSender.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); str.setSpan(new AbsoluteSizeSpan(mFontSizes.getMessageListSender(), true), 0, noSender.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } else { holder.from.setText(noSender); holder.from.setTypeface(null, Typeface.NORMAL); holder.from.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null); } holder.date.setText(getString(R.string.general_no_date)); //WARNING: Order of the next 2 lines matter holder.position = -1; holder.selected.setChecked(false); if (!mCheckboxes) { holder.selected.setVisibility(View.GONE); } holder.flagged.setChecked(false); } return view; } /** * Associate model data to view object. * * @param position * The position of the item within the adapter's data set of * the item whose view we want. * @param view * Main view component to alter. Never <code>null</code>. * @param holder * Convenience view holder - eases access to <tt>view</tt> * child views. Never <code>null</code>. * @param message * Never <code>null</code>. */ private void bindView(final int position, final View view, final MessageViewHolder holder, final MessageInfoHolder message) { holder.subject.setTypeface(null, message.read ? Typeface.NORMAL : Typeface.BOLD); // XXX TODO there has to be some way to walk our view hierarchy and get this holder.flagged.setTag(position); holder.flagged.setChecked(message.flagged); // So that the mSelectedCount is only incremented/decremented // when a user checks the checkbox (vs code) holder.position = -1; holder.selected.setChecked(message.selected); if (!mCheckboxes) { holder.selected.setVisibility(message.selected ? View.VISIBLE : View.GONE); } holder.chip.setBackgroundDrawable(message.message.getFolder().getAccount().generateColorChip(message.read).drawable()); // TODO: Make these colors part of the theme if (K9.getK9Theme() == K9.THEME_LIGHT) { // Light theme: light grey background for read messages view.setBackgroundColor(message.read ? Color.rgb(229, 229, 229) : Color.rgb(255, 255, 255)); } else { // Dark theme: dark grey background for unread messages view.setBackgroundColor(message.read ? 0 : Color.rgb(45, 45, 45)); } if ((message.message.getSubject() == null) || message.message.getSubject().equals("")) { holder.subject.setText(getText(R.string.general_no_subject)); } else { holder.subject.setText(message.message.getSubject()); } int senderTypeface = message.read ? Typeface.NORMAL : Typeface.BOLD; if (holder.preview != null) { /* * Because text views can't wrap around each other(?) we * compose a custom view containing the preview and the * from. */ holder.preview.setText(new SpannableStringBuilder(recipientSigil(message)) .append(message.sender).append(" ").append(message.message.getPreview()), TextView.BufferType.SPANNABLE); Spannable str = (Spannable)holder.preview.getText(); // Create a span section for the sender, and assign the correct font size and weight. str.setSpan(new StyleSpan(senderTypeface), 0, message.sender.length() + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); str.setSpan(new AbsoluteSizeSpan(mFontSizes.getMessageListSender(), true), 0, message.sender.length() + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); // TODO: Make these colors part of the theme int color = (K9.getK9Theme() == K9.THEME_LIGHT) ? Color.rgb(105, 105, 105) : Color.rgb(160, 160, 160); // set span for preview message. str.setSpan(new ForegroundColorSpan(color), // How do I can specify the android.R.attr.textColorTertiary message.sender.length() + 1, str.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } else { holder.from.setText(new SpannableStringBuilder(recipientSigil(message)).append(message.sender)); holder.from.setTypeface(null, senderTypeface); } holder.date.setText(message.getDate(mMessageHelper)); Drawable statusHolder = null; if (message.forwarded && message.answered) { statusHolder = mForwardedAnsweredIcon; } else if (message.answered) { statusHolder = mAnsweredIcon; } else if (message.forwarded) { statusHolder = mForwardedIcon; } holder.subject.setCompoundDrawablesWithIntrinsicBounds(statusHolder, // left null, // top message.message.hasAttachments() ? mAttachmentIcon : null, // right null); // bottom holder.position = position; } private String recipientSigil(MessageInfoHolder message) { if (message.message.toMe()) { return getString(R.string.messagelist_sent_to_me_sigil); } else if (message.message.ccMe()) { return getString(R.string.messagelist_sent_cc_me_sigil); } else { return ""; } } @Override public boolean hasStableIds() { return true; } } class MessageViewHolder implements OnCheckedChangeListener { public TextView subject; public TextView preview; public TextView from; public TextView time; public TextView date; public CheckBox flagged; public View chip; public CheckBox selected; public int position = -1; @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (position != -1) { MessageInfoHolder message = (MessageInfoHolder) mAdapter.getItem(position); toggleMessageSelect(message); if (!mCheckboxes) { selected.setVisibility(isChecked ? View.VISIBLE : View.GONE); } } } } private View getFooterView(ViewGroup parent) { if (mFooterView == null) { mFooterView = mInflater.inflate(R.layout.message_list_item_footer, parent, false); mFooterView.setId(R.layout.message_list_item_footer); FooterViewHolder holder = new FooterViewHolder(); holder.progress = (ProgressBar) mFooterView.findViewById(R.id.message_list_progress); holder.progress.setIndeterminate(true); holder.main = (TextView) mFooterView.findViewById(R.id.main_text); mFooterView.setTag(holder); } return mFooterView; } private void updateFooterView() { FooterViewHolder holder = (FooterViewHolder) mFooterView.getTag(); if (mCurrentFolder != null && mAccount != null) { if (mCurrentFolder.loading) { holder.main.setText(getString(R.string.status_loading_more)); holder.progress.setVisibility(ProgressBar.VISIBLE); } else { if (!mCurrentFolder.lastCheckFailed) { if (mAccount.getDisplayCount() == 0) { holder.main.setText(getString(R.string.message_list_load_more_messages_action)); } else { holder.main.setText(String.format(getString(R.string.load_more_messages_fmt), mAccount.getDisplayCount())); } } else { holder.main.setText(getString(R.string.status_loading_more_failed)); } holder.progress.setVisibility(ProgressBar.INVISIBLE); } } else { holder.progress.setVisibility(ProgressBar.INVISIBLE); } } static class FooterViewHolder { public ProgressBar progress; public TextView main; } private void setAllSelected(boolean isSelected) { mSelectedCount = 0; for (MessageInfoHolder holder : mAdapter.getMessages()) { holder.selected = isSelected; mSelectedCount += (isSelected ? 1 : 0); } mAdapter.notifyDataSetChanged(); } /** * Toggle all selected message states. Sort of. If anything selected, unselect everything. If nothing is * selected, select everything. */ private void toggleAllSelected() { boolean newState = true; // If there was anything selected, unselect everything. if (mSelectedCount > 0) { newState = false; } mAdapter.setSelectionForAllMesages(newState); if (newState) { mSelectedCount = mAdapter.getCount(); mActionMode = MessageList.this.startActionMode(mActionModeCallback); mActionMode.setTitle(String.format(getString(R.string.actionbar_selected), mSelectedCount)); } else { mSelectedCount = 0; mActionMode.finish(); } } private void setSelected(final List<MessageInfoHolder> holders, final boolean newState) { for (final MessageInfoHolder holder : holders) { if (holder.selected != newState) { holder.selected = newState; mSelectedCount += (newState ? 1 : -1); } } mAdapter.notifyDataSetChanged(); } private void toggleMessageSelect(int position){ MessageInfoHolder holder = (MessageInfoHolder) mAdapter.getItem(position); toggleMessageSelect(holder); } private void toggleMessageSelect(final MessageInfoHolder holder){ if (mActionMode != null) { if (mSelectedCount == 1 && holder.selected) { mActionMode.finish(); return; } } else { mActionMode = MessageList.this.startActionMode(mActionModeCallback); } if (holder.selected) { holder.selected = false; mSelectedCount -= 1; } else { holder.selected = true; mSelectedCount += 1; } mAdapter.notifyDataSetChanged(); mActionMode.setTitle(String.format(getString(R.string.actionbar_selected), mSelectedCount)); // make sure the onPrepareActionMode is called mActionMode.invalidate(); } /** * @param holders * Messages to update. Never {@code null}. * @param flag * Flag to be updated on the specified messages. Never * {@code null}. * @param newState * State to set for the given flag. */ private void setFlag(final List<MessageInfoHolder> holders, final Flag flag, final boolean newState) { if (holders.isEmpty()) { return; } final Message[] messageList = new Message[holders.size()]; int i = 0; for (final Iterator<MessageInfoHolder> iterator = holders.iterator(); iterator.hasNext(); i++) { final MessageInfoHolder holder = iterator.next(); messageList[i] = holder.message; if (flag == Flag.SEEN) { holder.read = newState; } else if (flag == Flag.FLAGGED) { holder.flagged = newState; } } mController.setFlag(messageList, flag, newState); mAdapter.sortMessages(); } /** * Display the message move activity. * * @param holders * Never {@code null}. */ private void onMove(final List<MessageInfoHolder> holders) { if (!checkCopyOrMovePossible(holders, FolderOperation.MOVE)) { return; } final Folder folder = holders.size() == 1 ? holders.get(0).message.getFolder() : mCurrentFolder.folder; displayFolderChoice(ACTIVITY_CHOOSE_FOLDER_MOVE, folder, holders); } /** * Display the message copy activity. * * @param holders * Never {@code null}. */ private void onCopy(final List<MessageInfoHolder> holders) { if (!checkCopyOrMovePossible(holders, FolderOperation.COPY)) { return; } final Folder folder = holders.size() == 1 ? holders.get(0).message.getFolder() : mCurrentFolder.folder; displayFolderChoice(ACTIVITY_CHOOSE_FOLDER_COPY, folder, holders); } /** * Helper method to manage the invocation of * {@link #startActivityForResult(Intent, int)} for a folder operation * ({@link ChooseFolder} activity), while saving a list of associated * messages. * * @param requestCode * If >= 0, this code will be returned in onActivityResult() when * the activity exits. * @param folder * Never {@code null}. * @param holders * Messages to be affected by the folder operation. Never * {@code null}. * @see #startActivityForResult(Intent, int) */ private void displayFolderChoice(final int requestCode, final Folder folder, final List<MessageInfoHolder> holders) { final Intent intent = new Intent(this, ChooseFolder.class); intent.putExtra(ChooseFolder.EXTRA_ACCOUNT, folder.getAccount().getUuid()); intent.putExtra(ChooseFolder.EXTRA_CUR_FOLDER, folder.getName()); intent.putExtra(ChooseFolder.EXTRA_SEL_FOLDER, folder.getAccount().getLastSelectedFolderName()); // remember the selected messages for #onActivityResult mActiveMessages = holders; startActivityForResult(intent, requestCode); } /** * @param holders * Never {@code null}. */ private void onArchive(final List<MessageInfoHolder> holders) { final String folderName = holders.get(0).message.getFolder().getAccount().getArchiveFolderName(); if (K9.FOLDER_NONE.equalsIgnoreCase(folderName)) { return; } // TODO one should separate messages by account and call move afterwards // (because each account might have a specific Archive folder name) move(holders, folderName); } /** * @param holders * Never {@code null}. */ private void onSpam(final List<MessageInfoHolder> holders) { if (K9.confirmSpam()) { // remember the message selection for #onCreateDialog(int) mActiveMessages = holders; showDialog(R.id.dialog_confirm_spam); } else { onSpamConfirmed(holders); } } /** * @param holders * Never {@code null}. */ private void onSpamConfirmed(final List<MessageInfoHolder> holders) { final String folderName = holders.get(0).message.getFolder().getAccount().getSpamFolderName(); if (K9.FOLDER_NONE.equalsIgnoreCase(folderName)) { return; } // TODO one should separate messages by account and call move afterwards // (because each account might have a specific Spam folder name) move(holders, folderName); } private static enum FolderOperation { COPY, MOVE } /** * Display an Toast message if any message isn't synchronized * * @param holders * Never <code>null</code>. * @param operation * Never {@code null}. * * @return <code>true</code> if operation is possible */ private boolean checkCopyOrMovePossible(final List<MessageInfoHolder> holders, final FolderOperation operation) { if (holders.isEmpty()) { return false; } boolean first = true; for (final MessageInfoHolder holder : holders) { final Message message = holder.message; if (first) { first = false; // account check final Account account = message.getFolder().getAccount(); if ((operation == FolderOperation.MOVE && !mController.isMoveCapable(account)) || (operation == FolderOperation.COPY && !mController.isCopyCapable(account))) { return false; } } // message check if ((operation == FolderOperation.MOVE && !mController.isMoveCapable(message)) || (operation == FolderOperation.COPY && !mController.isCopyCapable(message))) { final Toast toast = Toast.makeText(this, R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG); toast.show(); return false; } } return true; } /** * Helper method to get a List of message ready to be processed. This implementation will return a list containing the sole argument. * * @param holder Never {@code null}. * @return Never {@code null}. */ private List<MessageInfoHolder> getSelectionFromMessage(final MessageInfoHolder holder) { final List<MessageInfoHolder> selection = Collections.singletonList(holder); return selection; } /** * Helper method to get a List of message ready to be processed. This implementation will iterate over messages and choose the checked ones. * * @return Never {@code null}. */ private List<MessageInfoHolder> getSelectionFromCheckboxes() { final List<MessageInfoHolder> selection = new ArrayList<MessageInfoHolder>(); for (final MessageInfoHolder holder : mAdapter.getMessages()) { if (holder.selected) { selection.add(holder); } } return selection; } /** * Copy the specified messages to the specified folder. * * @param holders Never {@code null}. * @param destination Never {@code null}. */ private void copy(final List<MessageInfoHolder> holders, final String destination) { copyOrMove(holders, destination, FolderOperation.COPY); } /** * Move the specified messages to the specified folder. * * @param holders Never {@code null}. * @param destination Never {@code null}. */ private void move(final List<MessageInfoHolder> holders, final String destination) { copyOrMove(holders, destination, FolderOperation.MOVE); } /** * The underlying implementation for {@link #copy(List, String)} and * {@link #move(List, String)}. This method was added mainly because those 2 * methods share common behavior. * * Note: Must be called from the UI thread! * * @param holders * Never {@code null}. * @param destination * Never {@code null}. * @param operation * Never {@code null}. */ private void copyOrMove(final List<MessageInfoHolder> holders, final String destination, final FolderOperation operation) { if (K9.FOLDER_NONE.equalsIgnoreCase(destination)) { return; } boolean first = true; Account account = null; String folderName = null; final List<Message> messages = new ArrayList<Message>(holders.size()); for (final MessageInfoHolder holder : holders) { final Message message = holder.message; if (first) { first = false; folderName = message.getFolder().getName(); account = message.getFolder().getAccount(); if ((operation == FolderOperation.MOVE && !mController.isMoveCapable(account)) || (operation == FolderOperation.COPY && !mController.isCopyCapable(account))) { // account is not copy/move capable return; } } else if (!account.equals(message.getFolder().getAccount()) || !folderName.equals(message.getFolder().getName())) { // make sure all messages come from the same account/folder? return; } if ((operation == FolderOperation.MOVE && !mController.isMoveCapable(message)) || (operation == FolderOperation.COPY && !mController.isCopyCapable(message))) { final Toast toast = Toast.makeText(this, R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG); toast.show(); // XXX return meaningful error value? // message isn't synchronized return; } messages.add(message); } if (operation == FolderOperation.MOVE) { mController.moveMessages(account, folderName, messages.toArray(new Message[messages.size()]), destination, null); mAdapter.removeMessages(holders); } else { mController.copyMessages(account, folderName, messages.toArray(new Message[messages.size()]), destination, null); } } protected void onAccountUnavailable() { finish(); // TODO inform user about account unavailability using Toast Accounts.listAccounts(this); } /** * Return the currently "open" account if available. * * @param prefs * A {@link Preferences} instance that might be used to retrieve the current * {@link Account}. * * @return The {@code Account} all displayed messages belong to. */ private Account getCurrentAccount(Preferences prefs) { Account account = null; if (mQueryString != null && !mIntegrate && mAccountUuids != null && mAccountUuids.length == 1) { String uuid = mAccountUuids[0]; account = prefs.getAccount(uuid); } else if (mAccount != null) { account = mAccount; } return account; } private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() { @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { // enable or disable forward, reply,.... menu.findItem(R.id.single_message_options) .setVisible(mSelectedCount > 1 ? false : true); if (mQueryString != null) { // show all menu.findItem(R.id.move).setVisible(true); menu.findItem(R.id.archive).setVisible(true); menu.findItem(R.id.spam).setVisible(true); menu.findItem(R.id.copy).setVisible(true); // hide uncapable /* * TODO think of a better way then looping over all * messages. */ final List<MessageInfoHolder> selection = getSelectionFromCheckboxes(); Account account; for (MessageInfoHolder holder : selection) { account = holder.message.getFolder().getAccount(); setContextCapabilities(account, menu); } } return true; } @Override public void onDestroyActionMode(ActionMode mode) { mActionMode = null; setAllSelected(false); } @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { MenuInflater inflater = mode.getMenuInflater(); inflater.inflate(R.menu.message_list_context, menu); // check capabilities if (mQueryString == null) { setContextCapabilities(mAccount, menu); } return true; } /** * Disables menu options based on if the account supports it or not. * It also checks the controller and for now the 'mode' the messagelist * is operation in ( query or not ). * * @param mAccount Account to check capabilities of. * @param menu Menu to adapt. */ private void setContextCapabilities(Account mAccount, Menu menu) { /* * TODO get rid of this when we finally split the messagelist into * a folder content display and a search result display */ if (mQueryString != null) { menu.findItem(R.id.move).setVisible(false); menu.findItem(R.id.copy).setVisible(false); menu.findItem(R.id.archive).setVisible(false); menu.findItem(R.id.spam).setVisible(false); return; } // hide unsupported if (!mController.isCopyCapable(mAccount)) { menu.findItem(R.id.copy).setVisible(false); } if (!mController.isMoveCapable(mAccount)) { menu.findItem(R.id.move).setVisible(false); menu.findItem(R.id.archive).setVisible(false); menu.findItem(R.id.spam).setVisible(false); } if (!mAccount.hasArchiveFolder()) { menu.findItem(R.id.archive).setVisible(false); } if (!mAccount.hasSpamFolder()) { menu.findItem(R.id.spam).setVisible(false); } } @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { final List<MessageInfoHolder> selection = getSelectionFromCheckboxes(); /* * In the following we assume that we can't move or copy * mails to the same folder. Also that spam isn't available if we are * in the spam folder,same for archive. * * This is the case currently so safe assumption. */ switch (item.getItemId()) { case R.id.delete: { onDelete(selection); mSelectedCount = 0; break; } case R.id.read_toggle: { onToggleRead(selection); break; } case R.id.flag_toggle: { onToggleFlag(selection); break; } // only if the account supports this case R.id.archive: { onArchive(selection); mSelectedCount = 0; break; } case R.id.spam: { onSpam(selection); mSelectedCount = 0; break; } case R.id.move: { onMove(selection); mSelectedCount = 0; break; } case R.id.copy: { onCopy(selection); mSelectedCount = 0; break; } // only if a single message is selected case R.id.reply: { onReply(selection.get(0)); mSelectedCount = 0; break; } case R.id.reply_all: { onReplyAll(selection.get(0)); mSelectedCount = 0; break; } case R.id.forward: { onForward(selection.get(0)); mSelectedCount = 0; break; } case R.id.send_again: { onResendMessage(selection.get(0)); mSelectedCount = 0; break; } case R.id.same_sender: { MessageList.actionHandle(MessageList.this, "From " + selection.get(0).sender, selection.get(0).senderAddress, false, null, null); mSelectedCount = 0; break; } } if (mSelectedCount == 0) { mActionMode.finish(); } return true; } }; }
package com.fsck.k9.activity; // import android.os.Debug; import android.app.AlertDialog; import android.app.Dialog; import android.app.NotificationManager; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; import android.util.Config; import android.util.Log; import android.view.*; import android.view.ContextMenu.ContextMenuInfo; import android.view.View.OnClickListener; import android.widget.*; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.CompoundButton.OnCheckedChangeListener; import com.fsck.k9.*; import com.fsck.k9.MessagingController.SORT_TYPE; import com.fsck.k9.activity.setup.AccountSettings; import com.fsck.k9.activity.setup.FolderSettings; import com.fsck.k9.mail.*; import com.fsck.k9.mail.Message.RecipientType; import com.fsck.k9.mail.store.LocalStore; import com.fsck.k9.mail.store.LocalStore.LocalFolder; import com.fsck.k9.mail.store.LocalStore.LocalMessage; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * MessageList is the primary user interface for the program. This * Activity shows a list of messages. * From this Activity the user can perform all standard message * operations. * */ public class MessageList extends K9Activity implements OnClickListener, AdapterView.OnItemClickListener { private static final int DIALOG_MARK_ALL_AS_READ = 1; private static final int ACTIVITY_CHOOSE_FOLDER_MOVE = 1; private static final int ACTIVITY_CHOOSE_FOLDER_COPY = 2; private static final String EXTRA_ACCOUNT = "account"; private static final String EXTRA_STARTUP = "startup"; private static final String EXTRA_FOLDER = "folder"; private static final String EXTRA_QUERY = "query"; private static final String STATE_KEY_LIST = "com.fsck.k9.activity.messagelist_state"; private static final String STATE_CURRENT_FOLDER = "com.fsck.k9.activity.messagelist_folder"; private static final String STATE_QUERY = "com.fsck.k9.activity.query"; private static final String STATE_KEY_SELECTION = "com.fsck.k9.activity.messagelist_selection"; private static final String STATE_KEY_SELECTED_COUNT = "com.fsck.k9.activity.messagelist_selected_count"; private static final int WIDGET_NONE = 1; private static final int WIDGET_FLAG = 2; private static final int WIDGET_MULTISELECT = 3; private static final int[] colorChipResIds = new int[] { R.drawable.appointment_indicator_leftside_1, R.drawable.appointment_indicator_leftside_2, R.drawable.appointment_indicator_leftside_3, R.drawable.appointment_indicator_leftside_4, R.drawable.appointment_indicator_leftside_5, R.drawable.appointment_indicator_leftside_6, R.drawable.appointment_indicator_leftside_7, R.drawable.appointment_indicator_leftside_8, R.drawable.appointment_indicator_leftside_9, R.drawable.appointment_indicator_leftside_10, R.drawable.appointment_indicator_leftside_11, R.drawable.appointment_indicator_leftside_12, R.drawable.appointment_indicator_leftside_13, R.drawable.appointment_indicator_leftside_14, R.drawable.appointment_indicator_leftside_15, R.drawable.appointment_indicator_leftside_16, R.drawable.appointment_indicator_leftside_17, R.drawable.appointment_indicator_leftside_18, R.drawable.appointment_indicator_leftside_19, R.drawable.appointment_indicator_leftside_20, R.drawable.appointment_indicator_leftside_21, }; private ListView mListView; private int mSelectedWidget = WIDGET_FLAG; private MessageListAdapter mAdapter; private FolderInfoHolder mCurrentFolder; private LayoutInflater mInflater; private MessagingController mController; private Account mAccount; private int mUnreadMessageCount = 0; /** * Stores the name of the folder that we want to open as soon as possible * after load. */ private String mFolderName; private String mQueryString; private MessageListHandler mHandler = new MessageListHandler(); private SORT_TYPE sortType = SORT_TYPE.SORT_DATE; private boolean sortAscending = true; private boolean sortDateAscending = false; private boolean mLeftHanded = false; private int mSelectedCount = 0; private View mBatchButtonArea; private Button mBatchReadButton; private Button mBatchDeleteButton; private Button mBatchFlagButton; class MessageListHandler extends Handler { public void removeMessage(final List<MessageInfoHolder> messages) { runOnUiThread(new Runnable() { public void run() { for (MessageInfoHolder message : messages) { if (mFolderName == null || message.folder.name.equals(mFolderName)) { if (message != null && message.selected && mSelectedCount > 0) { mSelectedCount } mAdapter.messages.remove(message); } } mAdapter.notifyDataSetChanged(); configureBatchButtons(); } }); } public void addMessages(List<MessageInfoHolder> messages) { final boolean wasEmpty = mAdapter.messages.isEmpty(); for (final MessageInfoHolder message : messages) { if (mFolderName == null || message.folder.name.equals(mFolderName)) { runOnUiThread(new Runnable() { public void run() { int index = Collections.binarySearch(mAdapter.messages, message); if (index < 0) { index = (index * -1) - 1; } mAdapter.messages.add(index, message); } }); } } runOnUiThread(new Runnable() { public void run() { if (wasEmpty) { mListView.setSelection(0); } mAdapter.notifyDataSetChanged(); } }); } private void sortMessages() { runOnUiThread(new Runnable() { public void run() { synchronized (mAdapter.messages) { Collections.sort(mAdapter.messages); } mAdapter.notifyDataSetChanged(); } }); } public void folderLoading(String folder, boolean loading) { if (mCurrentFolder != null && mCurrentFolder.name.equals(folder)) { mCurrentFolder.loading = loading; } } private void refreshTitle() { runOnUiThread(new Runnable() { public void run() { setWindowTitle(); setWindowProgress(); } }); } private void setWindowProgress() { int level = Window.PROGRESS_END; if (mCurrentFolder != null && mCurrentFolder.loading && mAdapter.mListener.getFolderTotal() > 0) { level = (Window.PROGRESS_END / mAdapter.mListener.getFolderTotal()) * (mAdapter.mListener.getFolderCompleted()) ; if (level > Window.PROGRESS_END) { level = Window.PROGRESS_END; } } getWindow().setFeatureInt(Window.FEATURE_PROGRESS, level); } private void setWindowTitle() { String displayName; if (mFolderName != null) { displayName = mFolderName; if (K9.INBOX.equalsIgnoreCase(displayName)) { displayName = getString(R.string.special_mailbox_name_inbox); } String dispString = mAdapter.mListener.formatHeader(MessageList.this, getString(R.string.message_list_title, mAccount.getDescription(), displayName), mUnreadMessageCount); setTitle(dispString); } else if (mQueryString != null) { setTitle(getString(R.string.search_results) + ": "+ mQueryString); } } public void progress(final boolean progress) { runOnUiThread(new Runnable() { public void run() { showProgressIndicator(progress); } }); } } /** * This class is responsible for loading the list of local messages for a * given folder */ public static void actionHandleFolder(Context context, Account account, String folder, boolean startup) { Intent intent = new Intent(context, MessageList.class); intent.putExtra(EXTRA_ACCOUNT, account); intent.putExtra(EXTRA_STARTUP, startup); if (folder != null) { intent.putExtra(EXTRA_FOLDER, folder); } context.startActivity(intent); } public void onItemClick(AdapterView parent, View v, int position, long id) { // Debug.stopMethodTracing(); if ( mCurrentFolder != null && ((position+1) == mAdapter.getCount()) ) { mController.loadMoreMessages( mAccount, mFolderName, mAdapter.mListener); return; } else if (mSelectedWidget == WIDGET_MULTISELECT) { CheckBox selected = (CheckBox) v.findViewById(R.id.selected_checkbox); selected.setChecked(!selected.isChecked()); } else { MessageInfoHolder message = (MessageInfoHolder) mAdapter.getItem(position); onOpenMessage(message); } } @Override public void onCreate(Bundle savedInstanceState) { // Debug.startMethodTracing("k9"); super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); requestWindowFeature(Window.FEATURE_PROGRESS); setContentView(R.layout.message_list); mListView = (ListView) findViewById(R.id.message_list); mListView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_INSET); mListView.setLongClickable(true); mListView.setFastScrollEnabled(true); mListView.setScrollingCacheEnabled(true); mListView.setOnItemClickListener(this); registerForContextMenu(mListView); /* * We manually save and restore the list's state because our adapter is * slow. */ mListView.setSaveEnabled(false); mInflater = getLayoutInflater(); mBatchButtonArea = findViewById(R.id.batch_button_area); mBatchReadButton = (Button) findViewById(R.id.batch_read_button); mBatchReadButton.setOnClickListener(this); mBatchDeleteButton = (Button) findViewById(R.id.batch_delete_button); mBatchDeleteButton.setOnClickListener(this); mBatchFlagButton = (Button) findViewById(R.id.batch_flag_button); mBatchFlagButton.setOnClickListener(this); Intent intent = getIntent(); mAccount = (Account)intent.getSerializableExtra(EXTRA_ACCOUNT); // Take the initial folder into account only if we are *not* restoring the // activity already if (savedInstanceState == null) { mFolderName = intent.getStringExtra(EXTRA_FOLDER); mQueryString = intent.getStringExtra(EXTRA_QUERY); if (mFolderName == null && mQueryString == null) { mFolderName = mAccount.getAutoExpandFolderName(); } } else { mFolderName = savedInstanceState.getString(STATE_CURRENT_FOLDER); mQueryString = savedInstanceState.getString(STATE_QUERY); mSelectedCount = savedInstanceState.getInt(STATE_KEY_SELECTED_COUNT); } if (mAccount != null) { mLeftHanded = mAccount.getLeftHanded(); } mAdapter = new MessageListAdapter(); final Object previousData = getLastNonConfigurationInstance(); if (previousData != null) { //noinspection unchecked mAdapter.messages.addAll((List<MessageInfoHolder>) previousData); } if (mFolderName != null) { mCurrentFolder = mAdapter.getFolder(mFolderName, mAccount); } mController = MessagingController.getInstance(getApplication()); mListView.setAdapter(mAdapter); if (savedInstanceState != null) { onRestoreListState(savedInstanceState); } } private void onRestoreListState(Bundle savedInstanceState) { mFolderName = savedInstanceState.getString(STATE_CURRENT_FOLDER); mQueryString = savedInstanceState.getString(STATE_QUERY); int selectedChild = savedInstanceState.getInt(STATE_KEY_SELECTION, -1); if (selectedChild != 0) { mListView.setSelection(selectedChild); } if (mFolderName != null) { mCurrentFolder = mAdapter.getFolder(mFolderName, mAccount); } mListView.onRestoreInstanceState(savedInstanceState.getParcelable(STATE_KEY_LIST)); } @Override public void onPause() { super.onPause(); //Debug.stopMethodTracing(); mController.removeListener(mAdapter.mListener); } /** * On resume we refresh * messages for the folder that is currently open. This guarantees that things * like unread message count and read status are updated. */ @Override public void onResume() { super.onResume(); sortType = mController.getSortType(); sortAscending = mController.isSortAscending(sortType); sortDateAscending = mController.isSortAscending(SORT_TYPE.SORT_DATE); mController.addListener(mAdapter.mListener); mAdapter.messages.clear(); mAdapter.notifyDataSetChanged(); if (mFolderName != null) { mController.listLocalMessagesSynchronous(mAccount, mFolderName, mAdapter.mListener); NotificationManager notifMgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notifMgr.cancel(mAccount.getAccountNumber()); notifMgr.cancel(-1000 - mAccount.getAccountNumber()); mController.getFolderUnreadMessageCount(mAccount, mFolderName, mAdapter.mListener); } else if (mQueryString != null) { mController.searchLocalMessages(mAccount, mQueryString, mAdapter.mListener); } mHandler.refreshTitle(); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelable(STATE_KEY_LIST, mListView.onSaveInstanceState()); outState.putInt(STATE_KEY_SELECTION, mListView .getSelectedItemPosition()); outState.putString(STATE_CURRENT_FOLDER, mFolderName); outState.putString(STATE_QUERY, mQueryString); outState.putInt(STATE_KEY_SELECTED_COUNT, mSelectedCount); } @Override public Object onRetainNonConfigurationInstance() { return mAdapter.messages; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { //Shortcuts that work no matter what is selected switch (keyCode) { case KeyEvent.KEYCODE_DPAD_LEFT: { if (mQueryString != null) { // no widget customization in search results yet return false; } else if (mBatchButtonArea.hasFocus()) { return false; } else { cycleVisibleWidgets(true); return true; } } case KeyEvent.KEYCODE_DPAD_RIGHT: { if (mQueryString != null) { // no widget customization in search results yet return false; } else if (mBatchButtonArea.hasFocus()) { return false; } else { cycleVisibleWidgets(false); return true; } } case KeyEvent.KEYCODE_C: { onCompose(); return true; } case KeyEvent.KEYCODE_Q: //case KeyEvent.KEYCODE_BACK: { onShowFolderList(); return true; } case KeyEvent.KEYCODE_O: { onCycleSort(); return true; } case KeyEvent.KEYCODE_I: { onToggleSortAscending(); return true; } case KeyEvent.KEYCODE_H: { Toast toast = Toast.makeText(this, R.string.message_list_help_key, Toast.LENGTH_LONG); toast.show(); return true; } }//switch int position = mListView.getSelectedItemPosition(); try { if (position >= 0) { MessageInfoHolder message = (MessageInfoHolder) mAdapter.getItem(position); if (message != null) { switch (keyCode) { case KeyEvent.KEYCODE_DEL: { onDelete(message, position); return true; } case KeyEvent.KEYCODE_D: { onDelete(message, position); return true; } case KeyEvent.KEYCODE_F: { onForward(message); return true; } case KeyEvent.KEYCODE_A: { onReplyAll(message); return true; } case KeyEvent.KEYCODE_R: { onReply(message); return true; } case KeyEvent.KEYCODE_G: { onToggleFlag(message); return true; } case KeyEvent.KEYCODE_M: { onMove(message); return true; } case KeyEvent.KEYCODE_Y: { onCopy(message); return true; } case KeyEvent.KEYCODE_Z: { onToggleRead(message); return true; } } } } } finally { return super.onKeyDown(keyCode, event); } }//onKeyDown private void onOpenMessage(MessageInfoHolder message) { if ( message.folder.name.equals(message.account.getDraftsFolderName())) { MessageCompose.actionEditDraft(this, message.account, message.message); } else { // Need to get the list before the sort starts ArrayList<String> messageUids = new ArrayList<String>(); for (MessageInfoHolder holder : mAdapter.messages) { messageUids.add(holder.uid); } MessageView.actionView(this, message.account, message.folder.name, message.uid, messageUids); } /* * We set read=true here for UI performance reasons. The actual value will * get picked up on the refresh when the Activity is resumed but that may * take a second or so and we don't want this to show and then go away. I've * gone back and forth on this, and this gives a better UI experience, so I * am putting it back in. */ if (!message.read) { message.read = true; mHandler.sortMessages(); } } public void cycleVisibleWidgets(boolean ascending) { if (ascending) { switch (mSelectedWidget) { case WIDGET_FLAG: { mSelectedWidget = WIDGET_MULTISELECT; break; } case WIDGET_MULTISELECT: { mSelectedWidget = WIDGET_NONE; break; } case WIDGET_NONE: { mSelectedWidget = WIDGET_FLAG; break; } } } else { switch (mSelectedWidget) { case WIDGET_FLAG: { mSelectedWidget=WIDGET_NONE; break; } case WIDGET_NONE: { mSelectedWidget=WIDGET_MULTISELECT; break; } case WIDGET_MULTISELECT: { mSelectedWidget=WIDGET_FLAG; break; } } } configureWidgets(); } private void configureWidgets() { switch (mSelectedWidget) { case WIDGET_FLAG: hideBatchButtons(); break; case WIDGET_NONE: hideBatchButtons(); break; case WIDGET_MULTISELECT: showBatchButtons(); break; } int count = mListView.getChildCount(); for (int i=0; i<count; i++) { setVisibleWidgetsForListItem(mListView.getChildAt(i), mSelectedWidget); } } private void setVisibleWidgetsForListItem(View v, int nextWidget) { Button flagged = (Button) v.findViewById(R.id.flagged); CheckBox selected = (CheckBox) v.findViewById(R.id.selected_checkbox); if (flagged == null || selected == null) { return; } if (nextWidget == WIDGET_NONE) { v.findViewById(R.id.widgets).setVisibility(View.GONE); return; } else { v.findViewById(R.id.widgets).setVisibility(View.VISIBLE); } if (nextWidget == WIDGET_MULTISELECT) { flagged.setVisibility(View.GONE); selected.setVisibility(View.VISIBLE); } else { flagged.setVisibility(View.VISIBLE); selected.setVisibility(View.GONE); } } private void onShowFolderList() { FolderList.actionHandleAccount(this, mAccount, false); finish(); } private void onCompose() { if (mQueryString != null) {// if we have a query string, we don't have an account, to let compose start the default action MessageCompose.actionCompose(this, null); } else { MessageCompose.actionCompose(this, mAccount); } } private void onEditAccount() { AccountSettings.actionSettings(this, mAccount); } private void changeSort(SORT_TYPE newSortType) { if (sortType == newSortType) { onToggleSortAscending(); } else { sortType = newSortType; mController.setSortType(sortType); sortAscending = mController.isSortAscending(sortType); sortDateAscending = mController.isSortAscending(SORT_TYPE.SORT_DATE); reSort(); } } private void reSort() { int toastString = sortType.getToast(sortAscending); Toast toast = Toast.makeText(this, toastString, Toast.LENGTH_SHORT); toast.show(); mHandler.sortMessages(); } private void onAccounts() { Accounts.listAccounts(this); finish(); } private void onCycleSort() { SORT_TYPE[] sorts = SORT_TYPE.values(); int curIndex = 0; for (int i = 0; i < sorts.length; i++) { if (sorts[i] == sortType) { curIndex = i; break; } } curIndex++; if (curIndex == sorts.length) { curIndex = 0; } changeSort(sorts[curIndex]); } private void onToggleSortAscending() { mController.setSortAscending(sortType, !sortAscending); sortAscending = mController.isSortAscending(sortType); sortDateAscending = mController.isSortAscending(SORT_TYPE.SORT_DATE); reSort(); } private void onDelete(MessageInfoHolder holder, int position) { mAdapter.removeMessage(holder); mController.deleteMessages(mAccount, holder.message.getFolder().getName(), new Message[] { holder.message }, null); mListView.setSelection(position); } private void onMove(MessageInfoHolder holder) { if (mController.isMoveCapable(mAccount) == false) { return; } if (mController.isMoveCapable(holder.message) == false) { Toast toast = Toast.makeText(this, R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG); toast.show(); return; } Intent intent = new Intent(this, ChooseFolder.class); intent.putExtra(ChooseFolder.EXTRA_ACCOUNT, mAccount); intent.putExtra(ChooseFolder.EXTRA_CUR_FOLDER, holder.folder.name); intent.putExtra(ChooseFolder.EXTRA_MESSAGE_UID, holder.message.getUid()); startActivityForResult(intent, ACTIVITY_CHOOSE_FOLDER_MOVE); } private void onCopy(MessageInfoHolder holder) { if (mController.isCopyCapable(mAccount) == false) { return; } if (mController.isCopyCapable(holder.message) == false) { Toast toast = Toast.makeText(this, R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG); toast.show(); return; } Intent intent = new Intent(this, ChooseFolder.class); intent.putExtra(ChooseFolder.EXTRA_ACCOUNT, mAccount); intent.putExtra(ChooseFolder.EXTRA_CUR_FOLDER, holder.folder.name); intent.putExtra(ChooseFolder.EXTRA_MESSAGE_UID, holder.message.getUid()); startActivityForResult(intent, ACTIVITY_CHOOSE_FOLDER_COPY); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) return; switch (requestCode) { case ACTIVITY_CHOOSE_FOLDER_MOVE: case ACTIVITY_CHOOSE_FOLDER_COPY: if (data == null) return; String destFolderName = data.getStringExtra(ChooseFolder.EXTRA_NEW_FOLDER); String uid = data.getStringExtra(ChooseFolder.EXTRA_MESSAGE_UID); MessageInfoHolder m = mAdapter.getMessage(uid); if (destFolderName != null && m != null) { switch (requestCode) { case ACTIVITY_CHOOSE_FOLDER_MOVE: onMoveChosen(m, destFolderName); break; case ACTIVITY_CHOOSE_FOLDER_COPY: onCopyChosen(m, destFolderName); break; } } } } private void onMoveChosen(MessageInfoHolder holder, String folderName) { if (mController.isMoveCapable(mAccount) == true && folderName != null) { mAdapter.removeMessage(holder); mController.moveMessage(mAccount, holder.message.getFolder().getName(), holder.message, folderName, null); } } private void onCopyChosen(MessageInfoHolder holder, String folderName) { if (mController.isCopyCapable(mAccount) == true && folderName != null) { mController.copyMessage(mAccount, holder.message.getFolder().getName(), holder.message, folderName, null); } } private void onReply(MessageInfoHolder holder) { MessageCompose.actionReply(this, mAccount, holder.message, false); } private void onReplyAll(MessageInfoHolder holder) { MessageCompose.actionReply(this, mAccount, holder.message, true); } private void onForward(MessageInfoHolder holder) { MessageCompose.actionForward(this, mAccount, holder.message); } private void onMarkAllAsRead(final Account account, final String folder) { showDialog(DIALOG_MARK_ALL_AS_READ); } private void onExpunge(final Account account, String folderName) { mController.expunge(account, folderName, null); } @Override public Dialog onCreateDialog(int id) { switch (id) { case DIALOG_MARK_ALL_AS_READ: return createMarkAllAsReadDialog(); } return super.onCreateDialog(id); } public void onPrepareDialog(int id, Dialog dialog) { switch (id) { case DIALOG_MARK_ALL_AS_READ: if (mCurrentFolder != null) { ((AlertDialog)dialog).setMessage(getString(R.string.mark_all_as_read_dlg_instructions_fmt, mCurrentFolder.displayName)); } break; default: super.onPrepareDialog(id, dialog); } } private Dialog createMarkAllAsReadDialog() { return new AlertDialog.Builder(this) .setTitle(R.string.mark_all_as_read_dlg_title) .setMessage(getString(R.string.mark_all_as_read_dlg_instructions_fmt, mCurrentFolder.displayName)) .setPositiveButton(R.string.okay_action, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dismissDialog(DIALOG_MARK_ALL_AS_READ); try { mController.markAllMessagesRead(mAccount, mCurrentFolder.name); for (MessageInfoHolder holder : mAdapter.messages) { holder.read = true; } mHandler.sortMessages(); } catch (Exception e) { // Ignore } } }) .setNegativeButton(R.string.cancel_action, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dismissDialog(DIALOG_MARK_ALL_AS_READ); } }) .create(); } private void onToggleRead(MessageInfoHolder holder) { mController.setFlag(holder.account, holder.message.getFolder().getName(), new String[] { holder.uid }, Flag.SEEN, !holder.read); holder.read = !holder.read; mHandler.sortMessages(); } private void onToggleFlag(MessageInfoHolder holder) { mController.setFlag(holder.account, holder.message.getFolder().getName(), new String[] { holder.uid }, Flag.FLAGGED, !holder.flagged); holder.flagged = !holder.flagged; mHandler.sortMessages(); } private void checkMail(Account account, String folderName) { mController.synchronizeMailbox(account, folderName, mAdapter.mListener); sendMail(account); } private void sendMail(Account account) { mController.sendPendingMessages(account, mAdapter.mListener); } @Override public boolean onOptionsItemSelected(MenuItem item) { int itemId = item.getItemId(); switch (itemId) { case R.id.check_mail: if (mFolderName != null) { checkMail(mAccount, mFolderName); } return true; case R.id.send_messages: sendMail(mAccount); return true; case R.id.compose: onCompose(); return true; case R.id.accounts: onAccounts(); return true; case R.id.set_sort_date: changeSort(SORT_TYPE.SORT_DATE); return true; case R.id.set_sort_subject: changeSort(SORT_TYPE.SORT_SUBJECT); return true; case R.id.set_sort_sender: changeSort(SORT_TYPE.SORT_SENDER); return true; case R.id.set_sort_flag: changeSort(SORT_TYPE.SORT_FLAGGED); return true; case R.id.set_sort_unread: changeSort(SORT_TYPE.SORT_UNREAD); return true; case R.id.set_sort_attach: changeSort(SORT_TYPE.SORT_ATTACHMENT); return true; case R.id.list_folders: onShowFolderList(); return true; } if (mQueryString != null) { return false; // none of the options after this point are "safe" for search results } switch (itemId) { case R.id.mark_all_as_read: if (mFolderName != null) { onMarkAllAsRead(mAccount, mFolderName); } return true; case R.id.folder_settings: if (mFolderName != null) { FolderSettings.actionSettings(this, mAccount, mFolderName); } return true; case R.id.account_settings: onEditAccount(); return true; case R.id.batch_select_all: setAllSelected(true); return true; case R.id.batch_deselect_all: setAllSelected(false); return true; case R.id.batch_copy_op: moveOrCopySelected(false); return true; case R.id.batch_move_op: moveOrCopySelected(true); return true; case R.id.batch_delete_op: deleteSelected(); return true; case R.id.batch_mark_read_op: flagSelected(Flag.SEEN, true); return true; case R.id.batch_mark_unread_op: flagSelected(Flag.SEEN, false); return true; case R.id.batch_flag_op: flagSelected(Flag.FLAGGED, true); return true; case R.id.batch_unflag_op: flagSelected(Flag.FLAGGED, false); return true; case R.id.batch_plain_mode: mSelectedWidget = WIDGET_NONE; configureWidgets(); return true; case R.id.batch_select_mode: mSelectedWidget = WIDGET_MULTISELECT; configureWidgets(); return true; case R.id.batch_flag_mode: mSelectedWidget = WIDGET_FLAG; configureWidgets(); return true; case R.id.expunge: if (mCurrentFolder != null) { onExpunge(mAccount, mCurrentFolder.name); } return true; default: return super.onOptionsItemSelected(item); } } private final int[] batch_ops = { R.id.batch_copy_op, R.id.batch_delete_op, R.id.batch_flag_op, R.id.batch_unflag_op, R.id.batch_mark_read_op, R.id.batch_mark_unread_op, R.id.batch_move_op , R.id.batch_select_all, R.id.batch_deselect_all }; private final int[] batch_modes = { R.id.batch_flag_mode, R.id.batch_select_mode, R.id.batch_plain_mode }; private void setOpsState(Menu menu, boolean state, boolean enabled) { for (int id : batch_ops) { menu.findItem(id).setVisible(state); menu.findItem(id).setEnabled(enabled); } } private void setOpsMode(Menu menu, int currentModeId) { for (int id : batch_modes) { menu.findItem(id).setVisible(id != currentModeId); } } @Override public boolean onPrepareOptionsMenu(Menu menu) { if (mQueryString != null) { menu.findItem(R.id.batch_ops).setVisible(false); menu.findItem(R.id.mark_all_as_read).setVisible(false); menu.findItem(R.id.folder_settings).setVisible(false); menu.findItem(R.id.account_settings).setVisible(false); menu.findItem(R.id.list_folders).setVisible(false); menu.findItem(R.id.expunge).setVisible(false); } switch (mSelectedWidget) { case WIDGET_FLAG: { setOpsState(menu, false, false); setOpsMode(menu, R.id.batch_flag_mode); break; } case WIDGET_MULTISELECT: { boolean anySelected = anySelected(); setOpsState(menu, true, anySelected); setOpsMode(menu, R.id.batch_select_mode); boolean newFlagState = computeBatchDirection(true); boolean newReadState = computeBatchDirection(false); menu.findItem(R.id.batch_flag_op).setVisible(newFlagState); menu.findItem(R.id.batch_unflag_op).setVisible(!newFlagState); menu.findItem(R.id.batch_mark_read_op).setVisible(newReadState); menu.findItem(R.id.batch_mark_unread_op).setVisible(!newReadState); menu.findItem(R.id.batch_deselect_all).setEnabled(anySelected); menu.findItem(R.id.batch_select_all).setEnabled(true); // TODO: batch move and copy not yet implemented menu.findItem(R.id.batch_move_op).setVisible(false); menu.findItem(R.id.batch_copy_op).setVisible(false); break; } case WIDGET_NONE: { setOpsState(menu, false, false); setOpsMode(menu, R.id.batch_plain_mode); break; } } if (mCurrentFolder != null && mCurrentFolder.outbox) { menu.findItem(R.id.check_mail).setVisible(false); } else { menu.findItem(R.id.send_messages).setVisible(false); } if (mCurrentFolder != null && K9.ERROR_FOLDER_NAME.equals(mCurrentFolder.name)) { menu.findItem(R.id.expunge).setVisible(false); } return true; } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.message_list_option, menu); return true; } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item .getMenuInfo(); MessageInfoHolder holder = (MessageInfoHolder) mAdapter.getItem(info.position); switch (item.getItemId()) { case R.id.open: onOpenMessage(holder); break; case R.id.delete: onDelete(holder, info.position); break; case R.id.reply: onReply(holder); break; case R.id.reply_all: onReplyAll(holder); break; case R.id.forward: onForward(holder); break; case R.id.mark_as_read: onToggleRead(holder); break; case R.id.flag: onToggleFlag(holder); break; case R.id.move: onMove(holder); break; case R.id.copy: onCopy(holder); break; case R.id.send_alternate: onSendAlternate(mAccount, holder); break; } return super.onContextItemSelected(item); } public void onSendAlternate(Account account, MessageInfoHolder holder) { mController.sendAlternate(this, account, holder.message); } public void showProgressIndicator(boolean status) { setProgressBarIndeterminateVisibility(status); ProgressBar bar = (ProgressBar)mListView.findViewById(R.id.message_list_progress); if (bar == null) { return; } bar.setIndeterminate(true); if (status) { bar.setVisibility(bar.VISIBLE); } else { bar.setVisibility(bar.INVISIBLE); } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; MessageInfoHolder message = (MessageInfoHolder) mAdapter.getItem(info.position); if (message == null) { return; } getMenuInflater().inflate(R.menu.message_list_context, menu); menu.setHeaderTitle((CharSequence) message.subject); if (message.read) { menu.findItem(R.id.mark_as_read).setTitle(R.string.mark_as_unread_action); } if (message.flagged) { menu.findItem(R.id.flag).setTitle(R.string.unflag_action); } if (mController.isCopyCapable(mAccount) == false) { menu.findItem(R.id.copy).setVisible(false); } if (mController.isMoveCapable(mAccount) == false) { menu.findItem(R.id.move).setVisible(false); } } class MessageListAdapter extends BaseAdapter { private List<MessageInfoHolder> messages = java.util.Collections.synchronizedList(new ArrayList<MessageInfoHolder>()); private ActivityListener mListener = new ActivityListener() { @Override public void synchronizeMailboxStarted(Account account, String folder) { super.synchronizeMailboxStarted(account, folder); if (updateForMe(account, folder)) { mHandler.progress(true); mHandler.folderLoading(folder, true); } mHandler.refreshTitle(); } @Override public void synchronizeMailboxFinished(Account account, String folder, int totalMessagesInMailbox, int numNewMessages) { super.synchronizeMailboxFinished(account, folder, totalMessagesInMailbox, numNewMessages); if (updateForMe(account, folder)) { mHandler.progress(false); mHandler.folderLoading(folder, false); mHandler.sortMessages(); } mHandler.refreshTitle(); } @Override public void synchronizeMailboxFailed(Account account, String folder, String message) { super.synchronizeMailboxFailed(account, folder, message); if (updateForMe(account, folder)) { mHandler.progress(false); mHandler.folderLoading(folder, false); mHandler.sortMessages(); } mHandler.refreshTitle(); } @Override public void sendPendingMessagesStarted(Account account) { super.sendPendingMessagesStarted(account); mHandler.refreshTitle(); } @Override public void sendPendingMessagesCompleted(Account account) { super.sendPendingMessagesCompleted(account); mHandler.refreshTitle(); } @Override public void sendPendingMessagesFailed(Account account) { super.sendPendingMessagesFailed(account); mHandler.refreshTitle(); } @Override public void synchronizeMailboxProgress(Account account, String folder, int completed, int total) { super.synchronizeMailboxProgress(account, folder, completed, total); mHandler.refreshTitle(); } @Override public void synchronizeMailboxAddOrUpdateMessage(Account account, String folder, Message message) { // eventually, we may want to check a message added during sync against the query filter if (mQueryString == null) { addOrUpdateMessage(account, folder, message); } } @Override public void synchronizeMailboxRemovedMessage(Account account, String folder,Message message) { removeMessage(getMessage(message.getUid())); } @Override public void listLocalMessagesStarted(Account account, String folder) { if ((mQueryString != null && folder == null) || (account != null && account.equals(mAccount)) ) { mHandler.progress(true); if (folder != null) { mHandler.folderLoading(folder, true); } } } @Override public void listLocalMessagesFailed(Account account, String folder, String message) { if ((mQueryString != null && folder == null) || (account != null && account.equals(mAccount))) { mHandler.sortMessages(); mHandler.progress(false); if (folder != null) { mHandler.folderLoading(folder, false); } } } @Override public void listLocalMessagesFinished(Account account, String folder) { if ((mQueryString != null && folder == null) || (account != null && account.equals(mAccount))) { mHandler.sortMessages(); mHandler.progress(false); if (folder != null) { mHandler.folderLoading(folder, false); } } } @Override public void listLocalMessagesRemoveMessage(Account account, String folder,Message message) { if (updateForMe(account, folder)) { MessageInfoHolder holder = getMessage(message.getUid()); if (holder != null) { removeMessage(getMessage(message.getUid())); } } } @Override public void listLocalMessagesAddMessages(Account account, String folder, List<Message> messages) { addOrUpdateMessages(account, folder, messages); } @Override public void listLocalMessagesUpdateMessage(Account account, String folder, Message message) { addOrUpdateMessage(account, folder, message); } @Override public void folderStatusChanged(Account account, String folder, int unreadMessageCount) { if (updateForMe(account, folder)) { mUnreadMessageCount = unreadMessageCount; mHandler.refreshTitle(); } } public void pendingCommandsProcessing(Account account) { super.pendingCommandsProcessing(account); mHandler.refreshTitle(); } public void pendingCommandsFinished(Account account) { super.pendingCommandsFinished(account); mHandler.refreshTitle(); } public void pendingCommandStarted(Account account, String commandTitle) { super.pendingCommandStarted(account, commandTitle); mHandler.refreshTitle(); } public void pendingCommandCompleted(Account account, String commandTitle) { super.pendingCommandCompleted(account, commandTitle); mHandler.refreshTitle(); } }; private boolean updateForMe(Account account, String folder) { if (mQueryString != null || (account.equals(mAccount) && mFolderName != null && folder.equals(mFolderName))) { return true; } else { return false; } } private Drawable mAttachmentIcon; private Drawable mAnsweredIcon; private View footerView = null; MessageListAdapter() { mAttachmentIcon = getResources().getDrawable(R.drawable.ic_mms_attachment_small); mAnsweredIcon = getResources().getDrawable(R.drawable.ic_mms_answered_small); } public void removeMessages(List<MessageInfoHolder> holders) { if (holders != null) { mHandler.removeMessage(holders); } } public void removeMessage(MessageInfoHolder holder) { List<MessageInfoHolder> messages = new ArrayList<MessageInfoHolder>(); messages.add(holder); removeMessages(messages); } private void addOrUpdateMessage(Account account, String folder, Message message) { List<Message> messages = new ArrayList<Message>(); messages.add(message); addOrUpdateMessages(account, folder, messages); } private void addOrUpdateMessages(Account account, String folder, List<Message> messages) { boolean needsSort = false; List<MessageInfoHolder> messagesToAdd = new ArrayList<MessageInfoHolder>(); List<MessageInfoHolder> messagesToRemove = new ArrayList<MessageInfoHolder>(); FolderInfoHolder f = mCurrentFolder; // This is wrong, but what the old code did. for (Message message : messages) { if (updateForMe(account, folder)) { MessageInfoHolder m = getMessage(message.getUid()); if (m == null) { m = new MessageInfoHolder(message, account); messagesToAdd.add(m); } else { if (message.isSet(Flag.DELETED)) { messagesToRemove.add(m); } else { m.populate(message, new FolderInfoHolder(message.getFolder(), account), account); needsSort = true; } } } } if (messagesToRemove.size() > 0) { removeMessages(messagesToRemove); } if (messagesToAdd.size() > 0) { mHandler.addMessages(messagesToAdd); } if (needsSort) { mHandler.sortMessages(); } } // XXX TODO - make this not use a for loop public MessageInfoHolder getMessage(String messageUid) { MessageInfoHolder searchHolder = new MessageInfoHolder(); searchHolder.uid = messageUid; int index = mAdapter.messages.indexOf((Object) searchHolder); if (index >= 0) { return (MessageInfoHolder)mAdapter.messages.get(index); } return null; } public FolderInfoHolder getFolder(String folder, Account account) { LocalFolder local_folder = null; try { LocalStore localStore = (LocalStore)Store.getInstance(account.getLocalStoreUri(), getApplication()); local_folder = localStore.getFolder(folder); return new FolderInfoHolder((Folder)local_folder, account); } catch (Exception e) { Log.e(K9.LOG_TAG, "getFolder(" + folder + ") goes boom: ",e); return null; } finally { if (local_folder != null) { local_folder.close(); } } } private static final int NON_MESSAGE_ITEMS = 1; public int getCount() { if (mAdapter.messages == null || mAdapter.messages.size() == 0) { return NON_MESSAGE_ITEMS ; } return mAdapter.messages.size() +NON_MESSAGE_ITEMS ; } public long getItemId(int position) { try { MessageInfoHolder messageHolder =(MessageInfoHolder) getItem(position); if (messageHolder != null) { return ((LocalStore.LocalMessage) messageHolder.message).getId(); } } catch (Exception e) { Log.i(K9.LOG_TAG,"getItemId("+position+") ",e); } return -1; } public Object getItem(long position) { return getItem((int)position); } public Object getItem(int position) { try { if (position < mAdapter.messages.size()) { return mAdapter.messages.get(position); } } catch (Exception e) { Log.e(K9.LOG_TAG, "getItem(" + position + "), but folder.messages.size() = " + mAdapter.messages.size(), e); } return null; } public View getView(int position, View convertView, ViewGroup parent) { if (position == mAdapter.messages.size()) { return getFooterView(position, convertView, parent); } else { return getItemView(position, convertView, parent); } } public View getItemView(int position, View convertView, ViewGroup parent) { MessageInfoHolder message = (MessageInfoHolder) getItem(position); View view; if ((convertView != null) && (convertView.getId() == R.layout.message_list_item)) { view = convertView; } else { view = mInflater.inflate(R.layout.message_list_item, parent, false); view.setId(R.layout.message_list_item); View widgetParent; if (mLeftHanded == false) { widgetParent = view.findViewById(R.id.widgets_right); } else { widgetParent = view.findViewById(R.id.widgets_left); } View widgets = mInflater.inflate(R.layout.message_list_widgets,parent,false); widgets.setId(R.id.widgets); ((LinearLayout) widgetParent).addView(widgets); } MessageViewHolder holder = (MessageViewHolder) view.getTag(); if (holder == null) { holder = new MessageViewHolder(); holder.subject = (TextView) view.findViewById(R.id.subject); holder.from = (TextView) view.findViewById(R.id.from); holder.date = (TextView) view.findViewById(R.id.date); holder.chip = view.findViewById(R.id.chip); holder.flagged = (CheckBox) view.findViewById(R.id.flagged); holder.flagged.setOnClickListener(new OnClickListener() { public void onClick(View v) { // Perform action on clicks MessageInfoHolder message = (MessageInfoHolder) getItem((Integer)v.getTag()); onToggleFlag(message); } }); holder.chip.setBackgroundResource(colorChipResIds[message.account.getAccountNumber() % colorChipResIds.length]); holder.selected = (CheckBox) view.findViewById(R.id.selected_checkbox); if (holder.selected!=null) { holder.selected.setOnCheckedChangeListener(holder); } view.setTag(holder); } if (message != null) { holder.subject.setTypeface(null, message.read ? Typeface.NORMAL : Typeface.BOLD); setVisibleWidgetsForListItem(view, mSelectedWidget); // XXX TODO there has to be some way to walk our view hierarchy and get this holder.flagged.setTag((Integer)position); holder.flagged.setChecked(message.flagged); //So that the mSelectedCount is only incremented/decremented //when a user checks the checkbox (vs code) holder.position = -1; holder.selected.setChecked(message.selected); holder.chip.getBackground().setAlpha(message.read ? 127 : 255); if (message.downloaded) { view.getBackground().setAlpha(0); } else { view.getBackground().setAlpha(127); } holder.subject.setText(message.subject); holder.from.setText(message.sender); holder.from.setTypeface(null, message.read ? Typeface.NORMAL : Typeface.BOLD); holder.date.setText(message.date); holder.subject.setCompoundDrawablesWithIntrinsicBounds( message.answered ? mAnsweredIcon : null, // left null, // top message.hasAttachments ? mAttachmentIcon : null, // right null); // bottom holder.position = position; } else { holder.chip.getBackground().setAlpha(0); holder.subject.setText("No subject"); holder.subject.setTypeface(null, Typeface.NORMAL); holder.from.setText("No sender"); holder.from.setTypeface(null, Typeface.NORMAL); holder.date.setText("No date"); holder.from.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null); //WARNING: Order of the next 2 lines matter holder.position = -1; holder.selected.setChecked(false); holder.flagged.setChecked(false); } return view; } public View getFooterView(int position, View convertView, ViewGroup parent) { if (footerView == null) { footerView = mInflater.inflate(R.layout.message_list_item_footer, parent, false); if (mQueryString != null) { footerView.setVisibility(View.GONE); } footerView.setId(R.layout.message_list_item_footer); FooterViewHolder holder = new FooterViewHolder(); holder.progress = (ProgressBar)footerView.findViewById(R.id.message_list_progress); holder.progress.setIndeterminate(true); holder.main = (TextView)footerView.findViewById(R.id.main_text); footerView.setTag(holder); } FooterViewHolder holder = (FooterViewHolder)footerView.getTag(); if (mCurrentFolder != null && mCurrentFolder.loading) { holder.main.setText(getString(R.string.status_loading_more)); holder.progress.setVisibility(ProgressBar.VISIBLE); } else { if (mCurrentFolder != null && mCurrentFolder.lastCheckFailed == false) { holder.main.setText(String.format(getString(R.string.load_more_messages_fmt), mAccount.getDisplayCount())); } else { holder.main.setText(getString(R.string.status_loading_more_failed)); } holder.progress.setVisibility(ProgressBar.INVISIBLE); } return footerView; } public boolean hasStableIds() { return true; } public boolean isItemSelectable(int position) { if (position < mAdapter.messages.size()) { return true; } else { return false; } } } public class MessageInfoHolder implements Comparable<MessageInfoHolder> { public String subject; public String date; public Date compareDate; public String compareSubject; public String sender; public String compareCounterparty; public String[] recipients; public boolean hasAttachments; public String uid; public boolean read; public boolean answered; public boolean flagged; public boolean downloaded; public boolean partially_downloaded; public Message message; public Account account; public FolderInfoHolder folder; public boolean selected; // Empty constructor for comparison public MessageInfoHolder() { this.selected = false; } public MessageInfoHolder(Message m, Account account) { this(); populate(m, new FolderInfoHolder(m.getFolder(), account), account); } public MessageInfoHolder(Message m, FolderInfoHolder folder, Account account) { this(); populate(m, folder, account); } public void populate(Message m, FolderInfoHolder folder, Account account) { try { LocalMessage message = (LocalMessage) m; Date date = message.getSentDate(); this.compareDate = date; this.folder = folder; if (Utility.isDateToday(date)) { this.date = getTimeFormat().format(date); } else { this.date = getDateFormat().format(date); } this.hasAttachments = message.getAttachmentCount() > 0; this.read = message.isSet(Flag.SEEN); this.answered = message.isSet(Flag.ANSWERED); this.flagged = message.isSet(Flag.FLAGGED); this.downloaded = message.isSet(Flag.X_DOWNLOADED_FULL); this.partially_downloaded = message.isSet(Flag.X_DOWNLOADED_PARTIAL); Address[] addrs = message.getFrom(); if (addrs.length > 0 && account.isAnIdentity(addrs[0])) { this.compareCounterparty = Address.toFriendly(message .getRecipients(RecipientType.TO)); this.sender = String.format(getString(R.string.message_list_to_fmt), this.compareCounterparty); } else { this.sender = Address.toFriendly(addrs); this.compareCounterparty = this.sender; } this.subject = message.getSubject(); this.uid = message.getUid(); this.message = m; this.account = account; } catch (MessagingException me) { if (Config.LOGV) { Log.v(K9.LOG_TAG, "Unable to load message info", me); } } } public boolean equals(Object o) { if (this.uid.equals(((MessageInfoHolder)o).uid)) { return true; } else { return false; } } public int compareTo(MessageInfoHolder o) { int ascender = (sortAscending ? 1 : -1); int comparison = 0; if (sortType == SORT_TYPE.SORT_SUBJECT) { if (compareSubject == null) { compareSubject = stripPrefixes(subject).toLowerCase(); } if (o.compareSubject == null) { o.compareSubject = stripPrefixes(o.subject).toLowerCase(); } comparison = this.compareSubject.compareTo(o.compareSubject); } else if (sortType == SORT_TYPE.SORT_SENDER) { comparison = this.compareCounterparty.toLowerCase().compareTo(o.compareCounterparty.toLowerCase()); } else if (sortType == SORT_TYPE.SORT_FLAGGED) { comparison = (this.flagged ? 0 : 1) - (o.flagged ? 0 : 1); } else if (sortType == SORT_TYPE.SORT_UNREAD) { comparison = (this.read ? 1 : 0) - (o.read ? 1 : 0); } else if (sortType == SORT_TYPE.SORT_ATTACHMENT) { comparison = (this.hasAttachments ? 0 : 1) - (o.hasAttachments ? 0 : 1); } if (comparison != 0) { return comparison * ascender; } int dateAscender = (sortDateAscending ? 1 : -1); return this.compareDate.compareTo(o.compareDate) * dateAscender; } Pattern pattern = null; String patternString = "^ *(re|aw|fw|fwd): *"; private String stripPrefixes(String in) { synchronized (patternString) { if (pattern == null) { pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE); } } Matcher matcher = pattern.matcher(in); int lastPrefix = -1; while (matcher.find()) { lastPrefix = matcher.end(); } if (lastPrefix > -1 && lastPrefix < in.length() - 1) { return in.substring(lastPrefix); } else { return in; } } } class MessageViewHolder implements OnCheckedChangeListener { public TextView subject; public TextView preview; public TextView from; public TextView time; public TextView date; public CheckBox flagged; public View chip; public CheckBox selected; public int position = -1; public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (position!=-1) { MessageInfoHolder message = (MessageInfoHolder) mAdapter.getItem(position); if (message.selected!=isChecked) { if (isChecked) { mSelectedCount++; } else if (mSelectedCount > 0) { mSelectedCount } showBatchButtons(); message.selected = isChecked; } } } } private void enableBatchButtons() { mBatchDeleteButton.setEnabled(true); mBatchReadButton.setEnabled(true); mBatchFlagButton.setEnabled(true); } private void disableBatchButtons() { mBatchDeleteButton.setEnabled(false); mBatchReadButton.setEnabled(false); mBatchFlagButton.setEnabled(false); } private void hideBatchButtons() { //TODO: Fade out animation mBatchButtonArea.setVisibility(View.GONE); } private void showBatchButtons() { configureBatchButtons(); //TODO: Fade in animation mBatchButtonArea.setVisibility(View.VISIBLE); } private void configureBatchButtons() { if (mSelectedCount < 0) { mSelectedCount = 0; } if (mSelectedCount==0) { disableBatchButtons(); } else { enableBatchButtons(); } } class FooterViewHolder { public ProgressBar progress; public TextView main; } public class FolderInfoHolder { public String name; public String displayName; public boolean loading; public boolean lastCheckFailed; public Folder folder; /** * Outbox is handled differently from any other folder. */ public boolean outbox; public FolderInfoHolder(Folder folder, Account account) { populate(folder, account); } public void populate(Folder folder, Account account) { this.folder = folder; this.name = folder.getName(); if (this.name.equalsIgnoreCase(K9.INBOX)) { this.displayName = getString(R.string.special_mailbox_name_inbox); } else { this.displayName = this.name; } if (this.name.equals(account.getOutboxFolderName())) { this.displayName = String.format(getString(R.string.special_mailbox_name_outbox_fmt), this.name); this.outbox = true; } if (this.name.equals(account.getDraftsFolderName())) { this.displayName = String.format(getString(R.string.special_mailbox_name_drafts_fmt), this.name); } if (this.name.equals(account.getTrashFolderName())) { this.displayName = String.format(getString(R.string.special_mailbox_name_trash_fmt), this.name); } if (this.name.equals(account.getSentFolderName())) { this.displayName = String.format(getString(R.string.special_mailbox_name_sent_fmt), this.name); } } } private boolean computeBatchDirection(boolean flagged) { boolean newState = false; for (MessageInfoHolder holder : mAdapter.messages) { if (holder.selected) { if (flagged) { if (!holder.flagged) { newState = true; } } else { if (!holder.read) { newState = true; } } } } return newState; } private boolean anySelected() { for (MessageInfoHolder holder : mAdapter.messages) { if (holder.selected) { return true; } } return false; } public void onClick(View v) { boolean newState = false; List<Message> messageList = new ArrayList<Message>(); List<MessageInfoHolder> removeHolderList = new ArrayList<MessageInfoHolder>(); if (v == mBatchFlagButton) { newState = computeBatchDirection(true); } else { newState = computeBatchDirection(false); } for (MessageInfoHolder holder : mAdapter.messages) { if (holder.selected) { if (v == mBatchDeleteButton) { removeHolderList.add(holder); } else if (v == mBatchFlagButton) { holder.flagged = newState; } else if (v == mBatchReadButton) { holder.read = newState; } messageList.add(holder.message); } } mAdapter.removeMessages(removeHolderList); if (!messageList.isEmpty()) { if (mBatchDeleteButton == v) { mController.deleteMessages(mAccount, mCurrentFolder.name, messageList.toArray(new Message[0]), null); mSelectedCount = 0; configureBatchButtons(); } else { mController.setFlag(mAccount, mCurrentFolder.name, messageList.toArray(new Message[0]), (v == mBatchReadButton ? Flag.SEEN : Flag.FLAGGED), newState); } } else { //Should not happen Toast.makeText(this, R.string.no_message_seletected_toast, Toast.LENGTH_SHORT).show(); } mHandler.sortMessages(); } private void setAllSelected(boolean isSelected) { mSelectedCount = 0; for (MessageInfoHolder holder : mAdapter.messages) { holder.selected = isSelected; mSelectedCount += (isSelected ? 1 : 0); } mAdapter.notifyDataSetChanged(); showBatchButtons(); } private void flagSelected(Flag flag, boolean newState) { List<Message> messageList = new ArrayList<Message>(); for (MessageInfoHolder holder : mAdapter.messages) { if (holder.selected) { messageList.add(holder.message); if (flag == Flag.SEEN) { holder.read = newState; } else if (flag == Flag.FLAGGED) { holder.flagged = newState; } } } mController.setFlag(mAccount, mCurrentFolder.name, messageList.toArray(new Message[0]), flag , newState); mHandler.sortMessages(); } private void deleteSelected() { List<Message> messageList = new ArrayList<Message>(); List<MessageInfoHolder> removeHolderList = new ArrayList<MessageInfoHolder>(); for (MessageInfoHolder holder : mAdapter.messages) { if (holder.selected) { removeHolderList.add(holder); messageList.add(holder.message); } } mAdapter.removeMessages(removeHolderList); mController.deleteMessages(mAccount, mCurrentFolder.name, messageList.toArray(new Message[0]), null); mSelectedCount = 0; configureBatchButtons(); } private void moveOrCopySelected(boolean isMove) { } }
package com.fsck.k9.activity; // import android.os.Debug; import android.app.AlertDialog; import android.app.Dialog; import android.app.NotificationManager; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; import android.util.Config; import android.util.Log; import android.view.*; import android.view.ContextMenu.ContextMenuInfo; import android.view.View.OnClickListener; import android.widget.*; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.CompoundButton.OnCheckedChangeListener; import com.fsck.k9.*; import com.fsck.k9.MessagingController.SORT_TYPE; import com.fsck.k9.activity.setup.AccountSettings; import com.fsck.k9.activity.setup.FolderSettings; import com.fsck.k9.mail.*; import com.fsck.k9.mail.Message.RecipientType; import com.fsck.k9.mail.store.LocalStore; import com.fsck.k9.mail.store.LocalStore.LocalFolder; import com.fsck.k9.mail.store.LocalStore.LocalMessage; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * MessageList is the primary user interface for the program. This * Activity shows a list of messages. * From this Activity the user can perform all standard message * operations. * */ public class MessageList extends K9Activity implements OnClickListener, AdapterView.OnItemClickListener { private static final int DIALOG_MARK_ALL_AS_READ = 1; private static final int ACTIVITY_CHOOSE_FOLDER_MOVE = 1; private static final int ACTIVITY_CHOOSE_FOLDER_COPY = 2; private static final String EXTRA_ACCOUNT = "account"; private static final String EXTRA_STARTUP = "startup"; private static final String EXTRA_FOLDER = "folder"; private static final String EXTRA_QUERY = "query"; private static final String STATE_KEY_LIST = "com.fsck.k9.activity.messagelist_state"; private static final String STATE_CURRENT_FOLDER = "com.fsck.k9.activity.messagelist_folder"; private static final String STATE_QUERY = "com.fsck.k9.activity.query"; private static final String STATE_KEY_SELECTION = "com.fsck.k9.activity.messagelist_selection"; private static final String STATE_KEY_SELECTED_COUNT = "com.fsck.k9.activity.messagelist_selected_count"; private static final int WIDGET_NONE = 1; private static final int WIDGET_FLAG = 2; private static final int WIDGET_MULTISELECT = 3; private ListView mListView; private int mSelectedWidget = WIDGET_FLAG; private MessageListAdapter mAdapter; private FolderInfoHolder mCurrentFolder; private LayoutInflater mInflater; private MessagingController mController; private Account mAccount; private int mUnreadMessageCount = 0; /** * Stores the name of the folder that we want to open as soon as possible * after load. */ private String mFolderName; private String mQueryString; private MessageListHandler mHandler = new MessageListHandler(); private SORT_TYPE sortType = SORT_TYPE.SORT_DATE; private boolean sortAscending = true; private boolean sortDateAscending = false; private boolean mLeftHanded = false; private int mSelectedCount = 0; private View mBatchButtonArea; private Button mBatchReadButton; private Button mBatchDeleteButton; private Button mBatchFlagButton; class MessageListHandler extends Handler { public void removeMessage(final List<MessageInfoHolder> messages) { runOnUiThread(new Runnable() { public void run() { for (MessageInfoHolder message : messages) { if (message != null) { if (mFolderName == null || (message.folder != null && message.folder.name.equals(mFolderName))) { if (message.selected && mSelectedCount > 0) { mSelectedCount } mAdapter.messages.remove(message); } } } mAdapter.notifyDataSetChanged(); configureBatchButtons(); } }); } public void addMessages(List<MessageInfoHolder> messages) { final boolean wasEmpty = mAdapter.messages.isEmpty(); for (final MessageInfoHolder message : messages) { if (mFolderName == null || (message.folder != null && message.folder.name.equals(mFolderName))) { runOnUiThread(new Runnable() { public void run() { int index = Collections.binarySearch(mAdapter.messages, message); if (index < 0) { index = (index * -1) - 1; } mAdapter.messages.add(index, message); } }); } } runOnUiThread(new Runnable() { public void run() { if (wasEmpty) { mListView.setSelection(0); } mAdapter.notifyDataSetChanged(); } }); } private void sortMessages() { runOnUiThread(new Runnable() { public void run() { synchronized (mAdapter.messages) { Collections.sort(mAdapter.messages); } mAdapter.notifyDataSetChanged(); } }); } public void folderLoading(String folder, boolean loading) { if (mCurrentFolder != null && mCurrentFolder.name.equals(folder)) { mCurrentFolder.loading = loading; } } private void refreshTitle() { runOnUiThread(new Runnable() { public void run() { setWindowTitle(); setWindowProgress(); } }); } private void setWindowProgress() { int level = Window.PROGRESS_END; if (mCurrentFolder != null && mCurrentFolder.loading && mAdapter.mListener.getFolderTotal() > 0) { level = (Window.PROGRESS_END / mAdapter.mListener.getFolderTotal()) * (mAdapter.mListener.getFolderCompleted()) ; if (level > Window.PROGRESS_END) { level = Window.PROGRESS_END; } } getWindow().setFeatureInt(Window.FEATURE_PROGRESS, level); } private void setWindowTitle() { String displayName; if (mFolderName != null) { displayName = mFolderName; if (K9.INBOX.equalsIgnoreCase(displayName)) { displayName = getString(R.string.special_mailbox_name_inbox); } String dispString = mAdapter.mListener.formatHeader(MessageList.this, getString(R.string.message_list_title, mAccount.getDescription(), displayName), mUnreadMessageCount); setTitle(dispString); } else if (mQueryString != null) { setTitle(getString(R.string.search_results) + ": "+ mQueryString); } } public void progress(final boolean progress) { runOnUiThread(new Runnable() { public void run() { showProgressIndicator(progress); } }); } } /** * This class is responsible for loading the list of local messages for a * given folder */ public static void actionHandleFolder(Context context, Account account, String folder, boolean startup) { Intent intent = new Intent(context, MessageList.class); intent.putExtra(EXTRA_ACCOUNT, account); intent.putExtra(EXTRA_STARTUP, startup); if (folder != null) { intent.putExtra(EXTRA_FOLDER, folder); } context.startActivity(intent); } public void onItemClick(AdapterView parent, View v, int position, long id) { // Debug.stopMethodTracing(); if ( mCurrentFolder != null && ((position+1) == mAdapter.getCount()) ) { mController.loadMoreMessages( mAccount, mFolderName, mAdapter.mListener); return; } else if (mSelectedWidget == WIDGET_MULTISELECT) { CheckBox selected = (CheckBox) v.findViewById(R.id.selected_checkbox); selected.setChecked(!selected.isChecked()); } else { MessageInfoHolder message = (MessageInfoHolder) mAdapter.getItem(position); onOpenMessage(message); } } @Override public void onCreate(Bundle savedInstanceState) { // Debug.startMethodTracing("k9"); super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); requestWindowFeature(Window.FEATURE_PROGRESS); setContentView(R.layout.message_list); mListView = (ListView) findViewById(R.id.message_list); mListView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_INSET); mListView.setLongClickable(true); mListView.setFastScrollEnabled(true); mListView.setScrollingCacheEnabled(true); mListView.setOnItemClickListener(this); registerForContextMenu(mListView); /* * We manually save and restore the list's state because our adapter is * slow. */ mListView.setSaveEnabled(false); mInflater = getLayoutInflater(); mBatchButtonArea = findViewById(R.id.batch_button_area); mBatchReadButton = (Button) findViewById(R.id.batch_read_button); mBatchReadButton.setOnClickListener(this); mBatchDeleteButton = (Button) findViewById(R.id.batch_delete_button); mBatchDeleteButton.setOnClickListener(this); mBatchFlagButton = (Button) findViewById(R.id.batch_flag_button); mBatchFlagButton.setOnClickListener(this); Intent intent = getIntent(); mAccount = (Account)intent.getSerializableExtra(EXTRA_ACCOUNT); // Take the initial folder into account only if we are *not* restoring the // activity already if (savedInstanceState == null) { mFolderName = intent.getStringExtra(EXTRA_FOLDER); mQueryString = intent.getStringExtra(EXTRA_QUERY); if (mFolderName == null && mQueryString == null) { mFolderName = mAccount.getAutoExpandFolderName(); } } else { mFolderName = savedInstanceState.getString(STATE_CURRENT_FOLDER); mQueryString = savedInstanceState.getString(STATE_QUERY); mSelectedCount = savedInstanceState.getInt(STATE_KEY_SELECTED_COUNT); } mAdapter = new MessageListAdapter(); final Object previousData = getLastNonConfigurationInstance(); if (previousData != null) { //noinspection unchecked mAdapter.messages.addAll((List<MessageInfoHolder>) previousData); } if (mFolderName != null) { mCurrentFolder = mAdapter.getFolder(mFolderName, mAccount); } mController = MessagingController.getInstance(getApplication()); mListView.setAdapter(mAdapter); if (savedInstanceState != null) { onRestoreListState(savedInstanceState); } } private void onRestoreListState(Bundle savedInstanceState) { mFolderName = savedInstanceState.getString(STATE_CURRENT_FOLDER); mQueryString = savedInstanceState.getString(STATE_QUERY); int selectedChild = savedInstanceState.getInt(STATE_KEY_SELECTION, -1); if (selectedChild != 0) { mListView.setSelection(selectedChild); } if (mFolderName != null) { mCurrentFolder = mAdapter.getFolder(mFolderName, mAccount); } mListView.onRestoreInstanceState(savedInstanceState.getParcelable(STATE_KEY_LIST)); } @Override public void onPause() { super.onPause(); //Debug.stopMethodTracing(); mController.removeListener(mAdapter.mListener); } /** * On resume we refresh * messages for the folder that is currently open. This guarantees that things * like unread message count and read status are updated. */ @Override public void onResume() { super.onResume(); mLeftHanded = K9.messageListLefthandedWidgets(); sortType = mController.getSortType(); sortAscending = mController.isSortAscending(sortType); sortDateAscending = mController.isSortAscending(SORT_TYPE.SORT_DATE); mController.addListener(mAdapter.mListener); mAdapter.messages.clear(); mAdapter.notifyDataSetChanged(); if (mFolderName != null) { mController.listLocalMessagesSynchronous(mAccount, mFolderName, mAdapter.mListener); NotificationManager notifMgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notifMgr.cancel(mAccount.getAccountNumber()); notifMgr.cancel(-1000 - mAccount.getAccountNumber()); mController.getFolderUnreadMessageCount(mAccount, mFolderName, mAdapter.mListener); } else if (mQueryString != null) { mController.searchLocalMessages(mAccount, mQueryString, mAdapter.mListener); } mHandler.refreshTitle(); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelable(STATE_KEY_LIST, mListView.onSaveInstanceState()); outState.putInt(STATE_KEY_SELECTION, mListView .getSelectedItemPosition()); outState.putString(STATE_CURRENT_FOLDER, mFolderName); outState.putString(STATE_QUERY, mQueryString); outState.putInt(STATE_KEY_SELECTED_COUNT, mSelectedCount); } @Override public Object onRetainNonConfigurationInstance() { return mAdapter.messages; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { //Shortcuts that work no matter what is selected switch (keyCode) { case KeyEvent.KEYCODE_DPAD_LEFT: { if (mQueryString != null) { // no widget customization in search results yet return false; } else if (mBatchButtonArea.hasFocus()) { return false; } else { cycleVisibleWidgets(true); return true; } } case KeyEvent.KEYCODE_DPAD_RIGHT: { if (mQueryString != null) { // no widget customization in search results yet return false; } else if (mBatchButtonArea.hasFocus()) { return false; } else { cycleVisibleWidgets(false); return true; } } case KeyEvent.KEYCODE_C: { onCompose(); return true; } case KeyEvent.KEYCODE_Q: //case KeyEvent.KEYCODE_BACK: { onShowFolderList(); return true; } case KeyEvent.KEYCODE_O: { onCycleSort(); return true; } case KeyEvent.KEYCODE_I: { onToggleSortAscending(); return true; } case KeyEvent.KEYCODE_H: { Toast toast = Toast.makeText(this, R.string.message_list_help_key, Toast.LENGTH_LONG); toast.show(); return true; } }//switch int position = mListView.getSelectedItemPosition(); try { if (position >= 0) { MessageInfoHolder message = (MessageInfoHolder) mAdapter.getItem(position); if (message != null) { switch (keyCode) { case KeyEvent.KEYCODE_DEL: { onDelete(message, position); return true; } case KeyEvent.KEYCODE_D: { onDelete(message, position); return true; } case KeyEvent.KEYCODE_F: { onForward(message); return true; } case KeyEvent.KEYCODE_A: { onReplyAll(message); return true; } case KeyEvent.KEYCODE_R: { onReply(message); return true; } case KeyEvent.KEYCODE_G: { onToggleFlag(message); return true; } case KeyEvent.KEYCODE_M: { onMove(message); return true; } case KeyEvent.KEYCODE_Y: { onCopy(message); return true; } case KeyEvent.KEYCODE_Z: { onToggleRead(message); return true; } } } } } finally { return super.onKeyDown(keyCode, event); } }//onKeyDown private void onOpenMessage(MessageInfoHolder message) { if (message.folder.name.equals(message.account.getDraftsFolderName())) { MessageCompose.actionEditDraft(this, message.account, message.message); } else { // Need to get the list before the sort starts ArrayList<String> messageUids = new ArrayList<String>(); for (MessageInfoHolder holder : mAdapter.messages) { messageUids.add(holder.uid); } MessageView.actionView(this, message.account, message.folder.name, message.uid, messageUids); } /* * We set read=true here for UI performance reasons. The actual value will * get picked up on the refresh when the Activity is resumed but that may * take a second or so and we don't want this to show and then go away. I've * gone back and forth on this, and this gives a better UI experience, so I * am putting it back in. */ if (!message.read) { message.read = true; mHandler.sortMessages(); } } public void cycleVisibleWidgets(boolean ascending) { if (ascending) { switch (mSelectedWidget) { case WIDGET_FLAG: { mSelectedWidget = WIDGET_MULTISELECT; break; } case WIDGET_MULTISELECT: { mSelectedWidget = WIDGET_NONE; break; } case WIDGET_NONE: { mSelectedWidget = WIDGET_FLAG; break; } } } else { switch (mSelectedWidget) { case WIDGET_FLAG: { mSelectedWidget=WIDGET_NONE; break; } case WIDGET_NONE: { mSelectedWidget=WIDGET_MULTISELECT; break; } case WIDGET_MULTISELECT: { mSelectedWidget=WIDGET_FLAG; break; } } } configureWidgets(); } private void configureWidgets() { switch (mSelectedWidget) { case WIDGET_FLAG: hideBatchButtons(); break; case WIDGET_NONE: hideBatchButtons(); break; case WIDGET_MULTISELECT: showBatchButtons(); break; } int count = mListView.getChildCount(); for (int i=0; i<count; i++) { setVisibleWidgetsForListItem(mListView.getChildAt(i), mSelectedWidget); } } private void setVisibleWidgetsForListItem(View v, int nextWidget) { Button flagged = (Button) v.findViewById(R.id.flagged); CheckBox selected = (CheckBox) v.findViewById(R.id.selected_checkbox); if (flagged == null || selected == null) { return; } if (nextWidget == WIDGET_NONE) { v.findViewById(R.id.widgets).setVisibility(View.GONE); return; } else { v.findViewById(R.id.widgets).setVisibility(View.VISIBLE); } if (nextWidget == WIDGET_MULTISELECT) { flagged.setVisibility(View.GONE); selected.setVisibility(View.VISIBLE); } else { flagged.setVisibility(View.VISIBLE); selected.setVisibility(View.GONE); } } private void onAccounts() { Accounts.listAccounts(this); finish(); } private void onShowFolderList() { FolderList.actionHandleAccount(this, mAccount, false); finish(); } private void onCompose() { if (mQueryString != null) {// if we have a query string, we don't have an account, to let compose start the default action MessageCompose.actionCompose(this, null); } else { MessageCompose.actionCompose(this, mAccount); } } private void onEditAccount() { AccountSettings.actionSettings(this, mAccount); } private void changeSort(SORT_TYPE newSortType) { if (sortType == newSortType) { onToggleSortAscending(); } else { sortType = newSortType; mController.setSortType(sortType); sortAscending = mController.isSortAscending(sortType); sortDateAscending = mController.isSortAscending(SORT_TYPE.SORT_DATE); reSort(); } } private void reSort() { int toastString = sortType.getToast(sortAscending); Toast toast = Toast.makeText(this, toastString, Toast.LENGTH_SHORT); toast.show(); mHandler.sortMessages(); } private void onCycleSort() { SORT_TYPE[] sorts = SORT_TYPE.values(); int curIndex = 0; for (int i = 0; i < sorts.length; i++) { if (sorts[i] == sortType) { curIndex = i; break; } } curIndex++; if (curIndex == sorts.length) { curIndex = 0; } changeSort(sorts[curIndex]); } private void onToggleSortAscending() { mController.setSortAscending(sortType, !sortAscending); sortAscending = mController.isSortAscending(sortType); sortDateAscending = mController.isSortAscending(SORT_TYPE.SORT_DATE); reSort(); } private void onDelete(MessageInfoHolder holder, int position) { mAdapter.removeMessage(holder); mController.deleteMessages(mAccount, holder.message.getFolder().getName(), new Message[] { holder.message }, null); mListView.setSelection(position); } private void onMove(MessageInfoHolder holder) { if (mController.isMoveCapable(mAccount) == false) { return; } if (mController.isMoveCapable(holder.message) == false) { Toast toast = Toast.makeText(this, R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG); toast.show(); return; } Intent intent = new Intent(this, ChooseFolder.class); intent.putExtra(ChooseFolder.EXTRA_ACCOUNT, mAccount); intent.putExtra(ChooseFolder.EXTRA_CUR_FOLDER, holder.folder.name); intent.putExtra(ChooseFolder.EXTRA_MESSAGE_UID, holder.message.getUid()); startActivityForResult(intent, ACTIVITY_CHOOSE_FOLDER_MOVE); } private void onCopy(MessageInfoHolder holder) { if (mController.isCopyCapable(mAccount) == false) { return; } if (mController.isCopyCapable(holder.message) == false) { Toast toast = Toast.makeText(this, R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG); toast.show(); return; } Intent intent = new Intent(this, ChooseFolder.class); intent.putExtra(ChooseFolder.EXTRA_ACCOUNT, mAccount); intent.putExtra(ChooseFolder.EXTRA_CUR_FOLDER, holder.folder.name); intent.putExtra(ChooseFolder.EXTRA_MESSAGE_UID, holder.message.getUid()); startActivityForResult(intent, ACTIVITY_CHOOSE_FOLDER_COPY); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) return; switch (requestCode) { case ACTIVITY_CHOOSE_FOLDER_MOVE: case ACTIVITY_CHOOSE_FOLDER_COPY: if (data == null) return; String destFolderName = data.getStringExtra(ChooseFolder.EXTRA_NEW_FOLDER); String uid = data.getStringExtra(ChooseFolder.EXTRA_MESSAGE_UID); MessageInfoHolder m = mAdapter.getMessage(uid); if (destFolderName != null && m != null) { switch (requestCode) { case ACTIVITY_CHOOSE_FOLDER_MOVE: onMoveChosen(m, destFolderName); break; case ACTIVITY_CHOOSE_FOLDER_COPY: onCopyChosen(m, destFolderName); break; } } } } private void onMoveChosen(MessageInfoHolder holder, String folderName) { if (mController.isMoveCapable(mAccount) == true && folderName != null) { mAdapter.removeMessage(holder); mController.moveMessage(mAccount, holder.message.getFolder().getName(), holder.message, folderName, null); } } private void onCopyChosen(MessageInfoHolder holder, String folderName) { if (mController.isCopyCapable(mAccount) == true && folderName != null) { mController.copyMessage(mAccount, holder.message.getFolder().getName(), holder.message, folderName, null); } } private void onReply(MessageInfoHolder holder) { MessageCompose.actionReply(this, mAccount, holder.message, false); } private void onReplyAll(MessageInfoHolder holder) { MessageCompose.actionReply(this, mAccount, holder.message, true); } private void onForward(MessageInfoHolder holder) { MessageCompose.actionForward(this, mAccount, holder.message); } private void onMarkAllAsRead(final Account account, final String folder) { showDialog(DIALOG_MARK_ALL_AS_READ); } private void onExpunge(final Account account, String folderName) { mController.expunge(account, folderName, null); } @Override public Dialog onCreateDialog(int id) { switch (id) { case DIALOG_MARK_ALL_AS_READ: return createMarkAllAsReadDialog(); } return super.onCreateDialog(id); } public void onPrepareDialog(int id, Dialog dialog) { switch (id) { case DIALOG_MARK_ALL_AS_READ: if (mCurrentFolder != null) { ((AlertDialog)dialog).setMessage(getString(R.string.mark_all_as_read_dlg_instructions_fmt, mCurrentFolder.displayName)); } break; default: super.onPrepareDialog(id, dialog); } } private Dialog createMarkAllAsReadDialog() { return new AlertDialog.Builder(this) .setTitle(R.string.mark_all_as_read_dlg_title) .setMessage(getString(R.string.mark_all_as_read_dlg_instructions_fmt, mCurrentFolder.displayName)) .setPositiveButton(R.string.okay_action, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dismissDialog(DIALOG_MARK_ALL_AS_READ); try { mController.markAllMessagesRead(mAccount, mCurrentFolder.name); for (MessageInfoHolder holder : mAdapter.messages) { holder.read = true; } mHandler.sortMessages(); } catch (Exception e) { // Ignore } } }) .setNegativeButton(R.string.cancel_action, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dismissDialog(DIALOG_MARK_ALL_AS_READ); } }) .create(); } private void onToggleRead(MessageInfoHolder holder) { mController.setFlag(holder.account, holder.message.getFolder().getName(), new String[] { holder.uid }, Flag.SEEN, !holder.read); holder.read = !holder.read; mHandler.sortMessages(); } private void onToggleFlag(MessageInfoHolder holder) { mController.setFlag(holder.account, holder.message.getFolder().getName(), new String[] { holder.uid }, Flag.FLAGGED, !holder.flagged); holder.flagged = !holder.flagged; mHandler.sortMessages(); } private void checkMail(Account account, String folderName) { mController.synchronizeMailbox(account, folderName, mAdapter.mListener); sendMail(account); } private void sendMail(Account account) { mController.sendPendingMessages(account, mAdapter.mListener); } @Override public boolean onOptionsItemSelected(MenuItem item) { int itemId = item.getItemId(); switch (itemId) { case R.id.check_mail: if (mFolderName != null) { checkMail(mAccount, mFolderName); } return true; case R.id.send_messages: sendMail(mAccount); return true; case R.id.compose: onCompose(); return true; case R.id.accounts: onAccounts(); return true; case R.id.set_sort_date: changeSort(SORT_TYPE.SORT_DATE); return true; case R.id.set_sort_subject: changeSort(SORT_TYPE.SORT_SUBJECT); return true; case R.id.set_sort_sender: changeSort(SORT_TYPE.SORT_SENDER); return true; case R.id.set_sort_flag: changeSort(SORT_TYPE.SORT_FLAGGED); return true; case R.id.set_sort_unread: changeSort(SORT_TYPE.SORT_UNREAD); return true; case R.id.set_sort_attach: changeSort(SORT_TYPE.SORT_ATTACHMENT); return true; case R.id.list_folders: onShowFolderList(); return true; } if (mQueryString != null) { return false; // none of the options after this point are "safe" for search results } switch (itemId) { case R.id.mark_all_as_read: if (mFolderName != null) { onMarkAllAsRead(mAccount, mFolderName); } return true; case R.id.folder_settings: if (mFolderName != null) { FolderSettings.actionSettings(this, mAccount, mFolderName); } return true; case R.id.account_settings: onEditAccount(); return true; case R.id.batch_select_all: setAllSelected(true); return true; case R.id.batch_deselect_all: setAllSelected(false); return true; case R.id.batch_copy_op: moveOrCopySelected(false); return true; case R.id.batch_move_op: moveOrCopySelected(true); return true; case R.id.batch_delete_op: deleteSelected(); return true; case R.id.batch_mark_read_op: flagSelected(Flag.SEEN, true); return true; case R.id.batch_mark_unread_op: flagSelected(Flag.SEEN, false); return true; case R.id.batch_flag_op: flagSelected(Flag.FLAGGED, true); return true; case R.id.batch_unflag_op: flagSelected(Flag.FLAGGED, false); return true; case R.id.batch_plain_mode: mSelectedWidget = WIDGET_NONE; configureWidgets(); return true; case R.id.batch_select_mode: mSelectedWidget = WIDGET_MULTISELECT; configureWidgets(); return true; case R.id.batch_flag_mode: mSelectedWidget = WIDGET_FLAG; configureWidgets(); return true; case R.id.expunge: if (mCurrentFolder != null) { onExpunge(mAccount, mCurrentFolder.name); } return true; default: return super.onOptionsItemSelected(item); } } private final int[] batch_ops = { R.id.batch_copy_op, R.id.batch_delete_op, R.id.batch_flag_op, R.id.batch_unflag_op, R.id.batch_mark_read_op, R.id.batch_mark_unread_op, R.id.batch_move_op , R.id.batch_select_all, R.id.batch_deselect_all }; private final int[] batch_modes = { R.id.batch_flag_mode, R.id.batch_select_mode, R.id.batch_plain_mode }; private void setOpsState(Menu menu, boolean state, boolean enabled) { for (int id : batch_ops) { menu.findItem(id).setVisible(state); menu.findItem(id).setEnabled(enabled); } } private void setOpsMode(Menu menu, int currentModeId) { for (int id : batch_modes) { menu.findItem(id).setVisible(id != currentModeId); } } @Override public boolean onPrepareOptionsMenu(Menu menu) { if (mQueryString != null) { menu.findItem(R.id.batch_ops).setVisible(false); menu.findItem(R.id.mark_all_as_read).setVisible(false); menu.findItem(R.id.folder_settings).setVisible(false); menu.findItem(R.id.account_settings).setVisible(false); menu.findItem(R.id.list_folders).setVisible(false); menu.findItem(R.id.expunge).setVisible(false); } switch (mSelectedWidget) { case WIDGET_FLAG: { setOpsState(menu, false, false); setOpsMode(menu, R.id.batch_flag_mode); break; } case WIDGET_MULTISELECT: { boolean anySelected = anySelected(); setOpsState(menu, true, anySelected); setOpsMode(menu, R.id.batch_select_mode); boolean newFlagState = computeBatchDirection(true); boolean newReadState = computeBatchDirection(false); menu.findItem(R.id.batch_flag_op).setVisible(newFlagState); menu.findItem(R.id.batch_unflag_op).setVisible(!newFlagState); menu.findItem(R.id.batch_mark_read_op).setVisible(newReadState); menu.findItem(R.id.batch_mark_unread_op).setVisible(!newReadState); menu.findItem(R.id.batch_deselect_all).setEnabled(anySelected); menu.findItem(R.id.batch_select_all).setEnabled(true); // TODO: batch move and copy not yet implemented menu.findItem(R.id.batch_move_op).setVisible(false); menu.findItem(R.id.batch_copy_op).setVisible(false); break; } case WIDGET_NONE: { setOpsState(menu, false, false); setOpsMode(menu, R.id.batch_plain_mode); break; } } if (mCurrentFolder != null && mCurrentFolder.outbox) { menu.findItem(R.id.check_mail).setVisible(false); } else { menu.findItem(R.id.send_messages).setVisible(false); } if (mCurrentFolder != null && K9.ERROR_FOLDER_NAME.equals(mCurrentFolder.name)) { menu.findItem(R.id.expunge).setVisible(false); } return true; } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.message_list_option, menu); return true; } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item .getMenuInfo(); MessageInfoHolder holder = (MessageInfoHolder) mAdapter.getItem(info.position); switch (item.getItemId()) { case R.id.open: onOpenMessage(holder); break; case R.id.delete: onDelete(holder, info.position); break; case R.id.reply: onReply(holder); break; case R.id.reply_all: onReplyAll(holder); break; case R.id.forward: onForward(holder); break; case R.id.mark_as_read: onToggleRead(holder); break; case R.id.flag: onToggleFlag(holder); break; case R.id.move: onMove(holder); break; case R.id.copy: onCopy(holder); break; case R.id.send_alternate: onSendAlternate(mAccount, holder); break; } return super.onContextItemSelected(item); } public void onSendAlternate(Account account, MessageInfoHolder holder) { mController.sendAlternate(this, account, holder.message); } public void showProgressIndicator(boolean status) { setProgressBarIndeterminateVisibility(status); ProgressBar bar = (ProgressBar)mListView.findViewById(R.id.message_list_progress); if (bar == null) { return; } bar.setIndeterminate(true); if (status) { bar.setVisibility(bar.VISIBLE); } else { bar.setVisibility(bar.INVISIBLE); } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; MessageInfoHolder message = (MessageInfoHolder) mAdapter.getItem(info.position); // in multi-select mode, the context menu pops up unintentionally // causes misclicks if (mSelectedWidget == WIDGET_MULTISELECT) { return; } if (message == null) { return; } getMenuInflater().inflate(R.menu.message_list_context, menu); menu.setHeaderTitle((CharSequence) message.subject); if (message.read) { menu.findItem(R.id.mark_as_read).setTitle(R.string.mark_as_unread_action); } if (message.flagged) { menu.findItem(R.id.flag).setTitle(R.string.unflag_action); } if (mController.isCopyCapable(mAccount) == false) { menu.findItem(R.id.copy).setVisible(false); } if (mController.isMoveCapable(mAccount) == false) { menu.findItem(R.id.move).setVisible(false); } } class MessageListAdapter extends BaseAdapter { private List<MessageInfoHolder> messages = java.util.Collections.synchronizedList(new ArrayList<MessageInfoHolder>()); private ActivityListener mListener = new ActivityListener() { @Override public void synchronizeMailboxStarted(Account account, String folder) { super.synchronizeMailboxStarted(account, folder); if (updateForMe(account, folder)) { mHandler.progress(true); mHandler.folderLoading(folder, true); } mHandler.refreshTitle(); } @Override public void synchronizeMailboxFinished(Account account, String folder, int totalMessagesInMailbox, int numNewMessages) { super.synchronizeMailboxFinished(account, folder, totalMessagesInMailbox, numNewMessages); if (updateForMe(account, folder)) { mHandler.progress(false); mHandler.folderLoading(folder, false); mHandler.sortMessages(); } mHandler.refreshTitle(); } @Override public void synchronizeMailboxFailed(Account account, String folder, String message) { super.synchronizeMailboxFailed(account, folder, message); if (updateForMe(account, folder)) { mHandler.progress(false); mHandler.folderLoading(folder, false); mHandler.sortMessages(); } mHandler.refreshTitle(); } @Override public void sendPendingMessagesStarted(Account account) { super.sendPendingMessagesStarted(account); mHandler.refreshTitle(); } @Override public void sendPendingMessagesCompleted(Account account) { super.sendPendingMessagesCompleted(account); mHandler.refreshTitle(); } @Override public void sendPendingMessagesFailed(Account account) { super.sendPendingMessagesFailed(account); mHandler.refreshTitle(); } @Override public void synchronizeMailboxProgress(Account account, String folder, int completed, int total) { super.synchronizeMailboxProgress(account, folder, completed, total); mHandler.refreshTitle(); } @Override public void synchronizeMailboxAddOrUpdateMessage(Account account, String folder, Message message) { // eventually, we may want to check a message added during sync against the query filter if (mQueryString == null) { addOrUpdateMessage(account, folder, message); } } @Override public void synchronizeMailboxRemovedMessage(Account account, String folder,Message message) { MessageInfoHolder holder = getMessage(message.getUid()); if (holder == null) { Log.w(K9.LOG_TAG, "Got callback to remove non-existent message with UID " + message.getUid()); } else { removeMessage(holder); } } @Override public void listLocalMessagesStarted(Account account, String folder) { if ((mQueryString != null && folder == null) || (account != null && account.equals(mAccount)) ) { mHandler.progress(true); if (folder != null) { mHandler.folderLoading(folder, true); } } } @Override public void listLocalMessagesFailed(Account account, String folder, String message) { if ((mQueryString != null && folder == null) || (account != null && account.equals(mAccount))) { mHandler.sortMessages(); mHandler.progress(false); if (folder != null) { mHandler.folderLoading(folder, false); } } } @Override public void listLocalMessagesFinished(Account account, String folder) { if ((mQueryString != null && folder == null) || (account != null && account.equals(mAccount))) { mHandler.sortMessages(); mHandler.progress(false); if (folder != null) { mHandler.folderLoading(folder, false); } } } @Override public void listLocalMessagesRemoveMessage(Account account, String folder,Message message) { if (updateForMe(account, folder)) { MessageInfoHolder holder = getMessage(message.getUid()); if (holder != null) { removeMessage(getMessage(message.getUid())); } } } @Override public void listLocalMessagesAddMessages(Account account, String folder, List<Message> messages) { addOrUpdateMessages(account, folder, messages); } @Override public void listLocalMessagesUpdateMessage(Account account, String folder, Message message) { addOrUpdateMessage(account, folder, message); } @Override public void folderStatusChanged(Account account, String folder, int unreadMessageCount) { super.folderStatusChanged(account, folder, unreadMessageCount); if (updateForMe(account, folder)) { mUnreadMessageCount = unreadMessageCount; mHandler.refreshTitle(); } } public void pendingCommandsProcessing(Account account) { super.pendingCommandsProcessing(account); mHandler.refreshTitle(); } public void pendingCommandsFinished(Account account) { super.pendingCommandsFinished(account); mHandler.refreshTitle(); } public void pendingCommandStarted(Account account, String commandTitle) { super.pendingCommandStarted(account, commandTitle); mHandler.refreshTitle(); } public void pendingCommandCompleted(Account account, String commandTitle) { super.pendingCommandCompleted(account, commandTitle); mHandler.refreshTitle(); } }; private boolean updateForMe(Account account, String folder) { if (mQueryString != null || (account.equals(mAccount) && mFolderName != null && folder.equals(mFolderName))) { return true; } else { return false; } } private Drawable mAttachmentIcon; private Drawable mAnsweredIcon; private View footerView = null; MessageListAdapter() { mAttachmentIcon = getResources().getDrawable(R.drawable.ic_mms_attachment_small); mAnsweredIcon = getResources().getDrawable(R.drawable.ic_mms_answered_small); } public void removeMessages(List<MessageInfoHolder> holders) { if (holders != null) { mHandler.removeMessage(holders); } } public void removeMessage(MessageInfoHolder holder) { List<MessageInfoHolder> messages = new ArrayList<MessageInfoHolder>(); messages.add(holder); removeMessages(messages); } private void addOrUpdateMessage(Account account, String folder, Message message) { List<Message> messages = new ArrayList<Message>(); messages.add(message); addOrUpdateMessages(account, folder, messages); } private void addOrUpdateMessages(Account account, String folder, List<Message> messages) { boolean needsSort = false; List<MessageInfoHolder> messagesToAdd = new ArrayList<MessageInfoHolder>(); List<MessageInfoHolder> messagesToRemove = new ArrayList<MessageInfoHolder>(); for (Message message : messages) { if (updateForMe(account, folder)) { MessageInfoHolder m = getMessage(message.getUid()); if (message.isSet(Flag.DELETED)) { if (m != null) { messagesToRemove.add(m); } } else if (m == null) { m = new MessageInfoHolder(message, account); messagesToAdd.add(m); } else { m.populate(message, new FolderInfoHolder(message.getFolder(), account), account); needsSort = true; } } } if (messagesToRemove.size() > 0) { removeMessages(messagesToRemove); } if (messagesToAdd.size() > 0) { mHandler.addMessages(messagesToAdd); } if (needsSort) { mHandler.sortMessages(); } } // XXX TODO - make this not use a for loop public MessageInfoHolder getMessage(String messageUid) { MessageInfoHolder searchHolder = new MessageInfoHolder(); searchHolder.uid = messageUid; int index = mAdapter.messages.indexOf((Object) searchHolder); if (index >= 0) { return (MessageInfoHolder)mAdapter.messages.get(index); } return null; } public FolderInfoHolder getFolder(String folder, Account account) { LocalFolder local_folder = null; try { LocalStore localStore = (LocalStore)Store.getInstance(account.getLocalStoreUri(), getApplication()); local_folder = localStore.getFolder(folder); return new FolderInfoHolder((Folder)local_folder, account); } catch (Exception e) { Log.e(K9.LOG_TAG, "getFolder(" + folder + ") goes boom: ",e); return null; } finally { if (local_folder != null) { local_folder.close(); } } } private static final int NON_MESSAGE_ITEMS = 1; public int getCount() { if (mAdapter.messages == null || mAdapter.messages.size() == 0) { return NON_MESSAGE_ITEMS ; } return mAdapter.messages.size() +NON_MESSAGE_ITEMS ; } public long getItemId(int position) { try { MessageInfoHolder messageHolder =(MessageInfoHolder) getItem(position); if (messageHolder != null) { return ((LocalStore.LocalMessage) messageHolder.message).getId(); } } catch (Exception e) { Log.i(K9.LOG_TAG,"getItemId("+position+") ",e); } return -1; } public Object getItem(long position) { return getItem((int)position); } public Object getItem(int position) { try { if (position < mAdapter.messages.size()) { return mAdapter.messages.get(position); } } catch (Exception e) { Log.e(K9.LOG_TAG, "getItem(" + position + "), but folder.messages.size() = " + mAdapter.messages.size(), e); } return null; } public View getView(int position, View convertView, ViewGroup parent) { if (position == mAdapter.messages.size()) { return getFooterView(position, convertView, parent); } else { return getItemView(position, convertView, parent); } } public View getItemView(int position, View convertView, ViewGroup parent) { MessageInfoHolder message = (MessageInfoHolder) getItem(position); View view; if ((convertView != null) && (convertView.getId() == R.layout.message_list_item)) { view = convertView; } else { view = mInflater.inflate(R.layout.message_list_item, parent, false); view.setId(R.layout.message_list_item); View widgetParent; if (mLeftHanded == false) { widgetParent = view.findViewById(R.id.widgets_right); } else { widgetParent = view.findViewById(R.id.widgets_left); } View widgets = mInflater.inflate(R.layout.message_list_widgets,parent,false); widgets.setId(R.id.widgets); ((LinearLayout) widgetParent).addView(widgets); } MessageViewHolder holder = (MessageViewHolder) view.getTag(); if (holder == null) { holder = new MessageViewHolder(); holder.subject = (TextView) view.findViewById(R.id.subject); holder.from = (TextView) view.findViewById(R.id.from); holder.date = (TextView) view.findViewById(R.id.date); holder.chip = view.findViewById(R.id.chip); holder.flagged = (CheckBox) view.findViewById(R.id.flagged); holder.flagged.setOnClickListener(new OnClickListener() { public void onClick(View v) { // Perform action on clicks MessageInfoHolder message = (MessageInfoHolder) getItem((Integer)v.getTag()); onToggleFlag(message); } }); holder.selected = (CheckBox) view.findViewById(R.id.selected_checkbox); if (holder.selected!=null) { holder.selected.setOnCheckedChangeListener(holder); } view.setTag(holder); } if (message != null) { holder.subject.setTypeface(null, message.read ? Typeface.NORMAL : Typeface.BOLD); setVisibleWidgetsForListItem(view, mSelectedWidget); // XXX TODO there has to be some way to walk our view hierarchy and get this holder.flagged.setTag((Integer)position); holder.flagged.setChecked(message.flagged); //So that the mSelectedCount is only incremented/decremented //when a user checks the checkbox (vs code) holder.position = -1; holder.selected.setChecked(message.selected); holder.chip.setBackgroundResource(K9.COLOR_CHIP_RES_IDS[message.account.getAccountNumber() % K9.COLOR_CHIP_RES_IDS.length]); holder.chip.getBackground().setAlpha(message.read ? 127 : 255); if (message.downloaded) { view.getBackground().setAlpha(0); } else { view.getBackground().setAlpha(127); } holder.subject.setText(message.subject); holder.from.setText(message.sender); holder.from.setTypeface(null, message.read ? Typeface.NORMAL : Typeface.BOLD); holder.date.setText(message.date); holder.subject.setCompoundDrawablesWithIntrinsicBounds( message.answered ? mAnsweredIcon : null, // left null, // top message.hasAttachments ? mAttachmentIcon : null, // right null); // bottom holder.position = position; } else { holder.chip.getBackground().setAlpha(0); holder.subject.setText("No subject"); holder.subject.setTypeface(null, Typeface.NORMAL); holder.from.setText("No sender"); holder.from.setTypeface(null, Typeface.NORMAL); holder.date.setText("No date"); holder.from.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null); //WARNING: Order of the next 2 lines matter holder.position = -1; holder.selected.setChecked(false); holder.flagged.setChecked(false); } return view; } public View getFooterView(int position, View convertView, ViewGroup parent) { if (footerView == null) { footerView = mInflater.inflate(R.layout.message_list_item_footer, parent, false); if (mQueryString != null) { footerView.setVisibility(View.GONE); } footerView.setId(R.layout.message_list_item_footer); FooterViewHolder holder = new FooterViewHolder(); holder.progress = (ProgressBar)footerView.findViewById(R.id.message_list_progress); holder.progress.setIndeterminate(true); holder.main = (TextView)footerView.findViewById(R.id.main_text); footerView.setTag(holder); } FooterViewHolder holder = (FooterViewHolder)footerView.getTag(); if (mCurrentFolder != null && mCurrentFolder.loading) { holder.main.setText(getString(R.string.status_loading_more)); holder.progress.setVisibility(ProgressBar.VISIBLE); } else { if (mCurrentFolder != null && mCurrentFolder.lastCheckFailed == false) { holder.main.setText(String.format(getString(R.string.load_more_messages_fmt), mAccount.getDisplayCount())); } else { holder.main.setText(getString(R.string.status_loading_more_failed)); } holder.progress.setVisibility(ProgressBar.INVISIBLE); } return footerView; } public boolean hasStableIds() { return true; } public boolean isItemSelectable(int position) { if (position < mAdapter.messages.size()) { return true; } else { return false; } } } public class MessageInfoHolder implements Comparable<MessageInfoHolder> { public String subject; public String date; public Date compareDate; public String compareSubject; public String sender; public String compareCounterparty; public String[] recipients; public boolean hasAttachments; public String uid; public boolean read; public boolean answered; public boolean flagged; public boolean downloaded; public boolean partially_downloaded; public Message message; public Account account; public FolderInfoHolder folder; public boolean selected; // Empty constructor for comparison public MessageInfoHolder() { this.selected = false; } public MessageInfoHolder(Message m, Account account) { this(); populate(m, new FolderInfoHolder(m.getFolder(), account), account); } public MessageInfoHolder(Message m, FolderInfoHolder folder, Account account) { this(); populate(m, folder, account); } public void populate(Message m, FolderInfoHolder folder, Account account) { try { LocalMessage message = (LocalMessage) m; Date date = message.getSentDate(); this.compareDate = date; this.folder = folder; if (Utility.isDateToday(date)) { this.date = getTimeFormat().format(date); } else { this.date = getDateFormat().format(date); } this.hasAttachments = message.getAttachmentCount() > 0; this.read = message.isSet(Flag.SEEN); this.answered = message.isSet(Flag.ANSWERED); this.flagged = message.isSet(Flag.FLAGGED); this.downloaded = message.isSet(Flag.X_DOWNLOADED_FULL); this.partially_downloaded = message.isSet(Flag.X_DOWNLOADED_PARTIAL); Address[] addrs = message.getFrom(); if (addrs.length > 0 && account.isAnIdentity(addrs[0])) { this.compareCounterparty = Address.toFriendly(message .getRecipients(RecipientType.TO)); this.sender = String.format(getString(R.string.message_list_to_fmt), this.compareCounterparty); } else { this.sender = Address.toFriendly(addrs); this.compareCounterparty = this.sender; } this.subject = message.getSubject(); this.uid = message.getUid(); this.message = m; this.account = account; } catch (MessagingException me) { if (Config.LOGV) { Log.v(K9.LOG_TAG, "Unable to load message info", me); } } } public boolean equals(Object o) { if (this.uid.equals(((MessageInfoHolder)o).uid)) { return true; } else { return false; } } public int compareTo(MessageInfoHolder o) { int ascender = (sortAscending ? 1 : -1); int comparison = 0; if (sortType == SORT_TYPE.SORT_SUBJECT) { if (compareSubject == null) { compareSubject = stripPrefixes(subject).toLowerCase(); } if (o.compareSubject == null) { o.compareSubject = stripPrefixes(o.subject).toLowerCase(); } comparison = this.compareSubject.compareTo(o.compareSubject); } else if (sortType == SORT_TYPE.SORT_SENDER) { comparison = this.compareCounterparty.toLowerCase().compareTo(o.compareCounterparty.toLowerCase()); } else if (sortType == SORT_TYPE.SORT_FLAGGED) { comparison = (this.flagged ? 0 : 1) - (o.flagged ? 0 : 1); } else if (sortType == SORT_TYPE.SORT_UNREAD) { comparison = (this.read ? 1 : 0) - (o.read ? 1 : 0); } else if (sortType == SORT_TYPE.SORT_ATTACHMENT) { comparison = (this.hasAttachments ? 0 : 1) - (o.hasAttachments ? 0 : 1); } if (comparison != 0) { return comparison * ascender; } int dateAscender = (sortDateAscending ? 1 : -1); return this.compareDate.compareTo(o.compareDate) * dateAscender; } Pattern pattern = null; String patternString = "^ *(re|aw|fw|fwd): *"; private String stripPrefixes(String in) { synchronized (patternString) { if (pattern == null) { pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE); } } Matcher matcher = pattern.matcher(in); int lastPrefix = -1; while (matcher.find()) { lastPrefix = matcher.end(); } if (lastPrefix > -1 && lastPrefix < in.length() - 1) { return in.substring(lastPrefix); } else { return in; } } } class MessageViewHolder implements OnCheckedChangeListener { public TextView subject; public TextView preview; public TextView from; public TextView time; public TextView date; public CheckBox flagged; public View chip; public CheckBox selected; public int position = -1; public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (position!=-1) { MessageInfoHolder message = (MessageInfoHolder) mAdapter.getItem(position); if (message.selected!=isChecked) { if (isChecked) { mSelectedCount++; } else if (mSelectedCount > 0) { mSelectedCount } showBatchButtons(); message.selected = isChecked; } } } } private void enableBatchButtons() { mBatchDeleteButton.setEnabled(true); mBatchReadButton.setEnabled(true); mBatchFlagButton.setEnabled(true); } private void disableBatchButtons() { mBatchDeleteButton.setEnabled(false); mBatchReadButton.setEnabled(false); mBatchFlagButton.setEnabled(false); } private void hideBatchButtons() { //TODO: Fade out animation mBatchButtonArea.setVisibility(View.GONE); } private void showBatchButtons() { configureBatchButtons(); //TODO: Fade in animation mBatchButtonArea.setVisibility(View.VISIBLE); } private void configureBatchButtons() { if (mSelectedCount < 0) { mSelectedCount = 0; } if (mSelectedCount==0) { disableBatchButtons(); } else { enableBatchButtons(); } } class FooterViewHolder { public ProgressBar progress; public TextView main; } public class FolderInfoHolder { public String name; public String displayName; public boolean loading; public boolean lastCheckFailed; public Folder folder; /** * Outbox is handled differently from any other folder. */ public boolean outbox; public FolderInfoHolder(Folder folder, Account account) { populate(folder, account); } public void populate(Folder folder, Account account) { this.folder = folder; this.name = folder.getName(); if (this.name.equalsIgnoreCase(K9.INBOX)) { this.displayName = getString(R.string.special_mailbox_name_inbox); } else { this.displayName = this.name; } if (this.name.equals(account.getOutboxFolderName())) { this.displayName = String.format(getString(R.string.special_mailbox_name_outbox_fmt), this.name); this.outbox = true; } if (this.name.equals(account.getDraftsFolderName())) { this.displayName = String.format(getString(R.string.special_mailbox_name_drafts_fmt), this.name); } if (this.name.equals(account.getTrashFolderName())) { this.displayName = String.format(getString(R.string.special_mailbox_name_trash_fmt), this.name); } if (this.name.equals(account.getSentFolderName())) { this.displayName = String.format(getString(R.string.special_mailbox_name_sent_fmt), this.name); } } } private boolean computeBatchDirection(boolean flagged) { boolean newState = false; for (MessageInfoHolder holder : mAdapter.messages) { if (holder.selected) { if (flagged) { if (!holder.flagged) { newState = true; } } else { if (!holder.read) { newState = true; } } } } return newState; } private boolean anySelected() { for (MessageInfoHolder holder : mAdapter.messages) { if (holder.selected) { return true; } } return false; } public void onClick(View v) { boolean newState = false; List<Message> messageList = new ArrayList<Message>(); List<MessageInfoHolder> removeHolderList = new ArrayList<MessageInfoHolder>(); if (v == mBatchFlagButton) { newState = computeBatchDirection(true); } else { newState = computeBatchDirection(false); } for (MessageInfoHolder holder : mAdapter.messages) { if (holder.selected) { if (v == mBatchDeleteButton) { removeHolderList.add(holder); } else if (v == mBatchFlagButton) { holder.flagged = newState; } else if (v == mBatchReadButton) { holder.read = newState; } messageList.add(holder.message); } } mAdapter.removeMessages(removeHolderList); if (!messageList.isEmpty()) { if (mBatchDeleteButton == v) { mController.deleteMessages(mAccount, mCurrentFolder.name, messageList.toArray(new Message[0]), null); mSelectedCount = 0; configureBatchButtons(); } else { mController.setFlag(mAccount, mCurrentFolder.name, messageList.toArray(new Message[0]), (v == mBatchReadButton ? Flag.SEEN : Flag.FLAGGED), newState); } } else { //Should not happen Toast.makeText(this, R.string.no_message_seletected_toast, Toast.LENGTH_SHORT).show(); } mHandler.sortMessages(); } private void setAllSelected(boolean isSelected) { mSelectedCount = 0; for (MessageInfoHolder holder : mAdapter.messages) { holder.selected = isSelected; mSelectedCount += (isSelected ? 1 : 0); } mAdapter.notifyDataSetChanged(); showBatchButtons(); } private void flagSelected(Flag flag, boolean newState) { List<Message> messageList = new ArrayList<Message>(); for (MessageInfoHolder holder : mAdapter.messages) { if (holder.selected) { messageList.add(holder.message); if (flag == Flag.SEEN) { holder.read = newState; } else if (flag == Flag.FLAGGED) { holder.flagged = newState; } } } mController.setFlag(mAccount, mCurrentFolder.name, messageList.toArray(new Message[0]), flag , newState); mHandler.sortMessages(); } private void deleteSelected() { List<Message> messageList = new ArrayList<Message>(); List<MessageInfoHolder> removeHolderList = new ArrayList<MessageInfoHolder>(); for (MessageInfoHolder holder : mAdapter.messages) { if (holder.selected) { removeHolderList.add(holder); messageList.add(holder.message); } } mAdapter.removeMessages(removeHolderList); mController.deleteMessages(mAccount, mCurrentFolder.name, messageList.toArray(new Message[0]), null); mSelectedCount = 0; configureBatchButtons(); } private void moveOrCopySelected(boolean isMove) { } }
package bpsm.edn.parser; import static bpsm.edn.Symbol.newSymbol; import static bpsm.edn.Tag.newTag; import static bpsm.edn.parser.Parser.Config.BIG_DECIMAL_TAG; import static bpsm.edn.parser.Parser.Config.BIG_INTEGER_TAG; import static bpsm.edn.parser.Parser.Config.DOUBLE_TAG; import static bpsm.edn.parser.Parser.Config.LONG_TAG; import static bpsm.edn.util.CharClassify.isDigit; import static bpsm.edn.util.CharClassify.isWhitespace; import static bpsm.edn.util.CharClassify.separatesTokens; import java.io.Closeable; import java.io.IOException; import java.io.Reader; import java.math.BigDecimal; import java.math.BigInteger; import bpsm.edn.EdnException; import bpsm.edn.Keyword; import bpsm.edn.Symbol; import bpsm.edn.Tag; import bpsm.edn.util.CharClassify; class Scanner implements Closeable { static final Symbol NIL_SYMBOL = newSymbol(null, "nil"); static final Symbol TRUE_SYMBOL = newSymbol(null, "true"); static final Symbol FALSE_SYMBOL = newSymbol(null, "false"); static final Symbol SLASH_SYMBOL = newSymbol(null, "/"); static final char END = 0; private final TagHandler longHandler; private final TagHandler bigDecimalHandler; private final TagHandler bigIntegerHandler; private final TagHandler doubleHandler; private Reader reader; private char curr = 0; private char peek = 0; private char getCurr() { return curr; } private void setCurr(char curr) { this.curr = curr; } private char getPeek() { return peek; } private void setPeek(char peek) { this.peek = peek; } /** * Scanner may throw an IOException during construction, in which case * an attempt will be made to close Reader cleanly. * @param reader * @throws IOException */ Scanner(Parser.Config cfg, Reader reader) throws IOException { if (cfg == null) { throw new IllegalArgumentException("cfg must not be null"); } if (reader == null) { throw new IllegalArgumentException("reader must not be null"); } this.longHandler = cfg.getTagHandler(LONG_TAG); this.bigIntegerHandler = cfg.getTagHandler(BIG_INTEGER_TAG); this.doubleHandler = cfg.getTagHandler(DOUBLE_TAG); this.bigDecimalHandler = cfg.getTagHandler(BIG_DECIMAL_TAG); this.reader = reader; try { this.setCurr((char) Math.max(0, reader.read())); if (getCurr() != 0) { this.setPeek((char) Math.max(0, reader.read())); } } catch (IOException e) { try { reader.close(); } catch (IOException _) { // suppress _ in favor of e } throw e; } } private char nextChar() throws IOException { setCurr(getPeek()); if (getCurr() != 0) { setPeek((char) Math.max(0, reader.read())); } return getCurr(); } public void close() throws IOException { if (reader != null) { reader.close(); reader = null; } } public Object nextToken() throws IOException { try { return nextToken0(); } catch (IOException e) { try { close(); } catch (IOException _) { // suppress _ in favor of e } throw e; } } private Object nextToken0() throws IOException { skipWhitespaceAndComments(); switch(getCurr()) { case END: return Token.END_OF_INPUT; case 'a': case 'b': case 'c': case 'd': case 'e': return readSymbol(); case 'f': { Symbol sym = readSymbol(); return FALSE_SYMBOL.equals(sym) ? false : sym; } case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': return readSymbol(); case 'n': { Symbol sym = readSymbol(); return NIL_SYMBOL.equals(sym) ? Token.NIL : sym; } case 'o': case 'p': case 'q': case 'r': case 's': return readSymbol(); case 't': { Symbol sym = readSymbol(); return TRUE_SYMBOL.equals(sym) ? true : sym; } case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '*': case '!': case '_': case '?': case '/': case '.': return readSymbol(); case '+': case '-': if (isDigit(getPeek())) { return readNumber(); } else { return readSymbol(); } case ':': return readKeyword(); case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return readNumber(); case '{': nextChar(); return Token.BEGIN_MAP; case '}': nextChar(); return Token.END_MAP_OR_SET; case '[': nextChar(); return Token.BEGIN_VECTOR; case ']': nextChar(); return Token.END_VECTOR; case '(': nextChar(); return Token.BEGIN_LIST; case ')': nextChar(); return Token.END_LIST; case ' switch(getPeek()) { case '{': nextChar(); nextChar(); return Token.BEGIN_SET; case '_': nextChar(); nextChar(); return Token.DISCARD; default: return readTag(); } case '"': return readStringLiteral(); case '\\': return readCharacterLiteral(); default: throw new EdnException( String.format("Unexpected character '%c', \\"+"u%04x", getCurr(), (int)getCurr())); } } private void skipWhitespaceAndComments() throws IOException { skipWhitespace(); while (getCurr() == ';') { skipComment(); skipWhitespace(); } } private void skipWhitespace() throws IOException { while (isWhitespace(getCurr()) && getCurr() != END) { nextChar(); } } private void skipComment() throws IOException { assert getCurr() == ';'; do { nextChar(); } while (!isEndOfLine(getCurr()) && getCurr() != END); } private static final boolean isEndOfLine(char c) { return c == '\n' || c == '\r'; } private char readCharacterLiteral() throws IOException { assert getCurr() == '\\'; nextChar(); if (isWhitespace(getCurr())) { throw new EdnException( "A backslash introducing character literal must not be "+ "immediately followed by whitespace."); } StringBuilder b = new StringBuilder(); do { b.append(getCurr()); } while (!separatesTokens(nextChar())); String s = b.toString(); if (s.length() == 1) { return s.charAt(0); } else { return charForName(s); } } private static char charForName(String name) { switch (name.charAt(0)) { case 'n': if ("newline".equals(name)) { return '\n'; } // fall through case 's': if ("space".equals(name)) { return ' '; } // fall through case 't': if ("tab".equals(name)) { return '\t'; } // fall through case 'b': if ("backspace".equals(name)) { return '\b'; } // fall through case 'f': if ("formfeed".equals(name)) { return '\f'; } // fall through case 'r': if ("return".equals(name)) { return '\r'; } // fall through default: throw new EdnException( "The character \\"+ name +" was not recognized."); } } private String readStringLiteral() throws IOException { assert getCurr() == '"'; nextChar(); StringBuffer b = new StringBuffer(); while (getCurr() != '"' && getCurr() != END) { if (getCurr() == '\\') { nextChar(); switch(getCurr()) { case 'b': b.append('\b'); break; case 't': b.append('\t'); break; case 'n': b.append('\n'); break; case 'f': b.append('\f'); break; case 'r': b.append('\r'); break; case '"': b.append('"'); break; case '\'': b.append('\''); break; case '\\': b.append('\\'); break; default: throw new EdnException("Unsupported '"+ getCurr() +"' escape in string"); } } else { b.append(getCurr()); } nextChar(); } if (getCurr() == '"') { nextChar(); } else { throw new EdnException("Unclosed string literal"); } return b.toString(); } private Object readNumber() throws IOException { assert CharClassify.startsNumber(getCurr()); StringBuffer digits = new StringBuffer(); if (getCurr() != '+') { digits.append(getCurr()); } while (isDigit(nextChar())) { digits.append(getCurr()); } if (getCurr() == '.' || getCurr() == 'e' || getCurr() == 'E' || getCurr() == 'M') { return parseFloat(digits); } else { return parseInteger(digits); } } private Object parseFloat(StringBuffer digits) throws IOException { if (getCurr() == '.') { do { digits.append(getCurr()); } while (isDigit(nextChar())); } if (getCurr() == 'e' || getCurr() == 'E') { digits.append(getCurr()); nextChar(); if (!(getCurr() == '-' || getCurr() == '+' || isDigit(getCurr()))) { throw new EdnException("Not a number: '"+ digits + getCurr() +"'."); } do { digits.append(getCurr()); } while (isDigit(nextChar())); } final boolean decimal; if (getCurr() == 'M') { decimal = true; nextChar(); } else { decimal = false; } if (!separatesTokens(getCurr())) { throw new EdnException("Not a number: '"+ digits + getCurr() +"'."); } if (decimal) { BigDecimal d = new BigDecimal(digits.toString()); return bigDecimalHandler.transform(BIG_DECIMAL_TAG, d); } else { double d = Double.parseDouble(digits.toString()); return doubleHandler.transform(DOUBLE_TAG, d); } } private Object parseInteger(CharSequence digits) throws IOException { final boolean bigint; if (getCurr() == 'N') { bigint = true; nextChar(); } else { bigint = false; } if (!separatesTokens(getCurr())) { throw new EdnException("Not a number: '"+ digits + getCurr() +"'."); } final BigInteger n = new BigInteger(digits.toString()); if (bigint || MIN_LONG.compareTo(n) > 0 || n.compareTo(MAX_LONG) > 0) { return bigIntegerHandler.transform(BIG_INTEGER_TAG, n); } else { return longHandler.transform(LONG_TAG, n.longValue()); } } private Keyword readKeyword() throws IOException { assert getCurr() == ':'; nextChar(); Symbol sym = readSymbol(); if (SLASH_SYMBOL.equals(sym)) { throw new EdnException("':/' is not a valid keyword."); } return Keyword.newKeyword(sym); } private Tag readTag() throws IOException { assert getCurr() == ' nextChar(); return newTag(readSymbol()); } private Symbol readSymbol() throws IOException { assert CharClassify.symbolStart(getCurr()); StringBuilder b = new StringBuilder(); int n = 0; int p = Integer.MIN_VALUE; do { if (getCurr() == '/') { n += 1; p = b.length(); } b.append(getCurr()); nextChar(); } while (!separatesTokens(getCurr())); validateUseOfSlash(b, n, p); return makeSymbol(b, n, p); } private Symbol makeSymbol(StringBuilder b, int slashCount, int slashPos) { if (slashCount == 0) { return newSymbol(null, b.toString()); } else { assert slashCount == 1; if (slashPos == 0) { assert b.length() == 1 && b.charAt(0) == '/'; return newSymbol(null, b.toString()); } else { return newSymbol(b.substring(0, slashPos), b.substring(slashPos+1)); } } } private void validateUseOfSlash(CharSequence s, int slashCount, int lastSlashPos) { if (slashCount > 1) { throw new EdnException( "The name '"+ s +"' must not contain more than one '/'."); } if (lastSlashPos == 0 && s.length() > 1) { throw new EdnException( "The name '"+ s +"' must not start with '/'."); } if (s.length() > 1) { if (lastSlashPos == s.length() - 1) { throw new EdnException( "The name '"+ s +"' must not end with '/'."); } } } private static final BigInteger MIN_LONG = BigInteger.valueOf(Long.MIN_VALUE); private static final BigInteger MAX_LONG = BigInteger.valueOf(Long.MAX_VALUE); }
package br.com.dbsoft.io; import java.lang.reflect.Field; import java.sql.Connection; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.faces.context.FacesContext; import javax.faces.event.PhaseId; import javax.faces.model.DataModelEvent; import javax.faces.model.DataModelListener; import javax.servlet.jsp.jstl.sql.Result; import javax.servlet.jsp.jstl.sql.ResultSupport; import br.com.dbsoft.annotation.DBSTableModel; import br.com.dbsoft.core.DBSSDK.IO.DATATYPE; import br.com.dbsoft.error.DBSIOException; import br.com.dbsoft.util.DBSIO; import br.com.dbsoft.util.DBSIO.MOVE_DIRECTION; import br.com.dbsoft.util.DBSObject; import br.com.dbsoft.util.DBSString; /** * @author ricardo.villar * * @param <DataModelClass> */ public class DBSDAO<DataModelClass> extends DBSDAOBase<DataModelClass> { private static final long serialVersionUID = -3273102169619413848L; public static enum COMMAND{ INSERT, UPDATE, DELETE, SELECT, LOCK; } // //## Working Variables # // private Connection wConnection; private String wQuerySQL = ""; //private ResultSet wSelectResultSet; private String wUK = ""; private String wPK = ""; private String[] wPKs = new String[]{}; private String[] wUKs = new String[]{}; private ResultSetMetaData wQueryResultSetMetaData; private String wQuerySQLUK=""; private DBSRow wQueryColumns = new DBSRow(); //Colunas existente na pesquisa private DBSRow wCommandColumns = new DBSRow(); private String wCommandTableName = ""; private boolean wAutoIncrementPK = true; //Efetua o insert e recuperar o valores do campos com autoincrement; private DBSResultDataModel wResultDataModel; private int wCurrentRowIndex = -1; private boolean wIsMerging = false; private DataModelListener wDataModelListener = new DataModelListener(){ @Override public void rowSelected(DataModelEvent pEvent) { if (FacesContext.getCurrentInstance() == null){return;} PhaseId xId = FacesContext.getCurrentInstance().getCurrentPhaseId(); // System.out.println("PahseId:" + xId.toString()); // System.out.println("PahseId:" + getQuerySQL()); // System.out.println("PahseId:" + FacesContext.getCurrentInstance().getPartialViewContext().isAjaxRequest() + ":" + xId.toString() + "[" + wCurrentRowIndex + ":" + pEvent.getRowIndex() + "]"); // if ((!xId.equals(PhaseId.RENDER_RESPONSE) && !xId.equals(PhaseId.INVOKE_APPLICATION)) || pEvent.getRowIndex() != -1){ if (xId == null // || (!xId.equals(PhaseId.RENDER_RESPONSE) && !xId.equals(PhaseId.INVOKE_APPLICATION)) || pEvent.getRowIndex() != -1) { || (xId.equals(PhaseId.INVOKE_APPLICATION) && pEvent.getRowIndex() != -1)){ try { pvCopyValueFromResultDataModel(pEvent.getRowIndex()); } catch (DBSIOException e) { wLogger.error(e); } } // if (xId == null // || ((xId.equals(PhaseId.RENDER_RESPONSE) || xId.equals(PhaseId.INVOKE_APPLICATION)) && pEvent.getRowIndex() != -1)){ // try { // synchronize(); // } catch (DBSIOException e) { // wLogger.error(e); // if (xId == null // || (pEvent.getRowIndex() != -1 && // ((xId.equals(PhaseId.INVOKE_APPLICATION) && pEvent.getRowIndex() != -1) || xId.equals(PhaseId.RENDER_RESPONSE)))){ // setCurrentRowIndex(pEvent.getRowIndex()); // }else{ // System.out.println("stop"); } }; //private boolean wHasVersionControl=false; // //## Public Properties # // public DBSDAO(Connection pConnection) { this.setConnection(pConnection); } public DBSDAO(Class<DataModelClass> pDataModelClass, Connection pConnection) throws DBSIOException { super(pDataModelClass); this.setConnection(pConnection); DBSTableModel xAnnotation = DBSIO.getAnnotationDataModel(wDataModel); if (xAnnotation!=null){ this.setCommandTableName(xAnnotation.tablename()); } } public DBSDAO(Connection pConnection, String pCommandTableName) throws DBSIOException{ this.setConnection(pConnection); this.setCommandTableName(pCommandTableName); } public DBSDAO(Class<DataModelClass> pDataModelClass, Connection pConnection, String pCommandTableName) throws DBSIOException{ super(pDataModelClass); this.setConnection(pConnection); this.setCommandTableName(pCommandTableName); } public DBSDAO(Connection pConnection, String pCommandTableName, String pPK) throws DBSIOException{ this.setConnection(pConnection); this.setCommandTableName(pCommandTableName, pPK); } public DBSDAO(Class<DataModelClass> pDataModelClass, Connection pConnection, String pCommandTableName, String pPK) throws DBSIOException{ super(pDataModelClass); this.setConnection(pConnection); this.setCommandTableName(pCommandTableName, pPK); } public final void setConnection(Connection pConnection) { if (!DBSObject.isEmpty(pConnection)){ this.wConnection = pConnection; } } public final Connection getConnection() { return wConnection; } /** * Retorna comando SQL utilizado para efetuar a pesquisa. * @return Comando Sql utilizado */ public final String getQuerySQL() { return wQuerySQL; } /** * Configura o comando SQL utilizado para pesquisa.<br/> * @param pQuerySQL */ public final void setQuerySQL(String pQuerySQL) { wQuerySQL = pQuerySQL; } /** * @return Quantidade de colunas da pesquisa. * @throws SQLException */ public final int getQueryColumnsCount() throws SQLException{ return wQueryResultSetMetaData.getColumnCount(); } @Override public final int getRowsCount() throws DBSIOException{ if (wResultDataModel == null){ if (DBSObject.isEmpty(this.wQuerySQL) && !DBSObject.isEmpty(this.wCommandTableName)){ return DBSIO.getTableRowsCount(this.wConnection, this.wCommandTableName); } return 0; }else{ return wResultDataModel.getRowCount(); } // try { // if (!DBSObject.isEmpty(this.wQuerySQL)){ // return DBSIO.getSQLRowsCount(this.wConnection, this.wQuerySQL); // }else if (!DBSObject.isEmpty(this.wCommandTableName)){ // return DBSIO.getTableRowsCount(this.wConnection, this.wCommandTableName); // }else{ // return 0; // } catch (DBSIOException e) { // wLogger.error("getRowsCount", e); // return 0; } public final int getCurrentRowIndex(){ if (getResultDataModel()==null){ wCurrentRowIndex = -1; } return wCurrentRowIndex; //getResultDataModel().getRowIndex(); } public final boolean setCurrentRowIndex(int pRowIndex) throws DBSIOException{ if (getResultDataModel()==null){ return false; } boolean xOk = true; if ((pRowIndex + 1) > getResultDataModel().getRowCount()){ pRowIndex = getResultDataModel().getRowCount() - 1; xOk = false; } //Posiciona no registro anterior ao primeiro caso o valor informado seja inferior a -1 if (pRowIndex < -1){ pRowIndex = - 1; xOk = false; } //Indica qual o registro corrente a partir o indice informado. //Este comando dispara automativamente o evento rowSelected, que por sua vez chama pvSetRowPositionChanged, if (pRowIndex != getResultDataModel().getRowIndex()){ getResultDataModel().setRowIndex(pRowIndex); } pvCopyValueFromResultDataModel(pRowIndex); return xOk; } public final boolean getIsNewRow(){ if (wResultDataModel == null){ return false; } if (wResultDataModel.getRowIndex() > (getRowsCountAfterRefresh() - 1)){ return true; } return false; } public boolean isMerging() { return wIsMerging; } public void setMerging(boolean pMerging) { wIsMerging = pMerging; } public final String getQueryColumnName(Integer pColumnIndex) throws SQLException{ return wQueryResultSetMetaData.getColumnName(pColumnIndex); } /** * Retorna todas as colunas da query. * @return */ @Override public final Collection<DBSColumn> getColumns() { return wQueryColumns.getColumns(); } @Override public final DBSColumn getColumn(String pColumnName) { if (pColumnName==null){return null;} String xColumnName = pvGetColumnName(pColumnName); if (wQueryColumns.containsKey(xColumnName)){ return wQueryColumns.getColumn(xColumnName); }else if (wCommandColumns.containsKey(xColumnName)){ return wCommandColumns.getColumn(xColumnName); } wLogger.error("getValue:Coluna não encontrada.[" + pColumnName + "][" + wQuerySQL + "][" + wCommandTableName + "]"); return null; } @Override public final DBSColumn getColumn(int pColumnIndex) { return wQueryColumns.getColumn(pColumnIndex); } public final Collection<DBSColumn> getCommandColumns() { return wCommandColumns.getColumns(); } public final DBSColumn getCommandColumn(String pColumnName){ if (pColumnName==null){return null;} pColumnName = pvGetColumnName(pColumnName); return wCommandColumns.getColumn(pvGetColumnName(pColumnName)); } public final String getCommandTableName() { return wCommandTableName; } public final void setCommandTableName(String pCommandTableName) throws DBSIOException{ setCommandTableName(pCommandTableName, ""); } public final void setCommandTableName(String pCommandTableName, String pPK) throws DBSIOException{ if (!DBSObject.isEmpty(pCommandTableName) && !wCommandTableName.equals(pCommandTableName.trim())){//Se nome da table for diferente da anterior if (wQueryColumns.size() > 0){ wLogger.error("DBSDAO: CommandTableName deve ser configurada ANTES de efetuar o Open() ou no momento da criação da nova instância do DAO."); } this.wCommandTableName = pCommandTableName.trim(); pvSetPK(pPK); pvCreateCommandColumns(); } } public final String getPK(){ return wPK; } @Override public final String getUK(){ return wUK; } @Override public final Object getUKValue(){ return this.getValue(UKName); } public final boolean isAutoIncrementPK() { return wAutoIncrementPK; } public final void setAutoIncrementPK(boolean pAutoIncrementPK) { this.wAutoIncrementPK = pAutoIncrementPK; } public final <A> A getValueOriginal(String pColumnName){ if (pColumnName==null){return null;} String xColumnName = pvGetColumnName(pColumnName); if (wCommandColumns.containsKey(xColumnName)){ return wCommandColumns.<A>getValueOriginal(xColumnName); }else if (wQueryColumns.containsKey(xColumnName)){ return wQueryColumns.<A>getValueOriginal(xColumnName); } if (getShowColumnNameNotFoundMessage()){ wLogger.error("DBSDAO.getValue:Coluna não encontrada.[" + pColumnName + "][" + wQuerySQL + "]"); } return null; } // public static <A> A getValueX(String pColumnName){ // Double x = 0D; // return (A) x; /** * Retorna valor da coluna * @param pColumnName Nome da coluna * @return Valor */ @Override public final <A> A getValue(String pColumnName){ if (pColumnName==null){return null;} String xColumnName = pvGetColumnName(pColumnName); //Retorna valor do DataModel se existir if (wDataModel != null){ A xValue = pvGetLocalDataModelValue(xColumnName); if (xValue != null){ return xValue; }else{ Field xField = DBSIO.getDataModelField(wDataModel, xColumnName); if (xField!=null){ return null; } } } //Retorna valor a parti do controle local das colunas de comando if (wCommandColumns.containsKey(xColumnName)){ return wCommandColumns.<A>getValue(xColumnName); //Retorna valor a parti do controle local das colunas de pesquisa }else if (wQueryColumns.containsKey(xColumnName)){ return wQueryColumns.<A>getValue(xColumnName); } if (getShowColumnNameNotFoundMessage()){ wLogger.error("DBSDAO.getValue:Coluna não encontrada.[" + pColumnName + "][" + wQuerySQL + "]"); } return null; } public final <A> A getValue(String pColumnName, Class<A> pValueClass){ return DBSObject.<A>toClass(getValue(pColumnName), pValueClass); } @Override public final void setValue(String pColumnName, Object pValue){ this.setValue(pColumnName, pValue, false); } @Override public final void setValue(String pColumnName, Object pValue, boolean pOriginalValue){ if (pColumnName==null){return;} boolean xAchou = false; String xColumnName = pvGetColumnName(pColumnName); if (wCommandColumns.containsKey(xColumnName)){ wCommandColumns.setValue(xColumnName, pValue, pOriginalValue); xAchou = true; } //Seta o valor na coluna do select, independentemente de ser uma coluna que da tabela comando(CommandTableName) if (wQueryColumns.containsKey(xColumnName)){ wQueryColumns.setValue(xColumnName, pValue, pOriginalValue); xAchou = true; } if (this.pvSetLocalDataModelValue(xColumnName, pValue)){ xAchou = true; } if (!xAchou && getShowColumnNameNotFoundMessage()){ wLogger.error("DBSDAO.setValue:Coluna não encontrada.[" + pColumnName + "][" + wQuerySQL + "]"); } } @SuppressWarnings("unchecked") public final <A> A getListValue(String pColumnName){ if (wResultDataModel != null){ String xColumnName = pvGetColumnName(pColumnName); return (A) wResultDataModel.getRowData().get(xColumnName); }else{ return null; } } public final <A> A getListValue(String pColumnName, Class<A> pValueClass){ return DBSObject.<A>toClass(getListValue(pColumnName), pValueClass); } /** * Seta o valor da coluna informada diretamenteo no ResultDataModel. * @param pColumnName Nome da coluna * @param pValue Valor da coluna * @return */ public final void setListValue(String pColumnName, Object pValue){ if (wResultDataModel != null){ String xColumnName = pvGetColumnName(pColumnName); wResultDataModel.getRowData().put(xColumnName, pValue); } } public final String getSQLExecuteCommand(DBSDAO.COMMAND pCommand) throws DBSIOException{ String xStr = ""; pvCopyDataModelFieldsValueToCommandValue(wDataModel); xStr = DBSIO.getDAOSQLCommand(this, pCommand); return xStr; } public final DBSResultDataModel getResultDataModel(){ return wResultDataModel; } public final boolean containsColumn(String pColumnName){ if (pColumnName==null){return false;} String xColumnName = pvGetColumnName(pColumnName); if (wCommandColumns.containsKey(xColumnName)){ return true; }else if (wQueryColumns.containsKey(xColumnName)){ return true; } return false; } @Override public final boolean open() throws DBSIOException{ return this.open(wQuerySQL, getUK()); } @Override public final boolean open(String pQuerySQL) throws DBSIOException{ return this.open(pQuerySQL,""); } public final synchronized boolean open(String pQuerySQL, String pUK) throws DBSIOException{ if (wConnection == null){ wLogger.error("DBSDAO:open: Conexão não informada."); return false; } if (DBSObject.isEmpty(pQuerySQL)){ wResultDataModel = null; wQueryResultSetMetaData = null; return false; } if (DBSString.getInStr(pQuerySQL, "SELECT ",false)==0){ return false; } wQuerySQLUK = pQuerySQL.trim(); wQuerySQL = wQuerySQLUK; if (DBSObject.isEmpty(pUK)){ if (DBSString.getStringCount(wQuerySQLUK, "Select", false) <= 1){ pvSetUK(wPK); }else{ pvSetUK(""); } }else{ //Utiliza a UK informada; pvSetUK(pUK); } if (wUKs.length>0){ wQuerySQLUK = DBSIO.changeAsteriskFromQuerySQL(wQuerySQLUK); if (DBSString.getInStr(wQuerySQLUK, " DISTINCT ", false) >0){ //Altera o(s) SELECT DISTINCT wQuerySQLUK = DBSString.changeStr(wQuerySQLUK, "SELECT DISTINCT", "SELECT DISTINCT " + this.pvGetUKConcatenaded() + " AS " + UKName + ", ", false); }else{ wQuerySQLUK = DBSString.changeStr(wQuerySQLUK, "SELECT ", "SELECT " + this.pvGetUKConcatenaded() + " AS " + UKName + ", ", false); if (DBSString.getInStr(wQuerySQLUK, " UNION ", false) >0){ wQuerySQLUK = DBSString.changeStr(wQuerySQLUK, "UNION SELECT ", "UNION SELECT " + this.pvGetUKConcatenaded() + " AS " + UKName + ", ", false); } } //Inclui coluna DBSUK no GROUP BY se houver wQuerySQLUK = DBSString.changeStr(wQuerySQLUK, "GROUP BY ", "GROUP BY " + this.pvGetUKConcatenaded() + ", ", false); } //Atualiza a pesquisa refresh(); return true; } public synchronized boolean openCommandTable(String pAdditionalSQLWhereCondition) throws DBSIOException{ if (wCommandColumns.size() == 0){ wLogger.error("DBSDAO:executeUpdate: Não foram encontradas colunas alteradas para efetuar o comando de UPDATE."); return false; } if (this.wConnection!=null){ String xSQLCommand = DBSIO.getDAOSQLCommand(this, COMMAND.SELECT, pAdditionalSQLWhereCondition); open(xSQLCommand); if (getRowsCount() > 0){ return true; } } return false; } public synchronized boolean openCommandTable() throws DBSIOException{ return openCommandTable(""); } @Override public final synchronized void close() throws DBSIOException{ if (pvFireEventBeforeClose()){ wQueryColumns.clear(); wResultDataModel = null; pvFireEventAfterClose(true); } } /** * Popula o resultset com os registros atuais e cria lista. * @return true = Sem erro; false = Com erro * @throws SQLException */ @SuppressWarnings("unchecked") public final synchronized boolean refresh() throws DBSIOException{ //Executa a Select para recuperar os registros if (pvFireEventBeforeOpen()){ ResultSet xSelectResultSet; //Reset dos componentes wCurrentRowIndex = -1; wResultDataModel = null; wQueryResultSetMetaData = null; xSelectResultSet = DBSIO.openResultSet(this.getConnection(),wQuerySQLUK); Result xResult = ResultSupport.toResult(xSelectResultSet); wResultDataModel = new DBSResultDataModel(xResult.getRows()); xResult = null; wResultDataModel.addDataModelListener(wDataModelListener); try{ wQueryResultSetMetaData = xSelectResultSet.getMetaData(); pvCreateSelectColumns(wQueryResultSetMetaData); //Chame evento pvFireEventAfterOpen(true); if (!moveFirstRow()) { moveBeforeFirstRow(); } setRowsCountAfterRefresh(getRowsCount()); return true; }catch(SQLException e){ wLogger.error(e); //Chame evento pvFireEventAfterOpen(false); DBSIO.throwIOException("refreshResultSet:" + wQuerySQLUK, e, wConnection); return false; }finally{ DBSIO.closeResultSet(xSelectResultSet); } }else{ //Chame evento pvFireEventAfterOpen(false); return false; } } public void synchronize() throws DBSIOException{ if (getResultDataModel() != null){ pvCopyValueFromResultDataModel(getResultDataModel().getRowIndex()); } } public boolean getIsFist(){ if (wResultDataModel != null){ return wCurrentRowIndex==0; }else{ return false; } } public boolean getIsLast(){ if (wResultDataModel != null){ return wCurrentRowIndex == (wResultDataModel.getRowCount() - 1); }else{ return false; } } // //## Public Methods # // @Override public synchronized void moveBeforeFirstRow() throws DBSIOException{ pvMove(MOVE_DIRECTION.BEFORE_FIRST); } @Override public synchronized boolean moveFirstRow() throws DBSIOException{ return pvMove(MOVE_DIRECTION.FIRST); } @Override public synchronized boolean movePreviousRow() throws DBSIOException{ return pvMove(MOVE_DIRECTION.PREVIOUS); } @Override public synchronized boolean moveNextRow() throws DBSIOException{ return pvMove(MOVE_DIRECTION.NEXT); } @Override public synchronized boolean moveLastRow() throws DBSIOException{ return pvMove(MOVE_DIRECTION.LAST); } @Override public synchronized int executeInsert() throws DBSIOException{ if (!pvCheckColumnSize("executeInsert")){ return 0; } int xCount = 0; if (this.wConnection!=null){ pvCopyDataModelFieldsValueToCommandValue(wDataModel); if (pvFireEventBeforeInsert()){ xCount = DBSIO.executeDAOCommand(this, DBSDAO.COMMAND.INSERT, wAutoIncrementPK); pvFireEventAfterInsert(true); return xCount; } } pvFireEventAfterInsert(false); return xCount; } /** * Exclui e retorna a quantidade de registros excluidos.<br/> * @return Quantidade de linhas afetadas * @throws SQLException */ @Override public synchronized final int executeDelete() throws DBSIOException{ if (!pvCheckColumnSize("executeDelete")){ return 0; } int xCount = 0; if (this.wConnection!=null){ if(pvFireEventBeforeDelete()){ pvCopyDataModelFieldsValueToCommandValue(wDataModel); xCount = DBSIO.executeDAOCommand(this, DBSDAO.COMMAND.DELETE); pvFireEventAfterDelete(true); return xCount; } } pvFireEventAfterDelete(false); return xCount; } @Override public synchronized int executeUpdate() throws DBSIOException{ return executeUpdate(""); } public synchronized int executeUpdate(String pAdditionalSQLWhereCondition) throws DBSIOException{ if (!pvCheckColumnSize("executeUpdate")){ return 0; } int xCount = 0; if (this.wConnection!=null){ //Chama evento if (pvFireEventBeforeUpdate()){ pvCopyDataModelFieldsValueToCommandValue(wDataModel); //Executa o update xCount = DBSIO.executeDAOCommand(this, COMMAND.UPDATE, pAdditionalSQLWhereCondition); pvFireEventAfterUpdate(true); return xCount; } } pvFireEventAfterUpdate(false); return 0; } @Override public synchronized final int executeMerge() throws DBSIOException{ return executeMerge(""); } public synchronized final int executeMerge(String pAdditionalSQLWhereCondition) throws DBSIOException{ if (!pvCheckColumnSize("executeMerge")){ return 0; } int xN=-1; if (this.wConnection!=null){ pvCopyDataModelFieldsValueToCommandValue(wDataModel); if (pvFireEventBeforeMerge()){ try{ setMerging(true); xN = executeUpdate(pAdditionalSQLWhereCondition);//Atualiza registro, se existir if (xN==0){ xN = executeInsert(); //Insere novo registro } if (xN<=0){ } }catch(DBSIOException e){ throw e; }finally{ setMerging(false); } pvFireEventAfterMerge(true); return xN; } } pvFireEventAfterMerge(false); return xN; } public final void restoreValuesOriginal(){ wQueryColumns.restoreValuesOriginal(); wCommandColumns.restoreValuesOriginal(); } public final void restoreValuesDefault(){ wQueryColumns.restoreValuesDefault(); wCommandColumns.restoreValuesDefault(); } public final void copyValueToValueOriginal(){ wQueryColumns.copyValueToValueOriginal(); wCommandColumns.copyValueToValueOriginal(); } public final void paste(int pRowIndex) throws DBSIOException{ setCurrentRowIndex(pRowIndex); wQueryColumns.setChanged(); wCommandColumns.setChanged(); } public final void paste() throws DBSIOException{ setCurrentRowIndex(getCurrentRowIndex()); wQueryColumns.setChanged(); wCommandColumns.setChanged(); } public final void insertEmptyRow() throws DBSIOException{ DBSIO.insertEmptyRow(this); } private void pvCreateCommandColumns() throws DBSIOException{ ResultSet xMetaData = null; try{ if (!DBSObject.isEmpty(wCommandTableName)){ String xColumnName; boolean xEmpty = true; //Excluir todas as colunas caso existam wCommandColumns.clear(); xMetaData = DBSIO.getTableColumnsMetaData(this.getConnection(), wCommandTableName); //Inclui todas as colunas da tabela de comando no controle de colunas local while (DBSIO.moveNext(xMetaData)){ xEmpty = false; xColumnName = xMetaData.getString("COLUMN_NAME").toUpperCase().trim(); if (!DBSIO.isColumnsIgnored(xColumnName) && !wCommandColumns.containsKey(xColumnName)){ wCommandColumns.MergeColumn(xColumnName, DBSIO.toDataType(this.getConnection(), xMetaData.getInt("DATA_TYPE"), xMetaData.getInt("COLUMN_SIZE")), xMetaData.getInt("COLUMN_SIZE"), xMetaData.getObject("COLUMN_DEF")); // if (xMetaData.getString("COLUMN_NAME").toUpperCase().trim().equals(DBSSDK.IO.VERSION_COLUMN_NAME)){ if (pvIsPK(xColumnName)){ if (wCommandColumns.containsKey(xColumnName)){ wCommandColumns.getColumn(xColumnName).setPK(true); }else{ setAutoIncrementPK(false); } } } } if (xEmpty){ wLogger.error("Não foi encontrada a tabela " + wCommandTableName + ". Verifique o acesso, o nome e questões de letra maiúscula/minúscula."); } if (wPKs.length==0){ List<String> xPKs = DBSIO.getPrimaryKeys(this.getConnection(), wCommandTableName); String xPK = ""; if (xPKs != null){ for (int x=0; x<=xPKs.size()-1;x++){ wCommandColumns.getColumn(xPKs.get(x)).setPK(true); if (!xPK.equals("")){ xPK += ","; setAutoIncrementPK(false); } xPK += wCommandColumns.getColumn(xPKs.get(x)).getColumnName(); } } pvSetPK(xPK); } if (wPKs.length != 1) { this.setAutoIncrementPK(false); } } }catch (SQLException e){ DBSIO.throwIOException(wCommandTableName, e, wConnection); }finally{ DBSIO.closeResultSet(xMetaData); } } private void pvCreateSelectColumns(ResultSetMetaData pResultSetMetaData) throws DBSIOException{ try{ wQueryColumns.clear(); //Excluir todas as colunas caso existam //Inclui todas as colunas da pesquina no control de colunas local DBSColumn xColumn = null; String xColumnName = ""; for (int x=1; x<=pResultSetMetaData.getColumnCount();x++){ xColumnName = pResultSetMetaData.getColumnLabel(x).toUpperCase().trim(); wQueryColumns.MergeColumn(xColumnName, DBSIO.toDataType(this.getConnection(), pResultSetMetaData.getColumnType(x), pResultSetMetaData.getPrecision(x)), pResultSetMetaData.getColumnDisplaySize(x), null); xColumn = wQueryColumns.getColumn(xColumnName); xColumn.setDisplayColumnName(DBSString.toProper(xColumnName)); //Seta o tamanho do campo conforme o tamanho da coluna na tabela xColumn.setDisplaySize(pResultSetMetaData.getColumnDisplaySize(x)); //System.out.println(pResultSetMetaData.getColumnLabel(x).toUpperCase().trim() + ":" + pResultSetMetaData.isAutoIncrement(x)); if (pvIsUK(xColumnName)){ xColumn.setPK(true); } xColumn.setAutoIncrement(pResultSetMetaData.isAutoIncrement(x)); //Seta coluna UK criada if (xColumnName.equals(UKName)){ wQueryColumns.getColumn(UKName).setDisplayColumn(false); } } }catch(SQLException e){ DBSIO.throwIOException(e, wConnection); } } private void pvSetRowPositionChanged() throws DBSIOException{ super.setRowPositionChanged(true); } private void pvCopyValueFromResultDataModel(int pRowIndex) throws DBSIOException{ // if (getResultDataModel()==null){ // return; // getResultDataModel().setRowIndex(pRowIndex); if (pRowIndex != wCurrentRowIndex){ wCurrentRowIndex = pRowIndex; pvSetRowPositionChanged(); //Atualiza valores atuais e reseta valor original pvFireEventBeforeRead(); if (!wResultDataModel.isRowAvailable()){ restoreValuesDefault(); }else{ for (DBSColumn xColumn: wQueryColumns.getColumns()){ this.setValue(xColumn.getColumnName(), pvGetResultDataModelValueConvertedToDataType(xColumn.getColumnName(), xColumn.getDataType()), true); } } pvFireEventAfterRead(true); } } /** * Retorna valor do resultset convertido para o tipo informado em <b>pDataType</b> * @param pColumnName * @param pDataType * @return * @throws DBSIOException */ @SuppressWarnings("unchecked") private <A> A pvGetResultDataModelValueConvertedToDataType(String pColumnName, DATATYPE pDataType) throws DBSIOException{ return (A) DBSIO.getDataTypeConvertedValue(pDataType, wResultDataModel.getRowData().get(pColumnName)); //TODO } private boolean pvMove(MOVE_DIRECTION pDirection) throws DBSIOException { boolean xB = false; if (wConnection!=null){ //Se for para chmara o evento xB = pvFireEventBeforeMove(); int xRowIndex = 0; if (xB){ if (pDirection == MOVE_DIRECTION.BEFORE_FIRST){ restoreValuesDefault(); } xRowIndex = DBSIO.getIndexAfterMove(getCurrentRowIndex(), getRowsCount(), pDirection); if (DBSIO.getIndexAfterMoveIsOk(getCurrentRowIndex(), xRowIndex, getRowsCount(), pDirection)){ xB = setCurrentRowIndex(xRowIndex); }else{ xB = false; } pvFireEventAfterMove(xB); } } return xB; } private String pvGetUKConcatenaded(){ String xS = DBSString.changeStr(wUK, " ", ""); return DBSString.changeStr(xS, ",", " || "); } private void pvSetPK(String pPK){ this.wPK = pvCreatePKString(pPK, this.wCommandTableName); this.wPKs = pvCreatePKArray(pPK); } private void pvSetUK(String pUK){ this.wUK = pvCreatePKString(pUK, null); this.wUKs = pvCreatePKArray(pUK); } private String pvCreatePKString(String pPK, String pTableName){ String xTableAlias = pTableName; if (!DBSObject.isEmpty(wQuerySQL) && !DBSObject.isEmpty(xTableAlias)){ //Retorna o nome da tabela ou alias se existir. xTableAlias = DBSIO.getTableFromQuery(wQuerySQL, true, xTableAlias); } if (DBSObject.isEmpty(pPK)){ return ""; } String xPK = pPK.trim().toUpperCase(); String[] xPKs; if (pTableName == null){ pTableName = ""; }else{ pTableName = xTableAlias.trim().toUpperCase() + "."; } xPK = DBSString.changeStr(xPK, ",", " "); xPK = DBSString.changeStr(xPK, pTableName, ""); xPKs = xPK.split("\\s+"); xPK = ""; for (String xP: xPKs){ if (!xPK.equals("")){ xPK = xPK + ","; } xPK = xPK + pTableName + xP.trim(); } if (xPK.equals("")){ return xPK; }else{ return xPK.trim(); } } /** * Retorna array das chaves(PK/UK) desconsiderando o nome da tabela, se houver. * @param pPK * @return */ private static String[] pvCreatePKArray(String pPK){ if (pPK == null || pPK.equals("")){ return new String[]{}; } String[] xPKs; int xN; xPKs = pPK.split(","); for (int xI = 0; xI < xPKs.length; xI++){ xPKs[xI] = xPKs[xI].trim(); xN = xPKs[xI].lastIndexOf("."); if (xN != -1){ xPKs[xI] = xPKs[xI].substring(xN+1); } } return xPKs; } private boolean pvIsUK(String pColumnName){ pColumnName = pColumnName.trim().toUpperCase(); return (DBSString.findStringInArray(wUKs, pColumnName) > -1); } private boolean pvIsPK(String pColumnName){ pColumnName = pColumnName.trim().toUpperCase(); return (DBSString.findStringInArray(wPKs, pColumnName) > -1); } /** * Retorna o nome da coluna em caixa alta, trim e sem o nome date tabela, se houver. * @param pColumnName * @return */ private String pvGetColumnName(String pColumnName){ if (pColumnName == null){ return ""; } pColumnName = pColumnName.toUpperCase().trim(); int xI = pColumnName.indexOf("."); if (xI > 0){ return pColumnName.substring(xI + 1); }else{ return pColumnName; } } @SuppressWarnings("unchecked") @Override protected final synchronized <A> List<A> pvGetList(boolean pReturnListDataModel) throws DBSIOException { //Executa a Select para recuperar os registros if (pReturnListDataModel && wDataModelClass == null){ return null; } List<DBSRow> xListRow = new ArrayList<DBSRow>(); List<DataModelClass> xListDataModel = new ArrayList<DataModelClass>(); //Cria nova linha DBSRow xColumns = null; //objeto com base no DataModel DataModelClass xDataModel = null; //Popula o list com todos os registros do resultset if (pReturnListDataModel){ xListDataModel.clear(); }else{ xListRow.clear(); } //Loop de todos os registros do resulset moveBeforeFirstRow(); while (moveNextRow()){ if (pReturnListDataModel){ //Cria novo objeto com base no DataModel xDataModel = this.createDataModel(); }else{ //Cria nova linha xColumns = new DBSRow(); } for (int x=1; x< getColumns().size(); x++){ if (!pReturnListDataModel){ xColumns.MergeColumn(getColumn(x).getColumnName(), getColumn(x).getDataType(), getColumn(x).getDisplaySize(), null); //Copia o valor para a coluna da linha xColumns.setValue(getColumn(x).getColumnName(), pvGetResultDataModelValueConvertedToDataType(getColumn(x).getColumnName(), getColumn(x).getDataType())); } //Adiciona a coluna a linha if (xDataModel!=null){ //Copia o valor para o respectivo atributo no DataModel(Se houver) pvSetDataModelValue(xDataModel, getColumn(x).getColumnName(), pvGetResultDataModelValueConvertedToDataType(getColumn(x).getColumnName(), getColumn(x).getDataType())); } } //Adiciona linha como DataModel if (pReturnListDataModel){ xListDataModel.add(xDataModel); }else{ //Adiciona linha como DBSRow xListRow.add(xColumns); } } if (!moveFirstRow()) { moveBeforeFirstRow(); } if (pReturnListDataModel){ return (List<A>) xListDataModel; }else{ //Adiciona linha como DBSRow return (List<A>) xListRow; } } private boolean pvCheckColumnSize(String pMethodName){ if (wCommandColumns.size() == 0){ if (DBSObject.isEmpty(getCommandTableName())){ wLogger.error("DBSDAO:" + pMethodName + ": Não foi informada a tabela que sofrerá a edição."); }else{ wLogger.error("DBSDAO:" + pMethodName + ": Não foram encontradas colunas para efetuar a edição.[" + getCommandTableName() + "]"); } return false; } return true; } //Overrides @Override public void beforeOpen(DBSDAOEvent pEvent) { } @Override public void afterOpen(DBSDAOEvent pEvent) { } @Override public void beforeInsert(DBSDAOEvent pEvent) { } @Override public void afterInsert(DBSDAOEvent pEvent) { } @Override public void beforeRead(DBSDAOEvent pEvent) { } @Override public void afterRead(DBSDAOEvent pEvent) { } @Override public void beforeUpdate(DBSDAOEvent pEvent) { } @Override public void afterUpdate(DBSDAOEvent pEvent) { } @Override public void beforeMerge(DBSDAOEvent pEvent) { } @Override public void afterMerge(DBSDAOEvent pEvent) { } @Override public void beforeDelete(DBSDAOEvent pEvent) { } @Override public void afterDelete(DBSDAOEvent pEvent) { } @Override public void beforeMove(DBSDAOEvent pEvent) { } @Override public void afterMove(DBSDAOEvent pEvent) { } @Override public void beforeClose(DBSDAOEvent pEvent) { } @Override public void afterClose(DBSDAOEvent pEvent) { } }
package br.uff.ic.utility; import br.uff.ic.utility.IO.XMLWriter; import br.uff.ic.utility.graph.Edge; import br.uff.ic.utility.graph.Vertex; import br.uff.ic.utility.graphgenerator.NoiseGraph; import edu.uci.ics.jung.graph.DirectedGraph; import edu.uci.ics.jung.graph.DirectedSparseMultigraph; import edu.uci.ics.jung.graph.Graph; import java.awt.Color; import java.io.FileNotFoundException; import java.math.BigDecimal; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; /** * Class that contains utility functions * * @author Kohwalter */ public class Utils { Color[] colors = new Color[17]; public static Color getColor(int i) { int size = 15; int index = i % size; Color[] colors = new Color[size]; colors[0] = new Color(0, 0, 0); // Black // colors[1] = new Color(255, 0, 0); // Red // colors[2] = new Color(0, 255, 0); // Lime/Green colors[1] = new Color(0, 0, 255); // Blue colors[2] = new Color(153, 153, 0); // Yellow-Mostard colors[3] = new Color(0, 255, 255); // Cyan/Aqua colors[4] = new Color(255, 0, 255); // Magenta colors[5] = new Color(128, 128, 128); // Gray colors[6] = new Color(128, 0, 0); // Brown colors[7] = new Color(128, 128, 0); // olive // colors[10] = new Color(0, 128, 0); // Green colors[8] = new Color(210, 105, 30); // Chocolate // colors[12] = new Color(0, 128, 128); // Teal colors[9] = new Color(0, 0, 128); // Navy colors[10] = new Color(255, 128, 128); // Pink colors[11] = new Color(255, 128, 0); // Orange colors[12] = new Color(192, 192, 192); // Silver colors[13] = new Color(70, 130, 180); // Steel blue colors[14] = new Color(184, 134, 11); // Dark golden rod return colors[index]; } /** * Method to export the graph in an xml format * * @param graph is the desired graph to be exported * @param fileName is the name of the file (without extension) */ public static void exportGraph(DirectedGraph<Object, Edge> graph, String fileName) { try { XMLWriter xmlWriter = new XMLWriter(graph.getVertices(), graph.getEdges()); xmlWriter.saveToXML(fileName); } catch (FileNotFoundException ex) { Logger.getLogger(NoiseGraph.class.getName()).log(Level.SEVERE, null, ex); } } /** * Method to check if it is possible to parse the value to float * * @param value desired to be parsed to float * @return boolean */ public static boolean tryParseFloat(String value) { value = value.replace(" ", ""); value = value.replace(",", "."); if (value.isEmpty()) { return false; } else if (value == null) { return false; } else if (value.equalsIgnoreCase("")) { return false; } else if (value.equalsIgnoreCase("NaN")) { return false; } else { try { String v = new BigDecimal(value).toPlainString(); Float.parseFloat(v); return true; } catch (NumberFormatException nfe) { return false; } } } /** * Function that verifies if it is possible to convert the String to a float * * @param value is the String to be verified * @return true if it is possible to convert to a float */ public static float convertFloat(String value) { value = value.replace(" ", ""); value = value.replace(",", "."); String v = new BigDecimal(value.trim()).toPlainString(); return Float.valueOf(v); } /** * Function that verifies if it is possible to convert the String to a float * * @param value is the String to be verified * @return true if it is possible to convert to a float */ public static double convertDouble(String value) { value = value.replace(" ", ""); return Double.parseDouble(value); } /** * Function that verifies if it is possible to convert the String to an * integer * * @param value is the String to be verified * @return true if it is possible to convert to an integer */ public static boolean tryParseInt(String value) { value = value.replace(" ", ""); try { Integer.valueOf(value); return true; } catch (NumberFormatException nfe) { return false; } } /** * Function to convert a String to an Int value * * @param value is the String to be converted * @return the int value of the string */ public static int convertInt(String value) { value = value.replace(" ", ""); return Integer.valueOf(value); } /** * Function to convert a String to an Int value, rounding it * * @param value is the String to be converted * @return the rounded int value of the string */ public static float roundToInt(String value) { value = value.replace(" ", ""); return Math.round(convertFloat(value)); } /** * Function to compare two floats with an epsilon margin of error * * @param f1 is the first float * @param f2 is the second float * @param epsilon is the margin of error for the comparison * @return true if floats are equals within the epsilon error margin */ public static boolean FloatEqualTo(float f1, float f2, float epsilon) { return Math.abs(f1 - f2) <= epsilon; } public static boolean DoubleEqualTo(double f1, double f2, double epsilon) { return Math.abs(f1 - f2) <= epsilon; } public static boolean FloatSimilar(float f1, float f2, float epsilon) { float max = Math.max(f1, f2); float min = Math.min(f1, f2); return min + Math.abs(max * epsilon) >= max; } /** * Clamp function to clamp the value between min and max * * @param min is the minimal accepted value * @param max is the maximum accepted value * @param value is the value to be clamped between min and max * @return clamped value */ public static float clamp(float min, float max, float value) { return Math.max(min, Math.min(max, value)); } /** * Method to convert a string to XMLGregorianCalendar * * @param time is the desired date in the "yyyy-MM-dd'T'HH:mm:ss" * @return the converted XMLGregorian Date */ public static XMLGregorianCalendar stringToXMLGregorianCalendar(String time) { try { XMLGregorianCalendar result = null; Date date; SimpleDateFormat simpleDateFormat; GregorianCalendar gregorianCalendar; simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); date = simpleDateFormat.parse(time); gregorianCalendar = (GregorianCalendar) GregorianCalendar.getInstance(); gregorianCalendar.setTime(date); result = DatatypeFactory.newInstance().newXMLGregorianCalendar(gregorianCalendar); return result; } catch (ParseException ex) { Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex); } catch (DatatypeConfigurationException ex) { Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex); } return null; } /** * Function that verifies if it is possible to convert the String to Date * * @param value is the String to be verified * @return true if it is possible to convert to Date */ public static boolean tryParseDate(String value) { if (value.isEmpty()) { return false; } else if (value == null) { return false; } else if (value.equalsIgnoreCase("")) { return false; } else if (value.equalsIgnoreCase("NaN")) { return false; } try { SimpleDateFormat simpleDateFormat; simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); simpleDateFormat.parse(value); return true; } catch (ParseException ex) { return false; } } /** * Convert a Date in the format of a string to float * * @param d1 is the string to be converted * @return the value in Float for the date */ public static double convertStringDateToFloat(String d1) { // Try to convert to date format and return how many milliseconds have passed since January 1, 1970, 00:00:00 GMT try { Date date; SimpleDateFormat simpleDateFormat; simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); date = simpleDateFormat.parse(d1); return date.getTime(); } catch (ParseException ex) { Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex); } return 0; } /** * Method to return the median of a numeric array * * @param l is the array * @param start * @param end * @return the median */ public static String median(Object[] l, int start, int end) { if (end - start > 1) { int middle = (end - start) / 2; //l.length / 2; middle = middle + start; boolean isString = false; float[] v = new float[l.length]; int i = 0; for (Object s : l) { if (tryParseFloat((String) s)) { v[i++] = convertFloat((String) s); } else { isString = true; } } if (!isString) { Arrays.sort(v); if ((end - start) % 2 == 0) { float left = v[middle - 1]; float right = v[middle]; return String.valueOf((left + right) / 2); } else { return String.valueOf(v[middle]); } } else { Arrays.sort(l); return (String) l[middle]; } } else { return (String) l[start]; } } /** * Retrieve the quartile value from an array * * @param values THe array of data * @param lowerPercent The percent cut off. For the lower quartile use 25, * for the upper-quartile use 75 * @return */ public static String quartile(Object[] values, int lowerPercent) { if (values == null || values.length == 0) { throw new IllegalArgumentException("The data array either is null or does not contain any data."); } int start, end; if (lowerPercent == 1) { start = 0; end = values.length / 2; } else { if ((values.length % 2) == 0) { start = (values.length / 2); } else { start = (values.length / 2) + 1; } end = values.length; } return median(values, start, end); } /** * Method to remove the infinity numbers from an arrayList * * @param allNumbers is the arrayList of float * @return the same arrayList without the infinity numbers */ public static ArrayList<Float> removeInfinity(ArrayList<Float> allNumbers) { ArrayList<Float> normalNumbers = new ArrayList<>(); for (float number : allNumbers) { if ((number != Float.NEGATIVE_INFINITY) && (number != Float.POSITIVE_INFINITY)) { normalNumbers.add(number); } } return normalNumbers; } /** * Method to remove outliers from a list * * @param allNumbers is the arrayList of float * @return the same arrayList without the outliers */ public static ArrayList<Float> removeOutLierAnalysis(ArrayList<Float> allNumbers) { if (allNumbers.isEmpty()) { return null; } ArrayList<Float> normalNumbers = new ArrayList<>(); Collections.sort(allNumbers); // double mean; float q1; float q3; if (allNumbers.size() % 2 == 0) { int position; // mean = (allNumbers.get(position) + allNumbers.get(position - 1)) * 0.5; position = (int) (allNumbers.size() * 0.25); q1 = (allNumbers.get(position) + allNumbers.get(position - 1)) * 0.5f; position = (int) (allNumbers.size() * 0.75); q3 = (allNumbers.get(position) + allNumbers.get(position - 1)) * 0.5f; } else { int position; // mean = allNumbers.get(position); position = (int) (allNumbers.size() * 0.25); q1 = allNumbers.get(position); position = (int) (allNumbers.size() * 0.75); q3 = allNumbers.get(position); } float iqr = q3 - q1; float lowerThreshold = q1 - iqr * 1.5f; float upperThreshold = q3 + iqr * 1.5f; for (float number : allNumbers) { if ((lowerThreshold <= number) && (number <= upperThreshold)) { normalNumbers.add(number); } } return normalNumbers; } /** * Method to compute the standard deviation * * @param list is the list of float values * @return the stdev */ public static float stdev(Float[] list) { float mean = 0.0F; mean = mean(list); return stdev(list, mean); } /** * Method to compute the standard deviation when the mean is already known * * @param list is the list of float values * @param mean is the known mean of the list * @return the stdev */ public static float stdev(Float[] list, float mean) { float num = 0.0f; float numi = 0.0f; float deno = 0.0f; for (int i = 0; i < list.length; i++) { numi = (float) Math.pow((list[i] - mean), 2); num += numi; deno = list.length - 1; } float stdevResult = (float) Math.sqrt(num / deno); // float v = (float) ((int) stdevResult * 10000) * 0.0001f; return stdevResult; } /** * Computes the standard deviation for the attribute * * @param vertices the list of vertices * @param attribute the attribute in which we want to calculate the standard * deviation * @return the standard deviation */ public static float std(Collection<Object> vertices, String attribute) { ArrayList<Float> values = new ArrayList<>(); for (Object v1 : vertices) { float val = ((Vertex) v1).getAttributeValueFloat(attribute); if (!(val != val)) { values.add(val); } } Float[] floatArray = new Float[values.size()]; floatArray = Utils.listToFloatArray(values); return stdev(floatArray); } /** * Method to compute the mean of a list * * @param list is the list * @return the mean of the list */ public static float mean(Float[] list) { float mean = 0.0F; float sum = 0.0F; for (int i = 0; i < list.length; i++) { sum += list[i]; } mean = sum / list.length; return mean; } /** * Method to find the minimum value of a list * * @param list is the list of values * @return the minimum value of the list */ public static float minimumValue(Float[] list) { float min = Float.POSITIVE_INFINITY; for (int i = 0; i < list.length; i++) { min = Math.min(min, list[i]); } return min; } /** * Method to find the maximum value of a list * * @param list is the list of values * @return the maximum value of the list */ public static float maximumValue(Float[] list) { float max = Float.NEGATIVE_INFINITY; for (int i = 0; i < list.length; i++) { max = Math.max(max, list[i]); } return max; } /** * Method to find the maximum value in the graph from an attribute * @param nodes is the list of vertices * @param attribute is the attribute that we want to find the maximum value * @return the maximum value of attribute */ public static double findMaximumAttributeValue(Collection<Object> nodes, String attribute) { ArrayList<Float> derivateValues = new ArrayList<>(); double max = Double.NEGATIVE_INFINITY; for (Object node : nodes) { if (!((Vertex) node).getAttributeValue(attribute).contentEquals("Unknown")) { max = Math.max(max, ((Vertex) node).getAttributeValueFloat(attribute)); } } return max; } /** * Method to convert a list of objects to an arraylist of double * * @param values is the list of objects to be convertable * @return the arraylist of double */ // public static Double[] listToDoubleArray(ArrayList<Double> values) { // Double[] doubleArray = new Double[values.size()]; // int i = 0; // for (Double f : values) { // doubleArray[i++] = (f != null ? f : Double.NaN); // return doubleArray; /** * Method to convert a list of objects to an arraylist of double * * @param values is the list of objects to be convertable * @return the arraylist of double */ public static Float[] listToFloatArray(ArrayList<Float> values) { Float[] floatArray = new Float[values.size()]; int i = 0; for (Float f : values) { floatArray[i++] = (f != null ? f : Float.NaN); } return floatArray; } /** * Method to clone a graph * * @param graph The graph to be cloned * @return a clone of the graph */ public static DirectedGraph<Object, Edge> copyGraph(DirectedGraph<Object, Edge> graph) { DirectedGraph<Object, Edge> clone = new DirectedSparseMultigraph<>();; for (Edge e : graph.getEdges()) { clone.addEdge(e, e.getSource(), e.getTarget()); } return clone; } /** * Function to convert the timestamp to different time scales * * @param timeFormat is the original timestamp scale used in the graph XML * @param time is the time we want to convert * @param timeScale is the current timescale being used * @return the converted value */ public static long convertTime(String timeFormat, double time, String timeScale) { TimeUnit t; if(time == -1) return (long) time; // Convert the number to a lower scale being used to avoid losing the decimals switch (timeFormat) { case "nanoseconds": t = TimeUnit.NANOSECONDS; break; case "microseconds": t = TimeUnit.MICROSECONDS; // time *= 1000; break; case "milliseconds": t = TimeUnit.MILLISECONDS; // time *= 1000; break; case "seconds": t = TimeUnit.SECONDS; // time *= 1000; break; case "minutes": t = TimeUnit.MINUTES; // time *= 60; break; case "hours": t = TimeUnit.HOURS; // time *= 60; break; case "days": t = TimeUnit.DAYS; // time *= 24; break; case "weeks": t = TimeUnit.DAYS; time = time / 7; break; default: t = TimeUnit.NANOSECONDS; break; } switch (timeScale) { case "nanoseconds": return t.toNanos((long) time); case "microseconds": return t.toMicros((long) time); case "milliseconds": return t.toMillis((long) time); case "seconds": return t.toSeconds((long) time); case "minutes": return t.toMinutes((long) time); case "hours": return t.toHours((long) time); case "days": return t.toDays((long) time); case "weeks": return (int) t.toDays((long) time) / 7; default: return (long) time; } } /** * @deprecated * @param graph * @param graphFileName */ public static void updateVertexIDs(DirectedGraph<Object, Edge> graph, String graphFileName) { // Instead of changing ID, make an attribute with value as the graph file name for (Object v : graph.getVertices()) { if(!((Vertex)v).getID().contains(graphFileName)) { ((Vertex)v).setID(graphFileName + "_" + ((Vertex)v).getID()); } GraphAttribute att = ((Vertex)v).getAttribute("GraphFile"); if(att == null) { att = new GraphAttribute("GraphFile", graphFileName); ((Vertex)v).addAttribute(att); } else if(!att.getValue().contains(graphFileName)) { att.updateAttribute(graphFileName); ((Vertex)v).addAttribute(att); } } } /** * @deprecated * @param graph * @param graphFileName */ public static void updateEdgeIDs(DirectedGraph<Object, Edge> graph, String graphFileName) { for (Edge e : graph.getEdges()) { e.setID(graphFileName + "_" + e.getID()); GraphAttribute att = new GraphAttribute("GraphFile", graphFileName); e.addAttribute(att); } } /** * Method to normalize vertex's timestamps to start from 0 * @param graph * @param overwriteTime */ public static void NormalizeTime(DirectedGraph<Object, Edge> graph, boolean overwriteTime) { Collection<Object> vertices = graph.getVertices(); double minTime = Double.POSITIVE_INFINITY; for (Object v : vertices) { if (((Vertex) v).getTime() != -1) { minTime = Math.min(minTime, ((Vertex) v).getTime()); } } // Normalize time for (Object v : vertices) { if (((Vertex) v).getTime() >= 0) { double normalized = ((Vertex) v).getTime() - minTime; ((Vertex) v).setNormalizedTime(normalized); if (overwriteTime && minTime != 0) { ((Vertex) v).setTime(Double.toString(normalized)); } } else { ((Vertex) v).setNormalizedTime(-1); } } } /** * Method to detect all values for the ATTRIBUTE that appears in the graph * @param vertices * @param attribute * @return */ public static Collection<String> DetectAllPossibleValuesFromAttribute(Collection<Object> vertices, String attribute) { Map<String, String> attributeList = new HashMap<>(); for (Object v : vertices) { String value = ((Vertex) v).getAttributeValue(attribute); if(!value.contains("Unknown")) { String[] values = value.split(", "); for(String s : values) { attributeList.put(s, s); } } } return attributeList.values(); } /** * Method that determines if the provided attribute is a timestamp/date/time type of attribute * @param attribute the attribute we want to check * @return TRUE if it is Time/Timestamp/Date or FALSE if not */ public static boolean isItTime(String attribute) { if(attribute.equalsIgnoreCase("Time")) { return true; } if(attribute.equalsIgnoreCase("Timestamp")) { return true; } if(attribute.equalsIgnoreCase("Date")) { return true; } return false; } /** * Method to return a comparator that compares two vertices based on their timestamps * @return the comparator */ public static Comparator getVertexTimeComparator() { Comparator comparator = new Comparator<Object>() { @Override public int compare(Object c1, Object c2) { if (!(c1 instanceof Graph) && !(c2 instanceof Graph)) { double c1t = ((Vertex) c1).getTime(); double c2t = ((Vertex) c2).getTime(); if (c1t != c2t) { return Double.compare(c1t, c2t); } else { return ((Vertex) c2).getNodeType().compareTo(((Vertex) c1).getNodeType()); } //TODO make agent lose priority to appear after the activity } else { return 0; } } }; return comparator; } /** * Generic comparator * @param attribute Is the attribute that we want to sort * @return the comparator for the given attribute */ public static Comparator getVertexAttributeComparator(final String attribute) { Comparator comparator = new Comparator<Object>() { @Override public int compare(Object c1, Object c2) { if (!(c1 instanceof Graph) && !(c2 instanceof Graph)) { double c1t; double c2t; if(isItTime(attribute)) { c1t = ((Vertex) c1).getTime(); c2t = ((Vertex) c2).getTime(); } else { c1t = ((Vertex) c1).getAttributeValueFloat(attribute); c2t = ((Vertex) c2).getAttributeValueFloat(attribute); } if (c1t != c2t) { return Double.compare(c1t, c2t); } else { return ((Vertex) c2).getNodeType().compareTo(((Vertex) c1).getNodeType()); } //TODO make agent lose priority to appear after the activity } else { return 0; } } }; return comparator; } /** * Method that return a grayscale color from the grayscale gradient * @param value is the current value that we want the color * @param max is the maximum possible value that the previous value can assume * @return the gray color corresponding to the value, which is based on value/max */ public static Color getGrayscaleColor(float value, float max) { if(max == 0) max = 1; float gray = value / max * 191; int rgbNum = 255 - (int) gray; return new Color (rgbNum,rgbNum,rgbNum); } /** * Method to determine if the string has a minus sign in the beginning * @param s is the string that we want to know if it has a minus sign * @return TRUE if it has a minus sign and FALSE if it does not have it */ public static boolean getMinusSign(String s) { String sign = s.substring(0, 1); boolean isReverse = false; if("-".equals(sign)) { isReverse = true; } return isReverse; } /** * Method to remove the minus sign in the beginning of the string (if it has it) * @param s the string that we want to remove the minus sign * @return the string without the minus sign */ public static String removeMinusSign(String s) { String sign = s.substring(0, 1); if("-".equals(sign)) { return s.substring(1); } return s; } }
package com.hp.hpl.jena.test; import junit.framework.TestSuite; import junit.framework.Test; /** * All developers should edit this file to add their tests. * Please try to name your tests and test suites appropriately. * Note, it is better to name your test suites on creation * rather than in this file. * @author jjc */ public class TestPackage extends TestSuite { static public Test suite() { return new TestPackage(); } /** Creates new TestPackage */ private TestPackage() { super("jena"); addTest("Enhanced", com.hp.hpl.jena.enhanced.test.TestPackage.suite()); addTest("Graph", com.hp.hpl.jena.graph.test.TestPackage.suite()); addTest("Model", com.hp.hpl.jena.rdf.model.test.TestPackage.suite()); addTest("N3", com.hp.hpl.jena.n3.test.N3TestSuite.suite());; addTest("RDQL", com.hp.hpl.jena.rdql.test.RDQLTestSuite.suite()); addTest("XML Output", com.hp.hpl.jena.xmloutput.test.TestPackage.suite()); addTest("Util", com.hp.hpl.jena.util.test.TestPackage.suite()); addTest( com.hp.hpl.jena.util.iterator.test.TestPackage.suite() ); addTest("Mega", com.hp.hpl.jena.regression.MegaTestSuite.suite()); addTest( com.hp.hpl.jena.rdf.arp.test.TestPackage.suite()); addTest("Reasoners", com.hp.hpl.jena.reasoner.test.TestPackage.suite()); addTest("Composed graphs", com.hp.hpl.jena.graph.compose.test.TestPackage.suite() ); } private void addTest(String name, TestSuite tc) { tc.setName(name); addTest(tc); } }
package ch.openech.xml; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; import java.util.logging.Logger; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.minimalj.metamodel.model.MjEntity; import org.minimalj.metamodel.model.MjEntity.MjEntityType; import org.minimalj.metamodel.model.MjProperty; import org.minimalj.metamodel.model.MjProperty.MjPropertyType; import org.minimalj.model.Keys; import org.minimalj.util.StringUtils; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class XsdModel { public static final XsdModel $ = Keys.of(XsdModel.class); public static final String XMLSchemaInstance_URI = "http: public static final String XS = "http: public static final String XML_NS = "http: private static Logger log = Logger.getLogger(XsdModel.class.getName()); private Document document; private Map<String, XsdModel> models; private LinkedHashMap<String, MjEntity> entities = new LinkedHashMap<>(); private String namespace; private final Map<String, String> namespaceByPrefix = new HashMap<>(); private final Map<String, String> prefixByNamespace = new HashMap<>(); private static Map<String, MjEntity> XML_TYPES = new HashMap<>(); public Collection<MjEntity> getEntities() { return entities.values(); } public String getNamespace() { if (Keys.isKeyObject(this)) return Keys.methodOf(this, "namespace"); return namespace; } public Map<String, String> getNamespaceByPrefix() { return namespaceByPrefix; } public String getPrefix() { if (Keys.isKeyObject(this)) return Keys.methodOf(this, "prefix"); return prefixByNamespace.get(namespace); } static { MjEntity INT = new MjEntity(MjEntityType.Integer); XML_TYPES.put("unsignedInt", INT); XML_TYPES.put("int", INT); XML_TYPES.put("integer", INT); XML_TYPES.put("nonNegativeInteger", INT); MjEntity YEAR = new MjEntity(MjEntityType.Integer); YEAR.maxLength = 4; XML_TYPES.put("gYear", YEAR); MjEntity LONG = new MjEntity(MjEntityType.Long); XML_TYPES.put("unsignedLong", LONG); MjEntity STRING = new MjEntity(MjEntityType.String); XML_TYPES.put("string", STRING); XML_TYPES.put("normalizedString", STRING); XML_TYPES.put("token", STRING); MjEntity YEAR_MONTH = new MjEntity(MjEntityType.String); YEAR_MONTH.maxLength = 7; XML_TYPES.put("gYearMonth", YEAR_MONTH); MjEntity URI = new MjEntity(MjEntityType.String); URI.maxLength = 2047; XML_TYPES.put("anyURI", URI); XML_TYPES.put("boolean", new MjEntity(MjEntityType.Boolean)); XML_TYPES.put("decimal", new MjEntity(MjEntityType.BigDecimal)); XML_TYPES.put("date", new MjEntity(MjEntityType.LocalDate)); XML_TYPES.put("dateTime", new MjEntity(MjEntityType.LocalDateTime)); XML_TYPES.put("time", new MjEntity(MjEntityType.LocalTime)); XML_TYPES.put("anyType", new MjEntity(MjEntityType.ByteArray)); } public XsdModel() { } XsdModel(InputStream inputStream) { try { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); documentBuilderFactory.setIgnoringElementContentWhitespace(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); document = documentBuilder.parse(inputStream); Element documentElement = document.getDocumentElement(); this.namespace = documentElement.getAttribute("targetNamespace"); NamedNodeMap attributes = documentElement.getAttributes(); for (int i = 0; i<attributes.getLength(); i++) { Attr attribute = (Attr) attributes.item(i); if (XML_NS.equals(attribute.getNamespaceURI())) { String prefix = attribute.getLocalName(); String namespaceURI = attribute.getValue(); namespaceByPrefix.put(prefix, namespaceURI); prefixByNamespace.put(namespaceURI, prefix); } } } catch (Exception e) { throw new RuntimeException(e); } } void read(Map<String, XsdModel> models) { Objects.nonNull(models); boolean readBefore = this.models != null; if (readBefore) return; this.models = models; // dependencies must be read first to have the base types and its values for (String dependency : namespaceByPrefix.values()) { if (models.containsKey(dependency)) { models.get(dependency).read(models); } } Element documentElement = document.getDocumentElement(); // allocate all types to have them ready for references forEachChild(documentElement, element -> { if (StringUtils.equals(element.getLocalName(), "simpleType", "complexType")) { String name = element.getAttribute("name"); MjEntity entity = new MjEntity(name); entity.setElement(element); entities.put(name, entity); } }); forEachChild(documentElement, element -> { if ("simpleType".equals(element.getLocalName())) { // maybe only complex types are added to the model simpleType(element); } }); forEachChild(documentElement, element -> { if ("complexType".equals(element.getLocalName())) { complexType(element); } }); forEachChild(documentElement, element -> { if ("element".equals(element.getLocalName())) { MjProperty property = element(element); MjEntity entity = property.type; entity.setElement(element); if (StringUtils.isEmpty(entity.name)) { entity.name = property.name; entities.put(entity.name, entity); } } }); } public static void forEachChild(Node parent, Consumer<Element> function) { NodeList nodeList = parent.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node instanceof Element) { Element element = (Element) node; function.accept(element); } } } public static Element get(Element node, String localName) { NodeList childNodes = node.getChildNodes(); for (int i = 0; i<childNodes.getLength(); i++) { Node c = childNodes.item(i); if (XS.equals(c.getNamespaceURI()) && StringUtils.equals(localName, c.getLocalName())) { return (Element) c; } } return null; } private MjEntity simpleType(Element node) { String name = node.getAttribute("name"); boolean anonymous = StringUtils.isEmpty(name); MjEntity entity = anonymous ? new MjEntity(MjEntityType.ENTITY) : entities.get(name); Element restriction = get(node, "restriction"); if (restriction != null) { String base = restriction.getAttribute("base"); MjEntity baseEntity = findEntity(base); if (baseEntity == null) { throw new IllegalStateException("Base Entity not found: " + base + " for " + name); } entity.type = baseEntity.type; Node minInclusive = get(restriction, "minInclusive"); entity.minInclusive = minInclusive != null ? ((Element) minInclusive).getAttribute("value") : null; Node maxInclusive = get(restriction, "maxInclusive"); entity.maxInclusive = maxInclusive != null ? ((Element) maxInclusive).getAttribute("value") : null; Node minLength = get(restriction, "minLength"); entity.minLength = minLength != null ? Integer.parseInt(((Element) minLength).getAttribute("value")) : null; Node maxLength = get(restriction, "maxLength"); entity.maxLength = maxLength != null ? Integer.parseInt(((Element) maxLength).getAttribute("value")) : null; if (entity.maxLength == null) { int m = 0; if (entity.maxInclusive != null) m = entity.maxInclusive.length(); if (entity.minInclusive != null) m = Math.max(m, entity.minInclusive.length()); if (m > 0) entity.maxLength = m; } Node patternNode = get(restriction, "pattern"); if (patternNode instanceof Element) { String pattern = ((Element) patternNode).getAttribute("value"); int index = pattern.indexOf("{"); if (index >= 0 && pattern.endsWith("}")) { String[] patternValues = pattern.substring(index + 1, pattern.length()-1).split(","); if (patternValues.length > 1) { entity.minLength = Integer.parseInt(patternValues[0]); } entity.maxLength = Integer.parseInt(patternValues[patternValues.length-1]); } } if (get(restriction, "enumeration") != null) { entity.values = baseEntity.values != null ? new ArrayList<>(baseEntity.values) : new ArrayList<>(); AtomicInteger maxValueLength = new AtomicInteger(0); forEachChild(restriction, element -> { if ("enumeration".equals(element.getLocalName())) { entity.type = MjEntityType.String; String value = element.getAttribute("value"); maxValueLength.set(Math.max(maxValueLength.get(), value.length())); if (!entity.values.contains(value)) { entity.values.add(value); } } }); if (baseEntity.type == MjEntityType.String || baseEntity.type == MjEntityType.Integer || baseEntity.type == MjEntityType.Long) { if (maxValueLength.get() > 0 && entity.maxLength == null) { entity.maxLength = maxValueLength.get(); } } } else if (baseEntity.isEnumeration()) { // wenn von einer enum abgeleitet wird und keine Werte angegeben werden sollen // die Werte der "super - enum" verwendet werden entity.values = baseEntity.values; } } return entity; } private MjEntity complexType(Element node) { String name = node.getAttribute("name"); MjEntity entity = StringUtils.isEmpty(name) ? new MjEntity(MjEntityType.ENTITY) : entities.get(name); if (!entity.properties.isEmpty()) { return entity; } Element sequence = get(node, "sequence"); if (sequence != null) { entity.properties.addAll(sequence(sequence, false)); } Element choice = get(node, "choice"); if (choice != null) { entity.properties.addAll(sequence(choice, true)); } Element complexContent = get(node, "complexContent"); if (complexContent != null) { entity.properties.addAll(complexContent(complexContent)); } return entity; } private List<MjProperty> sequence(Node node, boolean overrideNotEmpty) { List<MjProperty> properties = new ArrayList<>(); forEachChild(node, new SequenceVisitor(properties, overrideNotEmpty)); return properties; } // sobald man sich in einer Choice befindet kann ein Property nicht // mehr mandatory (NotEmpty) sein. Daher muss hier rekursiv zusammengebaut // werden. Wichtig ist das letzte 'true' im 'choice' if - branch private class SequenceVisitor implements Consumer<Element> { private final List<MjProperty> properties; private final boolean overrideNotEmpty; public SequenceVisitor(List<MjProperty> properties, boolean overrideNotEmpty) { this.properties = properties; this.overrideNotEmpty = overrideNotEmpty; } @Override public void accept(Element element) { if ("element".equals(element.getLocalName())) { MjProperty property = element(element); if (overrideNotEmpty) { property.notEmpty = null; } // Omit '<xs:element ref="eCH-0020:extension" minOccurs="0"/>' if (property.type != null) { properties.add(property); } } else if ("sequence".equals(element.getLocalName())) { forEachChild(element, new SequenceVisitor(properties, overrideNotEmpty)); } else if ("choice".equals(element.getLocalName())) { // bei choice das "NotEmpty" rausschmeissen forEachChild(element, new SequenceVisitor(properties, true)); } else { // what to do with xs:any ? } } } private List<MjProperty> complexContent(Element node) { List<MjProperty> properties = new ArrayList<>(); Element extension = get(node, "extension"); if (extension != null) { String base = extension.getAttribute("base"); MjEntity baseEntity = findEntity(base); if (baseEntity == null) { throw new IllegalStateException("Base Entity not found: " + base); } if (baseEntity.properties.isEmpty() && baseEntity.getElement() != null) { complexType(baseEntity.getElement()); } properties.addAll(baseEntity.properties); MjEntity extensionContent = complexType(extension); properties.addAll(extensionContent.properties); } Element restriction = get(node, "restriction"); if (restriction != null) { MjEntity restrictionContent = complexType(restriction); properties.addAll(restrictionContent.properties); } return properties; } private MjProperty element(Element element) { MjProperty property = new MjProperty(); property.name = element.getAttribute("name"); String type = element.getAttribute("type"); property.type = findEntity(type); Element simpleType = get(element, "simpleType"); if (simpleType != null) { property.type = simpleType(simpleType); } Element complexType = get(element, "complexType"); if (complexType != null) { property.type = complexType(complexType); } if (property.type != null) { property.size = property.type.maxLength; } if (property.type != null && property.type.isPrimitiv()) { property.notEmpty = property.type.minLength != null && property.type.minLength > 0; } else { String minOccurs = element.getAttribute("minOccurs"); property.notEmpty = minOccurs == null || !minOccurs.equals("0"); } String maxOccurs = element.getAttribute("maxOccurs"); if (!StringUtils.isEmpty(maxOccurs)) { if ("unbounded".equals(maxOccurs)) { property.propertyType = MjPropertyType.LIST; } else { int size = Integer.parseInt(maxOccurs); if (size > 1) { property.propertyType = MjPropertyType.LIST; property.size = size; } } } return property; } public MjEntity findEntity(String type) { if (!StringUtils.isEmpty(type)) { if (type.contains(":")) { String[] parts = type.split(":"); String namespace = namespaceByPrefix.get(parts[0]); if ("xs".equals(parts[0])) { return XML_TYPES.get(parts[1]); } else if (!StringUtils.equals(namespace, this.namespace)) { XsdModel xsdModel = models.get(namespace); if (xsdModel != null) { return xsdModel.findEntity(parts[1]); } else { log.warning("Cannot resolve: " + namespace + ":" + parts[1]); MjEntity entity = new MjEntity(parts[1]); return entity; } } else { return entities.get(parts[1]); } } else { return entities.get(type); } } else { return null; } } }
package com.iSiteProyect; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.util.UUID; import android.app.Activity; import android.app.ProgressDialog; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.content.Intent; import android.graphics.Color; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import android.widget.ToggleButton; public class ll_Inicio_Login extends Activity { public static final String DEVICE_EXTRA = "com.blueserial.SOCKET"; public static final String DEVICE_UUID = "com.blueserial.uuid"; public static final String BUFFER_SIZE = "com.blueserial.buffersize"; public static final String TAG = "ISITE PROYECTO"; public int mMaxChars = 50000;//Default public BluetoothSocket mBTSocket; public ReadInput mReadThread = null; public boolean mIsUserInitiatedDisconnect = false; public Boolean Apuntamiento=false,Booteo=true,Habilitacion=false; public UUID mDeviceUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // Standard SPP UUID public int mBufferSize = 50000; //Default public Float NivelGlobal; public int NivelGlobalInt=0; public String strInputGlobal=""; public boolean mIsBluetoothConnected = false; public BluetoothDevice mDevice; // dialogos en progreso public ProgressBar progressBarBoot; public ProgressDialog progressDialog,progressDialog2; public ProgressDialog progressDialogInicio; public ProgressBar progressBar_Apuntamiento; public Button btn_LogOut; public Spinner spin_TX,spin_RX,spin_Otros; public ArrayAdapter<String> TxAdapter,RxAdapter,OtrosAdapter; public Button btn_EnviarOPT,btn_exit,btn_Ingresar,btn_Cargar_OPT,btn_SetFreq,btn_Reset,btn_Browser,btn_SetPower; public ToggleButton TB_Login,TB_CwOnOff,TB_Pointing; public TextView TextPointing,TextPrueba,TextNivel; public EditText EditFreq,EditPass,EditPrueba,EditTxPower; // hilos public Handler puente; public VentanaDialogoNivel DialogoNivel; public Boolean Lectura_pointing=false,boolPassword=true, telnet=true; ; public Thread th1; ////// opt private static final int REQUEST_PATH = 1; String curFileName,curFilePath; EditText EditPath; /// archivo procesamiento File f; FileReader lectorArchivo; String p; String[] CadenaPartida; int longitudArchivo; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.ll_inicio_login); ActivityHelper.initialize(this); Intent intent = getIntent(); Bundle b = intent.getExtras(); mDevice = b.getParcelable(Homescreen.DEVICE_EXTRA); mDeviceUUID = UUID.fromString(b.getString(Homescreen.DEVICE_UUID)); mMaxChars = b.getInt(Homescreen.BUFFER_SIZE); LevantarXML(); SetupUI(); Botones(); Log.d(TAG, "OnCreate"); } private void SetupUI() { TB_Login.setChecked(false); progressBar_Apuntamiento.setMax(100); progressBar_Apuntamiento.setProgress(0); } private void Botones() { btn_exit.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { FuncionEnviar("exit"); TB_Login.setChecked(false); Habilitacion=false; } }); btn_Browser.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent1 = new Intent(getApplicationContext(), FileChooser.class); startActivityForResult(intent1,REQUEST_PATH); } }); btn_SetFreq.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { FuncionEnviar("tx freq "+Float.parseFloat(EditFreq.getText().toString())); } }); btn_Reset.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { FuncionEnviar("reset board"); progressDialog.cancel(); } }); btn_Ingresar.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Habilitacion=true; TB_Login.setChecked(true); FuncionEnviar("telnet localhost"); } }); btn_Cargar_OPT.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Log.d("OPT", "boton opt"); p=LeerArchivo(EditPath.getText().toString()); CadenaPartida = p.split("\n"); longitudArchivo=CadenaPartida.length; Log.d("OPT", "lineas= "+longitudArchivo); for(int i=0;i<longitudArchivo;i++){ Log.d("OPT cargado: ",CadenaPartida[i]); } } }); TB_Login.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked){ Toast.makeText(getApplicationContext(), "Log Telnet ", Toast.LENGTH_SHORT).show(); Habilitacion=isChecked;} else{Habilitacion=isChecked; Toast.makeText(getApplicationContext(), "Log Linux ", Toast.LENGTH_SHORT).show();} } }); TB_CwOnOff.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked){ FuncionEnviar("rx iflDC off"); FuncionEnviar("tx cw on"); //Toast.makeText(getApplicationContext(), "CW ON", Toast.LENGTH_SHORT).show(); } else{ FuncionEnviar("tx cw off"); FuncionEnviar("rx iflDC on"); //Toast.makeText(getApplicationContext(), "CW OFF", Toast.LENGTH_SHORT).show(); } } }); btn_SetPower.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(EditTxPower.getText().toString().equals("")) { Toast.makeText(getApplicationContext(), "Ingrese potencia !!", Toast.LENGTH_SHORT).show(); } else{FuncionEnviar("tx power -"+EditTxPower.getText().toString());} } }); TB_Pointing.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked){ FuncionEnviar("rx pointing enable");// habiulita el comando de ponting FuncionEnviar("rx pointing on"); Lectura_pointing=true; Hilo(); th1.start(); }else{ FuncionEnviar("rx pointing off");// deshabilita el comando de ponting FuncionEnviar("rx pointing disable"); progressBar_Apuntamiento.setProgress(0); Lectura_pointing=false; } } }); btn_EnviarOPT.setOnClickListener(new OnClickListener() { char finCadena=0x03; @Override public void onClick(View v) { FuncionEnviar("cd /etc/idirect/falcon"); FuncionEnviar("mv falcon.opt falcon.opt.old"); // FuncionEnviar("cat> falcon.opt"); FuncionEnviar("cat> pepe.opt"); for(int i=0;i<longitudArchivo;i++){ FuncionEnviar(CadenaPartida[i]); } FuncionEnviar(""+finCadena); // FuncionEnviar("service idirect_falcon restart"); } }); } private void LevantarXML() { TextPointing=(TextView) findViewById(R.id.TextPointing); TextPrueba=(TextView) findViewById(R.id.TextPrueba); TextNivel=(TextView) findViewById(R.id.TextNivel); btn_Ingresar=(Button) findViewById(R.id.btn_Ingresar); btn_SetFreq=(Button) findViewById(R.id.btn_SetFreq); btn_Reset=(Button) findViewById(R.id.btn_Reset); btn_Cargar_OPT=(Button) findViewById(R.id.btn_CargarOPT); btn_Browser=(Button) findViewById(R.id.btn_Browser); btn_SetPower=(Button) findViewById(R.id.btn_SetPower); btn_exit=(Button) findViewById(R.id.btn_exit); btn_EnviarOPT=(Button) findViewById(R.id.btn_EnviarOPT); TB_CwOnOff=(ToggleButton) findViewById(R.id.TB_CwOnOff); TB_Login=(ToggleButton) findViewById(R.id.TB_Login); TB_Pointing=(ToggleButton) findViewById(R.id.TB_Pointing); EditFreq=(EditText) findViewById(R.id.EditFreq); EditPass=(EditText) findViewById(R.id.EditPass); EditPath=(EditText) findViewById(R.id.EditPath); EditTxPower=(EditText) findViewById(R.id.EditTxPower); progressBar_Apuntamiento=(ProgressBar) findViewById(R.id.progressBar_Apuntamiento); } public void FuncionEnviar(String StringEnviado){ try { mBTSocket.getOutputStream().write((StringEnviado+"\r").getBytes()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void FuncionDetectarComando(String detectorString,Boolean hab){ Log.d("FuncionDetectarComando", "detector string: "+detectorString+" Boolean: "+hab); String[] CadenaPartida = detectorString.split("\r"); int longitud =CadenaPartida.length; Log.d("FuncionDetectarComando","Esta es la longitud "+longitud); for(int i=0;i<longitud;i++){ Log.d("FuncionDetectarComando","Esta es la cadena "+i+": "+CadenaPartida[i]+"-"); } if(hab){ if (detectorString.contains("Username:")){ FuncionEnviar("admin"); } if(detectorString.contains("Password:")){ final String pass=EditPass.getText().toString(); runOnUiThread(new Runnable() { public void run() { Log.d("FuncionDetectarComando","PASS EDIT: "+pass); Toast.makeText(getApplicationContext(), "Password: "+pass, Toast.LENGTH_SHORT).show(); } }); FuncionEnviar(pass); } if(detectorString.contains(">")&telnet){ telnet=false; runOnUiThread(new Runnable() { public void run() { Toast.makeText(getApplicationContext(), " Logueado en Telnet", Toast.LENGTH_SHORT).show(); } }); } if(detectorString.contains(("tx cw on"))||detectorString.contains("tx cw off")){ FuncionEnviar("tx cw"); } if(detectorString.contains("cw =")){ runOnUiThread(new Runnable() { int posicion =strInputGlobal.indexOf("="); public void run() { Toast.makeText(getApplicationContext(), " Clean Carrier = "+strInputGlobal.substring(posicion+2,posicion+5), Toast.LENGTH_SHORT).show(); } }); } if(detectorString.contains("pointing =")){ runOnUiThread(new Runnable() { int posicion =strInputGlobal.indexOf("="); public void run() { Toast.makeText(getApplicationContext(), "Point = "+strInputGlobal.substring(posicion+2,posicion+5), Toast.LENGTH_SHORT).show(); } }); } if(detectorString.contains("power =")||detectorString.contains("Tx Power =")){ runOnUiThread(new Runnable() { int posicion =strInputGlobal.indexOf("="); public void run() { Toast.makeText(getApplicationContext(), "Tx Power = "+strInputGlobal.substring(posicion+2,posicion+5)+" dbm", Toast.LENGTH_SHORT).show(); } }); } if(detectorString.contains("Tx Frequency")){ runOnUiThread(new Runnable() { int posicion =strInputGlobal.indexOf("="); public void run() { Toast.makeText(getApplicationContext(), "Freq = "+strInputGlobal.substring(posicion+2,posicion+15), Toast.LENGTH_LONG).show(); } }); } } else { telnet =true; if (detectorString.contains("pwd")){ int posicion =strInputGlobal.indexOf("pwd"); Log.d("PWD","Directorio Linux pwd"+strInputGlobal.substring(posicion,posicion+15)); } if (detectorString.contains("iDirect login:")){ FuncionEnviar("root"); } if(detectorString.contains("Password:")){ Log.d("Linux", "Password:"); if(boolPassword){ FuncionEnviar("P@55w0rd!"); Log.d("FuncionDetectarComando","FuncionEnviar(P@55w0rd!);"); } else{ FuncionEnviar("iDirect"); Log.d("FuncionDetectarComando","FuncionEnviar(iDirect);"); } } if(detectorString.contains("Login incorrect")){ if (boolPassword){ boolPassword=false; }else{ boolPassword=true; } } } } ///////////////////////////////////////// public class DisConnectBT extends AsyncTask<Void, Void, Void> { @Override protected void onPreExecute() { } @Override protected Void doInBackground(Void... params) { if (mReadThread != null) { mReadThread.stop(); while (mReadThread.isRunning()) ; // Wait until it stops mReadThread = null; } try { mBTSocket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); mIsBluetoothConnected = false; if (mIsUserInitiatedDisconnect) { finish(); } } } public void msg(String s) { Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show(); } @Override protected void onPause() { /* if (mBTSocket != null && mIsBluetoothConnected) { new DisConnectBT().execute(); }*/ Log.d(TAG, "Paused"); super.onPause(); } @Override protected void onResume() { if (mBTSocket == null || !mIsBluetoothConnected) { new ConnectBT().execute(); } Log.d(TAG, "Resumed"); super.onResume(); } @Override protected void onStop() { if (mBTSocket != null && mIsBluetoothConnected) { new DisConnectBT().execute(); } Log.d(TAG, "Stopped"); super.onStop(); } @Override protected void onSaveInstanceState(Bundle outState) { // TODO Auto-generated method stub super.onSaveInstanceState(outState); } public class ConnectBT extends AsyncTask<Void, Void, Void> { private boolean mConnectSuccessful = true; @Override protected void onPreExecute() { progressDialog = ProgressDialog.show(ll_Inicio_Login.this, "Modulo Bluetooth...", "Conectando"); } @Override protected Void doInBackground(Void... devices) { try { if (mBTSocket == null || !mIsBluetoothConnected) { mBTSocket = mDevice.createInsecureRfcommSocketToServiceRecord(mDeviceUUID); BluetoothAdapter.getDefaultAdapter().cancelDiscovery(); mBTSocket.connect(); } } catch (IOException e) { // Unable to connect to device e.printStackTrace(); mConnectSuccessful = false; } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); if (!mConnectSuccessful) { Toast.makeText(getApplicationContext(), "Could not connect to device. Is it a Serial device? Also check if the UUID is correct in the settings", Toast.LENGTH_LONG).show(); finish(); } else { msg("Connected to device"); mIsBluetoothConnected = true; mReadThread = new ReadInput(); // Kick off input reader } progressDialog.dismiss(); FuncionEnviar("\r"); } } public class ReadInput implements Runnable { private boolean bStop = false; private Thread t; public ReadInput() { t = new Thread(this, "Input Thread"); t.start(); } public boolean isRunning() { return t.isAlive(); } @Override public void run() { InputStream inputStream; try { inputStream = mBTSocket.getInputStream(); while (!bStop) { byte[] buffer = new byte[256]; if (inputStream.available() > 0) { inputStream.read(buffer); int i = 0; for (i = 0; i < buffer.length && buffer[i] != 0; i++) { } final String strInput = new String(buffer, 0, i); strInputGlobal=strInput; FuncionDetectarComando(strInputGlobal,Habilitacion); Log.d("entrada de dato", strInput); } Thread.sleep(500); } } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } public void stop() { bStop = true; } } ///////////////////////////////////////// public class VentanaDialogoNivel extends AsyncTask<Void, Void, Void> { @Override protected void onPreExecute() { } @Override protected Void doInBackground(Void... devices) { return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); String[] NivelesAlmacenados = strInputGlobal.split("\r"); try { float nivelFlotante= Float.parseFloat(NivelesAlmacenados[0])*100; int NivelBaliza=(int)nivelFlotante; //TextPrueba.setText("String: "+NivelesAlmacenados[0]+" float * 10: "+nivelFlotante +" integer: "+NivelBaliza); progressBar_Apuntamiento.setProgress(NivelBaliza); TextNivel.setText("Nivel= -"+NivelBaliza+" dbm"); } catch (Exception e) { progressBar_Apuntamiento.setProgress(0); TextNivel.setText("Nivel= - dbm"); // Toast.makeText(getApplicationContext(), "No hay medicion", Toast.LENGTH_SHORT).show(); } strInputGlobal=""; } } public void Hilo() { Log.d("Hilo", "th1 = new Thread(new Runnable()"); th1 = new Thread(new Runnable() { @Override public void run() { runOnUiThread(new Runnable() { public void run() { progressDialog = new ProgressDialog(ll_Inicio_Login.this); progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); progressDialog.setMessage("Esperando medicion"); progressDialog.setMax(10); progressDialog.setProgress(0); progressDialog.setCancelable(false); progressDialog.show(); } }); try { Log.d("Hilo", "th1 = Thread.sleep(11000)"); Thread.sleep(12000); progressDialog.cancel(); } catch (Exception e) { // TODO: handle exception } while(Lectura_pointing){ Log.d("Hilo", "while"); try { Thread.sleep(1000); Log.d("Hilo", "DialogoNivel.execute()"); DialogoNivel= new VentanaDialogoNivel(); DialogoNivel.execute(); } catch (InterruptedException e) { Lectura_pointing=false; e.printStackTrace(); } } FuncionEnviar("tx iflDC on"); progressBar_Apuntamiento.setProgress(0); } }); } //////////////////////// cargar opt // Listen for results. protected void onActivityResult(int requestCode, int resultCode, Intent data){ // See which child activity is calling us back. if (requestCode == REQUEST_PATH){ if (resultCode == RESULT_OK) { curFileName = data.getStringExtra("GetFileName"); curFilePath = data.getStringExtra("GetPath"); EditPath.setText(curFilePath+"/"+curFileName); } } } public static String LeerArchivo(String nombre) //El parametro nombre indica el nombre del archivo por ejemplo "prueba.txt" { try{ File f; FileReader lectorArchivo; //Creamos el objeto del archivo que vamos a leer f = new File(nombre); //Creamos el objeto FileReader que abrira el flujo(Stream) de datos para realizar la lectura lectorArchivo = new FileReader(f); //Creamos un lector en buffer para recopilar datos a travez del flujo "lectorArchivo" que hemos creado BufferedReader br = new BufferedReader(lectorArchivo); String l=""; //Esta variable "l" la utilizamos para guardar mas adelante toda la lectura del archivo String aux="";/*variable auxiliar*/ while(true) //este ciclo while se usa para repetir el proceso de lectura, ya que se lee solo 1 linea de texto a la vez { aux=br.readLine(); //leemos una linea de texto y la guardamos en la variable auxiliar if(aux!=null) l=l+aux+"\n"; /*si la variable aux tiene datos se va acumulando en la variable l, * en caso de ser nula quiere decir que ya nos hemos leido todo * el archivo de texto*/ else break; } br.close(); lectorArchivo.close(); return l; }catch(IOException e){ System.out.println("Error:"+e.getMessage()); } return null; } }
package com.baicai.core; import java.lang.reflect.Field; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.baicai.annotation.Column; import com.baicai.annotation.Table; import com.baicai.domain.system.Pagination; import com.baicai.util.PropertiesTool; /** * DAO * @author 95 * */ public class DaoUtil { public static final String tableFix=PropertiesTool.get("system", "tableFix"); private static final Logger logger = LoggerFactory.getLogger(DaoUtil.class); public static final String INSERT="INSERT INTO "; public static final String COMMA=","; public static final String COLON=":"; public static final String BRACKET_LEFT=" ( "; public static final String BRACKET_RIGHT=" ) "; public static final String VALUES=" ) VALUES ( "; public static final String APOSTROPHE="`" ; public static final String APOSTROPHECOMMA="`," ; public static String format(String sql) { String result = sql.replace("{", tableFix); result = result.replace("}", " "); return result; } public static String limit(Pagination page){ return " limit "+page.getOffset()+","+page.getPageSize()+" "; } public static String insert(Object t){ Field[] at = t.getClass().getDeclaredFields(); String tableName = ""; try { Table table = (Table) t.getClass().getAnnotation(Table.class); tableName = table.name(); } catch (Exception e) { logger.warn(","+e.getMessage()); tableName = t.getClass().getSimpleName().toLowerCase(); } tableName=DaoUtil.tableFix+tableName; StringBuilder sb = new StringBuilder(40); sb.append(INSERT).append(tableName).append(BRACKET_LEFT); StringBuilder after = new StringBuilder(48);// SQL for (Field field : at) { field.setAccessible(true); String Tcolumn = field.getName(); try { if (field.get(t) != null || (field.isAnnotationPresent(Column.class) == true && field.getAnnotation(Column.class).insertZero() == true)) { Column dColumn = field.getAnnotation(Column.class); Tcolumn = dColumn != null ? dColumn.column() : field.getName(); if (field.getModifiers() == 25) continue; sb.append(APOSTROPHE).append(Tcolumn).append(APOSTROPHECOMMA); after.append(COLON).append(field.getName()).append(COMMA); } } catch (IllegalArgumentException | IllegalAccessException e) { logger.error("" + e.getMessage()); } } sb.deleteCharAt(sb.length()-1); after.deleteCharAt(after.length()-1); sb.append(VALUES).append(after) .append(BRACKET_RIGHT); return sb.toString(); } }
package com.boundary.sdk; import java.io.Serializable; import java.util.HashMap; import java.util.Map; /** * @author davidg * */ public class Source implements Serializable { private String ref; private String type; private String name; private Map<String,Object> properties; /** * Default constructor */ public Source() { this("",""); } /** * Constructor that uses ref and type * * @param ref * @param type */ public Source(String ref, String type) { this(ref,type,""); } /** * Constructor * * @param ref * @param type * @param name */ public Source(String ref,String type,String name) { this(ref,type,name,new HashMap<String,Object>()); } /** * Constructor * * @param ref * @param type * @param name * @param properties */ public Source(String ref, String type, String name, Map<String,Object> properties) { this.ref = ref; this.type = type; this.name = name; this.properties = properties; } /** * Set the ref value * * @param ref * @return */ public Source setRef(String ref) { this.ref = ref; return this; } /** * * @return */ public String getRef() { return this.ref; } /** * Set the type of the source. * @param type * @return */ public Source setType(String type) { this.type = type; return this; } /** * * @return */ public String getType() { return this.type; } /** * * @param name * @return */ public Source setName(String name) { this.name = name; return this; } /** * * @return */ public String getName() { return this.name; } public Map<String,Object> getProperties() { return properties; } /** * * @param properties * @return */ public Source setProperties(Map<String,Object> properties) { this.properties = properties; return this; } public String toString() { StringBuffer s = new StringBuffer(); s.append("ref: " + this.ref); s.append("type: " + this.type); s.append("name: " + this.name); s.append("properties: " + this.properties); return s.toString(); } }
package com.nullprogram.wheel; import java.util.Vector; import java.util.ArrayDeque; import java.util.Iterator; import java.util.Random; import java.awt.Color; import java.awt.Graphics; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseListener; import java.awt.event.MouseEvent; import javax.swing.Timer; import javax.swing.JFrame; import javax.swing.JComponent; /** * Simulates and displays a chaotic water wheel. * * Left-clicking adds a bucket and right-clicking removes a * bucket. The simulation discrete steps are uniform, making this a * bit rudimentary. * * This code is based on a Matlab program written by my friend Michael * Abraham. */ public class ChaosWheel extends JComponent implements MouseListener { private static final long serialVersionUID = 4764158473501226728L; /* Simulation constants. */ private static final int SIZE = 300; // display size in pixels private static final int DELAY = 30; // milliseconds private static final int DEFAULT_BUCKETS = 9; private static final int MIN_BUCKETS = 5; /* Simulation parameters. */ private double radius = 1; // feet private double wheelIntertia = .1; // slug * ft ^ 2 private double damping = 2.5; // ft * lbs / radians / sec private double gravity = 10.7; // ft / sec ^ 2 private double bucketFull = 1.0; // slug private double drainRate = 0.3; // slug / sec / slug private double fillRate = 0.33; // slug / sec /* Current state of the wheel. */ private double theta; // radians private double thetadot; // radians / sec private Vector<Double> buckets; // slug private Timer timer; private boolean graphMode; /* Histotic state information. */ private static final int MAX_HISTORY = 1000; private ArrayDeque<Double> rlRatio; // left/right water ratio private ArrayDeque<Double> tbRatio; // top/bottom water ratio private double rlRatioMax = 0; private double rlRatioMin = 0; private double tbRatioMax = 0; private double tbRatioMin = 0; /** * Create a water wheel with the default number of buckets. */ public ChaosWheel() { this(DEFAULT_BUCKETS); } /** * Create a water wheel with a specific number of buckets. * * @param numBuckets number of buckets. */ public ChaosWheel(final int numBuckets) { Random rng = new Random(); theta = rng.nextDouble() * 2d * Math.PI; thetadot = (rng.nextDouble() - 0.5); buckets = new Vector<Double>(); for (int i = 0; i < numBuckets; i++) { buckets.add(0d); } rlRatio = new ArrayDeque<Double>(); tbRatio = new ArrayDeque<Double>(); setPreferredSize(new Dimension(SIZE, SIZE)); addMouseListener(this); ActionListener listener = new ActionListener() { public void actionPerformed(final ActionEvent evt) { updateState(DELAY / 1000.0); repaint(); } }; graphMode = false; timer = new Timer(DELAY, listener); } /** * The main function when running standalone. * * @param args command line arguments */ public static void main(final String[] args) { JFrame frame = new JFrame("Lorenz Water Wheel"); ChaosWheel wheel = null; if (args.length == 0) { wheel = new ChaosWheel(); } else { int num = 0; try { num = Integer.parseInt(args[0]); } catch (NumberFormatException e) { System.out.println("Argument must be an integer."); System.exit(1); } if (num < MIN_BUCKETS) { System.out.println("Minimum # of buckets: " + MIN_BUCKETS); System.exit(1); } wheel = new ChaosWheel(num); } frame.add(wheel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); wheel.start(); } /** * Draw the water wheel to the display. * * @param g the graphics to draw on */ public final void paintComponent(final Graphics g) { super.paintComponent(g); if (graphMode) { paintGraph(g); return; } /* Draw the buckets. */ double diff = Math.PI * 2d / buckets.size(); int size = Math.min(getWidth(), getHeight()); int bucketSize = size / (int) (buckets.size() / 1.25); int drawRadius = size / 2 - bucketSize; int centerx = size / 2; int centery = size / 2; for (int i = 0; i < buckets.size(); i++) { double angle = i * diff + theta - Math.PI / 2; int x = centerx + (int) (Math.cos(angle) * drawRadius); int y = centery + (int) (Math.sin(angle) * drawRadius); g.setColor(Color.black); g.drawRect(x - bucketSize / 2, y - bucketSize / 2, bucketSize, bucketSize); g.setColor(Color.blue); int height = (int) (bucketSize * buckets.get(i) / bucketFull); g.fillRect(x - bucketSize / 2, y - bucketSize / 2 + (bucketSize - height), bucketSize, height); } } /** * Paint a graph of historical data. */ private void paintGraph(Graphics g) { if (rlRatio.size() < 2) { return; } g.setColor(Color.black); Iterator<Double> rlit = rlRatio.iterator(); Iterator<Double> tbit = tbRatio.iterator(); Double rlLast = rlit.next(); Double tbLast = tbit.next(); while (rlit.hasNext()) { Double rl = rlit.next(); Double tb = tbit.next(); int x0 = (int) (rlLast / (rlRatioMax - rlRatioMin) * getWidth()); int y0 = (int) (tbLast / (tbRatioMax - tbRatioMin) * getHeight()); int x1 = (int) (rl / (rlRatioMax - rlRatioMin) * getWidth()); int y1 = (int) (tb / (tbRatioMax - tbRatioMin) * getHeight()); g.drawLine(x0, y0, x1, y1); rlLast = rl; tbLast = tb; } } /** * Start running the wheel simulation. */ public final void start() { timer.start(); } /** * Tell the wheel to stop running. */ public final void stop() { timer.stop(); } /** * Update the state by the given amount of seconds. * * @param tdot number of seconds to update by. */ public final void updateState(final double tdot) { theta += thetadot * tdot; while (theta < 0) { theta += Math.PI * 2; } while (theta > Math.PI * 2) { theta -= Math.PI * 2; } /* Calculate inertia */ double inertia = wheelIntertia; for (int i = 0; i < buckets.size(); i++) { inertia += buckets.get(i) * radius * radius; } /* Calculate torque */ double torque = -1 * (damping * thetadot); double diff = Math.PI * 2d / buckets.size(); for (int i = 0; i < buckets.size(); i++) { torque += buckets.get(i) * radius * gravity * Math.sin(theta + diff * i); } thetadot += torque / inertia * tdot; /* Update buckets */ for (int i = 0; i < buckets.size(); i++) { double oldVal = buckets.get(i); double newVal = oldVal; newVal += buckets.get(i) * -drainRate * tdot + tdot * inflow(theta + diff * i); newVal = Math.max(0, newVal); newVal = Math.min(bucketFull, newVal); buckets.set(i, newVal); } logState(); } /** * Append some info about the current wheel state to the log. */ private final void logState() { double left = 0; double right = 0; double top = 0; double bottom = 0; double diff = Math.PI * 2d / buckets.size(); for (int i = 0; i < buckets.size(); i++) { double angle = theta + diff * i; if (Math.cos(angle) > 0) { right += buckets.get(i); } left += buckets.get(i); if (Math.sin(angle) > 0) { top += buckets.get(i); } bottom += buckets.get(i); } double rl = left/right; double tb = top/bottom; rlRatioMax = Math.max(rl, rlRatioMax); tbRatioMax = Math.max(tb, tbRatioMax); rlRatioMin = Math.min(rl, rlRatioMin); tbRatioMin = Math.min(tb, tbRatioMin); rlRatio.add(rl); tbRatio.add(tb); if (rlRatio.size() > MAX_HISTORY) { rl = rlRatio.remove(); tb = tbRatio.remove(); } } /** * The fill rate for a bucket at the given position. * * @param angle position of the bucket * @return fill rate of the bucket (slugs / sec) */ private double inflow(final double angle) { double lim = Math.abs(Math.cos(Math.PI * 2d / buckets.size())); if (Math.cos(angle) > lim) { return fillRate / 2d * (Math.cos(buckets.size() * Math.atan2(Math.tan(angle), 1) / 2d) + 1); } else { return 0; } } /** * Add one bucket to the display. */ private void addBucket() { buckets.add(0d); } /** * Remove one bucket from the display. */ private void removeBucket() { if (buckets.size() > MIN_BUCKETS) { buckets.remove(0); } } /** {@inheritDoc} */ public final void mouseReleased(final MouseEvent e) { System.out.println("click!"); switch (e.getButton()) { case MouseEvent.BUTTON1: addBucket(); break; case MouseEvent.BUTTON2: graphMode ^= true; break; case MouseEvent.BUTTON3: removeBucket(); break; default: /* do nothing */ break; } } /** {@inheritDoc} */ public void mouseExited(final MouseEvent e) { /* Do nothing */ } /** {@inheritDoc} */ public void mouseEntered(final MouseEvent e) { /* Do nothing */ } /** {@inheritDoc} */ public void mouseClicked(final MouseEvent e) { /* Do nothing */ } /** {@inheritDoc} */ public void mousePressed(final MouseEvent e) { /* Do nothing */ } }
package com.box.sdk; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashSet; import com.eclipsesource.json.JsonArray; import com.eclipsesource.json.JsonObject; import com.eclipsesource.json.JsonValue; /** * Receives real-time events from the API and forwards them to {@link EventListener EventListeners}. * * <p>This class handles long polling the Box events endpoint in order to receive real-time user or enterprise events. * When an EventStream is started, it begins long polling on a separate thread until the {@link #stop} method is called. * Since the API may return duplicate events, EventStream also maintains a small cache of the most recently received * event IDs in order to automatically deduplicate events.</p> * */ public class EventStream { private static final int LIMIT = 800; private static final int LRU_SIZE = 512; private static final URLTemplate EVENT_URL = new URLTemplate("events?limit=" + LIMIT + "&stream_position=%s"); private final BoxAPIConnection api; private final Collection<EventListener> listeners; private final Object listenerLock; private LinkedHashSet<String> receivedEvents; private boolean started; private Poller poller; private Thread pollerThread; /** * Constructs an EventStream using an API connection. * @param api the API connection to use. */ public EventStream(BoxAPIConnection api) { this.api = api; this.listeners = new ArrayList<EventListener>(); this.listenerLock = new Object(); } /** * Adds a listener that will be notified when an event is received. * @param listener the listener to add. */ public void addListener(EventListener listener) { synchronized (this.listenerLock) { this.listeners.add(listener); } } /** * Indicates whether or not this EventStream has been started. * @return true if this EventStream has been started; otherwise false. */ public boolean isStarted() { return this.started; } public void stop() { if (!this.started) { throw new IllegalStateException("Cannot stop the EventStream because it isn't started."); } this.started = false; this.pollerThread.interrupt(); } public void start() { if (this.started) { throw new IllegalStateException("Cannot start the EventStream because it isn't stopped."); } BoxAPIRequest request = new BoxAPIRequest(this.api, EVENT_URL.build(this.api.getBaseURL(), "now"), "GET"); BoxJSONResponse response = (BoxJSONResponse) request.send(); JsonObject jsonObject = JsonObject.readFrom(response.getJSON()); final long initialPosition = jsonObject.get("next_stream_position").asLong(); this.poller = new Poller(initialPosition); this.pollerThread = new Thread(this.poller); this.pollerThread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { EventStream.this.notifyException(e); } }); this.pollerThread.start(); this.started = true; } protected boolean isDuplicate(String eventID) { if (this.receivedEvents == null) { this.receivedEvents = new LinkedHashSet<String>(LRU_SIZE); } boolean newEvent = this.receivedEvents.add(eventID); if (newEvent && this.receivedEvents.size() > LRU_SIZE) { this.receivedEvents.iterator().remove(); } return newEvent; } private void notifyEvent(BoxEvent event) { synchronized (this.listenerLock) { boolean isDuplicate = this.isDuplicate(event.getID()); if (!isDuplicate) { for (EventListener listener : this.listeners) { listener.onEvent(event); } } } } private void notifyException(Throwable e) { if (e instanceof InterruptedException && !this.started) { return; } this.stop(); synchronized (this.listenerLock) { for (EventListener listener : this.listeners) { if (listener.onException(e)) { return; } } } } private class Poller implements Runnable { private final long initialPosition; private RealtimeServerConnection server; public Poller(long initialPosition) { this.initialPosition = initialPosition; this.server = new RealtimeServerConnection(EventStream.this.api); } @Override public void run() { long position = this.initialPosition; while (!Thread.interrupted()) { if (this.server.getRemainingRetries() == 0) { this.server = new RealtimeServerConnection(EventStream.this.api); } if (this.server.waitForChange(position)) { if (Thread.interrupted()) { return; } BoxAPIRequest request = new BoxAPIRequest(EventStream.this.api, EVENT_URL.build(EventStream.this.api.getBaseURL(), position), "GET"); BoxJSONResponse response = (BoxJSONResponse) request.send(); JsonObject jsonObject = JsonObject.readFrom(response.getJSON()); position = jsonObject.get("next_stream_position").asLong(); JsonArray entriesArray = jsonObject.get("entries").asArray(); for (JsonValue entry : entriesArray) { BoxEvent event = new BoxEvent(EventStream.this.api, entry.asObject()); EventStream.this.notifyEvent(event); } } } } } }
package com.vmware.vim25.mo.util; import java.lang.reflect.Constructor; import com.vmware.vim25.*; import com.vmware.vim25.mo.*; /** * Utility class for the Managed Object and ManagedObjectReference. * @author Steve JIN (sjin@vmware.com) */ public class MorUtil { final public static String moPackageName = "com.vmware.vim25.mo"; public static ManagedObjectReference[] createMORs(ManagedObject[] mos) { if(mos==null) { throw new IllegalArgumentException(); } ManagedObjectReference[] mors = new ManagedObjectReference[mos.length]; for(int i=0; i<mos.length; i++) { mors[i] = mos[i].getMOR(); } return mors; } public static ManagedObject createExactManagedObject(ServerConnection sc, ManagedObjectReference mor) { if(mor==null) { return null; } String moType = mor.getType(); try { Class moClass = Class.forName(moPackageName + "." + moType); Constructor constructor = moClass.getConstructor( new Class[] {ServerConnection.class, ManagedObjectReference.class}); return (ManagedObject) constructor.newInstance( new Object[] { sc, mor} ); } catch(Exception e) { e.printStackTrace(); return null; } } public static ManagedEntity createExactManagedEntity(ServerConnection sc, ManagedObjectReference mor) { return (ManagedEntity) createExactManagedObject(sc, mor); } public static ManagedEntity[] createManagedEntities(ServerConnection sc, ManagedObjectReference[] mors) { ManagedEntity[] mes = new ManagedEntity[mors.length]; for(int i=0; i< mors.length; i++) { mes[i] = createExactManagedEntity(sc, mors[i]); } return mes; } }
package com.jaamsim.input; import java.net.URI; import java.util.ArrayList; import java.util.Arrays; import java.util.regex.Pattern; import com.jaamsim.Samples.SampleConstant; import com.jaamsim.Samples.SampleProvider; import com.jaamsim.math.Color4d; import com.jaamsim.units.DimensionlessUnit; import com.jaamsim.units.TimeUnit; import com.jaamsim.units.Unit; import com.jaamsim.units.UserSpecifiedUnit; import com.sandwell.JavaSimulation.BooleanVector; import com.sandwell.JavaSimulation.ColourInput; import com.sandwell.JavaSimulation.DoubleVector; import com.sandwell.JavaSimulation.Entity; import com.sandwell.JavaSimulation.Group; import com.sandwell.JavaSimulation.InputErrorException; import com.sandwell.JavaSimulation.IntegerVector; import com.sandwell.JavaSimulation.ListInput; import com.sandwell.JavaSimulation.ObjectType; import com.sandwell.JavaSimulation.StringVector; import com.sandwell.JavaSimulation.Tester; import com.sandwell.JavaSimulation3D.Clock; public abstract class Input<T> { protected static final String INP_ERR_COUNT = "Expected an input with %s value(s), received: %s"; protected static final String INP_ERR_RANGECOUNT = "Expected an input with %d to %d values, received: %s"; protected static final String INP_ERR_EVENCOUNT = "Expected an input with even number of values, received: %s"; protected static final String INP_ERR_ODDCOUNT = "Expected an input with odd number of values, received: %s"; protected static final String INP_ERR_BOOLEAN = "Expected a boolean value, received: %s"; protected static final String INP_ERR_INTEGER = "Expected an integer value, received: %s"; protected static final String INP_ERR_INTEGERRANGE = "Expected an integer between %d and %d, received: %d"; protected static final String INP_ERR_DOUBLE = "Expected an numeric value, received: %s"; protected static final String INP_ERR_DOUBLERANGE = "Expected a number between %f and %f, received: %f"; protected static final String INP_ERR_TIME = "Expected a time value (hh:mm or hh:mm:ss), received: %s"; protected static final String INP_ERR_TIMEVALUE = "Expected a numeric value, 12 numeric values, or a probabilty distribution, received: %s"; protected static final String INP_ERR_BADSUM = "List must sum to %f, received:%f"; protected static final String INP_ERR_BADCHOICE = "Expected one of %s, received: %s"; protected static final String INP_ERR_ELEMENT = "Error parsing element %d: %s"; protected static final String INP_ERR_ENTNAME = "Could not find an Entity named: %s"; protected static final String INP_ERR_NOUNITFOUND = "A unit is required, could not parse '%s' as a %s"; protected static final String INP_ERR_NOTUNIQUE = "List must contain unique entries, repeated entry: %s"; protected static final String INP_ERR_NOTVALIDENTRY = "List must not contain: %s"; protected static final String INP_ERR_ENTCLASS = "Expected a %s, %s is a %s"; protected static final String INP_ERR_INTERFACE = "Expected an object implementing %s, %s does not"; protected static final String INP_ERR_UNITS = "Unit types do not match"; protected static final String INP_ERR_UNITUNSPECIFIED = "Unit type has not been specified"; protected static final String INP_ERR_NOTSUBCLASS = "Expected a subclass of %s, got %s"; protected static final String INP_ERR_BADDATE = "Expected a valid RFC8601 datetime, got: %s"; protected static final String INP_VAL_LISTSET = "Values found for %s without %s being set"; protected static final String INP_VAL_LISTSIZE = "%s and %s must be of equal size"; protected static final String NO_VALUE = "{ }"; protected static final String POSITIVE_INFINITY = "Infinity"; protected static final String NEGATIVE_INFINITY = "-Infinity"; protected static final String SEPARATOR = " "; private final String keyword; // the preferred name for the input keyword private final String category; protected T defValue; protected T value; private boolean edited; // indicates if input has been edited for this entity private boolean hidden; // Hide this input from the EditBox protected String valueString; // value from .cfg file public static class ParseContext { public URI context; public String jail; } public Input(String key, String cat, T def) { keyword = key; category = cat; setDefaultValue(def); edited = false; hidden = false; valueString = ""; } public void reset() { this.setDefaultValue( this.getDefaultValue() ); valueString = ""; edited = false; } @Override public String toString() { return String.format("%s", value); } public final String getKeyword() { return keyword; } public final String getCategory() { return category; } public void setDefaultValue(T val) { defValue = val; value = val; } public T getDefaultValue() { return defValue; } public String getDefaultString() { if (defValue == null) return NO_VALUE; StringBuilder tmp = new StringBuilder(defValue.toString()); if (tmp.length() == 0) return NO_VALUE; return tmp.toString(); } /** * Returns the input String used to designate no value or null. * * @return - the NO_VALUE input String. */ public static String getNoValue() { return NO_VALUE; } public T getValue() { return value; } public void setHidden(boolean hide) { hidden = hide; } public boolean getHidden() { return hidden; } public void setEdited(boolean bool) { edited = bool; } public boolean isEdited() { return edited; } public String getValueString() { return valueString; } public void setValueString(String str) { valueString = str; } public void parse(KeywordIndex kw) throws InputErrorException { StringVector data = new StringVector(kw.numArgs()); for (int i = 0; i < kw.numArgs(); i++) { data.add(kw.getArg(i)); } parse(data); } public void parse(StringVector input) throws InputErrorException { return; } public static void assertCount(DoubleVector input, int... counts) throws InputErrorException { // If there is no constraint on the element count, return if (counts == null || counts.length == 0) return; // If there is an exact constraint, check the count for (int each : counts) { if (each == input.size()) return; } // Input size is not equal to any of the specified counts throw new InputErrorException(INP_ERR_COUNT, Arrays.toString(counts), input.toString()); } public static void assertCount(KeywordIndex kw, int... counts) throws InputErrorException { // If there is no constraint on the element count, return if (counts.length == 0) return; // If there is an exact constraint, check the count for (int each : counts) { if (each == kw.numArgs()) return; } // Input size is not equal to any of the specified counts throw new InputErrorException(INP_ERR_COUNT, Arrays.toString(counts), kw.argString()); } public static void assertCountRange(KeywordIndex kw, int min, int max) throws InputErrorException { // For a range with a single value, fall back to the exact test if (min == max) { Input.assertCount(kw, min); return; } if (kw.numArgs() < min || kw.numArgs() > max) throw new InputErrorException(INP_ERR_RANGECOUNT, min, max, kw.argString()); } public static void assertCount(StringVector input, int... counts) throws InputErrorException { // If there is no constraint on the element count, return if (counts.length == 0) return; // If there is an exact constraint, check the count for (int each : counts) { if (each == input.size()) return; } // Input size is not equal to any of the specified counts throw new InputErrorException(INP_ERR_COUNT, Arrays.toString(counts), input.toString()); } public static void assertCountRange(DoubleVector input, int min, int max) throws InputErrorException { // For a range with a single value, fall back to the exact test if (min == max) { Input.assertCount(input, min); return; } if (input.size() < min || input.size() > max) throw new InputErrorException(INP_ERR_RANGECOUNT, min, max, input.toString()); } public static void assertCountRange(StringVector input, int min, int max) throws InputErrorException { // For a range with a single value, fall back to the exact test if (min == max) { Input.assertCount(input, min); return; } if (input.size() < min || input.size() > max) throw new InputErrorException(INP_ERR_RANGECOUNT, min, max, input.toString()); } public static void assertCountEven( StringVector input ) throws InputErrorException { if ( ( input.size() % 2 ) != 0 ) throw new InputErrorException(INP_ERR_EVENCOUNT, input.toString()); } public static void assertCountOdd( StringVector input ) throws InputErrorException { if ( ( input.size() % 2 ) == 0 ) throw new InputErrorException(INP_ERR_ODDCOUNT, input.toString()); } public static <T extends Entity> void assertNotPresent(ArrayList<? super T> list, T ent) throws InputErrorException { if (list.contains(ent)) throw new InputErrorException(INP_ERR_NOTVALIDENTRY, ent.getName()); } public static void assertSumTolerance(DoubleVector vec, double sum, double tol) throws InputErrorException { // Vector sum is within tolerance of given sum, no error if (Math.abs(vec.sum() - sum) < tol) return; throw new InputErrorException(INP_ERR_BADSUM, sum, vec.sum()); } public static <T> T parse(StringVector data, Class<T> aClass, String units, double minValue, double maxValue, int minCount, int maxCount, Class<? extends Unit> unitType) { if( aClass == Double.class ) { if( units != null ) return aClass.cast( Input.parseDouble( data, minValue, maxValue, units) ); else{ DoubleVector tmp = Input.parseDoubles( data, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, unitType ); Input.assertCount(tmp, 1); return aClass.cast( tmp.get(0)); } } if( aClass == DoubleVector.class ) { if( units != null ){ DoubleVector value = Input.parseDoubleVector( data, minValue, maxValue, units); if (value.size() < minCount || value.size() > maxCount) throw new InputErrorException(INP_ERR_RANGECOUNT, minCount, maxCount, data); return aClass.cast( value ); } else { DoubleVector tmp = Input.parseDoubles( data, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, unitType ); return aClass.cast( tmp ); } } if( Entity.class.isAssignableFrom(aClass) ) { Class<? extends Entity> temp = aClass.asSubclass(Entity.class); Input.assertCount(data, 1, 1); return aClass.cast( Input.parseEntity(data.get(0), temp) ); } if( aClass == Boolean.class ) { Input.assertCount(data, 1); Boolean value = Boolean.valueOf(Input.parseBoolean(data.get(0))); return aClass.cast(value); } if( aClass == Integer.class ) { Input.assertCount(data, 1); Integer value = Input.parseInteger(data.get( 0 ), (int)minValue, (int)maxValue); return aClass.cast(value); } if( aClass == SampleProvider.class ) { // Try to parse as a constant value try { DoubleVector tmp = Input.parseDoubles(data, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, unitType); Input.assertCount(tmp, 1); return aClass.cast( new SampleConstant(unitType, tmp.get(0)) ); } catch (InputErrorException e) {} // If not a constant, try parsing a SampleProvider Input.assertCount(data, 1); Entity ent = Input.parseEntity(data.get(0), Entity.class); SampleProvider s = Input.castImplements(ent, SampleProvider.class); if( s.getUnitType() != UserSpecifiedUnit.class ) Input.assertUnitsMatch(unitType, s.getUnitType()); return aClass.cast(s); } // TODO - parse other classes // if( aClass == IntegerVector.class ) { throw new InputErrorException("%s is not supported for parsing yet", aClass); } public static boolean parseBoolean(String data) throws InputErrorException { if ("TRUE".equals(data)) { return true; } if ("FALSE".equals(data)) { return false; } throw new InputErrorException(INP_ERR_BOOLEAN, data); } public static BooleanVector parseBooleanVector(KeywordIndex kw) throws InputErrorException { BooleanVector temp = new BooleanVector(kw.numArgs()); for (int i = 0; i < kw.numArgs(); i++) { try { boolean element = Input.parseBoolean(kw.getArg(i)); temp.add(element); } catch (InputErrorException e) { throw new InputErrorException(INP_ERR_ELEMENT, i, e.getMessage()); } } return temp; } public static BooleanVector parseBooleanVector(StringVector input) throws InputErrorException { BooleanVector temp = new BooleanVector(input.size()); for (int i = 0; i < input.size(); i++) { try { boolean element = Input.parseBoolean(input.get(i)); temp.add(element); } catch (InputErrorException e) { throw new InputErrorException(INP_ERR_ELEMENT, i, e.getMessage()); } } return temp; } public static ArrayList<Color4d> parseColorVector(KeywordIndex kw) throws InputErrorException { ArrayList<KeywordIndex> subArgs = kw.getSubArgs(); ArrayList<Color4d> temp = new ArrayList<Color4d>(subArgs.size()); for (int i = 0; i < subArgs.size(); i++) { try { Color4d element = Input.parseColour(subArgs.get(i)); temp.add(element); } catch (InputErrorException e) { throw new InputErrorException(INP_ERR_ELEMENT, i, e.getMessage()); } } return temp; } public static Class<? extends Entity> parseClass( String data ) { Class<? extends Entity> entProto = null; try { Class<?> proto = Class.forName( data ); entProto = proto.asSubclass(Entity.class); } catch (ClassNotFoundException e) { throw new InputErrorException( "Class not found " + data ); } return entProto; } public static int parseInteger(String data) throws InputErrorException { return Input.parseInteger(data, Integer.MIN_VALUE, Integer.MAX_VALUE); } public static int parseInteger(String data, int minValue, int maxValue) throws InputErrorException { int temp; try { temp = Integer.parseInt(data); } catch (NumberFormatException e) { throw new InputErrorException(INP_ERR_INTEGER, data); } if (temp < minValue || temp > maxValue) throw new InputErrorException(INP_ERR_INTEGERRANGE, minValue, maxValue, temp); return temp; } public static boolean isInteger(String val) { try { Integer.parseInt(val); return true; } catch (NumberFormatException e) { return false; } } public static IntegerVector parseIntegerVector(StringVector input, int minValue, int maxValue) throws InputErrorException { IntegerVector temp = new IntegerVector(input.size()); for (int i = 0; i < input.size(); i++) { try { int element = Input.parseInteger(input.get(i), minValue, maxValue); temp.add(element); } catch (InputErrorException e) { throw new InputErrorException(INP_ERR_ELEMENT, i, e.getMessage()); } } return temp; } public static IntegerVector parseIntegerVector(KeywordIndex kw, int minValue, int maxValue) throws InputErrorException { IntegerVector temp = new IntegerVector(kw.numArgs()); for (int i = 0; i <kw.numArgs(); i++) { try { int element = Input.parseInteger(kw.getArg(i), minValue, maxValue); temp.add(element); } catch (InputErrorException e) { throw new InputErrorException(INP_ERR_ELEMENT, i, e.getMessage()); } } return temp; } public static double parseTime(String data, double minValue, double maxValue) throws InputErrorException { return Input.parseTime(data, minValue, maxValue, 1.0); } /** * Convert the given String to a double and apply the given conversion factor */ public static double parseTime(String data, double minValue, double maxValue, double factor ) throws InputErrorException { double value = 0.0d; // check for hh:mm:ss or hh:mm if (data.indexOf(":") > -1) { String[] splitDouble = data.split( ":" ); if (splitDouble.length != 2 && splitDouble.length != 3) throw new InputErrorException(INP_ERR_TIME, data); try { double hour = Double.valueOf(splitDouble[0]); double min = Double.valueOf(splitDouble[1]); double sec = 0.0d; if (splitDouble.length == 3) sec = Double.valueOf(splitDouble[2]); value = hour + (min / 60.0d) + (sec / 3600.0d); } catch (NumberFormatException e) { throw new InputErrorException(INP_ERR_TIME, data); } } else { value = Input.parseDouble(data); } value = value * factor; if (value < minValue || value > maxValue) throw new InputErrorException(INP_ERR_DOUBLERANGE, minValue, maxValue, value); return value; } /** * Convert the given String to a double and apply the given conversion factor */ public static double parseSeconds(String data, double minValue, double maxValue, double factor ) throws InputErrorException { double value = 0.0d; // check for hh:mm:ss or hh:mm if (data.indexOf(":") > -1) { String[] splitDouble = data.split( ":" ); if (splitDouble.length != 2 && splitDouble.length != 3) throw new InputErrorException(INP_ERR_TIME, data); try { double hour = Double.valueOf(splitDouble[0]); double min = Double.valueOf(splitDouble[1]); double sec = 0.0d; if (splitDouble.length == 3) sec = Double.valueOf(splitDouble[2]); value = hour * 3600.0d + min * 60.0d + sec; } catch (NumberFormatException e) { throw new InputErrorException(INP_ERR_TIME, data); } } else { value = Input.parseDouble(data); value = value * factor; } if (value < minValue || value > maxValue) throw new InputErrorException(INP_ERR_DOUBLERANGE, minValue, maxValue, value); return value; } private static final Pattern is8601date = Pattern.compile("\\d{4}-\\d{2}-\\d{2}"); private static final Pattern is8601time = Pattern.compile("\\d{4}-\\d{2}-\\d{2}[ T]\\d{2}:\\d{2}:\\d{2}"); private static final Pattern is8601full = Pattern.compile("\\d{4}-\\d{2}-\\d{2}[ T]\\d{2}:\\d{2}:\\d{2}\\.\\d{1,6}"); private static final Pattern isextendtime = Pattern.compile("\\d{1,}:\\d{2}:\\d{2}"); private static final Pattern isextendfull = Pattern.compile("\\d{1,}:\\d{2}:\\d{2}.\\d{1,6}"); private static final long usPerSec = 1000000; private static final long usPerMin = 60 * usPerSec; private static final long usPerHr = 60 * usPerMin; private static final long usPerDay = 24 * usPerHr; public static final long usPerYr = 365 * usPerDay; /** * Parse an RFC8601 date time and return it as an offset in microseconds from * 0AD. This assumes a very simple concept of a 365 day year with no leap years * and no leap seconds. * * An RFC8601 date time looks like YYYY-MM-DD HH:MM:SS.mmm or YYYY-MM-DDTHH:MM:SS.mmm * * @param input * @param datumYear * @return */ public static long parseRFC8601DateTime(String input) { if (is8601time.matcher(input).matches()) { int YY = Integer.parseInt(input.substring(0, 4)); int MM = Integer.parseInt(input.substring(5, 7)); int DD = Integer.parseInt(input.substring(8, 10)); int hh = Integer.parseInt(input.substring(11, 13)); int mm = Integer.parseInt(input.substring(14, 16)); int ss = Integer.parseInt(input.substring(17, 19)); return getUS(input, YY, MM, DD, hh, mm, ss, 0); } if (is8601full.matcher(input).matches()) { int YY = Integer.parseInt(input.substring(0, 4)); int MM = Integer.parseInt(input.substring(5, 7)); int DD = Integer.parseInt(input.substring(8, 10)); int hh = Integer.parseInt(input.substring(11, 13)); int mm = Integer.parseInt(input.substring(14, 16)); int ss = Integer.parseInt(input.substring(17, 19)); // grab the us values and zero-pad to a full 6-digit number String usChars = input.substring(20, input.length()); int us = 0; switch (usChars.length()) { case 1: us = Integer.parseInt(usChars) * 100000; break; case 2: us = Integer.parseInt(usChars) * 10000; break; case 3: us = Integer.parseInt(usChars) * 1000; break; case 4: us = Integer.parseInt(usChars) * 100; break; case 5: us = Integer.parseInt(usChars) * 10; break; case 6: us = Integer.parseInt(usChars) * 1; break; } return getUS(input, YY, MM, DD, hh, mm, ss, us); } if (is8601date.matcher(input).matches()) { int YY = Integer.parseInt(input.substring(0, 4)); int MM = Integer.parseInt(input.substring(5, 7)); int DD = Integer.parseInt(input.substring(8, 10)); return getUS(input, YY, MM, DD, 0, 0, 0, 0); } if (isextendtime.matcher(input).matches()) { int len = input.length(); int hh = Integer.parseInt(input.substring(0, len - 6)); int mm = Integer.parseInt(input.substring(len - 5, len - 3)); int ss = Integer.parseInt(input.substring(len - 2, len)); if (mm < 0 || mm > 59 || ss < 0 || ss > 59) throw new InputErrorException(INP_ERR_BADDATE, input); long ret = 0; ret += hh * usPerHr; ret += mm * usPerMin; ret += ss * usPerSec; return ret; } if (isextendfull.matcher(input).matches()) { int len = input.indexOf("."); int hh = Integer.parseInt(input.substring(0, len - 6)); int mm = Integer.parseInt(input.substring(len - 5, len - 3)); int ss = Integer.parseInt(input.substring(len - 2, len)); if (mm < 0 || mm > 59 || ss < 0 || ss > 59) throw new InputErrorException(INP_ERR_BADDATE, input); // grab the us values and zero-pad to a full 6-digit number String usChars = input.substring(len + 1, input.length()); int us = 0; switch (usChars.length()) { case 1: us = Integer.parseInt(usChars) * 100000; break; case 2: us = Integer.parseInt(usChars) * 10000; break; case 3: us = Integer.parseInt(usChars) * 1000; break; case 4: us = Integer.parseInt(usChars) * 100; break; case 5: us = Integer.parseInt(usChars) * 10; break; case 6: us = Integer.parseInt(usChars) * 1; break; } long ret = 0; ret += hh * usPerHr; ret += mm * usPerMin; ret += ss * usPerSec; ret += us; return ret; } throw new InputErrorException(INP_ERR_BADDATE, input); } private static final long getUS(String input, int YY, int MM, int DD, int hh, int mm, int ss, int us) { // Validate ranges if (MM <= 0 || MM > 12) throw new InputErrorException(INP_ERR_BADDATE, input); if (DD <= 0 || DD > Clock.getDaysInMonth(MM)) throw new InputErrorException(INP_ERR_BADDATE, input); if (hh < 0 || hh > 23) throw new InputErrorException(INP_ERR_BADDATE, input); if (mm < 0 || mm > 59 || ss < 0 || ss > 59) throw new InputErrorException(INP_ERR_BADDATE, input); long ret = 0; ret += YY * usPerYr; ret += (Clock.getFirstDayOfMonth(MM) - 1) * usPerDay; ret += (DD - 1) * usPerDay; ret += hh * usPerHr; ret += mm * usPerMin; ret += ss * usPerSec; ret += us; return ret; } public static DoubleVector parseTimeVector(StringVector input, double minValue, double maxValue) throws InputErrorException { return parseTimeVector(input, minValue, maxValue, 1.0d); } public static DoubleVector parseTimeVector(StringVector input, double minValue, double maxValue, double factor) throws InputErrorException { DoubleVector temp = new DoubleVector(input.size()); for (int i = 0; i < input.size(); i++) { try { double element = Input.parseTime(input.get(i), minValue, maxValue, factor); temp.add(element); } catch (InputErrorException e) { throw new InputErrorException(INP_ERR_ELEMENT, i, e.getMessage()); } } return temp; } public static double parseDouble(String data) throws InputErrorException { return Input.parseDouble(data, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY); } public static double parseDouble(String data, double minValue, double maxValue) throws InputErrorException { return Input.parseDouble(data, minValue, maxValue, 1.0); } /** * Convert the given String to a double and apply the given conversion factor */ public static double parseDouble(String data, double minValue, double maxValue, double factor) throws InputErrorException { double temp; try { temp = Double.parseDouble(data) * factor; } catch (NumberFormatException e) { throw new InputErrorException(INP_ERR_DOUBLE, data); } if (temp < minValue || temp > maxValue) throw new InputErrorException(INP_ERR_DOUBLERANGE, minValue, maxValue, temp); return temp; } /** * Convert the given String to a double including a unit conversion, if necessary */ public static double parseDouble(StringVector input, double minValue, double maxValue, String defaultUnitString) throws InputErrorException { Input.assertCountRange(input, 1, 2); // Warn if the default unit is assumed by the input data if( input.size() == 1 && defaultUnitString.length() > 0 ) InputAgent.logWarning( "Missing units. Assuming %s.", defaultUnitString ); // If there are two values, then assume the last one is a unit double conversionFactor = 1.0; if( input.size() == 2 ) { // Determine the units Unit unit = Input.parseUnits( input.get(1) ); // Determine the default units Unit defaultUnit = Input.tryParseEntity( defaultUnitString.replaceAll("[()]", "").trim(), Unit.class ); if( defaultUnit == null ) { throw new InputErrorException( "Could not determine default units " + defaultUnitString ); } if (defaultUnit.getClass() != unit.getClass()) throw new InputErrorException( "Cannot convert from %s to %s", defaultUnit.getName(), unit.getName()); // Determine the conversion factor from units to default units conversionFactor = unit.getConversionFactorToUnit( defaultUnit ); } // Parse and convert the value return Input.parseDouble( input.get(0), minValue, maxValue, conversionFactor); } public static DoubleVector parseDoubleVector(StringVector input, double minValue, double maxValue) throws InputErrorException { return Input.parseDoubleVector(input, minValue, maxValue, 1.0); } /** * Convert the given StringVector to a DoubleVector and apply the given conversion factor */ public static DoubleVector parseDoubleVector(StringVector input, double minValue, double maxValue, double factor) throws InputErrorException { DoubleVector temp = new DoubleVector(input.size()); for (int i = 0; i < input.size(); i++) { try { double element = Input.parseDouble(input.get(i), minValue, maxValue, factor); temp.add(element); } catch (InputErrorException e) { throw new InputErrorException(INP_ERR_ELEMENT, i, e.getMessage()); } } return temp; } /** * Convert the given StringVector to a DoubleVector and apply the given conversion factor */ public static DoubleVector parseDoubles(KeywordIndex kw, double minValue, double maxValue, Class<? extends Unit> unitType) throws InputErrorException { if (unitType == UserSpecifiedUnit.class) throw new InputErrorException(INP_ERR_UNITUNSPECIFIED); double factor = 1.0d; int numDoubles = kw.numArgs(); // If not a Dimensionless value, a unit is mandatory if (unitType != DimensionlessUnit.class) { Entity ent = Entity.getNamedEntity(kw.getArg(kw.numArgs() - 1)); if (ent == null) throw new InputErrorException(INP_ERR_NOUNITFOUND, kw.getArg(kw.numArgs() - 1), unitType.getSimpleName()); Unit unit = Input.castEntity(ent, unitType); if (unit == null) throw new InputErrorException(INP_ERR_ENTCLASS, unitType.getSimpleName(), ent.getInputName(), ent.getClass().getSimpleName()); factor = unit.getConversionFactorToSI(); numDoubles = kw.numArgs() - 1; } DoubleVector temp = new DoubleVector(numDoubles); for (int i = 0; i < numDoubles; i++) { try { // Allow a special syntax for time-based inputs if (unitType == TimeUnit.class) { double element = Input.parseSeconds(kw.getArg(i), minValue, maxValue, factor); temp.add(element); } else { double element = Input.parseDouble(kw.getArg(i), minValue, maxValue, factor); temp.add(element); } } catch (InputErrorException e) { throw new InputErrorException(INP_ERR_ELEMENT, i, e.getMessage()); } } return temp; } /** * Convert the given StringVector to a DoubleVector and apply the given conversion factor */ public static DoubleVector parseDoubles(StringVector input, double minValue, double maxValue, Class<? extends Unit> unitType) throws InputErrorException { if (unitType == UserSpecifiedUnit.class) throw new InputErrorException(INP_ERR_UNITUNSPECIFIED); double factor = 1.0d; int numDoubles = input.size(); // If not a Dimensionless value, a unit is mandatory if (unitType != DimensionlessUnit.class) { Entity ent = Entity.getNamedEntity(input.get(input.size() - 1)); if (ent == null) throw new InputErrorException(INP_ERR_NOUNITFOUND, input.get(input.size() - 1), unitType.getSimpleName()); Unit unit = Input.castEntity(ent, unitType); if (unit == null) throw new InputErrorException(INP_ERR_ENTCLASS, unitType.getSimpleName(), ent.getInputName(), ent.getClass().getSimpleName()); factor = unit.getConversionFactorToSI(); numDoubles = input.size() - 1; } DoubleVector temp = new DoubleVector(numDoubles); for (int i = 0; i < numDoubles; i++) { try { // Allow a special syntax for time-based inputs if (unitType == TimeUnit.class) { double element = Input.parseSeconds(input.get(i), minValue, maxValue, factor); temp.add(element); } else { double element = Input.parseDouble(input.get(i), minValue, maxValue, factor); temp.add(element); } } catch (InputErrorException e) { throw new InputErrorException(INP_ERR_ELEMENT, i, e.getMessage()); } } return temp; } /** * Convert the given StringVector to a DoubleVector including a unit conversion, if necessary */ public static DoubleVector parseDoubleVector(StringVector data, double minValue, double maxValue, String defaultUnitString) throws InputErrorException { StringVector numericData = new StringVector(data); // If there is more than one value, and the last one is not a number, then assume it is a unit double conversionFactor = 1.0; String unitString = data.get( data.size()-1 ); if( data.size() > 1 && !Tester.isDouble(unitString) ) { // Determine the units Unit unit = Input.parseUnits(unitString); // Determine the default units Unit defaultUnit = Input.tryParseEntity( defaultUnitString.replaceAll("[()]", "").trim(), Unit.class ); if( defaultUnit == null ) { throw new InputErrorException( "Could not determine default units " + defaultUnitString ); } if (defaultUnit.getClass() != unit.getClass()) throw new InputErrorException( "Cannot convert from %s to %s", defaultUnit.getName(), unit.getName()); // Determine the conversion factor to the default units conversionFactor = unit.getConversionFactorToUnit( defaultUnit ); // Remove the unit string from the inputs numericData.remove( numericData.size()-1 ); } else { if( defaultUnitString.length() > 0 ) InputAgent.logWarning( "Missing units. Assuming %s.", defaultUnitString ); } // Parse and convert the values return Input.parseDoubleVector( numericData, minValue, maxValue, conversionFactor); } public static String parseString(String input, ArrayList<String> validList) throws InputErrorException { return parseString(input, validList, false); } public static String parseString(String input, ArrayList<String> validList, boolean caseSensitive) throws InputErrorException { for (String valid : validList) { if (caseSensitive && valid.equals(input)) return valid; if (!caseSensitive && valid.equalsIgnoreCase(input)) return valid; } throw new InputErrorException(INP_ERR_BADCHOICE, validList.toString(), input); } public static ArrayList<String> parseStrings(KeywordIndex kw, ArrayList<String> validList, boolean caseSensitive) throws InputErrorException { ArrayList<String> temp = new ArrayList<String>(kw.numArgs()); for (int i = 0; i < kw.numArgs(); i++) { try { String element = Input.parseString(kw.getArg(i), validList); temp.add(element); } catch (InputErrorException e) { throw new InputErrorException(INP_ERR_ELEMENT, i, e.getMessage()); } } return temp; } public static <T extends Enum<T>> T parseEnum(Class<T> aClass, String input) { try { return Enum.valueOf(aClass, input); } catch (IllegalArgumentException e) { throw new InputErrorException(INP_ERR_BADCHOICE, Arrays.toString(aClass.getEnumConstants()), input); } catch (NullPointerException e) { throw new InputErrorException(INP_ERR_BADCHOICE, Arrays.toString(aClass.getEnumConstants()), input); } } public static Class<? extends Entity> parseEntityType(String input) throws InputErrorException { ObjectType type = Input.tryParseEntity( input, ObjectType.class ); if (type == null) throw new InputErrorException("Entity type not found: %s", input); Class<? extends Entity> klass = type.getJavaClass(); if (klass == null) throw new InputErrorException("ObjectType %s does not have a java class set", input); return klass; } public static void assertUnitsMatch(Class<? extends Unit> u1, Class<? extends Unit> u2) throws InputErrorException { if (u1 != u2) throw new InputErrorException(INP_ERR_UNITS); } public static <T extends Entity> Class<? extends T> checkCast(Class<? extends Entity> klass, Class<T> parent) { try { return klass.asSubclass(parent); } catch (ClassCastException e) { throw new InputErrorException(INP_ERR_NOTSUBCLASS, parent.getName(), klass.getName()); } } public static <T> T castImplements(Entity ent, Class<T> klass) throws InputErrorException { try { return klass.cast(ent); } catch (ClassCastException e) { throw new InputErrorException(INP_ERR_INTERFACE, klass.getName(), ent.getInputName()); } } private static <T extends Entity> T castEntity(Entity ent, Class<T> aClass) throws InputErrorException { try { return aClass.cast(ent); } catch (ClassCastException e) { return null; } } public static <T extends Entity> T parseEntity(String choice, Class<T> aClass) throws InputErrorException { Entity ent = Entity.getNamedEntity(choice); if (ent == null) { throw new InputErrorException(INP_ERR_ENTNAME, choice); } T t = Input.castEntity(ent, aClass); if (t == null) { throw new InputErrorException(INP_ERR_ENTCLASS, aClass.getSimpleName(), choice, ent.getClass().getSimpleName()); } return t; } public static <T extends Entity> T tryParseEntity(String choice, Class<T> aClass) { return Input.castEntity(Entity.getNamedEntity(choice), aClass); } public static <T extends Entity> ArrayList<T> parseEntityList(KeywordIndex kw, Class<T> aClass, boolean unique) throws InputErrorException { ArrayList<T> temp = new ArrayList<T>(kw.numArgs()); for (int i = 0; i < kw.numArgs(); i++) { Entity ent = Entity.getNamedEntity(kw.getArg(i)); if (ent == null) { throw new InputErrorException(INP_ERR_ENTNAME, kw.getArg(i)); } // If we found a group, expand the list of Entities if (ent instanceof Group) { ArrayList<Entity> gList = ((Group)ent).getList(); for (int j = 0; j < gList.size(); j++) { T t = Input.castEntity(gList.get(j), aClass); if (t == null) { throw new InputErrorException(INP_ERR_ENTCLASS, aClass.getSimpleName(), gList.get(j), gList.get(j).getClass().getSimpleName()); } temp.add(t); } } else { T t = Input.castEntity(ent, aClass); if (t == null) { throw new InputErrorException(INP_ERR_ENTCLASS, aClass.getSimpleName(), kw.getArg(i), ent.getClass().getSimpleName()); } temp.add(t); } } if (unique) Input.assertUnique(temp); return temp; } public static <T extends Entity> ArrayList<T> parseEntityList(StringVector input, Class<T> aClass, boolean unique) throws InputErrorException { ArrayList<T> temp = new ArrayList<T>(input.size()); for (int i = 0; i < input.size(); i++) { Entity ent = Entity.getNamedEntity(input.get(i)); if (ent == null) { throw new InputErrorException(INP_ERR_ENTNAME, input.get(i)); } // If we found a group, expand the list of Entities if (ent instanceof Group) { ArrayList<Entity> gList = ((Group)ent).getList(); for (int j = 0; j < gList.size(); j++) { T t = Input.castEntity(gList.get(j), aClass); if (t == null) { throw new InputErrorException(INP_ERR_ENTCLASS, aClass.getSimpleName(), gList.get(j), gList.get(j).getClass().getSimpleName()); } temp.add(t); } } else { T t = Input.castEntity(ent, aClass); if (t == null) { throw new InputErrorException(INP_ERR_ENTCLASS, aClass.getSimpleName(), input.get(i), ent.getClass().getSimpleName()); } temp.add(t); } } if (unique) Input.assertUnique(temp); return temp; } public static <T extends Entity> ArrayList<ArrayList<T>> parseListOfEntityLists(KeywordIndex kw, Class<T> aClass, boolean unique) throws InputErrorException { ArrayList<KeywordIndex> subArgs = kw.getSubArgs(); ArrayList<ArrayList<T>> temp = new ArrayList<ArrayList<T>>(subArgs.size()); for (int i = 0; i < subArgs.size(); i++) { try { ArrayList<T> element = Input.parseEntityList(subArgs.get(i), aClass, unique); temp.add(element); } catch (InputErrorException e) { throw new InputErrorException(INP_ERR_ELEMENT, i, e.getMessage()); } } return temp; } public static Color4d parseColour(KeywordIndex kw) { Input.assertCount(kw, 1, 3); // Color names if (kw.numArgs() == 1) { Color4d colAtt = ColourInput.getColorWithName(kw.getArg(0).toLowerCase()); if( colAtt == null ) { throw new InputErrorException( "Color " + kw.getArg( 0 ) + " not found" ); } else { return colAtt; } } // RGB else { DoubleVector dbuf = Input.parseDoubles(kw, 0.0d, 255.0d, DimensionlessUnit.class); double r = dbuf.get(0); double g = dbuf.get(1); double b = dbuf.get(2); if (r > 1.0f || g > 1.0f || b > 1.0f) { r /= 255.0d; g /= 255.0d; b /= 255.0d; } return new Color4d(r, g, b); } } private static void assertUnique(ArrayList<? extends Entity> list) { for (int i = 0; i < list.size(); i++) { Entity ent = list.get(i); for (int j = i + 1; j < list.size(); j++) { if (ent == list.get(j)) { throw new InputErrorException(INP_ERR_NOTUNIQUE, ent.getName()); } } } } public static void validateIndexedLists(ListInput<?> keys, ListInput<?> vals) throws InputErrorException { // If no values set, no validation to be done if (vals.getValue() == null) return; // values are set but indexed list has not if (keys.getValue() == null) throw new InputErrorException(INP_VAL_LISTSET, keys.getKeyword(), vals.getKeyword()); // Both are set, but of differing size if (keys.getListSize() != vals.getListSize()) throw new InputErrorException(INP_VAL_LISTSIZE, keys.getKeyword(), vals.getKeyword()); } public static void validateInputSize(ListInput<?> list1, ListInput<?> list2) throws InputErrorException { // One list is set but not the other if (list1.getValue() != null && list2.getValue() == null) throw new InputErrorException(INP_VAL_LISTSIZE, list1.getKeyword(), list2.getKeyword()); if (list1.getValue() == null && list2.getValue() != null) throw new InputErrorException(INP_VAL_LISTSIZE, list1.getKeyword(), list2.getKeyword()); // Both are set, but of differing size if (list1.getListSize() != list2.getListSize()) throw new InputErrorException(INP_VAL_LISTSIZE, list1.getKeyword(), list2.getKeyword() ); } public static void validateIndexedLists(ArrayList<?> keys, DoubleVector values, String keyName, String valueName) throws InputErrorException { // If no values set, no validation to be done if (values == null) return; // values are set but indexed list has not if (keys == null) throw new InputErrorException(INP_VAL_LISTSET, valueName, keyName); // Both are set, but of differing size if (keys.size() != values.size()) throw new InputErrorException(INP_VAL_LISTSIZE, keyName, valueName); } /* * return a list of valid options if the input has limited number of * choices(e.g true or false for BooleanUinput). * if an input needs to be shown as a dropdown box in Input Editor, it has * to override this method. */ public ArrayList<String> getValidOptions() { return null; } public static Unit parseUnits(String str) { try { return Input.parseEntity(str, Unit.class); } catch(InputErrorException ex) { throw new InputErrorException(String.format("Could not find a unit named: %s", str)); } } public String getDefaultStringForKeyInputs(String unitString) { if (defValue == null) return NO_VALUE; if (defValue.getClass() == Boolean.class) { if((Boolean)defValue) return "TRUE"; return "FALSE"; } StringBuilder tmp = new StringBuilder(); if (defValue.getClass() == Double.class || defValue.getClass() == Integer.class || Entity.class.isAssignableFrom(Double.class)) { if (defValue.equals(Integer.MAX_VALUE) || defValue.equals(Double.POSITIVE_INFINITY)) return POSITIVE_INFINITY; if (defValue.equals(Integer.MIN_VALUE) || defValue.equals(Double.NEGATIVE_INFINITY)) return NEGATIVE_INFINITY; tmp.append(defValue); } else if (defValue.getClass() == SampleConstant.class ) { return defValue.toString(); } else if (defValue.getClass() == DoubleVector.class) { DoubleVector def = (DoubleVector)defValue; if (def.size() == 0) return NO_VALUE; tmp.append(def.get(0)); for (int i = 1; i < def.size(); i++) { tmp.append(SEPARATOR); tmp.append(def.get(i)); } } else if ( Entity.class.isAssignableFrom( defValue.getClass() ) ) { tmp.append(((Entity)defValue).getInputName()); } else { return "?????"; } if (unitString == null || !unitString.isEmpty()) { tmp.append(SEPARATOR); tmp.append(unitString); } return tmp.toString(); } }
package com.jajja.jorm; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.net.URL; import java.sql.SQLException; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.TreeMap; import javax.sql.DataSource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * The database abstraction implemented for {@link Jorm} mapped records. Relies * on {@link javax.sql.DataSource} for data access to configured data bases. One * recommended implementation for easy configuration is * <tt>org.apache.commons.dbcp.BasicDataSource</tt> from the Apache project * <tt>commons-dbcp</tt>. * * @see Jorm * @see Record * @author Martin Korinth <martin.korinth@jajja.com> * @author Andreas Allerdahl <andreas.allerdahl@jajja.com> * @author Daniel Adolfsson <daniel.adolfsson@jajja.com> * @since 1.0.0 */ public class Database { private ThreadLocal<HashMap<String, Transaction>> transactions = new ThreadLocal<HashMap<String, Transaction>>(); private Map<String, DataSource> dataSources = new HashMap<String, DataSource>(); protected Log log = LogFactory.getLog(Database.class); private static volatile Database instance = new Database(); private Database() { } /** * Acts as singleton factory for bean configuration access. All other access * to databases should be static. * * @return the singleton database representation containing configured data * sources for databases. */ public static synchronized Database get() { return instance; } private HashMap<String, Transaction> getTransactions() { if (transactions.get() == null) { transactions.set(new HashMap<String, Transaction>()); } return transactions.get(); } private DataSource getDataSource(String database) { synchronized (dataSources) { return dataSources.get(database); } } /** * Configures all databases accessible through {@link Database#open(String)} * and {@link Database#close(String)}. Overrides any previous configuration. * * @param dataSources the named databases, each represented by a string and * a data source. */ public void setDataSources(Map<String, DataSource> dataSources) { this.dataSources = dataSources; } /** * Configures the named database by means of a data source. * * @param database the named database. * @param dataSource the data source corresponding to the named data base. */ public static void configure(String database, DataSource dataSource) { configure(database, dataSource, false); } /** * Configures the named database by means of a data source. * * @param database the named database. * @param dataSource the data source corresponding to the named data base. * @param isOverride a flag defining configuration as override if a current * configuration for the named database already exists. */ public static void configure(String database, DataSource dataSource, boolean isOverride) { if (!isOverride && isConfigured(database)) { throw new IllegalStateException("Named database '" + database + "' already configured!"); } instance.dataSources.put(database, dataSource); } /** * Determines whether a named database has been configured or not. * * @param database the named database. * @return true if the named database has been configured, false otherwise. */ public static boolean isConfigured(String database) { return instance.dataSources.containsKey(database); } public static void ensureConfigured(String database) { if (!isConfigured(database)) { throw new IllegalStateException("Named database '" + database + "' has no configured data source!"); } } /** * Opens a thread local transaction for the given database name. If an open * transaction already exists, it is reused. This method is idempotent when * called from the same thread. * * @param database the name of the database. * @return the open transaction. */ public static Transaction open(String database) { HashMap<String, Transaction> transactions = instance.getTransactions(); Transaction transaction = transactions.get(database); if (transaction == null) { DataSource dataSource = instance.getDataSource(database); if (dataSource == null) { ensureConfigured(database); // throws! } transaction = new Transaction(dataSource, database); transactions.put(database, transaction); } return transaction; } /** * Commits the thread local transaction for the given database name if it * has been opened. * * @param database the name of the database. * @return the closed transaction or null for no active transaction. * @throws SQLException if a database access error occur */ public static Transaction commit(String database) throws SQLException { HashMap<String, Transaction> transactions = instance.getTransactions(); Transaction transaction = transactions.get(database); if (transaction != null) { transaction.commit(); } else { ensureConfigured(database); } return transaction; } /** * Closes the thread local transaction for the given database name if it has * been opened. This method is idempotent when called from the same thread. * * @param database the name of the database. * @return the closed transaction or null for no active transaction. */ public static Transaction close(String database) { HashMap<String, Transaction> transactions = instance.getTransactions(); Transaction transaction = transactions.get(database); if (transaction != null) { transaction.close(); } else { ensureConfigured(database); } return transaction; } /** * Closes and destroys all transactions for the current thread. */ public static void close() { HashMap<String, Transaction> map = instance.getTransactions(); for (Transaction transaction : map.values()) { transaction.destroy(); } map.clear(); instance.transactions.remove(); } private static List<Configuration> configuration; static { configuration = configure(); } public static void destroy() { for (Configuration conf : configuration) { conf.destroy(); } } private static List<Configuration> configure() { Map<String, Configuration> configurations = new HashMap<String, Configuration>(); Enumeration<URL> resources; try { resources = Thread.currentThread().getContextClassLoader().getResources("jorm.properties"); } catch (IOException ex) { Database.get().log.warn("Failed to find resource 'jorm.properties': " + ex.getMessage(), ex); return null; } while (resources.hasMoreElements()) { URL url = resources.nextElement(); Database.get().log.debug("Found jorm configuration @ " + url.toString()); Properties properties = new Properties(); try { InputStream is = url.openStream(); properties.load(is); is.close(); } catch (IOException ex) { Database.get().log.error("Failed to open jorm.properties: " + ex.getMessage(), ex); continue; } String database = null; String destroyMethodName = null; String dataSourceClassName = null; Map<String, String> dataSourceProperties = new HashMap<String, String>(); int priority = 0; for (Entry<String, String> property : new TreeMap<String, String>((Map) properties).entrySet()) { String[] parts = property.getKey().split("\\."); if (parts.length < 3 || !parts[0].equals("database")) { continue; } if (database != null && !parts[1].equals(database)) { Configuration conf = configurations.get(database); if (conf == null || conf.priority < priority) { conf = new Configuration(database, dataSourceClassName, dataSourceProperties, destroyMethodName, priority); configurations.put(database, conf); Database.get().log.debug("Configured " + conf); } database = null; destroyMethodName = null; dataSourceClassName = null; dataSourceProperties = new HashMap<String, String>(); priority = 0; } if (database == null) { database = parts[1]; } if (parts.length == 3 && parts[2].equals("destroyMethod")) { destroyMethodName = property.getValue(); } else if (parts.length == 3 && parts[2].equals("priority")) { try { priority = Integer.parseInt(property.getValue().trim()); } catch (Exception ex) { } } else if (parts[2].equals("dataSource")) { if (parts.length == 3) { dataSourceClassName = property.getValue(); } else if (parts.length == 4) { dataSourceProperties.put(parts[3], property.getValue()); } else { Database.get().log.warn("Invalid DataSource property '" + property.getKey() + "'"); } } else { Database.get().log.warn("Invalid property '" + property.getKey() + "'"); } } if (database != null) { Configuration conf = configurations.get(database); if (conf == null || conf.priority < priority) { conf = new Configuration(database, dataSourceClassName, dataSourceProperties, destroyMethodName, priority); configurations.put(database, conf); Database.get().log.debug("Configured " + conf); } } } for (Entry<String, Configuration> entry : configurations.entrySet()) { entry.getValue().apply(); Database.get().log.debug("Configured " + configuration); } return new ArrayList<Configuration>(configurations.values()); } public static class Configuration { private String database; private DataSource dataSource; private Map<String, String> dataSourceProperties; private Method destroyMethod; private int priority; @Override public String toString() { return "{ database => " + database + ", dataSourceClassName => " + dataSource.getClass().getName() + ", dataSourceProperties => " + dataSourceProperties + " }"; } public void apply() { configure(database, dataSource); } public Configuration(String database, String dataSourceClassName, Map<String, String> dataSourceProperties, String destroyMethodName, int priority) { this.database = database; this.dataSourceProperties = dataSourceProperties; this.priority = priority; try { Class<?> type = Class.forName(dataSourceClassName); if (destroyMethodName != null) { try { destroyMethod = type.getMethod(destroyMethodName); } catch (NoSuchMethodException e) { throw new IllegalArgumentException("The destroy method does not exist!", e); } catch (SecurityException e) { throw new IllegalArgumentException("The destroy method is not accessible!", e); } } dataSource = (DataSource) type.newInstance(); init(); } catch (InstantiationException e) { throw new IllegalArgumentException("The data source implementation " + dataSourceClassName + " has no default constructor!", e); } catch (IllegalAccessException e) { throw new IllegalArgumentException("The data source implementation " + dataSourceClassName + " has no public constructor!", e); } catch (ClassNotFoundException e) { throw new IllegalArgumentException("The data source implementation " + dataSourceClassName + " does not exist!", e); } catch (ClassCastException e) { throw new IllegalArgumentException("The data source implementation " + dataSourceClassName + " is not a data source!", e); } } private void init() { for (Method method : dataSource.getClass().getMethods()) { String methodName = method.getName(); Class<?>[] parameterTypes = method.getParameterTypes(); if (methodName.startsWith("set") && 3 < methodName.length() && parameterTypes.length == 1) { String name = method.getName().substring(3, 4).toLowerCase() + method.getName().substring(4); // setValue -> value String property = dataSourceProperties.get(name); if (property != null) { boolean isAccessible = method.isAccessible(); method.setAccessible(true); try { method.invoke(dataSource, parse(method.getParameterTypes()[0], property)); } catch (Exception e) { get().log.warn("Failed to invoke " + dataSource.getClass().getName() + "#" + method.getName() + "() in configuration of '" + database + "'", e); } finally { method.setAccessible(isAccessible); } } } } } public void destroy() { if (destroyMethod != null) { try { destroyMethod.invoke(dataSource); } catch (Exception e) { get().log.error("Failed to invoke destroy method for " + dataSource.getClass(), e); } } } @SuppressWarnings("unchecked") private static <T extends Object> T parse(Class<T> type, String property) { Object object; if (type.isAssignableFrom(String.class)) { object = property; } else if (type.isAssignableFrom(boolean.class) || type.isAssignableFrom(Boolean.class)) { object = Boolean.parseBoolean(property); } else if (type.isAssignableFrom(int.class) || type.isAssignableFrom(Integer.class)) { object = Integer.parseInt(property); } else if (type.isAssignableFrom(long.class) || type.isAssignableFrom(Long.class)) { object = Long.parseLong(property); } else { object = null; } return (T) object; } } }
package com.stripe.model; import com.stripe.exception.APIConnectionException; import com.stripe.exception.APIException; import com.stripe.exception.AuthenticationException; import com.stripe.exception.CardException; import com.stripe.exception.InvalidRequestException; import com.stripe.net.APIResource; import com.stripe.net.RequestOptions; import java.util.Collections; import java.util.Map; public class Charge extends APIResource implements MetadataStore<Charge> { Integer amount; Long created; String currency; String id; String status; Boolean livemode; Boolean paid; Boolean refunded; Boolean disputed; Boolean captured; String description; String failureMessage; String failureCode; Integer amountRefunded; String customer; String invoice; ChargeRefundCollection refunds; Card card; Dispute dispute; String balanceTransaction; Map<String, String> metadata; String receiptEmail; String receiptNumber; String statementDescriptor; @Deprecated String statementDescription; ShippingDetails shipping; PaymentSource source; public static final String FRAUD_DETAILS = "fraud_details"; FraudDetails fraudDetails; public FraudDetails getFraudDetails() { return fraudDetails; } public void setFraudDetails(FraudDetails fraudDetails) { this.fraudDetails = fraudDetails; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getStatus() { return status; } public Integer getAmount() { return amount; } public void setAmount(Integer amount) { this.amount = amount; } public Long getCreated() { return created; } public void setCreated(Long created) { this.created = created; } public String getCurrency() { return currency; } public void setCurrency(String currency) { this.currency = currency; } public Boolean getLivemode() { return livemode; } public void setLivemode(Boolean livemode) { this.livemode = livemode; } public Boolean getPaid() { return paid; } public void setPaid(Boolean paid) { this.paid = paid; } public Boolean getRefunded() { return refunded; } public void setRefunded(Boolean refunded) { this.refunded = refunded; } public Boolean getCaptured() { return captured; } public void setCaptured(Boolean captured) { this.captured = captured; } public ShippingDetails getShipping() { return shipping; } public void setShipping(ShippingDetails shipping) { this.shipping = shipping; } @Deprecated public Boolean getDisputed() { return disputed; } @Deprecated public void setDisputed(Boolean disputed) { this.disputed = disputed; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getStatementDescriptor() { return statementDescriptor; } public void setStatementDescriptor(String statementDescriptor) { this.statementDescriptor = statementDescriptor; } @Deprecated public String getStatementDescription() { return statementDescription; } @Deprecated public void setStatementDescription(String statementDescription) { this.statementDescription = statementDescription; } public String getFailureMessage() { return failureMessage; } public void setFailureMessage(String failureMessage) { this.failureMessage = failureMessage; } public String getFailureCode() { return failureCode; } public void setFailureCode(String failureCode) { this.failureCode = failureCode; } public Integer getAmountRefunded() { return amountRefunded; } public void setAmountRefunded(Integer amountRefunded) { this.amountRefunded = amountRefunded; } public String getCustomer() { return customer; } public void setCustomer(String customer) { this.customer = customer; } public String getInvoice() { return invoice; } public void setInvoice(String invoice) { this.invoice = invoice; } public ChargeRefundCollection getRefunds() { // API versions 2014-05-19 and earlier render charge refunds as an array // instead of an object, meaning there is no sublist URL. if (refunds.getURL() == null) { refunds.setURL(String.format("/v1/charges/%s/refunds", getId())); } return refunds; } public Card getCard() { return card; } public void setCard(Card card) { this.card = card; } public Dispute getDispute() { return dispute; } public void setDispute(Dispute dispute) { this.dispute = dispute; } public String getBalanceTransaction() { return balanceTransaction; } public void setBalanceTransaction(String balanceTransaction) { this.balanceTransaction = balanceTransaction; } public Map<String, String> getMetadata() { return metadata; } public void setMetadata(Map<String, String> metadata) { this.metadata = metadata; } public String getReceiptNumber() { return receiptNumber; } public void setReceiptNumber(String receiptNumber) { this.receiptNumber = receiptNumber; } public String getReceiptEmail() { return receiptEmail; } public void setReceiptEmail(String receiptEmail) { this.receiptEmail = receiptEmail; } public PaymentSource getSource() { return source; } public void setSource(PaymentSource source) { this.source = source; } public static Charge create(Map<String, Object> params) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return create(params, (RequestOptions) null); } public static Charge retrieve(String id) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return retrieve(id, (RequestOptions) null); } public Charge update(Map<String, Object> params) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return update(params, (RequestOptions) null); } public static ChargeCollection all(Map<String, Object> params) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return all(params, (RequestOptions) null); } public Charge refund() throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return this.refund(null, (RequestOptions) null); } public Charge capture() throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return this.capture(null, (RequestOptions) null); } public Dispute updateDispute(Map<String, Object> params) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return this.updateDispute(params, (RequestOptions) null); } public Dispute closeDispute() throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return this.closeDispute((RequestOptions) null); } public Charge refund(Map<String, Object> params) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return this.refund(params, (RequestOptions) null); } public Charge capture(Map<String, Object> params) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return this.capture(params, (RequestOptions) null); } @Deprecated public static Charge create(Map<String, Object> params, String apiKey) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return create(params, RequestOptions.builder().setApiKey(apiKey).build()); } public static Charge create(Map<String, Object> params, RequestOptions options) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return request(RequestMethod.POST, classURL(Charge.class), params, Charge.class, options); } @Deprecated public static Charge retrieve(String id, String apiKey) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return retrieve(id, RequestOptions.builder().setApiKey(apiKey).build()); } public static Charge retrieve(String id, RequestOptions options) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return request(RequestMethod.GET, instanceURL(Charge.class, id), null, Charge.class, options); } @Deprecated public Charge update(Map<String, Object> params, String apiKey) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return update(params, RequestOptions.builder().setApiKey(apiKey).build()); } public Charge update(Map<String, Object> params, RequestOptions options) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return request(RequestMethod.POST, instanceURL(Charge.class, id), params, Charge.class, options); } @Deprecated public static ChargeCollection all(Map<String, Object> params, String apiKey) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return all(params, RequestOptions.builder().setApiKey(apiKey).build()); } public static ChargeCollection all(Map<String, Object> params, RequestOptions options) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return request(RequestMethod.GET, classURL(Charge.class), params, ChargeCollection.class, options); } @Deprecated public Charge refund(String apiKey) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return this.refund(RequestOptions.builder().setApiKey(apiKey).build()); // full refund } public Charge refund(RequestOptions options) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return this.refund(null, options); // full refund } @Deprecated public Charge refund(Map<String, Object> params, String apiKey) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return refund(params, RequestOptions.builder().setApiKey(apiKey).build()); } public Charge refund(Map<String, Object> params, RequestOptions options) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return request(RequestMethod.POST, String.format("%s/refund", instanceURL(Charge.class, this.getId())), params, Charge.class, options); } @Deprecated public Charge capture(String apiKey) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return capture(RequestOptions.builder().setApiKey(apiKey).build()); } public Charge capture(RequestOptions options) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return this.capture(null, options); } @Deprecated public Charge capture(Map<String, Object> params, String apiKey) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return capture(params, RequestOptions.builder().setApiKey(apiKey).build()); } public Charge capture(Map<String, Object> params, RequestOptions options) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return request(RequestMethod.POST, String.format("%s/capture", instanceURL(Charge.class, this.getId())), params, Charge.class, options); } @Deprecated public Dispute updateDispute(Map<String, Object> params, String apiKey) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return updateDispute(params, RequestOptions.builder().setApiKey(apiKey).build()); } public Dispute updateDispute(Map<String, Object> params, RequestOptions options) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return request(RequestMethod.POST, String.format("%s/dispute", instanceURL(Charge.class, this.id)), params, Dispute.class, options); } @Deprecated public Dispute closeDispute(String apiKey) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return closeDispute(RequestOptions.builder().setApiKey(apiKey).build()); } public Dispute closeDispute(RequestOptions options) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return request(RequestMethod.POST, String.format("%s/dispute/close", instanceURL(Charge.class, this.getId())), null, Dispute.class, options); } /** * Convenience method to mark a given charge as fraudulent. */ public Charge markFraudulent(RequestOptions options) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { Map<String, Object> params = Collections.<String, Object>singletonMap(FRAUD_DETAILS, Collections.singletonMap(FraudDetails.USER_REPORT, "fraudulent")); return this.update(params, options); } /** * Convenience method to mark a given charge as not fraudulent. */ public Charge markSafe(RequestOptions options) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { Map<String, Object> params = Collections.<String, Object>singletonMap(FRAUD_DETAILS, Collections.singletonMap(FraudDetails.USER_REPORT, "safe")); return this.update(params, options); } }
package com.warptronic.itdm; import javax.json.Json; import javax.json.JsonArrayBuilder; import javax.json.JsonObject; import javax.json.JsonObjectBuilder; import javax.json.JsonValue; import javax.json.JsonValue.ValueType; import com.warptronic.itdm.io.JsonFileManager; import com.warptronic.itdm.jira.AuthType; import com.warptronic.itdm.jira.Request; /** * This is the main class that runs the Jira Issue Exporter * It is here just as an example. I advise you to write your own logic * @author Sebastian Luca * */ public class App { private App() { //class doesn't need initialization } /** * * @param args arguments provided from command line in order: <code>username password auth_type</code> */ public static void main (String[] args) { String baseUrl; String username; String password; AuthType authenticationType; if (args.length < 3) { System.out.println("Too few parameters Please provide the URL to Jira, the username and password"); System.out.println("e.g. java App.java http://jira.domain.com username password [d]"); System.out.println("Where 'd' is an optional number: 1 = Basic Jira Authentication, 2 = Cookie Jira Authentication"); System.exit(-1); } //TODO sanitization of strings/URLs and format validation baseUrl = args[0]; username = args[1]; password = args[2]; int auth = args[3] == null ? 0 : Integer.parseInt(args[3]); switch (auth) { case 1: authenticationType = AuthType.BASIC_AUTH; break; case 2: authenticationType = AuthType.COOKIE_BASED_AUTH; break; default: authenticationType = AuthType.BASIC_AUTH; break; } /** * This is an example showing how to save all Jira issues to file */ //JsonObject jsonObject = new Request(baseUrl, username, password, authenticationType).getJiraAllIssues(); /** * This is an example showing how to save only the needed data from Jira */ JsonObject jsonObject = new Request(baseUrl, username, password, authenticationType).getFilteredJiraIssues(App::jiraMinimalFilter); /** * This is an example of how to write the created JSON object to file */ //TODO name the file based on date-time JsonFileManager.writeJsonToFile(jsonObject, "response"); } private static JsonObject jiraMinimalFilter(JsonObject jsonObject) { JsonArrayBuilder jsonBuilder = Json.createArrayBuilder(); for (JsonValue j : jsonObject.getJsonArray("issues")) { if (!ValueType.OBJECT.equals(j.getValueType())) { //TODO throw exception System.out.println("expected JsonValue was Object, but was " + j.getValueType()); System.exit(-1); } JsonObject json = (JsonObject) j; JsonObjectBuilder jobjBuilder = Json.createObjectBuilder(); JsonObject parentKeyObj = json.getJsonObject("fields").getJsonObject("parent"); String parentKey = parentKeyObj == null ? "" : parentKeyObj.getString("key"); boolean isDone = json.getJsonObject("fields").containsKey("resolutiondate") && !ValueType.NULL.equals(json.getJsonObject("fields").get("resolutiondate").getValueType()); String endDate = isDone ? json.getJsonObject("fields").getString("resolutiondate") : ""; jobjBuilder.add("key", json.getString("key")) .add("parent-key", parentKey) .add("issuetype", json.getJsonObject("fields").getJsonObject("issuetype").getString("name")) .add("status", json.getJsonObject("fields").getJsonObject("status").getString("name")) .add("start-date", json.getJsonObject("fields").getString("created")) .add("end-date", endDate); jsonBuilder.add(jobjBuilder); } return Json.createObjectBuilder().add("total", jsonObject.getInt("total")) .add("issues", jsonBuilder).build(); } }
package de.lessvoid.nifty; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.logging.Logger; import org.newdawn.slick.util.Log; import org.newdawn.slick.util.ResourceLoader; import de.lessvoid.nifty.controls.Controller; import de.lessvoid.nifty.controls.NiftyInputControl; import de.lessvoid.nifty.effects.EffectEventId; import de.lessvoid.nifty.elements.Element; import de.lessvoid.nifty.input.keyboard.KeyboardInputEventCreator; import de.lessvoid.nifty.input.mapping.Default; import de.lessvoid.nifty.input.mouse.MouseInputEvent; import de.lessvoid.nifty.input.mouse.MouseInputEventQueue; import de.lessvoid.nifty.loader.xpp3.Attributes; import de.lessvoid.nifty.loader.xpp3.NiftyLoader; import de.lessvoid.nifty.loader.xpp3.elements.AttributesType; import de.lessvoid.nifty.loader.xpp3.elements.ControlType; import de.lessvoid.nifty.loader.xpp3.elements.PopupType; import de.lessvoid.nifty.loader.xpp3.elements.helper.StyleHandler; import de.lessvoid.nifty.loader.xpp3.processor.helper.TypeContext; import de.lessvoid.nifty.render.NiftyRenderEngine; import de.lessvoid.nifty.render.NiftyRenderEngineImpl; import de.lessvoid.nifty.render.spi.RenderDevice; import de.lessvoid.nifty.screen.NullScreenController; import de.lessvoid.nifty.screen.Screen; import de.lessvoid.nifty.screen.ScreenController; import de.lessvoid.nifty.sound.SoundSystem; import de.lessvoid.nifty.tools.TimeProvider; /** * The main Nifty class. * @author void */ public class Nifty { /** * The logger. */ private Logger log = Logger.getLogger(Nifty.class.getName()); /** * RenderDevice. */ private NiftyRenderEngine renderDevice; /** * SoundSystem. */ private SoundSystem soundSystem; /** * All screens with Id of screen as the key. */ private Map < String, Screen > screens = new Hashtable < String, Screen >(); /** * All popups with Id as the key. */ private Map < String, PopupType > popups = new Hashtable < String, PopupType >(); private Map < String, Element > activePopups = new Hashtable < String, Element >(); /** * The current screen. */ private Screen currentScreen; /** * The current xml file loaded. */ private String currentLoaded; /** * When everything is done exit is true. */ private boolean exit; /** * console for debugging purpose. * @param newRenderDevice RenderDevice * @param options options */ private NiftyDebugConsole console; /** * The TimeProvider to use. */ private TimeProvider timeProvider; /** * store the popup id we need to remove. */ private String removePopupId = null; /** * nifty loader. */ private NiftyLoader loader = new NiftyLoader(); /** * these controls need to be added. */ private List < ControlToAdd > controlsToAdd = new ArrayList < ControlToAdd >(); /** * these elements need to be removed. */ private List < ElementToRemove > elementsToRemove = new ArrayList < ElementToRemove >(); /** * use debug console. */ private boolean useDebugConsole; /** * KeyboardInputEventCreator. */ private KeyboardInputEventCreator inputEventCreator; /** * MouseInputEventQueue. */ private MouseInputEventQueue mouseInputEventQueue; /** * collection of registered ScreenController instances. */ private Collection < ScreenController > registeredScreenControllers = new ArrayList < ScreenController >(); /** * last x position of mouse. */ private int lastMouseX; /** * last y position of mouse. */ private int lastMouseY; /** * Create nifty for the given RenderDevice and TimeProvider. * @param newRenderDevice the RenderDevice * @param newSoundSystem SoundSystem * @param newTimeProvider the TimeProvider */ public Nifty( final NiftyRenderEngine newRenderDevice, final SoundSystem newSoundSystem, final TimeProvider newTimeProvider) { initialize(newRenderDevice, newSoundSystem, newTimeProvider); console = new NiftyDebugConsole(null); // this will cause trouble i'm sure, but i don't care at this point } /** * Create nifty with optional console parameter. * @param newRenderDevice the RenderDevice * @param newSoundSystem SoundSystem * @param newTimeProvider the TimeProvider */ public Nifty( final RenderDevice newRenderDevice, final SoundSystem newSoundSystem, final TimeProvider newTimeProvider) { initialize(new NiftyRenderEngineImpl(newRenderDevice), newSoundSystem, newTimeProvider); console = new NiftyDebugConsole(newRenderDevice); } /** * Initialize this instance. * @param newRenderDevice RenderDevice * @param newSoundSystem SoundSystem * @param newTimeProvider TimeProvider */ private void initialize( final NiftyRenderEngine newRenderDevice, final SoundSystem newSoundSystem, final TimeProvider newTimeProvider) { this.renderDevice = newRenderDevice; this.soundSystem = newSoundSystem; this.timeProvider = newTimeProvider; this.exit = false; this.currentLoaded = null; this.inputEventCreator = new KeyboardInputEventCreator(); this.mouseInputEventQueue = new MouseInputEventQueue(); } /** * Render all stuff in the current Screen. * @param clearScreen TODO * @param mouseX TODO * @param mouseY TODO * @param mouseDown TODO * @return true when nifty has finished processing the screen and false when rendering should continue. */ public boolean render( final boolean clearScreen, final int mouseX, final int mouseY, final boolean mouseDown) { if (currentScreen != null) { mouseInputEventQueue.process(mouseX, mouseY, mouseDown); lastMouseX = mouseX; lastMouseY = mouseY; } return render(clearScreen); } /** * This is a replacement render that does not take a mouse event. * @param clearScreen TODO * @return true when nifty has finished processing the screen and false when rendering should continue. */ public boolean render(final boolean clearScreen) { if (clearScreen) { renderDevice.clear(); } if (currentScreen != null) { MouseInputEvent inputEvent = mouseInputEventQueue.peek(); if (inputEvent != null) { currentScreen.mouseEvent(inputEvent); mouseInputEventQueue.remove(); } currentScreen.renderLayers(renderDevice); if (useDebugConsole) { console.render(this, currentScreen, renderDevice); } } if (exit) { renderDevice.clear(); } if (removePopupId != null) { if (currentScreen != null) { currentScreen.closePopup(activePopups.get(removePopupId)); } removePopupId = null; } if (currentScreen != null) { currentScreen.processAddAndRemoveLayerElements(); } addControls(); removeElements(); return exit; } /** * add controls. */ public void addControls() { if (!controlsToAdd.isEmpty()) { for (ControlToAdd controlToAdd : controlsToAdd) { controlToAdd.createControl(); } controlsToAdd.clear(); } } /** * remove elements. */ private void removeElements() { if (!elementsToRemove.isEmpty()) { for (ElementToRemove elementToRemove : elementsToRemove) { elementToRemove.remove(); } elementsToRemove.clear(); } } /** * Initialize this Nifty instance from the given xml file. * @param filename filename to nifty xml * @param startScreen screen to start exec */ public void fromXml(final String filename, final String startScreen) { prepareScreens(filename); loadFromFile(filename); gotoScreen(startScreen); } /** * Initialize this Nifty instance from the given xml file. * @param filename filename to nifty xml * @param startScreen screen to start exec * @param controllers controllers to use */ public void fromXml( final String filename, final String startScreen, final ScreenController ... controllers) { registerScreenController(controllers); prepareScreens(filename); loadFromFile(filename); gotoScreen(startScreen); } /** * fromXml. * @param fileId fileId * @param input inputStream * @param startScreen screen to start */ public void fromXml(final String fileId, final InputStream input, final String startScreen) { prepareScreens(fileId); loadFromStream(input); gotoScreen(startScreen); } /** * fromXml with ScreenControllers. * @param fileId fileId * @param input inputStream * @param startScreen screen to start * @param controllers controllers to use */ public void fromXml( final String fileId, final InputStream input, final String startScreen, final ScreenController ... controllers) { registerScreenController(controllers); prepareScreens(fileId); loadFromStream(input); gotoScreen(startScreen); } /** * load from the given file. * @param filename filename to load */ void loadFromFile(final String filename) { try { loader.loadXml(ResourceLoader.getResourceAsStream(filename), this, screens, timeProvider); } catch (Exception e) { e.printStackTrace(); } } /** * load from the given file. * @param stream stream to load */ private void loadFromStream(final InputStream stream) { try { loader.loadXml(stream, this, screens, timeProvider); } catch (Exception e) { e.printStackTrace(); } } /** * prepare/reset screens. * @param xmlId xml id */ void prepareScreens(final String xmlId) { screens.clear(); // this.currentScreen = null; this.currentLoaded = xmlId; this.exit = false; } /** * goto screen command. this will send first an endScreen event to the current screen. * @param id the new screen id we should go to. */ public final void gotoScreen(final String id) { if (currentScreen == null) { gotoScreenInternal(id); } else { // end current screen currentScreen.endScreen( new EndNotify() { public final void perform() { gotoScreenInternal(id); } }); } } /** * goto new screen. * @param id the new screen id we should go to. */ private void gotoScreenInternal(final String id) { currentScreen = screens.get(id); if (currentScreen == null) { log.warning("screen [" + id + "] not found"); return; } // start the new screen currentScreen.startScreen(); } /** * Set alternate key for all screen. This could be used to change behavior on all screens. * @param alternateKey the new alternate key to use */ public void setAlternateKey(final String alternateKey) { for (Screen screen : screens.values()) { screen.setAlternateKey(alternateKey); } } /** * exit. */ public void exit() { currentScreen.endScreen( new EndNotify() { public final void perform() { exit = true; } }); } /** * get a specific screen. * @param id the id of the screen to retrieve. * @return the screen */ public Screen getScreen(final String id) { Screen screen = screens.get(id); if (screen == null) { log.warning("screen [" + id + "] not found"); return null; } return screen; } /** * keyboard event. * @param eventKey eventKey * @param eventCharacter the character * @param keyDown key down */ public void keyEvent(final int eventKey, final char eventCharacter, final boolean keyDown) { // System.out.println("key " + eventKey + ", character " + eventCharacter + ", keyDown: " + keyDown); if (currentScreen != null) { currentScreen.keyEvent(inputEventCreator.createEvent(eventKey, eventCharacter, keyDown)); } } /** * Get the SoundSystem. * @return SoundSystem */ public SoundSystem getSoundSystem() { return soundSystem; } /** * Return the RenderDevice. * @return RenderDevice */ public NiftyRenderEngine getRenderDevice() { return renderDevice; } /** * Get current screen. * @return current screen */ public Screen getCurrentScreen() { return currentScreen; } /** * Check if nifty displays the file with the given filename and is at a screen with the given screenId. * @param filename filename * @param screenId screenId * @return true if the given screen is active and false when not */ public boolean isActive(final String filename, final String screenId) { if (currentLoaded != null && currentLoaded.equals(filename)) { if (currentScreen != null && currentScreen.getScreenId().equals(screenId)) { return true; } } return false; } /** * popup. * @param popup popup */ public void registerPopup(final PopupType popup) { popups.put(popup.getAttributes().getId(), popup); } /** * show popup in the given screen. * @param screen screen * @param id id */ public void showPopup(final Screen screen, final String id) { Element popup = activePopups.get(id); if (popup == null) { log.warning("missing popup [" + id + "] o_O"); } else { screen.addPopup(popup); } } private Element createPopupFromType(final PopupType popupType) { NiftyInputControl niftyInputControl = null; Controller controllerInstance = popupType.getControllerInstance(this); if (controllerInstance != null) { niftyInputControl = new NiftyInputControl(controllerInstance, new Default()); } log.info("createPopupFromType: " + controllerInstance + ", " + niftyInputControl); Element popupElement = popupType.createElement( this, null, getLoader().getRegisteredEffects(), getLoader().getRegisteredControls(), getStyleHandler(), timeProvider, niftyInputControl, new NullScreenController()); if (controllerInstance != null) { controllerInstance.bind( this, popupElement, null, null, new Attributes()); } return popupElement; } /** * Get Popup. * @param id get id * @return popup element */ public Element createPopup(final String id) { Element popupElement = createPopupFromType(popups.get(id)); activePopups.put(id, popupElement); return popupElement; } /** * close the given popup on the given screen. * @param id the popup id */ public void closePopup(final String id) { Element popup = activePopups.get(id); if (popup == null) { log.warning("missing popup [" + id + "] o_O"); } else { popup.resetEffects(); popup.startEffect(EffectEventId.onEndScreen, new EndNotify() { public void perform() { removePopupId = id; } }); } } /** * Add a control to this screen and the given parent element. * @param screen screen * @param parent parent element * @param controlName control name to add * @param id id of control * @param style style * @param focusable focusable */ public void addControl( final Screen screen, final Element parent, final String controlName, final String id, final String style, final Boolean focusable, final Attributes attributes) { controlsToAdd.add( new ControlToAdd( screen, parent, controlName, id, style, focusable, attributes)); } /** * ControlToAdd helper class. * @author void */ private class ControlToAdd { /** * screen. */ private Screen screen; /** * parent element. */ private Element parent; /** * control name. */ private String controlName; /** * control id. */ private String controlId; /** * current style. */ private String style; /** * focusable. */ private Boolean focusable; private Attributes attr; public ControlToAdd( final Screen newScreen, final Element newParent, final String newControlName, final String newId, final String newStyle, final Boolean newFocusable, final Attributes newAttributes) { this.screen = newScreen; this.parent = newParent; this.controlName = newControlName; this.controlId = newId; this.style = newStyle; this.focusable = newFocusable; this.attr = newAttributes; if (attr == null) { attr = new Attributes(); } } /** * create the control. */ public void createControl() { TypeContext typeContext = new TypeContext( loader.getStyleHandler(), Nifty.this, loader.getRegisteredEffects(), loader.getRegisteredControls(), timeProvider ); ControlType controlType = new ControlType(typeContext, controlName); attr.overwriteAttribute("id", controlId); if (style != null) { attr.overwriteAttribute("style", style); } AttributesType attributeType = new AttributesType(attr); controlType.setAttributes(attributeType); Element newControl = controlType.createElement( parent, screen, null, screen.getScreenController()); if (focusable != null) { newControl.setFocusable(focusable); } screen.layoutLayers(); newControl.startEffect(EffectEventId.onStartScreen, null); newControl.onStartScreen(screen); } } /** * ElementToRemove helper. * @author void */ private class ElementToRemove { /** * screen. */ private Screen screen; /** * element. */ private Element element; /** * create it. * @param newScreen screen * @param newElement element */ public ElementToRemove(final Screen newScreen, final Element newElement) { this.screen = newScreen; this.element = newElement; } /** * do the actual remove. */ public void remove() { element.remove(); element.removeFromParent(); screen.layoutLayers(); } } /** * Remove the given element from the given screen. * @param screen screen * @param element element to remove */ public void removeElement(final Screen screen, final Element element) { elementsToRemove.add(new ElementToRemove(screen, element)); } /** * toggle debug console on/off. * @param outputEffects outputEffects */ public void toggleDebugConsole(final boolean outputEffects) { useDebugConsole = !useDebugConsole; console.setOutputElements(outputEffects); } /** * @return the mouseInputEventQueue */ public MouseInputEventQueue getMouseInputEventQueue() { return mouseInputEventQueue; } /** * Register a ScreenController instance. * @param controllers ScreenController */ public void registerScreenController(final ScreenController ... controllers) { for (ScreenController c : controllers) { registeredScreenControllers.add(c); } } /** * find a ScreenController instance that matches the given controllerClass name. * @param controllerClass controller class name * @return ScreenController instance */ public ScreenController findScreenController(final String controllerClass) { for (ScreenController controller : registeredScreenControllers) { if (controller.getClass().getName().equals(controllerClass)) { return controller; } } return null; } /** * get last mouse x. * @return mouse x */ public int getLastMouseX() { return lastMouseX; } /** * get last mouse y. * @return mouse x */ public int getLastMouseY() { return lastMouseY; } /** * Get StyleHandler. * @return StyleHandler */ public StyleHandler getStyleHandler() { return loader.getStyleHandler(); } /** * Get Loader. * @return NiftyLoader */ public NiftyLoader getLoader() { return loader; } public TimeProvider getTimeProvider() { return timeProvider; } }
package drupalfit; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.squareup.okhttp.OkHttpClient; import retrofit.Callback; import retrofit.RestAdapter; import retrofit.RetrofitError; import retrofit.client.Client; import retrofit.client.OkClient; import retrofit.client.Response; import retrofit.http.Field; import retrofit.http.FormUrlEncoded; import retrofit.http.GET; import retrofit.http.Multipart; import retrofit.http.POST; import retrofit.http.Part; import retrofit.http.Path; import retrofit.http.Streaming; import retrofit.mime.TypedFile; import retrofit.RequestInterceptor; import proguard.annotation.Keep; import proguard.annotation.KeepClassMembers; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.security.GeneralSecurityException; import java.security.cert.X509Certificate; import java.io.IOException; import java.security.SecureRandom; import android.text.TextUtils; import drupalfit.DrupalOAuth2.Credential; public class DrupalManager implements DrupalService { private static DrupalManager sInstance = new DrupalManager(); private DrupalService mService; private String endpoint; private String accessToken; private String cookie; private String mXCsrfToken; //X-CSRF-Token private String username; // TODO private String email; // TODO private String password; // TODO protected SimpleRequestInterceptor mRequestInterceptor; private DrupalOAuth2Manager oauth; public DrupalManager setOAuth(DrupalOAuth2Manager oauth) { this.oauth = oauth; return sInstance; } public DrupalOAuth2Manager getOAuth() { return oauth; } public DrupalManager setEndpoint(String endpoint) { this.endpoint = endpoint; return sInstance; } public DrupalManager build() { getService(endpoint); return sInstance; } private DrupalManager() { } @Override public void userRegister( String username, String email, String password, Callback<User> callback) { /* this.username = username; this.password = password; this.email = email; */ getService().userRegister(username, email, password, callback); } public void userRegister( String email, String password, Callback<User> callback ) { userRegister(email, email, password, callback); } @Override public void userLogin( String username, String password, Callback<Login> callback ) { /* this.username = username; this.password = password; */ getService().userLogin(username, password, callback); } @Override public void userProfile( String accessToken, final Callback<User> callback ) { setAccessToken(accessToken); getService().userProfile(accessToken, callback); } @Override public void userProfile( final Callback<User> callback ) { if (cookie == null && accessToken == null) { if (oauth != null) { Log8.d(); oauth.getAccessToken(new Callback<Credential>() { @Override public void success(Credential credential, Response response) { setAccessToken(credential.access_token); Log8.d(accessToken); getService().userProfile(callback); } @Override public void failure(RetrofitError error) { Log8.d(); callback.failure(error); } }); } } else { Log8.d(); getService().userProfile(callback); } } @Override public void userLogout( Callback<Logout> callback ) { getService().userLogout(callback); } public static DrupalManager get() { return sInstance; } public static DrupalService getService() { return get().getService(null); } public String getAccessToken() { if (!TextUtils.isEmpty(accessToken)) { return accessToken; } if (oauth != null) { Credential c = oauth.getAccessToken(); if (c != null) { setAccessToken(c.access_token); } } return accessToken; } public String getAccessToken(String username, String password) { return getAccessToken(username, password, null); } public String getAccessToken(String username, String password, String authTokenType) { Credential c = oauth.getAccessToken(username, password); if (c != null) { setAccessToken(c.access_token); } return accessToken; } public DrupalManager setAccessToken(String accessToken) { this.accessToken = accessToken; if (mRequestInterceptor != null) { mRequestInterceptor.accessToken = accessToken; } return sInstance; } public DrupalService getService(String endpoint) { if (endpoint == null) return mService; if (mService == null) { this.endpoint = endpoint; OkHttpClient okHttpClient = new OkHttpClient(); okHttpClient.setSslSocketFactory(getTrustedFactory()); okHttpClient.setHostnameVerifier(getTrustedVerifier()); Client client = new OkClient(okHttpClient); if (mRequestInterceptor == null) { mRequestInterceptor = new SimpleRequestInterceptor(); } mRequestInterceptor.cookie = cookie; mRequestInterceptor.accessToken = accessToken; mRequestInterceptor.xcsrfToken = mXCsrfToken; mService = new RestAdapter.Builder() .setEndpoint(endpoint) .setRequestInterceptor(mRequestInterceptor) .setErrorHandler(new ErrorHandler()) .setClient(client) .setConverter(new retrofit.converter.JacksonConverter()) .build().create(DrupalService.class); } return mService; } public String getCookie() { return cookie; } public DrupalManager setCookie(String cookie) { this.cookie = cookie; if (mRequestInterceptor != null) { mRequestInterceptor.cookie = cookie; } return sInstance; } public class SimpleRequestInterceptor implements RequestInterceptor { public String cookie; public String accessToken; public String xcsrfToken; @Override public void intercept(RequestFacade request) { if (!TextUtils.isEmpty(cookie)) { request.addHeader("Cookie", cookie); } if (!TextUtils.isEmpty(mXCsrfToken)) { request.addHeader("X-CSRF-Token", xcsrfToken); } if (!TextUtils.isEmpty(accessToken)) { Log8.d(); //request.addQueryParam("access_token", accessToken); request.addEncodedQueryParam("access_token", accessToken); } } } public DrupalManager setXCsrfToken(String xcsrfToken) { mXCsrfToken = xcsrfToken; if (mRequestInterceptor != null) { mRequestInterceptor.xcsrfToken = xcsrfToken; } return sInstance; } @JsonIgnoreProperties(ignoreUnknown = true) public static class ErrorHandler implements retrofit.ErrorHandler { public ErrorHandler() {} @Override public Throwable handleError(RetrofitError cause) { cause.printStackTrace(); return cause; } } private static SSLSocketFactory sTrustedFactory; public static SSLSocketFactory getTrustedFactory() { if (sTrustedFactory == null) { final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } public void checkClientTrusted(X509Certificate[] chain, String authType) { // Intentionally left blank } public void checkServerTrusted(X509Certificate[] chain, String authType) { // Intentionally left blank } } }; try { SSLContext context = SSLContext.getInstance("TLS"); context.init(null, trustAllCerts, new SecureRandom()); sTrustedFactory = context.getSocketFactory(); } catch (GeneralSecurityException e) { IOException ioException = new IOException( "Security exception configuring SSL context"); ioException.initCause(e); e.printStackTrace(); } } return sTrustedFactory; } private static HostnameVerifier sTrustedVerifier; public static HostnameVerifier getTrustedVerifier() { if (sTrustedVerifier == null) { sTrustedVerifier = new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }; } return sTrustedVerifier; } /** {@inheritDoc} */ @Override public void systemConnect( Callback<User> callback ) { getService().systemConnect(callback); } /** {@inheritDoc} */ @Override public void getNode( int nid, Callback<Node> callback ) { getService().getNode(nid, callback); } public void getNode( String nid, Callback<Node> callback ) { int i; try { i = Integer.valueOf(nid); } catch (Exception e) { callback.failure(RetrofitError.unexpectedError("failure", e)); return; } getNode(i, callback); } /** {@inheritDoc} */ @Override public void getTaxonomyVocabulary( int vid, int parent, Callback<Vocabulary> callback ) { getService().getTaxonomyVocabulary(vid, parent, callback); } /** {@inheritDoc} */ @Override public void getTaxonomyVocabulary( int vid, int parent, int maxdepth, Callback<Vocabulary> callback ) { getService().getTaxonomyVocabulary(vid, parent, maxdepth, callback); } /** {@inheritDoc} */ @Override public void getViews( String name, int limit, String args, int displayId, Callback<Views> callback ) { getService().getViews(name, limit, args, displayId, callback); } /** {@inheritDoc} */ @Override public void token( String username, String password, Callback<Login> callback ) { getService().token(username, password, callback); } public void token( Callback<Login> callback ) { token(username, password, callback); } }
package gui.root; import gui.headerarea.DetailView; import gui.headerarea.ToolView; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar; import javafx.scene.control.MenuItem; import javafx.scene.effect.BlurType; import javafx.scene.effect.DropShadow; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import lombok.Getter; /** * Class that represents the whole of top-level elements in the gui. * In other words, the file-edit-view-help menus and any buttons below that. */ public class RootHeaderArea extends VBox { private RootPane rootPane; private VBox headerBar; @Getter private DetailView detailView; @Getter private ToolView toolView; private DropShadow dropShadow; /** * RootHeaderArea Constructor. * @param rootPane the root pane this pane itself is located in. */ public RootHeaderArea(RootPane rootPane) { this.rootPane = rootPane; // dropShadow = new DropShadow(BlurType.GAUSSIAN, Color.rgb(0,0,0,0.2), 20, 0.1, 0, 5); // this.setEffect(dropShadow); getChildren().add(initMenus()); getChildren().add(initHeaderBar()); this.setPrefHeight(50); } /** * Init the header bar of the RootHeaderArea. * @return - the hbox displaying the headerbar */ private VBox initHeaderBar() { headerBar = new VBox(); headerBar.getChildren().add(initButtons()); detailView = new DetailView(); headerBar.getChildren().add(detailView); return headerBar; } /** * Initializes top menu (file, edit, etc). * @return MenuBar containing menus. */ private MenuBar initMenus() { Menu editMenu = new Menu("Edit"); MenuItem editProjectItem = new MenuItem("Project"); editProjectItem.setOnAction(e -> { rootPane.getControllerManager().getProjectController().editProject(); }); editMenu.getItems().add(editProjectItem); Menu helpMenu = new Menu("Help"); MenuItem helpWebsiteItem = new MenuItem("Website"); helpMenu.setOnAction(e -> { try { java.awt.Desktop.getDesktop().browse(java.net.URI.create("http://gotofail.net")); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } }); helpMenu.getItems().add(helpWebsiteItem); Menu fileMenu = initFileMenu(); Menu viewMenu = new Menu("View"); MenuBar topMenuBar = new MenuBar(); topMenuBar.setUseSystemMenuBar(true); topMenuBar.getMenus().addAll(fileMenu, editMenu, viewMenu, helpMenu); return topMenuBar; } /** * Initialize the file menu. * @return the initialized file Menu */ private Menu initFileMenu() { MenuItem newItem = new MenuItem("New"); newItem.setOnAction(e -> { rootPane.getControllerManager().getProjectController().newProject(); }); MenuItem saveItem = new MenuItem("Save"); saveItem.setOnAction(e -> { rootPane.getControllerManager().getProjectController().save(); }); MenuItem saveAsItem = new MenuItem("Save as"); saveAsItem.setOnAction(e -> { rootPane.getControllerManager().getProjectController().saveAs(); }); MenuItem loadItem = new MenuItem("Load"); loadItem.setOnAction(e -> { rootPane.getControllerManager().getProjectController().load(); }); MenuItem quit = new MenuItem("Quit"); quit.setOnAction(e -> { if (rootPane.getControllerManager().getScriptingProject() != null && rootPane.getControllerManager() .getScriptingProject().isChanged()) { rootPane.getControllerManager().initSaveModal(); } else { rootPane.getPrimaryStage().close(); } }); Menu fileMenu = new Menu("File"); fileMenu.getItems().addAll(newItem, saveItem, saveAsItem, loadItem, quit); return fileMenu; } /** * Initializes top button area. * @return HBox box containing buttons. */ private HBox initButtons() { this.toolView = new ToolView(); return this.toolView; } }
package hudson.ivy; import static hudson.Util.fixEmpty; import static hudson.model.ItemGroupMixIn.loadChildren; import hudson.CopyOnWrite; import hudson.Extension; import hudson.FilePath; import hudson.Util; import hudson.ivy.builder.AntIvyBuilderType; import hudson.ivy.builder.IvyBuilderType; import hudson.ivy.builder.NAntIvyBuilderType; import hudson.model.AbstractProject; import hudson.model.Action; import hudson.model.BuildableItemWithBuildWrappers; import hudson.model.DependencyGraph; import hudson.model.Descriptor; import hudson.model.Executor; import hudson.model.Item; import hudson.model.ItemGroup; import hudson.model.Job; import hudson.model.PersistentDescriptor; import hudson.model.Queue; import hudson.model.ResourceActivity; import hudson.model.SCMedItem; import hudson.model.Saveable; import hudson.model.TopLevelItem; import hudson.model.Descriptor.FormException; import hudson.model.Queue.Task; import hudson.model.queue.CauseOfBlockage; import hudson.search.CollectionSearchIndex; import hudson.search.SearchIndexBuilder; import hudson.tasks.BuildStep; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.BuildWrapper; import hudson.tasks.BuildWrappers; import hudson.tasks.Publisher; import hudson.tasks.Ant.AntInstallation; import hudson.tasks.test.AbstractTestResultAction; import hudson.util.CopyOnWriteMap; import hudson.util.DescribableList; import hudson.util.FormValidation; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import javax.servlet.ServletException; import hudson.util.ListBoxModel; import jenkins.model.Jenkins; import net.sf.json.JSONObject; import org.jenkinsci.lib.configprovider.model.Config; import org.jenkinsci.plugins.configfiles.ConfigFiles; import org.kohsuke.stapler.AncestorInPath; import org.kohsuke.stapler.DataBoundSetter; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import org.kohsuke.stapler.export.Exported; /** * Group of {@link IvyModule}s. * <p> * This corresponds to the group of Ivy module descriptors that constitute a single * branch of projects. * * @author Timothy Bingaman */ public final class IvyModuleSet extends AbstractIvyProject<IvyModuleSet, IvyModuleSetBuild> implements TopLevelItem, ItemGroup<IvyModule>, SCMedItem, Saveable, BuildableItemWithBuildWrappers { /** * All {@link IvyModule}s, keyed by their {@link IvyModule#getModuleName()} module name}s. */ transient /*final*/ Map<ModuleName, IvyModule> modules = new CopyOnWriteMap.Tree<ModuleName, IvyModule>(); /** * Topologically sorted list of modules. This only includes live modules, * since archived ones usually don't have consistent history. */ @CopyOnWrite transient List<IvyModule> sortedActiveModules; private String ivyFilePattern; private String ivyFileExcludesPattern; private String targets; private String ivyBranch; private String relativePathToDescriptorFromModuleRoot; private String ivySettingsFile; private String settings; private String ivySettingsPropertyFiles; private IvyBuilderType ivyBuilderType; /** * Identifies {@link AntInstallation} to be used. */ private String antName; /** * ANT_OPTS if not null. */ private String antOpts; /** * Optional build script path relative to the workspace. * Used for the Ant '-f' option. */ private String buildFile; /** * Optional properties to be passed to Ant. Follows {@link Properties} syntax. */ private String antProperties; /** * If true, the build will be aggregator style, meaning all the modules are * executed in a single Ant invocation, as in CLI. False otherwise, meaning * each module is built separately and possibly in parallel. */ private boolean aggregatorStyleBuild = true; /** * If true, and if aggregatorStyleBuild is false, the build will check the * changeset before building, and if there are changes, only those modules * which have changes or those modules which failed or were unstable in the * previous build will be built directly. Any modules depending on the * directly built modules will also be built. */ private boolean incrementalBuild = false; /** * The name of the property used to pass the names of the changed modules * to the build when both incremental build and aggregated build options are * selected. */ private String changedModulesProperty; /** * If true, do not automatically schedule a build when one of the project * dependencies is built. */ private boolean ignoreUpstreamChanges = false; /** * If true, allow this project to trigger downstream projects based on * Ivy dependencies. */ private Boolean allowedToTriggerDownstream = true; /** * If true properties this build will use parameters specified on the triggering build */ private boolean useUpstreamParameters = false; public boolean isUseUpstreamParameters() { return useUpstreamParameters; } public void setUseUpstreamParameters(boolean useUpstreamParameters) { this.useUpstreamParameters = useUpstreamParameters; } /** * If true, do not archive artifacts to the master. */ private boolean archivingDisabled = false; /** * List of active {@link Publisher}s configured for this project. */ private DescribableList<Publisher, Descriptor<Publisher>> publishers = new DescribableList<Publisher, Descriptor<Publisher>>(this); /** * List of active {@link BuildWrapper}s configured for this project. */ private DescribableList<BuildWrapper, Descriptor<BuildWrapper>> buildWrappers = new DescribableList<BuildWrapper, Descriptor<BuildWrapper>>(this); public IvyModuleSet(String name) { this(Jenkins.getInstance(), name); } public IvyModuleSet(ItemGroup parent, String name) { super(parent, name); } public String getUrlChildPrefix() { // seemingly redundant "./" is used to make sure that ':' is not interpreted as the scheme identifier return "."; } public Collection<IvyModule> getItems() { return modules.values(); } @Exported public Collection<IvyModule> getModules() { return getItems(); } public IvyModule getItem(String name) { try { return modules.get(ModuleName.fromString(name)); } catch (IllegalArgumentException iae) { return null; } } public IvyModule getModule(String name) { return getItem(name); } public String getSettings() { return settings; } @Override // to make this accessible from IvyModuleSetBuild protected void updateTransientActions() { super.updateTransientActions(); } @Override protected List<Action> createTransientActions() { List<Action> r = super.createTransientActions(); for (IvyModule module : modules.values()) { module.updateTransientActions(); } if (publishers != null) { // this method can be loaded from within the onLoad method, where this might be null for (BuildStep step : publishers) { r.addAll(step.getProjectActions(this)); } } if (buildWrappers != null) { for (BuildWrapper step : buildWrappers) { r.addAll(step.getProjectActions(this)); } } return r; } @Override protected void addTransientActionsFromBuild(IvyModuleSetBuild build, List<Action> collection, Set<Class> added) { if (build == null) { return; } for (Action a : build.getActions()) { if (a instanceof IvyAggregatedReport) { if (added.add(a.getClass())) { collection.add(((IvyAggregatedReport) a).getProjectAction(this)); } } } List<IvyReporter> list = build.projectActionReporters; if (list == null) { return; } for (IvyReporter step : list) { if (!added.add(step.getClass())) { continue; // already added } Action a = step.getAggregatedProjectAction(this); if (a != null) { collection.add(a); } } } /** * Called by {@link IvyModule#doDoDelete(StaplerRequest, StaplerResponse)}. * Real deletion is done by the caller, and this method only adjusts the * data structure the parent maintains. */ /*package*/ void onModuleDeleted(IvyModule module) { modules.remove(module.getModuleName()); } /** * Returns true if there's any disabled module. */ public boolean hasDisabledModule() { for (IvyModule m : modules.values()) { if (m.isDisabled()) { return true; } } return false; } /** * Possibly empty list of all disabled modules (if disabled==true) * or all enabled modules (if disabled==false) */ public List<IvyModule> getDisabledModules(boolean disabled) { if (!disabled && sortedActiveModules != null) { return sortedActiveModules; } List<IvyModule> r = new ArrayList<IvyModule>(); for (IvyModule m : modules.values()) { if (m.isDisabled() == disabled) { r.add(m); } } return r; } public boolean isIncrementalBuild() { return incrementalBuild; } public String getChangedModulesProperty() { return changedModulesProperty; } public boolean isAggregatorStyleBuild() { return aggregatorStyleBuild; } public boolean ignoreUpstreamChanges() { return ignoreUpstreamChanges; } public boolean isAllowedToTriggerDownstream() { return allowedToTriggerDownstream; } public void setAllowedToTriggerDownstream(boolean allowedToTriggerDownstream) { this.allowedToTriggerDownstream = allowedToTriggerDownstream; } public boolean isArchivingDisabled() { return archivingDisabled; } public void setIncrementalBuild(boolean incrementalBuild) { this.incrementalBuild = incrementalBuild; } public String getIvyFilePattern() { return ivyFilePattern; } public void setIvyFilePattern(String ivyFilePattern) { this.ivyFilePattern = ivyFilePattern; } public String getIvyFileExcludesPattern() { return ivyFileExcludesPattern; } public void setIvyFileExcludesPattern(String ivyFileExcludesPattern) { this.ivyFileExcludesPattern = ivyFileExcludesPattern; } public String getIvySettingsFile() { return ivySettingsFile; } public void setIvySettingsFile(String ivySettingsFile) { this.ivySettingsFile = ivySettingsFile; } public String getIvySettingsPropertyFiles() { return ivySettingsPropertyFiles; } public void setIvySettingsPropertyFiles(String ivySettingsPropertyFiles) { this.ivySettingsPropertyFiles = ivySettingsPropertyFiles; } public String getIvyBranch() { return ivyBranch; } public void setIvyBranch(String ivyBranch) { this.ivyBranch = ivyBranch; } public IvyBuilderType getIvyBuilderType() { return ivyBuilderType; } public void setAggregatorStyleBuild(boolean aggregatorStyleBuild) { this.aggregatorStyleBuild = aggregatorStyleBuild; } public void setIgnoreUpstreamChanges(boolean ignoreUpstreamChanges) { this.ignoreUpstreamChanges = ignoreUpstreamChanges; } public void setIsArchivingDisabled(boolean archivingDisabled) { this.archivingDisabled = archivingDisabled; } /** * List of active {@link Publisher}s that should be applied to all module builds. */ public DescribableList<Publisher, Descriptor<Publisher>> getModulePublishers() { return aggregatorStyleBuild ? new DescribableList<Publisher, Descriptor<Publisher>>(this) : publishers; } /** * List of active {@link Publisher}s. Can be empty but never null. */ public DescribableList<Publisher, Descriptor<Publisher>> getPublishers() { return publishers; } @Override public DescribableList<Publisher, Descriptor<Publisher>> getPublishersList() { return publishers; } public DescribableList<BuildWrapper, Descriptor<BuildWrapper>> getBuildWrappersList() { return buildWrappers; } /** * List of active {@link BuildWrapper}s. Can be empty but never null. * * @deprecated as of 1.335 * Use {@link #getBuildWrappersList()} to be consistent with other subtypes of {@link AbstractProject}. */ @Deprecated public DescribableList<BuildWrapper, Descriptor<BuildWrapper>> getBuildWrappers() { return buildWrappers; } @Override public Object getDynamic(String token, StaplerRequest req, StaplerResponse rsp) { if (ModuleName.isValid(token)) { return getModule(token); } return super.getDynamic(token, req, rsp); } public File getRootDirFor(IvyModule child) { return new File(getModulesDir(), child.getModuleName().toFileSystemName()); } public void onRenamed(IvyModule item, String oldName, String newName) throws IOException { throw new UnsupportedOperationException(); } public void onDeleted(IvyModule item) throws IOException { // noop } @Override public Collection<Job> getAllJobs() { Set<Job> jobs = new HashSet<Job>(getItems()); jobs.add(this); return jobs; } @Override protected Class<IvyModuleSetBuild> getBuildClass() { return IvyModuleSetBuild.class; } @Override protected SearchIndexBuilder makeSearchIndex() { return super.makeSearchIndex() .add(new CollectionSearchIndex<IvyModule>() {// for computers @Override protected IvyModule get(String key) { for (IvyModule m : modules.values()) { if (m.getDisplayName().equals(key)) { return m; } } return null; } @Override protected Collection<IvyModule> all() { return modules.values(); } @Override protected String getName(IvyModule o) { return o.getName(); } }); } @Override public boolean isFingerprintConfigured() { return true; } @Override public synchronized void save() throws IOException { super.save(); if (!isAggregatorStyleBuild()) { for (IvyModule module : getModules()) { module.save(); } } } @Override public void onLoad(ItemGroup<? extends Item> parent, String name) throws IOException { modules = Collections.emptyMap(); // needed during load super.onLoad(parent, name); modules = loadChildren(this, getModulesDir(), module -> module.getModuleName()); if (publishers == null) { publishers = new DescribableList<Publisher, Descriptor<Publisher>>(this); } publishers.setOwner(this); if (buildWrappers == null) { buildWrappers = new DescribableList<BuildWrapper, Descriptor<BuildWrapper>>(this); buildWrappers.setOwner(this); } updateTransientActions(); } private File getModulesDir() { return new File(getRootDir(), "modules"); } /** * To make it easy to grasp relationship among modules * and the module set, we'll align the build numbers of * all the modules. * <p> * This method is invoked from {@link Executor#run()}, * and because of the mutual exclusion among {@link IvyModuleSetBuild} * and {@link IvyBuild}, we can safely touch all the modules. */ @Override public synchronized int assignBuildNumber() throws IOException { // determine the next value updateNextBuildNumber(); return super.assignBuildNumber(); } @Override public void logRotate() throws IOException, InterruptedException { super.logRotate(); // perform the log rotation of modules for (IvyModule m : modules.values()) { m.logRotate(); } } /** * The next build of {@link IvyModuleSet} must have * the build number newer than any of the current module build. */ /*package*/ void updateNextBuildNumber() throws IOException { int next = this.nextBuildNumber; for (IvyModule m : modules.values()) { next = Math.max(next, m.getNextBuildNumber()); } if (this.nextBuildNumber != next) { this.nextBuildNumber = next; this.saveNextBuildNumber(); } } @Override protected void buildDependencyGraph(DependencyGraph graph) { publishers.buildDependencyGraph(this, graph); buildWrappers.buildDependencyGraph(this, graph); } @Override protected Set<ResourceActivity> getResourceActivities() { final Set<ResourceActivity> activities = new HashSet<ResourceActivity>(); activities.addAll(super.getResourceActivities()); activities.addAll(Util.filter(publishers, ResourceActivity.class)); activities.addAll(Util.filter(buildWrappers, ResourceActivity.class)); return activities; } /** * Because one of our own modules is currently building. */ public static class BecauseOfModuleBuildInProgress extends CauseOfBlockage { public final IvyModule module; public BecauseOfModuleBuildInProgress(IvyModule module) { this.module = module; } public String getShortDescription() { return Messages.IvyModuleSet_ModuleBuildInProgress(module.getName()); } } @Override public CauseOfBlockage getCauseOfBlockage() { CauseOfBlockage cob = super.getCauseOfBlockage(); if (cob != null) { return cob; } for (IvyModule module : modules.values()) { if (module.isBuilding() || module.isInQueue()) { return new BecauseOfModuleBuildInProgress(module); } } return null; } public AbstractProject<?, ?> asProject() { return this; } public String getRelativePathToDescriptorFromModuleRoot() { return relativePathToDescriptorFromModuleRoot; } public void setRelativePathToDescriptorFromModuleRoot(String relativePathToDescriptorFromModuleRoot) { this.relativePathToDescriptorFromModuleRoot = relativePathToDescriptorFromModuleRoot; } /** * Returns the {@link IvyModule}s that are in the queue. */ public List<Queue.Item> getQueueItems() { List<Queue.Item> r = new ArrayList<hudson.model.Queue.Item>(); for (Queue.Item item : Jenkins.getInstance().getQueue().getItems()) { Task t = item.task; if ((t instanceof IvyModule && ((IvyModule) t).getParent() == this) || t == this) { r.add(item); } } return r; } // Web methods @Override protected void submit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException { super.submit(req, rsp); JSONObject json = req.getSubmittedForm(); ignoreUpstreamChanges = !json.has("triggerByDependency"); allowedToTriggerDownstream = json.has("allowedToTriggerDownstream"); useUpstreamParameters = json.has("useUpstreamParameters"); ivyFilePattern = Util.fixEmptyAndTrim(json.getString("ivyFilePattern")); ivyFileExcludesPattern = Util.fixEmptyAndTrim(json.getString("ivyFileExcludesPattern")); ivySettingsFile = Util.fixEmptyAndTrim(json.getString("ivySettingsFile")); settings = Util.fixEmptyAndTrim(json.getString("settings")); ivySettingsPropertyFiles = Util.fixEmptyAndTrim(json.getString("ivySettingsPropertyFiles")); ivyBranch = Util.fixEmptyAndTrim(json.getString("ivyBranch")); relativePathToDescriptorFromModuleRoot = Util.fixEmptyAndTrim(json.getString("relativePathToDescriptorFromModuleRoot")); JSONObject ivyBuilderTypeJson = json.getJSONObject("ivyBuilderType"); try { ivyBuilderType = (IvyBuilderType) req.bindJSON(Class.forName(ivyBuilderTypeJson.getString("stapler-class")), ivyBuilderTypeJson); } catch (ClassNotFoundException e) { throw new FormException("Error creating specified builder type.", e, "ivyBuilderType"); } aggregatorStyleBuild = !req.hasParameter("perModuleBuild"); incrementalBuild = req.hasParameter("incrementalBuild"); if (incrementalBuild) changedModulesProperty = Util.fixEmptyAndTrim(json.getJSONObject("incrementalBuild").getString("changedModulesProperty")); publishers.rebuild(req, json, BuildStepDescriptor.filter(Publisher.all(), this.getClass())); buildWrappers.rebuild(req, json, BuildWrappers.getFor(this)); if (!isAggregatorStyleBuild()) { for (IvyModule module : getModules()) { module.getBuildWrappersList().rebuild(req, json, BuildWrappers.getFor(module)); } } } public Class<? extends AbstractProject> getModuleClass() { return IvyModule.class; } public AbstractTestResultAction<?> getTestResultAction() { IvyModuleSetBuild b = getLastBuild(); return b != null ? b.getAction(AbstractTestResultAction.class) : null; } /** * Delete all disabled modules. */ public void doDoDeleteAllDisabledModules(StaplerResponse rsp) throws IOException, InterruptedException { checkPermission(DELETE); for (IvyModule m : getDisabledModules(true)) { m.delete(); } rsp.sendRedirect2("."); } /** * Check the location of the ivy descriptor file, alternate settings file, etc - any file. */ public FormValidation doCheckFileInWorkspace(@QueryParameter String value) throws IOException, ServletException { IvyModuleSetBuild lb = getLastBuild(); if (lb != null) { FilePath ws = lb.getModuleRoot(); if (ws != null) { return ws.validateRelativePath(value, true, true); } } return FormValidation.ok(); } /** * Check that the provided file exists, just in case. */ public FormValidation doCheckIvySettingsFile(@QueryParameter String value) throws IOException, ServletException { String v = fixEmpty(value); if ((v == null) || (v.length() == 0)) { // Null values are allowed. return FormValidation.ok(); } IvyModuleSetBuild lb = getLastBuild(); if (lb != null) { FilePath ws = lb.getWorkspace(); if (ws != null) { if ((v.startsWith("/")) || (v.startsWith("\\")) || (v.matches("^\\w\\:\\\\.*"))) { return validateAbsolutePath(ws, v); } else { return ws.validateRelativePath(v, true, true); } } } return FormValidation.ok(); } private FormValidation validateAbsolutePath(FilePath ws, String path) throws IOException { try { if (ws.child(path).exists()) { return FormValidation.ok(); } } catch (InterruptedException ignore) { } return FormValidation.error("Error reading ivy settings file: " + path); } @SuppressWarnings("unchecked") public ArrayList<Descriptor<IvyBuilderType>> getBuilderTypeDescriptors() { ArrayList<Descriptor<IvyBuilderType>> buildTypeDescriptors = new ArrayList<Descriptor<IvyBuilderType>>(); buildTypeDescriptors.add(Jenkins.getInstance().getDescriptor(AntIvyBuilderType.class)); if (Jenkins.getInstance().getPlugin("nant") != null) { buildTypeDescriptors.add(Jenkins.getInstance().getDescriptor(NAntIvyBuilderType.class)); } return buildTypeDescriptors; } public DescriptorImpl getDescriptor() { return DESCRIPTOR; } @Extension public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl(); public static final class DescriptorImpl extends AbstractProjectDescriptor implements PersistentDescriptor { /** * Globally-defined ANT_OPTS. */ private String globalAntOpts; public String getGlobalAntOpts() { return globalAntOpts; } @DataBoundSetter public void setGlobalAntOpts(String globalAntOpts) { this.globalAntOpts = Util.fixEmptyAndTrim(globalAntOpts); save(); } public ListBoxModel doFillSettingsItems(@AncestorInPath ItemGroup context) { List<Config> configsInContext = ConfigFiles.getConfigsInContext(context, null); ListBoxModel lb = new ListBoxModel(); lb.add("please select", ""); for (Config config : configsInContext) { lb.add(config.name, config.id); } return lb; } @Override public String getDisplayName() { return Messages.IvyModuleSet_DisplayName(); } public TopLevelItem newInstance(ItemGroup parent, String name) { return new IvyModuleSet(parent, name); } @Override public boolean configure(StaplerRequest req, JSONObject json) { req.bindJSON(this, json); save(); return true; } } protected Object readResolve() { if (ivyBuilderType == null) { // Convert builder settings to new format ivyBuilderType = new AntIvyBuilderType(antName, buildFile, targets, antProperties, antOpts); // Wipe out old builder settings to avoid confusion antName = null; buildFile = null; targets = null; antProperties = null; antOpts = null; } if (allowedToTriggerDownstream == null) { allowedToTriggerDownstream = true; } return this; } }
package hudson.remoting; import hudson.remoting.ExportTable.ExportList; import hudson.remoting.PipeWindow.Key; import hudson.remoting.PipeWindow.Real; import hudson.remoting.forward.ListeningPort; import hudson.remoting.forward.ForwarderFactory; import hudson.remoting.forward.PortForwarder; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.lang.ref.WeakReference; import java.util.Collections; import java.util.Hashtable; import java.util.Map; import java.util.Vector; import java.util.WeakHashMap; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; import java.util.logging.Logger; import java.net.URL; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; /** * Represents a communication channel to the remote peer. * * <p> * A {@link Channel} is a mechanism for two JVMs to communicate over * bi-directional {@link InputStream}/{@link OutputStream} pair. * {@link Channel} represents an endpoint of the stream, and thus * two {@link Channel}s are always used in a pair. * * <p> * Communication is established as soon as two {@link Channel} instances * are created at the end fo the stream pair * until the stream is terminated via {@link #close()}. * * <p> * The basic unit of remoting is an executable {@link Callable} object. * An application can create a {@link Callable} object, and execute it remotely * by using the {@link #call(Callable)} method or {@link #callAsync(Callable)} method. * * <p> * In this sense, {@link Channel} is a mechanism to delegate/offload computation * to other JVMs and somewhat like an agent system. This is bit different from * remoting technologies like CORBA or web services, where the server exposes a * certain functionality that clients invoke. * * <p> * {@link Callable} object, as well as the return value / exceptions, * are transported by using Java serialization. All the necessary class files * are also shipped over {@link Channel} on-demand, so there's no need to * pre-deploy such classes on both JVMs. * * * <h2>Implementor's Note</h2> * <p> * {@link Channel} builds its features in a layered model. Its higher-layer * features are built on top of its lower-layer features, and they * are called layer-0, layer-1, etc. * * <ul> * <li> * <b>Layer 0</b>: * See {@link Command} for more details. This is for higher-level features, * and not likely useful for applications directly. * <li> * <b>Layer 1</b>: * See {@link Request} for more details. This is for higher-level features, * and not likely useful for applications directly. * </ul> * * @author Kohsuke Kawaguchi */ public class Channel implements VirtualChannel, IChannel { private final ObjectInputStream ois; private final ObjectOutputStream oos; /** * {@link OutputStream} that's given to the constructor. This is the hand-off with the lower layer. */ private final OutputStream underlyingOutput; /** * Human readable description of where this channel is connected to. Used during diagnostic output * and error reports. */ private final String name; private volatile boolean isRestricted; /*package*/ final ExecutorService executor; /** * If non-null, the incoming link is already shut down, * and reader is already terminated. The {@link Throwable} object indicates why the outgoing channel * was closed. */ private volatile Throwable inClosed = null; /** * If non-null, the outgoing link is already shut down, * and no command can be sent. The {@link Throwable} object indicates why the outgoing channel * was closed. */ private volatile Throwable outClosed = null; /*package*/ final Map<Integer,Request<?,?>> pendingCalls = new Hashtable<Integer,Request<?,?>>(); /** * Records the {@link Request}s being executed on this channel, sent by the remote peer. */ /*package*/ final Map<Integer,Request<?,?>> executingCalls = Collections.synchronizedMap(new Hashtable<Integer,Request<?,?>>()); /** * {@link ClassLoader}s that are proxies of the remote classloaders. */ /*package*/ final ImportedClassLoaderTable importedClassLoaders = new ImportedClassLoaderTable(this); /** * Objects exported via {@link #export(Class, Object)}. */ /*package (for test)*/ final ExportTable<Object> exportedObjects = new ExportTable<Object>(); /** * {@link PipeWindow}s keyed by their OIDs (of the OutputStream exported by the other side.) * * <p> * To make the GC of {@link PipeWindow} automatic, the use of weak references here are tricky. * A strong reference to {@link PipeWindow} is kept from {@link ProxyOutputStream}, and * this is the only strong reference. Thus while {@link ProxyOutputStream} is alive, * it keeps {@link PipeWindow} referenced, which in turn keeps its {@link PipeWindow.Real#key} * referenced, hence this map can be looked up by the OID. When the {@link ProxyOutputStream} * will be gone, the key is no longer strongly referenced, so it'll get cleaned up. * * <p> * In some race condition situation, it might be possible for us to lose the tracking of the collect * window size. But as long as we can be sure that there's only one {@link PipeWindow} instance * per OID, it will only result in a temporary spike in the effective window size, * and therefore should be OK. */ private final WeakHashMap<PipeWindow.Key, WeakReference<PipeWindow>> pipeWindows = new WeakHashMap<PipeWindow.Key, WeakReference<PipeWindow>>(); /** * Registered listeners. */ private final Vector<Listener> listeners = new Vector<Listener>(); private int gcCounter; private int commandsSent; /** * Total number of nanoseconds spent for remote class loading. * <p> * Remote code execution often results in classloading activity * (more precisely, when the remote peer requests some computation * on this channel, this channel often has to load necessary * classes from the remote peer.) * <p> * This counter represents the total amount of time this channel * had to spend loading classes from the remote peer. The time * measurement doesn't include the time locally spent to actually * define the class (as the local classloading would have incurred * the same cost.) */ public final AtomicLong classLoadingTime = new AtomicLong(); /** * Total counts of remote classloading activities. Used in a pair * with {@link #classLoadingTime}. */ public final AtomicInteger classLoadingCount = new AtomicInteger(); /** * Total number of nanoseconds spent for remote resource loading. * @see #classLoadingTime */ public final AtomicLong resourceLoadingTime = new AtomicLong(); /** * Total count of remote resource loading. * @see #classLoadingCount */ public final AtomicInteger resourceLoadingCount = new AtomicInteger(); /** * Property bag that contains application-specific stuff. */ private final Hashtable<Object,Object> properties = new Hashtable<Object,Object>(); /** * Proxy to the remote {@link Channel} object. */ private IChannel remoteChannel; /** * Capability of the remote {@link Channel}. */ public final Capability remoteCapability; /** * When did we receive any data from this slave the last time? * This can be used as a basis for detecting dead connections. * <p> * Note that this doesn't include our sender side of the operation, * as successfully returning from {@link #send(Command)} doesn't mean * anything in terms of whether the underlying network was able to send * the data (for example, if the other end of a socket connection goes down * without telling us anything, the {@link SocketOutputStream#write(int)} will * return right away, and the socket only really times out after 10s of minutes. */ private volatile long lastHeard; /** * Single-thread executor for running pipe I/O operations. * * It is executed in a separate thread to avoid blocking the channel reader thread * in case read/write blocks. It is single thread to ensure FIFO; I/O needs to execute * in the same order the remote peer told us to execute them. */ /*package*/ final ExecutorService pipeWriter; /** * ClassLaoder that remote classloaders should use as the basis. */ /*package*/ final ClassLoader baseClassLoader; /** * Communication mode. * @since 1.161 */ public enum Mode { /** * Send binary data over the stream. Most efficient. */ BINARY(new byte[]{0,0,0,0}), /** * Send ASCII over the stream. Uses base64, so the efficiency goes down by 33%, * but this is useful where stream is binary-unsafe, such as telnet. */ TEXT("<===[HUDSON TRANSMISSION BEGINS]===>") { @Override protected OutputStream wrap(OutputStream os) { return BinarySafeStream.wrap(os); } @Override protected InputStream wrap(InputStream is) { return BinarySafeStream.wrap(is); } }, /** * Let the remote peer decide the transmission mode and follow that. * Note that if both ends use NEGOTIATE, it will dead lock. */ NEGOTIATE(new byte[0]); /** * Preamble used to indicate the tranmission mode. * Because of the algorithm we use to detect the preamble, * the string cannot be any random string. For example, * if the preamble is "AAB", we'll fail to find a preamble * in "AAAB". */ private final byte[] preamble; Mode(String preamble) { try { this.preamble = preamble.getBytes("US-ASCII"); } catch (UnsupportedEncodingException e) { throw new Error(e); } } Mode(byte[] preamble) { this.preamble = preamble; } protected OutputStream wrap(OutputStream os) { return os; } protected InputStream wrap(InputStream is) { return is; } } public Channel(String name, ExecutorService exec, InputStream is, OutputStream os) throws IOException { this(name,exec,Mode.BINARY,is,os,null); } public Channel(String name, ExecutorService exec, Mode mode, InputStream is, OutputStream os) throws IOException { this(name,exec,mode,is,os,null); } public Channel(String name, ExecutorService exec, InputStream is, OutputStream os, OutputStream header) throws IOException { this(name,exec,Mode.BINARY,is,os,header); } public Channel(String name, ExecutorService exec, Mode mode, InputStream is, OutputStream os, OutputStream header) throws IOException { this(name,exec,mode,is,os,header,false); } public Channel(String name, ExecutorService exec, Mode mode, InputStream is, OutputStream os, OutputStream header, boolean restricted) throws IOException { this(name,exec,mode,is,os,header,restricted,null); } public Channel(String name, ExecutorService exec, Mode mode, InputStream is, OutputStream os, OutputStream header, boolean restricted, ClassLoader base) throws IOException { this(name,exec,mode,is,os,header,restricted,base,new Capability()); } /*package*/ Channel(String name, ExecutorService exec, Mode mode, InputStream is, OutputStream os, OutputStream header, boolean restricted, ClassLoader base, Capability capability) throws IOException { this.name = name; this.executor = exec; this.isRestricted = restricted; this.underlyingOutput = os; if (base==null) base = getClass().getClassLoader(); this.baseClassLoader = base; if(export(this,false)!=1) throw new AssertionError(); // export number 1 is reserved for the channel itself remoteChannel = RemoteInvocationHandler.wrap(this,1,IChannel.class,true,false); // write the magic preamble. // certain communication channel, such as forking JVM via ssh, // may produce some garbage at the beginning (for example a remote machine // might print some warning before the program starts outputting its own data.) // so use magic preamble and discard all the data up to that to improve robustness. capability.writePreamble(os); ObjectOutputStream oos = null; if(mode!= Mode.NEGOTIATE) { os.write(mode.preamble); oos = new ObjectOutputStream(mode.wrap(os)); oos.flush(); // make sure that stream preamble is sent to the other end. avoids dead-lock } {// read the input until we hit preamble Mode[] modes={Mode.BINARY,Mode.TEXT}; byte[][] preambles = new byte[][]{Mode.BINARY.preamble, Mode.TEXT.preamble, Capability.PREAMBLE}; int[] ptr=new int[3]; Capability cap = new Capability(0); // remote capacity that we obtained. If we don't hear from remote, assume no capability while(true) { int ch = is.read(); if(ch==-1) throw new EOFException("unexpected stream termination"); for(int i=0;i<preambles.length;i++) { byte[] preamble = preambles[i]; if(preamble[ptr[i]]==ch) { if(++ptr[i]==preamble.length) { switch (i) { case 0: case 1: // transmission mode negotiation if(mode==Mode.NEGOTIATE) { // now we know what the other side wants, so send the consistent preamble mode = modes[i]; os.write(mode.preamble); oos = new ObjectOutputStream(mode.wrap(os)); oos.flush(); } else { if(modes[i]!=mode) throw new IOException("Protocol negotiation failure"); } this.oos = oos; this.remoteCapability = cap; this.pipeWriter = createPipeWriter(); this.ois = new ObjectInputStreamEx(mode.wrap(is),base); new ReaderThread(name).start(); return; case 2: cap = Capability.read(is); break; } ptr[i]=0; // reset } } else { // didn't match. ptr[i]=0; } } if(header!=null) header.write(ch); } } } /** * Callback "interface" for changes in the state of {@link Channel}. */ public static abstract class Listener { /** * When the channel was closed normally or abnormally due to an error. * * @param cause * if the channel is closed abnormally, this parameter * represents an exception that has triggered it. * Otherwise null. */ public void onClosed(Channel channel, IOException cause) {} } /*package*/ boolean isOutClosed() { return outClosed!=null; } /** * Creates the {@link ExecutorService} for writing to pipes. * * <p> * If the throttling is supported, use a separate thread to free up the main channel * reader thread (thus prevent blockage.) Otherwise let the channel reader thread do it, * which is the historical behaviour. */ private ExecutorService createPipeWriter() { if (remoteCapability.supportsPipeThrottling()) return Executors.newSingleThreadExecutor(new ThreadFactory() { public Thread newThread(Runnable r) { return new Thread(r,"Pipe writer thread: "+name); } }); return new SynchronousExecutorService(); } /** * Sends a command to the remote end and executes it there. * * <p> * This is the lowest layer of abstraction in {@link Channel}. * {@link Command}s are executed on a remote system in the order they are sent. */ /*package*/ synchronized void send(Command cmd) throws IOException { if(outClosed!=null) throw new ChannelClosedException(outClosed); if(logger.isLoggable(Level.FINE)) logger.fine("Send "+cmd); Channel old = Channel.setCurrent(this); try { oos.writeObject(cmd); oos.flush(); // make sure the command reaches the other end. } finally { Channel.setCurrent(old); commandsSent++; } // unless this is the last command, have OOS and remote OIS forget all the objects we sent // in this command. Otherwise it'll keep objects in memory unnecessarily. // However, this may fail if the command was the close, because that's supposed to be the last command // ever sent. See the comment from jglick on HUDSON-3077 about what happens if we do oos.reset(). if(!(cmd instanceof CloseCommand)) oos.reset(); } /** * {@inheritDoc} */ public <T> T export(Class<T> type, T instance) { return export(type,instance,true); } /** * @param userProxy * If true, the returned proxy will be capable to handle classes * defined in the user classloader as parameters and return values. * Such proxy relies on {@link RemoteClassLoader} and related mechanism, * so it's not usable for implementing lower-layer services that are * used by {@link RemoteClassLoader}. * * To create proxies for objects inside remoting, pass in false. */ /*package*/ <T> T export(Class<T> type, T instance, boolean userProxy) { if(instance==null) return null; // every so often perform GC on the remote system so that // unused RemoteInvocationHandler get released, which triggers // unexport operation. if((++gcCounter)%10000==0) try { send(new GCCommand()); } catch (IOException e) { // for compatibility reason we can't change the export method signature logger.log(Level.WARNING, "Unable to send GC command",e); } // either local side will auto-unexport, or the remote side will unexport when it's GC-ed boolean autoUnexportByCaller = exportedObjects.isRecording(); final int id = export(instance,autoUnexportByCaller); return RemoteInvocationHandler.wrap(null, id, type, userProxy, autoUnexportByCaller); } /*package*/ int export(Object instance) { return exportedObjects.export(instance); } /*package*/ int export(Object instance, boolean automaticUnexport) { return exportedObjects.export(instance,automaticUnexport); } /*package*/ Object getExportedObject(int oid) { return exportedObjects.get(oid); } /*package*/ void unexport(int id) { exportedObjects.unexportByOid(id); } /** * Increase reference count so much to effectively prevent de-allocation. * * @see ExportTable.Entry#pin() */ public void pin(Object instance) { exportedObjects.pin(instance); } /** * {@linkplain #pin(Object) Pin down} the exported classloader. */ public void pinClassLoader(ClassLoader cl) { RemoteClassLoader.pin(cl,this); } /** * Preloads jar files on the remote side. * * <p> * This is a performance improvement method that can be safely * ignored if your goal is just to make things working. * * <p> * Normally, classes are transferred over the network one at a time, * on-demand. This design is mainly driven by how Java classloading works * &mdash; we can't predict what classes will be necessarily upfront very easily. * * <p> * Classes are loaded only once, so for long-running {@link Channel}, * this is normally an acceptable overhead. But sometimes, for example * when a channel is short-lived, or when you know that you'll need * a majority of classes in certain jar files, then it is more efficient * to send a whole jar file over the network upfront and thereby * avoiding individual class transfer over the network. * * <p> * That is what this method does. It ensures that a series of jar files * are copied to the remote side (AKA "preloading.") * Classloading will consult the preloaded jars before performing * network transfer of class files. * * @param classLoaderRef * This parameter is used to identify the remote classloader * that will prefetch the specified jar files. That is, prefetching * will ensure that prefetched jars will kick in * when this {@link Callable} object is actually executed remote side. * * <p> * {@link RemoteClassLoader}s are created wisely, one per local {@link ClassLoader}, * so this parameter doesn't have to be exactly the same {@link Callable} * to be executed later &mdash; it just has to be of the same class. * @param classesInJar * {@link Class} objects that identify jar files to be preloaded. * Jar files that contain the specified classes will be preloaded into the remote peer. * You just need to specify one class per one jar. * @return * true if the preloading actually happened. false if all the jars * are already preloaded. This method is implemented in such a way that * unnecessary jar file transfer will be avoided, and the return value * will tell you if this optimization kicked in. Under normal circumstances * your program shouldn't depend on this return value. It's just a hint. * @throws IOException * if the preloading fails. */ public boolean preloadJar(Callable<?,?> classLoaderRef, Class... classesInJar) throws IOException, InterruptedException { return preloadJar(UserRequest.getClassLoader(classLoaderRef),classesInJar); } public boolean preloadJar(ClassLoader local, Class... classesInJar) throws IOException, InterruptedException { URL[] jars = new URL[classesInJar.length]; for (int i = 0; i < classesInJar.length; i++) jars[i] = Which.jarFile(classesInJar[i]).toURI().toURL(); return call(new PreloadJarTask(jars,local)); } public boolean preloadJar(ClassLoader local, URL... jars) throws IOException, InterruptedException { return call(new PreloadJarTask(jars,local)); } /*package*/ PipeWindow getPipeWindow(int oid) { synchronized (pipeWindows) { Key k = new Key(oid); WeakReference<PipeWindow> v = pipeWindows.get(k); if (v!=null) { PipeWindow w = v.get(); if (w!=null) return w; } PipeWindow w; if (remoteCapability.supportsPipeThrottling()) w = new Real(k, PIPE_WINDOW_SIZE); else w = new PipeWindow.Fake(); pipeWindows.put(k,new WeakReference<PipeWindow>(w)); return w; } } /** * {@inheritDoc} */ public <V,T extends Throwable> V call(Callable<V,T> callable) throws IOException, T, InterruptedException { UserRequest<V,T> request=null; try { request = new UserRequest<V, T>(this, callable); UserResponse<V,T> r = request.call(this); return r.retrieve(this, UserRequest.getClassLoader(callable)); // re-wrap the exception so that we can capture the stack trace of the caller. } catch (ClassNotFoundException e) { IOException x = new IOException("Remote call on "+name+" failed"); x.initCause(e); throw x; } catch (Error e) { IOException x = new IOException("Remote call on "+name+" failed"); x.initCause(e); throw x; } finally { // since this is synchronous operation, when the round trip is over // we assume all the exported objects are out of scope. // (that is, the operation shouldn't spawn a new thread or altter // global state in the remote system. if(request!=null) request.releaseExports(); } } /** * {@inheritDoc} */ public <V,T extends Throwable> Future<V> callAsync(final Callable<V,T> callable) throws IOException { final Future<UserResponse<V,T>> f = new UserRequest<V,T>(this, callable).callAsync(this); return new FutureAdapter<V,UserResponse<V,T>>(f) { protected V adapt(UserResponse<V,T> r) throws ExecutionException { try { return r.retrieve(Channel.this, UserRequest.getClassLoader(callable)); } catch (Throwable t) {// really means catch(T t) throw new ExecutionException(t); } } }; } /** * Aborts the connection in response to an error. * * @param e * The error that caused the connection to be aborted. Never null. */ protected synchronized void terminate(IOException e) { if (e==null) throw new IllegalArgumentException(); outClosed=inClosed=e; try { synchronized(pendingCalls) { for (Request<?,?> req : pendingCalls.values()) req.abort(e); pendingCalls.clear(); } synchronized (executingCalls) { for (Request<?, ?> r : executingCalls.values()) { java.util.concurrent.Future<?> f = r.future; if(f!=null) f.cancel(true); } executingCalls.clear(); } } finally { notifyAll(); if (e instanceof OrderlyShutdown) e = null; for (Listener l : listeners.toArray(new Listener[listeners.size()])) l.onClosed(this,e); } } /** * Registers a new {@link Listener}. * * @see #removeListener(Listener) */ public void addListener(Listener l) { listeners.add(l); } /** * Removes a listener. * * @return * false if the given listener has not been registered to begin with. */ public boolean removeListener(Listener l) { return listeners.remove(l); } /** * Waits for this {@link Channel} to be closed down. * * The close-down of a {@link Channel} might be initiated locally or remotely. * * @throws InterruptedException * If the current thread is interrupted while waiting for the completion. */ public synchronized void join() throws InterruptedException { while(inClosed==null || outClosed==null) wait(); } /** * If the receiving end of the channel is closed (that is, if we are guaranteed to receive nothing further), * this method returns true. */ /*package*/ boolean isInClosed() { return inClosed!=null; } /** * Returns true if this channel is currently does not load classes from the remote peer. */ public boolean isRestricted() { return isRestricted; } public void setRestricted(boolean b) { isRestricted = b; } /** * Waits for this {@link Channel} to be closed down, but only up the given milliseconds. * * @throws InterruptedException * If the current thread is interrupted while waiting for the completion. * @since 1.299 */ public synchronized void join(long timeout) throws InterruptedException { long start = System.currentTimeMillis(); while(System.currentTimeMillis()-start<timeout && (inClosed==null || outClosed==null)) wait(timeout+start-System.currentTimeMillis()); } /** * Notifies the remote peer that we are closing down. * * Execution of this command also triggers the {@link ReaderThread} to shut down * and quit. The {@link CloseCommand} is always the last command to be sent on * {@link ObjectOutputStream}, and it's the last command to be read. */ private static final class CloseCommand extends Command { private CloseCommand(Throwable cause) { super(cause); } protected void execute(Channel channel) { try { channel.close(); channel.terminate(new OrderlyShutdown(createdAt)); } catch (IOException e) { logger.log(Level.SEVERE,"close command failed on "+channel.name,e); logger.log(Level.INFO,"close command created at",createdAt); } } @Override public String toString() { return "close"; } } /** * Signals the orderly shutdown of the channel, but captures * where the termination was initiated as a nested exception. */ private static final class OrderlyShutdown extends IOException { private OrderlyShutdown(Throwable cause) { super(cause.getMessage()); initCause(cause); } private static final long serialVersionUID = 1L; } /** * Resets all the performance counters. */ public void resetPerformanceCounters() { classLoadingCount.set(0); classLoadingTime.set(0); resourceLoadingCount.set(0); resourceLoadingTime.set(0); } /** * {@inheritDoc} */ public synchronized void close() throws IOException { close(null); } /** * Closes the channel. * * @param diagnosis * If someone (either this side or the other side) tries to use a channel that's already closed, * they'll get a stack trace indicating that the channel has already been closed. This diagnosis, * if provided, will further chained to that exception, providing more contextual information * about why the channel was closed. */ public synchronized void close(Throwable diagnosis) throws IOException { if(outClosed!=null) return; // already closed send(new CloseCommand(diagnosis)); outClosed = new IOException().initCause(diagnosis); // last command sent. no further command allowed. lock guarantees that no command will slip inbetween try { oos.close(); } catch (IOException e) { // there's a race condition here. // the remote peer might have already responded to the close command // and closed the connection, in which case our close invocation // could fail with errors like // "java.io.IOException: The pipe is being closed" // so let's ignore this error. } // termination is done by CloseCommand when we received it. } public Object getProperty(Object key) { return properties.get(key); } public <T> T getProperty(ChannelProperty<T> key) { return key.type.cast(getProperty((Object) key)); } /** * Works like {@link #getProperty(Object)} but wait until some value is set by someone. */ public Object waitForProperty(Object key) throws InterruptedException { synchronized (properties) { while(true) { Object v = properties.get(key); if(v!=null) return v; properties.wait(); } } } public <T> T waitForProperty(ChannelProperty<T> key) throws InterruptedException { return key.type.cast(waitForProperty((Object) key)); } /** * Sets the property value on this side of the channel. * * @see #getProperty(Object) */ public Object setProperty(Object key, Object value) { synchronized (properties) { Object old = value!=null ? properties.put(key, value) : properties.remove(key); properties.notifyAll(); return old; } } public <T> T setProperty(ChannelProperty<T> key, T value) { return key.type.cast(setProperty((Object) key, value)); } /** * Gets the property set on the remote peer. * * @return null * if the property of the said key isn't set. */ public Object getRemoteProperty(Object key) { return remoteChannel.getProperty(key); } public <T> T getRemoteProperty(ChannelProperty<T> key) { return key.type.cast(getRemoteProperty((Object) key)); } /** * Gets the property set on the remote peer. * This method blocks until the property is set by the remote peer. */ public Object waitForRemoteProperty(Object key) throws InterruptedException { return remoteChannel.waitForProperty(key); } public <T> T waitForRemoteProperty(ChannelProperty<T> key) throws InterruptedException { return key.type.cast(waitForRemoteProperty((Object) key)); } /** * Obtain the output stream passed to the constructor. * * @deprecated * Future version of the remoting module may add other modes of creating channel * that doesn't involve stream pair. Therefore, we aren't committing to this method. * This method isn't a part of the committed API of the channel class. * @return * While the current version always return a non-null value, the caller must not * make that assumption for the above reason. This method may return null in the future version * to indicate that the {@link Channel} is not sitting on top of a stream pair. */ public OutputStream getUnderlyingOutput() { return underlyingOutput; } /** * Starts a local to remote port forwarding (the equivalent of "ssh -L"). * * @param recvPort * The port on this local machine that we'll listen to. 0 to let * OS pick a random available port. If you specify 0, use * {@link ListeningPort#getPort()} to figure out the actual assigned port. * @param forwardHost * The remote host that the connection will be forwarded to. * Connection to this host will be made from the other JVM that * this {@link Channel} represents. * @param forwardPort * The remote port that the connection will be forwarded to. * @return */ public ListeningPort createLocalToRemotePortForwarding(int recvPort, String forwardHost, int forwardPort) throws IOException, InterruptedException { return new PortForwarder( recvPort, ForwarderFactory.create(this,forwardHost,forwardPort)); } /** * Starts a remote to local port forwarding (the equivalent of "ssh -R"). * * @param recvPort * The port on the remote JVM (represented by this {@link Channel}) * that we'll listen to. 0 to let * OS pick a random available port. If you specify 0, use * {@link ListeningPort#getPort()} to figure out the actual assigned port. * @param forwardHost * The remote host that the connection will be forwarded to. * Connection to this host will be made from this JVM. * @param forwardPort * The remote port that the connection will be forwarded to. * @return */ public ListeningPort createRemoteToLocalPortForwarding(int recvPort, String forwardHost, int forwardPort) throws IOException, InterruptedException { return PortForwarder.create(this,recvPort, ForwarderFactory.create(forwardHost, forwardPort)); } /** * Blocks until all the I/O packets sent before this gets fully executed by the remote side, then return. * * @throws IOException * If the remote doesn't support this operation, or if sync fails for other reasons. */ public void syncIO() throws IOException, InterruptedException { call(new IOSyncer()); } public void syncLocalIO() throws InterruptedException { try { pipeWriter.submit(new Runnable() { public void run() { // noop } }).get(); } catch (ExecutionException e) { throw new AssertionError(e); // impossible } } private static final class IOSyncer implements Callable<Object, InterruptedException> { public Object call() throws InterruptedException { Channel.current().syncLocalIO(); return null; } private static final long serialVersionUID = 1L; } @Override public String toString() { return super.toString()+":"+name; } /** * Dumps the list of exported objects and their allocation traces to the given output. */ public void dumpExportTable(PrintWriter w) throws IOException { exportedObjects.dump(w); } public ExportList startExportRecording() { return exportedObjects.startRecording(); } /** * @see #lastHeard */ public long getLastHeard() { return lastHeard; } private final class ReaderThread extends Thread { private int commandsReceived = 0; private int commandsExecuted = 0; public ReaderThread(String name) { super("Channel reader thread: "+name); } @Override public void run() { try { while(inClosed==null) { Command cmd = null; try { Channel old = Channel.setCurrent(Channel.this); try { cmd = (Command)ois.readObject(); lastHeard = System.currentTimeMillis(); } finally { Channel.setCurrent(old); } } catch (EOFException e) { IOException ioe = new IOException("Unexpected termination of the channel"); ioe.initCause(e); throw ioe; } catch (ClassNotFoundException e) { logger.log(Level.SEVERE, "Unable to read a command (channel " + name + ")",e); continue; } finally { commandsReceived++; } if(logger.isLoggable(Level.FINE)) logger.fine("Received "+cmd); try { cmd.execute(Channel.this); } catch (Throwable t) { logger.log(Level.SEVERE, "Failed to execute command "+cmd+ " (channel " + name + ")",t); logger.log(Level.SEVERE, "This command is created here",cmd.createdAt); } finally { commandsExecuted++; } } ois.close(); } catch (IOException e) { logger.log(Level.SEVERE, "I/O error in channel "+name,e); terminate(e); } catch (RuntimeException e) { logger.log(Level.SEVERE, "Unexpected error in channel "+name,e); terminate((IOException)new IOException("Unexpected reader termination").initCause(e)); throw e; } catch (Error e) { logger.log(Level.SEVERE, "Unexpected error in channel "+name,e); terminate((IOException)new IOException("Unexpected reader termination").initCause(e)); throw e; } finally { pipeWriter.shutdown(); } } } /*package*/ static Channel setCurrent(Channel channel) { Channel old = CURRENT.get(); CURRENT.set(channel); return old; } /** * This method can be invoked during the serialization/deserialization of * objects when they are transferred to the remote {@link Channel}, * as well as during {@link Callable#call()} is invoked. * * @return null * if the calling thread is not performing serialization. */ public static Channel current() { return CURRENT.get(); } /** * Remembers the current "channel" associated for this thread. */ private static final ThreadLocal<Channel> CURRENT = new ThreadLocal<Channel>(); private static final Logger logger = Logger.getLogger(Channel.class.getName()); public static final int PIPE_WINDOW_SIZE = Integer.getInteger(Channel.class+".pipeWindowSize",128*1024); // static { // ConsoleHandler h = new ConsoleHandler(); // h.setFormatter(new Formatter(){ // public synchronized String format(LogRecord record) { // StringBuilder sb = new StringBuilder(); // sb.append((record.getMillis()%100000)+100000); // sb.append(" "); // if (record.getSourceClassName() != null) { // sb.append(record.getSourceClassName()); // } else { // sb.append(record.getLoggerName()); // if (record.getSourceMethodName() != null) { // sb.append(" "); // sb.append(record.getSourceMethodName()); // sb.append('\n'); // String message = formatMessage(record); // sb.append(record.getLevel().getLocalizedName()); // sb.append(": "); // sb.append(message); // sb.append('\n'); // if (record.getThrown() != null) { // try { // StringWriter sw = new StringWriter(); // PrintWriter pw = new PrintWriter(sw); // record.getThrown().printStackTrace(pw); // pw.close(); // sb.append(sw.toString()); // } catch (Exception ex) { // return sb.toString(); // h.setLevel(Level.FINE); // logger.addHandler(h); // logger.setLevel(Level.FINE); }
package hudson.remoting; import hudson.remoting.ExportTable.ExportList; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.Collections; import java.util.Hashtable; import java.util.Map; import java.util.Vector; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; import java.util.logging.Logger; import java.net.URL; /** * Represents a communication channel to the remote peer. * * <p> * A {@link Channel} is a mechanism for two JVMs to communicate over * bi-directional {@link InputStream}/{@link OutputStream} pair. * {@link Channel} represents an endpoint of the stream, and thus * two {@link Channel}s are always used in a pair. * * <p> * Communication is established as soon as two {@link Channel} instances * are created at the end fo the stream pair * until the stream is terminated via {@link #close()}. * * <p> * The basic unit of remoting is an executable {@link Callable} object. * An application can create a {@link Callable} object, and execute it remotely * by using the {@link #call(Callable)} method or {@link #callAsync(Callable)} method. * * <p> * In this sense, {@link Channel} is a mechanism to delegate/offload computation * to other JVMs and somewhat like an agent system. This is bit different from * remoting technologies like CORBA or web services, where the server exposes a * certain functionality that clients invoke. * * <p> * {@link Callable} object, as well as the return value / exceptions, * are transported by using Java serialization. All the necessary class files * are also shipped over {@link Channel} on-demand, so there's no need to * pre-deploy such classes on both JVMs. * * * <h2>Implementor's Note</h2> * <p> * {@link Channel} builds its features in a layered model. Its higher-layer * features are built on top of its lower-layer features, and they * are called layer-0, layer-1, etc. * * <ul> * <li> * <b>Layer 0</b>: * See {@link Command} for more details. This is for higher-level features, * and not likely useful for applications directly. * <li> * <b>Layer 1</b>: * See {@link Request} for more details. This is for higher-level features, * and not likely useful for applications directly. * </ul> * * @author Kohsuke Kawaguchi */ public class Channel implements VirtualChannel, IChannel { private final ObjectInputStream ois; private final ObjectOutputStream oos; private final String name; /*package*/ final boolean isRestricted; /*package*/ final ExecutorService executor; /** * If true, the incoming link is already shut down, * and reader is already terminated. */ private volatile boolean inClosed = false; /** * If true, the outgoing link is already shut down, * and no command can be sent. */ private volatile boolean outClosed = false; /*package*/ final Map<Integer,Request<?,?>> pendingCalls = new Hashtable<Integer,Request<?,?>>(); /** * Records the {@link Request}s being executed on this channel, sent by the remote peer. */ /*package*/ final Map<Integer,Request<?,?>> executingCalls = Collections.synchronizedMap(new Hashtable<Integer,Request<?,?>>()); /** * {@link ClassLoader}s that are proxies of the remote classloaders. */ /*package*/ final ImportedClassLoaderTable importedClassLoaders = new ImportedClassLoaderTable(this); /** * Objects exported via {@link #export(Class, Object)}. */ private final ExportTable<Object> exportedObjects = new ExportTable<Object>(); /** * Registered listeners. */ private final Vector<Listener> listeners = new Vector<Listener>(); private int gcCounter; /** * Total number of nanoseconds spent for remote class loading. * <p> * Remote code execution often results in classloading activity * (more precisely, when the remote peer requests some computation * on this channel, this channel often has to load necessary * classes from the remote peer.) * <p> * This counter represents the total amount of time this channel * had to spend loading classes from the remote peer. The time * measurement doesn't include the time locally spent to actually * define the class (as the local classloading would have incurred * the same cost.) */ public final AtomicLong classLoadingTime = new AtomicLong(); /** * Total counts of remote classloading activities. Used in a pair * with {@link #classLoadingTime}. */ public final AtomicInteger classLoadingCount = new AtomicInteger(); /** * Total number of nanoseconds spent for remote resource loading. * @see #classLoadingTime */ public final AtomicLong resourceLoadingTime = new AtomicLong(); /** * Total count of remote resource loading. * @see #classLoadingCount */ public final AtomicInteger resourceLoadingCount = new AtomicInteger(); /** * Property bag that contains application-specific stuff. */ private final Hashtable<Object,Object> properties = new Hashtable<Object,Object>(); /** * Proxy to the remote {@link Channel} object. */ private IChannel remoteChannel; /** * Communication mode. * @since 1.161 */ public enum Mode { /** * Send binary data over the stream. Most efficient. */ BINARY(new byte[]{0,0,0,0}), /** * Send ASCII over the stream. Uses base64, so the efficiency goes down by 33%, * but this is useful where stream is binary-unsafe, such as telnet. */ TEXT("<===[HUDSON TRANSMISSION BEGINS]===>") { protected OutputStream wrap(OutputStream os) { return BinarySafeStream.wrap(os); } protected InputStream wrap(InputStream is) { return BinarySafeStream.wrap(is); } }, /** * Let the remote peer decide the transmission mode and follow that. * Note that if both ends use NEGOTIATE, it will dead lock. */ NEGOTIATE(new byte[0]); /** * Preamble used to indicate the tranmission mode. * Because of the algorithm we use to detect the preamble, * the string cannot be any random string. For example, * if the preamble is "AAB", we'll fail to find a preamble * in "AAAB". */ private final byte[] preamble; Mode(String preamble) { try { this.preamble = preamble.getBytes("US-ASCII"); } catch (UnsupportedEncodingException e) { throw new Error(e); } } Mode(byte[] preamble) { this.preamble = preamble; } protected OutputStream wrap(OutputStream os) { return os; } protected InputStream wrap(InputStream is) { return is; } } public Channel(String name, ExecutorService exec, InputStream is, OutputStream os) throws IOException { this(name,exec,Mode.BINARY,is,os,null); } public Channel(String name, ExecutorService exec, Mode mode, InputStream is, OutputStream os) throws IOException { this(name,exec,mode,is,os,null); } public Channel(String name, ExecutorService exec, InputStream is, OutputStream os, OutputStream header) throws IOException { this(name,exec,Mode.BINARY,is,os,header); } public Channel(String name, ExecutorService exec, Mode mode, InputStream is, OutputStream os, OutputStream header) throws IOException { this(name,exec,mode,is,os,header,false); } public Channel(String name, ExecutorService exec, Mode mode, InputStream is, OutputStream os, OutputStream header, boolean restricted) throws IOException { this.name = name; this.executor = exec; this.isRestricted = restricted; ObjectOutputStream oos = null; if(export(this,false)!=1) throw new AssertionError(); // export number 1 is reserved for the channel itself remoteChannel = RemoteInvocationHandler.wrap(this,1,IChannel.class,false); // write the magic preamble. // certain communication channel, such as forking JVM via ssh, // may produce some garbage at the beginning (for example a remote machine // might print some warning before the program starts outputting its own data.) // so use magic preamble and discard all the data up to that to improve robustness. if(mode!= Mode.NEGOTIATE) { os.write(mode.preamble); oos = new ObjectOutputStream(mode.wrap(os)); oos.flush(); // make sure that stream preamble is sent to the other end. avoids dead-lock } {// read the input until we hit preamble int[] ptr=new int[2]; Mode[] modes={Mode.BINARY,Mode.TEXT}; while(true) { int ch = is.read(); if(ch==-1) throw new EOFException("unexpected stream termination"); for(int i=0;i<2;i++) { byte[] preamble = modes[i].preamble; if(preamble[ptr[i]]==ch) { if(++ptr[i]==preamble.length) { // found preamble if(mode==Mode.NEGOTIATE) { // now we know what the other side wants, so send the consistent preamble mode = modes[i]; os.write(mode.preamble); oos = new ObjectOutputStream(mode.wrap(os)); oos.flush(); } else { if(modes[i]!=mode) throw new IOException("Protocol negotiation failure"); } this.oos = oos; this.ois = new ObjectInputStream(mode.wrap(is)); new ReaderThread(name).start(); return; } } else { // didn't match. ptr[i]=0; } } if(header!=null) header.write(ch); } } } /** * Callback "interface" for changes in the state of {@link Channel}. */ public static abstract class Listener { /** * When the channel was closed normally or abnormally due to an error. * * @param cause * if the channel is closed abnormally, this parameter * represents an exception that has triggered it. */ public void onClosed(Channel channel, IOException cause) {} } /** * Sends a command to the remote end and executes it there. * * <p> * This is the lowest layer of abstraction in {@link Channel}. * {@link Command}s are executed on a remote system in the order they are sent. */ /*package*/ synchronized void send(Command cmd) throws IOException { if(outClosed) throw new IOException("already closed"); if(logger.isLoggable(Level.FINE)) logger.fine("Send "+cmd); Channel old = Channel.setCurrent(this); try { oos.writeObject(cmd); oos.flush(); // make sure the command reaches the other end. } finally { Channel.setCurrent(old); } // unless this is the last command, have OOS and remote OIS forget all the objects we sent // in this command. Otherwise it'll keep objects in memory unnecessarily. // However, this may fail if the command was the close, because that's supposed to be the last command // ever sent. See the comment from jglick on HUDSON-3077 about what happens if we do oos.reset(). if(!(cmd instanceof CloseCommand)) oos.reset(); } /** * {@inheritDoc} */ public <T> T export(Class<T> type, T instance) { return export(type,instance,true); } /** * @param userProxy * If true, the returned proxy will be capable to handle classes * defined in the user classloader as parameters and return values. * Such proxy relies on {@link RemoteClassLoader} and related mechanism, * so it's not usable for implementing lower-layer services that are * used by {@link RemoteClassLoader}. * * To create proxies for objects inside remoting, pass in false. */ /*package*/ <T> T export(Class<T> type, T instance, boolean userProxy) { if(instance==null) return null; // every so often perform GC on the remote system so that // unused RemoteInvocationHandler get released, which triggers // unexport operation. if((++gcCounter)%10000==0) try { send(new GCCommand()); } catch (IOException e) { // for compatibility reason we can't change the export method signature logger.log(Level.WARNING, "Unable to send GC command",e); } // proxy will unexport this instance when it's GC-ed on the remote machine. final int id = export(instance); return RemoteInvocationHandler.wrap(null,id,type,userProxy); } /*package*/ int export(Object instance) { return exportedObjects.export(instance); } /*package*/ int export(Object instance, boolean automaticUnexport) { return exportedObjects.export(instance,automaticUnexport); } /*package*/ Object getExportedObject(int oid) { return exportedObjects.get(oid); } /*package*/ void unexport(int id) { exportedObjects.unexport(id); } /** * Preloads jar files on the remote side. * * <p> * This is a performance improvement method that can be safely * ignored if your goal is just to make things working. * * <p> * Normally, classes are transferred over the network one at a time, * on-demand. This design is mainly driven by how Java classloading works * &mdash; we can't predict what classes will be necessarily upfront very easily. * * <p> * Classes are loaded only once, so for long-running {@link Channel}, * this is normally an acceptable overhead. But sometimes, for example * when a channel is short-lived, or when you know that you'll need * a majority of classes in certain jar files, then it is more efficient * to send a whole jar file over the network upfront and thereby * avoiding individual class transfer over the network. * * <p> * That is what this method does. It ensures that a series of jar files * are copied to the remote side (AKA "preloading.") * Classloading will consult the preloaded jars before performing * network transfer of class files. * * @param classLoaderRef * This parameter is used to identify the remote classloader * that will prefetch the specified jar files. That is, prefetching * will ensure that prefetched jars will kick in * when this {@link Callable} object is actually executed remote side. * * <p> * {@link RemoteClassLoader}s are created wisely, one per local {@link ClassLoader}, * so this parameter doesn't have to be exactly the same {@link Callable} * to be executed later &mdash; it just has to be of the same class. * @param classesInJar * {@link Class} objects that identify jar files to be preloaded. * Jar files that contain the specified classes will be preloaded into the remote peer. * You just need to specify one class per one jar. * @return * true if the preloading actually happened. false if all the jars * are already preloaded. This method is implemented in such a way that * unnecessary jar file transfer will be avoided, and the return value * will tell you if this optimization kicked in. Under normal circumstances * your program shouldn't depend on this return value. It's just a hint. * @throws IOException * if the preloading fails. */ public boolean preloadJar(Callable<?,?> classLoaderRef, Class... classesInJar) throws IOException, InterruptedException { return preloadJar(UserRequest.getClassLoader(classLoaderRef),classesInJar); } public boolean preloadJar(ClassLoader local, Class... classesInJar) throws IOException, InterruptedException { URL[] jars = new URL[classesInJar.length]; for (int i = 0; i < classesInJar.length; i++) jars[i] = Which.jarFile(classesInJar[i]).toURI().toURL(); return call(new PreloadJarTask(jars,local)); } /** * {@inheritDoc} */ public <V,T extends Throwable> V call(Callable<V,T> callable) throws IOException, T, InterruptedException { UserRequest<V,T> request=null; try { request = new UserRequest<V, T>(this, callable); UserResponse<V,T> r = request.call(this); return r.retrieve(this, UserRequest.getClassLoader(callable)); // re-wrap the exception so that we can capture the stack trace of the caller. } catch (ClassNotFoundException e) { IOException x = new IOException("Remote call failed"); x.initCause(e); throw x; } catch (Error e) { IOException x = new IOException("Remote call failed"); x.initCause(e); throw x; } finally { // since this is synchronous operation, when the round trip is over // we assume all the exported objects are out of scope. // (that is, the operation shouldn't spawn a new thread or altter // global state in the remote system. if(request!=null) request.releaseExports(); } } /** * {@inheritDoc} */ public <V,T extends Throwable> Future<V> callAsync(final Callable<V,T> callable) throws IOException { final Future<UserResponse<V,T>> f = new UserRequest<V,T>(this, callable).callAsync(this); return new FutureAdapter<V,UserResponse<V,T>>(f) { protected V adapt(UserResponse<V,T> r) throws ExecutionException { try { return r.retrieve(Channel.this, UserRequest.getClassLoader(callable)); } catch (Throwable t) {// really means catch(T t) throw new ExecutionException(t); } } }; } /** * Aborts the connection in response to an error. */ protected synchronized void terminate(IOException e) { outClosed=inClosed=true; try { synchronized(pendingCalls) { for (Request<?,?> req : pendingCalls.values()) req.abort(e); pendingCalls.clear(); } } finally { notifyAll(); for (Listener l : listeners.toArray(new Listener[listeners.size()])) l.onClosed(this,e); } } /** * Registers a new {@link Listener}. * * @see #removeListener(Listener) */ public void addListener(Listener l) { listeners.add(l); } /** * Removes a listener. * * @return * false if the given listener has not been registered to begin with. */ public boolean removeListener(Listener l) { return listeners.remove(l); } /** * Waits for this {@link Channel} to be closed down. * * The close-down of a {@link Channel} might be initiated locally or remotely. * * @throws InterruptedException * If the current thread is interrupted while waiting for the completion. */ public synchronized void join() throws InterruptedException { while(!inClosed || !outClosed) wait(); } /** * Waits for this {@link Channel} to be closed down, but only up the given milliseconds. * * @throws InterruptedException * If the current thread is interrupted while waiting for the completion. * @since 1.299 */ public synchronized void join(long timeout) throws InterruptedException { long start = System.currentTimeMillis(); while(System.currentTimeMillis()-start<timeout && (!inClosed || !outClosed)) wait(timeout+start-System.currentTimeMillis()); } /** * Notifies the remote peer that we are closing down. * * Execution of this command also triggers the {@link ReaderThread} to shut down * and quit. The {@link CloseCommand} is always the last command to be sent on * {@link ObjectOutputStream}, and it's the last command to be read. */ private static final class CloseCommand extends Command { protected void execute(Channel channel) { try { channel.close(); channel.terminate(new OrderlyShutdown(createdAt)); } catch (IOException e) { logger.log(Level.SEVERE,"close command failed on "+channel.name,e); logger.log(Level.INFO,"close command created at",createdAt); } } public String toString() { return "close"; } } /** * Signals the orderly shutdown of the channel, but captures * where the termination was initiated as a nested exception. */ private static final class OrderlyShutdown extends IOException { private OrderlyShutdown(Throwable cause) { super(cause.getMessage()); initCause(cause); } private static final long serialVersionUID = 1L; } /** * Resets all the performance counters. */ public void resetPerformanceCounters() { classLoadingCount.set(0); classLoadingTime.set(0); resourceLoadingCount.set(0); resourceLoadingTime.set(0); } /** * {@inheritDoc} */ public synchronized void close() throws IOException { if(outClosed) return; // already closed send(new CloseCommand()); outClosed = true; // last command sent. no further command allowed. lock guarantees that no command will slip inbetween try { oos.close(); } catch (IOException e) { // there's a race condition here. // the remote peer might have already responded to the close command // and closed the connection, in which case our close invocation // could fail with errors like // "java.io.IOException: The pipe is being closed" // so let's ignore this error. } // termination is done by CloseCommand when we received it. } public Object getProperty(Object key) { return properties.get(key); } /** * Works like {@link #getProperty(Object)} but wait until some value is set by someone. */ public Object waitForProperty(Object key) throws InterruptedException { synchronized (properties) { while(true) { Object v = properties.get(key); if(v!=null) return v; properties.wait(); } } } public Object setProperty(Object key, Object value) { synchronized (properties) { Object old = properties.put(key, value); properties.notifyAll(); return old; } } public Object getRemoteProperty(Object key) { return remoteChannel.getProperty(key); } public Object waitForRemoteProperty(Object key) throws InterruptedException { return remoteChannel.waitForProperty(key); } public String toString() { return super.toString()+":"+name; } /** * Dumps the list of exported objects and their allocation traces to the given output. */ public void dumpExportTable(PrintWriter w) throws IOException { exportedObjects.dump(w); } public ExportList startExportRecording() { return exportedObjects.startRecording(); } private final class ReaderThread extends Thread { public ReaderThread(String name) { super("Channel reader thread: "+name); } public void run() { Command cmd = null; try { while(!inClosed) { try { Channel old = Channel.setCurrent(Channel.this); try { cmd = (Command)ois.readObject(); } finally { Channel.setCurrent(old); } } catch (ClassNotFoundException e) { logger.log(Level.SEVERE, "Unable to read a command",e); } if(logger.isLoggable(Level.FINE)) logger.fine("Received "+cmd); try { cmd.execute(Channel.this); } catch (Throwable t) { logger.log(Level.SEVERE, "Failed to execute command "+cmd,t); logger.log(Level.SEVERE, "This command is created here",cmd.createdAt); } } ois.close(); } catch (IOException e) { logger.log(Level.SEVERE, "I/O error in channel "+name,e); terminate(e); } } } /*package*/ static Channel setCurrent(Channel channel) { Channel old = CURRENT.get(); CURRENT.set(channel); return old; } /** * This method can be invoked during the serialization/deserialization of * objects when they are transferred to the remote {@link Channel}, * as well as during {@link Callable#call()} is invoked. * * @return null * if the calling thread is not performing serialization. */ public static Channel current() { return CURRENT.get(); } /** * Remembers the current "channel" associated for this thread. */ private static final ThreadLocal<Channel> CURRENT = new ThreadLocal<Channel>(); private static final Logger logger = Logger.getLogger(Channel.class.getName()); // static { // ConsoleHandler h = new ConsoleHandler(); // h.setFormatter(new Formatter(){ // public synchronized String format(LogRecord record) { // StringBuilder sb = new StringBuilder(); // sb.append((record.getMillis()%100000)+100000); // sb.append(" "); // if (record.getSourceClassName() != null) { // sb.append(record.getSourceClassName()); // } else { // sb.append(record.getLoggerName()); // if (record.getSourceMethodName() != null) { // sb.append(" "); // sb.append(record.getSourceMethodName()); // sb.append('\n'); // String message = formatMessage(record); // sb.append(record.getLevel().getLocalizedName()); // sb.append(": "); // sb.append(message); // sb.append('\n'); // if (record.getThrown() != null) { // try { // StringWriter sw = new StringWriter(); // PrintWriter pw = new PrintWriter(sw); // record.getThrown().printStackTrace(pw); // pw.close(); // sb.append(sw.toString()); // } catch (Exception ex) { // return sb.toString(); // h.setLevel(Level.FINE); // logger.addHandler(h); // logger.setLevel(Level.FINE); }
package io.wovn.wovnjava; import org.jetbrains.annotations.Nullable; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.arnx.jsonic.JSON; class Values { private LinkedHashMap<String,LinkedHashMap<String,LinkedHashMap<String,ArrayList<LinkedHashMap<String,String>>>>> values; Values(String json) { LinkedHashMap<String,LinkedHashMap<String,LinkedHashMap<String,ArrayList<LinkedHashMap<String,String>>>>> v = JSON.decode(json); this.values = removeJsessionid(v); } private static LinkedHashMap<String,LinkedHashMap<String,LinkedHashMap<String,ArrayList<LinkedHashMap<String,String>>>>> removeJsessionid(LinkedHashMap<String,LinkedHashMap<String,LinkedHashMap<String,ArrayList<LinkedHashMap<String,String>>>>> v) { if (!v.containsKey("img_vals")) { return v; } LinkedHashMap<String,LinkedHashMap<String,ArrayList<LinkedHashMap<String,String>>>> newImgVals = new LinkedHashMap<String,LinkedHashMap<String,ArrayList<LinkedHashMap<String,String>>>>(); for (Map.Entry<String, LinkedHashMap<String, ArrayList<LinkedHashMap<String, String>>>> map : v.get("img_vals").entrySet()) { String key = map.getKey(); Matcher m = Pattern.compile(";jsessionid=[^=]+$", Pattern.CASE_INSENSITIVE).matcher(key); if (!m.find()) { newImgVals.put(key, map.getValue()); } else { String newKey = m.replaceFirst(""); newImgVals.put(newKey, map.getValue()); } } v.put("img_vals", newImgVals); return v; } ArrayList<String> getLangs() { Set<String> set = new HashSet<String>(); // Get languages from text data. LinkedHashMap<String,LinkedHashMap<String,ArrayList<LinkedHashMap<String,String>>>> textVals = this.values.get("text_vals"); if (textVals != null) { for (LinkedHashMap<String, ArrayList<LinkedHashMap<String,String>>> v : textVals.values()) { set.addAll(v.keySet()); } } // Get languages form image data. LinkedHashMap<String,LinkedHashMap<String,ArrayList<LinkedHashMap<String,String>>>> imgVals = this.values.get("img_vals"); if (imgVals != null) { for (LinkedHashMap<String, ArrayList<LinkedHashMap<String,String>>> v : imgVals.values()) { set.addAll(v.keySet()); } } // Remove blank. set.remove(""); // Change variable type and sort. ArrayList<String> langs = new ArrayList<String>(); langs.addAll(set); Collections.sort(langs); return langs; } @Nullable private String getCommon(String type, String text, String lang) { if (this.values.get(type) == null) { return null; } if (this.values.get(type).containsKey(text)) { if (this.values.get(type).get(text).containsKey(lang)) { if (this.values.get(type).get(text).get(lang).size() > 0) { return this.values.get(type).get(text).get(lang).get(0).get("data"); } } } return null; } String getText(String text, String lang) { return this.getCommon("text_vals", text, lang); } String getImage(String src, String lang) { return this.getCommon("img_vals", src, lang); } }
package jkit.gfx; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Shape; import java.awt.geom.AffineTransform; import java.awt.geom.PathIterator; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.util.ArrayList; import java.util.List; import jkit.gfx.pen.Pen; /** * A shape drawer using a {@link Pen}. * * @author Joschi <josua.krause@gmail.com> */ public final class PenShapeDrawer extends AbstractShapeDrawer { /** The pen. */ protected final Pen pen; /** The maximal segment length. */ protected final double segLen; /** * Creates a shape drawer for the given pen. * * @param pen The pen. */ public PenShapeDrawer(final Pen pen) { if(pen == null) throw new NullPointerException("pen"); this.pen = pen; segLen = pen.segmentLength(); } /** * A segment of an path iterator. * * @author Joschi <josua.krause@gmail.com> */ private final class Segment { /** The segment type. */ private final int segmentType; /** The current position. */ private final Point2D cur; /** Whether the segment is a move operation. */ private final boolean isMove; /** Whether this segment is a first segment of a line. */ private boolean isFirst; /** Whether this segment is a last segment of a line. */ private boolean isLast; /** The previous position. */ private Point2D last; /** The current position of the last move-to segment. */ private Point2D curMoveTo; /** The starting x position. */ private double x; /** The starting y position. */ private double y; /** The distance moved in x direction by this segment. */ private double dx; /** The distance moved in y direction by this segment. */ private double dy; /** * Creates a segment. * * @param pi The path iterator. * @param cmt The current position of the last move-to segment. * @param coords The array suitable to hold the coordinates. */ public Segment(final PathIterator pi, final Point2D cmt, final double[] coords) { curMoveTo = cmt; segmentType = pi.currentSegment(coords); isMove = segmentType == PathIterator.SEG_MOVETO; switch(segmentType) { case PathIterator.SEG_MOVETO: cur = create(coords, 0); curMoveTo = cur; break; case PathIterator.SEG_CLOSE: cur = curMoveTo; curMoveTo = null; break; case PathIterator.SEG_LINETO: cur = create(coords, 0); break; case PathIterator.SEG_QUADTO: // will not be used since we have a flattened path iterator cur = create(coords, 2); break; case PathIterator.SEG_CUBICTO: // will not be used since we have a flattened path iterator cur = create(coords, 4); break; default: throw new InternalError(); } } /** * Sets the previous segment and initializes corresponding values. * * @param lastSeg The previous segment. */ public void setLast(final Segment lastSeg) { last = lastSeg != null ? lastSeg.cur : null; if(last != null) { isFirst = isFirst || lastSeg.isMove; if(isMove) { lastSeg.isLast = true; } else { x = last.getX(); y = last.getY(); dx = cur.getX() - x; dy = cur.getY() - y; } } else { isFirst = true; } invalidate(); } /** Invalidates the cache. */ private void invalidate() { rot = Double.NaN; len = Double.NaN; } /** The cached length. */ private double len = Double.NaN; /** * Getter * * @return The length of this segment. */ private double getLength() { if(Double.isNaN(len)) { len = Math.sqrt(dx * dx + dy * dy); } return len; } /** A quarter pi. */ public static final double M_PI_4 = Math.PI / 4.0; /** * A fast implementation of {@link Math#atan(double)}. The maximum error is * <code>0.0015</code> radians. The behavior is the same as the library * function. The algorithm comes from: * <em>"Efficient approximations for the arctangent function", * Rajan, S. Sichun Wang Inkol, R. Joyal, A., May 2006</em> * * @param a The value whose arc tangent is to be returned. * @return The arc tangent of the argument. * @see Math#atan(double) */ private double fastArcTan(final double a) { if(a < -1 || a > 1) return Math.atan(a); return M_PI_4 * a - a * (Math.abs(a) - 1) * (0.2447 + 0.0663 * Math.abs(a)); } /** * Getter. * * @return The orientation of this segment. */ private double getOrientation() { if(Double.isNaN(rot)) { final double rot; if(dx == 0.0) { rot = Math.PI * (dy > 0.0 ? 0.5 : 1.5); } else { rot = (dx < 0 ? Math.PI : 0) + fastArcTan(dy / dx); } this.rot = rot; } return rot; } /** * Getter. * * @return The position of the last move-to operation. */ public Point2D getCurMoveTo() { return curMoveTo; } /** * Getter. * * @return Whether this segment is a move-to segment. */ public boolean isMove() { return isMove; } /** * Getter. * * @param coords The array holding the coordinates. * @param pos The position in the coordinates array. * @return The position specified by the coordinates array. */ private Point2D create(final double[] coords, final int pos) { return new Point2D.Double(coords[pos], coords[pos + 1]); } /** The cached value for the rotation. */ private double rot = Double.NaN; /** * Draws the current segment. * * @param gfx The graphics context. * @param no The number of the segment. * @return The number of the next segment. May be the same number as * <code>no</code> when nothing was drawn. */ public int drawCurrentSegment(final Graphics2D gfx, final int no) { if(dx == 0.0 && dy == 0.0) return no; final Graphics2D seg = (Graphics2D) gfx.create(); seg.translate(x, y); seg.rotate(getOrientation()); final int newNo = drawSeg(seg, getLength(), rot, no); seg.dispose(); return newNo; } /** * Adds the bounding box of this segment to the given rectangle. * * @param r The rectangle. */ public void bboxCurrentSegment(final Rectangle2D r) { if(dx == 0.0 && dy == 0.0) return; final AffineTransform at = AffineTransform.getTranslateInstance(x, y); final double rot = getOrientation(); at.rotate(rot); bbox(r, at, getLength(), rot); } /** * Whether this segment has to be drawn because it is in the visible area of * the graphics context. * * @param g The graphics context. * @param type The segment type. * @param rot The rotation of the segment. * @return Whether this segment needs to be drawn. */ private boolean mustDraw(final Graphics2D g, final int type, final double rot) { final Shape clip = g.getClip(); return clip == null || clip.intersects(pen.getBoundingBox(type, rot)); } /** * Adds the bounding box of the segment to the given rectangle. * * @param r The rectangle holding the bounding box. * @param af The transformation. * @param length The length of this segment. * @param rot The rotation of this segment. */ private void bbox(final Rectangle2D r, final AffineTransform af, final double length, final double rot) { double pos = 0.0; final double end = Math.max(length - segLen * 0.5, 0.0); while(pos <= end) { final AffineTransform at = new AffineTransform(af); final Shape s; if(isFirst && pos == 0.0) { s = pen.getBoundingBox(Pen.SEG_START, rot); } else if(isLast && pos + segLen > end) { s = pen.getBoundingBox(Pen.SEG_END, rot); } else { s = pen.getBoundingBox(Pen.SEG_NORM, rot); } unite(r, transform(at, s)); pos += segLen; af.translate(segLen, 0.0); } } /** * Transforms a shape and then computes the bounding box. Note that this * method is faster than actually transforming the shape. * * @param at The transformation. * @param s The shape. * @return The bounding box of the transformed shape. */ private Rectangle2D transform(final AffineTransform at, final Shape s) { final Rectangle2D r = s.getBounds2D(); final Point2D a = new Point2D.Double(r.getMinX(), r.getMinY()); final Point2D b = new Point2D.Double(r.getMaxX(), r.getMaxY()); final Point2D c = new Point2D.Double(r.getMinX(), r.getMaxY()); final Point2D d = new Point2D.Double(r.getMaxX(), r.getMinY()); at.transform(a, a); at.transform(b, b); at.transform(c, c); at.transform(d, d); final double minX = Math.min(a.getX(), Math.min(b.getX(), Math.min(c.getX(), d.getX()))); final double maxX = Math.max(a.getX(), Math.max(b.getX(), Math.max(c.getX(), d.getX()))); final double minY = Math.min(a.getY(), Math.min(b.getY(), Math.min(c.getY(), d.getY()))); final double maxY = Math.max(a.getY(), Math.max(b.getY(), Math.max(c.getY(), d.getY()))); return new Rectangle2D.Double(minX, minY, maxX - minX, maxY - minY); } /** * Draws the segment. * * @param seg The graphics context. * @param length The length of the segment. * @param rot The rotation of the segment. * @param oldNo The segment number before calling this method. * @return The segment number after calling this method. */ private int drawSeg(final Graphics2D seg, final double length, final double rot, final int oldNo) { int no = oldNo; double pos = 0.0; final double end = Math.max(length - segLen * 0.5, 0.0); while(pos <= end) { final Graphics2D s = (Graphics2D) seg.create(); if(isFirst && pos == 0.0) { if(mustDraw(s, Pen.SEG_START, rot)) { pen.start(s, no, rot); } } else if(isLast && pos + segLen > end) { if(mustDraw(s, Pen.SEG_END, rot)) { pen.end(s, no, rot); } } else { if(mustDraw(s, Pen.SEG_NORM, rot)) { pen.draw(s, no, rot); } } pos += segLen; ++no; s.dispose(); seg.translate(segLen, 0.0); } return no; } /** * Setter. * * @param isLast Whether this segment is the last of a line. */ public void setIsLast(final boolean isLast) { this.isLast = isLast; } } @Override public Drawable getDrawable(final Shape outline) { final List<Segment> list = new ArrayList<>(); { // prevents using those variables in the draw-able final PathIterator pi = outline.getPathIterator(null, Math.sqrt(segLen)); final double[] coords = new double[6]; Point2D curMoveTo = null; Segment last = null; Segment cur = null; while(!pi.isDone()) { cur = new Segment(pi, curMoveTo, coords); cur.setLast(last); list.add(last); curMoveTo = cur.getCurMoveTo(); last = cur; pi.next(); } if(cur != null) { cur.setIsLast(true); } list.add(cur); } return new Drawable() { @Override public void draw(final Graphics2D gfx) { int no = 0; final Graphics2D g = (Graphics2D) gfx.create(); pen.prepare(g, outline); for(final Segment s : list) { no = drawIfNotNull(g, s, no); } g.dispose(); } @Override protected Rectangle2D computeBounds() { final Rectangle2D r = new Rectangle2D.Double(); final Shape sb = pen.getSpecialBounds(outline); if(sb != null) { unite(r, sb); } for(final Segment s : list) { bboxIfNotNull(r, s); } return r; } }; } /** * Draws the segment if it is not <code>null</code>. * * @param gfx The graphics context. * @param seg The segment. * @param no The number of the segment. * @return The segment number after a call to this method. */ protected static int drawIfNotNull(final Graphics gfx, final Segment seg, final int no) { if(!(seg != null && !seg.isMove())) return no; return seg.drawCurrentSegment((Graphics2D) gfx, no); } /** * Adds the bounding box of the segment to the given rectangle if the segment * is not <code>null</code>. * * @param r The rectangle. * @param seg The segment. */ protected static void bboxIfNotNull(final Rectangle2D r, final Segment seg) { if(seg == null || seg.isMove()) return; seg.bboxCurrentSegment(r); } /** * Combines a rectangle with the bounding box of a shape. * * @param r The rectangle to enlarge. * @param s The shape. */ protected static void unite(final Rectangle2D r, final Shape s) { final Rectangle2D b = s.getBounds2D(); if(r.isEmpty()) { r.setRect(b); } else { r.add(b); } } @Override public void setColor(final Color color) { pen.setColor(color); } }
package org.ame.civspell; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.ItemStack; import java.util.HashMap; class Scroll implements Listener { Scroll(Main mainPlugin) { this.mainPlugin = mainPlugin; } private Main mainPlugin; private static HashMap<Player, Boolean> isOnCooldown = new HashMap<>(); @EventHandler public void onPlayerInteract(PlayerInteractEvent event) { // Handle cooldowns. if (isOnCooldown.get(event.getPlayer()) != null && isOnCooldown.get(event.getPlayer())) { return; } // Check if it's a scroll. else if (!(event.getMaterial() == Material.SUGAR_CANE) || !(event.getItem().getItemMeta().getDisplayName().startsWith("Magic Scroll return; } // Make it not trigger stepping on redstone. else if (event.getAction() == Action.PHYSICAL) { return; } String spellName = ""; for (String part : event.getItem().getItemMeta().getDisplayName().split("Magic Scroll spellName = spellName + part + "Magic Scroll spellName = spellName.replaceAll("(Magic Scroll -- )+$", ""); // Remove last "Magic Scroll -- " from string. } Spell spell = SpellManager.spellMap.get(spellName); if (spell == null) { event.getPlayer().sendMessage("Please report to the server admins how you got a scroll of " + "an invalid spell '" + spellName + "'."); event.getPlayer().getInventory().removeItem(new ItemStack(event.getItem())); return; } if (spell.canBeScroll()) { spell.cast(event); ItemStack toRemove = new ItemStack(event.getItem()); toRemove.setAmount(1); event.getPlayer().getInventory().removeItem(toRemove); isOnCooldown.put(event.getPlayer(), true); mainPlugin.getServer().getScheduler() .runTaskLater(mainPlugin, () -> isOnCooldown.put(event.getPlayer(), false), 5); } else { event.getPlayer().sendMessage("Please report to the server admins how you got a scroll of " + "a non-scrollable spell '" + spellName + "'."); event.getPlayer().getInventory().removeItem(new ItemStack(event.getItem())); } } }
package org.htmlcleaner; import java.io.*; import java.util.*; /** * <p> * XML node tag - basic node of the cleaned HTML tree. At the same time, it represents start tag token * after HTML parsing phase and before cleaning phase. After cleaning process, tree structure remains * containing tag nodes (TagNode class), content (text nodes - ContentNode), comments (CommentNode) * and optionally doctype node (DoctypeToken). * </p> */ public class TagNode extends TagToken implements HtmlNode { /** * Used as base for different node checkers. */ public interface ITagNodeCondition { public boolean satisfy(TagNode tagNode); } /** * All nodes. */ public class TagAllCondition implements ITagNodeCondition { public boolean satisfy(TagNode tagNode) { return true; } } /** * Checks if node has specified name. */ public class TagNodeNameCondition implements ITagNodeCondition { private String name; public TagNodeNameCondition(String name) { this.name = name; } public boolean satisfy(TagNode tagNode) { return tagNode == null ? false : tagNode.name.equalsIgnoreCase(this.name); } } /** * Checks if node contains specified attribute. */ public class TagNodeAttExistsCondition implements ITagNodeCondition { private String attName; public TagNodeAttExistsCondition(String attName) { this.attName = attName; } public boolean satisfy(TagNode tagNode) { return tagNode == null ? false : tagNode.attributes.containsKey( attName.toLowerCase() ); } } /** * Checks if node has specified attribute with specified value. */ public class TagNodeAttValueCondition implements ITagNodeCondition { private String attName; private String attValue; private boolean isCaseSensitive; public TagNodeAttValueCondition(String attName, String attValue, boolean isCaseSensitive) { this.attName = attName; this.attValue = attValue; this.isCaseSensitive = isCaseSensitive; } public boolean satisfy(TagNode tagNode) { if (tagNode == null || attName == null || attValue == null) { return false; } else { return isCaseSensitive ? attValue.equals( tagNode.getAttributeByName(attName) ) : attValue.equalsIgnoreCase( tagNode.getAttributeByName(attName) ); } } } private TagNode parent = null; private Map<String, String> attributes = new LinkedHashMap<String, String>(); private List children = new ArrayList(); private DoctypeToken docType = null; private Map<String, String> nsDeclarations = null; private List<BaseToken> itemsToMove = null; private transient boolean isFormed = false; public TagNode(String name) { super(name == null ? null : name.toLowerCase()); } /** * Changes name of the tag * @param name * @return True if new name is valid, false otherwise */ public boolean setName(String name) { if (Utils.isValidXmlIdentifier(name)) { this.name = name; return true; } return false; } /** * @param attName * @return Value of the specified attribute, or null if it this tag doesn't contain it. */ public String getAttributeByName(String attName) { return attName != null ? attributes.get(attName.toLowerCase()) : null; } /** * @return Map instance containing all attribute name/value pairs. */ public Map<String, String> getAttributes() { return attributes; } /** * Checks existance of specified attribute. * @param attName */ public boolean hasAttribute(String attName) { return attName != null ? attributes.containsKey(attName.toLowerCase()) : false; } /** * @deprecated Use setAttribute instead * Adds specified attribute to this tag or overrides existing one. * @param attName * @param attValue */ @Deprecated public void addAttribute(String attName, String attValue) { setAttribute(attName, attValue); } /** * Adding new attribute ir overriding existing one. * @param attName * @param attValue */ public void setAttribute(String attName, String attValue) { if ( attName != null && !"".equals(attName.trim()) ) { attName = attName.toLowerCase(); if ("xmlns".equals(attName)) { addNamespaceDeclaration("", attValue); } else if (attName.startsWith("xmlns:")) { addNamespaceDeclaration( attName.substring(6), attValue ); } else { attributes.put(attName, attValue == null ? "" : attValue ); } } } /** * Adds namespace declaration to the node * @param nsPrefix Namespace prefix * @param nsURI Namespace URI */ public void addNamespaceDeclaration(String nsPrefix, String nsURI) { if (nsDeclarations == null) { nsDeclarations = new TreeMap<String, String>(); } nsDeclarations.put(nsPrefix, nsURI); } /** * @return Map of namespace declarations for this node */ public Map<String, String> getNamespaceDeclarations() { return nsDeclarations; } /** * Removes specified attribute from this tag. * @param attName */ public void removeAttribute(String attName) { if ( attName != null && !"".equals(attName.trim()) ) { attributes.remove( attName.toLowerCase() ); } } /** * @return List of children objects. During the cleanup process there could be different kind of * childern inside, however after clean there should be only TagNode instances. */ public List getChildren() { return children; } /** * @return Whether this node has child elements or not. */ public boolean hasChildren() { return children.size() > 0; } void setChildren(List children) { this.children = children; } public List getChildTagList() { List childTagList = new ArrayList(); for (int i = 0; i < children.size(); i++) { Object item = children.get(i); if (item instanceof TagNode) { childTagList.add(item); } } return childTagList; } /** * @return An array of child TagNode instances. */ public TagNode[] getChildTags() { List childTagList = getChildTagList(); TagNode childrenArray[] = new TagNode[childTagList.size()]; for (int i = 0; i < childTagList.size(); i++) { childrenArray[i] = (TagNode) childTagList.get(i); } return childrenArray; } /** * @return Text content of this node and it's subelements. */ public StringBuffer getText() { StringBuffer text = new StringBuffer(); for (int i = 0; i < children.size(); i++) { Object item = children.get(i); if (item instanceof ContentNode) { text.append(item.toString()); } else if (item instanceof TagNode) { StringBuffer subtext = ((TagNode)item).getText(); text.append(subtext); } } return text; } /** * @return Parent of this node, or null if this is the root node. */ public TagNode getParent() { return parent; } public DoctypeToken getDocType() { return docType; } public void setDocType(DoctypeToken docType) { this.docType = docType; } public void addChild(Object child) { if (child == null) { return; } if (child instanceof List) { addChildren( (List)child ); } else { children.add(child); if (child instanceof TagNode) { TagNode childTagNode = (TagNode)child; childTagNode.parent = this; } } } /** * Add all elements from specified list to this node. * @param newChildren */ public void addChildren(List newChildren) { if (newChildren != null) { Iterator it = newChildren.iterator(); while (it.hasNext()) { Object child = it.next(); addChild(child); } } } /** * Finds first element in the tree that satisfy specified condition. * @param condition * @param isRecursive * @return First TagNode found, or null if no such elements. */ private TagNode findElement(ITagNodeCondition condition, boolean isRecursive) { if (condition == null) { return null; } for (int i = 0; i < children.size(); i++) { Object item = children.get(i); if (item instanceof TagNode) { TagNode currNode = (TagNode) item; if ( condition.satisfy(currNode) ) { return currNode; } else if (isRecursive) { TagNode inner = currNode.findElement(condition, isRecursive); if (inner != null) { return inner; } } } } return null; } /** * Get all elements in the tree that satisfy specified condition. * @param condition * @param isRecursive * @return List of TagNode instances with specified name. */ private List getElementList(ITagNodeCondition condition, boolean isRecursive) { List result = new LinkedList(); if (condition == null) { return result; } for (int i = 0; i < children.size(); i++) { Object item = children.get(i); if (item instanceof TagNode) { TagNode currNode = (TagNode) item; if ( condition.satisfy(currNode) ) { result.add(currNode); } if (isRecursive) { List innerList = currNode.getElementList(condition, isRecursive); if (innerList != null && innerList.size() > 0) { result.addAll(innerList); } } } } return result; } /** * @param condition * @param isRecursive * @return The array of all subelemets that satisfy specified condition. */ private TagNode[] getElements(ITagNodeCondition condition, boolean isRecursive) { final List list = getElementList(condition, isRecursive); TagNode array[] = new TagNode[ list == null ? 0 : list.size() ]; for (int i = 0; i < list.size(); i++) { array[i] = (TagNode) list.get(i); } return array; } public List getAllElementsList(boolean isRecursive) { return getElementList( new TagAllCondition(), isRecursive ); } public TagNode[] getAllElements(boolean isRecursive) { return getElements( new TagAllCondition(), isRecursive ); } public TagNode findElementByName(String findName, boolean isRecursive) { return findElement( new TagNodeNameCondition(findName), isRecursive ); } public List getElementListByName(String findName, boolean isRecursive) { return getElementList( new TagNodeNameCondition(findName), isRecursive ); } public TagNode[] getElementsByName(String findName, boolean isRecursive) { return getElements( new TagNodeNameCondition(findName), isRecursive ); } public TagNode findElementHavingAttribute(String attName, boolean isRecursive) { return findElement( new TagNodeAttExistsCondition(attName), isRecursive ); } public List getElementListHavingAttribute(String attName, boolean isRecursive) { return getElementList( new TagNodeAttExistsCondition(attName), isRecursive ); } public TagNode[] getElementsHavingAttribute(String attName, boolean isRecursive) { return getElements( new TagNodeAttExistsCondition(attName), isRecursive ); } public TagNode findElementByAttValue(String attName, String attValue, boolean isRecursive, boolean isCaseSensitive) { return findElement( new TagNodeAttValueCondition(attName, attValue, isCaseSensitive), isRecursive ); } public List getElementListByAttValue(String attName, String attValue, boolean isRecursive, boolean isCaseSensitive) { return getElementList( new TagNodeAttValueCondition(attName, attValue, isCaseSensitive), isRecursive ); } public TagNode[] getElementsByAttValue(String attName, String attValue, boolean isRecursive, boolean isCaseSensitive) { return getElements( new TagNodeAttValueCondition(attName, attValue, isCaseSensitive), isRecursive ); } * <li>/body/*[1]/@type</li> * <li>//div[3]//a[@id][@href='r/n4']</li> * <li>//div[last() >= 4]//./div[position() = last()])[position() > 22]//li[2]//a</li> * <li>//div[2]/@*[2]</li> * <li>data(//div//a[@id][@class])</li> * <li>//p/last()</li> * <li>//body//div[3][@class]//span[12.2<position()]/@id</li> * <li>data(//a['v' < @id])</li> * </ul> * </code> * @param xPathExpression * @return * @throws XPatherException */ public Object[] evaluateXPath(String xPathExpression) throws XPatherException { return new XPather(xPathExpression).evaluateAgainstNode(this); } /** * Remove this node from the tree. * @return True if element is removed (if it is not root node). */ public boolean removeFromTree() { if (parent != null) { boolean existed = parent.removeChild(this); parent = null; return existed; } return false; } /** * Remove specified child element from this node. * @param child * @return True if child object existed in the children list. */ public boolean removeChild(Object child) { return this.children.remove(child); } /** * Removes all children (subelements and text content). */ public void removeAllChildren() { this.children.clear(); } /** * Replaces specified child node with specified replacement node. * @param childToReplace Child node to be replaced * @param replacement Replacement node */ public void replaceChild(HtmlNode childToReplace, HtmlNode replacement) { if (replacement == null) { return; } ListIterator it = children.listIterator(); while (it.hasNext()) { Object curr = it.next(); if (curr == childToReplace) { it.set(replacement); break; } } } /** * @param child Child to find index of * @return Index of the specified child node inside this node's children, -1 if node is not the child */ public int getChildIndex(HtmlNode child) { int index = 0; for (Object curr: children) { if (curr == child) { return index; } index++; } return -1; } /** * Inserts specified node at specified position in array of children * @param index * @param childToAdd */ public void insertChild(int index, HtmlNode childToAdd) { children.add(index, childToAdd); } /** * Inserts specified node in the list of children before specified child * @param node Child before which to insert new node * @param nodeToInsert Node to be inserted at specified position */ public void insertChildBefore(HtmlNode node, HtmlNode nodeToInsert) { int index = getChildIndex(node); if (index >= 0) { insertChild(index, nodeToInsert); } } /** * Inserts specified node in the list of children after specified child * @param node Child after which to insert new node * @param nodeToInsert Node to be inserted at specified position */ public void insertChildAfter(HtmlNode node, HtmlNode nodeToInsert) { int index = getChildIndex(node); if (index >= 0) { insertChild(index + 1, nodeToInsert); } } void addItemForMoving(BaseToken item) { if (itemsToMove == null) { itemsToMove = new ArrayList<BaseToken>(); } itemsToMove.add(item); } List<BaseToken> getItemsToMove() { return itemsToMove; } void setItemsToMove(List<BaseToken> itemsToMove) { this.itemsToMove = itemsToMove; } boolean isFormed() { return isFormed; } void setFormed(boolean isFormed) { this.isFormed = isFormed; } void setFormed() { setFormed(true); } void transformAttributes(TagTransformation tagTrans) { boolean isPreserveSourceAtts = tagTrans.isPreserveSourceAttributes(); boolean hasAttTransforms = tagTrans.hasAttributeTransformations(); if ( hasAttTransforms || !isPreserveSourceAtts) { Map<String, String> newAttributes = isPreserveSourceAtts ? new LinkedHashMap<String, String>(attributes) : new LinkedHashMap<String, String>(); if (hasAttTransforms) { Map map = tagTrans.getAttributeTransformations(); Iterator iterator = map.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = (Map.Entry) iterator.next(); String attName = (String) entry.getKey(); String template = (String) entry.getValue(); if (template == null) { newAttributes.remove(attName); } else { String attValue = Utils.evaluateTemplate(template, attributes); newAttributes.put(attName, attValue); } } } this.attributes = newAttributes; } } /** * Traverses the tree and performs visitor's action on each node. It stops when it * finishes all the tree or when visitor returns false. * @param visitor TagNodeVisitor implementation */ public void traverse(TagNodeVisitor visitor) { traverseInternally(visitor); } private boolean traverseInternally(TagNodeVisitor visitor) { if (visitor != null) { boolean hasParent = parent != null; boolean toContinue = visitor.visit(parent, this); if (!toContinue) { return false; // if visitor stops traversal } else if (hasParent && parent == null) { return true; // if this node is pruned from the tree during the visit, then don't go deeper } for (Object child: children.toArray()) { // make an array to avoid ConcurrentModificationException when some node is cut if (child instanceof TagNode) { toContinue = ((TagNode)child).traverseInternally(visitor); } else if (child instanceof ContentNode) { toContinue = visitor.visit(this, (ContentNode)child); } else if (child instanceof CommentNode) { toContinue = visitor.visit(this, (CommentNode)child); } if (!toContinue) { return false; } } } return true; } /** * Collect all prefixes in namespace declarations up the path to the document root from the specified node * @param prefixes Set of prefixes to be collected */ void collectNamespacePrefixesOnPath(Set<String> prefixes) { Map<String, String> nsDeclarations = getNamespaceDeclarations(); if (nsDeclarations != null) { for (String prefix: nsDeclarations.keySet()) { prefixes.add(prefix); } } if (parent != null) { parent.collectNamespacePrefixesOnPath(prefixes); } } String getNamespaceURIOnPath(String nsPrefix) { if (nsDeclarations != null) { for (Map.Entry<String, String> nsEntry: nsDeclarations.entrySet()) { String currName = nsEntry.getKey(); if ( currName.equals(nsPrefix) || ("".equals(currName) && nsPrefix == null) ) { return nsEntry.getValue(); } } } if (parent != null) { return parent.getNamespaceURIOnPath(nsPrefix); } return null; } public void serialize(Serializer serializer, Writer writer) throws IOException { serializer.serialize(this, writer); } TagNode makeCopy() { TagNode copy = new TagNode(name); copy.attributes.putAll(attributes); return copy; } }
package org.takes; import java.io.IOException; @SuppressWarnings( { "PMD.OnlyOneConstructorShouldDoInitialization", "PMD.BeanMembersShouldSerialize" }) public class HttpException extends IOException { /** * Serialization marker. */ private static final long serialVersionUID = -505306086879848229L; /** * Status code. */ private final int status; /** * Ctor. * @param code HTTP status code */ public HttpException(final int code) { super(Integer.toString(code)); this.status = code; } /** * Ctor. * @param code HTTP status code * @param cause Cause of the problem */ public HttpException(final int code, final String cause) { // @checkstyle MultipleStringLiteralsCheck (1 line) super(String.format("[%03d] %s", code, cause)); this.status = code; } /** * Ctor. * @param code HTTP status code * @param cause Cause of the problem */ public HttpException(final int code, final Throwable cause) { super(cause); this.status = code; } /** * Ctor. * @param code HTTP status code * @param msg Exception message * @param cause Cause of the problem */ public HttpException(final int code, final String msg, final Throwable cause) { super(String.format("[%03d] %s", code, msg), cause); this.status = code; } /** * HTTP status code. * @return Code */ public final int code() { return this.status; } }
package org.traccar.entity; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.Table; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import rs.pelotas.arch.annotation.adapters.PasswordAdapter; import rs.pelotas.arch.entity.BaseEntity; /** * * @author Rafael Guterres */ @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) @Entity @Table(name="users") public class User extends BaseEntity<Long> { private static final long serialVersionUID = 2094535745860666195L; @Id private Long id; private String login; @XmlJavaTypeAdapter(PasswordAdapter.class) private String password; @XmlTransient @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JoinTable(name = "users_devices", joinColumns = {@JoinColumn(name = "users_id")}, inverseJoinColumns = {@JoinColumn(name = "devices_id")}) private List<Device> devices; @Override public Long getId() { return id; } @Override public void setId(Long id) { this.id = id; } public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public List<Device> getDevices() { return devices; } public void setDevices(List<Device> devices) { this.devices = devices; } }
package org.wetator; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.codehaus.plexus.util.DirectoryScanner; import org.wetator.core.WetatorEngine; import java.io.File; /** * This is the main Mojo for executing wetator tests. */ @Mojo(name = "execute") public class WetatorMojo extends AbstractMojo { /** * File pattern for the weator test files. */ private static final String INCLUDE_FILE_PATTERN = "**\\*.wet"; /** * Path with filename to the config file in file system. */ @Parameter(property = "execute.configFile") private String configFile; /** * Directory where the test files resides. */ @Parameter(property = "execute.testFileDir") private String testFileDir; @Override public void execute() throws MojoExecutionException, MojoFailureException { getLog().info("start running wetator tests ..."); getLog().info("using config file: " + configFile); getLog().info("using wetator test file directory: " + testFileDir); try { final WetatorEngine wetatorEngine = new WetatorEngine(); wetatorEngine.setConfigFileName(configFile); wetatorEngine.init(); final String[] weatorTestFilenames = scanForWetatorTestFiles(); for (String weatorTestFilename : weatorTestFilenames) { getLog().info("adding test file: " + weatorTestFilename); wetatorEngine.addTestCase(weatorTestFilename, new File(testFileDir, weatorTestFilename)); } wetatorEngine.executeTests(); getLog().info("find wetator test results in: " + wetatorEngine.getConfiguration().getOutputDir().getCanonicalPath()); getLog().info("wetator test execution complete!"); } catch (Exception e) { getLog().error(e.getMessage(), e); throw new MojoExecutionException(e.getMessage(), e); } } private String[] scanForWetatorTestFiles() { final DirectoryScanner directoryScanner = new DirectoryScanner(); directoryScanner.setBasedir(testFileDir); directoryScanner.setIncludes(new String[]{INCLUDE_FILE_PATTERN}); directoryScanner.scan(); return directoryScanner.getIncludedFiles(); } }