answer
stringlengths
17
10.2M
package org.opendaylight.yangtools.yang.parser.stmt.reactor; import static com.google.common.base.Verify.verify; import static java.util.Objects.requireNonNull; import com.google.common.base.VerifyException; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Streams; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; import org.eclipse.jdt.annotation.NonNull; import org.eclipse.jdt.annotation.Nullable; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.common.QNameModule; import org.opendaylight.yangtools.yang.model.api.SchemaPath; import org.opendaylight.yangtools.yang.model.api.YangStmtMapping; import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement; import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement; import org.opendaylight.yangtools.yang.model.api.meta.StatementDefinition; import org.opendaylight.yangtools.yang.model.api.stmt.SchemaTreeEffectiveStatement; import org.opendaylight.yangtools.yang.parser.spi.SchemaTreeNamespace; import org.opendaylight.yangtools.yang.parser.spi.meta.CopyHistory; import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType; import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException; import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.OnDemandSchemaTreeStorageNode; import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType; import org.opendaylight.yangtools.yang.parser.spi.meta.StatementFactory; import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext; import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils; import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A statement which has been inferred to exist. Functionally it is equivalent to a SubstatementContext, but it is not * backed by a declaration (and declared statements). It is backed by a prototype StatementContextBase and has only * effective substatements, which are either transformed from that prototype or added by inference. */ final class InferredStatementContext<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>> extends StatementContextBase<A, D, E> implements OnDemandSchemaTreeStorageNode { private static final Logger LOG = LoggerFactory.getLogger(InferredStatementContext.class); // Sentinel object for 'substatements' private static final Object SWEPT_SUBSTATEMENTS = new Object(); private final @NonNull StatementContextBase<A, D, E> prototype; private final @NonNull StatementContextBase<?, ?, ?> parent; private final @NonNull StmtContext<A, D, E> originalCtx; private final @NonNull CopyType childCopyType; private final QNameModule targetModule; private final A argument; /** * Effective substatements, lazily materialized. This field can have four states: * <ul> * <li>it can be {@code null}, in which case no materialization has taken place</li> * <li>it can be a {@link HashMap}, in which case partial materialization has taken place</li> * <li>it can be a {@link List}, in which case full materialization has taken place</li> * <li>it can be {@link SWEPT_SUBSTATEMENTS}, in which case materialized state is no longer available</li> * </ul> */ private Object substatements; private InferredStatementContext(final InferredStatementContext<A, D, E> original, final StatementContextBase<?, ?, ?> parent) { super(original); this.parent = requireNonNull(parent); this.childCopyType = original.childCopyType; this.targetModule = original.targetModule; this.prototype = original.prototype; this.originalCtx = original.originalCtx; this.argument = original.argument; // Substatements are initialized here this.substatements = ImmutableList.of(); } InferredStatementContext(final StatementContextBase<?, ?, ?> parent, final StatementContextBase<A, D, E> prototype, final CopyType myCopyType, final CopyType childCopyType, final QNameModule targetModule) { super(prototype.definition(), CopyHistory.of(myCopyType, prototype.history())); this.parent = requireNonNull(parent); this.prototype = requireNonNull(prototype); this.argument = targetModule == null ? prototype.argument() : prototype.definition().adaptArgumentValue(prototype, targetModule); this.childCopyType = requireNonNull(childCopyType); this.targetModule = targetModule; this.originalCtx = prototype.getOriginalCtx().orElse(prototype); // Mark prototype as blocking statement cleanup prototype.incRef(); } @Override public Collection<? extends StatementContextBase<?, ?, ?>> mutableDeclaredSubstatements() { return ImmutableList.of(); } @Override public Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements() { return mutableEffectiveSubstatements(ensureEffectiveSubstatements()); } @Override public Iterable<? extends StmtContext<?, ?, ?>> allSubstatements() { // No need to concat with declared return effectiveSubstatements(); } @Override public Stream<? extends StmtContext<?, ?, ?>> allSubstatementsStream() { // No need to concat with declared return effectiveSubstatements().stream(); } @Override public StatementSourceReference sourceReference() { return originalCtx.sourceReference(); } @Override public String rawArgument() { return originalCtx.rawArgument(); } @Override public Optional<StmtContext<A, D, E>> getOriginalCtx() { return Optional.of(originalCtx); } @Override public Optional<StmtContext<A, D, E>> getPreviousCopyCtx() { return Optional.of(prototype); } @Override public D declared() { /* * Share original instance of declared statement between all effective statements which have been copied or * derived from this original declared statement. */ return originalCtx.declared(); } @Override public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef) { substatements = removeStatementFromEffectiveSubstatements(ensureEffectiveSubstatements(), statementDef); } @Override public void removeStatementFromEffectiveSubstatements(final StatementDefinition statementDef, final String statementArg) { substatements = removeStatementFromEffectiveSubstatements(ensureEffectiveSubstatements(), statementDef, statementArg); } @Override public void addEffectiveSubstatement(final Mutable<?, ?, ?> substatement) { substatements = addEffectiveSubstatement(ensureEffectiveSubstatements(), substatement); } @Override void addEffectiveSubstatementsImpl(final Collection<? extends Mutable<?, ?, ?>> statements) { substatements = addEffectiveSubstatementsImpl(ensureEffectiveSubstatements(), statements); } @Override InferredStatementContext<A, D, E> reparent(final StatementContextBase<?, ?, ?> newParent) { return new InferredStatementContext<>(this, newParent); } @Override E createEffective(final StatementFactory<A, D, E> factory) { // If we have not materialized we do not have a difference in effective substatements, hence we can forward // towards the source of the statement. return substatements == null ? tryToReusePrototype(factory) : super.createEffective(factory); } private @NonNull E tryToReusePrototype(final StatementFactory<A, D, E> factory) { final E origEffective = prototype.buildEffective(); final Collection<? extends @NonNull EffectiveStatement<?, ?>> origSubstatements = origEffective.effectiveSubstatements(); // First check if we can reuse the entire prototype if (!factory.canReuseCurrent(this, prototype, origSubstatements)) { return tryToReuseSubstatements(factory, origSubstatements); } // No substatements to deal with, we can freely reuse the original if (origSubstatements.isEmpty()) { LOG.debug("Reusing empty: {}", origEffective); substatements = ImmutableList.of(); prototype.decRef(); return origEffective; } // We can reuse this statement let's see if all the statements agree final List<Entry<Mutable<?, ?, ?>, Mutable<?, ?, ?>>> declared = prototype.streamDeclared() .filter(StmtContext::isSupportedByFeatures) .map(sub -> effectiveCopy((ReactorStmtCtx<?, ?, ?>) sub)) .filter(Objects::nonNull) .collect(Collectors.toUnmodifiableList()); final List<Entry<Mutable<?, ?, ?>, Mutable<?, ?, ?>>> effective = prototype.streamEffective() .map(sub -> effectiveCopy((ReactorStmtCtx<?, ?, ?>) sub)) .filter(Objects::nonNull) .collect(Collectors.toUnmodifiableList()); // We no longer need the prototype's substatements, but we may need to retain ours prototype.decRef(); if (haveRef()) { substatements = Streams.concat(declared.stream(), effective.stream()) .map(Entry::getValue) .collect(ImmutableList.toImmutableList()); } else { // This should immediately get swept anyway. Should we use a poison object? substatements = List.of(); } if (allReused(declared) && allReused(effective)) { LOG.debug("Reusing after substatement check: {}", origEffective); return origEffective; } // Values are the effective copies, hence this efficienly deals with recursion. return factory.createEffective(this, declared.stream().map(Entry::getValue), effective.stream().map(Entry::getValue)); } private @NonNull E tryToReuseSubstatements(final StatementFactory<A, D, E> factory, final @NonNull Collection<? extends EffectiveStatement<?, ?>> origSubstatements) { // FIXME: YANGTOOLS-1067: an incremental improvement here is that we reuse statements that are not affected // by us changing parent. For example: if our SchemaPath changed, but the namespace // remained the same, 'key' statement should get reused. // Fall back to full instantiation return super.createEffective(factory); } private static boolean allReused(final List<Entry<Mutable<?, ?, ?>, Mutable<?, ?, ?>>> entries) { for (Entry<Mutable<?, ?, ?>, Mutable<?, ?, ?>> entry : entries) { if (entry.getKey() != entry.getValue()) { return false; } } return true; } @Override boolean hasEmptySubstatements() { if (substatements == null) { return prototype.hasEmptySubstatements(); } return substatements instanceof HashMap ? false : ((List<?>) substatements).isEmpty(); } @Override boolean noSensitiveSubstatements() { accessSubstatements(); if (substatements == null) { // No difference, defer to prototype return prototype.allSubstatementsContextIndependent(); } if (substatements instanceof List) { // Fully materialized, walk all statements return noSensitiveSubstatements(castEffective(substatements)); } // Partially-materialized. This case has three distinct outcomes: // - prototype does not have a sensitive statement (1) // - protype has a sensitive substatement, and // - we have not marked is as unsupported (2) // - we have marked it as unsupported (3) // Determining the outcome between (2) and (3) is a bother, this check errs on the side of false negative side // and treats (3) as (2) -- i.e. even if we marked a sensitive statement as unsupported, we still consider it // as affecting the result. return prototype.allSubstatementsContextIndependent() && noSensitiveSubstatements(castMaterialized(substatements).values()); } @Override public <X, Z extends EffectiveStatement<X, ?>> @NonNull Optional<X> findSubstatementArgument( final @NonNull Class<Z> type) { if (substatements instanceof List) { return super.findSubstatementArgument(type); } final Optional<X> templateArg = prototype.findSubstatementArgument(type); if (templateArg.isEmpty()) { return templateArg; } if (SchemaTreeEffectiveStatement.class.isAssignableFrom(type)) { // X is known to be QName return (Optional<X>) templateArg.map(template -> ((QName) template).bindTo(targetModule)); } return templateArg; } @Override public boolean hasSubstatement(final @NonNull Class<? extends EffectiveStatement<?, ?>> type) { return substatements instanceof List ? super.hasSubstatement(type) // We do not allow deletion of partially-materialized statements, hence this is accurate : prototype.hasSubstatement(type); } @Override public <Y extends DeclaredStatement<QName>, Z extends SchemaTreeEffectiveStatement<Y>> StmtContext<QName, Y, Z> requestSchemaTreeChild(final QName qname) { if (substatements instanceof List) { // We have performed materialization, hence we have triggered creation of all our schema tree child // statements. return null; } final QName templateQName = qname.bindTo(StmtContextUtils.getRootModuleQName(prototype)); LOG.debug("Materializing child {} from {}", qname, templateQName); final StmtContext<?, ?, ?> template; if (prototype instanceof InferredStatementContext) { // Note: we need to access namespace here, as the target statement may have already been populated, in which // case we want to obtain the statement in local namespace storage. template = (StmtContext) ((InferredStatementContext<?, ?, ?>) prototype).getFromNamespace( SchemaTreeNamespace.class, templateQName); } else { template = prototype.allSubstatementsStream() .filter(stmt -> stmt.producesEffective(SchemaTreeEffectiveStatement.class) && templateQName.equals(stmt.argument())) .findAny() .orElse(null); } if (template == null) { // We do not have a template, this child does not exist. It may be added later, but that is someone else's // responsibility. LOG.debug("Child {} does not have a template", qname); return null; } @SuppressWarnings("unchecked") final Mutable<QName, Y, Z> ret = (Mutable<QName, Y, Z>) copySubstatement((Mutable<?, ?, ?>) template) .orElseThrow( () -> new InferenceException(this, "Failed to materialize child %s template %s", qname, template)); ensureCompletedPhase(ret); addMaterialized(template, ret); LOG.debug("Child {} materialized", qname); return ret; } // Instantiate this statement's effective substatements. Note this method has side-effects in namespaces and overall // BuildGlobalContext, hence it must be called at most once. private List<ReactorStmtCtx<?, ?, ?>> ensureEffectiveSubstatements() { accessSubstatements(); return substatements instanceof List ? castEffective(substatements) : initializeSubstatements(castMaterialized(substatements)); } @Override Iterable<ReactorStmtCtx<?, ?, ?>> effectiveChildrenToComplete() { // When we have not initialized, there are no statements to catch up: we will catch up when we are copying // from prototype (which is already at ModelProcessingPhase.EFFECTIVE_MODEL). if (substatements == null) { return ImmutableList.of(); } accessSubstatements(); if (substatements instanceof HashMap) { return castMaterialized(substatements).values(); } else { return castEffective(substatements); } } @Override Stream<? extends StmtContext<?, ?, ?>> streamDeclared() { return Stream.empty(); } @Override Stream<? extends StmtContext<?, ?, ?>> streamEffective() { accessSubstatements(); return ensureEffectiveSubstatements().stream(); } private void accessSubstatements() { verify(substatements != SWEPT_SUBSTATEMENTS, "Attempted to access substatements of %s", this); } @Override void markNoParentRef() { final Object local = substatements; if (local != null) { markNoParentRef(castEffective(local)); } } @Override int sweepSubstatements() { final Object local = substatements; substatements = SWEPT_SUBSTATEMENTS; int count = 0; if (local != null) { final List<ReactorStmtCtx<?, ?, ?>> list = castEffective(local); sweep(list); count = countUnswept(list); } return count; } private List<ReactorStmtCtx<?, ?, ?>> initializeSubstatements( final Map<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> materializedSchemaTree) { final Collection<? extends StatementContextBase<?, ?, ?>> declared = prototype.mutableDeclaredSubstatements(); final Collection<? extends Mutable<?, ?, ?>> effective = prototype.mutableEffectiveSubstatements(); final List<Mutable<?, ?, ?>> buffer = new ArrayList<>(declared.size() + effective.size()); for (final Mutable<?, ?, ?> stmtContext : declared) { if (stmtContext.isSupportedByFeatures()) { copySubstatement(stmtContext, buffer, materializedSchemaTree); } } for (final Mutable<?, ?, ?> stmtContext : effective) { copySubstatement(stmtContext, buffer, materializedSchemaTree); } final List<ReactorStmtCtx<?, ?, ?>> ret = beforeAddEffectiveStatementUnsafe(ImmutableList.of(), buffer.size()); ret.addAll((Collection) buffer); substatements = ret; prototype.decRef(); return ret; } // Statement copy mess starts here // FIXME: This is messy and is probably wrong in some corner case. Even if it is correct, the way how it is correct // relies on hard-coded maps. At the end of the day, the logic needs to be controlled by statement's // StatementSupport. // FIXME: YANGTOOLS-652: this map looks very much like UsesStatementSupport.TOP_REUSED_DEF_SET private static final ImmutableSet<YangStmtMapping> REUSED_DEF_SET = ImmutableSet.of( YangStmtMapping.TYPE, YangStmtMapping.TYPEDEF, YangStmtMapping.USES); private Map.Entry<Mutable<?, ?, ?>, Mutable<?, ?, ?>> effectiveCopy(final ReactorStmtCtx<?, ?, ?> stmt) { // FIXME: YANGTOOLS-652: formerly known as "isReusedByUses" if (REUSED_DEF_SET.contains(stmt.definition().getPublicView())) { return Map.entry(stmt, stmt.replicaAsChildOf(this)); } final ReactorStmtCtx<?, ?, ?> effective = stmt.asEffectiveChildOf(this, childCopyType, targetModule); return effective == null ? null : Map.entry(stmt, effective); } private void copySubstatement(final Mutable<?, ?, ?> substatement, final Collection<Mutable<?, ?, ?>> buffer, final Map<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> materializedSchemaTree) { final StatementDefinition def = substatement.publicDefinition(); // FIXME: YANGTOOLS-652: formerly known as "isReusedByUses" if (REUSED_DEF_SET.contains(def)) { LOG.trace("Reusing substatement {} for {}", substatement, this); buffer.add(substatement.replicaAsChildOf(this)); return; } // Consult materialized substatements. We are in a copy operation and will end up throwing materialized // statements away -- hence we do not perform Map.remove() to save ourselves a mutation operation. // We could also perform a Map.containsKey() and perform a bulk add, but that would mean the statement order // against parent would change -- and we certainly do not want that to happen. final ReactorStmtCtx<?, ?, ?> materialized = findMaterialized(materializedSchemaTree, substatement); if (materialized == null) { copySubstatement(substatement).ifPresent(copy -> { ensureCompletedPhase(copy); buffer.add(copy); }); } else { buffer.add(materialized); } } private Optional<? extends Mutable<?, ?, ?>> copySubstatement(final Mutable<?, ?, ?> substatement) { // FIXME: YANGTOOLS-1195: this is not exactly what we want to do here, because we are dealing with two different // requests: copy for inference purposes (this method), while we also copy for purposes // of buildEffective() -- in which case we want to probably invoke asEffectiveChildOf() // or similar return substatement.copyAsChildOf(this, childCopyType, targetModule); } private void addMaterialized(final StmtContext<?, ?, ?> template, final Mutable<?, ?, ?> copy) { final HashMap<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> materializedSchemaTree; if (substatements == null) { // Lazy initialization of backing map. We do not expect this to be used often or multiple times -- each hit // here means an inference along schema tree, such as deviate/augment. HashMap requires power-of-two and // defaults to 0.75 load factor -- we therefore size it to 4, i.e. next two inserts will not cause a // resizing operation. materializedSchemaTree = new HashMap<>(4); substatements = materializedSchemaTree; } else { verify(substatements instanceof HashMap, "Unexpected substatements %s", substatements); materializedSchemaTree = castMaterialized(substatements); } final StmtContext<?, ?, ?> existing = materializedSchemaTree.put(template, (StatementContextBase<?, ?, ?>) copy); if (existing != null) { throw new VerifyException( "Unexpected duplicate request for " + copy.argument() + " previous result was " + existing); } } private static @Nullable ReactorStmtCtx<?, ?, ?> findMaterialized( final Map<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> materializedSchemaTree, final StmtContext<?, ?, ?> template) { return materializedSchemaTree == null ? null : materializedSchemaTree.get(template); } @SuppressWarnings("unchecked") private static List<ReactorStmtCtx<?, ?, ?>> castEffective(final Object substatements) { return (List<ReactorStmtCtx<?, ?, ?>>) substatements; } @SuppressWarnings("unchecked") private static HashMap<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>> castMaterialized(final Object substatements) { return (HashMap<StmtContext<?, ?, ?>, ReactorStmtCtx<?, ?, ?>>) substatements; } // Statement copy mess ends here /* * KEEP THINGS ORGANIZED! * * below methods exist in the same form in SubstatementContext. If any adjustment is made here, make sure it is * properly updated there. */ @Override @Deprecated public Optional<SchemaPath> schemaPath() { return substatementGetSchemaPath(); } @Override public A argument() { return argument; } @Override public StatementContextBase<?, ?, ?> getParentContext() { return parent; } @Override public StorageNodeType getStorageNodeType() { return StorageNodeType.STATEMENT_LOCAL; } @Override public StatementContextBase<?, ?, ?> getParentNamespaceStorage() { return parent; } @Override public RootStatementContext<?, ?, ?> getRoot() { return parent.getRoot(); } @Override public EffectiveConfig effectiveConfig() { return effectiveConfig(parent); } @Override protected boolean isIgnoringIfFeatures() { return isIgnoringIfFeatures(parent); } @Override protected boolean isIgnoringConfig() { return isIgnoringConfig(parent); } @Override protected boolean isParentSupportedByFeatures() { return parent.isSupportedByFeatures(); } }
package com.googlecode.jmxtrans.util; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.TreeMap; import org.codehaus.jackson.annotate.JsonIgnore; import com.googlecode.jmxtrans.OutputWriter; /** * Implements the common code for output filters. * * @author jon */ public abstract class BaseOutputWriter implements OutputWriter { public static final String HOST = "host"; public static final String PORT = "port"; public static final String OUTPUT_FILE = "outputFile"; public static final String TEMPLATE_FILE = "templateFile"; public static final String BINARY_PATH = "binaryPath"; public static final String DEBUG = "debug"; public static final String TYPE_NAMES = "typeNames"; private Boolean debugEnabled = null; private Map<String, Object> settings; public void addSetting(String key, Object value) { getSettings().put(key, value); } public Map<String, Object> getSettings() { if (this.settings == null) { this.settings = new TreeMap<String, Object>(); } return this.settings; } public void setSettings(Map<String, Object> settings) { this.settings = settings; } public boolean getBooleanSetting(String key) { Boolean result = null; if (this.getSettings().containsKey(key)) { Object foo = this.getSettings().get(key); if (foo instanceof String) { result = Boolean.valueOf((String)foo); } else if (foo instanceof Boolean) { result = (Boolean)foo; } } return result != null ? result : false; } @JsonIgnore public boolean isDebugEnabled() { if (debugEnabled == null) { return getBooleanSetting(DEBUG); } return debugEnabled != null ? debugEnabled : false; } public void setTypeNames(List<String> typeNames) { this.getSettings().put(TYPE_NAMES, typeNames); } @JsonIgnore @SuppressWarnings("unchecked") public List<String> getTypeNames() { if (!this.getSettings().containsKey(TYPE_NAMES)) { List<String> tmp = new ArrayList<String>(); this.getSettings().put(TYPE_NAMES, tmp); } return (List<String>) this.getSettings().get(TYPE_NAMES); } public void addTypeName(String str) { this.getTypeNames().add(str); } /** * Given a typeName string, get the first match from the typeNames setting. * In other words, suppose you have: * * typeName=name=PS Eden Space,type=MemoryPool * * If you addTypeName("name"), then it'll retrieve 'PS Eden Space' from the string */ protected String getConcatedTypeNameValues(String typeNameStr) { List<String> typeNames = getTypeNames(); if (typeNames == null || typeNames.size() == 0) { return null; } String[] tokens = typeNameStr.split(","); StringBuilder sb = new StringBuilder(); for (String key : typeNames) { String result = getTypeNameValue(key, tokens); if (result != null) { sb.append(result); sb.append("_"); } } return sb.toString(); } private String getTypeNameValue(String typeName, String[] tokens) { boolean foundIt = false; for (String token : tokens) { String[] keys = token.split("="); for (String key : keys) { // we want the next item in the array. if (foundIt) { return key; } if (typeName.equals(key)) { foundIt = true; } } } return null; } /** * Replaces all . with _ and removes all spaces. */ protected String cleanupStr(String name) { if (name == null) { return null; } String clean = name.replace(".", "_"); clean = clean.replace(" ", ""); return clean; } }
package org.csstudio.config.ioconfig.model; import static org.junit.Assert.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.sql.Date; import java.util.HashSet; import java.util.Set; import org.junit.After; import org.junit.Before; import org.junit.Test; public class FacilityDBOTest { @Test public void createFacility() throws PersistenceException{ final DocumentDBO document = new DocumentDBO("subDoc","descDoc","keyDoc"); final Set<DocumentDBO> docs = new HashSet<DocumentDBO>(); docs.add(document); final FacilityDBO facility = CreateFacility("FacNameTest", docs); assertEquals(0,facility.getId()); assertEquals(null, facility.getParent()); assertEquals("Creater", facility.getCreatedBy()); assertEquals(Date.valueOf("2011-11-11"),facility.getCreatedOn()); assertEquals("Updater", facility.getUpdatedBy()); assertEquals(Date.valueOf("2012-12-12"), facility.getUpdatedOn()); assertEquals("description line 1\r\ndescription line 2",facility.getDescription()); assertEquals(docs,facility.getDocuments()); assertEquals("FacNameTest",facility.getName()); assertEquals((short)12, (short) facility.getSortIndex()); assertEquals(11,facility.getVersion()); facility.localSave(); assertTrue(facility.getId()>0); assertEquals(null, facility.getParent()); assertEquals("Creater", facility.getCreatedBy()); assertEquals(Date.valueOf("2011-11-11"),facility.getCreatedOn()); assertEquals("Updater", facility.getUpdatedBy()); assertEquals(Date.valueOf("2012-12-12"), facility.getUpdatedOn()); assertEquals("description line 1\r\ndescription line 2",facility.getDescription()); assertEquals(docs,facility.getDocuments()); assertEquals("FacNameTest",facility.getName()); assertEquals((short)12, (short) facility.getSortIndex()); assertEquals(11,facility.getVersion()); } @Test public void compareFacilitys() throws Exception { final DocumentDBO document = new DocumentDBO("subDoc","descDoc","keyDoc"); final Set<DocumentDBO> docs = new HashSet<DocumentDBO>(); docs.add(document); final FacilityDBO facility1 = CreateFacility("FacNameTest1", docs); final FacilityDBO facility2 = CreateFacility("FacNameTest2", docs); facility1.localSave(); facility2.localSave(); assertTrue(facility1.equals(facility1)); assertTrue(facility2.equals(facility2)); assertFalse(facility1.equals(facility2)); assertFalse(facility2.equals(facility1)); assertEquals(facility1, facility1); assertEquals(facility2, facility2); assertNotSame(facility1, facility2); assertNotSame(facility2, facility1); assertFalse(0==facility1.compareTo(facility2)); assertFalse(0==facility2.compareTo(facility1)); } /** * @param string * @param docs * @return */ private FacilityDBO CreateFacility(String string, Set<DocumentDBO> docs) { final FacilityDBO facility = new FacilityDBO(); facility.setCreatedBy("Creater"); facility.setCreatedOn(Date.valueOf("2011-11-11")); facility.setUpdatedBy("Updater"); facility.setUpdatedOn(Date.valueOf("2012-12-12")); facility.setDescription("description line 1\r\ndescription line 2"); facility.setDocuments(docs); facility.setName("FacNameTest"); facility.setSortIndexNonHibernate((short)12); facility.setVersion(11); return facility; } @Before public void setUp() throws Exception { Repository.injectIRepository(new DummyRepository()); } @After public void setDown() { Repository.injectIRepository(null); } }
package com.matthewtamlin.spyglass.processor.validation; import com.matthewtamlin.java_utilities.testing.Tested; import com.matthewtamlin.spyglass.processor.annotation_utils.CallHandlerAnnoUtil; import com.matthewtamlin.spyglass.processor.annotation_utils.DefaultAnnoUtil; import com.matthewtamlin.spyglass.processor.annotation_utils.UseAnnoUtil; import com.matthewtamlin.spyglass.processor.annotation_utils.ValueHandlerAnnoUtil; import com.matthewtamlin.spyglass.processor.mirror_utils.TypeMirrorHelper; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.NestingKind; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import static com.matthewtamlin.java_utilities.checkers.NullChecker.checkNotNull; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.STATIC; @Tested(testMethod = "automated") public class Validator { private final List<Rule> rules = new ArrayList<>(); { // Check element is a method rules.add(new Rule() { @Override public void checkElement(final Element element) throws ValidationException { if (element.getKind() != ElementKind.METHOD) { final String message = "Spyglass annotations must only be applied to methods."; throw new ValidationException(message); } } }); // Check for multiple handler annotations rules.add(new Rule() { @Override public void checkElement(final Element element) throws ValidationException { if (countCombinedHandlerAnnotations(element) > 1) { final String message = "Methods must not have multiple handler annotations."; throw new ValidationException(message); } } }); // Check for multiple default annotations rules.add(new Rule() { @Override public void checkElement(final Element element) throws ValidationException { if (countDefaultAnnotations(element) > 1) { final String message = "Methods must not have multiple default annotations."; throw new ValidationException(message); } } }); // Check for a default annotation without a handler annotation rules.add(new Rule() { @Override public void checkElement(final Element element) throws ValidationException { final int handlerCount = countCombinedHandlerAnnotations(element); final int defaultCount = countDefaultAnnotations(element); if (handlerCount == 0 && defaultCount == 1) { final String message = "Methods without handler annotations must not have default annotations."; throw new ValidationException(message); } } }); // Check for call handlers with defaults rules.add(new Rule() { @Override public void checkElement(final Element element) throws ValidationException { final int callHandlerCount = countCallHandlerAnnotations(element); final int defaultCount = countDefaultAnnotations(element); if (callHandlerCount == 1 && defaultCount == 1) { final String message = "Methods with handlers annotations that pass no value must not have " + "default annotations."; throw new ValidationException(message); } } }); // Check parameter count exceeds 1 minimum for value handlers rules.add(new Rule() { @Override public void checkElement(final Element element) throws ValidationException { if (countValueHandlerAnnotations(element) == 1) { final int paramCount = ((ExecutableElement) element).getParameters().size(); if (paramCount < 1) { final String message = "Methods with handler annotations that pass a value must have at least" + " one parameter."; throw new ValidationException(message); } } } }); // Check for parameters with multiple use annotations rules.add(new Rule() { @Override public void checkElement(final Element element) throws ValidationException { final Map<Integer, Set<Annotation>> useAnnotations = getUseAnnotations( (ExecutableElement) element); for (final Integer paramIndex : useAnnotations.keySet()) { if (useAnnotations.get(paramIndex).size() > 1) { final String message = "Parameters must not have multiple use annotations."; throw new ValidationException(message); } } } }); // Check correct number of parameters have use annotations (value handlers case) rules.add(new Rule() { @Override public void checkElement(final Element element) throws ValidationException { if (countValueHandlerAnnotations(element) == 1) { final int paramCount = ((ExecutableElement) element).getParameters().size(); final int annotatedParamCount = countNonEmptySets( getUseAnnotations((ExecutableElement) element).values()); if (annotatedParamCount != paramCount - 1) { final String message = "Methods with handler annotations which pass a value must have use " + "annotations on every parameter except one."; throw new ValidationException(message); } } } }); // Check correct number of parameters have use annotations (call handlers case) rules.add(new Rule() { @Override public void checkElement(final Element element) throws ValidationException { if (countCallHandlerAnnotations(element) == 1) { final int paramCount = ((ExecutableElement) element).getParameters().size(); final int annotatedParamCount = countNonEmptySets( getUseAnnotations((ExecutableElement) element).values()); if (annotatedParamCount != paramCount) { final String message = "Methods with handler annotations which pass no value must have " + "use annotations on every parameter."; throw new ValidationException(message); } } } }); // Check correct modifiers are applied to annotation methods rules.add(new Rule() { @Override public void checkElement(final Element element) throws ValidationException { if (element.getModifiers().contains(PRIVATE)) { throw new ValidationException("Methods with handler annotations must have public, protected, or " + "default access. Private methods are not compatible with the Spyglass Framework."); } } }); // Check for methods which are members of non-static inner classes (recursively) rules.add(new Rule() { @Override public void checkElement(final Element element) throws ValidationException { if (!checkParentsRecursively(element)) { throw new ValidationException("Methods with handler annotations must be accessible from static " + "context."); } } private boolean checkParentsRecursively(final Element element) { final TypeElement parent = (TypeElement) element.getEnclosingElement(); if (parent == null) { // Input was a top level class return true; } else if (parent.getNestingKind() == NestingKind.TOP_LEVEL) { return true; } else if (parent.getNestingKind() == NestingKind.MEMBER) { // The enclosing element must be static, and its parents must also be valid return parent.getModifiers().contains(STATIC); } else if (parent.getNestingKind() == NestingKind.LOCAL) { return false; } else if (parent.getNestingKind() == NestingKind.ANONYMOUS) { return false; } else { throw new RuntimeException("This should never happen."); } } }); } private TypeMirrorHelper typeMirrorHelper; public Validator(final TypeMirrorHelper typeMirrorHelper) { this.typeMirrorHelper = checkNotNull(typeMirrorHelper, "Argument \'typeMirrorHelper\' cannot be null."); } public void validateElement(final Element element) throws ValidationException { for (final Rule rule : rules) { rule.checkElement(element); } } private static int countCallHandlerAnnotations(final Element e) { int count = 0; for (final Class<? extends Annotation> annotation : CallHandlerAnnoUtil.getClasses()) { if (e.getAnnotation(annotation) != null) { count++; } } return count; } private static int countValueHandlerAnnotations(final Element e) { int count = 0; for (final Class<? extends Annotation> annotation : ValueHandlerAnnoUtil.getClasses()) { if (e.getAnnotation(annotation) != null) { count++; } } return count; } private static int countCombinedHandlerAnnotations(final Element e) { return countCallHandlerAnnotations(e) + countValueHandlerAnnotations(e); } private static int countDefaultAnnotations(final Element e) { int count = 0; for (final Class<? extends Annotation> annotation : DefaultAnnoUtil.getClasses()) { if (e.getAnnotation(annotation) != null) { count++; } } return count; } private static Map<Integer, Set<Annotation>> getUseAnnotations( final ExecutableElement element) { final Map<Integer, Set<Annotation>> useAnnotations = new HashMap<>(); final List<? extends VariableElement> params = element.getParameters(); for (int i = 0; i < params.size(); i++) { useAnnotations.put(i, new HashSet<Annotation>()); for (final Class<? extends Annotation> annotation : UseAnnoUtil.getClasses()) { final Annotation foundAnnotation = params.get(i).getAnnotation(annotation); if (foundAnnotation != null) { useAnnotations.get(i).add(foundAnnotation); } } } return useAnnotations; } private static int countNonEmptySets(final Collection<? extends Set> collection) { int count = 0; for (final Set<?> s : collection) { if (!s.isEmpty()) { count++; } } return count; } private interface Rule { public void checkElement(Element element) throws ValidationException; } private Validator() { throw new RuntimeException("Util class. Do not instantiate."); } }
package org.openhab.binding.fritzboxtr064.internal; import static java.util.Collections.singleton; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.namespace.QName; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.soap.Detail; import javax.xml.soap.MessageFactory; import javax.xml.soap.Name; import javax.xml.soap.SOAPBody; import javax.xml.soap.SOAPBodyElement; import javax.xml.soap.SOAPElement; import javax.xml.soap.SOAPEnvelope; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPFault; import javax.xml.soap.SOAPHeader; import javax.xml.soap.SOAPMessage; import javax.xml.soap.SOAPPart; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.apache.commons.lang.WordUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.AuthCache; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.CookieStore; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.client.utils.URIBuilder; import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.TrustSelfSignedStrategy; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.auth.DigestScheme; import org.apache.http.impl.client.BasicAuthCache; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.ssl.SSLContextBuilder; import org.apache.http.util.EntityUtils; import org.openhab.core.types.Command; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * Controls communication and parsing for TR064 communication with FritzBox. * * @author gitbock * @version 1.8.0 */ public class Tr064Comm { private static final Logger logger = LoggerFactory.getLogger(Tr064Comm.class); private static final String DEFAULTUSER = "dslf-config"; // is used when no username is provided. private static final String TR064DOWNLOADFILE = "tr64desc.xml"; // filename of all available TR064 on fbox // access details for fbox private String _url = null; private String _user = null; private String _pw = null; // all services fbox offers mapped by service id private Map<String, Tr064Service> _allServices = null; // mappig table for mapping item command to tr064 parameters private Map<String, ItemMap> _allItemMap = null; // http client object used to communicate with fbox (needed for reading/writing // soap requests) private CloseableHttpClient _httpClient = null; private HttpClientContext _httpClientContext = null; // for reusing auth (?) public Tr064Comm(String _url, String user, String pass) { // base URL from config this._url = _url; this._user = user; this._pw = pass; _allServices = new HashMap<>(); _allItemMap = new HashMap<>(); init(); } public String getUrl() { return _url; } public void setUrl(String _url) { this._url = _url; } public String getUser() { return _user; } public void setUser(String _user) { this._user = _user; } public String getPw() { return _pw; } public void setPw(String _pw) { this._pw = _pw; } /** * Makes sure all values are set properly before starting communications. */ private void init() { if (_user == null) { _user = DEFAULTUSER; } if (_httpClient == null) { _httpClient = createTr064HttpClient(_url); // create http client used for communication } if (_allServices.isEmpty()) { // no services are known yet? readAllServices(); // can be done w/out item mappings and w/out auth } if (_allItemMap.isEmpty()) { // no mappings present yet? generateItemMappings(); } } public String getTr064Value(ItemConfiguration request) { Map<ItemConfiguration, String> values = getTr064Values(singleton(request)); return values.get(request); } /** * Fetches the values for the given item configurations from the FritzBox. Calls * the FritzBox SOAP services delivering the values for the item configurations. * The resulting map contains the values of all item configurations returned by * the invoked services. This can be more items than were given as parameter. * * @param request * string from config including the command and optional parameters * @return Parsed values for all item configurations returned by the invoked * services. */ public Map<ItemConfiguration, String> getTr064Values(Collection<ItemConfiguration> itemConfigurations) { Map<ItemConfiguration, String> values = new HashMap<>(); for (ItemConfiguration itemConfiguration : itemConfigurations) { String itemCommand = itemConfiguration.getItemCommand(); if (values.containsKey(itemCommand)) { // item value already read by earlier MultiItemMap continue; } // search for proper item Mapping ItemMap itemMap = determineItemMappingByItemCommand(itemCommand); if (itemMap == null) { logger.warn("No item mapping found for {}. Function not implemented by your FritzBox (?)", itemConfiguration); continue; } // determine which url etc. to connect to for accessing required value Tr064Service tr064service = determineServiceByItemMapping(itemMap); // construct soap Body which is added to soap msg later SOAPBodyElement bodyData = null; // holds data to be sent to fbox try { MessageFactory mf = MessageFactory.newInstance(); SOAPMessage msg = mf.createMessage(); // empty message SOAPBody body = msg.getSOAPBody(); // std. SAOP body QName bodyName = new QName(tr064service.getServiceType(), itemMap.getReadServiceCommand(), "u"); // header // for // body // element bodyData = body.addBodyElement(bodyName); // only if input parameter is present if (itemMap instanceof ParametrizedItemMap) { for (InputArgument inputArgument : ((ParametrizedItemMap) itemMap) .getConfigInputArguments(itemConfiguration)) { String dataInName = inputArgument.getName(); String dataInValue = inputArgument.getValue(); QName dataNode = new QName(dataInName); SOAPElement beDataNode = bodyData.addChildElement(dataNode); // if input is mac address, replace "-" with ":" as fbox wants if (itemConfiguration.getItemCommand().equals("maconline")) { dataInValue = dataInValue.replaceAll("-", ":"); } beDataNode.addTextNode(dataInValue); // add data which should be requested from fbox for this // service } } logger.trace("Raw SOAP Request to be sent to FritzBox: {}", soapToString(msg)); } catch (Exception e) { logger.warn("Error constructing request SOAP msg for getting parameter. {}", e.getMessage()); logger.debug("Request was: {}", itemConfiguration); } if (bodyData == null) { logger.warn("Could not determine data to be sent to FritzBox!"); return null; } SOAPMessage smTr064Request = constructTr064Msg(bodyData); // construct entire msg with body element String soapActionHeader = tr064service.getServiceType() + "#" + itemMap.getReadServiceCommand(); // needed // to be // sent // with // request // (not // in body // header) SOAPMessage response = readSoapResponse(soapActionHeader, smTr064Request, _url + tr064service.getControlUrl()); logger.trace("Raw SOAP Response from FritzBox: {}", soapToString(response)); if (response == null) { logger.warn("Error retrieving SOAP response from FritzBox"); continue; } values.putAll( itemMap.getSoapValueParser().parseValuesFromSoapMessage(response, itemMap, itemConfiguration)); } return values; } /** * Sets a parameter in fbox. Called from event bus. * * @param request * config string from itemconfig * @param cmd * command to set */ public void setTr064Value(ItemConfiguration request, Command cmd) { String itemCommand = request.getItemCommand(); // search for proper item Mapping ItemMap itemMapForCommand = determineItemMappingByItemCommand(itemCommand); if (!(itemMapForCommand instanceof WritableItemMap)) { logger.warn("Item command {} does not support setting values", itemCommand); return; } WritableItemMap itemMap = (WritableItemMap) itemMapForCommand; Tr064Service tr064service = determineServiceByItemMapping(itemMap); // determine which url etc. to connect to for accessing required value // construct soap Body which is added to soap msg later SOAPBodyElement bodyData = null; // holds data to be sent to fbox try { MessageFactory mf = MessageFactory.newInstance(); SOAPMessage msg = mf.createMessage(); // empty message SOAPBody body = msg.getSOAPBody(); // std. SAOP body QName bodyName = new QName(tr064service.getServiceType(), itemMap.getWriteServiceCommand(), "u"); // header // for // body // element bodyData = body.addBodyElement(bodyName); List<InputArgument> writeInputArguments = new ArrayList<>(); writeInputArguments.add(itemMap.getWriteInputArgument(cmd)); if (itemMap instanceof ParametrizedItemMap) { writeInputArguments.addAll(((ParametrizedItemMap) itemMap).getConfigInputArguments(request)); } for (InputArgument inputArgument : writeInputArguments) { QName dataNode = new QName(inputArgument.getName()); SOAPElement beDataNode = bodyData.addChildElement(dataNode); beDataNode.addTextNode(inputArgument.getValue()); } logger.debug("SOAP Msg to send to FritzBox for setting data: {}", soapToString(msg)); } catch (Exception e) { logger.error("Error constructing request SOAP msg for setting parameter. {}", e.getMessage()); logger.debug("Request was: {}. Command was: {}.", request, cmd.toString()); } if (bodyData == null) { logger.error("Could not determine data to be sent to FritzBox!"); return; } SOAPMessage smTr064Request = constructTr064Msg(bodyData); // construct entire msg with body element String soapActionHeader = tr064service.getServiceType() + "#" + itemMap.getWriteServiceCommand(); // needed to // be sent // with // request // (not in // body -> // header) SOAPMessage response = readSoapResponse(soapActionHeader, smTr064Request, _url + tr064service.getControlUrl()); if (response == null) { logger.error("Error retrieving SOAP response from FritzBox"); return; } logger.debug("SOAP response from FritzBox: {}", soapToString(response)); // Check if error received try { if (response.getSOAPBody().getFault() != null) { logger.error("Error received from FritzBox while trying to set parameter"); logger.debug("Soap Response was: {}", soapToString(response)); } } catch (SOAPException e) { logger.error("Could not parse soap response from FritzBox while setting parameter. {}", e.getMessage()); logger.debug("Soap Response was: {}", soapToString(response)); } } /** * Creates an Apache HTTP Client object, ignoring SSL Exceptions like self signed * certificates, and sets Auth. Scheme to Digest Auth. * * @param fboxUrl * the URL from config file of fbox to connect to * @return the ready-to-use httpclient for tr064 requests */ private synchronized CloseableHttpClient createTr064HttpClient(String fboxUrl) { CloseableHttpClient hc = null; // Convert URL String from config in easy explotable URI object URIBuilder uriFbox = null; try { uriFbox = new URIBuilder(fboxUrl); } catch (URISyntaxException e) { logger.error("Invalid FritzBox URL! {}", e.getMessage()); return null; } // Create context of the http client _httpClientContext = HttpClientContext.create(); CookieStore cookieStore = new BasicCookieStore(); _httpClientContext.setCookieStore(cookieStore); // SETUP AUTH // Auth is specific for this target HttpHost target = new HttpHost(uriFbox.getHost(), uriFbox.getPort(), uriFbox.getScheme()); // Add digest authentication with username/pw from global config CredentialsProvider credp = new BasicCredentialsProvider(); credp.setCredentials(new AuthScope(target.getHostName(), target.getPort()), new UsernamePasswordCredentials(_user, _pw)); // Create AuthCache instance. Manages authentication based on server response AuthCache authCache = new BasicAuthCache(); // Generate DIGEST scheme object, initialize it and add it to the local auth // cache. Digeste is standard for fbox auth SOAP DigestScheme digestAuth = new DigestScheme(); digestAuth.overrideParamter("realm", "HTTPS Access"); // known from fbox specification digestAuth.overrideParamter("nonce", ""); // never known at first request authCache.put(target, digestAuth); // Add AuthCache to the execution context _httpClientContext.setAuthCache(authCache); // SETUP SSL TRUST SSLContextBuilder sslContextBuilder = new SSLContextBuilder(); SSLConnectionSocketFactory sslsf = null; try { sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); // accept self signed certs // dont verify hostname against cert CN sslsf = new SSLConnectionSocketFactory(sslContextBuilder.build(), null, null, new NoopHostnameVerifier()); } catch (Exception ex) { logger.error(ex.getMessage()); } // Set timeout values RequestConfig rc = RequestConfig.copy(RequestConfig.DEFAULT).setSocketTimeout(4000).setConnectTimeout(4000) .setConnectionRequestTimeout(4000).build(); // BUILDER // setup builder with parameters defined before hc = HttpClientBuilder.create().setSSLSocketFactory(sslsf) // set the SSL options which trust every self signed // cert .setDefaultCredentialsProvider(credp) // set auth options using digest .setDefaultRequestConfig(rc) // set the request config specifying timeout .build(); return hc; } /** * Converts SOAP message into string. * * @param sm * @return */ public static String soapToString(SOAPMessage sm) { String strMsg = ""; try { ByteArrayOutputStream xmlStream = new ByteArrayOutputStream(); sm.writeTo(xmlStream); strMsg = new String(xmlStream.toByteArray()); } catch (Exception e) { logger.debug("Not able to parse SOAP message: {}", sm, e); } return strMsg; } /** * * @param soapActionHeader * String in HTTP Header. specific for each TR064 service * @param request * the SOAPMEssage Object to send to fbox as request * @param serviceUrl * URL to sent the SOAP Message to (service specific) * @return */ private SOAPMessage readSoapResponse(String soapActionHeader, SOAPMessage request, String serviceUrl) { SOAPMessage response = null; // Soap Body to post HttpPost postSoap = new HttpPost(serviceUrl); // url is service specific postSoap.addHeader("SOAPAction", soapActionHeader); // add the Header specific for this request HttpEntity entBody = null; HttpResponse resp = null; // stores raw response from fbox boolean exceptionOccurred = false; try { entBody = new StringEntity(soapToString(request), ContentType.create("text/xml", "UTF-8")); // add body postSoap.setEntity(entBody); synchronized (_httpClient) { resp = _httpClient.execute(postSoap, _httpClientContext); } // Fetch content data StatusLine slResponse = resp.getStatusLine(); HttpEntity heResponse = resp.getEntity(); // Check for (auth-) error if (slResponse.getStatusCode() == 401) { logger.warn( "Could not read response from FritzBox. Unauthorized! Check user and password in config. " + "Verify configured user for tr064 requests. Reason from Fritzbox was: {}", slResponse.getReasonPhrase()); postSoap.releaseConnection(); resetHttpClient(); return null; } // Parse response into SOAP Message response = MessageFactory.newInstance().createMessage(null, heResponse.getContent()); } catch (UnsupportedEncodingException e) { logger.error("Encoding not supported: {}", e.getMessage().toString()); exceptionOccurred = true; } catch (ClientProtocolException e) { logger.error("Client Protocol not supported: {}", e.getMessage().toString()); exceptionOccurred = true; } catch (IOException e) { logger.error("Cannot send/receive: {}", e.getMessage().toString()); exceptionOccurred = true; } catch (UnsupportedOperationException e) { logger.error("Operation unsupported: {}", e.getMessage().toString()); response = null; exceptionOccurred = true; } catch (SOAPException e) { logger.error("SOAP Error: {}", e.getMessage().toString()); exceptionOccurred = true; } finally { // Make sure connection is released. If error occurred make sure to print in log if (exceptionOccurred) { logger.warn("Releasing connection to FritzBox because of error."); resetHttpClient(); } else { logger.debug("Releasing connection"); } postSoap.releaseConnection(); } return response; } /** * In case of failure, reset the authentication state, close connection and init * again. */ private void resetHttpClient() { logger.trace("Drop client for fritzbox and setup connection again."); if (_httpClientContext.getTargetAuthState() != null) { _httpClientContext.getTargetAuthState().reset(); } try { _httpClient.close(); } catch (IOException e) { logger.debug("Failed to close connection to fritzbox at {}. " + "This might result in still open, but dead connections waiting for a timeout.", _url, e); } _httpClient = createTr064HttpClient(_url); } /** * Sets all required namespaces and prepares the SOAP message to send. * Creates skeleton + body data. * * @param bodyData * is attached to skeleton to form entire SOAP message * @return ready to send SOAP message */ private SOAPMessage constructTr064Msg(SOAPBodyElement bodyData) { SOAPMessage soapMsg = null; try { MessageFactory msgFac; msgFac = MessageFactory.newInstance(); soapMsg = msgFac.createMessage(); soapMsg.setProperty(SOAPMessage.WRITE_XML_DECLARATION, "true"); soapMsg.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, "UTF-8"); SOAPPart part = soapMsg.getSOAPPart(); // valid for entire SOAP msg String namespace = "s"; // create suitable fbox envelope SOAPEnvelope envelope = part.getEnvelope(); envelope.setPrefix(namespace); envelope.removeNamespaceDeclaration("SOAP-ENV"); // delete standard namespace which was already set envelope.addNamespaceDeclaration(namespace, "http://schemas.xmlsoap.org/soap/envelope/"); Name nEncoding = envelope.createName("encodingStyle", namespace, "http://schemas.xmlsoap.org/soap/encoding/"); envelope.addAttribute(nEncoding, "http://schemas.xmlsoap.org/soap/encoding/"); // create empty header SOAPHeader header = envelope.getHeader(); header.setPrefix(namespace); // create body with command based on parameter SOAPBody body = envelope.getBody(); body.setPrefix(namespace); body.addChildElement(bodyData); // bodyData already prepared. Needs only be added } catch (Exception e) { logger.error("Error creating SOAP message for fbox request with data {}", bodyData); e.printStackTrace(); } return soapMsg; } /** * Looks for the proper item mapping for the item command given from item file. * * @param itemCommand * String item command * @return found itemMap object if found, or null */ private ItemMap determineItemMappingByItemCommand(String itemCommand) { ItemMap foundMapping = _allItemMap.get(itemCommand); if (foundMapping == null) { logger.error("No mapping found for item command {}", itemCommand); } return foundMapping; } /** * Determines Service including which URL to connect to for value request. * * @param the * itemmap for which the service is searched * @return the found service or null */ private Tr064Service determineServiceByItemMapping(ItemMap mapping) { Tr064Service foundService = _allServices.get(mapping.getServiceId()); if (foundService == null) { logger.warn("No tr064 service found for service id {}", mapping.getServiceId()); } return foundService; } /** * Connects to fbox service xml to get a list of all services which are offered * by TR064. Saves it into local list. */ private void readAllServices() { Document xml = getFboxXmlResponse(_url + "/" + TR064DOWNLOADFILE); if (xml == null) { logger.error("Could not read xml response services"); return; } NodeList nlServices = xml.getElementsByTagName("service"); // get all service nodes Node currentNode = null; XPath xPath = XPathFactory.newInstance().newXPath(); for (int i = 0; i < nlServices.getLength(); i++) { // iterate over all services fbox offered us currentNode = nlServices.item(i); Tr064Service trS = new Tr064Service(); try { trS.setControlUrl((String) xPath.evaluate("controlURL", currentNode, XPathConstants.STRING)); trS.setEventSubUrl((String) xPath.evaluate("eventSubURL", currentNode, XPathConstants.STRING)); trS.setScpdurl((String) xPath.evaluate("SCPDURL", currentNode, XPathConstants.STRING)); trS.setServiceId((String) xPath.evaluate("serviceId", currentNode, XPathConstants.STRING)); trS.setServiceType((String) xPath.evaluate("serviceType", currentNode, XPathConstants.STRING)); } catch (XPathExpressionException e) { logger.debug("Could not parse service {}", currentNode.getTextContent()); e.printStackTrace(); } _allServices.put(trS.getServiceId(), trS); } } /** * Populates local static mapping table. * Sets the parser based on the itemcommand -> soap value parser "svp" * anonymous method for each mapping. */ // TODO: refactor to read from config file later? private void generateItemMappings() { // services available from fbox. Needed for e.g. wifi select 5GHz/Guest Wifi if (_allServices.isEmpty()) { // no services are known yet? readAllServices(); } // Mac Online Checker SingleItemMap imMacOnline = SingleItemMap.builder().itemCommand("maconline") .serviceId("urn:LanDeviceHosts-com:serviceId:Hosts1").itemArgumentName("NewActive") .configArgumentNames("NewMACAddress").readServiceCommand("GetSpecificHostEntry") .soapValueParser(new SoapValueParser() { @Override protected String parseValueFromSoapFault(ItemConfiguration itemConfiguration, SOAPFault soapFault, ItemMap mapping) { String value = null; Detail detail = soapFault.getDetail(); if (detail != null) { NodeList nlErrorCode = detail.getElementsByTagName("errorCode"); Node nErrorCode = nlErrorCode.item(0); String errorCode = nErrorCode.getTextContent(); if (errorCode.equals("714")) { value = "MAC not known to FritzBox!"; logger.debug(value); } } if (value == null) { value = super.parseValueFromSoapFault(itemConfiguration, soapFault, mapping); } return value; } }).build(); addItemMap(imMacOnline); addItemMap(new MultiItemMap(Arrays.asList("modelName", "manufacturerName", "softwareVersion", "serialNumber"), "GetInfo", "urn:DeviceInfo-com:serviceId:DeviceInfo1", name -> "New" + WordUtils.capitalize(name))); addItemMap(SingleItemMap.builder().itemCommand("wanip") .serviceId("urn:WANPPPConnection-com:serviceId:WANPPPConnection1") .itemArgumentName("NewExternalIPAddress").readServiceCommand("GetExternalIPAddress").build()); addItemMap(SingleItemMap.builder().itemCommand("externalWanip") .serviceId("urn:WANIPConnection-com:serviceId:WANIPConnection1") .itemArgumentName("NewExternalIPAddress").readServiceCommand("GetExternalIPAddress").build()); // WAN Status addItemMap(new MultiItemMap( Arrays.asList("wanWANAccessType", "wanLayer1UpstreamMaxBitRate", "wanLayer1DownstreamMaxBitRate", "wanPhysicalLinkStatus"), "GetCommonLinkProperties", "urn:WANCIfConfig-com:serviceId:WANCommonInterfaceConfig1", name -> name.replace("wan", "New"))); addItemMap(SingleItemMap.builder().itemCommand("wanTotalBytesSent") .serviceId("urn:WANCIfConfig-com:serviceId:WANCommonInterfaceConfig1") .itemArgumentName("NewTotalBytesSent").readServiceCommand("GetTotalBytesSent").build()); addItemMap(SingleItemMap.builder().itemCommand("wanTotalBytesReceived") .serviceId("urn:WANCIfConfig-com:serviceId:WANCommonInterfaceConfig1") .itemArgumentName("NewTotalBytesReceived").readServiceCommand("GetTotalBytesReceived").build()); // DSL Status addItemMap(new MultiItemMap( Arrays.asList("dslEnable", "dslStatus", "dslUpstreamCurrRate", "dslDownstreamCurrRate", "dslUpstreamMaxRate", "dslDownstreamMaxRate", "dslUpstreamNoiseMargin", "dslDownstreamNoiseMargin", "dslUpstreamAttenuation", "dslDownstreamAttenuation"), "GetInfo", "urn:WANDSLIfConfig-com:serviceId:WANDSLInterfaceConfig1", name -> name.replace("dsl", "New"))); addItemMap(new MultiItemMap(Arrays.asList("dslFECErrors", "dslHECErrors", "dslCRCErrors"), "GetStatisticsTotal", "urn:WANDSLIfConfig-com:serviceId:WANDSLInterfaceConfig1", name -> name.replace("dsl", "New"))); // Wifi 2,4GHz SingleItemMap imWifi24Switch = SingleItemMap.builder().itemCommand("wifi24Switch") .serviceId("urn:WLANConfiguration-com:serviceId:WLANConfiguration1").itemArgumentName("NewEnable") .readServiceCommand("GetInfo").writeServiceCommand("SetEnable").build(); addItemMap(imWifi24Switch); // wifi 5GHz SingleItemMap imWifi50Switch = SingleItemMap.builder().itemCommand("wifi50Switch") .serviceId("urn:WLANConfiguration-com:serviceId:WLANConfiguration2").itemArgumentName("NewEnable") .readServiceCommand("GetInfo").writeServiceCommand("SetEnable").build(); // guest wifi SingleItemMap imWifiGuestSwitch = SingleItemMap.builder().itemCommand("wifiGuestSwitch") .serviceId("urn:WLANConfiguration-com:serviceId:WLANConfiguration3").itemArgumentName("NewEnable") .readServiceCommand("GetInfo").writeServiceCommand("SetEnable").build(); // check if 5GHz wifi and/or guest wifi is available. Tr064Service svc5GHzWifi = determineServiceByItemMapping(imWifi50Switch); Tr064Service svcGuestWifi = determineServiceByItemMapping(imWifiGuestSwitch); if (svc5GHzWifi != null && svcGuestWifi != null) { // WLANConfiguration3+2 present -> guest wifi + 5Ghz present // prepared properly, only needs to be added addItemMap(imWifi50Switch); addItemMap(imWifiGuestSwitch); logger.debug("Found 2,4 Ghz, 5Ghz and Guest Wifi"); } if (svc5GHzWifi != null && svcGuestWifi == null) { // WLANConfiguration3 not present but 2 -> no 5Ghz Wifi // available but Guest Wifi // remap itemMap for Guest Wifi from 3 to 2 imWifiGuestSwitch.setServiceId("urn:WLANConfiguration-com:serviceId:WLANConfiguration2"); addItemMap(imWifiGuestSwitch);// only add guest wifi, no 5Ghz logger.debug("Found 2,4 Ghz and Guest Wifi"); } if (svc5GHzWifi == null && svcGuestWifi == null) { // WLANConfiguration3+2 not present > no 5Ghz Wifi or Guest // Wifi logger.debug("Found 2,4 Ghz Wifi"); } // Phonebook Download // itemcommand is dummy: not a real item ItemMap imPhonebook = SingleItemMap.builder().itemCommand("phonebook") .serviceId("urn:X_AVM-DE_OnTel-com:serviceId:X_AVM-DE_OnTel1").configArgumentNames("NewPhonebookID") .itemArgumentName("NewPhonebookURL").readServiceCommand("GetPhonebook").build(); addItemMap(imPhonebook); // TAM (telephone answering machine) Switch SingleItemMap imTamSwitch = SingleItemMap.builder().itemCommand("tamSwitch") .serviceId("urn:X_AVM-DE_TAM-com:serviceId:X_AVM-DE_TAM1").configArgumentNames("NewIndex") .itemArgumentName("NewEnable").readServiceCommand("GetInfo").writeServiceCommand("SetEnable").build(); addItemMap(imTamSwitch); // New Messages per TAM ID // two requests needed: First gets URL to download tam info from, 2nd contains // info of messages SingleItemMap imTamNewMessages = SingleItemMap.builder().itemCommand("tamNewMessages") .serviceId("urn:X_AVM-DE_TAM-com:serviceId:X_AVM-DE_TAM1").configArgumentNames("NewIndex") .itemArgumentName("NewURL").readServiceCommand("GetMessageList").soapValueParser(new SoapValueParser() { @Override protected String parseValueFromSoapBody(ItemConfiguration itemConfiguration, SOAPBody soapBody, ItemMap mapping) { String value = null; // extract URL from soap response String url = super.parseValueFromSoapBody(itemConfiguration, soapBody, mapping); if (url != null) { Document xmlTamInfo = getFboxXmlResponse(url); if (xmlTamInfo != null) { logger.debug("Parsing xml message TAM info {}", Helper.documentToString(xmlTamInfo)); NodeList nlNews = xmlTamInfo.getElementsByTagName("New"); // get all Nodes containing // "new", indicating message // was not listened to // When <new> contains 1 -> message is new, when 0, message not new -> Counting int newMessages = 0; for (int i = 0; i < nlNews.getLength(); i++) { if (nlNews.item(i).getTextContent().equals("1")) { newMessages++; } } value = Integer.toString(newMessages); logger.debug("Parsed new messages as: {}", value); } else { logger.warn("Failed to read TAM info from URL {}", url); // cause was already logged earlier } } return value; } }).build(); addItemMap(imTamNewMessages); // Missed calls // two requests: 1st fetches URL to download call list, 2nd fetches xml call // list SingleItemMap imMissedCalls = SingleItemMap.builder().itemCommand("missedCallsInDays") .serviceId("urn:X_AVM-DE_OnTel-com:serviceId:X_AVM-DE_OnTel1").itemArgumentName("NewCallListURL") .readServiceCommand("GetCallList").configArgumentNames("NewDays") .soapValueParser(new SoapValueParser() { @Override protected String parseValueFromSoapBody(ItemConfiguration itemConfiguration, SOAPBody soapBody, ItemMap mapping) { String value = null; // extract URL from soap response String url = super.parseValueFromSoapBody(itemConfiguration, soapBody, mapping); // extract how many days of call list should be examined for missed calls String days = "3"; // default if (!itemConfiguration.getArgumentValues().isEmpty()) { days = itemConfiguration.getArgumentValues().get(0); // set the days as defined in item // config. // Otherwise default value of 3 is used } if (url != null) { // only get missed calls of the last x days url = url + "&days=" + days; logger.debug("Downloading call list using url {}", url); Document callListInfo = getFboxXmlResponse(url); // download call list if (callListInfo != null) { logger.debug("Parsing xml message call list info {}", Helper.documentToString(callListInfo)); NodeList nlTypes = callListInfo.getElementsByTagName("Type"); // get all Nodes // containing "Type". Type // 2 => missed // When <type> contains 2 -> call was missed -> Counting only 2 entries int missedCalls = 0; for (int i = 0; i < nlTypes.getLength(); i++) { if (nlTypes.item(i).getTextContent().equals("2")) { missedCalls++; } } value = Integer.toString(missedCalls); logger.debug("Parsed new messages as: {}", value); } else { logger.warn("Failed to read call list info from URL {}", url); // cause was already logged earlier } } return value; } }).build(); addItemMap(imMissedCalls); // call deflection SingleItemMap callDeflection = SingleItemMap.builder().itemCommand("callDeflectionSwitch") .serviceId("urn:X_AVM-DE_OnTel-com:serviceId:X_AVM-DE_OnTel1").configArgumentNames("NewDeflectionId") .itemArgumentName("NewEnable").readServiceCommand("GetDeflection") .writeServiceCommand("SetDeflectionEnable").build(); addItemMap(callDeflection); } private void addItemMap(ItemMap itemMap) { for (String itemCommand : itemMap.getItemCommands()) { if (_allItemMap.containsKey(itemCommand)) { throw new IllegalStateException("ItemMap for itemCommand " + itemCommand + " already defined"); } _allItemMap.put(itemCommand, itemMap); } } /** * Sets up a raw http(s) connection to Fbox and gets xml response as XML * Document, ready for parsing. * * @return */ public Document getFboxXmlResponse(String url) { Document tr064response = null; HttpGet httpGet = new HttpGet(url); boolean exceptionOccurred = false; try { synchronized (_httpClient) { CloseableHttpResponse resp = _httpClient.execute(httpGet, _httpClientContext); int responseCode = resp.getStatusLine().getStatusCode(); if (responseCode == 200) { HttpEntity entity = resp.getEntity(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); tr064response = db.parse(entity.getContent()); EntityUtils.consume(entity); } else { logger.error("Failed to receive valid response from httpGet"); } } } catch (Exception e) { exceptionOccurred = true; logger.error("Failed to receive valid response from httpGet: {}", e.getMessage()); } finally { // Make sure connection is released. If error occurred make sure to print in log if (exceptionOccurred) { logger.error("Releasing connection to FritzBox because of error!"); } else { logger.debug("Releasing connection"); } httpGet.releaseConnection(); } return tr064response; } }
package com.opengamma.master.impl; import java.util.Iterator; import java.util.NoSuchElementException; import com.opengamma.OpenGammaRuntimeException; import com.opengamma.master.AbstractDocument; import com.opengamma.master.AbstractMaster; import com.opengamma.master.AbstractSearchRequest; import com.opengamma.master.AbstractSearchResult; import com.opengamma.util.ArgumentChecker; import com.opengamma.util.paging.PagingRequest; /** * An iterator that searches a config master as an iterator. * <p> * Large systems may store a large amount of data in each master. * A simple search request that pulls back the entire database is unrealistic. * This remote iterator allows the database to be queried in a consistent way remotely. * * @param <D> the type of the document * @param <M> the type of the master * @param <R> the type of the search request */ public abstract class AbstractSearchIterator<D extends AbstractDocument, M extends AbstractMaster<D>, R extends AbstractSearchRequest> implements Iterator<D> { /** * The master that is being used. */ private M _master; /** * The request object that is being used. */ private final R _request; /** * The last result object. */ private AbstractSearchResult<D> _currentBatch; /** * The index of the next object within the batch result. */ private int _currentBatchIndex; /** * The current document, null if not fetched, at end or removed. */ private D _current; /** * The overall index of the last retrieved object. */ private int _overallIndex; /** * Creates an instance based on a request. * <p> * The request will be altered during the iteration. * * @param master the underlying master, not null * @param request the request object, not null */ protected AbstractSearchIterator(M master, R request) { ArgumentChecker.notNull(master, "master"); ArgumentChecker.notNull(request, "request"); _master = master; _request = request; } @Override public boolean hasNext() { if (_currentBatch == null || _currentBatchIndex >= _currentBatch.getDocuments().size()) { doFetch(); } return (_currentBatch != null && _currentBatchIndex < _currentBatch.getDocuments().size()); } @Override public D next() { if (hasNext() == false) { throw new NoSuchElementException("No more elements found"); } return doNext(); } /** * Removes the last seen document. */ @Override public void remove() { if (_current == null) { throw new IllegalStateException(); } } /** * Gets the overall index of the next entry. * <p> * This number may skip if a bad entry is found. * * @return the overall index of the next entry, 0 if next() not called yet */ public int nextIndex() { return _overallIndex; } private void doFetch() { try { // try to fetch a batch of 20 documents _request.setPagingRequest(PagingRequest.ofIndex(_overallIndex, 20)); _currentBatch = doSearch(_request); } catch (RuntimeException ex) { doFetchOne(ex); } // ensure same vc for whole iterator _request.setVersionCorrection(_currentBatch.getVersionCorrection()); // check results if (_currentBatch.getPaging().getFirstItem() < _overallIndex) { _currentBatchIndex = (_overallIndex - _currentBatch.getPaging().getFirstItem()); } else { _currentBatchIndex = 0; } } /** * Fetches the next one document. * * @param ex the original exception, not null */ private void doFetchOne(RuntimeException ex) { // try to load just the next document int maxFailures = 5; if (_currentBatch != null) { maxFailures = _currentBatch.getPaging().getTotalItems() - _overallIndex; // if we have results, use maximum count maxFailures = Math.min(maxFailures, 20); } while (maxFailures > 0) { try { _request.setPagingRequest(PagingRequest.ofIndex(_overallIndex, 1)); _currentBatch = doSearch(_request); return; } catch (RuntimeException ex2) { _overallIndex++; // abandon this document maxFailures } } throw new OpenGammaRuntimeException("Multiple documents failed to load", ex); } private D doNext() { _current = _currentBatch.getDocuments().get(_currentBatchIndex); _currentBatchIndex++; _overallIndex++; return _current; } /** * Performs the search on the master. * * @param request the request to send, not null * @return the search result, not null * @throws RuntimeException if an error occurs */ protected abstract AbstractSearchResult<D> doSearch(R request); /** * Gets the underlying master. * * @return the master, not null */ public M getMaster() { return _master; } /** * Gets the request object that is being used. * * @return the request, not null */ public R getRequest() { return _request; } }
package com.opencms.file.genericSql; import javax.servlet.http.*; import java.util.*; import java.net.*; import java.io.*; import source.org.apache.java.io.*; import source.org.apache.java.util.*; import com.opencms.core.*; import com.opencms.file.*; import com.opencms.template.*; import java.sql.SQLException; public class CmsResourceBroker implements I_CmsResourceBroker, I_CmsConstants { //create a compare class to be used in the vector. class Resource { private String path = null; public Resource(String path) { this.path = path; } public boolean equals(Object obj) { return ( (obj instanceof CmsResource) && path.equals( ((CmsResource) obj).getAbsolutePath() )); } } /** * Constant to count the file-system changes. */ protected long m_fileSystemChanges = 0; /** * Constant to count the file-system changes if Folders are involved. */ protected long m_fileSystemFolderChanges = 0; /** * Hashtable with resource-types. */ protected Hashtable m_resourceTypes = null; /** * The configuration of the property-file. */ protected Configurations m_configuration = null; /** * The access-module. */ protected CmsDbAccess m_dbAccess = null; /** * The Registry */ protected I_CmsRegistry m_registry = null; /** * Define the caches */ protected CmsCache m_userCache = null; protected CmsCache m_groupCache = null; protected CmsCache m_usergroupsCache = null; protected CmsCache m_resourceCache = null; protected CmsCache m_subresCache = null; protected CmsCache m_projectCache = null; protected CmsCache m_onlineProjectCache = null; protected CmsCache m_propertyCache = null; protected CmsCache m_propertyDefCache = null; protected CmsCache m_propertyDefVectorCache = null; protected CmsCache m_accessCache = null; protected int m_cachelimit = 0; protected String m_refresh = null; /** * Delete published project */ protected boolean m_deletePublishedProject = false; /** * Accept a task from the Cms. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param taskid The Id of the task to accept. * * @exception CmsException Throws CmsException if something goes wrong. */ public void acceptTask(CmsUser currentUser, CmsProject currentProject, int taskId) throws CmsException { CmsTask task = m_dbAccess.readTask(taskId); task.setPercentage(1); task = m_dbAccess.writeTask(task); m_dbAccess.writeSystemTaskLog(taskId, "Task was accepted from " + currentUser.getFirstname() + " " + currentUser.getLastname() + "."); } /** * Checks, if the user may create this resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The resource to check. * * @return wether the user has access, or not. */ public boolean accessCreate(CmsUser currentUser, CmsProject currentProject, CmsResource resource) throws CmsException { // check, if this is the onlineproject if(onlineProject(currentUser, currentProject).equals(currentProject)){ // the online-project is not writeable! return(false); } // check the access to the project if( ! accessProject(currentUser, currentProject, currentProject.getId()) ) { // no access to the project! return(false); } // check if the resource belongs to the current project if(resource.getProjectId() != currentProject.getId()) { return false; } // check the rights and if the resource is not locked do { if( accessOther(currentUser, currentProject, resource, C_ACCESS_PUBLIC_WRITE) || accessOwner(currentUser, currentProject, resource, C_ACCESS_OWNER_WRITE) || accessGroup(currentUser, currentProject, resource, C_ACCESS_GROUP_WRITE) ) { // is the resource locked? if( resource.isLocked() && (resource.isLockedBy() != currentUser.getId() ) ) { // resource locked by anopther user, no creation allowed return(false); } // read next resource if(resource.getParent() != null) { // resource = readFolder(currentUser,currentProject, resource.getParent()); // readFolder without checking access resource = m_dbAccess.readFolder(resource.getProjectId(), resource.getParent()); } } else { // last check was negative return(false); } } while(resource.getParent() != null); // all checks are done positive return(true); } /** * Checks, if the user may create this resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The resource to check. * * @return wether the user has access, or not. */ public boolean accessCreate(CmsUser currentUser, CmsProject currentProject, String resourceName) throws CmsException { CmsResource resource = m_dbAccess.readFileHeader(currentProject.getId(), resourceName); return accessCreate(currentUser, currentProject, resource); } /** * Checks, if the group may access this resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The resource to check. * @param flags The flags to check. * * @return wether the user has access, or not. */ protected boolean accessGroup(CmsUser currentUser, CmsProject currentProject, CmsResource resource, int flags) throws CmsException { // is the user in the group for the resource? if(userInGroup(currentUser, currentProject, currentUser.getName(), readGroup(currentUser, currentProject, resource).getName())) { if( (resource.getAccessFlags() & flags) == flags ) { return true; } } // the resource isn't accesible by the user. return false; } /** * Checks, if the user may lock this resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The resource to check. * * @return wether the user may lock this resource, or not. */ public boolean accessLock(CmsUser currentUser, CmsProject currentProject, CmsResource resource) throws CmsException { // check, if this is the onlineproject if(onlineProject(currentUser, currentProject).equals(currentProject)){ // the online-project is not writeable! return(false); } // check the access to the project if( ! accessProject(currentUser, currentProject, currentProject.getId()) ) { // no access to the project! return(false); } // check if the resource belongs to the current project if(resource.getProjectId() != currentProject.getId()) { return false; } // read the parent folder if(resource.getParent() != null) { //resource = readFolder(currentUser,currentProject, resource.getParent()); // readFolder without checking access resource = m_dbAccess.readFolder(resource.getProjectId(), resource.getParent()); } else { // no parent folder! return true; } // check the rights and if the resource is not locked do { // is the resource locked? if( resource.isLocked() && (resource.isLockedBy() != currentUser.getId() ) ) { // resource locked by anopther user, no creation allowed return(false); } // read next resource if(resource.getParent() != null) { //resource = readFolder(currentUser,currentProject, resource.getParent()); // readFolder without checking access resource = m_dbAccess.readFolder(resource.getProjectId(), resource.getParent()); } } while(resource.getParent() != null); // all checks are done positive return(true); } /** * Checks, if the user may lock this resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The resource to check. * * @return wether the user may lock this resource, or not. */ public boolean accessLock(CmsUser currentUser, CmsProject currentProject, String resourceName) throws CmsException { CmsResource resource = m_dbAccess.readFileHeader(currentProject.getId(), resourceName); return accessLock(currentUser,currentProject,resource); } /** * Checks, if others may access this resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The resource to check. * @param flags The flags to check. * * @return wether the user has access, or not. */ protected boolean accessOther(CmsUser currentUser, CmsProject currentProject, CmsResource resource, int flags) throws CmsException { if ((resource.getAccessFlags() & flags) == flags) { return true; } else { return false; } } /** * Checks, if the owner may access this resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The resource to check. * @param flags The flags to check. * * @return wether the user has access, or not. */ protected boolean accessOwner(CmsUser currentUser, CmsProject currentProject, CmsResource resource, int flags) throws CmsException { // The Admin has always access if( isAdmin(currentUser, currentProject) ) { return(true); } // is the resource owned by this user? if(resource.getOwnerId() == currentUser.getId()) { if( (resource.getAccessFlags() & flags) == flags ) { return true ; } } // the resource isn't accesible by the user. return false; } // Methods working with projects /** * Tests if the user can access the project. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param projectId the id of the project. * @return true, if the user has access, else returns false. * @exception CmsException Throws CmsException if something goes wrong. */ public boolean accessProject(CmsUser currentUser, CmsProject currentProject, int projectId) throws CmsException { CmsProject testProject = readProject(currentUser, currentProject, projectId); if (projectId==C_PROJECT_ONLINE_ID) { return true; } // is the project unlocked? if( testProject.getFlags() != C_PROJECT_STATE_UNLOCKED ) { return(false); } // is the current-user admin, or the owner of the project? if( (currentProject.getOwnerId() == currentUser.getId()) || isAdmin(currentUser, currentProject) ) { return(true); } // get all groups of the user Vector groups = getGroupsOfUser(currentUser, currentProject, currentUser.getName()); // test, if the user is in the same groups like the project. for(int i = 0; i < groups.size(); i++) { int groupId = ((CmsGroup) groups.elementAt(i)).getId(); if( ( groupId == testProject.getGroupId() ) || ( groupId == testProject.getManagerGroupId() ) ) { return( true ); } } return( false ); } /** * Checks, if the user may read this resource. * NOTE: If the ressource is in the project you never have to fallback. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The resource to check. * * @return weather the user has access, or not. */ public boolean accessRead(CmsUser currentUser, CmsProject currentProject, CmsResource resource) throws CmsException { Boolean access=(Boolean)m_accessCache.get(currentUser.getId()+":"+currentProject.getId()+":"+resource.getName()); if (access != null) { return access.booleanValue(); } else { if ((resource == null) || !accessProject(currentUser, currentProject, resource.getProjectId()) || (!accessOther(currentUser, currentProject, resource, C_ACCESS_PUBLIC_READ) && !accessOwner(currentUser, currentProject, resource, C_ACCESS_OWNER_READ) && !accessGroup(currentUser, currentProject, resource, C_ACCESS_GROUP_READ))) { m_accessCache.put(currentUser.getId()+":"+currentProject.getId()+":"+resource.getName(),new Boolean(false)); return false; } // check the rights for all CmsResource res = resource; // save the original resource name to be used if an error occurs. while (res.getParent() != null) { // readFolder without checking access res = m_dbAccess.readFolder(res.getProjectId(), res.getParent()); //res = readFolder(currentUser, currentProject, res.getParent()); if (res == null) { A_OpenCms.log(A_OpenCms.C_OPENCMS_DEBUG, "Resource has no parent: " + resource.getAbsolutePath()); throw new CmsException(this.getClass().getName() + ".accessRead(): Cannot find \'" + resource.getName(), CmsException.C_NOT_FOUND); } if (!accessOther(currentUser, currentProject, res, C_ACCESS_PUBLIC_READ) && !accessOwner(currentUser, currentProject, res, C_ACCESS_OWNER_READ) && !accessGroup(currentUser, currentProject, res, C_ACCESS_GROUP_READ)) { m_accessCache.put(currentUser.getId()+":"+currentProject.getId()+":"+resource.getName(),new Boolean(false)); return false; } } m_accessCache.put(currentUser.getId()+":"+currentProject.getId()+":"+resource.getName(),new Boolean(true)); return true; } } /** * Checks, if the user may read this resource. * NOTE: If the ressource is in the project you never have to fallback. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The resource to check. * * @return weather the user has access, or not. */ public boolean accessRead(CmsUser currentUser, CmsProject currentProject, String resourceName) throws CmsException { CmsResource resource = m_dbAccess.readFileHeader(currentProject.getId(), resourceName); return accessRead(currentUser, currentProject, resource); } /** * Checks, if the user may unlock this resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The resource to check. * * @return wether the user may unlock this resource, or not. */ public boolean accessUnlock(CmsUser currentUser, CmsProject currentProject, CmsResource resource) throws CmsException { // check, if this is the onlineproject if(onlineProject(currentUser, currentProject).equals(currentProject)){ // the online-project is not writeable! return(false); } // check the access to the project if( ! accessProject(currentUser, currentProject, currentProject.getId()) ) { // no access to the project! return(false); } // check if the resource belongs to the current project if(resource.getProjectId() != currentProject.getId()) { return false; } // read the parent folder if(resource.getParent() != null) { // readFolder without checking access //resource = readFolder(currentUser,currentProject, resource.getParent()); resource = m_dbAccess.readFolder(resource.getProjectId(), resource.getParent()); } else { // no parent folder! return true; } // check if the resource is not locked do { // is the resource locked? if( resource.isLocked() ) { // resource locked by anopther user, no creation allowed return(false); } // read next resource if(resource.getParent() != null) { // readFolder without checking access //resource = readFolder(currentUser,currentProject, resource.getParent()); resource = m_dbAccess.readFolder(resource.getProjectId(), resource.getParent()); } } while(resource.getParent() != null); // all checks are done positive return(true); } /** * Checks, if the user may write this resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The resource to check. * * @return wether the user has access, or not. */ public boolean accessWrite(CmsUser currentUser, CmsProject currentProject, CmsResource resource) throws CmsException { // check, if this is the onlineproject if(onlineProject(currentUser, currentProject).equals(currentProject)){ // the online-project is not writeable! return(false); } // check the access to the project if( ! accessProject(currentUser, currentProject, currentProject.getId()) ) { // no access to the project! return(false); } // check if the resource belongs to the current project if(resource.getProjectId() != currentProject.getId()) { return false; } // check, if the resource is locked by the current user if(resource.isLockedBy() != currentUser.getId()) { // resource is not locked by the current user, no writing allowed return(false); } // check the rights for the current resource if( ! ( accessOther(currentUser, currentProject, resource, C_ACCESS_PUBLIC_WRITE) || accessOwner(currentUser, currentProject, resource, C_ACCESS_OWNER_WRITE) || accessGroup(currentUser, currentProject, resource, C_ACCESS_GROUP_WRITE) ) ) { // no write access to this resource! return false; } // read the parent folder if(resource.getParent() != null) { // readFolder without checking access //resource = readFolder(currentUser,currentProject, resource.getParent()); resource = m_dbAccess.readFolder(resource.getProjectId(), resource.getParent()); } else { // no parent folder! return true; } // check the rights and if the resource is not locked do { if( accessOther(currentUser, currentProject, resource, C_ACCESS_PUBLIC_WRITE) || accessOwner(currentUser, currentProject, resource, C_ACCESS_OWNER_WRITE) || accessGroup(currentUser, currentProject, resource, C_ACCESS_GROUP_WRITE) ) { // is the resource locked? if( resource.isLocked() && (resource.isLockedBy() != currentUser.getId() ) ) { // resource locked by anopther user, no creation allowed return(false); } // read next resource if(resource.getParent() != null) { // readFolder without checking access //resource = readFolder(currentUser,currentProject, resource.getParent()); resource = m_dbAccess.readFolder(resource.getProjectId(), resource.getParent()); } } else { // last check was negative return(false); } } while(resource.getParent() != null); // all checks are done positive return(true); } /** * Checks, if the user may write this resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The resource to check. * * @return wether the user has access, or not. */ public boolean accessWrite(CmsUser currentUser, CmsProject currentProject, String resourceName) throws CmsException { CmsResource resource = m_dbAccess.readFileHeader(currentProject.getId(), resourceName); return accessWrite(currentUser,currentProject,resource); } /** * adds a file extension to the list of known file extensions * * <B>Security:</B> * Users, which are in the group "administrators" are granted.<BR/> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param extension a file extension like 'html' * @param resTypeName name of the resource type associated to the extension */ public void addFileExtension(CmsUser currentUser, CmsProject currentProject, String extension, String resTypeName) throws CmsException { if (extension != null && resTypeName != null) { if (isAdmin(currentUser, currentProject)) { Hashtable suffixes=(Hashtable) m_dbAccess.readSystemProperty(C_SYSTEMPROPERTY_EXTENSIONS); if (suffixes == null) { suffixes = new Hashtable(); suffixes.put(extension, resTypeName); m_dbAccess.addSystemProperty(C_SYSTEMPROPERTY_EXTENSIONS, suffixes); } else { suffixes.put(extension, resTypeName); m_dbAccess.writeSystemProperty(C_SYSTEMPROPERTY_EXTENSIONS, suffixes); } } else { throw new CmsException("[" + this.getClass().getName() + "] " + extension, CmsException.C_NO_ACCESS); } } } /** * Add a new group to the Cms.<BR/> * * Only the admin can do this.<P/> * * <B>Security:</B> * Only users, which are in the group "administrators" are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param name The name of the new group. * @param description The description for the new group. * @int flags The flags for the new group. * @param name The name of the parent group (or null). * * @return Group * * @exception CmsException Throws CmsException if operation was not succesfull. */ public CmsGroup addGroup(CmsUser currentUser, CmsProject currentProject, String name, String description, int flags, String parent) throws CmsException { // Check the security if( isAdmin(currentUser, currentProject) ) { name = name.trim(); validName(name, false); // check the lenght of the groupname if(name.length() > 1) { return( m_dbAccess.createGroup(name, description, flags, parent) ); } else { throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_BAD_NAME); } } else { throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_NO_ACCESS); } } /** * Adds a CmsResourceTypes. * * <B>Security:</B> * Users, which are in the group "administrators" are granted.<BR/> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resourceType the name of the resource to get. * @param launcherType the launcherType-id * @param launcherClass the name of the launcher-class normaly "" * * Returns a CmsResourceTypes. * * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsResourceType addResourceType(CmsUser currentUser, CmsProject currentProject, String resourceType, int launcherType, String launcherClass) throws CmsException { if( isAdmin(currentUser, currentProject) ) { // read the resourceTypes from the propertys m_resourceTypes = (Hashtable) m_dbAccess.readSystemProperty(C_SYSTEMPROPERTY_RESOURCE_TYPE); synchronized(m_resourceTypes) { // get the last index and increment it. Integer lastIndex = new Integer(((Integer) m_resourceTypes.get(C_TYPE_LAST_INDEX)).intValue() + 1); // write the last index back m_resourceTypes.put(C_TYPE_LAST_INDEX, lastIndex); // add the new resource-type m_resourceTypes.put(resourceType, new CmsResourceType(lastIndex.intValue(), launcherType, resourceType, launcherClass)); // store the resource types in the properties m_dbAccess.writeSystemProperty(C_SYSTEMPROPERTY_RESOURCE_TYPE, m_resourceTypes); } // the cached resource types aren't valid any more. m_resourceTypes = null; // return the new resource-type return(getResourceType(currentUser, currentProject, resourceType)); } else { throw new CmsException("[" + this.getClass().getName() + "] " + resourceType, CmsException.C_NO_ACCESS); } } /** * Adds a user to the Cms. * * Only a adminstrator can add users to the cms.<P/> * * <B>Security:</B> * Only users, which are in the group "administrators" are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param name The new name for the user. * @param password The new password for the user. * @param group The default groupname for the user. * @param description The description for the user. * @param additionalInfos A Hashtable with additional infos for the user. These * Infos may be stored into the Usertables (depending on the implementation). * @param flags The flags for a user (e.g. C_FLAG_ENABLED) * * @return user The added user will be returned. * * @exception CmsException Throws CmsException if operation was not succesfull. */ public CmsUser addUser(CmsUser currentUser, CmsProject currentProject, String name, String password, String group, String description, Hashtable additionalInfos, int flags) throws CmsException { // Check the security if( isAdmin(currentUser, currentProject) ) { // no space before or after the name name = name.trim(); // check the username validName(name, false); // check the password minimumsize if( (name.length() > 0) && (password.length() >= C_PASSWORD_MINIMUMSIZE) ) { CmsGroup defaultGroup = readGroup(currentUser, currentProject, group); CmsUser newUser = m_dbAccess.addUser(name, password, description, " ", " ", " ", 0, 0, C_FLAG_ENABLED, additionalInfos, defaultGroup, " ", " ", C_USER_TYPE_SYSTEMUSER); addUserToGroup(currentUser, currentProject, newUser.getName(),defaultGroup.getName()); return newUser; } else { throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_SHORT_PASSWORD); } } else { throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_NO_ACCESS); } } /** * Adds a user to a group.<BR/> * * Only the admin can do this.<P/> * * <B>Security:</B> * Only users, which are in the group "administrators" are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param username The name of the user that is to be added to the group. * @param groupname The name of the group. * @exception CmsException Throws CmsException if operation was not succesfull. */ public void addUserToGroup(CmsUser currentUser, CmsProject currentProject, String username, String groupname) throws CmsException { /* ednfal: don't throw this exception because of problems in group administration there is a check in dbAccess, so the user is only added to group if he doesn't already exist // test if this user is already in the group if (userInGroup(currentUser,currentProject,username,groupname)) { // user already there, throw exception throw new CmsException("[" + this.getClass().getName() + "] add " + username+ " to " +groupname, CmsException.C_USER_EXISTS); } */ // Check the security if( isAdmin(currentUser, currentProject) ) { CmsUser user; CmsGroup group; user=readUser(currentUser,currentProject,username); //check if the user exists if (user != null) { group=readGroup(currentUser,currentProject,groupname); //check if group exists if (group != null){ //add this user to the group m_dbAccess.addUserToGroup(user.getId(),group.getId()); // update the cache m_usergroupsCache.clear(); } else { throw new CmsException("["+this.getClass().getName()+"]"+groupname,CmsException.C_NO_GROUP); } } else { throw new CmsException("["+this.getClass().getName()+"]"+username,CmsException.C_NO_USER); } } else { throw new CmsException("[" + this.getClass().getName() + "] " + username, CmsException.C_NO_ACCESS); } } /** * Adds a web user to the Cms. <br> * * A web user has no access to the workplace but is able to access personalized * functions controlled by the OpenCms. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param name The new name for the user. * @param password The new password for the user. * @param group The default groupname for the user. * @param description The description for the user. * @param additionalInfos A Hashtable with additional infos for the user. These * Infos may be stored into the Usertables (depending on the implementation). * @param flags The flags for a user (e.g. C_FLAG_ENABLED) * * @return user The added user will be returned. * * @exception CmsException Throws CmsException if operation was not succesfull. */ public CmsUser addWebUser(CmsUser currentUser, CmsProject currentProject, String name, String password, String group, String description, Hashtable additionalInfos, int flags) throws CmsException { // no space before or after the name name = name.trim(); // check the username validName(name, false); // check the password minimumsize if( (name.length() > 0) && (password.length() >= C_PASSWORD_MINIMUMSIZE) ) { CmsGroup defaultGroup = readGroup(currentUser, currentProject, group); CmsUser newUser = m_dbAccess.addUser(name, password, description, " ", " ", " ", 0, 0, C_FLAG_ENABLED, additionalInfos, defaultGroup, " ", " ", C_USER_TYPE_WEBUSER); CmsUser user; CmsGroup usergroup; user=m_dbAccess.readUser(newUser.getName(),C_USER_TYPE_WEBUSER); //check if the user exists if (user != null) { usergroup=readGroup(currentUser,currentProject,group); //check if group exists if (usergroup != null){ //add this user to the group m_dbAccess.addUserToGroup(user.getId(),usergroup.getId()); // update the cache m_usergroupsCache.clear(); } else { throw new CmsException("["+this.getClass().getName()+"]"+group,CmsException.C_NO_GROUP); } } else { throw new CmsException("["+this.getClass().getName()+"]"+name,CmsException.C_NO_USER); } return newUser; } else { throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_SHORT_PASSWORD); } } /** * Returns the anonymous user object.<P/> * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @return the anonymous user object. * @exception CmsException Throws CmsException if operation was not succesful */ public CmsUser anonymousUser(CmsUser currentUser, CmsProject currentProject) throws CmsException { return readUser(currentUser, currentProject, C_USER_GUEST); } /** * Checks, if all mandatory metainfos for the resource type are set as key in the * metainfo-hashtable. It throws a exception, if a mandatory metainfo is missing. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resourceType The type of the rersource to check the metainfos for. * @param propertyinfos The propertyinfos to check. * * @exception CmsException Throws CmsException if operation was not succesful. */ protected void checkMandatoryProperties(CmsUser currentUser, CmsProject currentProject, String resourceType, Hashtable propertyinfos) throws CmsException { // read the mandatory metadefs Vector metadefs = readAllPropertydefinitions(currentUser, currentProject, resourceType, C_PROPERTYDEF_TYPE_MANDATORY); // check, if the mandatory metainfo is given for(int i = 0; i < metadefs.size(); i++) { if( propertyinfos.containsKey(metadefs.elementAt(i) ) ) { // mandatory metainfo is missing - throw exception throw new CmsException("[" + this.getClass().getName() + "] " + (String)metadefs.elementAt(i), CmsException.C_MANDATORY_PROPERTY); } } } /** * Changes the group for this resource<br> * * Only the group of a resource in an offline project can be changed. The state * of the resource is set to CHANGED (1). * If the content of this resource is not exisiting in the offline project already, * it is read from the online project and written into the offline project. * The user may change this, if he is admin of the resource. <br> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user is owner of the resource or is admin</li> * <li>the resource is locked by the callingUser</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param filename The complete path to the resource. * @param newGroup The name of the new group for this resource. * * @exception CmsException Throws CmsException if operation was not succesful. */ public void chgrp(CmsUser currentUser, CmsProject currentProject, String filename, String newGroup) throws CmsException { CmsResource resource=null; // read the resource to check the access if (filename.endsWith("/")) { resource = readFolder(currentUser,currentProject,filename); } else { resource = (CmsFile)readFileHeader(currentUser,currentProject,filename); } // has the user write-access? and is he owner or admin? if( accessWrite(currentUser, currentProject, resource) && ( (resource.getOwnerId() == currentUser.getId()) || isAdmin(currentUser, currentProject))) { CmsGroup group = readGroup(currentUser, currentProject, newGroup); resource.setGroupId(group.getId()); // write-acces was granted - write the file. if (filename.endsWith("/")) { if (resource.getState()==C_STATE_UNCHANGED) { resource.setState(C_STATE_CHANGED); } m_dbAccess.writeFolder(currentProject,(CmsFolder)resource,true); // update the cache m_resourceCache.put(C_FOLDER+currentProject.getId()+filename,(CmsFolder)resource); } else { m_dbAccess.writeFileHeader(currentProject,(CmsFile)resource,true); if (resource.getState()==C_STATE_UNCHANGED) { resource.setState(C_STATE_CHANGED); } // update the cache m_resourceCache.put(C_FILE+currentProject.getId()+filename,resource); } m_subresCache.clear(); // inform about the file-system-change fileSystemChanged(false); } else { throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_NO_ACCESS); } } /** * Changes the flags for this resource.<br> * * Only the flags of a resource in an offline project can be changed. The state * of the resource is set to CHANGED (1). * If the content of this resource is not exisiting in the offline project already, * it is read from the online project and written into the offline project. * The user may change the flags, if he is admin of the resource <br>. * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can write the resource</li> * <li>the resource is locked by the callingUser</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param filename The complete path to the resource. * @param flags The new accessflags for the resource. * * @exception CmsException Throws CmsException if operation was not succesful. */ public void chmod(CmsUser currentUser, CmsProject currentProject, String filename, int flags) throws CmsException { CmsResource resource=null; // read the resource to check the access if (filename.endsWith("/")) { resource = readFolder(currentUser,currentProject,filename); } else { resource = (CmsFile)readFileHeader(currentUser,currentProject,filename); } // has the user write-access? if( accessWrite(currentUser, currentProject, resource)|| ((resource.isLockedBy() == currentUser.getId()) && (resource.getOwnerId() == currentUser.getId()||isAdmin(currentUser, currentProject))) ) { // write-acces was granted - write the file. //set the flags resource.setAccessFlags(flags); //update file if (filename.endsWith("/")) { if (resource.getState()==C_STATE_UNCHANGED) { resource.setState(C_STATE_CHANGED); } m_dbAccess.writeFolder(currentProject,(CmsFolder)resource,true); // update the cache m_resourceCache.put(C_FOLDER+currentProject.getId()+filename,(CmsFolder)resource); } else { m_dbAccess.writeFileHeader(currentProject,(CmsFile)resource,true); if (resource.getState()==C_STATE_UNCHANGED) { resource.setState(C_STATE_CHANGED); } // update the cache m_resourceCache.put(C_FILE+currentProject.getId()+filename,resource); } m_subresCache.clear(); m_accessCache.clear(); // inform about the file-system-change fileSystemChanged(false); } else { throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_NO_ACCESS); } } /** * Changes the owner for this resource.<br> * * Only the owner of a resource in an offline project can be changed. The state * of the resource is set to CHANGED (1). * If the content of this resource is not exisiting in the offline project already, * it is read from the online project and written into the offline project. * The user may change this, if he is admin of the resource. <br> * * <B>Security:</B> * Access is cranted, if: * <ul> * <li>the user has access to the project</li> * <li>the user is owner of the resource or the user is admin</li> * <li>the resource is locked by the callingUser</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param filename The complete path to the resource. * @param newOwner The name of the new owner for this resource. * * @exception CmsException Throws CmsException if operation was not succesful. */ public void chown(CmsUser currentUser, CmsProject currentProject, String filename, String newOwner) throws CmsException { CmsResource resource = null; // read the resource to check the access if (filename.endsWith("/")) { resource = readFolder(currentUser, currentProject, filename); } else { resource = (CmsFile) readFileHeader(currentUser, currentProject, filename); } // has the user write-access? and is he owner or admin? if (((resource.getOwnerId() == currentUser.getId()) || isAdmin(currentUser, currentProject)) && (resource.isLockedBy() == currentUser.getId())) { CmsUser owner = readUser(currentUser, currentProject, newOwner); resource.setUserId(owner.getId()); // write-acces was granted - write the file. if (filename.endsWith("/")) { if (resource.getState() == C_STATE_UNCHANGED) { resource.setState(C_STATE_CHANGED); } m_dbAccess.writeFolder(currentProject, (CmsFolder) resource, true); // update the cache m_resourceCache.put(C_FOLDER + currentProject.getId() + filename, (CmsFolder) resource); } else { m_dbAccess.writeFileHeader(currentProject, (CmsFile) resource, true); if (resource.getState() == C_STATE_UNCHANGED) { resource.setState(C_STATE_CHANGED); } // update the cache m_resourceCache.put(C_FILE + currentProject.getId() + filename, resource); } m_subresCache.clear(); m_accessCache.clear(); // inform about the file-system-change fileSystemChanged(false); } else { throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_NO_ACCESS); } } /** * Changes the state for this resource<BR/> * * The user may change this, if he is admin of the resource. * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user is owner of the resource or is admin</li> * <li>the resource is locked by the callingUser</li> * </ul> * * @param filename The complete path to the resource. * @param state The new state of this resource. * * @exception CmsException will be thrown, if the user has not the rights * for this resource. */ public void chstate(CmsUser currentUser, CmsProject currentProject, String filename, int state) throws CmsException { boolean isFolder=false; CmsResource resource=null; // read the resource to check the access if (filename.endsWith("/")) { isFolder=true; resource = readFolder(currentUser,currentProject,filename); } else { resource = (CmsFile)readFileHeader(currentUser,currentProject,filename); } // has the user write-access? if( accessWrite(currentUser, currentProject, resource)) { resource.setState(state); // write-acces was granted - write the file. if (filename.endsWith("/")) { m_dbAccess.writeFolder(currentProject,(CmsFolder)resource,false); // update the cache m_resourceCache.put(C_FOLDER+currentProject.getId()+filename,(CmsFolder)resource); } else { m_dbAccess.writeFileHeader(currentProject,(CmsFile)resource,false); // update the cache m_resourceCache.put(C_FILE+currentProject.getId()+filename,resource); } m_subresCache.clear(); // inform about the file-system-change fileSystemChanged(isFolder); } else { throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_NO_ACCESS); } } /** * Changes the resourcetype for this resource<br> * * Only the resourcetype of a resource in an offline project can be changed. The state * of the resource is set to CHANGED (1). * If the content of this resource is not exisiting in the offline project already, * it is read from the online project and written into the offline project. * The user may change this, if he is admin of the resource. <br> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user is owner of the resource or is admin</li> * <li>the resource is locked by the callingUser</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param filename The complete path to the resource. * @param newType The name of the new resourcetype for this resource. * * @exception CmsException Throws CmsException if operation was not succesful. */ public void chtype(CmsUser currentUser, CmsProject currentProject, String filename, String newType) throws CmsException { CmsResourceType type = getResourceType(currentUser, currentProject, newType); // read the resource to check the access CmsResource resource = readFileHeader(currentUser,currentProject, filename); // has the user write-access? and is he owner or admin? if( accessWrite(currentUser, currentProject, resource) && ( (resource.getOwnerId() == currentUser.getId()) || isAdmin(currentUser, currentProject))) { // write-acces was granted - write the file. resource.setType(type.getResourceType()); resource.setLauncherType(type.getLauncherType()); m_dbAccess.writeFileHeader(currentProject, (CmsFile)resource,true); if (resource.getState()==C_STATE_UNCHANGED) { resource.setState(C_STATE_CHANGED); } // update the cache m_resourceCache.put(C_FILE+currentProject.getId()+filename,resource); m_subresCache.clear(); // inform about the file-system-change fileSystemChanged(false); } else { throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_NO_ACCESS); } } /** * Clears all internal DB-Caches. */ public void clearcache() { m_userCache.clear(); m_groupCache.clear(); m_usergroupsCache.clear(); m_projectCache.clear(); m_resourceCache.clear(); m_subresCache.clear(); m_propertyCache.clear(); m_propertyDefCache.clear(); m_propertyDefVectorCache.clear(); m_onlineProjectCache.clear(); m_accessCache.clear(); CmsTemplateClassManager.clearCache(); } /** * Copies a file in the Cms. <br> * * <B>Security:</B> * Access is cranted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read the sourceresource</li> * <li>the user can create the destinationresource</li> * <li>the destinationresource dosn't exists</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param source The complete path of the sourcefile. * @param destination The complete path to the destination. * * @exception CmsException Throws CmsException if operation was not succesful. */ public void copyFile(CmsUser currentUser, CmsProject currentProject, String source, String destination) throws CmsException { // the name of the new file. String filename; // the name of the folder. String foldername; // checks, if the destinateion is valid, if not it throws a exception validFilename(destination.replace('/', 'a')); // read the source-file, to check readaccess CmsResource file = readFileHeader(currentUser, currentProject, source); // split the destination into file and foldername if (destination.endsWith("/")) { filename = file.getName(); foldername = destination; }else{ foldername = destination.substring(0, destination.lastIndexOf("/")+1); filename = destination.substring(destination.lastIndexOf("/")+1, destination.length()); } CmsFolder cmsFolder = readFolder(currentUser,currentProject, foldername); if( accessCreate(currentUser, currentProject, (CmsResource)cmsFolder) ) { // write-acces was granted - copy the file and the metainfos m_dbAccess.copyFile(currentProject, onlineProject(currentUser, currentProject), currentUser.getId(),source,cmsFolder.getResourceId(), foldername + filename); // copy the metainfos lockResource(currentUser, currentProject, destination, true); writeProperties(currentUser,currentProject, destination, readAllProperties(currentUser,currentProject,file.getAbsolutePath())); m_accessCache.clear(); // inform about the file-system-change fileSystemChanged(file.isFolder()); } else { throw new CmsException("[" + this.getClass().getName() + "] " + destination, CmsException.C_NO_ACCESS); } } /** * Copies a folder in the Cms. <br> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read the sourceresource</li> * <li>the user can create the destinationresource</li> * <li>the destinationresource dosn't exists</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param source The complete path of the sourcefolder. * @param destination The complete path to the destination. * * @exception CmsException Throws CmsException if operation was not succesful. */ public void copyFolder(CmsUser currentUser, CmsProject currentProject, String source, String destination) throws CmsException { // the name of the new file. String filename; // the name of the folder. String foldername; // read the sourcefolder to check readaccess //CmsFolder folder=(CmsFolder)readFolder(currentUser, currentProject, source); // checks, if the destinateion is valid, if not it throws a exception validFilename(destination.replace('/', 'a')); foldername = destination.substring(0, destination.substring(0,destination.length()-1).lastIndexOf("/")+1); CmsFolder cmsFolder = readFolder(currentUser,currentProject, foldername); if( accessCreate(currentUser, currentProject, (CmsResource)cmsFolder) ) { // write-acces was granted - copy the folder and the properties CmsFolder folder=readFolder(currentUser,currentProject,source); m_dbAccess.createFolder(currentUser,currentProject,onlineProject(currentUser, currentProject),folder,cmsFolder.getResourceId(),destination); // copy the properties lockResource(currentUser, currentProject, destination, true); writeProperties(currentUser,currentProject, destination, readAllProperties(currentUser,currentProject,folder.getAbsolutePath())); m_accessCache.clear(); // inform about the file-system-change fileSystemChanged(true); } else { throw new CmsException("[" + this.getClass().getName() + "] " + destination, CmsException.C_ACCESS_DENIED); } } public void copyResourceToProject(CmsProject currentProject, CmsProject fromProject, CmsResource resource) throws com.opencms.core.CmsException { m_dbAccess.copyResourceToProject(currentProject, fromProject, resource); } /** * Copies a resource from the online project to a new, specified project.<br> * Copying a resource will copy the file header or folder into the specified * offline project and set its state to UNCHANGED. * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user is the owner of the project</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The name of the resource. * @exception CmsException Throws CmsException if operation was not succesful. */ public void copyResourceToProject(CmsUser currentUser, CmsProject currentProject, String resource) throws CmsException { // read the onlineproject CmsProject online = onlineProject(currentUser, currentProject); // is the current project the onlineproject? // and is the current user the owner of the project? // and is the current project state UNLOCKED? if( (!currentProject.equals( online ) ) && (currentProject.getOwnerId() == currentUser.getId()) && (currentProject.getFlags() == C_PROJECT_STATE_UNLOCKED)) { // is offlineproject and is owner CmsResource onlineRes= readFileHeader(currentUser,online, resource); CmsResource offlineRes=null; // walk recursively through all parents and copy them, too String parent = onlineRes.getParent(); Stack resources=new Stack(); // go through all parens and store them on a stack while(parent != null) { // read the online-resource onlineRes = readFileHeader(currentUser,online, parent); resources.push(onlineRes); // get the parent parent = onlineRes.getParent(); } // now create all parent folders, starting at the root folder while (resources.size()>0){ onlineRes=(CmsResource)resources.pop(); parent=onlineRes.getAbsolutePath(); // copy it to the offlineproject try { m_dbAccess.copyResourceToProject(currentProject, online, onlineRes); // read the offline-resource offlineRes = readFileHeader(currentUser,currentProject, parent); // copy the metainfos writeProperties(currentUser,currentProject,offlineRes.getAbsolutePath(), readAllProperties(currentUser,currentProject,onlineRes.getAbsolutePath())); chstate(currentUser,currentProject,offlineRes.getAbsolutePath(),C_STATE_UNCHANGED); } catch (CmsException exc) { // if the subfolder exists already - all is ok } } helperCopyResourceToProject(currentUser,online, currentProject, resource); } else { // no changes on the onlineproject! throw new CmsException("[" + this.getClass().getName() + "] " + currentProject.getName(), CmsException.C_NO_ACCESS); } } /** * Counts the locked resources in this project. * * <B>Security</B> * Only the admin or the owner of the project can do this. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param id The id of the project * @return the amount of locked resources in this project. * * @exception CmsException Throws CmsException if something goes wrong. */ public int countLockedResources(CmsUser currentUser, CmsProject currentProject, int id) throws CmsException { // read the project. CmsProject project = readProject(currentUser, currentProject, id); // check the security if( isAdmin(currentUser, currentProject) || isManagerOfProject(currentUser, project) || (project.getFlags() == C_PROJECT_STATE_UNLOCKED )) { // count locks return m_dbAccess.countLockedResources(project); } else { throw new CmsException("[" + this.getClass().getName() + "] " + id, CmsException.C_NO_ACCESS); } } public com.opencms.file.genericSql.CmsDbAccess createDbAccess(Configurations configurations) throws CmsException { return new com.opencms.file.genericSql.CmsDbAccess(configurations); } /** * Creates a new file with the given content and resourcetype. <br> * * Files can only be created in an offline project, the state of the new file * is set to NEW (2). <br> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can write the resource</li> * <li>the folder-resource is not locked by another user</li> * <li>the file dosn't exists</li> * </ul> * * @param currentUser The user who owns this file. * @param currentGroup The group who owns this file. * @param currentProject The project in which the resource will be used. * @param folder The complete path to the folder in which the new folder will * be created. * @param file The name of the new file (No pathinformation allowed). * @param contents The contents of the new file. * @param type The name of the resourcetype of the new file. * @param propertyinfos A Hashtable of propertyinfos, that should be set for this folder. * The keys for this Hashtable are the names for propertydefinitions, the values are * the values for the propertyinfos. * @return file The created file. * * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsFile createFile(CmsUser currentUser, CmsGroup currentGroup, CmsProject currentProject, String folder, String filename, byte[] contents, String type, Hashtable propertyinfos) throws CmsException { // check for mandatory metainfos checkMandatoryProperties(currentUser, currentProject, type, propertyinfos); // checks, if the filename is valid, if not it throws a exception validFilename(filename); CmsFolder cmsFolder = readFolder(currentUser,currentProject, folder); if( accessCreate(currentUser, currentProject, (CmsResource)cmsFolder) ) { // write-access was granted - create and return the file. CmsFile file = m_dbAccess.createFile(currentUser, currentProject, onlineProject(currentUser, currentProject), folder + filename, 0, cmsFolder.getResourceId(), contents, getResourceType(currentUser, currentProject, type)); // update the access flags Hashtable startSettings=null; Integer accessFlags=null; startSettings=(Hashtable)currentUser.getAdditionalInfo(C_ADDITIONAL_INFO_STARTSETTINGS); if (startSettings != null) { accessFlags=(Integer)startSettings.get(C_START_ACCESSFLAGS); if (accessFlags != null) { file.setAccessFlags(accessFlags.intValue()); } } if(currentGroup != null) { file.setGroupId(currentGroup.getId()); } m_dbAccess.writeFileHeader(currentProject, file,false); m_subresCache.clear(); // write the metainfos m_dbAccess.writeProperties(propertyinfos, file.getResourceId(), file.getType()); // inform about the file-system-change fileSystemChanged(false); return file ; } else { throw new CmsException("[" + this.getClass().getName() + "] " + folder + filename, CmsException.C_NO_ACCESS); } } /** * Creates a new folder. * If some mandatory propertydefinitions for the resourcetype are missing, a * CmsException will be thrown, because the file cannot be created without * the mandatory propertyinformations.<BR/> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can write the resource</li> * <li>the resource is not locked by another user</li> * </ul> * * @param currentUser The user who requested this method. * @param currentGroup The group who requested this method. * @param currentProject The current project of the user. * @param folder The complete path to the folder in which the new folder will * be created. * @param newFolderName The name of the new folder (No pathinformation allowed). * @param propertyinfos A Hashtable of propertyinfos, that should be set for this folder. * The keys for this Hashtable are the names for propertydefinitions, the values are * the values for the propertyinfos. * * @return file The created file. * * @exception CmsException will be thrown for missing propertyinfos, for worng propertydefs * or if the filename is not valid. The CmsException will also be thrown, if the * user has not the rights for this resource. */ public CmsFolder createFolder(CmsUser currentUser, CmsGroup currentGroup, CmsProject currentProject, String folder, String newFolderName, Hashtable propertyinfos) throws CmsException { // check for mandatory metainfos checkMandatoryProperties(currentUser, currentProject, C_TYPE_FOLDER_NAME, propertyinfos); // checks, if the filename is valid, if not it throws a exception validFilename(newFolderName); CmsFolder cmsFolder = readFolder(currentUser,currentProject, folder); if( accessCreate(currentUser, currentProject, (CmsResource)cmsFolder) ) { // write-acces was granted - create the folder. CmsFolder newFolder = m_dbAccess.createFolder(currentUser, currentProject, cmsFolder.getResourceId(), C_UNKNOWN_ID, folder + newFolderName + C_FOLDER_SEPERATOR, 0); // update the access flags Hashtable startSettings=null; Integer accessFlags=null; startSettings=(Hashtable)currentUser.getAdditionalInfo(C_ADDITIONAL_INFO_STARTSETTINGS); if (startSettings != null) { accessFlags=(Integer)startSettings.get(C_START_ACCESSFLAGS); if (accessFlags != null) { newFolder.setAccessFlags(accessFlags.intValue()); } } if(currentGroup != null) { newFolder.setGroupId(currentGroup.getId()); } newFolder.setState(C_STATE_NEW); m_dbAccess.writeFolder(currentProject, newFolder, false); m_subresCache.clear(); // write metainfos for the folder m_dbAccess.writeProperties(propertyinfos, newFolder.getResourceId(), newFolder.getType()); // writeProperties(currentUser,currentProject, newFolder.getAbsolutePath(), propertyinfos); // inform about the file-system-change fileSystemChanged(true); // return the folder return newFolder ; } else { throw new CmsException("[" + this.getClass().getName() + "] " + folder + newFolderName, CmsException.C_NO_ACCESS); } } /** * Creates a project. * * <B>Security</B> * Only the users which are in the admin or projectleader-group are granted. * * Changed: added the parent id * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param name The name of the project to read. * @param description The description for the new project. * @param group the group to be set. * @param managergroup the managergroup to be set. * @param parentId the parent project * @exception CmsException Throws CmsException if something goes wrong. * @author Martin Langelund */ public CmsProject createProject(CmsUser currentUser, CmsProject currentProject, String name, String description, String groupname, String managergroupname) throws CmsException { if (isAdmin(currentUser, currentProject) || isProjectManager(currentUser, currentProject)) { // read the needed groups from the cms CmsGroup group = readGroup(currentUser, currentProject, groupname); CmsGroup managergroup = readGroup(currentUser, currentProject, managergroupname); // create a new task for the project CmsTask task = createProject(currentUser, name, 1, group.getName(), System.currentTimeMillis(), C_TASK_PRIORITY_NORMAL); return m_dbAccess.createProject(currentUser, group, managergroup, task, name, description, C_PROJECT_STATE_UNLOCKED, C_PROJECT_TYPE_NORMAL); } else { throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_NO_ACCESS); } } /** * Creates a new project for task handling. * * @param currentUser User who creates the project * @param projectName Name of the project * @param projectType Type of the Project * @param role Usergroup for the project * @param timeout Time when the Project must finished * @param priority Priority for the Project * * @return The new task project * * @exception CmsException Throws CmsException if something goes wrong. */ public CmsTask createProject(CmsUser currentUser, String projectName, int projectType, String roleName, long timeout, int priority) throws CmsException { CmsGroup role = null; // read the role if(roleName!=null && !roleName.equals("")) { role = readGroup(currentUser, null, roleName); } // create the timestamp java.sql.Timestamp timestamp = new java.sql.Timestamp(timeout); java.sql.Timestamp now = new java.sql.Timestamp(System.currentTimeMillis()); return m_dbAccess.createTask(0,0, 1, // standart project type, currentUser.getId(), currentUser.getId(), role.getId(), projectName, now, timestamp, priority); } // Methods working with properties and propertydefinitions /** * Creates the propertydefinition for the resource type.<BR/> * * <B>Security</B> * Only the admin can do this. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param name The name of the propertydefinition to overwrite. * @param resourcetype The name of the resource-type for the propertydefinition. * @param type The type of the propertydefinition (normal|mandatory|optional) * * @exception CmsException Throws CmsException if something goes wrong. */ public CmsPropertydefinition createPropertydefinition(CmsUser currentUser, CmsProject currentProject, String name, String resourcetype, int type) throws CmsException { // check the security if( isAdmin(currentUser, currentProject) ) { // no space before or after the name name = name.trim(); // check the name validName(name, true); m_propertyDefVectorCache.clear(); return( m_dbAccess.createPropertydefinition(name, getResourceType(currentUser, currentProject, resourcetype), type) ); } else { throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_NO_ACCESS); } } public void createResource(CmsProject project, CmsProject onlineProject, CmsResource resource) throws com.opencms.core.CmsException { m_dbAccess.createResource(project, onlineProject, resource); } /** * Creates a new task. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param projectid The Id of the current project task of the user. * @param agentName User who will edit the task * @param roleName Usergroup for the task * @param taskName Name of the task * @param taskType Type of the task * @param taskComment Description of the task * @param timeout Time when the task must finished * @param priority Id for the priority * * @return A new Task Object * * @exception CmsException Throws CmsException if something goes wrong. */ public CmsTask createTask(CmsUser currentUser, int projectid, String agentName, String roleName, String taskName, String taskComment, int taskType, long timeout, int priority) throws CmsException { CmsUser agent = m_dbAccess.readUser(agentName, C_USER_TYPE_SYSTEMUSER); CmsGroup role = m_dbAccess.readGroup(roleName); java.sql.Timestamp timestamp = new java.sql.Timestamp(timeout); java.sql.Timestamp now = new java.sql.Timestamp(System.currentTimeMillis()); CmsTask task = m_dbAccess.createTask(projectid, projectid, taskType, currentUser.getId(), agent.getId(), role.getId(), taskName, now, timestamp, priority); if(taskComment!=null && !taskComment.equals("")) { m_dbAccess.writeTaskLog(task.getId(), currentUser.getId(), new java.sql.Timestamp(System.currentTimeMillis()), taskComment, C_TASKLOG_USER); } return task; } /** * Creates a new task. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param agent Username who will edit the task * @param role Usergroupname for the task * @param taskname Name of the task * @param taskcomment Description of the task. * @param timeout Time when the task must finished * @param priority Id for the priority * * @return A new Task Object * * @exception CmsException Throws CmsException if something goes wrong. */ public CmsTask createTask(CmsUser currentUser, CmsProject currentProject, String agentName, String roleName, String taskname, String taskcomment, long timeout, int priority) throws CmsException { CmsGroup role = m_dbAccess.readGroup(roleName); java.sql.Timestamp timestamp = new java.sql.Timestamp(timeout); java.sql.Timestamp now = new java.sql.Timestamp(System.currentTimeMillis()); int agentId = C_UNKNOWN_ID; try { agentId = m_dbAccess.readUser(agentName, C_USER_TYPE_SYSTEMUSER).getId(); } catch (Exception e) { // ignore that this user doesn't exist and create a task for the role } return m_dbAccess.createTask(currentProject.getTaskId(), currentProject.getTaskId(), 1, // standart Task Type currentUser.getId(), agentId, role.getId(), taskname, now, timestamp, priority); } /** * Deletes all propertyinformation for a file or folder. * * <B>Security</B> * Only the user is granted, who has the right to write the resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The name of the resource of which the propertyinformations * have to be deleted. * * @exception CmsException Throws CmsException if operation was not succesful */ public void deleteAllProperties(CmsUser currentUser, CmsProject currentProject, String resource) throws CmsException { // read the resource CmsResource res = readFileHeader(currentUser,currentProject, resource); // check the security if( ! accessWrite(currentUser, currentProject, res) ) { throw new CmsException("[" + this.getClass().getName() + "] " + resource, CmsException.C_NO_ACCESS); } // are there some mandatory metadefs? if(readAllPropertydefinitions(currentUser, currentProject,res.getType(), C_PROPERTYDEF_TYPE_MANDATORY).size() == 0 ) { // no - delete them all m_dbAccess.deleteAllProperties(res.getResourceId()); m_propertyCache.clear(); } else { // yes - throw exception throw new CmsException("[" + this.getClass().getName() + "] " + resource, CmsException.C_MANDATORY_PROPERTY); } } /** * Deletes a file in the Cms.<br> * * A file can only be deleteed in an offline project. * A file is deleted by setting its state to DELETED (3). <br> * * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can write the resource</li> * <li>the resource is locked by the callinUser</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param filename The complete path of the file. * * @exception CmsException Throws CmsException if operation was not succesful. */ public void deleteFile(CmsUser currentUser, CmsProject currentProject, String filename) throws CmsException { // read the file CmsResource onlineFile; CmsResource file = readFileHeader(currentUser,currentProject, filename); try { onlineFile = readFileHeader(currentUser,onlineProject(currentUser, currentProject), filename); } catch (CmsException exc) { // the file dosent exist onlineFile = null; } // has the user write-access? if( accessWrite(currentUser, currentProject, file) ) { // write-acces was granted - delete the file. // and the metainfos deleteAllProperties(currentUser,currentProject,file.getAbsolutePath()); if(onlineFile == null) { // the onlinefile dosent exist => remove the file realy! m_dbAccess.removeFile(currentProject.getId(), filename); } else { m_dbAccess.deleteFile(currentProject, filename); } // update the cache m_resourceCache.remove(C_FILE+currentProject.getId()+filename); m_subresCache.clear(); m_accessCache.clear(); // inform about the file-system-change fileSystemChanged(false); } else { throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_NO_ACCESS); } } /** * Deletes a folder in the Cms.<br> * * Only folders in an offline Project can be deleted. A folder is deleted by * setting its state to DELETED (3). <br> * * In its current implmentation, this method can ONLY delete empty folders. * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read and write this resource and all subresources</li> * <li>the resource is not locked</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param foldername The complete path of the folder. * * @exception CmsException Throws CmsException if operation was not succesful. */ public void deleteFolder(CmsUser currentUser, CmsProject currentProject, String foldername) throws CmsException { CmsResource onlineFolder; // read the folder, that shold be deleted CmsFolder cmsFolder = readFolder(currentUser,currentProject,foldername); try { onlineFolder = readFolder(currentUser,onlineProject(currentUser, currentProject), foldername); } catch (CmsException exc) { // the file dosent exist onlineFolder = null; } // check, if the user may delete the resource if( accessWrite(currentUser, currentProject, cmsFolder) ) { // write-acces was granted - delete the folder and metainfos. deleteAllProperties(currentUser,currentProject, cmsFolder.getAbsolutePath()); if(onlineFolder == null) { // the onlinefile dosent exist => remove the file realy! m_dbAccess.removeFolder(cmsFolder); } else { m_dbAccess.deleteFolder(currentProject,cmsFolder, false); } // update cache m_resourceCache.remove(C_FOLDER+currentProject.getId()+foldername); m_subresCache.clear(); m_accessCache.clear(); // inform about the file-system-change fileSystemChanged(true); } else { throw new CmsException("[" + this.getClass().getName() + "] " + foldername, CmsException.C_NO_ACCESS); } } /** * Delete a group from the Cms.<BR/> * Only groups that contain no subgroups can be deleted. * * Only the admin can do this.<P/> * * <B>Security:</B> * Only users, which are in the group "administrators" are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param delgroup The name of the group that is to be deleted. * @exception CmsException Throws CmsException if operation was not succesfull. */ public void deleteGroup(CmsUser currentUser, CmsProject currentProject, String delgroup) throws CmsException { // Check the security if( isAdmin(currentUser, currentProject) ) { Vector childs=null; Vector users=null; // get all child groups of the group childs=getChild(currentUser,currentProject,delgroup); // get all users in this group users=getUsersOfGroup(currentUser,currentProject,delgroup); // delete group only if it has no childs and there are no users in this group. if ((childs == null) && ((users == null) || (users.size() == 0))) { m_dbAccess.deleteGroup(delgroup); m_groupCache.remove(delgroup); } else { throw new CmsException(delgroup, CmsException.C_GROUP_NOT_EMPTY); } } else { throw new CmsException("[" + this.getClass().getName() + "] " + delgroup, CmsException.C_NO_ACCESS); } } /** * Deletes a project. * * <B>Security</B> * Only the admin or the owner of the project can do this. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param id The id of the project to be published. * * @exception CmsException Throws CmsException if something goes wrong. */ public void deleteProject(CmsUser currentUser, CmsProject currentProject, int id) throws CmsException { // read the project that should be deleted. CmsProject deleteProject = readProject(currentUser, currentProject, id); if(isAdmin(currentUser, currentProject) || isManagerOfProject(currentUser, deleteProject)) { // delete the project m_dbAccess.deleteProject(deleteProject); m_projectCache.remove(id); } else { throw new CmsException("[" + this.getClass().getName() + "] " + id, CmsException.C_NO_ACCESS); } } /** * Deletes a propertyinformation for a file or folder. * * <B>Security</B> * Only the user is granted, who has the right to write the resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The name of the resource of which the propertyinformation * has to be read. * @param property The propertydefinition-name of which the propertyinformation has to be set. * * @exception CmsException Throws CmsException if operation was not succesful */ public void deleteProperty(CmsUser currentUser, CmsProject currentProject, String resource, String property) throws CmsException { // read the resource CmsResource res = readFileHeader(currentUser,currentProject, resource); // check the security if( ! accessWrite(currentUser, currentProject, res) ) { throw new CmsException("[" + this.getClass().getName() + "] " + resource, CmsException.C_NO_ACCESS); } // read the metadefinition CmsResourceType resType = getResourceType(currentUser,currentProject,res.getType()); CmsPropertydefinition metadef = readPropertydefinition(currentUser,currentProject,property, resType.getResourceName()); // is this a mandatory metadefinition? if( (metadef != null) && (metadef.getPropertydefType() != C_PROPERTYDEF_TYPE_MANDATORY ) ) { // no - delete the information m_dbAccess.deleteProperty(property,res.getResourceId(),res.getType()); // set the file-state to changed if(res.isFile()){ m_dbAccess.writeFileHeader(currentProject, (CmsFile) res, true); if (res.getState()==C_STATE_UNCHANGED) { res.setState(C_STATE_CHANGED); } // update the cache m_resourceCache.put(C_FILE+currentProject.getId()+resource,res); } else { if (res.getState()==C_STATE_UNCHANGED) { res.setState(C_STATE_CHANGED); } m_dbAccess.writeFolder(currentProject, readFolder(currentUser,currentProject, resource), true); // update the cache m_resourceCache.put(C_FOLDER+currentProject.getId()+resource,(CmsFolder)res); } m_subresCache.clear(); m_propertyCache.clear(); } else { // yes - throw exception throw new CmsException("[" + this.getClass().getName() + "] " + resource, CmsException.C_MANDATORY_PROPERTY); } } /** * Delete the propertydefinition for the resource type.<BR/> * * <B>Security</B> * Only the admin can do this. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param name The name of the propertydefinition to read. * @param resourcetype The name of the resource type for which the * propertydefinition is valid. * * @exception CmsException Throws CmsException if something goes wrong. */ public void deletePropertydefinition(CmsUser currentUser, CmsProject currentProject, String name, String resourcetype) throws CmsException { // check the security if( isAdmin(currentUser, currentProject) ) { // first read and then delete the metadefinition. m_propertyDefVectorCache.clear(); m_propertyDefCache.remove(name + (getResourceType(currentUser,currentProject,resourcetype)).getResourceType()); m_dbAccess.deletePropertydefinition( readPropertydefinition(currentUser,currentProject,name,resourcetype)); } else { throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_NO_ACCESS); } } /** * Deletes a user from the Cms. * * Only a adminstrator can do this.<P/> * * <B>Security:</B> * Only users, which are in the group "administrators" are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param userId The Id of the user to be deleted. * * @exception CmsException Throws CmsException if operation was not succesfull. */ public void deleteUser(CmsUser currentUser, CmsProject currentProject, int userId) throws CmsException { CmsUser user = readUser(currentUser,currentProject,userId); deleteUser(currentUser,currentProject,user.getName()); } /** * Deletes a user from the Cms. * * Only a adminstrator can do this.<P/> * * <B>Security:</B> * Only users, which are in the group "administrators" are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param name The name of the user to be deleted. * * @exception CmsException Throws CmsException if operation was not succesfull. */ public void deleteUser(CmsUser currentUser, CmsProject currentProject, String username) throws CmsException { // Test is this user is existing CmsUser user=readUser(currentUser,currentProject,username); // Check the security // Avoid to delete admin or guest-user if( isAdmin(currentUser, currentProject) && !(username.equals(C_USER_ADMIN) || username.equals(C_USER_GUEST))) { m_dbAccess.deleteUser(username); // delete user from cache m_userCache.remove(username+user.getType()); } else { throw new CmsException("[" + this.getClass().getName() + "] " + username, CmsException.C_NO_ACCESS); } } /** * Deletes a web user from the Cms. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param userId The Id of the user to be deleted. * * @exception CmsException Throws CmsException if operation was not succesfull. */ public void deleteWebUser(CmsUser currentUser, CmsProject currentProject, int userId) throws CmsException { CmsUser user = readUser(currentUser,currentProject,userId); m_dbAccess.deleteUser(user.getName()); // delete user from cache m_userCache.remove(user.getName()+user.getType()); } /** * Destroys the resource broker and required modules and connections. * @exception CmsException Throws CmsException if something goes wrong. */ public void destroy() throws CmsException { // destroy the db-access. m_dbAccess.destroy(); } /** * Ends a task from the Cms. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param taskid The ID of the task to end. * * @exception CmsException Throws CmsException if something goes wrong. */ public void endTask(CmsUser currentUser, CmsProject currentProject, int taskid) throws CmsException { m_dbAccess.endTask(taskid); if(currentUser == null) { m_dbAccess.writeSystemTaskLog(taskid, "Task finished."); } else { m_dbAccess.writeSystemTaskLog(taskid, "Task finished by " + currentUser.getFirstname() + " " + currentUser.getLastname() + "."); } } /** * Exports cms-resources to zip. * * <B>Security:</B> * only Administrators can do this; * * @param currentUser user who requestd themethod * @param currentProject current project of the user * @param exportFile the name (absolute Path) of the export resource (zip) * @param exportPath the names (absolute Path) of folders and files which should be exported * @param cms the cms-object to use for the export. * * @exception Throws CmsException if something goes wrong. */ public void exportResources(CmsUser currentUser, CmsProject currentProject, String exportFile, String[] exportPaths, CmsObject cms) throws CmsException { if(isAdmin(currentUser, currentProject)) { new CmsExport(exportFile, exportPaths, cms); } else { throw new CmsException("[" + this.getClass().getName() + "] exportResources", CmsException.C_NO_ACCESS); } } /** * Exports cms-resources to zip. * * <B>Security:</B> * only Administrators can do this; * * @param currentUser user who requestd themethod * @param currentProject current project of the user * @param exportFile the name (absolute Path) of the export resource (zip) * @param exportPath the name (absolute Path) of folder from which should be exported * @param excludeSystem, decides whether to exclude the system * @param excludeUnchanged <code>true</code>, if unchanged files should be excluded. * @param cms the cms-object to use for the export. * * @exception Throws CmsException if something goes wrong. */ public void exportResources(CmsUser currentUser, CmsProject currentProject, String exportFile, String[] exportPaths, CmsObject cms, boolean excludeSystem, boolean excludeUnchanged) throws CmsException { if(isAdmin(currentUser, currentProject)) { new CmsExport(exportFile, exportPaths, cms, excludeSystem, excludeUnchanged); } else { throw new CmsException("[" + this.getClass().getName() + "] exportResources", CmsException.C_NO_ACCESS); } } // now private stuff /** * This method is called, when a resource was changed. Currently it counts the * changes. */ protected void fileSystemChanged(boolean folderChanged) { // count only the changes - do nothing else! // in the future here will maybe a event-story be added m_fileSystemChanges++; if(folderChanged){ m_fileSystemFolderChanges++; } } /** * Forwards a task to a new user. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param taskid The Id of the task to forward. * @param newRole The new Group for the task * @param newUser The new user who gets the task. if its "" the a new agent will automatic selected * * @exception CmsException Throws CmsException if something goes wrong. */ public void forwardTask(CmsUser currentUser, CmsProject currentProject, int taskid, String newRoleName, String newUserName) throws CmsException { CmsGroup newRole = m_dbAccess.readGroup(newRoleName); CmsUser newUser = null; if(newUserName.equals("")) { newUser = m_dbAccess.readUser(m_dbAccess.findAgent(newRole.getId())); } else { newUser = m_dbAccess.readUser(newUserName, C_USER_TYPE_SYSTEMUSER); } m_dbAccess.forwardTask(taskid, newRole.getId(), newUser.getId()); m_dbAccess.writeSystemTaskLog(taskid, "Task fowarded from " + currentUser.getFirstname() + " " + currentUser.getLastname() + " to " + newUser.getFirstname() + " " + newUser.getLastname() + "."); } /** * Returns all projects, which are owned by the user or which are accessible * for the group of the user. * * <B>Security</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * * @return a Vector of projects. */ public Vector getAllAccessibleProjects(CmsUser currentUser, CmsProject currentProject) throws CmsException { // get all groups of the user Vector groups = getGroupsOfUser(currentUser, currentProject, currentUser.getName()); // get all projects which are owned by the user. Vector projects = m_dbAccess.getAllAccessibleProjectsByUser(currentUser); // get all projects, that the user can access with his groups. for(int i = 0; i < groups.size(); i++) { Vector projectsByGroup; // is this the admin-group? if( ((CmsGroup) groups.elementAt(i)).getName().equals(C_GROUP_ADMIN) ) { // yes - all unlocked projects are accessible for him projectsByGroup = m_dbAccess.getAllProjects(C_PROJECT_STATE_UNLOCKED); } else { // no - get all projects, which can be accessed by the current group projectsByGroup = m_dbAccess.getAllAccessibleProjectsByGroup((CmsGroup) groups.elementAt(i)); } // merge the projects to the vector for(int j = 0; j < projectsByGroup.size(); j++) { // add only projects, which are new if(!projects.contains(projectsByGroup.elementAt(j))) { projects.addElement(projectsByGroup.elementAt(j)); } } } // return the vector of projects return(projects); } /** * Returns all projects, which are owned by the user or which are manageable * for the group of the user. * * <B>Security</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * * @return a Vector of projects. */ public Vector getAllManageableProjects(CmsUser currentUser, CmsProject currentProject) throws CmsException { // get all groups of the user Vector groups = getGroupsOfUser(currentUser, currentProject, currentUser.getName()); // get all projects which are owned by the user. Vector projects = m_dbAccess.getAllAccessibleProjectsByUser(currentUser); // get all projects, that the user can manage with his groups. for(int i = 0; i < groups.size(); i++) { // get all projects, which can be managed by the current group Vector projectsByGroup; // is this the admin-group? if( ((CmsGroup) groups.elementAt(i)).getName().equals(C_GROUP_ADMIN) ) { // yes - all unlocked projects are accessible for him projectsByGroup = m_dbAccess.getAllProjects(C_PROJECT_STATE_UNLOCKED); } else { // no - get all projects, which can be accessed by the current group projectsByGroup = m_dbAccess.getAllAccessibleProjectsByManagerGroup((CmsGroup)groups.elementAt(i)); } // merge the projects to the vector for(int j = 0; j < projectsByGroup.size(); j++) { // add only projects, which are new if(!projects.contains(projectsByGroup.elementAt(j))) { projects.addElement(projectsByGroup.elementAt(j)); } } } // remove the online-project, it is not manageable! projects.removeElement(onlineProject(currentUser, currentProject)); // return the vector of projects return(projects); } /** * Returns a Vector with all I_CmsResourceTypes. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * * Returns a Hashtable with all I_CmsResourceTypes. * * @exception CmsException Throws CmsException if operation was not succesful. */ public Hashtable getAllResourceTypes(CmsUser currentUser, CmsProject currentProject) throws CmsException { // check, if the resourceTypes were read bevore if(m_resourceTypes == null) { // read the resourceTypes from the propertys m_resourceTypes = (Hashtable) m_dbAccess.readSystemProperty(C_SYSTEMPROPERTY_RESOURCE_TYPE); // remove the last index. m_resourceTypes.remove(C_TYPE_LAST_INDEX); } // return the resource-types. return(m_resourceTypes); } /** * Returns informations about the cache<P/> * * <B>Security:</B> * All users are granted, except the anonymous user. * * @return A hashtable with informations about the cache. */ public Hashtable getCacheInfo() { Hashtable info = new Hashtable(); info.put("UserCache",""+m_userCache.size()); info.put("GroupCache",""+m_groupCache.size()); info.put("UserGroupCache",""+m_usergroupsCache.size()); info.put("ResourceCache",""+m_resourceCache.size()); info.put("SubResourceCache",""+m_subresCache.size()); info.put("ProjectCache",""+m_projectCache.size()); info.put("PropertyCache",""+m_propertyCache.size()); info.put("PropertyDefinitionCache",""+m_propertyDefCache.size()); info.put("PropertyDefinitionVectorCache",""+m_propertyDefVectorCache.size()); info.put("AccessCache",""+m_accessCache.size()); return info; } /** * Returns all child groups of a group<P/> * * <B>Security:</B> * All users are granted, except the anonymous user. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param groupname The name of the group. * @return groups A Vector of all child groups or null. * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector getChild(CmsUser currentUser, CmsProject currentProject, String groupname) throws CmsException { // check security if( ! anonymousUser(currentUser, currentProject).equals( currentUser ) ) { return m_dbAccess.getChild(groupname); } else { throw new CmsException("[" + this.getClass().getName() + "] " + groupname, CmsException.C_NO_ACCESS); } } /** * Returns all child groups of a group<P/> * This method also returns all sub-child groups of the current group. * * <B>Security:</B> * All users are granted, except the anonymous user. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param groupname The name of the group. * @return groups A Vector of all child groups or null. * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector getChilds(CmsUser currentUser, CmsProject currentProject, String groupname) throws CmsException { // check security if( ! anonymousUser(currentUser, currentProject).equals( currentUser ) ) { Vector childs=new Vector(); Vector allChilds=new Vector(); Vector subchilds=new Vector(); CmsGroup group=null; // get all child groups if the user group childs=m_dbAccess.getChild(groupname); if (childs!=null) { allChilds=childs; // now get all subchilds for each group Enumeration enu=childs.elements(); while (enu.hasMoreElements()) { group=(CmsGroup)enu.nextElement(); subchilds=getChilds(currentUser,currentProject,group.getName()); //add the subchilds to the already existing groups Enumeration enusub=subchilds.elements(); while (enusub.hasMoreElements()) { group=(CmsGroup)enusub.nextElement(); allChilds.addElement(group); } } } return allChilds; } else { throw new CmsException("[" + this.getClass().getName() + "] " + groupname, CmsException.C_NO_ACCESS); } } // Method to access the configuration /** * Method to access the configurations of the properties-file. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @return The Configurations of the properties-file. */ public Configurations getConfigurations(CmsUser currentUser, CmsProject currentProject) { return m_configuration; } /** * Returns the list of groups to which the user directly belongs to<P/> * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param username The name of the user. * @return Vector of groups * @exception CmsException Throws CmsException if operation was not succesful */ public Vector getDirectGroupsOfUser(CmsUser currentUser, CmsProject currentProject, String username) throws CmsException { return m_dbAccess.getGroupsOfUser(username); } /** * Returns a Vector with all files of a folder.<br> * * Files of a folder can be read from an offline Project and the online Project.<br> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read this resource</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param foldername the complete path to the folder. * * @return A Vector with all subfiles for the overgiven folder. * * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector getFilesInFolder(CmsUser currentUser, CmsProject currentProject, String foldername) throws CmsException { Vector files; // Todo: add caching for getFilesInFolder //files=(Vector)m_subresCache.get(C_FILE+currentProject.getId()+foldername); //System.err.println("--fof:"+foldername+":"+files); //if ((files==null) || (files.size()==0)) { // try to get the files in the current project try { files = helperGetFilesInFolder(currentUser, currentProject, foldername); } catch (CmsException e) { //if access is denied to the folder, dont try to read them from the online project.) if (e.getType() == CmsException.C_ACCESS_DENIED) return new Vector(); //an empty vector. else //can't handle it here. throw e; } if (files == null) { //we are not allowed to read the folder (folder deleted) return new Vector(); } Vector onlineFiles = null; if (!currentProject.equals(onlineProject(currentUser, currentProject))) { // this is not the onlineproject, get the files // from the onlineproject, too try { onlineFiles = helperGetFilesInFolder(currentUser, onlineProject(currentUser, currentProject), foldername); // merge the resources } catch (CmsException exc) { if (exc.getType() != CmsException.C_ACCESS_DENIED) //cant handle it. throw exc; else //access denied. return files; } } if(onlineFiles == null) //if it was null, the folder was marked deleted -> no files in online project. return files; //m_subresCache.put(C_FILE+currentProject.getId()+foldername,files); return files = mergeResources(files, onlineFiles); } /** * Returns a Vector with all resource-names that have set the given property to the given value. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param foldername the complete path to the folder. * @param propertydef, the name of the propertydefinition to check. * @param property, the value of the property for the resource. * * @return Vector with all names of resources. * * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector getFilesWithProperty(CmsUser currentUser, CmsProject currentProject, String propertyDefinition, String propertyValue) throws CmsException { return m_dbAccess.getFilesWithProperty(currentProject.getId(), propertyDefinition, propertyValue); } /** * This method can be called, to determine if the file-system was changed * in the past. A module can compare its previosly stored number with this * returned number. If they differ, a change was made. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * * @return the number of file-system-changes. */ public long getFileSystemChanges(CmsUser currentUser, CmsProject currentProject) { return m_fileSystemChanges; } /** * This method can be called, to determine if the file-system was changed * in the past. A module can compare its previosly stored number with this * returned number. If they differ, a change was made. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * * @return the number of file-system-changes. */ public long getFileSystemFolderChanges(CmsUser currentUser, CmsProject currentProject) { return m_fileSystemFolderChanges; } /** * Returns a Vector with the complete folder-tree for this project.<br> * * Subfolders can be read from an offline project and the online project. <br> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read this resource</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * * @return subfolders A Vector with the complete folder-tree for this project. * * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector getFolderTree(CmsUser currentUser, CmsProject currentProject) throws CmsException { Vector resources = m_dbAccess.getFolderTree(currentProject.getId()); Vector retValue = new Vector(resources.size()); String lastcheck = "#"; // just a char that is not valid in a filename //make sure that we have access to all these. for (Enumeration e = resources.elements(); e.hasMoreElements();) { CmsResource res = (CmsResource) e.nextElement(); if (!res.getAbsolutePath().startsWith(lastcheck)) { if (accessOther(currentUser, currentProject, res, C_ACCESS_PUBLIC_READ + C_ACCESS_PUBLIC_VISIBLE) || accessOwner(currentUser, currentProject, res, C_ACCESS_OWNER_READ + C_ACCESS_OWNER_VISIBLE) || accessGroup(currentUser, currentProject, res, C_ACCESS_GROUP_READ + C_ACCESS_GROUP_VISIBLE)) { retValue.addElement(res); } else { lastcheck = res.getAbsolutePath(); } } } return retValue; } /** * Returns all groups<P/> * * <B>Security:</B> * All users are granted, except the anonymous user. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @return users A Vector of all existing groups. * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector getGroups(CmsUser currentUser, CmsProject currentProject) throws CmsException { // check security if( ! anonymousUser(currentUser, currentProject).equals( currentUser ) ) { return m_dbAccess.getGroups(); } else { throw new CmsException("[" + this.getClass().getName() + "] " + currentUser.getName(), CmsException.C_NO_ACCESS); } } /** * Returns a list of groups of a user.<P/> * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param username The name of the user. * @return Vector of groups * @exception CmsException Throws CmsException if operation was not succesful */ public Vector getGroupsOfUser(CmsUser currentUser, CmsProject currentProject, String username) throws CmsException { Vector allGroups; allGroups=(Vector)m_usergroupsCache.get(C_USER+username); if ((allGroups==null) || (allGroups.size()==0)) { CmsGroup subGroup; CmsGroup group; // get all groups of the user Vector groups=m_dbAccess.getGroupsOfUser(username); allGroups=groups; // now get all childs of the groups Enumeration enu = groups.elements(); while (enu.hasMoreElements()) { group=(CmsGroup)enu.nextElement(); subGroup=getParent(currentUser, currentProject,group.getName()); while(subGroup != null) { // is the subGroup already in the vector? if(!allGroups.contains(subGroup)) { // no! add it allGroups.addElement(subGroup); } // read next sub group subGroup = getParent(currentUser, currentProject,subGroup.getName()); } } m_usergroupsCache.put(C_USER+username,allGroups); } return allGroups; } /** * Returns the parent group of a group<P/> * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param groupname The name of the group. * @return group The parent group or null. * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsGroup getParent(CmsUser currentUser, CmsProject currentProject, String groupname) throws CmsException { CmsGroup group = readGroup(currentUser, currentProject, groupname); if (group.getParentId() == C_UNKNOWN_ID) { return null; } // try to read from cache CmsGroup parent = (CmsGroup) m_groupCache.get(group.getParentId()); if (parent == null) { parent = m_dbAccess.readGroup(group.getParentId()); m_groupCache.put(group.getParentId(), parent); } return parent; //return m_dbAccess.getParent(groupname); } /** * Returns the parent resource of a resouce. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param filename The name of the file to be read. * * @return The file read from the Cms. * * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsResource getParentResource(CmsUser currentUser, CmsProject currentProject, String resourcename) throws CmsException { // TODO: this can maybe done via the new parent id'd String parentresourceName = readFileHeader(currentUser, currentProject, resourcename).getParent(); return readFileHeader(currentUser, currentProject, parentresourceName); } /** * Gets the Registry.<BR/> * * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param cms The actual CmsObject * @exception Throws CmsException if access is not allowed. */ public I_CmsRegistry getRegistry(CmsUser currentUser, CmsProject currentProject, CmsObject cms) throws CmsException { return m_registry.clone(cms); } /** * Returns a Vector with the subresources for a folder.<br> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read and view this resource</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param folder The name of the folder to get the subresources from. * * @return subfolders A Vector with resources. * * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector getResourcesInFolder(CmsUser currentUser, CmsProject currentProject, String folder) throws CmsException { CmsFolder onlineFolder = null; CmsFolder offlineFolder = null; Vector resources = new Vector(); int resId1, resId2; try { onlineFolder = readFolder(currentUser, onlineProject(currentUser, currentProject), folder); if (onlineFolder.getState() == C_STATE_DELETED) { onlineFolder = null; } } catch (CmsException exc) { // ignore the exception - folder was not found in this project } try { offlineFolder = readFolder(currentUser, currentProject, folder); if (offlineFolder.getState() == C_STATE_DELETED) { offlineFolder = null; } } catch (CmsException exc) { // ignore the exception - folder was not found in this project } if ((offlineFolder == null) && (onlineFolder == null)) { // the folder is not existent throw new CmsException("[" + this.getClass().getName() + "] " + folder, CmsException.C_NOT_FOUND); } else if (onlineFolder == null) { resId1 = offlineFolder.getResourceId(); resId2 = offlineFolder.getResourceId(); } else if (offlineFolder == null) { resId1 = onlineFolder.getResourceId(); resId2 = onlineFolder.getResourceId(); } else { resId1 = onlineFolder.getResourceId(); resId2 = offlineFolder.getResourceId(); } resources = m_dbAccess.getResourcesInFolder(resId1, resId2); Vector retValue = new Vector(resources.size()); //make sure that we have access to all these. for (Enumeration e = resources.elements(); e.hasMoreElements();) { CmsResource res = (CmsResource) e.nextElement(); if (accessOther(currentUser, currentProject, res, C_ACCESS_PUBLIC_READ + C_ACCESS_PUBLIC_VISIBLE) || accessOwner(currentUser, currentProject, res, C_ACCESS_OWNER_READ + C_ACCESS_OWNER_VISIBLE) || accessGroup(currentUser, currentProject, res, C_ACCESS_GROUP_READ + C_ACCESS_GROUP_VISIBLE)) { retValue.addElement(res); } } return retValue; } /** * Returns a CmsResourceTypes. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resourceType the id of the resourceType to get. * * Returns a CmsResourceTypes. * * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsResourceType getResourceType(CmsUser currentUser, CmsProject currentProject, int resourceType) throws CmsException { // try to get the resource-type Hashtable types = getAllResourceTypes(currentUser, currentProject); Enumeration keys = types.keys(); CmsResourceType currentType; while(keys.hasMoreElements()) { currentType = (CmsResourceType) types.get(keys.nextElement()); if(currentType.getResourceType() == resourceType) { return(currentType); } } // was not found - throw exception throw new CmsException("[" + this.getClass().getName() + "] " + resourceType, CmsException.C_NOT_FOUND); } /** * Returns a CmsResourceTypes. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resourceType the name of the resource to get. * * Returns a CmsResourceTypes. * * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsResourceType getResourceType(CmsUser currentUser, CmsProject currentProject, String resourceType) throws CmsException { // try to get the resource-type try { CmsResourceType type = (CmsResourceType)getAllResourceTypes(currentUser, currentProject).get(resourceType); if(type == null) { throw new CmsException("[" + this.getClass().getName() + "] " + resourceType, CmsException.C_NOT_FOUND); } return type; } catch(NullPointerException exc) { // was not found - throw exception throw new CmsException("[" + this.getClass().getName() + "] " + resourceType, CmsException.C_NOT_FOUND); } } /** * Returns the session storage after a securtity check. * * <B>Security:</B> * All users except the guest user are granted. * * @param currentUser The user who requested this method. * @param storage The storage of all active users. * @return The storage of all active users or null. */ public CmsCoreSession getSessionStorage(CmsUser currentUser, CmsCoreSession storage) { if (currentUser.getName().equals(C_USER_GUEST)) { return null; } else { return storage; } } /** * Returns a Vector with all subfolders.<br> * * Subfolders can be read from an offline project and the online project. <br> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read this resource</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param foldername the complete path to the folder. * * @return subfolders A Vector with all subfolders for the given folder. * * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector getSubFolders(CmsUser currentUser, CmsProject currentProject, String foldername) throws CmsException { Vector folders = new Vector(); // Todo: add caching for getSubFolders //folders=(Vector)m_subresCache.get(C_FOLDER+currentProject.getId()+foldername); if ((folders==null) || (folders.size()==0)){ folders=new Vector(); // try to get the folders in the current project try { folders = helperGetSubFolders(currentUser, currentProject, foldername); } catch (CmsException exc) { // no folders, ignoring them } if( !currentProject.equals(onlineProject(currentUser, currentProject))) { // this is not the onlineproject, get the files // from the onlineproject, too try { Vector onlineFolders = helperGetSubFolders(currentUser, onlineProject(currentUser, currentProject), foldername); // merge the resources folders = mergeResources(folders, onlineFolders); } catch(CmsException exc) { // no onlinefolders, ignoring them } } //m_subresCache.put(C_FOLDER+currentProject.getId()+foldername,folders); } // return the folders return(folders); } /** * Get a parameter value for a task. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param taskId The Id of the task. * @param parName Name of the parameter. * * @exception CmsException Throws CmsException if something goes wrong. */ public String getTaskPar(CmsUser currentUser, CmsProject currentProject, int taskId, String parName) throws CmsException { return m_dbAccess.getTaskPar(taskId, parName); } /** * Get the template task id fo a given taskname. * * @param taskName Name of the Task * * @return id from the task template * * @exception CmsException Throws CmsException if something goes wrong. */ public int getTaskType(String taskName) throws CmsException { return m_dbAccess.getTaskType(taskName); } /** * Returns all users<P/> * * <B>Security:</B> * All users are granted, except the anonymous user. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @return users A Vector of all existing users. * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector getUsers(CmsUser currentUser, CmsProject currentProject) throws CmsException { // check security if( ! anonymousUser(currentUser, currentProject).equals( currentUser ) ) { return m_dbAccess.getUsers(C_USER_TYPE_SYSTEMUSER); } else { throw new CmsException("[" + this.getClass().getName() + "] " + currentUser.getName(), CmsException.C_NO_ACCESS); } } /** * Returns all users from a given type<P/> * * <B>Security:</B> * All users are granted, except the anonymous user. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param type The type of the users. * @return users A Vector of all existing users. * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector getUsers(CmsUser currentUser, CmsProject currentProject, int type) throws CmsException { // check security if( ! anonymousUser(currentUser, currentProject).equals( currentUser ) ) { return m_dbAccess.getUsers(type); } else { throw new CmsException("[" + this.getClass().getName() + "] " + currentUser.getName(), CmsException.C_NO_ACCESS); } } /** * Returns all users from a given type that start with a specified string<P/> * * <B>Security:</B> * All users are granted, except the anonymous user. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param type The type of the users. * @param namestart The filter for the username * @return users A Vector of all existing users. * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector getUsers(CmsUser currentUser, CmsProject currentProject, int type, String namestart) throws CmsException { // check security if( ! anonymousUser(currentUser, currentProject).equals( currentUser ) ) { return m_dbAccess.getUsers(type,namestart); } else { throw new CmsException("[" + this.getClass().getName() + "] " + currentUser.getName(), CmsException.C_NO_ACCESS); } } /** * Returns a list of users in a group.<P/> * * <B>Security:</B> * All users are granted, except the anonymous user. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param groupname The name of the group to list users from. * @return Vector of users. * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector getUsersOfGroup(CmsUser currentUser, CmsProject currentProject, String groupname) throws CmsException { // check the security if( ! anonymousUser(currentUser, currentProject).equals( currentUser ) ) { return m_dbAccess.getUsersOfGroup(groupname, C_USER_TYPE_SYSTEMUSER); } else { throw new CmsException("[" + this.getClass().getName() + "] " + groupname, CmsException.C_NO_ACCESS); } } /** * A helper to copy a resource from the online project to a new, specified project.<br> * * @param onlineProject The online project. * @param offlineProject The offline project. * @param resource The name of the resource. * @exception CmsException Throws CmsException if operation was not succesful. */ protected void helperCopyResourceToProject(CmsUser currentUser, CmsProject onlineProject, CmsProject offlineProject, String resource) throws CmsException { try { // read the online-resource CmsResource onlineRes = readFileHeader(currentUser,onlineProject, resource); // copy it to the offlineproject m_dbAccess.copyResourceToProject(offlineProject, onlineProject,onlineRes); // read the offline-resource CmsResource offlineRes = readFileHeader(currentUser,offlineProject, resource); // copy the metainfos m_dbAccess.writeProperties(readAllProperties(currentUser,onlineProject,onlineRes.getAbsolutePath()),offlineRes.getResourceId(),offlineRes.getType()); //currentUser,offlineProject,offlineRes.getAbsolutePath(), readAllProperties(currentUser,onlineProject,onlineRes.getAbsolutePath())); offlineRes.setState(C_STATE_UNCHANGED); if (offlineRes instanceof CmsFolder) { m_dbAccess.writeFolder(offlineProject,(CmsFolder)offlineRes,false); // update the cache m_resourceCache.put(C_FOLDER+offlineProject.getId()+offlineRes.getName(),(CmsFolder)offlineRes); } else { //(offlineRes instanceof CmsFile) m_dbAccess.writeFileHeader(offlineProject,(CmsFile)offlineRes,false); // update the cache m_resourceCache.put(C_FILE+offlineProject.getId()+offlineRes.getName(),offlineRes); } m_subresCache.clear(); // inform about the file-system-change fileSystemChanged(true); // now walk recursive through all files and folders, and copy them too if(onlineRes.isFolder()) { Vector files = getFilesInFolder(currentUser,onlineProject, resource); Vector folders = getSubFolders(currentUser,onlineProject, resource); for(int i = 0; i < folders.size(); i++) { helperCopyResourceToProject(currentUser,onlineProject, offlineProject, ((CmsResource)folders.elementAt(i)).getAbsolutePath()); } for(int i = 0; i < files.size(); i++) { helperCopyResourceToProject(currentUser,onlineProject, offlineProject, ((CmsResource)files.elementAt(i)).getAbsolutePath()); } } } catch (CmsException exc) { exc.printStackTrace(); } } /** * A helper method for this resource-broker. * Returns a Vector with all files of a folder. * The method does not read any files from the parrent folder, * and do also return deleted files. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param foldername the complete path to the folder. * * @return subfiles A Vector with all subfiles for the overgiven folder. * * @exception CmsException Throws CmsException if operation was not succesful. */ protected Vector helperGetFilesInFolder(CmsUser currentUser, CmsProject currentProject, String foldername) throws CmsException { // get the folder CmsFolder cmsFolder = null; try { cmsFolder = readFolder(currentUser,currentProject, currentProject.getId(), foldername); } catch(CmsException exc) { if(exc.getType() == exc.C_NOT_FOUND) { // ignore the exception - file dosen't exist in this project return new Vector(); //just an empty vector. } else { throw exc; } } if (cmsFolder.getState() == I_CmsConstants.C_STATE_DELETED) { //indicate that the folder was found, but deleted, and resources are not avaiable. return null; } Vector _files = m_dbAccess.getFilesInFolder(cmsFolder); Vector files = new Vector(_files.size()); //make sure that we have access to all these. for (Enumeration e = _files.elements();e.hasMoreElements();) { CmsFile file = (CmsFile) e.nextElement(); if( accessOther(currentUser, currentProject, (CmsResource)file, C_ACCESS_PUBLIC_READ) || accessOwner(currentUser, currentProject, (CmsResource)file, C_ACCESS_OWNER_READ) || accessGroup(currentUser, currentProject, (CmsResource)file, C_ACCESS_GROUP_READ) ) { files.addElement(file); } } return files; } /** * A helper method for this resource-broker. * Returns a Hashtable with all subfolders.<br> * * Subfolders can be read from an offline project and the online project. <br> * * @param currentUser The user who requested this method. * @param currentProject The current project to read the folders from. * @param foldername the complete path to the folder. * * @return subfolders A Hashtable with all subfolders for the given folder. * * @exception CmsException Throws CmsException if operation was not succesful. */ protected Vector helperGetSubFolders(CmsUser currentUser, CmsProject currentProject, String foldername) throws CmsException{ CmsFolder cmsFolder = readFolder(currentUser,currentProject,currentProject.getId(),foldername); if( accessRead(currentUser, currentProject, (CmsResource)cmsFolder) ) { // acces to all subfolders was granted - return the sub-folders. Vector folders = m_dbAccess.getSubFolders(cmsFolder); CmsFolder folder; for(int z=0 ; z < folders.size() ; z++) { // read the current folder folder = (CmsFolder)folders.elementAt(z); // check the readability for the folder if( !( accessOther(currentUser, currentProject, (CmsResource)folder, C_ACCESS_PUBLIC_READ) || accessOwner(currentUser, currentProject, (CmsResource)folder, C_ACCESS_OWNER_READ) || accessGroup(currentUser, currentProject, (CmsResource)folder, C_ACCESS_GROUP_READ) ) ) { // access to the folder was not granted delete him folders.removeElementAt(z); // correct the index z } } return folders; } else { throw new CmsException("[" + this.getClass().getName() + "] " + foldername, CmsException.C_ACCESS_DENIED); } } /** * Imports a import-resource (folder or zipfile) to the cms. * * <B>Security:</B> * only Administrators can do this; * * @param currentUser user who requestd themethod * @param currentProject current project of the user * @param importFile the name (absolute Path) of the import resource (zip or folder) * @param importPath the name (absolute Path) of folder in which should be imported * @param cms the cms-object to use for the import. * * @exception Throws CmsException if something goes wrong. */ public void importFolder(CmsUser currentUser, CmsProject currentProject, String importFile, String importPath, CmsObject cms) throws CmsException { if(isAdmin(currentUser, currentProject)) { new CmsImportFolder(importFile, importPath, cms); } else { throw new CmsException("[" + this.getClass().getName() + "] importResources", CmsException.C_NO_ACCESS); } } // Methods working with database import and export /** * Imports a import-resource (folder or zipfile) to the cms. * * <B>Security:</B> * only Administrators can do this; * * @param currentUser user who requestd themethod * @param currentProject current project of the user * @param importFile the name (absolute Path) of the import resource (zip or folder) * @param importPath the name (absolute Path) of folder in which should be imported * @param cms the cms-object to use for the import. * * @exception Throws CmsException if something goes wrong. */ public void importResources(CmsUser currentUser, CmsProject currentProject, String importFile, String importPath, CmsObject cms) throws CmsException { if(isAdmin(currentUser, currentProject)) { CmsImport imp = new CmsImport(importFile, importPath, cms); imp.importResources(); } else { throw new CmsException("[" + this.getClass().getName() + "] importResources", CmsException.C_NO_ACCESS); } } // Internal ResourceBroker methods /** * Initializes the resource broker and sets up all required modules and connections. * @param config The OpenCms configuration. * @exception CmsException Throws CmsException if something goes wrong. */ public void init(Configurations config) throws CmsException { // Store the configuration. m_configuration = config; if (config.getString("publishproject.delete", "false").toLowerCase().equals("true")) { m_deletePublishedProject = true; } // initialize the access-module. if(A_OpenCms.isLogging()) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsResourceBroker] init the dbaccess-module."); } m_dbAccess = createDbAccess(config); // initalize the caches m_userCache=new CmsCache(config.getInteger(C_CONFIGURATION_CACHE + ".user", 50)); m_groupCache = new CmsCache(config.getInteger(C_CONFIGURATION_CACHE + ".group", 50)); m_usergroupsCache = new CmsCache(config.getInteger(C_CONFIGURATION_CACHE + ".usergroups", 50)); m_projectCache = new CmsCache(config.getInteger(C_CONFIGURATION_CACHE + ".project", 50)); m_onlineProjectCache = new CmsCache(config.getInteger(C_CONFIGURATION_CACHE + ".onlineproject", 50)); m_resourceCache=new CmsCache(config.getInteger(C_CONFIGURATION_CACHE + ".resource", 1000)); m_subresCache = new CmsCache(config.getInteger(C_CONFIGURATION_CACHE + ".subres", 100)); m_propertyCache = new CmsCache(config.getInteger(C_CONFIGURATION_CACHE + ".property", 1000)); m_propertyDefCache = new CmsCache(config.getInteger(C_CONFIGURATION_CACHE + ".propertydef", 100)); m_propertyDefVectorCache = new CmsCache(config.getInteger(C_CONFIGURATION_CACHE + ".propertyvectordef", 100)); m_accessCache = new CmsCache(config.getInteger(C_CONFIGURATION_CACHE + ".access", 1000)); m_cachelimit = config.getInteger(C_CONFIGURATION_CACHE + ".maxsize", 20000); m_refresh=config.getString(C_CONFIGURATION_CACHE + ".refresh", ""); // initialize the registry if(A_OpenCms.isLogging()) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[CmsResourceBroker] init registry."); } try { m_registry= new CmsRegistry(config.getString(C_CONFIGURATION_REGISTRY)); } catch (CmsException ex) { throw ex; } catch(Exception ex) { // init of registry failed - throw exception throw new CmsException("Init of registry failed", CmsException.C_REGISTRY_ERROR, ex); } } /** * Determines, if the users current group is the admin-group. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @return true, if the users current group is the admin-group, * else it returns false. * @exception CmsException Throws CmsException if operation was not succesful. */ public boolean isAdmin(CmsUser currentUser, CmsProject currentProject) throws CmsException { return userInGroup(currentUser, currentProject,currentUser.getName(), C_GROUP_ADMIN); } /** * Determines, if the users may manage a project.<BR/> * Only the manager of a project may publish it. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @return true, if the may manage this project. * @exception CmsException Throws CmsException if operation was not succesful. */ public boolean isManagerOfProject(CmsUser currentUser, CmsProject currentProject) throws CmsException { // is the user owner of the project? if( currentUser.getId() == currentProject.getOwnerId() ) { // YES return true; } // get all groups of the user Vector groups = getGroupsOfUser(currentUser, currentProject, currentUser.getName()); for(int i = 0; i < groups.size(); i++) { // is this a managergroup for this project? if( ((CmsGroup)groups.elementAt(i)).getId() == currentProject.getManagerGroupId() ) { // this group is manager of the project return true; } } // this user is not manager of this project return false; } /** * Determines, if the users current group is the projectleader-group.<BR/> * All projectleaders can create new projects, or close their own projects. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @return true, if the users current group is the projectleader-group, * else it returns false. * @exception CmsException Throws CmsException if operation was not succesful. */ public boolean isProjectManager(CmsUser currentUser, CmsProject currentProject) throws CmsException { return userInGroup(currentUser, currentProject,currentUser.getName(), C_GROUP_PROJECTLEADER); } /** * Returns the user, who had locked the resource.<BR/> * * A user can lock a resource, so he is the only one who can write this * resource. This methods checks, if a resource was locked. * * @param user The user who wants to lock the file. * @param project The project in which the resource will be used. * @param resource The resource. * * @return the user, who had locked the resource. * * @exception CmsException will be thrown, if the user has not the rights * for this resource. */ public CmsUser lockedBy(CmsUser currentUser, CmsProject currentProject, CmsResource resource) throws CmsException { return readUser(currentUser,currentProject,resource.isLockedBy() ) ; } /** * Returns the user, who had locked the resource.<BR/> * * A user can lock a resource, so he is the only one who can write this * resource. This methods checks, if a resource was locked. * * @param user The user who wants to lock the file. * @param project The project in which the resource will be used. * @param resource The complete path to the resource. * * @return the user, who had locked the resource. * * @exception CmsException will be thrown, if the user has not the rights * for this resource. */ public CmsUser lockedBy(CmsUser currentUser, CmsProject currentProject, String resource) throws CmsException { return readUser(currentUser,currentProject,readFileHeader(currentUser, currentProject, resource).isLockedBy() ) ; } /** * Locks a resource.<br> * * Only a resource in an offline project can be locked. The state of the resource * is set to CHANGED (1). * If the content of this resource is not exisiting in the offline project already, * it is read from the online project and written into the offline project. * A user can lock a resource, so he is the only one who can write this * resource. <br> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can write the resource</li> * <li>the resource is not locked by another user</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The complete path to the resource to lock. * @param force If force is true, a existing locking will be oberwritten. * * @exception CmsException Throws CmsException if operation was not succesful. * It will also be thrown, if there is a existing lock * and force was set to false. */ public void lockResource(CmsUser currentUser, CmsProject currentProject, String resourcename, boolean force) throws CmsException { CmsResource cmsResource=null; // read the resource, that shold be locked if (resourcename.endsWith("/")) { cmsResource = (CmsFolder)readFolder(currentUser,currentProject,resourcename); } else { cmsResource = (CmsFile)readFileHeader(currentUser,currentProject,resourcename); } // Can't lock what isn't there if (cmsResource == null) throw new CmsException(CmsException.C_NOT_FOUND); // check, if the resource is in the offline-project if(cmsResource.getProjectId() != currentProject.getId()) { // the resource is not in the current project and can't be locked - so ignore. return; } // check, if the user may lock the resource if( accessLock(currentUser, currentProject, cmsResource) ) { if(cmsResource.isLocked()) { //if (cmsResource.isLockedBy()!=currentUser.getId()) { // if the force switch is not set, throw an exception if (force==false) { throw new CmsException("["+this.getClass().getName()+"] "+resourcename,CmsException.C_LOCKED); } } // lock the resouece cmsResource.setLocked(currentUser.getId()); //update resource m_dbAccess.updateLockstate(cmsResource); // update the cache if (resourcename.endsWith("/")) { //m_dbAccess.writeFolder(currentProject,(CmsFolder)cmsResource,false); m_resourceCache.put(C_FOLDER+currentProject.getId()+resourcename,(CmsFolder)cmsResource); } else { //m_dbAccess.writeFileHeader(currentProject,onlineProject(currentUser, currentProject),(CmsFile)cmsResource,false); m_resourceCache.put(C_FILE+currentProject.getId()+resourcename,(CmsFile)cmsResource); } m_subresCache.clear(); // if this resource is a folder -> lock all subresources, too if(cmsResource.isFolder()) { Vector files = getFilesInFolder(currentUser,currentProject, cmsResource.getAbsolutePath()); Vector folders = getSubFolders(currentUser,currentProject, cmsResource.getAbsolutePath()); CmsResource currentResource; // lock all files in this folder for(int i = 0; i < files.size(); i++ ) { currentResource = (CmsResource)files.elementAt(i); if (currentResource.getState() != C_STATE_DELETED) { lockResource(currentUser, currentProject, currentResource.getAbsolutePath(), true); } } // lock all files in this folder for(int i = 0; i < folders.size(); i++) { currentResource = (CmsResource)folders.elementAt(i); if (currentResource.getState() != C_STATE_DELETED) { lockResource(currentUser, currentProject, currentResource.getAbsolutePath(), true); } } } } else { throw new CmsException("[" + this.getClass().getName() + "] " + resourcename, CmsException.C_NO_ACCESS); } } // Methods working with user and groups /** * Logs a user into the Cms, if the password is correct. * * <B>Security</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param username The name of the user to be returned. * @param password The password of the user to be returned. * @return the logged in user. * * @exception CmsException Throws CmsException if operation was not succesful */ public CmsUser loginUser(CmsUser currentUser, CmsProject currentProject, String username, String password) throws CmsException { CmsUser newUser = readUser(currentUser, currentProject, username, password); // is the user enabled? if( newUser.getFlags() == C_FLAG_ENABLED ) { // Yes - log him in! // first write the lastlogin-time. newUser.setLastlogin(new Date().getTime()); // write the user back to the cms. m_dbAccess.writeUser(newUser); // update cache m_userCache.put(newUser.getName()+newUser.getType(),newUser); return(newUser); } else { // No Access! throw new CmsException("[" + this.getClass().getName() + "] " + username, CmsException.C_NO_ACCESS ); } } /** * Logs a web user into the Cms, if the password is correct. * * <B>Security</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param username The name of the user to be returned. * @param password The password of the user to be returned. * @return the logged in user. * * @exception CmsException Throws CmsException if operation was not succesful */ public CmsUser loginWebUser(CmsUser currentUser, CmsProject currentProject, String username, String password) throws CmsException { CmsUser newUser = readWebUser(currentUser, currentProject, username, password); // is the user enabled? if( newUser.getFlags() == C_FLAG_ENABLED ) { // Yes - log him in! // first write the lastlogin-time. newUser.setLastlogin(new Date().getTime()); // write the user back to the cms. m_dbAccess.writeUser(newUser); // update cache m_userCache.put(newUser.getName()+newUser.getType(),newUser); return(newUser); } else { // No Access! throw new CmsException("[" + this.getClass().getName() + "] " + username, CmsException.C_NO_ACCESS ); } } /** * Merges two resource-vectors into one vector. * All offline-resources will be putted to the return-vector. All additional * online-resources will be putted to the return-vector, too. All online resources, * which are present in the offline-vector will be ignored. * * * @param offline The vector with the offline resources. * @param online The vector with the online resources. * @return The merged vector. */ protected Vector mergeResources(Vector offline, Vector online) { //dont do anything if any of the given vectors are empty or null. if ((offline == null) || (offline.size() == 0)) return (online!=null)?online:new Vector(); if ((online == null) || (online.size() == 0)) return (offline!=null)?offline:new Vector(); // create a vector for the merged offline //remove all objects in the online vector that are present in the offline vector. for (Enumeration e=offline.elements();e.hasMoreElements();) { CmsResource cr = (CmsResource) e.nextElement(); Resource r = new Resource(cr.getAbsolutePath()); online.removeElement(r); } //merge the two vectors. If both vectors were sorted, the mereged vector will remain sorted. Vector merged = new Vector(offline.size() + online.size()); int offIndex = 0; int onIndex = 0; while ((offIndex < offline.size()) || (onIndex < online.size())) { if (offIndex >= offline.size()) { merged.addElement(online.elementAt(onIndex++)); continue; } if (onIndex >= online.size()) { merged.addElement(offline.elementAt(offIndex++)); continue; } String on = ((CmsResource)online.elementAt(onIndex)).getAbsolutePath(); String off = ((CmsResource)offline.elementAt(offIndex)).getAbsolutePath(); if (on.compareTo(off) < 0) merged.addElement(online.elementAt(onIndex++)); else merged.addElement(offline.elementAt(offIndex++)); } return(merged); } /** * Moves the file. * * This operation includes a copy and a delete operation. These operations * are done with their security-checks. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param source The complete path of the sourcefile. * @param destination The complete path of the destinationfile. * * @exception CmsException will be thrown, if the file couldn't be moved. * The CmsException will also be thrown, if the user has not the rights * for this resource. */ public void moveFile(CmsUser currentUser, CmsProject currentProject, String source, String destination) throws CmsException { // read the file to check access CmsResource file = readFileHeader(currentUser,currentProject, source); // has the user write-access? if (accessWrite(currentUser, currentProject, file)) { // first copy the file, this may ends with an exception copyFile(currentUser, currentProject, source, destination); // then delete the source-file, this may end with an exception // => the file was only copied, not moved! deleteFile(currentUser, currentProject, source); // inform about the file-system-change fileSystemChanged(file.isFolder()); } else { throw new CmsException("[" + this.getClass().getName() + "] " + source, CmsException.C_NO_ACCESS); } } /** * Returns the onlineproject. All anonymous * (CmsUser callingUser, or guest) users will see the resources of this project. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @return the onlineproject object. * @exception CmsException Throws CmsException if something goes wrong. */ public CmsProject onlineProject(CmsUser currentUser, CmsProject currentProject) throws CmsException { CmsProject project = null; // try to get the online project for this offline project from cache project = (CmsProject) m_onlineProjectCache.get(currentProject.getId()); if (project == null) { // the project was not in the cache // lookup the currentProject in the CMS_SITE_PROJECT table, and in the same call return it. project = m_dbAccess.getOnlineProject(currentProject.getId()); // store the project into the cache m_onlineProjectCache.put(currentProject.getId(), project); } return project; } /** * Publishes a project. * * <B>Security</B> * Only the admin or the owner of the project can do this. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param id The id of the project to be published. * @return a vector of changed resources. * * @exception CmsException Throws CmsException if something goes wrong. */ public void publishProject(CmsUser currentUser, CmsProject currentProject, int id) throws CmsException { CmsProject publishProject = readProject(currentUser, currentProject, id); // check the security if ((isAdmin(currentUser, currentProject) || isManagerOfProject(currentUser, publishProject)) && (publishProject.getFlags() == C_PROJECT_STATE_UNLOCKED)) { m_dbAccess.publishProject(currentUser, id, onlineProject(currentUser, currentProject)); m_subresCache.clear(); // inform about the file-system-change fileSystemChanged(true); // the project-state will be set to "published", the date will be set. // the project must be written to the cms. CmsProject project = readProject(currentUser, currentProject, id); project.setFlags(C_PROJECT_STATE_ARCHIVE); project.setPublishingDate(new Date().getTime()); project.setPublishedBy(currentUser.getId()); m_dbAccess.writeProject(project); m_projectCache.put(project.getId(), project); // finally set the refrish signal to another server if nescessary if (m_refresh.length() > 0) { try { URL url = new URL(m_refresh); URLConnection con = url.openConnection(); con.connect(); InputStream in = con.getInputStream(); in.close(); System.err.println(in.toString()); } catch (Exception ex) { throw new CmsException(0, ex); } } // HACK: now currently we can delete the project to decrease the amount of data in the db if (m_deletePublishedProject) { deleteProject(currentUser, currentProject, id); } } else { throw new CmsException("[" + this.getClass().getName() + "] could not publish project " + id, CmsException.C_NO_ACCESS); } } /** * Reads the agent of a task from the OpenCms. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param task The task to read the agent from. * @return The owner of a task. * * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsUser readAgent(CmsUser currentUser, CmsProject currentProject, CmsTask task) throws CmsException { return readUser(currentUser,currentProject,task.getAgentUser()); } /** * Reads all file headers of a file in the OpenCms.<BR> * This method returns a vector with the histroy of all file headers, i.e. * the file headers of a file, independent of the project they were attached to.<br> * * The reading excludes the filecontent. * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user can read the resource</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param filename The name of the file to be read. * * @return Vector of file headers read from the Cms. * * @exception CmsException Throws CmsException if operation was not succesful. */ public Vector readAllFileHeaders(CmsUser currentUser, CmsProject currentProject, String filename) throws CmsException { CmsResource cmsFile = readFileHeader(currentUser,currentProject, filename); if( accessRead(currentUser, currentProject, cmsFile) ) { // acces to all subfolders was granted - return the file-history. return(m_dbAccess.readAllFileHeaders(filename)); } else { throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_ACCESS_DENIED); } } /** * Returns a list of all propertyinformations of a file or folder. * * <B>Security</B> * Only the user is granted, who has the right to view the resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The name of the resource of which the propertyinformation has to be * read. * * @return Vector of propertyinformation as Strings. * * @exception CmsException Throws CmsException if operation was not succesful */ public Hashtable readAllProperties(CmsUser currentUser, CmsProject currentProject, String resource) throws CmsException { CmsResource res; // read the resource from the currentProject, or the online-project try { res = readFileHeader(currentUser,currentProject, resource); } catch(CmsException exc) { // the resource was not readable if(currentProject.equals(onlineProject(currentUser, currentProject))) { // this IS the onlineproject - throw the exception throw exc; } else { // try to read the resource in the onlineproject res = readFileHeader(currentUser,onlineProject(currentUser, currentProject), resource); } } // check the security if( ! accessRead(currentUser, currentProject, res) ) { throw new CmsException("[" + this.getClass().getName() + "] " + resource, CmsException.C_NO_ACCESS); } Hashtable returnValue = null; returnValue = (Hashtable)m_propertyCache.get(Integer.toString(res.getResourceId()) +"_"+ Integer.toString(res.getType())); if (returnValue == null){ returnValue = m_dbAccess.readAllProperties(res.getResourceId(),res.getType()); m_propertyCache.put(Integer.toString(res.getResourceId()) +"_"+ Integer.toString(res.getType()),returnValue); } return returnValue; } /** * Reads all propertydefinitions for the given resource type. * * <B>Security</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param id The id the resource type to read the propertydefinitions for. * @param type The type of the propertydefinition (normal|mandatory|optional). * * @return propertydefinitions A Vector with propertydefefinitions for the resource type. * The Vector is maybe empty. * * @exception CmsException Throws CmsException if something goes wrong. */ public Vector readAllPropertydefinitions(CmsUser currentUser, CmsProject currentProject, int id, int type) throws CmsException { Vector returnValue = null; returnValue = (Vector) m_propertyDefVectorCache.get(Integer.toString(id) + "_" + Integer.toString(type)); if (returnValue == null){ returnValue = m_dbAccess.readAllPropertydefinitions(id,type); m_propertyDefVectorCache.put(Integer.toString(id) + "_" + Integer.toString(type), returnValue); } return returnValue; } /** * Reads all propertydefinitions for the given resource type. * * <B>Security</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resourcetype The name of the resource type to read the propertydefinitions for. * * @return propertydefinitions A Vector with propertydefefinitions for the resource type. * The Vector is maybe empty. * * @exception CmsException Throws CmsException if something goes wrong. */ public Vector readAllPropertydefinitions(CmsUser currentUser, CmsProject currentProject, String resourcetype) throws CmsException { Vector returnValue = null; CmsResourceType resType = getResourceType(currentUser, currentProject, resourcetype); returnValue = (Vector)m_propertyDefVectorCache.get(resType.getResourceName()); if (returnValue == null){ returnValue = m_dbAccess.readAllPropertydefinitions(resType); m_propertyDefVectorCache.put(resType.getResourceName(), returnValue); } return returnValue; } /** * Reads all propertydefinitions for the given resource type. * * <B>Security</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resourcetype The name the resource type to read the propertydefinitions for. * @param type The type of the propertydefinition (normal|mandatory|optional). * * @return propertydefinitions A Vector with propertydefefinitions for the resource type. * The Vector is maybe empty. * * @exception CmsException Throws CmsException if something goes wrong. */ public Vector readAllPropertydefinitions(CmsUser currentUser, CmsProject currentProject, String resourcetype, int type) throws CmsException { CmsResourceType restype=getResourceType(currentUser,currentProject,resourcetype); return readAllPropertydefinitions(currentUser, currentProject, restype.getResourceType(),type); } // Methods working with system properties /** * Reads the export-path for the system. * This path is used for db-export and db-import. * * <B>Security:</B> * All users are granted.<BR/> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @return the exportpath. */ public String readExportPath(CmsUser currentUser, CmsProject currentProject) throws CmsException { return (String) m_dbAccess.readSystemProperty(C_SYSTEMPROPERTY_EXPORTPATH); } /** * Reads a file from a previous project of the Cms.<BR/> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read the resource</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param projectId The id of the project to read the file from. * @param filename The name of the file to be read. * * @return The file read from the Cms. * * @exception CmsException Throws CmsException if operation was not succesful. * */ public CmsFile readFile(CmsUser currentUser, CmsProject currentProject, int projectId, String filename) throws CmsException { CmsFile cmsFile = null; // read the resource from the projectId, try { //cmsFile=(CmsFile)m_resourceCache.get(C_FILECONTENT+projectId+filename); if (cmsFile == null) { cmsFile = m_dbAccess.readFile(projectId, onlineProject(currentUser, currentProject).getId(), filename); // only put it in thecache until the size is below the max site /*if (cmsFile.getContents().length <m_cachelimit) { m_resourceCache.put(C_FILECONTENT+projectId+filename,cmsFile); } else { }*/ } if (accessRead(currentUser, currentProject, (CmsResource) cmsFile)) { // acces to all subfolders was granted - return the file. return cmsFile; } else { throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_ACCESS_DENIED); } } catch (CmsException exc) { throw exc; } } /** * Reads a file from the Cms.<BR/> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read the resource</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param filename The name of the file to be read. * * @return The file read from the Cms. * * @exception CmsException Throws CmsException if operation was not succesful. * */ public CmsFile readFile(CmsUser currentUser, CmsProject currentProject, String filename) throws CmsException { CmsFile cmsFile = null; // read the resource from the currentProject, or the online-project try { //cmsFile=(CmsFile)m_resourceCache.get(C_FILECONTENT+currentProject.getId()+filename); if (cmsFile == null) { cmsFile = m_dbAccess.readFile(currentProject.getId(), onlineProject(currentUser, currentProject).getId(), filename); // only put it in thecache until the size is below the max site /*if (cmsFile.getContents().length <m_cachelimit) { m_resourceCache.put(C_FILECONTENT+currentProject.getId()+filename,cmsFile); } else { }*/ } } catch (CmsException exc) { // the resource was not readable if (exc.getType() == CmsException.C_RESOURCE_DELETED) { //resource deleted throw exc; } else if (currentProject.equals(onlineProject(currentUser, currentProject))) { // this IS the onlineproject - throw the exception throw exc; } else { // try to read the resource in the onlineproject cmsFile = m_dbAccess.readFile(onlineProject(currentUser, currentProject).getId(), onlineProject(currentUser, currentProject).getId(), filename); } } if (accessRead(currentUser, currentProject, (CmsResource) cmsFile)) { // acces to all subfolders was granted - return the file. return cmsFile; } else { throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_ACCESS_DENIED); } } /** * Gets the known file extensions (=suffixes) * * <B>Security:</B> * All users are granted access<BR/> * * @param currentUser The user who requested this method, not used here * @param currentProject The current project of the user, not used here * * @return Hashtable with file extensions as Strings */ public Hashtable readFileExtensions(CmsUser currentUser, CmsProject currentProject) throws CmsException { Hashtable res=(Hashtable) m_dbAccess.readSystemProperty(C_SYSTEMPROPERTY_EXTENSIONS); return ( (res!=null)? res : new Hashtable()); } /** * Reads a file header a previous project of the Cms.<BR/> * The reading excludes the filecontent. <br> * * A file header can be read from an offline project or the online project. * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read the resource</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param projectId The id of the project to read the file from. * @param filename The name of the file to be read. * * @return The file read from the Cms. * * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsResource readFileHeader(CmsUser currentUser, CmsProject currentProject, int projectId, String filename) throws CmsException { CmsResource cmsFile; // read the resource from the currentProject, or the online-project try { cmsFile=(CmsResource)m_resourceCache.get(C_FILE+projectId+filename); if (cmsFile==null) { cmsFile = m_dbAccess.readFileHeader(projectId, filename); m_resourceCache.put(C_FILE+projectId+filename,cmsFile); } if( accessRead(currentUser, currentProject, cmsFile) ) { // acces to all subfolders was granted - return the file-header. return cmsFile; } else { throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_ACCESS_DENIED); } } catch(CmsException exc) { throw exc; } } /** * Reads a file header from the Cms.<BR/> * The reading excludes the filecontent. <br> * * A file header can be read from an offline project or the online project. * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read the resource</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param filename The name of the file to be read. * * @return The file read from the Cms. * * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsResource readFileHeader(CmsUser currentUser, CmsProject currentProject, String filename) throws CmsException { CmsResource cmsFile; // check if this method is misused to read a folder if (filename.endsWith("/")) { return (CmsResource) readFolder(currentUser,currentProject,filename); } // read the resource from the currentProject, or the online-project try { // try to read form cache first cmsFile=(CmsResource)m_resourceCache.get(C_FILE+currentProject.getId()+filename); if (cmsFile==null) { cmsFile = m_dbAccess.readFileHeader(currentProject.getId(), filename); m_resourceCache.put(C_FILE+currentProject.getId()+filename,cmsFile); } } catch(CmsException exc) { // the resource was not readable if(currentProject.equals(onlineProject(currentUser, currentProject))) { // this IS the onlineproject - throw the exception throw exc; } else { // try to read the resource in the onlineproject cmsFile=(CmsResource)m_resourceCache.get(C_FILE+ C_PROJECT_ONLINE_ID+filename); if (cmsFile==null) { cmsFile = m_dbAccess.readFileHeader(C_PROJECT_ONLINE_ID,filename); m_resourceCache.put(C_FILE+C_PROJECT_ONLINE_ID+filename,cmsFile); } } } if( accessRead(currentUser, currentProject, cmsFile) ) { // acces to all subfolders was granted - return the file-header. return cmsFile; } else { throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_ACCESS_DENIED); } } /** * Reads all file headers for a project from the Cms.<BR/> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param projectId The id of the project to read the resources for. * * @return a Vector of resources. * * @exception CmsException will be thrown, if the file couldn't be read. * The CmsException will also be thrown, if the user has not the rights * for this resource. */ public Vector readFileHeaders(CmsUser currentUser, CmsProject currentProject, int projectId) throws CmsException { CmsProject project = readProject(currentUser, currentProject, projectId); Vector resources = m_dbAccess.readResources(project); Vector retValue = new Vector(); // check the security for(int i = 0; i < resources.size(); i++) { if( accessRead(currentUser, currentProject, (CmsResource) resources.elementAt(i)) ) { retValue.addElement(resources.elementAt(i)); } } return retValue; } /** * Reads a folder from the Cms.<BR/> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read the resource</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param project the project to read the folder from. * @param foldername The complete path of the folder to be read. * * @return folder The read folder. * * @exception CmsException will be thrown, if the folder couldn't be read. * The CmsException will also be thrown, if the user has not the rights * for this resource */ protected CmsFolder readFolder(CmsUser currentUser, CmsProject currentProject, int project, String folder) throws CmsException { if (folder == null) return null; CmsFolder cmsFolder = (CmsFolder) m_resourceCache.get(C_FOLDER + currentProject.getId() + folder); if (cmsFolder == null) { cmsFolder = m_dbAccess.readFolder(project, folder); if (cmsFolder != null) m_resourceCache.put(C_FOLDER + currentProject.getId() + folder, (CmsFolder) cmsFolder); } if (cmsFolder != null) { if (!accessRead(currentUser, currentProject, (CmsResource) cmsFolder)) throw new CmsException("[" + this.getClass().getName() + "] " + folder, CmsException.C_ACCESS_DENIED); } return cmsFolder; } /** * Reads a folder from the Cms.<BR/> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read the resource</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param foldername The complete path of the folder to be read. * * @return folder The read folder. * * @exception CmsException will be thrown, if the folder couldn't be read. * The CmsException will also be thrown, if the user has not the rights * for this resource. */ public CmsFolder readFolder(CmsUser currentUser, CmsProject currentProject, String folder) throws CmsException { CmsFolder cmsFolder; // read the resource from the currentProject, or the online-project try { cmsFolder = (CmsFolder) m_resourceCache.get(C_FOLDER + currentProject.getId() + folder); if (cmsFolder == null) { cmsFolder = m_dbAccess.readFolder(currentProject.getId(), folder); if (cmsFolder.getState() != C_STATE_DELETED) { m_resourceCache.put(C_FOLDER + currentProject.getId() + folder, (CmsFolder) cmsFolder); } } } catch (CmsException exc) { // the resource was not readable if (currentProject.equals(onlineProject(currentUser, currentProject))) { // this IS the onlineproject - throw the exception throw exc; } else { // try to read the resource in the onlineproject cmsFolder = (CmsFolder) m_resourceCache.get(C_FOLDER + C_PROJECT_ONLINE_ID + folder); if (cmsFolder == null) { cmsFolder = cmsFolder = m_dbAccess.readFolder(C_PROJECT_ONLINE_ID, folder); m_resourceCache.put(C_FOLDER + currentProject.getId() + folder, (CmsFolder) cmsFolder); } } } if (accessRead(currentUser, currentProject, (CmsResource) cmsFolder)) { // acces to all subfolders was granted - return the folder. if (cmsFolder.getState() == C_STATE_DELETED) { throw new CmsException("[" + this.getClass().getName() + "]" + cmsFolder.getAbsolutePath(), CmsException.C_RESOURCE_DELETED); } else { return cmsFolder; } } else { throw new CmsException("[" + this.getClass().getName() + "] " + folder, CmsException.C_ACCESS_DENIED); } } /** * Reads a folder from the Cms.<BR/> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can read the resource</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param folder The complete path to the folder from which the folder will be * read. * @param foldername The name of the folder to be read. * * @return folder The read folder. * * @exception CmsException will be thrown, if the folder couldn't be read. * The CmsException will also be thrown, if the user has not the rights * for this resource. * * @see #readFolder(CmsUser, CmsProject, String) */ public CmsFolder readFolder(CmsUser currentUser, CmsProject currentProject, String folder, String folderName) throws CmsException { return readFolder(currentUser, currentProject, folder + folderName); } /** * Reads all given tasks from a user for a project. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param projectId The id of the Project in which the tasks are defined. * @param owner Owner of the task. * @param tasktype Task type you want to read: C_TASKS_ALL, C_TASKS_OPEN, C_TASKS_DONE, C_TASKS_NEW. * @param orderBy Chooses, how to order the tasks. * * @exception CmsException Throws CmsException if something goes wrong. */ public Vector readGivenTasks(CmsUser currentUser, CmsProject currentProject, int projectId, String ownerName, int taskType, String orderBy, String sort) throws CmsException { CmsProject project = null; CmsUser owner = null; if(ownerName != null) { owner = readUser(currentUser, currentProject, ownerName); } if(projectId != C_UNKNOWN_ID) { project = readProject(currentUser, currentProject, projectId); } return m_dbAccess.readTasks(project,null, owner, null, taskType, orderBy, sort); } /** * Reads the group of a project from the OpenCms. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @return The group of a resource. * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsGroup readGroup(CmsUser currentUser, CmsProject currentProject, CmsProject project) throws CmsException { CmsGroup group=null; // try to read group form cache group=(CmsGroup)m_groupCache.get(project.getGroupId()); if (group== null) { group=m_dbAccess.readGroup(project.getGroupId()) ; m_groupCache.put(project.getGroupId(),group); } return group; } /** * Reads the group of a resource from the OpenCms. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @return The group of a resource. * * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsGroup readGroup(CmsUser currentUser, CmsProject currentProject, CmsResource resource) throws CmsException { CmsGroup group=null; // try to read group form cache group=(CmsGroup)m_groupCache.get(resource.getGroupId()); if (group== null) { group=m_dbAccess.readGroup(resource.getGroupId()) ; m_groupCache.put(resource.getGroupId(),group); } return group; } /** * Reads the group (role) of a task from the OpenCms. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param task The task to read from. * @return The group of a resource. * * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsGroup readGroup(CmsUser currentUser, CmsProject currentProject, CmsTask task) throws CmsException { // TODO: To be implemented //return null; return m_dbAccess.readGroup(task.getRole()); } /** * Returns a group object.<P/> * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param groupname The name of the group that is to be read. * @return Group. * * @exception CmsException Throws CmsException if operation was not succesful */ public CmsGroup readGroup(CmsUser currentUser, CmsProject currentProject, String groupname) throws CmsException { CmsGroup group=null; // try to read group form cache group=(CmsGroup)m_groupCache.get(groupname); if (group== null) { group=m_dbAccess.readGroup(groupname) ; m_groupCache.put(groupname,group); } return group; } /** * Reads the managergroup of a project from the OpenCms. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @return The group of a resource. * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsGroup readManagerGroup(CmsUser currentUser, CmsProject currentProject, CmsProject project) throws CmsException { CmsGroup group=null; // try to read group form cache group=(CmsGroup)m_groupCache.get(project.getManagerGroupId()); if (group== null) { group=m_dbAccess.readGroup(project.getManagerGroupId()) ; m_groupCache.put(project.getManagerGroupId(),group); } return group; } /** * Gets the MimeTypes. * The Mime-Types will be returned. * * <B>Security:</B> * All users are garnted<BR/> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * * @return the mime-types. */ public Hashtable readMimeTypes(CmsUser currentUser, CmsProject currentProject) throws CmsException { return(Hashtable) m_dbAccess.readSystemProperty(C_SYSTEMPROPERTY_MIMETYPES); } /** * Reads the original agent of a task from the OpenCms. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param task The task to read the original agent from. * @return The owner of a task. * * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsUser readOriginalAgent(CmsUser currentUser, CmsProject currentProject, CmsTask task) throws CmsException { return readUser(currentUser,currentProject,task.getOriginalUser()); } /** * Reads the owner of a project from the OpenCms. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @return The owner of a resource. * * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsUser readOwner(CmsUser currentUser, CmsProject currentProject, CmsProject project) throws CmsException { return readUser(currentUser,currentProject,project.getOwnerId()); } /** * Reads the owner of a resource from the OpenCms. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @return The owner of a resource. * * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsUser readOwner(CmsUser currentUser, CmsProject currentProject, CmsResource resource) throws CmsException { return readUser(currentUser,currentProject,resource.getOwnerId() ); } /** * Reads the owner (initiator) of a task from the OpenCms. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param task The task to read the owner from. * @return The owner of a task. * * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsUser readOwner(CmsUser currentUser, CmsProject currentProject, CmsTask task) throws CmsException { return readUser(currentUser,currentProject,task.getInitiatorUser()); } /** * Reads the owner of a tasklog from the OpenCms. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @return The owner of a resource. * * @exception CmsException Throws CmsException if operation was not succesful. */ public CmsUser readOwner(CmsUser currentUser, CmsProject currentProject, CmsTaskLog log) throws CmsException { return readUser(currentUser,currentProject,log.getUser()); } /** * Reads a project from the Cms. * * <B>Security</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param id The id of the project to read. * * @exception CmsException Throws CmsException if something goes wrong. */ public CmsProject readProject(CmsUser currentUser, CmsProject currentProject, int id) throws CmsException { CmsProject project=null; project=(CmsProject)m_projectCache.get(id); if (project==null) { project=m_dbAccess.readProject(id); m_projectCache.put(id,project); } return project; } /** * Reads a project from the Cms. * * <B>Security</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param res The resource to read the project of. * * @exception CmsException Throws CmsException if something goes wrong. */ public CmsProject readProject(CmsUser currentUser, CmsProject currentProject, CmsResource res) throws CmsException { return readProject(currentUser, currentProject, res.getProjectId()); } /** * Reads a project from the Cms. * * <B>Security</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param task The task to read the project of. * * @exception CmsException Throws CmsException if something goes wrong. */ public CmsProject readProject(CmsUser currentUser, CmsProject currentProject, CmsTask task) throws CmsException { // read the parent of the task, until it has no parents. task = this.readTask(currentUser, currentProject, task.getId()); while(task.getParent() != 0) { task = readTask(currentUser, currentProject, task.getParent()); } return m_dbAccess.readProject(task); } /** * Reads log entries for a project. * * @param projectId The id of the projec for tasklog to read. * @return A Vector of new TaskLog objects * @exception CmsException Throws CmsException if something goes wrong. */ public Vector readProjectLogs(CmsUser currentUser, CmsProject currentProject, int projectid) throws CmsException { return m_dbAccess.readProjectLogs(projectid); } /** * Returns a propertyinformation of a file or folder. * * <B>Security</B> * Only the user is granted, who has the right to view the resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The name of the resource of which the propertyinformation has * to be read. * @param property The propertydefinition-name of which the propertyinformation has to be read. * * @return propertyinfo The propertyinfo as string. * * @exception CmsException Throws CmsException if operation was not succesful */ public String readProperty(CmsUser currentUser, CmsProject currentProject, String resource, String property) throws CmsException { CmsResource res; // read the resource from the currentProject, or the online-project try { res = readFileHeader(currentUser,currentProject, resource); } catch(CmsException exc) { // the resource was not readable if(currentProject.equals(onlineProject(currentUser, currentProject))) { // this IS the onlineproject - throw the exception throw exc; } else { // try to read the resource in the onlineproject res = readFileHeader(currentUser,onlineProject(currentUser, currentProject), resource); } } // check the security if( ! accessRead(currentUser, currentProject, res) ) { throw new CmsException("[" + this.getClass().getName() + "] " + resource, CmsException.C_NO_ACCESS); } String returnValue = null; returnValue = (String)m_propertyCache.get(property + Integer.toString(res.getResourceId()) +","+ Integer.toString(res.getType())); if (returnValue == null){ returnValue = m_dbAccess.readProperty(property,res.getResourceId(),res.getType()); if (returnValue == null) { returnValue=""; } m_propertyCache.put(property +Integer.toString(res.getResourceId()) + ","+ Integer.toString(res.getType()), returnValue); } if (returnValue.equals("")){returnValue=null;} return returnValue; } /** * Reads a definition for the given resource type. * * <B>Security</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param name The name of the propertydefinition to read. * @param resourcetype The name of the resource type for which the propertydefinition * is valid. * * @return propertydefinition The propertydefinition that corresponds to the overgiven * arguments - or null if there is no valid propertydefinition. * * @exception CmsException Throws CmsException if something goes wrong. */ public CmsPropertydefinition readPropertydefinition(CmsUser currentUser, CmsProject currentProject, String name, String resourcetype) throws CmsException { CmsResourceType resType = getResourceType(currentUser,currentProject,resourcetype); CmsPropertydefinition returnValue = null; returnValue = (CmsPropertydefinition)m_propertyDefCache.get(name + resType.getResourceType()); if (returnValue == null){ returnValue = m_dbAccess.readPropertydefinition(name, resType); m_propertyDefCache.put(name + resType.getResourceType(), returnValue); } return returnValue; } public Vector readResources(CmsProject project) throws com.opencms.core.CmsException { return m_dbAccess.readResources(project); } /** * Read a task by id. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param id The id for the task to read. * * @exception CmsException Throws CmsException if something goes wrong. */ public CmsTask readTask(CmsUser currentUser, CmsProject currentProject, int id) throws CmsException { return m_dbAccess.readTask(id); } /** * Reads log entries for a task. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param taskid The task for the tasklog to read . * @return A Vector of new TaskLog objects * @exception CmsException Throws CmsException if something goes wrong. */ public Vector readTaskLogs(CmsUser currentUser, CmsProject currentProject, int taskid) throws CmsException { return m_dbAccess.readTaskLogs(taskid);; } /** * Reads all tasks for a project. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param projectId The id of the Project in which the tasks are defined. Can be null for all tasks * @tasktype Task type you want to read: C_TASKS_ALL, C_TASKS_OPEN, C_TASKS_DONE, C_TASKS_NEW * @param orderBy Chooses, how to order the tasks. * @param sort Sort order C_SORT_ASC, C_SORT_DESC, or null * * @exception CmsException Throws CmsException if something goes wrong. */ public Vector readTasksForProject(CmsUser currentUser, CmsProject currentProject, int projectId, int tasktype, String orderBy, String sort) throws CmsException { CmsProject project = null; if(projectId != C_UNKNOWN_ID) { project = readProject(currentUser, currentProject, projectId); } return m_dbAccess.readTasks(project, null, null, null, tasktype, orderBy, sort); } /** * Reads all tasks for a role in a project. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param projectId The id of the Project in which the tasks are defined. * @param user The user who has to process the task. * @param tasktype Task type you want to read: C_TASKS_ALL, C_TASKS_OPEN, C_TASKS_DONE, C_TASKS_NEW. * @param orderBy Chooses, how to order the tasks. * @param sort Sort order C_SORT_ASC, C_SORT_DESC, or null * @exception CmsException Throws CmsException if something goes wrong. */ public Vector readTasksForRole(CmsUser currentUser, CmsProject currentProject, int projectId, String roleName, int tasktype, String orderBy, String sort) throws CmsException { CmsProject project = null; CmsGroup role = null; if(roleName != null) { role = readGroup(currentUser, currentProject, roleName); } if(projectId != C_UNKNOWN_ID) { project = readProject(currentUser, currentProject, projectId); } return m_dbAccess.readTasks(project, null, null, role, tasktype, orderBy, sort); } /** * Reads all tasks for a user in a project. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param projectId The id of the Project in which the tasks are defined. * @param userName The user who has to process the task. * @param taskType Task type you want to read: C_TASKS_ALL, C_TASKS_OPEN, C_TASKS_DONE, C_TASKS_NEW. * @param orderBy Chooses, how to order the tasks. * @param sort Sort order C_SORT_ASC, C_SORT_DESC, or null * @exception CmsException Throws CmsException if something goes wrong. */ public Vector readTasksForUser(CmsUser currentUser, CmsProject currentProject, int projectId, String userName, int taskType, String orderBy, String sort) throws CmsException { CmsUser user = m_dbAccess.readUser(userName, C_USER_TYPE_SYSTEMUSER); return m_dbAccess.readTasks(currentProject, user, null, null, taskType, orderBy, sort); } /** * Returns a user object.<P/> * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param id The id of the user that is to be read. * @return User * @exception CmsException Throws CmsException if operation was not succesful */ public CmsUser readUser(CmsUser currentUser, CmsProject currentProject, int id) throws CmsException { try { CmsUser user=null; // try to read the user from cache user=(CmsUser)m_userCache.get(id); if (user==null) { user=m_dbAccess.readUser(id); m_userCache.put(id,user); } return user; } catch (CmsException ex) { return new CmsUser(C_UNKNOWN_ID, id + "", "deleted user"); } } /** * Returns a user object.<P/> * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param username The name of the user that is to be read. * @return User * @exception CmsException Throws CmsException if operation was not succesful */ public CmsUser readUser(CmsUser currentUser, CmsProject currentProject, String username) throws CmsException { CmsUser user = null; // try to read the user from cache user = (CmsUser)m_userCache.get(username+C_USER_TYPE_SYSTEMUSER); if (user == null) { user = m_dbAccess.readUser(username, C_USER_TYPE_SYSTEMUSER); m_userCache.put(username+C_USER_TYPE_SYSTEMUSER,user); } return user; } /** * Returns a user object.<P/> * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param username The name of the user that is to be read. * @param type The type of the user. * @return User * @exception CmsException Throws CmsException if operation was not succesful */ public CmsUser readUser(CmsUser currentUser, CmsProject currentProject, String username,int type) throws CmsException { CmsUser user = null; // try to read the user from cache user = (CmsUser)m_userCache.get(username+type); if (user == null) { user = m_dbAccess.readUser(username, type); m_userCache.put(username+type,user); } return user; } /** * Returns a user object if the password for the user is correct.<P/> * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param username The username of the user that is to be read. * @param password The password of the user that is to be read. * @return User * * @exception CmsException Throws CmsException if operation was not succesful */ public CmsUser readUser(CmsUser currentUser, CmsProject currentProject, String username, String password) throws CmsException { CmsUser user = null; user = (CmsUser)m_userCache.get(username+C_USER_TYPE_SYSTEMUSER); // store user in cache if (user == null) { user = m_dbAccess.readUser(username, password, C_USER_TYPE_SYSTEMUSER); m_userCache.put(username+C_USER_TYPE_SYSTEMUSER, user); } return user; } /** * Returns a user object if the password for the user is correct.<P/> * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param username The username of the user that is to be read. * @return User * * @exception CmsException Throws CmsException if operation was not succesful */ public CmsUser readWebUser(CmsUser currentUser, CmsProject currentProject, String username) throws CmsException { CmsUser user = null; user = (CmsUser)m_userCache.get(username+C_USER_TYPE_WEBUSER); // store user in cache if (user == null) { user = m_dbAccess.readUser(username, C_USER_TYPE_WEBUSER); m_userCache.put(username+C_USER_TYPE_WEBUSER, user); } return user; } /** * Returns a user object if the password for the user is correct.<P/> * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param username The username of the user that is to be read. * @param password The password of the user that is to be read. * @return User * * @exception CmsException Throws CmsException if operation was not succesful */ public CmsUser readWebUser(CmsUser currentUser, CmsProject currentProject, String username, String password) throws CmsException { CmsUser user = null; user = (CmsUser)m_userCache.get(username+C_USER_TYPE_WEBUSER); // store user in cache if (user == null) { user = m_dbAccess.readUser(username, password, C_USER_TYPE_WEBUSER); m_userCache.put(username+C_USER_TYPE_WEBUSER,user); } return user; } /** * Reaktivates a task from the Cms. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param taskid The Id of the task to accept. * * @exception CmsException Throws CmsException if something goes wrong. */ public void reaktivateTask(CmsUser currentUser, CmsProject currentProject, int taskId) throws CmsException { CmsTask task = m_dbAccess.readTask(taskId); task.setState(C_TASK_STATE_STARTED); task.setPercentage(0); task = m_dbAccess.writeTask(task); m_dbAccess.writeSystemTaskLog(taskId, "Task was reactivated from " + currentUser.getFirstname() + " " + currentUser.getLastname() + "."); } /** * Sets a new password only if the user knows his recovery-password. * * All users can do this if he knows the recovery-password.<P/> * * <B>Security:</B> * All users can do this if he knows the recovery-password.<P/> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param username The name of the user. * @param recoveryPassword The recovery password. * @param newPassword The new password. * * @exception CmsException Throws CmsException if operation was not succesfull. */ public void recoverPassword(CmsUser currentUser, CmsProject currentProject, String username, String recoveryPassword, String newPassword) throws CmsException { // check the length of the new password. if(newPassword.length() < C_PASSWORD_MINIMUMSIZE) { throw new CmsException("[" + this.getClass().getName() + "] " + username, CmsException.C_SHORT_PASSWORD); } // check the length of the recovery password. if(recoveryPassword.length() < C_PASSWORD_MINIMUMSIZE) { throw new CmsException("[" + this.getClass().getName() + "] no recovery password."); } m_dbAccess.recoverPassword(username, recoveryPassword, newPassword); } /** * Removes a user from a group. * * Only the admin can do this.<P/> * * <B>Security:</B> * Only users, which are in the group "administrators" are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param username The name of the user that is to be removed from the group. * @param groupname The name of the group. * @exception CmsException Throws CmsException if operation was not succesful. */ public void removeUserFromGroup(CmsUser currentUser, CmsProject currentProject, String username, String groupname) throws CmsException { // test if this user is existing in the group if (!userInGroup(currentUser,currentProject,username,groupname)) { // user already there, throw exception throw new CmsException("[" + this.getClass().getName() + "] remove " + username+ " from " +groupname, CmsException.C_NO_USER); } if( isAdmin(currentUser, currentProject) ) { CmsUser user; CmsGroup group; user=readUser(currentUser,currentProject,username); //check if the user exists if (user != null) { group=readGroup(currentUser,currentProject,groupname); //check if group exists if (group != null){ // do not remmove the user from its default group if (user.getDefaultGroupId() != group.getId()) { //remove this user from the group m_dbAccess.removeUserFromGroup(user.getId(),group.getId()); m_usergroupsCache.clear(); } else { throw new CmsException("["+this.getClass().getName()+"]",CmsException.C_NO_DEFAULT_GROUP); } } else { throw new CmsException("["+this.getClass().getName()+"]"+groupname,CmsException.C_NO_GROUP); } } else { throw new CmsException("[" + this.getClass().getName() + "] " + username, CmsException.C_NO_ACCESS); } } } /** * Renames the file to a new name. <br> * * Rename can only be done in an offline project. To rename a file, the following * steps have to be done: * <ul> * <li> Copy the file with the oldname to a file with the new name, the state * of the new file is set to NEW (2). * <ul> * <li> If the state of the original file is UNCHANGED (0), the file content of the * file is read from the online project. </li> * <li> If the state of the original file is CHANGED (1) or NEW (2) the file content * of the file is read from the offline project. </li> * </ul> * </li> * <li> Set the state of the old file to DELETED (3). </li> * </ul> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can write the resource</li> * <li>the resource is locked by the callingUser</li> * </ul> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param oldname The complete path to the resource which will be renamed. * @param newname The new name of the resource (CmsUser callingUser, No path information allowed). * * @exception CmsException Throws CmsException if operation was not succesful. */ public void renameFile(CmsUser currentUser, CmsProject currentProject, String oldname, String newname) throws CmsException { // read the old file CmsResource file = readFileHeader(currentUser, currentProject, oldname); // checks, if the newname is valid, if not it throws a exception validFilename(newname); // has the user write-access? if (accessWrite(currentUser, currentProject, file)) { String path = oldname.substring(0, oldname.lastIndexOf("/") + 1); copyFile(currentUser, currentProject, oldname, path + newname); deleteFile(currentUser, currentProject, oldname); } else { throw new CmsException("[" + this.getClass().getName() + "] " + oldname, CmsException.C_NO_ACCESS); } /* // check, if the new name is a valid filename validFilename(newname); // read the old file CmsResource file = readFileHeader(currentUser, currentProject, oldname); // has the user write-access? if( accessWrite(currentUser, currentProject, file) ) { // write-acces was granted - rename the file. m_dbAccess.renameFile(currentProject, onlineProject(currentUser, currentProject), currentUser.getId(), file.getResourceId(), file.getPath() + newname ); // copy the metainfos writeProperties(currentUser,currentProject, file.getPath() + newname, readAllProperties(currentUser,currentProject,file.getAbsolutePath())); // inform about the file-system-change fileSystemChanged(); } else { throw new CmsException("[" + this.getClass().getName() + "] " + oldname, CmsException.C_NO_ACCESS); } */ } /** * This method loads old sessiondata from the database. It is used * for sessionfailover. * * @param oldSessionId the id of the old session. * @return the old sessiondata. */ public Hashtable restoreSession(String oldSessionId) throws CmsException { return m_dbAccess.readSession(oldSessionId); } /** * Set a new name for a task * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param taskid The Id of the task to set the percentage. * @param name The new name value * * @exception CmsException Throws CmsException if something goes wrong. */ public void setName(CmsUser currentUser, CmsProject currentProject, int taskId, String name) throws CmsException { if( (name == null) || name.length() == 0) { throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_BAD_NAME); } CmsTask task = m_dbAccess.readTask(taskId); task.setName(name); task = m_dbAccess.writeTask(task); m_dbAccess.writeSystemTaskLog(taskId, "Name was set to " + name + "% from " + currentUser.getFirstname() + " " + currentUser.getLastname() + "."); } /** * Sets a new parent-group for an already existing group in the Cms.<BR/> * * Only the admin can do this.<P/> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param groupName The name of the group that should be written to the Cms. * @param parentGroupName The name of the parentGroup to set, or null if the parent * group should be deleted. * @exception CmsException Throws CmsException if operation was not succesfull. */ public void setParentGroup(CmsUser currentUser, CmsProject currentProject, String groupName, String parentGroupName) throws CmsException { // Check the security if( isAdmin(currentUser, currentProject) ) { CmsGroup group = readGroup(currentUser, currentProject, groupName); int parentGroupId = C_UNKNOWN_ID; // if the group exists, use its id, else set to unknown. if( parentGroupName != null ) { parentGroupId = readGroup(currentUser, currentProject, parentGroupName).getId(); } group.setParentId(parentGroupId); // write the changes to the cms writeGroup(currentUser,currentProject,group); } else { throw new CmsException("[" + this.getClass().getName() + "] " + groupName, CmsException.C_NO_ACCESS); } } /** * Sets the password for a user. * * Only a adminstrator can do this.<P/> * * <B>Security:</B> * Users, which are in the group "administrators" are granted.<BR/> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param username The name of the user. * @param newPassword The new password. * * @exception CmsException Throws CmsException if operation was not succesfull. */ public void setPassword(CmsUser currentUser, CmsProject currentProject, String username, String newPassword) throws CmsException { // check the length of the new password. if(newPassword.length() < C_PASSWORD_MINIMUMSIZE) { throw new CmsException("[" + this.getClass().getName() + "] " + username, CmsException.C_SHORT_PASSWORD); } if( isAdmin(currentUser, currentProject) ) { m_dbAccess.setPassword(username, newPassword); } else { throw new CmsException("[" + this.getClass().getName() + "] " + username, CmsException.C_NO_ACCESS); } } /** * Sets the password for a user. * * Only a adminstrator or the curretuser can do this.<P/> * * <B>Security:</B> * Users, which are in the group "administrators" are granted.<BR/> * Current users can change their own password. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param username The name of the user. * @param oldPassword The new password. * @param newPassword The new password. * * @exception CmsException Throws CmsException if operation was not succesfull. */ public void setPassword(CmsUser currentUser, CmsProject currentProject, String username, String oldPassword, String newPassword) throws CmsException { // check the length of the new password. if(newPassword.length() < C_PASSWORD_MINIMUMSIZE) { throw new CmsException("[" + this.getClass().getName() + "] " + username, CmsException.C_SHORT_PASSWORD); } // read the user CmsUser user; try { user = readUser(currentUser, currentProject, username, oldPassword); } catch(CmsException exc) { // this is no system-user - maybe a webuser? user = readWebUser(currentUser, currentProject, username, oldPassword); } if( ! anonymousUser(currentUser, currentProject).equals( currentUser ) && ( isAdmin(user, currentProject) || user.equals(currentUser)) ) { m_dbAccess.setPassword(username, newPassword); } else { throw new CmsException("[" + this.getClass().getName() + "] " + username, CmsException.C_NO_ACCESS); } } /** * Set priority of a task * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param taskid The Id of the task to set the percentage. * @param new priority value * * @exception CmsException Throws CmsException if something goes wrong. */ public void setPriority(CmsUser currentUser, CmsProject currentProject, int taskId, int priority) throws CmsException { CmsTask task = m_dbAccess.readTask(taskId); task.setPriority(priority); task = m_dbAccess.writeTask(task); m_dbAccess.writeSystemTaskLog(taskId, "Priority was set to " + priority + " from " + currentUser.getFirstname() + " " + currentUser.getLastname() + "."); } /** * Sets the recovery password for a user. * * Only a adminstrator or the curretuser can do this.<P/> * * <B>Security:</B> * Users, which are in the group "administrators" are granted.<BR/> * Current users can change their own password. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param username The name of the user. * @param password The password of the user. * @param newPassword The new recoveryPassword to be set. * * @exception CmsException Throws CmsException if operation was not succesfull. */ public void setRecoveryPassword(CmsUser currentUser, CmsProject currentProject, String username, String password, String newPassword) throws CmsException { // check the length of the new password. if(newPassword.length() < C_PASSWORD_MINIMUMSIZE) { throw new CmsException("[" + this.getClass().getName() + "] " + username, CmsException.C_SHORT_PASSWORD); } // read the user CmsUser user; try { user = readUser(currentUser, currentProject, username, password); } catch(CmsException exc) { // this is no system-user - maybe a webuser? user = readWebUser(currentUser, currentProject, username, password); } if( ! anonymousUser(currentUser, currentProject).equals( currentUser ) && ( isAdmin(user, currentProject) || user.equals(currentUser)) ) { m_dbAccess.setRecoveryPassword(username, newPassword); } else { throw new CmsException("[" + this.getClass().getName() + "] " + username, CmsException.C_NO_ACCESS); } } /** * Set a Parameter for a task. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param taskId The Id of the task. * @param parName Name of the parameter. * @param parValue Value if the parameter. * * @return The id of the inserted parameter or 0 if the parameter already exists for this task. * * @exception CmsException Throws CmsException if something goes wrong. */ public void setTaskPar(CmsUser currentUser, CmsProject currentProject, int taskId, String parName, String parValue) throws CmsException { m_dbAccess.setTaskPar(taskId, parName, parValue); } /** * Set timeout of a task * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param taskid The Id of the task to set the percentage. * @param new timeout value * * @exception CmsException Throws CmsException if something goes wrong. */ public void setTimeout(CmsUser currentUser, CmsProject currentProject, int taskId, long timeout) throws CmsException { CmsTask task = m_dbAccess.readTask(taskId); java.sql.Timestamp timestamp = new java.sql.Timestamp(timeout); task.setTimeOut(timestamp); task = m_dbAccess.writeTask(task); m_dbAccess.writeSystemTaskLog(taskId, "Timeout was set to " + timeout + " from " + currentUser.getFirstname() + " " + currentUser.getLastname() + "."); } /** * This method stores sessiondata into the database. It is used * for sessionfailover. * * @param sessionId the id of the session. * @param isNew determines, if the session is new or not. * @return data the sessionData. */ public void storeSession(String sessionId, Hashtable sessionData) throws CmsException { // update the session int rowCount = m_dbAccess.updateSession(sessionId, sessionData); if(rowCount != 1) { // the entry dosn't exists - create it m_dbAccess.createSession(sessionId, sessionData); } } /** * Unlocks all resources in this project. * * <B>Security</B> * Only the admin or the owner of the project can do this. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param id The id of the project to be published. * * @exception CmsException Throws CmsException if something goes wrong. */ public void unlockProject(CmsUser currentUser, CmsProject currentProject, int id) throws CmsException { // read the project. CmsProject project = readProject(currentUser, currentProject, id); // check the security if( (isAdmin(currentUser, currentProject) || isManagerOfProject(currentUser, project) ) && (project.getFlags() == C_PROJECT_STATE_UNLOCKED )) { // unlock all resources in the project m_dbAccess.unlockProject(project); m_resourceCache.clear(); m_projectCache.clear(); } else { throw new CmsException("[" + this.getClass().getName() + "] " + id, CmsException.C_NO_ACCESS); } } /** * Unlocks a resource.<br> * * Only a resource in an offline project can be unlock. The state of the resource * is set to CHANGED (1). * If the content of this resource is not exisiting in the offline project already, * it is read from the online project and written into the offline project. * Only the user who locked a resource can unlock it. * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user had locked the resource before</li> * </ul> * * @param user The user who wants to lock the file. * @param project The project in which the resource will be used. * @param resourcename The complete path to the resource to lock. * * @exception CmsException Throws CmsException if operation was not succesful. */ public void unlockResource(CmsUser currentUser,CmsProject currentProject, String resourcename) throws CmsException { CmsResource cmsResource=null; // read the resource, that shold be locked if (resourcename.endsWith("/")) { cmsResource = readFolder(currentUser,currentProject,resourcename); } else { cmsResource = (CmsFile)readFileHeader(currentUser,currentProject,resourcename); } // check, if the user may lock the resource if( accessUnlock(currentUser, currentProject, cmsResource) ) { // unlock the resource. if (cmsResource.isLocked()){ // check if the resource is locked by the actual user if (cmsResource.isLockedBy()==currentUser.getId()) { // unlock the resource cmsResource.setLocked(C_UNKNOWN_ID); //update resource m_dbAccess.updateLockstate(cmsResource); if (resourcename.endsWith("/")) { //m_dbAccess.writeFolder(currentProject,(CmsFolder)cmsResource,false); // update the cache m_resourceCache.put(C_FOLDER+currentProject.getId()+resourcename,(CmsFolder)cmsResource); } else { //m_dbAccess.writeFileHeader(currentProject,onlineProject(currentUser, currentProject),(CmsFile)cmsResource,false); // update the cache m_resourceCache.put(C_FILE+currentProject.getId()+resourcename,(CmsFile)cmsResource); } m_subresCache.clear(); } else { throw new CmsException("[" + this.getClass().getName() + "] " + resourcename + CmsException.C_NO_ACCESS); } } // if this resource is a folder -> lock all subresources, too if(cmsResource.isFolder()) { Vector files = getFilesInFolder(currentUser,currentProject, cmsResource.getAbsolutePath()); Vector folders = getSubFolders(currentUser,currentProject, cmsResource.getAbsolutePath()); CmsResource currentResource; // lock all files in this folder for(int i = 0; i < files.size(); i++ ) { currentResource = (CmsResource)files.elementAt(i); if (currentResource.getState() != C_STATE_DELETED) { unlockResource(currentUser, currentProject, currentResource.getAbsolutePath()); } } // lock all files in this folder for(int i = 0; i < folders.size(); i++) { currentResource = (CmsResource)folders.elementAt(i); if (currentResource.getState() != C_STATE_DELETED) { unlockResource(currentUser, currentProject, currentResource.getAbsolutePath()); } } } } else { throw new CmsException("[" + this.getClass().getName() + "] " + resourcename, CmsException.C_NO_ACCESS); } } /** * Checks if a user is member of a group.<P/> * * <B>Security:</B> * All users are granted, except the anonymous user. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param callingUser The user who wants to use this method. * @param nameuser The name of the user to check. * @param groupname The name of the group to check. * @return True or False * * @exception CmsException Throws CmsException if operation was not succesful */ public boolean userInGroup(CmsUser currentUser, CmsProject currentProject, String username, String groupname) throws CmsException { Vector groups = getGroupsOfUser(currentUser,currentProject,username); CmsGroup group; for(int z = 0; z < groups.size(); z++) { group = (CmsGroup) groups.elementAt(z); if(groupname.equals(group.getName())) { return true; } } return false; } /** * Checks ii characters in a String are allowed for filenames * * @param filename String to check * * @exception throws a exception, if the check fails. */ protected void validFilename( String filename ) throws CmsException { if (filename == null) { throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_BAD_NAME); } int l = filename.length(); if (l == 0 || filename.startsWith(".")) { throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_BAD_NAME); } for (int i=0; i<l; i++) { char c = filename.charAt(i); if ( ((c < 'a') || (c > 'z')) && ((c < '0') || (c > '9')) && ((c < 'A') || (c > 'Z')) && (c != '-') && (c != '.') && (c != '|') && (c != '_') && (c != '~') ) { throw new CmsException("[" + this.getClass().getName() + "] " + filename, CmsException.C_BAD_NAME); } } } /** * Checks ii characters in a String are allowed for names * * @param name String to check * * @exception throws a exception, if the check fails. */ protected void validName(String name, boolean blank) throws CmsException { if (name == null || name.length() == 0 || name.trim().length() == 0) { throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_BAD_NAME); } // throw exception if no blanks are allowed if (!blank) { int l = name.length(); for (int i = 0; i < l; i++) { char c = name.charAt(i); if (c == ' ') { throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_BAD_NAME); } } } /* for (int i=0; i<l; i++) { char c = name.charAt(i); if ( ((c < 'a') || (c > 'z')) && ((c < '0') || (c > '9')) && ((c < 'A') || (c > 'Z')) && (c != '-') && (c != '.') && (c != '|') && (c != '_') && (c != '~') ) { throw new CmsException("[" + this.getClass().getName() + "] " + name, CmsException.C_BAD_NAME); } } */ } /** * Writes the export-path for the system. * This path is used for db-export and db-import. * * <B>Security:</B> * Users, which are in the group "administrators" are granted.<BR/> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param mountpoint The mount point in the Cms filesystem. */ public void writeExportPath(CmsUser currentUser, CmsProject currentProject, String path) throws CmsException { // check the security if( isAdmin(currentUser, currentProject) ) { // security is ok - write the exportpath. if(m_dbAccess.readSystemProperty(C_SYSTEMPROPERTY_EXPORTPATH) == null) { // the property wasn't set before. m_dbAccess.addSystemProperty(C_SYSTEMPROPERTY_EXPORTPATH, path); } else { // overwrite the property. m_dbAccess.writeSystemProperty(C_SYSTEMPROPERTY_EXPORTPATH, path); } } else { throw new CmsException("[" + this.getClass().getName() + "] " + path, CmsException.C_NO_ACCESS); } } /** * Writes a file to the Cms.<br> * * A file can only be written to an offline project.<br> * The state of the resource is set to CHANGED (1). The file content of the file * is either updated (if it is already existing in the offline project), or created * in the offline project (if it is not available there).<br> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can write the resource</li> * <li>the resource is locked by the callingUser</li> * </ul> * * @param currentUser The user who own this file. * @param currentProject The project in which the resource will be used. * @param file The name of the file to write. * * @exception CmsException Throws CmsException if operation was not succesful. */ public void writeFile(CmsUser currentUser, CmsProject currentProject, CmsFile file) throws CmsException { // has the user write-access? if( accessWrite(currentUser, currentProject, (CmsResource)file) ) { // write-acces was granted - write the file. m_dbAccess.writeFile(currentProject, onlineProject(currentUser, currentProject), file,true ); if (file.getState()==C_STATE_UNCHANGED) { file.setState(C_STATE_CHANGED); } // update the cache m_resourceCache.put(C_FILE+currentProject.getId()+file.getAbsolutePath(),file); //m_resourceCache.put(C_FILECONTENT+currentProject.getId()+file.getAbsolutePath(),file); m_subresCache.clear(); m_accessCache.clear(); // inform about the file-system-change fileSystemChanged(false); } else { throw new CmsException("[" + this.getClass().getName() + "] " + file.getAbsolutePath(), CmsException.C_NO_ACCESS); } } /** * Writes the file extensions * * <B>Security:</B> * Users, which are in the group "Administrators" are authorized.<BR/> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param extensions Holds extensions as keys and resourcetypes (Stings) as values */ public void writeFileExtensions(CmsUser currentUser, CmsProject currentProject, Hashtable extensions) throws CmsException { if (extensions != null) { if (isAdmin(currentUser, currentProject)) { if (m_dbAccess.readSystemProperty(C_SYSTEMPROPERTY_EXTENSIONS) == null) { // the property wasn't set before. m_dbAccess.addSystemProperty(C_SYSTEMPROPERTY_EXTENSIONS, extensions); } else { // overwrite the property. m_dbAccess.writeSystemProperty(C_SYSTEMPROPERTY_EXTENSIONS, extensions); } } else { throw new CmsException("[" + this.getClass().getName() + "] " + extensions.size(), CmsException.C_NO_ACCESS); } } } /** * Writes a fileheader to the Cms.<br> * * A file can only be written to an offline project.<br> * The state of the resource is set to CHANGED (1). The file content of the file * is either updated (if it is already existing in the offline project), or created * in the offline project (if it is not available there).<br> * * <B>Security:</B> * Access is granted, if: * <ul> * <li>the user has access to the project</li> * <li>the user can write the resource</li> * <li>the resource is locked by the callingUser</li> * </ul> * * @param currentUser The user who own this file. * @param currentProject The project in which the resource will be used. * @param file The file to write. * * @exception CmsException Throws CmsException if operation was not succesful. */ public void writeFileHeader(CmsUser currentUser, CmsProject currentProject, CmsFile file) throws CmsException { // has the user write-access? if( accessWrite(currentUser, currentProject, (CmsResource)file) ) { // write-acces was granted - write the file. m_dbAccess.writeFileHeader(currentProject, file,true ); if (file.getState()==C_STATE_UNCHANGED) { file.setState(C_STATE_CHANGED); } // update the cache m_resourceCache.put(C_FILE+currentProject.getId()+file.getAbsolutePath(),file); // inform about the file-system-change m_subresCache.clear(); m_accessCache.clear(); fileSystemChanged(false); } else { throw new CmsException("[" + this.getClass().getName() + "] " + file.getAbsolutePath(), CmsException.C_NO_ACCESS); } } /** * Writes an already existing group in the Cms.<BR/> * * Only the admin can do this.<P/> * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param group The group that should be written to the Cms. * @exception CmsException Throws CmsException if operation was not succesfull. */ public void writeGroup(CmsUser currentUser, CmsProject currentProject, CmsGroup group) throws CmsException { // Check the security if( isAdmin(currentUser, currentProject) ) { m_dbAccess.writeGroup(group); m_groupCache.put(group.getName(),group); } else { throw new CmsException("[" + this.getClass().getName() + "] " + group.getName(), CmsException.C_NO_ACCESS); } } /** * Writes a couple of propertyinformation for a file or folder. * * <B>Security</B> * Only the user is granted, who has the right to write the resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The name of the resource of which the propertyinformation * has to be read. * @param propertyinfos A Hashtable with propertydefinition- propertyinfo-pairs as strings. * * @exception CmsException Throws CmsException if operation was not succesful */ public void writeProperties(CmsUser currentUser, CmsProject currentProject, String resource, Hashtable propertyinfos) throws CmsException { // read the resource CmsResource res = readFileHeader(currentUser,currentProject, resource); // check the security if( ! accessWrite(currentUser, currentProject, res) ) { throw new CmsException("[" + this.getClass().getName() + "] " + resource, CmsException.C_NO_ACCESS); } m_dbAccess.writeProperties(propertyinfos,res.getResourceId(),res.getType()); m_propertyCache.clear(); if (res.getState()==C_STATE_UNCHANGED) { res.setState(C_STATE_CHANGED); } if(res.isFile()){ m_dbAccess.writeFileHeader(currentProject, (CmsFile) res, false); // update the cache m_resourceCache.put(C_FILE+currentProject.getId()+resource,res); } else { m_dbAccess.writeFolder(currentProject, readFolder(currentUser,currentProject, resource), false); // update the cache m_resourceCache.put(C_FOLDER+currentProject.getId()+resource,(CmsFolder)res); } m_subresCache.clear(); } /** * Writes a propertyinformation for a file or folder. * * <B>Security</B> * Only the user is granted, who has the right to write the resource. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param resource The name of the resource of which the propertyinformation has * to be read. * @param property The propertydefinition-name of which the propertyinformation has to be set. * @param value The value for the propertyinfo to be set. * * @exception CmsException Throws CmsException if operation was not succesful */ public void writeProperty(CmsUser currentUser, CmsProject currentProject, String resource, String property, String value) throws CmsException { // read the resource CmsResource res = readFileHeader(currentUser,currentProject, resource); // check the security if( ! accessWrite(currentUser, currentProject, res) ) { throw new CmsException("[" + this.getClass().getName() + "] " + resource, CmsException.C_NO_ACCESS); } m_dbAccess.writeProperty(property, value, res.getResourceId(),res.getType()); m_propertyCache.clear(); // set the file-state to changed if(res.isFile()){ m_dbAccess.writeFileHeader(currentProject, (CmsFile) res, true); if (res.getState()==C_STATE_UNCHANGED) { res.setState(C_STATE_CHANGED); } // update the cache m_resourceCache.put(C_FILE+currentProject.getId()+resource,res); } else { if (res.getState()==C_STATE_UNCHANGED) { res.setState(C_STATE_CHANGED); } m_dbAccess.writeFolder(currentProject, readFolder(currentUser,currentProject, resource), true); // update the cache m_resourceCache.put(C_FOLDER+currentProject.getId()+resource,(CmsFolder)res); } m_subresCache.clear(); } /** * Updates the propertydefinition for the resource type.<BR/> * * <B>Security</B> * Only the admin can do this. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param propertydef The propertydef to be deleted. * * @return The propertydefinition, that was written. * * @exception CmsException Throws CmsException if something goes wrong. */ public CmsPropertydefinition writePropertydefinition(CmsUser currentUser, CmsProject currentProject, CmsPropertydefinition propertydef) throws CmsException { // check the security if( isAdmin(currentUser, currentProject) ) { m_propertyDefVectorCache.clear(); return( m_dbAccess.writePropertydefinition(propertydef) ); } else { throw new CmsException("[" + this.getClass().getName() + "] " + propertydef.getName(), CmsException.C_NO_ACCESS); } } /** * Writes a new user tasklog for a task. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param taskid The Id of the task . * @param comment Description for the log * * @exception CmsException Throws CmsException if something goes wrong. */ public void writeTaskLog(CmsUser currentUser, CmsProject currentProject, int taskid, String comment) throws CmsException { m_dbAccess.writeTaskLog(taskid, currentUser.getId(), new java.sql.Timestamp(System.currentTimeMillis()), comment, C_TASKLOG_USER); } /** * Writes a new user tasklog for a task. * * <B>Security:</B> * All users are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param taskid The Id of the task . * @param comment Description for the log * @param tasktype Type of the tasklog. User tasktypes must be greater then 100. * * @exception CmsException Throws CmsException if something goes wrong. */ public void writeTaskLog(CmsUser currentUser, CmsProject currentProject, int taskid, String comment, int type) throws CmsException { m_dbAccess.writeTaskLog(taskid, currentUser.getId(), new java.sql.Timestamp(System.currentTimeMillis()), comment, type); } /** * Updates the user information.<BR/> * * Only the administrator can do this.<P/> * * <B>Security:</B> * Only users, which are in the group "administrators" are granted. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param user The user to be updated. * * @exception CmsException Throws CmsException if operation was not succesful */ public void writeUser(CmsUser currentUser, CmsProject currentProject, CmsUser user) throws CmsException { // Check the security if( isAdmin(currentUser, currentProject) || (currentUser.equals(user)) ) { // prevent the admin to be set disabled! if( isAdmin(user, currentProject) ) { user.setEnabled(); } m_dbAccess.writeUser(user); // update the cache m_userCache.put(user.getName()+user.getType(),user); } else { throw new CmsException("[" + this.getClass().getName() + "] " + user.getName(), CmsException.C_NO_ACCESS); } } /** * Updates the user information of a web user.<BR/> * * Only a web user can be updated this way.<P/> * * <B>Security:</B> * Only users of the user type webuser can be updated this way. * * @param currentUser The user who requested this method. * @param currentProject The current project of the user. * @param user The user to be updated. * * @exception CmsException Throws CmsException if operation was not succesful */ public void writeWebUser(CmsUser currentUser, CmsProject currentProject, CmsUser user) throws CmsException { // Check the security if( user.getType() == C_USER_TYPE_WEBUSER) { m_dbAccess.writeUser(user); // update the cache m_userCache.put(user.getName()+user.getType(),user); } else { throw new CmsException("[" + this.getClass().getName() + "] " + user.getName(), CmsException.C_NO_ACCESS); } } }
package org.jscsi.scsi.protocol; import static org.junit.Assert.fail; import org.jscsi.scsi.protocol.cdb.CommandDescriptorBlockFactory; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; // TODO: Describe class or interface public class CommandDescriptorBlockFactoryTest { private static final String DEFAULT_PACKAGE = "org.jscsi.scsi.protocol.cdb"; private static Serializer serializer; private static String INQUIRY = "Inquiry,OperationCode=8:0x12,reserved=7:0x0,EVPD=1:std,PageCode=8:std,AllocationLength=16:std,reserved=5:0x0,NormalACA=1:std,reserved=1:0x0,Linked=1:std"; private static String MODE_SELECT_6 = "ModeSelect6,OperationCode=8:0x15,reserved=3:0x0,PageFormat=1:std,reserved=3:0x0,SavePages=1:std,reserved=16:0x0,ParameterListLength=8:std,reserved=5:0x0,NormalACA=1:std,reserved=1:0x0,Linked=1:std"; private static String MODE_SELECT_10 = "ModeSelect10,OperationCode=8:0x55,reserved=3:0x0,PageFormat=1:std,reserved=3:0x0,SavePages=1:std,reserved=40:0x0,ParameterListLength=16:std,reserved=5:0x0,NormalACA=1:std,reserved=1:0x0,Linked=1:std"; private static String MODE_SENSE_6 = "ModeSense6,OperationCode=8:0x1A,reserved=4:0x0,Dbd=1:std,reserved=3:0x0,PageControl=2:std,PageCode=6:std,SubPageCode=8:std,AllocationLength=8:std,reserved=5:0x0,NormalACA=1:std,reserved=1:0x0,Linked=1:std"; private static String MODE_SENSE_10 = "ModeSense10,OperationCode=8:0x5A,reserved=3:0x0,LLBAA=1:std,Dbd=1:std,reserved=3:0x0,PageControl=2:std,PageCode=6:std,SubPageCode=8:std,reserved=24:0x0,AllocationLength=16:std,reserved=5:0x0,NormalACA=1:std,reserved=1:0x0,Linked=1:std"; private static String READ_6 = "Read6,OperationCode=8:0x08,reserved=3:0x0,LogicalBlockAddress=21:std,TransferLength=8:std,reserved=5:0x0,NormalACA=1:std,reserved=1:0x0,Linked=1:std"; private static String READ_10 = "Read10,OperationCode=8:0x28,reserved=3:0x0,Dpo=1:std,Fua=1:std,reserved=1:0x0,Fua_nv=1:std,reserved=1:0x0,LogicalBlockAddress=32:std,reserved=3:0x0,GroupNumber=5:std,TransferLength=16:std,reserved=5:0x0,NormalACA=1:std,reserved=1:0x0,Linked=1:std"; private static String READ_12 = "Read12,OperationCode=8:0xA8,reserved=3:0x0,Dpo=1:std,Fua=1:std,reserved=1:0x0,Fua_nv=1:std,reserved=1:0x0,LogicalBlockAddress=32:std,TransferLength=32:std,reserved=3:0x0,GroupNumber=5:std,reserved=5:0x0,NormalACA=1:std,reserved=1:0x0,Linked=1:std"; private static String READ_16 = "Read16,OperationCode=8:0x88,reserved=3:0x0,Dpo=1:std,Fua=1:std,reserved=1:0x0,Fua_nv=1:std,reserved=1:0x0,LogicalBlockAddress=64:std,TransferLength=32:std,reserved=3:0x0,GroupNumber=5:std,reserved=5:0x0,NormalACA=1:std,reserved=1:0x0,Linked=1:std"; private static String READ_CAPACITY_10 = "ReadCapacity10,OperationCode=8:0x25,reserved=8:0x0,LogicalBlockAddress=32:std,reserved=23:0x0,Pmi=1:std,reserved=5:0x0,NormalACA=1:std,reserved=1:0x0,Linked=1:std"; private static String READ_CAPACITY_16 = "ReadCapacity16,OperationCode=8:0x9E,reserved=3:0x0,ServiceAction=5:std,LogicalBlockAddress=64:std,AllocationLength=32:std,reserved=7:0x0,Pmi=1:std,reserved=5:0x0,NormalACA=1:std,reserved=1:0x0,Linked=1:std"; private static String REMOVE_DIAGNOSTIC_RESULTS = "ReceiveDiagnosticResults,OperationCode=8:0x1C,reserved=7:0x0,Pcv=1:std,PageCode=8:std,AllocationLength=16:std,reserved=5:0x0,NormalACA=1:std,reserved=1:0x0,Linked=1:std"; private static String REPORT_LUNS = "ReportLuns,OperationCode=8:0xA0,reserved=8:0x0,SelectReport=8:std,reserved=24:0x0,AllocationLength=32:std,reserved=8:0x0,reserved=5:0x0,NormalACA=1:std,reserved=1:0x0,Linked=1:std"; private static String REPORT_SUPPORTED_TASK_MANAGEMENT_FUNCTIONS = "ReportSupportedTaskManagementFunctions,OperationCode=8:0xA3,reserved=3:0x0,ServiceAction=5:std,reserved=32:0x0,AllocationLength=32:std,reserved=8:0x0,reserved=5:0x0,NormalACA=1:std,reserved=1:0x0,Linked=1:std"; private static String REQUEST_SENSE = "RequestSense,OperationCode=8:0x03,reserved=7:0x0,DescriptorFormat=1:std,reserved=16:0x0,AllocationLength=8:std,reserved=5:0x0,NormalACA=1:std,reserved=1:0x0,Linked=1:std"; private static String SEND_DIAGNOSTIC = "SendDiagnostic,OperationCode=8:0x1D,SelfTestCode=3:std,Pf=1:std,reserved=1:0x0,SelfTest=1:std,DevOffL=1:std,UnitOffL=1:std,reserved=8:0x0,ParameterListLength=16:std,reserved=5:0x0,NormalACA=1:std,reserved=1:0x0,Linked=1:std"; private static String TEST_UNIT_READY = "TestUnitReady,OperationCode=8:0x00,reserved=32:0x0,reserved=5:0x0,NormalACA=1:std,reserved=1:0x0,Linked=1:std"; private static String WRITE_6 = "Write6,OperationCode=8:0x0A,reserved=3:0x0,LogicalBlockAddress=21:std,TransferLength=8:std,reserved=5:0x0,NormalACA=1:std,reserved=1:0x0,Linked=1:std"; private static String WRITE_10 = "Write10,OperationCode=8:0x2A,reserved=3:0x0,Dpo=1:std,Fua=1:std,reserved=1:0x0,Fua_nv=1:std,reserved=1:0x0,LogicalBlockAddress=32:std,reserved=3:0x0,GroupNumber=5:std,TransferLength=16:std,reserved=5:0x0,NormalACA=1:std,reserved=1:0x0,Linked=1:std"; private static String WRITE_12 = "Write12,OperationCode=8:0xAA,reserved=3:0x0,Dpo=1:std,Fua=1:std,reserved=1:0x0,Fua_nv=1:std,reserved=1:0x0,LogicalBlockAddress=32:std,TransferLength=32:std,reserved=3:0x0,GroupNumber=5:std,reserved=5:0x0,NormalACA=1:std,reserved=1:0x0,Linked=1:std"; private static String WRITE_16 = "Write16,OperationCode=8:0x8A,reserved=3:0x0,Dpo=1:std,Fua=1:std,reserved=1:0x0,Fua_nv=1:std,reserved=1:0x0,LogicalBlockAddress=64:std,TransferLength=32:std,reserved=3:0x0,GroupNumber=5:std,reserved=5:0x0,NormalACA=1:std,reserved=1:0x0,Linked=1:std"; @BeforeClass public static void setUpBeforeClass() throws Exception { serializer = new CommandDescriptorBlockFactory(); } @AfterClass public static void tearDownAfterClass() throws Exception { } @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } private void runTest(String specification) { try { new SerializerTest(serializer, DEFAULT_PACKAGE, specification).runTest(); } catch (Exception e) { fail(e.getMessage()); } } @Test public void parseInquiry() { runTest(INQUIRY); } @Test public void parseModeSelect6() { runTest(MODE_SELECT_6); } @Test public void parseModeSelect10() { runTest(MODE_SELECT_10); } @Test public void parseModeSense6() { runTest(MODE_SENSE_6); } @Test public void parseModeSense10() { runTest(MODE_SENSE_10); } @Test public void parseRead6() { runTest(READ_6); } @Test public void parseRead10() { runTest(READ_10); } @Test public void parseRead12() { runTest(READ_12); } @Test public void parseRead16() { runTest(READ_16); } @Test public void parseReadCapacity10() { runTest(READ_CAPACITY_10); } @Test public void parseReadCapacity16() { runTest(READ_CAPACITY_16); } @Test public void parseRemoveDiagnosticResults() { runTest(REMOVE_DIAGNOSTIC_RESULTS); } @Test public void parseReportLuns() { runTest(REPORT_LUNS); } @Test public void parseReportSupportedTaskManagementFunctions() { runTest(REPORT_SUPPORTED_TASK_MANAGEMENT_FUNCTIONS); } @Test public void parseRequestSense() { runTest(REQUEST_SENSE); } @Test public void parseSendDiagnostic() { runTest(SEND_DIAGNOSTIC); } @Test public void parseTestUnitReady() { runTest(TEST_UNIT_READY); } @Test public void parseWrite6() { runTest(WRITE_6); } @Test public void parseWrite10() { runTest(WRITE_10); } @Test public void parseWrite12() { runTest(WRITE_12); } @Test public void parseWrite16() { runTest(WRITE_16); } }
package gov.nih.nci.cabig.caaers.web.fields.validators; import java.util.HashMap; import java.util.Map; import gov.nih.nci.cabig.caaers.AbstractTestCase; import gov.nih.nci.cabig.caaers.web.fields.InputField; import gov.nih.nci.cabig.caaers.web.fields.InputFieldFactory; import gov.nih.nci.cabig.caaers.web.fields.QualifiedPropertyNameInputField; import org.apache.commons.lang.StringUtils; /** * @author Biju Joseph */ public class QualifiedPropertyNameInputFieldTest extends AbstractTestCase { private QualifiedPropertyNameInputField field; public void testGetValidatorClassNameIfOnlySingleValidatorIsUsed() throws Exception { InputField dateField = InputFieldFactory.createPastDateField("propertyName", "displayName", false); createField(dateField); assertNotNull(field.getValidators()); assertTrue(field.getValidators().length > 0); assertEquals("commons-validations.js uses this class name for validation", "validate-DATE", field.getValidatorClassName()); } public void testGetValidatorClassNameForRequiredTextField() throws Exception { field = new TestQualifiedPropertyNameInputField(InputFieldFactory.createTextField("propertyName", "displayName", true)) { @Override public Category getCategory() { return Category.TEXT; } }; assertEquals("commons-validations.js uses this class name for validation", "validate-NOTEMPTY$$MAXLENGTH2000", field.getValidatorClassName()); } public void testGetValidatorClassNameForRequiredTextFieldWithSize() throws Exception { field = new TestQualifiedPropertyNameInputField(InputFieldFactory.createTextField("propertyName", "displayName", true)) { @Override public Category getCategory() { return Category.TEXT; } }; // Setting the size of the field. Map<String, Object> attrMap = new HashMap<String, Object>(); attrMap.put("size", new Integer(4)); field.setAttributes(attrMap ); assertEquals("commons-validations.js uses this class name for validation", "validate-NOTEMPTY$$MAXLENGTH4", field.getValidatorClassName()); } public void testGetValidatorClassNameForRequiredTextAreaField() throws Exception { field = new TestQualifiedPropertyNameInputField(InputFieldFactory.createTextArea("propertyName", "displayName", true)) { @Override public Category getCategory() { return Category.TEXTAREA; } }; assertEquals("commons-validations.js uses this class name for validation", "validate-NOTEMPTY$$MAXLENGTH2000", field.getValidatorClassName()); } public void testGetValidatorClassNameForNonRequiredTextField() throws Exception { field = new TestQualifiedPropertyNameInputField(InputFieldFactory.createTextField("propertyName", "displayName", false)) { @Override public Category getCategory() { return Category.TEXT; } }; assertEquals("commons-validations.js uses this class name for validation", "validate-MAXLENGTH2000", field.getValidatorClassName()); } public void testGetValidatorClassNameForNonRequiredTextAreaField() throws Exception { field = new TestQualifiedPropertyNameInputField(InputFieldFactory.createTextArea("propertyName", "displayName", false)) { @Override public Category getCategory() { return Category.TEXTAREA; } }; assertEquals("commons-validations.js uses this class name for validation", "validate-MAXLENGTH2000", field.getValidatorClassName()); } public void testGetValidatorClassNameIfNoValidatorsAreApplied() throws Exception { createField(InputFieldFactory.createInputField(InputField.Category.IMAGE, "propertyName", "displayName")); assertTrue("class name muast be empty", StringUtils.isEmpty(field.getValidatorClassName())); } public void testGetValidatorClassNameIfMultipleValidatorIsUsed() throws Exception { createField(InputFieldFactory.createEmailField("propertyName", "displayName", true)); assertEquals("commons-validations.js uses this class name for validation", "validate-NOTEMPTY$$EMAIL", field.getValidatorClassName()); } public void testReadable(){ InputField nameField = InputFieldFactory.createTextField("test", "test", false); nameField.setReadable(true); createField(nameField); assertTrue(field.isReadable()); field.setReadable(false); assertFalse(field.isReadable()); assertFalse(nameField.isReadable()); } public void testValidatable(){ InputField nameField = InputFieldFactory.createTextField("test", "test", false); nameField.setReadable(true); createField(nameField); assertTrue(field.isReadable()); assertTrue(field.isValidateable()); nameField.setModifiable(false); assertFalse(field.isValidateable()); } public void testSetPrivilegeToModify(){ InputField nameField = InputFieldFactory.createTextField("test", "test", false); nameField.setReadable(true); createField(nameField); assertNull(field.getPrivilegeToModify()); nameField.setPrivilegeToModify("abcd:efg"); assertEquals("abcd:efg", field.getPrivilegeToModify()); field.setPrivilegeToModify("kk:kk"); assertEquals("kk:kk", nameField.getPrivilegeToModify()); } public void testSetPrivilegeToRead(){ InputField nameField = InputFieldFactory.createTextField("test", "test", false); nameField.setReadable(true); createField(nameField); assertNull(field.getPrivilegeToRead()); nameField.setPrivilegeToRead("abcd:efg"); assertEquals("abcd:efg", field.getPrivilegeToRead()); field.setPrivilegeToRead("kk:kk"); assertEquals("kk:kk", nameField.getPrivilegeToRead()); } private void createField(final InputField dateField) { field = new TestQualifiedPropertyNameInputField(dateField); } private static class TestQualifiedPropertyNameInputField extends QualifiedPropertyNameInputField { public TestQualifiedPropertyNameInputField(InputField field) { super(field); } public Category getCategory() { return null; //To change body of implemented methods use File | Settings | File Templates. } protected String qualifyPropertyName(String propertyName) { return null; //To change body of implemented methods use File | Settings | File Templates. } protected InputField qualifySubfield(InputField subfield) { return null; //To change body of implemented methods use File | Settings | File Templates. } } }
package org.helioviewer.gl3d.view; import java.util.Calendar; import java.util.GregorianCalendar; import javax.media.opengl.GL; import org.helioviewer.base.math.Vector2dDouble; import org.helioviewer.base.physics.Astronomy; import org.helioviewer.base.physics.Constants; import org.helioviewer.base.physics.DifferentialRotation; import org.helioviewer.gl3d.changeevent.ImageTextureRecapturedReason; import org.helioviewer.gl3d.model.image.GL3DImageMesh; import org.helioviewer.gl3d.scenegraph.GL3DState; import org.helioviewer.gl3d.shader.GL3DImageFragmentShaderProgram; import org.helioviewer.gl3d.shader.GL3DImageVertexShaderProgram; import org.helioviewer.gl3d.shader.GL3DShaderFactory; import org.helioviewer.viewmodel.changeevent.CacheStatusChangedReason; import org.helioviewer.viewmodel.changeevent.ChangeEvent; import org.helioviewer.viewmodel.changeevent.RegionChangedReason; import org.helioviewer.viewmodel.changeevent.RegionUpdatedReason; import org.helioviewer.viewmodel.changeevent.SubImageDataChangedReason; import org.helioviewer.viewmodel.metadata.MetaData; import org.helioviewer.viewmodel.region.Region; import org.helioviewer.viewmodel.region.StaticRegion; import org.helioviewer.viewmodel.view.View; import org.helioviewer.viewmodel.view.ViewListener; import org.helioviewer.viewmodel.view.ViewportView; import org.helioviewer.viewmodel.view.jp2view.JHVJPXView; import org.helioviewer.viewmodel.view.opengl.GLTextureHelper; import org.helioviewer.viewmodel.view.opengl.shader.GLFragmentShaderView; import org.helioviewer.viewmodel.view.opengl.shader.GLShaderBuilder; import org.helioviewer.viewmodel.viewport.Viewport; /** * Connects the 3D viewchain to the 2D viewchain. The underlying 2D viewchain * renders it's image to the framebuffer. This view then copies that framebuffer * to a texture object which can then be used to be mapped onto a 3D mesh. Use a * {@link GL3DImageMesh} to connect the resulting texture to a mesh, or directly * use the {@link GL3DShaderFactory} to create standard Image Meshes. * * @author Simon Spoerri (simon.spoerri@fhnw.ch) * */ public class GL3DImageTextureView extends AbstractGL3DView implements GL3DView, GLFragmentShaderView { public GL3DImageTextureView() { super(); } private int textureId = -1; private Vector2dDouble textureScale = null; private Region capturedRegion = null; private boolean recaptureRequested = true; private boolean regionChanged = true; private boolean forceUpdate = false; private GL3DImageVertexShaderProgram vertexShader = null; public MetaData metadata = null; public double minZ = 0.0; public double maxZ = Constants.SunRadius; private final GL3DImageFragmentShaderProgram fragmentShader = new GL3DImageFragmentShaderProgram(); @Override public void renderGL(GL gl, boolean nextView) { render3D(GL3DState.get()); } @Override public void render3D(GL3DState state) { if (this.getView() != null) { // Only copy Framebuffer if necessary GLTextureHelper th = new GLTextureHelper(); if (true) { this.capturedRegion = copyScreenToTexture(state, th); // gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT); if (forceUpdate) { this.notifyViewListeners(new ChangeEvent(new ImageTextureRecapturedReason(this, this.textureId, this.textureScale, StaticRegion.createAdaptedRegion(this.capturedRegion.getRectangle())))); } regionChanged = false; forceUpdate = false; recaptureRequested = false; } } } @Override public void deactivate(GL3DState state) { textureHelper.delTextureID(state.gl, this.textureId); this.textureId = -1; } public int getTextureId() { return this.textureId; } public Region copyScreenToTexture(GL3DState state, GLTextureHelper th) { JHVJPXView jhvjpx = getAdapter(JHVJPXView.class); Region region = jhvjpx.getImageData().getRegion(); Viewport viewport = getAdapter(ViewportView.class).getViewport(); if (viewport == null || region == null) { regionChanged = false; return null; } this.textureId = getAdapter(JHVJPXView.class).texID; // th.copyFrameBufferToTexture(gl, textureId, captureRectangle); this.textureScale = th.getTextureScale(textureId); if (vertexShader != null) { double xOffset = (region.getLowerLeftCorner().getX()); double yOffset = (region.getLowerLeftCorner().getY()); double xScale = (1. / region.getWidth()); double yScale = (1. / region.getHeight()); double deltat = jhvjpx.getImageData().getDateMillis() / 1000.0 - Constants.referenceDate; Calendar cal = new GregorianCalendar(); cal.setTimeInMillis((long)deltat*1000); theta = Astronomy.getB0InRadians(cal); phi = DifferentialRotation.calculateRotationInRadians(0.0, deltat) % (Math.PI * 2.0); this.vertexShader.changeRect(xOffset, yOffset, xScale, yScale); this.vertexShader.changeTextureScale(jhvjpx.getImageData().getScaleX(), jhvjpx.getImageData().getScaleY()); this.vertexShader.changeAngles(theta, phi); if(!jhvjpx.getBaseDifferenceMode() && jhvjpx.getPreviousImageData()!=null){ Region differenceRegion = jhvjpx.getPreviousImageData().getRegion(); double differenceXOffset = (differenceRegion.getLowerLeftCorner().getX()); double differenceYOffset = (differenceRegion.getLowerLeftCorner().getY()); double differenceXScale = (1./differenceRegion.getWidth()); double differenceYScale = (1./differenceRegion.getHeight()); double differenceDeltat = jhvjpx.getPreviousImageData().getDateMillis() / 1000.0 - Constants.referenceDate; double differenceTheta = 0.0; double differencePhi = DifferentialRotation.calculateRotationInRadians(0.0, differenceDeltat) % (Math.PI * 2.0); this.vertexShader.changeDifferenceTextureScale(jhvjpx.getPreviousImageData().getScaleX(), jhvjpx.getPreviousImageData().getScaleY()); this.vertexShader.setDifferenceRect(differenceXOffset, differenceYOffset, differenceXScale, differenceYScale); this.vertexShader.changeDifferenceAngles(differenceTheta, differencePhi); this.fragmentShader.changeDifferenceTextureScale(jhvjpx.getPreviousImageData().getScaleX(), jhvjpx.getPreviousImageData().getScaleY()); this.fragmentShader.setDifferenceRect(differenceXOffset, differenceYOffset, differenceXScale, differenceYScale); this.fragmentShader.changeDifferenceAngles(differenceTheta, differencePhi); } else if(jhvjpx.getBaseDifferenceMode() && jhvjpx.getBaseDifferenceImageData()!=null){ Region differenceRegion = jhvjpx.getBaseDifferenceImageData().getRegion(); double differenceXOffset = (differenceRegion.getLowerLeftCorner().getX()); double differenceYOffset = (differenceRegion.getLowerLeftCorner().getY()); double differenceXScale = (1./differenceRegion.getWidth()); double differenceYScale = (1./differenceRegion.getHeight()); double differenceDeltat = jhvjpx.getBaseDifferenceImageData().getDateMillis() / 1000.0 - Constants.referenceDate; cal.setTimeInMillis((long)differenceDeltat*1000); double differenceTheta = Astronomy.getB0InRadians(cal); double differencePhi = DifferentialRotation.calculateRotationInRadians(0.0, differenceDeltat) % (Math.PI * 2.0); this.vertexShader.changeDifferenceTextureScale(jhvjpx.getBaseDifferenceImageData().getScaleX(), jhvjpx.getBaseDifferenceImageData().getScaleY()); this.vertexShader.setDifferenceRect(differenceXOffset, differenceYOffset, differenceXScale, differenceYScale); this.vertexShader.changeDifferenceAngles(differenceTheta, differencePhi); this.fragmentShader.changeDifferenceTextureScale(jhvjpx.getBaseDifferenceImageData().getScaleX(), jhvjpx.getBaseDifferenceImageData().getScaleY()); this.fragmentShader.setDifferenceRect(differenceXOffset, differenceYOffset, differenceXScale, differenceYScale); this.fragmentShader.changeDifferenceAngles(differenceTheta, differencePhi); } else{ this.fragmentShader.changeDifferenceTextureScale(jhvjpx.getImageData().getScaleX(), jhvjpx.getImageData().getScaleY()); this.fragmentShader.setDifferenceRect(xOffset, yOffset, xScale, yScale); this.fragmentShader.changeDifferenceAngles(theta, phi); } this.fragmentShader.changeTextureScale(jhvjpx.getImageData().getScaleX(), jhvjpx.getImageData().getScaleY()); this.fragmentShader.changeAngles(theta, phi); } this.recaptureRequested = false; return region; } public double phi = 0.0; public double theta = 0.0; @Override protected void setViewSpecificImplementation(View newView, ChangeEvent changeEvent) { newView.addViewListener(new ViewListener() { @Override public void viewChanged(View sender, ChangeEvent aEvent) { if (aEvent.reasonOccurred(RegionChangedReason.class)) { recaptureRequested = true; regionChanged = true; } else if (aEvent.reasonOccurred(RegionUpdatedReason.class)) { regionChanged = true; } else if (aEvent.reasonOccurred(SubImageDataChangedReason.class)) { recaptureRequested = true; } else if (aEvent.reasonOccurred(CacheStatusChangedReason.class)) { recaptureRequested = true; } } }); } public Vector2dDouble getTextureScale() { return textureScale; } public Region getCapturedRegion() { return capturedRegion; } public void forceUpdate() { this.forceUpdate = true; } public void setVertexShader(GL3DImageVertexShaderProgram vertexShader) { this.vertexShader = vertexShader; } @Override public GLShaderBuilder buildFragmentShader(GLShaderBuilder shaderBuilder) { GLFragmentShaderView nextView = view.getAdapter(GLFragmentShaderView.class); if (nextView != null) { shaderBuilder = nextView.buildFragmentShader(shaderBuilder); } fragmentShader.build(shaderBuilder); return shaderBuilder; } public GL3DImageFragmentShaderProgram getFragmentShader() { return this.fragmentShader; } }
package org.broadinstitute.sting.gatk.walkers.variantutils; import org.apache.poi.hpsf.Variant; import org.broadinstitute.sting.commandline.*; import org.broadinstitute.sting.gatk.arguments.StandardVariantContextInputArgumentCollection; import org.broadinstitute.sting.utils.MathUtils; import org.broadinstitute.sting.utils.codecs.vcf.*; import org.broadinstitute.sting.utils.exceptions.UserException; import org.broadinstitute.sting.utils.text.XReadLines; import org.broadinstitute.sting.gatk.GenomeAnalysisEngine; import org.broadinstitute.sting.utils.MendelianViolation; import org.broadinstitute.sting.utils.variantcontext.VariantContext; import org.broadinstitute.sting.commandline.Argument; import org.broadinstitute.sting.commandline.Output; import org.broadinstitute.sting.gatk.contexts.AlignmentContext; import org.broadinstitute.sting.gatk.contexts.ReferenceContext; import org.broadinstitute.sting.gatk.refdata.RefMetaDataTracker; import org.broadinstitute.sting.gatk.walkers.RodWalker; import org.broadinstitute.sting.utils.SampleUtils; import org.broadinstitute.sting.utils.variantcontext.Allele; import org.broadinstitute.sting.utils.variantcontext.Genotype; import org.broadinstitute.sting.utils.variantcontext.VariantContextUtils; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintStream; import java.util.*; public class SelectVariants extends RodWalker<Integer, Integer> { @ArgumentCollection protected StandardVariantContextInputArgumentCollection variantCollection = new StandardVariantContextInputArgumentCollection(); /** * A site is considered discordant if there exists some sample in the variant track that has a non-reference genotype * and either the site isn't present in this track, the sample isn't present in this track, * or the sample is called reference in this track. */ @Input(fullName="discordance", shortName = "disc", doc="Output variants that were not called in this comparison track", required=false) private RodBinding<VariantContext> discordanceTrack; /** * A site is considered concordant if (1) we are not looking for specific samples and there is a variant called * in both the variant and concordance tracks or (2) every sample present in the variant track is present in the * concordance track and they have the sample genotype call. */ @Input(fullName="concordance", shortName = "conc", doc="Output variants that were also called in this comparison track", required=false) private RodBinding<VariantContext> concordanceTrack; @Output(doc="File to which variants should be written",required=true) protected VCFWriter vcfWriter = null; @Argument(fullName="sample_name", shortName="sn", doc="Include genotypes from this sample. Can be specified multiple times", required=false) public Set<String> sampleNames = new HashSet<String>(0); @Argument(fullName="sample_expressions", shortName="se", doc="Regular expression to select many samples from the ROD tracks provided. Can be specified multiple times", required=false) public Set<String> sampleExpressions ; @Input(fullName="sample_file", shortName="sf", doc="File containing a list of samples (one per line) to include. Can be specified multiple times", required=false) public Set<File> sampleFiles; /** * Note that sample exclusion takes precedence over inclusion, so that if a sample is in both lists it will be excluded. */ @Argument(fullName="exclude_sample_name", shortName="xl_sn", doc="Exclude genotypes from this sample. Can be specified multiple times", required=false) public Set<String> XLsampleNames = new HashSet<String>(0); /** * Note that sample exclusion takes precedence over inclusion, so that if a sample is in both lists it will be excluded. */ @Input(fullName="exclude_sample_file", shortName="xl_sf", doc="File containing a list of samples (one per line) to exclude. Can be specified multiple times", required=false) public Set<File> XLsampleFiles = new HashSet<File>(0); /** * Note that these expressions are evaluated *after* the specified samples are extracted and the INFO field annotations are updated. */ @Argument(shortName="select", doc="One or more criteria to use when selecting the data", required=false) public ArrayList<String> SELECT_EXPRESSIONS = new ArrayList<String>(); @Argument(fullName="excludeNonVariants", shortName="env", doc="Don't include loci found to be non-variant after the subsetting procedure", required=false) private boolean EXCLUDE_NON_VARIANTS = false; @Argument(fullName="excludeFiltered", shortName="ef", doc="Don't include filtered loci in the analysis", required=false) private boolean EXCLUDE_FILTERED = false; /** * When this argument is used, we can choose to include only multiallelic or biallelic sites, depending on how many alleles are listed in the ALT column of a vcf. * For example, a multiallelic record such as: * 1 100 . A AAA,AAAAA * will be excluded if "-restrictAllelesTo BIALLELIC" is included, because there are two alternate alleles, whereas a record such as: * 1 100 . A T * will be included in that case, but would be excluded if "-restrictAllelesTo MULTIALLELIC */ @Argument(fullName="restrictAllelesTo", shortName="restrictAllelesTo", doc="Select only variants of a particular allelicity. Valid options are ALL (default), MULTIALLELIC or BIALLELIC", required=false) private NumberAlleleRestriction alleleRestriction = NumberAlleleRestriction.ALL; @Argument(fullName="keepOriginalAC", shortName="keepOriginalAC", doc="Don't update the AC, AF, or AN values in the INFO field after selecting", required=false) private boolean KEEP_ORIGINAL_CHR_COUNTS = false; @Hidden @Argument(fullName="keepAFSpectrum", shortName="keepAF", doc="Don't include loci found to be non-variant after the subsetting procedure", required=false) private boolean KEEP_AF_SPECTRUM = false; @Hidden @Argument(fullName="afFile", shortName="afFile", doc="The output recal file used by ApplyRecalibration", required=false) private File AF_FILE = new File(""); @Hidden @Argument(fullName="family_structure_file", shortName="familyFile", doc="USE YAML FILE INSTEAD (-SM) !!! string formatted as dad+mom=child where these parameters determine which sample names are examined", required=false) private File FAMILY_STRUCTURE_FILE = null; /** * String formatted as dad+mom=child where these parameters determine which sample names are examined. */ @Argument(fullName="family_structure", shortName="family", doc="Deprecated; use the -SM argument instead", required=false) private String FAMILY_STRUCTURE = ""; /** * Sample metadata information will be taken from a YAML file (see the -SM argument). */ @Argument(fullName="mendelianViolation", shortName="mv", doc="output mendelian violation sites only", required=false) private Boolean MENDELIAN_VIOLATIONS = false; @Argument(fullName="mendelianViolationQualThreshold", shortName="mvq", doc="Minimum genotype QUAL score for each trio member required to accept a site as a violation", required=false) private double MENDELIAN_VIOLATION_QUAL_THRESHOLD = 0; /** * Variants are kept in memory to guarantee that exactly n variants will be chosen randomly, so use it only for a reasonable * number of variants. Use --select_random_fraction for larger numbers of variants. */ @Argument(fullName="select_random_number", shortName="number", doc="Selects a number of variants at random from the variant track", required=false) private int numRandom = 0; /** * This routine is based on probability, so the final result is not guaranteed to carry the exact fraction. Can be used for large fractions. */ @Argument(fullName="select_random_fraction", shortName="fraction", doc="Selects a fraction (a number between 0 and 1) of the total variants at random from the variant track", required=false) private double fractionRandom = 0; /** * This argument select particular kinds of variants out of a list. If left empty, there is no type selection and all variant types are considered for other selection criteria. * When specified one or more times, a particular type of variant is selected. * */ @Argument(fullName="selectTypeToInclude", shortName="selectType", doc="Select only a certain type of variants from the input file. Valid types are INDEL, SNP, MIXED, MNP, SYMBOLIC, NO_VARIATION. Can be specified multiple times", required=false) private List<VariantContext.Type> TYPES_TO_INCLUDE = new ArrayList<VariantContext.Type>(); @Hidden @Argument(fullName="outMVFile", shortName="outMVFile", doc="USE YAML FILE INSTEAD (-SM) !!! string formatted as dad+mom=child where these parameters determine which sample names are examined", required=false) private String outMVFile = null; /* Private class used to store the intermediate variants in the integer random selection process */ private class RandomVariantStructure { private VariantContext vc; RandomVariantStructure(VariantContext vcP) { vc = vcP; } public void set (VariantContext vcP) { vc = vcP; } } public enum NumberAlleleRestriction { ALL, BIALLELIC, MULTIALLELIC } private ArrayList<VariantContext.Type> selectedTypes = new ArrayList<VariantContext.Type>(); private ArrayList<String> selectNames = new ArrayList<String>(); private List<VariantContextUtils.JexlVCMatchExp> jexls = null; private TreeSet<String> samples = new TreeSet<String>(); private boolean NO_SAMPLES_SPECIFIED = false; private boolean DISCORDANCE_ONLY = false; private boolean CONCORDANCE_ONLY = false; private Set<MendelianViolation> mvSet = new HashSet<MendelianViolation>(); /* variables used by the SELECT RANDOM modules */ private boolean SELECT_RANDOM_NUMBER = false; private boolean SELECT_RANDOM_FRACTION = false; private int variantNumber = 0; private int nVariantsAdded = 0; private int positionToAdd = 0; private RandomVariantStructure [] variantArray; /* Variables used for random selection with AF boosting */ private ArrayList<Double> afBreakpoints = null; private ArrayList<Double> afBoosts = null; double bkDelta = 0.0; private PrintStream outMVFileStream = null; /** * Set up the VCF writer, the sample expressions and regexs, and the JEXL matcher */ public void initialize() { // Get list of samples to include in the output List<String> rodNames = Arrays.asList(variantCollection.variants.getName()); Map<String, VCFHeader> vcfRods = VCFUtils.getVCFHeadersFromRods(getToolkit(), rodNames); TreeSet<String> vcfSamples = new TreeSet<String>(SampleUtils.getSampleList(vcfRods, VariantContextUtils.GenotypeMergeType.REQUIRE_UNIQUE)); Collection<String> samplesFromFile = SampleUtils.getSamplesFromFiles(sampleFiles); Collection<String> samplesFromExpressions = SampleUtils.matchSamplesExpressions(vcfSamples, sampleExpressions); // first, add any requested samples samples.addAll(samplesFromFile); samples.addAll(samplesFromExpressions); samples.addAll(sampleNames); // if none were requested, we want all of them if ( samples.isEmpty() ) { samples.addAll(vcfSamples); NO_SAMPLES_SPECIFIED = true; } // now, exclude any requested samples Collection<String> XLsamplesFromFile = SampleUtils.getSamplesFromFiles(XLsampleFiles); samples.removeAll(XLsamplesFromFile); samples.removeAll(XLsampleNames); if ( samples.size() == 0 && !NO_SAMPLES_SPECIFIED ) throw new UserException("All samples requested to be included were also requested to be excluded."); for ( String sample : samples ) logger.info("Including sample '" + sample + "'"); // if user specified types to include, add these, otherwise, add all possible variant context types to list of vc types to include if (TYPES_TO_INCLUDE.isEmpty()) { for (VariantContext.Type t : VariantContext.Type.values()) selectedTypes.add(t); } else { for (VariantContext.Type t : TYPES_TO_INCLUDE) selectedTypes.add(t); } // Initialize VCF header Set<VCFHeaderLine> headerLines = VCFUtils.smartMergeHeaders(vcfRods.values(), logger); headerLines.add(new VCFHeaderLine("source", "SelectVariants")); if (KEEP_ORIGINAL_CHR_COUNTS) { headerLines.add(new VCFFormatHeaderLine("AC_Orig", 1, VCFHeaderLineType.Integer, "Original AC")); headerLines.add(new VCFFormatHeaderLine("AF_Orig", 1, VCFHeaderLineType.Float, "Original AF")); headerLines.add(new VCFFormatHeaderLine("AN_Orig", 1, VCFHeaderLineType.Integer, "Original AN")); } vcfWriter.writeHeader(new VCFHeader(headerLines, samples)); for (int i = 0; i < SELECT_EXPRESSIONS.size(); i++) { // It's not necessary that the user supply select names for the JEXL expressions, since those // expressions will only be needed for omitting records. Make up the select names here. selectNames.add(String.format("select-%d", i)); } jexls = VariantContextUtils.initializeMatchExps(selectNames, SELECT_EXPRESSIONS); // Look at the parameters to decide which analysis to perform DISCORDANCE_ONLY = discordanceTrack.isBound(); if (DISCORDANCE_ONLY) logger.info("Selecting only variants discordant with the track: " + discordanceTrack.getName()); CONCORDANCE_ONLY = concordanceTrack.isBound(); if (CONCORDANCE_ONLY) logger.info("Selecting only variants concordant with the track: " + concordanceTrack.getName()); if (MENDELIAN_VIOLATIONS) { if ( FAMILY_STRUCTURE_FILE != null) { try { for ( final String line : new XReadLines( FAMILY_STRUCTURE_FILE ) ) { MendelianViolation mv = new MendelianViolation(line, MENDELIAN_VIOLATION_QUAL_THRESHOLD); if (samples.contains(mv.getSampleChild()) && samples.contains(mv.getSampleDad()) && samples.contains(mv.getSampleMom())) mvSet.add(mv); } } catch ( FileNotFoundException e ) { throw new UserException.CouldNotReadInputFile(AF_FILE, e); } if (outMVFile != null) try { outMVFileStream = new PrintStream(outMVFile); } catch (FileNotFoundException e) { throw new UserException.CouldNotCreateOutputFile(outMVFile, "Can't open output file", e); } } else mvSet.add(new MendelianViolation(getToolkit(), MENDELIAN_VIOLATION_QUAL_THRESHOLD)); } else if (!FAMILY_STRUCTURE.isEmpty()) { mvSet.add(new MendelianViolation(FAMILY_STRUCTURE, MENDELIAN_VIOLATION_QUAL_THRESHOLD)); MENDELIAN_VIOLATIONS = true; } SELECT_RANDOM_NUMBER = numRandom > 0; if (SELECT_RANDOM_NUMBER) { logger.info("Selecting " + numRandom + " variants at random from the variant track"); variantArray = new RandomVariantStructure[numRandom]; } SELECT_RANDOM_FRACTION = fractionRandom > 0; if (SELECT_RANDOM_FRACTION) logger.info("Selecting approximately " + 100.0*fractionRandom + "% of the variants at random from the variant track"); if (KEEP_AF_SPECTRUM) { try { afBreakpoints = new ArrayList<Double>(); afBoosts = new ArrayList<Double>(); logger.info("Reading in AF boost table..."); boolean firstLine = false; for ( final String line : new XReadLines( AF_FILE ) ) { if (!firstLine) { firstLine = true; continue; } final String[] vals = line.split(" "); double bkp = Double.valueOf(vals[0]); double afb = Double.valueOf(vals[1]); afBreakpoints.add(bkp); afBoosts.add(afb); } bkDelta = afBreakpoints.get(0); } catch ( FileNotFoundException e ) { throw new UserException.CouldNotReadInputFile(AF_FILE, e); } } } /** * Subset VC record if necessary and emit the modified record (provided it satisfies criteria for printing) * * @param tracker the ROD tracker * @param ref reference information * @param context alignment info * @return 1 if the record was printed to the output file, 0 if otherwise */ @Override public Integer map(RefMetaDataTracker tracker, ReferenceContext ref, AlignmentContext context) { if ( tracker == null ) return 0; Collection<VariantContext> vcs = tracker.getValues(variantCollection.variants, context.getLocation()); if ( vcs == null || vcs.size() == 0) { return 0; } for (VariantContext vc : vcs) { if (MENDELIAN_VIOLATIONS) { boolean foundMV = false; for (MendelianViolation mv : mvSet) { if (mv.isViolation(vc)) { foundMV = true; //System.out.println(vc.toString()); if (outMVFile != null) outMVFileStream.format("MV@%s:%d. REF=%s, ALT=%s, AC=%d, momID=%s, dadID=%s, childID=%s, momG=%s, momGL=%s, dadG=%s, dadGL=%s, " + "childG=%s childGL=%s\n",vc.getChr(), vc.getStart(), vc.getReference().getDisplayString(), vc.getAlternateAllele(0).getDisplayString(), vc.getChromosomeCount(vc.getAlternateAllele(0)), mv.getSampleMom(), mv.getSampleDad(), mv.getSampleChild(), vc.getGenotype(mv.getSampleMom()).toBriefString(), vc.getGenotype(mv.getSampleMom()).getLikelihoods().getAsString(), vc.getGenotype(mv.getSampleDad()).toBriefString(), vc.getGenotype(mv.getSampleMom()).getLikelihoods().getAsString(), vc.getGenotype(mv.getSampleChild()).toBriefString(),vc.getGenotype(mv.getSampleChild()).getLikelihoods().getAsString() ); } } if (!foundMV) break; } if (DISCORDANCE_ONLY) { Collection<VariantContext> compVCs = tracker.getValues(discordanceTrack, context.getLocation()); if (!isDiscordant(vc, compVCs)) return 0; } if (CONCORDANCE_ONLY) { Collection<VariantContext> compVCs = tracker.getValues(concordanceTrack, context.getLocation()); if (!isConcordant(vc, compVCs)) return 0; } if (alleleRestriction.equals(NumberAlleleRestriction.BIALLELIC) && !vc.isBiallelic()) continue; if (alleleRestriction.equals(NumberAlleleRestriction.MULTIALLELIC) && vc.isBiallelic()) continue; if (!selectedTypes.contains(vc.getType())) continue; VariantContext sub = subsetRecord(vc, samples); if ( (sub.isPolymorphic() || !EXCLUDE_NON_VARIANTS) && (!sub.isFiltered() || !EXCLUDE_FILTERED) ) { for ( VariantContextUtils.JexlVCMatchExp jexl : jexls ) { if ( !VariantContextUtils.match(sub, jexl) ) { return 0; } } if (SELECT_RANDOM_NUMBER) { randomlyAddVariant(++variantNumber, sub, ref.getBase()); } else if (!SELECT_RANDOM_FRACTION || (!KEEP_AF_SPECTRUM && GenomeAnalysisEngine.getRandomGenerator().nextDouble() < fractionRandom)) { vcfWriter.add(sub); } else { if (SELECT_RANDOM_FRACTION && KEEP_AF_SPECTRUM ) { // ok we have a comp VC and we need to match the AF spectrum of inputAFRodName. // We then pick a variant with probablity AF*desiredFraction if ( sub.hasAttribute(VCFConstants.ALLELE_FREQUENCY_KEY) ) { String afo = sub.getAttributeAsString(VCFConstants.ALLELE_FREQUENCY_KEY); double af; double afBoost = 1.0; if (afo.contains(",")) { String[] afs = afo.split(","); afs[0] = afs[0].substring(1,afs[0].length()); afs[afs.length-1] = afs[afs.length-1].substring(0,afs[afs.length-1].length()-1); double[] afd = new double[afs.length]; for (int k=0; k < afd.length; k++) afd[k] = Double.valueOf(afs[k]); af = MathUtils.arrayMax(afd); //af = Double.valueOf(afs[0]); } else af = Double.valueOf(afo); // now boost af by table read from file if desired //double bkpt = 0.0; int bkidx = 0; if (!afBreakpoints.isEmpty()) { for ( Double bkpt : afBreakpoints) { if (af < bkpt + bkDelta) break; else bkidx++; } if (bkidx >=afBoosts.size()) bkidx = afBoosts.size()-1; afBoost = afBoosts.get(bkidx); //System.out.formatPrin("af:%f bkidx:%d afboost:%f\n",af,bkidx,afBoost); } //System.out.format("%s .. %4.4f\n",afo.toString(), af); if (GenomeAnalysisEngine.getRandomGenerator().nextDouble() < fractionRandom * afBoost * afBoost) vcfWriter.add(sub); } } } } } return 1; } /** * Checks if vc has a variant call for (at least one of) the samples. * @param vc the variant rod VariantContext. Here, the variant is the dataset you're looking for discordances to (e.g. HapMap) * @param compVCs the comparison VariantContext (discordance * @return */ private boolean isDiscordant (VariantContext vc, Collection<VariantContext> compVCs) { if (vc == null) return false; // if we're not looking at specific samples then the absense of a compVC means discordance if (NO_SAMPLES_SPECIFIED && (compVCs == null || compVCs.isEmpty())) return true; // check if we find it in the variant rod Map<String, Genotype> genotypes = vc.getGenotypes(samples); for (Genotype g : genotypes.values()) { if (sampleHasVariant(g)) { // There is a variant called (or filtered with not exclude filtered option set) that is not HomRef for at least one of the samples. if (compVCs == null) return true; // Look for this sample in the all vcs of the comp ROD track. boolean foundVariant = false; for (VariantContext compVC : compVCs) { if (sampleHasVariant(compVC.getGenotype(g.getSampleName()))) { foundVariant = true; break; } } // if (at least one sample) was not found in all VCs of the comp ROD, we have discordance if (!foundVariant) return true; } } return false; // we only get here if all samples have a variant in the comp rod. } private boolean isConcordant (VariantContext vc, Collection<VariantContext> compVCs) { if (vc == null || compVCs == null || compVCs.isEmpty()) return false; // if we're not looking for specific samples then the fact that we have both VCs is enough to call it concordant. if (NO_SAMPLES_SPECIFIED) return true; // make a list of all samples contained in this variant VC that are being tracked by the user command line arguments. Set<String> variantSamples = vc.getSampleNames(); variantSamples.retainAll(samples); // check if we can find all samples from the variant rod in the comp rod. for (String sample : variantSamples) { boolean foundSample = false; for (VariantContext compVC : compVCs) { Genotype varG = vc.getGenotype(sample); Genotype compG = compVC.getGenotype(sample); if (haveSameGenotypes(varG, compG)) { foundSample = true; break; } } // if at least one sample doesn't have the same genotype, we don't have concordance if (!foundSample) { return false; } } return true; } private boolean sampleHasVariant(Genotype g) { return (g !=null && !g.isHomRef() && (g.isCalled() || (g.isFiltered() && !EXCLUDE_FILTERED))); } private boolean haveSameGenotypes(Genotype g1, Genotype g2) { if ((g1.isCalled() && g2.isFiltered()) || (g2.isCalled() && g1.isFiltered()) || (g1.isFiltered() && g2.isFiltered() && EXCLUDE_FILTERED)) return false; List<Allele> a1s = g1.getAlleles(); List<Allele> a2s = g2.getAlleles(); return (a1s.containsAll(a2s) && a2s.containsAll(a1s)); } @Override public Integer reduceInit() { return 0; } @Override public Integer reduce(Integer value, Integer sum) { return value + sum; } public void onTraversalDone(Integer result) { logger.info(result + " records processed."); if (SELECT_RANDOM_NUMBER) { int positionToPrint = positionToAdd; for (int i=0; i<numRandom; i++) { vcfWriter.add(variantArray[positionToPrint].vc); positionToPrint = nextCircularPosition(positionToPrint); } } } /** * Helper method to subset a VC record, modifying some metadata stored in the INFO field (i.e. AN, AC, AF). * * @param vc the VariantContext record to subset * @param samples the samples to extract * @return the subsetted VariantContext */ private VariantContext subsetRecord(VariantContext vc, Set<String> samples) { if ( samples == null || samples.isEmpty() ) return vc; ArrayList<Genotype> genotypes = new ArrayList<Genotype>(); for ( Map.Entry<String, Genotype> genotypePair : vc.getGenotypes().entrySet() ) { if ( samples.contains(genotypePair.getKey()) ) genotypes.add(genotypePair.getValue()); } VariantContext sub = vc.subContextFromGenotypes(genotypes, vc.getAlleles()); // if we have fewer alternate alleles in the selected VC than in the original VC, we need to strip out the GL/PLs (because they are no longer accurate) if ( vc.getAlleles().size() != sub.getAlleles().size() ) sub = VariantContext.modifyGenotypes(sub, VariantContextUtils.stripPLs(vc.getGenotypes())); HashMap<String, Object> attributes = new HashMap<String, Object>(sub.getAttributes()); int depth = 0; for (String sample : sub.getSampleNames()) { Genotype g = sub.getGenotype(sample); if (g.isNotFiltered() && g.isCalled()) { String dp = (String) g.getAttribute("DP"); if (dp != null && ! dp.equals(VCFConstants.MISSING_DEPTH_v3) && ! dp.equals(VCFConstants.MISSING_VALUE_v4) ) { depth += Integer.valueOf(dp); } } } if (KEEP_ORIGINAL_CHR_COUNTS) { if ( attributes.containsKey(VCFConstants.ALLELE_COUNT_KEY) ) attributes.put("AC_Orig",attributes.get(VCFConstants.ALLELE_COUNT_KEY)); if ( attributes.containsKey(VCFConstants.ALLELE_FREQUENCY_KEY) ) attributes.put("AF_Orig",attributes.get(VCFConstants.ALLELE_FREQUENCY_KEY)); if ( attributes.containsKey(VCFConstants.ALLELE_NUMBER_KEY) ) attributes.put("AN_Orig",attributes.get(VCFConstants.ALLELE_NUMBER_KEY)); } VariantContextUtils.calculateChromosomeCounts(sub,attributes,false); attributes.put("DP", depth); sub = VariantContext.modifyAttributes(sub, attributes); return sub; } private void randomlyAddVariant(int rank, VariantContext vc, byte refBase) { if (nVariantsAdded < numRandom) variantArray[nVariantsAdded++] = new RandomVariantStructure(vc); else { double v = GenomeAnalysisEngine.getRandomGenerator().nextDouble(); double t = (1.0/(rank-numRandom+1)); if ( v < t) { variantArray[positionToAdd].set(vc); nVariantsAdded++; positionToAdd = nextCircularPosition(positionToAdd); } } } private int nextCircularPosition(int cur) { if ((cur + 1) == variantArray.length) return 0; return cur + 1; } }
/** * Symboliverse * * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com */ package com.samdide.desktop.symboliverse; import javafx.application.Application; import javafx.event.Event; import javafx.event.EventHandler; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.control.Button; import javafx.scene.input.MouseEvent; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.stage.Stage; public class Symboliverse extends Application { final static int CANVAS_WIDTH = 400; final static int CANVAS_HEIGHT = 300; final static int GRID_LINE_WIDTH = 1; /** distance between grid lines in pixels */ final static int GRID_DISTANCE = 20; @Override public void start(Stage primaryStage) { primaryStage.setTitle("Symboliverse"); Group root = new Group(); Canvas canvas = new Canvas(CANVAS_WIDTH, CANVAS_HEIGHT); GraphicsContext gc = canvas.getGraphicsContext2D(); canvas.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent arg0) { System.out.println("Event mouse clicked"); } }); drawGrid(gc); drawShapes(gc); root.getChildren().add(canvas); primaryStage.setScene(new Scene(root)); primaryStage.show(); } private void drawGrid(GraphicsContext gc) { gc.setStroke(Color.LIGHTSTEELBLUE); gc.setLineWidth(GRID_LINE_WIDTH); for ( int i = GRID_DISTANCE; i < CANVAS_WIDTH; i += GRID_DISTANCE ) { gc.strokeLine(i, 0, i, CANVAS_HEIGHT); gc.strokeLine(0, i, CANVAS_WIDTH, i); } } private void drawShapes(GraphicsContext gc) { gc.setStroke(Color.BLUE); gc.setLineWidth(2); gc.strokeRect(100, 60, 150, 130); gc.strokeLine(100, 90, 250, 90); gc.strokeLine(100, 120, 250, 120); gc.setLineWidth(1); gc.setFont(new Font("Consolas", 14)); gc.fillText("BankAccount", 120, 80); } public static void main(String[] args) { Application.launch(args); } }
package com.stackallocated.imageupload; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import android.app.Activity; import android.content.Intent; import android.content.res.AssetFileDescriptor; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.widget.Toast; public class UploadActivity extends Activity { private final static String TAG = "UploadActivity"; void makeToast(String msg) { Toast toast = Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT); toast.show(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ArrayList<Uri> imageUris = null; final Intent intent = getIntent(); // We have an image to upload, get list of images. if (Intent.ACTION_SEND.equals(intent.getAction())) { Log.v(TAG, "Got send action"); Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM); if (imageUri != null) { imageUris = new ArrayList<Uri>(Arrays.asList(imageUri)); } else { makeToast("No image provided to upload!"); } } else if (Intent.ACTION_SEND_MULTIPLE.equals(intent.getAction())) { Log.v(TAG, "Got multiple send action"); imageUris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM); } // Sanitize the list of image URIs. Iterator<Uri> it = imageUris.iterator(); while (it.hasNext()) { Uri imageUri = it.next(); if (imageUri == null) { Log.d(TAG, "Removed null URI"); it.remove(); continue; } try { AssetFileDescriptor desc = getContentResolver().openAssetFileDescriptor(imageUri, "r"); desc.close(); } catch (Exception e) { Log.d(TAG, "Couldn't open URI '" + imageUri + "'"); it.remove(); } } // Trigger the upload. if (imageUris != null && imageUris.size() > 0) { if (imageUris.size() > 1) { makeToast("Uploading " + imageUris.size() + " images!"); } else{ makeToast("Uploading image!"); } for (Uri imageUri : imageUris) { Log.d(TAG, "Uploading image '" + imageUri + "'"); } } // This activity never needs to show the UI. finish(); return; } }
package org.springframework.roo.classpath.javaparser.details; import japa.parser.ast.expr.AnnotationExpr; import japa.parser.ast.expr.ArrayInitializerExpr; import japa.parser.ast.expr.BinaryExpr; import japa.parser.ast.expr.BooleanLiteralExpr; import japa.parser.ast.expr.CharLiteralExpr; import japa.parser.ast.expr.ClassExpr; import japa.parser.ast.expr.DoubleLiteralExpr; import japa.parser.ast.expr.Expression; import japa.parser.ast.expr.FieldAccessExpr; import japa.parser.ast.expr.IntegerLiteralExpr; import japa.parser.ast.expr.LongLiteralExpr; import japa.parser.ast.expr.MarkerAnnotationExpr; import japa.parser.ast.expr.MemberValuePair; import japa.parser.ast.expr.NameExpr; import japa.parser.ast.expr.NormalAnnotationExpr; import japa.parser.ast.expr.SingleMemberAnnotationExpr; import japa.parser.ast.expr.StringLiteralExpr; import japa.parser.ast.type.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.roo.classpath.details.annotations.AnnotationAttributeValue; import org.springframework.roo.classpath.details.annotations.AnnotationMetadata; import org.springframework.roo.classpath.details.annotations.ArrayAttributeValue; import org.springframework.roo.classpath.details.annotations.BooleanAttributeValue; import org.springframework.roo.classpath.details.annotations.CharAttributeValue; import org.springframework.roo.classpath.details.annotations.ClassAttributeValue; import org.springframework.roo.classpath.details.annotations.DoubleAttributeValue; import org.springframework.roo.classpath.details.annotations.EnumAttributeValue; import org.springframework.roo.classpath.details.annotations.IntegerAttributeValue; import org.springframework.roo.classpath.details.annotations.LongAttributeValue; import org.springframework.roo.classpath.details.annotations.NestedAnnotationAttributeValue; import org.springframework.roo.classpath.details.annotations.StringAttributeValue; import org.springframework.roo.classpath.javaparser.CompilationUnitServices; import org.springframework.roo.classpath.javaparser.JavaParserUtils; import org.springframework.roo.model.EnumDetails; import org.springframework.roo.model.JavaSymbolName; import org.springframework.roo.model.JavaType; import org.springframework.roo.support.style.ToStringCreator; import org.springframework.roo.support.util.Assert; /** * Java Parser implementation of {@link AnnotationMetadata}. * * @author Ben Alex * @since 1.0 */ public final class JavaParserAnnotationMetadata implements AnnotationMetadata { // Passed in private AnnotationExpr annotationExpr; private CompilationUnitServices compilationUnitServices; // Computed private JavaType annotationType; private List<AnnotationAttributeValue<?>> attributes = new ArrayList<AnnotationAttributeValue<?>>(); private Map<JavaSymbolName, AnnotationAttributeValue<?>> attributeMap = new HashMap<JavaSymbolName, AnnotationAttributeValue<?>>(); public JavaParserAnnotationMetadata(AnnotationExpr annotationExpr, CompilationUnitServices compilationUnitServices) { Assert.notNull(annotationExpr, "Annotation expression required"); Assert.notNull(compilationUnitServices, "Compilation unit services required"); // Store required source information for subsequent mutability support this.annotationExpr = annotationExpr; this.compilationUnitServices = compilationUnitServices; // Obtain the annotation type name from the assorted types of annotations we might have received (ie marker annotations, single member annotations, normal annotations etc) NameExpr nameToFind = JavaParserUtils.getNameExpr(annotationExpr); // Compute the actual annotation type, having regard to the compilation unit package and imports annotationType = JavaParserUtils.getJavaType(compilationUnitServices, nameToFind, null); // Generate some member-value pairs for subsequent parsing List<MemberValuePair> annotationPairs = new ArrayList<MemberValuePair>(); if (annotationExpr instanceof MarkerAnnotationExpr) { // A marker annotation has no values, so we can have no pairs to add } else if (annotationExpr instanceof SingleMemberAnnotationExpr) { SingleMemberAnnotationExpr a = (SingleMemberAnnotationExpr) annotationExpr; // Add the "value=" member-value pair. if (a.getMemberValue() != null) { annotationPairs.add(new MemberValuePair("value", a.getMemberValue())); } } else if (annotationExpr instanceof NormalAnnotationExpr) { NormalAnnotationExpr a = (NormalAnnotationExpr) annotationExpr; // Must iterate over the expressions if (a.getPairs() != null) { annotationPairs = a.getPairs(); } } // Iterate over the annotation attributes, creating our parsed attributes map for (MemberValuePair p : annotationPairs) { JavaSymbolName annotationName = new JavaSymbolName(p.getName()); AnnotationAttributeValue<?> value = convert(annotationName, p.getValue()); attributes.add(value); attributeMap.put(value.getName(), value); } } private AnnotationAttributeValue<?> convert(JavaSymbolName annotationName, Expression expression) { if (annotationName == null) { annotationName = new JavaSymbolName("__ARRAY_ELEMENT__"); } if (expression instanceof AnnotationExpr) { AnnotationExpr annotationExpr = (AnnotationExpr) expression; AnnotationMetadata value = new JavaParserAnnotationMetadata(annotationExpr, compilationUnitServices); return new NestedAnnotationAttributeValue(annotationName, value); } if (expression instanceof BooleanLiteralExpr) { boolean value = ((BooleanLiteralExpr) expression).getValue(); return new BooleanAttributeValue(annotationName, value); } if (expression instanceof CharLiteralExpr) { String value = ((CharLiteralExpr) expression).getValue(); Assert.isTrue(value.length() == 1, "Expected a char expression, but instead received '" + value + "' for attribute '" + annotationName + "'"); char c = value.charAt(0); return new CharAttributeValue(annotationName, c); } if (expression instanceof LongLiteralExpr) { String value = ((LongLiteralExpr) expression).getValue(); Assert.isTrue(value.toUpperCase().endsWith("L"), "Expected long literal expression '" + value + "' to end in 'l' or 'L'"); value = value.substring(0, value.length() - 1); long l = new Long(value); return new LongAttributeValue(annotationName, l); } if (expression instanceof IntegerLiteralExpr) { String value = ((IntegerLiteralExpr) expression).getValue(); int i = new Integer(value); return new IntegerAttributeValue(annotationName, i); } if (expression instanceof DoubleLiteralExpr) { String value = ((DoubleLiteralExpr) expression).getValue(); boolean floatingPrecisionOnly = false; if (value.toUpperCase().endsWith("F")) { value = value.substring(0, value.length() - 1); floatingPrecisionOnly = true; } if (value.toUpperCase().endsWith("D")) { value = value.substring(0, value.length() - 1); } double d = new Double(value); return new DoubleAttributeValue(annotationName, d, floatingPrecisionOnly); } if (expression instanceof BinaryExpr) { String result = ""; BinaryExpr current = (BinaryExpr) expression; while (current instanceof BinaryExpr) { Assert.isInstanceOf(StringLiteralExpr.class, current.getRight()); String right = ((StringLiteralExpr) current.getRight()).getValue(); result = right + result; if (current.getLeft() instanceof StringLiteralExpr) { String left = ((StringLiteralExpr) current.getLeft()).getValue(); result = left + result; } if (current.getLeft() instanceof BinaryExpr) { current = (BinaryExpr) current.getLeft(); } else { current = null; } } return new StringAttributeValue(annotationName, result); } if (expression instanceof StringLiteralExpr) { String value = ((StringLiteralExpr) expression).getValue(); return new StringAttributeValue(annotationName, value); } if (expression instanceof FieldAccessExpr) { FieldAccessExpr field = (FieldAccessExpr) expression; String fieldName = field.getField(); // Determine the type Expression scope = field.getScope(); NameExpr nameToFind = null; if (scope instanceof FieldAccessExpr) { FieldAccessExpr fScope = (FieldAccessExpr) scope; nameToFind = JavaParserUtils.getNameExpr(fScope.toString()); } else if (scope instanceof NameExpr) { nameToFind = (NameExpr) scope; } else { throw new UnsupportedOperationException("A FieldAccessExpr for '" + field.getScope() + "' should return a NameExpr or FieldAccessExpr (was " + field.getScope().getClass().getName() + ")"); } JavaType fieldType = JavaParserUtils.getJavaType(compilationUnitServices, nameToFind, null); EnumDetails enumDetails = new EnumDetails(fieldType, new JavaSymbolName(fieldName)); return new EnumAttributeValue(annotationName, enumDetails); } if (expression instanceof NameExpr) { NameExpr field = (NameExpr) expression; String name = field.getName(); JavaType fieldType = new JavaType("unknown.Object"); // as we have no way of finding out the real type EnumDetails enumDetails = new EnumDetails(fieldType, new JavaSymbolName(name)); return new EnumAttributeValue(annotationName, enumDetails); } if (expression instanceof ClassExpr) { ClassExpr clazz = (ClassExpr) expression; Type nameToFind = clazz.getType(); JavaType javaType = JavaParserUtils.getJavaType(compilationUnitServices, nameToFind, null); return new ClassAttributeValue(annotationName, javaType); } if (expression instanceof ArrayInitializerExpr) { ArrayInitializerExpr castExp = (ArrayInitializerExpr) expression; List<AnnotationAttributeValue<?>> arrayElements = new ArrayList<AnnotationAttributeValue<?>>(); for (Expression e : castExp.getValues()) { arrayElements.add(convert(null, e)); } return new ArrayAttributeValue<AnnotationAttributeValue<?>>(annotationName, arrayElements); } throw new UnsupportedOperationException("Unable to parse annotation attribute '" + annotationName + "' due to unsupported annotation expression '" + expression.getClass().getName() + "'"); } public JavaType getAnnotationType() { return annotationType; } public AnnotationAttributeValue<?> getAttribute(JavaSymbolName attributeName) { Assert.notNull(attributeName, "Attribute name required"); return attributeMap.get(attributeName); } public List<JavaSymbolName> getAttributeNames() { List<JavaSymbolName> result = new ArrayList<JavaSymbolName>(); for (AnnotationAttributeValue<?> value : attributes) { result.add(value.getName()); } return result; } /** * Facilitates the addition of the annotation to the presented type. * * @param compilationUnitServices to use (required) * @param annotations to add to the end of (required) * @param annotation to add (required) */ public static void addAnnotationToList(CompilationUnitServices compilationUnitServices, List<AnnotationExpr> annotations, AnnotationMetadata annotation) { Assert.notNull(compilationUnitServices, "Compilation unit services required"); Assert.notNull(annotations, "Annotations required"); Assert.notNull(annotation, "Annotation metadata required"); // Create a holder for the annotation we're going to create boolean foundExisting = false; // Search for an existing annotation of this type for (AnnotationExpr candidate : annotations) { NameExpr existingName = null; if (candidate instanceof NormalAnnotationExpr) { existingName = ((NormalAnnotationExpr) candidate).getName(); } else if (candidate instanceof MarkerAnnotationExpr) { existingName = ((MarkerAnnotationExpr) candidate).getName(); } else if (candidate instanceof SingleMemberAnnotationExpr) { existingName = ((SingleMemberAnnotationExpr) candidate).getName(); } // Convert the candidate annotation type's into a JavaType JavaType javaType = JavaParserUtils.getJavaType(compilationUnitServices, existingName, null); if (annotation.getAnnotationType().equals(javaType)) { foundExisting = true; break; } } Assert.isTrue(!foundExisting, "Found an existing annotation for type '" + annotation.getAnnotationType() + "'"); // Import the annotation type, if needed NameExpr nameToUse = JavaParserUtils.importTypeIfRequired(compilationUnitServices.getEnclosingTypeName(), compilationUnitServices.getImports(), annotation.getAnnotationType()); // Create member-value pairs in accordance with Java Parser requirements List<MemberValuePair> memberValuePairs = new ArrayList<MemberValuePair>(); for (JavaSymbolName attributeName : annotation.getAttributeNames()) { AnnotationAttributeValue<?> value = annotation.getAttribute(attributeName); Assert.notNull(value, "Unable to acquire value '" + attributeName + "' from annotation"); MemberValuePair memberValuePair = convert(value); Assert.notNull(memberValuePair, "Member value pair should have been set"); memberValuePairs.add(memberValuePair); } // Create the AnnotationExpr; it varies depending on how many member-value pairs we need to present AnnotationExpr annotationExpression = null; if (memberValuePairs.size() == 0) { annotationExpression = new MarkerAnnotationExpr(nameToUse); } else if (memberValuePairs.size() == 1 && (memberValuePairs.get(0).getName() == null || "value".equals(memberValuePairs.get(0).getName()))) { Expression toUse = JavaParserUtils.importExpressionIfRequired(compilationUnitServices.getEnclosingTypeName(), compilationUnitServices.getImports(), memberValuePairs.get(0).getValue()); annotationExpression = new SingleMemberAnnotationExpr(nameToUse, toUse); } else { // We have a number of pairs being presented annotationExpression = new NormalAnnotationExpr(nameToUse, new ArrayList<MemberValuePair>()); } // Add our AnnotationExpr to the actual annotations that will eventually be flushed through to the compilation unit annotations.add(annotationExpression); // Add member-value pairs to our AnnotationExpr if (memberValuePairs != null && memberValuePairs.size() > 0) { // have to check here for cases where we need to change an existing MarkerAnnotationExpr to a NormalAnnotationExpr or SingleMemberAnnotationExpr if (annotationExpression instanceof MarkerAnnotationExpr) { MarkerAnnotationExpr mae = (MarkerAnnotationExpr) annotationExpression; annotations.remove(mae); if (memberValuePairs != null && memberValuePairs.size() == 1 && (memberValuePairs.get(0).getName() == null || "value".equals(memberValuePairs.get(0).getName()))) { Expression toUse = JavaParserUtils.importExpressionIfRequired(compilationUnitServices.getEnclosingTypeName(), compilationUnitServices.getImports(), memberValuePairs.get(0).getValue()); annotationExpression = new SingleMemberAnnotationExpr(nameToUse, toUse); annotations.add(annotationExpression); } else { // We have a number of pairs being presented annotationExpression = new NormalAnnotationExpr(nameToUse, new ArrayList<MemberValuePair>()); annotations.add(annotationExpression); } } if (annotationExpression instanceof SingleMemberAnnotationExpr) { // Potentially upgrade this expression to a NormalAnnotationExpr SingleMemberAnnotationExpr smae = (SingleMemberAnnotationExpr) annotationExpression; if (memberValuePairs.size() == 1 && memberValuePairs.get(0).getName() == null || memberValuePairs.get(0).getName().equals("value") || memberValuePairs.get(0).getName().equals("")) { // they specified only a single member-value pair, and it is the default anyway, so we need not do anything except update the value Expression toUse = JavaParserUtils.importExpressionIfRequired(compilationUnitServices.getEnclosingTypeName(), compilationUnitServices.getImports(), memberValuePairs.get(0).getValue()); smae.setMemberValue(toUse); return; } else { // There is >1 expression, or they have provided some sort of non-default value, so it's time to upgrade the expression // (whilst retaining any potentially existing expression values) Expression existingValue = smae.getMemberValue(); annotationExpression = new NormalAnnotationExpr(smae.getName(), new ArrayList<MemberValuePair>()); ((NormalAnnotationExpr) annotationExpression).getPairs().add(new MemberValuePair("value", existingValue)); } } Assert.isInstanceOf(NormalAnnotationExpr.class, annotationExpression, "Attempting to add >1 annotation member-value pair requires an existing normal annotation expression"); List<MemberValuePair> annotationPairs = ((NormalAnnotationExpr) annotationExpression).getPairs(); annotationPairs.clear(); for (MemberValuePair pair : memberValuePairs) { Expression toUse = JavaParserUtils.importExpressionIfRequired(compilationUnitServices.getEnclosingTypeName(), compilationUnitServices.getImports(), pair.getValue()); pair.setValue(toUse); annotationPairs.add(pair); } } } /** * Facilitates the removal of the annotation type indicated. * * @param compilationUnitServices to use (required) * @param annotations to remove the annotation from (required) * @param annotation to remove (required) */ public static void removeAnnotationFromList(CompilationUnitServices compilationUnitServices, List<AnnotationExpr> annotations, JavaType annotation) { Assert.notNull(compilationUnitServices, "Compilation unit services required"); Assert.notNull(annotations, "Annotations required"); Assert.notNull(annotation, "Annotation metadata required"); AnnotationExpr toRemove = null; for (AnnotationExpr candidate : annotations) { NameExpr existingName = null; if (candidate instanceof NormalAnnotationExpr) { existingName = ((NormalAnnotationExpr) candidate).getName(); } else if (candidate instanceof MarkerAnnotationExpr) { existingName = ((MarkerAnnotationExpr) candidate).getName(); } else if (candidate instanceof SingleMemberAnnotationExpr) { existingName = ((SingleMemberAnnotationExpr) candidate).getName(); } JavaType javaType = JavaParserUtils.getJavaType(compilationUnitServices, existingName, null); if (annotation.equals(javaType)) { toRemove = candidate; break; } } Assert.notNull(toRemove, "Could not find annotation for type '" + annotation.getFullyQualifiedTypeName() + "' to remove"); annotations.remove(toRemove); } @SuppressWarnings("unchecked") private static MemberValuePair convert(AnnotationAttributeValue<?> value) { if (value instanceof NestedAnnotationAttributeValue) { NestedAnnotationAttributeValue castValue = (NestedAnnotationAttributeValue) value; Assert.isInstanceOf(JavaParserAnnotationMetadata.class, castValue.getValue(), "Cannot present nested annotations unless created by this class"); JavaParserAnnotationMetadata javaParserMutableAnnotationMetadata = (JavaParserAnnotationMetadata) castValue.getValue(); // Rely on the nested instance to know its member value pairs return new MemberValuePair(value.getName().getSymbolName(), javaParserMutableAnnotationMetadata.annotationExpr); } if (value instanceof BooleanAttributeValue) { boolean castValue = ((BooleanAttributeValue) value).getValue(); BooleanLiteralExpr convertedValue = new BooleanLiteralExpr(castValue); return new MemberValuePair(value.getName().getSymbolName(), convertedValue); } if (value instanceof CharAttributeValue) { char castValue = ((CharAttributeValue) value).getValue(); CharLiteralExpr convertedValue = new CharLiteralExpr(new String(new char[] { castValue })); return new MemberValuePair(value.getName().getSymbolName(), convertedValue); } if (value instanceof LongAttributeValue) { Long castValue = ((LongAttributeValue) value).getValue(); LongLiteralExpr convertedValue = new LongLiteralExpr(castValue.toString() + "L"); return new MemberValuePair(value.getName().getSymbolName(), convertedValue); } if (value instanceof IntegerAttributeValue) { Integer castValue = ((IntegerAttributeValue) value).getValue(); IntegerLiteralExpr convertedValue = new IntegerLiteralExpr(castValue.toString()); return new MemberValuePair(value.getName().getSymbolName(), convertedValue); } if (value instanceof DoubleAttributeValue) { DoubleAttributeValue doubleAttributeValue = (DoubleAttributeValue) value; Double castValue = doubleAttributeValue.getValue(); DoubleLiteralExpr convertedValue; if (doubleAttributeValue.isFloatingPrecisionOnly()) { convertedValue = new DoubleLiteralExpr(castValue.toString() + "F"); } else { convertedValue = new DoubleLiteralExpr(castValue.toString() + "D"); } return new MemberValuePair(value.getName().getSymbolName(), convertedValue); } if (value instanceof StringAttributeValue) { String castValue = ((StringAttributeValue) value).getValue(); StringLiteralExpr convertedValue = new StringLiteralExpr(castValue.toString()); return new MemberValuePair(value.getName().getSymbolName(), convertedValue); } if (value instanceof EnumAttributeValue) { EnumDetails castValue = ((EnumAttributeValue) value).getValue(); // this isn't as elegant as it could be (ie loss of type parameters), but it will do for now FieldAccessExpr convertedValue = new FieldAccessExpr(JavaParserUtils.getNameExpr(castValue.getType().getFullyQualifiedTypeName()), castValue.getField().getSymbolName()); return new MemberValuePair(value.getName().getSymbolName(), convertedValue); } if (value instanceof ClassAttributeValue) { JavaType castValue = ((ClassAttributeValue) value).getValue(); // this doesn't preserve type parameters NameExpr nameExpr = JavaParserUtils.getNameExpr(castValue.getFullyQualifiedTypeName()); ClassExpr convertedValue = new ClassExpr(JavaParserUtils.getReferenceType(nameExpr)); return new MemberValuePair(value.getName().getSymbolName(), convertedValue); } if (value instanceof ArrayAttributeValue) { ArrayAttributeValue<AnnotationAttributeValue<?>> castValue = (ArrayAttributeValue<AnnotationAttributeValue<?>>) value; List<Expression> arrayElements = new ArrayList<Expression>(); for (AnnotationAttributeValue<?> v : castValue.getValue()) { arrayElements.add(convert(v).getValue()); } return new MemberValuePair(value.getName().getSymbolName(), new ArrayInitializerExpr(arrayElements)); } throw new UnsupportedOperationException("Unsupported attribute value '" + value.getName() + "' of type '" + value.getClass().getName() + "'"); } public String toString() { ToStringCreator tsc = new ToStringCreator(this); tsc.append("annotationType", annotationType); tsc.append("attributes", attributes); return tsc.toString(); } }
package com.continuuity.data.runtime.main; import com.continuuity.app.guice.AppFabricServiceRuntimeModule; import com.continuuity.app.guice.ProgramRunnerRuntimeModule; import com.continuuity.common.conf.CConfiguration; import com.continuuity.common.guice.ConfigModule; import com.continuuity.common.guice.DiscoveryRuntimeModule; import com.continuuity.common.guice.IOModule; import com.continuuity.common.guice.KafkaClientModule; import com.continuuity.common.guice.LocationRuntimeModule; import com.continuuity.common.guice.TwillModule; import com.continuuity.common.guice.ZKClientModule; import com.continuuity.common.metrics.MetricsCollectionService; import com.continuuity.common.runtime.DaemonMain; import com.continuuity.common.zookeeper.election.ElectionHandler; import com.continuuity.common.zookeeper.election.LeaderElection; import com.continuuity.data.runtime.DataFabricModules; import com.continuuity.data.security.HBaseSecureStoreUpdater; import com.continuuity.data.security.HBaseTokenUtils; import com.continuuity.data2.util.hbase.HBaseTableUtilFactory; import com.continuuity.gateway.auth.AuthModule; import com.continuuity.internal.app.services.AppFabricServer; import com.continuuity.metrics.guice.MetricsClientRuntimeModule; import com.continuuity.test.internal.TempFolder; import com.google.common.base.Charsets; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.common.io.Files; import com.google.common.util.concurrent.MoreExecutors; import com.google.common.util.concurrent.Service; import com.google.inject.Guice; import com.google.inject.Injector; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.security.User; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.security.Credentials; import org.apache.twill.api.TwillApplication; import org.apache.twill.api.TwillController; import org.apache.twill.api.TwillPreparer; import org.apache.twill.api.TwillRunner; import org.apache.twill.api.TwillRunnerService; import org.apache.twill.api.logging.PrinterLogHandler; import org.apache.twill.common.ServiceListenerAdapter; import org.apache.twill.yarn.YarnSecureStore; import org.apache.twill.zookeeper.ZKClientService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.Writer; import java.net.URI; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; /** * Driver class for starting all reactor master services. * AppFabricHttpService * TwillRunnables: MetricsProcessor, MetricsHttp, LogSaver, TransactionService, StreamHandler. */ public class ReactorServiceMain extends DaemonMain { private static final Logger LOG = LoggerFactory.getLogger(ReactorServiceMain.class); private static final long MAX_BACKOFF_TIME_MS = TimeUnit.MILLISECONDS.convert(10, TimeUnit.MINUTES); private static final long SUCCESSFUL_RUN_DURATON_MS = TimeUnit.MILLISECONDS.convert(20, TimeUnit.MINUTES); public ReactorServiceMain(CConfiguration cConf, Configuration hConf) { this.cConf = cConf; this.hConf = hConf; } private boolean stopFlag = false; protected final CConfiguration cConf; protected final Configuration hConf; protected final Map<String, Configuration> extraConfs = Maps.newHashMap(); private final Set<URI> resources = Sets.newHashSet(); private final AtomicBoolean isLeader = new AtomicBoolean(false); private Injector baseInjector; private ZKClientService zkClientService; private LeaderElection leaderElection; private volatile TwillRunnerService twillRunnerService; private volatile TwillController twillController; private AppFabricServer appFabricServer; private MetricsCollectionService metricsCollectionService; private String serviceName; private TwillApplication twillApplication; private long lastRunTimeMs = System.currentTimeMillis(); private int currentRun = 0; public static void main(final String[] args) throws Exception { LOG.info("Starting Reactor Service Main..."); new ReactorServiceMain(CConfiguration.create(), HBaseConfiguration.create()).doMain(args); } @Override public void init(String[] args) { initHiveService(); twillApplication = createTwillApplication(); if (twillApplication == null) { throw new IllegalArgumentException("TwillApplication cannot be null"); } serviceName = twillApplication.configure().getName(); baseInjector = Guice.createInjector( new ConfigModule(cConf, hConf), new ZKClientModule(), new LocationRuntimeModule().getDistributedModules(), new IOModule(), new AuthModule(), new KafkaClientModule(), new TwillModule(), new DiscoveryRuntimeModule().getDistributedModules(), new AppFabricServiceRuntimeModule().getDistributedModules(), new ProgramRunnerRuntimeModule().getDistributedModules(), new DataFabricModules(cConf, hConf).getDistributedModules(), new MetricsClientRuntimeModule().getDistributedModules() ); // Initialize ZK client zkClientService = baseInjector.getInstance(ZKClientService.class); } @Override public void start() { zkClientService.startAndWait(); leaderElection = new LeaderElection(zkClientService, "/election/" + serviceName, new ElectionHandler() { @Override public void leader() { LOG.info("Became leader."); Injector injector = baseInjector.createChildInjector(); appFabricServer = injector.getInstance(AppFabricServer.class); appFabricServer.startAndWait(); twillRunnerService = injector.getInstance(TwillRunnerService.class); twillRunnerService.startAndWait(); scheduleSecureStoreUpdate(twillRunnerService); runTwillApps(); isLeader.set(true); } @Override public void follower() { LOG.info("Became follower."); if (twillRunnerService != null) { twillRunnerService.stopAndWait(); } if (appFabricServer != null) { appFabricServer.stopAndWait(); } isLeader.set(false); } }); } @Override public void stop() { LOG.info("Stopping {}", serviceName); stopFlag = true; if (isLeader.get() && twillController != null) { twillController.stopAndWait(); } leaderElection.cancel(); zkClientService.stopAndWait(); } @Override public void destroy() { } private void initHiveService() { HiveConf hiveConf = new HiveConf(); Configuration newConf = new Configuration(); newConf.clear(); newConf.set("hive.metastore.uris", hiveConf.get("hive.metastore.uris")); // Port will be set once in the yarn container newConf.set("hive.server2.thrift.port", "0"); newConf.set("mapreduce.framework.name", "yarn"); addExtraConf("hive-site.xml", newConf); } private void addExtraConf(String confName, Configuration conf) { extraConfs.put(confName, conf); } private void addResource(URI uri) { resources.add(uri); } private TwillApplication createTwillApplication() { try { ImmutableMap.Builder<String, File> extraConfFiles = ImmutableMap.builder(); for (Map.Entry<String, Configuration> extraConfEntry : extraConfs.entrySet()) { File conf = getSavedExtraConf(extraConfEntry.getKey(), extraConfEntry.getValue()); extraConfFiles.put(extraConfEntry.getKey(), conf); addResource(conf.toURI()); } return new ReactorTwillApplication(cConf, getSavedCConf(), getSavedHConf(), extraConfFiles.build()); } catch (Exception e) { throw Throwables.propagate(e); } } private void scheduleSecureStoreUpdate(TwillRunner twillRunner) { if (User.isHBaseSecurityEnabled(hConf)) { HBaseSecureStoreUpdater updater = new HBaseSecureStoreUpdater(hConf); twillRunner.scheduleSecureStoreUpdate(updater, 30000L, updater.getUpdateInterval(), TimeUnit.MILLISECONDS); } } private TwillPreparer prepare(TwillPreparer preparer) { return preparer.withDependencies(new HBaseTableUtilFactory().get().getClass()) .addSecureStore(YarnSecureStore.create(HBaseTokenUtils.obtainToken(hConf, new Credentials()))); } private void runTwillApps() { // If service is already running, return handle to that instance Iterable<TwillController> twillControllers = lookupService(); Iterator<TwillController> iterator = twillControllers.iterator(); if (iterator.hasNext()) { LOG.info("{} application is already running", serviceName); twillController = iterator.next(); if (iterator.hasNext()) { LOG.warn("Found more than one instance of {} running. Stopping the others...", serviceName); for (; iterator.hasNext(); ) { TwillController controller = iterator.next(); LOG.warn("Stopping one extra instance of {}", serviceName); controller.stopAndWait(); } LOG.warn("Done stopping extra instances of {}", serviceName); } } else { LOG.info("Starting {} application", serviceName); TwillPreparer twillPreparer = getPreparer(); twillController = twillPreparer.start(); twillController.addListener(new ServiceListenerAdapter() { @Override public void failed(Service.State from, Throwable failure) { LOG.error("{} failed with exception... restarting with back-off.", serviceName, failure); backOffRun(); } @Override public void terminated(Service.State from) { LOG.warn("{} got terminated... restarting with back-off", serviceName); backOffRun(); } }, MoreExecutors.sameThreadExecutor()); } } private File getSavedHConf() throws IOException { File hConfFile = saveConf(hConf, File.createTempFile("hConf", ".xml")); hConfFile.deleteOnExit(); return hConfFile; } private File getSavedCConf() throws IOException { File cConfFile = saveCConf(cConf, File.createTempFile("cConf", ".xml")); cConfFile.deleteOnExit(); return cConfFile; } private File getSavedExtraConf(String confName, Configuration conf) throws IOException { TempFolder tempFolder = new TempFolder(); File tFolder = tempFolder.newFolder("saved_confs"); return saveConf(conf, new File(tFolder, confName)); } /** * Wait for sometime while looking up service in twill. */ private Iterable<TwillController> lookupService() { int count = 100; Iterable<TwillController> iterable = twillRunnerService.lookup(serviceName); try { for (int i = 0; i < count; ++i) { if (iterable.iterator().hasNext()) { return iterable; } TimeUnit.MILLISECONDS.sleep(20); } } catch (InterruptedException e) { LOG.warn("Got interrupted exception: ", e); Thread.currentThread().interrupt(); } return iterable; } private TwillPreparer getPreparer() { return prepare(twillRunnerService.prepare(twillApplication) .addLogHandler(new PrinterLogHandler(new PrintWriter(System.out))).withResources(resources) ); } private void backOffRun() { if (stopFlag) { LOG.warn("Not starting a new run when stopFlag is true"); return; } if (System.currentTimeMillis() - lastRunTimeMs > SUCCESSFUL_RUN_DURATON_MS) { currentRun = 0; } try { long sleepMs = Math.min(500 * (long) Math.pow(2, currentRun), MAX_BACKOFF_TIME_MS); LOG.info("Current restart run = {}. Backing off for {} ms...", currentRun, sleepMs); TimeUnit.MILLISECONDS.sleep(sleepMs); } catch (InterruptedException e) { LOG.warn("Got interrupted exception: ", e); Thread.currentThread().interrupt(); } runTwillApps(); ++currentRun; lastRunTimeMs = System.currentTimeMillis(); } private static File saveConf(Configuration conf, File file) throws IOException { Writer writer = Files.newWriter(file, Charsets.UTF_8); try { conf.writeXml(writer); } finally { writer.close(); } return file; } private File saveCConf(CConfiguration conf, File file) throws IOException { Writer writer = Files.newWriter(file, Charsets.UTF_8); try { conf.writeXml(writer); } finally { writer.close(); } return file; } }
package org.wildfly.clustering.marshalling.spi.util; import java.util.Collection; import java.util.function.Function; import org.wildfly.clustering.marshalling.spi.ObjectExternalizer; /** * Externalizer for singleton collections. * @author Paul Ferraro */ public class SingletonCollectionExternalizer<T extends Collection<Object>> extends ObjectExternalizer<T> { @SuppressWarnings("unchecked") public SingletonCollectionExternalizer(Function<Object, T> factory) { super((Class<T>) factory.apply(null).getClass(), factory, new Accessor<>()); } public static class Accessor<T extends Collection<Object>> implements Function<T, Object> { @Override public Object apply(T collection) { return collection.iterator().next(); } } }
package i5.las2peer.services.ocd.graphs; import i5.las2peer.services.ocd.algorithms.BinarySearchRandomWalkLabelPropagationAlgorithm; import i5.las2peer.services.ocd.algorithms.ClizzAlgorithm; import i5.las2peer.services.ocd.algorithms.CostFunctionOptimizationClusteringAlgorithm; import i5.las2peer.services.ocd.algorithms.EvolutionaryAlgorithmBasedOnSimilarity; import i5.las2peer.services.ocd.algorithms.ExtendedSpeakerListenerLabelPropagationAlgorithm; import i5.las2peer.services.ocd.algorithms.LinkCommunitiesAlgorithm; import i5.las2peer.services.ocd.algorithms.MergingOfOverlappingCommunitiesAlgorithm; import i5.las2peer.services.ocd.algorithms.NISEAlgorithm; import i5.las2peer.services.ocd.algorithms.OcdAlgorithm; import i5.las2peer.services.ocd.algorithms.RandomWalkLabelPropagationAlgorithm; import i5.las2peer.services.ocd.algorithms.SignedDMIDAlgorithm; import i5.las2peer.services.ocd.algorithms.SignedProbabilisticMixtureAlgorithm; import i5.las2peer.services.ocd.algorithms.SpeakerListenerLabelPropagationAlgorithm; import i5.las2peer.services.ocd.algorithms.SskAlgorithm; import i5.las2peer.services.ocd.algorithms.WeightedLinkCommunitiesAlgorithm; import i5.las2peer.services.ocd.algorithms.WordClusteringRefinementAlgorithm; import i5.las2peer.services.ocd.algorithms.LocalSpectralClusteringAlgorithm; import i5.las2peer.services.ocd.algorithms.AntColonyOptimizationAlgorithm; import i5.las2peer.services.ocd.algorithms.LouvainAlgorithm; import i5.las2peer.services.ocd.algorithms.DetectingOverlappingCommunitiesAlgorithm; import i5.las2peer.services.ocd.benchmarks.GroundTruthBenchmark; import i5.las2peer.services.ocd.benchmarks.LfrBenchmark; import i5.las2peer.services.ocd.benchmarks.SignedLfrBenchmark; import i5.las2peer.services.ocd.utils.EnumDisplayNames; import i5.las2peer.services.ocd.benchmarks.NewmanBenchmark; import i5.las2peer.services.ocd.algorithms.FuzzyCMeansSpectralClusteringAlgorithm; import i5.las2peer.services.ocd.algorithms.WeakCliquePercolationMethodAlgorithm; import java.security.InvalidParameterException; import java.util.Locale; /** * Cover creation method registry. Contains algorithms, ground truth benchmarks and abstract types. * Used for factory instantiation, persistence or other context. * @author Sebastian * */ public enum CoverCreationType implements EnumDisplayNames { /* * Each enum constant is instantiated with a corresponding CoverCreationMethod class object (typically a concrete OcdAlgorithm or GroundTruthBenchmark subclass) and a UNIQUE id. * Abstract types that do not correspond to any algorithm are instantiated with the CoverCreationMethod interface itself. * Once the framework is in use ids must not be changed to avoid corrupting the persisted data. */ /** * Abstract type usable e.g. for importing covers that were calculated externally by other algorithms. * Cannot be used for algorithm instantiation. */ UNDEFINED ("Undefined", CoverCreationMethod.class, 0), /** * Abstract type mainly intended for importing ground truth covers. * Cannot be used for algorithm instantiation. */ GROUND_TRUTH ("Ground Truth", CoverCreationMethod.class, 1), /** * Type corresponding to the RandomWalkLabelPropagationAlgorithm. */ RANDOM_WALK_LABEL_PROPAGATION_ALGORITHM ("Random Walk Label Propagation Algorithm", RandomWalkLabelPropagationAlgorithm.class, 2), /** * Type corresponding to the SpeakerListenerLabelPropagationAlgorithm. */ SPEAKER_LISTENER_LABEL_PROPAGATION_ALGORITHM ("Speaker Listener Label Propagation Algorithm", SpeakerListenerLabelPropagationAlgorithm.class, 3), /** * Type corresponding to the ExtendedSpeakerListenerLabelPropagationAlgorithm. */ EXTENDED_SPEAKER_LISTENER_LABEL_PROPAGATION_ALGORITHM("Extended Speaker Listener Label Propagation Algorithm", ExtendedSpeakerListenerLabelPropagationAlgorithm.class, 4), /** * Type corresponding to the SskAlgorithm. */ SSK_ALGORITHM ("SSK Algorithm", SskAlgorithm.class, 5), /** * Type corresponding to the LinkCommunitiesAlgorithm. */ LINK_COMMUNITIES_ALGORITHM ("Link Communities Algorithm", LinkCommunitiesAlgorithm.class, 6), /** * Type corresponding to the WeightedLinkCommunitiesAlgorithm. */ WEIGHTED_LINK_COMMUNITIES_ALGORITHM ("Weighted Link Communities Algorithm", WeightedLinkCommunitiesAlgorithm.class, 7), /** * Type corresponding to the ClizzAlgorithm. */ CLIZZ_ALGORITHM ("CliZZ Algorithm", ClizzAlgorithm.class, 8), /** * Type corresponding to the MergingOfOverlappingCommunitiesAlgorithm. */ MERGING_OF_OVERLAPPING_COMMUNITIES_ALGORITHM("Merging Of Overlapping Communities Algorithm", MergingOfOverlappingCommunitiesAlgorithm.class, 9), /** * Type corresponding to the BinarySearchRandomWalkLabelPropagationAlgorithm. */ BINARY_SEARCH_RANDOM_WALK_LABEL_PROPAGATION_ALGORITHM("Binary Search Random Walk Label Propagation Algorithm", BinarySearchRandomWalkLabelPropagationAlgorithm.class, 10), /** * Type corresponding to the LfrBenchmark, which is a ground truth benchmark. * Cannot be used for algorithm instantiation. */ LFR("LFR Benchmark", LfrBenchmark.class, 11), /** * Type corresponding to the NewmanBenchmark, which is a ground truth benchmark. * Cannot be used for algorithm instantiation. */ NEWMAN("Newman Benchmark", NewmanBenchmark.class, 12), /** * Type corresponding to the LfrBenchmark, which is a ground truth benchmark. * Cannot be used for algorithm instantiation. */ SIGNED_LFR("Signed LFR Benchmark", SignedLfrBenchmark.class, 13), COST_FUNC_OPT_CLUSTERING_ALGORITHM("Cost Function Optimization Clustering Algorithm", CostFunctionOptimizationClusteringAlgorithm.class, 14), /** * Type corresponding to the SignedDMIDAlgorithm. */ SIGNED_DMID_ALGORITHM("Signed DMID Algorithm", SignedDMIDAlgorithm.class, 15), /** * Type corresponding to the EvolutionaryAlgorithmBasedOnSimilarity. */ EVOLUTIONARY_ALGORITHM_BASED_ON_SIMILARITY("Evolutionary Algorithm Based On Similarity", EvolutionaryAlgorithmBasedOnSimilarity.class,16), /** * Type corresponding to the SignedProbabilisticMixtureAlgorithm. */ SIGNED_PROBABILISTIC_MIXTURE_ALGORITHM("Signed Probabilistic Mixture Algorithm", SignedProbabilisticMixtureAlgorithm.class,17), // /** // * Type corresponding to the SignedDMIDExtendedAlgorithm. // */ // SIGNED_DMID_EXTENDED_ALGORITHM(SignedDMIDExtendedAlgorithm.class,17); /** * Type corresponding to the wordclustering algorithm with refinement. */ WORD_CLUSTERING_REF_ALGORITHM("Word Clustering Refinement Algorithm", WordClusteringRefinementAlgorithm.class, 18), /** * Type corresponding to the AntColonyOptimization algorithm */ ANT_COLONY_OPTIMIZATION("Ant Colony Optimization Algorithm", AntColonyOptimizationAlgorithm.class, 19), /** * Type corresponding to the LocalSpectralClustering algorithm. */ LOCAL_SPECTRAL_CLUSTERING_ALGORITHM("Local Spectral Clustering Algorithm", LocalSpectralClusteringAlgorithm.class, 20), /** * Type corresponding to the Louvain method algorithm. */ LOUVAIN_ALGORITHM("Louvain Algorithm", LouvainAlgorithm.class, 21), /** * Type corresponding to the DetectingOverlappingCommunities Algorithm. */ DETECTING_OVERLAPPING_COMMUNITIES_ALGORITHM("Detecting Overlapping Communities Algorithm", DetectingOverlappingCommunitiesAlgorithm.class, 22), /** * Type corresponding to the NISE Algorithm. */ NISE_ALGORITHM("Neighborhood-Inflated Seed Expansion Algorithm", NISEAlgorithm.class, 23), /** * Type corresponding to the FuzzyCMeansSpectralClustering Algorithm. */ FUZZY_C_MEANS_SPECTRAL_CLUSTERING_ALGORITHM("Fuzzy C Means Spectral Clustering Algorithm", FuzzyCMeansSpectralClusteringAlgorithm.class, 24), /** * Type corresponding to the WeakCliquePercolationMethodAlgorithm Algorithm. */ WEAK_CLIQUE_PERCOLATION_METHOD_ALGORITHM("Weak Clique Percolation Method Algorithm", WeakCliquePercolationMethodAlgorithm.class, 25); /** * The class corresponding to the type, typically a concrete OcdAlgorithm or GroundTruthBenchmark subclass. * Abstract types correspond to the CoverCreationMethod interface itself. */ private final Class<? extends CoverCreationMethod> creationMethodClass; /** * For persistence and other purposes. */ private final int id; /** * A display name for web frontends and more */ private final String displayName; /** * Creates a new instance. * @param displayName Defines the displayName attribute * @param creationMethodClass Defines the creationMethodClass attribute. * @param id Defines the id attribute. */ private CoverCreationType(String displayName, Class<? extends CoverCreationMethod> creationMethodClass, int id) { this.displayName = displayName; this.creationMethodClass = creationMethodClass; this.id = id; } /** * Returns the CoverCreationMethod subclass corresponding to the type. * @return The corresponding class. */ public Class<? extends CoverCreationMethod> getCreationMethodClass() { return this.creationMethodClass; } /** * Returns the unique id of the type. * @return The id. */ public int getId() { return id; } /** * Returns the display name of the type. * @return The name. */ public String getDisplayName() { return displayName; } /** * Returns the type corresponding to an id. * @param id The id. * @return The corresponding type. */ public static CoverCreationType lookupType(int id) { for (CoverCreationType type : CoverCreationType.values()) { if (id == type.getId()) { return type; } } throw new InvalidParameterException(); } /** * States whether the corresponding creation method class is actually an OcdAlgorithm. * @return TRUE if the class is an OcdAlgorithm, otherwise FALSE. */ public boolean correspondsAlgorithm() { if(OcdAlgorithm.class.isAssignableFrom(this.getCreationMethodClass())) { return true; } else { return false; } } /** * States whether the corresponding CoverCreationMethod class is a ground truth benchmark. * @return TRUE if the class is a ground truth benchmark, otherwise FALSE. */ public boolean correspondsGroundTruthBenchmark() { if(GroundTruthBenchmark.class.isAssignableFrom(this.getCreationMethodClass())) { return true; } else { return false; } } /** * Returns the name of the type written in lower case letters and with any underscores replaced by space characters. */ @Override public String toString() { String name = name(); name = name.replace('_', ' '); name = name.toLowerCase(Locale.ROOT); return name; } }
package org.eclipse.rdf4j.query.algebra.evaluation.iterator; import java.util.Iterator; import java.util.List; import org.eclipse.rdf4j.common.iteration.CloseableIteration; import org.eclipse.rdf4j.common.iteration.LookAheadIteration; import org.eclipse.rdf4j.query.BindingSet; import org.eclipse.rdf4j.query.QueryEvaluationException; import org.eclipse.rdf4j.query.algebra.evaluation.QueryBindingSet; /** * Iteration which forms the cross product of a list of materialized input bindings with each result obtained * from the inner iteration. Example: <source> inputBindings := {b1, b2, ...} resultIteration := {r1, r2, ...} * getNextElement() returns (r1,b1), (r1, b2), ..., (r2, b1), (r2, b2), ... i.e. compute the cross product per * result binding </source> * * @author Andreas Schwarte */ public class CrossProductIteration extends LookAheadIteration<BindingSet, QueryEvaluationException> { protected final List<BindingSet> inputBindings; protected final CloseableIteration<BindingSet, QueryEvaluationException> resultIteration; protected Iterator<BindingSet> inputBindingsIterator = null; protected BindingSet currentInputBinding = null; public CrossProductIteration(CloseableIteration<BindingSet, QueryEvaluationException> resultIteration, List<BindingSet> inputBindings) { super(); this.resultIteration = resultIteration; this.inputBindings = inputBindings; } @Override protected BindingSet getNextElement() throws QueryEvaluationException { if (currentInputBinding == null) { inputBindingsIterator = inputBindings.iterator(); if (resultIteration.hasNext()) currentInputBinding = resultIteration.next(); else return null; // no more results } if (inputBindingsIterator.hasNext()) { BindingSet next = inputBindingsIterator.next(); QueryBindingSet res = new QueryBindingSet(next.size() + currentInputBinding.size()); res.addAll(next); res.addAll(currentInputBinding); if (!inputBindingsIterator.hasNext()) currentInputBinding = null; return res; } return null; } @Override protected void handleClose() throws QueryEvaluationException { super.handleClose(); resultIteration.close(); } }
package com.rocketchat.common.listener; import java.util.List; public interface SimpleListCallback<T> extends Callback { void onSuccess(List<T> list); }
package org.lilycms.rowlog.impl.test; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.client.HTableInterface; import org.apache.hadoop.hbase.util.Bytes; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; import org.lilycms.rowlog.api.RowLog; import org.lilycms.rowlog.api.RowLogMessage; import org.lilycms.rowlog.api.RowLogProcessor; import org.lilycms.rowlog.api.RowLogShard; import org.lilycms.rowlog.api.RowLogSubscription; import org.lilycms.rowlog.impl.RowLogConfigurationManagerImpl; import org.lilycms.rowlog.impl.RowLogImpl; import org.lilycms.rowlog.impl.RowLogProcessorImpl; import org.lilycms.rowlog.impl.RowLogShardImpl; import org.lilycms.testfw.HBaseProxy; import org.lilycms.testfw.TestHelper; import org.lilycms.util.io.Closer; import org.lilycms.util.zookeeper.ZkUtil; import org.lilycms.util.zookeeper.ZooKeeperItf; public abstract class AbstractRowLogEndToEndTest { protected final static HBaseProxy HBASE_PROXY = new HBaseProxy(); protected static RowLog rowLog; protected static RowLogShard shard; protected static RowLogProcessor processor; protected static RowLogConfigurationManagerImpl rowLogConfigurationManager; protected String subscriptionId = "Subscription1"; protected ValidationMessageListener validationListener; private static Configuration configuration; protected static ZooKeeperItf zooKeeper; @Rule public TestName name = new TestName(); @BeforeClass public static void setUpBeforeClass() throws Exception { TestHelper.setupLogging(); HBASE_PROXY.start(); configuration = HBASE_PROXY.getConf(); HTableInterface rowTable = RowLogTableUtil.getRowTable(configuration); // Using a large ZooKeeper timeout, seems to help the build to succeed on Hudson (not sure if this is // the problem or the sympton, but HBase's Sleeper thread also reports it slept to long, so it appears // to be JVM-level). zooKeeper = ZkUtil.connect(HBASE_PROXY.getZkConnectString(), 120000); rowLogConfigurationManager = new RowLogConfigurationManagerImpl(zooKeeper); rowLog = new RowLogImpl("EndToEndRowLog", rowTable, RowLogTableUtil.PAYLOAD_COLUMN_FAMILY, RowLogTableUtil.EXECUTIONSTATE_COLUMN_FAMILY, 60000L, true, rowLogConfigurationManager); shard = new RowLogShardImpl("EndToEndShard", configuration, rowLog, 100); rowLog.registerShard(shard); processor = new RowLogProcessorImpl(rowLog, rowLogConfigurationManager); } @AfterClass public static void tearDownAfterClass() throws Exception { Closer.close(rowLogConfigurationManager); Closer.close(zooKeeper); HBASE_PROXY.stop(); } @Test(timeout=150000) public void testSingleMessage() throws Exception { RowLogMessage message = rowLog.putMessage(Bytes.toBytes("row1"), null, null, null); validationListener.expectMessage(message); validationListener.expectMessages(1); processor.start(); validationListener.waitUntilMessagesConsumed(120000); processor.stop(); validationListener.validate(); } @Test(timeout=150000) public void testSingleMessageProcessorStartsFirst() throws Exception { processor.start(); System.out.println(">>RowLogEndToEndTest#"+name.getMethodName()+": processor started"); RowLogMessage message = rowLog.putMessage(Bytes.toBytes("row2"), null, null, null); validationListener.expectMessage(message); validationListener.expectMessages(1); System.out.println(">>RowLogEndToEndTest#"+name.getMethodName()+": waiting for message to be processed"); validationListener.waitUntilMessagesConsumed(120000); System.out.println(">>RowLogEndToEndTest#"+name.getMethodName()+": message processed"); processor.stop(); System.out.println(">>RowLogEndToEndTest#"+name.getMethodName()+": processor stopped"); validationListener.validate(); } @Test(timeout=150000) public void testMultipleMessagesSameRow() throws Exception { RowLogMessage message; validationListener.expectMessages(10); for (int i = 0; i < 10; i++) { byte[] rowKey = Bytes.toBytes("row3"); message = rowLog.putMessage(rowKey, null, "aPayload".getBytes(), null); validationListener.expectMessage(message); } processor.start(); validationListener.waitUntilMessagesConsumed(120000); processor.stop(); validationListener.validate(); } @Test(timeout=150000) public void testMultipleMessagesMultipleRows() throws Exception { RowLogMessage message; validationListener.expectMessages(25); for (long seqnr = 0L; seqnr < 5; seqnr++) { for (int rownr = 10; rownr < 15; rownr++) { byte[] data = Bytes.toBytes(rownr); data = Bytes.add(data, Bytes.toBytes(seqnr)); message = rowLog.putMessage(Bytes.toBytes("row" + rownr), data, null, null); validationListener.expectMessage(message); } } processor.start(); validationListener.waitUntilMessagesConsumed(120000); processor.stop(); validationListener.validate(); } @Test(timeout=150000) public void testProblematicMessage() throws Exception { RowLogMessage message = rowLog.putMessage(Bytes.toBytes("row1"), null, null, null); validationListener.problematicMessages.add(message); validationListener.expectMessage(message, 3); validationListener.expectMessages(3); processor.start(); validationListener.waitUntilMessagesConsumed(120000); processor.stop(); Assert.assertTrue(rowLog.isProblematic(message, subscriptionId)); validationListener.validate(); } protected void waitForSubscription(String subscriptionId) throws InterruptedException { boolean subscriptionKnown = false; long waitUntil = System.currentTimeMillis() + 10000; while (!subscriptionKnown && System.currentTimeMillis() < waitUntil) { for (RowLogSubscription subscription : rowLog.getSubscriptions()) { if (subscriptionId.equals(subscription.getId())) { subscriptionKnown = true; break; } } Thread.sleep(10); } Assert.assertTrue("Subscription <" + subscriptionId +"> not known to rowlog within reasonable time <10s>", subscriptionKnown); } }
package org.deviceconnect.android.libmedia.streaming.muxer; import android.media.MediaCodec; import android.media.MediaFormat; import android.util.Log; import net.ossrs.rtmp.ConnectCheckerRtmp; import net.ossrs.rtmp.SrsFlvMuxer; import org.deviceconnect.android.libmedia.BuildConfig; import org.deviceconnect.android.libmedia.streaming.IMediaMuxer; import org.deviceconnect.android.libmedia.streaming.MediaEncoderException; import org.deviceconnect.android.libmedia.streaming.audio.AudioQuality; import org.deviceconnect.android.libmedia.streaming.video.VideoQuality; import java.nio.ByteBuffer; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; /** * RTMP URL . */ public class RtmpMuxer implements IMediaMuxer { private static final boolean DEBUG = BuildConfig.DEBUG; private static final String TAG = "RTMP-MUXER"; /** * RMTP . */ private SrsFlvMuxer mSrsFlvMuxer; /** * URL. */ private String mUrl; private OnEventListener mOnEventListener; /** * . * @param url URL */ public RtmpMuxer(String url) { if (url == null) { throw new IllegalArgumentException("url is null."); } mUrl = url; } /** * . * * @param listener */ public void setOnEventListener(OnEventListener listener) { mOnEventListener = listener; } /** * RTMP. * * @return RTMP truefalse */ private boolean isConnected() { return mSrsFlvMuxer != null && mSrsFlvMuxer.isConnected(); } @Override public boolean onPrepare(VideoQuality videoQuality, AudioQuality audioQuality) { if (DEBUG) { Log.e(TAG, "RtmpMuxer::onPrepare"); } final CountDownLatch latch = new CountDownLatch(1); final AtomicBoolean result = new AtomicBoolean(false); ConnectCheckerRtmpAdapter rtmpAdapter = new ConnectCheckerRtmpAdapter() { @Override public void onConnectionSuccessRtmp() { super.onConnectionSuccessRtmp(); result.set(true); latch.countDown(); } @Override public void onConnectionFailedRtmp(String reason) { super.onConnectionFailedRtmp(reason); result.set(false); latch.countDown(); if (mOnEventListener != null) { mOnEventListener.onError(new MediaEncoderException(reason)); } } @Override public void onAuthErrorRtmp() { super.onAuthErrorRtmp(); result.set(false); latch.countDown(); } }; mSrsFlvMuxer = new SrsFlvMuxer(rtmpAdapter); mSrsFlvMuxer.setLogs(false); if (videoQuality != null) { mSrsFlvMuxer.setVideoResolution(videoQuality.getVideoWidth(), videoQuality.getVideoHeight()); } if (audioQuality != null) { mSrsFlvMuxer.setSampleRate(audioQuality.getSamplingRate()); mSrsFlvMuxer.setIsStereo(audioQuality.getChannelCount() == 2); } mSrsFlvMuxer.start(mUrl); // RTMP try { latch.await(15, TimeUnit.SECONDS); } catch (InterruptedException e) { // ignore. } if (result.get() && mOnEventListener != null) { mOnEventListener.onConnected(); } return result.get(); } @Override public void onVideoFormatChanged(MediaFormat newFormat) { mSrsFlvMuxer.setSpsPPs(newFormat.getByteBuffer("csd-0"), newFormat.getByteBuffer("csd-1")); try { int width = newFormat.getInteger(MediaFormat.KEY_WIDTH); int height = newFormat.getInteger(MediaFormat.KEY_HEIGHT); mSrsFlvMuxer.setVideoResolution(width, height); } catch (Exception e) { // ignore. } } @Override public synchronized void onWriteVideoData(ByteBuffer encodedData, MediaCodec.BufferInfo bufferInfo) { if (isConnected()) { mSrsFlvMuxer.sendVideo(encodedData, bufferInfo); } } @Override public void onAudioFormatChanged(MediaFormat newFormat) { } @Override public synchronized void onWriteAudioData(ByteBuffer encodedData, MediaCodec.BufferInfo bufferInfo) { if (isConnected()) { mSrsFlvMuxer.sendAudio(encodedData, bufferInfo); } } @Override public void onReleased() { if (mSrsFlvMuxer != null) { mSrsFlvMuxer.stop(); mSrsFlvMuxer = null; } } private class ConnectCheckerRtmpAdapter implements ConnectCheckerRtmp { @Override public void onConnectionSuccessRtmp() { if (DEBUG) { Log.d(TAG, "RtmpMuxer::onConnectionSuccessRtmp"); } } @Override public void onConnectionFailedRtmp(String reason) { if (DEBUG) { Log.e(TAG, "RtmpMuxer::onConnectionFailedRtmp"); Log.e(TAG, " reason: "+ reason); } } @Override public void onNewBitrateRtmp(long bitrate) { if (DEBUG) { Log.d(TAG, "RtmpMuxer::onNewBitrateRtmp"); Log.d(TAG, " bitrate: "+ bitrate); } if (mOnEventListener != null) { mOnEventListener.onNewBitrate(bitrate); } } @Override public void onDisconnectRtmp() { if (DEBUG) { Log.d(TAG, "RtmpMuxer::onDisconnectRtmp"); } if (mOnEventListener != null) { mOnEventListener.onDisconnected(); } } @Override public void onAuthErrorRtmp() { if (DEBUG) { Log.e(TAG, "RtmpMuxer::onAuthErrorRtmp"); } } @Override public void onAuthSuccessRtmp() { if (DEBUG) { Log.d(TAG, "RtmpMuxer::onAuthSuccessRtmp"); } } } /** * RtmpMuxer . */ public interface OnEventListener { /** * RTMP . */ void onConnected(); /** * RTMP . */ void onDisconnected(); /** * RTMP . * * @param bitrate */ void onNewBitrate(long bitrate); /** * RTMP . * * @param e */ void onError(MediaEncoderException e); } }
package uk.ac.ebi.spot.goci.curation.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Sort; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import uk.ac.ebi.spot.goci.curation.model.StudySampleDescription; import uk.ac.ebi.spot.goci.curation.service.StudySampleDescriptionsDownloadService; import uk.ac.ebi.spot.goci.model.Ethnicity; import uk.ac.ebi.spot.goci.model.Study; import uk.ac.ebi.spot.goci.repository.EthnicityRepository; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Date; @Controller @RequestMapping("/sampledescriptions") public class StudySampleDesciptionsController { // Repositories allowing access to database objects associated with a study private EthnicityRepository ethnicityRepository; private StudySampleDescriptionsDownloadService studySampleDescriptionsDownloadService; @Autowired public StudySampleDesciptionsController(EthnicityRepository ethnicityRepository, StudySampleDescriptionsDownloadService studySampleDescriptionsDownloadService) { this.ethnicityRepository = ethnicityRepository; this.studySampleDescriptionsDownloadService = studySampleDescriptionsDownloadService; } private final Logger log = LoggerFactory.getLogger(getClass()); protected Logger getLog() { return log; } @RequestMapping(produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.GET) public void getStudiesSampleDescriptions(HttpServletResponse response, Model model) { // Get all ethnicities, this will also find all studies with ethnicity information Collection<Ethnicity> ethnicities = ethnicityRepository.findAll(sortByStudyDateDesc()); Collection<StudySampleDescription> studySampleDescriptions = new ArrayList<>(); for (Ethnicity ethnicity : ethnicities) { // Make sure ethnicity has an attached study if (ethnicity.getStudy() != null) { Study study = ethnicity.getStudy(); // Study attributes String author = study.getAuthor(); Date studyDate = study.getStudyDate(); String pubmedId = study.getPubmedId(); String initialSampleSize = study.getInitialSampleSize(); String replicateSampleSize = study.getReplicateSampleSize(); // Housekeeping attributes Boolean ethnicityCheckedLevelOne = false; Boolean ethnicityCheckedLevelTwo = false; if (study.getHousekeeping() != null) { ethnicityCheckedLevelOne = study.getHousekeeping().getEthnicityCheckedLevelOne(); ethnicityCheckedLevelTwo = study.getHousekeeping().getEthnicityCheckedLevelTwo(); } // Ethnicity attributes String type = ethnicity.getType(); Integer numberOfIndividuals = ethnicity.getNumberOfIndividuals(); String ethnicGroup = ethnicity.getEthnicGroup(); String countryOfOrigin = ethnicity.getCountryOfOrigin(); String countryOfRecruitment = ethnicity.getCountryOfRecruitment(); String sampleSizesMatch = ethnicity.getSampleSizesMatch(); String description = ethnicity.getDescription(); String notes = ethnicity.getNotes(); StudySampleDescription studySampleDescription = new StudySampleDescription(author, studyDate, pubmedId, initialSampleSize, replicateSampleSize, ethnicityCheckedLevelOne, ethnicityCheckedLevelTwo, type, numberOfIndividuals, ethnicGroup, countryOfOrigin, countryOfRecruitment, description, sampleSizesMatch, notes); studySampleDescriptions.add(studySampleDescription); } } // Create date stamped tsv download file DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date date = new Date(); String now = dateFormat.format(date); String fileName = "GWASEthnicity".concat("-").concat(now).concat(".tsv"); response.setContentType("text/tsv"); response.setHeader("Content-Disposition", "attachement; filename=" + fileName); try { studySampleDescriptionsDownloadService.createDownloadFile(response.getOutputStream(), studySampleDescriptions); } catch (IOException e) { getLog().error("Cannot create ethnicity download file"); e.printStackTrace(); } } // Returns a Sort object which sorts disease traits in ascending order by trait, ignoring case private Sort sortByStudyDateDesc() { return new Sort(new Sort.Order(Sort.Direction.DESC, "study.studyDate")); } }
package com.ctrip.ops.sysdev.outputs; import com.ctrip.ops.sysdev.baseplugin.BaseOutput; import com.ctrip.ops.sysdev.render.DateFormatter; import com.ctrip.ops.sysdev.render.TemplateRender; import org.apache.log4j.Logger; import org.elasticsearch.action.DocWriteRequest; import org.elasticsearch.action.bulk.BulkItemResponse; import org.elasticsearch.action.bulk.BulkProcessor; import org.elasticsearch.action.bulk.BulkRequest; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.InetSocketTransportAddress; import org.elasticsearch.common.unit.ByteSizeUnit; import org.elasticsearch.common.unit.ByteSizeValue; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.transport.client.PreBuiltTransportClient; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; public class Elasticsearch extends BaseOutput { private static final Logger logger = Logger.getLogger(Elasticsearch.class .getName()); private final static int BULKACTION = 20000; private final static int BULKSIZE = 15; private final static int FLUSHINTERVAL = 10; private final static int CONCURRENTREQSIZE = 0; private final static boolean DEFAULTSNIFF = true; private final static boolean DEFAULTCOMPRESS = false; private String index; private String indexTimezone; private BulkProcessor bulkProcessor; private TransportClient esclient; private TemplateRender indexTypeRender; private TemplateRender idRender; private TemplateRender parentRender; public Elasticsearch(Map config) { super(config); } protected void prepare() { this.index = (String) config.get("index"); if (config.containsKey("timezone")) { this.indexTimezone = (String) config.get("timezone"); } else { this.indexTimezone = "UTC"; } if (config.containsKey("document_id")) { String document_id = config.get("document_id").toString(); try { this.idRender = TemplateRender.getRender(document_id); } catch (IOException e) { logger.fatal("could not build tempalte from " + document_id); System.exit(1); } } else { this.idRender = null; } String index_type = "logs"; if (config.containsKey("index_type")) { index_type = config.get("index_type").toString(); } try { this.indexTypeRender = TemplateRender.getRender(index_type); } catch (IOException e) { logger.fatal("could not build tempalte from " + index_type); System.exit(1); } if (config.containsKey("document_parent")) { String document_parent = config.get("document_parent").toString(); try { this.parentRender = TemplateRender.getRender(document_parent); } catch (IOException e) { logger.fatal("could not build tempalte from " + document_parent); System.exit(1); } } else { this.parentRender = null; } this.initESClient(); } private void initESClient() throws NumberFormatException { String clusterName = (String) config.get("cluster"); boolean sniff = config.containsKey("sniff") ? (boolean) config.get("sniff") : DEFAULTSNIFF; boolean compress = config.containsKey("compress") ? (boolean) config.get("compress") : DEFAULTCOMPRESS; Settings.Builder settings = Settings.builder() .put("client.transport.sniff", sniff) .put("transport.tcp.compress", compress) .put("cluster.name", clusterName); if (config.containsKey("settings")) { HashMap<String, Object> otherSettings = (HashMap<String, Object>) this.config.get("settings"); otherSettings.entrySet().stream().forEach(entry -> settings.put(entry.getKey(), entry.getValue())); } esclient = new PreBuiltTransportClient(settings.build()); ArrayList<String> hosts = (ArrayList<String>) config.get("hosts"); hosts.stream().map(host -> host.split(":")).forEach(parsedHost -> { try { String host = parsedHost[0]; String port = parsedHost.length == 2 ? parsedHost[1] : "9300"; esclient.addTransportAddress(new InetSocketTransportAddress( InetAddress.getByName(host), Integer.parseInt(port))); } catch (UnknownHostException e) { e.printStackTrace(); } }); int bulkActions = config.containsKey("bulk_actions") ? (int) config.get("bulk_actions") : BULKACTION; int bulkSize = config.containsKey("bulk_size") ? (int) config.get("bulk_size") : BULKSIZE; int flushInterval = config.containsKey("flush_interval") ? (int) config.get("flush_interval") : FLUSHINTERVAL; int concurrentRequests = config.containsKey("concurrent_requests") ? (int) config.get("concurrent_requests") : CONCURRENTREQSIZE; bulkProcessor = BulkProcessor.builder( esclient, new BulkProcessor.Listener() { @Override public void beforeBulk(long executionId, BulkRequest request) { logger.info("executionId: " + executionId); logger.info("numberOfActions: " + request.numberOfActions()); logger.debug("Hosts:" + esclient.transportAddresses().toString()); } @Override public void afterBulk(long executionId, BulkRequest request, BulkResponse response) { logger.info("bulk done with executionId: " + executionId); List<DocWriteRequest> requests = request.requests(); int toBeTry = 0; int totalFailed = 0; for (BulkItemResponse item : response.getItems()) { if (item.isFailed()) { switch (item.getFailure().getStatus()) { case TOO_MANY_REQUESTS: case SERVICE_UNAVAILABLE: if (toBeTry == 0) { logger.error("bulk has failed item which NEED to retry"); logger.error(item.getFailureMessage()); } toBeTry++; bulkProcessor.add(requests.get(item.getItemId())); break; default: if (totalFailed == 0) { logger.error("bulk has failed item which do NOT need to retry"); logger.error(item.getFailureMessage()); } break; } totalFailed++; } } if (totalFailed > 0) { logger.info(totalFailed + " doc failed, " + toBeTry + " need to retry"); } else { logger.debug("no failed docs"); } if (toBeTry > 0) { try { logger.info("sleep " + toBeTry / 2 + "millseconds after bulk failure"); Thread.sleep(toBeTry / 2); } catch (InterruptedException e) { logger.error(e); } } else { logger.debug("no docs need to retry"); } } @Override public void afterBulk(long executionId, BulkRequest request, Throwable failure) { logger.error("bulk got exception: " + failure.getMessage()); } }).setBulkActions(bulkActions) .setBulkSize(new ByteSizeValue(bulkSize, ByteSizeUnit.MB)) .setFlushInterval(TimeValue.timeValueSeconds(flushInterval)) .setConcurrentRequests(concurrentRequests).build(); } protected void emit(final Map event) { String _index = DateFormatter.format(event, index, indexTimezone); String _indexType = indexTypeRender.render(event).toString(); IndexRequest indexRequest; if (this.idRender == null) { indexRequest = new IndexRequest(_index, _indexType).source(event); } else { String _id = (String) idRender.render(event); indexRequest = new IndexRequest(_index, _indexType, _id).source(event); } if (this.parentRender != null) { indexRequest.parent(parentRender.render(event).toString()); } this.bulkProcessor.add(indexRequest); } public void shutdown() { logger.info("flush docs and then shutdown"); //flush immediately this.bulkProcessor.flush(); // await for some time for rest data from input int flushInterval = 10; if (config.containsKey("flush_interval")) { flushInterval = (int) config.get("flush_interval"); } try { this.bulkProcessor.awaitClose(flushInterval, TimeUnit.SECONDS); } catch (InterruptedException e) { logger.error("failed to bulk docs before shutdown"); logger.error(e); } } }
package org.innovateuk.ifs.application.transactional; import org.innovateuk.ifs.application.resource.*; import org.innovateuk.ifs.commons.security.SecuredBySpring; import org.innovateuk.ifs.commons.service.ServiceResult; import org.innovateuk.ifs.fundingdecision.domain.FundingDecisionStatus; import org.springframework.security.access.prepost.PreAuthorize; import java.util.List; import java.util.Optional; public interface ApplicationSummaryService { @PreAuthorize("hasAnyAuthority('comp_admin' , 'project_finance', 'support','auditor')") @SecuredBySpring(value = "READ", description = "Internal users, apart from innovation lead, can see all Application Summaries across the whole system", securedType = ApplicationSummaryPageResource.class) ServiceResult<ApplicationSummaryPageResource> getApplicationSummariesByCompetitionId(long competitionId, String sortBy, int pageIndex, int pageSize, Optional<String> filter); @PreAuthorize("hasAnyAuthority('comp_admin' , 'project_finance', 'support', 'innovation_lead', 'stakeholder')") @SecuredBySpring(value = "READ", description = "Internal users can see all submitted Application Summaries across the whole system", securedType = ApplicationSummaryPageResource.class) ServiceResult<ApplicationSummaryPageResource> getSubmittedApplicationSummariesByCompetitionId(long competitionId, String sortBy, int pageIndex, int pageSize, Optional<String> filter, Optional<FundingDecisionStatus> fundingFilter, Optional<Boolean> inAssessmentReviewPanel); @PreAuthorize("hasAnyAuthority('comp_admin' , 'project_finance', 'support', 'innovation_lead', 'stakeholder')") @SecuredBySpring(value = "READ", description = "Internal users can see all submitted Application ids across the whole system", securedType = ApplicationSummaryPageResource.class) ServiceResult<List<Long>> getAllSubmittedApplicationIdsByCompetitionId(long competitionId, Optional<String> filter, Optional<FundingDecisionStatus> fundingFilter); @PreAuthorize("hasAnyAuthority('comp_admin' , 'project_finance', 'support', 'innovation_lead', 'stakeholder')") @SecuredBySpring(value = "READ", description = "Internal users can see all not-yet submitted Application Summaries across the whole system", securedType = ApplicationSummaryPageResource.class) ServiceResult<ApplicationSummaryPageResource> getNotSubmittedApplicationSummariesByCompetitionId(long competitionId, String sortBy, int pageIndex, int pageSize); @PreAuthorize("hasAnyAuthority('comp_admin' , 'project_finance', 'support', 'innovation_lead', 'stakeholder')") @SecuredBySpring(value = "READ", description = "Internal users can see all Application Summaries with funding decisions across the whole system", securedType = ApplicationSummaryPageResource.class) ServiceResult<ApplicationSummaryPageResource> getWithFundingDecisionApplicationSummariesByCompetitionId(long competitionId, String sortBy, int pageIndex, int pageSize, Optional<String> filter, Optional<Boolean> sendFilter, Optional<FundingDecisionStatus> fundingFilter); @PreAuthorize("hasAnyAuthority('comp_admin' , 'project_finance', 'support', 'innovation_lead', 'stakeholder')") @SecuredBySpring(value = "READ", description = "Internal users can see all Application Ids with funding decisions across the whole system", securedType = ApplicationSummaryResource.class) ServiceResult<List<Long>> getWithFundingDecisionIsChangeableApplicationIdsByCompetitionId(long competitionId, Optional<String> filter, Optional<Boolean> sendFilter, Optional<FundingDecisionStatus> fundingFilter); @PreAuthorize("hasAnyAuthority('comp_admin', 'support', 'innovation_lead', 'stakeholder')") @SecuredBySpring(value = "READ", description = "Internal users can see all Ineligable Application Summaries across the whole system", securedType = ApplicationSummaryPageResource.class) ServiceResult<ApplicationSummaryPageResource> getIneligibleApplicationSummariesByCompetitionId(long competitionId, String sortBy, int pageIndex, int pageSize, Optional<String> filter, Optional<Boolean> informFilter); @PreAuthorize("hasAnyAuthority('comp_admin' , 'project_finance', 'support', 'innovation_lead', 'stakeholder')") @SecuredBySpring(value = "READ", description = "Internal users can see all previous applications across the whole system", securedType = ApplicationSummaryPageResource.class) ServiceResult<List<PreviousApplicationResource>> getPreviousApplications(long competitionId); }
package com.worth.ifs.transactional; import com.fasterxml.jackson.databind.ObjectMapper; import com.worth.ifs.application.resource.ApplicationResource; import com.worth.ifs.application.service.ApplicationRestService; import com.worth.ifs.commons.BaseWebIntegrationTest; import com.worth.ifs.commons.error.CommonFailureKeys; import com.worth.ifs.commons.error.Error; import com.worth.ifs.commons.rest.RestErrorResponse; import com.worth.ifs.commons.rest.RestResult; import com.worth.ifs.commons.security.SecuritySetter; import com.worth.ifs.commons.security.UidAuthenticationService; import com.worth.ifs.commons.security.UserAuthentication; import com.worth.ifs.commons.service.HttpHeadersUtils; import com.worth.ifs.competition.resource.CompetitionResource; import com.worth.ifs.user.resource.UserResource; import com.worth.ifs.user.service.UserRestService; import org.junit.Assert; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.HttpServerErrorException; import org.springframework.web.client.RestTemplate; import java.io.IOException; import java.util.concurrent.Future; import static com.worth.ifs.commons.error.CommonFailureKeys.GENERAL_SPRING_SECURITY_FORBIDDEN_ACTION; import static com.worth.ifs.commons.security.UidAuthenticationService.AUTH_TOKEN; import static com.worth.ifs.commons.service.HttpHeadersUtils.getJSONHeaders; import static org.junit.Assert.*; import static org.springframework.http.HttpMethod.GET; import static org.springframework.http.HttpStatus.FORBIDDEN; import static org.springframework.http.HttpStatus.OK; /** * Tests for the {@link com.worth.ifs.rest.RestResultHandlingHttpMessageConverter}, to assert that it can take successful * RestResults from Controllers and convert them into the "body" of the RestResult, and that it can take failing RestResults * and convert them into {@link RestErrorResponse} objects. */ public class RestResultHandlingHttpMessageConverterIntegrationTest extends BaseWebIntegrationTest { @Value("${ifs.data.service.rest.baseURL}") private String dataUrl; @Autowired public ApplicationRestService applicationRestService; @Test public void testSuccessRestResultHandledAsTheBodyOfTheRestResult() { RestTemplate restTemplate = new RestTemplate(); final long applicationId = 1L; try { final String url = String.format("%s/competition/%s", dataUrl, applicationId); ResponseEntity<CompetitionResource> response = restTemplate.exchange(url, GET, leadApplicantHeadersEntity(), CompetitionResource.class); assertEquals(OK, response.getStatusCode()); assertNotNull(response.getBody()); } catch (HttpClientErrorException | HttpServerErrorException e) { fail("Should have handled the request and response ok, but got exception - " + e); } } @Test public void testFailureRestResultHandledAsARestErrorResponse() throws IOException { RestTemplate restTemplate = new RestTemplate(); try { String url = dataUrl + "/application/9999"; restTemplate.exchange(url, GET, leadApplicantHeadersEntity(), String.class); fail("Should have had a Not Found on the server side, as a non-existent id was specified"); } catch (HttpClientErrorException | HttpServerErrorException e) { assertEquals(FORBIDDEN, e.getStatusCode()); RestErrorResponse restErrorResponse = new ObjectMapper().readValue(e.getResponseBodyAsString(), RestErrorResponse.class); Error expectedError = new Error(CommonFailureKeys.GENERAL_FORBIDDEN.name(), null); RestErrorResponse expectedResponse = new RestErrorResponse(expectedError); Assert.assertEquals(expectedResponse, restErrorResponse); } } @Test public void testFailureRestResultHandledAsync() throws Exception { final UserResource initial = SecuritySetter.swapOutForUser(leadApplicantUser()); try { final long applicationIdThatDoesNotExist = -1L; final Future<RestResult<Double>> completeQuestionsPercentage = applicationRestService.getCompleteQuestionsPercentage(applicationIdThatDoesNotExist); // We have set the future going but now we need to call it. This call should not throw final RestResult<Double> doubleRestResult = completeQuestionsPercentage.get(); assertTrue(doubleRestResult.isFailure()); Assert.assertEquals(FORBIDDEN, doubleRestResult.getStatusCode()); } finally { SecuritySetter.swapOutForUser(initial); } } private <T> HttpEntity<T> leadApplicantHeadersEntity(){ return getUserJSONHeaders(leadApplicantUser()); } private <T> HttpEntity<T> getUserJSONHeaders(UserResource user) { HttpHeaders headers = HttpHeadersUtils.getJSONHeaders(); headers.set(UidAuthenticationService.AUTH_TOKEN, user.getUid()); return new HttpEntity<>(headers); } private UserResource leadApplicantUser(){ return SecuritySetter.basicSecurityUser; } }
package org.eclipse.birt.report.model.adapter.oda; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.birt.core.data.ExpressionUtil; import org.eclipse.birt.report.model.adapter.oda.model.DesignValues; import org.eclipse.birt.report.model.adapter.oda.model.util.SerializerImpl; import org.eclipse.birt.report.model.api.CommandStack; import org.eclipse.birt.report.model.api.DataSetHandle; import org.eclipse.birt.report.model.api.OdaDataSetHandle; import org.eclipse.birt.report.model.api.OdaDataSetParameterHandle; import org.eclipse.birt.report.model.api.ParameterGroupHandle; import org.eclipse.birt.report.model.api.PropertyHandle; import org.eclipse.birt.report.model.api.ScalarParameterHandle; import org.eclipse.birt.report.model.api.SelectionChoiceHandle; import org.eclipse.birt.report.model.api.StructureFactory; import org.eclipse.birt.report.model.api.activity.SemanticException; import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants; import org.eclipse.birt.report.model.api.elements.structures.OdaDataSetParameter; import org.eclipse.birt.report.model.api.elements.structures.SelectionChoice; import org.eclipse.birt.report.model.api.util.StringUtil; import org.eclipse.datatools.connectivity.oda.design.DataElementAttributes; import org.eclipse.datatools.connectivity.oda.design.DataElementUIHints; import org.eclipse.datatools.connectivity.oda.design.DataSetDesign; import org.eclipse.datatools.connectivity.oda.design.DataSetParameters; import org.eclipse.datatools.connectivity.oda.design.DesignFactory; import org.eclipse.datatools.connectivity.oda.design.DynamicValuesQuery; import org.eclipse.datatools.connectivity.oda.design.InputElementAttributes; import org.eclipse.datatools.connectivity.oda.design.InputElementUIHints; import org.eclipse.datatools.connectivity.oda.design.InputParameterAttributes; import org.eclipse.datatools.connectivity.oda.design.InputParameterUIHints; import org.eclipse.datatools.connectivity.oda.design.InputPromptControlStyle; import org.eclipse.datatools.connectivity.oda.design.ParameterDefinition; import org.eclipse.datatools.connectivity.oda.design.ScalarValueChoices; import org.eclipse.datatools.connectivity.oda.design.ScalarValueDefinition; import org.eclipse.emf.common.util.EList; /** * Converts values between a report parameter and ODA Design Session Request. * */ public class ReportParameterAdapter { /** * Default constructor. */ public ReportParameterAdapter( ) { } /** * Checks whether the given report parameter is updated. This method checks * values of report parameters and values in data set design. * <p> * If any input argument is null or the matched ODA parameter definition * cannot be found, return <code>true</code>. * * @param reportParam * the report parameter * @param param * the ROM data set parameter * @param dataSetDesign * the data set design * @return <code>true</code> if the report paramter is updated or has no * parameter definition in the data set design. Otherwise * <code>false</code>. */ public static boolean isUpdatedReportParameter( ScalarParameterHandle reportParam, OdaDataSetParameterHandle param, DataSetDesign dataSetDesign ) { if ( reportParam == null || param == null || dataSetDesign == null ) return true; ParameterDefinition matchedParam = getValidParameterDefinition( param, dataSetDesign.getParameters( ) ); if ( matchedParam == null ) return true; ParameterDefinition reportParamDefn = DesignFactory.eINSTANCE .createParameterDefinition( ); DataElementAttributes dataAttrs = DesignFactory.eINSTANCE .createDataElementAttributes( ); dataAttrs.setName( param.getNativeName( ) ); Integer position = param.getPosition( ); if ( position != null ) dataAttrs.setPosition( position.intValue( ) ); reportParamDefn.setAttributes( dataAttrs ); reportParamDefn = new ReportParameterAdapter( ) .updateParameterDefinitionFromReportParam( reportParamDefn, reportParam ); String reportParamString = DesignObjectSerializer .toExternalForm( reportParamDefn ); String matchedParamString = DesignObjectSerializer .toExternalForm( matchedParam ); if ( reportParamString.equals( matchedParamString ) ) return true; return false; } /** * Refreshes property values of the given report parameter by the given data * set design. This method first copies values from ROM data set parameter * to report parameter, then copies values from DataSetDesign to the report * parameter. * <p> * When copies values from DataSetDesign, cached value in * OdaDataSetHandle.designerValues are also considerred. * * * @param reportParam * the report parameter * @param dataSetDesign * the data set design * @throws SemanticException * if value in the data set design is invalid */ void updateLinkedReportParameter( ScalarParameterHandle reportParam, OdaDataSetParameterHandle dataSetParam, DataSetDesign dataSetDesign ) throws SemanticException { if ( reportParam == null || dataSetParam == null || dataSetDesign == null ) return; updateLinkedReportParameterFromROMParameter( reportParam, dataSetParam ); ParameterDefinition matchedParam = getValidParameterDefinition( dataSetParam, dataSetDesign.getParameters( ) ); if ( matchedParam == null ) return; ParameterDefinition cachedParam = null; OdaDataSetHandle setHandle = (OdaDataSetHandle) dataSetParam .getElementHandle( ); if ( setHandle != null ) { DesignValues values = null; try { values = SerializerImpl.instance( ).read( setHandle.getDesignerValues( ) ); } catch ( IOException e ) { } if ( values != null ) cachedParam = DataSetParameterAdapter.findParameterDefinition( values.getDataSetParameters( ), matchedParam .getAttributes( ).getName( ), new Integer( matchedParam.getAttributes( ).getPosition( ) ) ); } String dataType = DataSetParameterAdapter.getROMDataType( dataSetDesign .getOdaExtensionDataSourceId( ), dataSetDesign .getOdaExtensionDataSetId( ), (OdaDataSetParameter) dataSetParam.getStructure( ), setHandle == null ? null : setHandle.parametersIterator( ) ); updateLinkedReportParameter( reportParam, matchedParam, cachedParam, dataType ); } /** * Updates values in report parameter by given ROM data set parameter. * * @param reportParam * the report parameter * @param dataSetParam * the data set parameter * @throws SemanticException */ private void updateLinkedReportParameterFromROMParameter( ScalarParameterHandle reportParam, OdaDataSetParameterHandle dataSetParam ) throws SemanticException { assert reportParam != null; if ( dataSetParam == null ) return; String name = dataSetParam.getName( ); if ( !StringUtil.isBlank( name ) ) reportParam.setName( name ); String dataType = dataSetParam.getParameterDataType( ); if ( !StringUtil.isBlank( dataType ) ) reportParam.setDataType( dataType ); String defaultValue = dataSetParam.getDefaultValue( ); if ( !StringUtil.isBlank( defaultValue ) ) { boolean match = ExpressionUtil .isScalarParamReference( defaultValue ); if ( !match ) reportParam.setDefaultValue( defaultValue ); } String paramName = dataSetParam.getParamName( ); if ( StringUtil.isBlank( paramName ) ) { dataSetParam.setParamName( reportParam.getName( ) ); } } /** * Refreshes property values of the given report parameter by the given * parameter definition and cached parameter definition. If values in cached * parameter definition is null or values in cached parameter definition are * not equal to values in parameter defnition, update values in given report * parameter. * * @param reportParam * the report parameter * @param dataSetDesign * the data set design * @throws SemanticException * if value in the data set design is invalid */ void updateLinkedReportParameter( ScalarParameterHandle reportParam, ParameterDefinition paramDefn, ParameterDefinition cachedParamDefn, String dataType ) throws SemanticException { if ( paramDefn == null ) return; CommandStack cmdStack = reportParam.getModuleHandle( ) .getCommandStack( ); try { cmdStack.startTrans( null ); // any type is not support in report parameter data type. if ( dataType == null || !DesignChoiceConstants.PARAM_TYPE_ANY .equalsIgnoreCase( dataType ) ) reportParam.setDataType( dataType ); updateDataElementAttrsToReportParam( paramDefn.getAttributes( ), cachedParamDefn == null ? null : cachedParamDefn .getAttributes( ), reportParam ); updateInputParameterAttrsToReportParam( paramDefn .getInputAttributes( ), cachedParamDefn == null ? null : cachedParamDefn.getInputAttributes( ), reportParam ); } catch ( SemanticException e ) { cmdStack.rollback( ); throw e; } cmdStack.commit( ); } /** * Refreshes property values of the given ROM ODA data set parameter. * * * @param reportParam * the report parameter * @param dataSetParam * the Oda data set parameter * @throws SemanticException * if value in the data set design is invalid */ public void updateLinkedReportParameter( ScalarParameterHandle reportParam, OdaDataSetParameterHandle dataSetParam ) throws SemanticException { if ( reportParam == null || dataSetParam == null ) return; updateLinkedReportParameterFromROMParameter( reportParam, dataSetParam ); } /** * Returns the matched ODA data set parameter by the given ROM data set * parameter and data set design. * * @param param * the ROM data set parameter * @param dataSetDesign * the oda data set design * @return the matched ODA parameter defintion */ private static ParameterDefinition getValidParameterDefinition( OdaDataSetParameterHandle param, DataSetParameters odaParams ) { if ( param == null || odaParams == null ) return null; if ( odaParams.getParameterDefinitions( ).isEmpty( ) ) return null; ParameterDefinition matchedParam = DataSetParameterAdapter .findParameterDefinition( odaParams, param.getName( ), param .getPosition( ) ); return matchedParam; } /** * Updates values in DataElementAttributes to the given report parameter. * * @param dataAttrs * the latest data element attributes * @param cachedDataAttrs * the cached data element attributes * @param reportParam * the report parameter * @throws SemanticException */ private void updateDataElementAttrsToReportParam( DataElementAttributes dataAttrs, DataElementAttributes cachedDataAttrs, ScalarParameterHandle reportParam ) throws SemanticException { if ( dataAttrs == null ) return; boolean allowsNull = dataAttrs.allowsNull( ); if ( cachedDataAttrs == null || cachedDataAttrs.allowsNull( ) != allowsNull ) reportParam.setAllowNull( dataAttrs.allowsNull( ) ); DataElementUIHints dataUiHints = dataAttrs.getUiHints( ); DataElementUIHints cachedDataUiHints = ( cachedDataAttrs == null ? null : cachedDataAttrs.getUiHints( ) ); if ( dataUiHints != null ) { String displayName = dataUiHints.getDisplayName( ); String cachedDisplayName = cachedDataUiHints == null ? null : dataUiHints.getDisplayName( ); if ( cachedDisplayName == null || !cachedDisplayName.equals( displayName ) ) reportParam.setPromptText( displayName ); String description = dataUiHints.getDescription( ); String cachedDescription = cachedDataUiHints == null ? null : dataUiHints.getDescription( ); if ( cachedDescription == null || !cachedDescription.equals( description ) ) reportParam.setHelpText( description ); } } /** * Updates values in InputParameterAttributes to the given report parameter. * * @param dataAttrs * the latest input parameter attributes * @param cachedDataAttrs * the cached input parameter attributes * @param reportParam * the report parameter * @throws SemanticException */ private void updateInputParameterAttrsToReportParam( InputParameterAttributes inputParamAttrs, InputParameterAttributes cachedInputParamAttrs, ScalarParameterHandle reportParam ) throws SemanticException { if ( inputParamAttrs == null ) return; InputParameterUIHints paramUiHints = inputParamAttrs.getUiHints( ); if ( paramUiHints != null && reportParam.getContainer( ) instanceof ParameterGroupHandle ) { ParameterGroupHandle paramGroup = (ParameterGroupHandle) reportParam .getContainer( ); InputParameterUIHints cachedParamUiHints = cachedInputParamAttrs == null ? null : cachedInputParamAttrs.getUiHints( ); String cachedGroupPromptDisplayName = cachedParamUiHints == null ? null : cachedParamUiHints.getGroupPromptDisplayName( ); String groupPromptDisplayName = paramUiHints .getGroupPromptDisplayName( ); if ( cachedGroupPromptDisplayName == null || !cachedGroupPromptDisplayName .equals( groupPromptDisplayName ) ) paramGroup.setDisplayName( paramUiHints .getGroupPromptDisplayName( ) ); } updateInputElementAttrsToReportParam( inputParamAttrs .getElementAttributes( ), cachedInputParamAttrs == null ? null : cachedInputParamAttrs.getElementAttributes( ), reportParam ); } /** * Updates values in InputElementAttributes to the given report parameter. * * @param dataAttrs * the latest input element attributes * @param cachedDataAttrs * the cached input element attributes * @param reportParam * the report parameter * @throws SemanticException */ private void updateInputElementAttrsToReportParam( InputElementAttributes elementAttrs, InputElementAttributes cachedElementAttrs, ScalarParameterHandle reportParam ) throws SemanticException { if ( elementAttrs == null ) return; // update default values. String defaultValue = elementAttrs.getDefaultScalarValue( ); String cachedDefaultValue = cachedElementAttrs == null ? null : cachedElementAttrs.getDefaultScalarValue( ); if ( cachedDefaultValue == null || !cachedDefaultValue.equals( defaultValue ) ) reportParam.setDefaultValue( defaultValue ); // update conceal value Boolean masksValue = Boolean.valueOf( elementAttrs.isMasksValue( ) ); Boolean cachedMasksValues = cachedElementAttrs == null ? null : Boolean .valueOf( cachedElementAttrs.isMasksValue( ) ); if ( cachedMasksValues == null || !cachedMasksValues.equals( masksValue ) ) reportParam.setConcealValue( masksValue.booleanValue( ) ); updateROMSelectionList( elementAttrs.getStaticValueChoices( ), cachedElementAttrs == null ? null : cachedElementAttrs .getStaticValueChoices( ), reportParam ); updateROMDyanmicList( elementAttrs.getDynamicValueChoices( ), cachedElementAttrs == null ? null : cachedElementAttrs .getDynamicValueChoices( ), reportParam ); InputElementUIHints uiHints = elementAttrs.getUiHints( ); if ( uiHints != null ) { InputElementUIHints cachedUiHints = cachedElementAttrs == null ? null : cachedElementAttrs.getUiHints( ); InputPromptControlStyle style = uiHints.getPromptStyle( ); InputPromptControlStyle cachedStyle = cachedUiHints == null ? null : cachedUiHints.getPromptStyle( ); if ( cachedStyle == null || ( style != null && cachedStyle.getValue( ) == style .getValue( ) ) ) reportParam.setControlType( style == null ? null : newROMControlType( style.getValue( ) ) ); } } /** * Returns ROM defined control type by given ODA defined prompt style. * * @param promptStyle * the ODA defined prompt style * @return the ROM defined control type */ private static String newROMControlType( int promptStyle ) { switch ( promptStyle ) { case InputPromptControlStyle.CHECK_BOX : return DesignChoiceConstants.PARAM_CONTROL_CHECK_BOX; case InputPromptControlStyle.SELECTABLE_LIST : case InputPromptControlStyle.SELECTABLE_LIST_WITH_TEXT_FIELD : return DesignChoiceConstants.PARAM_CONTROL_LIST_BOX; case InputPromptControlStyle.RADIO_BUTTON : return DesignChoiceConstants.PARAM_CONTROL_RADIO_BUTTON; case InputPromptControlStyle.TEXT_FIELD : return DesignChoiceConstants.PARAM_CONTROL_TEXT_BOX; } return null; } /** * Updates values in ScalarValueChoices to the given report parameter. * * @param dataAttrs * the latest scalar values * @param cachedDataAttrs * the cached scalar value * @param reportParam * the report parameter * @throws SemanticException */ private void updateROMSelectionList( ScalarValueChoices staticChoices, ScalarValueChoices cachedStaticChoices, ScalarParameterHandle paramHandle ) throws SemanticException { if ( staticChoices == null ) return; String newChoiceStr = DesignObjectSerializer .toExternalForm( staticChoices ); String latestChoiceStr = DesignObjectSerializer .toExternalForm( cachedStaticChoices ); if ( latestChoiceStr != null && latestChoiceStr.equals( newChoiceStr ) ) return; List retList = new ArrayList( ); EList choiceList = staticChoices.getScalarValues( ); for ( int i = 0; i < choiceList.size( ); i++ ) { ScalarValueDefinition valueDefn = (ScalarValueDefinition) choiceList .get( i ); SelectionChoice choice = StructureFactory.createSelectionChoice( ); choice.setValue( valueDefn.getValue( ) ); choice.setLabel( valueDefn.getDisplayName( ) ); retList.add( choice ); } PropertyHandle propHandle = paramHandle .getPropertyHandle( ScalarParameterHandle.SELECTION_LIST_PROP ); propHandle.clearValue( ); for ( int i = 0; i < retList.size( ); i++ ) { propHandle.addItem( retList.get( i ) ); } } /** * Updates values in DynamicValuesQuery to the given report parameter. * * @param dataAttrs * the latest dynamic values * @param cachedDataAttrs * the cached dynamic values * @param reportParam * the report parameter * @throws SemanticException */ private void updateROMDyanmicList( DynamicValuesQuery valueQuery, DynamicValuesQuery cachedValueQuery, ScalarParameterHandle reportParam ) throws SemanticException { if ( valueQuery == null ) return; String value = valueQuery.getDataSetDesign( ).getName( ); String cachedValue = cachedValueQuery == null ? null : cachedValueQuery .getDataSetDesign( ).getName( ); if ( cachedValue == null || !cachedValue.equals( value ) ) reportParam.setDataSetName( value ); value = valueQuery.getValueColumn( ); cachedValue = cachedValueQuery == null ? null : cachedValueQuery .getValueColumn( ); if ( cachedValue == null || !cachedValue.equals( value ) ) reportParam.setValueExpr( value ); value = valueQuery.getDisplayNameColumn( ); cachedValue = cachedValueQuery == null ? null : cachedValueQuery .getDisplayNameColumn( ); if ( cachedValue == null || !cachedValue.equals( value ) ) reportParam.setLabelExpr( value ); } /** * Creates an ParameterDefinition with the given report parameter. * * @param paramDefn * the ROM report parameter. * @return the created ParameterDefinition */ ParameterDefinition updateParameterDefinitionFromReportParam( ParameterDefinition paramDefn, ScalarParameterHandle paramHandle ) { assert paramHandle != null; if ( paramDefn == null ) return null; paramDefn.setAttributes( updateDataElementAttrs( paramDefn .getAttributes( ), paramHandle ) ); paramDefn.setInputAttributes( updateInputElementAttrs( paramDefn .getInputAttributes( ), paramHandle ) ); return paramDefn; } /** * Creates an DataElementAttributes with the given ROM report parameter. * * @param paramHandle * the ROM report parameter. * @return the created DataElementAttributes */ private DataElementAttributes updateDataElementAttrs( DataElementAttributes dataAttrs, ScalarParameterHandle paramHandle ) { if ( dataAttrs == null ) dataAttrs = DesignFactory.eINSTANCE.createDataElementAttributes( ); dataAttrs.setNullability( DataSetParameterAdapter .newElementNullability( paramHandle.allowNull( ) ) ); DataElementUIHints uiHints = DesignFactory.eINSTANCE .createDataElementUIHints( ); uiHints.setDisplayName( paramHandle.getPromptText( ) ); uiHints.setDescription( paramHandle.getHelpText( ) ); dataAttrs.setUiHints( uiHints ); return dataAttrs; } /** * Creates a ODA InputParameterAttributes with the given ROM report * parameter. * * @param paramDefn * the ROM report parameter. * * @return the created <code>InputParameterAttributes</code>. */ private InputParameterAttributes updateInputElementAttrs( InputParameterAttributes inputParamAttrs, ScalarParameterHandle paramDefn ) { if ( inputParamAttrs == null ) inputParamAttrs = DesignFactory.eINSTANCE .createInputParameterAttributes( ); InputElementAttributes inputAttrs = inputParamAttrs .getElementAttributes( ); if ( inputAttrs == null ) inputAttrs = DesignFactory.eINSTANCE.createInputElementAttributes( ); inputAttrs.setDefaultScalarValue( paramDefn.getDefaultValue( ) ); inputAttrs.setOptional( paramDefn.allowBlank( ) ); inputAttrs.setMasksValue( paramDefn.isConcealValue( ) ); ScalarValueChoices staticChoices = null; Iterator selectionList = paramDefn.choiceIterator( ); while ( selectionList.hasNext( ) ) { if ( staticChoices == null ) staticChoices = DesignFactory.eINSTANCE .createScalarValueChoices( ); SelectionChoiceHandle choice = (SelectionChoiceHandle) selectionList .next( ); ScalarValueDefinition valueDefn = DesignFactory.eINSTANCE .createScalarValueDefinition( ); valueDefn.setValue( choice.getValue( ) ); valueDefn.setDisplayName( choice.getLabel( ) ); staticChoices.getScalarValues( ).add( valueDefn ); } inputAttrs.setStaticValueChoices( staticChoices ); DataSetHandle setHandle = paramDefn.getDataSet( ); String valueExpr = paramDefn.getValueExpr( ); String labelExpr = paramDefn.getLabelExpr( ); if ( setHandle instanceof OdaDataSetHandle && ( valueExpr != null || labelExpr != null ) ) { DynamicValuesQuery valueQuery = DesignFactory.eINSTANCE .createDynamicValuesQuery( ); valueQuery.setDataSetDesign( new ModelOdaAdapter( ) .createDataSetDesign( (OdaDataSetHandle) setHandle ) ); valueQuery.setDisplayNameColumn( labelExpr ); valueQuery.setValueColumn( valueExpr ); valueQuery.setEnabled( true ); inputAttrs.setDynamicValueChoices( valueQuery ); } InputElementUIHints uiHints = DesignFactory.eINSTANCE .createInputElementUIHints( ); uiHints.setPromptStyle( newPromptStyle( paramDefn.getControlType( ), paramDefn.isMustMatch( ) ) ); inputAttrs.setUiHints( uiHints ); if ( paramDefn.getContainer( ) instanceof ParameterGroupHandle ) { ParameterGroupHandle groupHandle = (ParameterGroupHandle) paramDefn .getContainer( ); InputParameterUIHints paramUiHints = DesignFactory.eINSTANCE .createInputParameterUIHints( ); paramUiHints.setGroupPromptDisplayName( groupHandle .getDisplayName( ) ); inputParamAttrs.setUiHints( paramUiHints ); } inputParamAttrs.setElementAttributes( inputAttrs ); return inputParamAttrs; } /** * Returns the prompty style with the given ROM defined parameter type. * * @param romType * the ROM defined parameter type * @param mustMatch * <code>true</code> if means list box, <code>false</code> * means combo box. * @return the new InputPromptControlStyle */ private static InputPromptControlStyle newPromptStyle( String romType, boolean mustMatch ) { if ( romType == null ) return null; int type = -1; if ( DesignChoiceConstants.PARAM_CONTROL_CHECK_BOX .equalsIgnoreCase( romType ) ) type = InputPromptControlStyle.CHECK_BOX; else if ( DesignChoiceConstants.PARAM_CONTROL_LIST_BOX .equalsIgnoreCase( romType ) ) { if ( mustMatch ) type = InputPromptControlStyle.SELECTABLE_LIST; else type = InputPromptControlStyle.SELECTABLE_LIST_WITH_TEXT_FIELD; } else if ( DesignChoiceConstants.PARAM_CONTROL_RADIO_BUTTON .equalsIgnoreCase( romType ) ) type = InputPromptControlStyle.RADIO_BUTTON; else if ( DesignChoiceConstants.PARAM_CONTROL_TEXT_BOX .equalsIgnoreCase( romType ) ) type = InputPromptControlStyle.TEXT_FIELD; return InputPromptControlStyle.get( type ); } }
package com.almasb.tutorial25; import java.util.List; import java.util.Random; import java.util.logging.Level; import javafx.animation.Interpolator; import javafx.animation.TranslateTransition; import javafx.geometry.Point2D; import javafx.scene.input.KeyCode; import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.util.Duration; import com.almasb.fxgl.FXGLLogger; import com.almasb.fxgl.GameApplication; import com.almasb.fxgl.GameSettings; import com.almasb.fxgl.entity.Control; import com.almasb.fxgl.entity.Entity; import com.almasb.fxgl.entity.EntityType; import com.almasb.fxgl.search.AStarLogic; import com.almasb.fxgl.search.AStarNode; public class FXGLPacmanApp extends GameApplication { private enum Type implements EntityType { WALL, PLAYER, ENEMY, BACKGROUND } private enum Action { UP(0, -5), DOWN(0, 5), LEFT(-5, 0), RIGHT(5, 0), NONE(0, 0); final int dx, dy; Action(int dx, int dy) { this.dx = dx; this.dy = dy; } } private static final int BLOCK_SIZE = 40; private static final int ENTITY_SIZE = BLOCK_SIZE - 10; private Random random = new Random(); private List<String> levelData; private AStarNode[][] aiGrid = new AStarNode[15][15]; private AStarLogic ai = new AStarLogic(); private AStarNode start, target; private Entity player; private Action action = Action.NONE; @Override protected void initSettings(GameSettings settings) { settings.setWidth(600); settings.setHeight(600); } @Override protected void initAssets() throws Exception { levelData = assetManager.loadText("pacman_level.txt"); } @Override protected void initGame(Pane gameRoot) { addEntities(Entity.noType().setGraphics(new Rectangle(600, 600))); initLevel(); initPlayer(); initEnemies(); } private void initLevel() { int w = levelData.get(0).length(); for (int i = 0; i < levelData.size(); i++) { String line = levelData.get(i); for (int j = 0; j < w; j++) { char c = line.charAt(j); if (c == '1') { Entity wall = new Entity(Type.WALL); wall.setPosition(j * BLOCK_SIZE, i * BLOCK_SIZE); Rectangle rect = new Rectangle(BLOCK_SIZE, BLOCK_SIZE); rect.setFill(Color.GREY); wall.setGraphics(rect); addEntities(wall); } aiGrid[j][i] = new AStarNode(j, i, 0, c == '1' ? 1 : 0); } } } private void initPlayer() { player = new Entity(Type.PLAYER); player.setPosition(300 - ENTITY_SIZE / 2, 300 - ENTITY_SIZE / 2); Rectangle rect = new Rectangle(ENTITY_SIZE, ENTITY_SIZE); rect.setFill(Color.BLUE); player.setGraphics(rect); addEntities(player); } Entity e = new Entity(Type.ENEMY); private void initEnemies() { e.setPosition(45, 45); Rectangle rect = new Rectangle(30, 30); rect.setFill(Color.RED); e.setGraphics(rect); e.addControl(smartAI); addEntities(e); Entity e2 = new Entity(Type.ENEMY); e2.setPosition(525, 45); Rectangle rect2 = new Rectangle(30, 30); rect2.setFill(Color.GREEN); e2.setGraphics(rect2); e2.addControl(randomAI); addEntities(e2); } @Override protected void initUI(Pane uiRoot) {} @Override protected void initInput() { addKeyPressBinding(KeyCode.W, () -> { action = Action.UP; }); addKeyPressBinding(KeyCode.S, () -> { action = Action.DOWN; }); addKeyPressBinding(KeyCode.A, () -> { action = Action.LEFT; }); addKeyPressBinding(KeyCode.D, () -> { action = Action.RIGHT; }); addKeyTypedBinding(KeyCode.SPACE, () -> { System.out.println(saveScreenshot()); }); } @Override protected void onUpdate(long now) { moveEntity(player, action); if (player.getTranslateX() >= 600) { player.setTranslateX(0); } if (player.getTranslateX() + ENTITY_SIZE <= 0) { player.setTranslateX(600 - ENTITY_SIZE); } } private boolean canMove(Entity entity, Action move) { entity.translate(move.dx, move.dy); boolean isPlayer = entity.isType(Type.PLAYER); boolean collision = getEntities(Type.WALL, isPlayer ? Type.ENEMY : Type.PLAYER).stream() .anyMatch(e -> e.getBoundsInParent().intersects(entity.getBoundsInParent())); if (!collision && !isPlayer) { collision = entity.getTranslateX() < 0 || entity.getTranslateX() + 40 > 600 || entity.getTranslateY() < 0 || entity.getTranslateY() + 40 > 600; } entity.translate(-move.dx, -move.dy); return !collision; } private void moveEntity(Entity entity, Action move) { if (move == Action.NONE || !canMove(entity, move)) return; entity.translate(move.dx, move.dy); } private void moveEntity(Entity entity, Point2D position) { TranslateTransition tt = new TranslateTransition(Duration.seconds(0.016 * 8 * 2), entity); tt.setToX(position.getX()); tt.setToY(position.getY()); tt.setInterpolator(Interpolator.LINEAR); tt.play(); } long last, last2 = 0; Action move = Action.NONE; private Control randomAI = (entity, now) -> { moveEntity(entity, move); if (now - last2 < 1 * SECOND) return; move = Action.values()[random.nextInt(5)]; last2 = now; }; private Control smartAI = (entity, now) -> { if (now - last < 0.016 * 8 * 2 * SECOND) return; int x = Math.abs(Math.min(14, (int)(player.getTranslateX() / 40))); int y = Math.abs(Math.min(14, (int)(player.getTranslateY() / 40))); target = aiGrid[x][y]; x = Math.abs(Math.min(14, (int)(e.getTranslateX() / 40))); y = Math.abs(Math.min(14, (int)(e.getTranslateY() / 40))); start = aiGrid[x][y]; for (int i = 0; i < 15; i++) { for (int j = 0; j < 15; j++) { aiGrid[j][i].setHCost(Math.abs(target.getX() - i) + Math.abs(target.getY() - j)); } } List<AStarNode> path = ai.getPath(aiGrid, start, target); if (path != null && path.size() > 0) { x = path.get(0).getX() * 40; y = path.get(0).getY() * 40; moveEntity(entity, new Point2D(x + 5, y + 5)); } last = now; }; public static void main(String[] args) { launch(args); } }
package net.runelite.client.plugins.clanchat; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.google.common.eventbus.Subscribe; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.awt.image.DataBufferByte; import java.awt.image.IndexColorModel; import java.awt.image.WritableRaster; import java.io.IOException; import java.time.temporal.ChronoUnit; import java.util.Arrays; import java.util.Objects; import java.util.concurrent.TimeUnit; import javax.imageio.ImageIO; import javax.inject.Inject; import lombok.extern.slf4j.Slf4j; import net.runelite.api.ChatMessageType; import net.runelite.api.ClanMember; import net.runelite.api.ClanMemberRank; import net.runelite.api.Client; import net.runelite.api.GameState; import net.runelite.api.IndexedSprite; import net.runelite.api.events.GameStateChanged; import net.runelite.api.events.SetMessage; import net.runelite.api.widgets.Widget; import net.runelite.api.widgets.WidgetInfo; import net.runelite.client.plugins.Plugin; import net.runelite.client.plugins.PluginDescriptor; import net.runelite.client.task.Schedule; @PluginDescriptor( name = "Clan chat" ) @Slf4j public class ClanChatPlugin extends Plugin { private static final String[] CLANCHAT_IMAGES = { "Friend_clan_rank.png", "Recruit_clan_rank.png", "Corporal_clan_rank.png", "Sergeant_clan_rank.png", "Lieutenant_clan_rank.png", "Captain_clan_rank.png", "General_clan_rank.png", "Owner_clan_rank.png" }; private final LoadingCache<String, ClanMemberRank> clanRanksCache = CacheBuilder.newBuilder() .maximumSize(100) .expireAfterAccess(1, TimeUnit.MINUTES) .build(new CacheLoader<String, ClanMemberRank>() { @Override public ClanMemberRank load(String key) throws Exception { final ClanMember[] clanMembersArr = client.getClanMembers(); if (clanMembersArr == null || clanMembersArr.length == 0) { return ClanMemberRank.UNRANKED; } return Arrays.stream(clanMembersArr) .filter(Objects::nonNull) .filter(clanMember -> sanitize(clanMember.getUsername()).equals(sanitize(key))) .map(ClanMember::getRank) .findAny() .orElse(ClanMemberRank.UNRANKED); } }); private int modIconsLength; @Inject private Client client; @Override protected void startUp() throws Exception { if (modIconsLength == 0 && client.getGameState().compareTo(GameState.LOGIN_SCREEN) >= 0) { loadClanChatIcons(); } } @Override protected void shutDown() { clanRanksCache.invalidateAll(); } @Subscribe public void onGameStateChanged(GameStateChanged gameStateChanged) { if (gameStateChanged.getGameState() == GameState.LOGIN_SCREEN && modIconsLength == 0) { // this is after "Loading sprites" so we can modify modicons now loadClanChatIcons(); } } @Schedule( period = 600, unit = ChronoUnit.MILLIS ) public void updateClanChatTitle() { if (client.getGameState() != GameState.LOGGED_IN) { return; } Widget clanChatTitleWidget = client.getWidget(WidgetInfo.CLAN_CHAT_TITLE); if (clanChatTitleWidget != null) { clanChatTitleWidget.setText("Clan Chat (" + client.getClanChatCount() + "/100)"); } } @Subscribe public void onSetMessage(SetMessage setMessage) { if (client.getGameState() != GameState.LOADING && client.getGameState() != GameState.LOGGED_IN) { return; } if (setMessage.getType() == ChatMessageType.CLANCHAT && client.getClanChatCount() > 0) { insertClanRankIcon(setMessage); } } private void loadClanChatIcons() { try { final IndexedSprite[] modIcons = client.getModIcons(); final IndexedSprite[] newModIcons = Arrays.copyOf(modIcons, modIcons.length + CLANCHAT_IMAGES.length); int curPosition = newModIcons.length - CLANCHAT_IMAGES.length; for (String resource : CLANCHAT_IMAGES) { IndexedSprite sprite = createIndexedSprite(resource); newModIcons[curPosition++] = sprite; } client.setModIcons(newModIcons); modIconsLength = newModIcons.length; } catch (IOException e) { log.warn("Failed loading of clan chat icons", e); } } private IndexedSprite createIndexedSprite(final String imagePath) throws IOException { final BufferedImage bufferedImage = rgbaToIndexedBufferedImage(ImageIO .read(this.getClass().getResource(imagePath))); final IndexColorModel indexedCM = (IndexColorModel) bufferedImage.getColorModel(); final int width = bufferedImage.getWidth(); final int height = bufferedImage.getHeight(); final byte[] pixels = ((DataBufferByte) bufferedImage.getRaster().getDataBuffer()).getData(); final int[] palette = new int[indexedCM.getMapSize()]; indexedCM.getRGBs(palette); final IndexedSprite newIndexedSprite = client.createIndexedSprite(); newIndexedSprite.setPixels(pixels); newIndexedSprite.setPalette(palette); newIndexedSprite.setWidth(width); newIndexedSprite.setHeight(height); newIndexedSprite.setOriginalWidth(width); newIndexedSprite.setOriginalHeight(height); newIndexedSprite.setOffsetX(0); newIndexedSprite.setOffsetY(0); return newIndexedSprite; } private static BufferedImage rgbaToIndexedBufferedImage(final BufferedImage sourceBufferedImage) { final BufferedImage indexedImage = new BufferedImage( sourceBufferedImage.getWidth(), sourceBufferedImage.getHeight(), BufferedImage.TYPE_BYTE_INDEXED); final ColorModel cm = indexedImage.getColorModel(); final IndexColorModel icm = (IndexColorModel) cm; final int size = icm.getMapSize(); final byte[] reds = new byte[size]; final byte[] greens = new byte[size]; final byte[] blues = new byte[size]; icm.getReds(reds); icm.getGreens(greens); icm.getBlues(blues); final WritableRaster raster = indexedImage.getRaster(); final int pixel = raster.getSample(0, 0, 0); final IndexColorModel resultIcm = new IndexColorModel(8, size, reds, greens, blues, pixel); final BufferedImage resultIndexedImage = new BufferedImage(resultIcm, raster, sourceBufferedImage.isAlphaPremultiplied(), null); resultIndexedImage.getGraphics().drawImage(sourceBufferedImage, 0, 0, null); return resultIndexedImage; } private void insertClanRankIcon(final SetMessage message) { final String playerName = sanitize(message.getName()); final ClanMemberRank rank = clanRanksCache.getUnchecked(playerName); if (rank != null && rank != ClanMemberRank.UNRANKED) { int iconNumber = getIconNumber(rank); message.getMessageNode() .setSender(message.getMessageNode().getSender() + " <img=" + iconNumber + ">"); client.refreshChat(); } } private int getIconNumber(final ClanMemberRank clanMemberRank) { return modIconsLength - CLANCHAT_IMAGES.length + clanMemberRank.getValue(); } private static String sanitize(String lookup) { final String cleaned = lookup.contains("<img") ? lookup.substring(lookup.lastIndexOf('>') + 1) : lookup; return cleaned.replace('\u00A0', ' '); } }
package org.lamport.tla.toolbox.tool.tlc.ui.modelexplorer; import java.util.HashMap; import java.util.Vector; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.debug.core.DebugPlugin; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.debug.core.ILaunchConfigurationType; import org.eclipse.debug.core.ILaunchManager; import org.eclipse.jface.action.IContributionItem; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.ui.actions.CompoundContributionItem; import org.eclipse.ui.menus.CommandContributionItem; import org.eclipse.ui.menus.CommandContributionItemParameter; import org.lamport.tla.toolbox.tool.ToolboxHandle; import org.lamport.tla.toolbox.tool.tlc.handlers.CloneModelHandlerDelegate; import org.lamport.tla.toolbox.tool.tlc.launch.TLCModelLaunchDelegate; import org.lamport.tla.toolbox.tool.tlc.ui.TLCUIActivator; import org.lamport.tla.toolbox.tool.tlc.util.ModelHelper; import org.lamport.tla.toolbox.util.UIHelper; /** * Contributes a list of models for cloning. * * @author Daniel Ricketts * */ public class CloneModelContributionItem extends CompoundContributionItem { private ImageDescriptor modelIcon = TLCUIActivator.getImageDescriptor("icons/full/choice_sc_obj.gif"); protected IContributionItem[] getContributionItems() { ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager(); ILaunchConfigurationType launchConfigurationType = launchManager .getLaunchConfigurationType(TLCModelLaunchDelegate.LAUNCH_CONFIGURATION_TYPE); Vector modelContributions = new Vector(); IProject specProject = ToolboxHandle.getCurrentSpec().getProject(); try { // refresh local to pick up any models that have been added // to the file system but not recognized by the toolbox's resource // framework. // TODO decouple from UI thread or question why it has to be done // here. Meaning, why doesn't the resource fw handle this case // already? specProject.refreshLocal(IResource.DEPTH_ONE, new NullProgressMonitor()); // First, search for all models for the given spec. ILaunchConfiguration[] launchConfigurations = launchManager .getLaunchConfigurations(launchConfigurationType); for (int i = 0; i < launchConfigurations.length; i++) { String modelName = launchConfigurations[i].getName(); // skip launches from other specs if (!specProject.equals(launchConfigurations[i].getFile().getProject())) { continue; } // Next, set the command and the parameters for the command // that will be called when the user selects this item. HashMap parameters = new HashMap(); // user visible model name String modelNameUser = ModelHelper.getModelName(launchConfigurations[i].getFile()); // fill the model name for the handler parameters.put(CloneModelHandlerDelegate.PARAM_MODEL_NAME, modelNameUser); // create the contribution item CommandContributionItemParameter param = new CommandContributionItemParameter(UIHelper .getActiveWindow(), "toolbox.command.model.clone." + modelName, CloneModelHandlerDelegate.COMMAND_ID, parameters, modelIcon, null, null, modelNameUser, null, "Clones " + modelNameUser, CommandContributionItem.STYLE_PUSH, null, true); // add contribution item to the list modelContributions.add(new CommandContributionItem(param)); } } catch (CoreException e) { } return (IContributionItem[]) modelContributions.toArray(new IContributionItem[modelContributions.size()]); } }
import ast.ASTVisitor; import ast.ASTVisitorException; import ast.AnonymousFunctionCall; import ast.ArrayDef; import ast.AssignmentExpression; import ast.BinaryExpression; import ast.Block; import ast.BreakStatement; import ast.ContinueStatement; import ast.DoubleLiteral; import ast.Expression; import ast.ExpressionStatement; import ast.ExtendedCall; import ast.FalseLiteral; import ast.ForStatement; import ast.FunctionDef; import ast.FunctionDefExpression; import ast.IdentifierExpression; import ast.IfStatement; import ast.IndexedElement; import ast.IntegerLiteral; import ast.LvalueCall; import ast.Member; import ast.MethodCall; import ast.NormCall; import ast.NullLiteral; import ast.ObjectDefinition; import ast.Program; import ast.ReturnStatement; import ast.Statement; import ast.StringLiteral; import ast.TermExpressionStmt; import ast.TrueLiteral; import ast.UnaryExpression; import ast.WhileStatement; import ast.utils.ASTUtils; import java.util.ArrayList; import java.util.HashMap; import java.util.ArrayDeque; import symbolTable.SymbolTable; import symbolTable.entries.AFunctionEntry; import symbolTable.entries.ASymTableEntry; import symbolTable.entries.FormalVariableEntry; import symbolTable.entries.GlobalVariableEntry; import symbolTable.entries.LocalVariableEntry; import symbolTable.entries.UserFunctionEntry; import symbolTable.libraryFunctions.LibraryFunctions; public class ExecutionASTVisitor implements ASTVisitor { private ArrayDeque<SymbolTable> _envStack; private SymbolTable _genv; private final SymbolTable _symTable; private int _scope; private int _inFunction; private int _inLoop; private void enterScopeSpace() { System.out.println("EnterScopeSpace"); _scope++; } private void exitScopeSpace() { System.out.println("ExitScopeSpace"); _scope } private void enterFunctionSpace() { System.out.println("EnterFunctionSpace"); _inFunction++; } private void exitFunctionSpace() { System.out.println("ExitFunctionSpace"); _inFunction } private void enterLoopSpace() { System.out.println("EnterLoopSpace"); _inLoop++; } private void exitLoopSpace() { System.out.println("ExitLoopSpace"); _inLoop } private void hideScopeSpaceAndExit() { System.out.println("HiddeScopeSpaceAndExit"); _symTable.hide(_scope); _scope } public ExecutionASTVisitor() { _genv = new SymbolTable(); _envStack = new ArrayDeque<SymbolTable>(); _envStack.push(_genv); _symTable = _genv; _scope = 0; _inFunction = 0; _inLoop = 0; } @Override public void visit(Program node) throws ASTVisitorException { System.out.println("-Program"); for (Statement stmt : node.getStatements()) { if(stmt != null) stmt.accept(this); } this._symTable.printAll(); } @Override public void visit(ExpressionStatement node) throws ASTVisitorException { System.out.println("-ExpressionStatement"); node.getExpression().accept(this); } @Override public void visit(AssignmentExpression node) throws ASTVisitorException { System.out.println("-AssignmentExpression"); node.getLvalue().accept(this); node.getExpression().accept(this); } @Override public void visit(BinaryExpression node) throws ASTVisitorException { System.out.println("-BinaryExpression"); node.getExpression1().accept(this); //System.out.print(" " + node.getOperator() + " "); node.getExpression2().accept(this); } @Override public void visit(TermExpressionStmt node) throws ASTVisitorException { System.out.println("-TermExpressionStmt"); node.getExpression().accept(this); } @Override public void visit(UnaryExpression node) throws ASTVisitorException { System.out.println("-UnaryExpression"); //System.out.print(node.getOperator()); if (node.getExpression() != null) { node.getExpression().accept(this); } else { if (node.getLvalue() instanceof IdentifierExpression){ IdentifierExpression name = (IdentifierExpression)node.getLvalue(); HashMap<String, Object> returnVal = _symTable.lookUpVariable(name.getIdentifier(), _scope); ASymTableEntry symTableEntry = (ASymTableEntry) returnVal.get("symbolTableEntry"); if (symTableEntry != null) { if (symTableEntry instanceof AFunctionEntry) { String msg = "Using function: "+ name.getIdentifier() + " as lvalue."; ASTUtils.error(node, msg); } } } node.getLvalue().accept(this); } } @Override public void visit(IdentifierExpression node) throws ASTVisitorException { System.out.println("-IdentifierExpression"); String name = node.getIdentifier(); //if variable have :: at the front it is "global" if (!node.isLocal()) { ASymTableEntry symTableEntry = _symTable.lookupGlobalScope(name); if (symTableEntry == null) { String msg = "Global variable: " + name + " doesn't exist"; ASTUtils.error(node, msg); } } else { HashMap<String, Object> returnVal = _symTable.lookUpVariable(name, _scope); ASymTableEntry symTableEntry = (ASymTableEntry) returnVal.get("symbolTableEntry"); boolean foundUserFunction = (boolean) returnVal.get("foundUserFunction"); if (symTableEntry == null) { if (!node.isLocal() || this._scope == 0) { symTableEntry = new GlobalVariableEntry(name); } else { symTableEntry = new LocalVariableEntry(name, _scope); } _symTable.insertSymbolTable(symTableEntry); } else { if (foundUserFunction && !symTableEntry.hasGlobalScope() && !(symTableEntry instanceof AFunctionEntry) && (_scope != symTableEntry.getScope())) { String msg = "Cannot access symbol: " + name + " (in scope " + symTableEntry.getScope() + " )."; ASTUtils.error(node, msg); } } } } @Override public void visit(Member node) throws ASTVisitorException { System.out.println("-Member"); if (node.getLvalue() != null) { node.getLvalue().accept(this); } else if (node.getCall() != null) { node.getCall().accept(this); } if (node.getIdentifier() != null) { //System.out.print("." + node.getIdentifier()); } else if (node.getExpression() != null) { node.getExpression().accept(this); } } @Override public void visit(ExtendedCall node) throws ASTVisitorException { System.out.println("-ExtendedCall"); node.getCall().accept(this); node.getExpressionList(); for (Expression expression : node.getExpressionList()) { expression.accept(this); } } @Override public void visit(LvalueCall node) throws ASTVisitorException { System.out.println("-LvalueCall"); node.getLvalue().accept(this); node.getCallSuffix().accept(this); } @Override public void visit(AnonymousFunctionCall node) throws ASTVisitorException { System.out.println("-AnonymousFunctionCall"); node.getFunctionDef().accept(this); for (Expression expression : node.getExpressionList()) { expression.accept(this); } } @Override public void visit(NormCall node) throws ASTVisitorException { System.out.println("-NormCall"); for (Expression expression : node.getExpressionList()) { expression.accept(this); } } @Override public void visit(MethodCall node) throws ASTVisitorException { System.out.println("-MethodCall"); //System.out.print(".." + node.getIdentifier() + "("); for (Expression expression : node.getExpressionList()) { expression.accept(this); } } @Override public void visit(ObjectDefinition node) throws ASTVisitorException { System.out.println("-ObjectDefinition"); enterScopeSpace(); if (!node.getIndexedElementList().isEmpty()) { for (IndexedElement indexed : node.getIndexedElementList()) { indexed.accept(this); } } hideScopeSpaceAndExit(); } @Override public void visit(IndexedElement node) throws ASTVisitorException { System.out.println("-IndexedElement"); node.getExpression1().accept(this); node.getExpression2().accept(this); } @Override public void visit(ArrayDef node) throws ASTVisitorException { System.out.println("-ArrayDef"); if(node.getExpressionList()!=null){ for (Expression expression : node.getExpressionList()) { expression.accept(this); } } } @Override public void visit(Block node) throws ASTVisitorException { System.out.println("-Block"); enterScopeSpace(); for (Statement stmt : node.getStatementList()) { stmt.accept(this); } hideScopeSpaceAndExit(); } @Override public void visit(FunctionDefExpression node) throws ASTVisitorException { System.out.println("-FunctionDefExpression"); node.getFunctionDef().accept(this); } @Override public void visit(FunctionDef node) throws ASTVisitorException { System.out.println("-FunctionDef"); String name = node.getFuncName(); /*Function Name*/ ASymTableEntry symbolTableEntry = _symTable.lookUpLocalScope(name, _scope); boolean isLibraryFunction = LibraryFunctions.isLibraryFunction(name); if (symbolTableEntry != null) { boolean isUserFunction = symbolTableEntry instanceof UserFunctionEntry; String msg; if (isUserFunction) { msg = "Redeclaration of User-Function: " + name + "."; } else if (isLibraryFunction) { msg = "User-Function shadows Library-Function: " + name + "."; } else { 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); } } /*Function arguments*/ enterScopeSpace(); ArrayList<FormalVariableEntry> args = new ArrayList(); for (IdentifierExpression argument : node.getArguments()) { name = argument.getIdentifier(); ASymTableEntry entry = _symTable.lookUpLocalScope(name, _scope); if (entry != null) { String msg = "Redeclaration of Formal-Argument: " + name + "."; ASTUtils.error(node, msg); } if (LibraryFunctions.isLibraryFunction(name)) { String msg = "Formal-Argument shadows Library-Function: " + name + "."; ASTUtils.error(node, msg); } FormalVariableEntry formalArg = new FormalVariableEntry(name, _scope); args.add(formalArg); _symTable.insertSymbolTable(formalArg); } exitScopeSpace(); ASymTableEntry symEntry = new UserFunctionEntry(node.getFuncName(), args, _scope); _symTable.insertSymbolTable(symEntry); enterFunctionSpace(); node.getBody().accept(this); exitFunctionSpace(); } @Override public void visit(IntegerLiteral node) throws ASTVisitorException { System.out.println("-IntegerLiteral"); } @Override public void visit(DoubleLiteral node) throws ASTVisitorException { System.out.println("-DoubleLiteral"); } @Override public void visit(StringLiteral node) throws ASTVisitorException { System.out.println("-StringLiteral"); } @Override public void visit(NullLiteral node) throws ASTVisitorException { System.out.println("-NullLiteral"); } @Override public void visit(TrueLiteral node) throws ASTVisitorException { System.out.println("-TrueLiteral"); } @Override public void visit(FalseLiteral node) throws ASTVisitorException { System.out.println("-FalseLiteral"); } @Override public void visit(IfStatement node) throws ASTVisitorException { System.out.println("-IfStatement"); node.getExpression().accept(this); node.getStatement().accept(this); if (node.getElseStatement() != null) { node.getElseStatement().accept(this); } } @Override public void visit(WhileStatement node) throws ASTVisitorException { System.out.println("-WhileStatement"); node.getExpression().accept(this); enterLoopSpace(); node.getStatement().accept(this); exitLoopSpace(); } @Override public void visit(ForStatement node) throws ASTVisitorException { System.out.println("-ForStatement"); for (Expression expression : node.getExpressionList1()) { expression.accept(this); } node.getExpression().accept(this); for (Expression expression : node.getExpressionList2()) { expression.accept(this); } enterLoopSpace(); node.getStatement().accept(this); exitLoopSpace(); } @Override public void visit(BreakStatement node) throws ASTVisitorException { System.out.println("-BreakStatement"); if( _inLoop == 0) { ASTUtils.error(node, "Use of 'break' while not in a loop."); } } @Override public void visit(ContinueStatement node) throws ASTVisitorException { System.out.println("-ContinueStatement"); if( _inLoop == 0) { ASTUtils.error(node, "Use of 'continue' while not in a loop."); } } @Override public void visit(ReturnStatement node) throws ASTVisitorException { System.out.println("-ReturnStatement"); if( _inFunction == 0) { ASTUtils.error(node, "Use of 'return' while not in a function."); } if(node.getExpression()!=null) node.getExpression().accept(this); } }
package org.qi4j.runtime.entity.association; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import org.qi4j.entity.EntityComposite; import org.qi4j.entity.association.AssociationInfo; import org.qi4j.entity.association.ManyAssociation; import org.qi4j.runtime.entity.UnitOfWorkInstance; import org.qi4j.spi.entity.QualifiedIdentity; /** * TODO */ public class ManyAssociationInstance<T> extends AbstractAssociationInstance<T> implements ManyAssociation<T> { private Collection<QualifiedIdentity> associated; public ManyAssociationInstance( AssociationInfo associationInfo, UnitOfWorkInstance unitOfWork, Collection<QualifiedIdentity> associated ) { super( associationInfo, unitOfWork ); if (associated==null) throw new IllegalArgumentException( "ManyAssociation must be a valid collection, shared with state"); this.associated = associated; } public boolean removeAll( Collection<?> objects ) { return associated.removeAll( getEntityIdCollection( objects ) ); } public boolean isEmpty() { return associated.isEmpty(); } public boolean contains( Object o ) { if( !( o instanceof EntityComposite ) ) { throw new IllegalArgumentException( "Object must be an EntityComposite" ); } return associated.contains( getEntityId( o ) ); } public Object[] toArray() { Object[] ids = associated.toArray(); for( int i = 0; i < ids.length; i++ ) { ids[ i ] = getEntity( (QualifiedIdentity) ids[ i ] ); } return ids; } public <T> T[] toArray( T[] ts ) { QualifiedIdentity[] ids = new QualifiedIdentity[ts.length]; associated.toArray( ids ); for( int i = 0; i < ids.length; i++ ) { QualifiedIdentity id = ids[ i ]; ts[ i ] = (T) getEntity( id ); } return ts; } public boolean add( T t ) { if( !( t instanceof EntityComposite ) ) { throw new IllegalArgumentException( "Associated object must be an EntityComposite" ); } return associated.add( getEntityId( t ) ); } public boolean remove( Object o ) { if( !( o instanceof EntityComposite ) ) { throw new IllegalArgumentException( "Associated object must be an EntityComposite" ); } return associated.remove( getEntityId( o ) ); } public boolean containsAll( Collection<?> objects ) { return associated.containsAll( getEntityIdCollection( objects ) ); } public boolean addAll( Collection<? extends T> ts ) { return associated.addAll( getEntityIdCollection( ts ) ); } public boolean retainAll( Collection<?> objects ) { return associated.retainAll( getEntityIdCollection( objects ) ); } public void clear() { associated.clear(); } public String toString() { return associated.toString(); } public Iterator<T> iterator() { return new ManyAssociationIterator( associated.iterator() ); } public int size() { return associated.size(); } public boolean equals( Object o ) { if( this == o ) { return true; } if( o == null || getClass() != o.getClass() ) { return false; } if( !super.equals( o ) ) { return false; } ManyAssociationInstance that = (ManyAssociationInstance) o; if( !associated.equals( that.associated ) ) { return false; } return true; } public int hashCode() { int result = super.hashCode(); result = 31 * result + associated.hashCode(); return result; } protected Collection<QualifiedIdentity> getEntityIdCollection( Collection ts ) { ArrayList<QualifiedIdentity> list = new ArrayList<QualifiedIdentity>(); for( Object t : ts ) { list.add( getEntityId( t ) ); } return list; } public void refresh( Collection<QualifiedIdentity> newAssociations ) { if (newAssociations==null) throw new IllegalArgumentException( "ManyAssociation must be a valid collection, shared with state"); associated = newAssociations; } protected class ManyAssociationIterator implements Iterator<T> { private final Iterator<QualifiedIdentity> idIterator; public ManyAssociationIterator( Iterator<QualifiedIdentity> idIterator ) { this.idIterator = idIterator; } public boolean hasNext() { return idIterator.hasNext(); } public T next() { return getEntity( idIterator.next() ); } public void remove() { idIterator.remove(); } } }
package com.calculator.aa.ui; import com.calculator.aa.Main; import com.calculator.aa.calc.Calc; import com.calculator.aa.calc.Portfolio; import javax.swing.*; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; import java.awt.*; import java.awt.event.*; import java.util.Arrays; import java.util.Enumeration; import java.util.LinkedList; import java.util.List; import java.util.stream.Collectors; class PortfolioChart extends JDialog { enum Coefficients { NONE, SHARPE, SORTINO } private JPanel contentPane; private JButton buttonOK; private JPanel chartPanel; private JTable tableLimitations; private JButton buttonCompute; private JCheckBox cbFrontierOnly; private JButton buttonAccuracy; private JButton buttonAccuracyMax; private JComboBox<String> comboBoxFrom; private JComboBox<String> comboBoxTo; private JCheckBox cbShowRebalances; private JCheckBox checkBoxCAL; private JSpinner spinnerCAL; private JButton buttonZoomPortfolios; private JButton buttonConvertRate; private JLabel labelRatePeriod; private JRadioButton radioButtonNone; private JRadioButton radioButtonSharpe; private JButton buttonCoefMin; private JPanel panelCoefGradient; private JButton buttonCoefMax; private JRadioButton radioButtonSortino; private JComboBox<String> comboBoxRebalanceMethod; private JSpinner spinnerThreshold; private JLabel labelThreshold; private ButtonGroup coefficientGroup; private final String[] instruments; private final double[][] data; private int indexFrom; private int indexTo; private final PortfolioChartHelper helper; private class LimitationTableCellRenderer extends DefaultTableCellRenderer { private final Color back = new Color(212, 212, 212); @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) { Component cell = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col); cell.setBackground(row == 3 ? back : Color.WHITE); cell.setForeground(Color.BLACK); return cell; } } private class LimitationTableModel extends DefaultTableModel { LimitationTableModel(Object[][] body, Object[] header) { super(body, header); } @Override public boolean isCellEditable(int row, int col) { return row != 3; } } private PortfolioChart(String[] i, double[][] d) { instruments = i; data = d; helper = new PortfolioChartHelper(); helper.setPanel((PortfolioChartPanel)chartPanel); ((PortfolioChartPanel)chartPanel).setHelper(helper); buttonConvertRate.setText(Main.resourceBundle.getString("ui.convert_y_m")); buttonConvertRate.setToolTipText(Main.resourceBundle.getString("ui.convert_y_m_help")); labelRatePeriod.setText(Main.resourceBundle.getString("ui.label_y")); setContentPane(contentPane); setModal(true); getRootPane().setDefaultButton(buttonCompute); buttonOK.addActionListener(e -> onOK()); String[] periods = Main.getPeriods(0, Integer.MAX_VALUE); comboBoxFrom.setModel(new DefaultComboBoxModel<>(Arrays.copyOfRange(periods, 0, periods.length - 2))); comboBoxFrom.setSelectedIndex(0); comboBoxTo.setModel(new DefaultComboBoxModel<>(Arrays.copyOfRange(periods, 2, periods.length))); comboBoxTo.setSelectedIndex(periods.length - 3); spinnerCAL.addMouseWheelListener(new SpinnerWheelListener(spinnerCAL)); spinnerThreshold.addMouseWheelListener(new SpinnerWheelListener(spinnerThreshold)); comboBoxRebalanceMethod.setModel(new DefaultComboBoxModel<>(new String[] { Main.resourceBundle.getString("text.periodical"), Main.resourceBundle.getString("text.threshold"), })); // call onCancel() when cross is clicked setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { onOK(); } }); // call onCancel() on ESCAPE contentPane.registerKeyboardAction(e -> onOK(), KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); buttonCompute.addActionListener(e -> { setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); SwingUtilities.invokeLater(() -> { int length = instruments.length - 1; LimitationTableModel model = (LimitationTableModel) tableLimitations.getModel(); int[] minimals = new int[length]; int[] maximals = new int[length]; int[] compares = new int[length]; for (int col = 0; col < length; col++) { int minValue = Integer.valueOf((String) model.getValueAt(0, col + 1)); int maxValue = Integer.valueOf((String) model.getValueAt(1, col + 1)); if (minValue < 0 || maxValue > 100 || minValue > maxValue) { return; } minimals[col] = minValue; maximals[col] = maxValue; compares[col] = Integer.valueOf((String) model.getValueAt(2, col + 1)); } List<String> periodsList = Arrays.asList(periods); int[] fromIndex = new int[1]; fromIndex[0] = periodsList.indexOf((String) comboBoxFrom.getSelectedItem()); if (fromIndex[0] < 0) { fromIndex[0] = 0; } int[] toIndex = new int[1]; toIndex[0] = periodsList.indexOf((String) comboBoxTo.getSelectedItem()); if (toIndex[0] < 0) { toIndex[0] = data.length - 1; } if (toIndex[0] - fromIndex[0] < 2) { setCursor(Cursor.getDefaultCursor()); return; } double[][] dataFiltered = Calc.filterValidData(data, maximals, fromIndex, toIndex); if (dataFiltered == null) { return; } indexFrom = fromIndex[0]; indexTo = toIndex[0]; double[][] corrTable = Calc.correlationTable(dataFiltered); double[] avYields = new double[length]; double[] sdYields = new double[length]; for (int col = 0; col < length; col++) { double[] column = Calc.column(dataFiltered, col); avYields[col] = Calc.averagePercentYields(column); sdYields[col] = Calc.stdevYields(column); } String[] trueInstr = Arrays.copyOfRange(instruments, 1, instruments.length); int dividers = calculateDivision(Arrays.copyOf(minimals, minimals.length), Arrays.copyOf(maximals, maximals.length), false, 0); if (dividers < 0) { int force = JOptionPane.showConfirmDialog( Main.getFrame(), Main.resourceBundle.getString("text.too_many_computations"), Main.resourceBundle.getString("text.warning"), JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); if (force == JOptionPane.YES_OPTION) { dividers = calculateDivision(Arrays.copyOf(minimals, minimals.length), Arrays.copyOf(maximals, maximals.length), true, -dividers); } else { setCursor(Cursor.getDefaultCursor()); return; } } Calc.RebalanceMode mode = getRebalaceMode(); int threshold = getRebalaceThreshold(); List<Portfolio> portfolios = Calc.iteratePortfolios(corrTable, avYields, sdYields, minimals, maximals, trueInstr, dataFiltered, dividers, mode, threshold); List<Portfolio> portfoliosCompare = null; if (Arrays.stream(compares).sum() == 100) { portfoliosCompare = Calc.iteratePortfolios(corrTable, avYields, sdYields, compares, compares, trueInstr, dataFiltered, 100, mode, threshold); } boolean isSelected = cbShowRebalances.isSelected(); portfolios.forEach(p -> p.setRebalancedMode(isSelected)); if (portfoliosCompare != null) { portfoliosCompare.forEach(p -> p.setRebalancedMode(isSelected)); portfoliosCompare.sort(Portfolio::compareTo); } if (isSelected) { portfolios.sort(Portfolio::compareTo); } updatePortfolios(portfolios, portfoliosCompare, dataFiltered); SwingUtilities.invokeLater(() -> setCursor(Cursor.getDefaultCursor())); }); }); cbFrontierOnly.addActionListener(e -> ((PortfolioChartPanel) chartPanel).setFrontierOnlyMode(cbFrontierOnly.isSelected())); buttonAccuracy.addActionListener(e -> { List<Portfolio> frontier = helper.getFrontierPortfoliosNoFilter(); if (frontier == null || frontier.isEmpty()) { return; } List<Portfolio> accuracyPortfolios = addAccuracy(); if (accuracyPortfolios.isEmpty()) { SwingUtilities.invokeLater(() -> { for(ActionListener a: buttonAccuracy.getActionListeners()) { a.actionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, null)); } }); } }); buttonAccuracyMax.addActionListener(e -> { List<Portfolio> frontier = helper.getFrontierPortfoliosNoFilter(); if (frontier == null || frontier.isEmpty()) { return; } setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); List<Portfolio> accuracyPortfolios = addAccuracy(); List<Portfolio> accuracyPortfolios2 = addAccuracy(); if (!accuracyPortfolios.equals(accuracyPortfolios2) || (accuracyPortfolios.size() == 0 && accuracyPortfolios2.size() == 0)) { SwingUtilities.invokeLater(() -> { for(ActionListener a: buttonAccuracyMax.getActionListeners()) { a.actionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, null)); } }); } else { setCursor(Cursor.getDefaultCursor()); } }); cbShowRebalances.addActionListener(e -> { if (cbShowRebalances.isSelected()) { comboBoxRebalanceMethod.setEnabled(true); boolean isThreshold = comboBoxRebalanceMethod.getSelectedIndex() == 1; labelThreshold.setEnabled(isThreshold); spinnerThreshold.setEnabled(isThreshold); } else { comboBoxRebalanceMethod.setEnabled(false); labelThreshold.setEnabled(false); spinnerThreshold.setEnabled(false); } for(ActionListener a: buttonCompute.getActionListeners()) { a.actionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, null)); } }); checkBoxCAL.addActionListener(actionEvent -> { boolean isSelected = checkBoxCAL.isSelected(); Enumeration<AbstractButton> radios = coefficientGroup.getElements(); while (radios.hasMoreElements()) { AbstractButton radio = radios.nextElement(); radio.setEnabled(isSelected); } buttonZoomPortfolios.setEnabled(isSelected); for(ActionListener a: buttonCompute.getActionListeners()) { a.actionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, null)); } }); buttonZoomPortfolios.addActionListener(actionEvent -> ((PortfolioChartPanel) chartPanel).zoomAllToPortfolios()); buttonConvertRate.addActionListener(e -> { double rate = (double)spinnerCAL.getValue() / 100.0 + 1; if (buttonConvertRate.getText().equals(Main.resourceBundle.getString("ui.convert_y_m"))) { buttonConvertRate.setText(Main.resourceBundle.getString("ui.convert_m_y")); buttonConvertRate.setToolTipText(Main.resourceBundle.getString("ui.convert_m_y_help")); labelRatePeriod.setText(Main.resourceBundle.getString("ui.label_m")); rate = Math.pow(rate, 1.0 / 12.0); } else { buttonConvertRate.setText(Main.resourceBundle.getString("ui.convert_y_m")); buttonConvertRate.setToolTipText(Main.resourceBundle.getString("ui.convert_y_m_help")); labelRatePeriod.setText(Main.resourceBundle.getString("ui.label_y")); rate = Math.pow(rate, 12); } spinnerCAL.setValue((rate - 1) * 100); if (checkBoxCAL.isSelected()) { for (ActionListener a : buttonCompute.getActionListeners()) { a.actionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, null)); } } }); radioButtonNone.addActionListener(e -> { if (radioButtonNone.isSelected()) { ((GradientSliderPanel)panelCoefGradient).resetPosition(); setCoefficientVisible(helper.getPortfolios()); } }); radioButtonSharpe.addActionListener(e -> { if (radioButtonSharpe.isSelected()) { ((GradientSliderPanel)panelCoefGradient).resetPosition(); setCoefficientVisible(helper.getPortfolios()); } }); radioButtonSortino.addActionListener(actionEvent -> { if (radioButtonSortino.isSelected()) { ((GradientSliderPanel)panelCoefGradient).resetPosition(); setCoefficientVisible(helper.getPortfolios()); } }); buttonCoefMin.addActionListener(actionEvent -> ((GradientSliderPanel)panelCoefGradient).setPosition(0)); buttonCoefMax.addActionListener(actionEvent -> ((GradientSliderPanel)panelCoefGradient).setPosition(0.99)); comboBoxRebalanceMethod.addActionListener(actionEvent -> { int selected = comboBoxRebalanceMethod.getSelectedIndex(); boolean isThreshold = selected == 1; labelThreshold.setEnabled(isThreshold); spinnerThreshold.setEnabled(isThreshold); }); } private int calculateDivision(int[] minimals, int[] maximals, boolean force, int start) { int[] variants = new int[] {100, 50, 25, 20, 10, 5, 4, 2, 1}; int length = variants.length; int checkLen = minimals.length; int limit = 50000; int[] sum = new int[1]; int nonEmpty = 0; for (int i = 0; i < checkLen; i++) { if (maximals[i] - minimals[i] > 0) { nonEmpty += 1; } } int lastNotZero = start; int result; if (nonEmpty >= 10) { result = 100 / variants[3]; if (checkModulo(minimals, maximals, result)) { return result; } else if (!force) { return -1; } } for (int i = start; i < length; i++) { sum[0] = 0; if (i == length - 1 && nonEmpty > 5) { result = 100 / variants[lastNotZero]; if (checkModulo(minimals, maximals, result)) { return result; } else if (!force) { return -(lastNotZero + 1); } } calculateDivisionHelper( Arrays.copyOf(minimals, minimals.length), Arrays.copyOf(maximals, maximals.length), Arrays.copyOf(minimals, minimals.length), 0, variants[i], sum ); if (sum[0] > limit) { int index = lastNotZero >= 0 ? lastNotZero : i; result = 100 / variants[index]; if (checkModulo(minimals, maximals, result)) { return result; } else if (!force) { return -(index + 1); } } if (sum[0] != 0) { lastNotZero = i; } } return 100; } // todo: optimize this shit! private void calculateDivisionHelper(int[] minimals, int[] maximals, int[] weights, int index, int step, int[] sum) { int l1 = weights.length - 1; while (weights[index] <= maximals[index]) { // clear tail System.arraycopy(minimals, index + 1, weights, index + 1, weights.length - (index + 1)); int testSum = Calc.sumIntArray(weights); if (testSum > 100) { break; } if (testSum == 100) { sum[0] += 1; } if (index < l1 && testSum < 100) { calculateDivisionHelper(minimals, maximals, weights, index + 1, step, sum); } weights[index] += step; } } private boolean checkModulo(int[] minimals, int[] maximals, int divider) { int step = 100 / divider; return Arrays.stream(minimals).allMatch(i -> i % step == 0) && Arrays.stream(maximals).allMatch(i -> i % step == 0); } private void onOK() { Rectangle bounds = getBounds(); Main.properties.setProperty("portfolio.x", String.valueOf((int)bounds.getX())); Main.properties.setProperty("portfolio.y", String.valueOf((int)bounds.getY())); Main.properties.setProperty("portfolio.w", String.valueOf((int)bounds.getWidth())); Main.properties.setProperty("portfolio.h", String.valueOf((int)bounds.getHeight())); dispose(); } private void updateLimitations() { int length = instruments.length; String[][] limits = new String[4][length]; for (int col = 0; col < length; col++) { limits[0][col] = col == 0 ? Main.resourceBundle.getString("text.min") : "0"; limits[1][col] = col == 0 ? Main.resourceBundle.getString("text.max") : "100"; limits[2][col] = col == 0 ? Main.resourceBundle.getString("text.compare") : "0"; limits[3][col] = col == 0 ? Main.resourceBundle.getString("text.nearest") : getNearestComponent(col - 1); } tableLimitations.setModel(new LimitationTableModel(limits, instruments)); for (int i = 0; i < length; i++) { tableLimitations.getColumnModel().getColumn(i).setCellRenderer(new LimitationTableCellRenderer()); } } void updateNearestWeights() { int length = instruments.length; LimitationTableModel model = (LimitationTableModel)tableLimitations.getModel(); for (int col = 1; col < length; col++) { model.setValueAt(getNearestComponent(col -1), 3, col); } } private String getNearestComponent(int component) { Portfolio pf = helper.getNearest(); if (pf == null) { return "0"; } return Integer.toString((int)(pf.weights()[component] * 100)); } private void createUIComponents() { chartPanel = new PortfolioChartPanel(); comboBoxFrom = new JComboBox<>(); comboBoxTo = new JComboBox<>(); spinnerCAL = new JSpinner(new SpinnerNumberModel(1.0, 0.0, 100.0, 0.1)); spinnerThreshold = new JSpinner(new SpinnerNumberModel(1, 1, 100, 1)); panelCoefGradient = new GradientSliderPanel(false, new AbstractAction() { @Override public void actionPerformed(ActionEvent actionEvent) { double filtered = ((GradientSliderPanel)panelCoefGradient).getPosition(); helper.setMinCoefficient(filtered); ((PortfolioChartPanel) chartPanel).repaintAll(); } }); ((GradientSliderPanel)panelCoefGradient).setColors( Main.gradient.getPointColor(GradientPainter.ColorName.Begin), Main.gradient.getPointColor(GradientPainter.ColorName.Middle), Main.gradient.getPointColor(GradientPainter.ColorName.End) ); } private List<Portfolio> addAccuracy() { List<Portfolio> frontier = helper.getFrontierPortfoliosNoFilter(); List<Portfolio> accuracyPortfolios = new LinkedList<>(); if (frontier == null || frontier.isEmpty()) { return accuracyPortfolios; } int length = instruments.length - 1; double[][] dataFiltered = helper.getDataFiltered(); double[][] corrTable = Calc.correlationTable(dataFiltered); double[] avYields = new double[length]; double[] sdYields = new double[length]; for (int col = 0; col < length; col++) { double[] column = Calc.column(dataFiltered, col); avYields[col] = Calc.averagePercentYields(column); sdYields[col] = Calc.stdevYields(column); } String[] trueInstr = Arrays.copyOfRange(instruments, 1, instruments.length); int dividers = 100; LimitationTableModel model = (LimitationTableModel)tableLimitations.getModel(); int[] userMinimals = new int[length]; int[] userMaximals = new int[length]; int[] compares = new int[length]; for (int col = 0; col < length; col++) { int minValue = Integer.valueOf((String) model.getValueAt(0, col + 1)); int maxValue = Integer.valueOf((String) model.getValueAt(1, col + 1)); if (minValue < 0 || maxValue > 100 || minValue > maxValue) { return accuracyPortfolios; } userMinimals[col] = minValue; userMaximals[col] = maxValue; compares[col] = Integer.valueOf((String) model.getValueAt(2, col + 1)); } Calc.RebalanceMode mode = getRebalaceMode(); int threshold = getRebalaceThreshold(); int index = 0; int size = frontier.size(); while (index < size) { Portfolio first = frontier.get(index); Portfolio next = index < size - 1 ? frontier.get(index + 1) : first; int[] minimals = new int[length]; int[] maximals = new int[length]; for (int col = 0; col < length; col++) { minimals[col] = Math.min((int)(first.weights()[col] * 100), (int)(next.weights()[col] * 100)) - 100 / dividers; if (minimals[col] < 0) { minimals[col] = 0; } maximals[col] = Math.max((int)(first.weights()[col] * 100), (int)(next.weights()[col] * 100)) + 100 / dividers; if (maximals[col] > 100) { maximals[col] = 100; } if (minimals[col] < userMinimals[col]) { minimals[col] = userMinimals[col]; } if (maximals[col] > userMaximals[col]) { maximals[col] = userMaximals[col]; } } accuracyPortfolios.addAll( Calc.iteratePortfolios(corrTable, avYields, sdYields, minimals, maximals, trueInstr, dataFiltered, dividers, mode, threshold) ); index += 1; } List<Portfolio> portfoliosCompare = null; if (Arrays.stream(compares).sum() == 100) { portfoliosCompare = Calc.iteratePortfolios(corrTable, avYields, sdYields, compares, compares, trueInstr, dataFiltered, 100, mode, threshold); } boolean isSelected = cbShowRebalances.isSelected(); accuracyPortfolios.forEach(p -> p.setRebalancedMode(isSelected)); if (portfoliosCompare != null) { portfoliosCompare.forEach(p -> p.setRebalancedMode(isSelected)); } accuracyPortfolios.sort(Portfolio::compareTo); updatePortfolios(accuracyPortfolios, portfoliosCompare, dataFiltered); return accuracyPortfolios; } private void updatePortfolios(List<Portfolio> pfs, List<Portfolio> pfsComp, double[][] df) { setCoefficientVisible(pfs); helper.setRebalanceMode(getRebalaceMode(), getRebalaceThreshold()); helper.setPortfolios(pfs, pfsComp, df, Main.getPeriods(indexFrom, indexTo), checkBoxCAL.isSelected() ? (double)spinnerCAL.getValue() / 100.0 : -1 ); } void setPortfolioToCompare(int[] weights) { LimitationTableModel model = (LimitationTableModel)tableLimitations.getModel(); int length = weights.length; for (int i = 0; i < length; i++) { model.setValueAt(String.valueOf(weights[i]), 2, i + 1); } } private void setCoefficientVisible(List<Portfolio> pfs) { Coefficients coefficient = Coefficients.NONE; if (radioButtonSharpe.isEnabled() && radioButtonSharpe.isSelected()) { coefficient = Coefficients.SHARPE; } if (radioButtonSortino.isEnabled() && radioButtonSortino.isSelected()) { coefficient = Coefficients.SORTINO; } if (coefficient == Coefficients.NONE) { pfs.forEach(p -> p.setCoefficient(Double.NaN)); buttonCoefMin.setText("0"); buttonCoefMin.setEnabled(false); buttonCoefMax.setText("0"); buttonCoefMax.setEnabled(false); ((GradientPanel)panelCoefGradient).setGradientEnabled(false); } double minCoef; double maxCoef; double dCoef; double rate = ((double)spinnerCAL.getValue()) / 100.0; Calc.RebalanceMode mode = getRebalaceMode(); int threshold = getRebalaceThreshold(); List<Double> coefList = null; if (coefficient == Coefficients.SHARPE) { coefList = pfs.stream() .map(p -> Calc.ratioSharpe(p, rate, mode, threshold)) .collect(Collectors.toList()); } else if (coefficient == Coefficients.SORTINO) { coefList = pfs.stream() .map(p -> Calc.ratioSortino(p, rate, mode, threshold)) .collect(Collectors.toList()); } if (coefList != null) { minCoef = coefList.stream().mapToDouble(d -> d).min().orElse(0); maxCoef = coefList.stream().mapToDouble(d -> d).max().orElse(1); dCoef = maxCoef - minCoef; if (Math.abs(dCoef) < Calc.epsilon) { dCoef = Calc.epsilon; } int length = pfs.size(); for (int i = 0; i < length; i++) { pfs.get(i).setCoefficient((coefList.get(i) - minCoef) / dCoef); } buttonCoefMin.setText(Calc.formatDouble2(minCoef)); buttonCoefMin.setEnabled(true); buttonCoefMax.setText(Calc.formatDouble2(maxCoef)); buttonCoefMax.setEnabled(true); ((GradientPanel) panelCoefGradient).setGradientEnabled(true); ((GradientSliderPanel) panelCoefGradient).setGradientBounds(minCoef, maxCoef); } ((PortfolioChartPanel) chartPanel).repaintAll(); } private Calc.RebalanceMode getRebalaceMode() { return comboBoxRebalanceMethod.getSelectedIndex() == 0 ? Calc.RebalanceMode.PERIODIC : Calc.RebalanceMode.THRESHOLD; } private int getRebalaceThreshold() { return (int)spinnerThreshold.getValue(); } static void showChart(String[] instruments, double[][] data) { PortfolioChart dialog = new PortfolioChart(instruments, data); dialog.updateLimitations(); dialog.setTitle(Main.resourceBundle.getString("text.portfolios")); dialog.setLocationRelativeTo(Main.getFrame()); dialog.pack(); int x = Calc.safeParseInt(Main.properties.getProperty("portfolio.x", "-1"), -1); int y = Calc.safeParseInt(Main.properties.getProperty("portfolio.y", "-1"), -1); int w = Calc.safeParseInt(Main.properties.getProperty("portfolio.w", "-1"), -1); int h = Calc.safeParseInt(Main.properties.getProperty("portfolio.h", "-1"), -1); if (x >= 0 && y >= 0 && w >= 0 && h >= 0) { Rectangle rec = new Rectangle(x, y, w, h); dialog.setBounds(rec); } SwingUtilities.invokeLater(() -> { for(ActionListener a: dialog.buttonCompute.getActionListeners()) { a.actionPerformed(new ActionEvent(dialog, ActionEvent.ACTION_PERFORMED, null)); } }); dialog.setVisible(true); } }
package org.spoofax.interpreter.library.language.spxlang; import static org.spoofax.interpreter.core.Tools.asJavaString; import java.io.File; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.spoofax.interpreter.core.Tools; import org.spoofax.interpreter.library.IOAgent; import org.spoofax.interpreter.terms.IStrategoAppl; import org.spoofax.interpreter.terms.IStrategoConstructor; import org.spoofax.interpreter.terms.IStrategoList; import org.spoofax.interpreter.terms.IStrategoString; import org.spoofax.interpreter.terms.IStrategoTerm; import org.spoofax.interpreter.terms.IStrategoTuple; import org.spoofax.interpreter.terms.ITermFactory; import org.spoofax.interpreter.terms.TermConverter; import org.spoofax.jsglr.client.imploder.ImploderAttachment; import org.spoofax.terms.attachments.TermAttachmentSerializer; import org.spoofax.terms.attachments.TermAttachmentStripper; public class SpxSemanticIndexFacade { //TODO : refactor this class to multiple facades one for package, one for modules //TODO FIXME : combine symbol table and index private final ISpxPersistenceManager _persistenceManager; private final String _projectName ; private final ITermFactory _termFactory; private final IOAgent _agent; private final TermAttachmentStripper _stripper; private final TermAttachmentSerializer _termAttachmentSerializer; private final TermConverter _converter; private static final String All = "*"; private static final String CURRENT = "."; public TermAttachmentSerializer getTermAttachmentSerializer() {return _termAttachmentSerializer;} /** * Initializes the SemanticIndexFactory * @param projectName name of the project * @param termFactory {@link ITermFactory} * @param agent {@link IOAgent} * @throws IOException throws {@link IOException} from underlying {@link SpxPersistenceManager} */ public SpxSemanticIndexFacade(IStrategoTerm projectName , ITermFactory termFactory , IOAgent agent) throws IOException { _projectName = asJavaString(projectName); _termFactory = termFactory; _agent = agent; _stripper = new TermAttachmentStripper(_termFactory); _converter = new TermConverter(_termFactory); _converter.setOriginEnabled(true); _termAttachmentSerializer = new TermAttachmentSerializer(_termFactory); _knownCons = new HashMap<ConstructorDef ,IStrategoConstructor>(); initKnownConstructors(); _persistenceManager = new SpxPersistenceManager(this); _persistenceManager.initializeSymbolTables(this._projectName, this); } /** * Returns the TermFactory * @return */ public ITermFactory getTermFactory() { return _termFactory; } public TermConverter getTermConverter() {return _converter ; } /** * Gets the project name as String * @return */ public String getProjectNameString(){ return _projectName; } /** * Get ProjectName as IStrategoTerm * * @return IStrategoTerm */ public IStrategoTerm getProjectName(){ return _termFactory.makeString(_projectName);} /** * Returns an instance of the Persistence Manager active for the current Facade * @return */ public ISpxPersistenceManager persistenceManager(){ return _persistenceManager; } /** * Returns CompilationUnit located in {@code spxCompilationUnitPath} as {@link IStrategoTerm} * * @param spxCompilationUnitPath Location to the CompilationUnit * @return {@link IStrategoTerm} */ public IStrategoTerm getCompilationUnit(IStrategoString spxCompilationUnitPath){ IStrategoAppl retTerm = null; URI resUri = toFileURI(spxCompilationUnitPath); logMessage("SpxSemanticIndexFacade.getCompilationUnit . Arguments : " + spxCompilationUnitPath); SpxCompilationUnitTable table = _persistenceManager.spxCompilcationUnitTable(); IStrategoAppl term = (IStrategoAppl)table.get(resUri); if ( term != null) retTerm = forceImploderAttachment(term, resUri); logMessage("SpxSemanticIndexFacade.getCompilationUnit : Returning Following APPL for uri " + resUri + " : "+ retTerm); return retTerm; } /** * Removes CompilationUnit located in {@code spxCompilationUnitPath} file path. * * @param spxCompilationUnitPath file path * @throws IOException */ public void removeCompilationUnit( IStrategoString spxCompilationUnitPath ) throws IOException{ URI resUri = toFileURI(spxCompilationUnitPath); SpxCompilationUnitTable table = _persistenceManager.spxCompilcationUnitTable(); table.remove(resUri); } /** * Indexes CompilationUnit in the symbol table. * * @param spxCompilationUnitPath path of the SpxCompilation Unit. It can be a relative path ( relative to project) or absolute path. * @param spxCompilationUnitAST SPXCompilationUnit AST * @throws IOException */ public void indexCompilationUnit( IStrategoString spxCompilationUnitPath, IStrategoAppl spxCompilationUnitAST) throws IOException { URI resUri = toFileURI(spxCompilationUnitPath); // Converting IStrategoString to File URI IStrategoTerm astTerm = toCompactPositionInfo(spxCompilationUnitAST); SpxCompilationUnitTable table = _persistenceManager.spxCompilcationUnitTable(); logMessage("Storing following compilation unit. Path : [" + spxCompilationUnitPath +"]" + " AST: "+ spxCompilationUnitAST ); table.define(resUri, astTerm); } public void indexModuleDefinition(IStrategoAppl moduleDefinition) throws IllegalArgumentException { verifyConstructor(moduleDefinition.getConstructor() , getModuleDefCon() , "Illegal Module Definition" ); indexModuleDefinition( (IStrategoAppl) moduleDefinition.getSubterm(ModuleDeclaration.ModuleTypedQNameIndex), (IStrategoString) moduleDefinition.getSubterm(ModuleDeclaration.ModulePathIndex), (IStrategoAppl) moduleDefinition.getSubterm(ModuleDeclaration.PackageTypedQNameIndex), (IStrategoAppl) moduleDefinition.getSubterm(ModuleDeclaration.AstIndex), (IStrategoAppl) moduleDefinition.getSubterm(ModuleDeclaration.AnalyzedAstIndex)); } /** * Indexes Module Definition, e.g. ModuleDef : Module * String * Package * Term * Term -> Def * * @param moduleQName * @param spxCompilationUnitPath * @param packageQName * @param ast * @param analyzedAst */ public void indexModuleDefinition(IStrategoAppl moduleQName, IStrategoString spxCompilationUnitPath, IStrategoAppl packageQName, IStrategoAppl ast, IStrategoAppl analyzedAst) { SpxModuleLookupTable table = _persistenceManager.spxModuleTable(); IStrategoList moduleId = ModuleDeclaration.getModuleId( this, moduleQName); IStrategoList packageId = PackageDeclaration.getPackageId(this, packageQName); _persistenceManager.spxPackageTable().verifyPackageIDExists(packageId) ; moduleId = (IStrategoList) toCompactPositionInfo(moduleId); packageId = (IStrategoList) toCompactPositionInfo(packageId); ast = (IStrategoAppl) ast; analyzedAst = (IStrategoAppl)analyzedAst; spxCompilationUnitPath = (IStrategoString) spxCompilationUnitPath; ModuleDeclaration mDecl = new ModuleDeclaration(toAbsulatePath(spxCompilationUnitPath), moduleId, packageId); // updating/adding module to index table.define(mDecl , ast, analyzedAst); //Defining ModuleNamespace for Symbol-Table defineNamespace(mDecl); } /** * Stores PackageDeclaration in Symbol Table * * @param packageDeclaration */ public void indexPackageDeclaration(IStrategoAppl packageDeclaration){ verifyConstructor( packageDeclaration.getConstructor(), getPackageDeclCon(), "Illegal PackageDeclaration"); indexPackageDeclaration( (IStrategoAppl) packageDeclaration.getSubterm(PackageDeclaration.PACKAGE_ID_INDEX), // package id (IStrategoString)packageDeclaration.getSubterm(PackageDeclaration.SPX_COMPILATION_UNIT_PATH) // package location absolute path ); } /** * Indexes {@link PackageDeclaration} * * @param packageIdAppl * @param spxCompilationUnitPath */ public void indexPackageDeclaration(IStrategoAppl packageIdAppl, IStrategoString spxCompilationUnitPath){ SpxPackageLookupTable table = _persistenceManager.spxPackageTable(); SpxCompilationUnitTable spxTable = _persistenceManager.spxCompilcationUnitTable(); IStrategoList packageId = PackageDeclaration.getPackageId(this, packageIdAppl); //verify valid package URI. Checking whether compilation unit exist with this URI // in compilation unit table. spxCompilationUnitPath = (IStrategoString)toCompactPositionInfo((IStrategoTerm)spxCompilationUnitPath); String absFilePath = toAbsulatePath(spxCompilationUnitPath); spxTable.verifyUriExists(absFilePath); packageId = (IStrategoList)toCompactPositionInfo((IStrategoTerm)packageId); if(table.containsPackage(packageId)){ // Package is already there in the index. Hence,just adding the Uri where // this package declaration is found. table.addPackageDeclarationLocation(packageId,absFilePath); }else{ // Defining PackageDeclaration in the Index PackageDeclaration pDecl = new PackageDeclaration(absFilePath,packageId); table.definePackageDeclaration(pDecl); defineNamespace(pDecl); } } public IStrategoTerm insertNewScope(IStrategoAppl namespaceAppl) throws SpxSymbolTableException { IStrategoList parentId = getNamespaceId(namespaceAppl); SpxPrimarySymbolTable symbolTable = persistenceManager().spxSymbolTable(); INamespace ns = symbolTable.newAnonymousNamespace(this, parentId); return this.getTermFactory().makeAppl(getLocalNamespaceTypeCon(), ns.namespaceUri().id()); } public IStrategoTerm destroyScope(IStrategoAppl namespaceAppl) throws SpxSymbolTableException { IStrategoList id = getNamespaceId(namespaceAppl); SpxPrimarySymbolTable symbolTable = persistenceManager().spxSymbolTable(); INamespace ns = symbolTable.destroyNamespace(this, id); return this.getTermFactory().makeAppl(getLocalNamespaceTypeCon(), ns.namespaceUri().id()); } // SymbolDef : namespace * id * type * value -> Def public void indexSymbol(IStrategoAppl symbolDefinition) throws SpxSymbolTableException, IOException{ final int NAMESPACE_ID_INDEX = 0; verifyConstructor(symbolDefinition.getConstructor(), getSymbolTableEntryDefCon(), "Illegal SymbolDefinition argument"); IStrategoConstructor typeCtor = null; try{ typeCtor = verifyKnownContructorExists((IStrategoAppl)symbolDefinition.getSubterm(SpxSymbolTableEntry.TYPE_INDEX)); }catch(IllegalArgumentException ex){ // It seems like the constructor does not exist in local type declarations. // Hence, defining it to be used further. IStrategoConstructor ctor = ((IStrategoAppl)symbolDefinition.getSubterm(SpxSymbolTableEntry.TYPE_INDEX)).getConstructor(); typeCtor = ConstructorDef.newInstance(ctor.getName() , ctor.getArity()).index(_knownCons, ctor); } // Constructing Spx Symbol-Table Entry from the provided symbolDefinition argument. // Note: TermAttachment or Annotation are stripped from the ID Term since, in symbol-table, term attachments // is not require and will make the equals operation a bit complicated. SpxSymbolTableEntry entry = SpxSymbolTableEntry.newEntry() .with( strip(symbolDefinition.getSubterm(SpxSymbolTableEntry.SYMBOL_ID_INDEX)) ) .instanceOf(typeCtor) .uses(this._termAttachmentSerializer) .data(symbolDefinition.getSubterm(SpxSymbolTableEntry.DATA_INDEX)) .build(); SpxPrimarySymbolTable symbolTable = persistenceManager().spxSymbolTable(); symbolTable.defineSymbol(this, getNamespaceId((IStrategoAppl)symbolDefinition.getSubterm(NAMESPACE_ID_INDEX)), entry); } // (namespace * idTolookupFor * type constructor) public IStrategoTerm resolveSymbols(IStrategoTuple searchCriteria) throws SpxSymbolTableException{ if (searchCriteria.getSubtermCount() != 4) throw new IllegalArgumentException(" Illegal symbolLookupTerm Argument ; expected 3 subterms. Found : " + searchCriteria.getSubtermCount()); String searchMode = asJavaString(searchCriteria.get(3)).trim(); IStrategoConstructor typeCtor = verifyKnownContructorExists((IStrategoAppl)searchCriteria.getSubterm(2)); Iterable<SpxSymbol> spxSymbols = null; if(searchMode.equalsIgnoreCase(All)) { spxSymbols = resolveSymbols( (IStrategoAppl)searchCriteria.get(0), searchCriteria.get(1), typeCtor); }else if(searchMode.equalsIgnoreCase(CURRENT)){ spxSymbols = resolveSymbol( (IStrategoAppl)searchCriteria.get(0), searchCriteria.get(1), typeCtor); } else{ throw new IllegalArgumentException(" Illegal symbolLookupTerm searchMode Argument ; expected * or . . Found : " + searchMode); } return SpxSymbol.toTerms(this, spxSymbols); } /** * Resolves symbols from {@link SpxPrimarySymbolTable}. * * @param namespaceToStartSearchWith Starts search from this namespace. * @param symbolId symbol Id to resolve * @param symbolType Type of Symbols to look for * * @return {@link IStrategoList} representation of resolved {@code symbols} * * @throws SpxSymbolTableException */ public Iterable<SpxSymbol> resolveSymbols(IStrategoAppl namespaceToStartSearchWith, IStrategoTerm symbolId, IStrategoConstructor symbolType) throws SpxSymbolTableException { IStrategoList namespaceID = this.getNamespaceId(namespaceToStartSearchWith); SpxPrimarySymbolTable symbolTable = persistenceManager().spxSymbolTable(); Iterable<SpxSymbol> resolvedSymbols = symbolTable.resolveSymbols(this, namespaceID, strip(symbolId), symbolType); return resolvedSymbols; } public Iterable<SpxSymbol> resolveSymbol(IStrategoAppl namespaceToStartSearchWith, IStrategoTerm symbolId, IStrategoConstructor symbolType) throws SpxSymbolTableException { List<SpxSymbol> resolvedSymbols= new ArrayList<SpxSymbol>(); IStrategoList namespaceID = this.getNamespaceId(namespaceToStartSearchWith); SpxPrimarySymbolTable symbolTable = persistenceManager().spxSymbolTable(); SpxSymbol sym = symbolTable.resolveSymbol(this, namespaceID, strip(symbolId), symbolType); if(sym != null) resolvedSymbols.add(sym) ; return resolvedSymbols; } private IStrategoConstructor verifyKnownContructorExists(IStrategoAppl symbolType) throws IllegalArgumentException { IStrategoConstructor typeCtor = getConstructor( symbolType.getConstructor().getName(), symbolType.getConstructor().getArity()) ; if(typeCtor == null) { throw new IllegalArgumentException("Illegal Argument . Unknown Symbol Type. Found " + symbolType.getConstructor()); } return typeCtor; } /** * @param namespaceTypedQname * @return * @throws SpxSymbolTableException */ private IStrategoList getNamespaceId(IStrategoAppl namespaceTypedQname) throws SpxSymbolTableException { IStrategoList namespaceId; if (namespaceTypedQname.getConstructor() == getModuleQNameCon() || namespaceTypedQname.getConstructor() == getPackageQNameCon()) { namespaceId = IdentifiableConstruct.getID(this, (IStrategoAppl) namespaceTypedQname.getSubterm(0)); } else if (namespaceTypedQname.getConstructor() == getGlobalNamespaceTypeCon()) { namespaceId = GlobalNamespace.getGlobalNamespaceId(this); } else if ( namespaceTypedQname.getConstructor() == getLocalNamespaceTypeCon()){ namespaceId = LocalNamespace.getLocalNamespaceId(namespaceTypedQname.getSubterm(0)); } else throw new SpxSymbolTableException("Unknown namespace uri : " + namespaceTypedQname); return namespaceId; } /** * Indexes LanguageDescriptor for a particular Package specified in {@code langaugeDescriptor} * * @param languageDescriptor */ public void indexLanguageDescriptor (IStrategoAppl languageDescriptor) { verifyConstructor(languageDescriptor.getConstructor(), getLanguageDescriptorCon(), "Invalid LanguageDescriptor argument : "+ languageDescriptor.toString()); IStrategoList qualifiedPackageId = PackageDeclaration.getPackageId(this, (IStrategoAppl)languageDescriptor.getSubterm(0)) ; SpxPackageLookupTable table = _persistenceManager.spxPackageTable(); table.verifyPackageIDExists(qualifiedPackageId) ; //FIXME : move the following logic to extract information and //construct instance in respective classes . e.g. in LanguageDesrciptor class qualifiedPackageId = (IStrategoList)toCompactPositionInfo((IStrategoTerm)qualifiedPackageId); IStrategoList lNames = (IStrategoList) this.strip(languageDescriptor.getSubterm(LanguageDescriptor.LanguageNamesIndex)); IStrategoList lIds = (IStrategoList) this.strip(languageDescriptor.getSubterm(LanguageDescriptor.LanguageIdsIndex)); IStrategoList lEsvStartSymbols = (IStrategoList) this.strip(languageDescriptor.getSubterm(LanguageDescriptor.EsvStartSymbolsIndex)); IStrategoList lSdfStartSymbols = (IStrategoList) this.strip(languageDescriptor.getSubterm(LanguageDescriptor.SdfStartSymbolsIndex)); LanguageDescriptor current = table.getLangaugeDescriptor(qualifiedPackageId); if( current != null){ current.addEsvDeclaredStartSymbols(this.getTermFactory(), lEsvStartSymbols); current.addSDFDeclaredStartSymbols(this.getTermFactory(), lSdfStartSymbols ); current.addLanguageIDs(this.getTermFactory(), lIds); current.addLanguageNames(this.getTermFactory(), lNames); } else current = LanguageDescriptor.newInstance(this.getTermFactory() , qualifiedPackageId , lIds, lNames,lSdfStartSymbols , lEsvStartSymbols); table.defineLanguageDescriptor(qualifiedPackageId, current); } /** * @param importReferences */ public void indexImportReferences(IStrategoAppl importReferences) throws SpxSymbolTableException{ IStrategoAppl namespaceId = (IStrategoAppl) importReferences.getSubterm(0); IStrategoList imports = (IStrategoList) importReferences.getSubterm(1); IStrategoList packageId; if (namespaceId.getConstructor() == getModuleQNameCon()) { packageId = persistenceManager() .spxModuleTable() .packageId(ModuleDeclaration.getModuleId(this, namespaceId)); } else if (namespaceId.getConstructor() == getPackageQNameCon()) { packageId = PackageDeclaration.getPackageId(this, namespaceId); } else throw new IllegalArgumentException("Unknown Namespace " + namespaceId.toString()); PackageDeclaration packageDeclaration= this.lookupPackageDecl(packageId); packageDeclaration.addImportRefernces(this, imports); persistenceManager().spxPackageTable().definePackageDeclaration(packageDeclaration); } /** * @param mDecl */ private void defineNamespace(INamespaceFactory nsFactory) { SpxPrimarySymbolTable symTable = this.persistenceManager().spxSymbolTable(); for( INamespace ns : nsFactory.newNamespaces(this) ) { symTable.defineNamespace(ns) ; } } /** * Returning all the import reference of the current package / module construct. Package/ Module * are the scoped symbol for the current implementation of the spoofaxlang. Whenever * looking for a import reference of a module, it returns the import refernece of it enclosing * namespace , i.e. package. * * Currently this lookup is hard-coded . Later , plan is to move to more generic and dynamic * lookup environment. * * @param namespaceId * @return {@link IStrategoTerm} * @throws SpxSymbolTableException */ public IStrategoTerm getImportReferences(IStrategoAppl namespaceId) throws SpxSymbolTableException { IdentifiableConstruct ns; if (namespaceId.getConstructor() == getModuleQNameCon()) { IStrategoList packageId = persistenceManager() .spxModuleTable() .packageId(ModuleDeclaration.getModuleId(this, namespaceId)); ns = lookupPackageDecl(packageId); } else if (namespaceId.getConstructor() == getPackageQNameCon()) { ns = this.lookupPackageDecl(namespaceId); } else throw new IllegalArgumentException("Unknown Namespace " + namespaceId.toString()); return ns.getImports(this); } /** * Returns the package declaration indexed with {@code packageIdAppl} typed qualified name. * * @param packageTypedQName * @return * @throws Exception */ public IStrategoTerm getPackageDeclaration(IStrategoAppl packageTypedQName) throws SpxSymbolTableException { PackageDeclaration decl = lookupPackageDecl(packageTypedQName); return decl.toTerm(this); } public PackageDeclaration lookupPackageDecl(IStrategoAppl packageTypedQName) throws SpxSymbolTableException { IStrategoList packageId = PackageDeclaration.getPackageId(this, packageTypedQName); return lookupPackageDecl(packageId); } public IStrategoList getPackageDeclarations(IStrategoString filePath) { logMessage("getPackageDeclarationsByUri | Arguments : " + filePath); SpxPackageLookupTable table = persistenceManager().spxPackageTable(); String filepathString = asJavaString(filePath); Iterable<PackageDeclaration> decls; if(All == filepathString) { decls = table.getPackageDeclarations(); //returning all the package declarations found in the current project }else{ String absFilePath = toAbsulatePath(filePath); table.verifyUriExists(absFilePath); // verifying file path exists decls = table.packageDeclarationsByUri(absFilePath); } IStrategoList result = Utils.toTerm(this, decls); logMessage("getPackageDeclarationsByUri | Returning IStrategoList : " + result ); return result; } public IStrategoTerm getModuleDeclaration(IStrategoAppl moduleTypeQName) throws IllegalArgumentException, SpxSymbolTableException { ModuleDeclaration decl = lookupModuleDecl(moduleTypeQName); return decl.toTerm(this); } /** * @param moduleTypeQName * @return * @throws SpxSymbolTableException */ public ModuleDeclaration lookupModuleDecl(IStrategoAppl moduleTypeQName) throws SpxSymbolTableException { SpxModuleLookupTable table = persistenceManager().spxModuleTable(); IStrategoList moduleId = ModuleDeclaration.getModuleId(this, moduleTypeQName); ModuleDeclaration decl = table.getModuleDeclaration(moduleId); if (decl == null) throw new SpxSymbolTableException( "Unknown Module Id "+ moduleTypeQName.toString()); return decl; } /** * Returns the {@link IStrategoTerm} representation of the list of {@link ModuleDeclaration} * of the specified File Uri or from the enclosed Package. * * @param res * @return {@link IStrategoTerm} * @throws SpxSymbolTableException */ public IStrategoTerm getModuleDeclarationsOf(IStrategoTerm res) throws SpxSymbolTableException { IStrategoTerm retValue ; if(Tools.isTermAppl(res)) retValue = this.getModuleDeclarations((IStrategoAppl)res); else if(Tools.isTermString(res)) retValue = this.getModuleDeclarations((IStrategoString)res); else throw new IllegalArgumentException("Unknown argument in getModuleDeclarationOf: " + res); return retValue; } public IStrategoList getModuleDeclarations (IStrategoString filePath){ logMessage("getModuleDeclarations | Arguments : " + filePath); SpxModuleLookupTable table = persistenceManager().spxModuleTable(); String filepathString = asJavaString(filePath); Iterable<ModuleDeclaration> decls; if(All == filepathString) { decls = table.getModuleDeclarations(); //returning all the package declarations found in the current project }else{ String absFilePath = toAbsulatePath(filePath); table.verifyUriExists(absFilePath); decls = table.getModuleDeclarationsByUri(absFilePath); } IStrategoList result = Utils.toTerm(this, decls); logMessage("getModuleDeclarations | Returning IStrategoList : " + result ); return result; } /** * Returns IStrategoList of {@link ModuleDeclaration} enclosed in a Package. * * @param packageQName Qualified Name of Package * @return {@link IStrategoList} * @throws SpxSymbolTableException */ public IStrategoList getModuleDeclarations(IStrategoAppl packageQName) throws SpxSymbolTableException { logMessage("getModuleDeclarations | Arguments : " + packageQName); IStrategoList packageID = PackageDeclaration.getPackageId(this, packageQName); Iterable<ModuleDeclaration> decls = getModuleDeclarations(packageID); logMessage("getModuleDeclarations | Found following result from SymbolTable : " + decls); IStrategoList result = Utils.toTerm(this, decls); logMessage("getModuleDeclarations | Returning IStrategoList : " + result ); return result; } public Iterable<ModuleDeclaration> getModuleDeclarations(IStrategoList pacakgeID) throws SpxSymbolTableException { SpxModuleLookupTable table = persistenceManager().spxModuleTable(); _persistenceManager.spxPackageTable().verifyPackageIDExists(pacakgeID) ; return table.getModuleDeclarationsByPackageId(pacakgeID); } public IStrategoTerm getModuleDefinition(IStrategoAppl moduleTypedQName) throws IllegalArgumentException, SpxSymbolTableException { ModuleDeclaration decl = lookupModuleDecl(moduleTypedQName); SpxModuleLookupTable table = persistenceManager().spxModuleTable(); IStrategoList qualifiedModuleId = ModuleDeclaration.getModuleId(this, moduleTypedQName); IStrategoTerm moduleAterm =table.getModuleDefinition(qualifiedModuleId) ; IStrategoTerm moduleAnnotatedAterm = table.getAnalyzedModuleDefinition(qualifiedModuleId); return new ModuleDefinition( decl , (IStrategoAppl)moduleAterm, (IStrategoAppl)moduleAnnotatedAterm).toTerm(this); } public IStrategoTerm getLanguageDescriptor ( IStrategoAppl packageTypedQName) throws IllegalArgumentException, Exception{ IStrategoList packageQName = PackageDeclaration.getPackageId(this, packageTypedQName); SpxPackageLookupTable table = persistenceManager().spxPackageTable(); table.verifyPackageIDExists(packageQName) ; LanguageDescriptor desc = table.getLangaugeDescriptor(packageQName); if ( desc == null){ throw new SpxSymbolTableException("Not Found LanguageDescriptor for " + packageQName.toString()); } return desc.toTerm(this); } /** * Removes PackageDeclaration mapped with the {@code spxCompilationUnitPath} * * @param spxCompilationUnitPath * @param packageId */ public void removePackageDeclaration( IStrategoString spxCompilationUnitPath , IStrategoAppl namespaceID){ SpxPackageLookupTable table = _persistenceManager.spxPackageTable(); spxCompilationUnitPath = (IStrategoString)toCompactPositionInfo((IStrategoTerm)spxCompilationUnitPath); IStrategoList packageId = (IStrategoList)toCompactPositionInfo(PackageDeclaration.getPackageId(this, namespaceID)); table.verifyPackageIDExists(packageId) ; table.removePackageDeclarationLocation( packageId, toAbsulatePath(spxCompilationUnitPath)); } /** * looks up for a package declaration given its ID. * * @param packageId * @return * @throws SpxSymbolTableException */ PackageDeclaration lookupPackageDecl(IStrategoList packageId) throws SpxSymbolTableException { SpxPackageLookupTable table = persistenceManager().spxPackageTable(); PackageDeclaration decl = table.getPackageDeclaration(packageId); if (decl == null) throw new SpxSymbolTableException( "Unknown Package Id : "+ packageId.toString()); return decl; } /** * Saves(Commits) any unsaved data. * * @throws IOException */ public void persistChanges() throws IOException { _persistenceManager.commit(); } /** * Closes any underlying open connection. * * @throws IOException */ public void close() throws IOException { if (!isPersistenceManagerClosed()) { logMessage("close | closing underlying persistence manager instance."); _persistenceManager.commitAndClose(); }else { logMessage("close | underlying persistence manager is already closed. "); } } /** * Re-initialize Symbol Tables . It clears all the existing entries from * symbol tables. * * @throws IOException */ public void reinitSymbolTable() throws IOException { if (! isPersistenceManagerClosed()) persistenceManager().clearAll(); persistenceManager().commit(); persistenceManager().initializeSymbolTables(this.getProjectNameString(), this); } /** * Checks whether the underlying persistence manager is already open. * * @return true if PersistenceManage is open. Otherwise returns false. */ boolean isPersistenceManagerClosed() { return _persistenceManager.IsClosed(); } /** * @param spxCompilationUnitAST * @return */ private IStrategoTerm toCompactPositionInfo(IStrategoTerm term) { if( term == null) return term; ImploderAttachment astAttachment = ImploderAttachment.getCompactPositionAttachment(term, true); IStrategoTerm astTerm = _stripper.strip(term); astTerm.putAttachment(astAttachment); return astTerm; } private IStrategoTerm strip(IStrategoTerm term) { return _stripper.strip(term); } /** * Returns the Absolute Path of the given URI * * @param uri URI of the Resource. * @return Absolute Path represented by the URI */ public String toAbsulatePath( IStrategoString uri){ URI resUri = toFileURI(uri); return new File(resUri).getAbsolutePath().trim(); } /** * Returns URI * @param path * @return */ private URI toFileURI(String path) { File file = new File(path); return file.isAbsolute()? file.toURI() : new File(_agent.getWorkingDir(), path).toURI(); } private URI toFileURI(IStrategoTerm filePath) { return toFileURI(Tools.asJavaString(filePath)); } /** * Verify type of declaration . * * @param actual * @param expected * @param message */ public void verifyConstructor( IStrategoConstructor actual , IStrategoConstructor expected , String message){ if( actual != expected) throw new IllegalArgumentException(message); } /** * Logs message * * @param message */ private void logMessage(String message) { _persistenceManager.logMessage("SpxSemanticIndexFacade", message); } String fromFileURI(URI uri) { File file = new File(uri); return file.toString(); } IOAgent getIOAgent() { return _agent; } /** * Prints error message * @param errMessage */ void printError(String errMessage){ _agent.printError(errMessage); } /** * Force an imploder attachment for a term. * This ensures that there is always some form of position info, * and makes sure that origin info is not added to the term. * (The latter would be bad since we cache in {@link #term}.) */ public static IStrategoAppl forceImploderAttachment(IStrategoAppl term , URI file) { return forceImploderAttachment(term, term, file); } public static IStrategoAppl forceImploderAttachment(IStrategoTerm id, IStrategoAppl term , URI file) { ImploderAttachment attach = ImploderAttachment.get(id); if (attach != null) { ImploderAttachment.putImploderAttachment(term, false, attach.getSort(), attach.getLeftToken(), attach.getRightToken()); } else { String fn = file == null ? null : file.toString(); term.putAttachment(ImploderAttachment.createCompactPositionAttachment( fn, 0, 0, 0, -1)); } return term; } //TODO : better handling of the known constructors public IStrategoConstructor getPackageDeclCon() { return getConstructor("PackageDecl",2);} public IStrategoConstructor getModuleDeclCon() { return getConstructor("ModuleDecl", 3); } public IStrategoConstructor getModuleDefCon() { return getConstructor("ModuleDef" , 5);} public IStrategoConstructor getLanguageDescriptorCon() { return getConstructor("LanguageDescriptor" , 5);} public IStrategoConstructor getModuleQNameCon() {return getConstructor("Module" , 1); } public IStrategoConstructor getPackageQNameCon() { return getConstructor("Package" , 1);} public IStrategoConstructor getQNameCon() { return getConstructor("QName" , 1); } public IStrategoConstructor getImportDeclCon() {return getConstructor("ImportDecl",2);} public IStrategoConstructor getGlobalNamespaceTypeCon() {return getConstructor("Globals",0);} public IStrategoConstructor getPackageNamespaceTypeCon() {return getConstructor("Package",0);} public IStrategoConstructor getModuleNamespaceTypeCon() {return getConstructor("Module",0);} public IStrategoConstructor getSymbolTableEntryDefCon() {return getConstructor("SymbolDef",4);} public IStrategoConstructor getLocalNamespaceTypeCon() { return getConstructor("Locals",1); } public IStrategoConstructor getConstructor(String symbolTypeCons, int arity) { return _knownCons.get(ConstructorDef.newInstance(symbolTypeCons ,arity)); } private void initKnownConstructors(){ ConstructorDef.newInstance("ModuleDef" ,5).index(_knownCons, _termFactory); ConstructorDef.newInstance("ModuleDecl" ,3).index(_knownCons, _termFactory); ConstructorDef.newInstance("SymbolDef" ,4).index(_knownCons, _termFactory); ConstructorDef.newInstance("PackageDecl",2).index(_knownCons, _termFactory); ConstructorDef.newInstance("ImportDecl" ,2).index(_knownCons, _termFactory); ConstructorDef.newInstance("LanguageDescriptor", 5).index(_knownCons, _termFactory); ConstructorDef.newInstance("Module" , 1).index(_knownCons, _termFactory); ConstructorDef.newInstance("Package", 1).index(_knownCons, _termFactory); ConstructorDef.newInstance("QName" , 1).index(_knownCons, _termFactory); ConstructorDef.newInstance("Locals" , 1).index(_knownCons, _termFactory); ConstructorDef.newInstance("Globals", 0).index(_knownCons, _termFactory); ConstructorDef.newInstance("Package", 0).index(_knownCons, _termFactory); ConstructorDef.newInstance("Module" , 0).index(_knownCons, _termFactory); } private final HashMap<ConstructorDef , IStrategoConstructor> _knownCons; private static class ConstructorDef { private String _name ; private int _arity; ConstructorDef( String name , int arity) { _name = name ; _arity = arity; } static ConstructorDef newInstance( String name , int arity) { return new ConstructorDef(name, arity); } private IStrategoConstructor toStrategoConstructor(ITermFactory fac) { return fac.makeConstructor(_name, _arity);} IStrategoConstructor index(HashMap<ConstructorDef , IStrategoConstructor> cons , ITermFactory fac){ return this.index(cons, this.toStrategoConstructor(fac)); } IStrategoConstructor index(HashMap<ConstructorDef , IStrategoConstructor> cons , IStrategoConstructor ctor){ cons.put(this, ctor) ; return ctor; } @Override public String toString() { return "ConstructorDef [_name=" + _name + ", _arity=" + _arity + "]"; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + _arity; result = prime * result + ((_name == null) ? 0 : _name.hashCode()); return result; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ConstructorDef other = (ConstructorDef) obj; if (_arity != other._arity) return false; if (_name == null) { if (other._name != null) return false; } else if (!_name.equals(other._name)) return false; return true; } } }
package com.conaltuohy.xprocz; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.net.URLEncoder; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.TimeZone; import java.util.HashMap; import java.util.Map; import java.util.Enumeration; import java.util.Properties; import com.xmlcalabash.core.XProcException; import org.apache.commons.codec.binary.Base64; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.ParserConfigurationException; import javax.xml.XMLConstants; import javax.xml.transform.OutputKeys; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Templates; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.Transformer; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.sax.TransformerHandler; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import net.sf.saxon.s9api.SaxonApiException; import com.xmlcalabash.core.XProcRuntime; import com.xmlcalabash.core.XProcConfiguration; import com.xmlcalabash.util.Input; import com.xmlcalabash.runtime.XPipeline; import com.xmlcalabash.model.RuntimeValue; import net.sf.saxon.s9api.Processor; import net.sf.saxon.s9api.XdmNode; import com.xmlcalabash.io.ReadablePipe; import java.io.OutputStreamWriter; import net.sf.saxon.s9api.Axis; import net.sf.saxon.s9api.QName; import net.sf.saxon.s9api.XdmItem; import net.sf.saxon.s9api.XdmSequenceIterator; import java.io.UnsupportedEncodingException; import java.io.Reader; import java.io.InputStreamReader; import javax.servlet.http.Part; import javax.servlet.annotation.MultipartConfig; import javax.xml.parsers.ParserConfigurationException; /** * Servlet implementation class XProcZServlet * The RetailerServlet is a host for HTTP server applications written in XProc. */ @MultipartConfig public class XProcZServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final String SERVLET_INIT_PARAMETERS_NS = "tag:conaltuohy.com,2015:servlet-init-parameters"; private static final String APPLICATION_INIT_PARAMETERS_NS = "tag:conaltuohy.com,2015:webapp-init-parameters"; private static final String SERVLET_CONTEXT_NS = "tag:conaltuohy.com,2015:servlet-context"; private static final String OS_ENVIRONMENT_VARIABLES_NS = "tag:conaltuohy.com,2015:os-environment-variables"; private static final String JAVA_SYSTEM_PROPERTIES_NS = "tag:conaltuohy.com,2015:java-system-properties"; private static final String XPROC_STEP_NS = "http: private final static SAXTransformerFactory transformerFactory = (SAXTransformerFactory) TransformerFactory.newInstance(); private final static DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); private DocumentBuilder builder; private XProcRuntime runtime = new XProcRuntime(new XProcConfiguration()); private Map<QName, String> parameters = new HashMap<QName, String>(); /** * @see HttpServlet#HttpServlet() */ public XProcZServlet() { super(); } private class RunnablePipeline implements Runnable { Exception e = null; XdmNode inputDocument = null; HttpServletResponse httpResponse = null; RunnablePipeline(XdmNode inputDocument) { this.inputDocument = inputDocument; } RunnablePipeline(XdmNode inputDocument, HttpServletResponse httpResponse) { this.inputDocument = inputDocument; this.httpResponse = httpResponse; } public void run() { try { getServletContext().log("Running pipeline..."); getServletContext().log("Initializing pipeline..."); Input input = new Input(getServletContext().getRealPath("/xproc/xproc-z.xpl")); XPipeline pipeline = runtime.load(input); getServletContext().log("Passing parameters to pipeline..."); // attach parameters from the application's environment for (QName name : parameters.keySet()) { pipeline.setParameter(name, new RuntimeValue(parameters.get(name))); } getServletContext().log("Passing input document (http request) to pipeline..."); // TODO for debug logging only // getServletContext().log(inputDocument.toString()); pipeline.writeTo("source", inputDocument); getServletContext().log("Actually executing the pipeline..."); pipeline.run(); // TODO read multiple result documents // The first is a c:response - use it make http response to client. // Remaining documents are inputs for subsequent executions - spawn separate threads to execute // the pipeline to handle each of these documents, and discarding any results. // This allows XProc-Z to execute multiple asynchronous long-running processes. // See https://github.com/ndw/xmlcalabash1/blob/saxon96/src/main/java/com/xmlcalabash/drivers/Main.java#L425 getServletContext().log("Reading results from pipeline..."); ReadablePipe result = pipeline.readFrom("result"); getServletContext().log("Reading first result from pipeline..."); XdmNode outputDocument = result.read(); // generate HTTP Response from pipeline output if (httpResponse != null) { // an HTTP client is waiting on a response - the pipelines's first output document is asssumed to specify that response getServletContext().log("Sending pipeline result as HTTP response"); respond(httpResponse, outputDocument); } if (httpResponse == null) { getServletContext().log("Pipeline first response ignored"); } while (result.moreDocuments()) { // subsequent documents are callbacks to the pipeline getServletContext().log("Reading subsequent results from pipeline..."); outputDocument = result.read(); getServletContext().log("Pipeline produced extra document: " + outputDocument.toString()); //XdmNode rootElement = (XdmNode) outputDocument.axisIterator(Axis.CHILD).next(); //while (! (rootElement.getNodeKind().equals(net.sf.saxon.s9api.XdmNodeKind.ELEMENT))) { //rootElement = (XdmNode) outputDocument.axisIterator(Axis.CHILD).next(); getServletContext().log("Launching asynchronous pipeline..."); new Thread(new RunnablePipeline(outputDocument)).start(); getServletContext().log("Pipeline launched."); } } catch (Exception e) { this.e = e; } } }; private void addParameter(String prefix, String xmlns, String localName, String value) { QName name = new QName(prefix, xmlns, purifyForXML(localName)); getServletContext().log("XProc-Z parameter <c:param name='" + name + "' value='" + value + "'/>"); parameters.put(name, purifyForXML(value)); }; /** * Remove characters which are invalid or discouraged in XML */ private String purifyForXML(String text) { return text.replaceAll("[^\\u0009\\u000a\\u000d\\u0020-\\ud7ff\\ue000-\\ufffd]", ""); } public void init() throws ServletException { getServletContext().log("XProc-Z initializing ..."); try { factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); builder = factory.newDocumentBuilder(); // initialize the set of parameters from the servlet's environment // The Servlet initialization parameters for (String name : Collections.list(getServletConfig().getInitParameterNames())) { addParameter("servlet", SERVLET_INIT_PARAMETERS_NS, name, getServletConfig().getInitParameter(name)); } // The web application's initialization parameters, // from WEB.xml or provided by the Servlet container // e.g. parameters listed in a Tomcat 'context.xml' file for (String name : Collections.list(getServletContext().getInitParameterNames())) { addParameter("webapp", APPLICATION_INIT_PARAMETERS_NS, name, getServletContext().getInitParameter(name)); } // The Operating System's environment variables, for (Map.Entry<String, String> entry: System.getenv().entrySet()) { addParameter("os", OS_ENVIRONMENT_VARIABLES_NS, entry.getKey(), entry.getValue()); } // Java System Properties Properties systemProperties = System.getProperties(); Enumeration systemPropertyNames = systemProperties.propertyNames(); while (systemPropertyNames.hasMoreElements()) { String key = (String) systemPropertyNames.nextElement(); addParameter("jvm", JAVA_SYSTEM_PROPERTIES_NS, key, systemProperties.getProperty(key)); } // Servlet Context properties addParameter("sc", SERVLET_CONTEXT_NS, "contextPath", getServletContext().getContextPath()); addParameter("sc", SERVLET_CONTEXT_NS, "realPath", getServletContext().getRealPath("")); getServletContext().log("XProc-Z initialization completed successfully."); } catch (ParserConfigurationException pce) { // should not happen as support for FEATURE_SECURE_PROCESSING is mandatory getServletContext().log("XProc-Z initialization failed!"); throw new ServletException(pce); } } private Document parseXML(InputStream inputStream) throws SAXException, IOException { // TODO should a parse failure trigger re-processing as plain text? Document document = builder.parse(inputStream); inputStream.close(); return document; } private XdmNode getRequestDocument(HttpServletRequest req) throws ParserConfigurationException, SAXException, IOException, ServletException { // Create a document describing the HTTP request, // from request parameters, headers, etc. // to be the input document for the XProc pipeline. Document requestXML = null; requestXML = factory.newDocumentBuilder().newDocument(); // Populate the XML document from the HTTP request data Element request = requestXML.createElementNS(XPROC_STEP_NS, "c:request"); requestXML.appendChild(request); String queryString = req.getQueryString(); String requestURI = req.getRequestURL().toString(); if (queryString != null) { requestURI += "?" + queryString; }; request.setAttribute("method", req.getMethod()); request.setAttribute("href", requestURI); request.setAttribute("detailed", "true"); request.setAttribute("status-only", "false"); if (req.getRemoteUser() != null) { request.setAttribute("username", req.getRemoteUser()); // NB password not available; pipeline would need to process the Authorization header }; if (req.getAuthType() != null) { request.setAttribute("auth-method", req.getAuthType()); }; // the HTTP request headers for (String name : Collections.list(req.getHeaderNames())) { Element header = requestXML.createElementNS(XPROC_STEP_NS, "c:header"); request.appendChild(header); header.setAttribute("name", name); header.setAttribute("value", req.getHeader(name)); } // the request body or parts if (req.getContentType() == null || req.getContentLength() == 0) { } else if (req.getContentType().startsWith("multipart/form-data;")) { // content is multipart // create c:multipart String boundary = req.getContentType().substring("multipart/form-data; boundary=".length()); Element multipart = requestXML.createElementNS(XPROC_STEP_NS, "c:multipart"); multipart.setAttribute("content-type", req.getContentType()); request.appendChild(multipart); multipart.setAttribute("boundary", boundary); // for each part, create a c:body for (Part part: req.getParts()) { Element body = requestXML.createElementNS(XPROC_STEP_NS, "c:body"); multipart.appendChild(body); String partContentType = part.getContentType(); if (partContentType == null) { partContentType = "text/plain"; } String disposition = part.getHeader("Content-Disposition"); if (disposition != null) { body.setAttribute("disposition", disposition); } body.setAttribute("content-type", partContentType); String contentId = part.getHeader("Content-ID"); if (contentId != null) { body.setAttribute("id", contentId); } String contentDescription = part.getHeader("Content-Description"); if (contentDescription != null) { body.setAttribute("description", contentDescription); } // TODO allow badly formed XML content to fall back to being processed as text // insert the actual content of the part if (isXMLMediaType(partContentType)) { // parse XML Document uploadedDocument = parseXML(part.getInputStream()); // TODO also import top-level comments, processing instructions, etc? body.appendChild( body.getOwnerDocument().adoptNode( uploadedDocument.getDocumentElement() ) ); } else if (isTextMediaType(partContentType)) { // otherwise if text then copy it unparsed // <c:body content-type="text/plain">This &amp; that</c:body> InputStream inputStream = part.getInputStream(); body.appendChild( requestXML.createTextNode( readText(inputStream, getCharacterEncoding(req)) ) ); inputStream.close(); } else { // Base64 encode binary data body.setAttribute("encoding", "base64"); InputStream inputStream = part.getInputStream(); body.appendChild( requestXML.createTextNode( readBinary(inputStream) ) ); inputStream.close(); } } } else { // content is simple // create c:body element Element body = requestXML.createElementNS(XPROC_STEP_NS, "c:body"); request.appendChild(body); body.setAttribute("content-type", req.getContentType()); String contentType = req.getContentType(); if (isXMLMediaType(contentType)) { // TODO if it's XML then parse it and place root element inside // <c:body content-type="application/rdf+xml"><rdf:RDF etc.../></c:body> Document uploadedDocument = parseXML(req.getInputStream()); // TODO also import top-level comments, processing instructions, etc? body.appendChild( body.getOwnerDocument().adoptNode( uploadedDocument.getDocumentElement() ) ); } else if (isTextMediaType(contentType)) { // otherwise if text then copy it unparsed // <c:body content-type="text/plain">This &amp; that</c:body> InputStream inputStream = req.getInputStream(); body.appendChild( requestXML.createTextNode( readText(inputStream, getCharacterEncoding(req)) ) ); inputStream.close(); } else { // ... or if binary then base64 encode it // <c:body content-type="application/pdf" encoding = "base64">...</c:body> body.setAttribute("encoding", "base64"); InputStream inputStream = req.getInputStream(); body.appendChild( requestXML.createTextNode( readBinary(inputStream) ) ); inputStream.close(); } } // wrap request DOM in Saxon XdmNode XdmNode inputDocument = runtime.getProcessor().newDocumentBuilder().wrap(requestXML); return inputDocument; } private void respond(HttpServletResponse resp, XdmNode outputDocument) throws IOException { // Create a stream to send response XML to the HTTP client OutputStream os = resp.getOutputStream(); QName responseName = new QName(XPROC_STEP_NS, "response"); XdmNode rootElement = (XdmNode) outputDocument.axisIterator(Axis.CHILD, responseName).next(); String statusAttribute = rootElement.getAttributeValue( new QName("status")); resp.setStatus(Integer.valueOf(statusAttribute)); QName headerName = new QName(XPROC_STEP_NS, "header"); XdmSequenceIterator headers = rootElement.axisIterator(Axis.CHILD, headerName); QName nameName = new QName("name"); QName valueName = new QName("value"); while (headers.hasNext()) { XdmNode headerNode = (XdmNode) headers.next(); resp.addHeader(headerNode.getAttributeValue(nameName), headerNode.getAttributeValue(valueName)); } QName bodyName = new QName(XPROC_STEP_NS, "body"); XdmSequenceIterator bodyIterator = rootElement.axisIterator(Axis.CHILD, bodyName); if (bodyIterator.hasNext()) { // there is an entity body to return XdmNode bodyElement = (XdmNode) bodyIterator.next(); String encoding = bodyElement.getAttributeValue( new QName("encoding") ); String contentType = bodyElement.getAttributeValue( new QName ("content-type") ); String contentDisposition = bodyElement.getAttributeValue( new QName ("disposition") ); if (contentDisposition != null) { resp.addHeader("Content-Disposition", contentDisposition); } XdmSequenceIterator content = bodyElement.axisIterator(Axis.CHILD); resp.setContentType(contentType); if ("base64".equals(encoding)) { // decode base64 encoded binary data and stream to http client os.write( Base64.decodeBase64( content.next().toString() ) ); } else if (isXMLMediaType(contentType)) { // output the sequence of XML nodes within the c:body element using toString to // produce an XML serialization of each one OutputStreamWriter writer = new OutputStreamWriter(os); while (content.hasNext()) { XdmItem contentItem = content.next(); writer.write(contentItem.toString()); } writer.flush(); } else { // output plain text content within the c:body element by writing its string value OutputStreamWriter writer = new OutputStreamWriter(os); while (content.hasNext()) { XdmItem contentItem = content.next(); writer.write(contentItem.getStringValue()); } writer.flush(); } } } @Override public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { // marshal the HTTP request into an XdmNode as a c:request document XdmNode inputDocument = getRequestDocument(req); // Process the XML document which describes the HTTP request, // sending the result to the HTTP client RunnablePipeline pipeline = new RunnablePipeline(inputDocument, resp); pipeline.run(); // this is clunky ... TODO replace with a call to pipeline.runReportingAnyErrors() throws Exception. Pipeline.run() should call // that same method and swallow (log) errors if (pipeline.e != null) {throw pipeline.e;}; } catch (Exception pipelineFailed) { getServletContext().log("Pipeline failed", pipelineFailed); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); resp.setContentType("text/plain"); OutputStream os = resp.getOutputStream(); PrintWriter writer = new PrintWriter(os); if (pipelineFailed instanceof SaxonApiException) { SaxonApiException e = (SaxonApiException) pipelineFailed; writer.print("Error "); writer.print(e.getErrorCode()); /* writer.print(" in module "); writer.print(e.getSystemId()); writer.print(" on line "); writer.print(e.getLineNumber()); */ } pipelineFailed.printStackTrace(writer); writer.flush(); os.close(); } } // logs an exception and re-throws it as a servlet exception private void fail(Exception e, String message) throws ServletException { getServletContext().log(message, e); throw new ServletException(message, e); } private String getCharacterEncoding(HttpServletRequest req) { // The HTTP 1.1 spec says that the default is "ISO-8859-1" // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1 String encoding = req.getCharacterEncoding(); if (encoding == null) { return "ISO-8859-1"; } else { return encoding; } } /** * Determine whether content is, or can be treated as, plain text */ private boolean isTextMediaType(String mediaType) { return ( mediaType.startsWith("text/") || mediaType.equals("application/x-www-form-urlencoded") || ( mediaType.startsWith("application/") && mediaType.endsWith("+json") ) ); } private boolean isXMLMediaType(String mediaType) { return ( mediaType.equals("application/xml") || mediaType.equals("application/xml-external-parsed-entity") || mediaType.equals("text/xml") || mediaType.equals("text/xml-external-parsed-entity") || ( mediaType.startsWith("application/") && mediaType.endsWith("+xml") ) ); } // Read text from the input stream private String readText(InputStream inputStream, String characterEncoding) throws IOException, UnsupportedEncodingException { char[] buffer = new char[1024]; StringBuilder builder = new StringBuilder(); Reader reader = new InputStreamReader(inputStream, characterEncoding); int charactersRead = reader.read(buffer, 0, buffer.length); while (charactersRead > -1) { builder.append(buffer, 0, charactersRead); charactersRead = reader.read(buffer, 0, buffer.length); } return builder.toString(); } // Read binary data from the input stream and return Base64 encoded text // NB if base64-encoding is performed on successive chunks of binary data, // those chunks must be multiples of 3 bytes long (except the last chunk which // may be any length), otherwise a chunk whose size is not divisible by 3 will // produce one or more "=" padding characters and prematurely terminate // the stream of base64 digits. private String readBinary(InputStream inputStream) throws IOException { StringBuilder builder = new StringBuilder(2048); byte[] buffer = new byte[3]; // buffer for 3 bytes of binary data byte[] readBuffer; int bytesRead = 0; do { int firstByteRead = inputStream.read(buffer, 0, 1); int secondByteRead = inputStream.read(buffer, 1, 1); int thirdByteRead = inputStream.read(buffer, 2, 1); if (thirdByteRead == 1) { bytesRead = 3; } else if (secondByteRead == 1) { bytesRead = 2; } else if (firstByteRead == 1) { bytesRead = 1; } else { bytesRead = 0; } if (bytesRead == 3) { readBuffer = buffer; } else { readBuffer = Arrays.copyOfRange(buffer, 0, bytesRead); } if (bytesRead > 0) { builder.append(Base64.encodeBase64String(readBuffer)); } } while (bytesRead == 3); return builder.toString(); } }
package uk.ac.ebi.atlas.experimentimport.analytics; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.jdbc.core.JdbcTemplate; import javax.inject.Inject; import javax.inject.Named; import java.util.ArrayList; import java.util.List; @Named public class SingleCellBaselineDao { private static final Logger LOGGER = LoggerFactory.getLogger(SingleCellBaselineDao.class); private static final int BATCH_SIZE = 2000; private static final String SC_EXPRESSION_INSERT = "INSERT INTO SINGLE_CELL_EXPRESSION " + "(EXPERIMENT_ACCESSION, GENE_ID, CELL_ID, EXPRESSION_LEVEL) VALUES (?, ?, ?, ?)"; private final JdbcTemplate jdbcTemplate; @Inject public SingleCellBaselineDao(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } public void loadAnalytics(final String experimentAccession, SingleCellBaselineInputStream singleCellInputStream) { LOGGER.info("loadSingleCellExpression for experiment {} begin", experimentAccession); SingleCellBaseline scb; final List<Object[]> batch = new ArrayList<>(BATCH_SIZE); while ((scb = singleCellInputStream.readNext()) != null) { // Prepare the batch batch.clear(); while (batch.size() < BATCH_SIZE && scb != null) { batch.add(new Object[] {experimentAccession, scb.getGeneId(), scb.getCellId(), scb.getExpressionLevel()}); scb = singleCellInputStream.readNext(); } // Insert the batch jdbcTemplate.batchUpdate(SC_EXPRESSION_INSERT, batch); } LOGGER.info("loadSingleCellExpression for experiment {} complete", experimentAccession); } public void deleteAnalytics(String experimentAccession) { LOGGER.info("delete SingleCellExpression for experiment {}", experimentAccession); jdbcTemplate.update("DELETE FROM SINGLE_CELL_EXPRESSION WHERE EXPERIMENT_ACCESSION = ?", experimentAccession); } }
package com.connork.mtgcounter; import android.animation.ValueAnimator; import android.animation.ValueAnimator.AnimatorUpdateListener; import android.annotation.TargetApi; import android.app.ActionBar; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Shader; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.WindowManager; import android.widget.Button; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.SeekBar; import android.widget.TextView; public class MainActivity extends Activity implements OnClickListener { // Some keys for passing information from setup public static String KEY_NUM_PLAYERS = "mtg_num_players"; public static String KEY_PLAYER_NAMES = "mtg_player_names"; public static String KEY_STARTING_LIFE = "mtg_starting_life"; public static String KEY_PLAYER_ICONS = "mtg_player_icons"; // TODO public static String KEY_CONTINUE_GAME = "mtg_continue_game"; private int NUM_PLAYERS, STARTING_LIFE, selected_p13 = 0, selected_p24 = 1; public static int PLAYER_1 = 0, PLAYER_2 = 1, PLAYER_3 = 2, PLAYER_4 = 3; private int[] life; private boolean[] alive = {false, false, false, false}; private boolean game_started; private String[] PLAYER_NAMES; private int[] PLAYER_ICONS; private TextView[] TEXTVIEW_LIFE; private SeekBar[] PROGRESSBAR_LIFE; private Button[] BUTTON_LIFE = new Button[8]; private RadioGroup radiogroup_p13, radiogroup_p24; private RadioButton radio_button[] = new RadioButton[4]; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); game_started = false; // Get passed information and initialize player names, life, etc. NUM_PLAYERS = getIntent().getIntExtra(KEY_NUM_PLAYERS, 2); String[] names = getIntent().getStringArrayExtra(KEY_PLAYER_NAMES); STARTING_LIFE = getIntent().getIntExtra(KEY_STARTING_LIFE, 20); int[] icons = getIntent().getIntArrayExtra(KEY_PLAYER_ICONS); PLAYER_NAMES = new String[NUM_PLAYERS]; PLAYER_ICONS = new int[NUM_PLAYERS]; life = new int[NUM_PLAYERS]; for (int i = 0; i < NUM_PLAYERS; i++) { PLAYER_NAMES[i] = names[i]; PLAYER_ICONS[i] = icons[i]; life[i] = STARTING_LIFE; alive[i] = true; } //TODO Restore last life state if possible if (savedInstanceState != null) { life = savedInstanceState.getIntArray("main_life"); } // The textview and progressbars to keep track of player life TEXTVIEW_LIFE = new TextView[NUM_PLAYERS]; PROGRESSBAR_LIFE = new SeekBar[NUM_PLAYERS]; // Set up all the views and change the layout based on the number of players // The switch has no breaks, so each case sets up that player number (with case 2 setting up players 1 and 2) //TODO make landscape layouts, tablet ui? switch (NUM_PLAYERS) { case 4: // Use the 4-player layout setContentView(R.layout.activity_main4); // Set Player 4's name ((TextView)findViewById(R.id.textview_main_p4_name)).setText(PLAYER_NAMES[PLAYER_4]); // Player 4's life text and progressbar TEXTVIEW_LIFE[PLAYER_4] = (TextView)findViewById(R.id.textview_main_p4_life); PROGRESSBAR_LIFE[PLAYER_4] = (SeekBar) findViewById(R.id.progressbar_main_p4_life); // Set mana icon PROGRESSBAR_LIFE[PLAYER_4].setThumb(getManaIcon(PLAYER_4)); // The radio group to select who the +-life buttons route to (player 2 or 4) radio_button[PLAYER_2] = (RadioButton) findViewById(R.id.radio_main_p2); radio_button[PLAYER_2].setText(PLAYER_NAMES[1]); radio_button[PLAYER_4] = (RadioButton) findViewById(R.id.radio_main_p4); radio_button[PLAYER_4].setText(PLAYER_NAMES[3]); radiogroup_p24 = (RadioGroup) findViewById(R.id.radiogroup_main_p24); radiogroup_p24.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { RadioButton checkedRadioButton = (RadioButton) findViewById(checkedId); String text = checkedRadioButton.getText().toString(); if (text.equals(radio_button[PLAYER_2].getText())) { selected_p24 = PLAYER_2; } else if (text.equals(radio_button[PLAYER_4].getText())) { selected_p24 = PLAYER_4; } } }); // Check settings to enable/prevent them from sliding the seekbar to change their life. PROGRESSBAR_LIFE[PLAYER_4].setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { // Check settings to enable/prevent them from sliding the seekbar to change their life. if (!fromUser || Prefs.getLifeCounterTouchable(MainActivity.this)) { life[PLAYER_4] = (int)((double)progress * STARTING_LIFE / seekBar.getMax()); updateViews(PLAYER_4); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); case 3: // Use the 3-player layout if (NUM_PLAYERS == 3) { setContentView(R.layout.activity_main3); } // Set Player 3's name ((TextView)findViewById(R.id.textview_main_p3_name)).setText(PLAYER_NAMES[PLAYER_3]); // Player 3's life text and progressbar TEXTVIEW_LIFE[PLAYER_3] = (TextView)findViewById(R.id.textview_main_p3_life); PROGRESSBAR_LIFE[PLAYER_3] = (SeekBar) findViewById(R.id.progressbar_main_p3_life); // Set mana icon PROGRESSBAR_LIFE[PLAYER_3].setThumb(getManaIcon(PLAYER_3)); // The radio group to select who the +-life buttons route to (player 1 or 3) radio_button[PLAYER_1] = (RadioButton) findViewById(R.id.radio_main_p1); radio_button[PLAYER_1].setText(PLAYER_NAMES[PLAYER_1]); radio_button[PLAYER_3] = (RadioButton) findViewById(R.id.radio_main_p3); radio_button[PLAYER_3].setText(PLAYER_NAMES[PLAYER_3]); radiogroup_p13 = (RadioGroup) findViewById(R.id.radiogroup_main_p13); radiogroup_p13.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { RadioButton checkedRadioButton = (RadioButton) findViewById(checkedId); String text = checkedRadioButton.getText().toString(); if (text.equals(radio_button[PLAYER_1].getText())) { selected_p13 = PLAYER_1; } else if (text.equals(radio_button[PLAYER_3].getText())) { selected_p13 = PLAYER_3; } } }); // Check settings to enable/prevent them from sliding the seekbar to change their life. PROGRESSBAR_LIFE[PLAYER_3].setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { // Check settings to enable/prevent them from sliding the seekbar to change their life. if (!fromUser || Prefs.getLifeCounterTouchable(MainActivity.this)) { life[PLAYER_3] = (int)((double)progress * STARTING_LIFE / seekBar.getMax()); updateViews(PLAYER_3); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); case 2: // Use the 2-player layout if (NUM_PLAYERS == 2) { setContentView(R.layout.activity_main); } // Set Player 1 and 2's names ((TextView)findViewById(R.id.textview_main_p1_name)).setText(PLAYER_NAMES[PLAYER_1]); ((TextView)findViewById(R.id.textview_main_p2_name)).setText(PLAYER_NAMES[PLAYER_2]); // Set up the +-life buttons BUTTON_LIFE[0] = (Button) findViewById(R.id.button_main_p1_lifep1); BUTTON_LIFE[1] = (Button) findViewById(R.id.button_main_p1_lifep5); BUTTON_LIFE[2] = (Button) findViewById(R.id.button_main_p1_lifem1); BUTTON_LIFE[3] = (Button) findViewById(R.id.button_main_p1_lifem5); BUTTON_LIFE[4] = (Button) findViewById(R.id.button_main_p2_lifep1); BUTTON_LIFE[5] = (Button) findViewById(R.id.button_main_p2_lifep5); BUTTON_LIFE[6] = (Button) findViewById(R.id.button_main_p2_lifem1); BUTTON_LIFE[7] = (Button) findViewById(R.id.button_main_p2_lifem5); for (int i = 0; i < BUTTON_LIFE.length; i++) { BUTTON_LIFE[i].setOnClickListener(this); } // Setup Player 1 and 2's life text and progressbars TEXTVIEW_LIFE[PLAYER_1] = (TextView)findViewById(R.id.textview_main_p1_life); TEXTVIEW_LIFE[PLAYER_2] = (TextView)findViewById(R.id.textview_main_p2_life); PROGRESSBAR_LIFE[PLAYER_1] = (SeekBar) findViewById(R.id.progressbar_main_p1_life); // Set mana icon PROGRESSBAR_LIFE[PLAYER_1].setThumb(getManaIcon(PLAYER_1)); PROGRESSBAR_LIFE[PLAYER_2] = (SeekBar) findViewById(R.id.progressbar_main_p2_life); // Set mana icon PROGRESSBAR_LIFE[PLAYER_2].setThumb(getManaIcon(PLAYER_2)); // Animate filling the life bars for (int i = 0; i < PROGRESSBAR_LIFE.length; i++) { final int player = i; ValueAnimator anim = ValueAnimator.ofInt(0, PROGRESSBAR_LIFE[player].getMax()); anim.setDuration(3000); anim.addUpdateListener(new AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { int animProgress = (Integer) animation.getAnimatedValue(); PROGRESSBAR_LIFE[player].setProgress(animProgress); } }); anim.setStartDelay(300); anim.start(); } // Make life text visible after the animation, and set max progress to initial life new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { try { Thread.sleep(3300); } catch (InterruptedException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); // Set the seekbar's maxes and progresses to be starting life for (int i = 0; i < NUM_PLAYERS; i++) { PROGRESSBAR_LIFE[i].setMax(STARTING_LIFE); PROGRESSBAR_LIFE[i].setProgress(STARTING_LIFE); } // Start checking if players have lost game_started = true; } }.execute(); // Player 2 PROGRESSBAR_LIFE[PLAYER_2].setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { // Check settings to enable/prevent them from sliding the seekbar to change their life. if (!fromUser || Prefs.getLifeCounterTouchable(MainActivity.this)) { life[PLAYER_2] = (int)((double)progress * STARTING_LIFE / seekBar.getMax()); updateViews(PLAYER_2); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); // Player 1 PROGRESSBAR_LIFE[PLAYER_1].setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { // Check settings to enable/prevent them from sliding the seekbar to change their life. if ((!fromUser && !game_started) || (fromUser && Prefs.getLifeCounterTouchable(MainActivity.this))) { life[PLAYER_1] = (int)((double)progress * STARTING_LIFE / seekBar.getMax()); updateViews(PLAYER_1); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); break; } // Style the ActionBar ActionBar actionBar = getActionBar(); Bitmap bMap = BitmapFactory.decodeResource(getResources(), R.drawable.ab_texture_tile); final BitmapDrawable bitmapDrawable = new BitmapDrawable(getResources(), bMap); bitmapDrawable.setTileModeXY(Shader.TileMode.REPEAT, Shader.TileMode.REPEAT); actionBar.setBackgroundDrawable(bitmapDrawable); actionBar.setDisplayHomeAsUpEnabled(true); // Keep screen on getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); //TODO Continue game //TODO Activity lifecycle stuff } // TODO: This is a hack to get the mana icons, needs more efficient method later private Drawable getManaIcon(int player) { Drawable output = null; switch (PLAYER_ICONS[player]) { case 0: output = getResources().getDrawable(R.drawable.mana_colorless); break; case 1: output = getResources().getDrawable(R.drawable.mana_white); break; case 2: output = getResources().getDrawable(R.drawable.mana_blue); break; case 3: output = getResources().getDrawable(R.drawable.mana_black); break; case 4: output = getResources().getDrawable(R.drawable.mana_red); break; case 5: output = getResources().getDrawable(R.drawable.mana_green); break; } return output; } /** Update life for a specific player */ void updateViews(int player) { TEXTVIEW_LIFE[player].setText(life[player] + " / " + STARTING_LIFE); // Color the text based on life int color = 0; if (life[player] > STARTING_LIFE) { color = android.R.color.holo_purple; } else if (life[player] > STARTING_LIFE*3.0/4.0) { color = android.R.color.holo_blue_dark; } else if (life[player] > STARTING_LIFE*2.0/4.0) { color = android.R.color.holo_green_dark; } else if (life[player] > STARTING_LIFE/4.0) { color = android.R.color.holo_orange_dark; } else if (life[player] <= STARTING_LIFE/4.0) { color = android.R.color.holo_red_dark; } TEXTVIEW_LIFE[player].setTextColor(getResources().getColor(color)); if (game_started) { for (int i = 0; i < life.length; i++) { if (life[i] <= 0) { // If someone has 0 or less life, make a gg dialog and mark them as dead (avoid multiple dialogs for same person). if (alive[i]) { alive[i] = false; gameOver(i); break; } } } } } /** Handle when a button is clicked, call appropriate action */ public void onClick(View v) { switch (v.getId()) { case R.id.button_main_p1_lifep1: // Adjust the selected player's life, then update the textview life[selected_p13] += 1; PROGRESSBAR_LIFE[selected_p13].setProgress(life[selected_p13]); updateViews(selected_p13); break; case R.id.button_main_p1_lifep5: life[selected_p13] += 5; PROGRESSBAR_LIFE[selected_p13].setProgress(life[selected_p13]); updateViews(selected_p13); break; case R.id.button_main_p1_lifem1: life[selected_p13] -= 1; PROGRESSBAR_LIFE[selected_p13].setProgress(life[selected_p13]); updateViews(selected_p13); break; case R.id.button_main_p1_lifem5: life[selected_p13] -= 5; PROGRESSBAR_LIFE[selected_p13].setProgress(life[selected_p13]); updateViews(selected_p13); break; case R.id.button_main_p2_lifep1: life[selected_p24] += 1; PROGRESSBAR_LIFE[selected_p24].setProgress(life[selected_p24]); updateViews(selected_p24); break; case R.id.button_main_p2_lifep5: life[selected_p24] += 5; PROGRESSBAR_LIFE[selected_p24].setProgress(life[selected_p24]); updateViews(selected_p24); break; case R.id.button_main_p2_lifem1: life[selected_p24] -= 1; PROGRESSBAR_LIFE[selected_p24].setProgress(life[selected_p24]); updateViews(selected_p24); break; case R.id.button_main_p2_lifem5: life[selected_p24] -= 5; PROGRESSBAR_LIFE[selected_p24].setProgress(life[selected_p24]); updateViews(selected_p24); break; } } /** Someone has lost */ private void gameOver(int player) { // Make an AlertDialog with a loss message AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create(); alertDialog.setTitle(PLAYER_NAMES[player] + " has lost."); alertDialog.setMessage("GG."); alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Continue", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { //Dismiss } }); alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "End Game", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }); alertDialog.show(); } /** Use KitKat Immersive Mode if possible otherwise just fullscreen */ @TargetApi(android.os.Build.VERSION_CODES.KITKAT) @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); // Immersive mode for kitkat if (Prefs.getImmersiveMode(MainActivity.this) && android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT && hasFocus) { getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE);} // Fullscreen for non-kitkat devices else if (Prefs.getImmersiveMode(MainActivity.this) && hasFocus) { MainActivity.this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); } } public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_main, menu); return super.onCreateOptionsMenu(menu); } public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; case R.id.menu_main_settings: Intent intent = new Intent(MainActivity.this, Prefs.class); startActivity(intent); return true; } return super.onOptionsItemSelected(item); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putIntArray("main_life", life); } @Override public void onPause() { getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); super.onPause(); } @Override public void onResume() { getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); super.onPause(); } }
package com.sintef_energy.ubisolar.configuration; import com.yammer.dropwizard.config.Configuration; import com.fasterxml.jackson.annotation.JsonProperty; import com.yammer.dropwizard.db.DatabaseConfiguration; import org.hibernate.validator.constraints.NotEmpty; import javax.validation.Valid; import javax.validation.constraints.NotNull; public class ServerConfiguration extends Configuration { @Valid @NotNull @JsonProperty private DatabaseConfiguration database = new DatabaseConfiguration(); public ServerConfiguration() { database.setUrl("jdbc:mysql://188.226.188.11/haavarhl_it2901"); database.setUser("haavarhl_it2901"); database.setPassword("julebrus"); database.setDriverClass("com.mysql.jdbc.Driver"); } public DatabaseConfiguration getDatabaseConfiguration() { return database; } }
package com.jivesoftware.os.routing.bird.server.oauth.validator; import com.jivesoftware.os.mlogger.core.MetricLogger; import com.jivesoftware.os.mlogger.core.MetricLoggerFactory; import com.jivesoftware.os.routing.bird.server.oauth.AuthValidationException; import org.glassfish.jersey.oauth1.signature.OAuth1Parameters; import org.glassfish.jersey.oauth1.signature.OAuth1Request; import org.glassfish.jersey.oauth1.signature.OAuth1Signature; public class DryRunOAuthValidator implements AuthValidator<OAuth1Signature, OAuth1Request> { private static final MetricLogger LOG = MetricLoggerFactory.getLogger(); private final AuthValidator<OAuth1Signature, OAuth1Request> authValidator; public DryRunOAuthValidator(AuthValidator<OAuth1Signature, OAuth1Request> authValidator) { this.authValidator = authValidator; } @Override public AuthValidationResult isValid(OAuth1Signature verifier, OAuth1Request request) throws AuthValidationException { OAuth1Parameters params = new OAuth1Parameters(); params.readRequest(request); String consumerKey = params.getConsumerKey(); try { AuthValidationResult result = authValidator.isValid(verifier, request); if (result.authorized) { LOG.info("Dry run validation passed for consumerKey:{}", consumerKey); return result; } else { LOG.info("Dry run validation failed for consumerKey:{}", consumerKey); return new AuthValidationResult(consumerKey, true); } } catch (AuthValidationException x) { if (LOG.isDebugEnabled()) { LOG.debug("Dry run validation failed for consumerKey:{}", new Object[]{consumerKey}, x); } else { LOG.warn("Dry run validation failed for consumerKey:{}", consumerKey); } return new AuthValidationResult(consumerKey, true); } } @Override public void clearSecretCache() { authValidator.clearSecretCache(); } @Override public void start() { authValidator.start(); } @Override public void stop() { authValidator.stop(); } }
package com.example.timestamp; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import javax.mail.MessagingException; import javax.mail.internet.AddressException; import android.app.ActionBar.LayoutParams; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnFocusChangeListener; import android.view.View.OnHoverListener; import android.view.View.OnTouchListener; import android.widget.*; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.LinearLayout; import android.widget.PopupWindow; import android.widget.Spinner; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; import android.widget.Toast; import com.example.timestamp.model.DB; import com.example.timestamp.model.Exporter; import com.example.timestamp.model.Project; import com.example.timestamp.model.SettingsManager; import com.example.timestamp.model.TimePost; import com.example.timestamp.model.Callbacker; public class ConfirmReport extends Fragment implements Callbacker{ public String[] projectsMenuString; // = {"Projekt 1", "Projekt 2", "Nytt projekt"}; public int[] projectMenuIds; private ArrayList<Project> projects; //private DB db; private Button button; private View rootView; private FragmentActivity parentActivity; private Callbacker callBack = this; private Spinner spinner; private CheckBox checkBoxShowSigned; private boolean handledIntent = false; private boolean allItemsSelected; //Fr popup vyn private Button editTimePostButton, addNewTimePostButton; boolean click = true; PopupWindow popUp; LinearLayout layout; TextView tv; LayoutParams params; LinearLayout mainLayout; Button but; //END Fr popup vyn private boolean showSigned= false; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { rootView = inflater.inflate(R.layout.activity_confirmreport, container, false); //db = new DB(getActivity().getApplicationContext()); //activityInitConfirmReport(); editTimePostButton = (Button) rootView.findViewById(R.id.sendReportButton); addNewTimePostButton = (Button) rootView.findViewById(R.id.addNewPost); checkBoxShowSigned = (CheckBox) rootView.findViewById(R.id.checkBoxShowSigned); //popUp = new PopupWindow(); addEditTimePostButtonListener(); addNewTimePostButtonListener(); addCheckBoxShowSignedListener(); return rootView; } public void addEditTimePostButtonListener(){ editTimePostButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //Intent intent = new Intent(getActivity(), EditReport.class); //startActivity(intent); if (click) { popUp.showAtLocation(rootView, Gravity.BOTTOM, 10, 10); popUp.update(50, 50, 300, 80); click = false; } else { popUp.dismiss(); click = true; } } }); } public void addNewTimePostButtonListener(){ addNewTimePostButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Log.d("Confirm report", "Add new time post"); int new_time_post_id = 0; //Call edit post for new post.Check if id is 0 and in that case adjust buttons with Add and Cancel. Intent editIntent = new Intent(getActivity(), EditReport.class); editIntent.putExtra(Constants.TIME_POST_ID, new_time_post_id); startActivity(editIntent); } }); } @Override public void onResume() { super.onResume(); activityInitConfirmReport(); //plotTimeTable(SettingsManager.getCurrentProjectId(parentActivity)); } public void addCheckBoxShowSignedListener() { checkBoxShowSigned.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { int currentProject = SettingsManager.getCurrentProjectId(getActivity()); showSigned = isChecked; if(allItemsSelected){ currentProject = -1; } plotTimeTable(currentProject); } }); } public void activityInitConfirmReport(){ parentActivity = getActivity(); //Letar efter en spinner i activity_main.xml med ett specifict id spinner = (Spinner) rootView.findViewById(R.id.projects_menu_spinner2); int selectedRow = 0; int currentProject; if (!handledIntent && parentActivity.getIntent().getAction() == Constants.SEND_TIMES_ACTION) { currentProject = parentActivity.getIntent().getIntExtra(Constants.PROJECT_ID, 0); SettingsManager.setCurrentProjectId(currentProject, parentActivity); handledIntent = true; } else currentProject = SettingsManager.getCurrentProjectId(parentActivity); DB db = new DB(getActivity().getApplicationContext()); projects = db.getAllProjects(); projectsMenuString = new String[projects.size() + 1]; projectMenuIds = new int[projects.size()+1]; for (int n = 0; n < projects.size(); n++) { projectsMenuString[n] = projects.get(n).getName(); projectMenuIds[n] = projects.get(n).getId(); if (currentProject == projectMenuIds[n]) selectedRow = n; } projectsMenuString[projects.size()]= "List all projects"; projectMenuIds[projects.size()] = -1; //Get names from a string array with menu items. ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, projectsMenuString){ // Style fr Spinnern.. Stter textstorlek samt centrerar.. public View getView(int position, View convertView,ViewGroup parent) { View v = super.getView(position, convertView, parent); ((TextView) v).setGravity(Gravity.CENTER); ((TextView) v).setTextColor(Color.WHITE); ((TextView) v).setTextSize(25); return v; } //Style for drop down menu under spinner.. public View getDropDownView(int position, View convertView,ViewGroup parent) { View v = super.getDropDownView(position, convertView,parent); ((TextView) v).setGravity(Gravity.CENTER); ((TextView) v).setBackgroundColor(Color.BLACK); ((TextView) v).setTextColor(Color.WHITE); ((TextView) v).setTextSize(18); return v; } }; //Spinner uses items from an adapter. spinner.setAdapter(adapter); spinnerListener(); spinner.setSelection(selectedRow); button = (Button) rootView.findViewById(R.id.sendReportButton); button.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View arg0){ new Exporter("Are you sure you want to send in the report?", new DB(getActivity()).getUnsignedTimes(), getActivity(), callBack); } }); plotTimeTable(currentProject); } public void plotTimeTable(int projectID){ DB db = new DB(getActivity()); TableLayout table = (TableLayout) rootView.findViewById(R.id.time_table); ArrayList<TimePost> times; //Return if no time posts exist for a given project if (!allItemsSelected) { //Get list of time posts if(showSigned){ times = db.getTimePosts(projectID); }else{ times = db.getUnsignedTimes(projectID); } } else { //Get list of All time posts if(showSigned){ times = db.getTimePosts(); }else{ times = db.getUnsignedTimes(); } } //Remove old rows from table (except the header row) int numRows = table.getChildCount(); if (numRows > 1) table.removeViews(1, numRows - 1); //Add time posts to the table for(int i = 0; i < times.size(); ++i){ //Init objects TableRow row = new TableRow(rootView.getContext()); TextView day = new TextView(rootView.getContext()); TextView interval = new TextView(rootView.getContext()); TextView time = new TextView(rootView.getContext()); TextView comment = new TextView(rootView.getContext()); GregorianCalendar start = times.get(i).startTime; //Put data in text views if(true) { //TODO: Chose how much detail to show.. if(LARGESCREEN) day.setText(Constants.WEEK_DAY_STRINGS[start.get(Calendar.DAY_OF_WEEK) - 1]); interval.setText(times.get(i).FormatedTimeInterval()); time.setText(times.get(i).getWorkedHoursFormated() + "h"); String com = times.get(i).comment; if(com.length() > 10) com = com.substring(0, 8) + "..."; comment.setText(com); } //else //Show less detail if small screen //Config text views LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT); day.setGravity(Gravity.CENTER); day.setTextColor(Color.BLACK); interval.setGravity(Gravity.CENTER); interval.setTextColor(Color.BLACK); time.setGravity(Gravity.CENTER); time.setTextColor(Color.BLACK); comment.setGravity(Gravity.CENTER); comment.setTextColor(Color.BLACK); //Add text views to object row.addView(day); row.addView(interval); row.addView(time); row.addView(comment); //Config row if(i%2 == 1) row.setBackgroundColor(Color.parseColor("#CCCCCC")); row.setPadding(3, 8, 3, 8); row.setClickable(true); row.setId(times.get(i).id); row.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { //Start the EditReport activity Intent editIntent = new Intent(getActivity(), EditReport.class); editIntent.putExtra(Constants.TIME_POST_ID, v.getId()); startActivity(editIntent); } }); //Test with focus colors // row.setFocusableInTouchMode(true); // row.setOnFocusChangeListener(new OnFocusChangeListener(){ // @Override // public void onFocusChange(View v, boolean isFocused) { // //Inform the user the button has been clicked // if (isFocused) // v.setBackgroundColor(Color.RED); // else // v.setBackgroundColor(Color.WHITE); //Add row to table table.addView(row, new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); } //End of for loop } public void spinnerListener() { spinner.setOnItemSelectedListener(new OnItemSelectedListener(){ @Override public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { // TODO Auto-generated method stub if(projectMenuIds[pos] != -1){ allItemsSelected = false; SettingsManager.setCurrentProjectId(projectMenuIds[pos], getActivity()); plotTimeTable(projectMenuIds[pos]); addNewTimePostButton.setEnabled(true); editTimePostButton.setEnabled(true); }else{ allItemsSelected = true; plotTimeTable(-1); // If all projects are chosen it will not be able to add a time post addNewTimePostButton.setEnabled(false); } } @Override public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub } }); } @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); if (isVisibleToUser) { if (rootView != null) activityInitConfirmReport(); }//plotTimeTable(SettingsManager.getCurrentProjectId(parentActivity)); } else { } } //this method get called from Exporter as a callback when the thread finishes @Override public void callback() { int currentProject = SettingsManager.getCurrentProjectId(getActivity()); if(allItemsSelected) currentProject = -1; plotTimeTable(currentProject); } }
package org.duracloud.services.duplication.impl; import org.duracloud.services.duplication.ContentDuplicator; import org.duracloud.services.duplication.error.DuplicationException; import org.duracloud.services.duplication.result.DuplicationEvent; import org.duracloud.services.duplication.result.ResultListener; import org.easymock.Capture; import org.easymock.EasyMock; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static org.duracloud.services.duplication.impl.ContentDuplicatorReportingImplTest.MODE.CREATE_SUCCESS; import static org.duracloud.services.duplication.impl.ContentDuplicatorReportingImplTest.MODE.UPDATE_SUCCESS; import static org.duracloud.services.duplication.impl.ContentDuplicatorReportingImplTest.MODE.DELETE_SUCCESS; import static org.duracloud.services.duplication.impl.ContentDuplicatorReportingImplTest.MODE.CREATE_ERROR; import static org.duracloud.services.duplication.impl.ContentDuplicatorReportingImplTest.MODE.UPDATE_ERROR; import static org.duracloud.services.duplication.impl.ContentDuplicatorReportingImplTest.MODE.DELETE_ERROR; public class ContentDuplicatorReportingImplTest { private ContentDuplicatorReportingImpl contentDuplicatorReporting; private ContentDuplicator contentDuplicator; private ResultListener listener; private static final String fromStoreId = "from-store-id"; private static final String toStoreId = "to-store-id"; private final String spaceId = "space-id"; private final String contentId = "content-id"; private final long waitMillis = 1; @Before public void setUp() throws Exception { contentDuplicator = EasyMock.createMock("ContentDuplicator", ContentDuplicator.class); EasyMock.expect(contentDuplicator.getFromStoreId()) .andReturn(fromStoreId).anyTimes(); EasyMock.expect(contentDuplicator.getToStoreId()) .andReturn(toStoreId).anyTimes(); listener = EasyMock.createMock("ResultListener", ResultListener.class); } @After public void tearDown() throws Exception { EasyMock.verify(contentDuplicator, listener); contentDuplicatorReporting.stop(); } private void replayMocks() { EasyMock.replay(contentDuplicator, listener); } @Test public void testStop() throws Exception { // set up mocks List<String> contents = new ArrayList<String>(); List<Capture<DuplicationEvent>> captures = new ArrayList<Capture<DuplicationEvent>>(); createStopMocks(contents, captures); replayMocks(); // create object under test contentDuplicatorReporting = new ContentDuplicatorReportingImpl( contentDuplicator, listener); // exercise the test scenario for (String content : contents) { contentDuplicatorReporting.createContent(spaceId, content); } Thread.sleep(3000); contentDuplicatorReporting.stop(); // verify Assert.assertEquals(contents.size(), captures.size()); for (Capture<DuplicationEvent> capture : captures) { DuplicationEvent event = capture.getValue(); Assert.assertNotNull(event); Assert.assertFalse(event.isSuccess()); } Assert.assertFalse(contentDuplicatorReporting.eventsExist()); } private void createStopMocks(List<String> contents, List<Capture<DuplicationEvent>> captures) { for (int i = 0; i < 5; ++i) { String content = contentId + "-" + i; contents.add(content); Capture<DuplicationEvent> capture = new Capture<DuplicationEvent>(); captures.add(capture); listener.processResult(EasyMock.capture(capture)); EasyMock.expectLastCall(); } EasyMock.makeThreadSafe(contentDuplicator, true); } @Test public void testCreateSpace() throws Exception { doTestSpace(CREATE_SUCCESS); } @Test public void testCreateSpaceError() throws Exception { doTestSpace(CREATE_ERROR); } @Test public void testUpdateSpace() throws Exception { doTestSpace(UPDATE_SUCCESS); } @Test public void testUpdateSpaceError() throws Exception { doTestSpace(UPDATE_ERROR); } @Test public void testDeleteSpace() throws Exception { doTestSpace(DELETE_SUCCESS); } @Test public void testDeleteSpaceError() throws Exception { doTestSpace(DELETE_ERROR); } private void doTestSpace(MODE mode) throws Exception { Capture<DuplicationEvent> capture = createMocks(mode); replayMocks(); contentDuplicatorReporting = new ContentDuplicatorReportingImpl( contentDuplicator, listener, waitMillis); switch (mode) { case CREATE_SUCCESS: case CREATE_ERROR: contentDuplicatorReporting.createContent(spaceId, contentId); break; case UPDATE_SUCCESS: case UPDATE_ERROR: contentDuplicatorReporting.updateContent(spaceId, contentId); break; case DELETE_SUCCESS: case DELETE_ERROR: contentDuplicatorReporting.deleteContent(spaceId, contentId); break; } waitForCompletion(); DuplicationEvent event = capture.getValue(); Assert.assertNotNull(event); Assert.assertEquals(mode.isValid(), event.isSuccess()); Assert.assertEquals(mode.getType(), event.getType()); } private Capture<DuplicationEvent> createMocks(MODE mode) { switch (mode) { case CREATE_SUCCESS: EasyMock.expect(contentDuplicator.createContent(spaceId, contentId)) .andReturn("md5"); break; case UPDATE_SUCCESS: contentDuplicator.updateContent(spaceId, contentId); EasyMock.expectLastCall(); break; case DELETE_SUCCESS: contentDuplicator.deleteContent(spaceId, contentId); EasyMock.expectLastCall(); break; case CREATE_ERROR: contentDuplicator.createContent(spaceId, contentId); EasyMock.expectLastCall().andThrow(new DuplicationException( "canned-exception")).times( SpaceDuplicatorReportingImpl.MAX_RETRIES + 1); EasyMock.makeThreadSafe(contentDuplicator, true); break; case UPDATE_ERROR: contentDuplicator.updateContent(spaceId, contentId); EasyMock.expectLastCall().andThrow(new DuplicationException( "canned-exception")).times( SpaceDuplicatorReportingImpl.MAX_RETRIES + 1); EasyMock.makeThreadSafe(contentDuplicator, true); break; case DELETE_ERROR: contentDuplicator.deleteContent(spaceId, contentId); EasyMock.expectLastCall().andThrow(new DuplicationException( "canned-exception")).times( SpaceDuplicatorReportingImpl.MAX_RETRIES + 1); EasyMock.makeThreadSafe(contentDuplicator, true); break; default: Assert.fail("Unexpected mode: " + mode); } Capture<DuplicationEvent> capturedResult = new Capture<DuplicationEvent>(); listener.processResult(EasyMock.capture(capturedResult)); return capturedResult; } private void waitForCompletion() throws InterruptedException { final long maxWait = 8000; long waited = 0; long wait = 400; while (contentDuplicatorReporting.eventsExist()) { Thread.sleep(wait); waited += wait; if (waited > maxWait) { Assert.fail("test exceeded time limit: " + maxWait); } } } protected enum MODE { CREATE_SUCCESS(true, DuplicationEvent.TYPE.CONTENT_CREATE), UPDATE_SUCCESS(true, DuplicationEvent.TYPE.CONTENT_UPDATE), DELETE_SUCCESS(true, DuplicationEvent.TYPE.CONTENT_DELETE), CREATE_ERROR(false, DuplicationEvent.TYPE.CONTENT_CREATE), UPDATE_ERROR(false, DuplicationEvent.TYPE.CONTENT_UPDATE), DELETE_ERROR(false, DuplicationEvent.TYPE.CONTENT_DELETE); private boolean valid; private DuplicationEvent.TYPE type; private MODE(boolean valid, DuplicationEvent.TYPE type) { this.valid = valid; this.type = type; } public boolean isValid() { return valid; } public DuplicationEvent.TYPE getType() { return type; } } }
package com.google.sitebricks.rendering.control; import com.google.sitebricks.Evaluator; import com.google.sitebricks.MvelEvaluator; import com.google.sitebricks.Respond; import com.google.sitebricks.RespondersForTesting; import com.google.sitebricks.compiler.ExpressionCompileException; import com.google.sitebricks.conversion.DummyTypeConverter; import com.google.sitebricks.conversion.TypeConverter; import com.google.sitebricks.rendering.DynTypedMvelEvaluatorCompiler; import org.mvel2.optimizers.OptimizerFactory; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.lang.reflect.Type; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; /** * @author Dhanji R. Prasanna (dhanji@gmail.com) */ public class RepeatWidgetTest { private static final String LISTS_AND_TIMES = "listsAndTimes"; private static final String EXPRS_AND_OBJECTS = "exprsNObjs"; private static final String A_NAME = "Dhanji"; @DataProvider(name = LISTS_AND_TIMES) public Object[][] getlistsAndTimes() { return new Object[][] { { 5, Arrays.asList(1,2,3,4,4) }, { 4, Arrays.asList(1,2,3,4) }, { 16, Arrays.asList(1,2,3,2,2,2,2,1,2,1,2,1,2,1,2,2) }, { 0, Arrays.asList() }, }; } @Test(dataProvider = LISTS_AND_TIMES) public final void repeatNumberOfTimes(int should, final Collection<Integer> ints) { final int[] times = new int[1]; final WidgetChain mockChain = new ProceedingWidgetChain() { @Override public void render(Object bound, Respond respond) { times[0]++; } }; RepeatWidget widget = new RepeatWidget(mockChain, "items=beans", new MvelEvaluator()); widget.setConverter(new DummyTypeConverter()); widget.render(new HashMap<String, Object>() {{ put("beans", ints); }}, RespondersForTesting.newRespond()); assert times[0] == should : "Did not run expected number of times: " + should; } @DataProvider(name = EXPRS_AND_OBJECTS) public Object[][] getExpressionsAndObjects() { return new Object[][] { { "items=things, var='thing', pageVar='page'", new HashMap<String, Object>() {{ put("things", Arrays.asList(new Thing(), new Thing(), new Thing())); }}, 3, "thing" }, { "items=things, pageVar='page'", new HashMap<String, Object>() {{ put("things", Arrays.asList(new Thing(), new Thing(), new Thing())); }}, 3, "__this" }, { "items=things, var='thingy', pageVar='page'", new HashMap<String, Object>() {{ put("things", Arrays.asList(new Thing(), new Thing(), new Thing())); }}, 3, "thingy" } }; } // @Test(dataProvider = EXPRS_AND_OBJECTS) public final void repeatNumberOfTimesWithVars(String expression, Object page, int should, final String exp) throws ExpressionCompileException { OptimizerFactory.setDefaultOptimizer(OptimizerFactory.SAFE_REFLECTIVE); final int[] times = new int[1]; final Evaluator evaluator = new DynTypedMvelEvaluatorCompiler(null).compile(exp); final WidgetChain mockChain = new ProceedingWidgetChain() { @Override public void render(final Object bound, Respond respond) { times[0]++; final Object thing = evaluator.evaluate(exp, bound); assert thing instanceof Thing : "Contextual (current) var not set: " + thing; assert A_NAME.equals(((Thing)thing).getName()); } }; new RepeatWidget(mockChain, expression, evaluator) .render(page, RespondersForTesting.newRespond()); assert times[0] == should : "Did not run expected number of times: " + should; } public static class Thing { private String name = A_NAME; public String getName() { return name; } public void setName(String name) { this.name = name; } } }
package org.gazzax.labs.solrdf.graph.cloud; import static org.gazzax.labs.solrdf.NTriples.asNtURI; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.impl.CloudSolrServer; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrException; import org.apache.solr.common.SolrException.ErrorCode; import org.apache.solr.request.SolrQueryRequest; import org.apache.solr.response.SolrQueryResponse; import org.apache.solr.search.QParser; import org.apache.solr.update.processor.DistributedUpdateProcessor; import org.gazzax.labs.solrdf.Field; import org.gazzax.labs.solrdf.graph.DatasetGraphSupertypeLayer; import org.gazzax.labs.solrdf.graph.GraphEventConsumer; import org.gazzax.labs.solrdf.graph.standalone.LocalDatasetGraph; import com.hp.hpl.jena.graph.Graph; import com.hp.hpl.jena.graph.Node; /** * A read only SolRDF implementation of a Jena Dataset. * This is a read only dataset graph because changes (i.e. updates and deletes) are executed using * {@link DistributedUpdateProcessor}; that means each node will be responsible to apply local changes using * its own {@link LocalDatasetGraph} instance. * * @author Andrea Gazzarini * @since 1.0 */ public class ReadOnlyCloudDatasetGraph extends DatasetGraphSupertypeLayer { protected CloudSolrServer cloud; /** * Builds a new Dataset graph with the given data. * * @param request the Solr query request. * @param response the Solr query response. */ public ReadOnlyCloudDatasetGraph( final SolrQueryRequest request, final SolrQueryResponse response) { super(request, response, null, null); } /** * Builds a new Dataset graph with the given data. * * @param request the Solr query request. * @param response the Solr query response. * @param qParser the (SPARQL) query parser. * */ public ReadOnlyCloudDatasetGraph( final SolrQueryRequest request, final SolrQueryResponse response, final QParser qParser, final GraphEventConsumer listener) { super(request, response, qParser, listener != null ? listener : NULL_GRAPH_EVENT_CONSUMER); this.cloud = new CloudSolrServer(request.getCore().getCoreDescriptor().getCoreContainer().getZkController().getZkServerAddress()); this.cloud.setDefaultCollection(request.getCore().getName()); } @Override public void close() { cloud.shutdown(); } @Override protected Graph _createNamedGraph(final Node graphNode) { return new ReadOnlyCloudGraph(graphNode, cloud, qParser, ReadOnlyCloudGraph.DEFAULT_QUERY_FETCH_SIZE, listener); } @Override protected Graph _createDefaultGraph() { return new ReadOnlyCloudGraph(null, cloud, qParser, ReadOnlyCloudGraph.DEFAULT_QUERY_FETCH_SIZE, listener); } @Override protected boolean _containsGraph(final Node graphNode) { final SolrQuery query = new SolrQuery("*:*"); query.addFilterQuery(Field.C + ":\"" + asNtURI(graphNode) + "\""); query.setRequestHandler("/solr-query"); query.setRows(0); try { final QueryResponse response = cloud.query(query); return response.getResults().getNumFound() > 0; } catch (final Exception exception) { throw new SolrException(ErrorCode.SERVER_ERROR, exception); } } }
package org.springframework.cloud.bus; import java.util.HashMap; import java.util.Map; import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.endpoint.Endpoint; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.cloud.bus.endpoint.BusEndpoint; import org.springframework.cloud.bus.endpoint.EnvironmentBusEndpoint; import org.springframework.cloud.bus.endpoint.RefreshBusEndpoint; import org.springframework.cloud.bus.event.EnvironmentChangeListener; import org.springframework.cloud.bus.event.RefreshListener; import org.springframework.cloud.bus.event.RemoteApplicationEvent; import org.springframework.cloud.context.environment.EnvironmentManager; import org.springframework.cloud.context.scope.refresh.RefreshScope; import org.springframework.cloud.endpoint.RefreshEndpoint; import org.springframework.cloud.stream.annotation.EnableBinding; import org.springframework.cloud.stream.annotation.Output; import org.springframework.cloud.stream.config.BindingProperties; import org.springframework.cloud.stream.config.ChannelBindingServiceProperties; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisherAware; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.event.EventListener; import org.springframework.integration.annotation.ServiceActivator; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.support.MessageBuilder; import org.springframework.util.AntPathMatcher; import org.springframework.util.PathMatcher; /** * @author Spencer Gibb * @author Dave Syer */ @Configuration @ConditionalOnBusEnabled @EnableBinding(SpringCloudBusClient.class) @EnableConfigurationProperties(BusProperties.class) public class BusAutoConfiguration implements ApplicationEventPublisherAware { public static final String BUS_PATH_MATCHER_NAME = "busPathMatcher"; @Autowired @Output(SpringCloudBusClient.OUTPUT) private MessageChannel cloudBusOutboundChannel; @Autowired private ServiceMatcher serviceMatcher; @Autowired private ChannelBindingServiceProperties bindings; @Autowired private BusProperties bus; private ApplicationEventPublisher applicationEventPublisher; @PostConstruct public void init() { BindingProperties inputBinding = this.bindings.getBindings().get(SpringCloudBusClient.INPUT); if (inputBinding == null) { this.bindings.getBindings().put(SpringCloudBusClient.INPUT, new BindingProperties()); } BindingProperties input = this.bindings.getBindings().get(SpringCloudBusClient.INPUT); if (input.getDestination() == null) { input.setDestination(this.bus.getDestination()); } BindingProperties outputBinding = this.bindings.getBindings().get(SpringCloudBusClient.OUTPUT); if (outputBinding == null) { this.bindings.getBindings().put(SpringCloudBusClient.OUTPUT, new BindingProperties()); } BindingProperties output = this.bindings.getBindings().get(SpringCloudBusClient.OUTPUT); if (output.getDestination() == null) { output.setDestination(this.bus.getDestination()); } } @Override public void setApplicationEventPublisher( ApplicationEventPublisher applicationEventPublisher) { this.applicationEventPublisher = applicationEventPublisher; } @EventListener(classes = RemoteApplicationEvent.class) public void acceptLocal(RemoteApplicationEvent event) { if (this.serviceMatcher.isFromSelf(event)) { this.cloudBusOutboundChannel.send(MessageBuilder.withPayload(event).build()); } } @ServiceActivator(inputChannel = SpringCloudBusClient.INPUT) public void acceptRemote(RemoteApplicationEvent event) { if (!this.serviceMatcher.isFromSelf(event) && this.serviceMatcher.isForSelf(event) && this.applicationEventPublisher != null) { this.applicationEventPublisher.publishEvent(event); } } @Configuration protected static class MatcherConfiguration { @BusPathMatcher // There is a @Bean of type PathMatcher coming from Spring MVC @ConditionalOnMissingBean(name = BusAutoConfiguration.BUS_PATH_MATCHER_NAME) @Bean(name = BusAutoConfiguration.BUS_PATH_MATCHER_NAME) public PathMatcher busPathMatcher() { return new AntPathMatcher(":"); } @Bean public ServiceMatcher serviceMatcher(@BusPathMatcher PathMatcher pathMatcher) { ServiceMatcher serviceMatcher = new ServiceMatcher(); serviceMatcher.setMatcher(pathMatcher); return serviceMatcher; } } @Configuration @ConditionalOnClass(Endpoint.class) protected static class BusEndpointConfiguration { @Bean public BusEndpoint busEndpoint() { return new BusEndpoint(); } } @Configuration @ConditionalOnClass({ Endpoint.class, RefreshScope.class }) @ConditionalOnBean(RefreshEndpoint.class) protected static class BusRefreshConfiguration { @Bean @ConditionalOnProperty(value = "spring.cloud.bus.refresh.enabled", matchIfMissing = true) public RefreshListener refreshListener(RefreshEndpoint refreshEndpoint) { return new RefreshListener(refreshEndpoint); } @Configuration @ConditionalOnProperty(value = "endpoints.spring.cloud.bus.refresh.enabled", matchIfMissing = true) protected static class BusRefreshEndpointConfiguration { @Bean public RefreshBusEndpoint refreshBusEndpoint(ApplicationContext context, BusEndpoint busEndpoint) { return new RefreshBusEndpoint(context, context.getId(), busEndpoint); } } } @Configuration @ConditionalOnClass(EnvironmentManager.class) @ConditionalOnBean(EnvironmentManager.class) protected static class BusEnvironmentConfiguration { @Bean @ConditionalOnProperty(value = "spring.cloud.bus.env.enabled", matchIfMissing = true) public EnvironmentChangeListener environmentChangeListener() { return new EnvironmentChangeListener(); } @Configuration @ConditionalOnClass(Endpoint.class) @ConditionalOnProperty(value = "endpoints.spring.cloud.bus.env.enabled", matchIfMissing = true) protected static class EnvironmentBusEndpointConfiguration { @Bean public EnvironmentBusEndpoint environmentBusEndpoint( ApplicationContext context, BusEndpoint busEndpoint) { return new EnvironmentBusEndpoint(context, context.getId(), busEndpoint); } } } }
package org.objectweb.proactive.core.runtime; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.rmi.AlreadyBoundException; import java.security.AccessControlException; import java.security.PublicKey; import java.util.List; import org.objectweb.proactive.Body; import org.objectweb.proactive.core.ProActiveException; import org.objectweb.proactive.core.body.UniversalBody; import org.objectweb.proactive.core.body.ft.checkpointing.Checkpoint; import org.objectweb.proactive.core.descriptor.data.ProActiveDescriptorInternal; import org.objectweb.proactive.core.descriptor.data.VirtualNodeInternal; import org.objectweb.proactive.core.filetransfer.FileTransferEngine; import org.objectweb.proactive.core.jmx.mbean.ProActiveRuntimeWrapperMBean; import org.objectweb.proactive.core.jmx.notification.GCMRuntimeRegistrationNotificationData; import org.objectweb.proactive.core.jmx.server.ServerConnector; import org.objectweb.proactive.core.mop.ConstructorCall; import org.objectweb.proactive.core.mop.ConstructorCallExecutionFailedException; import org.objectweb.proactive.core.node.NodeException; import org.objectweb.proactive.core.process.UniversalProcess; import org.objectweb.proactive.core.remoteobject.adapter.Adapter; import org.objectweb.proactive.core.security.PolicyServer; import org.objectweb.proactive.core.security.ProActiveSecurityManager; import org.objectweb.proactive.core.security.SecurityContext; import org.objectweb.proactive.core.security.TypedCertificate; import org.objectweb.proactive.core.security.crypto.KeyExchangeException; import org.objectweb.proactive.core.security.crypto.SessionException; import org.objectweb.proactive.core.security.exceptions.RenegotiateSessionException; import org.objectweb.proactive.core.security.exceptions.SecurityNotAvailableException; import org.objectweb.proactive.core.security.securityentity.Entities; import org.objectweb.proactive.core.security.securityentity.Entity; /** * @author acontes * this class provides some additional behaviours expected when talking with a * runtime. * - cache the vmInformation field */ public class ProActiveRuntimeRemoteObjectAdapter extends Adapter<ProActiveRuntime> implements ProActiveRuntime { /** * generated serial uid */ private static final long serialVersionUID = -8238213803072932083L; /** * Cache the vmInformation field */ protected VMInformation vmInformation; public ProActiveRuntimeRemoteObjectAdapter() { // empty non arg constructor } public ProActiveRuntimeRemoteObjectAdapter(ProActiveRuntime u) { super(u); } /* (non-Javadoc) * @see org.objectweb.proactive.core.remoteobject.adapter.Adapter#construct() */ @Override protected void construct() { this.vmInformation = target.getVMInformation(); } public void addAcquaintance(String proActiveRuntimeName) throws ProActiveException { target.addAcquaintance(proActiveRuntimeName); } public UniversalBody createBody(String nodeName, ConstructorCall bodyConstructorCall, boolean isNodeLocal) throws ProActiveException, ConstructorCallExecutionFailedException, InvocationTargetException { return target.createBody(nodeName, bodyConstructorCall, isNodeLocal); } public String createLocalNode(String nodeName, boolean replacePreviousBinding, ProActiveSecurityManager nodeSecurityManager, String vnName, String jobId) throws NodeException, AlreadyBoundException { return target.createLocalNode(nodeName, replacePreviousBinding, nodeSecurityManager, vnName, jobId); } public void createVM(UniversalProcess remoteProcess) throws IOException, ProActiveException { target.createVM(remoteProcess); } public String[] getAcquaintances() throws ProActiveException { return target.getAcquaintances(); } public List<UniversalBody> getActiveObjects(String nodeName) throws ProActiveException { return target.getActiveObjects(nodeName); } public List<UniversalBody> getActiveObjects(String nodeName, String className) throws ProActiveException { return target.getActiveObjects(nodeName, className); } public byte[] getClassDataFromParentRuntime(String className) throws ProActiveException { return target.getClassDataFromParentRuntime(className); } public byte[] getClassDataFromThisRuntime(String className) throws ProActiveException { return target.getClassDataFromThisRuntime(className); } public ProActiveDescriptorInternal getDescriptor(String url, boolean isHierarchicalSearch) throws IOException, ProActiveException { return target.getDescriptor(url, isHierarchicalSearch); } public FileTransferEngine getFileTransferEngine() { return target.getFileTransferEngine(); } public ServerConnector getJMXServerConnector() { return target.getJMXServerConnector(); } public String getJobID(String nodeUrl) throws ProActiveException { return target.getJobID(nodeUrl); } public String[] getLocalNodeNames() throws ProActiveException { return target.getLocalNodeNames(); } public String getLocalNodeProperty(String nodeName, String key) throws ProActiveException { return target.getLocalNodeProperty(nodeName, key); } public ProActiveRuntimeWrapperMBean getMBean() { return target.getMBean(); } public String getMBeanServerName() { return target.getMBeanServerName(); } public ProActiveRuntime getProActiveRuntime(String proActiveRuntimeName) throws ProActiveException { return target.getProActiveRuntime(proActiveRuntimeName); } public ProActiveRuntime[] getProActiveRuntimes() throws ProActiveException { return target.getProActiveRuntimes(); } public String getURL() { return target.getURL(); } public VMInformation getVMInformation() { return this.vmInformation; } public String getVNName(String Nodename) throws ProActiveException { return target.getVNName(Nodename); } public VirtualNodeInternal getVirtualNode(String virtualNodeName) throws ProActiveException { return target.getVirtualNode(virtualNodeName); } public void killAllNodes() throws ProActiveException { target.killAllNodes(); } public void killNode(String nodeName) throws ProActiveException { target.killNode(nodeName); } public void killRT(boolean softly) throws Exception { target.killRT(softly); } public void launchMain(String className, String[] parameters) throws ClassNotFoundException, NoSuchMethodException, ProActiveException { target.launchMain(className, parameters); } public void newRemote(String className) throws ClassNotFoundException, ProActiveException { target.newRemote(className); } public UniversalBody receiveBody(String nodeName, Body body) throws ProActiveException { return target.receiveBody(nodeName, body); } public UniversalBody receiveCheckpoint(String nodeName, Checkpoint ckpt, int inc) throws ProActiveException { return target.receiveCheckpoint(nodeName, ckpt, inc); } public void register(ProActiveRuntime proActiveRuntimeDist, String proActiveRuntimeUrl, String creatorID, String creationProtocol, String vmName) throws ProActiveException { target.register(proActiveRuntimeDist, proActiveRuntimeUrl, creatorID, creationProtocol, vmName); } public void register(GCMRuntimeRegistrationNotificationData event) { target.register(event); } public void registerVirtualNode(String virtualNodeName, boolean replacePreviousBinding) throws ProActiveException, AlreadyBoundException { target.registerVirtualNode(virtualNodeName, replacePreviousBinding); } public void rmAcquaintance(String proActiveRuntimeName) throws ProActiveException { target.rmAcquaintance(proActiveRuntimeName); } public Object setLocalNodeProperty(String nodeName, String key, String value) throws ProActiveException { return target.setLocalNodeProperty(nodeName, key, value); } public void startJMXServerConnector() { target.startJMXServerConnector(); } public void unregister(ProActiveRuntime proActiveRuntimeDist, String proActiveRuntimeUrl, String creatorID, String creationProtocol, String vmName) throws ProActiveException { target.unregister(proActiveRuntimeDist, proActiveRuntimeUrl, creatorID, creationProtocol, vmName); } public void unregisterAllVirtualNodes() throws ProActiveException { target.unregisterAllVirtualNodes(); } public void unregisterVirtualNode(String virtualNodeName) throws ProActiveException { target.unregisterVirtualNode(virtualNodeName); } public TypedCertificate getCertificate() throws SecurityNotAvailableException, IOException { return target.getCertificate(); } public Entities getEntities() throws SecurityNotAvailableException, IOException { return target.getEntities(); } public SecurityContext getPolicy(Entities local, Entities distant) throws SecurityNotAvailableException, IOException { return target.getPolicy(local, distant); } public ProActiveSecurityManager getProActiveSecurityManager(Entity user) throws SecurityNotAvailableException, AccessControlException, IOException { return target.getProActiveSecurityManager(user); } public PublicKey getPublicKey() throws SecurityNotAvailableException, IOException { return target.getPublicKey(); } public byte[] publicKeyExchange(long sessionID, byte[] signature) throws SecurityNotAvailableException, RenegotiateSessionException, KeyExchangeException, IOException { return target.publicKeyExchange(sessionID, signature); } public byte[] randomValue(long sessionID, byte[] clientRandomValue) throws SecurityNotAvailableException, RenegotiateSessionException, IOException { return target.randomValue(sessionID, clientRandomValue); } public byte[][] secretKeyExchange(long sessionID, byte[] encodedAESKey, byte[] encodedIVParameters, byte[] encodedClientMacKey, byte[] encodedLockData, byte[] parametersSignature) throws SecurityNotAvailableException, RenegotiateSessionException, IOException { return target.secretKeyExchange(sessionID, encodedAESKey, encodedIVParameters, encodedClientMacKey, encodedLockData, parametersSignature); } public void setProActiveSecurityManager(Entity user, PolicyServer policyServer) throws SecurityNotAvailableException, AccessControlException, IOException { target.setProActiveSecurityManager(user, policyServer); } public long startNewSession(long distantSessionID, SecurityContext policy, TypedCertificate distantCertificate) throws SessionException, SecurityNotAvailableException, IOException { return target.startNewSession(distantSessionID, policy, distantCertificate); } public void terminateSession(long sessionID) throws SecurityNotAvailableException, IOException { target.terminateSession(sessionID); } }
// checkstyle: Checks Java source code for adherence to a set of rules. // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.puppycrawl.tools.checkstyle.checks.coding; import antlr.collections.AST; import com.puppycrawl.tools.checkstyle.api.Check; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; /** * <p> * Checks that any combination of String literals with optional * assignment is on the left side of an equals() comparison. * </p> * * <p> * Rationale: Calling the equals() method on String literals * will avoid a potential NullPointerException. Also, it is * pretty common to see null check right before equals comparisons * which is not necessary in the below example. * * For example: * * <pre> * <code> * String nullString = null; * nullString.equals(&quot;My_Sweet_String&quot;); * </code> * </pre> * should be refactored to * * <pre> * <code> * String nullString = null; * &quot;My_Sweet_String&quot;.equals(nullString); * </code> * </pre> * </p> * * <p> * Limitations: If the equals method is overridden or * a covariant equals method is defined and the implementation * is incorrect (where s.equals(t) does not return the same result * as t.equals(s)) then rearranging the called on object and * parameter may have unexpected results * * <br/> * * Java's Autoboxing feature has an affect * on how this check is implemented. Pre Java 5 all IDENT + IDENT * object concatenations would not cause a NullPointerException even * if null. Those situations could have been included in this check. * They would simply act as if they surrounded by String.valueof() * which would concatenate the String null. * </p> * <p> * The following example will cause a * NullPointerException as a result of what autoboxing does. * <pre> * Integer i = null, j = null; * String number = "5" * number.equals(i + j); * </pre> * </p> * * Since, it is difficult to determine what kind of Object is being * concatenated all ident concatenation is considered unsafe. * * @author Travis Schneeberger * version 1.0 */ public class EqualsAvoidNullCheck extends Check { // Decides whether string literals with optional assignment // assignment should be checked to be on the left side of the // equalsIgnoreCase comparison. The earlier version of this class // checked only for equals() comparison. This is added to support // cases which may not want the equalsIgnoreCase() comparison for // some reason (backward compatibility) private boolean mPerformEqualsIgnoreCaseCheck = true; @Override public int[] getDefaultTokens() { return new int[] {TokenTypes.METHOD_CALL}; } @Override public void visitToken(final DetailAST aMethodCall) { final DetailAST dot = aMethodCall.getFirstChild(); if (dot.getType() != TokenTypes.DOT) { return; } final DetailAST objCalledOn = dot.getFirstChild(); //checks for calling equals on String literal and //anon object which cannot be null //Also, checks if calling using strange inner class //syntax outter.inner.equals(otherObj) by looking //for the dot operator which cannot be improved if ((objCalledOn.getType() == TokenTypes.STRING_LITERAL) || (objCalledOn.getType() == TokenTypes.LITERAL_NEW) || (objCalledOn.getType() == TokenTypes.DOT)) { return; } final DetailAST method = objCalledOn.getNextSibling(); final DetailAST expr = dot.getNextSibling().getFirstChild(); if ("equals".equals(method.getText()) || (mPerformEqualsIgnoreCaseCheck && "equalsIgnoreCase" .equals(method.getText()))) { if (containsOneArg(expr) && containsAllSafeTokens(expr)) { log(aMethodCall.getLineNo(), aMethodCall.getColumnNo(), "equals".equals(method.getText()) ? "equals.avoid.null" : "equalsIgnoreCase.avoid.null"); } } } /** * Checks if a method contains no arguments * starting at with the argument expression. * * @param aExpr the argument expression * @return true if the method contains no args, false if not */ private boolean containsNoArgs(final AST aExpr) { return (aExpr == null); } /** * Checks if a method contains multiple arguments * starting at with the argument expression. * * @param aExpr the argument expression * @return true if the method contains multiple args, false if not */ private boolean containsMultiArgs(final AST aExpr) { final AST comma = aExpr.getNextSibling(); return (comma != null) && (comma.getType() == TokenTypes.COMMA); } /** * Checks if a method contains a single argument * starting at with the argument expression. * * @param aExpr the argument expression * @return true if the method contains a single arg, false if not */ private boolean containsOneArg(final AST aExpr) { return !containsNoArgs(aExpr) && !containsMultiArgs(aExpr); } /** * <p> * Looks for all "safe" Token combinations in the argument * expression branch. * </p> * * <p> * See class documentation for details on autoboxing's affect * on this method implementation. * </p> * * @param aExpr the argument expression * @return - true if any child matches the set of tokens, false if not */ private boolean containsAllSafeTokens(final DetailAST aExpr) { DetailAST arg = aExpr.getFirstChild(); if (arg.branchContains(TokenTypes.METHOD_CALL)) { return false; } arg = skipVariableAssign(arg); //Plus assignment can have ill affects //do not want to recommend moving expression //See example: //String s = "SweetString"; //s.equals(s += "SweetString"); //false //s = "SweetString"; //(s += "SweetString").equals(s); //true //arg = skipVariablePlusAssign(arg); if ((arg).branchContains(TokenTypes.PLUS_ASSIGN) || (arg).branchContains(TokenTypes.IDENT)) { return false; } //must be just String literals if got here return true; } /** * Skips over an inner assign portion of an argument expression. * @param aCurrentAST current token in the argument expression * @return the next relevant token */ private DetailAST skipVariableAssign(final DetailAST aCurrentAST) { if ((aCurrentAST.getType() == TokenTypes.ASSIGN) && (aCurrentAST.getFirstChild().getType() == TokenTypes.IDENT)) { return aCurrentAST.getFirstChild().getNextSibling(); } return aCurrentAST; } /** * * @param performEqualsIgnoreCaseCheck - Decides whether string literals with optional assignment assignment * should be checked to be on the left side of the equalsIgnoreCase comparision. The earlier version of this class * checked only for equals() comparision. This is added to support cases which may not want the equalsIgnoreCase() * comparision for some reason (backward compatibility) */ public void setPerformEqualsIgnoreCaseCheck(boolean performEqualsIgnoreCaseCheck) { mPerformEqualsIgnoreCaseCheck = performEqualsIgnoreCaseCheck; } }
package org.python.types; public class DictKeys extends org.python.types.FrozenSet { static { org.python.types.Type.declarePythonType(DictKeys.class,"dict_keys",null,null); } public DictKeys(org.python.types.Dict dict) { this.value = dict.value.keySet(); } /** * A utility method to create a set from an iterable object * <p> * Used by the __and__,__or__,__sub__ and __xor__ operations * obj must have a valid iterator */ private java.util.Set<org.python.Object> fromIter(org.python.Object obj) { java.util.Set<org.python.Object> generated = new java.util.HashSet<org.python.Object>(); org.python.Object iterator = org.Python.iter(obj); try { while (true) { org.python.Object next = iterator.__next__(); generated.add(next); } } catch (org.python.exceptions.StopIteration si) { } return generated; } @Override public org.python.Object __hash__() { throw new org.python.exceptions.AttributeError(this, "__hash__"); } @org.python.Method( __doc__ = "Return repr(self)." ) public org.python.types.Str __repr__() { java.lang.StringBuilder buffer = new java.lang.StringBuilder("dict_keys(["); boolean first = true; for(org.python.Object item : this.value) { if (first) { first = false; } else { buffer.append(", "); } buffer.append(String.format("%s",item.__repr__())); } buffer.append("])"); return new org.python.types.Str(buffer.toString()); } @org.python.Method( __doc__ = "", args = {"index"} ) public org.python.Object __getitem__(org.python.Object index) { if (index instanceof org.python.types.Int || index instanceof org.python.types.Bool) { throw new org.python.exceptions.TypeError("'dict_keys' object does not support indexing"); } else { throw new org.python.exceptions.TypeError("'dict_keys' object is not subscriptable"); } } @org.python.Method( __doc__ = "" ) public org.python.Object __invert__() { throw new org.python.exceptions.TypeError("bad operand type for unary ~: 'dict_keys'"); } @org.python.Method( __doc__ = "" ) public org.python.Object __pos__() { throw new org.python.exceptions.TypeError("bad operand type for unary +: 'dict_keys'"); } @org.python.Method( __doc__ = "" ) public org.python.Object __neg__() { throw new org.python.exceptions.TypeError("bad operand type for unary -: 'dict_keys'"); } @org.python.Method( __doc__ = "Return self&value." ) public org.python.types.Set __and__(org.python.Object other) { java.util.Set<org.python.Object> generated = this.fromIter(other); generated.retainAll(this.value); return new org.python.types.Set(generated); } @org.python.Method( __doc__ = "Return self|value." ) public org.python.types.Set __or__(org.python.Object other) { java.util.Set<org.python.Object> generated = this.fromIter(other); generated.addAll(this.value); return new org.python.types.Set(generated); } @org.python.Method( __doc__ = "Return self-value." ) public org.python.types.Set __sub__(org.python.Object other) { java.util.Set<org.python.Object> set1 = new java.util.HashSet<org.python.Object>(this.value); java.util.Set<org.python.Object> set2 = this.fromIter(other); set1.removeAll(set2); return new org.python.types.Set(set1); } @org.python.Method( __doc__ = "Return self^value." ) public org.python.types.Set __xor__(org.python.Object other) { java.util.Set<org.python.Object> s1 = this.fromIter(other); java.util.Set<org.python.Object> sym_dif = new java.util.HashSet<org.python.Object>(s1); sym_dif.addAll(this.value); java.util.Set<org.python.Object> tmp = new java.util.HashSet<org.python.Object>(s1); tmp.retainAll(this.value); sym_dif.removeAll(tmp); return new org.python.types.Set(sym_dif); } @org.python.Method( __doc__ = "Return True if the set has no elements in common with other. Sets are\n" + "disjoint if and only if their intersection is the empty set.", args = {"other"} ) public org.python.Object isdisjoint(org.python.Object other) { java.util.Set<org.python.Object> generated = new java.util.HashSet<org.python.Object>(); org.python.Object iterator = org.Python.iter(other); try { while (true) { org.python.Object next = iterator.__next__(); generated.add(next); } } catch (org.python.exceptions.StopIteration si) { } generated.retainAll(this.value); return new org.python.types.Bool(generated.size() > 0); } /** * The following methods are not present in Python's dict_keys but are present in DictKeys (inherited from FrozenSet) * <p> * Hence, throw an AttributeError every time any of these methods is called */ public org.python.Object issubset(org.python.Object other) { throw new org.python.exceptions.AttributeError(this,"issubset"); } public org.python.Object issuperset(org.python.Object other) { throw new org.python.exceptions.AttributeError(this,"issuperset"); } public org.python.Object union(org.python.types.Tuple others) { throw new org.python.exceptions.AttributeError(this,"union"); } public org.python.Object intersection(org.python.types.Tuple others) { throw new org.python.exceptions.AttributeError(this,"intersection"); } public org.python.Object difference(org.python.types.Tuple others) { throw new org.python.exceptions.AttributeError(this,"difference"); } public org.python.Object symmetric_difference(org.python.Object other) { throw new org.python.exceptions.AttributeError(this,"issuperset"); } }
package org.endeavourhealth.queuereader; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.base.Strings; import com.google.common.hash.HashCode; import com.google.common.hash.HashFunction; import com.google.common.hash.Hasher; import com.google.common.hash.Hashing; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVPrinter; import org.apache.commons.csv.CSVRecord; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.endeavourhealth.common.cache.ObjectMapperPool; import org.endeavourhealth.common.config.ConfigManager; import org.endeavourhealth.common.fhir.*; import org.endeavourhealth.common.ods.OdsOrganisation; import org.endeavourhealth.common.ods.OdsWebService; import org.endeavourhealth.common.utility.FileHelper; import org.endeavourhealth.common.utility.JsonSerializer; import org.endeavourhealth.common.utility.XmlSerializer; import org.endeavourhealth.core.application.ApplicationHeartbeatHelper; import org.endeavourhealth.core.configuration.PostMessageToExchangeConfig; import org.endeavourhealth.core.csv.CsvHelper; import org.endeavourhealth.core.database.dal.DalProvider; import org.endeavourhealth.core.database.dal.admin.LibraryDalI; import org.endeavourhealth.core.database.dal.admin.LibraryRepositoryHelper; import org.endeavourhealth.core.database.dal.admin.ServiceDalI; import org.endeavourhealth.core.database.dal.admin.SystemHelper; import org.endeavourhealth.core.database.dal.admin.models.ActiveItem; import org.endeavourhealth.core.database.dal.admin.models.DefinitionItemType; import org.endeavourhealth.core.database.dal.admin.models.Item; import org.endeavourhealth.core.database.dal.admin.models.Service; import org.endeavourhealth.core.database.dal.audit.ExchangeBatchDalI; import org.endeavourhealth.core.database.dal.audit.ExchangeDalI; import org.endeavourhealth.core.database.dal.audit.models.*; import org.endeavourhealth.core.database.dal.eds.PatientSearchDalI; import org.endeavourhealth.core.database.dal.ehr.ResourceDalI; import org.endeavourhealth.core.database.dal.ehr.models.ResourceWrapper; import org.endeavourhealth.core.database.dal.subscriberTransform.SubscriberInstanceMappingDalI; import org.endeavourhealth.core.database.dal.subscriberTransform.SubscriberResourceMappingDalI; import org.endeavourhealth.core.database.dal.subscriberTransform.models.SubscriberId; import org.endeavourhealth.core.database.dal.usermanager.caching.DataSharingAgreementCache; import org.endeavourhealth.core.database.dal.usermanager.caching.OrganisationCache; import org.endeavourhealth.core.database.dal.usermanager.caching.ProjectCache; import org.endeavourhealth.core.database.rdbms.ConnectionManager; import org.endeavourhealth.core.database.rdbms.datasharingmanager.models.DataSharingAgreementEntity; import org.endeavourhealth.core.database.rdbms.datasharingmanager.models.ProjectEntity; import org.endeavourhealth.core.exceptions.TransformException; import org.endeavourhealth.core.fhirStorage.FhirResourceHelper; import org.endeavourhealth.core.fhirStorage.FhirSerializationHelper; import org.endeavourhealth.core.fhirStorage.ServiceInterfaceEndpoint; import org.endeavourhealth.core.messaging.pipeline.PipelineException; import org.endeavourhealth.core.messaging.pipeline.SubscriberConfig; import org.endeavourhealth.core.messaging.pipeline.components.DetermineRelevantProtocolIds; import org.endeavourhealth.core.messaging.pipeline.components.MessageTransformOutbound; import org.endeavourhealth.core.messaging.pipeline.components.PostMessageToExchange; import org.endeavourhealth.core.messaging.pipeline.components.RunDataDistributionProtocols; import org.endeavourhealth.core.queueing.QueueHelper; import org.endeavourhealth.core.terminology.Read2Code; import org.endeavourhealth.core.terminology.SnomedCode; import org.endeavourhealth.core.terminology.TerminologyService; import org.endeavourhealth.core.xml.QueryDocument.*; import org.endeavourhealth.core.xml.TransformErrorSerializer; import org.endeavourhealth.core.xml.transformError.TransformError; import org.endeavourhealth.im.client.IMClient; import org.endeavourhealth.subscriber.filer.EnterpriseFiler; import org.endeavourhealth.subscriber.filer.SubscriberFiler; import org.endeavourhealth.transform.common.*; import org.endeavourhealth.transform.common.resourceBuilders.EpisodeOfCareBuilder; import org.endeavourhealth.transform.common.resourceBuilders.GenericBuilder; import org.endeavourhealth.transform.emis.EmisCsvToFhirTransformer; import org.endeavourhealth.transform.enterprise.EnterpriseTransformHelper; import org.endeavourhealth.transform.enterprise.ObservationCodeHelper; import org.endeavourhealth.transform.enterprise.transforms.OrganisationEnterpriseTransformer; import org.endeavourhealth.transform.fhirhl7v2.FhirHl7v2Filer; import org.endeavourhealth.transform.fhirhl7v2.transforms.EncounterTransformer; import org.endeavourhealth.transform.subscriber.IMConstant; import org.endeavourhealth.transform.subscriber.IMHelper; import org.endeavourhealth.transform.subscriber.SubscriberTransformHelper; import org.endeavourhealth.transform.subscriber.targetTables.OutputContainer; import org.endeavourhealth.transform.subscriber.targetTables.SubscriberTableId; import org.endeavourhealth.transform.subscriber.transforms.OrganisationTransformer; import org.endeavourhealth.transform.ui.helpers.BulkHelper; import org.hl7.fhir.instance.model.*; import org.hl7.fhir.instance.model.Resource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.lang.System; import java.net.URI; import java.net.URL; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.security.CodeSource; import java.security.ProtectionDomain; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.text.SimpleDateFormat; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.regex.Pattern; import java.util.stream.Collectors; import static org.endeavourhealth.core.xml.QueryDocument.ServiceContractType.PUBLISHER; public abstract class SpecialRoutines { private static final Logger LOG = LoggerFactory.getLogger(SpecialRoutines.class); *//*String rootDir = null; }*//* /*public static void populateExchangeFileSizes(String odsCodeRegex) { LOG.info("Populating Exchange File Sizes for " + odsCodeRegex); try { String sharedStoragePath = TransformConfig.instance().getSharedStoragePath(); ServiceDalI serviceDal = DalProvider.factoryServiceDal(); List<Service> services = serviceDal.getAll(); for (Service service: services) { //check regex if (shouldSkipService(service, odsCodeRegex)) { continue; } LOG.debug("Doing " + service); List<UUID> systemIds = SystemHelper.getSystemIdsForService(service); for (UUID systemId: systemIds) { //skip ADT feeds because their JSON isn't the same if (systemId.equals(UUID.fromString("d874c58c-91fd-41bb-993e-b1b8b22038b2"))//live || systemId.equals(UUID.fromString("68096181-9e5d-4cca-821f-a9ecaa0ebc50"))) { //dev continue; } ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); List<Exchange> exchanges = exchangeDal.getExchangesByService(service.getId(), systemId, Integer.MAX_VALUE); LOG.debug("Found " + exchanges.size() + " exchanges"); int done = 0; for (Exchange exchange: exchanges) { boolean saveExchange = false; //make sure the individual file sizes are in the JSON body try { String body = exchange.getBody(); List<ExchangePayloadFile> files = ExchangeHelper.parseExchangeBody(body, false); for (ExchangePayloadFile file: files) { if (file.getSize() != null) { continue; } String path = file.getPath(); path = FilenameUtils.concat(sharedStoragePath, path); String name = FilenameUtils.getName(path); String dir = new File(path).getParent(); List<FileInfo> s3Listing = FileHelper.listFilesInSharedStorageWithInfo(dir); for (FileInfo s3Info : s3Listing) { String s3Path = s3Info.getFilePath(); long size = s3Info.getSize(); String s3Name = FilenameUtils.getName(s3Path); if (s3Name.equals(name)) { file.setSize(new Long(size)); //write back to JSON String newJson = JsonSerializer.serialize(files); exchange.setBody(newJson); saveExchange = true; break; } } } Map<String, ExchangePayloadFile> hmFilesByName = new HashMap<>(); String body = exchange.getBody(); List<ExchangePayloadFile> files = ExchangeHelper.parseExchangeBody(body, false); for (ExchangePayloadFile file: files) { if (file.getSize() != null) { continue; } String path = file.getPath(); path = FilenameUtils.concat(sharedStoragePath, path); String name = FilenameUtils.getName(path); hmFilesByName.put(name, file); String dir = new File(path).getParent(); if (rootDir == null || rootDir.equals(dir)) { rootDir = dir; } else { throw new Exception("Files not in same directory [" + rootDir + "] vs [" + dir + "]"); } } if (!hmFilesByName.isEmpty()) { List<FileInfo> s3Listing = FileHelper.listFilesInSharedStorageWithInfo(rootDir); for (FileInfo s3Info : s3Listing) { String path = s3Info.getFilePath(); long size = s3Info.getSize(); String name = FilenameUtils.getName(path); ExchangePayloadFile file = hmFilesByName.get(name); if (file == null) { LOG.debug("No info for file " + path + " found"); continue; //throw new Exception(); } file.setSize(new Long(size)); } //write back to JSON String newJson = JsonSerializer.serialize(files); exchange.setBody(newJson); saveExchange = true; } catch (Throwable t) { throw new Exception("Failed on exchange " + exchange.getId(), t); } //and make sure the total size is in the headers Long totalSize = exchange.getHeaderAsLong(HeaderKeys.TotalFileSize); if (totalSize == null) { long size = 0; String body = exchange.getBody(); List<ExchangePayloadFile> files = ExchangeHelper.parseExchangeBody(body, false); for (ExchangePayloadFile file: files) { if (file.getSize() == null) { throw new Exception("No file size for " + file.getPath() + " in exchange " + exchange.getId()); } size += file.getSize().longValue(); } exchange.setHeaderAsLong(HeaderKeys.TotalFileSize, new Long(size)); saveExchange = true; } //save to DB if (saveExchange) { AuditWriter.writeExchange(exchange); } done ++; if (done % 100 == 0) { LOG.debug("Done " + done); } } LOG.debug("Finished at " + done); } } LOG.info("Finished Populating Exchange File Sizes for " + odsCodeRegex); } catch (Throwable t) { LOG.error("", t); } }*/ public static boolean shouldSkipService(Service service, String odsCodeRegex) { if (Strings.isNullOrEmpty(odsCodeRegex)) { return false; } String odsCode = service.getLocalId(); if (!Strings.isNullOrEmpty(odsCode) && Pattern.matches(odsCodeRegex, odsCode)) { return false; } String ccgCode = service.getCcgCode(); if (!Strings.isNullOrEmpty(ccgCode) && Pattern.matches(odsCodeRegex, ccgCode)) { return false; } LOG.debug("Skipping " + service + " due to regex"); return true; } public static void getResourceHistory(String serviceIdStr, String resourceTypeStr, String resourceIdStr) { LOG.debug("Getting resource history for " + resourceTypeStr + " " + resourceIdStr + " for service " + serviceIdStr); try { LOG.debug(""); LOG.debug(""); UUID serviceId = UUID.fromString(serviceIdStr); UUID resourceId = UUID.fromString(resourceIdStr); ResourceType resourceType = ResourceType.valueOf(resourceTypeStr); ResourceDalI resourceDal = DalProvider.factoryResourceDal(); ResourceWrapper retrieved = resourceDal.getCurrentVersion(serviceId, resourceType.toString(), resourceId); LOG.debug("Retrieved current>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); LOG.debug(""); LOG.debug("" + retrieved); LOG.debug(""); LOG.debug(""); List<ResourceWrapper> history = resourceDal.getResourceHistory(serviceId, resourceType.toString(), resourceId); LOG.debug("Retrieved history " + history.size() + ">>>>>>>>>>>>>>>>>>>>>>>>>>>>"); LOG.debug(""); for (ResourceWrapper h: history) { LOG.debug("" + h); LOG.debug(""); } } catch (Throwable t) { LOG.error("", t); } } /** * validates NHS numbers from a file, outputting valid and invalid ones to separate output files * if the addComma parameter is true it'll add a comma to the end of each line, so it's ready * for sending to the National Data Opt-out service */ public static void validateNhsNumbers(String filePath, boolean addCommas) { LOG.info("Validating NHS Numbers in " + filePath); LOG.info("Adding commas = " + addCommas); try { File f = new File(filePath); if (!f.exists()) { throw new Exception("File " + f + " doesn't exist"); } List<String> lines = FileUtils.readLines(f); List<String> valid = new ArrayList<>(); List<String> invalid = new ArrayList<>(); for (String line: lines) { if (line.length() > 10) { String c = line.substring(10); if (c.equals(",")) { line = line.substring(0, 10); } else { invalid.add(line); continue; } } if (line.length() < 10) { invalid.add(line); continue; } Boolean isValid = IdentifierHelper.isValidNhsNumber(line); if (isValid == null) { continue; } if (!isValid.booleanValue()) { invalid.add(line); continue; } //if we make it here, we're valid if (addCommas) { line += ","; } valid.add(line); } File dir = f.getParentFile(); String fileName = f.getName(); File fValid = new File(dir, "VALID_" + fileName); FileUtils.writeLines(fValid, valid); LOG.info("" + valid.size() + " NHS numbers written to " + fValid); File fInvalid = new File(dir, "INVALID_" + fileName); FileUtils.writeLines(fInvalid, invalid); LOG.info("" + invalid.size() + " NHS numbers written to " + fInvalid); } catch (Throwable t) { LOG.error("", t); } } public static void getJarDetails() { LOG.debug("Get Jar Details OLD"); try { Class cls = SpecialRoutines.class; LOG.debug("Cls = " + cls); ProtectionDomain domain = cls.getProtectionDomain(); LOG.debug("Domain = " + domain); CodeSource source = domain.getCodeSource(); LOG.debug("Source = " + source); URL loc = source.getLocation(); LOG.debug("Location = " + loc); URI uri = loc.toURI(); LOG.debug("URI = " + uri); File f = new File(uri); LOG.debug("File = " + f); Date d = new Date(f.lastModified()); LOG.debug("Last Modified = " + d); } catch (Throwable t) { LOG.error("", t); } LOG.debug(""); LOG.debug(""); LOG.debug("Get Jar Details THIS class"); try { Class cls = SpecialRoutines.class; ApplicationHeartbeatHelper.findJarDateTime(cls, true); } catch (Throwable t) { LOG.error("", t); } LOG.debug(""); LOG.debug(""); LOG.debug("Get Jar Details CORE class"); try { Class cls = ApplicationHeartbeatHelper.class; ApplicationHeartbeatHelper.findJarDateTime(cls, true); } catch (Throwable t) { LOG.error("", t); } } public static void breakUpAdminBatches(String odsCodeRegex) { try { LOG.debug("Breaking up admin batches for " + odsCodeRegex); ServiceDalI serviceDal = DalProvider.factoryServiceDal(); List<Service> services = serviceDal.getAll(); for (Service service: services) { //check regex if (shouldSkipService(service, odsCodeRegex)) { continue; } String publisherConfig = service.getPublisherConfigName(); if (Strings.isNullOrEmpty(publisherConfig)) { continue; } Connection ehrConnection = ConnectionManager.getEhrNonPooledConnection(service.getId()); Connection auditConnection = ConnectionManager.getAuditNonPooledConnection(); int maxSize = TransformConfig.instance().getAdminBatchMaxSize(); LOG.debug("Doing " + service); List<UUID> systemIds = SystemHelper.getSystemIdsForService(service); for (UUID systemId: systemIds) { ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); ExchangeBatchDalI exchangeBatchDal = DalProvider.factoryExchangeBatchDal(); List<Exchange> exchanges = exchangeDal.getExchangesByService(service.getId(), systemId, Integer.MAX_VALUE); LOG.debug("Found " + exchanges.size() + " exchanges"); int done = 0; int fixed = 0; for (Exchange exchange: exchanges) { List<ExchangeBatch> batches = exchangeBatchDal.retrieveForExchangeId(exchange.getId()); for (ExchangeBatch batch: batches) { if (batch.getEdsPatientId() != null) { continue; } String sql = "SELECT COUNT(1) FROM resource_history WHERE exchange_batch_id = ?"; PreparedStatement psSelectCount = ehrConnection.prepareStatement(sql); psSelectCount.setString(1, batch.getBatchId().toString()); ResultSet rs = psSelectCount.executeQuery(); rs.next(); int count = rs.getInt(1); psSelectCount.close(); if (count > maxSize) { LOG.debug("Fixing batch " + batch.getBatchId() + " for exchange " + exchange.getId() + " with " + count + " resources"); //work backwards int numBlocks = count / maxSize; if (count % maxSize > 0) { numBlocks ++; } //exchange_event - to audit this PreparedStatement psExchangeEvent = null; sql = "INSERT INTO exchange_event" + " VALUES (?, ?, ?, ?)"; psExchangeEvent = auditConnection.prepareStatement(sql); psExchangeEvent.setString(1, UUID.randomUUID().toString()); psExchangeEvent.setString(2, exchange.getId().toString()); psExchangeEvent.setTimestamp(3, new java.sql.Timestamp(new Date().getTime())); psExchangeEvent.setString(4, "Split large admin batch of " + count + " resources into blocks of " + maxSize); psExchangeEvent.executeUpdate(); auditConnection.commit(); psExchangeEvent.close(); for (int blockNum=numBlocks; blockNum>1; blockNum--) { //skip block one as we want to leave it alone UUID newId = UUID.randomUUID(); int rangeStart = (blockNum-1) * maxSize; LOG.debug("Updating " + batch.getBatchId() + " " + rangeStart + " to " + (rangeStart+maxSize) + " to batch ID " + newId); PreparedStatement psExchangeBatch = null; PreparedStatement psSendAudit = null; PreparedStatement psTransformAudit = null; //insert into exchange_batch table sql = "INSERT INTO exchange_batch" + " SELECT exchange_id, '" + newId.toString() + "', inserted_at, eds_patient_id" + " FROM exchange_batch" + " WHERE exchange_id = ? AND batch_id = ?"; psExchangeBatch = auditConnection.prepareStatement(sql); psExchangeBatch.setString(1, exchange.getId().toString()); psExchangeBatch.setString(2, batch.getBatchId().toString()); psExchangeBatch.executeUpdate(); //exchange_subscriber_send_audit sql = "INSERT INTO exchange_subscriber_send_audit" + " SELECT exchange_id, '" + newId.toString() + "', subscriber_config_name, inserted_at, error_xml, queued_message_id" + " FROM exchange_subscriber_send_audit" + " WHERE exchange_id = ? AND exchange_batch_id = ?"; psSendAudit = auditConnection.prepareStatement(sql); psSendAudit.setString(1, exchange.getId().toString()); psSendAudit.setString(2, batch.getBatchId().toString()); psSendAudit.executeUpdate(); //exchange_subscriber_transform_audit sql = "INSERT INTO exchange_subscriber_transform_audit" + " SELECT exchange_id, '" + newId.toString() + "', subscriber_config_name, started, ended, error_xml, number_resources_transformed, queued_message_id" + " FROM exchange_subscriber_transform_audit" + " WHERE exchange_id = ? AND exchange_batch_id = ?"; psTransformAudit = auditConnection.prepareStatement(sql); psTransformAudit.setString(1, exchange.getId().toString()); psTransformAudit.setString(2, batch.getBatchId().toString()); psTransformAudit.executeUpdate(); auditConnection.commit(); psExchangeBatch.close(); psSendAudit.close(); psTransformAudit.close(); //update history PreparedStatement psDropTempTable = null; PreparedStatement psCreateTempTable = null; PreparedStatement psIndexTempTable = null; PreparedStatement psUpdateHistory = null; sql = "DROP TEMPORARY TABLE IF EXISTS tmp.tmp_admin_batch_fix"; psDropTempTable = ehrConnection.prepareStatement(sql); psDropTempTable.executeUpdate(); sql = "CREATE TEMPORARY TABLE tmp.tmp_admin_batch_fix AS" + " SELECT resource_id, resource_type, created_at, version" + " FROM resource_history" + " WHERE exchange_batch_id = ?" + " ORDER BY resource_type, resource_id" + " LIMIT " + rangeStart + ", " + maxSize; psCreateTempTable = ehrConnection.prepareStatement(sql); psCreateTempTable.setString(1, batch.getBatchId().toString()); psCreateTempTable.executeUpdate(); sql = "CREATE INDEX ix ON tmp.tmp_admin_batch_fix (resource_id, resource_type, created_at, version)"; psIndexTempTable = ehrConnection.prepareStatement(sql); psIndexTempTable.executeUpdate(); sql = "UPDATE resource_history" + " INNER JOIN tmp.tmp_admin_batch_fix f" + " ON f.resource_id = resource_history.resource_id" + " AND f.resource_type = f.resource_type" + " AND f.created_at = f.created_at" + " AND f.version = f.version" + " SET resource_history.created_at = resource_history.created_at," + " resource_history.exchange_batch_id = ?"; psUpdateHistory = ehrConnection.prepareStatement(sql); psUpdateHistory.setString(1, newId.toString()); psUpdateHistory.executeUpdate(); ehrConnection.commit(); psDropTempTable.close(); psCreateTempTable.close(); psIndexTempTable.close(); psUpdateHistory.close(); } } } done ++; if (done % 100 == 0) { LOG.debug("Checked " + done + " exchanges and fixed " + fixed); } } LOG.debug("Checked " + done + " exchanges and fixed " + fixed); } ehrConnection.close(); auditConnection.close(); } LOG.debug("Finished breaking up admin batches for " + odsCodeRegex); } catch (Throwable t) { LOG.error("", t); } } public static void testInformationModel() { LOG.debug("Testing Information Model"); try { LOG.debug(" LOG.debug(" gets Snomed concept ID for legacy code and scheme"); String legacyCode = "C10.."; String legacyScheme = IMConstant.READ2; String mappedCoreCode = IMClient.getMappedCoreCodeForSchemeCode(legacyScheme, legacyCode); LOG.debug("For " + legacyScheme + " " + legacyCode + ", got Snomed Concept ID " + mappedCoreCode); legacyCode = "C10.."; legacyScheme = IMConstant.CTV3; mappedCoreCode = IMClient.getMappedCoreCodeForSchemeCode(legacyScheme, legacyCode); LOG.debug("For " + legacyScheme + " " + legacyCode + ", got Snomed Concept ID " + mappedCoreCode); legacyCode = "G33.."; legacyScheme = IMConstant.READ2; mappedCoreCode = IMClient.getMappedCoreCodeForSchemeCode(legacyScheme, legacyCode); LOG.debug("For " + legacyScheme + " " + legacyCode + ", got Snomed Concept ID " + mappedCoreCode); legacyCode = "G33.."; legacyScheme = IMConstant.CTV3; mappedCoreCode = IMClient.getMappedCoreCodeForSchemeCode(legacyScheme, legacyCode); LOG.debug("For " + legacyScheme + " " + legacyCode + ", got Snomed Concept ID " + mappedCoreCode); legacyCode = "687309281"; legacyScheme = IMConstant.BARTS_CERNER; mappedCoreCode = IMClient.getMappedCoreCodeForSchemeCode(legacyScheme, legacyCode); LOG.debug("For " + legacyScheme + " " + legacyCode + ", got Snomed Concept ID " + mappedCoreCode); LOG.debug(" LOG.debug(" gets NON-CORE DBID for legacy code and scheme"); legacyCode = "C10.."; legacyScheme = IMConstant.READ2; Integer dbid = IMClient.getConceptDbidForSchemeCode(legacyScheme, legacyCode); LOG.debug("For " + legacyScheme + " " + legacyCode + ", got non-core DBID " + dbid); legacyCode = "C10.."; legacyScheme = IMConstant.CTV3; dbid = IMClient.getConceptDbidForSchemeCode(legacyScheme, legacyCode); LOG.debug("For " + legacyScheme + " " + legacyCode + ", got non-core DBID " + dbid); legacyCode = "G33.."; legacyScheme = IMConstant.READ2; dbid = IMClient.getConceptDbidForSchemeCode(legacyScheme, legacyCode); LOG.debug("For " + legacyScheme + " " + legacyCode + ", got non-core DBID " + dbid); legacyCode = "G33.."; legacyScheme = IMConstant.CTV3; dbid = IMClient.getConceptDbidForSchemeCode(legacyScheme, legacyCode); LOG.debug("For " + legacyScheme + " " + legacyCode + ", got non-core DBID " + dbid); legacyCode = "687309281"; legacyScheme = IMConstant.BARTS_CERNER; dbid = IMClient.getConceptDbidForSchemeCode(legacyScheme, legacyCode); LOG.debug("For " + legacyScheme + " " + legacyCode + ", got non-core DBID " + dbid); LOG.debug(" LOG.debug(" gets CORE DBID for legacy code and scheme"); legacyCode = "C10.."; legacyScheme = IMConstant.READ2; dbid = IMClient.getMappedCoreConceptDbidForSchemeCode(legacyScheme, legacyCode); LOG.debug("For " + legacyScheme + " " + legacyCode + ", got core DBID " + dbid); legacyCode = "C10.."; legacyScheme = IMConstant.CTV3; dbid = IMClient.getMappedCoreConceptDbidForSchemeCode(legacyScheme, legacyCode); LOG.debug("For " + legacyScheme + " " + legacyCode + ", got core DBID " + dbid); legacyCode = "G33.."; legacyScheme = IMConstant.READ2; dbid = IMClient.getMappedCoreConceptDbidForSchemeCode(legacyScheme, legacyCode); LOG.debug("For " + legacyScheme + " " + legacyCode + ", got core DBID " + dbid); legacyCode = "G33.."; legacyScheme = IMConstant.CTV3; dbid = IMClient.getMappedCoreConceptDbidForSchemeCode(legacyScheme, legacyCode); LOG.debug("For " + legacyScheme + " " + legacyCode + ", got core DBID " + dbid); legacyCode = "687309281"; legacyScheme = IMConstant.BARTS_CERNER; dbid = IMClient.getMappedCoreConceptDbidForSchemeCode(legacyScheme, legacyCode); LOG.debug("For " + legacyScheme + " " + legacyCode + ", got core DBID " + dbid); LOG.debug(" LOG.debug(" get Snomed concept ID for CORE DBID"); Integer coreConceptDbId = new Integer(61367); String codeForConcept = IMClient.getCodeForConceptDbid(coreConceptDbId); LOG.debug("For core DBID " + coreConceptDbId + " got " + codeForConcept); coreConceptDbId = new Integer(123390); codeForConcept = IMClient.getCodeForConceptDbid(coreConceptDbId); LOG.debug("For core DBID " + coreConceptDbId + " got " + codeForConcept); coreConceptDbId = new Integer(1406482); codeForConcept = IMClient.getCodeForConceptDbid(coreConceptDbId); LOG.debug("For core DBID " + coreConceptDbId + " got " + codeForConcept); LOG.debug(" LOG.debug(" gets NON-CORE DBID for encounter type text"); String encounterScheme = IMConstant.ENCOUNTER_LEGACY; String encounterTerm = "Clinical"; Integer encounterConceptId = IMClient.getConceptDbidForTypeTerm(encounterScheme, encounterTerm); LOG.debug("For " + encounterScheme + " " + encounterTerm + " got " + encounterConceptId); encounterScheme = IMConstant.ENCOUNTER_LEGACY; encounterTerm = "Administrative"; encounterConceptId = IMClient.getConceptDbidForTypeTerm(encounterScheme, encounterTerm); LOG.debug("For " + encounterScheme + " " + encounterTerm + " got " + encounterConceptId); encounterScheme = IMConstant.ENCOUNTER_LEGACY; encounterTerm = "GP Surgery"; encounterConceptId = IMClient.getConceptDbidForTypeTerm(encounterScheme, encounterTerm); LOG.debug("For " + encounterScheme + " " + encounterTerm + " got " + encounterConceptId); LOG.debug(" LOG.debug(" gets CORE DBID for encounter type text"); encounterScheme = IMConstant.ENCOUNTER_LEGACY; encounterTerm = "Clinical"; encounterConceptId = IMClient.getMappedCoreConceptDbidForTypeTerm(encounterScheme, encounterTerm); LOG.debug("For " + encounterScheme + " " + encounterTerm + " got " + encounterConceptId); encounterScheme = IMConstant.ENCOUNTER_LEGACY; encounterTerm = "Administrative"; encounterConceptId = IMClient.getMappedCoreConceptDbidForTypeTerm(encounterScheme, encounterTerm); LOG.debug("For " + encounterScheme + " " + encounterTerm + " got " + encounterConceptId); encounterScheme = IMConstant.ENCOUNTER_LEGACY; encounterTerm = "GP Surgery"; encounterConceptId = IMClient.getMappedCoreConceptDbidForTypeTerm(encounterScheme, encounterTerm); LOG.debug("For " + encounterScheme + " " + encounterTerm + " got " + encounterConceptId); LOG.debug(" LOG.debug(" gets locally generated Cerner code for test code and result text"); String code = "687309281"; String scheme = IMConstant.BARTS_CERNER; String term = "SARS-CoV-2 RNA DETECTED"; String codeForTypeTerm = IMClient.getCodeForTypeTerm(scheme, code, term); LOG.debug("For " + scheme + " " + code + " [" + term + "] got " + codeForTypeTerm); code = "687309281"; scheme = IMConstant.BARTS_CERNER; term = "SARS-CoV-2 RNA NOT detected"; codeForTypeTerm = IMClient.getCodeForTypeTerm(scheme, code, term); LOG.debug("For " + scheme + " " + code + " [" + term + "] got " + codeForTypeTerm); LOG.debug(""); LOG.debug(""); LOG.debug(" String testCode = "687309281"; String positiveResult = "SARS-CoV-2 RNA DETECTED"; String negativeResult = "SARS-CoV-2 RNA NOT detected"; LOG.debug("Want to find Snomed concept 1240511000000106 from Cerner test code 687309281"); String testCodeSnomedConceptId = IMClient.getMappedCoreCodeForSchemeCode(IMConstant.BARTS_CERNER, testCode); LOG.debug("Got Snomed test code " + testCodeSnomedConceptId); LOG.debug(""); LOG.debug("Want to get locally generated Cerner code for test code and positive textual result"); String locallyGeneratedPositiveCode = IMClient.getCodeForTypeTerm(IMConstant.BARTS_CERNER, testCode, positiveResult); LOG.debug("Got locally generated code " + locallyGeneratedPositiveCode); LOG.debug(""); LOG.debug("Want to get locally generated Cerner code for test code and negative textual result"); String locallyGeneratedNegativeCode = IMClient.getCodeForTypeTerm(IMConstant.BARTS_CERNER, testCode, negativeResult); LOG.debug("Got locally generated code " + locallyGeneratedNegativeCode); LOG.debug(""); LOG.debug("Want to get Snomed concept ID for test code and positive result"); String snomedPositiveCode = IMClient.getMappedCoreCodeForSchemeCode(IMConstant.BARTS_CERNER, locallyGeneratedPositiveCode); LOG.debug("Got positive snomed code " + snomedPositiveCode); LOG.debug(""); LOG.debug("Want to get Snomed concept ID for test code and negative result"); String snomedNegativeCode = IMClient.getMappedCoreCodeForSchemeCode(IMConstant.BARTS_CERNER, locallyGeneratedNegativeCode); LOG.debug("Got negative snomed code " + snomedNegativeCode); LOG.debug(""); LOG.debug(""); LOG.debug(""); LOG.debug(" LOG.debug("Want to find Snomed concept 1240511000000106 from Cerner test code 687309281"); testCodeSnomedConceptId = IMHelper.getMappedSnomedConceptForSchemeCode(IMConstant.BARTS_CERNER, testCode); LOG.debug("Got Snomed test code " + testCodeSnomedConceptId); LOG.debug(""); LOG.debug("Want to get locally generated Cerner code for test code and positive textual result"); locallyGeneratedPositiveCode = IMHelper.getMappedLegacyCodeForLegacyCodeAndTerm(IMConstant.BARTS_CERNER, testCode, positiveResult); LOG.debug("Got locally generated code " + locallyGeneratedPositiveCode); LOG.debug(""); LOG.debug("Want to get locally generated Cerner code for test code and negative textual result"); locallyGeneratedNegativeCode = IMHelper.getMappedLegacyCodeForLegacyCodeAndTerm(IMConstant.BARTS_CERNER, testCode, negativeResult); LOG.debug("Got locally generated code " + locallyGeneratedNegativeCode); LOG.debug(""); LOG.debug("Want to get Snomed concept ID for test code and positive result"); snomedPositiveCode = IMHelper.getMappedSnomedConceptForSchemeCode(IMConstant.BARTS_CERNER, locallyGeneratedPositiveCode); LOG.debug("Got positive snomed code " + snomedPositiveCode); LOG.debug(""); LOG.debug("Want to get Snomed concept ID for test code and negative result"); snomedNegativeCode = IMHelper.getMappedSnomedConceptForSchemeCode(IMConstant.BARTS_CERNER, locallyGeneratedNegativeCode); LOG.debug("Got negative snomed code " + snomedNegativeCode); LOG.debug(""); LOG.debug(""); LOG.debug(""); LOG.debug(" List<String> encounterTerms = new ArrayList<>(); //hospital terms encounterTerms.add("Outpatient Register a patient"); encounterTerms.add("Outpatient Discharge/end visit"); encounterTerms.add("Outpatient Update patient information"); encounterTerms.add("Emergency department Register a patient (emergency)"); encounterTerms.add("Inpatient Transfer a patient"); encounterTerms.add("Emergency department Discharge/end visit (emergency)"); encounterTerms.add("Outpatient Referral Update patient information (waitinglist)"); encounterTerms.add("Outpatient Referral Pre-admit a patient (waitinglist)"); encounterTerms.add("Inpatient Discharge/end visit"); encounterTerms.add("Inpatient Admit/visit notification"); encounterTerms.add("Emergency department Update patient information (emergency)"); encounterTerms.add("Outpatient Change an inpatient to an outpatient"); //primary care terms encounterTerms.add("Telephone call to a patient"); encounterTerms.add("G.P.Surgery"); encounterTerms.add("Externally entered"); encounterTerms.add("Third party"); encounterTerms.add("GP Surgery"); encounterTerms.add("Scanned document"); encounterTerms.add("Docman"); encounterTerms.add("D.N.A."); encounterTerms.add("Telephone"); encounterTerms.add("Message"); encounterTerms.add("Path. Lab."); encounterTerms.add("Administration note"); encounterTerms.add("Telephone consultation"); encounterTerms.add("Main Surgery"); for (String encTerm: encounterTerms) { LOG.debug("" + encTerm + " -> "); String legacyEncCode = IMHelper.getMappedLegacyCodeForLegacyCodeAndTerm(IMConstant.ENCOUNTER_LEGACY, "TYPE", encTerm); LOG.debug(" legacy code = " + legacyEncCode); /*String snomedCode = null; if (!Strings.isNullOrEmpty(legacyEncCode)) { snomedCode = IMHelper.getMappedSnomedConceptForSchemeCode(IMConstant.ENCOUNTER_LEGACY, legacyEncCode); } LOG.debug("" + encTerm + " -> " + (legacyEncCode != null ? legacyEncCode : "NULL") + " -> " + (snomedCode != null ? snomedCode : "NULL"));*/ Integer legacyDbId = IMHelper.getConceptDbidForTypeTerm(null, IMConstant.ENCOUNTER_LEGACY, encTerm); Integer coreDbId = IMHelper.getIMMappedConceptForTypeTerm(null, IMConstant.ENCOUNTER_LEGACY, encTerm); LOG.debug(" legacy DB ID = " + legacyDbId + ", core DB ID = " + coreDbId); // Integer oldLegacyDbId = IMHelper.getConceptDbidForTypeTerm(null, IMConstant.DCE_Type_of_encounter, encTerm); // Integer oldCoreDbId = IMHelper.getIMMappedConceptForTypeTerm(null, null, IMConstant.DCE_Type_of_encounter, encTerm); // LOG.debug(" OLD legacy DB ID = " + oldLegacyDbId + ", OLD core DB ID = " + oldCoreDbId); } LOG.debug("Finished Testing Information Model"); } catch (Throwable t) { LOG.error("", t); } } public static void testDsm(String odsCode) { LOG.info("Testing DSM for " + odsCode); try { LOG.debug("Testing doesOrganisationHaveDPA"); boolean b = OrganisationCache.doesOrganisationHaveDPA(odsCode); LOG.debug("Got " + b); LOG.debug(""); LOG.debug(""); LOG.debug("Testing getAllDSAsForPublisherOrg"); List<DataSharingAgreementEntity> list = DataSharingAgreementCache.getAllDSAsForPublisherOrg(odsCode); if (list == null) { LOG.debug("Got NULL"); } else { LOG.debug("Got " + list.size()); for (DataSharingAgreementEntity e: list) { LOG.debug(" -> " + e.getName() + " " + e.getUuid()); } } LOG.debug(""); LOG.debug(""); LOG.debug("Testing getAllProjectsForSubscriberOrg"); List<ProjectEntity> projects = ProjectCache.getAllProjectsForSubscriberOrg(odsCode); Set<String> projectIds = new HashSet<>(); if (list == null) { LOG.debug("Got NULL"); } else { LOG.debug("Got " + list.size()); for (ProjectEntity project: projects) { LOG.debug(" -> " + project.getName() + " " + project.getUuid()); String projectUuid = project.getUuid(); projectIds.add(projectUuid); } } LOG.debug(""); LOG.debug(""); LOG.debug("Testing getAllPublishersForProjectWithSubscriberCheck"); if (projectIds.isEmpty()) { LOG.debug(" -> no project IDs"); } else { for (String projectId: projectIds) { LOG.debug("PROJECT ID " + projectId); List<String> results = ProjectCache.getAllPublishersForProjectWithSubscriberCheck(projectId, odsCode); LOG.debug("Got publisher ODS codes: " + results); } } LOG.debug("Testing getValidDistributionProjectsForPublisher"); List<ProjectEntity> validDistributionProjects = ProjectCache.getValidDistributionProjectsForPublisher(odsCode); if (validDistributionProjects.size() < 1) { LOG.debug("Got no valid projects"); } else { LOG.debug("Got " + validDistributionProjects.size() + " valid projects"); for (ProjectEntity project: validDistributionProjects) { LOG.debug(" -> " + project.getName() + " " + project.getUuid()); } } LOG.debug(""); LOG.debug(""); LOG.debug(""); LOG.debug(""); LOG.info("Finished Testing DSM for " + odsCode); } catch (Throwable t) { LOG.error("", t); } } public static void compareDsm(boolean logDifferencesOnly, String toFile, String odsCodeRegex) { LOG.debug("Comparing DSM to DDS-UI for " + odsCodeRegex); LOG.debug("logDifferencesOnly = " + logDifferencesOnly); LOG.debug("toFile = " + toFile); try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); File dstFile = new File(toFile); FileOutputStream fos = new FileOutputStream(dstFile); OutputStreamWriter osw = new OutputStreamWriter(fos); BufferedWriter bufferedWriter = new BufferedWriter(osw); CSVFormat format = EmisCsvToFhirTransformer.CSV_FORMAT .withHeader("Name", "ODS Code", "Parent Code", "Notes", "DDS-UI DPA", "DSM DPA", "DPA matches", "DDS-UI Endpoints", "DSM Endpoints", "DSA matches" ); CSVPrinter printer = new CSVPrinter(bufferedWriter, format); ServiceDalI serviceDal = DalProvider.factoryServiceDal(); List<Service> services = serviceDal.getAll(); for (Service service: services) { String odsCode = service.getLocalId(); UUID serviceId = service.getId(); //skip if filtering on ODS code if (shouldSkipService(service, odsCodeRegex)) { continue; } //only do if a publisher String publisherConfig = service.getPublisherConfigName(); if (Strings.isNullOrEmpty(publisherConfig)) { continue; } List<String> logging = new ArrayList<>(); boolean gotDifference = false; logging.add("Doing " + service + " //check DPAs //check if publisher to DDS protocol List<String> protocolIdsOldWay = DetermineRelevantProtocolIds.getProtocolIdsForPublisherServiceOldWay(serviceId.toString()); boolean hasDpaOldWay = !protocolIdsOldWay.isEmpty(); //in the old way, we count as having a DPA if they're in any protocol //check if DSM DPA boolean hasDpaNewWay = OrganisationCache.doesOrganisationHaveDPA(odsCode); boolean dpaMatches = hasDpaNewWay == hasDpaOldWay; if (!dpaMatches) { logging.add("Old and new DPA do not match (old = " + hasDpaOldWay + ", new = " + hasDpaNewWay + ")"); gotDifference = true; } else { logging.add("Old and new DPA match (" + hasDpaOldWay + ")"); } //check DSAs //want to find target subscriber config names OLD way Set<String> subscriberConfigNamesOldWay = new HashSet<>(); for (String oldProtocolId: protocolIdsOldWay) { LibraryItem libraryItem = LibraryRepositoryHelper.getLibraryItemUsingCache(UUID.fromString(oldProtocolId)); Protocol protocol = libraryItem.getProtocol(); //skip disabled protocols if (protocol.getEnabled() != ProtocolEnabled.TRUE) { continue; } List<ServiceContract> subscribers = protocol .getServiceContract() .stream() .filter(sc -> sc.getType().equals(ServiceContractType.SUBSCRIBER)) .filter(sc -> sc.getActive() == ServiceContractActive.TRUE) //skip disabled service contracts .collect(Collectors.toList()); for (ServiceContract serviceContract : subscribers) { String subscriberConfigName = MessageTransformOutbound.getSubscriberEndpoint(serviceContract); if (!Strings.isNullOrEmpty(subscriberConfigName)) { subscriberConfigNamesOldWay.add(subscriberConfigName); } } } //find target subscriber config names NEW way Set<String> subscriberConfigNamesNewWay = new HashSet<>(); List<ProjectEntity> distributionProjects = ProjectCache.getValidDistributionProjectsForPublisher(odsCode); if (distributionProjects == null) { logging.add("Got NULL distribution projects for " + odsCode); } else { for (ProjectEntity distributionProject: distributionProjects) { String configName = distributionProject.getConfigName(); if (!Strings.isNullOrEmpty(configName)) { subscriberConfigNamesNewWay.add(configName); } } } //compare the two List<String> l = new ArrayList<>(subscriberConfigNamesOldWay); l.sort(((o1, o2) -> o1.compareToIgnoreCase(o2))); String subscribersOldWay = String.join(", ", l); l = new ArrayList<>(subscriberConfigNamesNewWay); l.sort(((o1, o2) -> o1.compareToIgnoreCase(o2))); String subscribersNewWay = String.join(", ", l); boolean dsaMatches = subscribersOldWay.equals(subscribersNewWay); //flatten the tags to a String String notesStr = ""; if (service.getTags() != null) { List<String> toks = new ArrayList<>(); Map<String, String> tags = service.getTags(); List<String> keys = new ArrayList<>(tags.keySet()); keys.sort(((o1, o2) -> o1.compareToIgnoreCase(o2))); for (String key: keys) { String s = key; String val = tags.get(key); if (val != null) { s += " " + val; } toks.add(s); } notesStr = String.join(", ", toks); } printer.printRecord(service.getName(), odsCode, service.getCcgCode(), notesStr, hasDpaOldWay, hasDpaNewWay, dpaMatches, subscribersOldWay, subscribersNewWay, dsaMatches); logging.add(""); //log what we found if we need to if (!logDifferencesOnly || gotDifference) { for (String line: logging) { LOG.debug(line); } } } printer.close(); LOG.debug("Finished Comparing DSM to DDS-UI for " + odsCodeRegex + " to " + toFile); } catch (Throwable t) { LOG.error("", t); } } /** * generates the JSON for the config record to move config from DDS-UI protocols to DSM (+JSON) */ public static void createConfigJsonForDSM(String ddsUiProtocolName, String dsmDsaId) { LOG.debug("Creating Config JSON for DDS-UI -> DSM migration"); try { //get DDS-UI protocol details LibraryItem libraryItem = BulkHelper.findProtocolLibraryItem(ddsUiProtocolName); LOG.debug("DDS-UI protocol [" + ddsUiProtocolName + "]"); LOG.debug("DDS-UI protocol UUID " + libraryItem.getUuid()); //get DSM DPA details DataSharingAgreementEntity dsa = DataSharingAgreementCache.getDSADetails(dsmDsaId); LOG.debug("DSM DSA [" + dsa.getName() + "]"); LOG.debug("DSM DSA UUID " + dsa.getUuid()); ObjectMapper mapper = new ObjectMapper(); ObjectNode root = new ObjectNode(mapper.getNodeFactory()); //put in DSA name for visibility root.put("dsa_name", dsa.getName()); //subscriber config ArrayNode subscriberArray = root.putArray("subscribers"); Protocol protocol = libraryItem.getProtocol(); if (protocol.getEnabled() != ProtocolEnabled.TRUE) { throw new Exception("Protocol isn't enabled"); } List<ServiceContract> subscribers = protocol .getServiceContract() .stream() .filter(sc -> sc.getType().equals(ServiceContractType.SUBSCRIBER)) .filter(sc -> sc.getActive() == ServiceContractActive.TRUE) //skip disabled service contracts .collect(Collectors.toList()); for (ServiceContract serviceContract: subscribers) { String subscriberConfigName = MessageTransformOutbound.getSubscriberEndpoint(serviceContract); subscriberArray.add(subscriberConfigName); } //cohort stuff ObjectNode cohortRoot = root.putObject("cohort"); String cohort = protocol.getCohort(); if (cohort.equals("All Patients")) { cohortRoot.put("type", "all_patients"); } else if (cohort.equals("Explicit Patients")) { //database is dependent on protocol ID, but I don't think this used throw new Exception("Protocol uses explicit patient cohort so cannot be converted"); //cohortRoot.put("type", "explicit_patients"); } else if (cohort.startsWith("Defining Services")) { cohortRoot.put("type", "registered_at"); ArrayNode registeredAtRoot = cohortRoot.putArray("services"); int index = cohort.indexOf(":"); if (index == -1) { throw new RuntimeException("Invalid cohort format " + cohort); } String suffix = cohort.substring(index+1); String[] toks = suffix.split("\r|\n|,| |;"); for (String tok: toks) { String odsCode = tok.trim().toUpperCase(); //when checking, we always make uppercase if (!Strings.isNullOrEmpty(tok)) { registeredAtRoot.add(odsCode); } } } else { throw new PipelineException("Unknown cohort [" + cohort + "]"); } String json = mapper.writeValueAsString(root); LOG.debug("JSON:\r\n\r\n" + json + "\r\n\r\n"); LOG.debug("Finished Creating Config JSON for DDS-UI -> DSM migration"); } catch (Throwable t) { LOG.error("", t); } } public static void testBulkLoad(String s3Path, String tableName) { LOG.debug("Testing Bulk Load from " + s3Path + " to " + tableName); try { File dst = FileHelper.copyFileFromStorageToTempDirIfNecessary(s3Path); LOG.debug("Tmp file = " + dst); LOG.debug("Dst exists = " + dst.exists()); LOG.debug("Dst len = " + dst.length()); //bulk load Connection connection = ConnectionManager.getEdsConnection(); connection.setAutoCommit(true); String path = dst.getAbsolutePath(); path = path.replace("\\", "\\\\"); String sql = "LOAD DATA LOCAL INFILE '" + path + "'" + " INTO TABLE " + tableName + " FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\\\"'" + " LINES TERMINATED BY '\\r\\n'" + " IGNORE 1 LINES"; LOG.debug("Load SQL = " + sql); LOG.debug("Starting bulk load"); Statement statement = connection.createStatement(); statement.executeUpdate(sql); //connection.commit(); LOG.debug("Finished bulk load"); statement.close(); connection.setAutoCommit(false); connection.close(); LOG.debug("Deleting temp file " + dst); FileHelper.deleteFileFromTempDirIfNecessary(dst); LOG.debug("Dst exists = " + dst.exists()); LOG.debug("Finished Testing Bulk Load from " + s3Path + " to " + tableName); } catch (Throwable t) { LOG.error("", t); } } *//*Response response = testTarget. .get();*//* /*public static void testCallToDdsUi() { try { //get the Keycloak details from the EMIS config JsonNode json = ConfigManager.getConfigurationAsJson("emis_config", "queuereader"); json = json.get("missing_code_fix"); String ddsUrl = json.get("dds-ui-url").asText(); String keyCloakUrl = json.get("keycloak-url").asText(); String keyCloakRealm = json.get("keycloak-realm").asText(); String keyCloakUser = json.get("keycloak-username").asText(); String keyCloakPass = json.get("keycloak-password").asText(); String keyCloakClientId = json.get("keycloak-client-id").asText(); KeycloakClient kcClient = new KeycloakClient(keyCloakUrl, keyCloakRealm, keyCloakUser, keyCloakPass, keyCloakClientId); WebTarget testTarget = ClientBuilder.newClient().target(ddsUrl).path("api/service/ccgCodes"); String token = kcClient.getToken().getToken(); token = JOptionPane.showInputDialog("TOKEN", token); LOG.debug("Token = token"); Invocation.Builder builder = testTarget.request(); builder = builder.header("Authorization", "Bearer " + token); Response response = builder.get(); .request() .header("Authorization", "Bearer " + kcClient.getToken().getToken()) //request.Headers.Add("Authorization", this.token); int status = response.getStatus(); LOG.debug("Status = " + status); String responseStr = response.readEntity(String.class); LOG.debug("responseStr = " + responseStr); } catch (Throwable t) { LOG.error("", t); } }*/ /*public static void loadTppStagingData(String odsCode, UUID fromExchange) { LOG.debug("Loading TPP Staging Data for " + odsCode + " from Exchange " + fromExchange); try { ServiceDalI serviceDal = DalProvider.factoryServiceDal(); Service service = serviceDal.getByLocalIdentifier(odsCode); List<UUID> systemIds = SystemHelper.getSystemIdsForService(service); if (systemIds.size() != 1) { throw new Exception("" + systemIds.size() + " system IDs found"); } UUID systemId = systemIds.get(0); ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); List<Exchange> exchanges = exchangeDal.getExchangesByService(service.getId(), systemId, Integer.MAX_VALUE); LOG.debug("Got " + exchanges.size() + " exchanges"); //go backwards, as they're most-recent-first for (int i=exchanges.size()-1; i>=0; i--) { Exchange exchange = exchanges.get(i); if (fromExchange != null) { if (!exchange.getId().equals(fromExchange)) { LOG.debug("Skipping exchange " + exchange.getId()); continue; } fromExchange = null; } LOG.debug("Doing exchange " + exchange.getId() + " from " + exchange.getHeader(HeaderKeys.DataDate)); Date dataDate = exchange.getHeaderAsDate(HeaderKeys.DataDate); List<ExchangePayloadFile> files = ExchangeHelper.parseExchangeBody(exchange.getBody()); for (ExchangePayloadFile file: files) { String type = file.getType(); String filePath = file.getPath(); if (type.equals("Ctv3")) { TppCtv3LookupDalI dal = DalProvider.factoryTppCtv3LookupDal(); dal.updateLookupTable(filePath, dataDate); } else if (type.equals("Ctv3Hierarchy")) { TppCtv3HierarchyRefDalI dal = DalProvider.factoryTppCtv3HierarchyRefDal(); dal.updateHierarchyTable(filePath, dataDate); } else if (type.equals("ImmunisationContent")) { TppImmunisationContentDalI dal = DalProvider.factoryTppImmunisationContentDal(); dal.updateLookupTable(filePath, dataDate); } else if (type.equals("ConfiguredListOption")) { TppConfigListOptionDalI dal = DalProvider.factoryTppConfigListOptionDal(); dal.updateLookupTable(filePath, dataDate); } else if (type.equals("MedicationReadCodeDetails")) { TppMultiLexToCtv3MapDalI dal = DalProvider.factoryTppMultiLexToCtv3MapDal(); dal.updateLookupTable(filePath, dataDate); } else if (type.equals("Mapping")) { TppMappingRefDalI dal = DalProvider.factoryTppMappingRefDal(); dal.updateLookupTable(filePath, dataDate); } else if (type.equals("StaffMember")) { TppCsvHelper helper = new TppCsvHelper(service.getId(), systemId, exchange.getId()); String[] arr = new String[]{filePath}; Map<String, String> versions = TppCsvToFhirTransformer.buildParserToVersionsMap(arr, helper); String version = versions.get(filePath); SRStaffMember parser = new SRStaffMember(service.getId(), systemId, exchange.getId(), version, filePath); while (parser.nextRecord()) { //just spin through it } //bulk load the file into the DB int fileId = parser.getFileAuditId().intValue(); TppStaffDalI dal = DalProvider.factoryTppStaffMemberDal(); dal.updateStaffMemberLookupTable(filePath, dataDate, fileId); } else if (type.equals("StaffMemberProfile")) { TppCsvHelper helper = new TppCsvHelper(service.getId(), systemId, exchange.getId()); String[] arr = new String[]{filePath}; Map<String, String> versions = TppCsvToFhirTransformer.buildParserToVersionsMap(arr, helper); String version = versions.get(filePath); SRStaffMemberProfile parser = new SRStaffMemberProfile(service.getId(), systemId, exchange.getId(), version, filePath); while (parser.nextRecord()) { //just spin through it } //bulk load the file into the DB int fileId = parser.getFileAuditId().intValue(); TppStaffDalI dal = DalProvider.factoryTppStaffMemberDal(); dal.updateStaffProfileLookupTable(filePath, dataDate, fileId); } else { //ignore any other file types } } } } catch (Throwable t) { LOG.error("", t); } }*/ /*public static void loadEmisStagingData(String odsCode, UUID fromExchange) { LOG.debug("Loading EMIS Staging Data for " + odsCode + " from Exchange " + fromExchange); try { ServiceDalI serviceDal = DalProvider.factoryServiceDal(); Service service = serviceDal.getByLocalIdentifier(odsCode); List<UUID> systemIds = SystemHelper.getSystemIdsForService(service); if (systemIds.size() != 1) { throw new Exception("" + systemIds.size() + " system IDs found"); } UUID systemId = systemIds.get(0); ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); List<Exchange> exchanges = exchangeDal.getExchangesByService(service.getId(), systemId, Integer.MAX_VALUE); LOG.debug("Got " + exchanges.size() + " exchanges"); //go backwards, as they're most-recent-first for (int i=exchanges.size()-1; i>=0; i--) { Exchange exchange = exchanges.get(i); if (fromExchange != null) { if (!exchange.getId().equals(fromExchange)) { LOG.debug("Skipping exchange " + exchange.getId()); continue; } fromExchange = null; } LOG.debug("Doing exchange " + exchange.getId() + " from " + exchange.getHeader(HeaderKeys.DataDate)); Date dataDate = exchange.getHeaderAsDate(HeaderKeys.DataDate); List<ExchangePayloadFile> files = ExchangeHelper.parseExchangeBody(exchange.getBody()); //skip custom extracts if (files.size() <= 2) { continue; } String version = EmisCsvToFhirTransformer.determineVersion(files); for (ExchangePayloadFile file: files) { String type = file.getType(); String filePath = file.getPath(); if (type.equals("Admin_Location")) { Location parser = new Location(service.getId(), systemId, exchange.getId(), version, filePath); while (parser.nextRecord()) { //just spin through it } //the above will have audited the table, so now we can load the bulk staging table with our file EmisLocationDalI dal = DalProvider.factoryEmisLocationDal(); int fileId = parser.getFileAuditId().intValue(); dal.updateLocationStagingTable(filePath, dataDate, fileId); } else if (type.equals("Admin_OrganisationLocation")) { OrganisationLocation parser = new OrganisationLocation(service.getId(), systemId, exchange.getId(), version, filePath); while (parser.nextRecord()) { //just spin through it } //the above will have audited the table, so now we can load the bulk staging table with our file EmisLocationDalI dal = DalProvider.factoryEmisLocationDal(); int fileId = parser.getFileAuditId().intValue(); dal.updateOrganisationLocationStagingTable(filePath, dataDate, fileId); } else if (type.equals("Admin_Organisation")) { Organisation parser = new Organisation(service.getId(), systemId, exchange.getId(), version, filePath); while (parser.nextRecord()) { //just spin through it } //the above will have audited the table, so now we can load the bulk staging table with our file EmisOrganisationDalI dal = DalProvider.factoryEmisOrganisationDal(); int fileId = parser.getFileAuditId().intValue(); dal.updateStagingTable(filePath, dataDate, fileId); } else if (type.equals("Admin_UserInRole")) { UserInRole parser = new UserInRole(service.getId(), systemId, exchange.getId(), version, filePath); while (parser.nextRecord()) { //just spin through it } EmisUserInRoleDalI dal = DalProvider.factoryEmisUserInRoleDal(); int fileId = parser.getFileAuditId().intValue(); dal.updateStagingTable(filePath, dataDate, fileId); } else if (type.equals("Coding_ClinicalCode")) { EmisCsvHelper helper = new EmisCsvHelper(service.getId(), systemId, exchange.getId(), null, null); ClinicalCode parser = new ClinicalCode(service.getId(), systemId, exchange.getId(), version, filePath); File extraColsFile = ClinicalCodeTransformer.createExtraColsFile(parser, helper); EmisCodeDalI dal = DalProvider.factoryEmisCodeDal(); dal.updateClinicalCodeTable(filePath, extraColsFile.getAbsolutePath(), dataDate); FileHelper.deleteRecursiveIfExists(extraColsFile); } else if (type.equals("Coding_DrugCode")) { EmisCodeDalI dal = DalProvider.factoryEmisCodeDal(); dal.updateDrugCodeTable(filePath, dataDate); } else { //ignore any other file types } } } } catch (Throwable t) { LOG.error("", t); } }*/ /*public static void requeueSkippedAdminData(boolean tpp, boolean oneAtATime) { LOG.debug("Re-queueing skipped admin data for TPP = " + tpp); try { Connection connection = ConnectionManager.getAuditNonPooledConnection(); String tagsLike = null; if (tpp) { tagsLike = "TPP"; } else { tagsLike = "EMIS"; } while (true) { String sql = "select s.local_id, a.exchange_id" + " from audit.skipped_admin_data a" + " inner join admin.service s" + " on s.id = a.service_id" + " where s.tags like '%" + tagsLike + "%'" + " and a.queued = false" + " order by a.service_id, a.dt_skipped" + " limit 1"; Statement statement = connection.createStatement(); ResultSet rs = statement.executeQuery(sql); if (!rs.next()) { LOG.debug("Finished"); break; } String odsCode = rs.getString(1); UUID firstExchangeId = UUID.fromString(rs.getString(2)); LOG.debug("Found " + odsCode + " from " + firstExchangeId); ServiceDalI serviceDal = DalProvider.factoryServiceDal(); Service service = serviceDal.getByLocalIdentifier(odsCode); List<UUID> systemIds = SystemHelper.getSystemIdsForService(service); if (systemIds.size() != 1) { throw new Exception("Not one system ID for " + service); } UUID systemId = systemIds.get(0); List<UUID> exchangeIds = new ArrayList<>(); ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); List<UUID> allExchangeIds = exchangeDal.getExchangeIdsForService(service.getId(), systemId); int index = allExchangeIds.indexOf(firstExchangeId); for (int i=index; i<allExchangeIds.size(); i++) { UUID exchangeId = allExchangeIds.get(i); exchangeIds.add(exchangeId); } Set<String> fileTypesToFilterOn = new HashSet<>(); if (tpp) { fileTypesToFilterOn.add("Ctv3"); fileTypesToFilterOn.add("Ctv3Hierarchy"); fileTypesToFilterOn.add("ImmunisationContent"); fileTypesToFilterOn.add("Mapping"); fileTypesToFilterOn.add("ConfiguredListOption"); fileTypesToFilterOn.add("MedicationReadCodeDetails"); fileTypesToFilterOn.add("Ccg"); fileTypesToFilterOn.add("Trust"); fileTypesToFilterOn.add("Organisation"); fileTypesToFilterOn.add("OrganisationBranch"); fileTypesToFilterOn.add("StaffMember"); fileTypesToFilterOn.add("StaffMemberProfile"); } else { fileTypesToFilterOn.add("Agreements_SharingOrganisation"); fileTypesToFilterOn.add("Admin_OrganisationLocation"); fileTypesToFilterOn.add("Admin_Location"); fileTypesToFilterOn.add("Admin_Organisation"); fileTypesToFilterOn.add("Admin_UserInRole"); fileTypesToFilterOn.add("Appointment_SessionUser"); fileTypesToFilterOn.add("Appointment_Session"); fileTypesToFilterOn.add("Appointment_Slot"); } QueueHelper.postToExchange(exchangeIds, QueueHelper.EXCHANGE_INBOUND, null, true, "Going back to skipped admin", fileTypesToFilterOn, null); //update table after re-queuing sql = "update audit.skipped_admin_data a" + " inner join admin.service s" + " on s.id = a.service_id" + " set a.queued = true" + " where s.local_id = '" + odsCode + "'"; statement.executeUpdate(sql); connection.commit(); LOG.debug("Requeued " + exchangeIds.size() + " for " + odsCode); if (oneAtATime) { continueOrQuit(); } } connection.close(); LOG.debug("Finished Re-queueing skipped admin data for " + tagsLike); } catch (Throwable t) { LOG.error("", t); } }*/ /** * handy fn to stop a routine for manual inspection before continuing (or quitting) */ private static void continueOrQuit() throws Exception { LOG.info("Enter y to continue, anything else to quit"); byte[] bytes = new byte[10]; System.in.read(bytes); char c = (char) bytes[0]; if (c != 'y' && c != 'Y') { System.out.println("Read " + c); System.exit(1); } } public static void catptureBartsEncounters(int count, String toFile) { LOG.debug("Capturing " + count + " Barts Encounters to " + toFile); try { UUID serviceId = UUID.fromString("b5a08769-cbbe-4093-93d6-b696cd1da483"); UUID systemId = UUID.fromString("d874c58c-91fd-41bb-993e-b1b8b22038b2"); File dstFile = new File(toFile); FileOutputStream fos = new FileOutputStream(dstFile); OutputStreamWriter osw = new OutputStreamWriter(fos); BufferedWriter bufferedWriter = new BufferedWriter(osw); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //the Emis records use Windows record separators, so we need to match that otherwise //the bulk import routine will fail CSVFormat format = EmisCsvToFhirTransformer.CSV_FORMAT .withHeader("patientId", "episodeId", "id", "startDateDesc", "endDateDesc", "messageTypeCode", "messageTypeDesc", "statusDesc", "statusHistorySize", "classDesc", "typeDesc", "practitionerId", "dtRecordedDesc", "exchangeDateDesc", "currentLocation", "locationHistorySize", "serviceProvider", "cegEnterpriseId", "bhrEnterpriseId", "json" ); CSVPrinter printer = new CSVPrinter(bufferedWriter, format); ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); List<Exchange> exchanges = exchangeDal.getExchangesByService(serviceId, systemId, count); LOG.debug("Found " + count + " exchanges"); int done = 0; for (Exchange exchange: exchanges) { String body = exchange.getBody(); try { Bundle bundle = (Bundle)FhirResourceHelper.deserialiseResouce(body); List<Bundle.BundleEntryComponent> entries = bundle.getEntry(); for (Bundle.BundleEntryComponent entry: entries) { Resource resource = entry.getResource(); if (resource instanceof Encounter) { Encounter encounter = (Encounter)resource; String id = encounter.getId(); String dtRecordedDesc = null; DateTimeType dtRecorded = (DateTimeType)ExtensionConverter.findExtensionValue(encounter, FhirExtensionUri.RECORDED_DATE); if (dtRecorded != null) { Date d = dtRecorded.getValue(); dtRecordedDesc = sdf.format(d); } String messageTypeDesc = null; String messageTypeCode = null; CodeableConcept messageTypeConcept = (CodeableConcept)ExtensionConverter.findExtensionValue(encounter, FhirExtensionUri.HL7_MESSAGE_TYPE); if (messageTypeConcept != null) { messageTypeDesc = messageTypeConcept.getText(); if (messageTypeConcept.hasCoding()) { Coding coding = messageTypeConcept.getCoding().get(0); messageTypeCode = coding.getCode(); } } String statusDesc = null; if (encounter.hasStatus()) { statusDesc = "" + encounter.getStatus(); } Integer statusHistorySize = 0; if (encounter.hasStatusHistory()) { statusHistorySize = new Integer(encounter.getStatusHistory().size()); } String classDesc = null; if (encounter.hasClass_()) { classDesc = "" + encounter.getClass_(); } String typeDesc = null; if (encounter.hasType()) { List<CodeableConcept> types = encounter.getType(); CodeableConcept type = types.get(0); typeDesc = type.getText(); } String patientId = null; if (encounter.hasPatient()) { Reference ref = encounter.getPatient(); patientId = ReferenceHelper.getReferenceId(ref); } String episodeId = null; if (encounter.hasEpisodeOfCare()) { List<Reference> refs = encounter.getEpisodeOfCare(); Reference ref = refs.get(0); episodeId = ReferenceHelper.getReferenceId(ref); } String practitionerId = null; if (encounter.hasParticipant()) { List<Encounter.EncounterParticipantComponent> parts = encounter.getParticipant(); Encounter.EncounterParticipantComponent part = parts.get(0); if (part.hasIndividual()) { Reference ref = part.getIndividual(); practitionerId = ReferenceHelper.getReferenceId(ref); } } String startDateDesc = null; String endDateDesc = null; if (encounter.hasPeriod()) { Period p = encounter.getPeriod(); if (p.hasStart()) { startDateDesc = sdf.format(p.getStart()); } if (p.hasEnd()) { endDateDesc = sdf.format(p.getEnd()); } } Date dataDate = exchange.getHeaderAsDate(HeaderKeys.DataDate); String exchangeDateDesc = sdf.format(dataDate); Integer locationHistorySize = 0; String currentLocation = null; if (encounter.hasLocation()) { locationHistorySize = new Integer(encounter.getLocation().size()); for (Encounter.EncounterLocationComponent loc: encounter.getLocation()) { if (loc.getStatus() == Encounter.EncounterLocationStatus.ACTIVE) { Reference ref = loc.getLocation(); currentLocation = ReferenceHelper.getReferenceId(ref); } } } String serviceProvider = null; if (encounter.hasServiceProvider()) { Reference ref = encounter.getServiceProvider(); serviceProvider = ReferenceHelper.getReferenceId(ref); } SubscriberResourceMappingDalI dal = DalProvider.factorySubscriberResourceMappingDal("ceg_enterprise"); Long cegEnterpriseId = dal.findEnterpriseIdOldWay(ResourceType.Encounter.toString(), id); dal = DalProvider.factorySubscriberResourceMappingDal("pcr_01_enterprise_pi"); Long bhrEnterpriseId = dal.findEnterpriseIdOldWay(ResourceType.Encounter.toString(), id); String json = FhirSerializationHelper.serializeResource(encounter); printer.printRecord(patientId, episodeId, id, startDateDesc, endDateDesc, messageTypeCode, messageTypeDesc, statusDesc, statusHistorySize, classDesc, typeDesc, practitionerId, dtRecordedDesc, exchangeDateDesc, currentLocation, locationHistorySize, serviceProvider, cegEnterpriseId, bhrEnterpriseId, json); } } } catch (Exception ex) { throw new Exception("Exception on exchange " + exchange.getId(), ex); } done ++; if (done % 100 == 0) { LOG.debug("Done " + done); } } printer.close(); LOG.debug("Finished Capturing Barts Encounters to " + dstFile); } catch (Throwable t) { LOG.error("", t); } } public static void transformAdtEncounters(String odsCode, String tableName) { LOG.debug("Transforming " + odsCode + " Encounters from " + tableName); try { ServiceDalI serviceDal = DalProvider.factoryServiceDal(); Service service = serviceDal.getByLocalIdentifier(odsCode); LOG.debug("Running for " + service); /*SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); Date from = sdf.parse(dFrom); Date to = sdf.parse(dTo);*/ UUID serviceId = service.getId(); UUID systemId = UUID.fromString("d874c58c-91fd-41bb-993e-b1b8b22038b2"); ResourceDalI resourceDal = DalProvider.factoryResourceDal(); ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); int done = 0; while (true) { Connection connection = ConnectionManager.getEdsNonPooledConnection(); Statement statement = connection.createStatement(); List<UUID> ids = new ArrayList<>(); ResultSet rs = statement.executeQuery("SELECT exchange_id FROM " + tableName + " WHERE done = 0 ORDER BY timestamp LIMIT 1000"); while (rs.next()) { UUID exchangeId = UUID.fromString(rs.getString(1)); ids.add(exchangeId); Exchange exchange = exchangeDal.getExchange(exchangeId); String body = exchange.getBody(); try { if (!body.equals("[]")) { Bundle bundle = (Bundle) FhirResourceHelper.deserialiseResouce(body); List<Bundle.BundleEntryComponent> entries = bundle.getEntry(); for (Bundle.BundleEntryComponent entry : entries) { Resource resource = entry.getResource(); if (resource instanceof Encounter) { Encounter encounter = (Encounter) resource; ResourceWrapper currentWrapper = resourceDal.getCurrentVersion(serviceId, encounter.getResourceType().toString(), UUID.fromString(encounter.getId())); if (currentWrapper != null && !currentWrapper.isDeleted()) { List<UUID> batchIdsCreated = new ArrayList<>(); TransformError transformError = new TransformError(); FhirResourceFiler innerFiler = new FhirResourceFiler(exchange.getId(), serviceId, systemId, transformError, batchIdsCreated); FhirHl7v2Filer.AdtResourceFiler filer = new FhirHl7v2Filer.AdtResourceFiler(innerFiler); ExchangeTransformAudit transformAudit = new ExchangeTransformAudit(); transformAudit.setServiceId(serviceId); transformAudit.setSystemId(systemId); transformAudit.setExchangeId(exchange.getId()); transformAudit.setId(UUID.randomUUID()); transformAudit.setStarted(new Date()); AuditWriter.writeExchangeEvent(exchange.getId(), "Re-transforming Encounter for encounter_event"); //actually call the transform code Encounter currentEncounter = (Encounter) currentWrapper.getResource(); EncounterTransformer.updateEncounter(currentEncounter, encounter, filer); innerFiler.waitToFinish(); transformAudit.setEnded(new Date()); transformAudit.setNumberBatchesCreated(new Integer(batchIdsCreated.size())); if (transformError.getError().size() > 0) { transformAudit.setErrorXml(TransformErrorSerializer.writeToXml(transformError)); } exchangeDal.save(transformAudit); if (!transformError.getError().isEmpty()) { throw new Exception("Had error on Exchange " + exchange.getId()); } String batchIdString = ObjectMapperPool.getInstance().writeValueAsString(batchIdsCreated.toArray()); exchange.setHeader(HeaderKeys.BatchIdsJson, batchIdString); //send on to protocol queue PostMessageToExchangeConfig exchangeConfig = QueueHelper.findExchangeConfig("EdsProtocol"); PostMessageToExchange component = new PostMessageToExchange(exchangeConfig); component.process(exchange); } } } } //mark as done Connection connection2 = ConnectionManager.getEdsConnection(); PreparedStatement ps = connection2.prepareStatement("UPDATE " + tableName + " SET done = 1 WHERE exchange_id = ?"); ps.setString(1, exchangeId.toString()); ps.executeUpdate(); connection2.commit(); ps.close(); connection2.close(); } catch (Exception ex) { throw new Exception("Exception on exchange " + exchange.getId(), ex); } done++; if (done % 100 == 0) { LOG.debug("Done " + done); } } statement.close(); connection.close(); if (ids.isEmpty()) { break; } } LOG.debug("Done " + done); LOG.debug("Finished Transforming Barts Encounters from " + tableName); } catch (Throwable t) { LOG.error("", t); } } public static void findEmisServicesNeedReprocessing(String odsCodeRegex) { LOG.debug("Finding Emis Services that Need Re-processing for " + odsCodeRegex); try { ServiceDalI serviceDal = DalProvider.factoryServiceDal(); List<Service> services = serviceDal.getAll(); for (Service service: services) { Map<String, String> tags = service.getTags(); if (tags == null || !tags.containsKey("EMIS")) { continue; } if (shouldSkipService(service, odsCodeRegex)) { continue; } List<UUID> systemIds = SystemHelper.getSystemIdsForService(service); if (systemIds.size() != 1) { throw new Exception("Wrong number of system IDs for " + service); } UUID systemId = systemIds.get(0); String publisherStatus = null; for (ServiceInterfaceEndpoint serviceInterface: service.getEndpointsList()) { if (serviceInterface.getSystemUuid().equals(systemId)) { publisherStatus = serviceInterface.getEndpoint(); } } if (publisherStatus == null) { throw new Exception("Failed to find publisher status for service " + service); } LOG.debug(""); LOG.debug("CHECKING " + service + " " + publisherStatus + " >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); if (publisherStatus.equals(ServiceInterfaceEndpoint.STATUS_AUTO_FAIL)) { LOG.debug("Skipping service because set to auto-fail"); continue; } //check if in the bulks skipped table and are waiting to be re-queued Connection connection = ConnectionManager.getEdsConnection(); String sql = "select 1 from audit.skipped_exchanges_left_and_dead where ods_code = ? and (queued = false or queued is null)"; PreparedStatement ps = connection.prepareStatement(sql); ps.setString(1, service.getLocalId()); ResultSet rs = ps.executeQuery(); boolean needsRequeueing = rs.next(); ps.close(); connection.close(); if (needsRequeueing) { LOG.debug(">>>>> NEEDS REQUEUEING FOR SKIPPED BULK"); } ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); List<Exchange> exchanges = exchangeDal.getExchangesByService(service.getId(), systemId, Integer.MAX_VALUE); for (int i=exchanges.size()-1; i>=0; i Exchange exchange = exchanges.get(i); //if can't be queued, ignore it Boolean allowQueueing = exchange.getHeaderAsBoolean(HeaderKeys.AllowQueueing); if (allowQueueing != null && !allowQueueing.booleanValue()) { continue; } //skip any custom extracts String body = exchange.getBody(); List<ExchangePayloadFile> files = ExchangeHelper.parseExchangeBody(body, false); if (files.size() <= 1) { continue; } //LOG.debug("Doing exchange " + exchange.getId() + " from " + exchange.getHeaderAsDate(HeaderKeys.DataDate)); List<ExchangeTransformAudit> audits = exchangeDal.getAllExchangeTransformAudits(service.getId(), systemId, exchange.getId()); List<ExchangeEvent> events = exchangeDal.getExchangeEvents(exchange.getId()); //was it transformed OK before it was re-queued with filtering? boolean transformedWithoutFiltering = false; List<String> logging = new ArrayList<>(); for (ExchangeTransformAudit audit: audits) { //transformed OK boolean transformedOk = audit.getEnded() != null && audit.getErrorXml() == null; if (!transformedOk) { logging.add("Audit " + audit.getStarted() + " didn't complete OK, so not counting"); continue; } //if transformed OK see whether filtering was applied BEFORE Date dtTransformStart = audit.getStarted(); logging.add("Audit completed OK from " + audit.getStarted()); //find immediately proceeding event showing loading into inbound queue ExchangeEvent previousLoadingEvent = null; for (int j=events.size()-1; j>=0; j ExchangeEvent event = events.get(j); Date dtEvent = event.getTimestamp(); if (dtEvent.after(dtTransformStart)) { logging.add("Ignoring event from " + dtEvent + " as AFTER transform"); continue; } String eventDesc = event.getEventDesc(); if (eventDesc.startsWith("Manually pushed into edsInbound exchange") || eventDesc.startsWith("Manually pushed into EdsInbound exchange")) { previousLoadingEvent = event; logging.add("Proceeding event from " + dtEvent + " [" + eventDesc + "]"); break; } else { logging.add("Ignoring event from " + dtEvent + " as doesn't match text [" + eventDesc + "]"); } } if (previousLoadingEvent == null) { //if transformed OK and no previous manual loading event, then it was OK transformedWithoutFiltering = true; //LOG.debug("Audit from " + audit.getStarted() + " was transformed OK without being manually loaded = OK"); } else { //if transformed OK and was manually loaded into queue, then see if event applied filtering or not String eventDesc = previousLoadingEvent.getEventDesc(); if (!eventDesc.contains("Filtered on file types")) { transformedWithoutFiltering = true; //LOG.debug("Audit from " + audit.getStarted() + " was transformed OK and was manually loaded without filtering = OK"); } else { logging.add("Event desc filters on file types, so DIDN'T transform OK"); } } } if (!transformedWithoutFiltering) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); LOG.error("" + service + " -> exchange " + exchange.getId() + " from " + sdf.format(exchange.getHeaderAsDate(HeaderKeys.DataDate))); /*for (String line: logging) { LOG.error(" " + line); }*/ } } } LOG.debug("Finished Finding Emis Services that Need Re-processing"); } catch (Throwable t) { LOG.error("", t); } } // For the protocol name provided, get the list of services which are publishers and send // their transformed Patient and EpisodeOfCare FHIR resources to the Enterprise Filer public static void transformAndFilePatientsAndEpisodesForProtocolServices (String protocolName, String subscriberConfigName) throws Exception { //find the protocol using the name parameter LibraryItem matchedLibraryItem = BulkHelper.findProtocolLibraryItem(protocolName); if (matchedLibraryItem == null) { System.out.println("Protocol not found : " + protocolName); return; } UUID protocolUuid = UUID.fromString(matchedLibraryItem.getUuid()); ResourceDalI dal = DalProvider.factoryResourceDal(); PatientSearchDalI patientSearchDal = DalProvider.factoryPatientSearchDal(); //get all the active publishing services for this protocol List<ServiceContract> serviceContracts = matchedLibraryItem.getProtocol().getServiceContract(); for (ServiceContract serviceContract : serviceContracts) { if (serviceContract.getType().equals(PUBLISHER) && serviceContract.getActive() == ServiceContractActive.TRUE) { UUID serviceUuid = UUID.fromString(serviceContract.getService().getUuid()); List<UUID> patientIds = patientSearchDal.getPatientIds(serviceUuid, true); for (UUID patientId : patientIds) { List<ResourceWrapper> patientResources = new ArrayList<>(); UUID batchUuid = UUID.randomUUID(); //need the Patient and the EpisodeOfCare resources for each service patient ResourceWrapper patientWrapper = dal.getCurrentVersion(serviceUuid, ResourceType.Patient.toString(), patientId); if (patientWrapper == null) { LOG.warn("Null patient resource for Patient " + patientId); continue; } patientResources.add(patientWrapper); String patientContainerString = BulkHelper.getEnterpriseContainerForPatientData(patientResources, serviceUuid, batchUuid, protocolUuid, subscriberConfigName, patientId); // Use a random UUID for a queued message ID if (patientContainerString != null) { EnterpriseFiler.file(batchUuid, UUID.randomUUID(), patientContainerString, subscriberConfigName); } List<ResourceWrapper> episodeResources = new ArrayList<>(); //patient may have multiple episodes of care at the service, so pass them in List<ResourceWrapper> episodeWrappers = dal.getResourcesByPatient(serviceUuid, patientId, ResourceType.EpisodeOfCare.toString()); if (episodeWrappers.isEmpty()) { LOG.warn("No episode resources for Patient " + patientId); continue; } for (ResourceWrapper episodeWrapper: episodeWrappers ) { episodeResources.add(episodeWrapper); } String episodeContainerString = BulkHelper.getEnterpriseContainerForEpisodeData(episodeResources, serviceUuid, batchUuid, protocolUuid, subscriberConfigName, patientId); // Use a random UUID for a queued message ID if (episodeContainerString != null) { EnterpriseFiler.file(batchUuid, UUID.randomUUID(), episodeContainerString, subscriberConfigName); } } } } } /** * we've found that the TPP data contains registration data for other organisations, which * is causing a lot of confusion (and potential duplication). The transform now doesn't process these * records, and this routine will tidy up any existing data */ public static void deleteTppEpisodesElsewhere(String odsCodeRegex, boolean testMode) { LOG.debug("Deleting TPP Episodes Elsewhere for " + odsCodeRegex); try { ServiceDalI serviceDal = DalProvider.factoryServiceDal(); List<Service> services = serviceDal.getAll(); for (Service service: services) { Map<String, String> tags = service.getTags(); if (tags == null || !tags.containsKey("TPP")) { continue; } if (shouldSkipService(service, odsCodeRegex)) { continue; } LOG.debug("Doing " + service); List<UUID> systemIds = SystemHelper.getSystemIdsForService(service); if (systemIds.size() != 1) { throw new Exception("Wrong number of system IDs for " + service); } UUID systemId = systemIds.get(0); PatientSearchDalI patientSearchDal = DalProvider.factoryPatientSearchDal(); ResourceDalI resourceDal = DalProvider.factoryResourceDal(); List<UUID> patientIds = patientSearchDal.getPatientIds(service.getId(), false); LOG.debug("Found " + patientIds.size()); //create dummy exchange String bodyJson = JsonSerializer.serialize(new ArrayList<ExchangePayloadFile>()); String odsCode = service.getLocalId(); Exchange exchange = null; UUID exchangeId = UUID.randomUUID(); List<UUID> batchIdsCreated = new ArrayList<>(); FhirResourceFiler filer = new FhirResourceFiler(exchangeId, service.getId(), systemId, new TransformError(), batchIdsCreated); int deleted = 0; for (int i=0; i<patientIds.size(); i++) { UUID patientId = patientIds.get(i); Patient patient = (Patient)resourceDal.getCurrentVersionAsResource(service.getId(), ResourceType.Patient, patientId.toString()); if (patient == null) { continue; } if (!patient.hasManagingOrganization()) { throw new Exception("No managing organization on Patient " + patientId); } Reference patientManagingOrgRef = patient.getManagingOrganization(); List<ResourceWrapper> wrappers = resourceDal.getResourcesByPatient(service.getId(), patientId, ResourceType.EpisodeOfCare.toString()); for (ResourceWrapper wrapper: wrappers) { if (wrapper.isDeleted()) { throw new Exception("Unexpected deleted resource " + wrapper.getResourceType() + " " + wrapper.getResourceId()); } EpisodeOfCare episodeOfCare = (EpisodeOfCare)wrapper.getResource(); if (!episodeOfCare.hasManagingOrganization()) { throw new Exception("No managing organization on Episode " + episodeOfCare.getId()); } Reference episodeManagingOrgRef = episodeOfCare.getManagingOrganization(); if (!ReferenceHelper.equals(patientManagingOrgRef, episodeManagingOrgRef)) { deleted ++; //delete this episode if (testMode) { LOG.debug("Would delete episode " + episodeOfCare.getId()); } else { if (exchange == null) { exchange = new Exchange(); exchange.setId(exchangeId); exchange.setBody(bodyJson); exchange.setTimestamp(new Date()); exchange.setHeaders(new HashMap<>()); exchange.setHeaderAsUuid(HeaderKeys.SenderServiceUuid, service.getId()); exchange.setHeader(HeaderKeys.ProtocolIds, ""); //just set to non-null value, so postToExchange(..) can safely recalculate exchange.setHeader(HeaderKeys.SenderLocalIdentifier, odsCode); exchange.setHeaderAsUuid(HeaderKeys.SenderSystemUuid, systemId); exchange.setHeader(HeaderKeys.SourceSystem, MessageFormat.TPP_CSV); exchange.setServiceId(service.getId()); exchange.setSystemId(systemId); AuditWriter.writeExchange(exchange); AuditWriter.writeExchangeEvent(exchange, "Manually created to delete Episodes at other organisations"); } //delete resource filer.deletePatientResource(null, false, new EpisodeOfCareBuilder(episodeOfCare)); } } } if (i % 1000 == 0) { LOG.debug("Done " + i); } } LOG.debug("Finished processing " + patientIds.size() + " patients and deleted " + deleted + " episodes"); if (!testMode) { //close down filer filer.waitToFinish(); if (exchange != null) { //set multicast header String batchIdString = ObjectMapperPool.getInstance().writeValueAsString(batchIdsCreated.toArray()); exchange.setHeader(HeaderKeys.BatchIdsJson, batchIdString); //post to Rabbit protocol queue List<UUID> exchangeIds = new ArrayList<>(); exchangeIds.add(exchange.getId()); QueueHelper.postToExchange(exchangeIds, "EdsProtocol", null, true, null); //set the flag to prevent any re-queuing exchange.setHeaderAsBoolean(HeaderKeys.AllowQueueing, new Boolean(false)); //don't allow this to be re-queued AuditWriter.writeExchange(exchange); } } } LOG.debug("Finished Deleting TPP Episodes Elsewhere for " + odsCodeRegex); } catch (Throwable t) { LOG.error("", t); } } public static void postToInboundFromFile(String filePath, String reason) { try { LOG.info("Posting to inbound exchange from file " + filePath); //read in file into map keyed by service and system Map<UUID, Map<UUID, List<UUID>>> hmExchangeIds = new HashMap<>(); FileReader fr = new FileReader(filePath); BufferedReader br = new BufferedReader(fr); ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); ServiceDalI serviceDalI = DalProvider.factoryServiceDal(); while (true) { String line = br.readLine(); if (line == null) { break; } UUID exchangeId = UUID.fromString(line); Exchange exchange = exchangeDal.getExchange(exchangeId); UUID serviceId = exchange.getServiceId(); UUID systemId = exchange.getSystemId(); Map<UUID, List<UUID>> inner = hmExchangeIds.get(serviceId); if (inner == null) { inner = new HashMap<>(); hmExchangeIds.put(serviceId, inner); } List<UUID> list = inner.get(systemId); if (list == null) { list = new ArrayList<>(); inner.put(systemId, list); } list.add(exchangeId); } br.close(); LOG.debug("Found exchanges for " + hmExchangeIds.size() + " services"); for (UUID serviceId: hmExchangeIds.keySet()) { Map<UUID, List<UUID>> inner = hmExchangeIds.get(serviceId); Service service = serviceDalI.getById(serviceId); LOG.debug("Doing " + service); for (UUID systemId: inner.keySet()) { List<UUID> exchangeIds = inner.get(systemId); int count = 0; List<UUID> exchangeIdBatch = new ArrayList<>(); for (UUID exchangeId : exchangeIds) { count++; exchangeIdBatch.add(exchangeId); //update the transform audit, so EDS UI knows we've re-queued this exchange ExchangeTransformAudit audit = exchangeDal.getMostRecentExchangeTransform(serviceId, systemId, exchangeId); if (audit != null && !audit.isResubmitted()) { audit.setResubmitted(true); exchangeDal.save(audit); } if (exchangeIdBatch.size() >= 1000) { QueueHelper.postToExchange(exchangeIdBatch, "EdsInbound", null, false, reason); exchangeIdBatch = new ArrayList<>(); LOG.info("Done " + count); } } if (!exchangeIdBatch.isEmpty()) { QueueHelper.postToExchange(exchangeIdBatch, "EdsInbound", null, false, reason); LOG.info("Done " + count); } } } LOG.info("Finished Posting to inbound"); } catch (Throwable ex) { LOG.error("", ex); } } public static void deleteDataFromOldCoreDB(UUID serviceId, String previousPublisherConfigName) { LOG.debug("Deleting data from old Core DB server for " + serviceId); try { ServiceDalI serviceDal = DalProvider.factoryServiceDal(); Service service = serviceDal.getById(serviceId); LOG.debug("Service = " + service); //find a service on the OLD config DB UUID altServiceId = null; for (Service s: serviceDal.getAll()) { if (s.getPublisherConfigName() != null && s.getPublisherConfigName().equals(previousPublisherConfigName)) { altServiceId = s.getId(); break; } } if (altServiceId == null) { throw new Exception("Failed to find any service on publisher " + previousPublisherConfigName); } //find all subscriber config names Set<String> subscriberConfigNames = new HashSet<>(); List<String> protocolIds = DetermineRelevantProtocolIds.getProtocolIdsForPublisherServiceOldWay(serviceId.toString()); for (String oldProtocolId: protocolIds) { LibraryItem libraryItem = LibraryRepositoryHelper.getLibraryItemUsingCache(UUID.fromString(oldProtocolId)); Protocol protocol = libraryItem.getProtocol(); //skip disabled protocols if (protocol.getEnabled() != ProtocolEnabled.TRUE) { continue; } List<ServiceContract> subscribers = protocol .getServiceContract() .stream() .filter(sc -> sc.getType().equals(ServiceContractType.SUBSCRIBER)) .filter(sc -> sc.getActive() == ServiceContractActive.TRUE) //skip disabled service contracts .collect(Collectors.toList()); for (ServiceContract serviceContract : subscribers) { String subscriberConfigName = MessageTransformOutbound.getSubscriberEndpoint(serviceContract); subscriberConfigNames.add(subscriberConfigName); } } LOG.debug("Found " + subscriberConfigNames.size() + " subscribers: " + subscriberConfigNames); PatientSearchDalI patientSearchDal = DalProvider.factoryPatientSearchDal(); List<UUID> patientIds = patientSearchDal.getPatientIds(serviceId, true); LOG.debug("Found " + patientIds.size()); patientIds.add(null); //for admin resources Connection ehrConnection = ConnectionManager.getEhrNonPooledConnection(altServiceId); int done = 0; for (UUID patientId: patientIds) { //send to each subscriber for (String subscriberConfigName: subscriberConfigNames) { SubscriberResourceMappingDalI subscriberDal = DalProvider.factorySubscriberResourceMappingDal(subscriberConfigName); OutputContainer output = new OutputContainer(); boolean doneSomething = false; String sql = "SELECT resource_id, resource_type" + " FROM resource_current" + " WHERE service_id = ?" + " AND patient_id = ?"; PreparedStatement ps = ehrConnection.prepareStatement(sql); ps.setFetchSize(500); ps.setString(1, serviceId.toString()); if (patientId == null) { ps.setString(2, ""); //get admin data } else { ps.setString(2, patientId.toString()); } ResultSet rs = ps.executeQuery(); while (rs.next()) { String resourceId = rs.getString(1); String resourceType = rs.getString(2); String sourceId = ReferenceHelper.createResourceReference(resourceType, resourceId); SubscriberTableId subscriberTableId = null; if (resourceType.equals("Patient")) { subscriberTableId = SubscriberTableId.PATIENT; } else if (resourceType.equals("AllergyIntolerance")) { subscriberTableId = SubscriberTableId.ALLERGY_INTOLERANCE; } else if (resourceType.equals("Encounter")) { subscriberTableId = SubscriberTableId.ENCOUNTER; } else if (resourceType.equals("EpisodeOfCare")) { subscriberTableId = SubscriberTableId.EPISODE_OF_CARE; } else if (resourceType.equals("Flag")) { subscriberTableId = SubscriberTableId.FLAG; } else if (resourceType.equals("Location")) { subscriberTableId = SubscriberTableId.LOCATION; } else if (resourceType.equals("MedicationOrder")) { subscriberTableId = SubscriberTableId.MEDICATION_ORDER; } else if (resourceType.equals("MedicationStatement")) { subscriberTableId = SubscriberTableId.MEDICATION_STATEMENT; } else if (resourceType.equals("Observation") || resourceType.equals("Condition") || resourceType.equals("Immunization") || resourceType.equals("FamilyMemberHistory")) { subscriberTableId = SubscriberTableId.OBSERVATION; } else if (resourceType.equals("Organization")) { subscriberTableId = SubscriberTableId.ORGANIZATION; } else if (resourceType.equals("Practitioner")) { subscriberTableId = SubscriberTableId.PRACTITIONER; } else if (resourceType.equals("ProcedureRequest")) { subscriberTableId = SubscriberTableId.PROCEDURE_REQUEST; } else if (resourceType.equals("ReferralRequest")) { subscriberTableId = SubscriberTableId.REFERRAL_REQUEST; } else if (resourceType.equals("Schedule")) { subscriberTableId = SubscriberTableId.SCHEDULE; } else if (resourceType.equals("Appointment")) { subscriberTableId = SubscriberTableId.APPOINTMENT; } else if (resourceType.equals("DiagnosticOrder")) { subscriberTableId = SubscriberTableId.DIAGNOSTIC_ORDER; } else if (resourceType.equals("Slot")) { //these were ignored continue; } else { throw new Exception("Unexpected resource type " + resourceType + " " + resourceId); } SubscriberId subscriberId = subscriberDal.findSubscriberId(subscriberTableId.getId(), sourceId); if (subscriberId == null) { continue; } doneSomething = true; if (resourceType.equals("Patient")) { output.getPatients().writeDelete(subscriberId); //the database doesn't have any pseudo IDs, so don't need to worry about that table int maxAddresses = 0; int maxTelecoms = 0; ResourceDalI resourceDal = DalProvider.factoryResourceDal(); List<ResourceWrapper> history = resourceDal.getResourceHistory(altServiceId, resourceType, UUID.fromString(resourceId)); for (ResourceWrapper h: history) { Patient p = (Patient)h.getResource(); if (p != null) { maxAddresses = Math.max(maxAddresses, p.getAddress().size()); maxTelecoms = Math.max(maxTelecoms, p.getTelecom().size()); } } for (int i=0; i<maxAddresses; i++) { String subSourceId = sourceId + "-ADDR-" + i; SubscriberId subTableId = subscriberDal.findSubscriberId(SubscriberTableId.PATIENT_ADDRESS.getId(), subSourceId); if (subTableId != null) { output.getPatientAddresses().writeDelete(subTableId); } } for (int i=0; i<maxTelecoms; i++) { String subSourceId = sourceId + "-TELECOM-" + i; SubscriberId subTableId = subscriberDal.findSubscriberId(SubscriberTableId.PATIENT_CONTACT.getId(), subSourceId); if (subTableId != null) { output.getPatientContacts().writeDelete(subTableId); } } } else if (resourceType.equals("AllergyIntolerance")) { output.getAllergyIntolerances().writeDelete(subscriberId); } else if (resourceType.equals("Encounter")) { output.getEncounters().writeDelete(subscriberId); } else if (resourceType.equals("EpisodeOfCare")) { output.getEpisodesOfCare().writeDelete(subscriberId); //reg status history table isn't populated yet, so can ignore that } else if (resourceType.equals("Flag")) { output.getFlags().writeDelete(subscriberId); } else if (resourceType.equals("Location")) { output.getLocations().writeDelete(subscriberId); } else if (resourceType.equals("MedicationOrder")) { output.getMedicationOrders().writeDelete(subscriberId); } else if (resourceType.equals("MedicationStatement")) { output.getMedicationStatements().writeDelete(subscriberId); } else if (resourceType.equals("Observation") || resourceType.equals("Condition") || resourceType.equals("Immunization") || resourceType.equals("FamilyMemberHistory")) { output.getObservations().writeDelete(subscriberId); } else if (resourceType.equals("Organization")) { output.getOrganisations().writeDelete(subscriberId); } else if (resourceType.equals("Practitioner")) { output.getPractitioners().writeDelete(subscriberId); } else if (resourceType.equals("ProcedureRequest")) { output.getProcedureRequests().writeDelete(subscriberId); } else if (resourceType.equals("ReferralRequest")) { output.getReferralRequests().writeDelete(subscriberId); } else if (resourceType.equals("Schedule")) { output.getSchedules().writeDelete(subscriberId); } else if (resourceType.equals("Appointment")) { output.getAppointments().writeDelete(subscriberId); } else if (resourceType.equals("DiagnosticOrder")) { output.getDiagnosticOrder().writeDelete(subscriberId); } else { throw new Exception("Unexpected resource type " + resourceType + " " + resourceId); } } ps.close(); if (doneSomething) { byte[] bytes = output.writeToZip(); String base64 = Base64.getEncoder().encodeToString(bytes); UUID batchId = UUID.randomUUID(); SubscriberFiler.file(batchId, UUID.randomUUID(), base64, subscriberConfigName); } } done ++; if (done % 100 == 0) { LOG.debug("Done " + done); } } LOG.debug("Done " + done); ehrConnection.close(); LOG.debug("Finished Deleting data from old Core DB server for " + serviceId); } catch (Throwable t) { LOG.error("", t); } } public static void populateMissingOrgsInCompassV1(String subscriberConfigName, boolean testMode) { LOG.debug("Populating Missing Orgs In CompassV1 " + subscriberConfigName + " testMode = " + testMode); try { Connection subscriberTransformConnection = ConnectionManager.getSubscriberTransformNonPooledConnection(subscriberConfigName); //get orgs in that subscriber DB Map<UUID, Long> hmOrgs = new HashMap<>(); String sql = "SELECT service_id, enterprise_id FROM enterprise_organisation_id_map"; Statement statement = subscriberTransformConnection.createStatement(); ResultSet rs = statement.executeQuery(sql); while (rs.next()) { String s = rs.getString(1); long id = rs.getLong(2); hmOrgs.put(UUID.fromString(s), new Long(id)); } LOG.debug("Found " + hmOrgs.size() + " orgs"); for (UUID serviceId: hmOrgs.keySet()) { Long enterpriseId = hmOrgs.get(serviceId); LOG.debug("Doing service " + serviceId + ", enterprise ID " + enterpriseId); /*ServiceDalI serviceDal = DalProvider.factoryServiceDal(); Service service = serviceDal.getById(serviceId);*/ //find the FHIR Organization this is from sql = "SELECT resource_id FROM enterprise_id_map WHERE enterprise_id = " + enterpriseId; rs = statement.executeQuery(sql); if (!rs.next()) { sql = "SELECT resource_id FROM enterprise_id_map_3 WHERE enterprise_id = " + enterpriseId; rs = statement.executeQuery(sql); if (!rs.next()) { throw new Exception("Failed to find resource ID for service ID " + serviceId + " and enterprise ID " + enterpriseId); } } String resourceId = rs.getString(1); Reference orgRef = ReferenceHelper.createReference(ResourceType.Organization, resourceId); //make sure our org is on the CoreXX server we expect and take over any instance mapping orgRef = findNewOrgRefOnCoreDb(subscriberConfigName, orgRef, serviceId, testMode); if (orgRef == null) { LOG.warn("<<<<<<<<No Organization resource could be found for " + resourceId + ">>>>>>>>>>>>>>>>>>>>>>>>>"); continue; } //find the org and work up to find all its parents too List<ResourceWrapper> resourceWrappers = new ArrayList<>(); while (orgRef != null) { ReferenceComponents comps = ReferenceHelper.getReferenceComponents(orgRef); if (comps.getResourceType() != ResourceType.Organization) { throw new Exception("Found non-organisation resource mapping for enterprise ID " + enterpriseId + ": " + resourceId); } UUID orgId = UUID.fromString(comps.getId()); ResourceDalI resourceDal = DalProvider.factoryResourceDal(); ResourceWrapper wrapper = resourceDal.getCurrentVersion(serviceId, ResourceType.Organization.toString(), orgId); if (wrapper == null) { throw new Exception("Failed to find resource wrapper for parent org with resource ID " + resourceId); } resourceWrappers.add(wrapper); Organization org = (Organization)wrapper.getResource(); if (org.hasPartOf()) { orgRef = org.getPartOf(); } else { orgRef = null; } } if (testMode) { LOG.debug("Found " + resourceWrappers.size() + " orgs"); for (ResourceWrapper wrapper: resourceWrappers) { Organization org = (Organization)wrapper.getResource(); String odsCode = IdentifierHelper.findOdsCode(org); LOG.debug(" Got " + org.getName() + " [" + odsCode + "]"); } } else { EnterpriseTransformHelper helper = new EnterpriseTransformHelper(serviceId, null, null, null, subscriberConfigName, resourceWrappers, false); org.endeavourhealth.transform.enterprise.outputModels.Organization orgWriter = helper.getOutputContainer().getOrganisations(); OrganisationEnterpriseTransformer t = new OrganisationEnterpriseTransformer(); t.transformResources(resourceWrappers, orgWriter, helper); org.endeavourhealth.transform.enterprise.outputModels.OutputContainer output = helper.getOutputContainer(); byte[] bytes = output.writeToZip(); if (bytes == null) { LOG.debug("Generated NULL bytes"); } else { LOG.debug("Generated " + bytes.length + " bytes"); String base64 = Base64.getEncoder().encodeToString(bytes); UUID batchId = UUID.randomUUID(); EnterpriseFiler.file(batchId, UUID.randomUUID(), base64, subscriberConfigName); } } } statement.close(); subscriberTransformConnection.close(); LOG.debug("Finished Populating Missing Orgs In CompassV1 " + subscriberConfigName); } catch (Throwable t) { LOG.error("", t); } } public static void populateMissingOrgsInCompassV2(String subscriberConfigName, boolean testMode) { LOG.debug("Populating Missing Orgs In CompassV2 " + subscriberConfigName + " testMode = " + testMode); try { Connection subscriberTransformConnection = ConnectionManager.getSubscriberTransformNonPooledConnection(subscriberConfigName); //get orgs in that subscriber DB Map<UUID, Long> hmOrgs = new HashMap<>(); String sql = "SELECT service_id, enterprise_id FROM enterprise_organisation_id_map"; Statement statement = subscriberTransformConnection.createStatement(); ResultSet rs = statement.executeQuery(sql); while (rs.next()) { String s = rs.getString(1); long id = rs.getLong(2); hmOrgs.put(UUID.fromString(s), new Long(id)); } LOG.debug("Found " + hmOrgs.size() + " orgs"); for (UUID serviceId: hmOrgs.keySet()) { Long subscriberId = hmOrgs.get(serviceId); LOG.debug("Doing service " + serviceId + ", subscriber ID " + subscriberId); /*ServiceDalI serviceDal = DalProvider.factoryServiceDal(); Service service = serviceDal.getById(serviceId);*/ //find the FHIR Organization this is from sql = "SELECT source_id FROM subscriber_id_map WHERE subscriber_id = " + subscriberId; rs = statement.executeQuery(sql); if (!rs.next()) { sql = "SELECT source_id FROM subscriber_id_map_3 WHERE subscriber_id = " + subscriberId; rs = statement.executeQuery(sql); if (!rs.next()) { throw new Exception("Failed to find source ID for service ID " + serviceId + " and subscriber ID " + subscriberId); } } String sourceId = rs.getString(1); Reference orgRef = ReferenceHelper.createReference(sourceId); //make sure our org is on the CoreXX server we expect and take over any instance mapping orgRef = findNewOrgRefOnCoreDb(subscriberConfigName, orgRef, serviceId, testMode); if (orgRef == null) { LOG.warn("<<<<<<<<No Organization resource could be found for " + sourceId + ">>>>>>>>>>>>>>>>>>>>>>>>>"); continue; } //find the org and work up to find all its parents too List<ResourceWrapper> resourceWrappers = new ArrayList<>(); while (orgRef != null) { ReferenceComponents comps = ReferenceHelper.getReferenceComponents(orgRef); if (comps.getResourceType() != ResourceType.Organization) { throw new Exception("Found non-organisation resource mapping for subscriber ID " + subscriberId + ": " + sourceId); } UUID orgId = UUID.fromString(comps.getId()); ResourceDalI resourceDal = DalProvider.factoryResourceDal(); ResourceWrapper wrapper = resourceDal.getCurrentVersion(serviceId, ResourceType.Organization.toString(), orgId); if (wrapper == null) { throw new Exception("Failed to find resource wrapper for parent org with source ID " + sourceId); } resourceWrappers.add(wrapper); Organization org = (Organization)wrapper.getResource(); if (org.hasPartOf()) { orgRef = org.getPartOf(); } else { orgRef = null; } } if (testMode) { LOG.debug("Found " + resourceWrappers.size() + " orgs"); for (ResourceWrapper wrapper: resourceWrappers) { Organization org = (Organization)wrapper.getResource(); String odsCode = IdentifierHelper.findOdsCode(org); LOG.debug(" Got " + org.getName() + " [" + odsCode + "]"); } } else { SubscriberTransformHelper helper = new SubscriberTransformHelper(serviceId, null, null, null, subscriberConfigName, resourceWrappers, false); OrganisationTransformer t = new OrganisationTransformer(); t.transformResources(resourceWrappers, helper); OutputContainer output = helper.getOutputContainer(); byte[] bytes = output.writeToZip(); if (bytes == null) { LOG.debug("Generated NULL bytes"); } else { LOG.debug("Generated " + bytes.length + " bytes"); String base64 = Base64.getEncoder().encodeToString(bytes); UUID batchId = UUID.randomUUID(); SubscriberFiler.file(batchId, UUID.randomUUID(), base64, subscriberConfigName); } } } statement.close(); subscriberTransformConnection.close(); LOG.debug("Finished Populating Missing Orgs In CompassV2 " + subscriberConfigName); } catch (Throwable t) { LOG.error("", t); } } private static Reference findNewOrgRefOnCoreDb(String subscriberConfigName, Reference oldOrgRef, UUID serviceId, boolean testMode) throws Exception { try { String oldOrgId = ReferenceHelper.getReferenceId(oldOrgRef); ResourceDalI resourceDal = DalProvider.factoryResourceDal(); ResourceWrapper wrapper = resourceDal.getCurrentVersion(serviceId, ResourceType.Organization.toString(), UUID.fromString(oldOrgId)); if (wrapper != null) { LOG.trace("Organization exists at service"); return oldOrgRef; } LOG.debug("Org doesn't exist at service, so need to take over instance mapping"); Reference newOrgRef = null; PatientSearchDalI patientSearchDal = DalProvider.factoryPatientSearchDal(); List<UUID> patientIds = patientSearchDal.getPatientIds(serviceId, false, 10000); for (UUID patientId : patientIds) { ResourceDalI resourceRepository = DalProvider.factoryResourceDal(); Patient patient = (Patient) resourceRepository.getCurrentVersionAsResource(serviceId, ResourceType.Patient, patientId.toString()); if (patient == null) { continue; } if (!patient.hasManagingOrganization()) { throw new TransformException("Patient " + patient.getId() + " doesn't have a managing org for service " + serviceId); } newOrgRef = patient.getManagingOrganization(); break; } if (newOrgRef == null) { throw new Exception("Failed to find new org ref from patient records"); } String newOrgId = ReferenceHelper.getReferenceId(newOrgRef); if (newOrgId.equals(oldOrgId)) { LOG.debug("Org ref correct but doesn't exist on DB - reference data is missing???"); return null; } if (testMode) { LOG.debug("Would need to take over instance mapping from " + oldOrgId + " -> " + newOrgId); } else { LOG.debug("Taking over instance mapping from " + oldOrgId + " -> " + newOrgId); //we need to update the subscriber transform DB to make this new org ref the defacto one SubscriberInstanceMappingDalI dal = DalProvider.factorySubscriberInstanceMappingDal(subscriberConfigName); dal.takeOverInstanceMapping(ResourceType.Organization, UUID.fromString(oldOrgId), UUID.fromString(newOrgId)); LOG.debug("Done"); } return newOrgRef; } catch (Exception e) { LOG.error("Exception finding org ref for service " + serviceId, e); return null; } } /*public static void testHashedFileFilteringForSRCode(String filePath, String uniqueKey) { LOG.info("Testing Hashed File Filtering for SRCode using " + filePath); try { //HashFunction hf = Hashing.md5(); //HashFunction hf = Hashing.murmur3_128(); HashFunction hf = Hashing.sha512(); Hasher hasher = hf.newHasher(); hasher.putString(filePath, Charset.defaultCharset()); HashCode hc = hasher.hash(); int fileUniqueId = hc.asInt(); //copy file to local file String name = FilenameUtils.getName(filePath); String srcTempName = "TMP_SRC_" + name; String dstTempName = "TMP_DST_" + name; File srcFile = new File(srcTempName); File dstFile = new File(dstTempName); InputStream is = FileHelper.readFileFromSharedStorage(filePath); Files.copy(is, srcFile.toPath(), StandardCopyOption.REPLACE_EXISTING); is.close(); LOG.debug("Copied " + srcFile.length() + "byte file from S3"); CSVParser parser = CSVParser.parse(srcFile, Charset.defaultCharset(), CSVFormat.DEFAULT.withHeader()); Map<String, Integer> headers = parser.getHeaderMap(); if (!headers.containsKey(uniqueKey)) { LOG.debug("Headers found: " + headers); throw new Exception("Couldn't find unique key " + uniqueKey); } String[] headerArray = CsvHelper.getHeaderMapAsArray(parser); int uniqueKeyIndex = headers.get(uniqueKey).intValue(); Map<StringMemorySaver, StringMemorySaver> hmHashes = new ConcurrentHashMap<>(); LOG.debug("Starting hash calculations"); int done = 0; Iterator<CSVRecord> iterator = parser.iterator(); while (iterator.hasNext()) { CSVRecord record = iterator.next(); String uniqueVal = record.get(uniqueKey); Hasher hashser = hf.newHasher(); int size = record.size(); for (int i=0; i<size; i++) { if (i == uniqueKeyIndex) { continue; } String val = record.get(i); hashser.putString(val, Charset.defaultCharset()); } hc = hashser.hash(); String hashString = hc.toString(); if (hmHashes.containsKey(uniqueVal)) { LOG.error("Duplicate unique value [" + uniqueVal + "]"); } hmHashes.put(new StringMemorySaver(uniqueVal), new StringMemorySaver(hashString)); done ++; if (done % 100000 == 0) { LOG.debug("Done " + done); } } parser.close(); LOG.debug("Finished hash calculations for " + hmHashes.size()); //hit DB for each record int threadPoolSize = 10; ThreadPool threadPool = new ThreadPool(threadPoolSize, 1000, "Tester"); Map<String, String> batch = new HashMap<>(); for (StringMemorySaver uniqueVal: hmHashes.keySet()) { StringMemorySaver hash = hmHashes.get(uniqueVal); batch.put(uniqueVal.toString(), hash.toString()); if (batch.size() > TransformConfig.instance().getResourceSaveBatchSize()) { threadPool.submit(new FindHashForBatchCallable(fileUniqueId, batch, hmHashes)); batch = new HashMap<>(); } } if (!batch.isEmpty()) { threadPool.submit(new FindHashForBatchCallable(fileUniqueId, batch, hmHashes)); batch = new HashMap<>(); } threadPool.waitUntilEmpty(); LOG.debug("Finished looking for hashes on DB, filtering down to " + hmHashes.size()); //filter file CSVFormat format = CSVFormat.DEFAULT.withHeader(headerArray); FileOutputStream fos = new FileOutputStream(dstFile); OutputStreamWriter osw = new OutputStreamWriter(fos); BufferedWriter bufferedWriter = new BufferedWriter(osw); CSVPrinter csvPrinter = new CSVPrinter(bufferedWriter, format); parser = CSVParser.parse(srcFile, Charset.defaultCharset(), CSVFormat.DEFAULT.withHeader()); while (iterator.hasNext()) { CSVRecord record = iterator.next(); String uniqueVal = record.get(uniqueKey); if (hmHashes.containsKey(new StringMemorySaver(uniqueVal))) { csvPrinter.printRecord(record); } } parser.close(); csvPrinter.close(); LOG.debug("Finished filtering file with " + hmHashes.size() + " records"); //store hashes in DB batch = new HashMap<>(); for (StringMemorySaver uniqueVal: hmHashes.keySet()) { StringMemorySaver hash = hmHashes.get(uniqueVal); batch.put(uniqueVal.toString(), hash.toString()); if (batch.size() > TransformConfig.instance().getResourceSaveBatchSize()) { threadPool.submit(new SaveHashForBatchCallable(fileUniqueId, batch)); batch = new HashMap<>(); } } if (!batch.isEmpty()) { threadPool.submit(new SaveHashForBatchCallable(fileUniqueId, batch)); batch = new HashMap<>(); } threadPool.waitUntilEmpty(); LOG.debug("Finished saving hashes to DB"); //delete all files srcFile.delete(); dstFile.delete(); LOG.info("Finished Testing Hashed File Filtering for SRCode using " + filePath); } catch (Throwable t) { LOG.error("", t); } } static class SaveHashForBatchCallable implements Callable { private int fileUniqueId; private Map<String, String> batch; public SaveHashForBatchCallable(int fileUniqueId, Map<String, String> batch) { this.fileUniqueId = fileUniqueId; this.batch = batch; } @Override public Object call() throws Exception { try { Connection connection = ConnectionManager.getEdsConnection(); String sql = "INSERT INTO tmp.file_record_hash (file_id, record_id, record_hash) VALUES (?, ?, ?)" + " ON DUPLICATE KEY UPDATE" + " record_hash = VALUES(record_hash)"; PreparedStatement ps = connection.prepareStatement(sql); for (String uniqueId: batch.keySet()) { String hash = batch.get(uniqueId); int col = 1; ps.setInt(col++, fileUniqueId); ps.setString(col++, uniqueId); ps.setString(col++, hash); ps.addBatch(); } ps.executeBatch(); connection.commit(); ps.close(); connection.close(); } catch (Throwable t) { LOG.error("", t); } return null; } } static class FindHashForBatchCallable implements Callable { private int fileUniqueId; private Map<String, String> batch; private Map<StringMemorySaver, StringMemorySaver> hmHashs; public FindHashForBatchCallable(int fileUniqueId, Map<String, String> batch, Map<StringMemorySaver, StringMemorySaver> hmHashs) { this.fileUniqueId = fileUniqueId; this.batch = batch; this.hmHashs = hmHashs; } @Override public Object call() throws Exception { try { Connection connection = ConnectionManager.getEdsConnection(); String sql = "SELECT record_id, record_hash FROM tmp.file_record_hash" + " WHERE file_id = ? AND record_id IN ("; for (int i=0; i<batch.size(); i++) { if (i > 0) { sql += ", "; } sql += "?"; } sql += ")"; PreparedStatement ps = connection.prepareStatement(sql); int col = 1; ps.setInt(col++, fileUniqueId); for (String uniqueId: batch.keySet()) { ps.setString(col++, uniqueId); } ResultSet rs = ps.executeQuery(); Map<String, String> hmResults = new HashMap<>(); while (rs.next()) { String recordId = rs.getString(1); String hash = rs.getString(2); hmResults.put(recordId, hash); } ps.close(); connection.close(); for (String uniqueId: batch.keySet()) { String newHash = batch.get(uniqueId); String dbHash = hmResults.get(uniqueId); if (dbHash != null && dbHash.equals(newHash)) { hmHashs.remove(new StringMemorySaver(uniqueId)); } } } catch (Throwable t) { LOG.error("", t); } return null; } }*/ public static void testHashedFileFilteringForSRCode(String filePath, String uniqueKey, String dataDateStr) { LOG.info("Testing Hashed File Filtering for SRCode using " + filePath); try { Date dataDate = new SimpleDateFormat("YYYY-MM-DD").parse(dataDateStr); //HashFunction hf = Hashing.md5(); //HashFunction hf = Hashing.murmur3_128(); HashFunction hf = Hashing.sha512(); //copy file to local file String name = FilenameUtils.getName(filePath); String srcTempName = "TMP_SRC_" + name; String dstTempName = "TMP_DST_" + name; File srcFile = new File(srcTempName); File dstFile = new File(dstTempName); InputStream is = FileHelper.readFileFromSharedStorage(filePath); Files.copy(is, srcFile.toPath(), StandardCopyOption.REPLACE_EXISTING); is.close(); LOG.debug("Copied " + srcFile.length() + " byte file from S3"); long msStart = System.currentTimeMillis(); CSVParser parser = CSVParser.parse(srcFile, Charset.defaultCharset(), CSVFormat.DEFAULT.withHeader()); Map<String, Integer> headers = parser.getHeaderMap(); if (!headers.containsKey(uniqueKey)) { LOG.debug("Headers found: " + headers); throw new Exception("Couldn't find unique key " + uniqueKey); } String[] headerArray = CsvHelper.getHeaderMapAsArray(parser); int uniqueKeyIndex = headers.get(uniqueKey).intValue(); LOG.debug("Starting hash calculations"); String hashTempName = "TMP_HSH_" + name; File hashFile = new File(hashTempName); FileOutputStream fos = new FileOutputStream(hashFile); OutputStreamWriter osw = new OutputStreamWriter(fos); BufferedWriter bufferedWriter = new BufferedWriter(osw); CSVPrinter csvPrinter = new CSVPrinter(bufferedWriter, CSVFormat.DEFAULT.withHeader("record_id", "record_hash")); int done = 0; Iterator<CSVRecord> iterator = parser.iterator(); while (iterator.hasNext()) { CSVRecord record = iterator.next(); String uniqueVal = record.get(uniqueKey); Hasher hashser = hf.newHasher(); int size = record.size(); for (int i=0; i<size; i++) { if (i == uniqueKeyIndex) { continue; } String val = record.get(i); hashser.putString(val, Charset.defaultCharset()); } HashCode hc = hashser.hash(); String hashString = hc.toString(); csvPrinter.printRecord(uniqueVal, hashString); done ++; if (done % 200000 == 0) { LOG.debug("Done " + done); } } csvPrinter.close(); parser.close(); LOG.debug("Finished hash calculations for " + done + " records to " + hashFile); Set<StringMemorySaver> hsUniqueIdsToKeep = new HashSet<>(); String tempTableName = ConnectionManager.generateTempTableName(FilenameUtils.getBaseName(filePath)); //load into TEMP table Connection connection = ConnectionManager.getEdsNonPooledConnection(); try { //turn on auto commit so we don't need to separately commit these large SQL operations connection.setAutoCommit(true); //create a temporary table to load the data into LOG.debug("Loading " + hashFile + " into " + tempTableName); String sql = "CREATE TABLE " + tempTableName + " (" + "record_id varchar(255), " + "record_hash char(128), " + "record_exists boolean DEFAULT FALSE, " + "ignore_record boolean DEFAULT FALSE, " + "PRIMARY KEY (record_id))"; Statement statement = connection.createStatement(); //one-off SQL due to table name, so don't use prepared statement statement.executeUpdate(sql); statement.close(); //bulk load temp table, adding record number as we go LOG.debug("Starting bulk load into " + tempTableName); statement = connection.createStatement(); //one-off SQL due to table name, so don't use prepared statement sql = "LOAD DATA LOCAL INFILE '" + hashFile.getAbsolutePath().replace("\\", "\\\\") + "'" + " INTO TABLE " + tempTableName + " FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\\\"'" + " LINES TERMINATED BY '\\r\\n'" + " IGNORE 1 LINES"; statement.executeUpdate(sql); statement.close(); //work out which records already exist in the target table LOG.debug("Finding records that exist in file_record_hash"); sql = "UPDATE " + tempTableName + " s" + " INNER JOIN tmp.file_record_hash t" + " ON t.record_id = s.record_id" + " SET s.record_exists = true," + " s.ignore_record = IF (s.record_hash = t.record_hash OR t.dt_last_updated > " + ConnectionManager.formatDateString(dataDate, true) + ", true, false)"; statement = connection.createStatement(); //one-off SQL due to table name, so don't use prepared statement statement.executeUpdate(sql); statement.close(); LOG.debug("Creating index on temp table"); sql = "CREATE INDEX ix ON " + tempTableName + " (ignore_record)"; statement = connection.createStatement(); //one-off SQL due to table name, so don't use prepared statement statement.executeUpdate(sql); statement.close(); LOG.debug("Selecting IDs with different hashes"); sql = "SELECT record_id FROM " + tempTableName + " s" + " WHERE ignore_record = false"; statement = connection.createStatement(); //one-off SQL due to table name, so don't use prepared statement statement.setFetchSize(10000); ResultSet rs = statement.executeQuery(sql); while (rs.next()) { String id = rs.getString(1); hsUniqueIdsToKeep.add(new StringMemorySaver(id)); } } finally { //MUST change this back to false connection.setAutoCommit(false); connection.close(); } LOG.debug("Found " + hsUniqueIdsToKeep.size() + " records to retain"); //filter file CSVFormat format = CSVFormat.DEFAULT.withHeader(headerArray); fos = new FileOutputStream(dstFile); osw = new OutputStreamWriter(fos); bufferedWriter = new BufferedWriter(osw); csvPrinter = new CSVPrinter(bufferedWriter, format); parser = CSVParser.parse(srcFile, Charset.defaultCharset(), CSVFormat.DEFAULT.withHeader()); while (iterator.hasNext()) { CSVRecord record = iterator.next(); String uniqueVal = record.get(uniqueKey); if (hsUniqueIdsToKeep.contains(new StringMemorySaver(uniqueVal))) { csvPrinter.printRecord(record); } } parser.close(); csvPrinter.close(); LOG.debug("Finished filtering file with " + hsUniqueIdsToKeep.size() + " records"); connection = ConnectionManager.getEdsNonPooledConnection(); try { //turn on auto commit so we don't need to separately commit these large SQL operations connection.setAutoCommit(true); //update any records that previously existed, but have a changed term LOG.debug("Updating existing records in target table file_record_hash"); String sql = "UPDATE tmp.file_record_hash t" + " INNER JOIN " + tempTableName + " s" + " ON t.record_id = s.record_id" + " SET t.record_hash = s.record_hash," + " t.dt_last_updated = " + ConnectionManager.formatDateString(dataDate, true) + " WHERE s.record_exists = true"; Statement statement = connection.createStatement(); //one-off SQL due to table name, so don't use prepared statement statement.executeUpdate(sql); statement.close(); //insert records into the target table where the staging has new records LOG.debug("Inserting new records in target table file_record_hash"); sql = "INSERT IGNORE INTO tmp.file_record_hash (record_id, record_hash, dt_last_updated)" + " SELECT record_id, record_hash, " + ConnectionManager.formatDateString(dataDate, true) + " FROM " + tempTableName + " WHERE record_exists = false"; statement = connection.createStatement(); //one-off SQL due to table name, so don't use prepared statement statement.executeUpdate(sql); statement.close(); //delete the temp table LOG.debug("Deleting temp table"); sql = "DROP TABLE " + tempTableName; statement = connection.createStatement(); //one-off SQL due to table name, so don't use prepared statement statement.executeUpdate(sql); statement.close(); } finally { //MUST change this back to false connection.setAutoCommit(false); connection.close(); } LOG.debug("Finished saving hashes to DB"); long msEnd = System.currentTimeMillis(); LOG.debug("Took " + ((msEnd - msStart) / 1000) + " s"); //delete all files srcFile.delete(); hashFile.delete(); dstFile.delete(); LOG.info("Finished Testing Hashed File Filtering for SRCode using " + filePath); } catch (Throwable t) { LOG.error("", t); } } public static void deleteResourcesForDeletedPatients(boolean testMode, String odsCodeRegex) { LOG.debug("Deleting Resources for Deleted Patients using " + odsCodeRegex); try { Connection conn = ConnectionManager.getEdsNonPooledConnection(); ServiceDalI serviceDal = DalProvider.factoryServiceDal(); ResourceDalI resourceDal = DalProvider.factoryResourceDal(); List<Service> services = serviceDal.getAll(); for (Service service: services) { //only do publishers if (Strings.isNullOrEmpty(service.getPublisherConfigName())) { continue; } if (shouldSkipService(service, odsCodeRegex)) { continue; } LOG.debug("Doing " + service); List<UUID> systemIds = SystemHelper.getSystemIdsForService(service); if (systemIds.isEmpty()) { continue; } UUID systemId = systemIds.get(0); UUID exchangeId = UUID.randomUUID(); List<UUID> batchIdsCreated = new ArrayList<>(); String bodyJson = JsonSerializer.serialize(new ArrayList<ExchangePayloadFile>()); String odsCode = service.getLocalId(); FhirResourceFiler filer = null; Exchange exchange = null; List<UUID> patientIds = new ArrayList<>(); String sql = "SELECT patient_id FROM patient_search WHERE service_id = ? AND dt_deleted IS NOT NULL"; PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, service.getId().toString()); ResultSet rs = ps.executeQuery(); while (rs.next()) { String id = rs.getString(1); patientIds.add(UUID.fromString(id)); } ps.close(); if (patientIds.isEmpty()) { LOG.debug("No deleted patients found"); continue; } LOG.debug("Found " + patientIds.size() + " deleted patients"); for (UUID patientId: patientIds) { List<ResourceWrapper> wrappers = resourceDal.getResourcesByPatient(service.getId(), patientId); LOG.debug("Doing patient " + patientId + " with " + wrappers.size() + " resources"); for (ResourceWrapper wrapper: wrappers) { if (testMode) { LOG.debug("Would delete resource " + wrapper.getResourceType() + " " + wrapper.getResourceId()); } else { if (exchange == null) { filer = new FhirResourceFiler(exchangeId, service.getId(), systemId, new TransformError(), batchIdsCreated); exchange = new Exchange(); exchange.setId(exchangeId); exchange.setBody(bodyJson); exchange.setTimestamp(new Date()); exchange.setHeaders(new HashMap<>()); exchange.setHeaderAsUuid(HeaderKeys.SenderServiceUuid, service.getId()); exchange.setHeader(HeaderKeys.ProtocolIds, ""); //just set to non-null value, so postToExchange(..) can safely recalculate exchange.setHeader(HeaderKeys.SenderLocalIdentifier, odsCode); exchange.setHeaderAsUuid(HeaderKeys.SenderSystemUuid, systemId); exchange.setHeader(HeaderKeys.SourceSystem, MessageFormat.TPP_CSV); exchange.setServiceId(service.getId()); exchange.setSystemId(systemId); AuditWriter.writeExchange(exchange); AuditWriter.writeExchangeEvent(exchange, "Manually created to delete resources for deleted patients"); } //delete resource Resource resource = wrapper.getResource(); filer.deletePatientResource(null, false, new GenericBuilder(resource)); } } } if (!testMode) { if (exchange != null) { //close down filer filer.waitToFinish(); //set multicast header String batchIdString = ObjectMapperPool.getInstance().writeValueAsString(batchIdsCreated.toArray()); exchange.setHeader(HeaderKeys.BatchIdsJson, batchIdString); //post to Rabbit protocol queue List<UUID> exchangeIds = new ArrayList<>(); exchangeIds.add(exchange.getId()); QueueHelper.postToExchange(exchangeIds, "EdsProtocol", null, true, null); //set this after posting to rabbit so we can't re-queue it later exchange.setHeaderAsBoolean(HeaderKeys.AllowQueueing, new Boolean(false)); //don't allow this to be re-queued AuditWriter.writeExchange(exchange); } } } conn.close(); LOG.debug("Finished Deleting Resources for Deleted Patients using " + odsCodeRegex); } catch (Throwable t) { LOG.error("", t); } } /** * checks to make sure that every exchange has been properly through the inbound transform without * being skipped, failing or being filtered on specific files */ public static void findTppServicesNeedReprocessing(String odsCodeRegex) { LOG.debug("Finding TPP Services that Need Re-processing for " + odsCodeRegex); try { ServiceDalI serviceDal = DalProvider.factoryServiceDal(); List<Service> services = serviceDal.getAll(); for (Service service: services) { Map<String, String> tags = service.getTags(); if (tags == null || !tags.containsKey("TPP")) { continue; } if (shouldSkipService(service, odsCodeRegex)) { continue; } List<UUID> systemIds = SystemHelper.getSystemIdsForService(service); if (systemIds.size() != 1) { throw new Exception("Wrong number of system IDs for " + service); } UUID systemId = systemIds.get(0); String publisherStatus = null; for (ServiceInterfaceEndpoint serviceInterface: service.getEndpointsList()) { if (serviceInterface.getSystemUuid().equals(systemId)) { publisherStatus = serviceInterface.getEndpoint(); } } if (publisherStatus == null) { throw new Exception("Failed to find publisher status for service " + service); } LOG.debug(""); LOG.debug("CHECKING " + service + " " + publisherStatus + " >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); if (publisherStatus.equals(ServiceInterfaceEndpoint.STATUS_AUTO_FAIL)) { LOG.debug("Skipping service because set to auto-fail"); continue; } //check if in the bulks skipped table and are waiting to be re-queued Connection connection = ConnectionManager.getEdsConnection(); String sql = "select 1 from audit.tpp_skipped_srcode where service_id = ? and (queued = false or queued is null)"; PreparedStatement ps = connection.prepareStatement(sql); ps.setString(1, service.getId().toString()); ResultSet rs = ps.executeQuery(); boolean needsRequeueing = rs.next(); ps.close(); connection.close(); if (needsRequeueing) { LOG.debug(">>>>> NEEDS REQUEUEING FOR SKIPPED SRCode BULK"); } ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); List<Exchange> exchanges = exchangeDal.getExchangesByService(service.getId(), systemId, Integer.MAX_VALUE); for (int i=exchanges.size()-1; i>=0; i Exchange exchange = exchanges.get(i); //if can't be queued, ignore it Boolean allowQueueing = exchange.getHeaderAsBoolean(HeaderKeys.AllowQueueing); if (allowQueueing != null && !allowQueueing.booleanValue()) { continue; } //LOG.debug("Doing exchange " + exchange.getId() + " from " + exchange.getHeaderAsDate(HeaderKeys.DataDate)); List<ExchangeTransformAudit> audits = exchangeDal.getAllExchangeTransformAudits(service.getId(), systemId, exchange.getId()); List<ExchangeEvent> events = exchangeDal.getExchangeEvents(exchange.getId()); //was it transformed OK before it was re-queued with filtering? boolean transformedWithoutFiltering = false; List<String> logging = new ArrayList<>(); for (ExchangeTransformAudit audit: audits) { //transformed OK boolean transformedOk = audit.getEnded() != null && audit.getErrorXml() == null; if (!transformedOk) { logging.add("Audit " + audit.getStarted() + " didn't complete OK, so not counting"); continue; } //if transformed OK see whether filtering was applied BEFORE Date dtTransformStart = audit.getStarted(); logging.add("Audit completed OK from " + audit.getStarted()); //find immediately proceeding event showing loading into inbound queue ExchangeEvent previousLoadingEvent = null; for (int j=events.size()-1; j>=0; j ExchangeEvent event = events.get(j); Date dtEvent = event.getTimestamp(); if (dtEvent.after(dtTransformStart)) { logging.add("Ignoring event from " + dtEvent + " as AFTER transform"); continue; } String eventDesc = event.getEventDesc(); if (eventDesc.startsWith("Manually pushed into edsInbound exchange") || eventDesc.startsWith("Manually pushed into EdsInbound exchange")) { previousLoadingEvent = event; logging.add("Proceeding event from " + dtEvent + " [" + eventDesc + "]"); break; } else { logging.add("Ignoring event from " + dtEvent + " as doesn't match text [" + eventDesc + "]"); } } if (previousLoadingEvent == null) { //if transformed OK and no previous manual loading event, then it was OK transformedWithoutFiltering = true; //LOG.debug("Audit from " + audit.getStarted() + " was transformed OK without being manually loaded = OK"); } else { //if transformed OK and was manually loaded into queue, then see if event applied filtering or not String eventDesc = previousLoadingEvent.getEventDesc(); if (!eventDesc.contains("Filtered on file types")) { transformedWithoutFiltering = true; //LOG.debug("Audit from " + audit.getStarted() + " was transformed OK and was manually loaded without filtering = OK"); } else { logging.add("Event desc filters on file types, so DIDN'T transform OK"); } } } if (!transformedWithoutFiltering) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); LOG.error("" + service + " -> exchange " + exchange.getId() + " from " + sdf.format(exchange.getHeaderAsDate(HeaderKeys.DataDate))); /*for (String line: logging) { LOG.error(" " + line); }*/ } } } LOG.debug("Finished Finding Emis Services that Need Re-processing"); } catch (Throwable t) { LOG.error("", t); } } public static void testSubscriberConfigs() { LOG.debug("Testing Subscriber Configs"); try { Map<String, String> configs = ConfigManager.getConfigurations("db_subscriber"); LOG.debug("Found " + configs.size() + " configs"); for (String configId: configs.keySet()) { String configData = configs.get(configId); LOG.debug("Doing >>>>>>>>>>>>>>>> " + configId); LOG.debug(configData); try { SubscriberConfig configRecord = SubscriberConfig.readFromConfig(configId); LOG.debug("Parsed OK"); LOG.debug("" + configRecord); } catch (Exception ex) { LOG.error("Failed to parse"); LOG.error("", ex); } } LOG.debug("Finished Testing Subscriber Configs"); } catch (Throwable t) { LOG.error("", t); } } public static void validateProtocolCohorts() { LOG.debug("Validating Protocol Cohorts"); try { DefinitionItemType itemType = DefinitionItemType.Protocol; Iterable<ActiveItem> activeItems = null; List<Item> items = new ArrayList(); LibraryDalI repository = DalProvider.factoryLibraryDal(); activeItems = repository.getActiveItemByTypeId(itemType.getValue(), false); for (ActiveItem activeItem: activeItems) { Item item = repository.getItemByKey(activeItem.getItemId(), activeItem.getAuditId()); if (!item.isDeleted()) { items.add(item); } } //LOG.trace("Found " + items.size() + " protocols to check for service " + serviceId + " and system " + systemId); for (int i = 0; i < items.size(); i++) { Item item = items.get(i); String xml = item.getXmlContent(); LibraryItem libraryItem = XmlSerializer.deserializeFromString(LibraryItem.class, xml, null); Protocol protocol = libraryItem.getProtocol(); LOG.debug(""); LOG.debug(""); LOG.debug(">>>>>>>>>>>>>>>>> " + libraryItem.getName()); try { String cohort = protocol.getCohort(); if (Strings.isNullOrEmpty(cohort)) { LOG.debug("Protocol doesn't have cohort explicitly set, so assuming ALL PATIENTS"); } else { if (cohort.equals("All Patients")) { LOG.debug("Cohort = all patients"); } else if (cohort.equals("Explicit Patients")) { LOG.debug("Cohort = explicit patients"); } else if (cohort.startsWith("Defining Services")) { LOG.debug("Cohort = defining services"); Set<String> odsCodes = RunDataDistributionProtocols.getOdsCodesForServiceDefinedProtocol(protocol); LOG.debug("Cohort is " + odsCodes.size() + " size"); List<String> list = new ArrayList<>(odsCodes); list.sort(((o1, o2) -> o1.compareToIgnoreCase(o2))); Map<String, List<String>> hmParents = new HashMap<>(); for (String odsCode: list) { OdsOrganisation org = OdsWebService.lookupOrganisationViaRest(odsCode); if (org == null) { LOG.error(odsCode + " -> Failed to find ODS record"); } else { if (!org.isActive()) { LOG.error(odsCode + " -> ODS record not active"); } Map<String, String> parents = org.getParents(); for (String parentOdsCode: parents.keySet()) { List<String> l = hmParents.get(parentOdsCode); if (l == null) { l = new ArrayList<>(); hmParents.put(parentOdsCode, l); } l.add(odsCode); } } } LOG.debug("Found " + hmParents.size() + " parents"); for (String parentOdsCode: hmParents.keySet()) { List<String> childOdsCodes = hmParents.get(parentOdsCode); OdsOrganisation parentOrg = OdsWebService.lookupOrganisationViaRest(parentOdsCode); if (parentOrg == null) { LOG.error(parentOdsCode + " -> Failed to find parent ODS record"); } else { LOG.error(parentOdsCode + " -> " + parentOrg.getOrganisationName()); } LOG.debug(" Has " + childOdsCodes.size() + " children"); LOG.debug(" " + String.join(", " + childOdsCodes)); } } else { throw new Exception("Unknown cohort type [" + cohort + "]"); } } } catch (Exception ex) { LOG.error("", ex); } } LOG.debug("Finished Validating Protocol Cohorts"); } catch (Throwable t) { LOG.error("", t); } } public static void countVaccinationCodes(String sinceDateStr, String ccgOdsCodes) { LOG.debug("Counting VaccinationCodes at " + ccgOdsCodes); try { Date cutoff = new SimpleDateFormat("yyyy-MM-dd").parse(sinceDateStr); LOG.debug("Counting vaccinations since " + sinceDateStr); ServiceDalI serviceDal = DalProvider.factoryServiceDal(); List<Service> services = serviceDal.getAll(); Map<String, AtomicInteger> emisResults = new HashMap<>(); Map<String, AtomicInteger> tppResults = new HashMap<>(); Map<String, AtomicInteger> visionResults = new HashMap<>(); for (Service service: services) { if (shouldSkipService(service, ccgOdsCodes)) { continue; } LOG.debug("Doing " + service); Map<String, AtomicInteger> hmResults = null; if (service.getTags() == null) { LOG.warn("No tags set"); continue; } else if (service.getTags().containsKey("TPP")) { hmResults = tppResults; } else if (service.getTags().containsKey("EMIS")) { hmResults = emisResults; } else if (service.getTags().containsKey("Vision")) { hmResults = visionResults; } else { LOG.error("Unknown system type"); continue; //throw new Exception(); } Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); cal.add(Calendar.YEAR, -20); Date d = cal.getTime(); //String dateStr = new SimpleDateFormat("yyyy-MM-dd").format(d); List<UUID> patientIds = new ArrayList<>(); String sql = "SELECT patient_id FROM patient_search WHERE dt_deleted IS NULL AND date_of_birth > ? AND service_id = ?"; Connection connection = ConnectionManager.getEdsConnection(); PreparedStatement ps = connection.prepareStatement(sql); ps.setTimestamp(1, new java.sql.Timestamp(d.getTime())); ps.setString(2, service.getId().toString()); ResultSet rs = ps.executeQuery(); while (rs.next()) { String s = rs.getString(1); patientIds.add(UUID.fromString(s)); } ps.close(); connection.close(); LOG.debug("Found " + patientIds.size() + " patient IDs"); int done = 0; for (UUID patientId: patientIds) { ResourceDalI resourceDal = DalProvider.factoryResourceDal(); List<ResourceWrapper> resources = resourceDal.getResourcesByPatient(service.getId(), patientId, ResourceType.Immunization.toString()); for (ResourceWrapper resourceWrapper: resources) { Immunization imm = (Immunization)resourceWrapper.getResource(); if (!imm.hasDateElement()) { continue; } DateTimeType dtVal = imm.getDateElement(); Date dt = dtVal.getValue(); if (dt.before(cutoff)) { continue; } if (imm.hasVaccineCode()) { CodeableConcept cc = imm.getVaccineCode(); ObservationCodeHelper codes = ObservationCodeHelper.extractCodeFields(cc); Long snomedConceptId = codes.getSnomedConceptId(); String originalCode = codes.getOriginalCode(); String originalTerm = codes.getOriginalTerm(); //there are Vision immunizations with a Snomed code only if (originalCode == null) { originalCode = "NULL"; } if (originalTerm == null) { originalTerm = "NULL"; } String snomedConceptIdStr; if (snomedConceptId != null) { snomedConceptIdStr = "" + snomedConceptId; } else { snomedConceptIdStr = "NULL"; } String cacheKey = originalCode + "¬" + originalTerm + "¬" + snomedConceptIdStr; AtomicInteger count = hmResults.get(cacheKey); if (count == null) { count = new AtomicInteger(0); hmResults.put(cacheKey, count); } count.incrementAndGet(); } } done ++; if (done % 100 == 0) { LOG.debug("Done " + done); } } LOG.debug("Finished " + done); } LOG.debug("Writing results"); List<String> fileNames = new ArrayList<>(); fileNames.add("Immunisation_Codes_TPP.csv"); fileNames.add("Immunisation_Codes_Emis.csv"); fileNames.add("Immunisation_Codes_Vision.csv"); for (String fileName: fileNames) { Map<String, AtomicInteger> hmResults = null; String localScheme = null; if (fileName.equals("Immunisation_Codes_TPP.csv")) { hmResults = tppResults; localScheme = "TPP local"; } else if (fileName.equals("Immunisation_Codes_Emis.csv")) { hmResults = emisResults; localScheme = "EMIS local"; } else if (fileName.equals("Immunisation_Codes_Vision.csv")) { hmResults = visionResults; localScheme = "Vision local"; } else { throw new Exception("Unknown file name " + fileName); } //find max count Map<Integer, List<String>> hmByCount = new HashMap<>(); int max = 0; for (String key: hmResults.keySet()) { AtomicInteger a = hmResults.get(key); int count = a.get(); List<String> l = hmByCount.get(new Integer(count)); if (l == null) { l = new ArrayList<>(); hmByCount.put(new Integer(count), l); } l.add(key); max = Math.max(max, count); } File dstFile = new File(fileName); FileOutputStream fos = new FileOutputStream(dstFile); OutputStreamWriter osw = new OutputStreamWriter(fos); BufferedWriter bufferedWriter = new BufferedWriter(osw); CSVFormat format = EmisCsvToFhirTransformer.CSV_FORMAT .withHeader("Code Scheme", "Code", "Term", "Mapped Snomed Concept", "Mapped Snomed Term", "Count" ); CSVPrinter printer = new CSVPrinter(bufferedWriter, format); for (int i=max; i>=0; i List<String> l = hmByCount.get(new Integer(i)); if (l == null) { continue; } for (String key: l) { String[] toks = key.split("¬"); String originalCode = toks[0]; String originalTerm = "NULL"; String snomedConceptId = "NULL"; String snomedTerm = "NULL"; if (toks.length > 1) { originalTerm = toks[1]; } if (toks.length > 2) { snomedConceptId = toks[2]; SnomedCode snomedCode = TerminologyService.lookupSnomedFromConceptId(snomedConceptId); if (snomedCode != null) { snomedTerm = snomedCode.getTerm(); } } String codeScheme = null; if (originalCode.startsWith("CTV3_")) { originalCode = originalCode.substring(5); if (originalCode.startsWith("Y")) { codeScheme = localScheme; } else { codeScheme = "CTV3"; } } else { Read2Code dbCode = TerminologyService.lookupRead2Code(originalCode); if (dbCode == null) { codeScheme = localScheme; } else { codeScheme = "Read2"; } } printer.printRecord(codeScheme, originalCode, originalTerm, snomedConceptId, snomedTerm, new Integer(i)); //String cacheKey = originalCode + "|" + originalTerm + "|" + snomedConceptId; } } printer.close(); } LOG.debug("Finished Counting VaccinationCodes at " + ccgOdsCodes); } catch (Throwable t) { LOG.error("", t); } } }
package org.endeavourhealth.queuereader; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.base.Strings; import com.google.common.hash.HashCode; import com.google.common.hash.HashFunction; import com.google.common.hash.Hasher; import com.google.common.hash.Hashing; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVPrinter; import org.apache.commons.csv.CSVRecord; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.endeavourhealth.common.cache.ObjectMapperPool; import org.endeavourhealth.common.fhir.*; import org.endeavourhealth.common.utility.FileHelper; import org.endeavourhealth.common.utility.JsonSerializer; import org.endeavourhealth.common.utility.ThreadPool; import org.endeavourhealth.core.application.ApplicationHeartbeatHelper; import org.endeavourhealth.core.configuration.PostMessageToExchangeConfig; import org.endeavourhealth.core.csv.CsvHelper; import org.endeavourhealth.core.database.dal.DalProvider; import org.endeavourhealth.core.database.dal.admin.LibraryRepositoryHelper; import org.endeavourhealth.core.database.dal.admin.ServiceDalI; import org.endeavourhealth.core.database.dal.admin.SystemHelper; import org.endeavourhealth.core.database.dal.admin.models.Service; import org.endeavourhealth.core.database.dal.audit.ExchangeBatchDalI; import org.endeavourhealth.core.database.dal.audit.ExchangeDalI; import org.endeavourhealth.core.database.dal.audit.models.*; import org.endeavourhealth.core.database.dal.eds.PatientSearchDalI; import org.endeavourhealth.core.database.dal.ehr.ResourceDalI; import org.endeavourhealth.core.database.dal.ehr.models.ResourceWrapper; import org.endeavourhealth.core.database.dal.subscriberTransform.SubscriberInstanceMappingDalI; import org.endeavourhealth.core.database.dal.subscriberTransform.SubscriberResourceMappingDalI; import org.endeavourhealth.core.database.dal.subscriberTransform.models.SubscriberId; import org.endeavourhealth.core.database.dal.usermanager.caching.DataSharingAgreementCache; import org.endeavourhealth.core.database.dal.usermanager.caching.OrganisationCache; import org.endeavourhealth.core.database.dal.usermanager.caching.ProjectCache; import org.endeavourhealth.core.database.rdbms.ConnectionManager; import org.endeavourhealth.core.database.rdbms.datasharingmanager.models.DataSharingAgreementEntity; import org.endeavourhealth.core.database.rdbms.datasharingmanager.models.ProjectEntity; import org.endeavourhealth.core.exceptions.TransformException; import org.endeavourhealth.core.fhirStorage.FhirResourceHelper; import org.endeavourhealth.core.fhirStorage.FhirSerializationHelper; import org.endeavourhealth.core.fhirStorage.ServiceInterfaceEndpoint; import org.endeavourhealth.core.messaging.pipeline.PipelineException; import org.endeavourhealth.core.messaging.pipeline.components.DetermineRelevantProtocolIds; import org.endeavourhealth.core.messaging.pipeline.components.MessageTransformOutbound; import org.endeavourhealth.core.messaging.pipeline.components.PostMessageToExchange; import org.endeavourhealth.core.queueing.QueueHelper; import org.endeavourhealth.core.xml.QueryDocument.*; import org.endeavourhealth.core.xml.TransformErrorSerializer; import org.endeavourhealth.core.xml.transformError.TransformError; import org.endeavourhealth.im.client.IMClient; import org.endeavourhealth.subscriber.filer.EnterpriseFiler; import org.endeavourhealth.subscriber.filer.SubscriberFiler; import org.endeavourhealth.transform.common.*; import org.endeavourhealth.transform.common.resourceBuilders.EpisodeOfCareBuilder; import org.endeavourhealth.transform.emis.EmisCsvToFhirTransformer; import org.endeavourhealth.transform.enterprise.EnterpriseTransformHelper; import org.endeavourhealth.transform.enterprise.transforms.OrganisationEnterpriseTransformer; import org.endeavourhealth.transform.fhirhl7v2.FhirHl7v2Filer; import org.endeavourhealth.transform.fhirhl7v2.transforms.EncounterTransformer; import org.endeavourhealth.transform.subscriber.IMConstant; import org.endeavourhealth.transform.subscriber.IMHelper; import org.endeavourhealth.transform.subscriber.SubscriberTransformHelper; import org.endeavourhealth.transform.subscriber.targetTables.OutputContainer; import org.endeavourhealth.transform.subscriber.targetTables.SubscriberTableId; import org.endeavourhealth.transform.subscriber.transforms.OrganisationTransformer; import org.endeavourhealth.transform.ui.helpers.BulkHelper; import org.hl7.fhir.instance.model.*; import org.hl7.fhir.instance.model.Resource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.lang.System; import java.net.URI; import java.net.URL; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.security.CodeSource; import java.security.ProtectionDomain; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.text.SimpleDateFormat; import java.util.*; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Pattern; import java.util.stream.Collectors; import static org.endeavourhealth.core.xml.QueryDocument.ServiceContractType.PUBLISHER; public abstract class SpecialRoutines { private static final Logger LOG = LoggerFactory.getLogger(SpecialRoutines.class); public static void findOutOfOrderTppServices() { LOG.info("Finding Out of Order TPP Services"); try { ServiceDalI serviceDal = DalProvider.factoryServiceDal(); List<Service> services = serviceDal.getAll(); for (Service service: services) { if (service.getTags() == null && !service.getTags().containsKey("TPP")) { continue; } LOG.info("Checking " + service); List<UUID> systemIds = SystemHelper.getSystemIdsForService(service); for (UUID systemId: systemIds) { ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); List<Exchange> exchanges = exchangeDal.getExchangesByService(service.getId(), systemId, Integer.MAX_VALUE); LOG.debug("Found " + exchanges.size() + " exchanges"); //exchanges are in insert date order, most recent first Date previousDate = null; for (int i=0; i<exchanges.size(); i++) { Exchange exchange = exchanges.get(i); Date dataDate = exchange.getHeaderAsDate(HeaderKeys.DataDate); if (dataDate == null) { throw new Exception("No data date for exchange " + exchange.getId()); } if (previousDate == null || dataDate.before(previousDate)) { previousDate = dataDate; } else { LOG.warn("Exchange " + exchange.getId() + " from " + exchange.getTimestamp() + " is out of order"); } } } } //find TPP services //get exchanges //work from MOST recent //see if exchanges have data date out of order //how to fix?... //If queued up - //If already processed - move exchange and re-queued from AFTER bulk //If not processed & not queued - just move exchange? LOG.info("Finished Finding Out of Order TPP Services"); } catch (Throwable t) { LOG.error("", t); } } *//*String rootDir = null; }*//* /*public static void populateExchangeFileSizes(String odsCodeRegex) { LOG.info("Populating Exchange File Sizes for " + odsCodeRegex); try { String sharedStoragePath = TransformConfig.instance().getSharedStoragePath(); ServiceDalI serviceDal = DalProvider.factoryServiceDal(); List<Service> services = serviceDal.getAll(); for (Service service: services) { //check regex if (shouldSkipService(service, odsCodeRegex)) { continue; } LOG.debug("Doing " + service); List<UUID> systemIds = SystemHelper.getSystemIdsForService(service); for (UUID systemId: systemIds) { //skip ADT feeds because their JSON isn't the same if (systemId.equals(UUID.fromString("d874c58c-91fd-41bb-993e-b1b8b22038b2"))//live || systemId.equals(UUID.fromString("68096181-9e5d-4cca-821f-a9ecaa0ebc50"))) { //dev continue; } ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); List<Exchange> exchanges = exchangeDal.getExchangesByService(service.getId(), systemId, Integer.MAX_VALUE); LOG.debug("Found " + exchanges.size() + " exchanges"); int done = 0; for (Exchange exchange: exchanges) { boolean saveExchange = false; //make sure the individual file sizes are in the JSON body try { String body = exchange.getBody(); List<ExchangePayloadFile> files = ExchangeHelper.parseExchangeBody(body, false); for (ExchangePayloadFile file: files) { if (file.getSize() != null) { continue; } String path = file.getPath(); path = FilenameUtils.concat(sharedStoragePath, path); String name = FilenameUtils.getName(path); String dir = new File(path).getParent(); List<FileInfo> s3Listing = FileHelper.listFilesInSharedStorageWithInfo(dir); for (FileInfo s3Info : s3Listing) { String s3Path = s3Info.getFilePath(); long size = s3Info.getSize(); String s3Name = FilenameUtils.getName(s3Path); if (s3Name.equals(name)) { file.setSize(new Long(size)); //write back to JSON String newJson = JsonSerializer.serialize(files); exchange.setBody(newJson); saveExchange = true; break; } } } Map<String, ExchangePayloadFile> hmFilesByName = new HashMap<>(); String body = exchange.getBody(); List<ExchangePayloadFile> files = ExchangeHelper.parseExchangeBody(body, false); for (ExchangePayloadFile file: files) { if (file.getSize() != null) { continue; } String path = file.getPath(); path = FilenameUtils.concat(sharedStoragePath, path); String name = FilenameUtils.getName(path); hmFilesByName.put(name, file); String dir = new File(path).getParent(); if (rootDir == null || rootDir.equals(dir)) { rootDir = dir; } else { throw new Exception("Files not in same directory [" + rootDir + "] vs [" + dir + "]"); } } if (!hmFilesByName.isEmpty()) { List<FileInfo> s3Listing = FileHelper.listFilesInSharedStorageWithInfo(rootDir); for (FileInfo s3Info : s3Listing) { String path = s3Info.getFilePath(); long size = s3Info.getSize(); String name = FilenameUtils.getName(path); ExchangePayloadFile file = hmFilesByName.get(name); if (file == null) { LOG.debug("No info for file " + path + " found"); continue; //throw new Exception(); } file.setSize(new Long(size)); } //write back to JSON String newJson = JsonSerializer.serialize(files); exchange.setBody(newJson); saveExchange = true; } catch (Throwable t) { throw new Exception("Failed on exchange " + exchange.getId(), t); } //and make sure the total size is in the headers Long totalSize = exchange.getHeaderAsLong(HeaderKeys.TotalFileSize); if (totalSize == null) { long size = 0; String body = exchange.getBody(); List<ExchangePayloadFile> files = ExchangeHelper.parseExchangeBody(body, false); for (ExchangePayloadFile file: files) { if (file.getSize() == null) { throw new Exception("No file size for " + file.getPath() + " in exchange " + exchange.getId()); } size += file.getSize().longValue(); } exchange.setHeaderAsLong(HeaderKeys.TotalFileSize, new Long(size)); saveExchange = true; } //save to DB if (saveExchange) { AuditWriter.writeExchange(exchange); } done ++; if (done % 100 == 0) { LOG.debug("Done " + done); } } LOG.debug("Finished at " + done); } } LOG.info("Finished Populating Exchange File Sizes for " + odsCodeRegex); } catch (Throwable t) { LOG.error("", t); } }*/ public static boolean shouldSkipService(Service service, String odsCodeRegex) { if (odsCodeRegex == null) { return false; } String odsCode = service.getLocalId(); if (Strings.isNullOrEmpty(odsCode) || !Pattern.matches(odsCodeRegex, odsCode)) { LOG.debug("Skipping " + service + " due to regex"); return true; } return false; } public static void getResourceHistory(String serviceIdStr, String resourceTypeStr, String resourceIdStr) { LOG.debug("Getting resource history for " + resourceTypeStr + " " + resourceIdStr + " for service " + serviceIdStr); try { LOG.debug(""); LOG.debug(""); UUID serviceId = UUID.fromString(serviceIdStr); UUID resourceId = UUID.fromString(resourceIdStr); ResourceType resourceType = ResourceType.valueOf(resourceTypeStr); ResourceDalI resourceDal = DalProvider.factoryResourceDal(); ResourceWrapper retrieved = resourceDal.getCurrentVersion(serviceId, resourceType.toString(), resourceId); LOG.debug("Retrieved current>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); LOG.debug(""); LOG.debug("" + retrieved); LOG.debug(""); LOG.debug(""); List<ResourceWrapper> history = resourceDal.getResourceHistory(serviceId, resourceType.toString(), resourceId); LOG.debug("Retrieved history " + history.size() + ">>>>>>>>>>>>>>>>>>>>>>>>>>>>"); LOG.debug(""); for (ResourceWrapper h: history) { LOG.debug("" + h); LOG.debug(""); } } catch (Throwable t) { LOG.error("", t); } } /** * validates NHS numbers from a file, outputting valid and invalid ones to separate output files * if the addComma parameter is true it'll add a comma to the end of each line, so it's ready * for sending to the National Data Opt-out service */ public static void validateNhsNumbers(String filePath, boolean addCommas) { LOG.info("Validating NHS Numbers in " + filePath); LOG.info("Adding commas = " + addCommas); try { File f = new File(filePath); if (!f.exists()) { throw new Exception("File " + f + " doesn't exist"); } List<String> lines = FileUtils.readLines(f); List<String> valid = new ArrayList<>(); List<String> invalid = new ArrayList<>(); for (String line: lines) { if (line.length() > 10) { String c = line.substring(10); if (c.equals(",")) { line = line.substring(0, 10); } else { invalid.add(line); continue; } } if (line.length() < 10) { invalid.add(line); continue; } Boolean isValid = IdentifierHelper.isValidNhsNumber(line); if (isValid == null) { continue; } if (!isValid.booleanValue()) { invalid.add(line); continue; } //if we make it here, we're valid if (addCommas) { line += ","; } valid.add(line); } File dir = f.getParentFile(); String fileName = f.getName(); File fValid = new File(dir, "VALID_" + fileName); FileUtils.writeLines(fValid, valid); LOG.info("" + valid.size() + " NHS numbers written to " + fValid); File fInvalid = new File(dir, "INVALID_" + fileName); FileUtils.writeLines(fInvalid, invalid); LOG.info("" + invalid.size() + " NHS numbers written to " + fInvalid); } catch (Throwable t) { LOG.error("", t); } } public static void getJarDetails() { LOG.debug("Get Jar Details OLD"); try { Class cls = SpecialRoutines.class; LOG.debug("Cls = " + cls); ProtectionDomain domain = cls.getProtectionDomain(); LOG.debug("Domain = " + domain); CodeSource source = domain.getCodeSource(); LOG.debug("Source = " + source); URL loc = source.getLocation(); LOG.debug("Location = " + loc); URI uri = loc.toURI(); LOG.debug("URI = " + uri); File f = new File(uri); LOG.debug("File = " + f); Date d = new Date(f.lastModified()); LOG.debug("Last Modified = " + d); } catch (Throwable t) { LOG.error("", t); } LOG.debug(""); LOG.debug(""); LOG.debug("Get Jar Details THIS class"); try { Class cls = SpecialRoutines.class; ApplicationHeartbeatHelper.findJarDateTime(cls, true); } catch (Throwable t) { LOG.error("", t); } LOG.debug(""); LOG.debug(""); LOG.debug("Get Jar Details CORE class"); try { Class cls = ApplicationHeartbeatHelper.class; ApplicationHeartbeatHelper.findJarDateTime(cls, true); } catch (Throwable t) { LOG.error("", t); } } public static void breakUpAdminBatches(String odsCodeRegex) { try { LOG.debug("Breaking up admin batches for " + odsCodeRegex); ServiceDalI serviceDal = DalProvider.factoryServiceDal(); List<Service> services = serviceDal.getAll(); for (Service service: services) { //check regex if (shouldSkipService(service, odsCodeRegex)) { continue; } String publisherConfig = service.getPublisherConfigName(); if (Strings.isNullOrEmpty(publisherConfig)) { continue; } Connection ehrConnection = ConnectionManager.getEhrNonPooledConnection(service.getId()); Connection auditConnection = ConnectionManager.getAuditNonPooledConnection(); int maxSize = TransformConfig.instance().getAdminBatchMaxSize(); LOG.debug("Doing " + service); List<UUID> systemIds = SystemHelper.getSystemIdsForService(service); for (UUID systemId: systemIds) { ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); ExchangeBatchDalI exchangeBatchDal = DalProvider.factoryExchangeBatchDal(); List<Exchange> exchanges = exchangeDal.getExchangesByService(service.getId(), systemId, Integer.MAX_VALUE); LOG.debug("Found " + exchanges.size() + " exchanges"); int done = 0; int fixed = 0; for (Exchange exchange: exchanges) { List<ExchangeBatch> batches = exchangeBatchDal.retrieveForExchangeId(exchange.getId()); for (ExchangeBatch batch: batches) { if (batch.getEdsPatientId() != null) { continue; } String sql = "SELECT COUNT(1) FROM resource_history WHERE exchange_batch_id = ?"; PreparedStatement psSelectCount = ehrConnection.prepareStatement(sql); psSelectCount.setString(1, batch.getBatchId().toString()); ResultSet rs = psSelectCount.executeQuery(); rs.next(); int count = rs.getInt(1); psSelectCount.close(); if (count > maxSize) { LOG.debug("Fixing batch " + batch.getBatchId() + " for exchange " + exchange.getId() + " with " + count + " resources"); //work backwards int numBlocks = count / maxSize; if (count % maxSize > 0) { numBlocks ++; } //exchange_event - to audit this PreparedStatement psExchangeEvent = null; sql = "INSERT INTO exchange_event" + " VALUES (?, ?, ?, ?)"; psExchangeEvent = auditConnection.prepareStatement(sql); psExchangeEvent.setString(1, UUID.randomUUID().toString()); psExchangeEvent.setString(2, exchange.getId().toString()); psExchangeEvent.setTimestamp(3, new java.sql.Timestamp(new Date().getTime())); psExchangeEvent.setString(4, "Split large admin batch of " + count + " resources into blocks of " + maxSize); psExchangeEvent.executeUpdate(); auditConnection.commit(); psExchangeEvent.close(); for (int blockNum=numBlocks; blockNum>1; blockNum--) { //skip block one as we want to leave it alone UUID newId = UUID.randomUUID(); int rangeStart = (blockNum-1) * maxSize; LOG.debug("Updating " + batch.getBatchId() + " " + rangeStart + " to " + (rangeStart+maxSize) + " to batch ID " + newId); PreparedStatement psExchangeBatch = null; PreparedStatement psSendAudit = null; PreparedStatement psTransformAudit = null; //insert into exchange_batch table sql = "INSERT INTO exchange_batch" + " SELECT exchange_id, '" + newId.toString() + "', inserted_at, eds_patient_id" + " FROM exchange_batch" + " WHERE exchange_id = ? AND batch_id = ?"; psExchangeBatch = auditConnection.prepareStatement(sql); psExchangeBatch.setString(1, exchange.getId().toString()); psExchangeBatch.setString(2, batch.getBatchId().toString()); psExchangeBatch.executeUpdate(); //exchange_subscriber_send_audit sql = "INSERT INTO exchange_subscriber_send_audit" + " SELECT exchange_id, '" + newId.toString() + "', subscriber_config_name, inserted_at, error_xml, queued_message_id" + " FROM exchange_subscriber_send_audit" + " WHERE exchange_id = ? AND exchange_batch_id = ?"; psSendAudit = auditConnection.prepareStatement(sql); psSendAudit.setString(1, exchange.getId().toString()); psSendAudit.setString(2, batch.getBatchId().toString()); psSendAudit.executeUpdate(); //exchange_subscriber_transform_audit sql = "INSERT INTO exchange_subscriber_transform_audit" + " SELECT exchange_id, '" + newId.toString() + "', subscriber_config_name, started, ended, error_xml, number_resources_transformed, queued_message_id" + " FROM exchange_subscriber_transform_audit" + " WHERE exchange_id = ? AND exchange_batch_id = ?"; psTransformAudit = auditConnection.prepareStatement(sql); psTransformAudit.setString(1, exchange.getId().toString()); psTransformAudit.setString(2, batch.getBatchId().toString()); psTransformAudit.executeUpdate(); auditConnection.commit(); psExchangeBatch.close(); psSendAudit.close(); psTransformAudit.close(); //update history PreparedStatement psDropTempTable = null; PreparedStatement psCreateTempTable = null; PreparedStatement psIndexTempTable = null; PreparedStatement psUpdateHistory = null; sql = "DROP TEMPORARY TABLE IF EXISTS tmp.tmp_admin_batch_fix"; psDropTempTable = ehrConnection.prepareStatement(sql); psDropTempTable.executeUpdate(); sql = "CREATE TEMPORARY TABLE tmp.tmp_admin_batch_fix AS" + " SELECT resource_id, resource_type, created_at, version" + " FROM resource_history" + " WHERE exchange_batch_id = ?" + " ORDER BY resource_type, resource_id" + " LIMIT " + rangeStart + ", " + maxSize; psCreateTempTable = ehrConnection.prepareStatement(sql); psCreateTempTable.setString(1, batch.getBatchId().toString()); psCreateTempTable.executeUpdate(); sql = "CREATE INDEX ix ON tmp.tmp_admin_batch_fix (resource_id, resource_type, created_at, version)"; psIndexTempTable = ehrConnection.prepareStatement(sql); psIndexTempTable.executeUpdate(); sql = "UPDATE resource_history" + " INNER JOIN tmp.tmp_admin_batch_fix f" + " ON f.resource_id = resource_history.resource_id" + " AND f.resource_type = f.resource_type" + " AND f.created_at = f.created_at" + " AND f.version = f.version" + " SET resource_history.created_at = resource_history.created_at," + " resource_history.exchange_batch_id = ?"; psUpdateHistory = ehrConnection.prepareStatement(sql); psUpdateHistory.setString(1, newId.toString()); psUpdateHistory.executeUpdate(); ehrConnection.commit(); psDropTempTable.close(); psCreateTempTable.close(); psIndexTempTable.close(); psUpdateHistory.close(); } } } done ++; if (done % 100 == 0) { LOG.debug("Checked " + done + " exchanges and fixed " + fixed); } } LOG.debug("Checked " + done + " exchanges and fixed " + fixed); } ehrConnection.close(); auditConnection.close(); } LOG.debug("Finished breaking up admin batches for " + odsCodeRegex); } catch (Throwable t) { LOG.error("", t); } } public static void testInformationModel() { LOG.debug("Testing Information Model"); try { LOG.debug(" LOG.debug(" gets Snomed concept ID for legacy code and scheme"); String legacyCode = "C10.."; String legacyScheme = IMConstant.READ2; String mappedCoreCode = IMClient.getMappedCoreCodeForSchemeCode(legacyScheme, legacyCode); LOG.debug("For " + legacyScheme + " " + legacyCode + ", got Snomed Concept ID " + mappedCoreCode); legacyCode = "C10.."; legacyScheme = IMConstant.CTV3; mappedCoreCode = IMClient.getMappedCoreCodeForSchemeCode(legacyScheme, legacyCode); LOG.debug("For " + legacyScheme + " " + legacyCode + ", got Snomed Concept ID " + mappedCoreCode); legacyCode = "G33.."; legacyScheme = IMConstant.READ2; mappedCoreCode = IMClient.getMappedCoreCodeForSchemeCode(legacyScheme, legacyCode); LOG.debug("For " + legacyScheme + " " + legacyCode + ", got Snomed Concept ID " + mappedCoreCode); legacyCode = "G33.."; legacyScheme = IMConstant.CTV3; mappedCoreCode = IMClient.getMappedCoreCodeForSchemeCode(legacyScheme, legacyCode); LOG.debug("For " + legacyScheme + " " + legacyCode + ", got Snomed Concept ID " + mappedCoreCode); legacyCode = "687309281"; legacyScheme = IMConstant.BARTS_CERNER; mappedCoreCode = IMClient.getMappedCoreCodeForSchemeCode(legacyScheme, legacyCode); LOG.debug("For " + legacyScheme + " " + legacyCode + ", got Snomed Concept ID " + mappedCoreCode); LOG.debug(" LOG.debug(" gets NON-CORE DBID for legacy code and scheme"); legacyCode = "C10.."; legacyScheme = IMConstant.READ2; Integer dbid = IMClient.getConceptDbidForSchemeCode(legacyScheme, legacyCode); LOG.debug("For " + legacyScheme + " " + legacyCode + ", got non-core DBID " + dbid); legacyCode = "C10.."; legacyScheme = IMConstant.CTV3; dbid = IMClient.getConceptDbidForSchemeCode(legacyScheme, legacyCode); LOG.debug("For " + legacyScheme + " " + legacyCode + ", got non-core DBID " + dbid); legacyCode = "G33.."; legacyScheme = IMConstant.READ2; dbid = IMClient.getConceptDbidForSchemeCode(legacyScheme, legacyCode); LOG.debug("For " + legacyScheme + " " + legacyCode + ", got non-core DBID " + dbid); legacyCode = "G33.."; legacyScheme = IMConstant.CTV3; dbid = IMClient.getConceptDbidForSchemeCode(legacyScheme, legacyCode); LOG.debug("For " + legacyScheme + " " + legacyCode + ", got non-core DBID " + dbid); legacyCode = "687309281"; legacyScheme = IMConstant.BARTS_CERNER; dbid = IMClient.getConceptDbidForSchemeCode(legacyScheme, legacyCode); LOG.debug("For " + legacyScheme + " " + legacyCode + ", got non-core DBID " + dbid); LOG.debug(" LOG.debug(" gets CORE DBID for legacy code and scheme"); legacyCode = "C10.."; legacyScheme = IMConstant.READ2; dbid = IMClient.getMappedCoreConceptDbidForSchemeCode(legacyScheme, legacyCode); LOG.debug("For " + legacyScheme + " " + legacyCode + ", got core DBID " + dbid); legacyCode = "C10.."; legacyScheme = IMConstant.CTV3; dbid = IMClient.getMappedCoreConceptDbidForSchemeCode(legacyScheme, legacyCode); LOG.debug("For " + legacyScheme + " " + legacyCode + ", got core DBID " + dbid); legacyCode = "G33.."; legacyScheme = IMConstant.READ2; dbid = IMClient.getMappedCoreConceptDbidForSchemeCode(legacyScheme, legacyCode); LOG.debug("For " + legacyScheme + " " + legacyCode + ", got core DBID " + dbid); legacyCode = "G33.."; legacyScheme = IMConstant.CTV3; dbid = IMClient.getMappedCoreConceptDbidForSchemeCode(legacyScheme, legacyCode); LOG.debug("For " + legacyScheme + " " + legacyCode + ", got core DBID " + dbid); legacyCode = "687309281"; legacyScheme = IMConstant.BARTS_CERNER; dbid = IMClient.getMappedCoreConceptDbidForSchemeCode(legacyScheme, legacyCode); LOG.debug("For " + legacyScheme + " " + legacyCode + ", got core DBID " + dbid); LOG.debug(" LOG.debug(" get Snomed concept ID for CORE DBID"); Integer coreConceptDbId = new Integer(61367); String codeForConcept = IMClient.getCodeForConceptDbid(coreConceptDbId); LOG.debug("For core DBID " + coreConceptDbId + " got " + codeForConcept); coreConceptDbId = new Integer(123390); codeForConcept = IMClient.getCodeForConceptDbid(coreConceptDbId); LOG.debug("For core DBID " + coreConceptDbId + " got " + codeForConcept); coreConceptDbId = new Integer(1406482); codeForConcept = IMClient.getCodeForConceptDbid(coreConceptDbId); LOG.debug("For core DBID " + coreConceptDbId + " got " + codeForConcept); LOG.debug(" LOG.debug(" gets NON-CORE DBID for encounter type text"); String encounterScheme = IMConstant.ENCOUNTER_LEGACY; String encounterTerm = "Clinical"; Integer encounterConceptId = IMClient.getConceptDbidForTypeTerm(encounterScheme, encounterTerm); LOG.debug("For " + encounterScheme + " " + encounterTerm + " got " + encounterConceptId); encounterScheme = IMConstant.ENCOUNTER_LEGACY; encounterTerm = "Administrative"; encounterConceptId = IMClient.getConceptDbidForTypeTerm(encounterScheme, encounterTerm); LOG.debug("For " + encounterScheme + " " + encounterTerm + " got " + encounterConceptId); encounterScheme = IMConstant.ENCOUNTER_LEGACY; encounterTerm = "GP Surgery"; encounterConceptId = IMClient.getConceptDbidForTypeTerm(encounterScheme, encounterTerm); LOG.debug("For " + encounterScheme + " " + encounterTerm + " got " + encounterConceptId); LOG.debug(" LOG.debug(" gets CORE DBID for encounter type text"); encounterScheme = IMConstant.ENCOUNTER_LEGACY; encounterTerm = "Clinical"; encounterConceptId = IMClient.getMappedCoreConceptDbidForTypeTerm(encounterScheme, encounterTerm); LOG.debug("For " + encounterScheme + " " + encounterTerm + " got " + encounterConceptId); encounterScheme = IMConstant.ENCOUNTER_LEGACY; encounterTerm = "Administrative"; encounterConceptId = IMClient.getMappedCoreConceptDbidForTypeTerm(encounterScheme, encounterTerm); LOG.debug("For " + encounterScheme + " " + encounterTerm + " got " + encounterConceptId); encounterScheme = IMConstant.ENCOUNTER_LEGACY; encounterTerm = "GP Surgery"; encounterConceptId = IMClient.getMappedCoreConceptDbidForTypeTerm(encounterScheme, encounterTerm); LOG.debug("For " + encounterScheme + " " + encounterTerm + " got " + encounterConceptId); LOG.debug(" LOG.debug(" gets locally generated Cerner code for test code and result text"); String code = "687309281"; String scheme = IMConstant.BARTS_CERNER; String term = "SARS-CoV-2 RNA DETECTED"; String codeForTypeTerm = IMClient.getCodeForTypeTerm(scheme, code, term); LOG.debug("For " + scheme + " " + code + " [" + term + "] got " + codeForTypeTerm); code = "687309281"; scheme = IMConstant.BARTS_CERNER; term = "SARS-CoV-2 RNA NOT detected"; codeForTypeTerm = IMClient.getCodeForTypeTerm(scheme, code, term); LOG.debug("For " + scheme + " " + code + " [" + term + "] got " + codeForTypeTerm); LOG.debug(""); LOG.debug(""); LOG.debug(" String testCode = "687309281"; String positiveResult = "SARS-CoV-2 RNA DETECTED"; String negativeResult = "SARS-CoV-2 RNA NOT detected"; LOG.debug("Want to find Snomed concept 1240511000000106 from Cerner test code 687309281"); String testCodeSnomedConceptId = IMClient.getMappedCoreCodeForSchemeCode(IMConstant.BARTS_CERNER, testCode); LOG.debug("Got Snomed test code " + testCodeSnomedConceptId); LOG.debug(""); LOG.debug("Want to get locally generated Cerner code for test code and positive textual result"); String locallyGeneratedPositiveCode = IMClient.getCodeForTypeTerm(IMConstant.BARTS_CERNER, testCode, positiveResult); LOG.debug("Got locally generated code " + locallyGeneratedPositiveCode); LOG.debug(""); LOG.debug("Want to get locally generated Cerner code for test code and negative textual result"); String locallyGeneratedNegativeCode = IMClient.getCodeForTypeTerm(IMConstant.BARTS_CERNER, testCode, negativeResult); LOG.debug("Got locally generated code " + locallyGeneratedNegativeCode); LOG.debug(""); LOG.debug("Want to get Snomed concept ID for test code and positive result"); String snomedPositiveCode = IMClient.getMappedCoreCodeForSchemeCode(IMConstant.BARTS_CERNER, locallyGeneratedPositiveCode); LOG.debug("Got positive snomed code " + snomedPositiveCode); LOG.debug(""); LOG.debug("Want to get Snomed concept ID for test code and negative result"); String snomedNegativeCode = IMClient.getMappedCoreCodeForSchemeCode(IMConstant.BARTS_CERNER, locallyGeneratedNegativeCode); LOG.debug("Got negative snomed code " + snomedNegativeCode); LOG.debug(""); LOG.debug(""); LOG.debug(""); LOG.debug(" LOG.debug("Want to find Snomed concept 1240511000000106 from Cerner test code 687309281"); testCodeSnomedConceptId = IMHelper.getMappedSnomedConceptForSchemeCode(IMConstant.BARTS_CERNER, testCode); LOG.debug("Got Snomed test code " + testCodeSnomedConceptId); LOG.debug(""); LOG.debug("Want to get locally generated Cerner code for test code and positive textual result"); locallyGeneratedPositiveCode = IMHelper.getMappedLegacyCodeForLegacyCodeAndTerm(IMConstant.BARTS_CERNER, testCode, positiveResult); LOG.debug("Got locally generated code " + locallyGeneratedPositiveCode); LOG.debug(""); LOG.debug("Want to get locally generated Cerner code for test code and negative textual result"); locallyGeneratedNegativeCode = IMHelper.getMappedLegacyCodeForLegacyCodeAndTerm(IMConstant.BARTS_CERNER, testCode, negativeResult); LOG.debug("Got locally generated code " + locallyGeneratedNegativeCode); LOG.debug(""); LOG.debug("Want to get Snomed concept ID for test code and positive result"); snomedPositiveCode = IMHelper.getMappedSnomedConceptForSchemeCode(IMConstant.BARTS_CERNER, locallyGeneratedPositiveCode); LOG.debug("Got positive snomed code " + snomedPositiveCode); LOG.debug(""); LOG.debug("Want to get Snomed concept ID for test code and negative result"); snomedNegativeCode = IMHelper.getMappedSnomedConceptForSchemeCode(IMConstant.BARTS_CERNER, locallyGeneratedNegativeCode); LOG.debug("Got negative snomed code " + snomedNegativeCode); LOG.debug(""); LOG.debug(""); LOG.debug(""); LOG.debug(" List<String> encounterTerms = new ArrayList<>(); //hospital terms encounterTerms.add("Outpatient Register a patient"); encounterTerms.add("Outpatient Discharge/end visit"); encounterTerms.add("Outpatient Update patient information"); encounterTerms.add("Emergency department Register a patient (emergency)"); encounterTerms.add("Inpatient Transfer a patient"); encounterTerms.add("Emergency department Discharge/end visit (emergency)"); encounterTerms.add("Outpatient Referral Update patient information (waitinglist)"); encounterTerms.add("Outpatient Referral Pre-admit a patient (waitinglist)"); encounterTerms.add("Inpatient Discharge/end visit"); encounterTerms.add("Inpatient Admit/visit notification"); encounterTerms.add("Emergency department Update patient information (emergency)"); encounterTerms.add("Outpatient Change an inpatient to an outpatient"); //primary care terms encounterTerms.add("Telephone call to a patient"); encounterTerms.add("G.P.Surgery"); encounterTerms.add("Externally entered"); encounterTerms.add("Third party"); encounterTerms.add("GP Surgery"); encounterTerms.add("Scanned document"); encounterTerms.add("Docman"); encounterTerms.add("D.N.A."); encounterTerms.add("Telephone"); encounterTerms.add("Message"); encounterTerms.add("Path. Lab."); encounterTerms.add("Administration note"); encounterTerms.add("Telephone consultation"); encounterTerms.add("Main Surgery"); for (String encTerm: encounterTerms) { LOG.debug("" + encTerm + " -> "); String legacyEncCode = IMHelper.getMappedLegacyCodeForLegacyCodeAndTerm(IMConstant.ENCOUNTER_LEGACY, "TYPE", encTerm); LOG.debug(" legacy code = " + legacyEncCode); /*String snomedCode = null; if (!Strings.isNullOrEmpty(legacyEncCode)) { snomedCode = IMHelper.getMappedSnomedConceptForSchemeCode(IMConstant.ENCOUNTER_LEGACY, legacyEncCode); } LOG.debug("" + encTerm + " -> " + (legacyEncCode != null ? legacyEncCode : "NULL") + " -> " + (snomedCode != null ? snomedCode : "NULL"));*/ Integer legacyDbId = IMHelper.getConceptDbidForTypeTerm(null, IMConstant.ENCOUNTER_LEGACY, encTerm); Integer coreDbId = IMHelper.getIMMappedConceptForTypeTerm(null, IMConstant.ENCOUNTER_LEGACY, encTerm); LOG.debug(" legacy DB ID = " + legacyDbId + ", core DB ID = " + coreDbId); // Integer oldLegacyDbId = IMHelper.getConceptDbidForTypeTerm(null, IMConstant.DCE_Type_of_encounter, encTerm); // Integer oldCoreDbId = IMHelper.getIMMappedConceptForTypeTerm(null, null, IMConstant.DCE_Type_of_encounter, encTerm); // LOG.debug(" OLD legacy DB ID = " + oldLegacyDbId + ", OLD core DB ID = " + oldCoreDbId); } LOG.debug("Finished Testing Information Model"); } catch (Throwable t) { LOG.error("", t); } } public static void testDsm(String odsCode) { LOG.info("Testing DSM for " + odsCode); try { LOG.debug("Testing doesOrganisationHaveDPA"); boolean b = OrganisationCache.doesOrganisationHaveDPA(odsCode); LOG.debug("Got " + b); LOG.debug(""); LOG.debug(""); LOG.debug("Testing getAllDSAsForPublisherOrg"); List<DataSharingAgreementEntity> list = DataSharingAgreementCache.getAllDSAsForPublisherOrg(odsCode); if (list == null) { LOG.debug("Got NULL"); } else { LOG.debug("Got " + list.size()); for (DataSharingAgreementEntity e: list) { LOG.debug(" -> " + e.getName() + " " + e.getUuid()); } } LOG.debug(""); LOG.debug(""); LOG.debug("Testing getAllProjectsForSubscriberOrg"); List<ProjectEntity> projects = ProjectCache.getAllProjectsForSubscriberOrg(odsCode); Set<String> projectIds = new HashSet<>(); if (list == null) { LOG.debug("Got NULL"); } else { LOG.debug("Got " + list.size()); for (ProjectEntity project: projects) { LOG.debug(" -> " + project.getName() + " " + project.getUuid()); String projectUuid = project.getUuid(); projectIds.add(projectUuid); } } LOG.debug(""); LOG.debug(""); LOG.debug("Testing getAllPublishersForProjectWithSubscriberCheck"); if (projectIds.isEmpty()) { LOG.debug(" -> no project IDs"); } else { for (String projectId: projectIds) { LOG.debug("PROJECT ID " + projectId); List<String> results = ProjectCache.getAllPublishersForProjectWithSubscriberCheck(projectId, odsCode); LOG.debug("Got publisher ODS codes: " + results); } } LOG.debug("Testing getValidDistributionProjectsForPublisher"); List<ProjectEntity> validDistributionProjects = ProjectCache.getValidDistributionProjectsForPublisher(odsCode); if (validDistributionProjects.size() < 1) { LOG.debug("Got no valid projects"); } else { LOG.debug("Got " + validDistributionProjects.size() + " valid projects"); for (ProjectEntity project: validDistributionProjects) { LOG.debug(" -> " + project.getName() + " " + project.getUuid()); } } LOG.debug(""); LOG.debug(""); LOG.debug(""); LOG.debug(""); LOG.info("Finished Testing DSM for " + odsCode); } catch (Throwable t) { LOG.error("", t); } } public static void compareDsm(boolean logDifferencesOnly, String toFile, String odsCodeRegex) { LOG.debug("Comparing DSM to DDS-UI for " + odsCodeRegex); LOG.debug("logDifferencesOnly = " + logDifferencesOnly); LOG.debug("toFile = " + toFile); try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); File dstFile = new File(toFile); FileOutputStream fos = new FileOutputStream(dstFile); OutputStreamWriter osw = new OutputStreamWriter(fos); BufferedWriter bufferedWriter = new BufferedWriter(osw); CSVFormat format = EmisCsvToFhirTransformer.CSV_FORMAT .withHeader("Name", "ODS Code", "Parent Code", "Notes", "DDS-UI DPA", "DSM DPA", "DPA matches", "DDS-UI Endpoints", "DSM Endpoints", "DSA matches" ); CSVPrinter printer = new CSVPrinter(bufferedWriter, format); ServiceDalI serviceDal = DalProvider.factoryServiceDal(); List<Service> services = serviceDal.getAll(); for (Service service: services) { String odsCode = service.getLocalId(); UUID serviceId = service.getId(); //skip if filtering on ODS code if (shouldSkipService(service, odsCodeRegex)) { continue; } //only do if a publisher String publisherConfig = service.getPublisherConfigName(); if (Strings.isNullOrEmpty(publisherConfig)) { continue; } List<String> logging = new ArrayList<>(); boolean gotDifference = false; logging.add("Doing " + service + " //check DPAs //check if publisher to DDS protocol List<String> protocolIdsOldWay = DetermineRelevantProtocolIds.getProtocolIdsForPublisherServiceOldWay(serviceId.toString()); boolean hasDpaOldWay = !protocolIdsOldWay.isEmpty(); //in the old way, we count as having a DPA if they're in any protocol //check if DSM DPA boolean hasDpaNewWay = OrganisationCache.doesOrganisationHaveDPA(odsCode); boolean dpaMatches = hasDpaNewWay == hasDpaOldWay; if (!dpaMatches) { logging.add("Old and new DPA do not match (old = " + hasDpaOldWay + ", new = " + hasDpaNewWay + ")"); gotDifference = true; } else { logging.add("Old and new DPA match (" + hasDpaOldWay + ")"); } //check DSAs //want to find target subscriber config names OLD way Set<String> subscriberConfigNamesOldWay = new HashSet<>(); for (String oldProtocolId: protocolIdsOldWay) { LibraryItem libraryItem = LibraryRepositoryHelper.getLibraryItemUsingCache(UUID.fromString(oldProtocolId)); Protocol protocol = libraryItem.getProtocol(); //skip disabled protocols if (protocol.getEnabled() != ProtocolEnabled.TRUE) { continue; } List<ServiceContract> subscribers = protocol .getServiceContract() .stream() .filter(sc -> sc.getType().equals(ServiceContractType.SUBSCRIBER)) .filter(sc -> sc.getActive() == ServiceContractActive.TRUE) //skip disabled service contracts .collect(Collectors.toList()); for (ServiceContract serviceContract : subscribers) { String subscriberConfigName = MessageTransformOutbound.getSubscriberEndpoint(serviceContract); if (!Strings.isNullOrEmpty(subscriberConfigName)) { subscriberConfigNamesOldWay.add(subscriberConfigName); } } } //find target subscriber config names NEW way Set<String> subscriberConfigNamesNewWay = new HashSet<>(); List<ProjectEntity> distributionProjects = ProjectCache.getValidDistributionProjectsForPublisher(odsCode); if (distributionProjects == null) { logging.add("Got NULL distribution projects for " + odsCode); } else { for (ProjectEntity distributionProject: distributionProjects) { String configName = distributionProject.getConfigName(); if (!Strings.isNullOrEmpty(configName)) { subscriberConfigNamesNewWay.add(configName); } } } //compare the two List<String> l = new ArrayList<>(subscriberConfigNamesOldWay); l.sort(((o1, o2) -> o1.compareToIgnoreCase(o2))); String subscribersOldWay = String.join(", ", l); l = new ArrayList<>(subscriberConfigNamesNewWay); l.sort(((o1, o2) -> o1.compareToIgnoreCase(o2))); String subscribersNewWay = String.join(", ", l); boolean dsaMatches = subscribersOldWay.equals(subscribersNewWay); //flatten the tags to a String String notesStr = ""; if (service.getTags() != null) { List<String> toks = new ArrayList<>(); Map<String, String> tags = service.getTags(); List<String> keys = new ArrayList<>(tags.keySet()); keys.sort(((o1, o2) -> o1.compareToIgnoreCase(o2))); for (String key: keys) { String s = key; String val = tags.get(key); if (val != null) { s += " " + val; } toks.add(s); } notesStr = String.join(", ", toks); } printer.printRecord(service.getName(), odsCode, service.getCcgCode(), notesStr, hasDpaOldWay, hasDpaNewWay, dpaMatches, subscribersOldWay, subscribersNewWay, dsaMatches); logging.add(""); //log what we found if we need to if (!logDifferencesOnly || gotDifference) { for (String line: logging) { LOG.debug(line); } } } printer.close(); LOG.debug("Finished Comparing DSM to DDS-UI for " + odsCodeRegex + " to " + toFile); } catch (Throwable t) { LOG.error("", t); } } /** * generates the JSON for the config record to move config from DDS-UI protocols to DSM (+JSON) */ public static void createConfigJsonForDSM(String ddsUiProtocolName, String dsmDsaId) { LOG.debug("Creating Config JSON for DDS-UI -> DSM migration"); try { //get DDS-UI protocol details LibraryItem libraryItem = BulkHelper.findProtocolLibraryItem(ddsUiProtocolName); LOG.debug("DDS-UI protocol [" + ddsUiProtocolName + "]"); LOG.debug("DDS-UI protocol UUID " + libraryItem.getUuid()); //get DSM DPA details DataSharingAgreementEntity dsa = DataSharingAgreementCache.getDSADetails(dsmDsaId); LOG.debug("DSM DSA [" + dsa.getName() + "]"); LOG.debug("DSM DSA UUID " + dsa.getUuid()); ObjectMapper mapper = new ObjectMapper(); ObjectNode root = new ObjectNode(mapper.getNodeFactory()); //put in DSA name for visibility root.put("dsa_name", dsa.getName()); //subscriber config ArrayNode subscriberArray = root.putArray("subscribers"); Protocol protocol = libraryItem.getProtocol(); if (protocol.getEnabled() != ProtocolEnabled.TRUE) { throw new Exception("Protocol isn't enabled"); } List<ServiceContract> subscribers = protocol .getServiceContract() .stream() .filter(sc -> sc.getType().equals(ServiceContractType.SUBSCRIBER)) .filter(sc -> sc.getActive() == ServiceContractActive.TRUE) //skip disabled service contracts .collect(Collectors.toList()); for (ServiceContract serviceContract: subscribers) { String subscriberConfigName = MessageTransformOutbound.getSubscriberEndpoint(serviceContract); subscriberArray.add(subscriberConfigName); } //cohort stuff ObjectNode cohortRoot = root.putObject("cohort"); String cohort = protocol.getCohort(); if (cohort.equals("All Patients")) { cohortRoot.put("type", "all_patients"); } else if (cohort.equals("Explicit Patients")) { //database is dependent on protocol ID, but I don't think this used throw new Exception("Protocol uses explicit patient cohort so cannot be converted"); //cohortRoot.put("type", "explicit_patients"); } else if (cohort.startsWith("Defining Services")) { cohortRoot.put("type", "registered_at"); ArrayNode registeredAtRoot = cohortRoot.putArray("services"); int index = cohort.indexOf(":"); if (index == -1) { throw new RuntimeException("Invalid cohort format " + cohort); } String suffix = cohort.substring(index+1); String[] toks = suffix.split("\r|\n|,| |;"); for (String tok: toks) { String odsCode = tok.trim().toUpperCase(); //when checking, we always make uppercase if (!Strings.isNullOrEmpty(tok)) { registeredAtRoot.add(odsCode); } } } else { throw new PipelineException("Unknown cohort [" + cohort + "]"); } String json = mapper.writeValueAsString(root); LOG.debug("JSON:\r\n\r\n" + json + "\r\n\r\n"); LOG.debug("Finished Creating Config JSON for DDS-UI -> DSM migration"); } catch (Throwable t) { LOG.error("", t); } } public static void testBulkLoad(String s3Path, String tableName) { LOG.debug("Testing Bulk Load from " + s3Path + " to " + tableName); try { File dst = FileHelper.copyFileFromStorageToTempDirIfNecessary(s3Path); LOG.debug("Tmp file = " + dst); LOG.debug("Dst exists = " + dst.exists()); LOG.debug("Dst len = " + dst.length()); //bulk load Connection connection = ConnectionManager.getEdsConnection(); connection.setAutoCommit(true); String path = dst.getAbsolutePath(); path = path.replace("\\", "\\\\"); String sql = "LOAD DATA LOCAL INFILE '" + path + "'" + " INTO TABLE " + tableName + " FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\\\"'" + " LINES TERMINATED BY '\\r\\n'" + " IGNORE 1 LINES"; LOG.debug("Load SQL = " + sql); LOG.debug("Starting bulk load"); Statement statement = connection.createStatement(); statement.executeUpdate(sql); //connection.commit(); LOG.debug("Finished bulk load"); statement.close(); connection.setAutoCommit(false); connection.close(); LOG.debug("Deleting temp file " + dst); FileHelper.deleteFileFromTempDirIfNecessary(dst); LOG.debug("Dst exists = " + dst.exists()); LOG.debug("Finished Testing Bulk Load from " + s3Path + " to " + tableName); } catch (Throwable t) { LOG.error("", t); } } *//*Response response = testTarget. .get();*//* /*public static void testCallToDdsUi() { try { //get the Keycloak details from the EMIS config JsonNode json = ConfigManager.getConfigurationAsJson("emis_config", "queuereader"); json = json.get("missing_code_fix"); String ddsUrl = json.get("dds-ui-url").asText(); String keyCloakUrl = json.get("keycloak-url").asText(); String keyCloakRealm = json.get("keycloak-realm").asText(); String keyCloakUser = json.get("keycloak-username").asText(); String keyCloakPass = json.get("keycloak-password").asText(); String keyCloakClientId = json.get("keycloak-client-id").asText(); KeycloakClient kcClient = new KeycloakClient(keyCloakUrl, keyCloakRealm, keyCloakUser, keyCloakPass, keyCloakClientId); WebTarget testTarget = ClientBuilder.newClient().target(ddsUrl).path("api/service/ccgCodes"); String token = kcClient.getToken().getToken(); token = JOptionPane.showInputDialog("TOKEN", token); LOG.debug("Token = token"); Invocation.Builder builder = testTarget.request(); builder = builder.header("Authorization", "Bearer " + token); Response response = builder.get(); .request() .header("Authorization", "Bearer " + kcClient.getToken().getToken()) //request.Headers.Add("Authorization", this.token); int status = response.getStatus(); LOG.debug("Status = " + status); String responseStr = response.readEntity(String.class); LOG.debug("responseStr = " + responseStr); } catch (Throwable t) { LOG.error("", t); } }*/ /*public static void loadTppStagingData(String odsCode, UUID fromExchange) { LOG.debug("Loading TPP Staging Data for " + odsCode + " from Exchange " + fromExchange); try { ServiceDalI serviceDal = DalProvider.factoryServiceDal(); Service service = serviceDal.getByLocalIdentifier(odsCode); List<UUID> systemIds = SystemHelper.getSystemIdsForService(service); if (systemIds.size() != 1) { throw new Exception("" + systemIds.size() + " system IDs found"); } UUID systemId = systemIds.get(0); ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); List<Exchange> exchanges = exchangeDal.getExchangesByService(service.getId(), systemId, Integer.MAX_VALUE); LOG.debug("Got " + exchanges.size() + " exchanges"); //go backwards, as they're most-recent-first for (int i=exchanges.size()-1; i>=0; i--) { Exchange exchange = exchanges.get(i); if (fromExchange != null) { if (!exchange.getId().equals(fromExchange)) { LOG.debug("Skipping exchange " + exchange.getId()); continue; } fromExchange = null; } LOG.debug("Doing exchange " + exchange.getId() + " from " + exchange.getHeader(HeaderKeys.DataDate)); Date dataDate = exchange.getHeaderAsDate(HeaderKeys.DataDate); List<ExchangePayloadFile> files = ExchangeHelper.parseExchangeBody(exchange.getBody()); for (ExchangePayloadFile file: files) { String type = file.getType(); String filePath = file.getPath(); if (type.equals("Ctv3")) { TppCtv3LookupDalI dal = DalProvider.factoryTppCtv3LookupDal(); dal.updateLookupTable(filePath, dataDate); } else if (type.equals("Ctv3Hierarchy")) { TppCtv3HierarchyRefDalI dal = DalProvider.factoryTppCtv3HierarchyRefDal(); dal.updateHierarchyTable(filePath, dataDate); } else if (type.equals("ImmunisationContent")) { TppImmunisationContentDalI dal = DalProvider.factoryTppImmunisationContentDal(); dal.updateLookupTable(filePath, dataDate); } else if (type.equals("ConfiguredListOption")) { TppConfigListOptionDalI dal = DalProvider.factoryTppConfigListOptionDal(); dal.updateLookupTable(filePath, dataDate); } else if (type.equals("MedicationReadCodeDetails")) { TppMultiLexToCtv3MapDalI dal = DalProvider.factoryTppMultiLexToCtv3MapDal(); dal.updateLookupTable(filePath, dataDate); } else if (type.equals("Mapping")) { TppMappingRefDalI dal = DalProvider.factoryTppMappingRefDal(); dal.updateLookupTable(filePath, dataDate); } else if (type.equals("StaffMember")) { TppCsvHelper helper = new TppCsvHelper(service.getId(), systemId, exchange.getId()); String[] arr = new String[]{filePath}; Map<String, String> versions = TppCsvToFhirTransformer.buildParserToVersionsMap(arr, helper); String version = versions.get(filePath); SRStaffMember parser = new SRStaffMember(service.getId(), systemId, exchange.getId(), version, filePath); while (parser.nextRecord()) { //just spin through it } //bulk load the file into the DB int fileId = parser.getFileAuditId().intValue(); TppStaffDalI dal = DalProvider.factoryTppStaffMemberDal(); dal.updateStaffMemberLookupTable(filePath, dataDate, fileId); } else if (type.equals("StaffMemberProfile")) { TppCsvHelper helper = new TppCsvHelper(service.getId(), systemId, exchange.getId()); String[] arr = new String[]{filePath}; Map<String, String> versions = TppCsvToFhirTransformer.buildParserToVersionsMap(arr, helper); String version = versions.get(filePath); SRStaffMemberProfile parser = new SRStaffMemberProfile(service.getId(), systemId, exchange.getId(), version, filePath); while (parser.nextRecord()) { //just spin through it } //bulk load the file into the DB int fileId = parser.getFileAuditId().intValue(); TppStaffDalI dal = DalProvider.factoryTppStaffMemberDal(); dal.updateStaffProfileLookupTable(filePath, dataDate, fileId); } else { //ignore any other file types } } } } catch (Throwable t) { LOG.error("", t); } }*/ /*public static void loadEmisStagingData(String odsCode, UUID fromExchange) { LOG.debug("Loading EMIS Staging Data for " + odsCode + " from Exchange " + fromExchange); try { ServiceDalI serviceDal = DalProvider.factoryServiceDal(); Service service = serviceDal.getByLocalIdentifier(odsCode); List<UUID> systemIds = SystemHelper.getSystemIdsForService(service); if (systemIds.size() != 1) { throw new Exception("" + systemIds.size() + " system IDs found"); } UUID systemId = systemIds.get(0); ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); List<Exchange> exchanges = exchangeDal.getExchangesByService(service.getId(), systemId, Integer.MAX_VALUE); LOG.debug("Got " + exchanges.size() + " exchanges"); //go backwards, as they're most-recent-first for (int i=exchanges.size()-1; i>=0; i--) { Exchange exchange = exchanges.get(i); if (fromExchange != null) { if (!exchange.getId().equals(fromExchange)) { LOG.debug("Skipping exchange " + exchange.getId()); continue; } fromExchange = null; } LOG.debug("Doing exchange " + exchange.getId() + " from " + exchange.getHeader(HeaderKeys.DataDate)); Date dataDate = exchange.getHeaderAsDate(HeaderKeys.DataDate); List<ExchangePayloadFile> files = ExchangeHelper.parseExchangeBody(exchange.getBody()); //skip custom extracts if (files.size() <= 2) { continue; } String version = EmisCsvToFhirTransformer.determineVersion(files); for (ExchangePayloadFile file: files) { String type = file.getType(); String filePath = file.getPath(); if (type.equals("Admin_Location")) { Location parser = new Location(service.getId(), systemId, exchange.getId(), version, filePath); while (parser.nextRecord()) { //just spin through it } //the above will have audited the table, so now we can load the bulk staging table with our file EmisLocationDalI dal = DalProvider.factoryEmisLocationDal(); int fileId = parser.getFileAuditId().intValue(); dal.updateLocationStagingTable(filePath, dataDate, fileId); } else if (type.equals("Admin_OrganisationLocation")) { OrganisationLocation parser = new OrganisationLocation(service.getId(), systemId, exchange.getId(), version, filePath); while (parser.nextRecord()) { //just spin through it } //the above will have audited the table, so now we can load the bulk staging table with our file EmisLocationDalI dal = DalProvider.factoryEmisLocationDal(); int fileId = parser.getFileAuditId().intValue(); dal.updateOrganisationLocationStagingTable(filePath, dataDate, fileId); } else if (type.equals("Admin_Organisation")) { Organisation parser = new Organisation(service.getId(), systemId, exchange.getId(), version, filePath); while (parser.nextRecord()) { //just spin through it } //the above will have audited the table, so now we can load the bulk staging table with our file EmisOrganisationDalI dal = DalProvider.factoryEmisOrganisationDal(); int fileId = parser.getFileAuditId().intValue(); dal.updateStagingTable(filePath, dataDate, fileId); } else if (type.equals("Admin_UserInRole")) { UserInRole parser = new UserInRole(service.getId(), systemId, exchange.getId(), version, filePath); while (parser.nextRecord()) { //just spin through it } EmisUserInRoleDalI dal = DalProvider.factoryEmisUserInRoleDal(); int fileId = parser.getFileAuditId().intValue(); dal.updateStagingTable(filePath, dataDate, fileId); } else if (type.equals("Coding_ClinicalCode")) { EmisCsvHelper helper = new EmisCsvHelper(service.getId(), systemId, exchange.getId(), null, null); ClinicalCode parser = new ClinicalCode(service.getId(), systemId, exchange.getId(), version, filePath); File extraColsFile = ClinicalCodeTransformer.createExtraColsFile(parser, helper); EmisCodeDalI dal = DalProvider.factoryEmisCodeDal(); dal.updateClinicalCodeTable(filePath, extraColsFile.getAbsolutePath(), dataDate); FileHelper.deleteRecursiveIfExists(extraColsFile); } else if (type.equals("Coding_DrugCode")) { EmisCodeDalI dal = DalProvider.factoryEmisCodeDal(); dal.updateDrugCodeTable(filePath, dataDate); } else { //ignore any other file types } } } } catch (Throwable t) { LOG.error("", t); } }*/ /*public static void requeueSkippedAdminData(boolean tpp, boolean oneAtATime) { LOG.debug("Re-queueing skipped admin data for TPP = " + tpp); try { Connection connection = ConnectionManager.getAuditNonPooledConnection(); String tagsLike = null; if (tpp) { tagsLike = "TPP"; } else { tagsLike = "EMIS"; } while (true) { String sql = "select s.local_id, a.exchange_id" + " from audit.skipped_admin_data a" + " inner join admin.service s" + " on s.id = a.service_id" + " where s.tags like '%" + tagsLike + "%'" + " and a.queued = false" + " order by a.service_id, a.dt_skipped" + " limit 1"; Statement statement = connection.createStatement(); ResultSet rs = statement.executeQuery(sql); if (!rs.next()) { LOG.debug("Finished"); break; } String odsCode = rs.getString(1); UUID firstExchangeId = UUID.fromString(rs.getString(2)); LOG.debug("Found " + odsCode + " from " + firstExchangeId); ServiceDalI serviceDal = DalProvider.factoryServiceDal(); Service service = serviceDal.getByLocalIdentifier(odsCode); List<UUID> systemIds = SystemHelper.getSystemIdsForService(service); if (systemIds.size() != 1) { throw new Exception("Not one system ID for " + service); } UUID systemId = systemIds.get(0); List<UUID> exchangeIds = new ArrayList<>(); ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); List<UUID> allExchangeIds = exchangeDal.getExchangeIdsForService(service.getId(), systemId); int index = allExchangeIds.indexOf(firstExchangeId); for (int i=index; i<allExchangeIds.size(); i++) { UUID exchangeId = allExchangeIds.get(i); exchangeIds.add(exchangeId); } Set<String> fileTypesToFilterOn = new HashSet<>(); if (tpp) { fileTypesToFilterOn.add("Ctv3"); fileTypesToFilterOn.add("Ctv3Hierarchy"); fileTypesToFilterOn.add("ImmunisationContent"); fileTypesToFilterOn.add("Mapping"); fileTypesToFilterOn.add("ConfiguredListOption"); fileTypesToFilterOn.add("MedicationReadCodeDetails"); fileTypesToFilterOn.add("Ccg"); fileTypesToFilterOn.add("Trust"); fileTypesToFilterOn.add("Organisation"); fileTypesToFilterOn.add("OrganisationBranch"); fileTypesToFilterOn.add("StaffMember"); fileTypesToFilterOn.add("StaffMemberProfile"); } else { fileTypesToFilterOn.add("Agreements_SharingOrganisation"); fileTypesToFilterOn.add("Admin_OrganisationLocation"); fileTypesToFilterOn.add("Admin_Location"); fileTypesToFilterOn.add("Admin_Organisation"); fileTypesToFilterOn.add("Admin_UserInRole"); fileTypesToFilterOn.add("Appointment_SessionUser"); fileTypesToFilterOn.add("Appointment_Session"); fileTypesToFilterOn.add("Appointment_Slot"); } QueueHelper.postToExchange(exchangeIds, QueueHelper.EXCHANGE_INBOUND, null, true, "Going back to skipped admin", fileTypesToFilterOn, null); //update table after re-queuing sql = "update audit.skipped_admin_data a" + " inner join admin.service s" + " on s.id = a.service_id" + " set a.queued = true" + " where s.local_id = '" + odsCode + "'"; statement.executeUpdate(sql); connection.commit(); LOG.debug("Requeued " + exchangeIds.size() + " for " + odsCode); if (oneAtATime) { continueOrQuit(); } } connection.close(); LOG.debug("Finished Re-queueing skipped admin data for " + tagsLike); } catch (Throwable t) { LOG.error("", t); } }*/ /** * handy fn to stop a routine for manual inspection before continuing (or quitting) */ private static void continueOrQuit() throws Exception { LOG.info("Enter y to continue, anything else to quit"); byte[] bytes = new byte[10]; System.in.read(bytes); char c = (char) bytes[0]; if (c != 'y' && c != 'Y') { System.out.println("Read " + c); System.exit(1); } } public static void catptureBartsEncounters(int count, String toFile) { LOG.debug("Capturing " + count + " Barts Encounters to " + toFile); try { UUID serviceId = UUID.fromString("b5a08769-cbbe-4093-93d6-b696cd1da483"); UUID systemId = UUID.fromString("d874c58c-91fd-41bb-993e-b1b8b22038b2"); File dstFile = new File(toFile); FileOutputStream fos = new FileOutputStream(dstFile); OutputStreamWriter osw = new OutputStreamWriter(fos); BufferedWriter bufferedWriter = new BufferedWriter(osw); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //the Emis records use Windows record separators, so we need to match that otherwise //the bulk import routine will fail CSVFormat format = EmisCsvToFhirTransformer.CSV_FORMAT .withHeader("patientId", "episodeId", "id", "startDateDesc", "endDateDesc", "messageTypeCode", "messageTypeDesc", "statusDesc", "statusHistorySize", "classDesc", "typeDesc", "practitionerId", "dtRecordedDesc", "exchangeDateDesc", "currentLocation", "locationHistorySize", "serviceProvider", "cegEnterpriseId", "bhrEnterpriseId", "json" ); CSVPrinter printer = new CSVPrinter(bufferedWriter, format); ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); List<Exchange> exchanges = exchangeDal.getExchangesByService(serviceId, systemId, count); LOG.debug("Found " + count + " exchanges"); int done = 0; for (Exchange exchange: exchanges) { String body = exchange.getBody(); try { Bundle bundle = (Bundle)FhirResourceHelper.deserialiseResouce(body); List<Bundle.BundleEntryComponent> entries = bundle.getEntry(); for (Bundle.BundleEntryComponent entry: entries) { Resource resource = entry.getResource(); if (resource instanceof Encounter) { Encounter encounter = (Encounter)resource; String id = encounter.getId(); String dtRecordedDesc = null; DateTimeType dtRecorded = (DateTimeType)ExtensionConverter.findExtensionValue(encounter, FhirExtensionUri.RECORDED_DATE); if (dtRecorded != null) { Date d = dtRecorded.getValue(); dtRecordedDesc = sdf.format(d); } String messageTypeDesc = null; String messageTypeCode = null; CodeableConcept messageTypeConcept = (CodeableConcept)ExtensionConverter.findExtensionValue(encounter, FhirExtensionUri.HL7_MESSAGE_TYPE); if (messageTypeConcept != null) { messageTypeDesc = messageTypeConcept.getText(); if (messageTypeConcept.hasCoding()) { Coding coding = messageTypeConcept.getCoding().get(0); messageTypeCode = coding.getCode(); } } String statusDesc = null; if (encounter.hasStatus()) { statusDesc = "" + encounter.getStatus(); } Integer statusHistorySize = 0; if (encounter.hasStatusHistory()) { statusHistorySize = new Integer(encounter.getStatusHistory().size()); } String classDesc = null; if (encounter.hasClass_()) { classDesc = "" + encounter.getClass_(); } String typeDesc = null; if (encounter.hasType()) { List<CodeableConcept> types = encounter.getType(); CodeableConcept type = types.get(0); typeDesc = type.getText(); } String patientId = null; if (encounter.hasPatient()) { Reference ref = encounter.getPatient(); patientId = ReferenceHelper.getReferenceId(ref); } String episodeId = null; if (encounter.hasEpisodeOfCare()) { List<Reference> refs = encounter.getEpisodeOfCare(); Reference ref = refs.get(0); episodeId = ReferenceHelper.getReferenceId(ref); } String practitionerId = null; if (encounter.hasParticipant()) { List<Encounter.EncounterParticipantComponent> parts = encounter.getParticipant(); Encounter.EncounterParticipantComponent part = parts.get(0); if (part.hasIndividual()) { Reference ref = part.getIndividual(); practitionerId = ReferenceHelper.getReferenceId(ref); } } String startDateDesc = null; String endDateDesc = null; if (encounter.hasPeriod()) { Period p = encounter.getPeriod(); if (p.hasStart()) { startDateDesc = sdf.format(p.getStart()); } if (p.hasEnd()) { endDateDesc = sdf.format(p.getEnd()); } } Date dataDate = exchange.getHeaderAsDate(HeaderKeys.DataDate); String exchangeDateDesc = sdf.format(dataDate); Integer locationHistorySize = 0; String currentLocation = null; if (encounter.hasLocation()) { locationHistorySize = new Integer(encounter.getLocation().size()); for (Encounter.EncounterLocationComponent loc: encounter.getLocation()) { if (loc.getStatus() == Encounter.EncounterLocationStatus.ACTIVE) { Reference ref = loc.getLocation(); currentLocation = ReferenceHelper.getReferenceId(ref); } } } String serviceProvider = null; if (encounter.hasServiceProvider()) { Reference ref = encounter.getServiceProvider(); serviceProvider = ReferenceHelper.getReferenceId(ref); } SubscriberResourceMappingDalI dal = DalProvider.factorySubscriberResourceMappingDal("ceg_enterprise"); Long cegEnterpriseId = dal.findEnterpriseIdOldWay(ResourceType.Encounter.toString(), id); dal = DalProvider.factorySubscriberResourceMappingDal("pcr_01_enterprise_pi"); Long bhrEnterpriseId = dal.findEnterpriseIdOldWay(ResourceType.Encounter.toString(), id); String json = FhirSerializationHelper.serializeResource(encounter); printer.printRecord(patientId, episodeId, id, startDateDesc, endDateDesc, messageTypeCode, messageTypeDesc, statusDesc, statusHistorySize, classDesc, typeDesc, practitionerId, dtRecordedDesc, exchangeDateDesc, currentLocation, locationHistorySize, serviceProvider, cegEnterpriseId, bhrEnterpriseId, json); } } } catch (Exception ex) { throw new Exception("Exception on exchange " + exchange.getId(), ex); } done ++; if (done % 100 == 0) { LOG.debug("Done " + done); } } printer.close(); LOG.debug("Finished Capturing Barts Encounters to " + dstFile); } catch (Throwable t) { LOG.error("", t); } } public static void transformAdtEncounters(String odsCode, String tableName) { LOG.debug("Transforming " + odsCode + " Encounters from " + tableName); try { ServiceDalI serviceDal = DalProvider.factoryServiceDal(); Service service = serviceDal.getByLocalIdentifier(odsCode); LOG.debug("Running for " + service); /*SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); Date from = sdf.parse(dFrom); Date to = sdf.parse(dTo);*/ UUID serviceId = service.getId(); UUID systemId = UUID.fromString("d874c58c-91fd-41bb-993e-b1b8b22038b2"); ResourceDalI resourceDal = DalProvider.factoryResourceDal(); ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); int done = 0; while (true) { Connection connection = ConnectionManager.getEdsNonPooledConnection(); Statement statement = connection.createStatement(); List<UUID> ids = new ArrayList<>(); ResultSet rs = statement.executeQuery("SELECT exchange_id FROM " + tableName + " WHERE done = 0 ORDER BY timestamp LIMIT 1000"); while (rs.next()) { UUID exchangeId = UUID.fromString(rs.getString(1)); ids.add(exchangeId); Exchange exchange = exchangeDal.getExchange(exchangeId); String body = exchange.getBody(); try { if (!body.equals("[]")) { Bundle bundle = (Bundle) FhirResourceHelper.deserialiseResouce(body); List<Bundle.BundleEntryComponent> entries = bundle.getEntry(); for (Bundle.BundleEntryComponent entry : entries) { Resource resource = entry.getResource(); if (resource instanceof Encounter) { Encounter encounter = (Encounter) resource; ResourceWrapper currentWrapper = resourceDal.getCurrentVersion(serviceId, encounter.getResourceType().toString(), UUID.fromString(encounter.getId())); if (currentWrapper != null && !currentWrapper.isDeleted()) { List<UUID> batchIdsCreated = new ArrayList<>(); TransformError transformError = new TransformError(); FhirResourceFiler innerFiler = new FhirResourceFiler(exchange.getId(), serviceId, systemId, transformError, batchIdsCreated); FhirHl7v2Filer.AdtResourceFiler filer = new FhirHl7v2Filer.AdtResourceFiler(innerFiler); ExchangeTransformAudit transformAudit = new ExchangeTransformAudit(); transformAudit.setServiceId(serviceId); transformAudit.setSystemId(systemId); transformAudit.setExchangeId(exchange.getId()); transformAudit.setId(UUID.randomUUID()); transformAudit.setStarted(new Date()); AuditWriter.writeExchangeEvent(exchange.getId(), "Re-transforming Encounter for encounter_event"); //actually call the transform code Encounter currentEncounter = (Encounter) currentWrapper.getResource(); EncounterTransformer.updateEncounter(currentEncounter, encounter, filer); innerFiler.waitToFinish(); transformAudit.setEnded(new Date()); transformAudit.setNumberBatchesCreated(new Integer(batchIdsCreated.size())); if (transformError.getError().size() > 0) { transformAudit.setErrorXml(TransformErrorSerializer.writeToXml(transformError)); } exchangeDal.save(transformAudit); if (!transformError.getError().isEmpty()) { throw new Exception("Had error on Exchange " + exchange.getId()); } String batchIdString = ObjectMapperPool.getInstance().writeValueAsString(batchIdsCreated.toArray()); exchange.setHeader(HeaderKeys.BatchIdsJson, batchIdString); //send on to protocol queue PostMessageToExchangeConfig exchangeConfig = QueueHelper.findExchangeConfig("EdsProtocol"); PostMessageToExchange component = new PostMessageToExchange(exchangeConfig); component.process(exchange); } } } } //mark as done Connection connection2 = ConnectionManager.getEdsConnection(); PreparedStatement ps = connection2.prepareStatement("UPDATE " + tableName + " SET done = 1 WHERE exchange_id = ?"); ps.setString(1, exchangeId.toString()); ps.executeUpdate(); connection2.commit(); ps.close(); connection2.close(); } catch (Exception ex) { throw new Exception("Exception on exchange " + exchange.getId(), ex); } done++; if (done % 100 == 0) { LOG.debug("Done " + done); } } statement.close(); connection.close(); if (ids.isEmpty()) { break; } } LOG.debug("Done " + done); LOG.debug("Finished Transforming Barts Encounters from " + tableName); } catch (Throwable t) { LOG.error("", t); } } public static void findEmisServicesNeedReprocessing(String odsCodeRegex) { LOG.debug("Finding Emis Services that Need Re-processing for " + odsCodeRegex); try { ServiceDalI serviceDal = DalProvider.factoryServiceDal(); List<Service> services = serviceDal.getAll(); for (Service service: services) { Map<String, String> tags = service.getTags(); if (tags == null || !tags.containsKey("EMIS")) { continue; } if (shouldSkipService(service, odsCodeRegex)) { continue; } List<UUID> systemIds = SystemHelper.getSystemIdsForService(service); if (systemIds.size() != 1) { throw new Exception("Wrong number of system IDs for " + service); } UUID systemId = systemIds.get(0); String publisherStatus = null; for (ServiceInterfaceEndpoint serviceInterface: service.getEndpointsList()) { if (serviceInterface.getSystemUuid().equals(systemId)) { publisherStatus = serviceInterface.getEndpoint(); } } if (publisherStatus == null) { throw new Exception("Failed to find publisher status for service " + service); } LOG.debug(""); LOG.debug("CHECKING " + service + " " + publisherStatus + " >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); if (publisherStatus.equals(ServiceInterfaceEndpoint.STATUS_AUTO_FAIL)) { LOG.debug("Skipping service because set to auto-fail"); continue; } //check if in the bulks skipped table and are waiting to be re-queued Connection connection = ConnectionManager.getEdsConnection(); String sql = "select 1 from audit.skipped_exchanges_left_and_dead where ods_code = ? and (queued = false or queued is null)"; PreparedStatement ps = connection.prepareStatement(sql); ps.setString(1, service.getLocalId()); ResultSet rs = ps.executeQuery(); boolean needsRequeueing = rs.next(); ps.close(); connection.close(); if (needsRequeueing) { LOG.debug(">>>>> NEEDS REQUEUEING FOR SKIPPED BULK"); } ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); List<Exchange> exchanges = exchangeDal.getExchangesByService(service.getId(), systemId, Integer.MAX_VALUE); for (int i=exchanges.size()-1; i>=0; i Exchange exchange = exchanges.get(i); //if can't be queued, ignore it Boolean allowQueueing = exchange.getHeaderAsBoolean(HeaderKeys.AllowQueueing); if (allowQueueing != null && !allowQueueing.booleanValue()) { continue; } //skip any custom extracts String body = exchange.getBody(); List<ExchangePayloadFile> files = ExchangeHelper.parseExchangeBody(body, false); if (files.size() <= 1) { continue; } //LOG.debug("Doing exchange " + exchange.getId() + " from " + exchange.getHeaderAsDate(HeaderKeys.DataDate)); List<ExchangeTransformAudit> audits = exchangeDal.getAllExchangeTransformAudits(service.getId(), systemId, exchange.getId()); List<ExchangeEvent> events = exchangeDal.getExchangeEvents(exchange.getId()); //was it transformed OK before it was re-queued with filtering? boolean transformedWithoutFiltering = false; List<String> logging = new ArrayList<>(); for (ExchangeTransformAudit audit: audits) { //transformed OK boolean transformedOk = audit.getEnded() != null && audit.getErrorXml() == null; if (!transformedOk) { logging.add("Audit " + audit.getStarted() + " didn't complete OK, so not counting"); continue; } //if transformed OK see whether filtering was applied BEFORE Date dtTransformStart = audit.getStarted(); logging.add("Audit completed OK from " + audit.getStarted()); //find immediately proceeding event showing loading into inbound queue ExchangeEvent previousLoadingEvent = null; for (int j=events.size()-1; j>=0; j ExchangeEvent event = events.get(j); Date dtEvent = event.getTimestamp(); if (dtEvent.after(dtTransformStart)) { logging.add("Ignoring event from " + dtEvent + " as AFTER transform"); continue; } String eventDesc = event.getEventDesc(); if (eventDesc.startsWith("Manually pushed into edsInbound exchange") || eventDesc.startsWith("Manually pushed into EdsInbound exchange")) { previousLoadingEvent = event; logging.add("Proceeding event from " + dtEvent + " [" + eventDesc + "]"); break; } else { logging.add("Ignoring event from " + dtEvent + " as doesn't match text [" + eventDesc + "]"); } } if (previousLoadingEvent == null) { //if transformed OK and no previous manual loading event, then it was OK transformedWithoutFiltering = true; //LOG.debug("Audit from " + audit.getStarted() + " was transformed OK without being manually loaded = OK"); } else { //if transformed OK and was manually loaded into queue, then see if event applied filtering or not String eventDesc = previousLoadingEvent.getEventDesc(); if (!eventDesc.contains("Filtered on file types")) { transformedWithoutFiltering = true; //LOG.debug("Audit from " + audit.getStarted() + " was transformed OK and was manually loaded without filtering = OK"); } else { logging.add("Event desc filters on file types, so DIDN'T transform OK"); } } } if (!transformedWithoutFiltering) { LOG.error("" + service + " -> exchange " + exchange.getId() + " from " + exchange.getHeaderAsDate(HeaderKeys.DataDate)); /*for (String line: logging) { LOG.error(" " + line); }*/ } } } LOG.debug("Finished Finding Emis Services that Need Re-processing"); } catch (Throwable t) { LOG.error("", t); } } // For the protocol name provided, get the list of services which are publishers and send // their transformed Patient and EpisodeOfCare FHIR resources to the Enterprise Filer public static void transformAndFilePatientsAndEpisodesForProtocolServices (String protocolName, String subscriberConfigName) throws Exception { //find the protocol using the name parameter LibraryItem matchedLibraryItem = BulkHelper.findProtocolLibraryItem(protocolName); if (matchedLibraryItem == null) { System.out.println("Protocol not found : " + protocolName); return; } UUID protocolUuid = UUID.fromString(matchedLibraryItem.getUuid()); ResourceDalI dal = DalProvider.factoryResourceDal(); PatientSearchDalI patientSearchDal = DalProvider.factoryPatientSearchDal(); //get all the active publishing services for this protocol List<ServiceContract> serviceContracts = matchedLibraryItem.getProtocol().getServiceContract(); for (ServiceContract serviceContract : serviceContracts) { if (serviceContract.getType().equals(PUBLISHER) && serviceContract.getActive() == ServiceContractActive.TRUE) { UUID serviceUuid = UUID.fromString(serviceContract.getService().getUuid()); List<UUID> patientIds = patientSearchDal.getPatientIds(serviceUuid, true); for (UUID patientId : patientIds) { List<ResourceWrapper> patientResources = new ArrayList<>(); UUID batchUuid = UUID.randomUUID(); //need the Patient and the EpisodeOfCare resources for each service patient ResourceWrapper patientWrapper = dal.getCurrentVersion(serviceUuid, ResourceType.Patient.toString(), patientId); if (patientWrapper == null) { LOG.warn("Null patient resource for Patient " + patientId); continue; } patientResources.add(patientWrapper); String patientContainerString = BulkHelper.getEnterpriseContainerForPatientData(patientResources, serviceUuid, batchUuid, protocolUuid, subscriberConfigName, patientId); // Use a random UUID for a queued message ID if (patientContainerString != null) { EnterpriseFiler.file(batchUuid, UUID.randomUUID(), patientContainerString, subscriberConfigName); } List<ResourceWrapper> episodeResources = new ArrayList<>(); //patient may have multiple episodes of care at the service, so pass them in List<ResourceWrapper> episodeWrappers = dal.getResourcesByPatient(serviceUuid, patientId, ResourceType.EpisodeOfCare.toString()); if (episodeWrappers.isEmpty()) { LOG.warn("No episode resources for Patient " + patientId); continue; } for (ResourceWrapper episodeWrapper: episodeWrappers ) { episodeResources.add(episodeWrapper); } String episodeContainerString = BulkHelper.getEnterpriseContainerForEpisodeData(episodeResources, serviceUuid, batchUuid, protocolUuid, subscriberConfigName, patientId); // Use a random UUID for a queued message ID if (episodeContainerString != null) { EnterpriseFiler.file(batchUuid, UUID.randomUUID(), episodeContainerString, subscriberConfigName); } } } } } /** * we've found that the TPP data contains registration data for other organisations, which * is causing a lot of confusion (and potential duplication). The transform now doesn't process these * records, and this routine will tidy up any existing data */ public static void deleteTppEpisodesElsewhere(String odsCodeRegex, boolean testMode) { LOG.debug("Deleting TPP Episodes Elsewhere for " + odsCodeRegex); try { ServiceDalI serviceDal = DalProvider.factoryServiceDal(); List<Service> services = serviceDal.getAll(); for (Service service: services) { Map<String, String> tags = service.getTags(); if (tags == null || !tags.containsKey("TPP")) { continue; } if (shouldSkipService(service, odsCodeRegex)) { continue; } LOG.debug("Doing " + service); List<UUID> systemIds = SystemHelper.getSystemIdsForService(service); if (systemIds.size() != 1) { throw new Exception("Wrong number of system IDs for " + service); } UUID systemId = systemIds.get(0); PatientSearchDalI patientSearchDal = DalProvider.factoryPatientSearchDal(); ResourceDalI resourceDal = DalProvider.factoryResourceDal(); List<UUID> patientIds = patientSearchDal.getPatientIds(service.getId(), false); LOG.debug("Found " + patientIds.size()); //create dummy exchange String bodyJson = JsonSerializer.serialize(new ArrayList<ExchangePayloadFile>()); String odsCode = service.getLocalId(); Exchange exchange = null; UUID exchangeId = UUID.randomUUID(); List<UUID> batchIdsCreated = new ArrayList<>(); FhirResourceFiler filer = new FhirResourceFiler(exchangeId, service.getId(), systemId, new TransformError(), batchIdsCreated); int deleted = 0; for (int i=0; i<patientIds.size(); i++) { UUID patientId = patientIds.get(i); Patient patient = (Patient)resourceDal.getCurrentVersionAsResource(service.getId(), ResourceType.Patient, patientId.toString()); if (patient == null) { continue; } if (!patient.hasManagingOrganization()) { throw new Exception("No managing organization on Patient " + patientId); } Reference patientManagingOrgRef = patient.getManagingOrganization(); List<ResourceWrapper> wrappers = resourceDal.getResourcesByPatient(service.getId(), patientId, ResourceType.EpisodeOfCare.toString()); for (ResourceWrapper wrapper: wrappers) { if (wrapper.isDeleted()) { throw new Exception("Unexpected deleted resource " + wrapper.getResourceType() + " " + wrapper.getResourceId()); } EpisodeOfCare episodeOfCare = (EpisodeOfCare)wrapper.getResource(); if (!episodeOfCare.hasManagingOrganization()) { throw new Exception("No managing organization on Episode " + episodeOfCare.getId()); } Reference episodeManagingOrgRef = episodeOfCare.getManagingOrganization(); if (!ReferenceHelper.equals(patientManagingOrgRef, episodeManagingOrgRef)) { deleted ++; //delete this episode if (testMode) { LOG.debug("Would delete episode " + episodeOfCare.getId()); } else { if (exchange == null) { exchange = new Exchange(); exchange.setId(exchangeId); exchange.setBody(bodyJson); exchange.setTimestamp(new Date()); exchange.setHeaders(new HashMap<>()); exchange.setHeaderAsUuid(HeaderKeys.SenderServiceUuid, service.getId()); exchange.setHeader(HeaderKeys.ProtocolIds, ""); //just set to non-null value, so postToExchange(..) can safely recalculate exchange.setHeader(HeaderKeys.SenderLocalIdentifier, odsCode); exchange.setHeaderAsUuid(HeaderKeys.SenderSystemUuid, systemId); exchange.setHeader(HeaderKeys.SourceSystem, MessageFormat.TPP_CSV); exchange.setServiceId(service.getId()); exchange.setSystemId(systemId); AuditWriter.writeExchange(exchange); AuditWriter.writeExchangeEvent(exchange, "Manually created to delete Episodes at other organisations"); } //delete resource filer.deletePatientResource(null, false, new EpisodeOfCareBuilder(episodeOfCare)); } } } if (i % 1000 == 0) { LOG.debug("Done " + i); } } LOG.debug("Finished processing " + patientIds.size() + " patients and deleted " + deleted + " episodes"); if (!testMode) { //close down filer filer.waitToFinish(); if (exchange != null) { //set multicast header String batchIdString = ObjectMapperPool.getInstance().writeValueAsString(batchIdsCreated.toArray()); exchange.setHeader(HeaderKeys.BatchIdsJson, batchIdString); //post to Rabbit protocol queue List<UUID> exchangeIds = new ArrayList<>(); exchangeIds.add(exchange.getId()); QueueHelper.postToExchange(exchangeIds, "EdsProtocol", null, true, null); } } } LOG.debug("Finished Deleting TPP Episodes Elsewhere for " + odsCodeRegex); } catch (Throwable t) { LOG.error("", t); } } public static void postToInboundFromFile(String filePath, String reason) { try { LOG.info("Posting to inbound exchange from file " + filePath); //read in file into map keyed by service and system Map<UUID, Map<UUID, List<UUID>>> hmExchangeIds = new HashMap<>(); FileReader fr = new FileReader(filePath); BufferedReader br = new BufferedReader(fr); ExchangeDalI exchangeDal = DalProvider.factoryExchangeDal(); ServiceDalI serviceDalI = DalProvider.factoryServiceDal(); while (true) { String line = br.readLine(); if (line == null) { break; } UUID exchangeId = UUID.fromString(line); Exchange exchange = exchangeDal.getExchange(exchangeId); UUID serviceId = exchange.getServiceId(); UUID systemId = exchange.getSystemId(); Map<UUID, List<UUID>> inner = hmExchangeIds.get(serviceId); if (inner == null) { inner = new HashMap<>(); hmExchangeIds.put(serviceId, inner); } List<UUID> list = inner.get(systemId); if (list == null) { list = new ArrayList<>(); inner.put(systemId, list); } list.add(exchangeId); } br.close(); LOG.debug("Found exchanges for " + hmExchangeIds.size() + " services"); for (UUID serviceId: hmExchangeIds.keySet()) { Map<UUID, List<UUID>> inner = hmExchangeIds.get(serviceId); Service service = serviceDalI.getById(serviceId); LOG.debug("Doing " + service); for (UUID systemId: inner.keySet()) { List<UUID> exchangeIds = inner.get(systemId); int count = 0; List<UUID> exchangeIdBatch = new ArrayList<>(); for (UUID exchangeId : exchangeIds) { count++; exchangeIdBatch.add(exchangeId); //update the transform audit, so EDS UI knows we've re-queued this exchange ExchangeTransformAudit audit = exchangeDal.getMostRecentExchangeTransform(serviceId, systemId, exchangeId); if (audit != null && !audit.isResubmitted()) { audit.setResubmitted(true); exchangeDal.save(audit); } if (exchangeIdBatch.size() >= 1000) { QueueHelper.postToExchange(exchangeIdBatch, "EdsInbound", null, false, reason); exchangeIdBatch = new ArrayList<>(); LOG.info("Done " + count); } } if (!exchangeIdBatch.isEmpty()) { QueueHelper.postToExchange(exchangeIdBatch, "EdsInbound", null, false, reason); LOG.info("Done " + count); } } } LOG.info("Finished Posting to inbound"); } catch (Throwable ex) { LOG.error("", ex); } } public static void deleteDataFromOldCoreDB(UUID serviceId, String previousPublisherConfigName) { LOG.debug("Deleting data from old Core DB server for " + serviceId); try { ServiceDalI serviceDal = DalProvider.factoryServiceDal(); Service service = serviceDal.getById(serviceId); LOG.debug("Service = " + service); //find a service on the OLD config DB UUID altServiceId = null; for (Service s: serviceDal.getAll()) { if (s.getPublisherConfigName() != null && s.getPublisherConfigName().equals(previousPublisherConfigName)) { altServiceId = s.getId(); break; } } if (altServiceId == null) { throw new Exception("Failed to find any service on publisher " + previousPublisherConfigName); } //find all subscriber config names Set<String> subscriberConfigNames = new HashSet<>(); List<String> protocolIds = DetermineRelevantProtocolIds.getProtocolIdsForPublisherServiceOldWay(serviceId.toString()); for (String oldProtocolId: protocolIds) { LibraryItem libraryItem = LibraryRepositoryHelper.getLibraryItemUsingCache(UUID.fromString(oldProtocolId)); Protocol protocol = libraryItem.getProtocol(); //skip disabled protocols if (protocol.getEnabled() != ProtocolEnabled.TRUE) { continue; } List<ServiceContract> subscribers = protocol .getServiceContract() .stream() .filter(sc -> sc.getType().equals(ServiceContractType.SUBSCRIBER)) .filter(sc -> sc.getActive() == ServiceContractActive.TRUE) //skip disabled service contracts .collect(Collectors.toList()); for (ServiceContract serviceContract : subscribers) { String subscriberConfigName = MessageTransformOutbound.getSubscriberEndpoint(serviceContract); subscriberConfigNames.add(subscriberConfigName); } } LOG.debug("Found " + subscriberConfigNames.size() + " subscribers: " + subscriberConfigNames); PatientSearchDalI patientSearchDal = DalProvider.factoryPatientSearchDal(); List<UUID> patientIds = patientSearchDal.getPatientIds(serviceId, true); LOG.debug("Found " + patientIds.size()); patientIds.add(null); //for admin resources Connection ehrConnection = ConnectionManager.getEhrNonPooledConnection(altServiceId); int done = 0; for (UUID patientId: patientIds) { //send to each subscriber for (String subscriberConfigName: subscriberConfigNames) { SubscriberResourceMappingDalI subscriberDal = DalProvider.factorySubscriberResourceMappingDal(subscriberConfigName); OutputContainer output = new OutputContainer(); boolean doneSomething = false; String sql = "SELECT resource_id, resource_type" + " FROM resource_current" + " WHERE service_id = ?" + " AND patient_id = ?"; PreparedStatement ps = ehrConnection.prepareStatement(sql); ps.setFetchSize(500); ps.setString(1, serviceId.toString()); if (patientId == null) { ps.setString(2, ""); //get admin data } else { ps.setString(2, patientId.toString()); } ResultSet rs = ps.executeQuery(); while (rs.next()) { String resourceId = rs.getString(1); String resourceType = rs.getString(2); String sourceId = ReferenceHelper.createResourceReference(resourceType, resourceId); SubscriberTableId subscriberTableId = null; if (resourceType.equals("Patient")) { subscriberTableId = SubscriberTableId.PATIENT; } else if (resourceType.equals("AllergyIntolerance")) { subscriberTableId = SubscriberTableId.ALLERGY_INTOLERANCE; } else if (resourceType.equals("Encounter")) { subscriberTableId = SubscriberTableId.ENCOUNTER; } else if (resourceType.equals("EpisodeOfCare")) { subscriberTableId = SubscriberTableId.EPISODE_OF_CARE; } else if (resourceType.equals("Flag")) { subscriberTableId = SubscriberTableId.FLAG; } else if (resourceType.equals("Location")) { subscriberTableId = SubscriberTableId.LOCATION; } else if (resourceType.equals("MedicationOrder")) { subscriberTableId = SubscriberTableId.MEDICATION_ORDER; } else if (resourceType.equals("MedicationStatement")) { subscriberTableId = SubscriberTableId.MEDICATION_STATEMENT; } else if (resourceType.equals("Observation") || resourceType.equals("Condition") || resourceType.equals("Immunization") || resourceType.equals("FamilyMemberHistory")) { subscriberTableId = SubscriberTableId.OBSERVATION; } else if (resourceType.equals("Organization")) { subscriberTableId = SubscriberTableId.ORGANIZATION; } else if (resourceType.equals("Practitioner")) { subscriberTableId = SubscriberTableId.PRACTITIONER; } else if (resourceType.equals("ProcedureRequest")) { subscriberTableId = SubscriberTableId.PROCEDURE_REQUEST; } else if (resourceType.equals("ReferralRequest")) { subscriberTableId = SubscriberTableId.REFERRAL_REQUEST; } else if (resourceType.equals("Schedule")) { subscriberTableId = SubscriberTableId.SCHEDULE; } else if (resourceType.equals("Appointment")) { subscriberTableId = SubscriberTableId.APPOINTMENT; } else if (resourceType.equals("DiagnosticOrder")) { subscriberTableId = SubscriberTableId.DIAGNOSTIC_ORDER; } else if (resourceType.equals("Slot")) { //these were ignored continue; } else { throw new Exception("Unexpected resource type " + resourceType + " " + resourceId); } SubscriberId subscriberId = subscriberDal.findSubscriberId(subscriberTableId.getId(), sourceId); if (subscriberId == null) { continue; } doneSomething = true; if (resourceType.equals("Patient")) { output.getPatients().writeDelete(subscriberId); //the database doesn't have any pseudo IDs, so don't need to worry about that table int maxAddresses = 0; int maxTelecoms = 0; ResourceDalI resourceDal = DalProvider.factoryResourceDal(); List<ResourceWrapper> history = resourceDal.getResourceHistory(altServiceId, resourceType, UUID.fromString(resourceId)); for (ResourceWrapper h: history) { Patient p = (Patient)h.getResource(); if (p != null) { maxAddresses = Math.max(maxAddresses, p.getAddress().size()); maxTelecoms = Math.max(maxTelecoms, p.getTelecom().size()); } } for (int i=0; i<maxAddresses; i++) { String subSourceId = sourceId + "-ADDR-" + i; SubscriberId subTableId = subscriberDal.findSubscriberId(SubscriberTableId.PATIENT_ADDRESS.getId(), subSourceId); if (subTableId != null) { output.getPatientAddresses().writeDelete(subTableId); } } for (int i=0; i<maxTelecoms; i++) { String subSourceId = sourceId + "-TELECOM-" + i; SubscriberId subTableId = subscriberDal.findSubscriberId(SubscriberTableId.PATIENT_CONTACT.getId(), subSourceId); if (subTableId != null) { output.getPatientContacts().writeDelete(subTableId); } } } else if (resourceType.equals("AllergyIntolerance")) { output.getAllergyIntolerances().writeDelete(subscriberId); } else if (resourceType.equals("Encounter")) { output.getEncounters().writeDelete(subscriberId); } else if (resourceType.equals("EpisodeOfCare")) { output.getEpisodesOfCare().writeDelete(subscriberId); //reg status history table isn't populated yet, so can ignore that } else if (resourceType.equals("Flag")) { output.getFlags().writeDelete(subscriberId); } else if (resourceType.equals("Location")) { output.getLocations().writeDelete(subscriberId); } else if (resourceType.equals("MedicationOrder")) { output.getMedicationOrders().writeDelete(subscriberId); } else if (resourceType.equals("MedicationStatement")) { output.getMedicationStatements().writeDelete(subscriberId); } else if (resourceType.equals("Observation") || resourceType.equals("Condition") || resourceType.equals("Immunization") || resourceType.equals("FamilyMemberHistory")) { output.getObservations().writeDelete(subscriberId); } else if (resourceType.equals("Organization")) { output.getOrganisations().writeDelete(subscriberId); } else if (resourceType.equals("Practitioner")) { output.getPractitioners().writeDelete(subscriberId); } else if (resourceType.equals("ProcedureRequest")) { output.getProcedureRequests().writeDelete(subscriberId); } else if (resourceType.equals("ReferralRequest")) { output.getReferralRequests().writeDelete(subscriberId); } else if (resourceType.equals("Schedule")) { output.getSchedules().writeDelete(subscriberId); } else if (resourceType.equals("Appointment")) { output.getAppointments().writeDelete(subscriberId); } else if (resourceType.equals("DiagnosticOrder")) { output.getDiagnosticOrder().writeDelete(subscriberId); } else { throw new Exception("Unexpected resource type " + resourceType + " " + resourceId); } } ps.close(); if (doneSomething) { byte[] bytes = output.writeToZip(); String base64 = Base64.getEncoder().encodeToString(bytes); UUID batchId = UUID.randomUUID(); SubscriberFiler.file(batchId, UUID.randomUUID(), base64, subscriberConfigName); } } done ++; if (done % 100 == 0) { LOG.debug("Done " + done); } } LOG.debug("Done " + done); ehrConnection.close(); LOG.debug("Finished Deleting data from old Core DB server for " + serviceId); } catch (Throwable t) { LOG.error("", t); } } public static void populateMissingOrgsInCompassV1(String subscriberConfigName, boolean testMode) { LOG.debug("Populating Missing Orgs In CompassV1 " + subscriberConfigName + " testMode = " + testMode); try { Connection subscriberTransformConnection = ConnectionManager.getSubscriberTransformNonPooledConnection(subscriberConfigName); //get orgs in that subscriber DB Map<UUID, Long> hmOrgs = new HashMap<>(); String sql = "SELECT service_id, enterprise_id FROM enterprise_organisation_id_map"; Statement statement = subscriberTransformConnection.createStatement(); ResultSet rs = statement.executeQuery(sql); while (rs.next()) { String s = rs.getString(1); long id = rs.getLong(2); hmOrgs.put(UUID.fromString(s), new Long(id)); } LOG.debug("Found " + hmOrgs.size() + " orgs"); for (UUID serviceId: hmOrgs.keySet()) { Long enterpriseId = hmOrgs.get(serviceId); LOG.debug("Doing service " + serviceId + ", enterprise ID " + enterpriseId); /*ServiceDalI serviceDal = DalProvider.factoryServiceDal(); Service service = serviceDal.getById(serviceId);*/ //find the FHIR Organization this is from sql = "SELECT resource_id FROM enterprise_id_map WHERE enterprise_id = " + enterpriseId; rs = statement.executeQuery(sql); if (!rs.next()) { sql = "SELECT resource_id FROM enterprise_id_map_3 WHERE enterprise_id = " + enterpriseId; rs = statement.executeQuery(sql); if (!rs.next()) { throw new Exception("Failed to find resource ID for service ID " + serviceId + " and enterprise ID " + enterpriseId); } } String resourceId = rs.getString(1); Reference orgRef = ReferenceHelper.createReference(ResourceType.Organization, resourceId); //make sure our org is on the CoreXX server we expect and take over any instance mapping orgRef = findNewOrgRefOnCoreDb(subscriberConfigName, orgRef, serviceId, testMode); if (orgRef == null) { LOG.warn("<<<<<<<<No Organization resource could be found for " + resourceId + ">>>>>>>>>>>>>>>>>>>>>>>>>"); continue; } //find the org and work up to find all its parents too List<ResourceWrapper> resourceWrappers = new ArrayList<>(); while (orgRef != null) { ReferenceComponents comps = ReferenceHelper.getReferenceComponents(orgRef); if (comps.getResourceType() != ResourceType.Organization) { throw new Exception("Found non-organisation resource mapping for enterprise ID " + enterpriseId + ": " + resourceId); } UUID orgId = UUID.fromString(comps.getId()); ResourceDalI resourceDal = DalProvider.factoryResourceDal(); ResourceWrapper wrapper = resourceDal.getCurrentVersion(serviceId, ResourceType.Organization.toString(), orgId); if (wrapper == null) { throw new Exception("Failed to find resource wrapper for parent org with resource ID " + resourceId); } resourceWrappers.add(wrapper); Organization org = (Organization)wrapper.getResource(); if (org.hasPartOf()) { orgRef = org.getPartOf(); } else { orgRef = null; } } if (testMode) { LOG.debug("Found " + resourceWrappers.size() + " orgs"); for (ResourceWrapper wrapper: resourceWrappers) { Organization org = (Organization)wrapper.getResource(); String odsCode = IdentifierHelper.findOdsCode(org); LOG.debug(" Got " + org.getName() + " [" + odsCode + "]"); } } else { EnterpriseTransformHelper helper = new EnterpriseTransformHelper(serviceId, null, null, null, subscriberConfigName, resourceWrappers); org.endeavourhealth.transform.enterprise.outputModels.Organization orgWriter = helper.getOutputContainer().getOrganisations(); OrganisationEnterpriseTransformer t = new OrganisationEnterpriseTransformer(); t.transformResources(resourceWrappers, orgWriter, helper); org.endeavourhealth.transform.enterprise.outputModels.OutputContainer output = helper.getOutputContainer(); byte[] bytes = output.writeToZip(); if (bytes == null) { LOG.debug("Generated NULL bytes"); } else { LOG.debug("Generated " + bytes.length + " bytes"); String base64 = Base64.getEncoder().encodeToString(bytes); UUID batchId = UUID.randomUUID(); EnterpriseFiler.file(batchId, UUID.randomUUID(), base64, subscriberConfigName); } } } statement.close(); subscriberTransformConnection.close(); LOG.debug("Finished Populating Missing Orgs In CompassV1 " + subscriberConfigName); } catch (Throwable t) { LOG.error("", t); } } public static void populateMissingOrgsInCompassV2(String subscriberConfigName, boolean testMode) { LOG.debug("Populating Missing Orgs In CompassV2 " + subscriberConfigName + " testMode = " + testMode); try { Connection subscriberTransformConnection = ConnectionManager.getSubscriberTransformNonPooledConnection(subscriberConfigName); //get orgs in that subscriber DB Map<UUID, Long> hmOrgs = new HashMap<>(); String sql = "SELECT service_id, enterprise_id FROM enterprise_organisation_id_map"; Statement statement = subscriberTransformConnection.createStatement(); ResultSet rs = statement.executeQuery(sql); while (rs.next()) { String s = rs.getString(1); long id = rs.getLong(2); hmOrgs.put(UUID.fromString(s), new Long(id)); } LOG.debug("Found " + hmOrgs.size() + " orgs"); for (UUID serviceId: hmOrgs.keySet()) { Long subscriberId = hmOrgs.get(serviceId); LOG.debug("Doing service " + serviceId + ", subscriber ID " + subscriberId); /*ServiceDalI serviceDal = DalProvider.factoryServiceDal(); Service service = serviceDal.getById(serviceId);*/ //find the FHIR Organization this is from sql = "SELECT source_id FROM subscriber_id_map WHERE subscriber_id = " + subscriberId; rs = statement.executeQuery(sql); if (!rs.next()) { sql = "SELECT source_id FROM subscriber_id_map_3 WHERE subscriber_id = " + subscriberId; rs = statement.executeQuery(sql); if (!rs.next()) { throw new Exception("Failed to find source ID for service ID " + serviceId + " and subscriber ID " + subscriberId); } } String sourceId = rs.getString(1); Reference orgRef = ReferenceHelper.createReference(sourceId); //make sure our org is on the CoreXX server we expect and take over any instance mapping orgRef = findNewOrgRefOnCoreDb(subscriberConfigName, orgRef, serviceId, testMode); if (orgRef == null) { LOG.warn("<<<<<<<<No Organization resource could be found for " + sourceId + ">>>>>>>>>>>>>>>>>>>>>>>>>"); continue; } //find the org and work up to find all its parents too List<ResourceWrapper> resourceWrappers = new ArrayList<>(); while (orgRef != null) { ReferenceComponents comps = ReferenceHelper.getReferenceComponents(orgRef); if (comps.getResourceType() != ResourceType.Organization) { throw new Exception("Found non-organisation resource mapping for subscriber ID " + subscriberId + ": " + sourceId); } UUID orgId = UUID.fromString(comps.getId()); ResourceDalI resourceDal = DalProvider.factoryResourceDal(); ResourceWrapper wrapper = resourceDal.getCurrentVersion(serviceId, ResourceType.Organization.toString(), orgId); if (wrapper == null) { throw new Exception("Failed to find resource wrapper for parent org with source ID " + sourceId); } resourceWrappers.add(wrapper); Organization org = (Organization)wrapper.getResource(); if (org.hasPartOf()) { orgRef = org.getPartOf(); } else { orgRef = null; } } if (testMode) { LOG.debug("Found " + resourceWrappers.size() + " orgs"); for (ResourceWrapper wrapper: resourceWrappers) { Organization org = (Organization)wrapper.getResource(); String odsCode = IdentifierHelper.findOdsCode(org); LOG.debug(" Got " + org.getName() + " [" + odsCode + "]"); } } else { SubscriberTransformHelper helper = new SubscriberTransformHelper(serviceId, null, null, null, subscriberConfigName, resourceWrappers); OrganisationTransformer t = new OrganisationTransformer(); t.transformResources(resourceWrappers, helper); OutputContainer output = helper.getOutputContainer(); byte[] bytes = output.writeToZip(); if (bytes == null) { LOG.debug("Generated NULL bytes"); } else { LOG.debug("Generated " + bytes.length + " bytes"); String base64 = Base64.getEncoder().encodeToString(bytes); UUID batchId = UUID.randomUUID(); SubscriberFiler.file(batchId, UUID.randomUUID(), base64, subscriberConfigName); } } } statement.close(); subscriberTransformConnection.close(); LOG.debug("Finished Populating Missing Orgs In CompassV2 " + subscriberConfigName); } catch (Throwable t) { LOG.error("", t); } } private static Reference findNewOrgRefOnCoreDb(String subscriberConfigName, Reference oldOrgRef, UUID serviceId, boolean testMode) throws Exception { String oldOrgId = ReferenceHelper.getReferenceId(oldOrgRef); ResourceDalI resourceDal = DalProvider.factoryResourceDal(); ResourceWrapper wrapper = resourceDal.getCurrentVersion(serviceId, ResourceType.Organization.toString(), UUID.fromString(oldOrgId)); if (wrapper != null) { LOG.trace("Organization exists at service"); return oldOrgRef; } LOG.debug("Org doesn't exist at service, so need to take over instance mapping"); Reference newOrgRef = null; PatientSearchDalI patientSearchDal = DalProvider.factoryPatientSearchDal(); List<UUID> patientIds = patientSearchDal.getPatientIds(serviceId, false, 10000); for (UUID patientId: patientIds) { ResourceDalI resourceRepository = DalProvider.factoryResourceDal(); Patient patient = (Patient) resourceRepository.getCurrentVersionAsResource(serviceId, ResourceType.Patient, patientId.toString()); if (patient == null) { continue; } if (!patient.hasManagingOrganization()) { throw new TransformException("Patient " + patient.getId() + " doesn't have a managing org for service " + serviceId); } newOrgRef = patient.getManagingOrganization(); break; } if (newOrgRef == null) { throw new Exception("Failed to find new org ref from patient records"); } String newOrgId = ReferenceHelper.getReferenceId(newOrgRef); if (newOrgId.equals(oldOrgId)) { LOG.debug("Org ref correct but doesn't exist on DB - reference data is missing???"); return null; } if (testMode) { LOG.debug("Would need to take over instance mapping from " + oldOrgId + " -> " + newOrgId); } else { LOG.debug("Taking over instance mapping from " + oldOrgId + " -> " + newOrgId); //we need to update the subscriber transform DB to make this new org ref the defacto one SubscriberInstanceMappingDalI dal = DalProvider.factorySubscriberInstanceMappingDal(subscriberConfigName); dal.takeOverInstanceMapping(ResourceType.Organization, UUID.fromString(oldOrgId), UUID.fromString(newOrgId)); LOG.debug("Done"); } return newOrgRef; } public static void testHashedFileFilteringForSRCode(String filePath, String uniqueKey) { LOG.info("Testing Hashed File Filtering for SRCode using " + filePath); try { //HashFunction hf = Hashing.md5(); //HashFunction hf = Hashing.murmur3_128(); HashFunction hf = Hashing.sha512(); Hasher hasher = hf.newHasher(); hasher.putString(filePath, Charset.defaultCharset()); HashCode hc = hasher.hash(); int fileUniqueId = hc.asInt(); //copy file to local file String name = FilenameUtils.getName(filePath); String srcTempName = "TMP_SRC_" + name; String dstTempName = "TMP_DST_" + name; File srcFile = new File(srcTempName); File dstFile = new File(dstTempName); InputStream is = FileHelper.readFileFromSharedStorage(filePath); Files.copy(is, srcFile.toPath(), StandardCopyOption.REPLACE_EXISTING); is.close(); LOG.debug("Copied " + srcFile.length() + "byte file from S3"); CSVParser parser = CSVParser.parse(srcFile, Charset.defaultCharset(), CSVFormat.DEFAULT.withHeader()); Map<String, Integer> headers = parser.getHeaderMap(); if (!headers.containsKey(uniqueKey)) { LOG.debug("Headers found: " + headers); throw new Exception("Couldn't find unique key " + uniqueKey); } String[] headerArray = CsvHelper.getHeaderMapAsArray(parser); int uniqueKeyIndex = headers.get(uniqueKey).intValue(); Map<StringMemorySaver, StringMemorySaver> hmHashes = new ConcurrentHashMap<>(); LOG.debug("Starting hash calculations"); int done = 0; Iterator<CSVRecord> iterator = parser.iterator(); while (iterator.hasNext()) { CSVRecord record = iterator.next(); String uniqueVal = record.get(uniqueKey); Hasher hashser = hf.newHasher(); int size = record.size(); for (int i=0; i<size; i++) { if (i == uniqueKeyIndex) { continue; } String val = record.get(i); hashser.putString(val, Charset.defaultCharset()); } hc = hashser.hash(); String hashString = hc.toString(); if (hmHashes.containsKey(uniqueVal)) { LOG.error("Duplicate unique value [" + uniqueVal + "]"); } hmHashes.put(new StringMemorySaver(uniqueVal), new StringMemorySaver(hashString)); done ++; if (done % 10000 == 0) { LOG.debug("Done " + done); } } parser.close(); LOG.debug("Finished hash calculations for " + hmHashes.size()); //hit DB for each record int threadPoolSize = 10; ThreadPool threadPool = new ThreadPool(threadPoolSize, 1000, "Tester"); Map<String, String> batch = new HashMap<>(); for (StringMemorySaver uniqueVal: hmHashes.keySet()) { StringMemorySaver hash = hmHashes.get(uniqueVal); batch.put(uniqueVal.toString(), hash.toString()); if (batch.size() > TransformConfig.instance().getResourceSaveBatchSize()) { threadPool.submit(new FindHashForBatchCallable(fileUniqueId, batch, hmHashes)); batch = new HashMap<>(); } } if (!batch.isEmpty()) { threadPool.submit(new FindHashForBatchCallable(fileUniqueId, batch, hmHashes)); batch = new HashMap<>(); } threadPool.waitUntilEmpty(); LOG.debug("Finished looking for hashes on DB, filtering down to " + hmHashes.size()); //filter file CSVFormat format = CSVFormat.DEFAULT.withHeader(headerArray); FileOutputStream fos = new FileOutputStream(dstFile); OutputStreamWriter osw = new OutputStreamWriter(fos); BufferedWriter bufferedWriter = new BufferedWriter(osw); CSVPrinter csvPrinter = new CSVPrinter(bufferedWriter, format); parser = CSVParser.parse(srcFile, Charset.defaultCharset(), CSVFormat.DEFAULT.withHeader()); while (iterator.hasNext()) { CSVRecord record = iterator.next(); String uniqueVal = record.get(uniqueKey); if (hmHashes.containsKey(new StringMemorySaver(uniqueVal))) { csvPrinter.printRecord(record); } } parser.close(); csvPrinter.close(); LOG.debug("Finished filtering file with " + hmHashes.size() + " records"); //store hashes in DB batch = new HashMap<>(); for (StringMemorySaver uniqueVal: hmHashes.keySet()) { StringMemorySaver hash = hmHashes.get(uniqueVal); batch.put(uniqueVal.toString(), hash.toString()); if (batch.size() > TransformConfig.instance().getResourceSaveBatchSize()) { threadPool.submit(new SaveHashForBatchCallable(fileUniqueId, batch)); batch = new HashMap<>(); } } if (!batch.isEmpty()) { threadPool.submit(new SaveHashForBatchCallable(fileUniqueId, batch)); batch = new HashMap<>(); } threadPool.waitUntilEmpty(); LOG.debug("Finished saving hashes to DB"); //delete all files srcFile.delete(); dstFile.delete(); LOG.info("Finished Testing Hashed File Filtering for SRCode using " + filePath); } catch (Throwable t) { LOG.error("", t); } } static class SaveHashForBatchCallable implements Callable { private int fileUniqueId; private Map<String, String> batch; public SaveHashForBatchCallable(int fileUniqueId, Map<String, String> batch) { this.fileUniqueId = fileUniqueId; this.batch = batch; } @Override public Object call() throws Exception { try { Connection connection = ConnectionManager.getEdsConnection(); String sql = "INSERT INTO tmp.file_record_hash (file_id, record_id, record_hash) VALUES (?, ?, ?)" + " ON DUPLICATE KEY UPDATE" + " record_hash = VALUES(record_hash)"; PreparedStatement ps = connection.prepareStatement(sql); for (String uniqueId: batch.keySet()) { String hash = batch.get(uniqueId); int col = 1; ps.setInt(col++, fileUniqueId); ps.setString(col++, uniqueId); ps.setString(col++, hash); ps.addBatch(); } ps.executeBatch(); connection.commit(); ps.close(); connection.close(); } catch (Throwable t) { LOG.error("", t); } return null; } } static class FindHashForBatchCallable implements Callable { private int fileUniqueId; private Map<String, String> batch; private Map<StringMemorySaver, StringMemorySaver> hmHashs; public FindHashForBatchCallable(int fileUniqueId, Map<String, String> batch, Map<StringMemorySaver, StringMemorySaver> hmHashs) { this.fileUniqueId = fileUniqueId; this.batch = batch; this.hmHashs = hmHashs; } @Override public Object call() throws Exception { try { Connection connection = ConnectionManager.getEdsConnection(); String sql = "SELECT record_id, record_hash FROM tmp.file_record_hash" + " WHERE file_id = ? AND record_id IN ("; for (int i=0; i<batch.size(); i++) { if (i > 0) { sql += ", "; } sql += "?"; } sql += ")"; PreparedStatement ps = connection.prepareStatement(sql); int col = 1; ps.setInt(col++, fileUniqueId); for (String uniqueId: batch.keySet()) { ps.setString(col++, uniqueId); } ResultSet rs = ps.executeQuery(); Map<String, String> hmResults = new HashMap<>(); while (rs.next()) { String recordId = rs.getString(1); String hash = rs.getString(2); hmResults.put(recordId, hash); } ps.close(); connection.close(); for (String uniqueId: batch.keySet()) { String newHash = batch.get(uniqueId); String dbHash = hmResults.get(uniqueId); if (dbHash != null && dbHash.equals(newHash)) { hmHashs.remove(new StringMemorySaver(uniqueId)); } } } catch (Throwable t) { LOG.error("", t); } return null; } } }
package gov.nih.nci.caintegrator.application.analysis.gp; import java.io.PrintWriter; import java.io.StringWriter; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import gov.nih.nci.caintegrator.security.PublicUserPool; import gov.nih.nci.caintegrator.security.EncryptionUtil; import gov.nih.nci.caintegrator.application.analysis.gp.GenePatternPublicUserPool; import gov.nih.nci.caintegrator.application.util.ApplicationConstants; import gov.nih.nci.caintegrator.application.security.UserInfoBean; public class GenePatternIntegrationHelper { public static String gpPoolString = ":GP30:RBT"; private static Logger logger = Logger.getLogger(GenePatternIntegrationHelper.class); public static String gpHomeURL(HttpServletRequest request) throws Exception { HttpSession session = request.getSession(); String user; UserInfoBean info = (UserInfoBean) session.getAttribute(ApplicationConstants.userInfoBean); if (info != null) { user = info.getUserName(); } else { //for backward compatability user = (String) session.getAttribute("name"); } String publicUser = System.getProperty("gov.nih.nci.caintegrator.gp.publicuser.name"); String encryptKey = System.getProperty("gov.nih.nci.caintegrator.gp.desencrypter.key"); return gpHomeURL(request, user, publicUser, encryptKey); } public static String gpHomeURL(HttpServletRequest request,String userName, String publicUserName, String encryptKey) throws Exception { HttpSession session = request.getSession(); String ticketString = null; String gpserverURL = System.getProperty("gov.nih.nci.caintegrator.gp.server")!=null ? (String)System.getProperty("gov.nih.nci.caintegrator.gp.server") : "localhost:8080"; //default to localhost try { if (userName.equals(publicUserName)){ String gpUser = (String)session.getAttribute(GenePatternPublicUserPool.PUBLIC_USER_NAME); if (gpUser == null){ PublicUserPool pool = GenePatternPublicUserPool.getInstance(); gpUser = pool.borrowPublicUser(); session.setAttribute(GenePatternPublicUserPool.PUBLIC_USER_NAME, gpUser); session.setAttribute(GenePatternPublicUserPool.PUBLIC_USER_POOL, pool); } userName = gpUser; } String urlString = EncryptionUtil.encrypt(userName+ gpPoolString, encryptKey); urlString = URLEncoder.encode(urlString, "UTF-8"); ticketString = gpserverURL+"gp?ticket="+ urlString; logger.debug(ticketString); URL url; try { url = new java.net.URL(ticketString); URLConnection conn = url.openConnection(); final int size = conn.getContentLength(); logger.debug(Integer.toString(size)); } catch (Exception e) { logger.error(e.getMessage()); } } catch (Exception e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); logger.error(sw.toString()); throw new Exception(e.getMessage()); } //ticketString logger.debug(ticketString); return ticketString; } }
package at.ac.ait.ubicity.ubicity.elasticsearch.impl; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.concurrent.ConcurrentLinkedQueue; import net.xeoh.plugins.base.annotations.PluginImplementation; import net.xeoh.plugins.base.annotations.events.Init; import net.xeoh.plugins.base.annotations.events.Shutdown; import org.apache.log4j.Logger; import org.elasticsearch.action.bulk.BulkRequestBuilder; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.index.IndexRequest; import at.ac.ait.ubicity.commons.broker.events.ESMetadata; import at.ac.ait.ubicity.commons.broker.events.ESMetadata.Properties; import at.ac.ait.ubicity.commons.broker.events.EventEntry; import at.ac.ait.ubicity.commons.broker.events.Metadata; import at.ac.ait.ubicity.commons.util.PropertyLoader; import at.ac.ait.ubicity.core.Core; import at.ac.ait.ubicity.ubicity.elasticsearch.ESClient; import at.ac.ait.ubicity.ubicity.elasticsearch.ElasticsearchAddOn; @PluginImplementation public class ElasticsearchAddOnImpl implements ElasticsearchAddOn, Runnable { private String name; private static ESClient client; private final HashSet<String> knownIndizes = new HashSet<String>(); private Core core; private int uniqueId; private static int BULK_SIZE; private static int BULK_TIMEOUT; protected static Logger logger = Logger .getLogger(ElasticsearchAddOnImpl.class); private boolean shutdown = false; ConcurrentLinkedQueue<IndexRequest> requests = new ConcurrentLinkedQueue<IndexRequest>(); @Init public void init() { uniqueId = new Random().nextInt(); PropertyLoader config = new PropertyLoader( ElasticsearchAddOnImpl.class.getResource("/elasticsearch.cfg")); this.name = config.getString("addon.elasticsearch.name"); BULK_SIZE = config.getInt("addon.elasticsearch.bulk_size"); BULK_TIMEOUT = config.getInt("addon.elasticsearch.bulk_timeout"); if (client == null) { String server = config.getString("addon.elasticsearch.host"); int port = config.getInt("addon.elasticsearch.host_port"); String cluster = config.getString("addon.elasticsearch.cluster"); client = new ESClient(server, port, cluster); } core = Core.getInstance(); core.register(this); Thread t = new Thread(this); t.setName("execution context for " + getName()); t.start(); } @Override public final int hashCode() { return uniqueId; } @Override public final boolean equals(Object o) { if (ElasticsearchAddOnImpl.class.isInstance(o)) { ElasticsearchAddOnImpl other = (ElasticsearchAddOnImpl) o; return other.uniqueId == this.uniqueId; } return false; } public void onEvent(EventEntry event, long sequence, boolean endOfBatch) throws Exception { if (event != null) { // shutdown addon if (event.isPoisoned()) { logger.info("ConsumerPoison received"); shutdown(); return; } ESMetadata meta = getMyConfiguration(event.getCurrentMetadata()); String esIdx = meta.getProperties().get( Properties.ES_INDEX.toString()); String esType = meta.getProperties().get( Properties.ES_TYPE.toString()); // Check if Idx exists otherwise create it if (!knownIndizes.contains(esIdx) && !client.indexExists(esIdx)) { client.createIndex(esIdx); knownIndizes.add(esIdx); } IndexRequest ir = new IndexRequest(esIdx, esType); ir.id(event.getId()); ir.source(event.getData()); requests.add(ir); } } private ESMetadata getMyConfiguration(List<Metadata> data) { for (Metadata d : data) { if (this.name.equals(d.getDestination()) && ESMetadata.class.isInstance(d)) { return (ESMetadata) d; } } return null; } public String getName() { return name; } private void closeConnections() { client.close(); } @Shutdown public void shutdown() { shutdown = true; core.deRegister(this); } public void run() { long startTime = System.currentTimeMillis(); BulkRequestBuilder bulk = client.getBulkRequestBuilder(); while (!shutdown) { try { Thread.sleep(100); if (requests.size() > BULK_SIZE || (System.currentTimeMillis() - startTime > BULK_TIMEOUT && requests .size() > 0)) { synchronized (requests) { while (!requests.isEmpty()) { bulk.add(requests.poll()); } } sendBulk(bulk); startTime = System.currentTimeMillis(); } } catch (InterruptedException e) { ; } } shutdown(); closeConnections(); } private void sendBulk(BulkRequestBuilder bulk) { BulkResponse resp = bulk.get(); if (resp.hasFailures()) { logger.warn("Bulk request failed with " + resp.buildFailureMessage()); } } }
package au.com.intercel.ems.energyanalyst.service; import java.io.File; import java.util.Collection; import java.util.Timer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.context.request.async.DeferredResult; import org.springframework.web.multipart.MultipartFile; import au.com.intercel.ems.energyanalyst.domain.Customer; import au.com.intercel.ems.energyanalyst.domain.CustomerRepository; import au.com.intercel.ems.energyanalyst.domain.DailyRecord; import au.com.intercel.ems.energyanalyst.domain.DailyRecordRepository; import au.com.intercel.ems.energyanalyst.utils.CSVEnergyFileProcessor; import au.com.intercel.ems.energyanalyst.utils.EnergyAnalyst; /** * The Class EnergyAnalyticServiceImpl. * * This class implements EnergyAnalyticService interface */ @Component("analyticService") @Transactional public class EnergyAnalyticServiceImpl implements EnergyAnalyticService { /** The customer repository. */ CustomerRepository customerRepository; /** The daily record repository. */ DailyRecordRepository dailyRecordRepository; private Timer timer = new Timer(); /** * Instantiates a new energy analytic service interface. * * @param customerRepository the customer repository * @param dailyRecordRepository the daily record repository */ @Autowired public EnergyAnalyticServiceImpl(CustomerRepository customerRepository, DailyRecordRepository dailyRecordRepository) { this.customerRepository = customerRepository; this.dailyRecordRepository = dailyRecordRepository; } /* (non-Javadoc) * @see au.com.intercel.ems.energyanalyst.service.EnergyAnalyticService#getCustomerData(java.lang.String) */ @Override public Customer getCustomerData(String userId) { return customerRepository.findById(userId); } /* (non-Javadoc) * @see au.com.intercel.ems.energyanalyst.service.EnergyAnalyticService#getCustomerData(java.lang.String, java.lang.String, java.lang.String) */ @Override public Customer getCustomerData(String userId, String startDate, String endDate) { Customer customer = customerRepository.findById(userId); double energyUsagePrediction = EnergyAnalyst.getEnergyUsagePrediction(customer, dailyRecordRepository, startDate, endDate); customer.setEnergyUsagePrediction(energyUsagePrediction); return customer; } /* (non-Javadoc) * @see au.com.intercel.ems.energyanalyst.service.EnergyAnalyticService#importEnergyData(org.springframework.web.multipart.MultipartFile) */ @Override public String importEnergyDataBlocking(MultipartFile file) { String status = ""; try{ // save file File savedFile = CSVEnergyFileProcessor.save(file); // verify file File verifiedFile = CSVEnergyFileProcessor.verify(savedFile); //read file and load into db CSVEnergyFileProcessor.load2Db(verifiedFile, customerRepository, dailyRecordRepository); status = "File " + file.getOriginalFilename() + " saved"; } catch (Exception ex){ ex.printStackTrace(); status = ex.toString(); } return status; } /* (non-Javadoc) * @see au.com.intercel.ems.energyanalyst.service.EnergyAnalyticService#getEnergyData(java.lang.String) */ @Override public Collection<DailyRecord> getEnergyData(String userId) { return dailyRecordRepository.findFirst7ByUidOrderByDateDesc(userId); } /* (non-Javadoc) * @see au.com.intercel.ems.energyanalyst.service.EnergyAnalyticService#importEnergyDataNonBlocking(org.springframework.web.multipart.MultipartFile) */ @Override public String importEnergyDataNonBlocking(MultipartFile file) { String status = ""; try{ // create the task EnergyAnalyticCSVFileProcessor task = new EnergyAnalyticCSVFileProcessor(file, customerRepository, dailyRecordRepository); // start the scheduled task now timer.schedule(task, 0); status = file.getOriginalFilename() + " uploaded successfully."; } catch (Exception ex){ ex.printStackTrace(); status = ex.toString(); } return status; } }
package todods.TodoDS.js; import net.java.html.js.JavaScriptBody; public final class Dialogs { private Dialogs() { } }
package com.censoredsoftware.Demigods.Episodes.Demo.Deity.Insignian; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.bukkit.*; import org.bukkit.block.BlockFace; import org.bukkit.entity.*; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityChangeBlockEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.scheduler.BukkitRunnable; import com.censoredsoftware.Demigods.Engine.Demigods; import com.censoredsoftware.Demigods.Engine.Object.Ability.Ability; import com.censoredsoftware.Demigods.Engine.Object.Ability.AbilityInfo; import com.censoredsoftware.Demigods.Engine.Object.Ability.Devotion; import com.censoredsoftware.Demigods.Engine.Object.Deity.Deity; import com.censoredsoftware.Demigods.Engine.Object.Deity.DeityInfo; import com.censoredsoftware.Demigods.Engine.Object.Mob.TameableWrapper; import com.censoredsoftware.Demigods.Engine.Object.Player.PlayerCharacter; import com.censoredsoftware.Demigods.Engine.Object.Player.PlayerWrapper; import com.censoredsoftware.Demigods.Engine.Utility.*; import com.google.common.collect.Lists; import com.google.common.collect.Sets; public class DrD1sco extends Deity { private static String name = "DrD1sco", alliance = "Insignian", permission = "demigods.insignian.disco"; private static ChatColor color = ChatColor.DARK_PURPLE; private static Set<Material> claimItems = new HashSet<Material>() { { add(Material.DIRT); } }; private static List<String> lore = new ArrayList<String>() { { add(" "); add(ChatColor.AQUA + " Demigods > " + ChatColor.RESET + color + name); add(ChatColor.RESET + " add(ChatColor.YELLOW + " Claim Items:"); for(Material item : claimItems) { add(ChatColor.GRAY + " " + UnicodeUtility.rightwardArrow() + " " + ChatColor.WHITE + item.name()); } add(ChatColor.YELLOW + " Abilities:"); } }; private static Type type = Type.DEMO; private static Set<Ability> abilities = new HashSet<Ability>() { { add(new RainbowWalking()); add(new RainbowHorse()); add(new Discoball()); } }; public DrD1sco() { super(new DeityInfo(name, alliance, permission, color, claimItems, lore, type), abilities); } protected static void playRandomNote(Location location, float volume) { location.getWorld().playSound(location, Sound.NOTE_BASS_GUITAR, volume, (float) ((double) MiscUtility.generateIntRange(5, 10) / 10.0)); } } class RainbowWalking extends Ability { private static String deity = "DrD1sco", name = "Rainbow Walking", command = null, permission = "demigods.insignian.disco"; private static int cost = 0, delay = 0, repeat = 5; private static AbilityInfo info; private static List<String> details = new ArrayList<String>() { { add(ChatColor.GRAY + " " + UnicodeUtility.rightwardArrow() + " " + ChatColor.WHITE + "Spread the disco while sneaking."); } }; private static Devotion.Type type = Devotion.Type.STEALTH; protected RainbowWalking() { super(info = new AbilityInfo(deity, name, command, permission, cost, delay, repeat, details, type), null, new BukkitRunnable() { @Override public void run() { for(Player online : Bukkit.getOnlinePlayers()) { if(Deity.canUseDeitySilent(online, "DrD1sco") && online.isSneaking() && !online.isFlying() && !ZoneUtility.zoneNoPVP(online.getLocation()) && !StructureUtility.isTrespassingInNoGriefingZone(online)) doEffect(online, true); else if(Deity.canUseDeitySilent(online, "DrD1sco")) doEffect(online, false); } } private void doEffect(Player player, boolean effect) { for(Entity entity : player.getNearbyEntities(30, 30, 30)) { if(!(entity instanceof Player)) continue; Player viewing = (Player) entity; if(effect) { viewing.hidePlayer(player); rainbow(player, viewing); } else viewing.showPlayer(player); } if(effect) { rainbow(player, player); DrD1sco.playRandomNote(player.getLocation(), 0.5F); } } }); } private static void rainbow(Player disco, Player player) { player.sendBlockChange(disco.getLocation().getBlock().getRelative(BlockFace.DOWN).getLocation(), Material.WOOL, (byte) MiscUtility.generateIntRange(0, 15)); if(SpigotUtility.runningSpigot()) SpigotUtility.playParticle(disco.getLocation(), Effect.COLOURED_DUST, 1, 0, 1, 10F, 100, 30); } } class RainbowHorse extends Ability { private static String deity = "DrD1sco", name = "Horse of a Different Color", command = null, permission = "demigods.insignian.disco"; private static int cost = 0, delay = 0, repeat = 200; private static AbilityInfo info; private static List<String> details = new ArrayList<String>() { { add(ChatColor.GRAY + " " + UnicodeUtility.rightwardArrow() + " " + ChatColor.WHITE + "All of you horse are belong to us."); } }; private static Devotion.Type type = Devotion.Type.PASSIVE; protected RainbowHorse() { super(info = new AbilityInfo(deity, name, command, permission, cost, delay, repeat, details, type), null, new BukkitRunnable() { @Override public void run() { for(TameableWrapper horse : TameableWrapper.findByType(EntityType.HORSE)) { if(horse.getDeity().getInfo().getName().equals("DrD1sco") && horse.getEntity() != null && !horse.getEntity().isDead()) { ((Horse) horse.getEntity()).setColor(getRandomHorseColor()); } } } private Horse.Color getRandomHorseColor() { return Lists.newArrayList(Horse.Color.values()).get(MiscUtility.generateIntRange(0, 5)); } }); } } class Discoball extends Ability { private static String deity = "DrD1sco", name = "Discoball of Doom", command = "discoball", permission = "demigods.insignian.disco"; private static int cost = 30, delay = 0, repeat = 3; private static AbilityInfo info; private static List<String> details = new ArrayList<String>() { { add(ChatColor.GRAY + " " + UnicodeUtility.rightwardArrow() + " " + ChatColor.GREEN + "/discoball" + ChatColor.WHITE + " - Spread the music while causing destruction."); } }; private static Devotion.Type type = Devotion.Type.ULTIMATE; private static Set<FallingBlock> discoBalls = Sets.newHashSet(); protected Discoball() { super(info = new AbilityInfo(deity, name, command, permission, cost, delay, repeat, details, type), new Listener() { @EventHandler(priority = EventPriority.HIGHEST) public void onPlayerInteract(PlayerInteractEvent interactEvent) { // Set variables Player player = interactEvent.getPlayer(); PlayerCharacter character = PlayerWrapper.getPlayer(player).getCurrent(); if(!Ability.isLeftClick(interactEvent)) return; if(!Deity.canUseDeitySilent(player, deity)) return; if(character.getMeta().isEnabledAbility(name)) { if(!PlayerCharacter.isCooledDown(character, name, false)) return; discoBall(player); } } @EventHandler(priority = EventPriority.HIGHEST) public void onBlockChange(EntityChangeBlockEvent changeEvent) { if(changeEvent.getEntityType() != EntityType.FALLING_BLOCK) return; changeEvent.getBlock().setType(Material.AIR); FallingBlock block = (FallingBlock) changeEvent.getEntity(); if(discoBalls.contains(block)) { discoBalls.remove(block); block.remove(); } } }, new BukkitRunnable() { @Override public void run() { for(FallingBlock block : discoBalls) { if(block != null) { Location location = block.getLocation(); DrD1sco.playRandomNote(location, 2F); sparkleSparkle(location); destoryNearby(location); } } } }); } private static void discoBall(final Player player) { // Set variables PlayerCharacter character = PlayerWrapper.getPlayer(player).getCurrent(); if(!Ability.doAbilityPreProcess(player, name, cost, info)) return; character.getMeta().subtractFavor(cost); PlayerCharacter.setCoolDown(character, name, System.currentTimeMillis() + delay); balls(player); player.sendMessage(ChatColor.YELLOW + "Dance!"); Bukkit.getScheduler().scheduleSyncDelayedTask(Demigods.plugin, new BukkitRunnable() { @Override public void run() { player.sendMessage(ChatColor.RED + "B" + ChatColor.GOLD + "o" + ChatColor.YELLOW + "o" + ChatColor.GREEN + "g" + ChatColor.AQUA + "i" + ChatColor.LIGHT_PURPLE + "e" + ChatColor.DARK_PURPLE + " W" + ChatColor.BLUE + "o" + ChatColor.RED + "n" + ChatColor.GOLD + "d" + ChatColor.YELLOW + "e" + ChatColor.GREEN + "r" + ChatColor.AQUA + "l" + ChatColor.LIGHT_PURPLE + "a" + ChatColor.DARK_PURPLE + "n" + ChatColor.BLUE + "d" + ChatColor.RED + "!"); } }, 40); } private static void balls(Player player) { for(Location location : MiscUtility.getCirclePoints(new Location(player.getWorld(), player.getLocation().getBlockX(), player.getLocation().getBlockY() + 120 < 256 ? player.getLocation().getBlockY() + 120 : 256, player.getLocation().getBlockZ()), 3.0, 50)) { spawnBall(location); } } private static void spawnBall(Location location) { final FallingBlock discoBall = location.getWorld().spawnFallingBlock(location, Material.GLOWSTONE, (byte) 0); discoBalls.add(discoBall); Bukkit.getScheduler().scheduleSyncDelayedTask(Demigods.plugin, new BukkitRunnable() { @Override public void run() { discoBalls.remove(discoBall); discoBall.remove(); } }, 600); } private static void sparkleSparkle(Location location) { if(SpigotUtility.runningSpigot()) SpigotUtility.playParticle(location, Effect.COLOURED_DUST, 1, 1, 1, 10F, 100, 30); } private static void destoryNearby(Location location) { location.getWorld().createExplosion(location, 2F); } }
package com.github.mikhailerofeev.mars.calendar.model.values; import org.joda.time.*; import sun.reflect.generics.reflectiveObjects.NotImplementedException; import java.util.Date; public class PlanetDateTime { private final DateTime timePoint; private final DateTime epoch; private PlanetCalendar calendar = null; private Duration solDuration; private Integer year = null; private Integer weekNum = null; private Integer monthNum = null; // from 1 ... private Integer day = null; // from 1 ... private Integer hour = null; // from 1 ... @SuppressWarnings("UnusedDeclaration") private Integer minute = null; // from 1 ... @SuppressWarnings("UnusedDeclaration") private Integer second = null; // from 1 ... @SuppressWarnings("UnusedDeclaration") public PlanetDateTime() { this.timePoint = DateTime.now(); this.epoch = new DateTime(0); } @SuppressWarnings("UnusedDeclaration") public PlanetDateTime(DateTime timePoint) { this.timePoint = timePoint; this.epoch = new DateTime(0); } @SuppressWarnings("UnusedDeclaration") public PlanetDateTime(DateTime timePoint, DateTime epoch) { this.timePoint = timePoint; this.epoch = epoch; } @SuppressWarnings("UnusedDeclaration") public PlanetDateTime(long unixTimeStamp) { this.timePoint = new DateTime(unixTimeStamp); this.epoch = new DateTime(0); } @SuppressWarnings("UnusedDeclaration") public PlanetDateTime(long unixTimeStamp, long epoch) { this.timePoint = new DateTime(unixTimeStamp); this.epoch = new DateTime(epoch); } public PlanetDateTime(DateTime timePoint, DateTime epoch, PlanetCalendar calendar, Duration solDuration) { this.timePoint = timePoint; this.epoch = epoch; this.calendar = calendar; this.solDuration = solDuration; } @SuppressWarnings("UnusedDeclaration") public Duration timeSinceEpoch() { return new Duration(epoch, timePoint); } private double solsSinceEpoch() { return timeSinceEpoch().getMillis() / solDuration.getMillis(); } public long wholeSolsSinceEpoch() { return (long)solsSinceEpoch(); } public Duration durationSinceSolStart() { return new Duration(timeSinceEpoch().getMillis() % solDuration.getMillis()); } @SuppressWarnings("UnusedDeclaration") public DateTime toTerrestrial() { return timePoint; } /** * Determines the (terrestrial) duration of the specific year * @param year * @return */ public Duration yearDuration(int year) { return new Duration(solDuration.getMillis() * calendar.solsInYear(year)); } public Duration monthDuration(int year, int month) { return new Duration(solDuration.getMillis() * calendar.solsInMonth(year, month)); } /** * returns the year in the natural form * @return */ public int getYear() { if (year == null) { // todo: optimization // year = 0; // MutableDateTime timePoint = new MutableDateTime(this.epoch); // while (timePoint.isBefore(this.timePoint)) { // ++year; // timePoint.add(yearDuration(year)); int solsSincePeriod = (int)(wholeSolsSinceEpoch() % (long)calendar.solsInLeapPeriod()); int periodsSinceEpoch = (int)(wholeSolsSinceEpoch() / (long)calendar.solsInLeapPeriod()); year = periodsSinceEpoch * calendar.getLeapPeriod().size(); int solsElapsed = 0; // may need to be changed to 1 (instead of 0) while (solsElapsed < solsSincePeriod) { solsElapsed += calendar.solsInYear(0); ++year; } --year; // because we return the nearest PREVIOUS year, not the NEXT one (!!!) } return year; } /** * returns the the month number starting from 1 * @return */ public int getMonthNum() { if (monthNum == null) { // todo: optimization MutableDateTime timePoint = new MutableDateTime(this.epoch); year = getYear(); timePoint.add(yearDuration(year)); monthNum = 0; while (timePoint.isBefore(this.timePoint)) { timePoint.add(monthDuration(year, monthNum)); ++monthNum; } } return monthNum; } @SuppressWarnings("UnusedDeclaration") public PlanetMonth getMonth() { return calendar.getMonths().get(getMonthNum() - 1); } public int getDay() { if (day == null) { // todo: optimization MutableDateTime timePoint = new MutableDateTime(this.epoch); year = getYear(); monthNum = getMonthNum(); timePoint.add(yearDuration(year)); timePoint.add(monthDuration(year, monthNum)); day = 1; while (timePoint.isBefore(this.timePoint)) { ++day; timePoint.add(solDuration); } } return day; } @SuppressWarnings("UnusedDeclaration") public long getHour() { if (hour == null) { return durationSinceSolStart().getStandardHours(); } else { return hour; } } public long getMinute() { if (minute == null) return (durationSinceSolStart().getStandardMinutes() - durationSinceSolStart().getStandardHours() * 60); else { return minute; } } public long getSecond() { if (second == null) return (durationSinceSolStart().getStandardSeconds() - durationSinceSolStart().getStandardHours() * 60 * 60); else { return second; } } public int getWeekNum(){ throw new NotImplementedException(); } }
package com.stratio.streaming.shell.configuration; import org.springframework.beans.factory.annotation.Value; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import com.stratio.streaming.api.IStratioStreamingAPI; import com.stratio.streaming.api.StratioStreamingAPIFactory; @Configuration @PropertySource("classpath:shell.properties") @EnableCaching public class StreamingApiConfiguration { @Value("${kafka.host}") private String kafkaHost; @Value("${kafka.port}") private Integer kafkaPort; @Value("${zookeeper.host}") private String zookeeperHost; @Value("${zookeeper.port}") private Integer zookeeperPort; @Bean public IStratioStreamingAPI stratioStreamingApi() { return StratioStreamingAPIFactory.create().initializeWithServerConfig(kafkaHost, kafkaPort, zookeeperHost, zookeeperPort); } }
package com.vexus2.jenkins.chatwork.jenkinschatworkplugin; import hudson.Extension; import hudson.Launcher; import hudson.model.*; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.BuildStepMonitor; import hudson.tasks.Publisher; import hudson.util.VariableResolver; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.StaplerRequest; import java.io.IOException; import java.io.PrintStream; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ChatworkPublisher extends Publisher { private final String rid; private final String defaultMessage; private static final Pattern pattern = Pattern.compile("\\$\\{(.+)\\}|\\$(.+)\\s?"); private AbstractBuild build; //TODO: private PrintStream logger; // Fields in config.jelly must match the parameter names in the "DataBoundConstructor" @DataBoundConstructor public ChatworkPublisher(String rid, String defaultMessage) { this.rid = rid; this.defaultMessage = (defaultMessage != null) ? defaultMessage : ""; } /** * We'll use this from the <tt>config.jelly</tt>. */ public String getRid() { return rid; } public String getDefaultMessage() { return defaultMessage; } @Override public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) { Boolean result = true; this.build = build; this.logger = listener.getLogger(); try { String message = createMessage(); ChatworkClient chatworkClient = new ChatworkClient(build, getDescriptor().getApikey(), getRid(), getDefaultMessage()); chatworkClient.sendMessage(message); } catch (Exception e) { result = false; listener.getLogger().println(e.getMessage()); } return result; } private String createMessage() throws Exception { String message = this.defaultMessage; Matcher m = pattern.matcher(message); while (m.find()) { // If ${VARNAME} match found, return that group, else return $NoWhiteSpace group String matches = (m.group(1) != null) ? m.group(1) : m.group(2); String globalValue = getValue(matches); if (globalValue != null) { message = message.replaceAll(matches, globalValue); } } return message; } private String getValue(String key) { if (key == null) { return null; } else { VariableResolver buildVariableResolver = build.getBuildVariableResolver(); Object defaultValue = buildVariableResolver.resolve(key); return (defaultValue == null) ? "" : ("payload".equals(key)) ? analyzePayload(defaultValue.toString()) : defaultValue.toString(); } } private String analyzePayload(String parameterDefinition) { JSONObject json = JSONObject.fromObject(parameterDefinition); //TODO: String action = json.getString("action"); StringBuilder message; if (action != null && "opened".equals(action)) { JSONObject pull_request = json.getJSONObject("pull_request"); String title = pull_request.getString("title"); String url = pull_request.getString("url"); String repositoryName = json.getJSONObject("repository").getString("name"); String pusher = pull_request.getJSONObject("user").getString("login"); message = new StringBuilder().append(String.format("%s created Pull Request into %s,\n\n", pusher, repositoryName)); message.append(String.format("\n%s", title)); message.append(String.format("\n%s", url)); } else { String compareUrl = json.getString("compare"); String pusher = json.getJSONObject("pusher").getString("name"); String repositoryName = json.getJSONObject("repository").getString("name"); message = new StringBuilder().append(String.format("%s pushed into %s,\n", pusher, repositoryName)); JSONArray commits = json.getJSONArray("commits"); int size = commits.size(); for (int i = 0; i < size; i++) { JSONObject value = (JSONObject) commits.get(i); String s = value.getString("message"); message.append(String.format("- %s \n", (s.length() > 50) ? s.substring(0, 50) + "..." : s)); } message.append(String.format("\n%s", compareUrl)); } return message.toString(); } @Override public DescriptorImpl getDescriptor() { return (DescriptorImpl) super.getDescriptor(); } public BuildStepMonitor getRequiredMonitorService() { return BuildStepMonitor.BUILD; } * See <tt>src/main/resource/com.vexus2.jenkins.chatwork.jenkinschatworkplugin/ChatworkPublisher/*.jelly</tt> * for the actual HTML fragment for the configuration screen. */ @Extension // This indicates to Jenkins that this is an implementation of an extension point. public static final class DescriptorImpl extends BuildStepDescriptor<Publisher> { private String apikey; public String getApikey() { return apikey; } public DescriptorImpl() { load(); } public boolean isApplicable(Class<? extends AbstractProject> aClass) { return true; } public String getDisplayName() { return "Notify the ChatWork"; } @Override public boolean configure(StaplerRequest req, JSONObject formData) throws FormException { apikey = formData.getString("apikey"); save(); return super.configure(req, formData); } } }
package de.unibi.cebitec.bibigrid.meta.googlecloud; import com.google.cloud.compute.*; import com.jcraft.jsch.ChannelExec; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; import de.unibi.cebitec.bibigrid.meta.CreateCluster; import de.unibi.cebitec.bibigrid.model.Configuration; import de.unibi.cebitec.bibigrid.util.DeviceMapper; import de.unibi.cebitec.bibigrid.util.JSchLogger; import de.unibi.cebitec.bibigrid.util.SshFactory; import de.unibi.cebitec.bibigrid.util.UserDataCreator; import org.apache.commons.codec.binary.Base64; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Method; import java.nio.ByteBuffer; import java.util.*; import static de.unibi.cebitec.bibigrid.util.ImportantInfoOutputFilter.I; import static de.unibi.cebitec.bibigrid.util.VerboseOutputFilter.V; /** * Implementation of the general CreateCluster interface for a Google based cluster. * * @author mfriedrichs(at)techfak.uni-bielefeld.de */ public class CreateClusterGoogleCloud implements CreateCluster<CreateClusterGoogleCloud, CreateClusterEnvironmentGoogleCloud> { private static final Logger log = LoggerFactory.getLogger(CreateClusterGoogleCloud.class); private static final String PREFIX = "bibigrid-"; static final String SUBNET_PREFIX = PREFIX + "subnet-"; private static final String MASTER_SSH_USER = "ubuntu"; private final Configuration conf; private Compute compute; private Instance masterInstance; private List<Instance> slaveInstances; private String base64MasterUserData; private List<NetworkInterface> masterNetworkInterfaces, slaveNetworkInterfaces; private CreateClusterEnvironmentGoogleCloud environment; private String bibigridid, username; private String clusterId; private DeviceMapper slaveDeviceMapper; public CreateClusterGoogleCloud(final Configuration conf) { this.conf = conf; } public CreateClusterEnvironmentGoogleCloud createClusterEnvironment() { compute = GoogleCloudUtils.getComputeService(conf); // Cluster ID is a cut down base64 encoded version of a random UUID: UUID clusterIdUUID = UUID.randomUUID(); ByteBuffer bb = ByteBuffer.wrap(new byte[16]); bb.putLong(clusterIdUUID.getMostSignificantBits()); bb.putLong(clusterIdUUID.getLeastSignificantBits()); String clusterIdBase64 = Base64.encodeBase64URLSafeString(bb.array()).replace("-", "").replace("_", ""); int len = clusterIdBase64.length() >= 15 ? 15 : clusterIdBase64.length(); clusterId = clusterIdBase64.substring(0, len); bibigridid = "bibigrid-id:" + clusterId; username = "user:" + conf.getUser(); log.debug("cluster id: {}", clusterId); return environment = new CreateClusterEnvironmentGoogleCloud(this); } public CreateClusterGoogleCloud configureClusterMasterInstance() { // done for master. More volume description later when master is running // preparing blockdevicemappings for master Map<String, String> masterSnapshotToMountPointMap = conf.getMasterMounts(); int ephemerals = conf.getMasterInstanceType().getSpec().ephemerals; DeviceMapper masterDeviceMapper = new DeviceMapper(conf.getMode(), masterSnapshotToMountPointMap, ephemerals); /* TODO masterDeviceMappings = new ArrayList<>(); // create Volumes first if (!conf.getMasterMounts().isEmpty()) { log.info(V, "Defining master volumes"); masterDeviceMappings = createBlockDeviceMappings(masterDeviceMapper); } List<BlockDeviceMapping> ephemeralList = new ArrayList<>(); for (int i = 0; i < conf.getMasterInstanceType().getSpec().ephemerals; ++i) { BlockDeviceMapping temp = new BlockDeviceMapping(); String virtualName = "ephemeral" + i; String deviceName = "/dev/sd" + ephemeral(i); temp.setVirtualName(virtualName); temp.setDeviceName(deviceName); ephemeralList.add(temp); } masterDeviceMappings.addAll(ephemeralList); */ base64MasterUserData = UserDataCreator.masterUserData(masterDeviceMapper, conf, environment.getKeypair()); log.info(V, "Master UserData:\n {}", new String(Base64.decodeBase64(base64MasterUserData))); // create NetworkInterfaceSpecification for MASTER instance with FIXED internal IP and public ip masterNetworkInterfaces = new ArrayList<>(); NetworkInterface.Builder inis = NetworkInterface.newBuilder(environment.getSubnet().getNetwork()); inis.setSubnetwork(environment.getSubnet().getSubnetworkId()) .setAccessConfigurations(NetworkInterface.AccessConfig.newBuilder() .setType(NetworkInterface.AccessConfig.Type.ONE_TO_ONE_NAT) .setName("external-nat") .build()); // Currently only accessible through reflection. Should be public according to docs... try { Method m = NetworkInterface.Builder.class.getDeclaredMethod("setNetworkIp", String.class); m.setAccessible(true); m.invoke(inis, environment.getMasterIP()); } catch (Exception e) { e.printStackTrace(); } masterNetworkInterfaces.add(inis.build()); // add eth0 slaveNetworkInterfaces = new ArrayList<>(); inis = NetworkInterface.newBuilder(environment.getSubnet().getNetwork()); inis.setSubnetwork(environment.getSubnet().getSubnetworkId()); // TODO: private-ip-google-accesss? // TODO .withAssociatePublicIpAddress(conf.isPublicSlaveIps()) slaveNetworkInterfaces.add(inis.build()); return this; } public CreateClusterGoogleCloud configureClusterSlaveInstance() { //now defining Slave Volumes Map<String, String> snapShotToSlaveMounts = conf.getSlaveMounts(); int ephemerals = conf.getSlaveInstanceType().getSpec().ephemerals; slaveDeviceMapper = new DeviceMapper(conf.getMode(), snapShotToSlaveMounts, ephemerals); /* TODO slaveBlockDeviceMappings = new ArrayList<>(); // configure volumes first ... if (!snapShotToSlaveMounts.isEmpty()) { log.info(V, "configure slave volumes"); slaveBlockDeviceMappings = createBlockDeviceMappings(slaveDeviceMapper); } // configure ephemeral devices List<BlockDeviceMapping> ephemeralList = new ArrayList<>(); if (ephemerals > 0) { for (int i = 0; i < ephemerals; ++i) { BlockDeviceMapping temp = new BlockDeviceMapping(); String virtualName = "ephemeral" + i; String deviceName = "/dev/sd" + ephemeral(i); temp.setVirtualName(virtualName); temp.setDeviceName(deviceName); ephemeralList.add(temp); } } slaveBlockDeviceMappings.addAll(ephemeralList); */ return this; } public boolean launchClusterInstances() { log.info("Requesting master instance ..."); String zone = conf.getAvailabilityZone(); String masterInstanceName = PREFIX + "master-" + clusterId; InstanceInfo.Builder masterBuilder = GoogleCloudUtils.getInstanceBuilder(conf.getMasterImage(), zone, masterInstanceName, conf.getMasterInstanceType().getValue()) .setNetworkInterfaces(masterNetworkInterfaces) .setTags(Tags.of(bibigridid, username, "Name:" + masterInstanceName)) .setMetadata(Metadata.newBuilder().add("startup-script", base64MasterUserData).build()); // TODO .withBlockDeviceMappings(masterDeviceMappings) // TODO .withKeyName(conf.getKeypair()) GoogleCloudUtils.setInstanceSchedulingOptions(masterBuilder, conf.isUseSpotInstances()); // Waiting for master instance to run log.info("Waiting for master instance to finish booting ..."); Operation createMasterOperation = compute.create(masterBuilder.build()); masterInstance = waitForInstances(Collections.singletonList(createMasterOperation)).get(0); log.info(I, "Master instance is now running!"); waitForStatusCheck("master", Collections.singletonList(masterInstance)); String masterPrivateIp = GoogleCloudUtils.getInstancePrivateIp(masterInstance); String masterPublicIp = GoogleCloudUtils.getInstancePublicIp(masterInstance); String masterDnsName = GoogleCloudUtils.getInstanceFQDN(masterInstance); // run slave instances and supply userdata if (conf.getSlaveInstanceCount() > 0) { String base64SlaveUserData = UserDataCreator.forSlave(masterPrivateIp, masterDnsName, slaveDeviceMapper, conf, environment.getKeypair()); // Google doesn't use base64 encoded startup scripts. Just use plain text base64SlaveUserData = new String(Base64.decodeBase64(base64SlaveUserData)); log.info(V, "Slave Userdata:\n{}", base64SlaveUserData); List<Operation> slaveInstanceOperations = new ArrayList<>(); for (int i = 0; i < conf.getSlaveInstanceCount(); i++) { String slaveInstanceName = PREFIX + "slave-" + clusterId; String slaveInstanceId = PREFIX + "slave" + i + "-" + clusterId; InstanceInfo.Builder slaveBuilder = GoogleCloudUtils.getInstanceBuilder(conf.getSlaveImage(), zone, slaveInstanceId, conf.getSlaveInstanceType().getValue()) .setNetworkInterfaces(slaveNetworkInterfaces) .setTags(Tags.of(bibigridid, username, "Name:" + slaveInstanceName)) .setMetadata(Metadata.newBuilder().add("startup-script", base64SlaveUserData).build()); // TODO .withBlockDeviceMappings(slaveBlockDeviceMappings) // TODO .withKeyName(this.config.getKeypair()) GoogleCloudUtils.setInstanceSchedulingOptions(masterBuilder, conf.isUseSpotInstances()); Operation createSlaveOperation = compute.create(slaveBuilder.build()); slaveInstanceOperations.add(createSlaveOperation); } log.info("Waiting for slave instance(s) to finish booting ..."); slaveInstances = waitForInstances(slaveInstanceOperations); log.info(I, "Slave instance(s) is now running!"); } else { log.info("No Slave instance(s) requested!"); } // post configure master configureMaster(); // Human friendly output StringBuilder sb = new StringBuilder(); sb.append("\n You might want to set the following environment variable:\n\n"); sb.append("export BIBIGRID_MASTER=").append(masterPublicIp).append("\n\n"); sb.append("You can then log on the master node with:\n\n") .append("ssh -i ") .append(conf.getIdentityFile()) .append(" ubuntu@$BIBIGRID_MASTER\n\n"); sb.append("The cluster id of your started cluster is : ") .append(clusterId) .append("\n\n"); sb.append("The can easily terminate the cluster at any time with :\n") .append("./bibigrid -t ").append(clusterId).append(" "); if (conf.isAlternativeConfigFile()) { sb.append("-o ").append(conf.getAlternativeConfigPath()).append(" "); } sb.append("\n"); log.info(sb.toString()); // Grid Properties file if (conf.getGridPropertiesFile() != null) { Properties gp = new Properties(); gp.setProperty("BIBIGRID_MASTER", masterPublicIp); gp.setProperty("IdentityFile", conf.getIdentityFile().toString()); gp.setProperty("clusterId", clusterId); if (conf.isAlternativeConfigFile()) { gp.setProperty("AlternativeConfigFile", conf.getAlternativeConfigPath()); } try { gp.store(new FileOutputStream(conf.getGridPropertiesFile()), "Autogenerated by BiBiGrid"); } catch (IOException e) { log.error(I, "Exception while creating grid properties file : " + e.getMessage()); } } return true; } private void waitForStatusCheck(String type, List<Instance> instances) { log.info("Waiting for Status Checks on {} ...", type); for (Instance instance : instances) { do { InstanceInfo.Status status = instance.getStatus(); log.debug("Status of {} instance: " + status, type); if (status == InstanceInfo.Status.RUNNING) { break; } else { log.info(V, "..."); sleep(10); } } while (true); } log.info(I, "Status checks successful."); } private List<Instance> waitForInstances(List<Operation> operations) { if (operations.isEmpty()) { log.error("No instances found"); return new ArrayList<>(); } List<Instance> returnList = new ArrayList<>(); for (Operation operation : operations) { while (!operation.isDone()) { log.info(V, "..."); sleep(1); } operation = operation.reload(); if (operation.getErrors() == null) { returnList.add(compute.getInstance(InstanceId.of(conf.getAvailabilityZone(), operation.getTargetId()))); } else { log.error("Creation of instance failed: {}", operation.getErrors()); break; } } return returnList; } private void sleep(int seconds) { try { Thread.sleep(seconds * 1000); } catch (InterruptedException ie) { log.error("Thread.sleep interrupted!"); } } private void configureMaster() { JSch ssh = new JSch(); JSch.setLogger(new JSchLogger()); // Building Command log.info("Now configuring ..."); String execCommand = SshFactory.buildSshCommandGoogleCloud(clusterId, getConfig(), masterInstance, slaveInstances); log.info(V, "Building SSH-Command : {}", execCommand); boolean uploaded = false; boolean configured = false; int ssh_attempts = 25; // TODO attempts while (!configured && ssh_attempts > 0) { try { ssh.addIdentity(getConfig().getIdentityFile().toString()); log.info("Trying to connect to master ({})...", ssh_attempts); Thread.sleep(4000); // Create new Session to avoid packet corruption. Session sshSession = SshFactory.createNewSshSession(ssh, masterInstance.getNetworkInterfaces().get(0) .getAccessConfigurations().get(0) .getNatIp(), MASTER_SSH_USER, getConfig().getIdentityFile()); // Start connect attempt sshSession.connect(); log.info("Connected to master!"); //if (!uploaded || ssh_attempts > 0) { // String remoteDirectory = "/home/ubuntu/.ssh"; // String filename = "id_rsa"; // String localFile = getConfiguration().getIdentityFile().toString(); // log.info(V, "Uploading key"); // ChannelSftp channelPut = (ChannelSftp) sshSession.openChannel("sftp"); // channelPut.connect(); // channelPut.cd(remoteDirectory); // channelPut.put(new FileInputStream(localFile), filename); // channelPut.disconnect(); // log.info(V, "Upload done"); // uploaded = true; ChannelExec channel = (ChannelExec) sshSession.openChannel("exec"); BufferedReader stdout = new BufferedReader(new InputStreamReader(channel.getInputStream())); BufferedReader stderr = new BufferedReader(new InputStreamReader(channel.getErrStream())); channel.setCommand(execCommand); log.info(V, "Connecting ssh channel..."); channel.connect(); String lineout = null, lineerr = null; while (((lineout = stdout.readLine()) != null) || ((lineerr = stderr.readLine()) != null)) { if (lineout != null) { if (lineout.contains("CONFIGURATION_FINISHED")) { configured = true; } log.info(V, "SSH: {}", lineout); } //if (lineerr != null) { if (lineerr != null && !configured) { log.error(V, "SSH: {}", lineerr); } //if (channel.isClosed() || configured) { if (channel.isClosed() && configured) { log.info(V, "SSH: exit-status: {}", channel.getExitStatus()); configured = true; } Thread.sleep(2000); } if (configured) { channel.disconnect(); sshSession.disconnect(); } } catch (IOException | JSchException e) { ssh_attempts if (ssh_attempts == 0) { log.error(V, "SSH: {}", e); } //try { // Thread.sleep(2000); //} catch (InterruptedException ex) { // log.error("Interrupted ..."); } catch (InterruptedException ex) { log.error("Interrupted ..."); } } log.info(I, "Master instance has been configured."); } public Configuration getConfig() { return conf; } public Compute getCompute() { return compute; } String getClusterId() { return clusterId; } }
package edu.itla.sistemacomisiones.database.controlador; import edu.itla.sistemacomisiones.database.model.Direccion; import edu.itla.sistemacomisiones.database.model.Inmueble; import edu.itla.sistemacomisiones.database.model.Moneda; import edu.itla.sistemacomisiones.database.model.TipoInmueble; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; public class InmuebleControlador extends Controlador<Inmueble>{ private static InmuebleControlador controlador; public static InmuebleControlador getInstancia (){ if (controlador == null){ controlador = new InmuebleControlador(); } return controlador; } private InmuebleControlador() { super("inmuebles"); } @Override public Inmueble crear(Inmueble obj) { try { PreparedStatement st = con.prepareStatement("INSERT INTO "+ tablaBaseDeDatos + " (`detalles`, `precio`, `superficie`, `dormitorios`, `tipo_inmuebles_id`," + " `direccion_id`, `moneda_id`, `comision`) VALUES (?, ?, ?, ?, ?, ?, ?, ?); " ); st.setString(1, obj.getDetalles()); st.setDouble(2, obj.getPrecio()); st.setString(3, obj.getSuperficie()); st.setInt(4, obj.getDormitorios()); st.setInt(5, obj.getTipoInmueble().getId()); st.setInt(6, obj.getDireccion().getId()); st.setInt(7, obj.getMoneda().getId()); st.setDouble(8, obj.getComision()); obj.setId(st.executeUpdate()); } catch (SQLException ex) { Logger.getLogger(Controlador.class.getName()).log(Level.SEVERE,"crear" , ex); } return obj; } @Override public Inmueble actualizar(Inmueble obj) { try { PreparedStatement st = con.prepareStatement("UPDATE "+ tablaBaseDeDatos + " SET `detalles`=?, `precio`=?, `superficie`=?, `dormitorios`=?," + " `tipo_inmuebles_id`=?, `direccion_id`=?, `moneda_id`=?," + " comision=? WHERE `id`=?;" ); st.setString(1, obj.getDetalles()); st.setDouble(2, obj.getPrecio()); st.setString(3, obj.getSuperficie()); st.setInt(4, obj.getDormitorios()); st.setInt(5, obj.getTipoInmueble().getId()); st.setInt(6, obj.getDireccion().getId()); st.setInt(7, obj.getMoneda().getId()); st.setDouble(8, obj.getComision()); st.setInt(9, obj.getId()); st.executeUpdate(); } catch (SQLException ex) { Logger.getLogger(Controlador.class.getName()).log(Level.SEVERE,"actulizar" , ex); } return obj; } @Override public Inmueble buscar(String term) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public Inmueble crearDeResultSet(ResultSet rs) throws SQLException { TipoInmueble tipoInmueble = TipoInmuebleControlador.getInstancia() .obtenerPorId(rs.getInt("tipo_inmuebles_id")); Direccion direccion = DireccionControlador.getInstancia() .obtenerPorId(rs.getInt("direccion_id")); Moneda moneda = MonedaControlador.getInstancia() .obtenerPorId(rs.getInt("moneda_id")); return new Inmueble(rs.getInt("id"), rs.getString("detalles"), rs.getDouble("precio"),rs.getString("superficie"), rs.getInt("dormitorios"),tipoInmueble,direccion, moneda, rs.getDouble("comision_venta")); } }
import org.apache.thrift.TException; import org.apache.thrift.transport.TTransport; import org.apache.thrift.transport.TSocket; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TProtocol; // Generated code import loadbalancer.*; public class LoadBalancerHandler implements LoadBalancer.Iface { private Server server; public LoadBalancerHandler (Server server) { this.server = server; } public void load (String str) { System.out.println ("load()"); System.out.println (str); Utils.prependStringToFileUsingEd(str, server.getFileName()); } }
package org.echocat.unittest.utils.rules; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import static java.lang.Character.isLetterOrDigit; import static java.nio.file.FileVisitResult.CONTINUE; import static java.nio.file.Files.*; import static java.util.Objects.requireNonNull; public abstract class TemporaryDirectoryBasedRuleSupport<T extends TemporaryDirectoryBasedRuleSupport<T>> implements TestRule { @Nullable private Path baseDirectory; private boolean failOnProblemsWhileCleanup = true; public boolean isFailOnProblemsWhileCleanup() { return failOnProblemsWhileCleanup; } @Nonnull public T setFailOnProblemsWhileCleanup(boolean failOnProblemsWhileCleanup) { this.failOnProblemsWhileCleanup = failOnProblemsWhileCleanup; //noinspection unchecked return (T) this; } @Override public Statement apply(@Nonnull Statement base, @Nonnull Description description) { return new Statement() { @Override public void evaluate() throws Throwable { TemporaryDirectoryBasedRuleSupport.this.evaluate(base, description); } }; } protected void evaluate(@Nonnull Statement base, @Nonnull Description description) throws Throwable { final Path baseDirectory = generateTemporaryFolderFor(description); TemporaryDirectoryBasedRuleSupport.this.baseDirectory = baseDirectory; try { evaluate(base, description, baseDirectory); } finally { TemporaryDirectoryBasedRuleSupport.this.baseDirectory = null; deleteDirectory(baseDirectory); } } protected abstract void evaluate(@Nonnull Statement base, @Nonnull Description description, @Nonnull Path baseDirectory) throws Throwable; @Nonnull protected Path baseDirectory() { return requireNonNull(baseDirectory, "Method was not called within test evaluation or @Rule/@ClassRule was missing at field."); } @Nonnull protected Path generateTemporaryFolderFor(@Nonnull Description description) throws Exception { final String name = folderNameFor(description); return createTempDirectory(name + "-"); } @Nonnull protected String folderNameFor(@Nonnull Description description) { return normalizeFolderName(description.getDisplayName()); } @Nonnull protected String normalizeFolderName(@Nonnull String input) { final char[] inputCharacters = input.toCharArray(); final char[] result = new char[inputCharacters.length]; for (int i = 0; i < inputCharacters.length; i++) { final char c = inputCharacters[i]; if (isLetterOrDigit(c) || c == '.' || c == ',' || c == '_' || c == '-' || c == '@' || c == '%' || c == '~' || c == '(' || c == ')' || c == '[' || c == ']' || c == '!' ) { result[i] = c; } else { result[i] = '_'; } } return new String(result); } protected void deleteDirectory(@Nonnull Path what) throws Exception { try { walkFileTree(what, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { try { delete(file); } catch (final IOException e) { handleExceptionIfRequired(e); } return CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { if (exc != null) { handleExceptionIfRequired(exc); } else { try { delete(dir); } catch (final IOException e) { handleExceptionIfRequired(e); } } return CONTINUE; } }); } catch (final IOException e) { handleExceptionIfRequired(e); } } protected void handleExceptionIfRequired(@Nonnull IOException e) throws IOException { if (e instanceof NoSuchFileException) { return; } if (isFailOnProblemsWhileCleanup()) { throw e; } } }
package org.spongepowered.common.registry.builtin.sponge; import com.google.common.reflect.TypeToken; import org.spongepowered.api.ResourceKey; import org.spongepowered.api.data.Key; import org.spongepowered.api.data.value.Value; import org.spongepowered.api.util.TypeTokens; import org.spongepowered.common.data.key.SpongeKey; import org.spongepowered.common.data.key.SpongeKeyBuilder; import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; public final class KeyStreamGenerator { private KeyStreamGenerator() { } @SuppressWarnings("rawtypes") public static Stream<Key> stream() { // Do not remove the explicit generic unless you like 40+ min compile times final List<Key> keys = new ArrayList<>(); // @formatter:off keys.add(KeyStreamGenerator.key(ResourceKey.sponge("absorption"), TypeTokens.DOUBLE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("acceleration"), TypeTokens.VECTOR_3D_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("active_item"), TypeTokens.ITEM_STACK_SNAPSHOT_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("affects_spawning"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("age"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("airborne_velocity_modifier"), TypeTokens.VECTOR_3D_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("anger_level"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("applicable_potion_effects"), TypeTokens.LIST_POTION_EFFECT_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("applied_enchantments"), TypeTokens.LIST_ENCHANTMENT_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("armor_material"), TypeTokens.ARMOR_MATERIAL_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("art_type"), TypeTokens.ART_TYPE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("attachment_surface"), TypeTokens.ATTACHMENT_SURFACE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("attack_damage"), TypeTokens.DOUBLE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("attack_time"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("author"), TypeTokens.COMPONENT_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("axis"), TypeTokens.AXIS_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("baby_ticks"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("banner_pattern_layers"), TypeTokens.LIST_BANNER_PATTERN_LAYER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("base_size"), TypeTokens.DOUBLE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("base_vehicle"), TypeTokens.ENTITY_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("beam_target_entity"), TypeTokens.LIVING_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("biome_temperature"), TypeTokens.DOUBLE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("blast_resistance"), TypeTokens.DOUBLE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("block_light"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("block_state"), TypeTokens.BLOCK_STATE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("block_temperature"), TypeTokens.DOUBLE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("body_rotations"), TypeTokens.MAP_BODY_VECTOR3D_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("boss_bar"), TypeTokens.BOSS_BAR_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("breakable_block_types"), TypeTokens.SET_BLOCK_TYPE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("breeder"), TypeTokens.UUID_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("breeding_cooldown"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("burn_time"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("can_breed"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("can_drop_as_item"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("can_fly"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("can_grief"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("can_harvest"), TypeTokens.SET_BLOCK_TYPE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("can_hurt_entities"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("can_join_raid"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("can_move_on_land"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("can_place_as_block"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("casting_time"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("cat_type"), TypeTokens.CAT_TYPE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("chest_attachment_type"), TypeTokens.CHEST_ATTACHMENT_TYPE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("chest_rotation"), TypeTokens.VECTOR_3D_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("color"), TypeTokens.COLOR_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("command"), TypeTokens.STRING_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("comparator_mode"), TypeTokens.COMPARATOR_MODE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("connected_directions"), TypeTokens.SET_DIRECTION_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("container_item"), TypeTokens.ITEM_TYPE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("cooldown"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("creator"), TypeTokens.UUID_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("current_spell"), TypeTokens.SPELL_TYPE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("custom_attack_damage"), TypeTokens.MAP_ENTITY_TYPE_DOUBLE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("damage_absorption"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("damage_per_block"), TypeTokens.DOUBLE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("decay_distance"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("derailed_velocity_modifier"), TypeTokens.VECTOR_3D_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("despawn_delay"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("detonator"), TypeTokens.LIVING_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("direction"), TypeTokens.DIRECTION_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("display_name"), TypeTokens.COMPONENT_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("dominant_hand"), TypeTokens.HAND_PREFERENCE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("door_hinge"), TypeTokens.DOOR_HINGE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("do_exact_teleport"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("duration"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("duration_on_use"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("dye_color"), TypeTokens.DYE_COLOR_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("eating_time"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("efficiency"), TypeTokens.DOUBLE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("egg_time"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("end_gateway_age"), TypeTokens.LONG_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("equipment_type"), TypeTokens.EQUIPMENT_TYPE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("exhaustion"), TypeTokens.DOUBLE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("experience"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("experience_from_start_of_level"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("experience_level"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("experience_since_level"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("explosion_radius"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("eye_height"), TypeTokens.DOUBLE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("eye_position"), TypeTokens.VECTOR_3D_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("fall_distance"), TypeTokens.DOUBLE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("fall_time"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("firework_effects"), TypeTokens.LIST_FIREWORK_EFFECT_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("firework_flight_modifier"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("fire_damage_delay"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("fire_ticks"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("first_date_joined"), TypeTokens.INSTANT_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("first_trusted"), TypeTokens.UUID_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("fluid_item_stack"), TypeTokens.FLUID_STACK_SNAPSHOT_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("fluid_level"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("fluid_tank_contents"), TypeTokens.MAP_DIRECTION_FLUID_STACK_SNAPSHOT_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("flying_speed"), TypeTokens.DOUBLE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("food_level"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("fox_type"), TypeTokens.FOX_TYPE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("fuel"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("fuse_duration"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("game_mode"), TypeTokens.GAME_MODE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("game_profile"), TypeTokens.GAME_PROFILE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("generation"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("growth_stage"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("hardness"), TypeTokens.DOUBLE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("has_arms"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("has_base_plate"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("has_chest"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("has_egg"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("has_fish"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("has_marker"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("has_pores_down"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("has_pores_east"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("has_pores_north"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("has_pores_south"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("has_pores_up"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("has_pores_west"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("has_viewed_credits"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("head_rotation"), TypeTokens.VECTOR_3D_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("healing_crystal"), TypeTokens.ENDER_CRYSTAL_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("health"), TypeTokens.DOUBLE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("health_scale"), TypeTokens.DOUBLE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("height"), TypeTokens.DOUBLE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("held_item"), TypeTokens.ITEM_TYPE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("hidden_gene"), TypeTokens.PANDA_GENE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("hide_attributes"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("hide_can_destroy"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("hide_can_place"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("hide_enchantments"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("hide_miscellaneous"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("hide_unbreakable"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("home_position"), TypeTokens.VECTOR_3I_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("horse_color"), TypeTokens.HORSE_COLOR_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("horse_style"), TypeTokens.HORSE_STYLE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("infinite_despawn_delay"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("infinite_pickup_delay"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("instrument_type"), TypeTokens.INSTRUMENT_TYPE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("inverted"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("invulnerability_ticks"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("invulnerable"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("in_wall"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_adult"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_aflame"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_ai_enabled"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_angry"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_attached"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_begging_for_food"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_celebrating"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_charged"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_charging_crossbow"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_climbing"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_connected_east"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_connected_north"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_connected_south"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_connected_up"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_connected_west"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_critical_hit"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_crouching"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_custom_name_visible"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_defending"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_disarmed"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_eating"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_effect_only"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_elytra_flying"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_extended"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_faceplanted"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_filled"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_flammable"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_flying"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_frightened"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_full_block"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_glowing"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_going_home"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_gravity_affected"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_hissing"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_immobilized"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_indirectly_powered"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_interested"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_invisible"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_in_water"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_johnny"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_laying_egg"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_leader"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_lit"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_lying_down"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_lying_on_back"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_occupied"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_on_rail"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_open"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_passable"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_patrolling"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_persistent"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_placing_disabled"), TypeTokens.MAP_EQUIPMENT_TYPE_BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_player_created"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_pouncing"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_powered"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_primed"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_purring"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_relaxed"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_replaceable"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_roaring"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_rolling_around"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_saddled"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_screaming"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_sheared"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_silent"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_sitting"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_sleeping"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_sleeping_ignored"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_small"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_sneaking"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_sneezing"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_snowy"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_solid"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_sprinting"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_standing"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_stunned"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_surrogate_block"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_taking_disabled"), TypeTokens.MAP_EQUIPMENT_TYPE_BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_tamed"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_trading"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_traveling"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_trusting"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_unbreakable"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_unhappy"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_waterlogged"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("is_wet"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("item_durability"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("item_stack_snapshot"), TypeTokens.ITEM_STACK_SNAPSHOT_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("knockback_strength"), TypeTokens.DOUBLE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("known_gene"), TypeTokens.PANDA_GENE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("last_attacker"), TypeTokens.ENTITY_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("last_command_output"), TypeTokens.COMPONENT_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("last_damage_received"), TypeTokens.DOUBLE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("last_date_joined"), TypeTokens.INSTANT_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("last_date_played"), TypeTokens.INSTANT_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("layer"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("leash_holder"), TypeTokens.ENTITY_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("left_arm_rotation"), TypeTokens.VECTOR_3D_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("left_leg_rotation"), TypeTokens.VECTOR_3D_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("life_ticks"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("light_emission"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("llama_type"), TypeTokens.LLAMA_TYPE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("lock_token"), TypeTokens.STRING_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("lore"), TypeTokens.LIST_COMPONENT_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("matter_state"), TypeTokens.MATTER_STATE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("max_air"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("max_burn_time"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("max_cook_time"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("max_durability"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("max_fall_damage"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("max_health"), TypeTokens.DOUBLE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("max_nearby_entities"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("max_spawn_delay"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("max_speed"), TypeTokens.DOUBLE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("max_stack_size"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("minecart_block_offset"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("min_spawn_delay"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("moisture"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("mooshroom_type"), TypeTokens.MOOSHROOM_TYPE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("music_disc"), TypeTokens.MUSIC_DISC_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("next_entity_to_spawn"), TypeTokens.WEIGHTED_ENTITY_ARCHETYPE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("note_pitch"), TypeTokens.NOTE_PITCH_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("notifier"), TypeTokens.UUID_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("occupied_deceleration"), TypeTokens.DOUBLE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("on_ground"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("pages"), TypeTokens.LIST_COMPONENT_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("parrot_type"), TypeTokens.PARROT_TYPE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("particle_effect"), TypeTokens.PARTICLE_EFFECT_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("passed_cook_time"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("passengers"), TypeTokens.LIST_ENTITY_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("pattern_color"), TypeTokens.DYE_COLOR_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("phantom_phase"), TypeTokens.PHANTOM_PHASE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("pickup_delay"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("pickup_rule"), TypeTokens.PICKUP_RULE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("piston_type"), TypeTokens.PISTON_TYPE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("placeable_block_types"), TypeTokens.SET_BLOCK_TYPE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("plain_pages"), TypeTokens.LIST_STRING_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("plugin_container"), TypeTokens.PLUGIN_CONTAINER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("pores"), TypeTokens.SET_DIRECTION_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("portion_type"), TypeTokens.PORTION_TYPE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("potential_max_speed"), TypeTokens.DOUBLE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("potion_effects"), TypeTokens.LIST_POTION_EFFECT_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("potion_type"), TypeTokens.POTION_TYPE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("power"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("primary_potion_effect_type"), TypeTokens.POTION_EFFECT_TYPE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("profession_type"), TypeTokens.PROFESSION_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("profession_level"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("rabbit_type"), TypeTokens.RABBIT_TYPE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("radius"), TypeTokens.DOUBLE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("radius_on_use"), TypeTokens.DOUBLE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("radius_per_tick"), TypeTokens.DOUBLE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("raid_wave"), TypeTokens.RAID_WAVE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("rail_direction"), TypeTokens.RAIL_DIRECTION_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("reapplication_delay"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("redstone_delay"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("remaining_air"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("remaining_brew_time"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("remaining_spawn_delay"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("replenished_food"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("replenished_saturation"), TypeTokens.DOUBLE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("represented_instrument"), TypeTokens.INSTRUMENT_TYPE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("required_player_range"), TypeTokens.DOUBLE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("respawn_locations"), TypeTokens.MAP_UUID_RESPAWN_LOCATION_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("right_arm_rotation"), TypeTokens.VECTOR_3D_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("right_leg_rotation"), TypeTokens.VECTOR_3D_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("roaring_time"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("rotation"), TypeTokens.ROTATION_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("saturation"), TypeTokens.DOUBLE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("scale"), TypeTokens.DOUBLE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("scoreboard_tags"), TypeTokens.SET_STRING_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("secondary_potion_effect_type"), TypeTokens.POTION_EFFECT_TYPE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("second_trusted"), TypeTokens.UUID_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("shooter"), TypeTokens.PROJECTILE_SOURCE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("show_bottom"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("sign_lines"), TypeTokens.LIST_COMPONENT_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("size"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("skin_profile_property"), TypeTokens.PROFILE_PROPERTY_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("skin_moisture"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("sky_light"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("slab_portion"), TypeTokens.SLAB_PORTION_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("slot_index"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("slot_position"), TypeTokens.VECTOR_2I_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("slot_side"), TypeTokens.DIRECTION_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("slows_unoccupied"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("sneezing_time"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("spawnable_entities"), TypeTokens.WEIGHTED_ENTITY_ARCHETYPE_COLLECTION_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("spawn_count"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("spawn_range"), TypeTokens.DOUBLE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("spectator_target"), TypeTokens.ENTITY_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("stair_shape"), TypeTokens.STAIR_SHAPE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("statistics"), TypeTokens.MAP_STATISTIC_LONG_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("stored_enchantments"), TypeTokens.LIST_ENCHANTMENT_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("strength"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("structure_author"), TypeTokens.STRING_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("structure_ignore_entities"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("structure_integrity"), TypeTokens.DOUBLE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("structure_mode"), TypeTokens.STRUCTURE_MODE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("structure_position"), TypeTokens.VECTOR_3I_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("structure_powered"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("structure_seed"), TypeTokens.LONG_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("structure_show_air"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("structure_show_bounding_box"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("structure_size"), TypeTokens.VECTOR_3I_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("stuck_arrows"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("stunned_time"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("success_count"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("suspended"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("swiftness"), TypeTokens.DOUBLE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("tamer"), TypeTokens.UUID_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("target_entity"), TypeTokens.ENTITY_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("target_location"), TypeTokens.VECTOR_3D_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("target_position"), TypeTokens.VECTOR_3I_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("ticks_remaining"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("tool_type"), TypeTokens.TOOL_TYPE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("tracks_output"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("trade_offers"), TypeTokens.LIST_TRADE_OFFER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("transient"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("tropical_fish_shape"), TypeTokens.TROPICAL_FISH_SHAPE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("unhappy_time"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("unique_id"), TypeTokens.UUID_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("unoccupied_deceleration"), TypeTokens.DOUBLE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("unstable"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("update_game_profile"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("vanish"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("vanish_ignores_collision"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("vanish_prevents_targeting"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("vehicle"), TypeTokens.ENTITY_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("velocity"), TypeTokens.VECTOR_3D_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("villager_type"), TypeTokens.VILLAGER_TYPE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("wait_time"), TypeTokens.INTEGER_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("walking_speed"), TypeTokens.DOUBLE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("will_shatter"), TypeTokens.BOOLEAN_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("wire_attachments"), TypeTokens.MAP_DIRECTION_WIRE_ATTACHMENT_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("wire_attachment_east"), TypeTokens.WIRE_ATTACHMENT_TYPE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("wire_attachment_north"), TypeTokens.WIRE_ATTACHMENT_TYPE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("wire_attachment_south"), TypeTokens.WIRE_ATTACHMENT_TYPE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("wire_attachment_west"), TypeTokens.WIRE_ATTACHMENT_TYPE_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("wither_targets"), TypeTokens.LIST_ENTITY_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("wololo_target"), TypeTokens.SHEEP_VALUE_TOKEN)); keys.add(KeyStreamGenerator.key(ResourceKey.sponge("wood_type"), TypeTokens.WOOD_TYPE_VALUE_TOKEN)); // @formatter:on return keys.stream(); } private static <E, V extends Value<E>> SpongeKey<V, E> key(final ResourceKey key, final TypeToken<V> token) { final SpongeKeyBuilder<E, V> builder = new SpongeKeyBuilder<>(); return (SpongeKey<V, E>) builder .key(key) .type(token) .build(); } }
package org.teachingextensions.approvals.lite.util.servlets; import org.teachingextensions.approvals.lite.util.StringUtils; import java.util.HashMap; import java.util.HashSet; public class ValidationError extends RuntimeException { private static final long serialVersionUID = 7940285202708976073L; private HashMap<String, String> errors = new HashMap<>(); private HashSet<String> assertions = null; public ValidationError(Enum enumerations[]) { this.assertions = new HashSet<>(); for (Enum e : enumerations) { this.assertions.add(e.toString()); } } public String getMessage() { return toString(); } public String toString() { return "Validation(s) failed " + errors.keySet().toString() + " - " + errors.values().toString(); } public void set(Enum assertion, boolean isOk, String errorDescription) { setError(assertion.toString(), !isOk, errorDescription); } public void setError(String assertion, boolean isError, String errorDescription) { if (isError && !StringUtils.isNonZero(errorDescription)) { throw new Error("You can not use empty error descriptions"); } assertValidAssertion(assertion); if (isError) { errors.put(assertion, errorDescription); } else { errors.remove(assertion); } } public ValidationError add(String prefix, int index, ValidationError error) { return add(getPrefixForIndex(prefix, index), error); } public static String getPrefixForIndex(String prefix, int index) { return prefix + "[" + index + "]"; } public ValidationError add(String prefix, ValidationError error) { prefix = StringUtils.isEmpty(prefix) ? "" : (prefix + "."); String[] assertions = StringUtils.toArray(error.assertions); for (String assertion : assertions) { this.assertions.add(prefix + assertion); } for (String key : error.errors.keySet()) { errors.put(prefix + key, error.errors.get(key)); } return this; } public boolean isOk() { return (errors.size() == 0); } private void assertValidAssertion(String assertion) { if (!this.assertions.contains(assertion)) { throw new Error("Assertion '" + assertion + "' not found from " + assertions.toString()); } } public int size() { return errors.size(); } }
package tv.floe.metronome.deeplearning.rbm.visualization; import java.awt.Graphics; import java.awt.Image; import java.awt.image.BufferStrategy; import java.awt.image.BufferedImage; import java.awt.image.DataBufferInt; import java.awt.image.WritableRaster; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import org.apache.mahout.math.Matrix; import tv.floe.metronome.math.MatrixUtils; public class DrawMnistGreyscale { public JFrame frame; BufferedImage img; private int width = 28; private int height = 28; public String title = "TEST"; private int heightOffset = 0; private int widthOffset = 0; public DrawMnistGreyscale(Matrix data,int heightOffset,int widthOffset) { img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); this.heightOffset = heightOffset; this.widthOffset = widthOffset; WritableRaster r = img.getRaster(); int[] equiv = new int[ MatrixUtils.length( data ) ]; for (int i = 0; i < equiv.length; i++) { equiv[i] = (int) Math.round( MatrixUtils.getElement(data, i) ); } r.setDataElements(0, 0, width, height, equiv); } public DrawMnistGreyscale(Matrix data) { img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); WritableRaster r = img.getRaster(); int[] equiv = new int[ MatrixUtils.length( data ) ]; for (int i = 0; i < equiv.length; i++) { equiv[i] = (int) Math.round( MatrixUtils.getElement(data, i) ); } r.setDataElements(0, 0, width, height, equiv); } public void saveImageToDisk(BufferedImage img, String imageName) throws IOException { File outputfile = new File( imageName ); ImageIO.write(img, "png", outputfile); } public void draw() { frame = new JFrame(title); frame.setVisible(true); start(); frame.add(new JLabel(new ImageIcon(getImage()))); frame.pack(); // Better to DISPOSE than EXIT frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); } public void close() { frame.dispose(); } public Image getImage() { return img; } public void start(){ int[] pixels = ((DataBufferInt)img.getRaster().getDataBuffer()).getData(); boolean running = true; while(running){ BufferStrategy bs = frame.getBufferStrategy(); if(bs==null){ frame.createBufferStrategy(4); return; } for (int i = 0; i < width * height; i++) pixels[i] = 0; Graphics g= bs.getDrawGraphics(); g.drawImage(img, heightOffset, widthOffset, width, height, null); g.dispose(); bs.show(); } } }
package org.tigris.subversion.svnclientadapter.commandline; import java.net.MalformedURLException; import java.net.URL; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import org.tigris.subversion.svnclientadapter.ISVNDirEntry; import org.tigris.subversion.svnclientadapter.SVNNodeKind; import org.tigris.subversion.svnclientadapter.SVNRevision; /** * * @author philip schatz */ public class CmdLineRemoteDirEntry implements ISVNDirEntry { private static DateFormat df1 = new SimpleDateFormat("MMM dd hh:mm", Locale.US); private static DateFormat df2 = new SimpleDateFormat("MMM dd yyyy", Locale.US); private String path; private URL url; private SVNRevision.Number revision; private SVNNodeKind nodeKind; private String lastCommitAuthor; private Date lastChangedDate; /** * @param line */ public CmdLineRemoteDirEntry(String baseUrl, String line) { // see ls-cmd.c for the format used int last = line.length() - 1; boolean folder = ('/' == line.charAt(last)); path = (folder) ? line.substring(41, last) : line.substring(41); try { url = new URL(baseUrl + '/' + path); } catch (MalformedURLException e) { //do nothing } revision = new SVNRevision.Number(Long.parseLong(line.substring(1, 9).trim())); nodeKind = (folder) ? SVNNodeKind.DIR : SVNNodeKind.FILE; lastCommitAuthor = line.substring(9, 18).trim(); String dateString = line.substring(28, 40); try { // two formats are possible (see ls-cmd.c) depending on the numbers of days between current date // and lastChangedDate if (dateString.indexOf(':') != -1) { lastChangedDate = df1.parse(dateString); // something like "Sep 24 18:01" } else { lastChangedDate = df2.parse(dateString); // something like "Mar 01 2003" } } catch (ParseException e1) { e1.printStackTrace(); } } /* (non-Javadoc) * @see org.tigris.subversion.subclipse.client.ISVNDirEntry#getHasProps() */ public boolean getHasProps() { //TODO unhardcode this return false; } /* (non-Javadoc) * @see org.tigris.subversion.subclipse.client.ISVNDirEntry#getNodeKind() */ public SVNNodeKind getNodeKind() { return nodeKind; } /* (non-Javadoc) * @see org.tigris.subversion.subclipse.client.ISVNDirEntry#getLastChangedRevision() */ public SVNRevision.Number getLastChangedRevision() { return revision; } /* (non-Javadoc) * @see org.tigris.subversion.subclipse.client.ISVNDirEntry#getLastChangedDate() */ public Date getLastChangedDate() { return lastChangedDate; } /* (non-Javadoc) * @see org.tigris.subversion.subclipse.client.ISVNDirEntry#getLastCommitAuthor() */ public String getLastCommitAuthor() { return lastCommitAuthor; } /* (non-Javadoc) * @see org.tigris.subversion.subclipse.client.ISVNDirEntry#getPath() */ public String getPath() { return path; } public long getSize() { // TODO : implement getSize return 0; } }
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; /** * This class loads the file corpus.txt, reads the file line by line up to the nr of lines provided in args[0]. * Each line is processed according to a set of rules, and the resuls are written to ppCorpus.txt, line by line. * After next it reads the following lines args[0]+1 to args[0]+args[1] and preprocesses them for testing, * saving the results in testSentences.txt * * * @author Jasmin Suljkic */ public class CorpusPreprocess { /** * No arguments are taken in account. * Statically configured file corpus.txt is read and ppCorpus.txt as well as testSentences.txt is created and written to. * @param args -> X Y, (X: lines to for learning, Y: lines for testing) */ public static void main(String[] args) { //args[0] -> Amount of lines to preprocess for learning //args[1] -> Amount of lines to preprocess for testing // TODO Auto-generated method stub BufferedReader br; BufferedWriter bw; BufferedWriter bwT; BufferedWriter bwTC; StringBuffer sb = new StringBuffer(); StringBuffer sbt = new StringBuffer(); int nrLines=0; int toLearn=Integer.parseInt(args[0]); int toTest=Integer.parseInt(args[1]); try { br = new BufferedReader(new FileReader("corpus.txt")); bw = new BufferedWriter(new FileWriter("ppCorpus.txt")); bwT = new BufferedWriter(new FileWriter("testSentences.txt")); bwTC = new BufferedWriter(new FileWriter("testScentencesCorrect.txt")); String line; char[] lc; //Go trough the corpus and count the amount of lines present while ((line=br.readLine()) != null) { nrLines++; } br.close(); if((toLearn+toTest)>nrLines){ System.err.println("Request invalid: Number of lines requested > nr of lines available in corpus."); return; } br=new BufferedReader(new FileReader("corpus.txt")); //Read a line from file (as long as there are lines in the file) //Process the line //Write the result to output file. int current =0; boolean testing =false; while ((line=br.readLine()) != null) { if(current==toLearn+1){ testing=true; } if(current==(toLearn+toTest)){ break; } lc = line.toCharArray(); for(char c : lc){ if(c=='.'){ if(testing){ sbt.append(" "); } sb.append(" .PERIOD"); } else if(c=='!'){ if(testing){ sbt.append(" "); } sb.append(" !EXCL"); } else if(c=='?'){ if(testing){ sbt.append(" "); } sb.append(" ?QMARK"); } else if(c==','){ if(testing){ sbt.append(" "); } sb.append(" ,COMMA"); } // else if(c==' '){ // sb.append(' '); else{ if(testing){ sbt.append(c); } sb.append(c); } } if(testing){ bwT.write(sbt.toString()); sbt = new StringBuffer(); bwT.newLine(); bwTC.write(sb.toString()); sb = new StringBuffer(); bwTC.newLine(); } else{ bw.write(sb.toString()); sb = new StringBuffer(); bw.newLine(); } current++; } br.close(); bw.close(); bwT.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
package water.api; import org.apache.commons.lang.exception.ExceptionUtils; import water.*; import water.api.schemas3.H2OErrorV3; import water.api.schemas3.H2OModelBuilderErrorV3; import water.api.schemas99.AssemblyV99; import water.exceptions.*; import water.init.NodePersistentStorage; import water.nbhm.NonBlockingHashMap; import water.rapids.Assembly; import water.server.ServletUtils; import water.util.*; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.MalformedURLException; import java.util.*; import java.util.concurrent.atomic.AtomicLong; /** * This is a simple web server which accepts HTTP requests and routes them * to methods in Handler classes for processing. Schema classes are used to * provide a more stable external JSON interface while allowing the implementation * to evolve rapidly. As part of request handling the framework translates * back and forth between the stable external representation of objects (Schema) * and the less stable internal classes. * <p> * Request <i>routing</i> is done by searching a list of registered * handlers, in order of registration, for a handler whose path regex matches * the request URI and whose HTTP method (GET, POST, DELETE...) matches the * request's method. If none is found an HTTP 404 is returned. * <p> * A Handler class is parametrized by the kind of Schema that it accepts * for request handling, as well as the internal implementation class (Iced * class) that the Schema translates from and to. Handler methods are allowed to * return other Schema types than in the type parameter if that makes * sense for a given request. For example, a prediction (scoring) call on * a Model might return a Frame schema. * <p> * When an HTTP request is accepted the framework does the following steps: * <ol> * <li>searches the registered handler methods for a matching URL and HTTP method</li> * <li>collects any parameters which are captured from the URI and adds them to the map of HTTP query parameters</li> * <li>creates an instance of the correct Handler class and calls handle() on it, passing the version, route and params</li> * <li>Handler.handle() creates the correct Schema object given the version and calls fillFromParms(params) on it</li> * <li>calls schema.createImpl() to create a schema-independent "back end" object</li> * <li>dispatches to the handler method, passing in the schema-independent impl object and returning the result Schema object</li> * </ol> * * @see water.api.Handler * @see water.api.RegisterV3Api */ public class RequestServer extends HttpServlet { // TODO: merge doGeneric() and serve() // Originally we had RequestServer based on NanoHTTPD. At some point we switched to JettyHTTPD, but there are // still some leftovers from the Nano times. // TODO: invoke DatasetServlet, PostFileServlet and NpsBinServlet using standard Routes // Right now those 3 servlets are handling 5 "special" api endpoints from JettyHTTPD, and we also have several // "special" endpoints in maybeServeSpecial(). We don't want them to be special. The Route class should be // made flexible enough to generate responses of various kinds, and then all of those "special" cases would // become regular API calls. // TODO: Move JettyHTTPD.sendErrorResponse here, and combine with other error-handling functions // That method is only called from 3 servlets mentioned above, and we want to standardize the way how errors // are handled in different responses. // Returned in REST API responses as X-h2o-rest-api-version-max // Do not bump to 4 until when the API v4 is fully ready for release. public static final int H2O_REST_API_VERSION = 3; private static RouteTree routesTree = new RouteTree(""); private static ArrayList<Route> routesList = new ArrayList<>(150); public static int numRoutes() { return routesList.size(); } public static ArrayList<Route> routes() { return routesList; } public static Route lookupRoute(RequestUri uri) { return routesTree.lookup(uri, null); } private static HttpLogFilter[] _filters=new HttpLogFilter[]{defaultFilter()}; public static void setFilters(HttpLogFilter... filters) { _filters=filters; } /** * Some HTTP response status codes */ public static final String HTTP_OK = "200 OK", HTTP_CREATED = "201 Created", HTTP_ACCEPTED = "202 Accepted", HTTP_NO_CONTENT = "204 No Content", HTTP_PARTIAL_CONTENT = "206 Partial Content", HTTP_REDIRECT = "301 Moved Permanently", HTTP_NOT_MODIFIED = "304 Not Modified", HTTP_BAD_REQUEST = "400 Bad Request", HTTP_UNAUTHORIZED = "401 Unauthorized", HTTP_FORBIDDEN = "403 Forbidden", HTTP_NOT_FOUND = "404 Not Found", HTTP_BAD_METHOD = "405 Method Not Allowed", HTTP_PRECONDITION_FAILED = "412 Precondition Failed", HTTP_TOO_LONG_REQUEST = "414 Request-URI Too Long", HTTP_RANGE_NOT_SATISFIABLE = "416 Requested Range Not Satisfiable", HTTP_TEAPOT = "418 I'm a Teapot", HTTP_THROTTLE = "429 Too Many Requests", HTTP_INTERNAL_ERROR = "500 Internal Server Error", HTTP_NOT_IMPLEMENTED = "501 Not Implemented", HTTP_SERVICE_NOT_AVAILABLE = "503 Service Unavailable"; /** * Common mime types for dynamic content */ public static final String MIME_PLAINTEXT = "text/plain", MIME_HTML = "text/html", MIME_CSS = "text/css", MIME_JSON = "application/json", MIME_JS = "application/javascript", MIME_JPEG = "image/jpeg", MIME_PNG = "image/png", MIME_SVG = "image/svg+xml", MIME_GIF = "image/gif", MIME_WOFF = "application/x-font-woff", MIME_DEFAULT_BINARY = "application/octet-stream", MIME_XML = "text/xml"; /** * Calculates number of routes having the specified version. */ public static int numRoutes(int version) { int count = 0; for (Route route : routesList) if (route.getVersion() == version) count++; return count; } /** * Register an HTTP request handler method for a given URL pattern, with parameters extracted from the URI. * <p> * URIs which match this pattern will have their parameters collected from the path and from the query params * * @param api_name suggested method name for this endpoint in the external API library. These names should be * unique. If null, the api_name will be created from the class name and the handler method name. * @param method_uri combined method / url pattern of the request, e.g.: "GET /3/Jobs/{job_id}" * @param handler_class class which contains the handler method * @param handler_method name of the handler method * @param summary help string which explains the functionality of this endpoint * @see Route * @see water.api.RequestServer * @return the Route for this request */ public static Route registerEndpoint( String api_name, String method_uri, Class<? extends Handler> handler_class, String handler_method, String summary ) { String[] spl = method_uri.split(" "); assert spl.length == 2 : "Unexpected method_uri parameter: " + method_uri; return registerEndpoint(api_name, spl[0], spl[1], handler_class, handler_method, summary, HandlerFactory.DEFAULT); } /** * @param api_name suggested method name for this endpoint in the external API library. These names should be * unique. If null, the api_name will be created from the class name and the handler method name. * @param http_method HTTP verb (GET, POST, DELETE) this handler will accept * @param url url path, possibly containing placeholders in curly braces, e.g: "/3/DKV/{key}" * @param handler_class class which contains the handler method * @param handler_method name of the handler method * @param summary help string which explains the functionality of this endpoint * @param handler_factory factory to create instance of handler (used by Sparkling Water) * @return the Route for this request */ public static Route registerEndpoint( String api_name, String http_method, String url, Class<? extends Handler> handler_class, String handler_method, String summary, HandlerFactory handler_factory ) { assert api_name != null : "api_name should not be null"; try { RequestUri uri = new RequestUri(http_method, url); Route route = new Route(uri, api_name, summary, handler_class, handler_method, handler_factory); routesTree.add(uri, route); routesList.add(route); return route; } catch (MalformedURLException e) { throw H2O.fail(e.getMessage()); } } /** * Register an HTTP request handler for the given URL pattern. * * @param method_uri combined method/url pattern of the endpoint, for * example: {@code "GET /3/Jobs/{job_id}"} * @param handler_clz class of the handler (should inherit from * {@link RestApiHandler}). */ public static Route registerEndpoint(String method_uri, Class<? extends RestApiHandler> handler_clz) { try { RestApiHandler handler = handler_clz.newInstance(); return registerEndpoint(handler.name(), method_uri, handler_clz, null, handler.help()); } catch (Exception e) { throw H2O.fail(e.getMessage()); } } @Override protected void doGet(HttpServletRequest rq, HttpServletResponse rs) { doGeneric("GET", rq, rs); } @Override protected void doPut(HttpServletRequest rq, HttpServletResponse rs) { doGeneric("PUT", rq, rs); } @Override protected void doPost(HttpServletRequest rq, HttpServletResponse rs) { doGeneric("POST", rq, rs); } @Override protected void doHead(HttpServletRequest rq, HttpServletResponse rs) { doGeneric("HEAD", rq, rs); } @Override protected void doDelete(HttpServletRequest rq, HttpServletResponse rs) { doGeneric("DELETE", rq, rs); } @Override protected void doOptions(HttpServletRequest rq, HttpServletResponse rs) { if (System.getProperty(H2O.OptArgs.SYSTEM_DEBUG_CORS) != null) { rs.setHeader("Access-Control-Allow-Origin", "*"); rs.setHeader("Access-Control-Allow-Headers", "Content-Type"); rs.setStatus(HttpServletResponse.SC_OK); } } /** * Top-level dispatch handling */ public void doGeneric(String method, HttpServletRequest request, HttpServletResponse response) { try { ServletUtils.startTransaction(request.getHeader("User-Agent")); // Note that getServletPath does an un-escape so that the %24 of job id's are turned into $ characters. String uri = request.getServletPath(); Properties headers = new Properties(); Enumeration<String> en = request.getHeaderNames(); while (en.hasMoreElements()) { String key = en.nextElement(); String value = request.getHeader(key); headers.put(key, value); } final String contentType = request.getContentType(); Properties parms = new Properties(); String postBody = null; if (System.getProperty(H2O.OptArgs.SYSTEM_PROP_PREFIX + "debug.cors") != null) { response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Headers", "Content-Type"); } if (contentType != null && contentType.startsWith(MIME_JSON)) { StringBuffer jb = new StringBuffer(); String line = null; try { BufferedReader reader = request.getReader(); while ((line = reader.readLine()) != null) jb.append(line); } catch (Exception e) { throw new H2OIllegalArgumentException("Exception reading POST body JSON for URL: " + uri); } postBody = jb.toString(); } else { // application/x-www-form-urlencoded Map<String, String[]> parameterMap; parameterMap = request.getParameterMap(); for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) { String key = entry.getKey(); String[] values = entry.getValue(); if (values.length == 1) { parms.put(key, values[0]); } else if (values.length > 1) { StringBuilder sb = new StringBuilder(); sb.append("["); boolean first = true; for (String value : values) { if (!first) sb.append(","); sb.append("\"").append(value).append("\""); first = false; } sb.append("]"); parms.put(key, sb.toString()); } } } // Make serve() call. NanoResponse resp = serve(uri, method, headers, parms, postBody); // Un-marshal Nano response back to Jetty. String choppedNanoStatus = resp.status.substring(0, 3); assert (choppedNanoStatus.length() == 3); int sc = Integer.parseInt(choppedNanoStatus); ServletUtils.setResponseStatus(response, sc); response.setContentType(resp.mimeType); Properties header = resp.header; Enumeration<Object> en2 = header.keys(); while (en2.hasMoreElements()) { String key = (String) en2.nextElement(); String value = header.getProperty(key); response.setHeader(key, value); } resp.writeTo(response.getOutputStream()); } catch (Error e) { try { // Send the full stackTrack as message to the client directly. Default error response error in Jetty's ServletHandler // is made inactive by ending the error, as the response is marked as committed. response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ExceptionUtils.getFullStackTrace(e)); // After the response is sent, the exceptions is re-thrown to finish the process as without this interception throw e; } catch (IOException ex) { ServletUtils.setResponseStatus(response, 500); Log.err(e); } } catch (IOException e) { e.printStackTrace(); ServletUtils.setResponseStatus(response, 500); Log.err(e); // Trying to send an error message or stack trace will produce another IOException... } finally { ServletUtils.logRequest(method, request, response); // Handle shutdown if it was requested. if (H2O.getShutdownRequested()) { (new Thread() { public void run() { boolean [] confirmations = new boolean[H2O.CLOUD.size()]; if (H2O.SELF.index() >= 0) { confirmations[H2O.SELF.index()] = true; } for(H2ONode n:H2O.CLOUD._memary) { if(n != H2O.SELF) new RPC<>(n, new UDPRebooted.ShutdownTsk(H2O.SELF,n.index(), 1000, confirmations, 0)).call(); } try { Thread.sleep(2000); } catch (Exception ignore) {} int failedToShutdown = 0; // shutdown failed for(boolean b:confirmations) if(!b) failedToShutdown++; Log.info("Orderly shutdown: " + (failedToShutdown > 0? failedToShutdown + " nodes failed to shut down! ":"") + " Shutting down now."); H2O.closeAll(); H2O.exit(failedToShutdown); } }).start(); } ServletUtils.endTransaction(); } } /** * Subsequent handling of the dispatch */ public static NanoResponse serve(String url, String method, Properties header, Properties parms, String post_body) { boolean hideParameters = true; try { // Jack priority for user-visible requests Thread.currentThread().setPriority(Thread.MAX_PRIORITY - 1); RequestType type = RequestType.requestType(url); RequestUri uri = new RequestUri(method, url); // Log the request hideParameters = maybeLogRequest(uri, header, parms); // For certain "special" requests that produce non-JSON payloads we require special handling. NanoResponse special = maybeServeSpecial(uri); if (special != null) return special; // Determine the Route corresponding to this request, and also fill in {parms} with the path parameters Route route = routesTree.lookup(uri, parms); // These APIs are broken, because they lead users to create invalid URLs. For example the endpoint // /3/Frames/{frameid}/export/{path}/overwrite/{force} // is invalid, because it leads to URLs like this: // /3/Frames/predictions_9bd5_GLM_model_R_1471148_36_on_RTMP_sid_afec_27/export//tmp/pred.csv/overwrite/TRUE // Here both the {frame_id} and {path} usually contain "/" (making them non-tokens), they may contain other // special characters not valid within URLs (for example if filename is not in ASCII); finally the use of strings // to represent booleans creates ambiguities: should I write "true", "True", "TRUE", or perhaps "1"? // TODO These should be removed as soon as possible... if (url.startsWith("/3/Frames/")) { // /3/Frames/{frame_id}/export/{path}/overwrite/{force} if ((url.toLowerCase().endsWith("/overwrite/true") || url.toLowerCase().endsWith("/overwrite/false")) && url.contains("/export/")) { int i = url.indexOf("/export/"); boolean force = url.toLowerCase().endsWith("true"); parms.put("frame_id", url.substring(10, i)); parms.put("path", url.substring(i+8, url.length()-15-(force?0:1))); parms.put("force", force? "true" : "false"); route = findRouteByApiName("exportFrame_deprecated"); } // /3/Frames/{frame_id}/export else if (url.endsWith("/export")) { parms.put("frame_id", url.substring(10, url.length()-7)); route = findRouteByApiName("exportFrame"); } // /3/Frames/{frame_id}/columns/{column}/summary else if (url.endsWith("/summary") && url.contains("/columns/")) { int i = url.indexOf("/columns/"); parms.put("frame_id", url.substring(10, i)); parms.put("column", url.substring(i+9, url.length()-8)); route = findRouteByApiName("frameColumnSummary"); } // /3/Frames/{frame_id}/columns/{column}/domain else if (url.endsWith("/domain") && url.contains("/columns/")) { int i = url.indexOf("/columns/"); parms.put("frame_id", url.substring(10, i)); parms.put("column", url.substring(i+9, url.length()-7)); route = findRouteByApiName("frameColumnDomain"); } // /3/Frames/{frame_id}/columns/{column} else if (url.contains("/columns/")) { int i = url.indexOf("/columns/"); parms.put("frame_id", url.substring(10, i)); parms.put("column", url.substring(i+9)); route = findRouteByApiName("frameColumn"); } // /3/Frames/{frame_id}/summary else if (url.endsWith("/summary")) { parms.put("frame_id", url.substring(10, url.length()-8)); route = findRouteByApiName("frameSummary"); } // /3/Frames/{frame_id}/light else if (url.endsWith("/light")) { parms.put("frame_id", url.substring(10, url.length()-"/light".length())); route = findRouteByApiName("lightFrame"); } // /3/Frames/{frame_id}/columns else if (url.endsWith("/columns")) { parms.put("frame_id", url.substring(10, url.length()-8)); route = findRouteByApiName("frameColumns"); } // /3/Frames/{frame_id} else { parms.put("frame_id", url.substring(10)); route = findRouteByApiName(method.equals("DELETE")? "deleteFrame" : "frame"); } } else if (url.startsWith("/3/ModelMetrics/predictions_frame/")){ route = findRouteByApiName("makeMetrics"); } if (route == null) { // if the request is not known, treat as resource request, or 404 if not found if (uri.isGetMethod()) return getResource(type, url); else return response404(method + " " + url, type); } else { Schema response = route._handler.handle(uri.getVersion(), route, parms, post_body); PojoUtils.filterFields(response, (String)parms.get("_include_fields"), (String)parms.get("_exclude_fields")); return serveSchema(response, type); } } catch (H2OFailException e) { H2OError error = e.toH2OError(url); Log.fatal("Caught exception (fatal to the cluster): " + error.toString()); throw H2O.fail(serveError(error).toString()); } catch (H2OModelBuilderIllegalArgumentException e) { H2OModelBuilderError error = e.toH2OError(url); Log.warn("Caught exception: " + error.toString()); return serveSchema(new H2OModelBuilderErrorV3().fillFromImpl(error), RequestType.json); } catch (H2OAbstractRuntimeException e) { H2OError error = e.toH2OError(url); Log.warn("Caught exception: " + error.toString()); return serveError(error); } catch (AssertionError e) { H2OError error = new H2OError( System.currentTimeMillis(), url, e.toString(), e.toString(), HttpResponseStatus.INTERNAL_SERVER_ERROR.getCode(), new IcedHashMapGeneric.IcedHashMapStringObject(), e); Log.err("Caught assertion error: " + error.toString()); return serveError(error); } catch (Exception e) { // make sure that no Exception is ever thrown out from the request H2OError error = new H2OError(e, url); // some special cases for which we return 400 because it's likely a problem with the client request: if (e instanceof IllegalArgumentException || e instanceof FileNotFoundException || e instanceof MalformedURLException) error._http_status = HttpResponseStatus.BAD_REQUEST.getCode(); String parmsInfo = hideParameters ? "<hidden>" : String.valueOf(parms); Log.err("Caught exception: " + error.toString() + ";parms=" + parmsInfo); return serveError(error); } } /** * Log the request (unless it's an overly common one). * @return flag whether the request parameters might be sensitive or not */ private static boolean maybeLogRequest(RequestUri uri, Properties header, Properties parms) { LogFilterLevel level = LogFilterLevel.LOG; for (HttpLogFilter f : _filters) level = level.reduce(f.filter(uri, header, parms)); switch (level) { case DO_NOT_LOG: return false; // do not log the request by default but allow parameters to be logged on exceptional completion case URL_ONLY: Log.info(uri, ", parms: <hidden>"); return true; // parameters are sensitive - never log them default: Log.info(uri + ", parms: " + parms); return false; } } public enum LogFilterLevel { LOG(0), URL_ONLY(1), DO_NOT_LOG(Integer.MAX_VALUE); private int level; LogFilterLevel(int level) { this.level = level; } LogFilterLevel reduce(LogFilterLevel other) { if (other.level > this.level) { return other; } else { return this; } } } /** * Create a new HttpLogFilter. * * Implement this interface to create new filters used by maybeLogRequest */ public interface HttpLogFilter { LogFilterLevel filter(RequestUri uri, Properties header, Properties parms); } /** * Provide the default filters for H2O's HTTP logging. * @return an array of HttpLogFilter instances */ public static HttpLogFilter defaultFilter() { return new HttpLogFilter() { // this is much prettier with 1.8 lambdas @Override public LogFilterLevel filter(RequestUri uri, Properties header, Properties parms) { // static web content String url = uri.getUrl(); if (url.endsWith(".css") || url.endsWith(".js") || url.endsWith(".png") || url.endsWith(".ico") ) { return LogFilterLevel.DO_NOT_LOG; } // endpoints that might take sensitive parameters (passwords and other credentials) String[] path = uri.getPath(); if (path[2].equals("PersistS3") || path[2].equals("ImportSQLTable") || path[2].equals("DecryptionSetup") ) { return LogFilterLevel.URL_ONLY; } // endpoints that are called very frequently AND DON'T accept any sensitive information in parameters if (path[2].equals("Cloud") || path[2].equals("Jobs") && uri.isGetMethod() || path[2].equals("Log") || path[2].equals("Progress") || path[2].equals("Typeahead") || path[2].equals("WaterMeterCpuTicks") ) { return LogFilterLevel.DO_NOT_LOG; } return LogFilterLevel.LOG; } }; } private static class RouteTree { private String root; private boolean isWildcard; private HashMap<String, RouteTree> branches; private Route leaf; public RouteTree(String token) { isWildcard = isWildcardToken(token); root = isWildcard ? "*" : token; branches = new HashMap<>(); leaf = null; } public void add(RequestUri uri, Route route) { String[] path = uri.getPath(); addByPath(path, 0, route); } public Route lookup(RequestUri uri, Properties parms) { if (!uri.isApiUrl()) return null; String[] path = uri.getPath(); ArrayList<String> path_params = new ArrayList<>(3); Route route = this.lookupByPath(path, 0, path_params); // Fill in the path parameters if (parms != null && route != null) { String[] param_names = route._path_params; assert path_params.size() == param_names.length; for (int i = 0; i < param_names.length; i++) parms.put(param_names[i], path_params.get(i)); } return route; } private void addByPath(String[] path, int index, Route route) { if (index + 1 < path.length) { String nextToken = isWildcardToken(path[index+1])? "*" : path[index+1]; if (!branches.containsKey(nextToken)) branches.put(nextToken, new RouteTree(nextToken)); branches.get(nextToken).addByPath(path, index + 1, route); } else { assert leaf == null : "Duplicate path encountered: " + Arrays.toString(path); leaf = route; } } private Route lookupByPath(String[] path, int index, ArrayList<String> path_params) { assert isWildcard || root.equals(path[index]); if (index + 1 < path.length) { String nextToken = path[index+1]; // First attempt an exact match if (branches.containsKey(nextToken)) { Route route = branches.get(nextToken).lookupByPath(path, index+1, path_params); if (route != null) return route; } // Then match against a wildcard if (branches.containsKey("*")) { path_params.add(path[index+1]); Route route = branches.get("*").lookupByPath(path, index + 1, path_params); if (route != null) return route; path_params.remove(path_params.size() - 1); } // If we are at the deepest level of the tree and no match was found, attempt to look for alternative versions. // For example, if the user requests /4/About, and we only have /3/About, then we should deliver that version // instead. if (index == path.length - 2) { int v = Integer.parseInt(nextToken); for (String key : branches.keySet()) { if (branches.get(key).leaf == null) continue; if (Integer.parseInt(key) <= v) { // We also create a new branch in the tree to memorize this new route path. RouteTree newBranch = new RouteTree(nextToken); newBranch.leaf = branches.get(key).leaf; branches.put(nextToken, newBranch); return newBranch.leaf; } } } } else { return leaf; } return null; } private static boolean isWildcardToken(String token) { return token.equals("*") || token.startsWith("{") && token.endsWith("}"); } } private static Route findRouteByApiName(String apiName) { for (Route route : routesList) { if (route._api_name.equals(apiName)) return route; } return null; } /** * Handle any URLs that bypass the standard route approach. This is stuff that has abnormal non-JSON response * payloads. * @param uri RequestUri object of the incoming request. * @return Response object, or null if the request does not require any special handling. */ private static NanoResponse maybeServeSpecial(RequestUri uri) { assert uri != null; if (uri.isHeadMethod()) { // Blank response used by R's uri.exists("/") if (uri.getUrl().equals("/")) return new NanoResponse(HTTP_OK, MIME_PLAINTEXT, ""); } if (uri.isGetMethod()) { // url "/3/Foo/bar" => path ["", "GET", "Foo", "bar", "3"] String[] path = uri.getPath(); if (path[2].equals("")) return redirectToFlow(); if (path[2].equals("Logs") && path[3].equals("download")) { // if archive type was specified path will look like ["", "GET", "Logs", "download", "<TYPE>", 3] // if archive type was not specified it will be just ["", "GET", "Logs", "download", 3] boolean containerTypeSpecified = path.length >= 6; LogArchiveContainer container = containerTypeSpecified ? LogArchiveContainer.valueOf(path[4].toUpperCase()) : LogArchiveContainer.ZIP; // use ZIP as default return LogsHandler.downloadLogsViaRestAPI(container); } if (path[2].equals("NodePersistentStorage.bin") && path.length == 6) return downloadNps(path[3], path[4]); } return null; } private static NanoResponse response404(String what, RequestType type) { H2ONotFoundArgumentException e = new H2ONotFoundArgumentException(what + " not found", what + " not found"); H2OError error = e.toH2OError(what); Log.warn(error._dev_msg); return serveError(error); } private static NanoResponse serveSchema(Schema s, RequestType type) { // Convert Schema to desired output flavor String http_response_header = H2OError.httpStatusHeader(HttpResponseStatus.OK.getCode()); // If we're given an http response code use it. if (s instanceof SpecifiesHttpResponseCode) { http_response_header = H2OError.httpStatusHeader(((SpecifiesHttpResponseCode) s).httpStatus()); } // If we've gotten an error always return the error as JSON if (s instanceof SpecifiesHttpResponseCode && HttpResponseStatus.OK.getCode() != ((SpecifiesHttpResponseCode) s).httpStatus()) { type = RequestType.json; } if (s instanceof H2OErrorV3) { return new NanoResponse(http_response_header, MIME_JSON, s.toJsonString()); } if (s instanceof StreamingSchema) { StreamingSchema ss = (StreamingSchema) s; NanoResponse r = new NanoStreamResponse(http_response_header, MIME_DEFAULT_BINARY, ss.getStreamWriter()); // Needed to make file name match class name r.addHeader("Content-Disposition", "attachment; filename=\"" + ss.getFilename() + "\""); return r; } // TODO: remove this entire switch switch (type) { case html: // return JSON for html requests case json: return new NanoResponse(http_response_header, MIME_JSON, s.toJsonString()); case xml: throw H2O.unimpl("Unknown type: " + type.toString()); case java: if (s instanceof AssemblyV99) { // TODO: fix the AssemblyV99 response handler so that it produces the appropriate StreamingSchema Assembly ass = DKV.getGet(((AssemblyV99) s).assembly_id); NanoResponse r = new NanoResponse(http_response_header, MIME_DEFAULT_BINARY, ass.toJava(((AssemblyV99) s).pojo_name)); r.addHeader("Content-Disposition", "attachment; filename=\""+JCodeGen.toJavaId(((AssemblyV99) s).pojo_name)+".java\""); return r; } else { throw new H2OIllegalArgumentException("Cannot generate java for type: " + s.getClass().getSimpleName()); } default: throw H2O.unimpl("Unknown type to serveSchema(): " + type); } } @SuppressWarnings(value = "unchecked") private static NanoResponse serveError(H2OError error) { // Note: don't use Schema.schema(version, error) because we have to work at bootstrap: return serveSchema(new H2OErrorV3().fillFromImpl(error), RequestType.json); } private static NanoResponse redirectToFlow() { NanoResponse res = new NanoResponse(HTTP_REDIRECT, MIME_PLAINTEXT, ""); res.addHeader("Location", H2O.ARGS.context_path + "/flow/index.html"); return res; } private static NanoResponse downloadNps(String categoryName, String keyName) { NodePersistentStorage nps = H2O.getNPS(); AtomicLong length = new AtomicLong(); InputStream is = nps.get(categoryName, keyName, length); NanoResponse res = new NanoResponse(HTTP_OK, MIME_DEFAULT_BINARY, is); res.addHeader("Content-Length", Long.toString(length.get())); res.addHeader("Content-Disposition", "attachment; filename=" + keyName + ".flow"); return res; } // cache of all loaded resources @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") // remove this once TO-DO below is addressed private static final NonBlockingHashMap<String,byte[]> _cache = new NonBlockingHashMap<>(); // Returns the response containing the given uri with the appropriate mime type. private static NanoResponse getResource(RequestType request_type, String url) { byte[] bytes = _cache.get(url); if (bytes == null) { // Try-with-resource try (InputStream resource = water.init.JarHash.getResource2(url)) { if( resource != null ) { try { bytes = toByteArray(resource); } catch (IOException e) { Log.err(e); } // PP 06-06-2014 Disable caching for now so that the browser // always gets the latest sources and assets when h2o-client is rebuilt. // TODO need to rethink caching behavior when h2o-dev is merged into h2o. // if (bytes != null) { // byte[] res = _cache.putIfAbsent(url, bytes); // if (res != null) bytes = res; // Racey update; take what is in the _cache } } catch( IOException ignore ) { } } if (bytes == null || bytes.length == 0) // No resource found? return response404("Resource " + url, request_type); int i = url.lastIndexOf('.'); String mime; switch (url.substring(i + 1)) { case "js": mime = MIME_JS; break; case "css": mime = MIME_CSS; break; case "htm":case "html": mime = MIME_HTML; break; case "jpg":case "jpeg": mime = MIME_JPEG; break; case "png": mime = MIME_PNG; break; case "svg": mime = MIME_SVG; break; case "gif": mime = MIME_GIF; break; case "woff": mime = MIME_WOFF; break; default: mime = MIME_DEFAULT_BINARY; } NanoResponse res = new NanoResponse(HTTP_OK, mime, new ByteArrayInputStream(bytes)); res.addHeader("Content-Length", Long.toString(bytes.length)); return res; } // Convenience utility private static byte[] toByteArray(InputStream is) throws IOException { try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { byte[] buffer = new byte[0x2000]; for (int len; (len = is.read(buffer)) != -1; ) os.write(buffer, 0, len); return os.toByteArray(); } } /** * Dummy Rest API context which is redirecting calls to static method API. */ public static class DummyRestApiContext implements RestApiContext { @Override public Route registerEndpoint(String apiName, String methodUri, Class<? extends Handler> handlerClass, String handlerMethod, String summary) { return RequestServer.registerEndpoint(apiName, methodUri, handlerClass, handlerMethod, summary); } @Override public Route registerEndpoint(String apiName, String httpMethod, String url, Class<? extends Handler> handlerClass, String handlerMethod, String summary, HandlerFactory handlerFactory) { return RequestServer.registerEndpoint(apiName, httpMethod, url, handlerClass, handlerMethod, summary, handlerFactory); } @Override public Route registerEndpoint(String methodUri, Class<? extends RestApiHandler> handlerClass) { return RequestServer.registerEndpoint(methodUri, handlerClass); } private Set<Schema> allSchemas = new HashSet<>(); @Override public void registerSchema(Schema... schemas) { for (Schema schema : schemas) { allSchemas.add(schema); } } public Schema[] getAllSchemas() { return allSchemas.toArray(new Schema[0]); } }; }
package br.com.caelum.tubaina.parser.html.desktop; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import org.junit.Before; import org.junit.Test; import br.com.caelum.tubaina.util.CommandExecutor; public class HtmlSyntaxHighlighterTest { private String sampleCode; @Before public void setUp() { sampleCode = "public class Foo {\n" + "public int Bar(){\n" + "return 0;\n" + "}\n" + "}"; } @Test public void shouldCallPygmentsWithJavaLexer() throws Exception { CommandExecutor executor = mock(CommandExecutor.class); String code = "public class Foo {\n" + "public int Bar(){\n" + "return 0;\n" + "}\n" + "}"; HtmlSyntaxHighlighter highlighter = new HtmlSyntaxHighlighter(executor); highlighter.highlight(code, "java", false); String encoding = System.getProperty("file.encoding"); verify(executor).execute( eq("pygmentize -O encoding=" + encoding + ",outencoding=UTF-8 -f html -l java"), eq(sampleCode)); } @Test public void shouldCallPygmentsWithNumberedLinesOption() throws Exception { CommandExecutor executor = mock(CommandExecutor.class); HtmlSyntaxHighlighter highlighter = new HtmlSyntaxHighlighter(executor); highlighter.highlight(sampleCode, "java", true); String encoding = System.getProperty("file.encoding"); verify(executor).execute( eq("pygmentize -O encoding=" + encoding + ",outencoding=UTF-8,linenos=inline -f html -l java"), eq(sampleCode)); } }
package com.aol.cyclops.functions.collections.extensions.standard; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; import java.util.HashMap; import java.util.Map; import org.jooq.lambda.tuple.Tuple; import org.junit.Test; import com.aol.cyclops.data.collections.extensions.standard.DequeX; import com.aol.cyclops.data.collections.extensions.standard.ListX; import com.aol.cyclops.data.collections.extensions.standard.MapX; import com.aol.cyclops.data.collections.extensions.standard.MapXs; import com.aol.cyclops.data.collections.extensions.standard.QueueX; import com.aol.cyclops.data.collections.extensions.standard.SetX; import com.aol.cyclops.data.collections.extensions.standard.SortedSetX; public class MapXsTest { @Test public void toListX(){ MapX<String,Integer> maps = MapXs.of("a",1,"b",2); ListX<String> strs = maps.toListX(t->""+t.v1+t.v2); assertThat(strs,equalTo(ListX.of("a1","b2"))); } @Test public void toSetX(){ MapX<String,Integer> maps = MapXs.of("a",1,"b",2); SetX<String> strs = maps.toSetX(t->""+t.v1+t.v2); assertThat(strs,equalTo(SetX.of("a1","b2"))); } @Test public void toSortedSetX(){ MapX<String,Integer> maps = MapXs.of("a",1,"b",2); SortedSetX<String> strs = maps.toSortedSetX(t->""+t.v1+t.v2); assertThat(strs,equalTo(SortedSetX.of("a1","b2"))); } @Test public void toQueueX(){ MapX<String,Integer> maps = MapXs.of("a",1,"b",2); QueueX<String> strs = maps.toQueueX(t->""+t.v1+t.v2); assertThat(strs.toList(),equalTo(QueueX.of("a1","b2").toList())); } @Test public void toDequeX(){ MapX<String,Integer> maps = MapXs.of("a",1,"b",2); DequeX<String> strs = maps.toDequeX(t->""+t.v1+t.v2); assertThat(strs,equalTo(QueueX.of("a1","b2"))); } @Test public void onEmpty(){ assertThat(MapX.empty().onEmpty(Tuple.tuple("hello",10)).get("hello"),equalTo(10)); } @Test public void onEmptyGet(){ assertThat(MapX.empty().onEmptyGet(()->Tuple.tuple("hello",10)).get("hello"),equalTo(10)); } @Test(expected=RuntimeException.class) public void onEmptyThrow(){ MapX.empty().onEmptyThrow(()->new RuntimeException("hello")); } @Test public void onEmptySwitch(){ assertThat(MapX.<String,Integer>empty().onEmptySwitch(()->MapX.fromMap(MapXs.of("hello",10))).get("hello"),equalTo(10)); } @Test public void testOf() { assertThat(MapXs.of(),equalTo(new HashMap())); } @Test public void testOfKV() { Map<String,Integer> map = new HashMap<>(); map.put("key",1); assertThat(MapXs.of("key",1),equalTo(map)); } @Test public void testOfKVKV() { Map<String,Integer> map = new HashMap<>(); map.put("1",1); map.put("2",2); assertThat(MapXs.of("1",1,"2",2),equalTo(map)); } @Test public void testOfKVKVKV() { Map<String,Integer> map = new HashMap<>(); map.put("1",1); map.put("2",2); map.put("3",3); assertThat(MapXs.of("1",1,"2",2,"3",3),equalTo(map)); } @Test public void testOfKVKVKVKV() { Map<String,Integer> map = new HashMap<>(); map.put("1",1); map.put("2",2); map.put("3",3); map.put("4",4); assertThat(MapXs.of("1",1,"2",2,"3",3,"4",4),equalTo(map)); } @Test public void testFrom() { Map<String,Integer> map = new HashMap<>(); map.put("1",1); map.put("2",2); map.put("3",3); map.put("4",4); assertThat(MapXs.from(map).build(),equalTo(map)); } @Test public void testMapKV() { Map<String,Integer> map = new HashMap<>(); map.put("1",1); map.put("2",2); assertThat(MapXs.map("1",1).put("2", 2).build(),equalTo(map)); } @Test public void testMapKVPutAll() { Map<String,Integer> map = new HashMap<>(); map.put("1",1); map.put("2",2); map.put("3",3); map.put("4",4); map.put("5",5); map.put("6",6); Map<String,Integer> map2 = new HashMap<>(); map2.put("1",1); map2.put("2",2); map2.put("3",3); map2.put("4",4); map2.put("5",5); map2.put("6",6); assertThat(MapXs.map("1",1).putAll(map2).build(),equalTo(map)); } @Test public void testMapKVKV() { Map<String,Integer> map = new HashMap<>(); map.put("1",1); map.put("2",2); map.put("3",3); map.put("4",4); assertThat(MapXs.map("1",1,"2", 2).put("3", 3,"4",4).build(),equalTo(map)); } @Test public void testMapKVKVKV() { Map<String,Integer> map = new HashMap<>(); map.put("1",1); map.put("2",2); map.put("3",3); map.put("4",4); map.put("5",5); map.put("6",6); assertThat(MapXs.map("1",1,"2", 2,"3", 3).put("4",4,"5",5,"6",6).build(),equalTo(map)); } @Test public void testMapKVKVKVKV() { Map<String,Integer> map = new HashMap<>(); map.put("1",1); map.put("2",2); map.put("3",3); map.put("4",4); map.put("5",5); map.put("6",6); map.put("7",7); map.put("8",8); assertThat(MapXs.map("1",1,"2", 2,"3", 3,"4",4).put("5",5,"6",6,"7",7,"8",8).build(),equalTo(map)); } }
package com.siemens.ct.exi.grammars.persistency; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import junit.framework.TestCase; import org.junit.Test; import com.siemens.ct.exi.core.exceptions.EXIException; import com.siemens.ct.exi.core.grammars.SchemaInformedGrammars; import com.siemens.ct.exi.grammars.XSDGrammarsBuilder; public class Grammars2JavaSourceCodeTest extends TestCase { static String USER_HOME = System.getProperty("user.home"); static String TMP_DIR = System.getProperty("java.io.tmpdir"); static String WORKSPACE_DIR = System.getProperty("workspace"); static String FILE_SEPARATOR = System.getProperty("file.separator"); static String OS = System.getProperty("os.name").toLowerCase(); static final String EXIFICIENT_CORE_JAR = "/.m2/repository/com/siemens/ct/exi/exificient-core/1.0.2-SNAPSHOT/exificient-core-1.0.2-SNAPSHOT.jar"; XSDGrammarsBuilder grammarBuilder = XSDGrammarsBuilder.newInstance(); public Grammars2JavaSourceCodeTest() throws EXIException { super(); } protected void _test(String xsd) throws EXIException, IOException { grammarBuilder.loadGrammars(xsd); SchemaInformedGrammars grammars = grammarBuilder.toGrammars(); Grammars2JavaSourceCode g2j = new Grammars2JavaSourceCode(grammars); g2j.generateCode(); String packageName = Grammars2JavaSourceCode.class.getPackage() .toString(); String className = "Test" + System.currentTimeMillis(); String sSource = g2j.getGrammars(packageName, className); // further validation (try to compile Java Code) String sTempDir = getTemporaryFolder("javaSource_"); String jpath = packageName.replace("package ", ""); // replace leading // "package "; jpath = jpath.replaceAll("\\.", "/"); // replace all dots with file // separator File f = new File(sTempDir + jpath + "/" + className + ".java"); f.getParentFile().mkdirs(); writeStringToFile(sSource, f); System.out.println("File " + f + " exists: " + f.exists()); String sCmd = "javac -cp " + getEXIficientCoreJar() + " " + sTempDir + jpath + "/" + "*.java"; System.out.println("CMD: " + sCmd); ProcessBuilder builder; if (isWindows()) { builder = new ProcessBuilder("javac", "-cp", getEXIficientCoreJar(), sTempDir + jpath + "/" + "*.java"); } else if (isUnix()) { builder = new ProcessBuilder("/bin/sh", "-c", sCmd); } else { throw new RuntimeException("Unsupported operating system: " + OS); } final Process process = builder.start(); // read streams String errMsg = getMsg(process.getErrorStream()); String inpMsg = getMsg(process.getInputStream()); if (errMsg == null || errMsg.startsWith("Picked up _JAVA_OPTIONS")) { // NO Error // Travis seems to report always // "Picked up _JAVA_OPTIONS: -Xmx2048m -Xms512m" } else { if (inpMsg != null) { errMsg += "\nCompilerMsg:\n" + inpMsg; } fail(errMsg); } } static String getEXIficientCoreJar() { // String url = final String DEFAULT_EXIFICIENT_CORE_JAR = USER_HOME + EXIFICIENT_CORE_JAR; return DEFAULT_EXIFICIENT_CORE_JAR; } static void writeStringToFile(String str, File file) throws IOException { BufferedWriter writer = new BufferedWriter(new FileWriter(file)); writer.write(str); writer.close(); } protected static String getMsg(InputStream is) throws IOException { int b; ByteArrayOutputStream baos = new ByteArrayOutputStream(); while ((b = is.read()) != -1) { baos.write(b); } String msg = null; if (baos.size() > 0) { msg = new String(baos.toByteArray()); } baos.close(); return msg; } public static boolean isWindows() { return (OS.indexOf("win") >= 0); } public static boolean isUnix() { return (OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0 || OS .indexOf("aix") > 0); } public static boolean isMac() { return (OS.indexOf("mac") >= 0); } public static boolean isSolaris() { return (OS.indexOf("sunos") >= 0); } String getTemporaryFolder(String prefix) throws IOException { String dirName = TMP_DIR; // + FILE_SEPARATOR; // // System.getProperty("java.io.tmpdir"); // String dirName = "D:" + FILE_SEPARATOR + "EXI_TMP" ; dirName += FILE_SEPARATOR + prefix + System.currentTimeMillis() // + FILE_SEPARATOR ; File f = new File(dirName); if (!f.mkdirs()) { throw new RuntimeException("Error while creating temp folder: " + dirName); } return dirName; } @Test public void testNotebook() throws EXIException, IOException { String xsd = "data/W3C/PrimerNotebook/notebook.xsd"; _test(xsd); } @Test public void testEXIForJSON() throws EXIException, IOException { String xsd = "data/W3C/EXIforJSON/exi4json.xsd"; _test(xsd); } @Test public void testPull5() throws Exception { // very special case: same attribute with different type --> represented // as a String (default string) String xsd = "data/general/pull5.xsd"; _test(xsd); } @Test public void testGaml100() throws EXIException, IOException { String xsd = "data/Gaml/gaml100.xsd"; _test(xsd); } }
package com.wandrell.testing.persistence.util.model; import java.util.Collection; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.stereotype.Repository; import com.wandrell.pattern.repository.DefaultQueryData; import com.wandrell.pattern.repository.FilteredRepository; import com.wandrell.pattern.repository.QueryData; import com.wandrell.persistence.repository.JPARepository; @Repository public final class JPATestEntityRepository implements TestEntityRepository { private FilteredRepository<JPATestEntity, QueryData> repository; /** * Constructs a {@code JPATestEntityRepository}. */ public JPATestEntityRepository() { super(); } @Override public final void add(final JPATestEntity entity) { getBaseRepository().add(entity); } @Override public final Collection<JPATestEntity> getAll() { return getBaseRepository().getAll(); } @Override public final Collection<JPATestEntity> getCollection(final QueryData filter) { return getBaseRepository().getCollection(filter); } @Override public final JPATestEntity getEntity(final QueryData filter) { return getBaseRepository().getEntity(filter); } @Override public final void remove(final JPATestEntity entity) { getBaseRepository().remove(entity); } @PersistenceContext public final void setEntityManager(final EntityManager entityManager) { repository = new JPARepository<JPATestEntity>(entityManager, new DefaultQueryData("SELECT entity FROM TestEntity entity")); } @Override public final void update(final JPATestEntity entity) { getBaseRepository().update(entity); } private final FilteredRepository<JPATestEntity, QueryData> getBaseRepository() { return repository; } }
package org.sagebionetworks.web.unitclient.widget.table; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.sagebionetworks.repo.model.EntityBundle; import org.sagebionetworks.repo.model.EntityChildrenRequest; import org.sagebionetworks.repo.model.EntityChildrenResponse; import org.sagebionetworks.repo.model.EntityHeader; import org.sagebionetworks.repo.model.EntityType; import org.sagebionetworks.repo.model.Project; import org.sagebionetworks.repo.model.auth.UserEntityPermissions; import org.sagebionetworks.repo.model.entity.Direction; import org.sagebionetworks.repo.model.entity.SortBy; import org.sagebionetworks.web.client.DisplayUtils; import org.sagebionetworks.web.client.SynapseJavascriptClient; import org.sagebionetworks.web.client.cookie.CookieProvider; import org.sagebionetworks.web.client.utils.CallbackP; import org.sagebionetworks.web.client.widget.LoadMoreWidgetContainer; import org.sagebionetworks.web.client.widget.entity.controller.SynapseAlert; import org.sagebionetworks.web.client.widget.table.TableListWidget; import org.sagebionetworks.web.client.widget.table.TableListWidgetView; import org.sagebionetworks.web.client.widget.table.modal.fileview.CreateTableViewWizard; import org.sagebionetworks.web.test.helper.AsyncMockStubber; import com.google.gwt.user.client.rpc.AsyncCallback; public class TableListWidgetTest { private static final String ENTITY_ID = "syn123"; private TableListWidgetView mockView; private TableListWidget widget; private EntityBundle parentBundle; private UserEntityPermissions permissions; @Mock CreateTableViewWizard mockCreateTableViewWizard; @Mock CookieProvider mockCookies; @Mock LoadMoreWidgetContainer mockLoadMoreWidgetContainer; @Mock EntityChildrenResponse mockResults; @Mock SynapseJavascriptClient mockSynapseJavascriptClient; @Mock SynapseAlert mockSynAlert; @Mock CallbackP<String> mockTableClickedCallback; List<EntityHeader> searchResults; @Before public void before(){ MockitoAnnotations.initMocks(this); permissions = new UserEntityPermissions(); permissions.setCanEdit(true); Project project = new Project(); project.setId(ENTITY_ID); parentBundle = new EntityBundle(); parentBundle.setEntity(project); parentBundle.setPermissions(permissions); mockView = Mockito.mock(TableListWidgetView.class); widget = new TableListWidget(mockView, mockSynapseJavascriptClient, mockLoadMoreWidgetContainer, mockSynAlert); AsyncMockStubber.callSuccessWith(mockResults).when(mockSynapseJavascriptClient).getEntityChildren(any(EntityChildrenRequest.class), any(AsyncCallback.class)); searchResults = new ArrayList<EntityHeader>(); when(mockResults.getPage()).thenReturn(searchResults); when(mockCookies.getCookie(DisplayUtils.SYNAPSE_TEST_WEBSITE_COOKIE_KEY)).thenReturn("true"); } @Test public void testCreateQuery(){ String parentId = ENTITY_ID; EntityChildrenRequest query = widget.createQuery(parentId); assertEquals(parentId, query.getParentId()); assertTrue(query.getIncludeTypes().contains(EntityType.entityview)); assertTrue(query.getIncludeTypes().contains(EntityType.table)); assertEquals(SortBy.CREATED_ON, query.getSortBy()); assertEquals(Direction.DESC, query.getSortDirection()); } @Test public void testConfigureUnderPageSize(){ widget.configure(parentBundle); verify(mockView, times(2)).hideLoading(); verify(mockView).resetSortUI(); verify(mockLoadMoreWidgetContainer).setIsMore(false); } @Test public void testConfigureOverPageSize(){ when(mockResults.getNextPageToken()).thenReturn("ismore"); widget.configure(parentBundle); verify(mockView).resetSortUI(); verify(mockLoadMoreWidgetContainer).setIsMore(true); } @Test public void testConfigureFailure(){ parentBundle.getPermissions().setCanEdit(false); String error = "an error"; Throwable th = new Throwable(error); AsyncMockStubber.callFailureWith(th).when(mockSynapseJavascriptClient).getEntityChildren(any(EntityChildrenRequest.class), any(AsyncCallback.class)); widget.configure(parentBundle); verify(mockSynAlert).handleException(th); } @Test public void testOnTableClicked() { widget.setTableClickedCallback(mockTableClickedCallback); widget.onTableClicked(ENTITY_ID); verify(mockView).showLoading(); verify(mockView).clearTableWidgets(); verify(mockTableClickedCallback).invoke(ENTITY_ID); } }
package picard.sam.markduplicates; import htsjdk.samtools.SAMRecord; import htsjdk.samtools.SamReader; import htsjdk.samtools.SamReaderFactory; import htsjdk.samtools.metrics.MetricsFile; import org.apache.commons.lang3.StringUtils; import org.testng.Assert; import picard.cmdline.CommandLineProgram; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.List; /** * This class is an extension of AbstractMarkDuplicatesCommandLineProgramTester used to test * AbstractMarkDuplicatesCommandLineProgram's with SAM files generated on the fly. This performs the underlying tests * defined by classes such as AbstractMarkDuplicatesCommandLineProgramTest. * @author fleharty */ public class UmiAwareMarkDuplicatesWithMateCigarTester extends AbstractMarkDuplicatesCommandLineProgramTester { private int readNameCounter = 0; private List<String> expectedAssignedUmis; private UmiMetrics expectedMetrics; private File umiMetricsFile = new File(getOutputDir(), "umi_metrics.txt"); // This tag is only used for testing, it indicates what we expect to see in the inferred UMI tag. private final String expectedUmiTag = "RE"; // This default constructor is intended to be used by tests inherited from // AbstractMarkDuplicatesCommandLineProgramTester. Since those tests use // reads that don't have UMIs we enable the ALLOW_MISSING_UMIS option. UmiAwareMarkDuplicatesWithMateCigarTester() { addArg("UMI_METRICS_FILE=" + umiMetricsFile); addArg("ALLOW_MISSING_UMIS=" + true); } UmiAwareMarkDuplicatesWithMateCigarTester(final boolean allowMissingUmis) { addArg("UMI_METRICS_FILE=" + umiMetricsFile); if (allowMissingUmis) { addArg("ALLOW_MISSING_UMIS=" + true); } } @Override public void recordOpticalDuplicatesMarked() {} public void addMatePairWithUmi(final String library, final String umi, final String assignedUMI, final boolean isDuplicate1, final boolean isDuplicate2) { final String readName = "READ" + readNameCounter++; final String cigar1 = null; final String cigar2 = null; final boolean strand1 = false; final boolean strand2 = true; final int referenceSequenceIndex1 = 0; final int referenceSequenceIndex2 = 0; final int alignmentStart1 = 20; final int alignmentStart2 = 20; final boolean record1Unmapped = false; final boolean record2Unmapped = false; final boolean firstOnly = false; final boolean record1NonPrimary = false; final boolean record2NonPrimary = false; final int defaultQuality = 10; addMatePairWithUmi(library, readName, referenceSequenceIndex1, referenceSequenceIndex2, alignmentStart1, alignmentStart2, record1Unmapped, record2Unmapped, isDuplicate1, isDuplicate2, cigar1, cigar2, strand1, strand2, firstOnly, record1NonPrimary, record2NonPrimary, defaultQuality, umi, assignedUMI); } public void addMatePairWithUmi(final String library, final String umi, final String assignedUMI, final boolean isDuplicate1, final boolean isDuplicate2, final int alignmentStart1, final int alignmentStart2, final boolean strand1, final boolean strand2) { final String readName = "READ" + readNameCounter++; final String cigar1 = null; final String cigar2 = null; final int referenceSequenceIndex1 = 0; final int referenceSequenceIndex2 = 0; final boolean record1Unmapped = false; final boolean record2Unmapped = false; final boolean firstOnly = false; final boolean record1NonPrimary = false; final boolean record2NonPrimary = false; final int defaultQuality = 10; addMatePairWithUmi(library, readName, referenceSequenceIndex1, referenceSequenceIndex2, alignmentStart1, alignmentStart2, record1Unmapped, record2Unmapped, isDuplicate1, isDuplicate2, cigar1, cigar2, strand1, strand2, firstOnly, record1NonPrimary, record2NonPrimary, defaultQuality, umi, assignedUMI); } public void addMatePairWithUmi(final String library, final String readName, final int referenceSequenceIndex1, final int referenceSequenceIndex2, final int alignmentStart1, final int alignmentStart2, final boolean record1Unmapped, final boolean record2Unmapped, final boolean isDuplicate1, final boolean isDuplicate2, final String cigar1, final String cigar2, final boolean strand1, final boolean strand2, final boolean firstOnly, final boolean record1NonPrimary, final boolean record2NonPrimary, final int defaultQuality, final String umi, final String assignedUMI) { final List<SAMRecord> samRecordList = samRecordSetBuilder.addPair(readName, referenceSequenceIndex1, referenceSequenceIndex2, alignmentStart1, alignmentStart2, record1Unmapped, record2Unmapped, cigar1, cigar2, strand1, strand2, record1NonPrimary, record2NonPrimary, defaultQuality); final SAMRecord record1 = samRecordList.get(0); final SAMRecord record2 = samRecordList.get(1); record1.getReadGroup().setLibrary(library); record2.getReadGroup().setLibrary(library); if (this.noMateCigars) { record1.setAttribute("MC", null); record2.setAttribute("MC", null); } if (firstOnly) { samRecordSetBuilder.getRecords().remove(record2); } final String key1 = samRecordToDuplicatesFlagsKey(record1); Assert.assertFalse(this.duplicateFlags.containsKey(key1)); this.duplicateFlags.put(key1, isDuplicate1); final String key2 = samRecordToDuplicatesFlagsKey(record2); Assert.assertFalse(this.duplicateFlags.containsKey(key2)); this.duplicateFlags.put(key2, isDuplicate2); if (umi != null) { // TODO: Replace "RX" with SAMTag.RX once this tag is available in HTSJDK record1.setAttribute("RX", umi); record2.setAttribute("RX", umi); } if (assignedUMI != null) { // Set the expected UMI, this is a special tag used only for testing. record1.setAttribute(expectedUmiTag, assignedUMI); record2.setAttribute(expectedUmiTag, assignedUMI); } } UmiAwareMarkDuplicatesWithMateCigarTester setExpectedAssignedUmis(final List<String> expectedAssignedUmis) { this.expectedAssignedUmis = expectedAssignedUmis; return this; } UmiAwareMarkDuplicatesWithMateCigarTester setExpectedMetrics(final UmiMetrics expectedMetrics) { this.expectedMetrics = expectedMetrics; return this; } @Override public void test() { final SamReader reader = SamReaderFactory.makeDefault().open(getOutput()); for (final SAMRecord record : reader) { // If there are expected assigned UMIs, check to make sure they match if (expectedAssignedUmis != null) { Assert.assertEquals(getAssignedUmi(record.getStringAttribute("MI")), record.getAttribute(expectedUmiTag)); } } if (expectedMetrics != null) { // Check the values written to metrics.txt against our input expectations final MetricsFile<UmiMetrics, Comparable<?>> metricsOutput = new MetricsFile<UmiMetrics, Comparable<?>>(); try { metricsOutput.read(new FileReader(umiMetricsFile)); } catch (final FileNotFoundException ex) { System.err.println("Metrics file not found: " + ex); } final double tolerance = 1e-6; Assert.assertEquals(metricsOutput.getMetrics().size(), 1); final UmiMetrics observedMetrics = metricsOutput.getMetrics().get(0); Assert.assertEquals(observedMetrics.LIBRARY, expectedMetrics.LIBRARY, "LIBRARY does not match expected"); Assert.assertEquals(observedMetrics.MEAN_UMI_LENGTH, expectedMetrics.MEAN_UMI_LENGTH, "UMI_LENGTH does not match expected"); Assert.assertEquals(observedMetrics.OBSERVED_UNIQUE_UMIS, expectedMetrics.OBSERVED_UNIQUE_UMIS, "OBSERVED_UNIQUE_UMIS does not match expected"); Assert.assertEquals(observedMetrics.INFERRED_UNIQUE_UMIS, expectedMetrics.INFERRED_UNIQUE_UMIS, "INFERRED_UNIQUE_UMIS does not match expected"); Assert.assertEquals(observedMetrics.OBSERVED_BASE_ERRORS, expectedMetrics.OBSERVED_BASE_ERRORS, "OBSERVED_BASE_ERRORS does not match expected"); Assert.assertEquals(observedMetrics.DUPLICATE_SETS_IGNORING_UMI, expectedMetrics.DUPLICATE_SETS_IGNORING_UMI, "DUPLICATE_SETS_IGNORING_UMI does not match expected"); Assert.assertEquals(observedMetrics.DUPLICATE_SETS_WITH_UMI, expectedMetrics.DUPLICATE_SETS_WITH_UMI, "DUPLICATE_SETS_WITH_UMI does not match expected"); Assert.assertEquals(observedMetrics.INFERRED_UMI_ENTROPY, expectedMetrics.INFERRED_UMI_ENTROPY, tolerance, "INFERRED_UMI_ENTROPY does not match expected"); Assert.assertEquals(observedMetrics.OBSERVED_UMI_ENTROPY, expectedMetrics.OBSERVED_UMI_ENTROPY, tolerance, "OBSERVED_UMI_ENTROPY does not match expected"); Assert.assertEquals(observedMetrics.UMI_BASE_QUALITIES, expectedMetrics.UMI_BASE_QUALITIES, tolerance, "UMI_BASE_QUALITIES does not match expected"); Assert.assertEquals(observedMetrics.PCT_UMI_WITH_N, expectedMetrics.PCT_UMI_WITH_N, tolerance,"PERCENT_UMI_WITH_N does not match expected" ); } // Also do tests from AbstractMarkDuplicatesCommandLineProgramTester try { super.test(); } catch (IOException ex) { Assert.fail("Could not open metrics file: ", ex); } } @Override protected CommandLineProgram getProgram() { UmiAwareMarkDuplicatesWithMateCigar uamdwmc = new UmiAwareMarkDuplicatesWithMateCigar(); return uamdwmc; } /** * * @param molecularIndex * @return */ private String getAssignedUmi(final String molecularIndex) { if (molecularIndex == null) { return null; } if (StringUtils.countMatches(molecularIndex, UmiUtil.UMI_NAME_SEPARATOR) == 2) { return StringUtils.substringBetween(molecularIndex, UmiUtil.UMI_NAME_SEPARATOR, UmiUtil.UMI_NAME_SEPARATOR); } else { return StringUtils.substringAfter(molecularIndex, UmiUtil.UMI_NAME_SEPARATOR); } } }
package pl.grzeslowski.jsupla.proto.serializers; import org.junit.Test; import static java.lang.Integer.MAX_VALUE; import static java.lang.Integer.MIN_VALUE; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Fail.fail; import static pl.grzeslowski.jsupla.consts.JavaConsts.INT_SIZE; public class PrimitiveIntSerizaliserTest { private static final int VALUE_THAT_I_DO_NOT_CARE = 5; @Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionWhenArrayIsToSmall() { // given byte[] bytes = new byte[INT_SIZE - 1]; // when PrimitiveSerizaliser.putUnsignedInt(VALUE_THAT_I_DO_NOT_CARE, bytes, 0); // then fail("Should throw IllegalArgumentException"); } @Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionWhenArrayIsToSmallBecauseOfOffset() { // given int offset = 3; byte[] bytes = new byte[offset + INT_SIZE - 1]; // when PrimitiveSerizaliser.putUnsignedInt(VALUE_THAT_I_DO_NOT_CARE, bytes, offset); // then fail("Should throw IllegalArgumentException"); } @Test public void shouldPutSmallUnsignedIntIntoBuffer() { // given int value = 5 + MIN_VALUE; // 5(10) is 00000101(2) byte[] bytes = new byte[INT_SIZE]; // when PrimitiveSerizaliser.putUnsignedInt(value, bytes, 0); // then assertThat(bytes[0]).isEqualTo((byte) 5); assertThat(bytes[1]).isEqualTo((byte) 0); assertThat(bytes[2]).isEqualTo((byte) 0); assertThat(bytes[3]).isEqualTo((byte) 0); } @Test public void shouldPutFullUnsignedIntIntoBuffer() { // given /* * 2857749555 + Integer.MIN_VALUE = 710265907 */ int value = 710265907; // 2857749555(10) is 10101010 01010101 11001100 00110011(2) byte[] bytes = new byte[INT_SIZE]; // when PrimitiveSerizaliser.putUnsignedInt(value, bytes, 0); // then assertThat(bytes[0]).isEqualTo((byte) 51); assertThat(bytes[1]).isEqualTo((byte) 204); assertThat(bytes[2]).isEqualTo((byte) 85); assertThat(bytes[3]).isEqualTo((byte) 170); } @Test public void shouldPutFullUnsignedIntIntoBufferWithOffset() { // given /* * 2857749555 + Integer.MIN_VALUE = 710265907 */ int value = 710265907; // 2857749555(10) is 10101010 01010101 11001100 00110011(2) int offset = 5; byte[] bytes = new byte[INT_SIZE + offset]; // when PrimitiveSerizaliser.putUnsignedInt(value, bytes, offset); // then //noinspection PointlessArithmeticExpression assertThat(bytes[offset + 0]).isEqualTo((byte) 51); assertThat(bytes[offset + 1]).isEqualTo((byte) 204); assertThat(bytes[offset + 2]).isEqualTo((byte) 85); assertThat(bytes[offset + 3]).isEqualTo((byte) 170); } @SuppressWarnings("UnnecessaryLocalVariable") @Test public void shouldPutMinimalUnsignedIntIntoBuffer() { // given int value = MIN_VALUE; byte[] bytes = new byte[INT_SIZE]; // when PrimitiveSerizaliser.putUnsignedInt(value, bytes, 0); // then assertThat(bytes[0]).isEqualTo((byte) 0); assertThat(bytes[1]).isEqualTo((byte) 0); assertThat(bytes[2]).isEqualTo((byte) 0); assertThat(bytes[3]).isEqualTo((byte) 0); } @SuppressWarnings("UnnecessaryLocalVariable") @Test public void shouldPutMaxUnsignedIntIntoBuffer() { // given int value = MAX_VALUE; byte[] bytes = new byte[INT_SIZE]; // when PrimitiveSerizaliser.putUnsignedInt(value, bytes, 0); // then assertThat(bytes[0]).isEqualTo((byte) -1); assertThat(bytes[1]).isEqualTo((byte) -1); assertThat(bytes[2]).isEqualTo((byte) -1); assertThat(bytes[3]).isEqualTo((byte) -1); } }
package de.mwvb.stechuhr.gui.bearbeiten; import java.time.LocalTime; import java.util.Optional; import de.mwvb.stechuhr.Application; import de.mwvb.stechuhr.dao.StechuhrDAO; import de.mwvb.stechuhr.entity.Stunden; import de.mwvb.stechuhr.gui.StageAdapter; import de.mwvb.stechuhr.gui.Window; import de.mwvb.stechuhr.gui.stechuhr.StechuhrWindow; import javafx.application.Platform; import javafx.beans.value.ChangeListener; import javafx.fxml.FXML; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.Button; import javafx.scene.control.ButtonType; import javafx.scene.control.TableView; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.stage.Stage; public class BearbeitenWindowController { @FXML private TextField uhrzeit; @FXML private TextField leistung; @FXML private TextField ticket; @FXML private TextArea notizPrivat; @FXML private Button save; @FXML private Button delete; @FXML private Button close; @FXML private TableView<Stunden> grid; @FXML protected void initialize() { try { Window.disableTabKey(notizPrivat); save.setDefaultButton(true); grid.addEventFilter(KeyEvent.KEY_PRESSED, event -> { KeyCode code = event.getCode(); if (KeyCode.DELETE.equals(code)) { onDelete(); } }); grid.getSelectionModel().selectedItemProperty().addListener((a, b, sel) -> { display((Stunden) sel); save.setDisable(true); }); save.setDisable(true); ChangeListener<? super String> listener = (observable, oldValue, newValue) -> { if (!grid.getSelectionModel().getSelectedIndices().isEmpty()) { save.setDisable(false); } }; this.uhrzeit.textProperty().addListener(listener); this.ticket.textProperty().addListener(listener); this.leistung.textProperty().addListener(listener); this.notizPrivat.textProperty().addListener(listener); Platform.runLater(() -> leistung.requestFocus()); } catch (Exception e) { Window.errorAlert(e); } } public void model2View() { try { getStage().addEventFilter(KeyEvent.KEY_PRESSED, event -> { KeyCode code = event.getCode(); if (KeyCode.ESCAPE.equals(code)) { event.consume(); onClose(); } }); StechuhrWindow.model.calculateDauer(); grid.getItems().addAll(StechuhrWindow.model.getStundenliste()); final int index = grid.getItems().size() - 1; if (index >= 0) { grid.getSelectionModel().select(index); Platform.runLater(() -> grid.scrollTo(index)); } else { delete.setDisable(true); } } catch (Exception e) { Window.errorAlert(e); } } private void display(Stunden s) { try { if (s == null) return; if (s.getUhrzeit() != null) { uhrzeit.setText(s.getUhrzeit().toString()); } else { uhrzeit.setText(""); } ticket.setText(s.getTicket()); leistung.setText(s.getLeistung()); notizPrivat.setText(s.getNotizPrivat()); } catch (Exception e) { Window.errorAlert(e); } } @FXML public void onSave() { try { int i = grid.getSelectionModel().getSelectedIndex(); if (i < 0) return; Stunden s = grid.getItems().get(i); if (s == null) return; // Validierung String ut = validateUhrzeit(i); if (ut == null) return; String nr = validateTicket(ticket.getText()); s.setUhrzeit(LocalTime.parse(ut)); s.setTicket(nr); s.setLeistung(leistung.getText().trim()); s.setNotizPrivat(notizPrivat.getText()); updateGrid_andSave(); uhrzeit.setText(ut); ticket.setText(nr); leistung.setText(s.getLeistung()); save.setDisable(true); } catch (Exception e) { Window.errorAlert(e); } } private String validateUhrzeit(int i) { // Uhrzeit valide? String ut = uhrzeit.getText().trim(); ut = validateUhrzeit(ut); if (ut == null) { return null; } LocalTime davor = LocalTime.MIDNIGHT; if (i > 0) { davor = grid.getItems().get(i - 1).getUhrzeit(); } if (LocalTime.parse(ut).isBefore(davor)) { Window.alert("Bitte gebe eine Uhrzeit nach " + davor.toString() + " ein!" + "\nAlternativ kann auch der Vorgängerdatensatz geändert werden."); return null; } return ut; } /** * Eingegebene Uhrzeit validieren. * @param uhrzeit eingegebene Uhrzeit * @return formatierte Uhrzeit, oder null wenn die Uhrzeit nicht ok ist. Es wurde in dem Fall eine entsprechende Meldung ausgegeben. */ public static String validateUhrzeit(String uhrzeit) { uhrzeit = uhrzeit.replace(",", ":"); // Eingabevereinfachung // TODO Idee: "SMM" und "SSMM" Eingabe auch erlauben if ((uhrzeit.length() == "S:MM".length() && uhrzeit.charAt(1) == ':') || (uhrzeit.length() == "S".length() && uhrzeit.charAt(0) != ':')) { uhrzeit = "0" + uhrzeit; } if (!uhrzeit.contains(":")) { // Aus Kurzfurm "9" wird "09:00". try { int h = Integer.parseInt(uhrzeit); if ("0".equals(uhrzeit) || h > 0) { uhrzeit += ":00"; } } catch (NumberFormatException ignore) { } } try { LocalTime ret = LocalTime.parse(uhrzeit).withSecond(0).withNano(0); return ret.toString(); } catch (Exception e) { Window.alert("Bitte gebe eine Uhrzeit im Format SS:MM ein!"); return null; } } /** * Eingegebene Ticketnummer validieren * @param ticket eingegebene Ticketnummer * @return Ticket wenn ok, sonst null. Es wurde in dem Fall eine entsprechende Meldung ausgegeben. */ public static String validateTicket(String ticket) { ticket = ticket.trim(); if (ticket.isEmpty()) { Window.alert("Bitte Ticketnummer eingeben!"); return null; } else if (ticket.contains(";")) { Window.alert("Das Zeichen \";\" ist in der Ticketnummer nicht erlaubt!"); return null; } return ticket; } @FXML public void onDelete() { try { Stunden s = grid.getSelectionModel().getSelectedItem(); if (s == null) { return; } if (shallDelete(s.getTicket())) { StechuhrWindow.model.getStundenliste().remove(s); grid.getItems().remove(s); if (grid.getItems().isEmpty()) { uhrzeit.setText(""); ticket.setText(""); leistung.setText(""); notizPrivat.setText(""); save.setDisable(true); delete.setDisable(true); } else { int neuerIndex = grid.getSelectionModel().getSelectedIndex() + 1; if (neuerIndex >= grid.getItems().size()) { neuerIndex = grid.getItems().size() - 1; } grid.getSelectionModel().select(neuerIndex); } updateGrid_andSave(); } } catch (Exception e) { Window.errorAlert(e); } } private boolean shallDelete(String ticket) { Alert alert = new Alert(AlertType.CONFIRMATION); alert.setTitle("Löschen"); alert.setHeaderText(""); alert.setContentText("Hiermit l\u00F6schst Du den " + ticket + " Datensatz."); Optional<ButtonType> result = alert.showAndWait(); return result.get() == ButtonType.OK; } private void updateGrid_andSave() { StechuhrWindow.model.calculateDauer(); grid.getColumns().get(0).setVisible(false); // Workaround fr Refresh der Zeile grid.getColumns().get(0).setVisible(true); new StechuhrDAO().save(StechuhrWindow.model); } @FXML public void onClose() { try { Application.config.saveWindowPosition(BearbeitenWindow.class.getSimpleName(), new StageAdapter(getStage())); getStage().close(); } catch (Exception e) { Window.errorAlert(e); } } private Stage getStage() { return (Stage) uhrzeit.getScene().getWindow(); } }
// Kyle Russell // AUT University 2015 package com.graphi.display.layout; import cern.colt.matrix.impl.SparseDoubleMatrix2D; import com.graphi.app.AppManager; import com.graphi.app.Consts; import com.graphi.display.MainMenu; import com.graphi.io.AdjMatrixParser; import com.graphi.io.GMLParser; import com.graphi.io.GraphMLParser; import com.graphi.io.Storage; import com.graphi.plugins.Plugin; import com.graphi.plugins.PluginConfig; import com.graphi.plugins.PluginManager; import com.graphi.sim.GraphPlayback; import com.graphi.util.Edge; import com.graphi.sim.Network; import com.graphi.sim.PlaybackEntry; import com.graphi.util.EdgeLabelTransformer; import com.graphi.util.GraphData; import com.graphi.util.GraphUtilities; import com.graphi.util.MatrixTools; import com.graphi.util.Node; import com.graphi.util.ObjectFillTransformer; import com.graphi.util.VertexLabelTransformer; import com.graphi.util.WeightTransformer; import de.javasoft.swing.DateComboBox; import edu.uci.ics.jung.algorithms.layout.AggregateLayout; import edu.uci.ics.jung.algorithms.layout.FRLayout; import edu.uci.ics.jung.algorithms.matrix.GraphMatrixOperations; import edu.uci.ics.jung.algorithms.scoring.BetweennessCentrality; import edu.uci.ics.jung.algorithms.scoring.ClosenessCentrality; import edu.uci.ics.jung.graph.Graph; import edu.uci.ics.jung.graph.SparseMultigraph; import edu.uci.ics.jung.graph.util.EdgeType; import edu.uci.ics.jung.visualization.VisualizationViewer; import edu.uci.ics.jung.visualization.control.CrossoverScalingControl; import edu.uci.ics.jung.visualization.control.EditingModalGraphMouse; import edu.uci.ics.jung.visualization.control.GraphMouseListener; import edu.uci.ics.jung.visualization.control.ModalGraphMouse; import edu.uci.ics.jung.visualization.control.ScalingControl; import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.GridLayout; import java.util.List; import java.awt.Shape; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.MouseEvent; import java.awt.geom.Ellipse2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.text.MessageFormat; import java.text.SimpleDateFormat; import java.util.AbstractMap.SimpleEntry; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.PriorityQueue; import java.util.Set; import javax.imageio.ImageIO; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.ButtonGroup; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JColorChooser; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSlider; import javax.swing.JSpinner; import javax.swing.JSplitPane; import javax.swing.JTabbedPane; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.SpinnerNumberModel; import javax.swing.SwingUtilities; import javax.swing.Timer; import javax.swing.border.Border; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.table.DefaultTableModel; import net.miginfocom.swing.MigLayout; import org.apache.commons.collections15.Transformer; import org.apache.commons.io.FilenameUtils; public class MainPanel extends JPanel { protected final ControlPanel controlPanel; protected final ScreenPanel screenPanel; protected final JSplitPane splitPane; protected final JScrollPane controlScroll; protected BufferedImage addIcon, removeIcon, colourIcon; protected BufferedImage clipIcon, openIcon, saveIcon; protected BufferedImage editBlackIcon, pointerIcon, moveIcon; protected BufferedImage moveSelectedIcon, editSelectedIcon, pointerSelectedIcon; protected BufferedImage graphIcon, tableIcon, resetIcon, executeIcon; protected BufferedImage editIcon, playIcon, stopIcon, recordIcon, closeIcon; protected GraphData data; protected MainMenu menu; protected JFrame frame; protected AppManager appManager; public MainPanel(AppManager appManager) { setPreferredSize(new Dimension(Consts.WINDOW_WIDTH, Consts.WINDOW_HEIGHT)); setLayout(new BorderLayout()); initResources(); this.appManager = appManager; menu = appManager.getWindow().getMenu(); frame = appManager.getWindow().getFrame(); data = new GraphData(); controlPanel = new ControlPanel(this); screenPanel = new ScreenPanel(this); splitPane = new JSplitPane(); controlScroll = new JScrollPane(controlPanel); controlScroll.setBorder(null); splitPane.setLeftComponent(screenPanel); splitPane.setRightComponent(controlScroll); splitPane.setResizeWeight(Consts.MAIN_SPLIT_WG); add(splitPane, BorderLayout.CENTER); } public GraphData getGraphData() { return data; } public void setGraphData(GraphData data) { this.data = data; } protected void sendToOutput(String output) { SimpleDateFormat sdf = new SimpleDateFormat("K:MM a dd.MM.yy"); String date = sdf.format(new Date()); String prefix = "\n[" + date + "] "; JTextArea outputArea = screenPanel.outputPanel.outputArea; SwingUtilities.invokeLater(()-> { outputArea.setText(outputArea.getText() + prefix + output); }); } protected File getFile(boolean open, String desc, String...extensions) { JFileChooser jfc = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter(desc, extensions); jfc.setFileFilter(filter); if(open) jfc.showOpenDialog(null); else jfc.showSaveDialog(null); return jfc.getSelectedFile(); } protected String getFileExtension(File file) { if(file == null) return ""; return FilenameUtils.getExtension(file.getPath()); } public static JPanel wrapComponents(Border border, Component... components) { JPanel panel = new JPanel(); panel.setBorder(border); for(Component component : components) panel.add(component); return panel; } protected void initResources() { try { addIcon = ImageIO.read(new File(Consts.IMG_DIR + "addSmallIcon.png")); removeIcon = ImageIO.read(new File(Consts.IMG_DIR + "removeSmallIcon.png")); colourIcon = ImageIO.read(new File(Consts.IMG_DIR + "color_icon.png")); clipIcon = ImageIO.read(new File(Consts.IMG_DIR + "clipboard.png")); saveIcon = ImageIO.read(new File(Consts.IMG_DIR + "new_file.png")); openIcon = ImageIO.read(new File(Consts.IMG_DIR + "open_icon.png")); editBlackIcon = ImageIO.read(new File(Consts.IMG_DIR + "editblack.png")); pointerIcon = ImageIO.read(new File(Consts.IMG_DIR + "pointer.png")); moveIcon = ImageIO.read(new File(Consts.IMG_DIR + "move.png")); moveSelectedIcon = ImageIO.read(new File(Consts.IMG_DIR + "move_selected.png")); editSelectedIcon = ImageIO.read(new File(Consts.IMG_DIR + "editblack_selected.png")); pointerSelectedIcon = ImageIO.read(new File(Consts.IMG_DIR + "pointer_selected.png")); graphIcon = ImageIO.read(new File(Consts.IMG_DIR + "graph.png")); tableIcon = ImageIO.read(new File(Consts.IMG_DIR + "table.png")); executeIcon = ImageIO.read(new File(Consts.IMG_DIR + "execute.png")); resetIcon = ImageIO.read(new File(Consts.IMG_DIR + "reset.png")); editIcon = ImageIO.read(new File(Consts.IMG_DIR + "edit.png")); playIcon = ImageIO.read(new File(Consts.IMG_DIR + "play.png")); stopIcon = ImageIO.read(new File(Consts.IMG_DIR + "stop.png")); recordIcon = ImageIO.read(new File(Consts.IMG_DIR + "record.png")); closeIcon = ImageIO.read(new File(Consts.IMG_DIR + "close.png")); } catch(IOException e) { JOptionPane.showMessageDialog(null, "Failed to load resources: " + e.getMessage()); } } public void initConfigPlugins(PluginManager pm) { controlPanel.loadConfigPlugins(pm); } }
package io.lumify.opencvObjectDetector; import io.lumify.core.config.Configuration; import io.lumify.core.exception.LumifyException; import io.lumify.core.ingest.ArtifactDetectedObject; import io.lumify.core.ingest.graphProperty.GraphPropertyWorkData; import io.lumify.core.ingest.graphProperty.GraphPropertyWorker; import io.lumify.core.ingest.graphProperty.GraphPropertyWorkerPrepareData; import io.lumify.core.model.audit.AuditAction; import io.lumify.core.model.properties.LumifyProperties; import io.lumify.core.security.LumifyVisibility; import io.lumify.core.util.LumifyLogger; import io.lumify.core.util.LumifyLoggerFactory; import org.apache.commons.io.IOUtils; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.core.MatOfRect; import org.opencv.core.Rect; import org.opencv.objdetect.CascadeClassifier; import org.securegraph.Element; import org.securegraph.Property; import org.securegraph.Vertex; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import static com.google.common.base.Preconditions.checkNotNull; public class OpenCVObjectDetectorPropertyWorker extends GraphPropertyWorker { private static final LumifyLogger LOGGER = LumifyLoggerFactory.getLogger(OpenCVObjectDetectorPropertyWorker.class); public static final String MULTI_VALUE_KEY_PREFIX = OpenCVObjectDetectorPropertyWorker.class.getName(); public static final String OPENCV_CLASSIFIER_CONCEPT_LIST = "objectdetection.classifierConcepts"; public static final String OPENCV_CLASSIFIER_PATH_PREFIX = "objectdetection.classifier."; public static final String OPENCV_CLASSIFIER_PATH_SUFFIX = ".path"; private static final String PROCESS = OpenCVObjectDetectorPropertyWorker.class.getName(); private List<CascadeClassifierHolder> objectClassifiers = new ArrayList<CascadeClassifierHolder>(); @Override public void prepare(GraphPropertyWorkerPrepareData workerPrepareData) throws Exception { super.prepare(workerPrepareData); loadNativeLibrary(); String conceptListString = (String) workerPrepareData.getStormConf().get(OPENCV_CLASSIFIER_CONCEPT_LIST); checkNotNull(conceptListString, OPENCV_CLASSIFIER_CONCEPT_LIST + " is a required configuration parameter"); String[] classifierConcepts = conceptListString.split(","); for (String classifierConcept : classifierConcepts) { String classifierFilePath = (String) workerPrepareData.getStormConf().get(OPENCV_CLASSIFIER_PATH_PREFIX + classifierConcept + OPENCV_CLASSIFIER_PATH_SUFFIX); File localFile = createLocalFile(classifierFilePath, workerPrepareData.getHdfsFileSystem()); CascadeClassifier objectClassifier = new CascadeClassifier(localFile.getPath()); String iriConfigurationKey = Configuration.ONTOLOGY_IRI_PREFIX + classifierConcept; String conceptIRI = (String) workerPrepareData.getStormConf().get(iriConfigurationKey); if (conceptIRI == null) { throw new LumifyException("Could not find concept IRI for " + iriConfigurationKey); } addObjectClassifier(classifierConcept, objectClassifier, conceptIRI); if (!localFile.delete()) { LOGGER.warn("Could not delete file: %s", localFile.getAbsolutePath()); } } } public void loadNativeLibrary() { try { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); } catch (UnsatisfiedLinkError ex) { String javaLibraryPath = System.getProperty("java.library.path"); throw new RuntimeException("Could not find opencv library: " + Core.NATIVE_LIBRARY_NAME + " (java.library.path: " + javaLibraryPath + ")", ex); } } public void addObjectClassifier(String concept, CascadeClassifier objectClassifier, String conceptIRI) { objectClassifiers.add(new CascadeClassifierHolder(concept, objectClassifier, conceptIRI)); } private File createLocalFile(String classifierFilePath, FileSystem fs) throws IOException { File tempFile = File.createTempFile("lumify-opencv-objdetect", ".xml"); FileOutputStream fos = null; InputStream in = null; try { in = fs.open(new Path(classifierFilePath)); fos = new FileOutputStream(tempFile); IOUtils.copy(in, fos); } catch (IOException e) { throw new LumifyException("Could not create local file", e); } finally { if (in != null) { in.close(); } if (fos != null) { fos.close(); } } return tempFile; } @Override public void execute(InputStream in, GraphPropertyWorkData data) throws Exception { BufferedImage bImage = ImageIO.read(in); List<ArtifactDetectedObject> detectedObjects = detectObjects(bImage); saveDetectedObjects((Vertex) data.getElement(), data.getProperty(), detectedObjects); } private void saveDetectedObjects(Vertex artifactVertex, Property property, List<ArtifactDetectedObject> detectedObjects) { getAuditRepository().auditAnalyzedBy(AuditAction.ANALYZED_BY, artifactVertex, getClass().getSimpleName(), getUser(), artifactVertex.getVisibility()); for (ArtifactDetectedObject detectedObject : detectedObjects) { saveDetectedObject(artifactVertex, property, detectedObject); } } private void saveDetectedObject(Vertex artifactVertex, Property property, ArtifactDetectedObject detectedObject) { String multiKey = detectedObject.getMultivalueKey(MULTI_VALUE_KEY_PREFIX); LumifyProperties.DETECTED_OBJECT.addPropertyValue(artifactVertex, multiKey, detectedObject, property.getMetadata(), new LumifyVisibility().getVisibility(), getAuthorizations()); } public List<ArtifactDetectedObject> detectObjects(BufferedImage bImage) { List<ArtifactDetectedObject> detectedObjectList = new ArrayList<ArtifactDetectedObject>(); Mat image = OpenCVUtils.bufferedImageToMat(bImage); if (image != null) { MatOfRect faceDetections = new MatOfRect(); double width = image.width(); double height = image.height(); for (CascadeClassifierHolder objectClassifier : objectClassifiers) { objectClassifier.cascadeClassifier.detectMultiScale(image, faceDetections); for (Rect rect : faceDetections.toArray()) { ArtifactDetectedObject detectedObject = new ArtifactDetectedObject( rect.x / width, rect.y / height, (rect.x + rect.width) / width, (rect.y + rect.height) / height, objectClassifier.conceptIRI, PROCESS); detectedObjectList.add(detectedObject); } } } return detectedObjectList; } @Override public boolean isHandled(Element element, Property property) { if (property == null) { return false; } String mimeType = (String) property.getMetadata().get(LumifyProperties.MIME_TYPE.getPropertyName()); return !(mimeType == null || !mimeType.startsWith("image")); } private class CascadeClassifierHolder { public final String concept; public final CascadeClassifier cascadeClassifier; public final String conceptIRI; public CascadeClassifierHolder(String concept, CascadeClassifier cascadeClassifier, String conceptIRI) { this.concept = concept; this.cascadeClassifier = cascadeClassifier; this.conceptIRI = conceptIRI; } } }
package com.hackerrank.structures; import java.util.ArrayList; import java.util.Scanner; import java.util.Stack; /** * ({}[]) (({()}))) ({(){}()})()({(){}()})(){()} {}()))(()()({}}{} }}}} )))) {{{ ((( []{}(){()}((())){{{}}}{()()}{{}{}} [[]][][] true false true false false false false false true true */ public class JavaStack { public static void main(String[] args) { ArrayList<String> inputs = new ArrayList<String>(); inputs.add("({}[])"); inputs.add("(({()})))"); inputs.add("({(){}()})()({(){}()})(){()}"); inputs.add("{}()))(()()({}}{}"); inputs.add("}}}}"); inputs.add("))))"); inputs.add("{{{"); inputs.add("((("); inputs.add("[]{}(){()}((())){{{}}}{()()}{{}{}}"); inputs.add("[[]][][]"); Scanner sc = new Scanner(System.in); for ( int i = 0; i < inputs.size(); i++ ){ //while (sc.hasNext()) { //String input = sc.next(); String input = inputs.get(i); validateInput(input); //withRegex(input); } } public static void validateInput(String input) { Stack<String> myStack = new Stack<String>(); //Complete the code int len = input.length(); for (int i = 0; i < len; i++){ String c = input.substring(i, i + 1); if (!myStack.empty()){ if ((c.equals(")")) && (myStack.peek().equals("("))){ myStack.pop(); } else if ((c.equals("]"))&&(myStack.peek().equals("["))){ myStack.pop(); } else if ((c.equals("}"))&&(myStack.peek().equals("{"))){ myStack.pop(); } else { myStack.push(c); } } else{ myStack.push(c); } } if (myStack.empty()){ System.out.println("true"); }else{ System.out.println("false"); } } /** * * @param input */ public static void withRegex(String input) { while(input.length() != (input = input.replaceAll("\\(\\)|\\[\\]|\\{\\}", "")).length()); System.out.println(input.isEmpty()); } }
package be.cegeka.batchers.taxcalculator.batch.config; import be.cegeka.batchers.taxcalculator.application.domain.Employee; import be.cegeka.batchers.taxcalculator.infrastructure.config.PersistenceConfig; import org.springframework.batch.item.database.JpaItemWriter; import org.springframework.batch.item.database.JpaPagingItemReader; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class ItemReaderWriterConfig { @Autowired private PersistenceConfig persistenceConfig; @Bean public JpaPagingItemReader<Employee> taxCalculatorItemReader() { JpaPagingItemReader<Employee> employeeItemReader = new JpaPagingItemReader<>(); employeeItemReader.setEntityManagerFactory(persistenceConfig.entityManagerFactory()); employeeItemReader.setQueryString(Employee.GET_ALL_QUERY); return employeeItemReader; } @Bean public JpaItemWriter<Employee> taxCalculatorItemWriter() { JpaItemWriter<Employee> employeeJpaItemWriter = new JpaItemWriter<>(); employeeJpaItemWriter.setEntityManagerFactory(persistenceConfig.entityManagerFactory()); return employeeJpaItemWriter; } @Bean public JpaPagingItemReader<Employee> wsCallItemReader() { JpaPagingItemReader<Employee> employeeItemReader = new JpaPagingItemReader<>(); employeeItemReader.setEntityManagerFactory(persistenceConfig.entityManagerFactory()); employeeItemReader.setQueryString(Employee.GET_ALL_QUERY); return employeeItemReader; } @Bean public JpaItemWriter<Employee> wsCallItemWriter() { JpaItemWriter<Employee> employeeJpaItemWriter = new JpaItemWriter<>(); employeeJpaItemWriter.setEntityManagerFactory(persistenceConfig.entityManagerFactory()); return employeeJpaItemWriter; } @Bean public JpaPagingItemReader<Employee> generatePDFItemReader() { JpaPagingItemReader<Employee> employeeItemReader = new JpaPagingItemReader<>(); employeeItemReader.setEntityManagerFactory(persistenceConfig.entityManagerFactory()); employeeItemReader.setQueryString(Employee.GET_ALL_QUERY); return employeeItemReader; } @Bean public JpaItemWriter<Employee> generatePDFItemWriter() { JpaItemWriter<Employee> employeeJpaItemWriter = new JpaItemWriter<>(); employeeJpaItemWriter.setEntityManagerFactory(persistenceConfig.entityManagerFactory()); return employeeJpaItemWriter; } }
package com.mamewo.podplayer0; import java.io.IOException; import java.io.Serializable; import java.util.List; import android.app.Notification; import android.app.PendingIntent; import android.app.Service; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.media.AudioManager; import android.media.MediaPlayer; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Binder; import android.os.IBinder; import android.preference.PreferenceManager; import android.util.Log; import android.view.KeyEvent; import android.widget.Toast; public class PlayerService extends Service implements MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener, MediaPlayer.OnPreparedListener { final static public String PACKAGE_NAME = PlayerService.class.getPackage().getName(); final static public String STOP_MUSIC_ACTION = PACKAGE_NAME + ".STOP_MUSIC_ACTION"; final static public String JACK_UNPLUGGED_ACTION = PACKAGE_NAME + ".JUCK_UNPLUGGED_ACTION"; final static public String MEDIA_BUTTON_ACTION = PACKAGE_NAME + ".MEDIA_BUTTON_ACTION"; final static public int STOP = 1; final static public int PAUSE = 2; final static private int PREV_INTERVAL_MILLIS = 3000; final static private Class<MainActivity> USER_CLASS = MainActivity.class; final static private String TAG = "podplayer"; final static private int NOTIFY_PLAYING_ID = 1; private final IBinder binder_ = new LocalBinder(); private List<MusicInfo> currentPlaylist_; private int playCursor_; private MediaPlayer player_; private PlayerStateListener listener_; private Receiver receiver_; private boolean isPreparing_; private boolean stopOnPrepared_; private boolean isPausing_; private ComponentName mediaButtonReceiver_; private long previousPrevKeyTime_; //error code //error code from base/include/media/stagefright/MediaErrors.h final static private int MEDIA_ERROR_BASE = -1000; final static private int ERROR_ALREADY_CONNECTED = MEDIA_ERROR_BASE; final static private int ERROR_NOT_CONNECTED = MEDIA_ERROR_BASE - 1; final static private int ERROR_UNKNOWN_HOST = MEDIA_ERROR_BASE - 2; final static private int ERROR_CANNOT_CONNECT = MEDIA_ERROR_BASE - 3; final static private int ERROR_IO = MEDIA_ERROR_BASE - 4; final static private int ERROR_CONNECTION_LOST = MEDIA_ERROR_BASE - 5; final static private int ERROR_MALFORMED = MEDIA_ERROR_BASE - 7; final static private int ERROR_OUT_OF_RANGE = MEDIA_ERROR_BASE - 8; final static private int ERROR_BUFFER_TOO_SMALL = MEDIA_ERROR_BASE - 9; final static private int ERROR_UNSUPPORTED = MEDIA_ERROR_BASE - 10; final static private int ERROR_END_OF_STREAM = MEDIA_ERROR_BASE - 11; // Not technically an error. final static private int INFO_FORMAT_CHANGED = MEDIA_ERROR_BASE - 12; final static private int INFO_DISCONTINUITY = MEDIA_ERROR_BASE - 13; //TODO: check static public boolean isNetworkConnected(Context context) { ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); return (networkInfo != null && networkInfo.isConnected()); } public void setPlaylist(List<MusicInfo> playlist) { currentPlaylist_ = playlist; } @Override public int onStartCommand(Intent intent, int flags, int startId){ String action = intent.getAction(); Log.d(TAG, "onStartCommand: " + action); if (STOP_MUSIC_ACTION.equals(action)) { stopMusic(); } else if (JACK_UNPLUGGED_ACTION.equals(action)) { SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this); boolean pause = pref.getBoolean("pause_on_unplugged", PodplayerPreference.DEFAULT_PAUSE_ON_UNPLUGGED); if (pause && player_.isPlaying()) { pauseMusic(); } } else if (MEDIA_BUTTON_ACTION.equals(action)) { KeyEvent event = intent.getParcelableExtra("event"); Log.d(TAG, "SERVICE: Received media button: " + event.getKeyCode()); if (event.getAction() != KeyEvent.ACTION_UP) { return START_STICKY; } switch(event.getKeyCode()) { case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE: if (player_.isPlaying()){ pauseMusic(); } else { playMusic(); } break; case KeyEvent.KEYCODE_MEDIA_NEXT: if (player_.isPlaying()) { playNext(); } break; case KeyEvent.KEYCODE_MEDIA_PREVIOUS: long currentTime = System.currentTimeMillis(); Log.d(TAG, "Interval: " + (currentTime - previousPrevKeyTime_)); if ((currentTime - previousPrevKeyTime_) <= PREV_INTERVAL_MILLIS) { if(0 == playCursor_){ playCursor_ = currentPlaylist_.size() - 1; } else { playCursor_ } playNth(playCursor_); } else { //rewind playMusic(); } previousPrevKeyTime_ = currentTime; break; default: break; } } return START_STICKY; } public boolean isPlaying() { return (! stopOnPrepared_) && (isPreparing_ || player_.isPlaying()); } public List<MusicInfo> getCurrentPlaylist() { return currentPlaylist_; } /** * get current playing or pausing music * @return current music info */ public MusicInfo getCurrentPodInfo(){ if(null == currentPlaylist_ || playCursor_ >= currentPlaylist_.size()){ return null; } return currentPlaylist_.get(playCursor_); } public boolean playNext() { Log.d(TAG, "playNext"); if(currentPlaylist_ == null || currentPlaylist_.size() == 0) { return false; } if (player_.isPlaying()) { player_.pause(); } playCursor_ = (playCursor_ + 1) % currentPlaylist_.size(); return playMusic(); } /** * plays music of given index * @param pos index on currentPlayList_ * @return true if succeed */ public boolean playNth(int pos) { if(currentPlaylist_ == null || currentPlaylist_.size() == 0){ Log.d(TAG, "playNth: currentPlaylist_: " + currentPlaylist_); return false; } if(isPreparing_){ Log.d(TAG, "playNth: preparing"); return false; } isPausing_ = false; playCursor_ = pos % currentPlaylist_.size(); return playMusic(); } /** * start music from paused position * @return true if succeed */ public boolean restartMusic() { Log.d(TAG, "restartMusic: " + isPausing_); if(! isPausing_) { return false; } if(isPreparing_) { stopOnPrepared_ = false; return true; } player_.start(); MusicInfo info = currentPlaylist_.get(playCursor_); if(null != listener_){ listener_.onStartMusic(currentPlaylist_.get(playCursor_)); } startForeground("Playing podcast", info.title_); return true; } /** * play current music from beginning * @return true if succeed */ public boolean playMusic() { if (isPreparing_) { Log.d(TAG, "playMusic: preparing"); stopOnPrepared_ = false; return false; } if (null == currentPlaylist_ || currentPlaylist_.isEmpty()) { Log.i(TAG, "playMusic: playlist is null"); return false; } MusicInfo info = currentPlaylist_.get(playCursor_); Log.d(TAG, "playMusic: " + playCursor_ + ": " + info.url_); try { player_.reset(); player_.setDataSource(info.url_); player_.prepareAsync(); isPreparing_ = true; isPausing_ = false; } catch (IOException e) { return false; } if(null != listener_){ listener_.onStartLoadingMusic(info); } startForeground(getString(R.string.notify_playing_podcast), info.title_); return true; } public void stopMusic() { if (isPreparing_) { stopOnPrepared_ = true; } else if(player_.isPlaying()){ player_.stop(); } isPausing_ = false; stopForeground(true); if(null != listener_){ Log.d(TAG, "call onStopMusic"); listener_.onStopMusic(STOP); } } //TODO: correct paused state public void pauseMusic() { Log.d(TAG, "pauseMusic: " + player_.isPlaying()); if (isPreparing_) { stopOnPrepared_ = true; } else if(player_.isPlaying()){ player_.pause(); } isPausing_ = true; stopForeground(true); if(null != listener_){ listener_.onStopMusic(PAUSE); } } public class LocalBinder extends Binder { public PlayerService getService() { return PlayerService.this; } } @Override public void onCreate(){ super.onCreate(); currentPlaylist_ = null; listener_ = null; player_ = new MediaPlayer(); player_.setOnCompletionListener(this); player_.setOnErrorListener(this); player_.setOnPreparedListener(this); receiver_ = new Receiver(); registerReceiver(receiver_, new IntentFilter(Intent.ACTION_HEADSET_PLUG)); isPreparing_ = false; stopOnPrepared_ = false; isPausing_ = false; playCursor_ = 0; previousPrevKeyTime_ = 0; AudioManager manager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); mediaButtonReceiver_ = new ComponentName(getPackageName(), Receiver.class.getName()); manager.registerMediaButtonEventReceiver(mediaButtonReceiver_); } @Override public void onDestroy() { AudioManager manager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); manager.unregisterMediaButtonEventReceiver(mediaButtonReceiver_); unregisterReceiver(receiver_); stopForeground(false); player_.setOnCompletionListener(null); player_.setOnErrorListener(null); player_.setOnPreparedListener(null); player_ = null; listener_ = null; currentPlaylist_ = null; super.onDestroy(); } @Override public IBinder onBind(Intent intent) { return binder_; } private void startForeground(String title, String description) { String podTitle = getString(R.string.notify_playing_podcast); Notification note = new Notification(R.drawable.ic_launcher, podTitle, 0); Intent ni = new Intent(this, USER_CLASS); PendingIntent npi = PendingIntent.getActivity(this, 0, ni, 0); note.setLatestEventInfo(this, title, description, npi); startForeground(NOTIFY_PLAYING_ID, note); } @Override public void onPrepared(MediaPlayer player) { Log.d(TAG, "onPrepared"); isPreparing_ = false; if(stopOnPrepared_) { Log.d(TAG, "onPrepared aborted"); stopOnPrepared_ = false; return; } player_.start(); if(null != listener_){ listener_.onStartMusic(currentPlaylist_.get(playCursor_)); } } @Override public void onCompletion(MediaPlayer mp) { playNext(); } private String ErrorCode2String(int err) { String result; switch(err){ //TODO: localize? case ERROR_ALREADY_CONNECTED: result = "Already Connected"; break; case ERROR_NOT_CONNECTED: result = "Not Connected"; break; case ERROR_UNKNOWN_HOST: result = "Unknown Host"; break; case ERROR_CANNOT_CONNECT: result = "Cannot Connect"; break; case ERROR_IO: result = "I/O Error"; break; case ERROR_CONNECTION_LOST: result = "Connection Lost"; break; case ERROR_MALFORMED: result = "Malformed Media"; break; case ERROR_OUT_OF_RANGE: result = "Out of Range"; break; case ERROR_BUFFER_TOO_SMALL: result = "Buffer too Small"; break; case ERROR_UNSUPPORTED: result = "Unsupported Media"; break; case ERROR_END_OF_STREAM: result = "End of Stream"; break; case INFO_FORMAT_CHANGED: result = "Format Changed"; break; case INFO_DISCONTINUITY: result = "Info Discontinuity"; break; default: result = "Unknown error: " + err; break; } return result; } // This method is not called when DRM error occurs @Override public boolean onError(MediaPlayer mp, int what, int extra) { //TODO: show error message to GUI MusicInfo info = currentPlaylist_.get(playCursor_); isPreparing_ = false; Log.i(TAG, "onError: what: " + what + " error code: " + ErrorCode2String(extra) + " url: " + info.url_); showMessage(ErrorCode2String(extra)); stopMusic(); if (isNetworkConnected(this)) { playNext(); } return true; } //use intent instead? public void setOnStartMusicListener(PlayerStateListener listener) { listener_ = listener; } public void clearOnStartMusicListener() { listener_ = null; } public interface PlayerStateListener { public void onStartLoadingMusic(MusicInfo info); public void onStartMusic(MusicInfo info); public void onStopMusic(int mode); } final static public class Receiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Log.d(TAG, "onReceive is called"); String action = intent.getAction(); if (null == action) { return; } if(Intent.ACTION_HEADSET_PLUG.equals(action)) { if(intent.getIntExtra("state", 1) == 0) { //unplugged Intent i = new Intent(context, PlayerService.class); i.setAction(JACK_UNPLUGGED_ACTION); context.startService(i); } } else if(Intent.ACTION_MEDIA_BUTTON.equals(action)) { Log.d(TAG, "media button"); Intent i = new Intent(context, PlayerService.class); i.setAction(MEDIA_BUTTON_ACTION); i.putExtra("event", intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT)); context.startService(i); } } } static public class MusicInfo implements Serializable { private static final long serialVersionUID = 1L; final public String url_; final public String title_; final public String pubdate_; final public String link_; final public int index_; public MusicInfo(String url, String title, String pubdate, String link, int index) { url_ = url; title_ = title; pubdate_ = pubdate; link_ = link; index_ = index; } } public void showMessage(String message) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); } }
package com.sdl.dxa.modules.docs.search.controller; import com.sdl.dxa.modules.docs.exception.DocsExceptionHandler; import com.sdl.dxa.modules.docs.model.ErrorMessage; import com.sdl.dxa.modules.docs.search.exception.SearchException; import com.sdl.dxa.modules.docs.search.model.SearchResultSet; import com.sdl.dxa.modules.docs.search.service.SearchService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import static org.springframework.web.bind.annotation.RequestMethod.POST; /** * Search Controller. * Contains MVC controller methods for Ish Search module functionality. */ @Slf4j @Controller public class SearchController { @Autowired private DocsExceptionHandler exceptionHandler; @Autowired private SearchService searchProvider; @RequestMapping(method = POST, value = "/api/search") @ResponseBody public SearchResultSet search(@RequestBody String parametersJson) throws SearchException { return searchProvider.search(parametersJson); } @ExceptionHandler(value = Exception.class) @ResponseBody ResponseEntity<ErrorMessage> handleException(Exception ex) { ErrorMessage message = exceptionHandler.handleException(ex); return new ResponseEntity(message, message.getHttpStatus()); } }
package org.elasticsearch.xpack.ml.integration; import org.elasticsearch.action.ActionFuture; import org.elasticsearch.action.bulk.BulkRequestBuilder; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.support.WriteRequest; import org.elasticsearch.action.update.UpdateAction; import org.elasticsearch.action.update.UpdateRequest; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.rest.RestStatus; import org.elasticsearch.search.SearchHit; import org.elasticsearch.xpack.core.ml.action.DeleteExpiredDataAction; import org.elasticsearch.xpack.core.ml.action.UpdateModelSnapshotAction; import org.elasticsearch.xpack.core.ml.datafeed.DatafeedConfig; import org.elasticsearch.xpack.core.ml.job.config.AnalysisConfig; import org.elasticsearch.xpack.core.ml.job.config.DataDescription; import org.elasticsearch.xpack.core.ml.job.config.Detector; import org.elasticsearch.xpack.core.ml.job.config.Job; import org.elasticsearch.xpack.core.ml.job.persistence.AnomalyDetectorsIndex; import org.elasticsearch.xpack.core.ml.job.process.autodetect.state.ModelSnapshot; import org.elasticsearch.xpack.core.ml.job.results.Bucket; import org.elasticsearch.xpack.core.ml.job.results.ForecastRequestStats; import org.junit.After; import org.junit.Before; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; import static org.elasticsearch.index.mapper.MapperService.SINGLE_MAPPING_NAME; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.lessThanOrEqualTo; public class DeleteExpiredDataIT extends MlNativeAutodetectIntegTestCase { private static final String DATA_INDEX = "delete-expired-data-test-data"; @Before public void setUpData() throws IOException { client().admin().indices().prepareCreate(DATA_INDEX) .addMapping(SINGLE_MAPPING_NAME, "time", "type=date,format=epoch_millis") .get(); // We are going to create data for last 2 days long nowMillis = System.currentTimeMillis(); int totalBuckets = 3 * 24; int normalRate = 10; int anomalousRate = 100; int anomalousBucket = 30; BulkRequestBuilder bulkRequestBuilder = client().prepareBulk(); for (int bucket = 0; bucket < totalBuckets; bucket++) { long timestamp = nowMillis - TimeValue.timeValueHours(totalBuckets - bucket).getMillis(); int bucketRate = bucket == anomalousBucket ? anomalousRate : normalRate; for (int point = 0; point < bucketRate; point++) { IndexRequest indexRequest = new IndexRequest(DATA_INDEX); indexRequest.source("time", timestamp); bulkRequestBuilder.add(indexRequest); } } BulkResponse bulkResponse = bulkRequestBuilder .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE) .get(); assertThat(bulkResponse.hasFailures(), is(false)); } @After public void tearDownData() { client().admin().indices().prepareDelete(DATA_INDEX).get(); cleanUp(); } public void testDeleteExpiredDataGivenNothingToDelete() throws Exception { // Tests that nothing goes wrong when there's nothing to delete client().execute(DeleteExpiredDataAction.INSTANCE, new DeleteExpiredDataAction.Request()).get(); } @AwaitsFix(bugUrl = "https://github.com/elastic/elasticsearch/issues/39575") public void testDeleteExpiredData() throws Exception { // Index some unused state documents (more than 10K to test scrolling works) BulkRequestBuilder bulkRequestBuilder = client().prepareBulk(); bulkRequestBuilder.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); for (int i = 0; i < 10010; i++) { String docId = "non_existing_job_" + randomFrom("model_state_1234567#" + i, "quantiles", "categorizer_state#" + i); IndexRequest indexRequest = new IndexRequest(AnomalyDetectorsIndex.jobStateIndexWriteAlias()).id(docId); indexRequest.source(Collections.emptyMap()); bulkRequestBuilder.add(indexRequest); } ActionFuture<BulkResponse> indexUnusedStateDocsResponse = bulkRequestBuilder.execute(); registerJob(newJobBuilder("no-retention").setResultsRetentionDays(null).setModelSnapshotRetentionDays(1000L)); registerJob(newJobBuilder("results-retention").setResultsRetentionDays(1L).setModelSnapshotRetentionDays(1000L)); registerJob(newJobBuilder("snapshots-retention").setResultsRetentionDays(null).setModelSnapshotRetentionDays(2L)); registerJob(newJobBuilder("snapshots-retention-with-retain").setResultsRetentionDays(null).setModelSnapshotRetentionDays(2L)); registerJob(newJobBuilder("results-and-snapshots-retention").setResultsRetentionDays(1L).setModelSnapshotRetentionDays(2L)); List<String> shortExpiryForecastIds = new ArrayList<>(); long now = System.currentTimeMillis(); long oneDayAgo = now - TimeValue.timeValueHours(48).getMillis() - 1; // Start all jobs for (Job.Builder job : getJobs()) { putJob(job); String datafeedId = job.getId() + "-feed"; DatafeedConfig.Builder datafeedConfig = new DatafeedConfig.Builder(datafeedId, job.getId()); datafeedConfig.setIndices(Arrays.asList(DATA_INDEX)); DatafeedConfig datafeed = datafeedConfig.build(); registerDatafeed(datafeed); putDatafeed(datafeed); // Run up to a day ago openJob(job.getId()); startDatafeed(datafeedId, 0, now - TimeValue.timeValueHours(24).getMillis()); } // Now let's wait for all jobs to be closed for (Job.Builder job : getJobs()) { waitUntilJobIsClosed(job.getId()); } for (Job.Builder job : getJobs()) { assertThat(getBuckets(job.getId()).size(), is(greaterThanOrEqualTo(47))); assertThat(getRecords(job.getId()).size(), equalTo(1)); List<ModelSnapshot> modelSnapshots = getModelSnapshots(job.getId()); assertThat(modelSnapshots.size(), equalTo(1)); String snapshotDocId = ModelSnapshot.documentId(modelSnapshots.get(0)); // Update snapshot timestamp to force it out of snapshot retention window String snapshotUpdate = "{ \"timestamp\": " + oneDayAgo + "}"; UpdateRequest updateSnapshotRequest = new UpdateRequest(".ml-anomalies-" + job.getId(), snapshotDocId); updateSnapshotRequest.doc(snapshotUpdate.getBytes(StandardCharsets.UTF_8), XContentType.JSON); client().execute(UpdateAction.INSTANCE, updateSnapshotRequest).get(); // Now let's create some forecasts openJob(job.getId()); // We must set a very small value for expires_in to keep this testable as the deletion cutoff point is the moment // the DeleteExpiredDataAction is called. String forecastShortExpiryId = forecast(job.getId(), TimeValue.timeValueHours(3), TimeValue.timeValueSeconds(1)); shortExpiryForecastIds.add(forecastShortExpiryId); String forecastDefaultExpiryId = forecast(job.getId(), TimeValue.timeValueHours(3), null); String forecastNoExpiryId = forecast(job.getId(), TimeValue.timeValueHours(3), TimeValue.ZERO); waitForecastToFinish(job.getId(), forecastShortExpiryId); waitForecastToFinish(job.getId(), forecastDefaultExpiryId); waitForecastToFinish(job.getId(), forecastNoExpiryId); } // Refresh to ensure the snapshot timestamp updates are visible client().admin().indices().prepareRefresh("*").get(); // We need to wait a second to ensure the second time around model snapshots will have a different ID (it depends on epoch seconds) awaitBusy(() -> false, 1, TimeUnit.SECONDS); for (Job.Builder job : getJobs()) { // Run up to now startDatafeed(job.getId() + "-feed", 0, now); waitUntilJobIsClosed(job.getId()); assertThat(getBuckets(job.getId()).size(), is(greaterThanOrEqualTo(70))); assertThat(getRecords(job.getId()).size(), equalTo(1)); List<ModelSnapshot> modelSnapshots = getModelSnapshots(job.getId()); assertThat(modelSnapshots.size(), equalTo(2)); } retainAllSnapshots("snapshots-retention-with-retain"); long totalModelSizeStatsBeforeDelete = client().prepareSearch("*") .setQuery(QueryBuilders.termQuery("result_type", "model_size_stats")) .get().getHits().getTotalHits().value; long totalNotificationsCountBeforeDelete = client().prepareSearch(".ml-notifications").get().getHits().getTotalHits().value; assertThat(totalModelSizeStatsBeforeDelete, greaterThan(0L)); assertThat(totalNotificationsCountBeforeDelete, greaterThan(0L)); // Verify forecasts were created List<ForecastRequestStats> forecastStats = getForecastStats(); assertThat(forecastStats.size(), equalTo(getJobs().size() * 3)); for (ForecastRequestStats forecastStat : forecastStats) { assertThat(countForecastDocs(forecastStat.getJobId(), forecastStat.getForecastId()), equalTo(forecastStat.getRecordCount())); } // Before we call the delete-expired-data action we need to make sure the unused state docs were indexed assertThat(indexUnusedStateDocsResponse.get().status(), equalTo(RestStatus.OK)); // Now call the action under test client().execute(DeleteExpiredDataAction.INSTANCE, new DeleteExpiredDataAction.Request()).get(); // We need to refresh to ensure the deletion is visible client().admin().indices().prepareRefresh("*").get(); // no-retention job should have kept all data assertThat(getBuckets("no-retention").size(), is(greaterThanOrEqualTo(70))); assertThat(getRecords("no-retention").size(), equalTo(1)); assertThat(getModelSnapshots("no-retention").size(), equalTo(2)); List<Bucket> buckets = getBuckets("results-retention"); assertThat(buckets.size(), is(lessThanOrEqualTo(24))); assertThat(buckets.size(), is(greaterThanOrEqualTo(22))); assertThat(buckets.get(0).getTimestamp().getTime(), greaterThanOrEqualTo(oneDayAgo)); assertThat(getRecords("results-retention").size(), equalTo(0)); assertThat(getModelSnapshots("results-retention").size(), equalTo(2)); assertThat(getBuckets("snapshots-retention").size(), is(greaterThanOrEqualTo(70))); assertThat(getRecords("snapshots-retention").size(), equalTo(1)); assertThat(getModelSnapshots("snapshots-retention").size(), equalTo(1)); assertThat(getBuckets("snapshots-retention-with-retain").size(), is(greaterThanOrEqualTo(70))); assertThat(getRecords("snapshots-retention-with-retain").size(), equalTo(1)); assertThat(getModelSnapshots("snapshots-retention-with-retain").size(), equalTo(2)); buckets = getBuckets("results-and-snapshots-retention"); assertThat(buckets.size(), is(lessThanOrEqualTo(24))); assertThat(buckets.size(), is(greaterThanOrEqualTo(22))); assertThat(buckets.get(0).getTimestamp().getTime(), greaterThanOrEqualTo(oneDayAgo)); assertThat(getRecords("results-and-snapshots-retention").size(), equalTo(0)); assertThat(getModelSnapshots("results-and-snapshots-retention").size(), equalTo(1)); long totalModelSizeStatsAfterDelete = client().prepareSearch("*") .setQuery(QueryBuilders.termQuery("result_type", "model_size_stats")) .get().getHits().getTotalHits().value; long totalNotificationsCountAfterDelete = client().prepareSearch(".ml-notifications").get().getHits().getTotalHits().value; assertThat(totalModelSizeStatsAfterDelete, equalTo(totalModelSizeStatsBeforeDelete)); assertThat(totalNotificationsCountAfterDelete, greaterThanOrEqualTo(totalNotificationsCountBeforeDelete)); // Verify short expiry forecasts were deleted only forecastStats = getForecastStats(); assertThat(forecastStats.size(), equalTo(getJobs().size() * 2)); for (ForecastRequestStats forecastStat : forecastStats) { assertThat(countForecastDocs(forecastStat.getJobId(), forecastStat.getForecastId()), equalTo(forecastStat.getRecordCount())); } for (Job.Builder job : getJobs()) { for (String forecastId : shortExpiryForecastIds) { assertThat(countForecastDocs(job.getId(), forecastId), equalTo(0L)); } } // Verify .ml-state doesn't contain unused state documents SearchResponse stateDocsResponse = client().prepareSearch(AnomalyDetectorsIndex.jobStateIndexPattern()) .setFetchSource(false) .setTrackTotalHits(true) .setSize(10000) .get(); // Assert at least one state doc for each job assertThat(stateDocsResponse.getHits().getTotalHits().value, greaterThanOrEqualTo(5L)); int nonExistingJobDocsCount = 0; List<String> nonExistingJobExampleIds = new ArrayList<>(); for (SearchHit hit : stateDocsResponse.getHits().getHits()) { if (hit.getId().startsWith("non_existing_job")) { nonExistingJobDocsCount++; if (nonExistingJobExampleIds.size() < 10) { nonExistingJobExampleIds.add(hit.getId()); } } } assertThat("Documents for non_existing_job are still around; examples: " + nonExistingJobExampleIds, nonExistingJobDocsCount, equalTo(0)); } private static Job.Builder newJobBuilder(String id) { Detector.Builder detector = new Detector.Builder(); detector.setFunction("count"); AnalysisConfig.Builder analysisConfig = new AnalysisConfig.Builder(Arrays.asList(detector.build())); analysisConfig.setBucketSpan(TimeValue.timeValueHours(1)); DataDescription.Builder dataDescription = new DataDescription.Builder(); dataDescription.setTimeField("time"); Job.Builder jobBuilder = new Job.Builder(id); jobBuilder.setAnalysisConfig(analysisConfig); jobBuilder.setDataDescription(dataDescription); return jobBuilder; } private void retainAllSnapshots(String jobId) throws Exception { List<ModelSnapshot> modelSnapshots = getModelSnapshots(jobId); for (ModelSnapshot modelSnapshot : modelSnapshots) { UpdateModelSnapshotAction.Request request = new UpdateModelSnapshotAction.Request(jobId, modelSnapshot.getSnapshotId()); request.setRetain(true); client().execute(UpdateModelSnapshotAction.INSTANCE, request).get(); } // We need to refresh to ensure the updates are visible client().admin().indices().prepareRefresh("*").get(); } }
package com.vikas.projs.ml.autonomousvehicle; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.concurrent.ArrayBlockingQueue; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.layout.GridLayout; import org.eclipse.wb.swt.SWTResourceManager; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.graphics.PaletteData; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.custom.CCombo; import org.eclipse.swt.widgets.TabFolder; import org.eclipse.swt.widgets.TabItem; import org.eclipse.swt.widgets.Combo; /** * Implements the functionality required to provide a Front End Desktop application for the Autonomous car project * which will perform the following: * - Stream the Video and other sensory information from the Sensor Device on the Vehicle * - Allow User to train the Autonomous Vehicle by providing directional inputs in response * to the displayed sensory data * - Process sensory information from the vehicle and take decisions to steer by making use of * trained machine learning algorithms * * @author Vikas K Vijayakumar (kvvikas@yahoo.co.in) * @version 1.0 * */ public class DriverDisplayAndController { private static Shell shell; private static Display display; private Text ipV4Address; private Text streamingPort; private static StyledText applicationLog; //Maximum number of lines which can be displayed in the application log on the screen private static int maxLinesInLog = 40; //Boolean field used to store the current status of connection with the sensor device private static boolean connectedToSensor = false; //Boolean field used to store the current status of connection with the Arduino / Controller private static boolean connectedToController = false; //Button which is used to initiate connection/disconnection to Sensor Device private static Button btnConnectToSensor; private static Button btnForward; private static Button btnLeft; private static Button btnReverse; private static Button btnRight; private static Button btnConnectToController; //Label where the Sensor Video frames are displayed. private static Label lblSensorVideoOut; //Define an RGB class to hold the 256 different (grey) values, pixel depth is 8. private RGB[] rgbGrayscale = new RGB[256]; private static PaletteData paletteDataGrayscale; private static org.eclipse.swt.graphics.ImageData grayscaleFrameData; private SensorClient sensorClient; private VehicleController vehicleController; private DisplayTrainingData displayTrainingData; //To capture the driving mode private Text trainingDataDirectory; private Label lblTrainingDataDirectory; private final static String manualDrivingModeCode = "Manual"; private final static String autoDrivingModeCode = "Automatic"; private static String appDrivingMode = manualDrivingModeCode; //Java Blocking queue is used to send feature information from SWT main thread to the persister thread //Capacity of the queue is 200, which means the persister can lag behind by persisting upto 200 features before the SWT main //thread gets blocked. private static int featureQueueCapacity = 100; private static ArrayBlockingQueue<FeatureMessage> featureQueue = new ArrayBlockingQueue<FeatureMessage>(featureQueueCapacity); private static int featureQueueCapacityWarnPercent = 50; //Blocking queue to send the controls to Arduino from the SWT main thread in case of training and //prediction thread in case of auto mode private static int controllerQueueCapacity = 100; private static ArrayBlockingQueue<ControlMessage> controllerQueue = new ArrayBlockingQueue<ControlMessage>(controllerQueueCapacity); private static int controllerQueueCapacityWarnPercent = 50; private static Text pixelRowsToStripFromTop; private static Text pixelRowsToStripFromBottom; private Label lblNavigationControl; private Label lblSensorVideoOutput; private Composite trainingDataReviewComposite; private static Label lblTrainingDataReview; private Label lblCapturedTrainingData; private Label lblTrainingFileName; private static Text trainingFileNameUnderReview; private Label lblTrainingDataReviewFrameWidth; private static Text trainingDataReviewFrameWidth; private Button btnLoadTrainingDataFile; private Label lblTrainingDataReviewFrameHeight; private static Text trainingDataReviewFrameHeight; //Default values for the Frame Width, Height and Depth. Any changes to this can have unexpected results private static final int defaultFrameWidth = 176; private static final int defaultFrameHeight = 144; private static final int defaultFrameDepth = 8; private static Label lblTrainingDataSteeringDirection; private Label lblConnectionSetup; private Composite loggingComposite; private Label lblLogLevel; private static Button chkbtnErrorsWarnings; private static Button chkbtnInfoLogging; private static Boolean infoLoggingRequired=false; private Label lblStep; private Label lblStep_1; private Label lblArduinoPortName; private Text arduinoPortName; private TabFolder tabFolder; private TabItem TrainingReviewTab; private TabItem LiveTab; private Composite sensorConfigurationcomposite; private Composite navigationControlComposite; private Composite trainingDataReviewConfigComposite; private Label lblCapturedTrainingsetNavigation; private Composite trainingDataReviewNavgationDetails; private static Button btnPreviousTrainingDataImage; private static Button btnNextTrainingDataImage; private static Button btnDeleteTrainingDataImage; private Button btnGenerateSets; private Text capturedDataDirectoryName; private Button btnResizeTrainingFile; private Label lblPixelRowsToStripFromTopTrain; private Label lblPixelRowsToStripFromBotTrain; private Text pixelRowsToStripFromTopTraining; private Text pixelRowsToStripFromBottomTraining; private Label lblPredictedTrainingsetNavigation; private static Label lblTrainingDataPredictedSteeringDirection; private Label lblPredictNoOfHiddenLayers; private Label lblPredictWeightsForInputLayer; private Label lblPredictWeightsForFirstHiddenLayer; private Label lblPredictWeightsForSecondHiddenLayer; private Label lblPredictWeightsForThirdHiddenLayer; private Label lblInputsForPrediction; private Text textPredictWeightsForInputLayer; private Text textPredictWeightsForSecondHiddenLayer; private Text textPredictWeightsForFirstHiddenLayer; private Text textPredictWeightsForThirdHiddenLayer; private Text textPredictNumberOfHiddenLayers; private Composite predictionComposite; private static Button btnAssociatePredictionWeights; private static Boolean predictionInProgress = false; private PredictUsingNN predictUsingNN; private Button btnReassignDirection; private Combo comboReAssignDirection; private Label label; private Label label_1; private Label label_2; private Label label_3; private Label label_4; private static Text textTrainingPredictionConfidence; private Label lblPredictionConfidence; private Button btnPredictForAllDataSetsInFile; /** * Launch the application. * @param args */ public static void main(String[] args) { try { DriverDisplayAndController window = new DriverDisplayAndController(); window.open(); //An EventLoop is required in order to transfer user inputs from underlying //OS widgets to the SWT event system window.createEventLoop(); } catch (Exception e) { e.printStackTrace(); } } /** * Open the window. */ private void open() { System.out.println("DriverDisplayAndController: About to get default display"); display = Display.getDefault(); //Set the Shell shell = new Shell(); //Create the Shell contents createContents(); //Open the Shell System.out.println("DriverDisplayAndController: About to open the shell"); shell.open(); } /** * Create contents of the window. */ private void createContents() { //Build grey scale palette: 256 different grey values are generated. for (int i = 0; i < 256; i++) { rgbGrayscale[i] = new RGB(i, i, i); } //Construct a new indexed palette given an array of Grayscale RGB values. paletteDataGrayscale = new PaletteData(rgbGrayscale); System.out.println("DriverDisplayAndController: About to create contents of the shell"); shell.setSize(1094, 655); shell.setLayout(new GridLayout(4, false)); Label lblNewLabel = new Label(shell, SWT.NONE); lblNewLabel.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 4, 1)); lblNewLabel.setFont(SWTResourceManager.getFont("Segoe UI", 16, SWT.BOLD)); lblNewLabel.setText("Autonomous Vehicle Desktop Application"); new Label(shell, SWT.NONE); tabFolder = new TabFolder(shell, SWT.NONE); GridData gd_tabFolder = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1); gd_tabFolder.heightHint = 566; gd_tabFolder.widthHint = 664; tabFolder.setLayoutData(gd_tabFolder); LiveTab = new TabItem(tabFolder, SWT.NONE); LiveTab.setText("Live"); Composite configurationComposite = new Composite(tabFolder, SWT.NONE); LiveTab.setControl(configurationComposite); configurationComposite.setLayout(new GridLayout(2, false)); new Label(configurationComposite, SWT.NONE); lblSensorVideoOutput = new Label(configurationComposite, SWT.NONE); GridData gd_lblSensorVideoOutput = new GridData(SWT.CENTER, SWT.CENTER, true, true, 1, 2); gd_lblSensorVideoOutput.heightHint = 51; gd_lblSensorVideoOutput.widthHint = 119; lblSensorVideoOutput.setLayoutData(gd_lblSensorVideoOutput); lblSensorVideoOutput.setForeground(SWTResourceManager.getColor(SWT.COLOR_DARK_BLUE)); lblSensorVideoOutput.setText("Sensor Video \r\n Output"); lblSensorVideoOutput.setFont(SWTResourceManager.getFont("Segoe UI", 10, SWT.BOLD)); sensorConfigurationcomposite = new Composite(configurationComposite, SWT.NONE); sensorConfigurationcomposite.setLayout(new GridLayout(3, false)); GridData gd_sensorConfigurationcomposite = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 3); gd_sensorConfigurationcomposite.widthHint = 393; gd_sensorConfigurationcomposite.heightHint = 241; sensorConfigurationcomposite.setLayoutData(gd_sensorConfigurationcomposite); lblStep = new Label(sensorConfigurationcomposite, SWT.NONE); lblStep.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, true, 1, 1)); lblStep.setText("Step 1 - Choose \r\nDriving Mode"); lblStep.setForeground(SWTResourceManager.getColor(SWT.COLOR_DARK_BLUE)); lblStep.setFont(SWTResourceManager.getFont("Segoe UI", 10, SWT.BOLD)); Label lblDrivingMode = new Label(sensorConfigurationcomposite, SWT.NONE); lblDrivingMode.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, true, 1, 1)); lblDrivingMode.setText("Driving Mode"); lblDrivingMode.setFont(SWTResourceManager.getFont("Segoe UI", 10, SWT.BOLD)); final CCombo drivingMode = new CCombo(sensorConfigurationcomposite, SWT.BORDER); drivingMode.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, true, 1, 1)); drivingMode.setBackground(SWTResourceManager.getColor(255, 250, 205)); drivingMode.setEditable(false); drivingMode.setItems(new String[] {manualDrivingModeCode, autoDrivingModeCode}); //Add Selection Listener drivingMode.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e){ appDrivingMode = drivingMode.getText(); logInfoToApplicationDisplay("Info: Selected Driving Mode is: "+appDrivingMode); //Enable the direction buttons and the Training Data directory only for Manual mode if(appDrivingMode.equals(manualDrivingModeCode)){ lblTrainingDataDirectory.setVisible(true); trainingDataDirectory.setVisible(true); }else if(appDrivingMode.equals(autoDrivingModeCode)){ lblTrainingDataDirectory.setVisible(false); trainingDataDirectory.setVisible(false); }else{ //Do Nothing } } }); label_3 = new Label(sensorConfigurationcomposite, SWT.SEPARATOR | SWT.HORIZONTAL); GridData gd_label_3 = new GridData(SWT.FILL, SWT.CENTER, false, false, 3, 1); gd_label_3.widthHint = 404; label_3.setLayoutData(gd_label_3); label_3.setForeground(SWTResourceManager.getColor(SWT.COLOR_BLUE)); label_3.setFont(SWTResourceManager.getFont("Segoe UI", 14, SWT.BOLD)); lblConnectionSetup = new Label(sensorConfigurationcomposite, SWT.NONE); lblConnectionSetup.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, true, 1, 1)); lblConnectionSetup.setForeground(SWTResourceManager.getColor(SWT.COLOR_DARK_BLUE)); lblConnectionSetup.setText("Step 2 - Connect \r\nto Sensor"); lblConnectionSetup.setFont(SWTResourceManager.getFont("Segoe UI", 10, SWT.BOLD)); Label label_IP = new Label(sensorConfigurationcomposite, SWT.NONE); label_IP.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, true, 1, 1)); label_IP.setFont(SWTResourceManager.getFont("Segoe UI", 10, SWT.BOLD)); label_IP.setText("Sensor IPv4 Address"); ipV4Address = new Text(sensorConfigurationcomposite, SWT.BORDER); ipV4Address.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, true, 1, 1)); ipV4Address.setBackground(SWTResourceManager.getColor(255, 250, 205)); ipV4Address.setToolTipText("Eg: 192.168.0.51"); new Label(sensorConfigurationcomposite, SWT.NONE); Label label_Port = new Label(sensorConfigurationcomposite, SWT.NONE); label_Port.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, true, 1, 1)); label_Port.setFont(SWTResourceManager.getFont("Segoe UI", 10, SWT.BOLD)); label_Port.setText("Sensor Streaming Port"); streamingPort = new Text(sensorConfigurationcomposite, SWT.BORDER); streamingPort.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, true, 1, 1)); streamingPort.setBackground(SWTResourceManager.getColor(255, 250, 205)); streamingPort.setToolTipText("Eg: 6666"); streamingPort.setText("6666"); lblTrainingDataDirectory = new Label(sensorConfigurationcomposite, SWT.NONE); lblTrainingDataDirectory.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, true, 1, 1)); lblTrainingDataDirectory.setText("Training \r\nFeatures Dir"); lblTrainingDataDirectory.setFont(SWTResourceManager.getFont("Segoe UI", 10, SWT.BOLD)); trainingDataDirectory = new Text(sensorConfigurationcomposite, SWT.BORDER); GridData gd_trainingDataDirectory = new GridData(SWT.FILL, SWT.CENTER, true, true, 2, 1); gd_trainingDataDirectory.widthHint = 253; trainingDataDirectory.setLayoutData(gd_trainingDataDirectory); trainingDataDirectory.setBackground(SWTResourceManager.getColor(255, 250, 205)); trainingDataDirectory.setToolTipText("Eg: D:\\Vikas\\TrainingData"); Label lblPixelStripsFromTop = new Label(sensorConfigurationcomposite, SWT.NONE); lblPixelStripsFromTop.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, true, 2, 1)); lblPixelStripsFromTop.setText("Pixel Rows To Strip from Top"); lblPixelStripsFromTop.setFont(SWTResourceManager.getFont("Segoe UI", 10, SWT.BOLD)); pixelRowsToStripFromTop = new Text(sensorConfigurationcomposite, SWT.BORDER); GridData gd_pixelRowsToStripFromTop = new GridData(SWT.LEFT, SWT.CENTER, true, true, 1, 1); gd_pixelRowsToStripFromTop.widthHint = 38; pixelRowsToStripFromTop.setLayoutData(gd_pixelRowsToStripFromTop); pixelRowsToStripFromTop.setBackground(SWTResourceManager.getColor(255, 250, 205)); pixelRowsToStripFromTop.setToolTipText("Eg: 6666"); pixelRowsToStripFromTop.setText("0"); Label lblPixelStripsFromBottom = new Label(sensorConfigurationcomposite, SWT.NONE); lblPixelStripsFromBottom.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, true, 2, 1)); lblPixelStripsFromBottom.setText("Pixel Rows To Strip from Bottom"); lblPixelStripsFromBottom.setFont(SWTResourceManager.getFont("Segoe UI", 10, SWT.BOLD)); pixelRowsToStripFromBottom = new Text(sensorConfigurationcomposite, SWT.BORDER); GridData gd_pixelRowsToStripFromBottom = new GridData(SWT.LEFT, SWT.CENTER, true, true, 1, 1); gd_pixelRowsToStripFromBottom.widthHint = 38; pixelRowsToStripFromBottom.setLayoutData(gd_pixelRowsToStripFromBottom); pixelRowsToStripFromBottom.setBackground(SWTResourceManager.getColor(255, 250, 205)); pixelRowsToStripFromBottom.setToolTipText("Eg: 6666"); pixelRowsToStripFromBottom.setText("0"); btnConnectToSensor = new Button(sensorConfigurationcomposite, SWT.NONE); GridData gd_btnConnectToSensor = new GridData(SWT.CENTER, SWT.CENTER, true, true, 3, 1); gd_btnConnectToSensor.widthHint = 130; btnConnectToSensor.setLayoutData(gd_btnConnectToSensor); btnConnectToSensor.setFont(SWTResourceManager.getFont("Segoe UI", 9, SWT.BOLD)); btnConnectToSensor.setText("Connect"); //Register listener for button click btnConnectToSensor.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e){ if(connectedToSensor){ logInfoToApplicationDisplay("Info: DisconnectFromSensor button has been pressed"); //Disconnect from sensor Device if (sensorClient != null){ sensorClient.disconnectFromSensor(); } }else{ logInfoToApplicationDisplay("Info: ConnectToSensor button has been pressed"); //Validate user inputs if(!Utilities.validateIPv4Address(ipV4Address.getText())){ displayErrorMessageOnscreen("Sensor IPv4 Address must have a valid IP V4 Address"); }else if(!Utilities.validateInteger(streamingPort.getText(), 5000, 55000)){ displayErrorMessageOnscreen("Sensor Streaming Port must have a value between 5000 and 55000"); }else if(!Utilities.validateInteger(pixelRowsToStripFromTop.getText(), 0, 176)){ displayErrorMessageOnscreen("Pixel Rows to Strip from Top must have a value between 0 and 176"); }else if(!Utilities.validateInteger(pixelRowsToStripFromBottom.getText(), 0, 176)){ displayErrorMessageOnscreen("Pixel Rows to Strip from Bottom must have a value between 0 and 176"); }else if((Integer.valueOf(pixelRowsToStripFromBottom.getText()) + Integer.valueOf(pixelRowsToStripFromBottom.getText())) > 176){ displayErrorMessageOnscreen("The sum of Pixel Rows to be stripped from Top and Bottom cannot exceed 176"); }else{ //Create a thread to start the communication protocol with Sensor Device if(appDrivingMode.equals(manualDrivingModeCode)){ sensorClient = new SensorClient(ipV4Address.getText(),Integer.valueOf(streamingPort.getText()), display, featureQueue,trainingDataDirectory.getText(), true, Integer.valueOf(pixelRowsToStripFromTop.getText()), Integer.valueOf(pixelRowsToStripFromBottom.getText())); }else{ sensorClient = new SensorClient(ipV4Address.getText(),Integer.valueOf(streamingPort.getText()), display, featureQueue,trainingDataDirectory.getText(), false, Integer.valueOf(pixelRowsToStripFromTop.getText()), Integer.valueOf(pixelRowsToStripFromBottom.getText())); } } } } }); label_4 = new Label(sensorConfigurationcomposite, SWT.SEPARATOR | SWT.HORIZONTAL); GridData gd_label_4 = new GridData(SWT.FILL, SWT.CENTER, false, false, 3, 1); gd_label_4.widthHint = 411; label_4.setLayoutData(gd_label_4); label_4.setForeground(SWTResourceManager.getColor(SWT.COLOR_BLUE)); label_4.setFont(SWTResourceManager.getFont("Segoe UI", 14, SWT.BOLD)); lblStep_1 = new Label(sensorConfigurationcomposite, SWT.NONE); lblStep_1.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, true, 1, 1)); lblStep_1.setText("Step 3 - Connect \r\nto Controller"); lblStep_1.setForeground(SWTResourceManager.getColor(SWT.COLOR_DARK_BLUE)); lblStep_1.setFont(SWTResourceManager.getFont("Segoe UI", 10, SWT.BOLD)); lblArduinoPortName = new Label(sensorConfigurationcomposite, SWT.NONE); lblArduinoPortName.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, true, 1, 1)); lblArduinoPortName.setText("Serial Port Name"); lblArduinoPortName.setFont(SWTResourceManager.getFont("Segoe UI", 10, SWT.BOLD)); arduinoPortName = new Text(sensorConfigurationcomposite, SWT.BORDER); GridData gd_arduinoPortName = new GridData(SWT.LEFT, SWT.CENTER, true, true, 1, 1); gd_arduinoPortName.widthHint = 42; arduinoPortName.setLayoutData(gd_arduinoPortName); arduinoPortName.setBackground(SWTResourceManager.getColor(255, 250, 205)); arduinoPortName.setToolTipText("Eg: 6666"); arduinoPortName.setText("COM3"); btnConnectToController = new Button(sensorConfigurationcomposite, SWT.NONE); GridData gd_btnConnectToController = new GridData(SWT.CENTER, SWT.CENTER, true, true, 3, 1); gd_btnConnectToController.widthHint = 129; btnConnectToController.setLayoutData(gd_btnConnectToController); btnConnectToController.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if(connectedToController){ logInfoToApplicationDisplay("Info: DisconnectFromController button has been pressed"); //Disconnect from Arduino / Controller if (vehicleController != null){ vehicleController.disconnectFromController(); } }else{ logInfoToApplicationDisplay("Info: ConnectToController button has been pressed"); //Create a thread to start the communication protocol with Sensor Device vehicleController = new VehicleController(arduinoPortName.getText(), display, controllerQueue); } } }); btnConnectToController.setText("Connect"); btnConnectToController.setFont(SWTResourceManager.getFont("Segoe UI", 9, SWT.BOLD)); lblSensorVideoOut = new Label(configurationComposite, SWT.NONE); GridData gd_lblSensorVideoOut = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1); gd_lblSensorVideoOut.widthHint = 45; gd_lblSensorVideoOut.minimumWidth = 200; gd_lblSensorVideoOut.minimumHeight = 200; lblSensorVideoOut.setLayoutData(gd_lblSensorVideoOut); lblSensorVideoOut.setBackground(SWTResourceManager.getColor(176, 224, 230)); lblSensorVideoOut.setFont(SWTResourceManager.getFont("Segoe UI", 10, SWT.BOLD)); navigationControlComposite = new Composite(configurationComposite, SWT.NONE); navigationControlComposite.setLayout(new GridLayout(3, false)); GridData gd_navigationControlComposite = new GridData(SWT.CENTER, SWT.FILL, true, true, 1, 1); gd_navigationControlComposite.heightHint = 123; navigationControlComposite.setLayoutData(gd_navigationControlComposite); lblNavigationControl = new Label(navigationControlComposite, SWT.NONE); lblNavigationControl.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 3, 1)); lblNavigationControl.setSize(165, 0); lblNavigationControl.setForeground(SWTResourceManager.getColor(SWT.COLOR_DARK_BLUE)); lblNavigationControl.setText("Navigation Control"); lblNavigationControl.setFont(SWTResourceManager.getFont("Segoe UI", 10, SWT.BOLD)); new Label(navigationControlComposite, SWT.NONE); //Forward Button btnForward = new Button(navigationControlComposite, SWT.NONE); btnForward.setSize(34, 15); btnForward.setFont(SWTResourceManager.getFont("Segoe UI", 16, SWT.BOLD)); btnForward.setText(" \u2191 "); btnForward.setEnabled(false); new Label(navigationControlComposite, SWT.NONE); btnLeft = new Button(navigationControlComposite, SWT.NONE); btnLeft.setSize(30, 15); btnLeft.setFont(SWTResourceManager.getFont("Segoe UI", 16, SWT.BOLD)); btnLeft.setText("\u2190"); btnLeft.setEnabled(false); //Register listener for button click btnLeft.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e){ logInfoToApplicationDisplay("Info: Left button has been pressed"); //Send the Control Message to VehicleController if(appDrivingMode.equals(manualDrivingModeCode)){ try { //Send a warning if the controllerQueue capacity has reached the configured warning threshold float controlQueueCapacityPercent = (((controllerQueueCapacity - controllerQueue.remainingCapacity()) / controllerQueueCapacity) * 100); if(controlQueueCapacityPercent > controllerQueueCapacityWarnPercent){ logWarningToApplicationDisplay("Warning: The ControllerQueue has reached "+controlQueueCapacityPercent+" of its capacity. Controls are not being processed fast enough"); } ControlMessage controlMessage = new ControlMessage(); controlMessage.setSteeringDirection(FeatureMessage.steerLeft); controllerQueue.put(controlMessage); logInfoToApplicationDisplay("Info: Successfully sent a ControlMessage to Steer Left"); } catch (InterruptedException ex) { logErrorToApplicationDisplay(ex, "ERROR: InterruptedException when trying to publish ControlMessage to BlockingQueue"); } } //Push the features to BlockingQueue for persistence in case the mode is Manual if(appDrivingMode.equals(manualDrivingModeCode) && (grayscaleFrameData != null)){ FeatureMessage currentfeatureList = new FeatureMessage(); currentfeatureList.setFrameWidth(grayscaleFrameData.width); currentfeatureList.setFrameHeight(grayscaleFrameData.height); currentfeatureList.setPixelDepth(grayscaleFrameData.depth); currentfeatureList.setFramePixelData(grayscaleFrameData.data); currentfeatureList.setSteeringDirection(FeatureMessage.steerLeft); try { //Send a warning if the featureQueue capacity has reached the configured warning threshold float featureQueueCapacityPercent = (((featureQueueCapacity - featureQueue.remainingCapacity()) / featureQueueCapacity) * 100); if(featureQueueCapacityPercent > featureQueueCapacityWarnPercent){ logWarningToApplicationDisplay("Warning: The FeatureQueue has reached "+featureQueueCapacityPercent+" of its capacity. Features are not being persisted fast enough"); } featureQueue.put(currentfeatureList); logInfoToApplicationDisplay("Info: Successfully sent a "+grayscaleFrameData.width+" X "+grayscaleFrameData.height+" frame for persistance"); } catch (InterruptedException ex) { logErrorToApplicationDisplay(ex, "ERROR: InterruptedException when trying to publish FeatureMessage to BlockingQueue for Persistance"); } } } }); btnReverse = new Button(navigationControlComposite, SWT.NONE); btnReverse.setSize(34, 15); btnReverse.setFont(SWTResourceManager.getFont("Segoe UI", 16, SWT.BOLD)); btnReverse.setText(" \u2193 "); btnReverse.setEnabled(false); //Register listener for button click btnReverse.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e){ logInfoToApplicationDisplay("Info: Reverse button has been pressed"); //Send the Control Message to VehicleController if(appDrivingMode.equals(manualDrivingModeCode)){ try { //Send a warning if the controllerQueue capacity has reached the configured warning threshold float controlQueueCapacityPercent = (((controllerQueueCapacity - controllerQueue.remainingCapacity()) / controllerQueueCapacity) * 100); if(controlQueueCapacityPercent > controllerQueueCapacityWarnPercent){ logWarningToApplicationDisplay("Warning: The ControllerQueue has reached "+controlQueueCapacityPercent+" of its capacity. Controls are not being processed fast enough"); } ControlMessage controlMessage = new ControlMessage(); controlMessage.setSteeringDirection(FeatureMessage.steerReverse); controllerQueue.put(controlMessage); logInfoToApplicationDisplay("Info: Successfully sent a ControlMessage to Steer Reverse"); } catch (InterruptedException ex) { logErrorToApplicationDisplay(ex, "ERROR: InterruptedException when trying to publish ControlMessage to BlockingQueue"); } } //Push the features to BlockingQueue for persistence in case the mode is Manual if(appDrivingMode.equals(manualDrivingModeCode) && (grayscaleFrameData != null)){ FeatureMessage currentfeatureList = new FeatureMessage(); currentfeatureList.setFrameWidth(grayscaleFrameData.width); currentfeatureList.setFrameHeight(grayscaleFrameData.height); currentfeatureList.setPixelDepth(grayscaleFrameData.depth); currentfeatureList.setFramePixelData(grayscaleFrameData.data); currentfeatureList.setSteeringDirection(FeatureMessage.steerReverse); try { //Send a warning if the featureQueue capacity has reached the configured warning threshold float featureQueueCapacityPercent = (((featureQueueCapacity - featureQueue.remainingCapacity()) / featureQueueCapacity) * 100); if(featureQueueCapacityPercent > featureQueueCapacityWarnPercent){ logWarningToApplicationDisplay("Warning: The FeatureQueue has reached "+featureQueueCapacityPercent+" of its capacity. Features are not being persisted fast enough"); } featureQueue.put(currentfeatureList); logInfoToApplicationDisplay("Info: Successfully sent a "+grayscaleFrameData.width+" X "+grayscaleFrameData.height+" frame for persistance"); } catch (InterruptedException ex) { logErrorToApplicationDisplay(ex, "ERROR: InterruptedException when trying to publish FeatureMessage to BlockingQueue for Persistance"); } } } }); btnRight = new Button(navigationControlComposite, SWT.NONE); btnRight.setSize(30, 15); btnRight.setFont(SWTResourceManager.getFont("Segoe UI", 16, SWT.BOLD)); btnRight.setText("\u2192"); btnRight.setEnabled(false); //Register listener for button click btnRight.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e){ logInfoToApplicationDisplay("Info: Right button has been pressed"); //Send the Control Message to VehicleController if(appDrivingMode.equals(manualDrivingModeCode)){ try { //Send a warning if the controllerQueue capacity has reached the configured warning threshold float controlQueueCapacityPercent = (((controllerQueueCapacity - controllerQueue.remainingCapacity()) / controllerQueueCapacity) * 100); if(controlQueueCapacityPercent > controllerQueueCapacityWarnPercent){ logWarningToApplicationDisplay("Warning: The ControllerQueue has reached "+controlQueueCapacityPercent+" of its capacity. Controls are not being processed fast enough"); } ControlMessage controlMessage = new ControlMessage(); controlMessage.setSteeringDirection(FeatureMessage.steerRight); controllerQueue.put(controlMessage); logInfoToApplicationDisplay("Info: Successfully sent a ControlMessage to Steer Right"); } catch (InterruptedException ex) { logErrorToApplicationDisplay(ex, "ERROR: InterruptedException when trying to publish ControlMessage to BlockingQueue"); } } //Push the features to BlockingQueue for persistence in case the mode is Manual if(appDrivingMode.equals(manualDrivingModeCode) && (grayscaleFrameData != null)){ FeatureMessage currentfeatureList = new FeatureMessage(); currentfeatureList.setFrameWidth(grayscaleFrameData.width); currentfeatureList.setFrameHeight(grayscaleFrameData.height); currentfeatureList.setPixelDepth(grayscaleFrameData.depth); currentfeatureList.setFramePixelData(grayscaleFrameData.data); currentfeatureList.setSteeringDirection(FeatureMessage.steerRight); try { //Send a warning if the featureQueue capacity has reached the configured warning threshold float featureQueueCapacityPercent = (((featureQueueCapacity - featureQueue.remainingCapacity()) / featureQueueCapacity) * 100); if(featureQueueCapacityPercent > featureQueueCapacityWarnPercent){ logWarningToApplicationDisplay("Warning: The FeatureQueue has reached "+featureQueueCapacityPercent+" of its capacity. Features are not being persisted fast enough"); } featureQueue.put(currentfeatureList); logInfoToApplicationDisplay("Info: Successfully sent a "+grayscaleFrameData.width+" X "+grayscaleFrameData.height+" frame for persistance"); } catch (InterruptedException ex) { logErrorToApplicationDisplay(ex, "ERROR: InterruptedException when trying to publish FeatureMessage to BlockingQueue for Persistance"); } } } }); //Register listener for button click btnForward.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e){ logInfoToApplicationDisplay("Info: Forward button has been pressed"); //Send the Control Message to VehicleController if(appDrivingMode.equals(manualDrivingModeCode)){ try { //Send a warning if the controllerQueue capacity has reached the configured warning threshold float controlQueueCapacityPercent = (((controllerQueueCapacity - controllerQueue.remainingCapacity()) / controllerQueueCapacity) * 100); if(controlQueueCapacityPercent > controllerQueueCapacityWarnPercent){ logWarningToApplicationDisplay("Warning: The ControllerQueue has reached "+controlQueueCapacityPercent+" of its capacity. Controls are not being processed fast enough"); } ControlMessage controlMessage = new ControlMessage(); controlMessage.setSteeringDirection(FeatureMessage.steerforward); controllerQueue.put(controlMessage); logInfoToApplicationDisplay("Info: Successfully sent a ControlMessage to Steer Forward"); } catch (InterruptedException ex) { logErrorToApplicationDisplay(ex, "ERROR: InterruptedException when trying to publish ControlMessage to BlockingQueue"); } } //Push the features to BlockingQueue for persistence in case the mode is Manual if(appDrivingMode.equals(manualDrivingModeCode) && (grayscaleFrameData != null)){ FeatureMessage currentfeatureList = new FeatureMessage(); currentfeatureList.setFrameWidth(grayscaleFrameData.width); currentfeatureList.setFrameHeight(grayscaleFrameData.height); currentfeatureList.setPixelDepth(grayscaleFrameData.depth); currentfeatureList.setFramePixelData(grayscaleFrameData.data); currentfeatureList.setSteeringDirection(FeatureMessage.steerforward); try { //Send a warning if the featureQueue capacity has reached the configured warning threshold float featureQueueCapacityPercent = (((featureQueueCapacity - featureQueue.remainingCapacity()) / featureQueueCapacity) * 100); if(featureQueueCapacityPercent > featureQueueCapacityWarnPercent){ logWarningToApplicationDisplay("Warning: The FeatureQueue has reached "+featureQueueCapacityPercent+" of its capacity. Features are not being persisted fast enough"); } featureQueue.put(currentfeatureList); logInfoToApplicationDisplay("Info: Successfully sent a "+grayscaleFrameData.width+" X "+grayscaleFrameData.height+" frame for persistance"); } catch (InterruptedException ex) { logErrorToApplicationDisplay(ex, "ERROR: InterruptedException when trying to publish FeatureMessage to BlockingQueue for Persistance"); } } } }); TrainingReviewTab = new TabItem(tabFolder, SWT.NONE); TrainingReviewTab.setText("Training and Prediction Review"); trainingDataReviewComposite = new Composite(tabFolder, SWT.NONE); TrainingReviewTab.setControl(trainingDataReviewComposite); trainingDataReviewComposite.setLayout(new GridLayout(2, false)); trainingDataReviewConfigComposite = new Composite(trainingDataReviewComposite, SWT.NONE); trainingDataReviewConfigComposite.setLayout(new GridLayout(4, false)); GridData gd_trainingDataReviewConfigComposite = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1); gd_trainingDataReviewConfigComposite.widthHint = 390; trainingDataReviewConfigComposite.setLayoutData(gd_trainingDataReviewConfigComposite); lblTrainingDataReviewFrameHeight = new Label(trainingDataReviewConfigComposite, SWT.NONE); lblTrainingDataReviewFrameHeight.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, true, 1, 1)); lblTrainingDataReviewFrameHeight.setText("Frame \r\nHeight"); lblTrainingDataReviewFrameHeight.setFont(SWTResourceManager.getFont("Segoe UI", 10, SWT.BOLD)); trainingDataReviewFrameHeight = new Text(trainingDataReviewConfigComposite, SWT.BORDER); trainingDataReviewFrameHeight.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, true, 1, 1)); trainingDataReviewFrameHeight.setBackground(SWTResourceManager.getColor(255, 250, 205)); trainingDataReviewFrameHeight.setToolTipText("Eg: 192.168.0.51"); trainingDataReviewFrameHeight.setText("144"); lblTrainingDataReviewFrameWidth = new Label(trainingDataReviewConfigComposite, SWT.NONE); lblTrainingDataReviewFrameWidth.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, true, 1, 1)); lblTrainingDataReviewFrameWidth.setText("Frame \r\nWidth"); lblTrainingDataReviewFrameWidth.setFont(SWTResourceManager.getFont("Segoe UI", 10, SWT.BOLD)); trainingDataReviewFrameWidth = new Text(trainingDataReviewConfigComposite, SWT.BORDER); trainingDataReviewFrameWidth.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, true, 1, 1)); trainingDataReviewFrameWidth.setBackground(SWTResourceManager.getColor(255, 250, 205)); trainingDataReviewFrameWidth.setToolTipText("Eg: 192.168.0.51"); trainingDataReviewFrameWidth.setText("176"); lblTrainingFileName = new Label(trainingDataReviewConfigComposite, SWT.NONE); lblTrainingFileName.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, true, 1, 1)); lblTrainingFileName.setText("Training \r\nFile Name"); lblTrainingFileName.setFont(SWTResourceManager.getFont("Segoe UI", 10, SWT.BOLD)); trainingFileNameUnderReview = new Text(trainingDataReviewConfigComposite, SWT.BORDER); GridData gd_trainingFileNameUnderReview = new GridData(SWT.FILL, SWT.CENTER, true, true, 3, 1); gd_trainingFileNameUnderReview.widthHint = 249; trainingFileNameUnderReview.setLayoutData(gd_trainingFileNameUnderReview); trainingFileNameUnderReview.setBackground(SWTResourceManager.getColor(255, 250, 205)); trainingFileNameUnderReview.setToolTipText("Eg: D:\\Vikas\\TrainingData"); btnLoadTrainingDataFile = new Button(trainingDataReviewConfigComposite, SWT.NONE); btnLoadTrainingDataFile.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, true, 4, 1)); btnLoadTrainingDataFile.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { logInfoToApplicationDisplay("Info: Button to load Training Data File for review pressed"); //Validate User Inputs if(!Utilities.validateInteger(trainingDataReviewFrameWidth.getText(), 0, 176)){ displayErrorMessageOnscreen("Training data Frame Width must have a value between 0 and 176"); }else if(!Utilities.validateInteger(trainingDataReviewFrameHeight.getText(), 0, 144)){ displayErrorMessageOnscreen("Training data Frame Height must have a value between 0 and 144"); }else{ //Cancel any currently running thread if(displayTrainingData != null){ displayTrainingData.cancel(); } //Load file and display images displayTrainingData = new DisplayTrainingData(display, trainingFileNameUnderReview.getText(), Integer.valueOf(trainingDataReviewFrameWidth.getText()), Integer.valueOf(trainingDataReviewFrameHeight.getText()), DriverDisplayAndController.defaultFrameDepth); } } }); btnLoadTrainingDataFile.setToolTipText("Load File"); btnLoadTrainingDataFile.setFont(SWTResourceManager.getFont("Segoe UI", 9, SWT.BOLD)); btnLoadTrainingDataFile.setText("Load"); label_2 = new Label(trainingDataReviewConfigComposite, SWT.SEPARATOR | SWT.HORIZONTAL); GridData gd_label_2 = new GridData(SWT.FILL, SWT.CENTER, false, false, 4, 1); gd_label_2.widthHint = 380; label_2.setLayoutData(gd_label_2); label_2.setForeground(SWTResourceManager.getColor(SWT.COLOR_BLUE)); label_2.setFont(SWTResourceManager.getFont("Segoe UI", 14, SWT.BOLD)); btnPreviousTrainingDataImage = new Button(trainingDataReviewConfigComposite, SWT.NONE); GridData gd_btnPreviousTrainingDataImage = new GridData(SWT.RIGHT, SWT.CENTER, true, true, 2, 1); gd_btnPreviousTrainingDataImage.widthHint = 184; gd_btnPreviousTrainingDataImage.heightHint = 26; btnPreviousTrainingDataImage.setLayoutData(gd_btnPreviousTrainingDataImage); btnPreviousTrainingDataImage.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { //Display the PreviousImage in the Training Data File if(displayTrainingData != null){ displayTrainingData.displayPreviousImage(predictUsingNN, predictionInProgress); } } }); btnPreviousTrainingDataImage.setText("Previous Training Set"); btnPreviousTrainingDataImage.setFont(SWTResourceManager.getFont("Segoe UI", 9, SWT.BOLD)); btnNextTrainingDataImage = new Button(trainingDataReviewConfigComposite, SWT.NONE); GridData gd_btnNextTrainingDataImage = new GridData(SWT.LEFT, SWT.CENTER, true, true, 2, 1); gd_btnNextTrainingDataImage.heightHint = 27; gd_btnNextTrainingDataImage.widthHint = 170; btnNextTrainingDataImage.setLayoutData(gd_btnNextTrainingDataImage); btnNextTrainingDataImage.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { //Display the NextImage in the Training Data File if(displayTrainingData != null){ displayTrainingData.displayNextImage(predictUsingNN, predictionInProgress); } } }); btnNextTrainingDataImage.setText("Next TrainingSet"); btnNextTrainingDataImage.setFont(SWTResourceManager.getFont("Segoe UI", 9, SWT.BOLD)); btnDeleteTrainingDataImage = new Button(trainingDataReviewConfigComposite, SWT.NONE); btnDeleteTrainingDataImage.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { //Delete the current image in the Training Data File if(displayTrainingData != null){ displayTrainingData.deleteCurrentImage(); } } }); GridData gd_btnDeleteTrainingDataImage = new GridData(SWT.RIGHT, SWT.CENTER, false, false, 2, 1); gd_btnDeleteTrainingDataImage.widthHint = 173; btnDeleteTrainingDataImage.setLayoutData(gd_btnDeleteTrainingDataImage); btnDeleteTrainingDataImage.setFont(SWTResourceManager.getFont("Segoe UI", 9, SWT.BOLD)); btnDeleteTrainingDataImage.setText("Delete Training Set"); btnReassignDirection = new Button(trainingDataReviewConfigComposite, SWT.NONE); btnReassignDirection.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { //ReAssign the direction which was captured for the current training data set //System.out.println(comboReAssignDirection.getText()+","+comboReAssignDirection.getText().trim()); if(displayTrainingData != null){ int newSteeringDirection = -1; if(comboReAssignDirection.getText().trim().startsWith("Forward")){ logInfoToApplicationDisplay("INFO: Will reassign the steering direction to - Forward"); newSteeringDirection = Integer.valueOf(FeatureMessage.steerforward); }else if(comboReAssignDirection.getText().trim().startsWith("Right")){ logInfoToApplicationDisplay("INFO: Will reassign the steering direction to - Right"); newSteeringDirection = Integer.valueOf(FeatureMessage.steerRight); }else if(comboReAssignDirection.getText().trim().startsWith("Left")){ logInfoToApplicationDisplay("INFO: Will reassign the steering direction to - Left"); newSteeringDirection = Integer.valueOf(FeatureMessage.steerLeft); }else{ logWarningToApplicationDisplay("WARNING: Unable to understand the provided steering direction for reassignment"); } if(newSteeringDirection != -1){ displayTrainingData.reAssignSteeringDirection(newSteeringDirection); } } } }); btnReassignDirection.setFont(SWTResourceManager.getFont("Segoe UI", 9, SWT.BOLD)); btnReassignDirection.setText("ReAssign Direction"); comboReAssignDirection = new Combo(trainingDataReviewConfigComposite, SWT.NONE); GridData gd_comboReAssignDirection = new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 1); gd_comboReAssignDirection.minimumWidth = 65; gd_comboReAssignDirection.widthHint = 87; comboReAssignDirection.setLayoutData(gd_comboReAssignDirection); comboReAssignDirection.add("Forward"); comboReAssignDirection.add("Right"); comboReAssignDirection.add("Left"); label = new Label(trainingDataReviewConfigComposite, SWT.SEPARATOR | SWT.HORIZONTAL); label.setForeground(SWTResourceManager.getColor(SWT.COLOR_BLUE)); label.setFont(SWTResourceManager.getFont("Segoe UI", 14, SWT.BOLD)); GridData gd_label = new GridData(SWT.FILL, SWT.CENTER, false, false, 4, 1); gd_label.widthHint = 379; label.setLayoutData(gd_label); lblPixelRowsToStripFromTopTrain = new Label(trainingDataReviewConfigComposite, SWT.NONE); lblPixelRowsToStripFromTopTrain.setFont(SWTResourceManager.getFont("Segoe UI", 9, SWT.BOLD)); lblPixelRowsToStripFromTopTrain.setText("Pixel Rows to \r\nStrip from Top"); pixelRowsToStripFromTopTraining = new Text(trainingDataReviewConfigComposite, SWT.BORDER); pixelRowsToStripFromTopTraining.setBackground(SWTResourceManager.getColor(245, 245, 220)); pixelRowsToStripFromTopTraining.setText("0"); GridData gd_pixelRowsToStripFromTopTraining = new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 1); gd_pixelRowsToStripFromTopTraining.widthHint = 28; pixelRowsToStripFromTopTraining.setLayoutData(gd_pixelRowsToStripFromTopTraining); lblPixelRowsToStripFromBotTrain = new Label(trainingDataReviewConfigComposite, SWT.NONE); lblPixelRowsToStripFromBotTrain.setFont(SWTResourceManager.getFont("Segoe UI", 9, SWT.BOLD)); lblPixelRowsToStripFromBotTrain.setText("Pixel Rows to \r\nStrip from Bottom"); pixelRowsToStripFromBottomTraining = new Text(trainingDataReviewConfigComposite, SWT.BORDER); pixelRowsToStripFromBottomTraining.setBackground(SWTResourceManager.getColor(245, 245, 220)); pixelRowsToStripFromBottomTraining.setText("0"); GridData gd_pixelRowsToStripFromBottomTraining = new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 1); gd_pixelRowsToStripFromBottomTraining.widthHint = 27; pixelRowsToStripFromBottomTraining.setLayoutData(gd_pixelRowsToStripFromBottomTraining); btnResizeTrainingFile = new Button(trainingDataReviewConfigComposite, SWT.NONE); btnResizeTrainingFile.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 4, 1)); btnResizeTrainingFile.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { logInfoToApplicationDisplay("Info: Button to Resize Training Data File pressed"); //Validate User Inputs if(!Utilities.validateInteger(String.valueOf((Integer.valueOf(pixelRowsToStripFromTopTraining.getText()) + Integer.valueOf(pixelRowsToStripFromBottomTraining.getText()))), 0, Integer.valueOf(trainingDataReviewFrameHeight.getText()))){ displayErrorMessageOnscreen("Sum of pixels rows to be stripped from top and bottom cannot exceed the current image height"); }else{ //Cancel any currently running thread if(displayTrainingData != null){ displayTrainingData.cancel(); } //Resize file try{ Utilities.resizeTrainingImage(trainingFileNameUnderReview.getText(), Integer.valueOf(trainingDataReviewFrameHeight.getText()), Integer.valueOf(trainingDataReviewFrameWidth.getText()), Integer.valueOf(pixelRowsToStripFromTopTraining.getText()), Integer.valueOf(pixelRowsToStripFromBottomTraining.getText())); displayInfoMessageOnscreen("Successfully finished resizing the images in the file"); }catch (IOException e1){ logErrorToApplicationDisplay(e1, "ERROR: IOException when trying to executing the resize"); } } } }); btnResizeTrainingFile.setFont(SWTResourceManager.getFont("Segoe UI", 9, SWT.BOLD)); btnResizeTrainingFile.setText("Resize Images in TrainingSet"); label_1 = new Label(trainingDataReviewConfigComposite, SWT.SEPARATOR | SWT.HORIZONTAL); GridData gd_label_1 = new GridData(SWT.FILL, SWT.CENTER, false, false, 4, 1); gd_label_1.widthHint = 375; label_1.setLayoutData(gd_label_1); label_1.setForeground(SWTResourceManager.getColor(SWT.COLOR_BLUE)); label_1.setFont(SWTResourceManager.getFont("Segoe UI", 14, SWT.BOLD)); capturedDataDirectoryName = new Text(trainingDataReviewConfigComposite, SWT.BORDER); capturedDataDirectoryName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 4, 1)); capturedDataDirectoryName.setToolTipText("Directory where the captured data is present in .csv files"); capturedDataDirectoryName.setBackground(SWTResourceManager.getColor(255, 228, 196)); btnGenerateSets = new Button(trainingDataReviewConfigComposite, SWT.NONE); GridData gd_btnGenerateSets = new GridData(SWT.CENTER, SWT.CENTER, false, false, 4, 1); gd_btnGenerateSets.widthHint = 382; btnGenerateSets.setLayoutData(gd_btnGenerateSets); btnGenerateSets.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { logInfoToApplicationDisplay("Info: Will start generating Training, Cross Validation and Testing data files"); if(capturedDataDirectoryName.getText() != null){ GenerateMachineLearningDataSets GMLD = new GenerateMachineLearningDataSets(); GMLD.createDataFiles(capturedDataDirectoryName.getText(), display); }else{ displayErrorMessageOnscreen("Supply a value for the directory where the captured data is present"); } } }); btnGenerateSets.setSize(349, 30); btnGenerateSets.setFont(SWTResourceManager.getFont("Segoe UI", 9, SWT.BOLD)); btnGenerateSets.setText("Generate Training, Cross \r\nValidation and Testing sets"); trainingDataReviewNavgationDetails = new Composite(trainingDataReviewComposite, SWT.NONE); trainingDataReviewNavgationDetails.setLayout(new GridLayout(2, false)); trainingDataReviewNavgationDetails.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1)); lblCapturedTrainingData = new Label(trainingDataReviewNavgationDetails, SWT.NONE); lblCapturedTrainingData.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, true, 2, 1)); lblCapturedTrainingData.setForeground(SWTResourceManager.getColor(SWT.COLOR_DARK_BLUE)); lblCapturedTrainingData.setText("TrainingSet Image"); lblCapturedTrainingData.setFont(SWTResourceManager.getFont("Segoe UI", 10, SWT.BOLD)); lblTrainingDataReview = new Label(trainingDataReviewNavgationDetails, SWT.NONE); GridData gd_lblTrainingDataReview = new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1); gd_lblTrainingDataReview.widthHint = 255; gd_lblTrainingDataReview.minimumWidth = 200; gd_lblTrainingDataReview.minimumHeight = 200; lblTrainingDataReview.setLayoutData(gd_lblTrainingDataReview); lblTrainingDataReview.setFont(SWTResourceManager.getFont("Segoe UI", 10, SWT.BOLD)); lblTrainingDataReview.setBackground(SWTResourceManager.getColor(176, 224, 230)); lblCapturedTrainingsetNavigation = new Label(trainingDataReviewNavgationDetails, SWT.NONE); GridData gd_lblCapturedTrainingsetNavigation = new GridData(SWT.CENTER, SWT.CENTER, true, true, 1, 1); gd_lblCapturedTrainingsetNavigation.widthHint = 64; lblCapturedTrainingsetNavigation.setLayoutData(gd_lblCapturedTrainingsetNavigation); lblCapturedTrainingsetNavigation.setText("Actual\r\nDirection"); lblCapturedTrainingsetNavigation.setForeground(SWTResourceManager.getColor(SWT.COLOR_DARK_BLUE)); lblCapturedTrainingsetNavigation.setFont(SWTResourceManager.getFont("Segoe UI", 9, SWT.BOLD)); lblPredictedTrainingsetNavigation = new Label(trainingDataReviewNavgationDetails, SWT.NONE); lblPredictedTrainingsetNavigation.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1)); lblPredictedTrainingsetNavigation.setFont(SWTResourceManager.getFont("Segoe UI", 9, SWT.BOLD)); lblPredictedTrainingsetNavigation.setForeground(SWTResourceManager.getColor(SWT.COLOR_DARK_BLUE)); lblPredictedTrainingsetNavigation.setText("Predicted\r\nDirection"); lblTrainingDataSteeringDirection = new Label(trainingDataReviewNavgationDetails, SWT.NONE); GridData gd_lblTrainingDataSteeringDirection = new GridData(SWT.CENTER, SWT.FILL, true, true, 1, 1); gd_lblTrainingDataSteeringDirection.widthHint = 133; lblTrainingDataSteeringDirection.setLayoutData(gd_lblTrainingDataSteeringDirection); lblTrainingDataSteeringDirection.setAlignment(SWT.CENTER); lblTrainingDataPredictedSteeringDirection = new Label(trainingDataReviewNavgationDetails, SWT.NONE); GridData gd_lblTrainingDataPredictedSteeringDirection = new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1); gd_lblTrainingDataPredictedSteeringDirection.widthHint = -29; lblTrainingDataPredictedSteeringDirection.setLayoutData(gd_lblTrainingDataPredictedSteeringDirection); lblPredictionConfidence = new Label(trainingDataReviewNavgationDetails, SWT.NONE); lblPredictionConfidence.setFont(SWTResourceManager.getFont("Segoe UI", 9, SWT.BOLD)); lblPredictionConfidence.setForeground(SWTResourceManager.getColor(SWT.COLOR_DARK_BLUE)); lblPredictionConfidence.setLayoutData(new GridData(SWT.RIGHT, SWT.FILL, false, false, 1, 1)); lblPredictionConfidence.setText("Prediction Confidence"); textTrainingPredictionConfidence = new Text(trainingDataReviewNavgationDetails, SWT.BORDER); textTrainingPredictionConfidence.setEditable(false); textTrainingPredictionConfidence.setBackground(SWTResourceManager.getColor(255, 255, 204)); textTrainingPredictionConfidence.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 1)); loggingComposite = new Composite(shell, SWT.NONE); loggingComposite.setLayout(new GridLayout(5, false)); GridData gd_loggingComposite = new GridData(SWT.FILL, SWT.FILL, true, true, 2, 2); gd_loggingComposite.widthHint = 339; gd_loggingComposite.heightHint = 568; loggingComposite.setLayoutData(gd_loggingComposite); Label lblApplicationLog = new Label(loggingComposite, SWT.NONE); lblApplicationLog.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, true, 5, 1)); lblApplicationLog.setForeground(SWTResourceManager.getColor(SWT.COLOR_DARK_BLUE)); lblApplicationLog.setFont(SWTResourceManager.getFont("Segoe UI", 10, SWT.BOLD)); lblApplicationLog.setText("Application Log"); lblLogLevel = new Label(loggingComposite, SWT.NONE); lblLogLevel.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, true, 1, 1)); lblLogLevel.setText("Log Level"); lblLogLevel.setFont(SWTResourceManager.getFont("Segoe UI", 10, SWT.BOLD)); new Label(loggingComposite, SWT.NONE); new Label(loggingComposite, SWT.NONE); chkbtnInfoLogging = new Button(loggingComposite, SWT.CHECK); chkbtnInfoLogging.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, true, 1, 1)); chkbtnInfoLogging.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if(chkbtnInfoLogging.getSelection()){ infoLoggingRequired = true; logInfoToApplicationDisplay("Info: Information logging is enabled"); }else{ logInfoToApplicationDisplay("Info: Information logging is disabled"); infoLoggingRequired = false; } } }); chkbtnInfoLogging.setText("Info"); chkbtnErrorsWarnings = new Button(loggingComposite, SWT.CHECK); chkbtnErrorsWarnings.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, true, 1, 1)); chkbtnErrorsWarnings.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if(chkbtnErrorsWarnings.getSelection()){ logInfoToApplicationDisplay("Info: Errors & Warnings will be logged"); }else{ logInfoToApplicationDisplay("Info: Errors & Warnings will NOT be logged"); } } }); chkbtnErrorsWarnings.setEnabled(false); chkbtnErrorsWarnings.setSelection(true); chkbtnErrorsWarnings.setText("Errors, Warnings"); applicationLog = new StyledText(loggingComposite, SWT.BORDER | SWT.WRAP | SWT.V_SCROLL | SWT.H_SCROLL); GridData gd_applicationLog = new GridData(SWT.FILL, SWT.FILL, true, true, 5, 1); gd_applicationLog.heightHint = 499; gd_applicationLog.widthHint = 325; applicationLog.setLayoutData(gd_applicationLog); applicationLog.setEditable(false); applicationLog.setEnabled(true); applicationLog.setAlwaysShowScrollBars(true); applicationLog.setTextLimit(100); new Label(shell, SWT.NONE); predictionComposite = new Composite(shell, SWT.NONE); GridData gd_predictionComposite = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1); gd_predictionComposite.widthHint = 557; predictionComposite.setLayoutData(gd_predictionComposite); predictionComposite.setLayout(new GridLayout(4, false)); lblInputsForPrediction = new Label(predictionComposite, SWT.NONE); lblInputsForPrediction.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 4, 1)); lblInputsForPrediction.setSize(147, 20); lblInputsForPrediction.setFont(SWTResourceManager.getFont("Segoe UI", 9, SWT.BOLD)); lblInputsForPrediction.setForeground(SWTResourceManager.getColor(SWT.COLOR_DARK_BLUE)); lblInputsForPrediction.setText("Inputs For Prediction"); lblPredictNoOfHiddenLayers = new Label(predictionComposite, SWT.NONE); lblPredictNoOfHiddenLayers.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); lblPredictNoOfHiddenLayers.setSize(145, 20); lblPredictNoOfHiddenLayers.setFont(SWTResourceManager.getFont("Segoe UI", 9, SWT.BOLD)); lblPredictNoOfHiddenLayers.setText("No Of Hidden Layers"); textPredictNumberOfHiddenLayers = new Text(predictionComposite, SWT.BORDER); textPredictNumberOfHiddenLayers.setSize(78, 26); textPredictNumberOfHiddenLayers.setBackground(SWTResourceManager.getColor(255, 255, 204)); textPredictNumberOfHiddenLayers.setText("1"); btnAssociatePredictionWeights = new Button(predictionComposite, SWT.NONE); btnAssociatePredictionWeights.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1)); btnAssociatePredictionWeights.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if(predictionInProgress){ logInfoToApplicationDisplay("Info: Removing Prediction thread, will not predict anymore"); //Disconnect from prediction if (predictUsingNN != null){ predictUsingNN.cancel(); } updatePredictionStatus("stopped"); }else{ logInfoToApplicationDisplay("Info: Will try to associate the weights for prediction"); //Check if required information has been supplied if(!Utilities.validateInteger(String.valueOf((Integer.valueOf(textPredictNumberOfHiddenLayers.getText()))), 1, 3)){ displayErrorMessageOnscreen("Number of hidden layer must be either 1, 2 or 3"); }else if((Integer.valueOf(textPredictNumberOfHiddenLayers.getText()) == 1) && ((textPredictWeightsForFirstHiddenLayer.getText().isEmpty()) || (textPredictWeightsForInputLayer.getText().isEmpty()))){ displayErrorMessageOnscreen("Provide weights for Input layer and first hidden layer"); }else if((Integer.valueOf(textPredictNumberOfHiddenLayers.getText()) == 2) && ((textPredictWeightsForFirstHiddenLayer.getText().isEmpty()) || (textPredictWeightsForInputLayer.getText().isEmpty()) || (textPredictWeightsForSecondHiddenLayer.getText().isEmpty()))){ displayErrorMessageOnscreen("Provide weights for Input layer, first and second hidden layers"); }else if((Integer.valueOf(textPredictNumberOfHiddenLayers.getText()) == 3) && ((textPredictWeightsForFirstHiddenLayer.getText().isEmpty()) || (textPredictWeightsForInputLayer.getText().isEmpty()) || (textPredictWeightsForSecondHiddenLayer.getText().isEmpty()) || (textPredictWeightsForThirdHiddenLayer.getText().isEmpty()))){ displayErrorMessageOnscreen("Provide weights for Input layer, first, second and third hidden layers"); }else{ //Create a thread to start the prediction try{ if(Integer.valueOf(textPredictNumberOfHiddenLayers.getText()) == 1){ String[] weightFileNames = {textPredictWeightsForInputLayer.getText(), textPredictWeightsForFirstHiddenLayer.getText()}; predictUsingNN = new PredictUsingNN(display, weightFileNames); }else if(Integer.valueOf(textPredictNumberOfHiddenLayers.getText()) == 2){ String[] weightFileNames = {textPredictWeightsForInputLayer.getText(), textPredictWeightsForFirstHiddenLayer.getText(), textPredictWeightsForSecondHiddenLayer.getText()}; predictUsingNN = new PredictUsingNN(display, weightFileNames); }else{ String[] weightFileNames = {textPredictWeightsForInputLayer.getText(), textPredictWeightsForFirstHiddenLayer.getText(), textPredictWeightsForSecondHiddenLayer.getText(), textPredictWeightsForThirdHiddenLayer.getText()}; predictUsingNN = new PredictUsingNN(display, weightFileNames); } }catch(FileNotFoundException e1){ logErrorToApplicationDisplay(e1,"ERROR: Unable to find weights file"); }catch(IOException e1){ logErrorToApplicationDisplay(e1,"ERROR: When trying to read the file"); } } } } }); btnAssociatePredictionWeights.setFont(SWTResourceManager.getFont("Segoe UI", 9, SWT.BOLD)); btnAssociatePredictionWeights.setText("Associate Weights for Prediction"); btnPredictForAllDataSetsInFile = new Button(predictionComposite, SWT.NONE); btnPredictForAllDataSetsInFile.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { //Check if the prediction weights are associated and a filename if specified if(predictUsingNN != null){ if(trainingFileNameUnderReview.getText() != null){ try{ BufferedReader brTrainingFile = new BufferedReader(new FileReader(trainingFileNameUnderReview.getText())); String trainingSet = null; chkbtnInfoLogging.setSelection(true); infoLoggingRequired = true; //Define variables for capturing stats float trainingFileLineNumber = 0; float noOfCorrectPredictions = 0; float noOfForwardsInFiles = 0; float noOfRightsInFiles = 0; float noOfLeftsInFiles = 0; float noOfForwardsPredictedCorrectly = 0; float noOfRightsPredictedCorrectly = 0; float noOfLeftsPredictedCorrectly = 0; float noOfForwardsPredictedAsRight = 0; float noOfForwardsPredictedAsLeft = 0; float noOfRightsPredictedAsForward = 0; float noOfRightsPredictedAsLeft = 0; float noOfLeftsPredictedAsForward = 0; float noOfLeftsPredictedAsRight = 0; while((trainingSet = brTrainingFile.readLine()) != null){ trainingFileLineNumber++; String[] columnValues = trainingSet.split(","); int[] framePixelData = new int[columnValues.length - 1]; int actualSteeringDirection = -1; for(int i=0;i<columnValues.length;i++){ if(i == (columnValues.length - 1)){ actualSteeringDirection = Integer.valueOf(columnValues[i]); if(actualSteeringDirection == 1){ noOfForwardsInFiles++; }else if(actualSteeringDirection == 2){ noOfRightsInFiles++; }else if(actualSteeringDirection == 3){ noOfLeftsInFiles++; }else{ //Do Nothing } }else{ framePixelData[i] = Integer.valueOf(columnValues[i]); } } FeatureMessage featureMessage = new FeatureMessage(); featureMessage.setFramePixelDataInt(framePixelData); FeatureMessage returnedFeatureMessage = predictUsingNN.predictSteeringDirection(featureMessage); int javaPredictedSteeringDirection = Integer.valueOf(returnedFeatureMessage.getSteeringDirection()); if(actualSteeringDirection == javaPredictedSteeringDirection){ noOfCorrectPredictions++; if(actualSteeringDirection == 1){ noOfForwardsPredictedCorrectly++; }else if(actualSteeringDirection == 2){ noOfRightsPredictedCorrectly++; }else if(actualSteeringDirection == 3){ noOfLeftsPredictedCorrectly++; }else{ //Do Nothing } }else{ if(actualSteeringDirection == 1){ if(javaPredictedSteeringDirection == 2){ noOfForwardsPredictedAsRight++; }else if(javaPredictedSteeringDirection == 3){ noOfForwardsPredictedAsLeft++; }else{ //Do Nothing } }else if(actualSteeringDirection == 2){ if(javaPredictedSteeringDirection == 1){ noOfRightsPredictedAsForward++; }else if(javaPredictedSteeringDirection == 3){ noOfRightsPredictedAsLeft++; }else{ //Do Nothing } }else if(actualSteeringDirection == 3){ if(javaPredictedSteeringDirection == 1){ noOfLeftsPredictedAsForward++; }else if(javaPredictedSteeringDirection == 2){ noOfLeftsPredictedAsRight++; }else{ //Do Nothing } }else{ //Do Nothing } } } brTrainingFile.close(); //Output the stats float predictedCorrectlyPercent = (noOfCorrectPredictions / trainingFileLineNumber)*100; float forwardsPredictedCorrectlyPercent = (noOfForwardsPredictedCorrectly / noOfForwardsInFiles)*100; float forwardsPredictedAsRight = (noOfForwardsPredictedAsRight / noOfForwardsInFiles)*100; float forwardsPredictedAsLeft = (noOfForwardsPredictedAsLeft / noOfForwardsInFiles)*100; float rightsPredictedCorrectlyPercent = (noOfRightsPredictedCorrectly / noOfRightsInFiles)*100; float rightsPredictedAsForward = (noOfRightsPredictedAsForward / noOfRightsInFiles)*100; float rightsPredictedAsLeft = (noOfRightsPredictedAsLeft / noOfRightsInFiles)*100; float leftsPredictedCorrectlyPercent = (noOfLeftsPredictedCorrectly / noOfLeftsInFiles)*100; float leftsPredcitedAsForward = (noOfLeftsPredictedAsForward / noOfLeftsInFiles)*100; float leftsPredictedAsRight = (noOfLeftsPredictedAsRight / noOfLeftsInFiles)*100; logInfoToApplicationDisplay(""); logInfoToApplicationDisplay(""); logInfoToApplicationDisplay("====================================="); logInfoToApplicationDisplay("====================================="); logInfoToApplicationDisplay("Number of data sets in file = "+Integer.valueOf((int) Math.floor(trainingFileLineNumber))); logInfoToApplicationDisplay("Predicted correctly percentage = "+Math.round(predictedCorrectlyPercent)+" %"); logInfoToApplicationDisplay(" logInfoToApplicationDisplay("Number of Forward steers = "+Integer.valueOf((int) Math.floor(noOfForwardsInFiles))); logInfoToApplicationDisplay("Predicted correctly percentage= "+Math.round(forwardsPredictedCorrectlyPercent)+" %"); logInfoToApplicationDisplay("Predicted wrongly as Right percentage= "+Math.round(forwardsPredictedAsRight)+" %"); logInfoToApplicationDisplay("Predicted wrongly as Left percentage= "+Math.round(forwardsPredictedAsLeft)+" %"); logInfoToApplicationDisplay(" logInfoToApplicationDisplay("Number of Right steers = "+Integer.valueOf((int) Math.floor(noOfRightsInFiles))); logInfoToApplicationDisplay("Predicted correctly percentage= "+Math.round(rightsPredictedCorrectlyPercent)+" %"); logInfoToApplicationDisplay("Predicted wrongly as Forward percentage= "+Math.round(rightsPredictedAsForward)+" %"); logInfoToApplicationDisplay("Predicted wrongly as Left percentage= "+Math.round(rightsPredictedAsLeft)+" %"); logInfoToApplicationDisplay(" logInfoToApplicationDisplay("Number of Left steers = "+Integer.valueOf((int) Math.floor(noOfLeftsInFiles))); logInfoToApplicationDisplay("Predicted correctly percentage= "+Math.round(leftsPredictedCorrectlyPercent)+" %"); logInfoToApplicationDisplay("Predicted wrongly as Forward percentage= "+Math.round(leftsPredcitedAsForward)+" %"); logInfoToApplicationDisplay("Predicted wrongly as Right percentage= "+Math.round(leftsPredictedAsRight)+" %"); logInfoToApplicationDisplay("====================================="); logInfoToApplicationDisplay("====================================="); logInfoToApplicationDisplay(""); logInfoToApplicationDisplay(""); }catch(Exception e2){ logErrorToApplicationDisplay(e2, "Error with the training file"); } }else{ logWarningToApplicationDisplay("WARN: Specify a valid training file"); } }else{ logWarningToApplicationDisplay("WARN: Prediction weights have not been associated"); } } }); btnPredictForAllDataSetsInFile.setFont(SWTResourceManager.getFont("Segoe UI", 9, SWT.BOLD)); btnPredictForAllDataSetsInFile.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1)); btnPredictForAllDataSetsInFile.setText("Bulk Predict"); lblPredictWeightsForInputLayer = new Label(predictionComposite, SWT.NONE); lblPredictWeightsForInputLayer.setSize(87, 40); lblPredictWeightsForInputLayer.setFont(SWTResourceManager.getFont("Segoe UI", 9, SWT.BOLD)); lblPredictWeightsForInputLayer.setText("Weights for \r\nInput Layer"); textPredictWeightsForInputLayer = new Text(predictionComposite, SWT.BORDER); GridData gd_textPredictWeightsForInputLayer = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); gd_textPredictWeightsForInputLayer.widthHint = 173; textPredictWeightsForInputLayer.setLayoutData(gd_textPredictWeightsForInputLayer); textPredictWeightsForInputLayer.setSize(180, 26); textPredictWeightsForInputLayer.setBackground(SWTResourceManager.getColor(255, 255, 204)); lblPredictWeightsForFirstHiddenLayer = new Label(predictionComposite, SWT.NONE); lblPredictWeightsForFirstHiddenLayer.setSize(127, 40); lblPredictWeightsForFirstHiddenLayer.setFont(SWTResourceManager.getFont("Segoe UI", 9, SWT.BOLD)); lblPredictWeightsForFirstHiddenLayer.setText("Weights for \r\nFirst Hidden Layer"); textPredictWeightsForFirstHiddenLayer = new Text(predictionComposite, SWT.BORDER); GridData gd_textPredictWeightsForFirstHiddenLayer = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); gd_textPredictWeightsForFirstHiddenLayer.widthHint = 172; textPredictWeightsForFirstHiddenLayer.setLayoutData(gd_textPredictWeightsForFirstHiddenLayer); textPredictWeightsForFirstHiddenLayer.setSize(180, 26); textPredictWeightsForFirstHiddenLayer.setBackground(SWTResourceManager.getColor(255, 255, 204)); lblPredictWeightsForSecondHiddenLayer = new Label(predictionComposite, SWT.NONE); lblPredictWeightsForSecondHiddenLayer.setSize(146, 40); lblPredictWeightsForSecondHiddenLayer.setFont(SWTResourceManager.getFont("Segoe UI", 9, SWT.BOLD)); lblPredictWeightsForSecondHiddenLayer.setText("Weights for \r\nSecond Hidden Layer"); textPredictWeightsForSecondHiddenLayer = new Text(predictionComposite, SWT.BORDER); textPredictWeightsForSecondHiddenLayer.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); textPredictWeightsForSecondHiddenLayer.setSize(255, 26); textPredictWeightsForSecondHiddenLayer.setBackground(SWTResourceManager.getColor(255, 255, 204)); lblPredictWeightsForThirdHiddenLayer = new Label(predictionComposite, SWT.NONE); lblPredictWeightsForThirdHiddenLayer.setSize(133, 40); lblPredictWeightsForThirdHiddenLayer.setFont(SWTResourceManager.getFont("Segoe UI", 9, SWT.BOLD)); lblPredictWeightsForThirdHiddenLayer.setText("Weights for \r\nThird Hidden Layer"); textPredictWeightsForThirdHiddenLayer = new Text(predictionComposite, SWT.BORDER); textPredictWeightsForThirdHiddenLayer.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1)); textPredictWeightsForThirdHiddenLayer.setSize(654, 26); textPredictWeightsForThirdHiddenLayer.setBackground(SWTResourceManager.getColor(255, 255, 204)); } /** * Create the Event loop */ private void createEventLoop(){ while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); //System.out.println("Display Sleeping"); } System.out.println("Info: About to dispose the display"); display.dispose(); } /** * Update the current status of connection to the Sensor device * @param currentStatus */ protected static synchronized void updateSensorConnectionStatus(boolean connected){ connectedToSensor = connected; if(connectedToSensor){ btnConnectToSensor.setText("Disconnect"); if(connectedToController){ //Enable direction buttons btnForward.setEnabled(true); btnLeft.setEnabled(true); btnReverse.setEnabled(true); btnRight.setEnabled(true); }else{ //Disable direction buttons btnForward.setEnabled(false); btnLeft.setEnabled(false); btnReverse.setEnabled(false); btnRight.setEnabled(false); } }else{ btnConnectToSensor.setText("Connect"); //Disable direction buttons btnForward.setEnabled(false); btnLeft.setEnabled(false); btnReverse.setEnabled(false); btnRight.setEnabled(false); } } /** * Update the current status of connection to the Arduino / Controller * @param currentStatus */ protected static synchronized void updateControllerConnectionStatus(boolean connected){ connectedToController = connected; if(connectedToController){ btnConnectToController.setText("Disconnect"); if(connectedToSensor){ //Enable direction buttons btnForward.setEnabled(true); btnLeft.setEnabled(true); btnReverse.setEnabled(true); btnRight.setEnabled(true); }else{ //Disable direction buttons btnForward.setEnabled(false); btnLeft.setEnabled(false); btnReverse.setEnabled(false); btnRight.setEnabled(false); } }else{ btnConnectToSensor.setText("Connect"); //Disable direction buttons btnForward.setEnabled(false); btnLeft.setEnabled(false); btnReverse.setEnabled(false); btnRight.setEnabled(false); } } /** * Display the frame received from Sensor Device on screen */ protected static synchronized void displayFramesOnCanvas(int width, int height, int depth, byte[] frameData, boolean sensorVideo){ if(sensorVideo){ //Display Sensor Video //Initialize Imagedata grayscaleFrameData = new ImageData(width, height, depth, paletteDataGrayscale); //Assign ImageData grayscaleFrameData.data = frameData; //Create Image org.eclipse.swt.graphics.Image grayscaleFrame = new Image(display,grayscaleFrameData); //Paint Image lblSensorVideoOut.setImage(grayscaleFrame); //Release OS resources sampleImage to the image/frame //grayscaleFrame.dispose(); logInfoToApplicationDisplay("Info: Successfully painted a "+width+" X "+height+" frame from Sensor Device on Screen"); } else{ //Display captured training data image //Initialize Imagedata ImageData trainingFrameData = new ImageData(width, height, depth, paletteDataGrayscale); //Assign ImageData trainingFrameData.data = frameData; //Create Image org.eclipse.swt.graphics.Image trainingFrame = new Image(display,trainingFrameData); //Paint Image lblTrainingDataReview.setImage(trainingFrame); //Release OS resources sampleImage to the image/frame //grayscaleFrame.dispose(); logInfoToApplicationDisplay("Info: Successfully painted a "+width+" X "+height+" frame from capture training data on Screen"); } } /** * This method can be used to log Informational message onto to the Application Log on the screen */ protected static synchronized void logInfoToApplicationDisplay(String logEntry){ if(infoLoggingRequired){ if (applicationLog.getLineCount() < maxLinesInLog){ //Log after prefixing with a new line applicationLog.insert(System.getProperty("line.separator")+logEntry); System.out.println(logEntry); }else{ //Remove the oldest line from the logs and insert the new entry after prefixing with a new line String currentLogContent = applicationLog.getText(); applicationLog.setText(currentLogContent.substring(0, currentLogContent.lastIndexOf(System.getProperty("line.separator")))); applicationLog.insert(System.getProperty("line.separator")+logEntry); System.out.println(logEntry); } }else{ //Dont Log } } /** * This method can be used to log Exception Stack traces in a readable format on the Application Log */ protected static synchronized void logErrorToApplicationDisplay(Exception e, String informationMessage){ if(chkbtnErrorsWarnings.getSelection()){ if(infoLoggingRequired){ StackTraceElement[] stackTraceLines = e.getStackTrace(); for (int i=0;i<stackTraceLines.length;i++){ logInfoToApplicationDisplay("\t"+"\t"+"\t"+"\t"+stackTraceLines[i].toString()); } logInfoToApplicationDisplay(e.getMessage()); logInfoToApplicationDisplay(informationMessage); }else{ infoLoggingRequired = true; StackTraceElement[] stackTraceLines = e.getStackTrace(); for (int i=0;i<stackTraceLines.length;i++){ logInfoToApplicationDisplay("\t"+"\t"+"\t"+"\t"+stackTraceLines[i].toString()); } logInfoToApplicationDisplay(e.getMessage()); logInfoToApplicationDisplay(informationMessage); infoLoggingRequired = false; } }else{ //Dont Log } } /** * This method can be used to log warnings on the Application Log */ protected static synchronized void logWarningToApplicationDisplay(String logEntry){ if(chkbtnErrorsWarnings.getSelection()){ if(infoLoggingRequired){ logInfoToApplicationDisplay(logEntry); }else{ infoLoggingRequired = true; logInfoToApplicationDisplay(logEntry); infoLoggingRequired = false; } }else{ //Dont Log } } /** * Update the name of the current Training Data File on screen for review * */ protected static synchronized void updateCurrentTrainingParams(String trainingDataFileName){ trainingFileNameUnderReview.setText(trainingDataFileName); trainingDataReviewFrameWidth.setText(String.valueOf(DriverDisplayAndController.defaultFrameWidth)); trainingDataReviewFrameHeight.setText(String.valueOf(DriverDisplayAndController.defaultFrameHeight - (Integer.valueOf(pixelRowsToStripFromTop.getText()) + Integer.valueOf(pixelRowsToStripFromBottom.getText())))); } /** * When reviewing the Training data, used to display the Steering Direction which was chosen * @param steeringDirection */ protected static synchronized void displayTrainingDataSteeringDirection(String steeringDirection){ logInfoToApplicationDisplay("Info: SteeringDirection is: "+steeringDirection); if(Integer.valueOf(steeringDirection) == Integer.valueOf(FeatureMessage.steerforward)){ lblTrainingDataSteeringDirection.setImage(SWTResourceManager.getImage(DriverDisplayAndController.class, "/com/vikas/projs/ml/autonomousvehicle/images/Forward.jpg")); }else if(Integer.valueOf(steeringDirection) == Integer.valueOf(FeatureMessage.steerReverse)){ lblTrainingDataSteeringDirection.setImage(SWTResourceManager.getImage(DriverDisplayAndController.class, "/com/vikas/projs/ml/autonomousvehicle/images/Reverse.jpg")); }else if(Integer.valueOf(steeringDirection) == Integer.valueOf(FeatureMessage.steerLeft)){ lblTrainingDataSteeringDirection.setImage(SWTResourceManager.getImage(DriverDisplayAndController.class, "/com/vikas/projs/ml/autonomousvehicle/images/Left.jpg")); }else if(Integer.valueOf(steeringDirection) == Integer.valueOf(FeatureMessage.steerRight)){ lblTrainingDataSteeringDirection.setImage(SWTResourceManager.getImage(DriverDisplayAndController.class, "/com/vikas/projs/ml/autonomousvehicle/images/Right.jpg")); }else{ logWarningToApplicationDisplay("Warning: Unable to understand the captured Steering Direction: "+steeringDirection); } } /** * When reviewing the Training data, used to display the predicted Steering Direction * @param steeringDirection */ protected static synchronized void displayPredictedTrainingDataSteeringDirection(String steeringDirection, Boolean resetImage){ if(resetImage){ lblTrainingDataPredictedSteeringDirection.setImage(null); }else{ logInfoToApplicationDisplay("Info: Prediced SteeringDirection is: "+steeringDirection); if(Integer.valueOf(steeringDirection) == Integer.valueOf(FeatureMessage.steerforward)){ lblTrainingDataPredictedSteeringDirection.setImage(SWTResourceManager.getImage(DriverDisplayAndController.class, "/com/vikas/projs/ml/autonomousvehicle/images/Forward.jpg")); }else if(Integer.valueOf(steeringDirection) == Integer.valueOf(FeatureMessage.steerReverse)){ lblTrainingDataPredictedSteeringDirection.setImage(SWTResourceManager.getImage(DriverDisplayAndController.class, "/com/vikas/projs/ml/autonomousvehicle/images/Reverse.jpg")); }else if(Integer.valueOf(steeringDirection) == Integer.valueOf(FeatureMessage.steerLeft)){ lblTrainingDataPredictedSteeringDirection.setImage(SWTResourceManager.getImage(DriverDisplayAndController.class, "/com/vikas/projs/ml/autonomousvehicle/images/Left.jpg")); }else if(Integer.valueOf(steeringDirection) == Integer.valueOf(FeatureMessage.steerRight)){ lblTrainingDataPredictedSteeringDirection.setImage(SWTResourceManager.getImage(DriverDisplayAndController.class, "/com/vikas/projs/ml/autonomousvehicle/images/Right.jpg")); }else{ logWarningToApplicationDisplay("Warning: Unable to understand the predicted Steering Direction: "+steeringDirection); } } } /** * Used to display message on the screen to the user in a message box / message dialog * @param message */ protected static synchronized void displayErrorMessageOnscreen(String message){ MessageDialog.openError(shell, "Error", message); } /** * Used to display message on the screen to the user in a message box / message dialog * @param message */ protected static synchronized void displayInfoMessageOnscreen(String message){ MessageDialog.openInformation(shell, "Info", message); } /** * Update the button text for previous, current and next image/training set * @param previous * @param current * @param next */ protected static synchronized void updateTrainingDataFrameButtonText(int previous, int current, int next){ btnPreviousTrainingDataImage.setText("Previous TrainingSet "+"("+previous+")"); btnDeleteTrainingDataImage.setText("Delete Training Set "+"("+current+")"); btnNextTrainingDataImage.setText("Next TrainingSet "+"("+next+")"); } /** * Update the text of Prediction button * @param currentStatus */ protected static synchronized void updatePredictionStatus(String currentStatus){ if(currentStatus.equalsIgnoreCase("started")){ predictionInProgress = true; btnAssociatePredictionWeights.setText("Stop Prediction"); }else{ btnAssociatePredictionWeights.setText("Start Prediction"); predictionInProgress = false; } } /** * Update the background of the Training Data Review label to reflect the prediction status * @param status */ protected static synchronized void updateTrainingDataReviewLabelBgd(String status){ if(status.equalsIgnoreCase("GREEN")){ lblTrainingDataReview.setBackground(new Color(display, 173, 255, 47)); }else if(status.equalsIgnoreCase("RED")){ lblTrainingDataReview.setBackground(new Color(display, 255, 140, 0)); }else{ lblTrainingDataReview.setBackground(new Color(display, 176, 224, 230)); } } /** * Update the Steering direction Prediction confidence * @param predictionConfidence */ protected static synchronized void updateSteeringPredictionConfidence(int predictionConfidence){ if(predictionConfidence == -1){ textTrainingPredictionConfidence.setText(""); }else{ textTrainingPredictionConfidence.setText(String.valueOf(predictionConfidence)+" %"); } } }
package com.siondream.core; public interface PlatformResolver { public void openURL(String url); public void rateApp(); public void sendFeedback(); }
package org.eclipse.birt.report.designer.data.ui.dataset; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.eclipse.birt.core.exception.BirtException; import org.eclipse.birt.data.engine.api.IResultIterator; import org.eclipse.birt.data.engine.api.IResultMetaData; import org.eclipse.birt.data.engine.core.DataException; import org.eclipse.birt.data.engine.script.ScriptEvalUtil; import org.eclipse.birt.report.data.adapter.impl.DataSetMetaDataHelper; import org.eclipse.birt.report.designer.data.ui.util.DTPUtil; import org.eclipse.birt.report.designer.data.ui.util.DataSetProvider; import org.eclipse.birt.report.designer.data.ui.util.Utility; import org.eclipse.birt.report.designer.internal.ui.util.ExceptionHandler; import org.eclipse.birt.report.designer.nls.Messages; import org.eclipse.birt.report.designer.ui.ReportPlugin; import org.eclipse.birt.report.designer.ui.dialogs.properties.AbstractPropertyPage; import org.eclipse.birt.report.designer.ui.preferences.DateSetPreferencePage; import org.eclipse.birt.report.engine.api.EngineConfig; import org.eclipse.birt.report.engine.api.EngineConstants; import org.eclipse.birt.report.model.api.DataSetHandle; import org.eclipse.birt.report.model.api.DesignElementHandle; import org.eclipse.birt.report.model.api.ModuleHandle; import org.eclipse.birt.report.model.api.activity.NotificationEvent; import org.eclipse.birt.report.model.api.activity.SemanticException; import org.eclipse.birt.report.model.api.core.Listener; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Preferences; import org.eclipse.core.runtime.Status; import org.eclipse.datatools.connectivity.oda.util.ResourceIdentifiers; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.dialogs.IMessageProvider; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.ColumnPixelData; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.TableLayout; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerSorter; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CLabel; import org.eclipse.swt.dnd.Clipboard; import org.eclipse.swt.dnd.TextTransfer; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TableItem; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.progress.UIJob; /** * Property page to preview the resultset. * */ public class ResultSetPreviewPage extends AbstractPropertyPage implements Listener { private TableViewer resultSetTableViewer = null; private transient Table resultSetTable = null; private boolean modelChanged = true; private boolean needsUpdateUI = true; private int columnCount = -1; private List recordList = null; private DataSetViewData[] metaData; private List errorList = new ArrayList(); private String[] columnBindingNames; private int previousMaxRow = -1; private CLabel promptLabel; /** * The constructor. */ public ResultSetPreviewPage( ) { super( ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.designer.ui.IPropertyPage#createPageControl(org.eclipse.swt.widgets.Composite) */ public Control createPageControl( Composite parent ) { Composite resultSetComposite = new Composite( parent, SWT.NONE ); GridLayout layout = new GridLayout( ); layout.verticalSpacing = 15; resultSetComposite.setLayout( layout ); resultSetComposite.setLayoutData( new GridData( GridData.FILL_BOTH ) ); resultSetTable = new Table( resultSetComposite, SWT.FULL_SELECTION | SWT.MULTI | SWT.VIRTUAL | SWT.BORDER ); resultSetTable.setHeaderVisible( true ); resultSetTable.setLinesVisible( true ); resultSetTable.setLayoutData( new GridData( GridData.FILL_BOTH ) ); ( (DataSetHandle) getContainer( ).getModel( ) ).addListener( this ); resultSetTable.addMouseListener( new MouseAdapter( ) { public void mouseUp( MouseEvent e ) { // if not mouse left button if ( e.button != 1 ) { MenuManager menuManager = new MenuManager( ); ResultSetTableAction copyAction = ResultSetTableActionFactory.createResultSetTableAction( resultSetTable, ResultSetTableActionFactory.COPY_ACTION ); ResultSetTableAction selectAllAction = ResultSetTableActionFactory.createResultSetTableAction( resultSetTable, ResultSetTableActionFactory.SELECTALL_ACTION ); menuManager.add( copyAction ); menuManager.add( selectAllAction ); menuManager.update( ); copyAction.update( ); selectAllAction.update( ); Menu contextMenu = menuManager.createContextMenu( resultSetTable ); contextMenu.setEnabled( true ); contextMenu.setVisible( true ); } } } ); createResultSetTableViewer( ); promptLabel = new CLabel( resultSetComposite, SWT.WRAP ); GridData labelData = new GridData( GridData.FILL_HORIZONTAL ); promptLabel.setLayoutData( labelData ); return resultSetComposite; } private void createResultSetTableViewer( ) { resultSetTableViewer = new TableViewer( resultSetTable ); resultSetTableViewer.setSorter( null ); resultSetTableViewer.setContentProvider( new IStructuredContentProvider( ) { public Object[] getElements( Object inputElement ) { if ( inputElement instanceof List ) { return ( (List) inputElement ).toArray( ); } return new Object[0]; } public void inputChanged( Viewer viewer, Object oldInput, Object newInput ) { } public void dispose( ) { } } ); resultSetTableViewer.setLabelProvider( new ITableLabelProvider( ) { public Image getColumnImage( Object element, int columnIndex ) { return null; } public String getColumnText( Object element, int columnIndex ) { if ( ( element instanceof CellValue[] ) && ( ( (CellValue[]) element ).length > 0 ) ) { return ( (CellValue[]) element )[columnIndex].getDisplayValue( ); } else { return null; } } public void addListener( ILabelProviderListener listener ) { } public void dispose( ) { } public boolean isLabelProperty( Object element, String property ) { return false; } public void removeListener( ILabelProviderListener listener ) { } } ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.designer.ui.IPropertyPage#pageActivated() */ public void pageActivated( ) { getContainer( ).setMessage( Messages.getString( "dataset.editor.preview" ),//$NON-NLS-1$ IMessageProvider.NONE ); if ( modelChanged || ( (DataSetEditor) this.getContainer( ) ).modelChanged( ) ) { modelChanged = false; new UIJob( "" ) { //$NON-NLS-1$ public IStatus runInUIThread( IProgressMonitor monitor ) { updateResultsProcess( ); return Status.OK_STATUS; } }.schedule( ); } } protected final void clearResultSetTable( ) { if ( recordList == null ) recordList = new ArrayList( ); else recordList.clear( ); // clear everything else resultSetTable.removeAll( ); // Clear the columns TableColumn[] columns = resultSetTable.getColumns( ); for ( int n = 0; n < columns.length; n++ ) { columns[n].dispose( ); } } private int getMaxRowPreference( ) { int maxRow; Preferences preferences = ReportPlugin.getDefault( ) .getPluginPreferences( ); if ( preferences.contains( DateSetPreferencePage.USER_MAXROW ) ) { maxRow = preferences.getInt( DateSetPreferencePage.USER_MAXROW ); } else { maxRow = DateSetPreferencePage.DEFAULT_MAX_ROW; preferences.setValue( DateSetPreferencePage.USER_MAXROW, maxRow ); } return maxRow; } /** * Show ProgressMonitorDialog * */ private void updateResultsProcess( ) { needsUpdateUI = true; clearResultSetTable( ); IRunnableWithProgress runnable = new IRunnableWithProgress( ) { public void run( IProgressMonitor monitor ) throws InvocationTargetException, InterruptedException { monitor.beginTask( "", IProgressMonitor.UNKNOWN ); //$NON-NLS-1$ if ( resultSetTable != null && !resultSetTable.isDisposed( ) ) { ModuleHandle handle = null; DataSetHandle dsHandle = ( (DataSetEditor) getContainer( ) ).getHandle( ); handle = dsHandle.getModuleHandle( ); DataSetPreviewer previewer = new DataSetPreviewer( dsHandle, getMaxRowPreference( )); Map dataSetBindingMap = new HashMap( ); Map dataSourceBindingMap = new HashMap( ); try { clearProperyBindingMap( dataSetBindingMap, dataSourceBindingMap ); Map appContext = new HashMap( ); ResourceIdentifiers identifiers = new ResourceIdentifiers( ); String resouceIDs = ResourceIdentifiers.ODA_APP_CONTEXT_KEY_CONSUMER_RESOURCE_IDS; identifiers.setApplResourceBaseURI( DTPUtil.getInstance( ).getBIRTResourcePath( ) ); identifiers.setDesignResourceBaseURI( DTPUtil.getInstance( ).getReportDesignPath( ) ); appContext.put( resouceIDs,identifiers); AppContextPopulator.populateApplicationContext( dsHandle, appContext ); previewer.open( appContext, getEngineConfig( handle ) ); populateRecords( previewer.preview( ) ); previewer.close( ); monitor.done( ); } catch ( BirtException e ) { throw new InvocationTargetException( e ); } finally { resetPropertyBinding( dataSetBindingMap, dataSourceBindingMap ); } } } }; try { new ProgressMonitorDialog( PlatformUI.getWorkbench( ) .getDisplay( ) .getActiveShell( ) ) { protected void cancelPressed( ) { super.cancelPressed( ); needsUpdateUI = false; } }.run( true, true, runnable ); } catch ( InvocationTargetException e ) { //this ExceptionHandler can show exception stacktrace org.eclipse.datatools.connectivity.internal.ui.dialogs.ExceptionHandler.showException( resultSetTable.getShell( ), Messages.getString( "CssErrDialog.Error" ), e.getCause( ).getLocalizedMessage( ), e.getCause( ) ); } catch ( InterruptedException e ) { //this ExceptionHandler can show exception stacktrace org.eclipse.datatools.connectivity.internal.ui.dialogs.ExceptionHandler.showException( resultSetTable.getShell( ), Messages.getString( "CssErrDialog.Error" ), e.getLocalizedMessage( ), e ); } updateResultSetTableUI( ); } private EngineConfig getEngineConfig( ModuleHandle handle ) { EngineConfig ec = new EngineConfig( ); ClassLoader parent = Thread.currentThread( ).getContextClassLoader( ); if ( parent == null ) { parent = this.getClass( ).getClassLoader( ); } ClassLoader customClassLoader = DataSetProvider.getCustomScriptClassLoader( parent, handle ); ec.getAppContext( ).put( EngineConstants.APPCONTEXT_CLASSLOADER_KEY, customClassLoader ); return ec; } /** * Populate records to be retrieved when re-render resultSetTable * * @param metaData * @param query * @throws BirtException */ private void populateRecords( IResultIterator iter ) { try { if ( iter != null ) { IResultMetaData meta = iter.getResultMetaData( ); while ( iter.next( ) ) { CellValue[] record = new CellValue[meta.getColumnCount( )]; for ( int n = 0; n < record.length; n++ ) { CellValue cv = new CellValue( ); Object value = iter.getValue( meta.getColumnName( n+1 ) ); String disp = null; if( value instanceof Number ) disp = value.toString( ); else disp = iter.getString( meta.getColumnName( n+1 ) ); cv.setDisplayValue( disp ); cv.setRealValue( value ); record[n] = cv; } recordList.add( record ); } setPromptLabelText( ); iter.close( ); } } catch ( RuntimeException e ) { errorList.add( e ); } catch ( BirtException e ) { errorList.add( e ); } } /** * Set the prompt label text * */ private void setPromptLabelText( ) { Display.getDefault( ).syncExec( new Runnable( ) { public void run( ) { String prompt = ""; prompt = Messages.getFormattedString( "dataset.resultset.preview.promptMessage.recordsNum", new Object[]{ recordList.size( ) } ); if ( recordList != null ) { if ( recordList.size( ) >= getMaxRowPreference( ) ) { prompt += " " + Messages.getString( "dataset.resultset.preview.promptMessage.MoreRecordsExist" ); } } if ( promptLabel != null ) { promptLabel.setText( prompt ); } } } ); } private void updateResultSetTableUI( ) { if ( !needsUpdateUI ) return; if ( !errorList.isEmpty( ) ) { setPromptLabelText( ); ExceptionHandler.handle( (Exception) errorList.get( 0 ) ); } else { metaData = ( (DataSetEditor) this.getContainer( ) ).getCurrentItemModel( ); if ( metaData != null ) createColumns( metaData ); insertRecords( ); } } private void createColumns( DataSetViewData[] rsMd ) { DataSetViewData[] columnsModel = rsMd; TableColumn column = null; TableLayout layout = new TableLayout( ); for ( int n = 0; n < rsMd.length; n++ ) { column = new TableColumn( resultSetTable, SWT.LEFT ); column.setText( getColumnDisplayName( columnsModel, n ) ); column.setResizable( true ); layout.addColumnData( new ColumnPixelData( 120, true ) ); addColumnSortListener( column, n ); column.pack( ); } resultSetTable.setLayout( layout ); resultSetTable.layout( true ); } private void insertRecords( ) { resultSetTableViewer.setInput( recordList ); } private String getColumnDisplayName( DataSetViewData[] columnsModel, int index ) { if ( columnsModel == null || columnsModel.length == 0 || index < 0 || index > columnsModel.length ) { return "";//$NON-NLS-1$ } String externalizedName = columnsModel[index].getExternalizedName( ); if ( externalizedName != null && ( !externalizedName.equals( "" ) ) ) return externalizedName; return columnsModel[index].getDisplayName( ); } /** * Add listener to a column * * @param column * @param n */ private void addColumnSortListener( TableColumn column, final int index ) { column.addSelectionListener( new SelectionListener( ) { private boolean asc = false; public void widgetSelected( SelectionEvent e ) { sort( index, asc ); asc = !asc; } public void widgetDefaultSelected( SelectionEvent e ) { } } ); } /** * Carry out sort operation against certain column * * @param columnIndex * the column based on which the sort operation would be carried * out * @param asc * the sort direction */ private void sort( final int columnIndex, final boolean asc ) { resultSetTable.setSortColumn( resultSetTable.getColumn( columnIndex ) ); resultSetTable.setSortDirection( asc == true ? SWT.DOWN : SWT.UP ); this.resultSetTableViewer.setSorter( new ViewerSorter( ) { // @Override public int compare( Viewer viewer, Object e1, Object e2 ) { CellValue cv1 = ( (CellValue[]) e1 )[columnIndex]; CellValue cv2 = ( (CellValue[]) e2 )[columnIndex]; int result = 0; if ( cv1 == null && cv1 != cv2 ) result = -1; else if ( cv1 != null ) result = cv1.compareTo( cv2 ); if ( !asc ) return result; else return result * -1; } } ); } /* * (non-Javadoc) * * @see org.eclipse.birt.model.core.Listener#elementChanged(org.eclipse.birt.model.api.DesignElementHandle, * org.eclipse.birt.model.activity.NotificationEvent) */ public void elementChanged( DesignElementHandle focus, NotificationEvent ev ) { if ( focus.equals( getContainer( ).getModel( ) ) || ( (DataSetEditor) this.getContainer( ) ).modelChanged( ) ) { modelChanged = true; } } /* * (non-Javadoc) * * @see org.eclipse.birt.report.designer.ui.dialogs.properties.IPropertyPage#performCancel() */ public boolean performCancel( ) { ( (DataSetHandle) getContainer( ).getModel( ) ).removeListener( this ); return super.performCancel( ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.designer.ui.dialogs.properties.IPropertyPage#performOk() */ public boolean performOk( ) { ( (DataSetHandle) getContainer( ).getModel( ) ).removeListener( this ); return super.performOk( ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.designer.ui.dialogs.properties.IPropertyPage#getToolTip() */ public String getToolTip( ) { return Messages.getString( "dataset.resultset.preview.tooltip" ); //$NON-NLS-1$ } private void resetPropertyBinding( final Map dataSetBindingMap, final Map dataSourceBindingMap ) { Display.getDefault( ).syncExec( new Runnable( ) { public void run( ) { try { DataSetHandle dsHandle = ( (DataSetEditor) getContainer( ) ).getHandle( ); DataSetMetaDataHelper.resetPropertyBinding( dsHandle, dataSetBindingMap, dataSourceBindingMap ); } catch ( SemanticException e ) { ExceptionHandler.handle( e ); } } } ); } private void clearProperyBindingMap( final Map dataSetBindingMap, final Map dataSourceBindingMap ) { Display.getDefault( ).syncExec( new Runnable( ) { public void run( ) { DataSetHandle dsHandle = ( (DataSetEditor) getContainer( ) ).getHandle( ); try { DataSetMetaDataHelper.clearPropertyBindingMap( dsHandle, dataSetBindingMap, dataSourceBindingMap ); } catch ( SemanticException e ) { ExceptionHandler.handle( e ); } } } ); } } /** * The Action factory */ final class ResultSetTableActionFactory { public static final int COPY_ACTION = 1; public static final int SELECTALL_ACTION = 2; public static ResultSetTableAction createResultSetTableAction( Table resultSetTable, int operationID ) { assert resultSetTable != null; ResultSetTableAction rsTableAction = null; if ( operationID == COPY_ACTION ) { rsTableAction = new CopyAction( resultSetTable ); } else if ( operationID == SELECTALL_ACTION ) { rsTableAction = new SelectAllAction( resultSetTable ); } return rsTableAction; } } /** * An implementation of Action */ abstract class ResultSetTableAction extends Action { protected Table resultSetTable = null; public ResultSetTableAction( Table resultSetTable, String actionName ) { super( actionName ); this.resultSetTable = resultSetTable; } /** * This method update the state of the action. Particularly, it will disable * the action under certain circumstance. */ public abstract void update( ); } /** * Copy action. */ final class CopyAction extends ResultSetTableAction { /** * @param resultSetTable * the ResultSetTable against which the action is applied to */ public CopyAction( Table resultSetTable ) { super( resultSetTable, Messages.getString( "CopyAction.text" ) ); //$NON-NLS-1$ this.setImageDescriptor( Utility.getImageDescriptor( ISharedImages.IMG_TOOL_COPY ) ); } /* * @see org.eclipse.jface.action.IAction#run() */ public void run( ) { StringBuffer textData = new StringBuffer( ); for ( int i = 0; i < resultSetTable.getColumnCount( ); i++ ) { textData.append( resultSetTable.getColumn( i ).getText( ) + "\t" ); //$NON-NLS-1$ } textData.append( "\n" ); //$NON-NLS-1$ TableItem[] tableItems = resultSetTable.getSelection( ); for ( int i = 0; i < tableItems.length; i++ ) { for ( int j = 0; j < resultSetTable.getColumnCount( ); j++ ) { textData.append( tableItems[i].getText( j ) + "\t" ); //$NON-NLS-1$ } textData.append( "\n" ); //$NON-NLS-1$ } Clipboard clipboard = new Clipboard( resultSetTable.getDisplay( ) ); clipboard.setContents( new Object[]{ textData.toString( ) }, new Transfer[]{ TextTransfer.getInstance( ) } ); clipboard.dispose( ); } /* * @see org.eclipse.birt.report.designer.internal.ui.dialogs.ResultSetTableAction#update() */ public void update( ) { if ( resultSetTable.getItems( ).length < 1 || resultSetTable.getSelectionCount( ) < 1 ) { this.setEnabled( false ); } } } /** * Select All Action */ final class SelectAllAction extends ResultSetTableAction { /** * @param resultSetTable * the ResultSetTable against which the action is applied to */ public SelectAllAction( Table resultSetTable ) { super( resultSetTable, Messages.getString( "SelectAllAction.text" ) ); //$NON-NLS-1$ } /* * @see org.eclipse.jface.action.IAction#run() */ public void run( ) { resultSetTable.selectAll( ); } /* * @see org.eclipse.birt.report.designer.internal.ui.dialogs.ResultSetTableAction#update() */ public void update( ) { if ( resultSetTable.getItems( ).length < 1 ) { this.setEnabled( false ); } } } final class CellValue implements Comparable { private Object realValue; private String displayValue; public int compareTo( Object o ) { if ( o == null ) { return 1; } CellValue other = (CellValue) o; try { return ScriptEvalUtil.compare( this.realValue, other.realValue); } catch ( DataException e ) { // should never get here assert ( false ); return -1; } } public String toString( ) { return displayValue == null ? "" : displayValue; //$NON-NLS-1$ } public void setRealValue( Object realValue ) { this.realValue = realValue; } public void setDisplayValue( String displayValue ) { this.displayValue = displayValue; } public String getDisplayValue( ) { return displayValue; } }
package com.stevex86.napper.request; import com.stevex86.napper.http.elements.content.BodyContent; import com.stevex86.napper.http.elements.content.QueryContent; import com.stevex86.napper.http.elements.header.Header; import com.stevex86.napper.http.elements.method.RequestMethod; import java.util.HashSet; import java.util.Set; public class Request { private RequestMethod requestMethod; private Set<Header> headers; private QueryContent queryContent; private BodyContent bodyContent; public Request(RequestMethod requestMethod) { this.requestMethod = requestMethod; this.headers = new HashSet<Header>(); } public void addHeader(Header header) { headers.add(header); } public void setQueryContent(QueryContent content) { queryContent = content; } public void setBodyContent(BodyContent content) { bodyContent = content; } public void addHeaders(Set<Header> headers) { this.headers.addAll(headers); } }
package com.thedarkfours.ldap; import com.thedarkfours.ldap.reflection.LdapAttributeParser; import com.thedarkfours.ldap.schema.LdapObject; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Hashtable; import javax.naming.Context; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.directory.Attribute; import javax.naming.directory.Attributes; import javax.naming.directory.InitialDirContext; import javax.naming.directory.SearchControls; import javax.naming.directory.SearchResult; /** * * @author rene */ public class LdapPersistor { private final String connectString; private final String baseDn; private final String userDn; private final String password; private InitialDirContext ctx; /** * * @param connectString * @param baseDn * @param userDn * @param password * @throws NamingException */ public LdapPersistor(String connectString, String baseDn, String userDn, String password) { this.connectString = connectString; this.baseDn = baseDn; this.userDn = userDn; this.password = password; } public void connect() throws NamingException { Hashtable<String, Object> env = new Hashtable<String, Object>(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, connectString + "/" + baseDn); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, userDn); env.put(Context.SECURITY_CREDENTIALS, password); env.put(Context.BATCHSIZE, "10000"); ctx = new InitialDirContext(env); } public <T extends LdapObject> T getByDn(String dn, Class<T> clazz) throws NamingException { NamingEnumeration<SearchResult> search = searchDn(dn, SearchControls.OBJECT_SCOPE); Collection<T> newInstance = extractAndInvoke(search, clazz, dn); if (newInstance.isEmpty()) { return null; } else if (newInstance.size() == 1) { for (T t : newInstance) { return t; } } throw new NamingException("No result found!"); } private NamingEnumeration<SearchResult> searchDn(String dn, int searchScope) throws NamingException { SearchControls sc = new SearchControls(); sc.setSearchScope(searchScope); sc.setCountLimit(10000L); sc.setReturningAttributes(new String[]{"*"}); sc.setReturningObjFlag(true); NamingEnumeration<SearchResult> search = ctx.search(dn, "(objectclass=*)", sc); return search; } public <T extends LdapObject> Collection<T> search(String dn, Class<T> clazz) throws NamingException, SecurityException { NamingEnumeration<SearchResult> search = searchDn(dn, SearchControls.SUBTREE_SCOPE); Collection<T> convertedObjects = extractAndInvoke(search, clazz, dn); return convertedObjects; } private <T extends LdapObject> Collection<T> extractAndInvoke(NamingEnumeration<SearchResult> search, Class<T> clazz, String dn) throws NamingException, SecurityException { Collection<String> objectClass = new ArrayList<String>(); Collection<HashMap<String, Object>> searchResults = processSearchResults(search, objectClass); LdapAttributeParser attributeParser = new LdapAttributeParser(); ArrayList<T> convertedObjects = new ArrayList<T>(); for (HashMap<String, Object> extractedAttributes : searchResults) { T newInstance = attributeParser.createNewInstance(extractedAttributes, clazz); newInstance.setDn(dn); newInstance.setObjectClass(objectClass); convertedObjects.add(newInstance); } return convertedObjects; } private Collection<HashMap<String, Object>> processSearchResults(NamingEnumeration<SearchResult> search, Collection<String> objectClass) throws NamingException { ArrayList<HashMap<String, Object>> searchResults = new ArrayList<HashMap<String, Object>>(); while (search.hasMore()) { HashMap<String, Object> attributeMap = extractAttributes(search, objectClass); searchResults.add(attributeMap); } return searchResults; } private HashMap<String, Object> extractAttributes(NamingEnumeration<SearchResult> search, Collection<String> objectClass) throws NamingException { HashMap<String, Object> attributeMap = new HashMap<String, Object>(); SearchResult next = search.next(); Attributes attributes = next.getAttributes(); NamingEnumeration<? extends Attribute> all = attributes.getAll(); while (all.hasMore()) { Attribute attribute = all.next(); String id = attribute.getID(); Object value = null; if (id.equals("objectClass")) { for (int i = 0; i < attribute.size(); i++) { objectClass.add((String) attribute.get(i)); } continue; } if (attribute.size() > 1) { Object[] attArray = new Object[attribute.size()]; for (int i = 0; i < attribute.size(); i++) { attArray[i] = attribute.get(i); } value = attArray; } else { value = attribute.get(); } attributeMap.put(id, value); } return attributeMap; } }
package org.csstudio.config.ioconfig.editorparts; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.csstudio.config.ioconfig.config.view.ChannelConfigDialog; import org.csstudio.config.ioconfig.config.view.ModuleListLabelProvider; import org.csstudio.config.ioconfig.config.view.helper.ConfigHelper; import org.csstudio.config.ioconfig.model.AbstractNodeDBO; import org.csstudio.config.ioconfig.model.PersistenceException; import org.csstudio.config.ioconfig.model.pbmodel.ChannelDBO; import org.csstudio.config.ioconfig.model.pbmodel.ChannelStructureDBO; import org.csstudio.config.ioconfig.model.pbmodel.GSDFileDBO; import org.csstudio.config.ioconfig.model.pbmodel.GSDModuleDBO; import org.csstudio.config.ioconfig.model.pbmodel.ModuleDBO; import org.csstudio.config.ioconfig.model.pbmodel.SlaveDBO; import org.csstudio.config.ioconfig.model.pbmodel.gsdParser.GsdModuleModel2; import org.csstudio.config.ioconfig.view.DeviceDatabaseErrorDialog; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.viewers.ComboViewer; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.jface.viewers.ViewerSorter; import org.eclipse.jface.window.Window; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.ScrolledComposite; import org.eclipse.swt.events.ControlAdapter; import org.eclipse.swt.events.ControlEvent; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.layout.RowLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Spinner; import org.eclipse.swt.widgets.Text; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ModuleEditor extends AbstractGsdNodeEditor<ModuleDBO> { public static final String ID = "org.csstudio.config.ioconfig.view.editor.module"; protected static final Logger LOG = LoggerFactory.getLogger(ModuleEditor.class); private final class FilterButtonSelectionListener implements SelectionListener { private final TableViewer _mTypList; /** * Constructor. */ public FilterButtonSelectionListener(@Nonnull final TableViewer moduleTypList) { _mTypList = moduleTypList; } @Override public void widgetDefaultSelected(@Nonnull final SelectionEvent e) { _mTypList.refresh(); } @Override public void widgetSelected(@Nonnull final SelectionEvent e) { _mTypList.refresh(); } } private final class EditButtonSelectionListener implements SelectionListener { private final TableViewer _mTypList; /** * Constructor. * @param moduleTypList */ public EditButtonSelectionListener(@Nonnull final TableViewer moduleTypList) { _mTypList = moduleTypList; } @Override public void widgetDefaultSelected(@Nonnull final SelectionEvent e) { editSelected(); } @Override public void widgetSelected(@Nonnull final SelectionEvent e) { editSelected(); } private void editSelected() { final GsdModuleModel2 firstElement = (GsdModuleModel2) ((StructuredSelection) _mTypList .getSelection()).getFirstElement(); GSDModuleDBO gsdModule = getNode().getGSDModule(); gsdModule = openChannelConfigDialog(firstElement, gsdModule); if(gsdModule != null) { final GSDFileDBO gsdFile = getNode().getGSDFile(); if(gsdFile != null) { gsdFile.addGSDModule(gsdModule); getProfiBusTreeView().refresh(getNode()); } } } } private final class FilterModifyListener implements ModifyListener { private final TableViewer _mTypList; /** * Constructor. * @param moduleTypList */ public FilterModifyListener(@Nonnull final TableViewer moduleTypList) { _mTypList = moduleTypList; } @Override public void modifyText(@Nonnull final ModifyEvent e) { _mTypList.refresh(); } } private final class ISelectionChangedListenerForModuleTypeList implements ISelectionChangedListener { private final Group _topGroup; private final TableViewer _mTypList; ISelectionChangedListenerForModuleTypeList(@Nonnull final Group topGroup, @Nonnull final TableViewer moduleTypList) { _topGroup = topGroup; _mTypList = moduleTypList; } @Override public void selectionChanged(@Nonnull final SelectionChangedEvent event) { final GsdModuleModel2 selectedModule = (GsdModuleModel2) ((StructuredSelection) _mTypList .getSelection()).getFirstElement(); if(ifSameModule(selectedModule)) { return; } final int selectedModuleNo = selectedModule.getModuleNumber(); final int savedModuleNo = (Integer) _mTypList.getTable().getData(); final boolean hasChanged = savedModuleNo != selectedModuleNo; final ModuleDBO module = getNode(); try { final String createdBy = getUserName(); GSDModuleDBO gsdModule; try { module.setNewModel(selectedModuleNo, createdBy); gsdModule = module.getGSDModule(); } catch (final IllegalArgumentException iea) { // Unknown Module (--> Config the Epics Part) gsdModule = createNewModulePrototype(selectedModule, selectedModuleNo, module); if(gsdModule==null) { return; } } final Text nameWidget = getNameWidget(); if(nameWidget != null) { nameWidget.setText(gsdModule.getName()); } } catch (final PersistenceException e1) { openErrorDialog(e1, getProfiBusTreeView()); LOG.error("Database error!", e1); } setSavebuttonEnabled("ModuleTyp", hasChanged); try { makeCurrentUserParamData(_topGroup); } catch (final IOException e) { LOG.error("File read error!", e); DeviceDatabaseErrorDialog.open(null, "File read error!", e); } getProfiBusTreeView().refresh(module.getParent()); } @CheckForNull public GSDModuleDBO createNewModulePrototype(@Nonnull final GsdModuleModel2 selectedModule, final int selectedModuleNo, @Nonnull final ModuleDBO module) throws PersistenceException { GSDModuleDBO gsdModule; gsdModule = openChannelConfigDialog(selectedModule, null); if(gsdModule == null) { return null; } gsdModule.setModuleId(selectedModuleNo); final GSDFileDBO gsdFile = module.getGSDFile(); if(gsdFile != null) { gsdFile.addGSDModule(gsdModule); } gsdModule.save(); return gsdModule; } private boolean ifSameModule(@Nullable final GsdModuleModel2 selectedModule) { final ModuleDBO module = getNode(); return ( (selectedModule == null) || (module == null) || ( (module .getGSDModule() != null) && (module.getGSDModule().getModuleId() == selectedModule .getModuleNumber()))); } } /** * This class provides the content for the table. */ public static class ComboContentProvider implements IStructuredContentProvider { /** * {@inheritDoc} */ @Override @SuppressWarnings("unchecked") @CheckForNull public final Object[] getElements(@Nullable final Object arg0) { if(arg0 instanceof Map) { final Map<Integer, GsdModuleModel2> map = (Map<Integer, GsdModuleModel2>) arg0; return map.values().toArray(new GsdModuleModel2[0]); } return null; } /** * {@inheritDoc} */ @Override public final void dispose() { // We don't create any resources, so we don't dispose any } /** * {@inheritDoc} */ @Override public final void inputChanged(@Nullable final Viewer arg0, @Nullable final Object arg1, @Nullable final Object arg2) { // do nothing } } /** * The Module Object. */ private ModuleDBO _module; /** * The List to choose the type of module. */ private TableViewer _moduleTypList; private final ArrayList<Object> _prmTextCV = new ArrayList<Object>(); private Group _currentUserParamDataGroup; private Text _ioNamesText; private Text _channelNameText; /** * {@inheritDoc} */ @Override public void createPartControl(@Nonnull final Composite parent) { _module = getNode(); super.createPartControl(parent); if(_module == null) { newNode(); _module.setModuleNumber(-1); } setSavebuttonEnabled(null, getNode().isPersistent()); ioNames("IO-Names"); moduels("Module"); selecttTabFolder(0); } /** * @param string */ private void ioNames(@Nonnull final String head) { final Composite comp = getNewTabItem(head, 2); comp.setLayout(new GridLayout(2, false)); _channelNameText = new Text(comp, SWT.MULTI | SWT.WRAP | SWT.BORDER | SWT.READ_ONLY); _channelNameText.setLayoutData(new GridData(SWT.BEGINNING, SWT.FILL, false, true)); _ioNamesText = new Text(comp, SWT.MULTI | SWT.WRAP | SWT.V_SCROLL | SWT.BORDER | SWT.READ_ONLY); _ioNamesText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); _channelNameText.addPaintListener(new PaintListener() { @Override public void paintControl(@Nonnull final PaintEvent e) { _ioNamesText.setTopIndex(_channelNameText.getTopIndex()); } }); _ioNamesText.addPaintListener(new PaintListener() { @Override public void paintControl(@Nonnull final PaintEvent e) { _channelNameText.setTopIndex(_ioNamesText.getTopIndex()); } }); try { setIONamesText(); } catch (final PersistenceException e) { DeviceDatabaseErrorDialog.open(null, "Can't read from Database", e); LOG.error("Can't read from Database", e); } } /** * @throws PersistenceException * */ private void setIONamesText() throws PersistenceException { final StringBuilder ioNamesSB = new StringBuilder(); final StringBuilder channelNamesSB = new StringBuilder(); final Set<Entry<Short, ChannelStructureDBO>> channelStructureEntrySet = getNode().getChildrenAsMap().entrySet(); for (Entry<Short, ChannelStructureDBO> channelStructureEntry : channelStructureEntrySet) { final Set<Entry<Short, ChannelDBO>> channelEntrySet = channelStructureEntry.getValue().getChildrenAsMap().entrySet(); for (Entry<Short, ChannelDBO> channelEntry : channelEntrySet) { String channelName = channelEntry.getValue().getName(); if (channelName==null) { channelName=""; } channelNamesSB.append(channelName); channelNamesSB.append("\n"); String ioName = channelEntry.getValue().getIoName(); if (ioName==null) { ioName=""; } ioNamesSB.append(ioName); ioNamesSB.append("\n"); } } _channelNameText.setText(channelNamesSB.toString()); _ioNamesText.setText(ioNamesSB.toString()); } /** * @param head * the tabItemName * */ private void moduels(@Nonnull final String head) { final Composite comp = getNewTabItem(head, 2); comp.setLayout(new GridLayout(2, false)); buildNameGroup(comp); final Group topGroup = new Group(comp, SWT.NONE); topGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, true, 1, 1)); topGroup.setLayout(new GridLayout(3, false)); topGroup.setText("Module selection"); makeDescGroup(comp, 1); final Text text = new Text(topGroup, SWT.SINGLE | SWT.LEAD | SWT.READ_ONLY | SWT.BORDER); text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 3, 1)); // TODO (hrickens) [02.05.2011]: Hier sollte bei jeder nderung der Werte Aktualisiert werden. (Momentan garnicht aber auch nicht nur beim Speichern) text.setText(_module.getConfigurationData()); final Composite filterComposite = buildFilterComposite(topGroup); final Text filter = buildFilterText(filterComposite); final Button filterButton = buildFilterButton(filterComposite); final Button epicsEditButton = buildEditButton(topGroup); buildModuleTypList(comp, topGroup, filter, filterButton); epicsEditButton.addSelectionListener(new EditButtonSelectionListener(_moduleTypList)); filterButton.addSelectionListener(new FilterButtonSelectionListener(_moduleTypList)); filter.addModifyListener(new FilterModifyListener(_moduleTypList)); } private void buildModuleTypList(@Nonnull final Composite comp, @Nonnull final Group topGroup, @Nonnull final Text filter, @Nonnull final Button filterButton) { _moduleTypList = new TableViewer(topGroup, SWT.SINGLE | SWT.V_SCROLL | SWT.BORDER); _moduleTypList.getTable().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 3)); _moduleTypList.setContentProvider(new ComboContentProvider()); _moduleTypList.setLabelProvider(new ModuleListLabelProvider(_moduleTypList.getTable())); setTypListFilter(filter, filterButton); setTypeListSorter(); try { makeCurrentUserParamData(topGroup); _moduleTypList .addSelectionChangedListener(new ISelectionChangedListenerForModuleTypeList(topGroup, _moduleTypList)); final GSDFileDBO gsdFile = getGsdFile(); if (gsdFile != null) { final Map<Integer, GsdModuleModel2> gsdModuleList = gsdFile.getParsedGsdFileModel() .getModuleMap(); _moduleTypList.setInput(gsdModuleList); comp.layout(); _moduleTypList.getTable().setData(_module.getModuleNumber()); final GsdModuleModel2 selectModuleModel = gsdModuleList.get(_module.getModuleNumber()); if (selectModuleModel != null) { _moduleTypList.setSelection(new StructuredSelection(selectModuleModel)); } } _moduleTypList.getTable().showSelection(); } catch (final IOException e2) { DeviceDatabaseErrorDialog.open(null, "Can't save Module. GSD File read error", e2); LOG.error("Can't save Module. GSD File read error", e2); } } @Nonnull private Text buildFilterText(@Nonnull final Composite filterComposite) { final Text filter = new Text(filterComposite, SWT.SINGLE | SWT.BORDER | SWT.SEARCH); filter.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1)); filter.setMessage("Module Filter"); return filter; } @Nonnull private Composite buildFilterComposite(@Nonnull final Group topGroup) { final Composite filterComposite = new Composite(topGroup, SWT.NONE); filterComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 2, 1)); final GridLayout layout = new GridLayout(2, false); layout.marginLeft = 0; layout.marginWidth = 0; layout.marginHeight = 0; layout.marginTop = 0; layout.marginBottom = 0; filterComposite.setLayout(layout); return filterComposite; } /** * @param filterComposite * @return */ @Nonnull private Button buildFilterButton(@Nonnull final Composite filterComposite) { final Button filterButton = new Button(filterComposite, SWT.CHECK); filterButton.setLayoutData(new GridData(SWT.CENTER, SWT.FILL, false, false, 1, 1)); filterButton.setText("Only have prototype"); return filterButton; } /** * @param topGroup */ @Nonnull private Button buildEditButton(@Nonnull final Group topGroup) { final Button epicsEditButton = new Button(topGroup, SWT.PUSH); epicsEditButton.setText("Edit Prototype"); return epicsEditButton; } private void setTypListFilter(@Nonnull final Text filter, @Nonnull final Button filterButton) { _moduleTypList.addFilter(new ViewerFilter() { @Override public boolean select(@Nullable final Viewer viewer, @Nullable final Object parentElement, @Nullable final Object element) { if(element instanceof GsdModuleModel2) { final GsdModuleModel2 gsdModuleModel = (GsdModuleModel2) element; if( (filter.getText() == null) || (filter.getText().length() < 1)) { return true; } final String filterString = ".*" + filter.getText().replaceAll("\\*", ".*") + ".*"; return gsdModuleModel.toString().matches(filterString); } return false; } }); _moduleTypList.addFilter(new ViewerFilter() { @Override public boolean select(@Nullable final Viewer viewer, @Nullable final Object parentElement, @Nullable final Object element) { if(filterButton.getSelection()) { if(element instanceof GsdModuleModel2) { final GsdModuleModel2 gmm = (GsdModuleModel2) element; final int selectedModuleNo = gmm.getModuleNumber(); final GSDFileDBO gsdFile = getGsdFile(); GSDModuleDBO module = null; if(gsdFile != null) { module = gsdFile.getGSDModule(selectedModuleNo); } return module != null; } } return true; } }); } private void setTypeListSorter() { _moduleTypList.setSorter(new ViewerSorter() { @Override public int compare(@Nullable final Viewer viewer, @Nullable final Object e1, @Nullable final Object e2) { if( (e1 instanceof GsdModuleModel2) && (e2 instanceof GsdModuleModel2)) { final GsdModuleModel2 eUPD1 = (GsdModuleModel2) e1; final GsdModuleModel2 eUPD2 = (GsdModuleModel2) e2; return eUPD1.getModuleNumber() - eUPD2.getModuleNumber(); } return super.compare(viewer, e1, e2); } }); } private void buildNameGroup(@Nonnull final Composite comp) { final Group gName = new Group(comp, SWT.NONE); gName.setText("Name"); gName.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1)); gName.setLayout(new GridLayout(3, false)); setNameWidget(new Text(gName, SWT.BORDER | SWT.SINGLE)); final Text nameWidget = getNameWidget(); if(nameWidget != null) { setText(nameWidget, _module.getName(), 255); nameWidget.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1)); } setIndexSpinner(ConfigHelper.getIndexSpinner(gName, _module, getMLSB(), "Sort Index", getProfiBusTreeView())); } /** * @param topGroup The parent Group for the CurrentUserParamData content. * @throws IOException */ protected void makeCurrentUserParamData(@Nonnull final Group topGroup) throws IOException { if(_currentUserParamDataGroup != null) { _currentUserParamDataGroup.dispose(); } // Current User Param Data Group _currentUserParamDataGroup = new Group(topGroup, SWT.NONE); final GridData gd = new GridData(SWT.FILL, SWT.FILL, false, true, 1, 3); _currentUserParamDataGroup.setLayoutData(gd); _currentUserParamDataGroup.setLayout(new FillLayout()); _currentUserParamDataGroup.setText("Current User Param Data:"); final ScrolledComposite scrollComposite = new ScrolledComposite(_currentUserParamDataGroup, SWT.V_SCROLL); final Composite currentUserParamDataComposite = new Composite(scrollComposite, SWT.NONE); final RowLayout rowLayout = new RowLayout(SWT.VERTICAL); rowLayout.wrap = false; rowLayout.fill = true; currentUserParamDataComposite.setLayout(rowLayout); scrollComposite.setContent(currentUserParamDataComposite); scrollComposite.setExpandHorizontal(true); scrollComposite.setExpandVertical(true); _currentUserParamDataGroup.addControlListener(new ControlAdapter() { @Override public void controlResized(@Nullable final ControlEvent e) { final Rectangle r = scrollComposite.getClientArea(); scrollComposite.setMinSize(scrollComposite.computeSize(r.width, SWT.DEFAULT)); } }); scrollComposite.addControlListener(new ControlAdapter() { @Override public void controlResized(@Nullable final ControlEvent e) { final Rectangle r = scrollComposite.getClientArea(); scrollComposite.setMinSize(currentUserParamDataComposite.computeSize(r.width, SWT.DEFAULT)); } }); buildCurrentUserPrmData(currentUserParamDataComposite); topGroup.layout(); } /** * {@inheritDoc} */ @Override public void doSave(@Nullable final IProgressMonitor monitor) { super.doSave(monitor); // Module final Text nameWidget = getNameWidget(); if(nameWidget != null) { _module.setName(nameWidget.getText()); nameWidget.setData(nameWidget.getText()); } final Spinner indexSpinner = getIndexSpinner(); if(indexSpinner != null) { indexSpinner.setData(indexSpinner.getSelection()); } try { updateChannels(); saveUserPrmData(); // Document if(getDocumentationManageView() != null) { _module.setDocuments(getDocumentationManageView().getDocuments()); } save(); } catch (final PersistenceException e) { LOG.error("Can't save Module! Database error.", e); DeviceDatabaseErrorDialog.open(null, "Can't save Module! Database error.", e); } catch (final IOException e2) { DeviceDatabaseErrorDialog.open(null, "Can't save Slave.GSD File read error", e2); LOG.error("Can't save Slave.GSD File read error", e2); } } private void updateChannels() throws PersistenceException { final Set<ChannelStructureDBO> channelStructs = _module.getChildren(); for (ChannelStructureDBO channelStructure : channelStructs) { final Set<ChannelDBO> channels = channelStructure.getChildren(); for (ChannelDBO channel : channels) { channel.assembleEpicsAddressString(); } } } /** * Cancel all change value. */ @Override public final void cancel() { super.cancel(); cancelNameWidget(); cancelIndexSpinner(); cancelGsdModuleModel(); for (Object prmTextObject : _prmTextCV) { if(prmTextObject instanceof ComboViewer) { cancelComboViewer(prmTextObject); } else if(prmTextObject instanceof Text) { cancelText(prmTextObject); } } save(); } public void cancelGsdModuleModel() { try { final GSDFileDBO gsdFile = _module.getGSDFile(); if (gsdFile != null) { final GsdModuleModel2 gsdModuleModel = gsdFile.getParsedGsdFileModel() .getModule((Integer) _moduleTypList .getTable().getData()); if (gsdModuleModel != null) { _moduleTypList.setSelection(new StructuredSelection(gsdModuleModel), true); } } } catch (final NullPointerException e) { _moduleTypList.getTable().select(0); } } public void cancelIndexSpinner() { final Spinner indexSpinner = getIndexSpinner(); if(indexSpinner != null) { indexSpinner.setSelection((Short) indexSpinner.getData()); } } public void cancelNameWidget() { final Text nameWidget = getNameWidget(); if(nameWidget != null) { nameWidget.setText((String) nameWidget.getData()); } } /** * @param prmTextObject */ public final void cancelComboViewer(@Nonnull final Object prmTextObject) { final ComboViewer prmTextCV = (ComboViewer) prmTextObject; if(!prmTextCV.getCombo().isDisposed()) { final Integer index = (Integer) prmTextCV.getCombo().getData(); if(index != null) { prmTextCV.getCombo().select(index); } } } /** * @param prmTextObject */ public final void cancelText(@Nonnull final Object prmTextObject) { final Text prmText = (Text) prmTextObject; if(!prmText.isDisposed()) { final String value = (String) prmText.getData(); if(value != null) { prmText.setText(value); } } } /** {@inheritDoc} */ @Override public final void fill(@Nullable final GSDFileDBO gsdFile) { return; } /** {@inheritDoc} */ @Override @CheckForNull public final GSDFileDBO getGsdFile() { return _module.getSlave().getGSDFile(); } /** * {@inheritDoc} * @throws IOException */ @Override public void setGsdFile(@CheckForNull final GSDFileDBO gsdFile) { _module.getSlave().setGSDFile(gsdFile); } /** * Open a Config-Dialog for {@link GSDModuleDBO} and create and store. * * @param model The {@link GsdModuleModel} Module Module from the GSD File. * @param gsdModule the {@link GSDModuleDBO} or null for a new one to configure . * @return the new or modified GSDModule or null when canceled. */ @CheckForNull protected GSDModuleDBO openChannelConfigDialog(@Nonnull final GsdModuleModel2 model, @CheckForNull final GSDModuleDBO gsdModuleDBO) { final GSDModuleDBO gsdModule = gsdModuleDBO == null ? new GSDModuleDBO(model.getName()) : gsdModuleDBO; if(_module != null) { gsdModule.setModuleId(_module.getModuleNumber()); if(_module.getGSDFile() != null) { gsdModule.setGSDFile(_module.getGSDFile()); } } final String createdBy = getUserName(); final Date date = new Date(); if(gsdModuleDBO==null) { gsdModule.setCreationData(createdBy, date); } else { gsdModule.setUpdatedBy(createdBy); gsdModule.setUpdatedOn(date); } final ChannelConfigDialog channelConfigDialog = new ChannelConfigDialog(Display.getCurrent() .getActiveShell(), model, gsdModule); if(channelConfigDialog.open() == Window.OK) { return gsdModule; } return null; } /** * Have no Name Dialog. * {@inheritDoc} */ @Override protected boolean newNode() { getNode().setCreationData(getUserName(), new Date()); getNode().setVersion(-2); final Object obj = ((StructuredSelection) getProfiBusTreeView().getTreeViewer().getSelection()) .getFirstElement(); try { if( obj == null) { getProfiBusTreeView().getTreeViewer().setInput(getNode()); } else if(obj instanceof SlaveDBO) { final SlaveDBO nodeParent = (SlaveDBO) obj; getNode().moveSortIndex(nodeParent.getfirstFreeStationAddress(AbstractNodeDBO.getMaxStationAddress())); nodeParent.addChild(getNode()); } } catch (final PersistenceException e) { LOG.error("Can't create new Module! Database error.", e); DeviceDatabaseErrorDialog.open(null, "Can't create new Module! Database error.", e); } return true; } /** * {@inheritDoc} */ @Override @CheckForNull GsdModuleModel2 getGsdPropertyModel() throws IOException { return _module.getGsdModuleModel2(); } /** * {@inheritDoc} */ @Override @Nonnull List<Integer> getPrmUserDataList() { return _module.getConfigurationDataList(); } /** * {@inheritDoc} */ @Override void setPrmUserData(@Nonnull final Integer index, @Nonnull final Integer value) { _module.setConfigurationDataByte(index, value); } /** * {@inheritDoc} */ @Override @CheckForNull Integer getPrmUserData(@Nonnull final Integer index) { if(_module.getConfigurationDataList().size() > index) { return _module.getConfigurationDataList().get(index); } return null; } }
package org.csstudio.dct.treemodelexporter; import static org.csstudio.utility.ldap.treeconfiguration.LdapEpicsAlarmcfgConfiguration.COMPONENT; import static org.csstudio.utility.ldap.treeconfiguration.LdapEpicsAlarmcfgConfiguration.FACILITY; import static org.csstudio.utility.ldap.treeconfiguration.LdapEpicsAlarmcfgConfiguration.RECORD; import static org.csstudio.utility.ldap.treeconfiguration.LdapEpicsAlarmcfgConfiguration.UNIT; import static org.csstudio.utility.ldap.treeconfiguration.LdapEpicsAlarmcfgConfiguration.VIRTUAL_ROOT; import java.util.ArrayList; import java.util.List; import javax.annotation.Nonnull; import javax.naming.InvalidNameException; import javax.naming.ldap.LdapName; import javax.naming.ldap.Rdn; import org.csstudio.dct.model.IContainer; import org.csstudio.dct.model.IProject; import org.csstudio.dct.model.IRecord; import org.csstudio.dct.util.AliasResolutionException; import org.csstudio.dct.util.AliasResolutionUtil; import org.csstudio.dct.util.ResolutionUtil; import org.csstudio.utility.ldap.treeconfiguration.LdapEpicsAlarmcfgConfiguration; import org.csstudio.utility.ldap.utils.LdapUtils; import org.csstudio.utility.treemodel.ContentModel; import org.csstudio.utility.treemodel.CreateContentModelException; import org.csstudio.utility.treemodel.ISubtreeNodeComponent; import org.csstudio.utility.treemodel.TreeNodeComponent; import org.csstudio.utility.treemodel.builder.AbstractContentModelBuilder; /** * Build content model from dct export. * * @author jhatje * @author $Author$ * @version $Revision$ * @since 22.06.2010 */ public class DctContentModelBuilder extends AbstractContentModelBuilder<LdapEpicsAlarmcfgConfiguration> { private final IProject _dctPoject; /** * Constructor. */ public DctContentModelBuilder(@Nonnull final IProject dctPoject) { _dctPoject = dctPoject; } /** * {@inheritDoc} */ @Override protected ContentModel<LdapEpicsAlarmcfgConfiguration> createContentModel() throws CreateContentModelException { ContentModel<LdapEpicsAlarmcfgConfiguration> contentModel = null; try { contentModel = new ContentModel<LdapEpicsAlarmcfgConfiguration>( VIRTUAL_ROOT); } catch (final InvalidNameException e) { throw new CreateContentModelException(e.getMessage(), e); } try { ISubtreeNodeComponent<LdapEpicsAlarmcfgConfiguration> unit = addUnit( contentModel, "EpicsAlarmcfg"); addFacility(contentModel, _dctPoject.getName(), unit); } catch (final InvalidNameException e) { throw new CreateContentModelException(e.getMessage(), e); } for (final IRecord record : _dctPoject.getFinalRecords()) { final List<String> prototypeInstances = new ArrayList<String>(); getParentPrototypeInstances(record.getContainer(), prototypeInstances); try { addToContentModel(contentModel, prototypeInstances, record); } catch (final InvalidNameException e) { throw new CreateContentModelException(e.getMessage(), e); } catch (final AliasResolutionException e) { throw new CreateContentModelException(e.getMessage(), e); } } return contentModel; } /** * Add record with its parent prototype instances (components in LDAP) to * content model. * * @param contentModel * @param prototypeInstances * @param record * @throws InvalidNameException * @throws AliasResolutionException */ private void addToContentModel( @Nonnull final ContentModel<LdapEpicsAlarmcfgConfiguration> contentModel, @Nonnull final List<String> prototypeInstances, @Nonnull final IRecord record) throws InvalidNameException, AliasResolutionException { final String ldapName = LdapUtils.createLdapName( FACILITY.getNodeTypeName(), _dctPoject.getName(), UNIT.getNodeTypeName(), _dctPoject.getName()).toString(); ISubtreeNodeComponent<LdapEpicsAlarmcfgConfiguration> parent = contentModel .getChildByLdapName(ldapName); ISubtreeNodeComponent<LdapEpicsAlarmcfgConfiguration> newChild; for (final String instance : prototypeInstances) { newChild = null; final LdapName parentName = new LdapName(parent.getLdapName() .getRdns()); parentName.add(new Rdn(COMPONENT.getNodeTypeName(), instance)); newChild = contentModel.getChildByLdapName(parentName.toString()); if (newChild == null) { newChild = new TreeNodeComponent<LdapEpicsAlarmcfgConfiguration>( instance, COMPONENT, parent, null, parentName); contentModel.addChild(parent, newChild); } parent = newChild; } final String epicsName = ResolutionUtil.resolve( AliasResolutionUtil.getEpicsNameFromHierarchy(record), record); final LdapName parentName = new LdapName(parent.getLdapName().getRdns()); parentName.add(new Rdn(RECORD.getNodeTypeName(), epicsName)); newChild = new TreeNodeComponent<LdapEpicsAlarmcfgConfiguration>( epicsName, RECORD, parent, null, parentName); contentModel.addChild(parent, newChild); } /** * Add unit to content model * * @param contentModel * @param projectName * @return * @throws InvalidNameException */ private ISubtreeNodeComponent<LdapEpicsAlarmcfgConfiguration> addUnit( @Nonnull final ContentModel<LdapEpicsAlarmcfgConfiguration> contentModel, @Nonnull final String projectName) throws InvalidNameException { // LdapNameUtils. final LdapName ldapName = new LdapName(new Rdn(UNIT.getNodeTypeName(), _dctPoject.getName()).toString()); ldapName.add(new Rdn(UNIT.getNodeTypeName(), _dctPoject.getName())); final ISubtreeNodeComponent<LdapEpicsAlarmcfgConfiguration> parent = contentModel .getVirtualRoot(); ISubtreeNodeComponent<LdapEpicsAlarmcfgConfiguration> newChild; newChild = new TreeNodeComponent<LdapEpicsAlarmcfgConfiguration>( projectName, UNIT, parent, null, ldapName); contentModel.addChild(parent, newChild); return newChild; } /** * Add dct project name as facility to content model * * @param contentModel * @param projectName * @param unit * @throws InvalidNameException */ private void addFacility( @Nonnull final ContentModel<LdapEpicsAlarmcfgConfiguration> contentModel, @Nonnull final String projectName, ISubtreeNodeComponent<LdapEpicsAlarmcfgConfiguration> parent) throws InvalidNameException { final LdapName ldapName = LdapUtils.createLdapName( UNIT.getNodeTypeName(), _dctPoject.getName()); ldapName.add(new Rdn(FACILITY.getNodeTypeName(), _dctPoject.getName())); ISubtreeNodeComponent<LdapEpicsAlarmcfgConfiguration> newChild; newChild = new TreeNodeComponent<LdapEpicsAlarmcfgConfiguration>( projectName, FACILITY, parent, null, ldapName); contentModel.addChild(parent, newChild); } /** * @param container * Container of record * @return List of nested prototype instances starting with root */ private void getParentPrototypeInstances( @Nonnull final IContainer container, @Nonnull final List<String> instances) { final String name = AliasResolutionUtil.getNameFromHierarchy(container); instances.add(0, name); if (container.getContainer() != null) { getParentPrototypeInstances(container.getContainer(), instances); } } }
package org.innovateuk.ifs.cofunder.transactional; import org.innovateuk.ifs.cofunder.domain.CofunderAssignment; import org.innovateuk.ifs.cofunder.domain.CofunderOutcome; import org.innovateuk.ifs.cofunder.mapper.CofunderAssignmentMapper; import org.innovateuk.ifs.cofunder.repository.CofunderAssignmentRepository; import org.innovateuk.ifs.cofunder.resource.*; import org.innovateuk.ifs.cofunder.workflow.CofunderAssignmentWorkflowHandler; import org.innovateuk.ifs.commons.exception.ObjectNotFoundException; import org.innovateuk.ifs.commons.service.ServiceResult; import org.innovateuk.ifs.organisation.domain.SimpleOrganisation; import org.innovateuk.ifs.profile.domain.Profile; import org.innovateuk.ifs.profile.repository.ProfileRepository; import org.innovateuk.ifs.transactional.BaseTransactionalService; import org.innovateuk.ifs.user.domain.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; import static java.util.Optional.ofNullable; import static java.util.stream.Collectors.toList; import static org.innovateuk.ifs.commons.error.CommonErrors.notFoundError; import static org.innovateuk.ifs.commons.error.CommonFailureKeys.*; import static org.innovateuk.ifs.commons.service.ServiceResult.serviceFailure; import static org.innovateuk.ifs.commons.service.ServiceResult.serviceSuccess; import static org.innovateuk.ifs.util.CollectionFunctions.simpleMap; import static org.innovateuk.ifs.util.EntityLookupCallbacks.find; @Service public class CofunderAssignmentServiceImpl extends BaseTransactionalService implements CofunderAssignmentService { @Autowired private CofunderAssignmentWorkflowHandler cofunderAssignmentWorkflowHandler; @Autowired private CofunderAssignmentRepository cofunderAssignmentRepository; @Autowired private ProfileRepository profileRepository; @Autowired private CofunderAssignmentMapper mapper; @Override public ServiceResult<CofunderAssignmentResource> getAssignment(long userId, long applicationId) { return findCofunderAssignmentByUserAndApplication(userId, applicationId) .andOnSuccessReturn(mapper::mapToResource); } @Override public ServiceResult<List<CofunderAssignmentResource>> getAssignmentsByApplicationId(long applicationId) { return findCofunderAssignmentsByApplicationId(applicationId) .andOnSuccessReturn(assignments -> simpleMap(assignments,mapper::mapToResource)); } @Override @Transactional public ServiceResult<CofunderAssignmentResource> assign(long userId, long applicationId) { boolean exists = cofunderAssignmentRepository.existsByParticipantIdAndTargetId(userId, applicationId); if (exists) { return serviceFailure(COFUNDER_ASSIGNMENT_ALREADY_EXISTS); } return find(application(applicationId), user(userId)).andOnSuccess( (application, user) -> { if (application.getCompetition().isAssessmentClosed()) { return serviceFailure(COFUNDER_AFTER_ASSESSMENT_CLOSE); } return serviceSuccess(mapper.mapToResource(cofunderAssignmentRepository.save(new CofunderAssignment(application, user)))); } ); } @Override @Transactional public ServiceResult<Void> removeAssignment(long userId, long applicationId) { return findCofunderAssignmentByUserAndApplication(userId, applicationId).andOnSuccess(assignment -> { if (assignment.getTarget().getCompetition().isAssessmentClosed()) { return serviceFailure(COFUNDER_AFTER_ASSESSMENT_CLOSE); } cofunderAssignmentRepository.delete(assignment); return serviceSuccess(); } ); } @Override @Transactional public ServiceResult<Void> decision(long assignmentId, CofunderDecisionResource decision) { return findCofunderAssignmentById(assignmentId).andOnSuccess(assignment -> { if (assignment.getTarget().getCompetition().isAssessmentClosed()) { return serviceFailure(COFUNDER_AFTER_ASSESSMENT_CLOSE); } CofunderOutcome outcome = new CofunderOutcome(decision.isAccept(), decision.getComments()); boolean success; if (decision.isAccept()) { success = cofunderAssignmentWorkflowHandler.accept(assignment, outcome); } else { success = cofunderAssignmentWorkflowHandler.reject(assignment, outcome); } if (!success) { return serviceFailure(COFUNDER_WORKFLOW_TRANSITION_FAILURE); } return serviceSuccess(); } ); } @Override @Transactional public ServiceResult<Void> edit(long assignmentId) { return findCofunderAssignmentById(assignmentId).andOnSuccess(assignment -> { if (assignment.getTarget().getCompetition().isAssessmentClosed()) { return serviceFailure(COFUNDER_AFTER_ASSESSMENT_CLOSE); } boolean success = cofunderAssignmentWorkflowHandler.edit(assignment); if (!success) { return serviceFailure(COFUNDER_WORKFLOW_TRANSITION_FAILURE); } assignment.setCofunderOutcome(null); return serviceSuccess(); } ); } @Override public ServiceResult<ApplicationsForCofundingPageResource> findApplicationsNeedingCofunders(long competitionId, String filter, Pageable pageable) { Page<ApplicationsForCofundingResource> result = cofunderAssignmentRepository.findApplicationsForCofunding(competitionId, filter, pageable); return serviceSuccess(new ApplicationsForCofundingPageResource( result.getTotalElements(), result.getTotalPages(), result.getContent(), result.getNumber(), result.getSize()) ); } @Override public ServiceResult<CofundersAvailableForApplicationPageResource> findAvailableCofundersForApplication(long applicationId, String filter, Pageable pageable) { Page<User> result = cofunderAssignmentRepository.findUsersAvailableForCofunding(applicationId, filter, pageable); List<CofunderAssignment> assignments = cofunderAssignmentRepository.findByTargetId(applicationId); return serviceSuccess(new CofundersAvailableForApplicationPageResource( result.getTotalElements(), result.getTotalPages(), result.getContent().stream().map(this::mapToCofunderUser).collect(toList()), result.getNumber(), result.getSize(), assignments.stream().map(CofunderAssignment::getParticipant).map(this::mapToCofunderUser).collect(toList())) ); } private CofunderUserResource mapToCofunderUser(User user) { CofunderUserResource cofunderUser = new CofunderUserResource(); Profile profile = profileRepository.findById(user.getProfileId()).orElseThrow(ObjectNotFoundException::new); cofunderUser.setUserId(user.getId()); cofunderUser.setEmail(user.getEmail()); cofunderUser.setName(user.getFirstName() + " " + user.getLastName()); cofunderUser.setOrganisation(ofNullable(profile.getSimpleOrganisation()).map(SimpleOrganisation::getName).orElse(null)); return cofunderUser; } private ServiceResult<CofunderAssignment> findCofunderAssignmentByUserAndApplication(long userId, long applicationId) { return find(cofunderAssignmentRepository.findByParticipantIdAndTargetId(userId, applicationId), notFoundError(CofunderAssignment.class, userId, applicationId)); } private ServiceResult<List<CofunderAssignment>> findCofunderAssignmentsByApplicationId(long applicationId) { return find(cofunderAssignmentRepository.findByTargetId(applicationId), notFoundError(CofunderAssignment.class, applicationId)); } private ServiceResult<CofunderAssignment> findCofunderAssignmentById(long assignmentId) { return find(cofunderAssignmentRepository.findById(assignmentId), notFoundError(CofunderAssignment.class, assignmentId)); } }
package org.inheritsource.service.delegates; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.Properties; import java.util.Set; import java.util.logging.Logger; import java.util.regex.Pattern; import javax.mail.Message; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import org.activiti.engine.delegate.DelegateTask; import org.activiti.engine.delegate.TaskListener; import org.activiti.engine.task.IdentityLink; import org.inheritsource.service.common.domain.UserDirectoryEntry; import org.inheritsource.service.common.util.ConfigUtil; import org.inheritsource.service.identity.UserDirectoryService; public class TaskMessageListener implements TaskListener { private static final long serialVersionUID = -1141071604517769171L; public static final Logger log = Logger .getLogger(SimplifiedServiceMessageDelegate.class.getName()); public static String PROC_VAR_RECIPIENT_USER_ID = "recipientUserId"; public static String PROC_VAR_SERVICE_DOC_URI = "serviceDocUri"; public static String ACT_VAR_MESSAGE_TEXT = "emailMessageText"; public static String ACT_VAR_SUBJECT = "emailSubject"; public void notify(DelegateTask execution) { log.info("SimplifiedServiceMessageDelegate called from " + execution.getProcessInstanceId() + " at " + new Date()); Boolean isPublic = false; // NOTE Properties props = ConfigUtil.getConfigProperties(); String messageText = (String) props.get("mail.text.messageTaskText"); String siteUri = (String) props.get("site.base.uri"); String SMTPSERVER = (String) props.get("mail.smtp.host"); String from = (String) props.get("mail.text.from"); String to = "none@nowhere.com"; String inbox = (String) props.get("site.base.intranet"); if (messageText == null || messageText.trim().length() == 0) { messageText = "Du har ett ärende i din inkorg "; } String taskName = execution.getName(); messageText = messageText + "( " + taskName + " ) \n"; if ((siteUri != null) && (inbox != null)) { messageText = messageText + " " + siteUri + "/" + inbox; } String messageSubject = (String) props .get("mail.text.messageTaskSubject"); if (messageSubject == null || messageSubject.trim().length() == 0) { messageSubject = "Nytt ärende"; } // log.info("Email to: " + recipientUserId); if (isPublic) { log.severe("public not implemented "); } else { inbox = (String) props.get("site.base.intranet"); // read info for task UserDirectoryService userDirectoryService = new UserDirectoryService(); String assignee = execution.getAssignee(); ArrayList<UserDirectoryEntry> userDirectoryEntries = new ArrayList<UserDirectoryEntry>(); if (assignee != null) { // send mail to Assignee log.info("sending email to assignee"); String[] userIds = { assignee }; userDirectoryEntries.addAll(userDirectoryService .lookupUserEntries(userIds)); for (UserDirectoryEntry user : userDirectoryEntries) { to = user.getMail(); if (to != null) { sendEmail(to, from, messageSubject, messageText, siteUri, inbox, SMTPSERVER); } } } else { // go through list and send mail to all candidates Set<IdentityLink> identityLinks = execution.getCandidates(); if (identityLinks == null) { log.severe("no candidates found"); return; } else { for (IdentityLink identityLink : identityLinks) { String groupId = identityLink.getGroupId(); if (groupId != null) { log.info("looking up group " + groupId); try { ArrayList<UserDirectoryEntry> userDirectoryEntry = userDirectoryService .lookupUserEntriesByGroup(groupId); if (userDirectoryEntry != null) { userDirectoryEntries .addAll(userDirectoryEntry); log.info("add1 :" + userDirectoryEntries.toString()); } } catch (Exception e) { log.severe(e.toString()); } } else { String userId = identityLink.getUserId(); String[] userIds = { userId }; if (userId != null) { log.info("looking up userId " + userId); try { ArrayList<UserDirectoryEntry> userDirectoryEntry = userDirectoryService .lookupUserEntries(userIds); if (userDirectoryEntry != null) { userDirectoryEntries .addAll(userDirectoryEntry); log.info("add2 :" + userDirectoryEntries .toString()); } } catch (Exception e) { log.severe(e.toString()); } } } } } // make unique if (userDirectoryEntries.isEmpty()) { log.severe("No candidates found "); return; } else { HashSet<UserDirectoryEntry> users = new HashSet<UserDirectoryEntry>(); users.addAll(userDirectoryEntries); log.info("add3 :" + users.toString()); for (UserDirectoryEntry user : users) { to = user.getMail(); if (to != null) { sendEmail(to, from, messageSubject, messageText, siteUri, inbox, SMTPSERVER); } } } } } return; } private void sendEmail(String to, String from, String messageSubject, String messageText, String siteUri, String inbox, String SMTPSERVER) { log.info("to: " + to); // check email address // might like to replace this with EmailValidator from apache.commons if (!rfc2822.matcher(to).matches()) { log.severe("Invalid address"); return; } log.info("siteUri:" + siteUri); log.info("inbox:" + inbox); log.info("SMTPSERVER:" + SMTPSERVER); log.info("Email subject: " + messageSubject); log.info("Email text: " + messageText); // Setup mail server Properties mailprops = new Properties(); mailprops.setProperty("mail.smtp.host", SMTPSERVER); try { Session session = Session.getInstance(mailprops); // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from.replaceAll("\\+", " "))); message.addRecipient(Message.RecipientType.TO, new InternetAddress( to)); message.setSubject(messageSubject.replaceAll("\\+", " ")); message.setText(messageText.replaceAll("\\+", " ")); // Send message log.info("EmailToInitiator: Sending message to " + to + " via smtpserver: " + SMTPSERVER); log.info((String) message.getContent()); Transport.send(message); } catch (Exception e) { e.printStackTrace(); } return; } private static final Pattern rfc2822 = Pattern .compile("^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$"); }
package com.konkerlabs.platform.registry.business.services; import com.konkerlabs.platform.registry.business.model.Application; import com.konkerlabs.platform.registry.business.model.Device; import com.konkerlabs.platform.registry.business.model.DeviceModel; import com.konkerlabs.platform.registry.business.model.Tenant; import com.konkerlabs.platform.registry.business.model.validation.CommonValidations; import com.konkerlabs.platform.registry.business.repositories.ApplicationRepository; import com.konkerlabs.platform.registry.business.repositories.DeviceModelRepository; import com.konkerlabs.platform.registry.business.repositories.DeviceRepository; import com.konkerlabs.platform.registry.business.repositories.TenantRepository; import com.konkerlabs.platform.registry.business.services.api.ApplicationService; import com.konkerlabs.platform.registry.business.services.api.DeviceModelService; import com.konkerlabs.platform.registry.business.services.api.ServiceResponse; import com.konkerlabs.platform.registry.business.services.api.ServiceResponseBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.Scope; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; @Service @Scope(BeanDefinition.SCOPE_PROTOTYPE) public class DeviceModelServiceImpl implements DeviceModelService { private Logger LOGGER = LoggerFactory.getLogger(DeviceModelServiceImpl.class); @Autowired private ApplicationRepository applicationRepository; @Autowired private TenantRepository tenantRepository; @Autowired private DeviceModelRepository deviceModelRepository; @Autowired private DeviceRepository deviceRepository; private ServiceResponse<DeviceModel> basicValidate(Tenant tenant, Application application, DeviceModel deviceModel) { if (!Optional.ofNullable(tenant).isPresent()) { Application app = Application.builder() .name("NULL") .tenant(Tenant.builder().domainName("unknown_domain").build()) .build(); if(LOGGER.isDebugEnabled()){ LOGGER.debug(CommonValidations.TENANT_NULL.getCode(), app.toURI(), app.getTenant().getLogLevel()); } return ServiceResponseBuilder.<DeviceModel>error() .withMessage(CommonValidations.TENANT_NULL.getCode()) .build(); } if (!tenantRepository.exists(tenant.getId())) { LOGGER.debug("device cannot exists", Application.builder().name("NULL").tenant(tenant).build().toURI(), tenant.getLogLevel()); return ServiceResponseBuilder.<DeviceModel>error() .withMessage(CommonValidations.TENANT_DOES_NOT_EXIST.getCode()) .build(); } if (!Optional.ofNullable(application).isPresent()) { Application app = Application.builder() .name("NULL") .tenant(tenant) .build(); if(LOGGER.isDebugEnabled()){ LOGGER.debug(ApplicationService.Validations.APPLICATION_NULL.getCode(), app.toURI(), app.getTenant().getLogLevel()); } return ServiceResponseBuilder.<DeviceModel>error() .withMessage(ApplicationService.Validations.APPLICATION_NULL.getCode()) .build(); } if (!applicationRepository.exists(application.getName())) { Application app = Application.builder() .name("NULL") .tenant(tenant) .build(); if(LOGGER.isDebugEnabled()){ LOGGER.debug(ApplicationService.Validations.APPLICATION_DOES_NOT_EXIST.getCode(), app.toURI(), app.getTenant().getLogLevel()); } return ServiceResponseBuilder.<DeviceModel>error() .withMessage(ApplicationService.Validations.APPLICATION_DOES_NOT_EXIST.getCode()) .build(); } if (!Optional.ofNullable(deviceModel).isPresent()) { DeviceModel app = DeviceModel.builder() .guid("NULL") .tenant(tenant) .build(); if(LOGGER.isDebugEnabled()){ LOGGER.debug(Validations.DEVICE_MODEL_NULL.getCode(), app.toURI(), app.getTenant().getLogLevel()); } return ServiceResponseBuilder.<DeviceModel>error() .withMessage(Validations.DEVICE_MODEL_NULL.getCode()) .build(); } return null; } @Override public ServiceResponse<DeviceModel> register(Tenant tenant, Application application, DeviceModel deviceModel) { ServiceResponse<DeviceModel> response = basicValidate(tenant, application, deviceModel); if (Optional.ofNullable(response).isPresent()) return response; Optional<Map<String,Object[]>> validations = deviceModel.applyValidations(); if (validations.isPresent()) { LOGGER.debug("error saving device model", DeviceModel.builder().guid("NULL").tenant(tenant).build().toURI(), tenant.getLogLevel()); return ServiceResponseBuilder.<DeviceModel>error() .withMessages(validations.get()) .build(); } if (deviceModelRepository .findByTenantIdApplicationNameAndName(tenant.getId(), application.getName(), deviceModel.getName()) != null) { LOGGER.debug("error saving device model", DeviceModel.builder().guid("NULL").tenant(tenant).build().toURI(), tenant.getLogLevel()); return ServiceResponseBuilder.<DeviceModel>error() .withMessage(Validations.DEVICE_MODEL_ALREADY_REGISTERED.getCode()) .build(); } if (deviceModel.isDefaultModel()) { DeviceModel defaultModel = deviceModelRepository.findDefault(tenant.getId(), application.getName(), true); Optional.ofNullable(defaultModel).ifPresent(def -> { def.setDefaultModel(false); deviceModelRepository.save(def); }); } List<DeviceModel> allModels = deviceModelRepository.findAllByTenantIdAndApplicationName(tenant.getId(), application.getName()); if (allModels.isEmpty()) { deviceModel.setDefaultModel(true); } deviceModel.setTenant(tenant); deviceModel.setApplication(application); deviceModel.setGuid(UUID.randomUUID().toString()); DeviceModel save = deviceModelRepository.save(deviceModel); LOGGER.info("DeviceModel created. Name: {}", save.getName(), tenant.toURI(), tenant.getLogLevel()); return ServiceResponseBuilder.<DeviceModel>ok().withResult(save).build(); } @Override public ServiceResponse<DeviceModel> update(Tenant tenant, Application application, String name, DeviceModel updatingDeviceModel) { ServiceResponse<DeviceModel> response = basicValidate(tenant, application, updatingDeviceModel); if (Optional.ofNullable(response).isPresent()) return response; if (!Optional.ofNullable(name).isPresent()) return ServiceResponseBuilder.<DeviceModel>error() .withMessage(Validations.DEVICE_MODEL_NAME_IS_NULL.getCode()) .build(); DeviceModel devModelFromDB = getByTenantApplicationAndName(tenant, application, name).getResult(); if (!Optional.ofNullable(devModelFromDB).isPresent()) { return ServiceResponseBuilder.<DeviceModel>error() .withMessage(Validations.DEVICE_MODEL_DOES_NOT_EXIST.getCode()) .build(); } if (devModelFromDB.isDefaultModel()) { return ServiceResponseBuilder.<DeviceModel>error() .withMessage(Validations.DEVICE_MODEL_NOT_UPDATED_IS_DEFAULT.getCode()) .build(); } if (!devModelFromDB.getName().equals(updatingDeviceModel.getName()) && deviceModelRepository .findByTenantIdApplicationNameAndName(tenant.getId(), application.getName(), updatingDeviceModel.getName()) != null) { LOGGER.debug("error saving device model", DeviceModel.builder().guid("NULL").tenant(tenant).build().toURI(), tenant.getLogLevel()); return ServiceResponseBuilder.<DeviceModel>error() .withMessage(Validations.DEVICE_MODEL_ALREADY_REGISTERED.getCode()) .build(); } devModelFromDB.setName(updatingDeviceModel.getName()); devModelFromDB.setDescription(updatingDeviceModel.getDescription()); devModelFromDB.setContentType(updatingDeviceModel.getContentType()); devModelFromDB.setDefaultModel(updatingDeviceModel.isDefaultModel()); Optional<Map<String, Object[]>> validations = devModelFromDB.applyValidations(); if (validations.isPresent()) { return ServiceResponseBuilder.<DeviceModel>error() .withMessages(validations.get()) .build(); } if (devModelFromDB.isDefaultModel()) { DeviceModel defaultModel = deviceModelRepository.findDefault(tenant.getId(), application.getName(), true); defaultModel.setDefaultModel(false); deviceModelRepository.save(defaultModel); } DeviceModel updated = deviceModelRepository.save(devModelFromDB); LOGGER.info("DeviceModel updated. Name: {}", devModelFromDB.getName(), tenant.toURI(), tenant.getLogLevel()); return ServiceResponseBuilder.<DeviceModel>ok().withResult(updated).build(); } @Override public ServiceResponse<DeviceModel> remove(Tenant tenant, Application application, String name) { if (!Optional.ofNullable(tenant).isPresent()) { return ServiceResponseBuilder.<DeviceModel>error() .withMessage(CommonValidations.TENANT_NULL.getCode()) .build(); } if (!Optional.ofNullable(application).isPresent()) { return ServiceResponseBuilder.<DeviceModel>error() .withMessage(ApplicationService.Validations.APPLICATION_NULL.getCode()) .build(); } if (!Optional.ofNullable(name).isPresent()) { return ServiceResponseBuilder.<DeviceModel>error() .withMessage(Validations.DEVICE_MODEL_NAME_IS_NULL.getCode()) .build(); } DeviceModel deviceModel = deviceModelRepository.findByTenantIdApplicationNameAndName(tenant.getId(), application.getName(), name); if (!Optional.ofNullable(deviceModel).isPresent()) { return ServiceResponseBuilder.<DeviceModel>error() .withMessage(Validations.DEVICE_MODEL_DOES_NOT_EXIST.getCode()) .build(); } if (deviceModel.isDefaultModel()) { return ServiceResponseBuilder.<DeviceModel>error() .withMessage(Validations.DEVICE_MODEL_NOT_REMOVED_IS_DEFAULT.getCode()) .build(); } List<Device> devices = deviceRepository.findAllByTenantIdApplicationNameAndDeviceModel(tenant.getId(), application.getName(), deviceModel.getId()); if (!devices.isEmpty()) { return ServiceResponseBuilder.<DeviceModel>error() .withMessage(Validations.DEVICE_MODEL_HAS_DEVICE.getCode()) .build(); } deviceModelRepository.delete(deviceModel); return ServiceResponseBuilder.<DeviceModel>ok() .withMessage(Messages.DEVICE_MODEL_REMOVED_SUCCESSFULLY.getCode()) .withResult(deviceModel) .build(); } @Override public ServiceResponse<List<DeviceModel>> findAll(Tenant tenant, Application application) { List<DeviceModel> all = deviceModelRepository.findAllByTenantIdAndApplicationName(tenant.getId(), application.getName()); if (all.isEmpty()) { ServiceResponse<DeviceModel> defaultResponse = findDefault(tenant, application); if (defaultResponse.isOk()) { all.add(defaultResponse.getResult()); } } return ServiceResponseBuilder.<List<DeviceModel>>ok().withResult(all).build(); } @Override public ServiceResponse<Page<DeviceModel>> findAll(Tenant tenant, Application application, int page, int size) { page = page > 0 ? page - 1 : 0; if (size <= 0) { return ServiceResponseBuilder.<Page<DeviceModel>>error() .withMessage(CommonValidations.SIZE_ELEMENT_PAGE_INVALID.getCode()) .build(); } Page<DeviceModel> all = deviceModelRepository.findAllByTenantIdAndApplicationName(tenant.getId(), application.getName(), new PageRequest(page, size)); return ServiceResponseBuilder.<Page<DeviceModel>>ok().withResult(all).build(); } @Override public ServiceResponse<DeviceModel> getByTenantApplicationAndName(Tenant tenant, Application application, String name) { if (!Optional.ofNullable(tenant).isPresent()) { return ServiceResponseBuilder.<DeviceModel>error() .withMessage(CommonValidations.TENANT_NULL.getCode()) .build(); } if (!Optional.ofNullable(application).isPresent()) { return ServiceResponseBuilder.<DeviceModel>error() .withMessage(ApplicationService.Validations.APPLICATION_NULL.getCode()) .build(); } if (!Optional.ofNullable(name).isPresent()) { return ServiceResponseBuilder.<DeviceModel>error() .withMessage(Validations.DEVICE_MODEL_NAME_IS_NULL.getCode()) .build(); } Tenant tenantFromDB = tenantRepository.findByDomainName(tenant.getDomainName()); if (!Optional.ofNullable(tenantFromDB).isPresent()) return ServiceResponseBuilder.<DeviceModel> error() .withMessage(CommonValidations.TENANT_DOES_NOT_EXIST.getCode()).build(); Application appFromDB = applicationRepository.findByTenantAndName(tenantFromDB.getId(), application.getName()); if (!Optional.ofNullable(appFromDB).isPresent()) return ServiceResponseBuilder.<DeviceModel> error() .withMessage(ApplicationService.Validations.APPLICATION_DOES_NOT_EXIST.getCode()).build(); DeviceModel deviceModel = deviceModelRepository.findByTenantIdApplicationNameAndName(tenantFromDB.getId(), appFromDB.getName(), name); if (!Optional.ofNullable(deviceModel).isPresent()) { return ServiceResponseBuilder.<DeviceModel> error() .withMessage(Validations.DEVICE_MODEL_DOES_NOT_EXIST.getCode()).build(); } return ServiceResponseBuilder.<DeviceModel>ok().withResult(deviceModel).build(); } @Override public ServiceResponse<DeviceModel> getByTenantApplicationAndGuid(Tenant tenant, Application application, String guid) { if (!Optional.ofNullable(tenant).isPresent()) { return ServiceResponseBuilder.<DeviceModel>error() .withMessage(CommonValidations.TENANT_NULL.getCode()) .build(); } if (!Optional.ofNullable(application).isPresent()) { return ServiceResponseBuilder.<DeviceModel>error() .withMessage(ApplicationService.Validations.APPLICATION_NULL.getCode()) .build(); } Tenant tenantFromDB = tenantRepository.findByDomainName(tenant.getDomainName()); if (!Optional.ofNullable(tenantFromDB).isPresent()) return ServiceResponseBuilder.<DeviceModel> error() .withMessage(CommonValidations.TENANT_DOES_NOT_EXIST.getCode()).build(); Application appFromDB = applicationRepository.findByTenantAndName(tenantFromDB.getId(), application.getName()); if (!Optional.ofNullable(appFromDB).isPresent()) return ServiceResponseBuilder.<DeviceModel> error() .withMessage(ApplicationService.Validations.APPLICATION_DOES_NOT_EXIST.getCode()).build(); DeviceModel deviceModel = deviceModelRepository.findByTenantIdApplicationNameAndGuid(tenantFromDB.getId(), appFromDB.getName(), guid); if (!Optional.ofNullable(deviceModel).isPresent()) { return ServiceResponseBuilder.<DeviceModel> error() .withMessage(Validations.DEVICE_MODEL_DOES_NOT_EXIST.getCode()).build(); } return ServiceResponseBuilder.<DeviceModel>ok().withResult(deviceModel).build(); } @Override public ServiceResponse<List<Device>> listDevicesByDeviceModelName(Tenant tenant, Application application, String deviceModelName) { if (!Optional.ofNullable(tenant).isPresent()) return ServiceResponseBuilder.<List<Device>>error() .withMessage(CommonValidations.TENANT_NULL.getCode()) .build(); if (!Optional.ofNullable(application).isPresent()) return ServiceResponseBuilder.<List<Device>>error() .withMessage(ApplicationService.Validations.APPLICATION_NULL.getCode()) .build(); DeviceModel devModel = getByTenantApplicationAndName(tenant, application, deviceModelName).getResult(); if (!Optional.ofNullable(devModel).isPresent()) { return ServiceResponseBuilder.<List<Device>>error() .withMessage(Validations.DEVICE_MODEL_DOES_NOT_EXIST.getCode()) .build(); } List<Device> devices = deviceRepository.findAllByTenantIdApplicationNameAndDeviceModel( tenant.getId(), application.getName(), devModel.getId()); return ServiceResponseBuilder.<List<Device>>ok() .withResult(devices) .build(); } @Override public ServiceResponse<DeviceModel> findDefault(Tenant tenant, Application application) { if (!Optional.ofNullable(tenant).isPresent()) return ServiceResponseBuilder.<DeviceModel>error() .withMessage(CommonValidations.TENANT_NULL.getCode()) .build(); if (!Optional.ofNullable(application).isPresent()) return ServiceResponseBuilder.<DeviceModel>error() .withMessage(ApplicationService.Validations.APPLICATION_NULL.getCode()) .build(); DeviceModel deviceModelDefault = deviceModelRepository.findDefault(tenant.getId(), application.getName(), true); if (!Optional.ofNullable(deviceModelDefault).isPresent()) { deviceModelDefault = DeviceModel.builder() .name("default") .description("default model") .contentType(DeviceModel.ContentType.APPLICATION_JSON) .defaultModel(true) .guid(UUID.randomUUID().toString()) .build(); ServiceResponse<DeviceModel> serviceResponse = register(tenant, application, deviceModelDefault); deviceModelDefault = serviceResponse.getResult(); } return ServiceResponseBuilder.<DeviceModel>ok() .withResult(deviceModelDefault) .build(); } }
package nl.mvdr.tinustris.engine; import java.util.ArrayList; import java.util.Collections; import java.util.List; import lombok.extern.slf4j.Slf4j; import nl.mvdr.tinustris.input.Input; import nl.mvdr.tinustris.input.InputState; import nl.mvdr.tinustris.input.InputStateHistory; import nl.mvdr.tinustris.model.Action; import nl.mvdr.tinustris.model.GameState; import nl.mvdr.tinustris.model.Orientation; import nl.mvdr.tinustris.model.Point; import nl.mvdr.tinustris.model.Tetromino; /** * Implementation of {@link GameEngine}. * * @author Martijn van de Rijdt */ @Slf4j public class TinusTrisEngine implements GameEngine { /** Gravity, expressed in G, that is, cells per frame. Must be at least 0. */ // TODO have this be variable, depending on current level // 1 / 60 means the tetromino falls one cell every second private static final float GRAVITY = 1f / 60f; /** Number of frames before a block locks into place. Should be greater than the number of frames between drops. */ // TODO have this be variable, depending on current level private static final int LOCK_DELAY = 120; /** * Number of frames the input is ignored while the user is holding down a button. * * Say this value is 30 and the user is holding the left button. The active block will now move left once every * thirty frames. */ private static final int INPUT_FRAMES = 10; /** Tetromino generator. */ private final TetrominoGenerator generator; /** Constructor. */ public TinusTrisEngine() { super(); this.generator = new RandomTetrominoGenerator(); } /** {@inheritDoc} */ @Override public GameState initGameState() { List<Tetromino> grid = new ArrayList<>(GameState.DEFAULT_WIDTH * GameState.DEFAULT_HEIGHT); while (grid.size() != GameState.DEFAULT_WIDTH * GameState.DEFAULT_HEIGHT) { grid.add(null); } grid = Collections.unmodifiableList(grid); GameState gameState = new GameState(grid, GameState.DEFAULT_WIDTH, generator.get(0), generator.get(1)); return gameState; } /** {@inheritDoc} */ @Override public GameState computeNextState(GameState previousState, InputState inputState) { GameState result = updateInputStateAndCounters(previousState, inputState); if (previousState.getNumFramesUntilLinesDisappear() == 1) { result = removeLines(result); } if (result.getNumFramesUntilLinesDisappear() == 0) { List<Action> actions = determineActions(previousState, inputState); for (Action action : actions) { result = executeAction(result, action); } } return result; } /** * Determines which actions should be performed. * * @param previousState previous game state * @param inputState input state * @return actions */ private List<Action> determineActions(GameState previousState, InputState inputState) { List<Action> actions = new ArrayList<>(); // process gravity if (1f / GRAVITY <= previousState.getNumFramesSinceLastDownMove()) { int cells = Math.round(GRAVITY); if (cells == 0) { cells = 1; } for (int i = 0; i != cells; i++) { actions.add(Action.GRAVITY_DROP); } } // process player input for (Input input: Input.values()) { if (inputState.isPressed(input) && previousState.getInputStateHistory().getNumberOfFrames(input) % INPUT_FRAMES == 0) { actions.add(input.getAction()); } } // process lock delay if (LOCK_DELAY <= previousState.getNumFramesSinceLastMove()) { actions.add(Action.LOCK); } return actions; } /** * Returns a new game state based on the given previous state. * * The input history is updated with the given input state and the frame counters are updated. All other values * are the same as in the given state. * * @param previousState previous game state * @param inputState input state for the current frame * @return game state with updated input history and frame counter, otherwise unchanged */ private GameState updateInputStateAndCounters(GameState previousState, InputState inputState) { InputStateHistory inputStateHistory = previousState.getInputStateHistory().next(inputState); int numFramesSinceLastTick = previousState.getNumFramesSinceLastDownMove() + 1; int numFramesSinceLastMove = previousState.getNumFramesSinceLastMove() + 1; int numFramesUntilLinesDisappear = Math.max(0, previousState.getNumFramesUntilLinesDisappear() - 1); return new GameState(previousState.getGrid(), previousState.getWidth(), previousState.getCurrentBlock(), previousState.getCurrentBlockLocation(), previousState.getCurrentBlockOrientation(), previousState.getNextBlock(), numFramesSinceLastTick, numFramesSinceLastMove, inputStateHistory, previousState.getBlockCounter(), previousState.getLines(), numFramesUntilLinesDisappear); } /** * Executes the given action on the given game state. * * @param state base game state * @param action action to be performed * @return updated game state */ private GameState executeAction(GameState state, Action action) { if (log.isTraceEnabled()) { log.trace("State before executing action {}: {}", action, state); } GameState result; if (action == Action.MOVE_DOWN) { result = executeMoveDown(state); } else if (action == Action.GRAVITY_DROP) { result = executeGravityDrop(state); } else if (action == Action.LOCK) { result = executeLock(state); } else if (action == Action.MOVE_LEFT) { result = executeMoveLeft(state); } else if (action == Action.MOVE_RIGHT){ result = executeMoveRight(state); } else if (action == Action.HARD_DROP) { result = executeInstantDrop(state); } else if (action == Action.TURN_LEFT) { result = executeTurnLeft(state); } else if (action == Action.TURN_RIGHT) { result = executeTurnRight(state); } else if (action == Action.HOLD) { result = executeHold(state); } else { throw new IllegalArgumentException("Unexpected action: " + action); } if (log.isTraceEnabled()) { log.trace("State after executing action {}: {}", action, result); } return result; } /** * Executes the down action. * * @param state game state * @return updated game state */ private GameState executeMoveDown(GameState state) { GameState result; if (state.canMoveDown()) { result = moveDown(state); } else { result = lockBlock(state); } return result; } /** * Executes the gravity drop action. * * @param state game state * @return updated game state */ private GameState executeGravityDrop(GameState state) { GameState result; if (state.canMoveDown()) { result = moveDown(state); } else { // do nothing result = state; } return result; } /** * Executes the lock block action. * * @param state game state * @return updated game state */ private GameState executeLock(GameState state) { GameState result; if (!state.canMoveDown()) { result = lockBlock(state); } else { // do nothing result = state; } return result; } /** * Moves the current block down one position on the given state. * * This method does not check that state.canMoveDown() is true. * * @param state game state * @return updated state */ private GameState moveDown(GameState state) { Point location = state.getCurrentBlockLocation().translate(0, -1); return new GameState(state.getGrid(), state.getWidth(), state.getCurrentBlock(), location, state.getCurrentBlockOrientation(), state.getNextBlock(), 0, 0, state.getInputStateHistory(), state.getBlockCounter(), state.getLines()); } /** * Locks the current block in its current position. * * @param state game state * @return updated game state */ private GameState lockBlock(GameState state) { int width = state.getWidth(); int height = state.getHeight(); // Update the grid: old grid plus current location of the active block. List<Tetromino>grid = new ArrayList<>(state.getGrid()); for (Point point : state.getCurrentActiveBlockPoints()) { int index = state.toGridIndex(point); grid.set(index, state.getCurrentBlock()); } grid = Collections.unmodifiableList(grid); // Check for newly formed lines. int linesScored = countLines(width, height, grid); log.info("Lines scored: " + linesScored); // Create the new game state. Tetromino block; Tetromino nextBlock; Point location; Orientation orientation; int blockCounter; int numFramesUntilLinesDisappear; if (0 < linesScored) { block = null; nextBlock = state.getNextBlock(); location = null; orientation = null; blockCounter = state.getBlockCounter(); numFramesUntilLinesDisappear = GameState.FRAMES_LINES_STAY; } else { block = state.getNextBlock(); nextBlock = generator.get(state.getBlockCounter() + 2); location = state.getBlockSpawnLocation(); orientation = Orientation.getDefault(); blockCounter = state.getBlockCounter() + 1; numFramesUntilLinesDisappear = 0; } int lines = state.getLines() + linesScored; GameState result = new GameState(grid, width, block, location, orientation, nextBlock, 0, 0, state.getInputStateHistory(), blockCounter, lines, numFramesUntilLinesDisappear); if (linesScored != 0 && log.isDebugEnabled()) { log.debug(result.toString()); } return result; } /** * Counts the number of full lines in the grid. * * @param width * width of the grid * @param height * height of the grid * @param grid * list containing the grid * @return number of lines; between 0 and 4 */ private int countLines(int width, int height, List<Tetromino> grid) { int linesScored = 0; for (int line = height - 1; 0 <= line; line boolean filled = true; int x = 0; while (filled && x != width) { filled = grid.get(x + line * width) != null; x++; } if (filled) { linesScored++; } } return linesScored; } /** * Removes any full lines from the grid and drops down the lines above them. * * @param width * width of the grid * @param height * height of the grid * @param grid * list containing the grid * @return updated copy of the game state */ private GameState removeLines(GameState state) { int width = state.getWidth(); int height = state.getHeight(); List<Tetromino> grid = new ArrayList<>(state.getGrid()); // Update the grid by removing all full lines. for (int line = height - 1; 0 <= line; line if (state.isFullLine(line)) { // Line found. // Drop all the lines above it down. for (int y = line; y != height - 1; y++) { for (int x = 0; x != width; x++) { Tetromino tetromino = grid.get(x + (y + 1) * width); grid.set(x + y * width, tetromino); } } // Make the top line empty. for (int x = 0; x != width; x++) { grid.set(x + (height - 1) * width, null); } } } Tetromino block = state.getNextBlock(); Tetromino nextBlock = generator.get(state.getBlockCounter() + 2); Point location = state.getBlockSpawnLocation(); Orientation orientation = Orientation.getDefault(); int blockCounter = state.getBlockCounter() + 1; return new GameState(grid, width, block, location, orientation, nextBlock, 0, 0, state.getInputStateHistory(), blockCounter, state.getLines()); } /** * Executes the left action. * * @param state game state * @return updated game state */ private GameState executeMoveLeft(GameState state) { GameState result; if (state.canMoveLeft()) { result = moveLeft(state); } else { // do nothing result = state; } return result; } /** * Moves the current block left one position on the given state. * * This method does not check that state.canMoveLeft() is true. * * @param state game state * @return updated state */ private GameState moveLeft(GameState state) { GameState result; Point location = state.getCurrentBlockLocation().translate(-1, 0); result = new GameState(state.getGrid(), state.getWidth(), state.getCurrentBlock(), location, state.getCurrentBlockOrientation(), state.getNextBlock(), state.getNumFramesSinceLastDownMove(), 0, state.getInputStateHistory(), state.getBlockCounter(), state.getLines()); return result; } /** * Executes the right action. * * @param state game state * @return updated game state */ private GameState executeMoveRight(GameState state) { GameState result; if (state.canMoveRight()) { result = moveRight(state); } else { // do nothing result = state; } return result; } /** * Moves the current block right one position on the given state. * * This method does not check that state.canMoveRight() is true. * * @param state game state * @return updated state */ private GameState moveRight(GameState state) { GameState result; Point location = state.getCurrentBlockLocation().translate(1, 0); result = new GameState(state.getGrid(), state.getWidth(), state.getCurrentBlock(), location, state.getCurrentBlockOrientation(), state.getNextBlock(), state.getNumFramesSinceLastDownMove(), 0, state.getInputStateHistory(), state.getBlockCounter(), state.getLines()); return result; } /** * Executes the instant drop action. * * @param state game state * @return updated game state */ private GameState executeInstantDrop(GameState state) { GameState result = state; while (result.canMoveDown()) { result = moveDown(result); } result = lockBlock(result); return result; } /** * Executes the turn left action. * * @param state game state * @return updated game state */ private GameState executeTurnLeft(GameState state) { GameState stateAfterTurn = turnLeft(state); return fixStateAfterAction(state, stateAfterTurn); } /** * Turns the current active block counter-clockwise. * * This method does not check whether the resulting game state is valid! * * @param state state * @return updated game state (may be invalid) */ private GameState turnLeft(GameState state) { Orientation orientation = state.getCurrentBlockOrientation().getNextCounterClockwise(); return new GameState(state.getGrid(), state.getWidth(), state.getCurrentBlock(), state.getCurrentBlockLocation(), orientation, state.getNextBlock(), state.getNumFramesSinceLastDownMove(), 0, state.getInputStateHistory(), state.getBlockCounter(), state.getLines()); } /** * Executes the turn right action. * * @param state game state * @return updated game state */ private GameState executeTurnRight(GameState state) { GameState stateAfterTurn = turnRight(state); return fixStateAfterAction(state, stateAfterTurn); } /** * Turns the current active block clockwise. * * This method does not check whether the resulting game state is valid! * * @param state state * @return updated game state (may be invalid) */ private GameState turnRight(GameState state) { Orientation orientation = state.getCurrentBlockOrientation().getNextClockwise(); return new GameState(state.getGrid(), state.getWidth(), state.getCurrentBlock(), state.getCurrentBlockLocation(), orientation, state.getNextBlock(), state.getNumFramesSinceLastDownMove(), 0, state.getInputStateHistory(), state.getBlockCounter(), state.getLines()); } /** * Executes the hold action. * * @param state game state * @return updated game state */ private GameState executeHold(GameState state) { Tetromino block = state.getNextBlock(); Tetromino nextBlock = state.getCurrentBlock(); GameState stateAfterHold = new GameState(state.getGrid(), state.getWidth(), block, state.getCurrentBlockLocation(), state.getCurrentBlockOrientation(), nextBlock, state.getNumFramesSinceLastDownMove(), 0, state.getInputStateHistory(), state.getBlockCounter(), state.getLines()); return fixStateAfterAction(state, stateAfterHold); } /** * Fixes the state after an action that may have left the game in an invalid state. * * @param originalState * original game state * @param stateAfterAction * game state after execution of the action; this game state is allowed to be invalid (that is, a game * over state or a state where the active block is partially or completely out of bounds) * @return new game state */ private GameState fixStateAfterAction(GameState originalState, GameState stateAfterAction) { GameState result; if (stateAfterAction.isCurrentBlockWithinBounds() && !stateAfterAction.isTopped()) { // no problemo! result = stateAfterAction; } else { // state is not valid if (stateAfterAction.canMoveRight()) { result = moveRight(stateAfterAction); } else if (stateAfterAction.canMoveLeft()) { result = moveLeft(stateAfterAction); } else { // impossible to fix; cancel the action result = originalState; } } return result; } }
package org.opennms.netmgt.correlation.drools; import static org.easymock.EasyMock.expect; import org.opennms.netmgt.EventConstants; import org.opennms.netmgt.utils.EventBuilder; import org.opennms.netmgt.xml.event.Event; import org.opennms.test.mock.EasyMockUtils; public class NodeParentRulesTest extends CorrelationRulesTestCase { private EasyMockUtils m_mocks = new EasyMockUtils(); public void testParentNodeDown() throws Exception { //anticipate(createRootCauseEvent(1, 1)); NodeService nodeService = m_mocks.createMock(NodeService.class); expect(nodeService.getParentNode(1L)).andReturn(null); m_mocks.replayAll(); DroolsCorrelationEngine engine = findEngineByName("nodeParentRules"); engine.setGlobal("nodeService", nodeService); engine.correlate(createNodeDownEvent(1)); // event + root cause m_anticipatedMemorySize = 2; m_mocks.verifyAll(); verify(engine); anticipate(createRootCauseResolvedEvent(1, 1)); } private Event createRootCauseResolvedEvent(int symptom, int cause) { return new EventBuilder(createNodeEvent("rootCauseResolved", cause)).getEvent(); } // Currently unused // private Event createRootCauseEvent(int symptom, int cause) { // return new EventBuilder(createNodeEvent("rootCauseEvent", cause)).getEvent(); public Event createNodeDownEvent(int nodeid) { return createNodeEvent(EventConstants.NODE_DOWN_EVENT_UEI, nodeid); } public Event createNodeUpEvent(int nodeid) { return createNodeEvent(EventConstants.NODE_UP_EVENT_UEI, nodeid); } private Event createNodeEvent(String uei, int nodeid) { return new EventBuilder(uei, "test") .setNodeid(nodeid) .getEvent(); } }
package org.spoofax.jsglr2.inputstack.incremental; import static org.spoofax.jsglr2.incremental.parseforest.IncrementalCharacterNode.EOF_NODE; import org.spoofax.jsglr2.incremental.IIncrementalParseState; import org.spoofax.jsglr2.incremental.diff.IStringDiff; import org.spoofax.jsglr2.incremental.diff.ProcessUpdates; import org.spoofax.jsglr2.incremental.parseforest.IncrementalCharacterNode; import org.spoofax.jsglr2.incremental.parseforest.IncrementalParseForest; import org.spoofax.jsglr2.incremental.parseforest.IncrementalParseNode; import org.spoofax.jsglr2.incremental.parseforest.IncrementalSkippedNode; import org.spoofax.jsglr2.parser.AbstractParseState; import org.spoofax.jsglr2.stack.IStackNode; /** * This type of incremental input stack preprocesses the previous parse forest using the list of updates. * {@link LazyPreprocessingIncrementalInputStack} also uses this strategy, but does not inherit this class because of * its completely different way of handling the stack. */ public abstract class AbstractPreprocessingIncrementalInputStack extends AbstractInputStack implements IIncrementalInputStack { /** * The stack contains all subtrees that are yet to be popped. The top of the stack also contains the subtree that * has been returned last time. The stack initially only contains EOF and the root. */ protected final IStack<IncrementalParseForest> stack; protected abstract IStack<IncrementalParseForest> createStack(); /** Copy constructor. Only used in {@link #clone()}. */ AbstractPreprocessingIncrementalInputStack(AbstractPreprocessingIncrementalInputStack original) { super(original.inputString); this.currentOffset = original.currentOffset; this.stack = original.stack.clone(); } /** * @param inputString * should be equal to the yield of the root. */ public AbstractPreprocessingIncrementalInputStack(IncrementalParseForest root, String inputString) { super(inputString); stack = createStack(); stack.push(EOF_NODE); stack.push(root); } static <StackNode extends IStackNode, ParseState extends AbstractParseState<IIncrementalInputStack, StackNode> & IIncrementalParseState> IncrementalParseForest preProcessParseForest(ProcessUpdates<StackNode, ParseState> processUpdates, IStringDiff diff, String inputString, String previousInput, IncrementalParseForest previousResult) { return previousInput != null && previousResult != null ? processUpdates.processUpdates(previousInput, previousResult, diff.diff(previousInput, inputString)) : processUpdates.getParseNodeFromString(inputString); } @Override public abstract AbstractPreprocessingIncrementalInputStack clone(); @Override public void breakDown() { if(stack.isEmpty()) return; IncrementalParseForest current = stack.peek(); if(current.isTerminal()) return; stack.pop(); // always pop last lookahead, whether it has children or not if(current instanceof IncrementalSkippedNode) { // Break down a skipped node by explicitly instantiating character nodes for the skipped part pushCharactersToStack(inputString.substring(currentOffset, currentOffset + current.width())); } else { IncrementalParseForest[] children = ((IncrementalParseNode) current).getFirstDerivation().parseForests(); // Push all children to stack in reverse order for(int i = children.length - 1; i >= 0; i stack.push(children[i]); } } } @Override public void next() { currentOffset += stack.pop().width(); } @Override public IncrementalParseForest getNode() { return stack.isEmpty() ? null : stack.peek(); } protected void pushCharactersToStack(String inputString) { int[] chars = inputString.codePoints().toArray(); for(int i = chars.length - 1; i >= 0; i stack.push(new IncrementalCharacterNode(chars[i])); } } // Note: this method cannot be implemented precisely enough for PreprocessingIncrementalInputStacks. // The commented-out implementation below returns false when the node following the lookahead is a temporary node. // However, it should also return false for all nodes that are broken down after this point, // until we have processed the temporary node in question. // Moreover, this method should return false only when the first character of the temporary node has been changed, // but we cannot detect this efficiently in a preprocessed tree. // Having this method always return false is always correct, though it negatively impacts the amount of reuse, // but we don't currently use the PreprocessingIncrementalInputStacks at the moment, so that doesn't matter. @Override public boolean lookaheadIsUnchanged() { return false; // if(stack.size() < 2) return true; // EOF is always unchanged // IncrementalParseForest node = stack.get(stack.size() - 2); // if(node.isTerminal()) return true; // return ((IncrementalParseNode) node).production() != null; } }
package fr.inria.spirals.repairnator.process.inspectors; import fr.inria.spirals.repairnator.BuildToBeInspected; import fr.inria.spirals.repairnator.ProjectState; import fr.inria.spirals.repairnator.ScannedBuildStatus; import fr.inria.spirals.repairnator.notifier.AbstractNotifier; import fr.inria.spirals.repairnator.process.step.*; import fr.inria.spirals.repairnator.process.step.checkoutrepository.CheckoutBuild; import fr.inria.spirals.repairnator.process.step.checkoutrepository.CheckoutPreviousBuild; import fr.inria.spirals.repairnator.process.step.checkoutrepository.CheckoutPreviousBuildSourceCode; import fr.inria.spirals.repairnator.process.step.gatherinfo.BuildShouldFail; import fr.inria.spirals.repairnator.process.step.gatherinfo.BuildShouldPass; import fr.inria.spirals.repairnator.process.step.gatherinfo.GatherTestInformation; import fr.inria.spirals.repairnator.serializer.AbstractDataSerializer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; public class ProjectInspector4Bears extends ProjectInspector { private final Logger logger = LoggerFactory.getLogger(ProjectInspector4Bears.class); private boolean isFixerBuild_Case1; private boolean isFixerBuild_Case2; public ProjectInspector4Bears(BuildToBeInspected buildToBeInspected, String workspace, List<AbstractDataSerializer> serializers, List<AbstractNotifier> notifiers) { super(buildToBeInspected, workspace, serializers, notifiers); this.isFixerBuild_Case1 = false; this.isFixerBuild_Case2 = false; } public void run() { AbstractStep firstStep; AbstractStep cloneRepo = new CloneRepository(this); if (this.getBuildToBeInspected().getStatus() == ScannedBuildStatus.FAILING_AND_PASSING) { cloneRepo.setNextStep(new CheckoutBuild(this)) .setNextStep(new ResolveDependency(this)) .setNextStep(new BuildProject(this, BuildProject.class.getSimpleName()+"Build")) .setNextStep(new ComputeClasspath(this)) .setNextStep(new TestProject(this, TestProject.class.getSimpleName()+"Build")) .setNextStep(new GatherTestInformation(this, new BuildShouldPass(), true, GatherTestInformation.class.getSimpleName()+"Build")) .setNextStep(new CheckoutPreviousBuild(this)) .setNextStep(new BuildProject(this, BuildProject.class.getSimpleName()+"PreviousBuild")) .setNextStep(new TestProject(this, TestProject.class.getSimpleName()+"PreviousBuild")) .setNextStep(new GatherTestInformation(this, new BuildShouldFail(), false, GatherTestInformation.class.getSimpleName()+"PreviousBuild")) .setNextStep(new SquashRepository(this)) .setNextStep(new PushIncriminatedBuild(this)); } else { if (this.getBuildToBeInspected().getStatus() == ScannedBuildStatus.PASSING_AND_PASSING_WITH_TEST_CHANGES) { cloneRepo.setNextStep(new CheckoutBuild(this)) .setNextStep(new ResolveDependency(this)) .setNextStep(new BuildProject(this, BuildProject.class.getSimpleName()+"Build")) .setNextStep(new ComputeClasspath(this)) .setNextStep(new TestProject(this, TestProject.class.getSimpleName()+"Build")) .setNextStep(new GatherTestInformation(this, new BuildShouldPass(), true, GatherTestInformation.class.getSimpleName()+"Build")) .setNextStep(new CheckoutPreviousBuild(this)) .setNextStep(new BuildProject(this, BuildProject.class.getSimpleName()+"PreviousBuild")) .setNextStep(new TestProject(this, TestProject.class.getSimpleName()+"PreviousBuild")) .setNextStep(new GatherTestInformation(this, new BuildShouldPass(), true, GatherTestInformation.class.getSimpleName()+"PreviousBuild")) .setNextStep(new CheckoutPreviousBuildSourceCode(this)) .setNextStep(new BuildProject(this, BuildProject.class.getSimpleName()+"PreviousBuildSourceCode")) .setNextStep(new TestProject(this, TestProject.class.getSimpleName()+"PreviousBuildSourceCode")) .setNextStep(new GatherTestInformation(this, new BuildShouldFail(), false, GatherTestInformation.class.getSimpleName()+"PreviousBuildSourceCode")) .setNextStep(new SquashRepository(this)) .setNextStep(new PushIncriminatedBuild(this)); } else { this.logger.debug("The pair of scanned builds is not interesting."); return; } } firstStep = cloneRepo; firstStep.setDataSerializer(this.getSerializers()); firstStep.setState(ProjectState.INIT); try { firstStep.execute(); } catch (Exception e) { this.getJobStatus().addStepError("Unknown", e.getMessage()); this.logger.debug("Exception catch while executing steps: ", e); } } public boolean isFixerBuildCase1() { return this.isFixerBuild_Case1; } public void setFixerBuildCase1(boolean fixerBuildCase1) { this.isFixerBuild_Case1 = fixerBuildCase1; } public boolean isFixerBuildCase2() { return this.isFixerBuild_Case2; } public void setFixerBuildCase2(boolean fixerBuildCase2) { this.isFixerBuild_Case2 = fixerBuildCase2; } }
package io.github.ihongs; import java.util.Map; import java.util.HashMap; import java.util.Iterator; import java.util.TimeZone; import java.util.Locale; import java.util.function.Supplier; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * * * <p> * Servlet , * ; * Core , , * , * getInstance . * Core Core.getInstance() * </p> * * <p> * THREAD_CORE ThreadLocal, * , * ; * GLOBAL_CORE , * , . * Cleanable,Singleton . * </p> * * <h3>:</h3> * <pre> * ENVIR (0 cmd, 1 web) * DEBUG (0 , 1 , 2 , 4 8 ; 3 ) * BASE_HREF (WEBContextPath) * BASE_PATH (WEBRealPath(/)) * CORE_PATH (WEBWEB-INF) * CONF_PATH * DATA_PATH * SERVER_ID ID ( Core.getUniqueId()) * : Servlet/Filter/Cmdlet . , , . * </pre> * * <h3>:</h3> * <pre> * 0x24 * 0x25 * 0x26 * 0x27 * 0x28 * </pre> * * @author Hongs */ abstract public class Core extends HashMap<String, Object> implements AutoCloseable { /** * (0 Cmd , 1 Web ) */ public static byte ENVIR; /** * (0 , 1 , 2 , 4 Trace, 8 Debug) * : , 0 */ public static byte DEBUG; public static String SERVER_ID = "0" ; /** * WEB, : , */ public static String SITE_HREF = null; /** * WEB, : , */ public static String BASE_HREF = null; /** * WEB, : , */ public static String BASE_PATH = null; public static String CORE_PATH = null; public static String CONF_PATH = null; public static String DATA_PATH = null; public static final long STARTS_TIME = System.currentTimeMillis(); public static final Core GLOBAL_CORE = new Global(); public static final ThreadLocal<Core> THREAD_CORE = new ThreadLocal() { @Override protected Core initialValue() { return new Simple (); } @Override public void remove() { try { ( (Core) get()).close(); } catch (Throwable ex) { throw new Error(ex); } super.remove(); } }; public static final InheritableThreadLocal< Long > ACTION_TIME = new InheritableThreadLocal(); public static final InheritableThreadLocal<String> ACTION_ZONE = new InheritableThreadLocal(); public static final InheritableThreadLocal<String> ACTION_LANG = new InheritableThreadLocal(); public static final InheritableThreadLocal<String> ACTION_NAME = new InheritableThreadLocal(); public static final InheritableThreadLocal<String> CLIENT_ADDR = new InheritableThreadLocal(); /** * * @return */ public static final Core getInstance() { return THREAD_CORE.get(); } /** * * * @param <T> * @param clas * @return */ public static final <T>T getInstance(Class<T> clas) { return getInstance().get(clas); } /** * * * @param name * @return */ public static final Object getInstance(String name) { return getInstance().get(name); } public static final <T>T newInstance(Class<T> clas) { try { java.lang.reflect.Method method; method = clas.getMethod("getInstance", new Class [] {}); try { return ( T ) method.invoke( null , new Object[] {}); } catch (IllegalAccessException ex) { throw new HongsError(0x27, "Can not build "+clas.getName(), ex); } catch (IllegalArgumentException ex) { throw new HongsError(0x27, "Can not build "+clas.getName(), ex); } catch (java.lang.reflect.InvocationTargetException ex ) { Throwable ta = ex.getCause(); if (ta instanceof StackOverflowError) { throw ( StackOverflowError ) ta ; } throw new HongsError(0x27, "Can not build "+clas.getName(), ta); } } catch (NoSuchMethodException ez) { try { return clas.newInstance(); } catch (IllegalAccessException ex) { throw new HongsError(0x28, "Can not build "+clas.getName(), ex); } catch (InstantiationException ex) { Throwable ta = ex.getCause(); if (ta instanceof StackOverflowError) { throw ( StackOverflowError ) ta ; } throw new HongsError(0x28, "Can not build "+clas.getName(), ex); } } catch (SecurityException se) { throw new HongsError(0x26, "Can not build "+clas.getName(), se); } } public static final Object newInstance(String name) { Class klass; try { klass = Class.forName( name ); } catch (ClassNotFoundException ex) { throw new HongsError(0x25, "Can not find class by name '" + name + "'."); } return newInstance(klass); } /** * * * 3616(ID), * "2059/04/26 01:38:27". * : 0~9A~Z * * @param svid ID * @return */ public static final String newIdentity(String svid) { long trid = Thread.currentThread( ).getId( ) % 1296L; // 36^2 long time = System.currentTimeMillis () % 2821109907456L; // 36^8 int rand = ThreadLocalRandom.current().nextInt(1679616); // 36^4 return String.format( "%8s%4s%2s%2s", Long.toString(time, 36), Long.toString(rand, 36), Long.toString(trid, 36), svid ).replace(' ','0') .toUpperCase( ); } /** * * * ID(Core.SERVER_ID) * * @return */ public static final String newIdentity() { return Core.newIdentity(Core.SERVER_ID); } /** * * @return */ public static final Locale getLocality() { Core core = Core.getInstance(); String name = Locale.class.getName(); Locale inst = (Locale)core.got(name); if (null != inst) { return inst; } String[] lang = Core.ACTION_LANG.get().split("_",2); if (2 <= lang.length) { inst = new Locale(lang[0],lang[1]); } else { inst = new Locale(lang[0]); } core.put(name, inst); return inst; } /** * * @return */ public static final TimeZone getTimezone() { Core core = Core.getInstance(); String name = TimeZone.class.getName(); TimeZone inst = (TimeZone)core.got(name); if (null != inst) { return inst; } inst = TimeZone.getTimeZone(Core.ACTION_ZONE.get()); core.put(name, inst); return inst; } / /** * * * @param key [.] * @return */ abstract public Object get(String key); /** * * * @param <T> * @param cls [.].class * @return */ abstract public <T>T get(Class<T> cls); /** * , * @param <T> * @param key * @param fun * @return fun , */ abstract public <T>T get(String key, Supplier<T> fun); /** * , * @param <T> * @param key * @param fun * @return put , */ abstract public <T>T set(String key, Supplier<T> fun); /** * get * * @param name * @return , */ public Object got(String name) { return super.get(name); } /** * get(Object), got(String),get(String|Class) * * @param name * @return , * @throws UnsupportedOperationException * @deprecated */ @Override public Object get(Object name) { throw new UnsupportedOperationException( "May cause an error on 'get(Object)', use 'got(String)' or 'get(String|Class)'"); } public void clean() { if (this.isEmpty()) { return; } Iterator i = this.entrySet().iterator(); while ( i.hasNext( ) ) { Entry e = (Entry)i.next(); Object o = e . getValue(); try { if (o instanceof Cleanable) { Cleanable c = (Cleanable) o; if (c.cleanable ()) { if (o instanceof AutoCloseable ) { ((AutoCloseable) c ).close( ); } i.remove(); } } } catch ( Throwable x ) { x.printStackTrace ( System.err ); } } } @Override public void clear() { if (this.isEmpty()) { return; } /** * ConcurrentModificationException, * . */ Object[] a = this.values().toArray(); for (int i = 0; i < a.length; i ++ ) { Object o = a [i]; try { if (o instanceof AutoCloseable ) { ((AutoCloseable) o ).close( ); } } catch ( Throwable x ) { x.printStackTrace ( System.err ); } } super.clear(); } @Override public void close() { clear(); } @Override protected void finalize() throws Throwable { try { close(); } finally { super.finalize(); } } @Override public String toString() { StringBuilder sb = new StringBuilder(); for(Map.Entry<String, Object> et : entrySet()) { sb.append('['); int ln = sb.length(); Object ob = et.getValue(); if (ob instanceof AutoCloseable) { sb.append('A'); } if (ob instanceof Cleanable) { sb.append('C'); } if (ob instanceof Singleton) { sb.append('S'); } if (ln < sb.length() ) { sb.append(']'); } else { sb.setLength(ln - 1); } sb.append(et.getKey()).append(", "); } int sl = sb.length(); if (sl > 0 ) { sb.setLength(sl-2); } return sb.toString(); } private static final class Simple extends Core { @Override public Object get(String name) { Core core = Core.GLOBAL_CORE; if (this.containsKey(name)) { return this.got(name); } if (core.containsKey(name)) { return core.got(name); } Object inst = newInstance( name ); if (inst instanceof Singleton) { core.put( name, inst ); } else { this.put( name, inst ); } return inst; } @Override public <T>T get(Class<T> clas) { String name = clas.getName( ); Core core = Core.GLOBAL_CORE; if (this.containsKey(name)) { return (T)this.got(name); } if (core.containsKey(name)) { return (T)core.got(name); } T inst = newInstance( clas ); if (inst instanceof Singleton) { core.put( name, inst ); } else { this.put( name, inst ); } return inst; } @Override public <T>T get(String key, Supplier<T> fun) { Object abj=super.got(key); if (null != abj) return (T) abj; T obj = fun.get( ); super.put(key,obj); return obj; } @Override public <T>T set(String key, Supplier<T> fun) { T obj = fun.get( ); super.put(key,obj); return obj; } } private static final class Global extends Core { private final ReadWriteLock LOCK = new ReentrantReadWriteLock(); @Override public Object got(String key) { LOCK.readLock( ).lock(); try { return super.got(key); } finally { LOCK.readLock( ).unlock(); } } @Override public Object get(String key) { LOCK.readLock( ).lock(); try { if (super.containsKey(key)) { return super.got(key); } } finally { LOCK.readLock( ).unlock(); } LOCK.writeLock().lock(); try { Object obj = newInstance(key); super.put( key, obj ); return obj; } finally { LOCK.writeLock().unlock(); } } @Override public <T>T get(Class<T> cls) { String key = cls.getName( ); LOCK.readLock( ).lock(); try { if (super.containsKey(key)) { return (T) super.got(key); } } finally { LOCK.readLock( ).unlock(); } LOCK.writeLock().lock(); try { T obj = newInstance(cls); super.put( key, obj ); return obj; } finally { LOCK.writeLock().unlock(); } } @Override public <T>T get(String key, Supplier<T> fun) { LOCK.readLock( ).lock(); try { Object obj=super.got(key); if (null != obj) return (T) obj; } finally { LOCK.readLock( ).unlock(); } LOCK.writeLock().lock(); try { T obj = fun.get( ); super.put(key,obj); return obj; } finally { LOCK.writeLock().unlock(); } } @Override public <T>T set(String key, Supplier<T> fun) { LOCK.writeLock().lock(); try { T obj = fun.get( ); super.put(key,obj); return obj; } finally { LOCK.writeLock().unlock(); } } @Override public Object put(String key, Object obj) { LOCK.writeLock().lock(); try { return super.put(key,obj); } finally { LOCK.writeLock().unlock(); } } @Override public void clear() { LOCK.writeLock().lock(); try { super.clear(); } finally { LOCK.writeLock().unlock(); } } @Override public void clean() { LOCK.writeLock().lock(); try { super.clean(); } finally { LOCK.writeLock().unlock(); } } } / static public interface Cleanable { public boolean cleanable (); } static public interface Singleton {} }
package limelight.ui.model.inputs; import java.awt.event.KeyEvent; import java.awt.font.TextHitInfo; public abstract class KeyProcessor { protected TextModel modelInfo; public KeyProcessor(TextModel modelInfo) { this.modelInfo = modelInfo; } public abstract void processKey(KeyEvent event); protected boolean isACharacter(int keyCode) { return (keyCode > 40 && keyCode < 100 || keyCode == 222 || keyCode == 32); } protected void insertCharIntoTextBox(char c) { modelInfo.text.insert(modelInfo.getCursorIndex(), c); modelInfo.setCursorIndex(modelInfo.getCursorIndex() + 1); } protected boolean isMoveRightEvent(int keyCode) { return keyCode == KeyEvent.VK_RIGHT && modelInfo.getCursorIndex() < modelInfo.getText().length(); } protected boolean isMoveLeftEvent(int keyCode) { return keyCode == KeyEvent.VK_LEFT && modelInfo.getCursorIndex() > 0; } protected boolean isMoveUpEvent(int keyCode) { return keyCode == KeyEvent.VK_UP && modelInfo.getLineNumberOfIndex(modelInfo.cursorIndex) > 0; } protected boolean isMoveDownEvent(int keyCode) { return keyCode == KeyEvent.VK_DOWN && modelInfo.getLineNumberOfIndex(modelInfo.cursorIndex) < modelInfo.textLayouts.size() - 1; } protected void initSelection() { modelInfo.selectionOn = true; modelInfo.setSelectionIndex(modelInfo.getCursorIndex()); } protected int findNearestWordToTheLeft() { return modelInfo.findWordsLeftEdge(modelInfo.getCursorIndex() - 1); } protected int findNearestWordToTheRight() { return findNextWordSkippingSpaces(modelInfo.findWordsRightEdge(modelInfo.getCursorIndex())); } private int findNextWordSkippingSpaces(int startIndex) { for (int i = startIndex; i <= modelInfo.getText().length() - 1; i++) { if (modelInfo.getText().charAt(i - 1) == ' ' && modelInfo.getText().charAt(i) != ' ') return i; } return modelInfo.getText().length(); } protected void selectAll() { modelInfo.selectionOn = true; modelInfo.setCursorIndex(modelInfo.getText().length()); modelInfo.setSelectionIndex(0); } protected void moveCursorUpALine() { if (modelInfo.getLastKeyPressed() == KeyEvent.VK_DOWN) { modelInfo.setCursorIndex(modelInfo.getLastCursorIndex()); return; } int currentLine = modelInfo.getLineNumberOfIndex(modelInfo.cursorIndex); if (modelInfo.isLastCharacterAReturn(modelInfo.cursorIndex)) currentLine++; System.out.println("currentLine = " + currentLine); int charCount = 0; for (int i = 0; i < currentLine - 1; i++) charCount += modelInfo.textLayouts.get(i).getText().length(); int xPos = modelInfo.getXPosFromIndex(modelInfo.cursorIndex); int previousLineLength = modelInfo.textLayouts.get(currentLine - 1).getText().length(); int newCursorIndex = charCount + previousLineLength; if (modelInfo.isLastCharacterAReturn(newCursorIndex)) newCursorIndex if (modelInfo.getXPosFromIndex(newCursorIndex) < xPos) { modelInfo.setCursorIndex(newCursorIndex); } else { TextHitInfo hitInfo = modelInfo.textLayouts.get(currentLine - 1).hitTestChar(xPos, 5); newCursorIndex = hitInfo.getCharIndex() + charCount; System.out.println("newCursorIndex = " + newCursorIndex); System.out.println("charCount = " + charCount); if (modelInfo.isLastCharacterAReturn(newCursorIndex)) newCursorIndex modelInfo.setCursorIndex(newCursorIndex); } } protected void moveCursorDownALine() { if (modelInfo.getLastKeyPressed() == KeyEvent.VK_UP) { modelInfo.setCursorIndex(modelInfo.getLastCursorIndex()); return; } int currentLine = modelInfo.getLineNumberOfIndex(modelInfo.cursorIndex); int charCount = 0; for (int i = 0; i <= currentLine; i++) charCount += modelInfo.textLayouts.get(i).getText().length(); int xPos = modelInfo.getXPosFromIndex(modelInfo.cursorIndex); int nextLineLength = modelInfo.textLayouts.get(currentLine + 1).getText().length(); int newCursorIndex = charCount + nextLineLength; if (modelInfo.isLastCharacterAReturn(newCursorIndex)) newCursorIndex if (modelInfo.getXPosFromIndex(newCursorIndex) < xPos) { modelInfo.setCursorIndex(newCursorIndex); } else { TextHitInfo hitInfo = modelInfo.textLayouts.get(currentLine + 1).hitTestChar(xPos, 5); newCursorIndex = hitInfo.getCharIndex() + charCount; if (modelInfo.isLastCharacterAReturn(newCursorIndex)) newCursorIndex modelInfo.setCursorIndex(newCursorIndex); } } protected boolean isAnExtraKey(int keyCode) { return keyCode == KeyEvent.VK_ENTER || keyCode == KeyEvent.VK_TAB; } protected void sendCursorToStartOfLine() { int currentLine = modelInfo.getLineNumberOfIndex(modelInfo.getCursorIndex()); if (currentLine == 0) { modelInfo.setCursorIndex(0); } else { modelInfo.setCursorIndex(modelInfo.getIndexOfLastCharInLine(currentLine - 1)); } } protected void sendCursorToEndOfLine() { int currentLine = modelInfo.getLineNumberOfIndex(modelInfo.getCursorIndex()); modelInfo.setCursorIndex(modelInfo.getIndexOfLastCharInLine(currentLine)); } }
package Main; import javafx.fxml.FXML; import javafx.geometry.Insets; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.layout.AnchorPane; import javafx.scene.paint.Color; import javafx.scene.text.Font; import java.util.Stack; import javafx.event.ActionEvent; public class MainController { Stack<Tab> tabs = new Stack<Tab>(); int counter = 0; @FXML private TabPane tabPane; @FXML private Font x3; @FXML private Color x4; @FXML void newProof(ActionEvent event) { Tab tab = new Tab(""+counter++); TableColumn tableColumnLeft = new TableColumn(); tableColumnLeft.setText("Expression"); tableColumnLeft.setMaxWidth(5000); tableColumnLeft.setMinWidth(10); tableColumnLeft.setEditable(true); //tableColumnLeft.setPrefWidth(356); TableColumn tableColumnRight = new TableColumn(); tableColumnRight.setText("Type"); tableColumnRight.setMaxWidth(5000); tableColumnRight.setMinWidth(10); tableColumnRight.setEditable(true); //tableColumnRight.setPrefWidth(356); TableView tableView = new TableView(); tableView.setPadding(new Insets(0, 0, 0, 0)); tableView.getColumns().addAll(tableColumnLeft, tableColumnRight); AnchorPane anchorPane = new AnchorPane(tableView); anchorPane.setPrefWidth(714); anchorPane.setPrefHeight(460); anchorPane.setPadding(new Insets(0, 0, 0, 0)); anchorPane.setScaleShape(true); anchorPane.setCacheShape(true); anchorPane.setCenterShape(true); tab.setContent(anchorPane); tabs.push(tab); tabPane.setPadding(new Insets(0, 0, 0, 0)); tabPane.getTabs().add(tabs.peek()); } @FXML void openInstructions(ActionEvent event) { } @FXML void ruleButtonPressed(ActionEvent event) { System.out.println("Yay!"); } @FXML void symbolButtonPressed(ActionEvent event) { } }
package com.vswamy.hackerranksolutions; import com.vswamy.hackerranksolutions.interfaces.Problem; import com.vswamy.hackerranksolutions.problems.*; /** * @author vswamy * Main class to run execute multiple problems */ public class Main { public static void main(String[] args) { Problem problem = new FindDigits(); problem.run(); return; } }
package com.atlassian.sal.refimpl.pluginsettings; import com.atlassian.sal.api.pluginsettings.PluginSettings; import com.atlassian.sal.api.pluginsettings.PluginSettingsFactory; import com.atlassian.sal.api.ApplicationProperties; import org.apache.log4j.Logger; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.AbstractMap; import java.util.Collections; import java.util.List; import java.util.Properties; import java.util.Set; /** * This implementation can be backed by a file on the file system. If a file in the current working directory called * "pluginsettings.xml" exists (can be overridden with system property sal.pluginsettings.store) exists, it loads and * persists all plugin settings to and from this file. If no file exists, plugin settings are purely in memory. */ public class RefimplPluginSettingsFactory implements PluginSettingsFactory { private static final String CHARLIE_KEYS = "charlie.keys"; private static final Logger log = Logger.getLogger(RefimplPluginSettingsFactory.class); private final Properties properties; private final File file; public RefimplPluginSettingsFactory(ApplicationProperties applicationProperties) { // Maintain backwards compatibility, check the old locations File file = new File(System.getProperty("sal.pluginsettings.store", "pluginsettings.xml")); boolean useMemoryStore = Boolean.valueOf(System.getProperty("sal.pluginsettings.memorystore", "false")); properties = new Properties(); if (useMemoryStore) { log.info("Using memory store for plugin settings"); file = null; } else if (!file.exists() || !file.canRead()) { // Use refapp home directory File dataDir = new File(applicationProperties.getHomeDirectory(), "data"); try { if (!dataDir.exists()) { dataDir.mkdirs(); } file = new File(dataDir, "pluginsettings.xml"); file.createNewFile(); } catch (IOException ioe) { log.error("Error creating plugin settings properties, using memory store", ioe); file = null; } } if (file != null && file.length() > 0) { InputStream is = null; try { is = new FileInputStream(file); properties.loadFromXML(is); } catch (Exception e) { log.error("Error loading plugin settings properties, using memory store", e); file = null; } finally { if (is != null) { try { is.close(); } catch (IOException ioe) { log.error("Error closing file", ioe); } } } } if (file != null) { // File is a new file log.info("Using " + file.getAbsolutePath() + " as plugin settings store"); } this.file = file; } public PluginSettings createSettingsForKey(String key) { if (key != null) { List<String> charlies = (List<String>) new RefimplPluginSettings(new SettingsMap(null)).get(CHARLIE_KEYS); if (charlies == null || !charlies.contains(key)) { throw new IllegalArgumentException("No Charlie with key " + key + " exists."); } } return new RefimplPluginSettings(new SettingsMap(key)); } public PluginSettings createGlobalSettings() { return createSettingsForKey(null); } @SuppressWarnings("AccessToStaticFieldLockedOnInstance") private synchronized void store() { if (file == null || !file.canWrite()) { // Read only settings return; } OutputStream os = null; try { os = new FileOutputStream(file); properties.storeToXML(os, "SAL Reference Implementation plugin settings"); } catch (IOException ioe) { log.error("Error storing properties", ioe); } finally { if (os != null) { try { os.close(); } catch (IOException ioe) { log.error("Error closing output stream", ioe); } } } } private class SettingsMap extends AbstractMap<String, String> { private final String settingsKey; private SettingsMap(String settingsKey) { if (settingsKey == null) { this.settingsKey = "global."; } else { this.settingsKey = "keys." + settingsKey + "."; } } public Set<Entry<String, String>> entrySet() { // Not used return Collections.emptySet(); } public String get(Object key) { return properties.getProperty(settingsKey + key); } public String put(String key, String value) { String result = (String) properties.setProperty(settingsKey + key, value); store(); return result; } public String remove(Object key) { String result = (String) properties.remove(settingsKey + key); store(); return result; } } }