answer
stringlengths
17
10.2M
package org.cactoos.text; import org.cactoos.Func; import org.cactoos.Text; import org.cactoos.scalar.Ternary; /** * Text in capitalized case, * changed the first character to title case as per {@link Character#toTitleCase(int)}, * no other characters are changed. * * @since 0.46 */ public final class Capitalized extends TextEnvelope { /** * Ctor. * * @param text The text */ public Capitalized(final String text) { this(new TextOf(text)); } /** * Ctor. * * @param text The text */ public Capitalized(final Text text) { super( new TextOf( () -> { final Func<Text, Text> capitalize = cap -> { final Text titled = new TextOf( Character.toChars( Character.toTitleCase( cap.asString().codePointAt(0) ) ) ); return new Ternary<Text>( new StartsWith(cap, titled), () -> cap, () -> new Joined( "", titled, new Sub(text, 1) ) ) .value(); }; return new Ternary<Text>( new IsBlank(text), () -> text, () -> capitalize.apply(text) ).value().asString(); })); } }
package org.cojen.tupl.rows; import java.io.IOException; import java.lang.invoke.VarHandle; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.NavigableMap; import java.util.NavigableSet; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import java.util.function.Consumer; import java.util.function.Supplier; import org.cojen.tupl.CorruptDatabaseException; import org.cojen.tupl.Cursor; import org.cojen.tupl.DeletedIndexException; import org.cojen.tupl.DurabilityMode; import org.cojen.tupl.EventListener; import org.cojen.tupl.EventType; import org.cojen.tupl.Index; import org.cojen.tupl.LockFailureException; import org.cojen.tupl.LockMode; import org.cojen.tupl.Table; import org.cojen.tupl.Transaction; import org.cojen.tupl.UniqueConstraintException; import org.cojen.tupl.View; import org.cojen.tupl.core.CoreDatabase; import org.cojen.tupl.core.LHashTable; import org.cojen.tupl.core.RowPredicateLock; import org.cojen.tupl.core.ScanVisitor; import org.cojen.tupl.util.Runner; import static org.cojen.tupl.rows.RowUtils.*; /** * Main class for managing row persistence via tables. * * @author Brian S O'Neill */ public class RowStore { private final WeakReference<RowStore> mSelfRef; final CoreDatabase mDatabase; /* Schema metadata for all types. (indexId) -> int current schemaVersion, ColumnSet[] alternateKeys, (a type of secondary index) ColumnSet[] secondaryIndexes (indexId, schemaVersion) -> primary ColumnSet (indexId, hash(primary ColumnSet)) -> schemaVersion[] // hash collision chain (indexId, 0, K_SECONDARY, descriptor) -> secondaryIndexId, state (indexId, 0, K_TYPE_NAME) -> current type name (UTF-8) (secondaryIndexId, 0, K_DROPPED) -> primaryIndexId, descriptor (0L, indexId, taskType) -> ... workflow task against an index The schemaVersion is limited to 2^31, and the hash is encoded with bit 31 set, preventing collisions. In addition, schemaVersion cannot be 0, and so the extended keys won't collide, although the longer overall key length prevents collisions as well. Because indexId 0 is reserved (for the registry), it won't be used for row storage, and so it can be used for tracking workflow tasks. */ private final Index mSchemata; private final WeakCache<Index, TableManager<?>> mTableManagers; private final LHashTable.Obj<RowPredicateLock<?>> mIndexLocks; // Used by tests. volatile boolean mStallTasks; // Extended key for referencing secondary indexes. private static final int K_SECONDARY = 1; // Extended key to store the fully qualified type name. private static final int K_TYPE_NAME = 2; // Extended key to track secondary indexes which are being dropped. private static final int K_DROPPED = 3; private static final int TASK_DELETE_SCHEMA = 1, TASK_NOTIFY_SCHEMA = 2; public RowStore(CoreDatabase db, Index schemata) throws IOException { mSelfRef = new WeakReference<>(this); mDatabase = db; mSchemata = schemata; mTableManagers = new WeakCache<>(); mIndexLocks = new LHashTable.Obj<>(8); registerToUpdateSchemata(); // Finish any tasks left over from when the RowStore was last used. Call this from a // separate thread to unblock LocalDatabase, which is holding mOpenTreesLatch when // constructing this RowStore instance. Runner.start(() -> { try { finishAllWorkflowTasks(); } catch (Throwable e) { uncaught(e); } }); } WeakReference<RowStore> ref() { return mSelfRef; } public Index schemata() { return mSchemata; } /** * Scans the schemata and all table secondary indexes. Doesn't scan table primary indexes. */ public void scanAllIndexes(ScanVisitor visitor) throws IOException { visitor.apply(mSchemata); try (Cursor c = mSchemata.newCursor(null)) { byte[] key; for (c.first(); (key = c.key()) != null; ) { if (key.length <= 8) { c.next(); continue; } long indexId = decodeLongBE(key, 0); if (indexId == 0 || decodeIntBE(key, 8) != 0 || decodeIntBE(key, 8 + 4) != K_SECONDARY) { if (++indexId == 0) { break; } c.findNearbyGe(key(indexId)); } else { Index secondaryIndex = mDatabase.indexById(decodeLongLE(c.value(), 0)); if (secondaryIndex != null) { visitor.apply(secondaryIndex); } c.next(); } } } } /** * Try to find a table which is bound to the given index, and return a partially decoded * row. Returns null if not found. */ public Object asRow(Index ix, byte[] key) { var manager = (TableManager<?>) mTableManagers.get(ix); if (manager != null) { AbstractTable<?> table = manager.mostRecentTable(); if (table != null) { try { return table.asRow(key); } catch (Throwable e) { // Ignore any decoding errors. } } } return null; } private TableManager<?> tableManager(Index ix) { var manager = (TableManager<?>) mTableManagers.get(ix); if (manager == null) { synchronized (mTableManagers) { manager = (TableManager<?>) mTableManagers.get(ix); if (manager == null) { manager = new TableManager<>(ix); mTableManagers.put(ix, manager); } } } return manager; } /** * @return null if predicate lock is unsupported */ <R> RowPredicateLock<R> indexLock(Index index) { return indexLock(index.id()); } /** * @return null if predicate lock is unsupported */ @SuppressWarnings("unchecked") <R> RowPredicateLock<R> indexLock(long indexId) { var lock = mIndexLocks.getValue(indexId); if (lock == null) { lock = makeIndexLock(indexId); } return (RowPredicateLock<R>) lock; } private RowPredicateLock<?> makeIndexLock(long indexId) { synchronized (mIndexLocks) { var lock = mIndexLocks.getValue(indexId); if (lock == null) { lock = mDatabase.newRowPredicateLock(indexId); VarHandle.storeStoreFence(); mIndexLocks.insert(indexId).value = lock; } return lock; } } private void removeIndexLock(long indexId) { synchronized (mIndexLocks) { mIndexLocks.remove(indexId); } } @SuppressWarnings("unchecked") public <R> Table<R> asTable(Index ix, Class<R> type) throws IOException { return ((TableManager<R>) tableManager(ix)).asTable(this, ix, type); } /** * Called by TableManager via asTable. * * @param doubleCheck invoked with schema lock held, to double check before making the table * @param consumer called with lock held, to accept the newly made table */ @SuppressWarnings("unchecked") <R> AbstractTable<R> makeTable(TableManager<R> manager, Index ix, Class<R> type, Supplier<AbstractTable<R>> doubleCheck, Consumer<AbstractTable<R>> consumer) throws IOException { // Throws an exception if type is malformed. RowInfo info = RowInfo.find(type); AbstractTable<R> table; // Can use NO_FLUSH because transaction will be only used for reading data. Transaction txn = mSchemata.newTransaction(DurabilityMode.NO_FLUSH); try { txn.lockMode(LockMode.REPEATABLE_READ); // Acquire the lock, but don't check for schema changes just yet. RowInfo currentInfo = decodeExisting(txn, null, ix.id()); if (doubleCheck != null && (table = doubleCheck.get()) != null) { // Found the table, so just use that. return table; } // With a txn lock held, check if the schema has changed incompatibly. if (currentInfo != null) { checkSchema(type.getName(), currentInfo, info); } RowPredicateLock<R> indexLock = indexLock(ix); try { var mh = new TableMaker(this, type, info.rowGen(), ix.id(), indexLock != null).finish(); table = (AbstractTable) mh.invoke(manager, ix, indexLock); } catch (Throwable e) { throw rethrow(e); } if (consumer != null) { consumer.accept(table); } } finally { txn.reset(); } // Attempt to eagerly update schema metadata and secondary indexes. try { // Pass false for notify because examineSecondaries will be invoked by caller. schemaVersion(info, true, ix.id(), false); } catch (IOException e) { // Ignore and try again when storing rows or when the leadership changes. } return table; } private static boolean checkSchema(String typeName, RowInfo oldInfo, RowInfo newInfo) { if (oldInfo.matches(newInfo) && matches(oldInfo.alternateKeys, newInfo.alternateKeys) && matches(oldInfo.secondaryIndexes, newInfo.secondaryIndexes)) { return true; } if (!oldInfo.keyColumns.equals(newInfo.keyColumns)) { // FIXME: Better exception. throw new IllegalStateException("Cannot alter primary key: " + typeName); } // Checks for alternate keys and secondary indexes is much more strict. Any change to // a column used by one is considered incompatible. checkIndexes(typeName, "alternate keys", oldInfo.alternateKeys, newInfo.alternateKeys); checkIndexes(typeName, "secondary indexes", oldInfo.secondaryIndexes, newInfo.secondaryIndexes); return false; } /** * Checks if the set of indexes has changed incompatibly. */ private static void checkIndexes(String typeName, String which, NavigableSet<ColumnSet> oldSet, NavigableSet<ColumnSet> newSet) { // Quick check. if (oldSet.isEmpty() || newSet.isEmpty() || matches(oldSet, newSet)) { return; } // Create mappings keyed by index descriptor, which isn't the most efficient approach, // but it matches how secondaries are persisted. So it's safe and correct. The type // descriptor prefix is fake, but that's okay. This isn't actually persisted. var encoder = new Encoder(64); NavigableMap<byte[], ColumnSet> oldMap = indexMap('_', encoder, oldSet); NavigableMap<byte[], ColumnSet> newMap = indexMap('_', encoder, newSet); Iterator<Map.Entry<byte[], ColumnSet>> oldIt = oldMap.entrySet().iterator(); Iterator<Map.Entry<byte[], ColumnSet>> newIt = newMap.entrySet().iterator(); Map.Entry<byte[], ColumnSet> oldEntry = null, newEntry = null; while (true) { if (oldEntry == null) { if (!oldIt.hasNext()) { break; } oldEntry = oldIt.next(); } if (newEntry == null) { if (!newIt.hasNext()) { break; } newEntry = newIt.next(); } int cmp = Arrays.compareUnsigned(oldEntry.getKey(), newEntry.getKey()); if (cmp == 0) { // Same descriptor, so check if the index has changed. if (!oldEntry.getValue().matches(newEntry.getValue())) { // FIXME: Better exception. throw new IllegalStateException("Cannot alter " + which + ": " + typeName); } oldEntry = null; newEntry = null; } else if (cmp < 0) { // This index will be dropped, so not an incompatibility. oldEntry = null; } else { // This index will be added, so not an incompatibility. newEntry = null; } } } private static boolean matches(NavigableSet<ColumnSet> a, NavigableSet<ColumnSet> b) { var ia = a.iterator(); var ib = b.iterator(); while (ia.hasNext()) { if (!ib.hasNext() || !ia.next().matches(ib.next())) { return false; } } return !ib.hasNext(); } private static NavigableMap<byte[], ColumnSet> indexMap(char type, Encoder encoder, NavigableSet<ColumnSet> set) { var map = new TreeMap<byte[], ColumnSet>(Arrays::compareUnsigned); for (ColumnSet cs : set) { map.put(EncodedRowInfo.encodeDescriptor(type, encoder, cs), cs); } return map; } public <R> Table<R> indexTable(AbstractTable<R> primaryTable, boolean alt, String... columns) throws IOException { Object key = ArrayKey.make(alt, columns); WeakCache<Object, AbstractTable<R>> indexTables = primaryTable.mTableManager.indexTables(); AbstractTable<R> table = indexTables.get(key); if (table == null) { synchronized (indexTables) { table = indexTables.get(key); if (table == null) { table = makeIndexTable(indexTables, primaryTable, alt, columns); if (table == null) { throw new IllegalStateException ((alt ? "Alternate key" : "Secondary index") + " not found: " + Arrays.toString(columns)); } indexTables.put(key, table); } } } return table; } @SuppressWarnings("unchecked") private <R> AbstractTable<R> makeIndexTable(WeakCache<Object, AbstractTable<R>> indexTables, AbstractTable<R> primaryTable, boolean alt, String... columns) throws IOException { Class<R> rowType = primaryTable.rowType(); RowInfo rowInfo = RowInfo.find(rowType); ColumnSet cs = rowInfo.examineIndex(null, columns, alt); if (cs == null) { throw new IllegalStateException ((alt ? "Alternate key" : "Secondary index") + " not found: " + Arrays.toString(columns)); } var encoder = new Encoder(columns.length * 16); char type = alt ? 'A' : 'I'; byte[] search = EncodedRowInfo.encodeDescriptor(type, encoder, cs); View secondariesView = viewExtended(primaryTable.mSource.id(), K_SECONDARY); secondariesView = secondariesView.viewPrefix(new byte[] {(byte) type}, 0); // Identify the first match. Ascending order is encoded with bit 7 clear (see // ColumnInfo), and so matches for ascending order are generally found first when an // unspecified order was given. long indexId; RowInfo indexRowInfo; byte[] descriptor; find: { try (Cursor c = secondariesView.newCursor(null)) { for (c.first(); c.key() != null; c.next()) { if (!descriptorMatches(search, c.key())) { continue; } if (c.value()[8] != 'A') { // Not active. return null; } indexId = decodeLongLE(c.value(), 0); indexRowInfo = indexRowInfo(RowInfo.find(rowType), c.key()); descriptor = c.key(); break find; } } return null; } Object key = ArrayKey.make(descriptor); AbstractTable<R> table = indexTables.get(key); if (table != null) { return table; } Index ix = mDatabase.indexById(indexId); if (ix == null) { return null; } // Indexes don't have indexes. indexRowInfo.alternateKeys = Collections.emptyNavigableSet(); indexRowInfo.secondaryIndexes = Collections.emptyNavigableSet(); RowPredicateLock<R> indexLock = indexLock(ix); try { var maker = new TableMaker(this, rowType, rowInfo.rowGen(), indexRowInfo.rowGen(), descriptor, ix.id(), indexLock != null); var mh = maker.finish(); table = (AbstractTable<R>) mh.invoke(primaryTable.mTableManager, ix, indexLock); } catch (Throwable e) { throw rethrow(e); } indexTables.put(key, table); return table; } /** * Compares descriptors as encoded by EncodedRowInfo.encodeDescriptor. Column types are * ignored except for comparing key column ordering. * * @param search typeCode can be -1 for unspecified orderings * @param found should not have any unspecified orderings */ private static boolean descriptorMatches(byte[] search, byte[] found) { if (search.length != found.length) { return false; } int offset = 1; // skip the type prefix for (int part=1; part<=2; part++) { // part 1 is keys section, part 2 is values section int numColumns = decodePrefixPF(search, offset); if (numColumns != decodePrefixPF(found, offset)) { return false; } offset += lengthPrefixPF(numColumns); for (int i=0; i<numColumns; i++) { if (part == 1) { // Only examine the key column ordering. int searchTypeCode = decodeIntBE(search, offset) ^ (1 << 31); if (searchTypeCode != -1) { // is -1 when unspecified int foundTypeCode = decodeIntBE(found, offset) ^ (1 << 31); if ((searchTypeCode & ColumnInfo.TYPE_DESCENDING) != (foundTypeCode & ColumnInfo.TYPE_DESCENDING)) { // Ordering doesn't match. return false; } } } else { // Ignore value column type codes. } offset += 4; // Now compare the column name. int nameLength = decodePrefixPF(search, offset); if (nameLength != decodePrefixPF(found, offset)) { return false; } if (!Arrays.equals(search, offset, offset + nameLength, found, offset, offset + nameLength)) { return false; } offset += lengthPrefixPF(nameLength); offset += nameLength; } } return offset == search.length; // should always be true unless descriptor is malformed } private void registerToUpdateSchemata() { // The second task is invoked when leadership is lost, which sets things up for when // leadership is acquired again. mDatabase.uponLeader(this::updateSchemata, this::registerToUpdateSchemata); } /** * Called when database has become the leader, providing an opportunity to update the * schema for all tables currently in use. */ private void updateSchemata() { List<TableManager<?>> managers = mTableManagers.copyValues(); if (managers != null) { try { for (var manager : managers) { AbstractTable<?> table = manager.mostRecentTable(); if (table != null) { RowInfo info = RowInfo.find(table.rowType()); long indexId = manager.mPrimaryIndex.id(); schemaVersion(info, true, indexId, true); // notify = true } } } catch (IOException e) { // Ignore and try again when storing rows or when the leadership changes. } catch (Throwable e) { uncaught(e); } } } private void uncaught(Throwable e) { if (!mDatabase.isClosed()) { RowUtils.uncaught(e); } } /** * Called in response to a redo log message. Implementation should examine the set of * secondary indexes associated with the table and perform actions to build or drop them. */ public void notifySchema(long indexId) throws IOException { byte[] taskKey = newTaskKey(TASK_NOTIFY_SCHEMA, indexId); Transaction txn = beginWorkflowTask(taskKey); // Test mode only. if (mStallTasks) { txn.reset(); return; } // Must launch from a separate thread because locks are held by this thread until the // transaction finishes. Runner.start(() -> { try { try { doNotifySchema(null, null, indexId); mSchemata.delete(txn, taskKey); } finally { txn.reset(); } } catch (Throwable e) { uncaught(e); } }); } /** * @param txn if non-null, pass to mSchemata.delete when false is returned * @param taskKey is non-null if this is a recovered workflow task * @return true if workflow task (if any) can be immediately deleted */ private boolean doNotifySchema(Transaction txn, byte[] taskKey, long indexId) throws IOException { Index ix = mDatabase.indexById(indexId); // Index won't be found if it was concurrently dropped. if (ix != null) { examineSecondaries(tableManager(ix)); } return true; } /** * Called in response to a redo log message. * * @return null or a Lock, or an array of Locks * @see RowPredicateLock#acquireLocksNoPush */ public Object acquireLocksNoPush(Transaction txn, long indexId, byte[] key, byte[] value) throws LockFailureException { return indexLock(indexId).acquireLocksNoPush(txn, key, value); } /** * Called when an index is deleted. If the indexId refers to a known secondary index, then * it gets deleted by the returned Runnable. Otherwise, null is returned and the caller * should perform the delete. * * @param taskFactory returns a task which performs the actual delete */ public Runnable redoDeleteIndex(long indexId, Supplier<Runnable> taskFactory) throws IOException { byte[] value = viewExtended(indexId, K_DROPPED).load(Transaction.BOGUS, EMPTY_BYTES); if (value == null) { return null; } long primaryIndexId = decodeLongLE(value, 0); byte[] descriptor = Arrays.copyOfRange(value, 8, value.length); return deleteIndex(primaryIndexId, indexId, descriptor, null, taskFactory); } /** * Also called from TableManager.asTable. */ <R> void examineSecondaries(TableManager<R> manager) throws IOException { long indexId = manager.mPrimaryIndex.id(); // Can use NO_FLUSH because transaction will be only used for reading data. Transaction txn = mDatabase.newTransaction(DurabilityMode.NO_FLUSH); try { txn.lockTimeout(-1, null); // Lock to prevent changes and to allow one thread to call examineSecondaries. mSchemata.lockUpgradable(txn, key(indexId)); txn.lockMode(LockMode.READ_COMMITTED); manager.update(this, txn, viewExtended(indexId, K_SECONDARY)); } finally { txn.reset(); } } /** * Called by IndexBackfill when an index backfill has finished. */ void activateSecondaryIndex(IndexBackfill backfill, boolean success) throws IOException { long indexId = backfill.mManager.mPrimaryIndex.id(); long secondaryId = backfill.mSecondaryIndex.id(); boolean activated = false; // Use NO_REDO it because this method can be called by a replica. Transaction txn = mDatabase.newTransaction(DurabilityMode.NO_REDO); try { txn.lockTimeout(-1, null); // Lock to prevent changes and to allow one thread to call examineSecondaries. mSchemata.lockUpgradable(txn, key(indexId)); View secondariesView = viewExtended(indexId, K_SECONDARY); if (success) { try (Cursor c = secondariesView.newCursor(txn)) { c.find(backfill.mSecondaryDescriptor); byte[] value = c.value(); if (value != null && value[8] == 'B' && decodeLongLE(value, 0) == secondaryId) { // Switch to "active" state. value[8] = 'A'; c.store(value); activated = true; } } } backfill.mManager.update(this, txn, secondariesView); txn.commit(); } finally { txn.reset(); } if (activated) { // With NO_REDO, need a checkpoint to ensure durability. If the database is closed // before it finishes, the whole backfill process starts over when the database is // later reopened. mDatabase.checkpoint(); } } /** * Should be called when the index is being dropped. Does nothing if index wasn't used for * storing rows. * * This method should be called with the shared commit lock held, and it * non-transactionally stores task metadata which indicates that the schema should be * deleted. The caller should run the returned object without holding the commit lock. * * If no checkpoint occurs, then the expectation is that the deleteSchema method is called * again, which allows the deletion to run again. This means that deleteSchema should * only really be called from removeFromTrash, which automatically runs again if no * checkpoint occurs. * * @param indexKey long index id, big-endian encoded * @return an optional task to run without commit lock held */ public Runnable deleteSchema(byte[] indexKey) throws IOException { try (Cursor c = mSchemata.viewPrefix(indexKey, 0).newCursor(Transaction.BOGUS)) { c.autoload(false); c.first(); if (c.key() == null) { return null; } } byte[] taskKey = newTaskKey(TASK_DELETE_SCHEMA, indexKey); Transaction txn = beginWorkflowTask(taskKey); // Test mode only. if (mStallTasks) { txn.reset(); return null; } return () -> { try { try { doDeleteSchema(null, null, indexKey); mSchemata.delete(txn, taskKey); } finally { txn.reset(); } } catch (IOException e) { throw rethrow(e); } }; } /** * @param txn if non-null, pass to mSchemata.delete when false is returned * @param taskKey is non-null if this is a recovered workflow task * @param indexKey long index id, big-endian encoded * @return true if workflow task (if any) can be immediately deleted */ private boolean doDeleteSchema(Transaction txn, byte[] taskKey, byte[] indexKey) throws IOException { long primaryIndexId = decodeLongBE(indexKey, 0); removeIndexLock(primaryIndexId); List<Runnable> deleteTasks = null; try (Cursor c = mSchemata.viewPrefix(indexKey, 0).newCursor(Transaction.BOGUS)) { c.autoload(false); byte[] key; for (c.first(); (key = c.key()) != null; c.next()) { if (key.length >= (8 + 4 + 4) && decodeIntBE(key, 8) == 0 && decodeIntBE(key, 8 + 4) == K_SECONDARY) { // Delete a secondary index. c.load(); // autoload is false, so load the value now byte[] value = c.value(); if (value != null && value.length >= 8) { Index secondaryIndex = mDatabase.indexById(decodeLongLE(c.value(), 0)); if (secondaryIndex != null) { byte[] descriptor = Arrays.copyOfRange(key, 8 + 4 + 4, key.length); Runnable task = deleteIndex (primaryIndexId, 0, descriptor, secondaryIndex, null); if (deleteTasks == null) { deleteTasks = new ArrayList<>(); } deleteTasks.add(task); } } } c.delete(); } } if (deleteTasks == null) { return true; } final var tasks = deleteTasks; Runner.start(() -> { try { try { for (Runnable task : tasks) { task.run(); } mSchemata.delete(txn, taskKey); txn.commit(); } finally { txn.reset(); } } catch (Throwable e) { uncaught(e); } }); return false; } /** * @param indexKey long index id, big-endian encoded */ private byte[] newTaskKey(int taskType, byte[] indexKey) { var taskKey = new byte[8 + 8 + 4]; System.arraycopy(indexKey, 0, taskKey, 8, 8); encodeIntBE(taskKey, 8 + 8, taskType); return taskKey; } private byte[] newTaskKey(int taskType, long indexKey) { var taskKey = new byte[8 + 8 + 4]; encodeLongBE(taskKey, 8, indexKey); encodeIntBE(taskKey, 8 + 8, taskType); return taskKey; } /** * @return a transaction to reset when task is done */ private Transaction beginWorkflowTask(byte[] taskKey) throws IOException { // Use a transaction to lock the task, and so finishAllWorkflowTasks will skip it. Transaction txn = mDatabase.newTransaction(DurabilityMode.NO_REDO); try { mSchemata.lockUpgradable(txn, taskKey); mSchemata.store(Transaction.BOGUS, taskKey, EMPTY_BYTES); } catch (Throwable e) { txn.reset(e); throw e; } return txn; } // Is package-private to be accessible for testing. void finishAllWorkflowTasks() throws IOException { // Use transaction locks to identity tasks which should be skipped. Transaction txn = mDatabase.newTransaction(DurabilityMode.NO_REDO); try { txn.lockMode(LockMode.UNSAFE); // don't auto acquire locks; is auto-commit var prefix = new byte[8]; // 0L is the prefix for all workflow tasks try (Cursor c = mSchemata.viewPrefix(prefix, 0).newCursor(txn)) { c.autoload(false); for (c.first(); c.key() != null; c.next()) { if (!txn.tryLockUpgradable(mSchemata.id(), c.key(), 0).isHeld()) { // Skip it. continue; } // Load and check the value again, in case another thread deleted it // before the lock was acquired. c.load(); byte[] taskValue = c.value(); if (taskValue != null) { if (runRecoveredWorkflowTask(txn, c.key(), taskValue)) { c.delete(); } else { // Need a replacement transaction. txn = mDatabase.newTransaction(DurabilityMode.NO_REDO); txn.lockMode(LockMode.UNSAFE); c.link(txn); continue; } } txn.unlock(); } } } finally { txn.reset(); } } /** * @param txn must pass to mSchemata.delete when false is returned * @param taskKey (0L, indexId, taskType) * @return true if task can be immediately deleted */ private boolean runRecoveredWorkflowTask(Transaction txn, byte[] taskKey, byte[] taskValue) throws IOException { var indexKey = new byte[8]; System.arraycopy(taskKey, 8, indexKey, 0, 8); int taskType = decodeIntBE(taskKey, 8 + 8); return switch (taskType) { default -> throw new CorruptDatabaseException("Unknown task: " + taskType); case TASK_DELETE_SCHEMA -> doDeleteSchema(txn, taskKey, indexKey); case TASK_NOTIFY_SCHEMA -> doNotifySchema(txn, taskKey, decodeLongBE(indexKey, 0)); }; } /** * @param secondaryIndexId ignored when secondaryIndex is provided * @param secondaryIndex required when no taskFactory is provided * @param taskFactory can be null when a secondaryIndex is provided */ private Runnable deleteIndex(long primaryIndexId, long secondaryIndexId, byte[] descriptor, Index secondaryIndex, Supplier<Runnable> taskFactory) throws IOException { if (secondaryIndex != null) { secondaryIndexId = secondaryIndex.id(); } // Remove it from the cache. tableManager(mDatabase.indexById(primaryIndexId)).removeFromIndexTables(secondaryIndexId); EventListener listener = mDatabase.eventListener(); String eventStr; if (listener == null) { eventStr = null; } else { SecondaryInfo secondaryInfo = null; try { RowInfo primaryInfo = decodeExisting(null, null, primaryIndexId); secondaryInfo = indexRowInfo(primaryInfo, descriptor); } catch (Exception e) { } if (secondaryInfo == null) { eventStr = String.valueOf(secondaryIndexId); } else { eventStr = secondaryInfo.eventString(); } } RowPredicateLock<?> lock = indexLock(secondaryIndexId); if (lock == null) { if (listener != null) { listener.notify(EventType.TABLE_INDEX_INFO, "Dropping %1$s", eventStr); } Runnable task; if (taskFactory == null) { task = mDatabase.deleteIndex(secondaryIndex); } else { task = taskFactory.get(); } if (listener == null) { return task; } return () -> { task.run(); listener.notify(EventType.TABLE_INDEX_INFO, "Finished dropping %1$s", eventStr); }; } final long fSecondaryIndexId = secondaryIndexId; return () -> { try { Transaction txn = mDatabase.newTransaction(); try { // Acquire the predicate lock to wait for all scans to complete, and to // prevent new ones from starting. txn.lockTimeout(-1, null); Runnable mustWait = null; if (listener != null) { mustWait = () -> listener.notify (EventType.TABLE_INDEX_INFO, "Waiting to drop %1$s", eventStr); } lock.withExclusiveNoRedo(txn, mustWait, () -> { try { if (listener != null) { listener.notify(EventType.TABLE_INDEX_INFO, "Dropping %1$s", eventStr); } Runnable task; if (taskFactory == null) { task = mDatabase.deleteIndex(secondaryIndex); } else { task = taskFactory.get(); } task.run(); if (listener != null) { listener.notify(EventType.TABLE_INDEX_INFO, "Finished dropping %1$s", eventStr); } } catch (Throwable e) { uncaught(e); } }); txn.commit(); } finally { txn.exit(); } removeIndexLock(fSecondaryIndexId); } catch (Throwable e) { uncaught(e); } }; } /** * Returns the schema version for the given row info, creating a new version if necessary. * * @param mostRecent true if the given info is known to be the most recent definition * @param notify true to call notifySchema if anything changed */ int schemaVersion(RowInfo info, boolean mostRecent, long indexId, boolean notify) throws IOException { if (mDatabase.indexById(indexId) == null) { throw new DeletedIndexException(); } int schemaVersion; Map<Index, byte[]> secondariesToDelete = null; Transaction txn = mSchemata.newTransaction(DurabilityMode.SYNC); try (Cursor current = mSchemata.newCursor(txn)) { txn.lockTimeout(-1, null); current.find(key(indexId)); if (current.value() != null) { // Check if the schema has changed. schemaVersion = decodeIntLE(current.value(), 0); RowInfo currentInfo = decodeExisting (txn, info.name, indexId, current.value(), schemaVersion); if (checkSchema(info.name, currentInfo, info)) { // Exactly the same, so don't create a new version. return schemaVersion; } if (!mostRecent) { RowInfo info2 = info.withIndexes(currentInfo); if (info2 != info) { // Don't change the indexes. info = info2; if (checkSchema(info.name, currentInfo, info)) { // Don't create a new version. return schemaVersion; } } } } // Find an existing schemaVersion or create a new one. final boolean isTempIndex = mDatabase.isInTrash(txn, indexId); if (isTempIndex) { // Temporary trees are always in the trash, and they don't replicate. For this // reason, don't attempt to replicate schema metadata either. txn.durabilityMode(DurabilityMode.NO_REDO); } final var encoded = new EncodedRowInfo(info); assignVersion: try (Cursor byHash = mSchemata.newCursor(txn)) { byHash.find(key(indexId, encoded.primaryHash | (1 << 31))); byte[] schemaVersions = byHash.value(); if (schemaVersions != null) { for (int pos=0; pos<schemaVersions.length; pos+=4) { schemaVersion = decodeIntLE(schemaVersions, pos); RowInfo existing = decodeExisting (txn, info.name, indexId, null, schemaVersion); if (info.matches(existing)) { break assignVersion; } } } // Create a new version. View versionView = mSchemata.viewGt(key(indexId)).viewLt(key(indexId, 1 << 31)); try (Cursor highest = versionView.newCursor(txn)) { highest.autoload(false); highest.last(); if (highest.value() == null) { // First version. schemaVersion = 1; } else { byte[] key = highest.key(); schemaVersion = decodeIntBE(key, key.length - 4) + 1; } highest.findNearby(key(indexId, schemaVersion)); highest.store(encoded.primaryData); } if (schemaVersions == null) { schemaVersions = new byte[4]; } else { schemaVersions = Arrays.copyOfRange (schemaVersions, 0, schemaVersions.length + 4); } encodeIntLE(schemaVersions, schemaVersions.length - 4, schemaVersion); byHash.store(schemaVersions); } encodeIntLE(encoded.currentData, 0, schemaVersion); current.store(encoded.currentData); // Store the type name, which is usually the same as the class name. In case the // table isn't currently open, this name can be used for reporting background // status updates. Although the index name could be used, it's not required to be // the same as the class name. View nameView = viewExtended(indexId, K_TYPE_NAME); try (Cursor c = nameView.newCursor(txn)) { c.find(EMPTY_BYTES); byte[] nameBytes = encodeStringUTF(info.name); if (!Arrays.equals(nameBytes, c.value())) { c.store(nameBytes); } } // Start with the full set of secondary descriptors and later prune it down to // those that need to be created. TreeSet<byte[]> secondaries = encoded.secondaries; // Access a view of persisted secondary descriptors to index ids and states. View secondariesView = viewExtended(indexId, K_SECONDARY); // Find and update secondary indexes that should be deleted. TableManager<?> manager = null; try (Cursor c = secondariesView.newCursor(txn)) { byte[] key; for (c.first(); (key = c.key()) != null; c.next()) { byte[] value = c.value(); Index secondaryIndex = mDatabase.indexById(decodeLongLE(value, 0)); if (secondaryIndex == null) { c.store(null); // already deleted, so remove the entry } else if (!secondaries.contains(key)) { if (value[8] != 'D') { value[8] = 'D'; // "deleting" state c.store(value); } // Encode primaryIndexId and secondary descriptor. This entry is only // required with replication, allowing it to quickly identify a deleted // index as being a secondary index. This entry is deleted when // doDeleteSchema is called. var droppedEntry = new byte[8 + key.length]; encodeLongLE(droppedEntry, 0, indexId); System.arraycopy(key, 0, droppedEntry, 8, key.length); View droppedView = viewExtended(secondaryIndex.id(), K_DROPPED); droppedView.store(txn, EMPTY_BYTES, droppedEntry); if (manager == null) { manager = tableManager(mDatabase.indexById(indexId)); } // This removes entries from a cache, so not harmful if txn fails. manager.removeFromIndexTables(secondaryIndex.id()); if (secondariesToDelete == null) { secondariesToDelete = new LinkedHashMap<>(); } secondariesToDelete.put(secondaryIndex, c.key()); } } } // Find and update secondary indexes to create. try (Cursor c = secondariesView.newCursor(txn)) { Iterator<byte[]> it = secondaries.iterator(); while (it.hasNext()) { c.findNearby(it.next()); byte[] value = c.value(); if (value != null) { // Secondary index already exists. it.remove(); // If state is "deleting", switch it to "backfill". if (value[8] == 'D') { value[8] = 'B'; c.store(value); } } else if (isTempIndex) { // Secondary index doesn't exist, but temporary ones can be // immediately created because they're not replicated. it.remove(); value = new byte[8 + 1]; encodeLongLE(value, 0, mDatabase.newTemporaryIndex().id()); value[8] = 'B'; // "backfill" state c.store(value); } } } // The newly created index ids are copied into the array. Note that the array can // be empty, in which case calling createSecondaryIndexes is still necessary for // informing any replicas that potential changes have been made. The state of some // secondary indexes might have changed from "backfill" to "deleting", or vice // versa. If nothing changed, there's no harm in sending the notification anyhow. var ids = new long[secondaries.size()]; // Transaction is committed as a side-effect. mDatabase.createSecondaryIndexes(txn, indexId, ids, () -> { try { int i = 0; for (byte[] desc : secondaries) { byte[] value = new byte[8 + 1]; encodeLongLE(value, 0, ids[i++]); value[8] = 'B'; // "backfill" state if (!secondariesView.insert(txn, desc, value)) { // Not expected. throw new UniqueConstraintException(); } } } catch (IOException e) { rethrow(e); } }); } finally { txn.reset(); } if (secondariesToDelete != null) { for (var entry : secondariesToDelete.entrySet()) { try { Index secondaryIndex = entry.getKey(); byte[] descriptor = entry.getValue(); Runner.start(deleteIndex(indexId, 0, descriptor, secondaryIndex, null)); } catch (IOException e) { // Assume leadership was lost. } } } if (notify) { // We're currently the leader, and so this method must be invoked directly. notifySchema(indexId); } return schemaVersion; } /** * Finds a RowInfo for a specific schemaVersion. If not the same as the current version, * the alternateKeys and secondaryIndexes will be null (not just empty sets). * * If the given schemaVersion is 0, then the returned RowInfo only consists a primary key * and no value columns. * * @param rowType can pass null if not available (unless schemaVersion is 0) * @throws CorruptDatabaseException if not found */ RowInfo rowInfo(Class<?> rowType, long indexId, int schemaVersion) throws IOException, CorruptDatabaseException { if (schemaVersion == 0) { // No value columns to decode, and the primary key cannot change. RowInfo fullInfo = RowInfo.find(rowType); if (fullInfo.valueColumns.isEmpty()) { return fullInfo; } RowInfo info = new RowInfo(fullInfo.name); info.keyColumns = fullInfo.keyColumns; info.valueColumns = Collections.emptyNavigableMap(); info.allColumns = new TreeMap<>(info.keyColumns); return info; } // Can use NO_FLUSH because transaction will be only used for reading data. Transaction txn = mSchemata.newTransaction(DurabilityMode.NO_FLUSH); txn.lockMode(LockMode.REPEATABLE_READ); try (Cursor c = mSchemata.newCursor(txn)) { // Check if the indexId matches and the schemaVersion is the current one. c.autoload(false); c.find(key(indexId)); RowInfo current = null; if (c.value() != null && rowType != null) { var buf = new byte[4]; if (decodeIntLE(buf, 0) == schemaVersion) { // Matches, but don't simply return it. The current one might not have been // updated yet. current = RowInfo.find(rowType); } } c.autoload(true); c.findNearby(key(indexId, schemaVersion)); String typeName = rowType == null ? null : rowType.getName(); RowInfo info = decodeExisting(typeName, null, c.value()); if (current != null && current.allColumns.equals(info.allColumns)) { // Current one matches, so use the canonical RowInfo instance. return current; } else if (info == null) { throw new CorruptDatabaseException ("Schema version not found: " + schemaVersion + ", indexId=" + indexId); } else { return info; } } finally { txn.reset(); } } static SecondaryInfo indexRowInfo(RowInfo primaryInfo, byte[] desc) { byte type = desc[0]; int offset = 1; var info = new SecondaryInfo(primaryInfo, type == 'A'); int numKeys = decodePrefixPF(desc, offset); offset += lengthPrefixPF(numKeys); info.keyColumns = new LinkedHashMap<>(numKeys); for (int i=0; i<numKeys; i++) { offset = decodeIndexColumn(primaryInfo, desc, offset, info.keyColumns); } int numValues = decodePrefixPF(desc, offset); if (numValues == 0) { info.valueColumns = Collections.emptyNavigableMap(); } else { offset += lengthPrefixPF(numValues); info.valueColumns = new TreeMap<>(); offset = decodeIndexColumn(primaryInfo, desc, offset, info.valueColumns); } info.allColumns = new TreeMap<>(info.keyColumns); info.allColumns.putAll(info.valueColumns); return info; } /** * @param columns decoded column goes here * @return updated offset */ private static int decodeIndexColumn(RowInfo primaryInfo, byte[] desc, int offset, Map<String, ColumnInfo> columns) { int typeCode = decodeIntBE(desc, offset) ^ (1 << 31); offset += 4; int nameLength = decodePrefixPF(desc, offset); offset += lengthPrefixPF(nameLength); String name = decodeStringUTF(desc, offset, nameLength); offset += nameLength; ColumnInfo column = primaryInfo.allColumns.get(name); makeColumn: { if (column == null) { name = name.intern(); column = new ColumnInfo(); column.name = name; } else if (column.typeCode != typeCode) { column = column.copy(); } else { break makeColumn; } column.typeCode = typeCode; column.assignType(); } columns.put(column.name, column); return offset; } /** * Decodes a set of secondary index RowInfo objects. */ static SecondaryInfo[] indexRowInfos(RowInfo primaryInfo, byte[][] descriptors) { var infos = new SecondaryInfo[descriptors.length]; for (int i=0; i<descriptors.length; i++) { infos[i] = indexRowInfo(primaryInfo, descriptors[i]); } return infos; } /** * Returns a primary RowInfo or a secondary RowInfo, for the current schema version. Only * key columns are stable across schema versions. * * @param indexId can be the primaryIndexId or a secondary index id * @return RowInfo or SecondaryInfo, or null if not found */ RowInfo currentRowInfo(Class<?> rowType, long primaryIndexId, long indexId) throws IOException { RowInfo primaryInfo = RowInfo.find(rowType); if (primaryIndexId == indexId) { return primaryInfo; } Index primaryIndex = mDatabase.indexById(primaryIndexId); if (primaryIndex == null) { return null; } TableManager<?> manager = tableManager(primaryIndex); // Scan the set of secondary indexes to find it. Not the most efficient approach, but // tables aren't expected to have tons of secondaries. View secondariesView = viewExtended(primaryIndexId, K_SECONDARY); try (Cursor c = secondariesView.newCursor(null)) { for (c.first(); c.key() != null; c.next()) { if (indexId == decodeLongLE(c.value(), 0)) { return manager.secondaryInfo(primaryInfo, c.key()); } } } return null; } /** * @param key K_SECONDARY, etc */ private View viewExtended(long indexId, int key) { var prefix = new byte[8 + 4 + 4]; encodeLongBE(prefix, 0, indexId); encodeIntBE(prefix, 8 + 4, key); return mSchemata.viewPrefix(prefix, prefix.length); } /** * Decode the existing RowInfo for the current schema version. * * @param typeName pass null to decode the current type name * @return null if not found */ RowInfo decodeExisting(Transaction txn, String typeName, long indexId) throws IOException { byte[] currentData = mSchemata.load(txn, key(indexId)); if (currentData == null) { return null; } return decodeExisting(txn, typeName, indexId, currentData, decodeIntLE(currentData, 0)); } /** * Decode the existing RowInfo for the given schema version. * * @param typeName pass null to decode the current type name * @param currentData can be null if not the current schema * @return null if not found */ private RowInfo decodeExisting(Transaction txn, String typeName, long indexId, byte[] currentData, int schemaVersion) throws IOException { byte[] primaryData = mSchemata.load(txn, key(indexId, schemaVersion)); if (typeName == null) { byte[] currentName = viewExtended(indexId, K_TYPE_NAME).load(txn, EMPTY_BYTES); if (currentName == null) { typeName = String.valueOf(indexId); } else { typeName = decodeStringUTF(currentName, 0, currentName.length); } } return decodeExisting(typeName, currentData, primaryData); } /** * @param currentData if null, then alternateKeys and secondaryIndexes won't be decoded * @param primaryData if null, then null is returned * @return null only if primaryData is null */ private static RowInfo decodeExisting(String typeName, byte[] currentData, byte[] primaryData) throws CorruptDatabaseException { if (primaryData == null) { return null; } int pos = 0; int encodingVersion = primaryData[pos++] & 0xff; if (encodingVersion != 1) { throw new CorruptDatabaseException("Unknown encoding version: " + encodingVersion); } var info = new RowInfo(typeName); info.allColumns = new TreeMap<>(); var names = new String[decodePrefixPF(primaryData, pos)]; pos += lengthPrefixPF(names.length); for (int i=0; i<names.length; i++) { int nameLen = decodePrefixPF(primaryData, pos); pos += lengthPrefixPF(nameLen); String name = decodeStringUTF(primaryData, pos, nameLen).intern(); pos += nameLen; names[i] = name; var ci = new ColumnInfo(); ci.name = name; ci.typeCode = decodeIntLE(primaryData, pos); pos += 4; info.allColumns.put(name, ci); } info.keyColumns = new LinkedHashMap<>(); pos = decodeColumns(primaryData, pos, names, info.keyColumns); info.valueColumns = new TreeMap<>(); pos = decodeColumns(primaryData, pos, names, info.valueColumns); if (info.valueColumns.isEmpty()) { info.valueColumns = Collections.emptyNavigableMap(); } if (pos < primaryData.length) { throw new CorruptDatabaseException ("Trailing primary data: " + pos + " < " + primaryData.length); } if (currentData != null) { info.alternateKeys = new TreeSet<>(ColumnSetComparator.THE); pos = decodeColumnSets(currentData, 4, names, info.alternateKeys); if (info.alternateKeys.isEmpty()) { info.alternateKeys = Collections.emptyNavigableSet(); } info.secondaryIndexes = new TreeSet<>(ColumnSetComparator.THE); pos = decodeColumnSets(currentData, pos, names, info.secondaryIndexes); if (info.secondaryIndexes.isEmpty()) { info.secondaryIndexes = Collections.emptyNavigableSet(); } if (pos < currentData.length) { throw new CorruptDatabaseException ("Trailing current data: " + pos + " < " + currentData.length); } } return info; } /** * @param columns to be filled in * @return updated position */ private static int decodeColumns(byte[] data, int pos, String[] names, Map<String, ColumnInfo> columns) { int num = decodePrefixPF(data, pos); pos += lengthPrefixPF(num); for (int i=0; i<num; i++) { int columnNumber = decodePrefixPF(data, pos); pos += lengthPrefixPF(columnNumber); var ci = new ColumnInfo(); ci.name = names[columnNumber]; ci.typeCode = decodeIntLE(data, pos); pos += 4; ci.assignType(); columns.put(ci.name, ci); } return pos; } /** * @param columnSets to be filled in * @return updated position */ private static int decodeColumnSets(byte[] data, int pos, String[] names, Set<ColumnSet> columnSets) { int size = decodePrefixPF(data, pos); pos += lengthPrefixPF(size); for (int i=0; i<size; i++) { var cs = new ColumnSet(); cs.allColumns = new TreeMap<>(); pos = decodeColumns(data, pos, names, cs.allColumns); cs.keyColumns = new LinkedHashMap<>(); pos = decodeColumns(data, pos, names, cs.keyColumns); cs.valueColumns = new TreeMap<>(); pos = decodeColumns(data, pos, names, cs.valueColumns); if (cs.valueColumns.isEmpty()) { cs.valueColumns = Collections.emptyNavigableMap(); } columnSets.add(cs); } return pos; } private static byte[] key(long indexId) { var key = new byte[8]; encodeLongBE(key, 0, indexId); return key; } private static byte[] key(long indexId, int suffix) { var key = new byte[8 + 4]; encodeLongBE(key, 0, indexId); encodeIntBE(key, 8, suffix); return key; } private static class EncodedRowInfo { // All the column names, in lexicographical order. final String[] names; // Primary ColumnSet. final byte[] primaryData; // Hash code over the primary data. final int primaryHash; // Current schemaVersion (initially zero), alternateKeys, and secondaryIndexes. final byte[] currentData; // Set of descriptors. final TreeSet<byte[]> secondaries; /** * Constructor for encoding and writing. */ EncodedRowInfo(RowInfo info) { names = new String[info.allColumns.size()]; var columnNameMap = new HashMap<String, Integer>(); var encoder = new Encoder(names.length * 16); // with initial capacity guess encoder.writeByte(1); // encoding version encoder.writePrefixPF(names.length); int columnNumber = 0; for (ColumnInfo column : info.allColumns.values()) { String name = column.name; columnNameMap.put(name, columnNumber); names[columnNumber++] = name; encoder.writeStringUTF(name); encoder.writeIntLE(column.typeCode); } encodeColumns(encoder, info.keyColumns.values(), columnNameMap); encodeColumns(encoder, info.valueColumns.values(), columnNameMap); primaryData = encoder.toByteArray(); primaryHash = Arrays.hashCode(primaryData); encoder.reset(0); encoder.writeIntLE(0); // slot for current schemaVersion encodeColumnSets(encoder, info.alternateKeys, columnNameMap); encodeColumnSets(encoder, info.secondaryIndexes, columnNameMap); currentData = encoder.toByteArray(); secondaries = new TreeSet<>(Arrays::compareUnsigned); info.alternateKeys.forEach(cs -> secondaries.add(encodeDescriptor('A', encoder, cs))); info.secondaryIndexes.forEach(cs -> secondaries.add(encodeDescriptor('I', encoder,cs))); } /** * Encode columns using name indexes instead of strings. */ private static void encodeColumns(Encoder encoder, Collection<ColumnInfo> columns, Map<String, Integer> columnNameMap) { encoder.writePrefixPF(columns.size()); for (ColumnInfo column : columns) { encoder.writePrefixPF(columnNameMap.get(column.name)); encoder.writeIntLE(column.typeCode); } } /** * Encode column sets using name indexes instead of strings. */ private static void encodeColumnSets(Encoder encoder, Collection<ColumnSet> columnSets, Map<String, Integer> columnNameMap) { encoder.writePrefixPF(columnSets.size()); for (ColumnSet cs : columnSets) { encodeColumns(encoder, cs.allColumns.values(), columnNameMap); encodeColumns(encoder, cs.keyColumns.values(), columnNameMap); encodeColumns(encoder, cs.valueColumns.values(), columnNameMap); } } /** * Encode a secondary index descriptor. * * @param type 'A' or 'I'; alternate key descriptors are ordered first */ private static byte[] encodeDescriptor(char type, Encoder encoder, ColumnSet cs) { encoder.reset(0); encoder.writeByte((byte) type); encodeColumns(encoder, cs.keyColumns); encodeColumns(encoder, cs.valueColumns); return encoder.toByteArray(); } private static void encodeColumns(Encoder encoder, Map<String, ColumnInfo> columns) { encoder.writePrefixPF(columns.size()); for (ColumnInfo column : columns.values()) { encoder.writeIntBE(column.typeCode ^ (1 << 31)); encoder.writeStringUTF(column.name); } } } }
package org.commcare.xml; import org.commcare.resources.model.Resource; import org.commcare.resources.model.ResourceTable; import org.commcare.suite.model.Detail; import org.commcare.suite.model.Entry; import org.commcare.suite.model.Menu; import org.commcare.suite.model.Suite; import org.javarosa.core.model.instance.FormInstance; import org.javarosa.core.services.storage.IStorageUtilityIndexed; import org.javarosa.core.services.storage.StorageManager; import org.javarosa.xml.ElementParser; import org.javarosa.xml.util.InvalidStructureException; import org.javarosa.xml.util.UnfullfilledRequirementsException; import org.kxml2.io.KXmlParser; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.io.InputStream; import java.util.Hashtable; import java.util.Vector; /** * Parses a suite file resource and creates the associated object * containing the menu, detail, entry, etc definitions. This parser * will also create models for any resource installers that are defined * by the suite file and add them to the resource table provided * with the suite resource as the parent, that behavior can be skipped * by setting a flag if the resources have already been promised. * * @author ctsims */ public class SuiteParser extends ElementParser<Suite> { private final IStorageUtilityIndexed<FormInstance> fixtureStorage; private ResourceTable table; private String resourceGuid; private int maximumResourceAuthority = -1; /** * If set to true, the parser won't process adding incoming resources to the resource table. * This is helpful if the suite is being processed during a non-install phase */ private final boolean skipResources; private final boolean isValidationPass; private final boolean isUpgrade; public SuiteParser(InputStream suiteStream, ResourceTable table, String resourceGuid, IStorageUtilityIndexed<FormInstance> fixtureStorage) throws IOException { super(ElementParser.instantiateParser(suiteStream)); this.table = table; this.resourceGuid = resourceGuid; this.fixtureStorage = fixtureStorage; this.skipResources = false; this.isValidationPass = false; this.isUpgrade = false; } public SuiteParser(InputStream suiteStream, ResourceTable table, String resourceGuid, IStorageUtilityIndexed<FormInstance> fixtureStorage, boolean skipResources, boolean isValidationPass, boolean isUpgrade) throws IOException { super(ElementParser.instantiateParser(suiteStream)); this.table = table; this.resourceGuid = resourceGuid; this.fixtureStorage = fixtureStorage; this.skipResources = skipResources; this.isValidationPass = isValidationPass; this.isUpgrade = isUpgrade; } @Override public Suite parse() throws InvalidStructureException, IOException, XmlPullParserException, UnfullfilledRequirementsException { checkNode("suite"); String sVersion = parser.getAttributeValue(null, "version"); int version = Integer.parseInt(sVersion); Hashtable<String, Detail> details = new Hashtable<>(); Hashtable<String, Entry> entries = new Hashtable<>(); Vector<Menu> menus = new Vector<>(); try { //Now that we've covered being inside of a suite, //start traversing. parser.next(); int eventType = parser.getEventType(); do { if (eventType == KXmlParser.START_TAG) { String tagName = parser.getName().toLowerCase(); switch (tagName) { case "entry": Entry entry = EntryParser.buildEntryParser(parser).parse(); entries.put(entry.getCommandId(), entry); break; case "view": Entry viewEntry = EntryParser.buildViewParser(parser).parse(); entries.put(viewEntry.getCommandId(), viewEntry); break; case EntryParser.REMOTE_REQUEST_TAG: Entry remoteRequestEntry = EntryParser.buildRemoteSyncParser(parser).parse(); entries.put(remoteRequestEntry.getCommandId(), remoteRequestEntry); break; case "locale": String localeKey = parser.getAttributeValue(null, "language"); //resource def parser.nextTag(); Resource localeResource = new ResourceParser(parser, maximumResourceAuthority).parse(); if (!skipResources) { table.addResource(localeResource, table.getInstallers().getLocaleFileInstaller(localeKey), resourceGuid); } break; case "media": String path = parser.getAttributeValue(null, "path"); //Can be an arbitrary number of resources inside of a media block. while (this.nextTagInBlock("media")) { Resource mediaResource = new ResourceParser(parser, maximumResourceAuthority).parse(); if (!skipResources) { table.addResource(mediaResource, table.getInstallers().getMediaInstaller(path), resourceGuid); } } break; case "xform": //skip xform stuff for now parser.nextTag(); Resource xformResource = new ResourceParser(parser, maximumResourceAuthority).parse(); if (!skipResources) { table.addResource(xformResource, table.getInstallers().getXFormInstaller(), resourceGuid); } break; case "user-restore": parser.nextTag(); break; case "detail": Detail d = getDetailParser().parse(); details.put(d.getId(), d); break; case "menu": Menu m = new MenuParser(parser).parse(); menus.addElement(m); break; case "fixture": if (!isValidationPass) { // commit fixture to the memory, overwriting existing // fixture only during first init after app upgrade new FixtureXmlParser(parser, isUpgrade, fixtureStorage).parse(); } break; default: System.out.println("Unrecognized Tag: " + parser.getName()); break; } } eventType = parser.next(); } while (eventType != KXmlParser.END_DOCUMENT); return new Suite(version, details, entries, menus); } catch (XmlPullParserException e) { e.printStackTrace(); throw new InvalidStructureException("Pull Parse Exception, malformed XML.", parser); } } public void setMaximumAuthority(int authority) { maximumResourceAuthority = authority; } protected DetailParser getDetailParser() { return new DetailParser(parser); } }
package org.influxdb.inflow; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.TimeUnit; import org.influxdb.InfluxDB; import org.influxdb.InfluxDB.RetentionPolicy; import org.influxdb.TimeUtil; import org.influxdb.dto.Point; import org.influxdb.dto.QueryResult; import org.influxdb.dto.QueryResult.Result; import org.influxdb.dto.QueryResult.Series; public class Database { protected String name; protected Client client; public Database(String name, Client client) { if (name == null) { throw new IllegalArgumentException("Database name is null"); } if (name.length() == 0) { throw new IllegalArgumentException("Database name is zero length"); } this.name = name; this.client = client; } public static Database fromURI(String uri, int timeout, boolean verifySSL) throws InflowException { Client client = Client.fromURI(uri, timeout, verifySSL); String databaseName = null; URI u; try { u = new URI(uri); } catch (URISyntaxException use) { throw new InflowException("Malformed URI:" + use.getMessage(), use); } if (!u.getPath().isEmpty()) { databaseName = u.getPath().substring(1); } return new Database(databaseName, client); } public static Database fromURI(String uri, int timeout) throws InflowException { return Database.fromURI(uri, timeout, false); } public static Database fromURI(String uri) throws InflowException { return Database.fromURI(uri, 0); } public String getName() { return this.name; } public QueryResult query(String query) throws InflowException { return this.client.query(this.name, query); } /** * Create this database * * @param retentionPolicy * @param createIfNotExists Only create the database if it does not yet exist */ public QueryResult create(RetentionPolicy retentionPolicy, boolean createIfNotExists) throws InflowDatabaseException { QueryResult queryResult = null; try { String query = String.format( "CREATE DATABASE %s%s", (createIfNotExists ? "IF NOT EXISTS " : ""), this.name ); queryResult = this.query(query); if (retentionPolicy != null) { this.createRetentionPolicy(retentionPolicy); } } catch (Exception ex) { throw new InflowDatabaseException("Failed to created database %s" + this.name + "\n" + ex.getMessage(), ex); } return queryResult; } public QueryResult create(RetentionPolicy retentionPolicy) throws InflowDatabaseException { return this.create(retentionPolicy, true); } public QueryResult create() throws InflowDatabaseException { return this.create(null); } /** * Writes points into InfluxDB * * @param points Array of points * @param precision The timestamp precision (defaults to nanoseconds) */ public void writePoints(Point[] points, TimeUnit precision) throws InflowException { List<String> lines = new ArrayList<>(); for (Point point : points) { lines.add(point.lineProtocol()); } // TODO: get retention polcy and consistency levels passed // or refactor a write() that does not require them and use them as defined in the driver? this.client.driver.write( this.name, new RetentionPolicy("default"), InfluxDB.ConsistencyLevel.ONE, lines ); } public void writePoints(Point[] points) throws InflowException { this.writePoints(points, TimeUnit.NANOSECONDS); } public boolean exists() throws InflowException { Series databaseSeries = this.client.listDatabases(); String[] databases = databaseSeries.getValuesAsStringArray(); return Arrays.asList(databases).contains(this.name); } public QueryResult createRetentionPolicy(RetentionPolicy retentionPolicy) throws InflowException { return this.query(RetentionPolicy.toQueryString("CREATE", retentionPolicy, this.name)); } public QueryResult alterRetentionPolicy(RetentionPolicy retentionPolicy) throws InflowException { return this.query(RetentionPolicy.toQueryString("ALTER", retentionPolicy, this.name)); } public Series listRetentionPolicies() throws InflowException { QueryResult queryResult = this.query(String.format("SHOW RETENTION POLICIES ON %s", this.name)); List<Result> results = queryResult.getResults(); Result result = results.get(0); List<Series> series = result.getSeries(); Series serie = series.get(0); return serie; // callers can use series.getValuesAsStringArray(); } public QueryResult drop() throws InflowException { return this.query(String.format("DROP DATABASE %s", this.name)); } /** * Retrieve a query builder for this database * */ public QueryBuilder getQueryBuilder() { return new QueryBuilder(this); } public Client getClient() { return this.client; } }
package org.jenetics.util; import static org.jenetics.util.Validator.nonNull; import java.io.Serializable; import java.util.Arrays; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Random; public final class ArrayUtils { /** * The empty, immutable array. This array is {@link Serializable}. */ @SuppressWarnings("unchecked") public static final Array EMPTY_ARRAY = new Array(0); private ArrayUtils() { } /** * Return the empty, immutable array. This array is {@link Serializable}. * * @see #EMPTY_ARRAY * @param <T> the element type. * @return the empty, immutable array. */ @SuppressWarnings("unchecked") public static <T> Array<T> emptyArray() { return (Array<T>)EMPTY_ARRAY; } /** * Swap two elements of an given array. * * @param array the array * @param i index of the first array element. * @param j index of the second array element. * @throws ArrayIndexOutOfBoundsException if <tt>i &lt; 0</tt> or * <tt>j &lt; 0</tt> or <tt>i &gt; a.length</tt> or * <tt>j &gt; a.length</tt> * @throws NullPointerException if the give array is {@code null}. */ public static void swap(final int[] array, final int i, final int j) { nonNull(array, "Array"); final int old = array[i]; array[i] = array[j]; array[j] = old; } /** * Swap two elements of an given array. * * @param <T> the array type. * @param array the array * @param i index of the first array element. * @param j index of the second array element. * @throws ArrayIndexOutOfBoundsException if <tt>i &lt; 0</tt> or * <tt>j &lt; 0</tt> or <tt>i &gt; a.length</tt> or * <tt>j &gt; a.length</tt> * @throws NullPointerException if the give array is {@code null}. */ public static <T> void swap(final T[] array, final int i, final int j) { nonNull(array, "Array"); final T old = array[i]; array[i] = array[j]; array[j] = old; } /** * Swap two elements of an given list. * * @param <T> the list type. * @param list the array * @param i index of the first list element. * @param j index of the second list element. * @throws ArrayIndexOutOfBoundsException if <tt>i &lt; 0</tt> or * <tt>j &lt; 0</tt> or <tt>i &gt; a.length</tt> or * <tt>j &gt; a.length</tt> * @throws NullPointerException if the give list is {@code null}. */ public static <T> void swap(final List<T> list, final int i, final int j) { nonNull(list, "Array"); final T old = list.get(i); list.set(i, list.get(j)); list.set(j, old); } /** * Swap two elements of an given array. * * @param <T> the array type. * @param array the array * @param i index of the first array element. * @param j index of the second array element. * @throws ArrayIndexOutOfBoundsException if <tt>i &lt; 0</tt> or * <tt>j &lt; 0</tt> or <tt>i &gt; a.length</tt> or * <tt>j &gt; a.length</tt> * @throws NullPointerException if the give array is {@code null}. * @throws UnsupportedOperationException if the array is sealed * ({@code array.isSealed() == true}). */ public static <T> void swap(final Array<T> array, final int i, final int j) { nonNull(array, "Array"); final T old = array.get(i); array.set(i, array.get(j)); array.set(j, old); } public static <T> void sort( final Array<T> array, final int from, final int to, final Comparator<? super T> comparator ) { nonNull(array, "Array"); nonNull(comparator, "Comparator"); array.checkSeal(); array.checkIndex(from, to); @SuppressWarnings("unchecked") final Comparator<Object> c = (Comparator<Object>)comparator; Arrays.sort(array._array, from + array._start, to + array._start, c); } /** * Calls the sort method on the {@link Arrays} class. * @see Arrays#sort(Object[], Comparator) * * @throws NullPointerException if the give array or comparator is * {@code null}. * @throws UnsupportedOperationException if the array is sealed * ({@code array.isSealed() == true}). */ public static <T> void sort( final Array<T> array, final Comparator<? super T> comparator ) { nonNull(array, "Array"); nonNull(comparator, "Comparator"); array.checkSeal(); sort(array, 0, array.length(), comparator); } public static <T extends Object & Comparable<? super T>> void sort(final Array<T> array, final int from, final int to) { nonNull(array, "Array"); array.checkSeal(); array.checkIndex(from, to); Arrays.sort(array._array, from + array._start, to + array._start); } /** * Calls the sort method on the {@link Arrays} class. * * @see Arrays#sort(Object[]) * @throws NullPointerException if the give array is {@code null}. * @throws UnsupportedOperationException if the array is sealed * ({@code array.isSealed() == true}). */ public static <T extends Object & Comparable<? super T>> void sort(final Array<T> array) { nonNull(array, "Array"); array.checkSeal(); Arrays.sort(array._array, 0, array.length()); } /* * Some experiments with quick sort. Is more efficient on large arrays. * The java build in merge sort performs an array copy which can lead to * an OutOfMemoryError. * */ static <T extends Object & Comparable<? super T>> void quicksort(final Array<T> array) { quicksort(array, 0, array.length()); } static <T extends Object & Comparable<? super T>> void quicksort(final Array<T> array, final int from, final int to) { quicksort(array, from, to, new Comparator<T>() { @Override public int compare(final T o1, final T o2) { return o1.compareTo(o2); } }); } static <T> void quicksort( final Array<T> array, final int from, final int to, final Comparator<? super T> comparator ) { nonNull(array, "Array"); nonNull(comparator, "Comparator"); array.checkSeal(); _quicksort(array, from, to - 1, comparator); } private static <T> void _quicksort( final Array<T> array, final int left, final int right, final Comparator<? super T> comparator ) { if (right > left) { final int j = _partition(array, left, right, comparator); _quicksort(array, left, j - 1, comparator); _quicksort(array, j + 1, right, comparator); } } @SuppressWarnings("unchecked") private static <T> int _partition( final Array<T> array, final int left, final int right, final Comparator<? super T> comparator ) { final T pivot = array.get(left); int i = left; int j = right + 1; while (true) { do { ++i; } while ( i < right && comparator.compare((T)array._array[i + array._start], pivot) < 0 ); do { --j; } while ( j > left && comparator.compare((T)array._array[j + array._start], pivot) > 0 ); if (j <= i) { break; } _swap(array, i, j); } _swap(array, left, j); return j; } private static <T> void _swap(final Array<T> array, final int i, final int j) { final Object temp = array._array[i + array._start]; array._array[i + array._start] = array._array[j + array._start]; array._array[j + array._start] = temp; } /** * Finds the minimum and maximum value of the given array. * * @param <T> the comparable type. * @param array the array to search. * @return an array of size two. The first element contains the minimum and * the second element contains the maximum value. If the given array * has size zero, the min and max values of the returned array are * {@code null}. * @throws NullPointerException if the give array is {@code null}. */ public static <T extends Object & Comparable<? super T>> Array<T> minmax(final Array<T> array) { nonNull(array, "Array"); final int size = array.length(); T min = null; T max = null; int start = 0; if (size%2 == 0 && size > 0) { start = 2; if (array.get(0).compareTo(array.get(1)) < 0) { min = array.get(0); max = array.get(1); } else { min = array.get(1); max = array.get(0); } } else if (size%2 == 1) { start = 1; min = array.get(0); max = array.get(0); } for (int i = start; i < size; i += 2) { final T first = array.get(i); final T second = array.get(i + 1); if (first.compareTo(second) < 0) { if (first.compareTo(min) < 0) { min = first; } if (second.compareTo(max) > 0) { max = second; } } else { if (second.compareTo(min) < 0) { min = second; } if (first.compareTo(max) > 0) { max = first; } } } return new Array<T>(min, max); } public static <T extends Object & Comparable<? super T>> T select(final Array<T> array, final int k) { return array.get(iselect(array, k)); } public static <T extends Object & Comparable<? super T>> int iselect(final Array<T> array, final int k) { nonNull(array, "Array"); if (k < 0) { throw new IllegalArgumentException("k is smaller than zero: " + k); } if (k > array.length() - 1) { throw new IllegalArgumentException(String.format( "k is greater than values.length() - 1 (%d): %d", array.length() - 1, k )); } //Init the pivot array. This avoids the rearrangement of the given array. final int[] pivot = new int[array.length()]; for (int i = 0; i < pivot.length; ++i) { pivot[i] = i; } int l = 0; int ir = array.length() - 1; int index = -1; while (index == -1) { if (ir <= l + 1) { if (ir == l + 1 && array.get(pivot[ir]).compareTo(array.get(pivot[l])) < 0) { swap(pivot, l, ir); } index = pivot[k]; } else { final int mid = (l + ir) >> 1; swap(pivot, mid, l + 1); if (array.get(pivot[l]).compareTo(array.get(pivot[ir])) > 0) { swap(pivot, l, ir); } if (array.get(pivot[l + 1]).compareTo(array.get(pivot[ir])) > 0) { swap(pivot, l + 1, ir); } if (array.get(pivot[l]).compareTo(array.get(pivot[l + 1])) > 0) { swap(pivot, l, l + 1); } int i = l + 1; int j = ir; final T a = array.get(pivot[l + 1]); while (true) { do { ++i; } while (array.get(pivot[i]).compareTo(a) < 0); do { --j; } while (array.get(pivot[j]).compareTo(a) > 0); if (j < i) { break; } swap(pivot, i, j); } array.set(pivot[l + 1], array.get(pivot[j])); array.set(pivot[j], a); if (j >= k) { ir = j -1; } if (j <= k) { l = i; } } } return index; } /** * Finding the median of the give array. The input array will not be * rearranged. * * @param <T> the array element type. * @param array the array. * @return the median * @throws NullPointerException if the give array is {@code null}. */ public static <T extends Object & Comparable<? super T>> T median(final Array<T> array) { nonNull(array, "Array"); if (array.length() == 0) { throw new IllegalArgumentException("Array length is zero."); } T median = null; if (array.length() == 1) { median = array.get(0); } else if (array.length() == 2) { if (array.get(0).compareTo(array.get(1)) < 0) { median = array.get(0); } else { median = array.get(1); } } else { median = select(array, array.length()/2); } return median; } /** * Randomize the {@code array} using the given {@link Random} object. The used * shuffling algorithm is from D. Knuth TAOCP, Seminumerical Algorithms, * Third edition, page 142, Algorithm S (Selection sampling technique). * * @param array the {@code array} to randomize. * @param random the {@link Random} object to use for randomize. * @throws NullPointerException if the give array or the random object is * {@code null}. */ public static void shuffle(final int[] array, final Random random) { nonNull(array, "Array"); for (int j = array.length - 1; j > 0; --j) { swap(array, j, random.nextInt(j + 1)); } } /** * Randomize the {@code array} using the given {@link Random} object. The used * shuffling algorithm is from D. Knuth TAOCP, Seminumerical Algorithms, * Third edition, page 142, Algorithm S (Selection sampling technique). * * @param array the {@code array} to randomize. * @param random the {@link Random} object to use for randomize. * @param <T> the component type of the array to randomize. * @throws NullPointerException if the give array or the random object is * {@code null}. */ public static <T> void shuffle(final T[] array, final Random random) { nonNull(array, "Array"); for (int j = array.length - 1; j > 0; --j) { swap(array, j, random.nextInt(j + 1)); } } /** * Randomize the {@code array} using the given {@link Random} object. The used * shuffling algorithm is from D. Knuth TAOCP, Seminumerical Algorithms, * Third edition, page 142, Algorithm S (Selection sampling technique). * * @param array the {@code array} to randomize. * @param random the {@link Random} object to use for randomize. * @param <T> the component type of the array to randomize. * @throws NullPointerException if the give array or the random object is * {@code null}. * @throws UnsupportedOperationException if the array is sealed * ({@code array.isSealed() == true}). */ public static <T> void shuffle(final Array<T> array, final Random random) { nonNull(array, "Array"); nonNull(random, "Random"); for (int j = array.length() - 1; j > 0; --j) { swap(array, j, random.nextInt(j + 1)); } } /** * Randomize the {@code list} using the given {@link Random} object. The used * shuffling algorithm is from D. Knuth TAOCP, Seminumerical Algorithms, * Third edition, page 142, Algorithm S (Selection sampling technique). * * @param list the {@code array} to randomize. * @param random the {@link Random} object to use for randomize. * @param <T> the component type of the array to randomize. * @throws NullPointerException if the give list or the random object is * {@code null}. */ public static <T> void shuffle(final List<T> list, final Random random) { nonNull(list, "List"); nonNull(random, "Random"); for (int j = list.size() - 1; j > 0; --j) { swap(list, j, random.nextInt(j + 1)); } } public static <T> void reverse(final T[] array, final int from, final int to) { nonNull(array, "Array"); rangeCheck(array.length, from, to); int i = from; int j = to; while (i < j) { --j; swap(array, i, j); ++i; } } public static <T> void reverse(final Array<T> array, final int from, final int to) { nonNull(array, "Array"); rangeCheck(array.length(), from, to); int i = from; int j = to; while (i < j) { --j; swap(array, i, j); ++i; } } /** * Reverses the given array in place. * * @param <T> the array type. * @param array the array to reverse. * @throws NullPointerException if the give array is {@code null}. */ public static <T> void reverse(final T[] array) { nonNull(array, "Array"); reverse(array, 0, array.length); } /** * Reverses the given array in place. * * @param <T> the array type. * @param array the array to reverse. * @throws NullPointerException if the give array is {@code null}. * @throws UnsupportedOperationException if the array is sealed * ({@code array.isSealed() == true}). */ public static <T> void reverse(final Array<T> array) { nonNull(array, "Array"); reverse(array, 0, array.length()); } private static void rangeCheck(int length, int from, int to) { if (from > to) { throw new IllegalArgumentException( "fromIndex(" + from + ") > toIndex(" + to+ ")" ); } if (from < 0) { throw new ArrayIndexOutOfBoundsException(from); } if (to > length) { throw new ArrayIndexOutOfBoundsException(to); } } public static int[] partition(final int size, final int parts) { if (size < 1) { throw new IllegalArgumentException( "Size must greater than zero: " + size ); } if (parts < 1) { throw new IllegalArgumentException( "Number of partitions must greater than zero: " + parts ); } final int pts = Math.min(size, parts); final int[] partition = new int[pts + 1]; final int bulk = size/pts; final int rest = size%pts; assert ((bulk*pts + rest) == size); for (int i = 0, n = pts - rest; i < n; ++i) { partition[i] = i*bulk; } for (int i = 0, n = rest + 1; i < n; ++i) { partition[pts - rest + i] = (pts - rest)*bulk + i*(bulk + 1); } return partition; } public static int[] subset(final int n, final int k, final Random random) { nonNull(random, "Random"); if (k <= 0) { throw new IllegalArgumentException(String.format( "Subset size smaller or equal zero: %s", k )); } if (n < k) { throw new IllegalArgumentException(String.format( "n smaller than k: %s < %s.", n, k )); } final int[] sub = new int[k]; subset(n, sub,random); return sub; } public static void subset(final int n, final int sub[], final Random random) { nonNull(random, "Random"); nonNull(sub, "Sub set array"); final int k = sub.length; if (k <= 0) { throw new IllegalArgumentException(String.format( "Subset size smaller or equal zero: %s", k )); } if (n < k) { throw new IllegalArgumentException(String.format( "n smaller than k: %s < %s.", n, k )); } if (!MathUtils.isMultiplicationSave(n, k)) { throw new IllegalArgumentException(String.format( "n*sub.length > Integer.MAX_VALUE (%s*%s = %s > %s)", n, sub.length, (long)n*(long)k, Integer.MAX_VALUE )); } if (sub.length == n) { for (int i = 0; i < sub.length; ++i) { sub[i] = i; } return; } for (int i = 0; i < k; ++i) { sub[i] = (i*n)/k; } int l = 0; int ix = 0; for (int i = 0; i < k; ++i) { do { ix = nextInt(random, 1, n); l = (ix*k - 1)/n; } while (sub[l] >= ix); sub[l] = sub[l] + 1; } int m = 0; int ip = 0; int is = k; for (int i = 0; i < k; ++i) { m = sub[i]; sub[i] = 0; if (m != (i*n)/k) { ip = ip + 1; sub[ip - 1] = m; } } int ihi = ip; int ids = 0; for (int i = 1; i <= ihi; ++i) { ip = ihi + 1 - i; l = 1 + (sub[ip - 1]*k - 1)/n; ids = sub[ip - 1] - ((l - 1)*n)/k; sub[ip - 1] = 0; sub[is - 1] = l; is = is - ids; } int ir = 0; int m0 = 0; for (int ll = 1; ll <= k; ++ll) { l = k + 1 - ll; if (sub[l - 1] != 0) { ir = l; m0 = 1 + ((sub[l - 1] - 1)*n)/k; m = (sub[l-1]*n)/k - m0 + 1; } ix = nextInt(random, m0, m0 + m - 1); int i = l + 1; while (i <= ir && ix >= sub[i - 1]) { ix = ix + 1; sub[ i- 2] = sub[i - 1]; i = i + 1; } sub[i - 2] = ix; --m; } } private static int nextInt(final Random random, final int a, final int b) { int value = 0; if (a == b) { value = a - 1; } else { value = random.nextInt(b - a) + a; } return value; } /** * Calculates a random permutation. * * @param p the permutation array. * @param random the random number generator. * @throws NullPointerException if the permutation array or the random number * generator is {@code null}. */ public static void permutation(final int[] p, final Random random) { nonNull(p, "Permutation array"); nonNull(random, "Random"); for (int i = 0; i < p.length; ++i) { p[i] = i; } shuffle(p, random); } public static void permutation(final int[] p, final long rank) { nonNull(p, "Permutation array"); if (rank < 1) { throw new IllegalArgumentException(String.format( "Rank smaler than 1: %s", rank )); } Arrays.fill(p, 0); long jrank = rank - 1; for (int i = 1; i <= p.length; ++i) { int iprev = p.length + 1 - i; int irem = (int)(jrank%iprev); jrank = jrank/iprev; int j = 0; int jdir = 0; if ((jrank%2) == 1) { j = 0; jdir = 1; } else { j = p.length + 1; jdir = -1; } int icount = 0; do { j = j + jdir; if (p[j - 1] == 0) { ++icount; } } while (irem >= icount); p[j - 1] = iprev; } } public static int indexOf( final Object[] array, final int start, final int end, final Object element ) { nonNull(array, "Array"); if (start < 0 || end > array.length || start > end) { throw new IndexOutOfBoundsException(String.format( "Invalid index range: [%d, %s]", start, end )); } int index = -1; if (element != null) { for (int i = start; i < end && index == -1; ++i) { if (element.equals(array[i])) { index = i; } } } else { for (int i = start; i < end && index == -1; ++i) { if (array[i] == null) { index = i; } } } return index; } /** * Returns the index of the first occurrence of the specified element in * the {@code array}, or -1 if the {@code array} does not contain the element. * @param array the array to search. * @param element the element to search for. * @return the index of the first occurrence of the specified element in the * given {@code array}, of -1 if the {@code array} does not contain * the element. * @throws NullPointerException if the given {@code array} is {@code null}. */ public static int indexOf(final Object[] array, final Object element) { return indexOf(array, 0, array.length, element); } /** * @see #indexOf(Object[], Object) */ public static <T> int indexOf(final T[] array, final Predicate<? super T> predicate) { nonNull(array, "Array"); nonNull(predicate, "Predicate"); int index = -1; for (int i = 0; i < array.length && index == -1; ++i) { if (predicate.evaluate(array[i])) { index = i; } } return index; } /** * @see #indexOf(Object[], Object) */ public static <T> int indexOf( final Iterable<? extends T> values, final Predicate<? super T> predicate ) { nonNull(values, "Array"); nonNull(predicate, "Predicate"); int index = -1; int i = 0; for (Iterator<? extends T> it = values.iterator(); it.hasNext() && index == -1; ++i) { if (predicate.evaluate(it.next())) { index = i; } } return index; } /** * Iterates over all elements of the given {@code array} as long as the * {@code predicate} returns {@code true} (which means <i>continue</i>) and * returns the index the iteration has been interrupted. -1 is returned if * all elements were visited. * <p/> * Can be used to check all array elements for nullness. * * [code] * public void foo(final Integer[] values) { * ArrayUtils.foreach(values, new Validator.NonNull()); * ... * } * [/code] * * @param array the array to iterate. * @param predicate the applied predicate. * @return the index of the last visited element, or -1 if all elements has * been visited. * @throws NullPointerException if one of the elements are {@code null}. */ public static <T> int foreach( final T[] array, final Predicate<? super T> predicate ) { nonNull(array, "Array"); nonNull(predicate, "Predicate"); int index = -1; for (int i = 0; i < array.length && index == -1; ++i) { if (!predicate.evaluate(array[i])) { index = i; } } return index; } /** * Iterates over all elements of the given {@code values} as long as the * {@code predicate} returns {@code true} (which means <i>continue</i>) and * returns the index the iteration has been interrupted. -1 is returned if * all elements were visited. * * @param values the values to iterate. * @param predicate the applied predicate. * @return the index of the last visited element, or -1 if all elements has * been visited. * @throws NullPointerException if one of the elements are {@code null}. */ public static <T> int foreach( final Iterable<? extends T> values, final Predicate<? super T> predicate ) { nonNull(values, "Array"); nonNull(predicate, "Predicate"); int index = -1; int i = 0; for (Iterator<? extends T> it = values.iterator(); it.hasNext() && index == -1; ++i) { if (!predicate.evaluate(it.next())) { index = i; } } return index; } public static double sum(final double[] values) { double sum = 0.0; double c = 0.0; double y = 0.0; double t = 0.0; for (int i = values.length; --i >= 0;) { y = values[i] - c; t = sum + y; c = t - sum - y; sum = t; } return sum; } /** * Normalize the given double array, so that it sum to one. * * @param values the values to normalize. * @throws NullPointerException if the given double array is {@code null}. */ public static void normalize(final double[] values) { final double sum = 1.0/sum(values); for (int i = values.length; --i >= 0;) { values[i] = values[i]*sum; } } /** * Return the minimum value of the given double array. * * @param values the double array. * @return the minimum value or {@link Double#NaN} if the given array is empty. * @throws NullPointerException if the given array is {@code null}. */ public static double min(final double[] values) { nonNull(values); double min = Double.NaN; if (values.length > 0) { min = values[0]; for (int i = values.length; --i >= 1;) { if (values[i] < min) { min = values[i]; } } } return min; } /** * Return the maximum value of the given double array. * * @param values the double array. * @return the maximum value or {@link Double#NaN} if the given array is empty. * @throws NullPointerException if the given array is {@code null}. */ public static double max(final double[] values) { nonNull(values); double max = Double.NaN; if (values.length > 0) { max = values[0]; for (int i = values.length; --i >= 1;) { if (values[i] > max) { max = values[i]; } } } return max; } /** * Component wise multiplication of the given double array. * * @param values the double values to multiply. * @param multiplier the multiplier. * @throws NullPointerException if the given double array is {@code null}. */ public static void times(final double[] values, final double multiplier) { for (int i = values.length; --i >= 0;) { values[i] *= multiplier; } } /** * Component wise division of the given double array. * * @param values the double values to divide. * @param divisor the divisor. * @throws NullPointerException if the given double array is {@code null}. */ public static void divide(final double[] values, final double divisor) { for (int i = values.length; --i >= 0;) { values[i] /= divisor; } } }
package org.jtrfp.trcl.obj; import org.jtrfp.trcl.Model; import org.jtrfp.trcl.beh.AccelleratedByPropulsion; import org.jtrfp.trcl.beh.AutoLeveling; import org.jtrfp.trcl.beh.BouncesOffSurfaces; import org.jtrfp.trcl.beh.ChaseBehavior; import org.jtrfp.trcl.beh.CollidesWithDEFObjects; import org.jtrfp.trcl.beh.CollidesWithTerrain; import org.jtrfp.trcl.beh.DamageableBehavior; import org.jtrfp.trcl.beh.DeathBehavior; import org.jtrfp.trcl.beh.ExplodesOnDeath; import org.jtrfp.trcl.beh.HasPropulsion; import org.jtrfp.trcl.beh.LoopingPositionBehavior; import org.jtrfp.trcl.beh.MovesByVelocity; import org.jtrfp.trcl.beh.RotationalDragBehavior; import org.jtrfp.trcl.beh.RotationalMomentumBehavior; import org.jtrfp.trcl.beh.TerrainLocked; import org.jtrfp.trcl.beh.VelocityDragBehavior; import org.jtrfp.trcl.core.TR; import org.jtrfp.trcl.file.DEFFile.EnemyDefinition; import org.jtrfp.trcl.file.DEFFile.EnemyDefinition.EnemyLogic; import org.jtrfp.trcl.file.DEFFile.EnemyPlacement; import org.jtrfp.trcl.obj.Explosion.ExplosionType; public class DEFObject extends WorldObject { private final double boundingRadius; public DEFObject(TR tr,Model model, EnemyDefinition def, EnemyPlacement pl){ super(tr,model); boundingRadius = TR.legacy2Modern(def.getBoundingBoxRadius())/2.; final EnemyLogic logic = def.getLogic(); boolean mobile=true; boolean groundLocked=false; switch(logic){ case groundDumb: mobile=false; break; case groundTargeting: mobile=true; groundLocked=true; break; case flyingDumb: mobile=false; break; case groundTargetingDumb: groundLocked=true; break; case flyingSmart: break; case bankSpinDrill: break; case sphereBoss: mobile=true; break; case flyingAttackRetreatSmart: break; case splitShipSmart: break; case groundStaticRuin: mobile=false; break; case targetHeadingSmart: break; case targetPitchSmart: break; case coreBossSmart: mobile=false; break; case cityBossSmart: mobile=false; break; case staticFiringSmart: mobile=false; break; case sittingDuck: mobile=false; break; case tunnelAttack: mobile=false; break; case takeoffAndEscape: break; case fallingAsteroid: mobile=false; break; case cNome://Walky bot? groundLocked=true; break; case cNomeLegs://Walky bot? groundLocked=true; break; case cNomeFactory: mobile=false; break; case geigerBoss: mobile=false; break; case volcanoBoss: mobile=false; break; case volcano: mobile=false; break; case missile://Silo? mobile=false; break; case bob: mobile=false; break; case alienBoss: break; case canyonBoss1: mobile=false; break; case canyonBoss2: mobile=false; break; case lavaMan: mobile=false; break; case arcticBoss: mobile=false; break; case helicopter: break; case tree: mobile=false; break; case ceilingStatic: mobile=false; break; case bobAndAttack: mobile=false; break; case forwardDrive: groundLocked=true; break; case fallingStalag: mobile=false; break; case attackRetreatBelowSky: break; case attackRetreatAboveSky: break; case bobAboveSky: mobile=false; break; case factory: mobile=false; break; }//end switch(logic) addBehavior(new DeathBehavior()); addBehavior(new DamageableBehavior().setHealth(pl.getStrength())); if(mobile){ addBehavior(new ChaseBehavior(tr.getPlayer())); addBehavior(new MovesByVelocity()); addBehavior(new HasPropulsion()); addBehavior(new AccelleratedByPropulsion()); addBehavior(new VelocityDragBehavior()); addBehavior(new AutoLeveling()); addBehavior(new RotationalMomentumBehavior()); addBehavior(new RotationalDragBehavior()); if(groundLocked)addBehavior(new TerrainLocked()); else {addBehavior(new BouncesOffSurfaces()); addBehavior(new CollidesWithTerrain());} addBehavior(new LoopingPositionBehavior()); addBehavior(new ExplodesOnDeath(ExplosionType.BigExplosion)); getBehavior().probeForBehavior(VelocityDragBehavior.class).setDragCoefficient(.86); getBehavior().probeForBehavior(Propelled.class).setMinPropulsion(0); getBehavior().probeForBehavior(Propelled.class).setPropulsion(def.getThrustSpeed()); getBehavior().probeForBehavior(RotationalDragBehavior.class).setDragCoefficient(.86); addBehavior(new ExplodesOnDeath(ExplosionType.Blast)); }//end if(mobile) else{addBehavior(new ExplodesOnDeath(ExplosionType.BigExplosion));} }//end DEFObject /** * @return the boundingRadius */ public double getBoundingRadius() { return boundingRadius; } }//end DEFObject
package org.kohsuke.github; import com.fasterxml.jackson.databind.JsonMappingException; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.InterruptedIOException; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.NoSuchElementException; import java.util.Objects; import java.util.function.Consumer; import java.util.logging.Logger; import java.util.zip.GZIPInputStream; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import javax.annotation.WillClose; import static java.util.Arrays.asList; import static java.util.logging.Level.*; import static org.apache.commons.lang3.StringUtils.defaultString; import static org.kohsuke.github.GitHub.MAPPER; import static org.kohsuke.github.GitHub.connect; /** * A builder pattern for making HTTP call and parsing its output. * * @author Kohsuke Kawaguchi */ class Requester { private final GitHub root; private final List<Entry> args = new ArrayList<Entry>(); private final Map<String, String> headers = new LinkedHashMap<String, String>(); @Nonnull private String urlPath = "/"; /** * Request method. */ private String method = "GET"; private String contentType = null; private InputStream body; /** * Current connection. */ private HttpURLConnection uc; private boolean forceBody; private static class Entry { final String key; final Object value; private Entry(String key, Object value) { this.key = key; this.value = value; } } Requester(GitHub root) { this.root = root; } /** * Sets the request HTTP header. * <p> * If a header of the same name is already set, this method overrides it. * * @param name * the name * @param value * the value */ public void setHeader(String name, String value) { headers.put(name, value); } /** * With header requester. * * @param name * the name * @param value * the value * @return the requester */ public Requester withHeader(String name, String value) { setHeader(name, value); return this; } public Requester withPreview(String name) { return withHeader("Accept", name); } /** * With requester. * * @param key * the key * @param value * the value * @return the requester */ public Requester with(String key, int value) { return with(key, (Object) value); } /** * With requester. * * @param key * the key * @param value * the value * @return the requester */ public Requester with(String key, long value) { return with(key, (Object) value); } /** * With requester. * * @param key * the key * @param value * the value * @return the requester */ public Requester with(String key, boolean value) { return with(key, (Object) value); } /** * With requester. * * @param key * the key * @param e * the e * @return the requester */ public Requester with(String key, Enum e) { if (e == null) return with(key, (Object) null); return with(key, transformEnum(e)); } /** * With requester. * * @param key * the key * @param value * the value * @return the requester */ public Requester with(String key, String value) { return with(key, (Object) value); } /** * With requester. * * @param key * the key * @param value * the value * @return the requester */ public Requester with(String key, Collection<?> value) { return with(key, (Object) value); } /** * With requester. * * @param key * the key * @param value * the value * @return the requester */ public Requester with(String key, Map<String, String> value) { return with(key, (Object) value); } /** * With requester. * * @param body * the body * @return the requester */ public Requester with(@WillClose /* later */ InputStream body) { this.body = body; return this; } /** * With nullable requester. * * @param key * the key * @param value * the value * @return the requester */ public Requester withNullable(String key, Object value) { args.add(new Entry(key, value)); return this; } /** * With requester. * * @param key * the key * @param value * the value * @return the requester */ public Requester with(String key, Object value) { if (value != null) { args.add(new Entry(key, value)); } return this; } /** * Unlike {@link #with(String, String)}, overrides the existing value * * @param key * the key * @param value * the value * @return the requester */ public Requester set(String key, Object value) { for (int index = 0; index < args.size(); index++) { if (args.get(index).key.equals(key)) { args.set(index, new Entry(key, value)); return this; } } return with(key, value); } /** * Method requester. * * @param method * the method * @return the requester */ public Requester method(String method) { this.method = method; return this; } /** * Content type requester. * * @param contentType * the content type * @return the requester */ public Requester contentType(String contentType) { this.contentType = contentType; return this; } /** * NOT FOR PUBLIC USE. Do not make this method public. * <p> * Sets the path component of api URL without URI encoding. * <p> * Should only be used when passing a literal URL field from a GHObject, such as {@link GHContent#refresh()} or when * needing to set query parameters on requests methods that don't usually have them, such as * {@link GHRelease#uploadAsset(String, InputStream, String)}. * * @param urlOrPath * the content type * @return the requester */ Requester setRawUrlPath(String urlOrPath) { Objects.requireNonNull(urlOrPath); this.urlPath = urlOrPath; return this; } /** * Path component of api URL. Appended to api url. * <p> * If urlPath starts with a slash, it will be URI encoded as a path. If it starts with anything else, it will be * used as is. * * @param urlPathItems * the content type * @return the requester */ public Requester withUrlPath(String... urlPathItems) { if (!this.urlPath.startsWith("/")) { throw new GHException("Cannot append to url path after setting a raw path"); } if (urlPathItems.length == 1 && !urlPathItems[0].startsWith("/")) { return setRawUrlPath(urlPathItems[0]); } String tailUrlPath = String.join("/", urlPathItems); if (this.urlPath.endsWith("/")) { tailUrlPath = StringUtils.stripStart(tailUrlPath, "/"); } else { tailUrlPath = StringUtils.prependIfMissing(tailUrlPath, "/"); } this.urlPath += urlPathEncode(tailUrlPath); return this; } /** * Small number of GitHub APIs use HTTP methods somewhat inconsistently, and use a body where it's not expected. * Normally whether parameters go as query parameters or a body depends on the HTTP verb in use, but this method * forces the parameters to be sent as a body. */ public Requester inBody() { forceBody = true; return this; } /** * Sends a request to the specified URL and checks that it is sucessful. * * @throws IOException * the io exception */ public void send() throws IOException { _fetch(() -> parse(null, null)); } /** * Sends a request and parses the response into the given type via databinding. * * @param <T> * the type parameter * @param type * the type * @return {@link Reader} that reads the response. * @throws IOException * if the server returns 4xx/5xx responses. */ public <T> T fetch(@Nonnull Class<T> type) throws IOException { return _fetch(() -> parse(type, null)); } /** * Sends a request and parses the response into an array of the given type via databinding. * * @param <T> * the type parameter * @param type * the type * @return {@link Reader} that reads the response. * @throws IOException * if the server returns 4xx/5xx responses. */ public <T> T[] fetchArray(@Nonnull Class<T[]> type) throws IOException { T[] result = null; try { // for arrays we might have to loop for pagination // use the iterator to handle it List<T[]> pages = new ArrayList<>(); int totalSize = 0; for (Iterator<T[]> iterator = asIterator(type, 0); iterator.hasNext();) { T[] nextResult = iterator.next(); totalSize += Array.getLength(nextResult); pages.add(nextResult); } result = concatenatePages(type, pages, totalSize); } catch (GHException e) { // if there was an exception inside the iterator it is wrapped as a GHException // if the wrapped exception is an IOException, throw that if (e.getCause() instanceof IOException) { throw (IOException) e.getCause(); } else { throw e; } } return result; } /** * Like {@link #fetch(Class)} but updates an existing object instead of creating a new instance. * * @param <T> * the type parameter * @param existingInstance * the existing instance * @return the t * @throws IOException * the io exception */ public <T> T fetchInto(@Nonnull T existingInstance) throws IOException { return _fetch(() -> parse(null, existingInstance)); } /** * Makes a request and just obtains the HTTP status code. Method does not throw exceptions for many status codes * that would otherwise throw. * * @return the int * @throws IOException * the io exception */ public int fetchHttpStatusCode() throws IOException { return _fetch(() -> uc.getResponseCode()); } /** * As stream input stream. * * @return the input stream * @throws IOException * the io exception */ public InputStream fetchStream() throws IOException { return _fetch(() -> parse(InputStream.class, null)); } private <T> T _fetch(SupplierThrows<T, IOException> supplier) throws IOException { String tailApiUrl = buildTailApiUrl(urlPath); URL url = root.getApiURL(tailApiUrl); return _fetch(tailApiUrl, url, supplier); } private <T> T _fetch(String tailApiUrl, URL url, SupplierThrows<T, IOException> supplier) throws IOException { while (true) {// loop while API rate limit is hit uc = setupConnection(url); try { retryInvalidCached404Response(); return supplier.get(); } catch (IOException e) { handleApiError(e); } finally { noteRateLimit(tailApiUrl); } } } private <T> T[] concatenatePages(Class<T[]> type, List<T[]> pages, int totalLength) { T[] result = type.cast(Array.newInstance(type.getComponentType(), totalLength)); int position = 0; for (T[] page : pages) { final int pageLength = Array.getLength(page); System.arraycopy(page, 0, result, position, pageLength); position += pageLength; } return result; } private String buildTailApiUrl(String tailApiUrl) { if (!isMethodWithBody() && !args.isEmpty()) { try { boolean questionMarkFound = tailApiUrl.indexOf('?') != -1; StringBuilder argString = new StringBuilder(); argString.append(questionMarkFound ? '&' : '?'); for (Iterator<Entry> it = args.listIterator(); it.hasNext();) { Entry arg = it.next(); argString.append(URLEncoder.encode(arg.key, StandardCharsets.UTF_8.name())); argString.append('='); argString.append(URLEncoder.encode(arg.value.toString(), StandardCharsets.UTF_8.name())); if (it.hasNext()) { argString.append('&'); } } tailApiUrl += argString; } catch (UnsupportedEncodingException e) { throw new AssertionError(e); // UTF-8 is mandatory } } return tailApiUrl; } private void noteRateLimit(String tailApiUrl) { if (uc == null) { return; } if (tailApiUrl.startsWith("/search")) { // the search API uses a different rate limit return; } String limitString = uc.getHeaderField("X-RateLimit-Limit"); if (StringUtils.isBlank(limitString)) { // if we are missing a header, return fast return; } String remainingString = uc.getHeaderField("X-RateLimit-Remaining"); if (StringUtils.isBlank(remainingString)) { // if we are missing a header, return fast return; } String resetString = uc.getHeaderField("X-RateLimit-Reset"); if (StringUtils.isBlank(resetString)) { // if we are missing a header, return fast return; } int limit, remaining; long reset; try { limit = Integer.parseInt(limitString); } catch (NumberFormatException e) { if (LOGGER.isLoggable(FINEST)) { LOGGER.log(FINEST, "Malformed X-RateLimit-Limit header value " + limitString, e); } return; } try { remaining = Integer.parseInt(remainingString); } catch (NumberFormatException e) { if (LOGGER.isLoggable(FINEST)) { LOGGER.log(FINEST, "Malformed X-RateLimit-Remaining header value " + remainingString, e); } return; } try { reset = Long.parseLong(resetString); } catch (NumberFormatException e) { if (LOGGER.isLoggable(FINEST)) { LOGGER.log(FINEST, "Malformed X-RateLimit-Reset header value " + resetString, e); } return; } GHRateLimit.Record observed = new GHRateLimit.Record(limit, remaining, reset, uc.getHeaderField("Date")); root.updateCoreRateLimit(observed); } /** * Gets response header. * * @param header * the header * @return the response header */ public String getResponseHeader(String header) { return uc.getHeaderField(header); } /** * Set up the request parameters or POST payload. */ private void buildRequest(HttpURLConnection connection) throws IOException { if (isMethodWithBody()) { connection.setDoOutput(true); if (body == null) { connection.setRequestProperty("Content-type", defaultString(contentType, "application/json")); Map json = new HashMap(); for (Entry e : args) { json.put(e.key, e.value); } MAPPER.writeValue(connection.getOutputStream(), json); } else { connection.setRequestProperty("Content-type", defaultString(contentType, "application/x-www-form-urlencoded")); try { byte[] bytes = new byte[32768]; int read; while ((read = body.read(bytes)) != -1) { connection.getOutputStream().write(bytes, 0, read); } } finally { body.close(); } } } } private boolean isMethodWithBody() { return forceBody || !METHODS_WITHOUT_BODY.contains(method); } <T> PagedIterable<T> toIterable(Class<T[]> type, Consumer<T> consumer) { return new PagedIterableWithConsumer<>(type, consumer); } class PagedIterableWithConsumer<T> extends PagedIterable<T> { private final Class<T[]> clazz; private final Consumer<T> consumer; PagedIterableWithConsumer(Class<T[]> clazz, Consumer<T> consumer) { this.clazz = clazz; this.consumer = consumer; } @Override public PagedIterator<T> _iterator(int pageSize) { final Iterator<T[]> iterator = asIterator(clazz, pageSize); return new PagedIterator<T>(iterator) { @Override protected void wrapUp(T[] page) { if (consumer != null) { for (T item : page) { consumer.accept(item); } } } }; } } /** * Loads paginated resources. * * @param type * type of each page (not the items in the page). * @param pageSize * the size of the * @param <T> * type of each page (not the items in the page). * @return */ <T> Iterator<T> asIterator(Class<T> type, int pageSize) { if (!"GET".equals(method)) { throw new IllegalStateException("Request method \"GET\" is required for iterator."); } if (pageSize > 0) args.add(new Entry("per_page", pageSize)); String tailApiUrl = buildTailApiUrl(urlPath); try { return new PagingIterator<>(type, tailApiUrl, root.getApiURL(tailApiUrl)); } catch (IOException e) { throw new GHException("Unable to build github Api URL", e); } } /** * May be used for any item that has pagination information. * * Works for array responses, also works for search results which are single instances with an array of items * inside. * * @param <T> * type of each page (not the items in the page). */ class PagingIterator<T> implements Iterator<T> { private final Class<T> type; private final String tailApiUrl; /** * The next batch to be returned from {@link #next()}. */ private T next; /** * URL of the next resource to be retrieved, or null if no more data is available. */ private URL url; PagingIterator(Class<T> type, String tailApiUrl, URL url) { this.type = type; this.tailApiUrl = tailApiUrl; this.url = url; } public boolean hasNext() { fetch(); return next != null; } public T next() { fetch(); T r = next; if (r == null) throw new NoSuchElementException(); next = null; return r; } public void remove() { throw new UnsupportedOperationException(); } private void fetch() { if (next != null) return; // already fetched if (url == null) return; // no more data to fetch try { next = _fetch(tailApiUrl, url, () -> parse(type, null)); assert next != null; findNextURL(); } catch (IOException e) { throw new GHException("Failed to retrieve " + url, e); } } /** * Locate the next page from the pagination "Link" tag. */ private void findNextURL() throws MalformedURLException { url = null; // start defensively String link = uc.getHeaderField("Link"); if (link == null) return; for (String token : link.split(", ")) { if (token.endsWith("rel=\"next\"")) { // found the next page. This should look something like int idx = token.indexOf('>'); url = new URL(token.substring(1, idx)); return; } } // no more "next" link. we are done. } } private HttpURLConnection setupConnection(URL url) throws IOException { if (LOGGER.isLoggable(FINE)) { LOGGER.log(FINE, "GitHub API request [" + (root.login == null ? "anonymous" : root.login) + "]: " + method + " " + url.toString()); } HttpURLConnection connection = root.getConnector().connect(url); // if the authentication is needed but no credential is given, try it anyway (so that some calls // that do work with anonymous access in the reduced form should still work.) if (root.encodedAuthorization != null) connection.setRequestProperty("Authorization", root.encodedAuthorization); for (Map.Entry<String, String> e : headers.entrySet()) { String v = e.getValue(); if (v != null) connection.setRequestProperty(e.getKey(), v); } setRequestMethod(connection); connection.setRequestProperty("Accept-Encoding", "gzip"); buildRequest(connection); return connection; } private void setRequestMethod(HttpURLConnection connection) throws IOException { try { connection.setRequestMethod(method); } catch (ProtocolException e) { // JDK only allows one of the fixed set of verbs. Try to override that try { Field $method = HttpURLConnection.class.getDeclaredField("method"); $method.setAccessible(true); $method.set(connection, method); } catch (Exception x) { throw (IOException) new IOException("Failed to set the custom verb").initCause(x); } try { Field $delegate = connection.getClass().getDeclaredField("delegate"); $delegate.setAccessible(true); Object delegate = $delegate.get(connection); if (delegate instanceof HttpURLConnection) { HttpURLConnection nested = (HttpURLConnection) delegate; setRequestMethod(nested); } } catch (NoSuchFieldException x) { // no problem } catch (IllegalAccessException x) { throw (IOException) new IOException("Failed to set the custom verb").initCause(x); } } if (!connection.getRequestMethod().equals(method)) throw new IllegalStateException("Failed to set the request method to " + method); } @CheckForNull private <T> T parse(Class<T> type, T instance) throws IOException { return parse(type, instance, 2); } private <T> T parse(Class<T> type, T instance, int timeouts) throws IOException { InputStreamReader r = null; int responseCode = -1; String responseMessage = null; try { responseCode = uc.getResponseCode(); responseMessage = uc.getResponseMessage(); if (responseCode == 304) { return null; // special case handling for 304 unmodified, as the content will be "" } if (responseCode == 204 && type != null && type.isArray()) { // no content return type.cast(Array.newInstance(type.getComponentType(), 0)); } // Response code 202 means data is being generated still being cached. // This happens in for statistics: // See https://developer.github.com/v3/repos/statistics/#a-word-about-caching // And for fork creation: // See https://developer.github.com/v3/repos/forks/#create-a-fork if (responseCode == 202) { if (uc.getURL().toString().endsWith("/forks")) { LOGGER.log(INFO, "The fork is being created. Please try again in 5 seconds."); } else if (uc.getURL().toString().endsWith("/statistics")) { LOGGER.log(INFO, "The statistics are being generated. Please try again in 5 seconds."); } else { LOGGER.log(INFO, "Received 202 from " + uc.getURL().toString() + " . Please try again in 5 seconds."); } // Maybe throw an exception instead? return null; } if (type != null && type.equals(InputStream.class)) { return type.cast(wrapStream(uc.getInputStream())); } r = new InputStreamReader(wrapStream(uc.getInputStream()), StandardCharsets.UTF_8); String data = IOUtils.toString(r); if (type != null) try { return setResponseHeaders(MAPPER.readValue(data, type)); } catch (JsonMappingException e) { String message = "Failed to deserialize " + data; throw (IOException) new IOException(message).initCause(e); } if (instance != null) { return setResponseHeaders(MAPPER.readerForUpdating(instance).<T>readValue(data)); } return null; } catch (FileNotFoundException e) { // java.net.URLConnection handles 404 exception as FileNotFoundException, // don't wrap exception in HttpException to preserve backward compatibility throw e; } catch (IOException e) { if ((e instanceof SocketException || e instanceof SocketTimeoutException) && timeouts > 0) { LOGGER.log(INFO, "timed out accessing " + uc.getURL() + ". Sleeping 5 seconds before retrying... ; will try" + timeouts + " more time(s)", e); try { Thread.sleep(5000); } catch (InterruptedException ie) { throw (IOException) new InterruptedIOException().initCause(e); } return parse(type, instance, timeouts - 1); } throw new HttpException(responseCode, responseMessage, uc.getURL(), e); } finally { IOUtils.closeQuietly(r); } } private void retryInvalidCached404Response() throws IOException { // WORKAROUND FOR ISSUE #669: // When the Requester detects a 404 response with an ETag (only happpens when the server's 304 // is bogus and would cause cache corruption), try the query again with new request header // that forces the server to not return 304 and return new data instead. // This solution is transparent to users of this library and automatically handles a // situation that was cause insidious and hard to debug bad responses in caching // scenarios. If GitHub ever fixes their issue and/or begins providing accurate ETags to // their 404 responses, this will result in at worst two requests being made for each 404 // responses. However, only the second request will count against rate limit. int responseCode = uc.getResponseCode(); if (responseCode == 404 && Objects.equals(uc.getRequestMethod(), "GET") && uc.getHeaderField("ETag") != null && !Objects.equals(uc.getRequestProperty("Cache-Control"), "no-cache")) { uc = setupConnection(uc.getURL()); // Setting "Cache-Control" to "no-cache" stops the cache from supplying // "If-Modified-Since" or "If-None-Match" values. // This makes GitHub give us current data (not incorrectly cached data) uc.setRequestProperty("Cache-Control", "no-cache"); uc.getResponseCode(); } } private <T> T setResponseHeaders(T readValue) { if (readValue instanceof GHObject[]) { for (GHObject ghObject : (GHObject[]) readValue) { setResponseHeaders(ghObject); } } else if (readValue instanceof GHObject) { setResponseHeaders((GHObject) readValue); } else if (readValue instanceof JsonRateLimit) { // if we're getting a GHRateLimit it needs the server date ((JsonRateLimit) readValue).resources.getCore().recalculateResetDate(uc.getHeaderField("Date")); } return readValue; } private void setResponseHeaders(GHObject readValue) { readValue.responseHeaderFields = uc.getHeaderFields(); } /** * Handles the "Content-Encoding" header. */ private InputStream wrapStream(InputStream in) throws IOException { String encoding = uc.getContentEncoding(); if (encoding == null || in == null) return in; if (encoding.equals("gzip")) return new GZIPInputStream(in); throw new UnsupportedOperationException("Unexpected Content-Encoding: " + encoding); } /** * Handle API error by either throwing it or by returning normally to retry. */ void handleApiError(IOException e) throws IOException { int responseCode; try { responseCode = uc.getResponseCode(); } catch (IOException e2) { // likely to be a network exception (e.g. SSLHandshakeException), // uc.getResponseCode() and any other getter on the response will cause an exception if (LOGGER.isLoggable(FINE)) LOGGER.log(FINE, "Silently ignore exception retrieving response code for '" + uc.getURL() + "'" + " handling exception " + e, e); throw e; } InputStream es = wrapStream(uc.getErrorStream()); if (es != null) { try { String error = IOUtils.toString(es, StandardCharsets.UTF_8); if (e instanceof FileNotFoundException) { // pass through 404 Not Found to allow the caller to handle it intelligently e = (IOException) new GHFileNotFoundException(error).withResponseHeaderFields(uc).initCause(e); } else if (e instanceof HttpException) { HttpException http = (HttpException) e; e = new HttpException(error, http.getResponseCode(), http.getResponseMessage(), http.getUrl(), e); } else { e = (IOException) new GHIOException(error).withResponseHeaderFields(uc).initCause(e); } } finally { IOUtils.closeQuietly(es); } } if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) // 401 Unauthorized == bad creds or OTP request // In the case of a user with 2fa enabled, a header with X-GitHub-OTP // will be returned indicating the user needs to respond with an otp if (uc.getHeaderField("X-GitHub-OTP") != null) throw (IOException) new GHOTPRequiredException().withResponseHeaderFields(uc).initCause(e); else throw e; // usually org.kohsuke.github.HttpException (which extends IOException) if ("0".equals(uc.getHeaderField("X-RateLimit-Remaining"))) { root.rateLimitHandler.onError(e, uc); return; } // Retry-After is not documented but apparently that field exists if (responseCode == HttpURLConnection.HTTP_FORBIDDEN && uc.getHeaderField("Retry-After") != null) { this.root.abuseLimitHandler.onError(e, uc); return; } throw e; } /** * Transform Java Enum into Github constants given its conventions * * @param en * Enum to be transformed * @return a String containing the value of a Github constant */ static String transformEnum(Enum en) { // by convention Java constant names are upper cases, but github uses // lower-case constants. GitHub also uses '-', which in Java we always // replace by '_' return en.toString().toLowerCase(Locale.ENGLISH).replace('_', '-'); } /** * Encode the path to url safe string. * * @param value * string to be path encoded. * @return The encoded string. */ public static String urlPathEncode(String value) { try { return new URI(null, null, value, null, null).toString(); } catch (URISyntaxException ex) { throw new AssertionError(ex); } } private static final List<String> METHODS_WITHOUT_BODY = asList("GET", "DELETE"); private static final Logger LOGGER = Logger.getLogger(Requester.class.getName()); /** * Represents a supplier of results that can throw. * * <p> * This is a <a href="package-summary.html">functional interface</a> whose functional method is {@link #get()}. * * @param <T> * the type of results supplied by this supplier * @param <E> * the type of throwable that could be thrown */ @FunctionalInterface interface SupplierThrows<T, E extends Throwable> { /** * Gets a result. * * @return a result * @throws E */ T get() throws E; } }
package org.lightmare.cache; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.Stack; import java.util.concurrent.atomic.AtomicBoolean; import javax.ejb.TransactionAttributeType; import javax.ejb.TransactionManagementType; import javax.persistence.PersistenceContext; import javax.persistence.PersistenceUnit; import org.lightmare.ejb.handlers.BeanHandler; import org.lightmare.utils.CollectionUtils; /** * Container class to save bean {@link Field} with annotation * {@link PersistenceContext} and bean class * * @author Levan Tsinadze * @since 0.0.45-SNAPSHOT * @see org.lightmare.deploy.BeanLoader#loadBean(org.lightmare.deploy.BeanLoader.BeanParameters) * @see org.lightmare.ejb.EjbConnector#connectToBean(MetaData) * @see org.lightmare.ejb.EjbConnector#createRestHandler(MetaData) * @see org.lightmare.ejb.handlers.BeanHandler */ public class MetaData { // EJB bean class private Class<?> beanClass; // EJB bean implementation interfaces private Class<?>[] interfaceClasses; // All EJB local interfaces private Class<?>[] localInterfaces; // All EJB remote interfaces private Class<?>[] remoteInterfaces; // EJB bean's Field to set JTA UserTransaction instance private Field transactionField; // All connections for appropriated EJB bean private Collection<ConnectionData> connections; // Appropriated ClassLoader with loaded EJB bean class private ClassLoader loader; // Check if appropriated EJB bean is in deployment progress private AtomicBoolean inProgress = new AtomicBoolean(); // Check if appropriated EJB bean has bean managed or container managed transactions private boolean transactional; private TransactionAttributeType transactionAttrType; private TransactionManagementType transactionManType; private List<InjectionData> injects; private Collection<Field> unitFields; private Queue<InterceptorData> interceptors; private BeanHandler handler; public Class<?> getBeanClass() { return beanClass; } public void setBeanClass(Class<?> beanClass) { this.beanClass = beanClass; } public Class<?>[] getInterfaceClasses() { return interfaceClasses; } public void setInterfaceClasses(Class<?>[] interfaceClasses) { this.interfaceClasses = interfaceClasses; } public Class<?>[] getLocalInterfaces() { return localInterfaces; } public void setLocalInterfaces(Class<?>[] localInterfaces) { this.localInterfaces = localInterfaces; } public Class<?>[] getRemoteInterfaces() { return remoteInterfaces; } public void setRemoteInterfaces(Class<?>[] remoteInterfaces) { this.remoteInterfaces = remoteInterfaces; } public Field getTransactionField() { return transactionField; } public void setTransactionField(Field transactionField) { this.transactionField = transactionField; } public Collection<ConnectionData> getConnections() { return connections; } public void setConnections(Collection<ConnectionData> connections) { this.connections = connections; } /** * Caches passed connection information * * @param connection */ public void addConnection(ConnectionData connection) { if (connections == null) { connections = new ArrayList<ConnectionData>(); } connections.add(connection); } /** * Caches {@link javax.persistence.PersistenceUnit} annotated field and unit * name to cache * * @param unitName * @param unitField */ private void addUnitField(String unitName, Field unitField) { for (ConnectionData connection : connections) { if (unitName.equals(connection.getUnitName())) { connection.setUnitField(unitField); } } } /** * Adds {@link javax.ejb.PersistenceUnit} annotated field to * {@link MetaData} for cache * * @param unitFields */ public void addUnitFields(Collection<Field> unitFields) { if (CollectionUtils.validAll(connections, unitFields)) { String unitName; for (Field unitField : unitFields) { unitName = unitField.getAnnotation(PersistenceUnit.class) .unitName(); addUnitField(unitName, unitField); } this.unitFields = unitFields; } } public ClassLoader getLoader() { return loader; } public void setLoader(ClassLoader loader) { this.loader = loader; } public boolean isInProgress() { return inProgress.get(); } public void setInProgress(boolean inProgress) { this.inProgress.getAndSet(inProgress); } public boolean isTransactional() { return transactional; } public void setTransactional(boolean transactional) { this.transactional = transactional; } public TransactionAttributeType getTransactionAttrType() { return transactionAttrType; } public void setTransactionAttrType( TransactionAttributeType transactionAttrType) { this.transactionAttrType = transactionAttrType; } public TransactionManagementType getTransactionManType() { return transactionManType; } public void setTransactionManType( TransactionManagementType transactionManType) { this.transactionManType = transactionManType; } public List<InjectionData> getInjects() { return injects; } /** * Adds passed {@link InjectionData} to cache * * @param inject */ public void addInject(InjectionData inject) { if (injects == null) { injects = new ArrayList<InjectionData>(); } injects.add(inject); } public Collection<Field> getUnitFields() { return this.unitFields; } /** * Offers {@link InterceptorData} to {@link Stack} to process request by * order * * @param interceptor */ public void addInterceptor(InterceptorData interceptor) { if (interceptors == null) { interceptors = new LinkedList<InterceptorData>(); } interceptors.offer(interceptor); } public Collection<InterceptorData> getInterceptors() { return interceptors; } public BeanHandler getHandler() { return handler; } public void setHandler(BeanHandler handler) { this.handler = handler; } }
package org.petapico.npop; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import net.trustyuri.TrustyUriException; import org.nanopub.MalformedNanopubException; import org.nanopub.MultiNanopubRdfHandler; import org.nanopub.MultiNanopubRdfHandler.NanopubHandler; import org.nanopub.Nanopub; import org.nanopub.NanopubImpl; import org.nanopub.NanopubUtils; import org.nanopub.extra.index.IndexUtils; import org.nanopub.extra.index.NanopubIndex; import org.nanopub.extra.index.NanopubIndexCreator; import org.nanopub.extra.index.SimpleIndexCreator; import org.openrdf.model.URI; import org.openrdf.model.impl.URIImpl; import org.openrdf.rio.RDFFormat; import org.openrdf.rio.RDFHandlerException; import org.openrdf.rio.RDFParseException; import org.openrdf.rio.Rio; import com.beust.jcommander.JCommander; import com.beust.jcommander.ParameterException; public class IndexReuse { @com.beust.jcommander.Parameter(description = "input-nanopub-cache", required = true) private List<File> inputNanopubCache = new ArrayList<File>(); @com.beust.jcommander.Parameter(names = "-x", description = "Index nanopubs to be reused (need to be sorted; no subindex supported)") private File reuseIndexFile; @com.beust.jcommander.Parameter(names = "-o", description = "Output file of new index nanopublications") private File outputFile; @com.beust.jcommander.Parameter(names = "-a", description = "Output file of all index nanopublications") private File allOutputFile; @com.beust.jcommander.Parameter(names = "-r", description = "Append line to this table file") private File tableFile; @com.beust.jcommander.Parameter(names = "--reuse-format", description = "Format of the nanopubs to be reused: trig, nq, trix, trig.gz, ...") private String reuseFormat; @com.beust.jcommander.Parameter(names = "--out-format", description = "Format of the output nanopubs: trig, nq, trix, trig.gz, ...") private String outFormat; @com.beust.jcommander.Parameter(names = "-s", description = "Add npx:supersedes backlinks for changed nanopublications") private boolean addSupersedesBacklinks = false; @com.beust.jcommander.Parameter(names = "-U", description = "Base URI for index nanopubs") private String baseUri = "http://purl.org/np/"; @com.beust.jcommander.Parameter(names = "-T", description = "Title of index") private String iTitle; @com.beust.jcommander.Parameter(names = "-D", description = "Description of index") private String iDesc; @com.beust.jcommander.Parameter(names = "-C", description = "Creator of index") private List<String> iCreators = new ArrayList<>(); @com.beust.jcommander.Parameter(names = "-A", description = "'See also' resources") private List<String> seeAlso = new ArrayList<>(); public static void main(String[] args) { NanopubImpl.ensureLoaded(); IndexReuse obj = new IndexReuse(); JCommander jc = new JCommander(obj); try { jc.parse(args); } catch (ParameterException ex) { jc.usage(); System.exit(1); } try { obj.run(); } catch (Exception ex) { ex.printStackTrace(); System.exit(1); } } private URI previousIndexUri = null; private NanopubIndex lastIndexNp; private RDFFormat rdfReuseFormat, rdfOutFormat; private PrintStream outputStream = System.out; private PrintStream allOutputStream; private List<String> contentNanopubList = new ArrayList<>(); private Map<String,Boolean> contentNanopubMap = new HashMap<>(); private int reuseCount; private boolean reuseStopped = false; private NanopubIndexCreator indexCreator = null; private void run() throws IOException, RDFParseException, RDFHandlerException, MalformedNanopubException, TrustyUriException { reuseCount = 0; for (File inputFile : inputNanopubCache) { if (outputFile == null) { if (outFormat == null) { outFormat = "trig"; } rdfOutFormat = Rio.getParserFormatForFileName("file." + outFormat); } else { rdfOutFormat = Rio.getParserFormatForFileName(outputFile.getName()); if (outputFile.getName().endsWith(".gz")) { outputStream = new PrintStream(new GZIPOutputStream(new FileOutputStream(outputFile))); } else { outputStream = new PrintStream(new FileOutputStream(outputFile)); } } if (allOutputFile != null) { if (allOutputFile.getName().endsWith(".gz")) { allOutputStream = new PrintStream(new GZIPOutputStream(new FileOutputStream(allOutputFile))); } else { allOutputStream = new PrintStream(new FileOutputStream(allOutputFile)); } } BufferedReader br = null; try { if (inputFile.getName().endsWith(".gz")) { br = new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream(inputFile)))); } else { br = new BufferedReader(new FileReader(inputFile)); } String line; while ((line = br.readLine()) != null) { line = line.trim(); if (line.isEmpty()) continue; String[] columns = line.split(" "); String uri = columns[0]; contentNanopubList.add(uri); contentNanopubMap.put(uri, true); } } finally { if (br != null) br.close(); } if (reuseIndexFile != null) { if (reuseFormat != null) { rdfReuseFormat = Rio.getParserFormatForFileName("file." + reuseFormat); } else { rdfReuseFormat = Rio.getParserFormatForFileName(reuseIndexFile.toString()); } MultiNanopubRdfHandler.process(rdfReuseFormat, reuseIndexFile, new NanopubHandler() { @Override public void handleNanopub(Nanopub np) { try { processIndexNanopub(np); } catch (IOException ex) { throw new RuntimeException(ex); } catch (RDFHandlerException ex) { throw new RuntimeException(ex); } catch (MalformedNanopubException ex) { throw new RuntimeException(ex); } } }); } if (lastIndexNp != null && lastIndexNp.isIncomplete()) { throw new RuntimeException("Last index nanopub in file is not a complete index"); } indexCreator = new IndexCreator(previousIndexUri); if (lastIndexNp != null && addSupersedesBacklinks) { indexCreator.setSupersededIndex(lastIndexNp); } for (String npUri : contentNanopubList) { if (!contentNanopubMap.containsKey(npUri)) continue; indexCreator.addElement(new URIImpl(npUri)); } indexCreator.finalizeNanopub(); outputStream.flush(); if (outputStream != System.out) { outputStream.close(); } if (allOutputStream != null) { allOutputStream.flush(); allOutputStream.close(); } System.err.println("Index reuse count: " + reuseCount); if (tableFile != null) { PrintStream st = new PrintStream(new FileOutputStream(tableFile, true)); st.println(inputFile.getName() + "," + reuseCount); st.close(); } } } private void processIndexNanopub(Nanopub np) throws IOException, RDFHandlerException, MalformedNanopubException { NanopubIndex npi = IndexUtils.castToIndex(np); lastIndexNp = npi; if (reuseStopped) { return; } if (!npi.getSubIndexes().isEmpty()) { throw new RuntimeException("Subindexes are not supported"); } if (previousIndexUri == null && npi.getAppendedIndex() != null) { throw new RuntimeException("Starting index nanopub expected first in file"); } else if (previousIndexUri != null && npi.getAppendedIndex() == null) { throw new RuntimeException("Non-appending index nanopub found after first position"); } boolean canBeReused = true; for (URI c : npi.getElements()) { if (!contentNanopubMap.containsKey(c.stringValue())) { canBeReused = false; break; } } if (canBeReused && !npi.getElements().isEmpty()) { reuseCount++; outputOld(npi); for (URI c : npi.getElements()) { contentNanopubMap.remove(c.stringValue()); } previousIndexUri = npi.getUri(); } else { reuseStopped = true; } } private void output(NanopubIndex npi) { try { outputStream.print(NanopubUtils.writeToString(npi, rdfOutFormat) + "\n\n"); if (allOutputStream != null) { allOutputStream.print(NanopubUtils.writeToString(npi, rdfOutFormat) + "\n\n"); } } catch (Exception ex) { throw new RuntimeException(ex); } } private void outputOld(NanopubIndex npi) { try { if (allOutputStream != null) { allOutputStream.print(NanopubUtils.writeToString(npi, rdfOutFormat) + "\n\n"); } } catch (Exception ex) { throw new RuntimeException(ex); } } private class IndexCreator extends SimpleIndexCreator { public IndexCreator(URI previousIndexUri) { super(previousIndexUri); setBaseUri(baseUri); if (iTitle != null) { setTitle(iTitle); } if (iDesc != null) { setDescription(iDesc); } for (String creator : iCreators) { addCreator(creator); } for (String sa : seeAlso) { addSeeAlsoUri(new URIImpl(sa)); } } @Override public void handleIncompleteIndex(NanopubIndex npi) { output(npi); } @Override public void handleCompleteIndex(NanopubIndex npi) { System.out.println("Index URI: " + npi.getUri()); output(npi); } } }
package org.pignat.app.qr2gerber; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.SwingUtilities; import net.miginfocom.swing.MigLayout; import java.awt.Dimension; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.EnumMap; import com.google.zxing.EncodeHintType; import com.google.zxing.WriterException; import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; public class App extends JFrame implements ActionListener { class CustomDraw extends JPanel { int lx; int ly; transient BufferedImage img = null; CustomDraw(int x, int y) { lx = x; ly = y; } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); if (img != null) { g.drawImage(img, 0, 0, this); } } @Override public Dimension getPreferredSize() { return new Dimension(lx, ly); } @Override public Dimension getMinimumSize() { return new Dimension(lx, ly); } public void setImage(BufferedImage i) { img = i; repaint(); } } private JButton gobutton; private JButton browseButton; private JTextField stringField; private JTextField sizeField; private JTextField destField; private CustomDraw preview; public App() { setLayout(new MigLayout()); stringField = new JTextField("https://github.com/RandomReaper/qr2gerber", 35); sizeField = new JTextField("10.0", 35); gobutton = new JButton("Generate"); gobutton.addActionListener(this); browseButton = new JButton("browse"); browseButton.addActionListener(this); destField = new JTextField("/tmp/toto.txt"); preview = new CustomDraw(177, 177); setDefaultCloseOperation(EXIT_ON_CLOSE); setTitle("qr2gerber"); setSize(400, 300); setLocationRelativeTo(null); add(new JLabel("String")); add(stringField , "wrap"); add(new JLabel("Size (mm): ") , "gap unrelated"); add(sizeField , "wrap"); add(new JLabel("Preview")); add(preview , "wrap, grow"); add(new JLabel("Save to")); add(destField , "grow"); add(browseButton , "wrap"); add(gobutton , "wrap"); pack(); } public void actionPerformed(ActionEvent e) { if (e.getSource() == gobutton) { try { double size = Double.parseDouble(sizeField.getText()); QRPlusInfo qrcode = null; EnumMap<EncodeHintType, Object> encodingOptions = new EnumMap<EncodeHintType, Object>(EncodeHintType.class); encodingOptions.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); qrcode = QRPlusInfo.encode(stringField.getText(), encodingOptions).invert(); QRPlusInfo.encode(stringField.getText()); preview.setImage(MatrixToImageWriter.toBufferedImage(QRPlusInfo.encode(stringField.getText()).m_qrcode)); preview.setSize(qrcode.size(), qrcode.size()); QRtoGerber q2g = new QRtoGerber(qrcode, size); PrintWriter out = new PrintWriter(destField.getText()); out.println(q2g.toGerber()); out.close(); } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (WriterException ex) { ex.printStackTrace(); } } if (e.getSource() == browseButton) { final JFileChooser fc = new JFileChooser(); int returnVal = fc.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { destField.setText(fc.getSelectedFile().getAbsolutePath()); } } } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { App ex = new App(); ex.setVisible(true); } }); } }
package org.telegram.mtproto; import org.telegram.actors.*; import org.telegram.mtproto.backoff.ExponentalBackoff; import org.telegram.mtproto.log.Logger; import org.telegram.mtproto.schedule.PrepareSchedule; import org.telegram.mtproto.schedule.PreparedPackage; import org.telegram.mtproto.schedule.Scheduller; import org.telegram.mtproto.secure.Entropy; import org.telegram.mtproto.state.AbsMTProtoState; import org.telegram.mtproto.state.KnownSalt; import org.telegram.mtproto.time.TimeOverlord; import org.telegram.mtproto.tl.*; import org.telegram.mtproto.transport.ConnectionType; import org.telegram.mtproto.transport.TcpContext; import org.telegram.mtproto.transport.TcpContextCallback; import org.telegram.mtproto.transport.TransportRate; import org.telegram.mtproto.util.BytesCache; import org.telegram.tl.DeserializeException; import org.telegram.tl.StreamingUtils; import org.telegram.tl.TLMethod; import org.telegram.tl.TLObject; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicInteger; import static org.telegram.mtproto.secure.CryptoUtils.*; import static org.telegram.mtproto.util.TimeUtil.getUnixTime; import static org.telegram.tl.StreamingUtils.*; public class MTProto { private static final int MODE_GENERAL = 0; private static final int MODE_KEEP_ALIVE_LOW = 1; private static final int MODE_LOW = 2; private static final AtomicInteger instanceIndex = new AtomicInteger(1000); private static final int MESSAGES_CACHE = 100; private static final int MESSAGES_CACHE_MIN = 10; private static final int MAX_INTERNAL_FLOOD_WAIT = 10;//10 sec private static final int PING_INTERVAL_REQUEST = 60000;// 1 min private static final int PING_INTERVAL = 75;//75 secs private static final int PING_INTERVAL_REQUEST_LOW_MODE = 5 * 60 * 1000; // 5 Min private static final int PING_INTERVAL_LOW_MODE = 6 * 60 * 1000; // 6 min private static final int CONNECTION_KEEP_ALIVE_LOW = 30 * 1000; // 30 secs private static final int ERROR_MSG_ID_TOO_SMALL = 16; private static final int ERROR_MSG_ID_TOO_BIG = 17; private static final int ERROR_MSG_ID_BITS = 18; private static final int ERROR_CONTAINER_MSG_ID_INCORRECT = 19; private static final int ERROR_TOO_OLD = 20; private static final int ERROR_SEQ_NO_TOO_SMALL = 32; private static final int ERROR_SEQ_NO_TOO_BIG = 33; private static final int ERROR_SEQ_EXPECTED_EVEN = 34; private static final int ERROR_SEQ_EXPECTED_ODD = 35; private static final int ERROR_BAD_SERVER_SALT = 48; private static final int ERROR_BAD_CONTAINER = 64; private static final int PING_TIMEOUT = 60 * 1000; private static final int RESEND_TIMEOUT = 60 * 1000; private static final int FUTURE_REQUEST_COUNT = 64; private static final int FUTURE_MINIMAL = 5; private static final long FUTURE_TIMEOUT = 30 * 60 * 1000;//30 secs private static final boolean USE_CHECKSUM = false; private final String TAG; private final int INSTANCE_INDEX; private MTProtoContext protoContext; private int desiredConnectionCount; private final HashSet<TcpContext> contexts = new HashSet<TcpContext>(); private final HashMap<Integer, Integer> contextConnectionId = new HashMap<Integer, Integer>(); private final HashSet<Integer> connectedContexts = new HashSet<Integer>(); private final HashSet<Integer> initedContext = new HashSet<Integer>(); private TcpContextCallback tcpListener; private final Scheduller scheduller; private SchedullerThread schedullerThread; private final ConcurrentLinkedQueue<MTMessage> inQueue = new ConcurrentLinkedQueue<MTMessage>(); private ResponseProcessor responseProcessor; private final ArrayList<Long> receivedMessages = new ArrayList<Long>(); private byte[] authKey; private byte[] authKeyId; private byte[] session; private boolean isClosed; private MTProtoCallback callback; private AbsMTProtoState state; private long futureSaltsRequestedTime = Long.MIN_VALUE; private long futureSaltsRequestId = -1; private int roundRobin = 0; private TransportRate connectionRate; private long lastPingTime = System.nanoTime() / 1000000L - PING_INTERVAL_REQUEST * 10; private ExponentalBackoff exponentalBackoff; private ActorSystem actorSystem; private int mode = MODE_GENERAL; private ConnectorMessenger connectionActor; public MTProto(AbsMTProtoState state, MTProtoCallback callback, CallWrapper callWrapper, int connectionsCount) { this.INSTANCE_INDEX = instanceIndex.incrementAndGet(); this.TAG = "MTProto#" + INSTANCE_INDEX; this.exponentalBackoff = new ExponentalBackoff(TAG + "#BackOff"); this.state = state; this.connectionRate = new TransportRate(state.getAvailableConnections()); this.callback = callback; this.authKey = state.getAuthKey(); this.authKeyId = substring(SHA1(authKey), 12, 8); this.protoContext = new MTProtoContext(); this.desiredConnectionCount = connectionsCount; this.session = Entropy.generateSeed(8); this.tcpListener = new TcpListener(); this.scheduller = new Scheduller(this, callWrapper); this.schedullerThread = new SchedullerThread(); this.schedullerThread.start(); this.responseProcessor = new ResponseProcessor(); this.responseProcessor.start(); this.actorSystem = new ActorSystem(); this.actorSystem.addThread("connector"); this.connectionActor = new ConnectorMessenger(new ConnectionActor(actorSystem).self(), null); this.connectionActor.check(); } public AbsMTProtoState getState() { return state; } public void resetNetworkBackoff() { this.exponentalBackoff.reset(); } public void reloadConnectionInformation() { this.connectionRate = new TransportRate(state.getAvailableConnections()); } public int getInstanceIndex() { return INSTANCE_INDEX; } /* package */ Scheduller getScheduller() { return scheduller; } /* package */ int getDesiredConnectionCount() { return desiredConnectionCount; } @Override public String toString() { return "mtproto#" + INSTANCE_INDEX; } public void close() { if (!isClosed) { this.isClosed = true; // if (this.connectionFixerThread != null) { // this.connectionFixerThread.interrupt(); if (this.schedullerThread != null) { this.schedullerThread.interrupt(); } if (this.responseProcessor != null) { this.responseProcessor.interrupt(); } closeConnections(); } } public boolean isClosed() { return isClosed; } public void closeConnections() { synchronized (contexts) { for (TcpContext context : contexts) { context.close(); scheduller.onConnectionDies(context.getContextId()); } contexts.clear(); connectionActor.check(); } } private boolean needProcessing(long messageId) { synchronized (receivedMessages) { if (receivedMessages.contains(messageId)) { return false; } if (receivedMessages.size() > MESSAGES_CACHE_MIN) { boolean isSmallest = true; for (Long l : receivedMessages) { if (messageId > l) { isSmallest = false; break; } } if (isSmallest) { return false; } } while (receivedMessages.size() >= MESSAGES_CACHE - 1) { receivedMessages.remove(0); } receivedMessages.add(messageId); } return true; } public void forgetMessage(int id) { scheduller.forgetMessage(id); } public int sendRpcMessage(TLMethod request, long timeout, boolean highPriority) { return sendMessage(request, timeout, true, highPriority); } public int sendMessage(TLObject request, long timeout, boolean isRpc, boolean highPriority) { int id = scheduller.postMessage(request, isRpc, timeout, highPriority); Logger.d(TAG, "sendMessage #" + id + " " + request.toString()); synchronized (scheduller) { scheduller.notifyAll(); } return id; } private void onMTMessage(MTMessage mtMessage) { if (futureSaltsRequestedTime - System.nanoTime() > FUTURE_TIMEOUT * 1000L) { Logger.d(TAG, "Salt check timeout"); int count = state.maximumCachedSalts(getUnixTime(mtMessage.getMessageId())); if (count < FUTURE_MINIMAL) { Logger.d(TAG, "Too fiew actual salts: " + count + ", requesting news"); futureSaltsRequestId = scheduller.postMessage(new MTGetFutureSalts(FUTURE_REQUEST_COUNT), false, FUTURE_TIMEOUT); futureSaltsRequestedTime = System.nanoTime(); } } if (mtMessage.getSeqNo() % 2 == 1) { scheduller.confirmMessage(mtMessage.getMessageId()); } if (!needProcessing(mtMessage.getMessageId())) { if (Logger.LOG_IGNORED) { Logger.d(TAG, "Ignoring messages #" + mtMessage.getMessageId()); } return; } try { TLObject intMessage = protoContext.deserializeMessage(new ByteArrayInputStream(mtMessage.getContent())); onMTProtoMessage(mtMessage.getMessageId(), intMessage); } catch (DeserializeException e) { onApiMessage(mtMessage.getContent()); } catch (IOException e) { Logger.e(TAG, e); } } private void onApiMessage(byte[] data) { callback.onApiMessage(data, this); } private void onMTProtoMessage(long msgId, TLObject object) { Logger.d(TAG, "MTProtoMessage: " + object.toString()); if (object instanceof MTBadMessage) { MTBadMessage badMessage = (MTBadMessage) object; Logger.d(TAG, "BadMessage: " + badMessage.getErrorCode() + " #" + badMessage.getBadMsgId()); scheduller.onMessageConfirmed(badMessage.getBadMsgId()); long time = scheduller.getMessageIdGenerationTime(badMessage.getBadMsgId()); if (time != 0) { if (badMessage.getErrorCode() == ERROR_MSG_ID_TOO_BIG || badMessage.getErrorCode() == ERROR_MSG_ID_TOO_SMALL) { long delta = System.nanoTime() / 1000000 - time; TimeOverlord.getInstance().onForcedServerTimeArrived((msgId >> 32) * 1000, delta); if (badMessage.getErrorCode() == ERROR_MSG_ID_TOO_BIG) { scheduller.resetMessageId(); } scheduller.resendAsNewMessage(badMessage.getBadMsgId()); requestSchedule(); } else if (badMessage.getErrorCode() == ERROR_SEQ_NO_TOO_BIG || badMessage.getErrorCode() == ERROR_SEQ_NO_TOO_SMALL) { if (scheduller.isMessageFromCurrentGeneration(badMessage.getBadMsgId())) { Logger.d(TAG, "Resetting session"); session = Entropy.generateSeed(8); scheduller.resetSession(); } scheduller.resendAsNewMessage(badMessage.getBadMsgId()); requestSchedule(); } else if (badMessage.getErrorCode() == ERROR_BAD_SERVER_SALT) { long salt = ((MTBadServerSalt) badMessage).getNewSalt(); // Sync time long delta = System.nanoTime() / 1000000 - time; TimeOverlord.getInstance().onMethodExecuted(badMessage.getBadMsgId(), msgId, delta); state.badServerSalt(salt); Logger.d(TAG, "Reschedule messages because bad_server_salt #" + badMessage.getBadMsgId()); scheduller.resendAsNewMessage(badMessage.getBadMsgId()); requestSchedule(); } else if (badMessage.getErrorCode() == ERROR_BAD_CONTAINER || badMessage.getErrorCode() == ERROR_CONTAINER_MSG_ID_INCORRECT) { scheduller.resendMessage(badMessage.getBadMsgId()); requestSchedule(); } else if (badMessage.getErrorCode() == ERROR_TOO_OLD) { scheduller.resendAsNewMessage(badMessage.getBadMsgId()); requestSchedule(); } else { if (Logger.LOG_IGNORED) { Logger.d(TAG, "Ignored BadMsg #" + badMessage.getErrorCode() + " (" + badMessage.getBadMsgId() + ", " + badMessage.getBadMsqSeqno() + ")"); } scheduller.forgetMessageByMsgId(badMessage.getBadMsgId()); } } else { if (Logger.LOG_IGNORED) { Logger.d(TAG, "Unknown package #" + badMessage.getBadMsgId()); } } } else if (object instanceof MTMsgsAck) { MTMsgsAck ack = (MTMsgsAck) object; String log = ""; for (Long ackMsgId : ack.getMessages()) { scheduller.onMessageConfirmed(ackMsgId); if (log.length() > 0) { log += ", "; } log += ackMsgId; int id = scheduller.mapSchedullerId(ackMsgId); if (id > 0) { callback.onConfirmed(id); } } Logger.d(TAG, "msgs_ack: " + log); } else if (object instanceof MTRpcResult) { MTRpcResult result = (MTRpcResult) object; Logger.d(TAG, "rpc_result: " + result.getMessageId()); int id = scheduller.mapSchedullerId(result.getMessageId()); if (id > 0) { int responseConstructor = readInt(result.getContent()); if (responseConstructor == MTRpcError.CLASS_ID) { try { MTRpcError error = (MTRpcError) protoContext.deserializeMessage(result.getContent()); BytesCache.getInstance().put(result.getContent()); if (error.getErrorCode() == 420) { if (error.getErrorTag().startsWith("FLOOD_WAIT_")) { // Secs int delay = Integer.parseInt(error.getErrorTag().substring("FLOOD_WAIT_".length())); if (delay <= MAX_INTERNAL_FLOOD_WAIT) { scheduller.resendAsNewMessageDelayed(result.getMessageId(), delay * 1000); requestSchedule(); return; } } } if (error.getErrorCode() == 401) { if (error.getErrorTag().equals("AUTH_KEY_UNREGISTERED") || error.getErrorTag().equals("AUTH_KEY_INVALID") || error.getErrorTag().equals("USER_DEACTIVATED") || error.getErrorTag().equals("SESSION_REVOKED") || error.getErrorTag().equals("SESSION_EXPIRED")) { Logger.w(TAG, "Auth key invalidated"); callback.onAuthInvalidated(this); close(); return; } } callback.onRpcError(id, error.getErrorCode(), error.getMessage(), this); scheduller.forgetMessage(id); } catch (IOException e) { Logger.e(TAG, e); return; } } else { Logger.d(TAG, "rpc_result: " + result.getMessageId() + " #" + Integer.toHexString(responseConstructor)); callback.onRpcResult(id, result.getContent(), this); BytesCache.getInstance().put(result.getContent()); scheduller.forgetMessage(id); } } else { if (Logger.LOG_IGNORED) { Logger.d(TAG, "ignored rpc_result: " + result.getMessageId()); } BytesCache.getInstance().put(result.getContent()); } scheduller.onMessageConfirmed(result.getMessageId()); long time = scheduller.getMessageIdGenerationTime(result.getMessageId()); if (time != 0) { long delta = System.nanoTime() / 1000000 - time; TimeOverlord.getInstance().onMethodExecuted(result.getMessageId(), msgId, delta); } } else if (object instanceof MTPong) { MTPong pong = (MTPong) object; if (Logger.LOG_PING) { Logger.d(TAG, "pong: " + pong.getPingId()); } scheduller.onMessageConfirmed(pong.getMessageId()); scheduller.forgetMessageByMsgId(pong.getMessageId()); long time = scheduller.getMessageIdGenerationTime(pong.getMessageId()); if (time != 0) { long delta = System.nanoTime() / 1000000 - time; TimeOverlord.getInstance().onMethodExecuted(pong.getMessageId(), msgId, delta); } } else if (object instanceof MTFutureSalts) { MTFutureSalts salts = (MTFutureSalts) object; scheduller.onMessageConfirmed(salts.getRequestId()); scheduller.forgetMessageByMsgId(salts.getRequestId()); long time = scheduller.getMessageIdGenerationTime(salts.getRequestId()); if (time > 0) { KnownSalt[] knownSalts = new KnownSalt[salts.getSalts().size()]; for (int i = 0; i < knownSalts.length; i++) { MTFutureSalt salt = salts.getSalts().get(i); knownSalts[i] = new KnownSalt(salt.getValidSince(), salt.getValidUntil(), salt.getSalt()); } long delta = System.nanoTime() / 1000000 - time; TimeOverlord.getInstance().onForcedServerTimeArrived(salts.getNow(), delta); state.mergeKnownSalts(salts.getNow(), knownSalts); } } else if (object instanceof MTMessageDetailedInfo) { MTMessageDetailedInfo detailedInfo = (MTMessageDetailedInfo) object; Logger.d(TAG, "msg_detailed_info: " + detailedInfo.getMsgId() + ", answer: " + detailedInfo.getAnswerMsgId()); if (receivedMessages.contains(detailedInfo.getAnswerMsgId())) { scheduller.confirmMessage(detailedInfo.getAnswerMsgId()); } else { int id = scheduller.mapSchedullerId(detailedInfo.getMsgId()); if (id > 0) { scheduller.postMessage(new MTNeedResendMessage(new long[]{detailedInfo.getAnswerMsgId()}), false, RESEND_TIMEOUT); } else { scheduller.confirmMessage(detailedInfo.getAnswerMsgId()); scheduller.forgetMessageByMsgId(detailedInfo.getMsgId()); } } } else if (object instanceof MTNewMessageDetailedInfo) { MTNewMessageDetailedInfo detailedInfo = (MTNewMessageDetailedInfo) object; Logger.d(TAG, "msg_new_detailed_info: " + detailedInfo.getAnswerMsgId()); if (receivedMessages.contains(detailedInfo.getAnswerMsgId())) { scheduller.confirmMessage(detailedInfo.getAnswerMsgId()); } else { scheduller.postMessage(new MTNeedResendMessage(new long[]{detailedInfo.getAnswerMsgId()}), false, RESEND_TIMEOUT); } } else if (object instanceof MTNewSessionCreated) { callback.onSessionCreated(this); } else { if (Logger.LOG_IGNORED) { Logger.d(TAG, "Ignored MTProto message " + object.toString()); } } } private void internalSchedule() { long time = System.nanoTime() / 1000000; if (mode == MODE_GENERAL) { if (time - lastPingTime > PING_INTERVAL_REQUEST) { lastPingTime = time; synchronized (contexts) { for (TcpContext context : contexts) { scheduller.postMessageDelayed( new MTPingDelayDisconnect(Entropy.generateRandomId(), PING_INTERVAL), false, PING_INTERVAL_REQUEST, 0, context.getContextId(), false); } } } } } public void requestSchedule() { synchronized (scheduller) { scheduller.notifyAll(); } } private EncryptedMessage encrypt(int seqNo, long messageId, byte[] content) throws IOException { long salt = state.findActualSalt((int) (TimeOverlord.getInstance().getServerTime() / 1000)); ByteArrayOutputStream messageBody = new ByteArrayOutputStream(); writeLong(salt, messageBody); writeByteArray(session, messageBody); writeLong(messageId, messageBody); writeInt(seqNo, messageBody); writeInt(content.length, messageBody); writeByteArray(content, messageBody); byte[] innerData = messageBody.toByteArray(); byte[] msgKey = substring(SHA1(innerData), 4, 16); int fastConfirm = readInt(SHA1(innerData)) | (1 << 31); ByteArrayOutputStream out = new ByteArrayOutputStream(); writeByteArray(authKeyId, out); writeByteArray(msgKey, out); byte[] sha1_a = SHA1(msgKey, substring(authKey, 0, 32)); byte[] sha1_b = SHA1(substring(authKey, 32, 16), msgKey, substring(authKey, 48, 16)); byte[] sha1_c = SHA1(substring(authKey, 64, 32), msgKey); byte[] sha1_d = SHA1(msgKey, substring(authKey, 96, 32)); byte[] aesKey = concat(substring(sha1_a, 0, 8), substring(sha1_b, 8, 12), substring(sha1_c, 4, 12)); byte[] aesIv = concat(substring(sha1_a, 8, 12), substring(sha1_b, 0, 8), substring(sha1_c, 16, 4), substring(sha1_d, 0, 8)); byte[] encoded = AES256IGEEncrypt(align(innerData, 16), aesIv, aesKey); writeByteArray(encoded, out); EncryptedMessage res = new EncryptedMessage(); res.data = out.toByteArray(); res.fastConfirm = fastConfirm; return res; } private byte[] optimizedSHA(byte[] serverSalt, byte[] session, long msgId, int seq, int len, byte[] data, int datalen) { try { MessageDigest crypt = MessageDigest.getInstance("SHA-1"); crypt.reset(); crypt.update(serverSalt); crypt.update(session); crypt.update(longToBytes(msgId)); crypt.update(intToBytes(seq)); crypt.update(intToBytes(len)); crypt.update(data, 0, datalen); return crypt.digest(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; } private MTMessage decrypt(byte[] data, int offset, int len) throws IOException { ByteArrayInputStream stream = new ByteArrayInputStream(data); stream.skip(offset); byte[] msgAuthKey = readBytes(8, stream); for (int i = 0; i < authKeyId.length; i++) { if (msgAuthKey[i] != authKeyId[i]) { Logger.w(TAG, "Unsupported msgAuthKey"); throw new SecurityException(); } } byte[] msgKey = readBytes(16, stream); byte[] sha1_a = SHA1(msgKey, substring(authKey, 8, 32)); byte[] sha1_b = SHA1(substring(authKey, 40, 16), msgKey, substring(authKey, 56, 16)); byte[] sha1_c = SHA1(substring(authKey, 72, 32), msgKey); byte[] sha1_d = SHA1(msgKey, substring(authKey, 104, 32)); byte[] aesKey = concat(substring(sha1_a, 0, 8), substring(sha1_b, 8, 12), substring(sha1_c, 4, 12)); byte[] aesIv = concat(substring(sha1_a, 8, 12), substring(sha1_b, 0, 8), substring(sha1_c, 16, 4), substring(sha1_d, 0, 8)); int totalLen = len - 8 - 16; byte[] encMessage = BytesCache.getInstance().allocate(totalLen); readBytes(encMessage, 0, totalLen, stream); byte[] rawMessage = BytesCache.getInstance().allocate(totalLen); long decryptStart = System.currentTimeMillis(); AES256IGEDecryptBig(encMessage, rawMessage, totalLen, aesIv, aesKey); Logger.d(TAG, "Decrypted in " + (System.currentTimeMillis() - decryptStart) + " ms"); BytesCache.getInstance().put(encMessage); ByteArrayInputStream bodyStream = new ByteArrayInputStream(rawMessage); byte[] serverSalt = readBytes(8, bodyStream); byte[] session = readBytes(8, bodyStream); long messageId = readLong(bodyStream); int mes_seq = StreamingUtils.readInt(bodyStream); int msg_len = StreamingUtils.readInt(bodyStream); int bodySize = totalLen - 32; if (msg_len % 4 != 0) { throw new SecurityException(); } if (msg_len > bodySize) { throw new SecurityException(); } if (msg_len - bodySize > 15) { throw new SecurityException(); } byte[] message = BytesCache.getInstance().allocate(msg_len); readBytes(message, 0, msg_len, bodyStream); BytesCache.getInstance().put(rawMessage); byte[] checkHash = optimizedSHA(serverSalt, session, messageId, mes_seq, msg_len, message, msg_len); if (!arrayEq(substring(checkHash, 4, 16), msgKey)) { throw new SecurityException(); } if (!arrayEq(session, this.session)) { return null; } if (TimeOverlord.getInstance().getTimeAccuracy() < 10) { long time = (messageId >> 32); long serverTime = TimeOverlord.getInstance().getServerTime(); if (serverTime + 30 < time) { Logger.w(TAG, "Incorrect message time: " + time + " with server time: " + serverTime); // return null; } if (time < serverTime - 300) { Logger.w(TAG, "Incorrect message time: " + time + " with server time: " + serverTime); // return null; } } return new MTMessage(messageId, mes_seq, message, message.length); } private class SchedullerThread extends Thread { private SchedullerThread() { setName("Scheduller#" + hashCode()); } @Override public void run() { setPriority(Thread.MIN_PRIORITY); PrepareSchedule prepareSchedule = new PrepareSchedule(); while (!isClosed) { if (Logger.LOG_THREADS) { Logger.d(TAG, "Scheduller Iteration"); } int[] contextIds; synchronized (contexts) { TcpContext[] currentContexts = contexts.toArray(new TcpContext[0]); contextIds = new int[currentContexts.length]; for (int i = 0; i < contextIds.length; i++) { contextIds[i] = currentContexts[i].getContextId(); } } synchronized (scheduller) { scheduller.prepareScheduller(prepareSchedule, contextIds); if (prepareSchedule.isDoWait()) { if (Logger.LOG_THREADS) { Logger.d(TAG, "Scheduller:wait " + prepareSchedule.getDelay()); } try { scheduller.wait(prepareSchedule.getDelay()); } catch (InterruptedException e) { Logger.e(TAG, e); return; } continue; } } TcpContext context = null; synchronized (contexts) { TcpContext[] currentContexts = contexts.toArray(new TcpContext[0]); outer: for (int i = 0; i < currentContexts.length; i++) { int index = (i + roundRobin + 1) % currentContexts.length; for (int allowed : prepareSchedule.getAllowedContexts()) { if (currentContexts[index].getContextId() == allowed) { context = currentContexts[index]; break outer; } } } if (currentContexts.length != 0) { roundRobin = (roundRobin + 1) % currentContexts.length; } } if (context == null) { if (Logger.LOG_THREADS) { Logger.d(TAG, "Scheduller: no context"); } continue; } if (Logger.LOG_THREADS) { Logger.d(TAG, "doSchedule"); } internalSchedule(); synchronized (scheduller) { long start = System.currentTimeMillis(); PreparedPackage preparedPackage = scheduller.doSchedule(context.getContextId(), initedContext.contains(context.getContextId())); if (Logger.LOG_THREADS) { Logger.d(TAG, "Schedulled in " + (System.currentTimeMillis() - start) + " ms"); } if (preparedPackage == null) { continue; } if (Logger.LOG_THREADS) { Logger.d(TAG, "MessagePushed (#" + context.getContextId() + "): time:" + getUnixTime(preparedPackage.getMessageId())); Logger.d(TAG, "MessagePushed (#" + context.getContextId() + "): seqNo:" + preparedPackage.getSeqNo() + ", msgId" + preparedPackage.getMessageId()); } try { EncryptedMessage msg = encrypt(preparedPackage.getSeqNo(), preparedPackage.getMessageId(), preparedPackage.getContent()); if (preparedPackage.isHighPriority()) { scheduller.registerFastConfirm(preparedPackage.getMessageId(), msg.fastConfirm); } if (!context.isClosed()) { context.postMessage(msg.data, preparedPackage.isHighPriority()); initedContext.add(context.getContextId()); } else { scheduller.onConnectionDies(context.getContextId()); } } catch (IOException e) { Logger.e(TAG, e); } } } } } private class ResponseProcessor extends Thread { public ResponseProcessor() { setName("ResponseProcessor#" + hashCode()); } @Override public void run() { setPriority(Thread.MIN_PRIORITY); while (!isClosed) { if (Logger.LOG_THREADS) { Logger.d(TAG, "Response Iteration"); } synchronized (inQueue) { if (inQueue.isEmpty()) { try { inQueue.wait(); } catch (InterruptedException e) { return; } } if (inQueue.isEmpty()) { continue; } } MTMessage message = inQueue.poll(); onMTMessage(message); BytesCache.getInstance().put(message.getContent()); } } } private class ResponseActor extends ReflectedActor { public ResponseActor(ActorSystem system) { super(system, "response", "response"); } protected void onNewMessage(MTMessage message) { onMTMessage(message); BytesCache.getInstance().put(message.getContent()); } protected void onRawMessage(byte[] data, int offset, int len, int contextId) { } } private class ResponseMessenger extends ActorMessenger { protected ResponseMessenger(ActorReference reference) { super(reference, null); } protected ResponseMessenger(ActorReference reference, ActorReference sender) { super(reference, sender); } public void onMessage(MTMessage message) { talkRaw("new", message); } public void onRawMessage(byte[] data, int offset, int len, int contextId) { talkRaw("raw", data, offset, len, contextId); } @Override public ActorMessenger cloneForSender(ActorReference sender) { return new ResponseMessenger(reference, sender); } } private class ConnectionActor extends ReflectedActor { private ConnectionActor(ActorSystem system) { super(system, "connector", "connector"); } @Override protected void registerMethods() { registerMethod("check") .enabledBackOff() .enableSingleShot(); } protected void onCheckMessage() throws Exception { synchronized (contexts) { if (contexts.size() >= desiredConnectionCount) { return; } } ConnectionType type = connectionRate.tryConnection(); try { TcpContext context = new TcpContext(MTProto.this, type.getHost(), type.getPort(), USE_CHECKSUM, tcpListener); if (isClosed) { return; } scheduller.postMessageDelayed(new MTPing(Entropy.generateRandomId()), false, PING_TIMEOUT, 0, context.getContextId(), false); synchronized (contexts) { contexts.add(context); contextConnectionId.put(context.getContextId(), type.getId()); } synchronized (scheduller) { scheduller.notifyAll(); } } catch (IOException e) { Logger.e(TAG, e); connectionRate.onConnectionFailure(type.getId()); throw e; } self().talk("check", null); } } private class ConnectorMessenger extends ActorMessenger { private ConnectorMessenger(ActorReference reference) { super(reference, null); } private ConnectorMessenger(ActorReference reference, ActorReference sender) { super(reference, sender); } public void check() { talkRaw("check"); } @Override public ActorMessenger cloneForSender(ActorReference sender) { return new ConnectorMessenger(reference, sender); } } private class TcpListener implements TcpContextCallback { @Override public void onRawMessage(byte[] data, int offset, int len, TcpContext context) { if (isClosed) { return; } try { MTMessage decrypted = decrypt(data, offset, len); if (decrypted == null) { Logger.d(TAG, "message ignored"); return; } if (!connectedContexts.contains(context.getContextId())) { connectedContexts.add(context.getContextId()); exponentalBackoff.onSuccess(); connectionRate.onConnectionSuccess(contextConnectionId.get(context.getContextId())); } Logger.d(TAG, "MessageArrived (#" + context.getContextId() + "): time: " + getUnixTime(decrypted.getMessageId())); Logger.d(TAG, "MessageArrived (#" + context.getContextId() + "): seqNo: " + decrypted.getSeqNo() + ", msgId:" + decrypted.getMessageId()); if (readInt(decrypted.getContent()) == MTMessagesContainer.CLASS_ID) { try { TLObject object = protoContext.deserializeMessage(new ByteArrayInputStream(decrypted.getContent())); if (object instanceof MTMessagesContainer) { for (MTMessage mtMessage : ((MTMessagesContainer) object).getMessages()) { inQueue.add(mtMessage); } synchronized (inQueue) { inQueue.notifyAll(); } } BytesCache.getInstance().put(decrypted.getContent()); } catch (DeserializeException e) { // Ignore this Logger.e(TAG, e); } } else { inQueue.add(decrypted); synchronized (inQueue) { inQueue.notifyAll(); } } } catch (IOException e) { Logger.e(TAG, e); synchronized (contexts) { context.close(); if (!connectedContexts.contains(context.getContextId())) { exponentalBackoff.onFailureNoWait(); connectionRate.onConnectionFailure(contextConnectionId.get(context.getContextId())); } contexts.remove(context); connectionActor.check(); scheduller.onConnectionDies(context.getContextId()); } } } @Override public void onError(int errorCode, TcpContext context) { if (isClosed) { return; } Logger.d(TAG, "OnError (#" + context.getContextId() + "): " + errorCode); // Fully maintained at transport level: TcpContext dies } @Override public void onChannelBroken(TcpContext context) { if (isClosed) { return; } int contextId = context.getContextId(); Logger.d(TAG, "onChannelBroken (#" + contextId + ")"); synchronized (contexts) { contexts.remove(context); if (!connectedContexts.contains(contextId)) { if (contextConnectionId.containsKey(contextId)) { exponentalBackoff.onFailureNoWait(); connectionRate.onConnectionFailure(contextConnectionId.get(contextId)); } } connectionActor.check(); } scheduller.onConnectionDies(context.getContextId()); requestSchedule(); } @Override public void onFastConfirm(int hash) { if (isClosed) { return; } int[] ids = scheduller.mapFastConfirm(hash); for (int id : ids) { callback.onConfirmed(id); } } } private class EncryptedMessage { public byte[] data; public int fastConfirm; } }
package phWGinfo; public class DemoParallelThreads { public static void main(String[] args) { new DemoParallelThreads().run(); } public void run() { new Thread(new Ticker(+1)).start(); new Thread(new Ticker(-1)).start(); } int count = 0; class Ticker implements Runnable { Ticker(int increment) { this.increment = increment; } int increment; public void run() { while(true) { try { Thread.sleep(50); count = count + increment; System.out.println(count); if(Math.abs(count)>5) System.exit(0); } catch (InterruptedException x) { x.printStackTrace(); } } } } }
package pl.hycom.mr; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; public class maczugaherkulesa { @RequestMapping("/") @ResponseBody String home() { return "maczuga herkulesa !"; } }
package scrum.client.wiki; import scrum.client.ScrumGwtApplication; public class WikiParser { public static void main(String[] args) { WikiParser wikiParser = new WikiParser("tsk17, (req122)\n"); WikiModel model = wikiParser.parse(); System.out.println(model); } private String input; private WikiModel model; private boolean oneliner; public WikiParser(String input) { this.input = input; } private void appendWord(Paragraph p, String word) { if (isUrl(word)) { p.add(new Link(word)); return; } if (word.length() > 1 && isIgnorableWordPrefix(word.charAt(0))) { p.add(new Text(word.substring(0, 1))); word = word.substring(1); } StringBuilder suffix = null; for (int i = word.length() - 1; i >= 0; i if (isIgnorableWordSuffix(word.charAt(i))) { if (suffix == null) suffix = new StringBuilder(); suffix.insert(0, word.charAt(i)); } else { break; } } if (suffix != null) word = word.substring(0, word.length() - suffix.length()); if (isEntityReference(word)) { p.add(new EntityReference(word)); if (suffix != null) p.add(new Text(suffix.toString())); return; } p.add(new Text(word)); if (suffix != null) p.add(new Text(suffix.toString())); } private Paragraph appendText(Paragraph p, String text) { int begin; // code begin = text.indexOf("<code>"); if (begin >= 0 && begin < text.length() - 7) { int end = text.indexOf("</code>", begin); if (end > begin) { String prefix = text.substring(0, begin); String content = text.substring(begin + 6, end); String suffix = text.substring(end + 7); if (content.trim().length() > 0) { appendText(p, prefix); p.add(new Code(content)); appendText(p, suffix); return p; } } } text = text.replace('\n', ' '); // internal links begin = text.indexOf("[["); if (begin >= 0 && begin < text.length() - 4) { int end = text.indexOf("]]", begin); if (end > begin) { String prefix = text.substring(0, begin); String content = text.substring(begin + 2, end); String suffix = text.substring(end + 2); if (content.trim().length() > 0) { appendText(p, prefix); if (content.startsWith("Image:")) { createImage(p, content.substring(6)); } else { createEntityReference(p, content); } appendText(p, suffix); return p; } } } // external links begin = text.indexOf("["); if (begin >= 0 && begin < text.length() - 3) { if (text.charAt(begin + 1) != '[') { int end = text.indexOf("]", begin); if (end > begin) { String prefix = text.substring(0, begin); String link = text.substring(begin + 1, end); String suffix = text.substring(end + 1); appendText(p, prefix); int spaceIdx = link.indexOf(' '); if (spaceIdx > 0) { String href = link.substring(0, spaceIdx); String label = link.substring(spaceIdx + 1); p.add(new Link(href, label)); } else { p.add(new Link(link)); } appendText(p, suffix); return p; } } } // strong end emph begin = text.indexOf("'''''"); if (begin >= 0 && begin < text.length() - 5) { int end = text.indexOf("'''''", begin + 5); if (end >= 0) { String prefix = text.substring(0, begin); String content = text.substring(begin + 5, end); String suffix = text.substring(end + 5); if (content.trim().length() > 0) { appendText(p, prefix); Highlight h = new Highlight(true, true); appendText(h, content); p.add(h); appendText(p, suffix); return p; } } } else { begin = text.indexOf("'''"); if (begin >= 0 && begin < text.length() - 3) { int end = text.indexOf("'''", begin + 3); if (end >= 0) { String prefix = text.substring(0, begin); String content = text.substring(begin + 3, end); String suffix = text.substring(end + 3); if (content.trim().length() > 0) { appendText(p, prefix); Highlight h = new Highlight(false, true); appendText(h, content); p.add(h); appendText(p, suffix); return p; } } } else { begin = text.indexOf("''"); if (begin >= 0 && begin < text.length() - 2) { int end = text.indexOf("''", begin + 2); if (end >= 0) { String prefix = text.substring(0, begin); String content = text.substring(begin + 2, end); String suffix = text.substring(end + 2); if (content.trim().length() > 0) { appendText(p, prefix); Highlight h = new Highlight(true, false); appendText(h, content); p.add(h); appendText(p, suffix); return p; } } } } } while (text.length() > 0) { int idx = text.indexOf(' '); if (idx < 0) { appendWord(p, text); text = ""; } else { appendWord(p, text.substring(0, idx)); p.add(Text.SPACE); text = text.substring(idx + 1); } } p.add(new Text(text)); return p; } private void createImage(Paragraph p, String code) { boolean thumb = code.contains("|thumb"); if (thumb) { code = code.replace("|thumb", ""); } boolean left = code.contains("|left"); if (left) { code = code.replace("|left", ""); } p.add(new Image(code, thumb, left)); } private void createEntityReference(Paragraph p, String code) { int sepIdx = code.indexOf('|'); if (sepIdx > 0) { String name = code.substring(0, sepIdx); String label = code.substring(sepIdx + 1); p.add(new EntityReference("[[" + name + "]]", label)); } else { p.add(new EntityReference("[[" + code + "]]", code)); } } private void nextPart() { nextLine = null; // empty if (input.length() == 0) { input = null; return; } // empty lines if (input.startsWith("\n")) { String line = getNextLine(); while (line.trim().length() == 0 && input.length() > 0) { burn(line.length() + 1); line = getNextLine(); } return; } if (input.startsWith("= ")) { String line = getNextLine(); if (line.length() > 4 && line.endsWith(" =")) { model.add(new Header(line.substring(2, line.length() - 2), 1)); burn(line.length() + 1); return; } } if (input.startsWith("== ")) { String line = getNextLine(); if (line.length() > 6 && line.endsWith(" ==")) { model.add(new Header(line.substring(3, line.length() - 3), 2)); burn(line.length() + 1); return; } } if (input.startsWith("=== ")) { String line = getNextLine(); if (line.length() > 8 && line.endsWith(" ===")) { model.add(new Header(line.substring(4, line.length() - 4), 3)); burn(line.length() + 1); return; } } if (input.startsWith("==== ")) { String line = getNextLine(); if (line.length() > 10 && line.endsWith(" ====")) { model.add(new Header(line.substring(5, line.length() - 5), 4)); burn(line.length() + 1); return; } } // pre if (input.startsWith(" ")) { StringBuilder sb = new StringBuilder(); String line = getNextLine(); boolean first = true; while (line.startsWith(" ")) { if (first) { first = false; } else { sb.append("\n"); } sb.append(line); burn(line.length() + 1); line = getNextLine(); } model.add(new Pre(sb.toString())); return; } // unordered list if (input.startsWith("* ") || input.startsWith(" boolean ordered = input.startsWith(" ItemList list = new ItemList(ordered); Paragraph item = null; String line = getNextLine(); while (!line.startsWith("\n") && line.length() > 0) { if (line.startsWith(ordered ? " item = new Paragraph(false); appendText(item, line.substring(2)); list.add(item); } else { item.add(Text.SPACE); appendText(item, line); } burn(line.length() + 1); line = getNextLine(); } model.add(list); return; } // toc if (input.startsWith("TOC")) { String line = getNextLine(); if (line.equals("TOC")) { burn(line.length() + 1); model.add(new Toc(model)); return; } } // paragraph model.add(appendText(new Paragraph(!oneliner), cutParagraph())); } public WikiModel parse() { model = new WikiModel(); input = input.replace("\r", ""); input = input.replace("\t", " "); oneliner = input.indexOf('\n') < 0; while (input != null) { nextPart(); } return model; } private boolean isIgnorableWordPrefix(char c) { return c == '('; } private boolean isIgnorableWordSuffix(char c) { return c == '.' || c == ',' || c == '!' || c == '?' || c == ')'; } private boolean isUrl(String s) { if (s.startsWith("http://")) return true; if (s.startsWith("https://")) return true; if (s.startsWith("www.")) return true; if (s.startsWith("ftp://")) return true; return false; } private boolean isEntityReference(String s) { if (s.length() < 4) return false; if (!Character.isDigit(s.charAt(3))) return false; boolean prefixOk = false; for (String prefix : ScrumGwtApplication.REFERENCE_PREFIXES) { if (s.startsWith(prefix)) { prefixOk = true; break; } } if (!prefixOk) return false; int len = s.length(); for (int i = 3; i < len; i++) { if (!Character.isDigit(s.charAt(i))) return false; } try { String number = s.substring(3); Integer.parseInt(number); } catch (NumberFormatException ex) { return false; } return true; } private String cutParagraph() { StringBuilder sb = new StringBuilder(); boolean first = true; while (input.length() > 0) { String line = getNextLine(); if (line.trim().length() == 0) { break; } if (first) { first = false; } else { sb.append('\n'); } sb.append(line); burn(line.length() + 1); } return sb.toString(); } private void burn(int length) { nextLine = null; if (length >= input.length()) { input = ""; } else { input = input.substring(length); } } private String nextLine; private String getNextLine() { if (nextLine == null) { int idx = input.indexOf('\n'); if (idx < 0) return input; nextLine = input.substring(0, idx); } return nextLine; } public static final String SYNTAX_INFO_HTML = "<table class='WikiParser-syntax-table' cellpadding='5px'>" + "<tr><td><i>Italic text</i></td> <td><code>''italic text''</code></td></tr>" + "<tr><td><b>Bold text</b></td> <td><code>'''bold text'''</code></td></tr>" + "<tr><td><b><i>Bold and italic</i></b></td> <td><code>'''''bold and italic'''''</td></tr>" + "<tr><td>Internal link</td> <td><code>[[Name of page]]<br>[[Name of page|Text to display]]</code></td></tr>" + "<tr><td>External link</td> <td><code>[http: + "<tr><td><h2>Section headings</h2></td> <td><code>= heading 1 =<br>== heading 2 ==<br>=== heading 3 ===<br>==== heading 4 ====</code></td></tr>" + "<tr><td>Bulleted list</td> <td><code>* Item 1<br>* Item 2<br>* Item 3</code></td></tr>" + "<tr><td>Numbered list</td> <td><code># Item<br># Item 2<br># Item 3</code></td></tr>" + "<tr><td>Internal image<br>thumb</td> <td><code>[[Image:fle3]]<br>[[Image:fle3|thumb]]</code></td></tr>" + "<tr><td>External image<br>thumb</td> <td><code>[[Image:http: + "<tr><td><code>Code</code></td> <td><code>&lt;code&gt;Code&lt;/code&gt;</code></td></tr>" + "</table>"; }
package scrum.server.project; import ilarkesto.base.Money; import ilarkesto.base.Str; import ilarkesto.base.Utl; import ilarkesto.base.time.Date; import ilarkesto.pdf.APdfBuilder; import ilarkesto.persistence.AEntity; import ilarkesto.persistence.Persist; import ilarkesto.rss.Rss20Builder; import ilarkesto.search.Searchable; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import scrum.client.UsersStatusData; import scrum.server.ScrumConfig; import scrum.server.admin.ProjectUserConfig; import scrum.server.admin.ProjectUserConfigDao; import scrum.server.admin.User; import scrum.server.calendar.SimpleEvent; import scrum.server.calendar.SimpleEventDao; import scrum.server.collaboration.Comment; import scrum.server.collaboration.CommentDao; import scrum.server.collaboration.Subject; import scrum.server.collaboration.SubjectDao; import scrum.server.collaboration.Wikipage; import scrum.server.collaboration.WikipageDao; import scrum.server.estimation.RequirementEstimationVote; import scrum.server.estimation.RequirementEstimationVoteDao; import scrum.server.files.File; import scrum.server.files.FileDao; import scrum.server.impediments.Impediment; import scrum.server.impediments.ImpedimentDao; import scrum.server.issues.Issue; import scrum.server.issues.IssueDao; import scrum.server.journal.ProjectEvent; import scrum.server.journal.ProjectEventDao; import scrum.server.release.Release; import scrum.server.release.ReleaseDao; import scrum.server.risks.Risk; import scrum.server.risks.RiskDao; import scrum.server.sprint.Sprint; import scrum.server.sprint.SprintDaySnapshot; import scrum.server.sprint.SprintDaySnapshotDao; import scrum.server.sprint.Task; import scrum.server.sprint.TaskDao; public class Project extends GProject { private transient UsersStatusData usersStatus; private static ProjectUserConfigDao projectUserConfigDao; private static ImpedimentDao impedimentDao; private static IssueDao issueDao; private static RequirementDao requirementDao; private static QualityDao qualityDao; private static ProjectSprintSnapshotDao projectSprintSnapshotDao; private static RiskDao riskDao; private static TaskDao taskDao; private static WikipageDao wikipageDao; private static ProjectEventDao projectEventDao; private static SimpleEventDao simpleEventDao; private static FileDao fileDao; private static ScrumConfig config; private static CommentDao commentDao; private static ReleaseDao releaseDao; private static RequirementEstimationVoteDao requirementEstimationVoteDao; private static SprintDaySnapshotDao sprintDaySnapshotDao; private static SubjectDao subjectDao; public void updateRequirementsOrder(List<Requirement> requirements) { setRequirementsOrderIds(Persist.getIdsAsList(requirements)); } public static void setSubjectDao(SubjectDao subjectDao) { Project.subjectDao = subjectDao; } public static void setCommentDao(CommentDao commentDao) { Project.commentDao = commentDao; } public static void setSprintDaySnapshotDao(SprintDaySnapshotDao sprintDaySnapshotDao) { Project.sprintDaySnapshotDao = sprintDaySnapshotDao; } public static void setRequirementEstimationVoteDao(RequirementEstimationVoteDao requirementEstimationVoteDao) { Project.requirementEstimationVoteDao = requirementEstimationVoteDao; } public static void setReleaseDao(ReleaseDao releaseDao) { Project.releaseDao = releaseDao; } public static void setConfig(ScrumConfig config) { Project.config = config; } public static void setFileDao(FileDao fileDao) { Project.fileDao = fileDao; } public static void setSimpleEventDao(SimpleEventDao simpleEventDao) { Project.simpleEventDao = simpleEventDao; } public static void setProjectEventDao(ProjectEventDao projectEventDao) { Project.projectEventDao = projectEventDao; } public static void setWikipageDao(WikipageDao wikipageDao) { Project.wikipageDao = wikipageDao; } public static void setProjectUserConfigDao(ProjectUserConfigDao projectUserConfigDao) { Project.projectUserConfigDao = projectUserConfigDao; } public static void setIssueDao(IssueDao issueDao) { Project.issueDao = issueDao; } public static void setTaskDao(TaskDao taskDao) { Project.taskDao = taskDao; } public static void setRiskDao(RiskDao riskDao) { Project.riskDao = riskDao; } public static void setImpedimentDao(ImpedimentDao impedimentDao) { Project.impedimentDao = impedimentDao; } public static void setRequirementDao(RequirementDao storyDao) { Project.requirementDao = storyDao; } public static void setQualityDao(QualityDao qualityDao) { Project.qualityDao = qualityDao; } public static void setProjectSprintSnapshotDao(ProjectSprintSnapshotDao projectSprintSnapshotDao) { Project.projectSprintSnapshotDao = projectSprintSnapshotDao; } public void buildProductBacklogReport(APdfBuilder pdf) {} public void scanFiles() { java.io.File dir = new java.io.File(getFileRepositoryPath()); java.io.File[] files = dir.listFiles(); if (files != null) { for (java.io.File f : files) { File file = fileDao.getFilesByName(f.getName(), this); if (file == null) { file = fileDao.postFile(f, this); } } } } @SuppressWarnings("unchecked") public ArrayList<AEntity> search(String text) { String[] keys = Str.tokenize(text, " "); ArrayList ret = new ArrayList(); ret.addAll(getMatching(getRequirements(), keys)); ret.addAll(getMatching(getQualitys(), keys)); ret.addAll(getMatching(getTasks(), keys)); ret.addAll(getMatching(getWikipages(), keys)); ret.addAll(getMatching(getIssues(), keys)); ret.addAll(getMatching(getImpediments(), keys)); ret.addAll(getMatching(getRisks(), keys)); ret.addAll(getMatching(getFiles(), keys)); ret.addAll(getMatching(getReleases(), keys)); return ret; } private <T extends Searchable> List<T> getMatching(Collection<T> entities, String[] keys) { List<T> ret = new ArrayList<T>(); for (T entity : entities) { if (matchesKeys(entity, keys)) ret.add(entity); } return ret; } private boolean matchesKeys(Searchable entity, String[] keys) { for (String key : keys) { if (!entity.matchesKey(key)) return false; } return true; } public void writeJournalAsRss(OutputStream out, String encoding, String baseUrl) { Rss20Builder rss = new Rss20Builder(); rss.setTitle(getLabel() + " Event Journal"); rss.setLanguage("en"); rss.setLink(baseUrl + "#project=" + getId()); for (ProjectEvent event : getLatestProjectEvents()) { Rss20Builder.Item item = rss.addItem(); item.setTitle(event.getLabel()); item.setDescription(event.getLabel()); item.setLink(baseUrl + "#project=" + getId()); item.setGuid(event.getId()); item.setPubDate(event.getDateAndTime()); } rss.sortItems(); rss.write(out, encoding); } public String getFileRepositoryPath() { return config.getFileRepositoryPath() + "/" + getId(); } public Set<SimpleEvent> getCalendarEvents() { return simpleEventDao.getSimpleEventsByProject(this); } public List<ProjectEvent> getLatestProjectEvents() { List<ProjectEvent> events = new LinkedList<ProjectEvent>(getProjectEvents()); int max = 30; if (events.size() <= max) return events; Collections.sort(events); while (events.size() > max) { events.remove(0); } return events; } public Set<ProjectEvent> getProjectEvents() { return projectEventDao.getProjectEventsByProject(this); } public UsersStatusData getUsersStatus() { if (usersStatus == null) usersStatus = new UsersStatusData(); return usersStatus; } public Set<ProjectUserConfig> getUserConfigs() { Set<ProjectUserConfig> configs = new HashSet<ProjectUserConfig>(); for (User user : getParticipants()) { configs.add(getUserConfig(user)); } return configs; } public ProjectUserConfig getUserConfig(User user) { return projectUserConfigDao.getProjectUserConfig(this, user); } public Set<Wikipage> getWikipages() { return wikipageDao.getWikipagesByProject(this); } public Set<Task> getTasks() { return taskDao.getTasksByProject(this); } public Requirement getRequirementByNumber(int number) { return requirementDao.getRequirementByNumber(number, this); } public Task getTaskByNumber(int number) { return taskDao.getTaskByNumber(number, this); } public Quality getQualityByNumber(int number) { return qualityDao.getQualityByNumber(number, this); } public Issue getIssueByNumber(int number) { return issueDao.getIssueByNumber(number, this); } public Impediment getImpedimentByNumber(int number) { return impedimentDao.getImpedimentByNumber(number, this); } public Subject getSubjectByNumber(int number) { return subjectDao.getSubjectsByNumber(number, this); } public File getFileByNumber(int number) { return fileDao.getFileByNumber(number, this); } public File getFileByReference(String reference) { return getFileByNumber(Integer.parseInt(reference.substring(3))); } public SimpleEvent getSimpleEventByNumber(int number) { return simpleEventDao.getSimpleEventByNumber(number, this); } public Release getReleaseByNumber(int number) { return releaseDao.getReleaseByNumber(number, this); } public Wikipage getWikipageByName(String name) { return wikipageDao.getWikipageByName(name, this); } public synchronized int generateTaskNumber() { int number = getLastTaskNumber() + 1; setLastTaskNumber(number); return number; } public synchronized int generateEventNumber() { int number = getLastEventNumber() + 1; setLastEventNumber(number); return number; } public synchronized int generateFileNumber() { int number = getLastFileNumber() + 1; setLastFileNumber(number); return number; } public synchronized int generateRequirementNumber() { int number = getLastRequirementNumber() + 1; setLastRequirementNumber(number); return number; } public synchronized int generateImpedimentNumber() { int number = getLastImpedimentNumber() + 1; setLastImpedimentNumber(number); return number; } public synchronized int generateSubjectNumber() { int number = getLastSubjectNumber() + 1; setLastSubjectNumber(number); return number; } public synchronized int generateRiskNumber() { int number = getLastRiskNumber() + 1; setLastRiskNumber(number); return number; } public synchronized int generateIssueNumber() { int number = getLastIssueNumber() + 1; setLastIssueNumber(number); return number; } public synchronized int generateReleaseNumber() { int number = getLastReleaseNumber() + 1; setLastReleaseNumber(number); return number; } public synchronized int generateQualityNumber() { int number = getLastQualityNumber() + 1; setLastQualityNumber(number); return number; } public ProjectSprintSnapshot getCurrentSprintSnapshot() { ProjectSprintSnapshot snapshot = projectSprintSnapshotDao.getProjectSprintSnapshotBySprint(getCurrentSprint()); if (snapshot == null) snapshot = createSprintSnapshot(); return snapshot; } // public int getRemainingWork() { // int sum = 0; // for (Requirement requirement : getRequirements()) { // if (requirement.isClosed()) continue; // Integer work = requirement.getEstimatedWork(); // if (work != null) sum += work; // return sum; // public int getBurnedWork() { // int sum = 0; // for (Requirement requirement : getRequirements()) { // if (!requirement.isClosed()) continue; // Integer work = requirement.getEstimatedWork(); // if (work != null) sum += work; // return sum; public List<ProjectSprintSnapshot> getSprintSnapshots() { return projectSprintSnapshotDao.getProjectSprintSnapshotsByProject(this); } public void switchToNextSprint() { Sprint oldSprint = getCurrentSprint(); oldSprint.close(); oldSprint.setEnd(Date.today()); getCurrentSprintSnapshot().update(); Sprint newSprint = getNextSprint(); if (newSprint == null) newSprint = createNextSprint(); if (!newSprint.isBeginSet() || newSprint.getBegin().isPast()) newSprint.setBegin(Date.today()); if (!newSprint.isEndSet() || newSprint.getEnd().isBeforeOrSame(newSprint.getBegin())) newSprint.setEnd(newSprint.getBegin().addDays(oldSprint.getLengthInDays())); setCurrentSprint(newSprint); createNextSprint(); createSprintSnapshot(); for (Task task : oldSprint.getTasks()) { if (task.isClosed()) { taskDao.deleteEntity(task); } } } private ProjectSprintSnapshot createSprintSnapshot() { ProjectSprintSnapshot snapshot = projectSprintSnapshotDao.newEntityInstance(); snapshot.setSprint(getCurrentSprint()); snapshot.update(); projectSprintSnapshotDao.saveEntity(snapshot); return snapshot; } public Sprint createNextSprint() { Sprint sprint = sprintDao.newEntityInstance(); sprint.setProject(this); sprint.setLabel("Next Sprint"); if (isCurrentSprintSet()) { sprint.setBegin(getCurrentSprint().getEnd()); Integer length = getCurrentSprint().getLengthInDays(); if (length != null) sprint.setEnd(sprint.getBegin().addDays(length)); } sprintDao.saveEntity(sprint); setNextSprint(sprint); return sprint; } public Set<Sprint> getSprints() { return sprintDao.getSprintsByProject(this); } public Set<Impediment> getImpediments() { return impedimentDao.getImpedimentsByProject(this); } public Set<Issue> getIssues() { return issueDao.getIssuesByProject(this); } public Set<Issue> getAcceptedIssues() { return issueDao.getAcceptedIssues(this); } public Set<Issue> getClosedIssues() { return issueDao.getClosedIssues(this); } public Set<Issue> getUrgentAndOpenIssues() { return issueDao.getUrgentAndOpenIssues(this); } public Set<Risk> getRisks() { return riskDao.getRisksByProject(this); } public Set<Requirement> getRequirements() { return requirementDao.getRequirementsByProject(this); } public Set<File> getFiles() { return fileDao.getFilesByProject(this); } public Set<Subject> getSubjects() { return subjectDao.getSubjectsByProject(this); } public Set<Release> getReleases() { return releaseDao.getReleasesByProject(this); } public Set<RequirementEstimationVote> getRequirementEstimationVotes() { Set<RequirementEstimationVote> ret = new HashSet<RequirementEstimationVote>(); for (Requirement requirement : getRequirements()) { ret.addAll(requirement.getEstimationVotes()); } return ret; } public Set<SprintDaySnapshot> getSprintDaySnapshots() { Set<SprintDaySnapshot> ret = new HashSet<SprintDaySnapshot>(); for (Sprint sprint : getSprints()) { ret.addAll(sprint.getDaySnapshots()); } return ret; } public Set<SprintDaySnapshot> getExistingSprintDaySnapshots() { Set<SprintDaySnapshot> ret = new HashSet<SprintDaySnapshot>(); for (Sprint sprint : getSprints()) { ret.addAll(sprint.getExistingDaySnapshots()); } return ret; } public Set<SimpleEvent> getSimpleEvents() { return simpleEventDao.getSimpleEventsByProject(this); } public Set<Comment> getAllComments() { return getComments(false); } public Set<Comment> getLatestComments() { return getComments(true); } private Set<Comment> getComments(boolean latestOnly) { Set<Comment> ret = new HashSet<Comment>(); ret.addAll(commentDao.getCommentsByParent(this)); ret.addAll(getComments(getSprints(), latestOnly)); ret.addAll(getComments(getParticipants(), latestOnly)); ret.addAll(getComments(getRequirements(), latestOnly)); ret.addAll(getComments(getQualitys(), latestOnly)); ret.addAll(getComments(getTasks(), latestOnly)); ret.addAll(getComments(getImpediments(), latestOnly)); ret.addAll(getComments(getIssues(), latestOnly)); ret.addAll(getComments(getRisks(), latestOnly)); ret.addAll(getComments(getWikipages(), latestOnly)); ret.addAll(getComments(getSimpleEvents(), latestOnly)); ret.addAll(getComments(getFiles(), latestOnly)); ret.addAll(getComments(getReleases(), latestOnly)); ret.addAll(getComments(getSprintSnapshots(), latestOnly)); ret.addAll(getComments(getRequirementEstimationVotes(), latestOnly)); ret.addAll(getComments(getUserConfigs(), latestOnly)); ret.addAll(getComments(getProjectEvents(), latestOnly)); ret.addAll(getComments(getSubjects(), latestOnly)); ret.addAll(getComments(getReleases(), latestOnly)); return ret; } private Set<Comment> getComments(Collection<? extends AEntity> entities, boolean latestOnly) { Set<Comment> ret = new HashSet<Comment>(); for (AEntity entity : entities) { ret.addAll(commentDao.getCommentsByParent(entity)); } return latestOnly ? getLatest(ret) : ret; } private Set<Comment> getLatest(Set<Comment> comments) { if (comments.size() < 2) return comments; Comment latest = null; for (Comment comment : comments) { if (latest == null || comment.getDateAndTime().isAfter(latest.getDateAndTime())) latest = comment; } return latest == null ? new HashSet<Comment>(0) : Utl.toSet(latest); } public Set<Quality> getQualitys() { return qualityDao.getQualitysByProject(this); } @Override public String toString() { return getLabel(); } @Override public void ensureIntegrity() { super.ensureIntegrity(); addParticipants(getAdmins()); addParticipants(getProductOwners()); addParticipants(getScrumMasters()); addParticipants(getTeamMembers()); if (!isCurrentSprintSet()) { Sprint sprint = sprintDao.newEntityInstance(); sprint.setProject(this); sprintDao.saveEntity(sprint); setCurrentSprint(sprint); } if (!isNextSprintSet()) { createNextSprint(); } if (!isPunishmentUnitSet()) { setPunishmentUnit(Money.EUR); } if (getPunishmentFactor() == 0) { setPunishmentFactor(1); } } public boolean isVisibleFor(User user) { return containsParticipant(user); } public boolean isEditableBy(User user) { return containsParticipant(user); } public boolean isDeletableBy(User user) { return containsAdmin(user); } public void addTestImpediments() { Impediment imp = null; // no documentation imp = impedimentDao.postImpediment(this, Date.randomPast(5), "There is no documentation. Seriously.", false); imp.setDescription("Someone promised that, I remember. Where is it?"); // no daily scrums imp = impedimentDao.postImpediment(this, Date.randomPast(5), "Daily Scrums are not daily", true); imp.setDescription("\"Daily Scrums\" are supposed to be daily. That's why they are called DAILY Scrums."); imp .setSolution("Fixed time and place to 09.00 p. m. at Starbucks every morning (except weekdays, weekends and holydays)."); // no coffee imp = impedimentDao.postImpediment(this, Date.randomPast(5), "There is no coffee machine", false); } public void addTestRisks() { Risk rsk = null; // god rsk = riskDao.postRisk(this, "God comes to judge the living and the dead", 0, 100); rsk.setImpactMitigation("Nothing we can do here."); // duke rsk = riskDao.postRisk(this, "Duke Nukem Forever is released", 20, 100); rsk.setProbabilityMitigation("Nothing to mitigate here. The probability is close to nothing."); rsk.setImpactMitigation("Nothing to mitigate here. Everyone will be playing. Everything will be lost."); // sudden death rsk = riskDao.postRisk(this, "Sudden Death", 50, 40); rsk.setImpactMitigation("Go to the roof if it's by rising sea level."); } public void addTestSimpleEvents() { // let people generate their own events } public void addTestEvents() { // no test events } public void addTestIssues() { Issue iss = null; // noobs iss = issueDao.postIssue(this, "thiz cr4p don't work, n00bz!!1"); iss.setDescription("go home, u noobz .. // eclipse integration iss = issueDao.postIssue(this, "I want eclipse integration"); iss.setDescription("I would be really nice if eclipse commits would be represented in Kunagi! Thank you!"); // link bug iss = issueDao.postIssue(this, "Bug: Links don't work"); iss.setDescription("When I try to post links to other pages, I get links to the Wiki. WTF?"); // date crash iss = issueDao.postIssue(this, "Crash when using Dates after 2012"); iss .setDescription("The program crashes whenever I enter dates after 2012. Can't figure out what the problem is though."); iss.setAcceptDate(Date.beforeDays(2)); iss.setUrgent(true); iss.setSeverity(scrum.client.issues.Issue.SEVERE); // gui bug iss = issueDao.postIssue(this, "GUI inconsistency between PB and SB"); iss .setDescription("The order of Qualities and Tests is different between widgets in the PB and SB. It should be the same."); iss.setAcceptDate(Date.beforeDays(35)); iss.setUrgent(true); iss.setSeverity(scrum.client.issues.Issue.MINOR); // navi display bug iss = issueDao.postIssue(this, "navigation displays wrong current view"); iss .setDescription("When I open the Whiteboard, \"Sprint Backlog\" is selected in the navigation. Same for other jumps."); iss.setAcceptDate(Date.today()); iss.setUrgent(true); iss.setSeverity(scrum.client.issues.Issue.MINOR); // terrific pb suggestion iss = issueDao.postIssue(this, "Product Backlog should be terrific, not amazing"); iss .setDescription("56% of users want a terrific PB, not an amazing one. We should change that in one of the upcoming releases."); iss.setAcceptDate(Date.today()); // flattr iss = issueDao.postIssue(this, "Add a flattr-button"); iss.setDescription("See [http://flattr.com]."); iss.setCloseDate(Date.beforeDays(1)); // thank you iss = issueDao.postIssue(this, "I like this software, thank you!"); iss.setDescription("I'm using Kunagi for my own project now. Thanks for the great work."); iss.setCloseDate(Date.today()); } public void addTestRequirements() { Requirement req = null; List<Requirement> reqOrder = new LinkedList<Requirement>(); // Unsurpassed Concept req = requirementDao.postRequirement(this, "Unsurpassed Concept", 3f); req .setDescription("As a Product Owner I want the concept to be unsurpassable so I don't have to worry about ROI anymore."); reqOrder.add(req); req.setSprint(getCurrentSprint()); taskDao.postTask(req, "Create Concept", 2, 1); taskDao.postTask(req, "Make Sure All Others Are Inferior", 5, 3); // Amazing Product Backlog req = requirementDao.postRequirement(this, "Amazing Product Backlog", 2f); req.setDescription("As a Product Owner I want my Backlog to be amazing so that people stand in awe."); reqOrder.add(req); req.setSprint(getCurrentSprint()); taskDao.postTask(req, "Creation of Storys", 1, 0); taskDao.postTask(req, "Intelligent Design of Storys", 1, 0); taskDao.postTask(req, "Deletion of Storys", 1, 0); // Functional Quality Backlog req = requirementDao.postRequirement(this, "Functional Quality Backlog", 1f); req .setDescription("As a Product Owner I want my non-functional Requirements to be functional, so I can use them."); reqOrder.add(req); req.setSprint(getCurrentSprint()); taskDao.postTask(req, "Copy And Paste Product Backlog", 1, 0); taskDao.postTask(req, "Marry Storys and Qualitys", 1, 0); // Groundbraking Scrum Backlog req = requirementDao.postRequirement(this, "Groundbraking Scrum Backlog", 1f); req .setDescription("As a Team member I want the Scrum Backlog to be groundbreaking, so that everybody can see that I am the most important here."); reqOrder.add(req); req.setSprint(getCurrentSprint()); taskDao.postTask(req, "Create Tasks", 1, 0); taskDao.postTask(req, "Create More Tasks", 1, 0); // Breathtaking Whiteboard req = requirementDao.postRequirement(this, "Breathtaking Whiteboard", 8f); req .setDescription("As a Team member I want the current state of things to be displayed on a Whiteboard, so I can play around when I am bored."); reqOrder.add(req); // Empowering Impediment List req = requirementDao.postRequirement(this, "Empowering Impediment List", 2f); req .setDescription("As a Scrum Master I want the Impedimen List to be empowering. Best thing would be self-resolving Impediments."); reqOrder.add(req); // Divine Risk Management req = requirementDao.postRequirement(this, "Divine Risk Management", 5f); req .setDescription("As a Team member, I want Risk Management to be devine. Wait, that makes Risk Management superfluous, I guess."); reqOrder.add(req); // Miraculous Issue Management req = requirementDao.postRequirement(this, "Miraculous Issue Management", 3f); req .setDescription("As a Product Owner I want my Issue Management to be miraculous, so that Issues close themselves AND sometimes even each other."); reqOrder.add(req); // Immaculate Bug Tracking req = requirementDao.postRequirement(this, "Immaculate Bug Tracking", 2f); req .setDescription("As a Team member I want immaculate Bug Tracking. A Bug Tracking containing no bugs would be suitable."); reqOrder.add(req); // Unbeatable Planning Poker req = requirementDao.postRequirement(this, "Unbeatable Planning Poker", null); req.setDescription("As I User I want Planning Poker to be so good that nobody can beat it."); reqOrder.add(req); // Enlightening Wiki req = requirementDao.postRequirement(this, "Enlightening Wiki", 5f); req .setDescription("As a User I want the Wiki to enlighten me so that I am enlightened after reading (makes sense, doesn't it?)."); reqOrder.add(req); // Absorbing Discussion Board req = requirementDao.postRequirement(this, "Absorbing Discussion Board", 5f); req .setDescription("As a User I want the Discussion Board to be absorbing, so that I never have time to do my work."); reqOrder.add(req); // Irresistable User Interface req = requirementDao.postRequirement(this, "Irresistable User Interface", 20f); req .setDescription("As a User I want the User Interface to be irresistable so that I can experience Orgasmic Joy-of-Use."); reqOrder.add(req); // Succulent Documentation req = requirementDao.postRequirement(this, "Succulent Documentation", null); req.setDescription("As a Noob I want Succulent Documentation. Yammy!"); reqOrder.add(req); // Outlasting Collaboration req = requirementDao.postRequirement(this, "Outlasting Collaboration", null); req.setDescription("This is still an epic. Nothing to see, really."); reqOrder.add(req); updateRequirementsOrder(reqOrder); } public void addTestQualitys() { Quality qly = null; qly = qualityDao.postQuality(this, "Undeniable Success"); qly = qualityDao.postQuality(this, "Orgasmic Joy-of-Use"); qly = qualityDao.postQuality(this, "Effervescent Happiness"); qly = qualityDao.postQuality(this, "Supersonic Communication"); qly = qualityDao.postQuality(this, "Endless Freedom"); qly = qualityDao.postQuality(this, "Flawless Integration"); } public void addTestSprints() { sprintDao.createTestSprint(this); } }
package seedu.todo.models; import java.io.IOException; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import seedu.todo.commons.exceptions.CannotRedoException; import seedu.todo.commons.exceptions.CannotUndoException; import seedu.todo.storage.JsonStorage; import seedu.todo.storage.Storage; /** * This class holds the entire persistent database for the TodoList app. * <ul> * <li>This is a singleton class. For obvious reasons, the TodoList app should * not be working with multiple DB instances simultaneously.</li> * <li>Object to object dynamic references should not be expected to survive * serialization.</li> * </ul> * * @author louietyj * */ public class TodoListDB { private static TodoListDB instance = null; private static Storage storage = new JsonStorage(); private Set<Task> tasks = new LinkedHashSet<Task>(); private Set<Event> events = new LinkedHashSet<Event>(); protected TodoListDB() { // Prevent instantiation. } /** * Get a list of Tasks in the DB. * * @return tasks */ public List<Task> getAllTasks() { return new ArrayList<Task>(tasks); } public int countIncompleteTasks() { int count = 0; for (Task task : tasks) { if (!task.isCompleted()) { count++; } } return count; } public int countOverdueTasks() { LocalDateTime now = LocalDateTime.now(); int count = 0; for (Task task : tasks) { LocalDateTime dueDate = task.getDueDate(); if (!task.isCompleted() && dueDate != null && dueDate.compareTo(now) < 0) { count++; } } return count; } /** * Get a list of Events in the DB. * * @return events */ public List<Event> getAllEvents() { return new ArrayList<Event>(events); } public int countFutureEvents() { LocalDateTime now = LocalDateTime.now(); int count = 0; for (Event event : events) { LocalDateTime startDate = event.getStartDate(); if (startDate != null && startDate.compareTo(now) >= 0) { count++; } } return count; } /** * Create a new Task in the DB and return it.<br> * <i>The new record is not persisted until <code>save</code> is explicitly * called.</i> * * @return task */ public Task createTask() { Task task = new Task(); tasks.add(task); return task; } /** * Destroys a Task in the DB and persists the commit. * * @param task * @return true if the save was successful, false otherwise */ public boolean destroyTask(Task task) { tasks.remove(task); return save(); } /** * Create a new Event in the DB and return it.<br> * <i>The new record is not persisted until <code>save</code> is explicitly * called.</i> * * @return event */ public Event createEvent() { Event event = new Event(); events.add(event); return event; } /** * Destroys an Event in the DB and persists the commit. * * @param event * @return true if the save was successful, false otherwise */ public boolean destroyEvent(Event event) { events.remove(event); return save(); } /** * Gets the singleton instance of the TodoListDB. * * @return TodoListDB */ public static TodoListDB getInstance() { if (instance == null) { instance = new TodoListDB(); } return instance; } /** * Explicitly persists the database to disk. * * @return true if the save was successful, false otherwise */ public boolean save() { try { storage.save(this); return true; } catch (IOException e) { return false; } } /** * Explicitly reloads the database from disk. * * @return true if the load was successful, false otherwise */ public boolean load() { try { instance = storage.load(); return true; } catch (IOException e) { return false; } } public void move(String newPath) throws IOException { storage.move(newPath); } /** * Returns the maximum possible number of undos. * * @return undoSize */ public int undoSize() { return storage.undoSize(); } /** * Rolls back the DB by one commit. * * @return true if the rollback was successful, false otherwise */ public boolean undo() { try { instance = storage.undo(); return true; } catch (CannotUndoException | IOException e) { return false; } } /** * Returns the maximum possible number of redos. * * @return redoSize */ public int redoSize() { return storage.redoSize(); } /** * Rolls forward the DB by one undo commit. * * @return true if the redo was successful, false otherwise */ public boolean redo() { try { instance = storage.redo(); return true; } catch (CannotRedoException | IOException e) { return false; } } }
package ste.travian.gui; import java.awt.Point; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.dnd.DnDConstants; import java.awt.dnd.DragGestureEvent; import java.awt.dnd.DragGestureListener; import java.awt.dnd.DragSource; import java.awt.dnd.DragSourceDragEvent; import java.awt.dnd.DragSourceDropEvent; import java.awt.dnd.DragSourceEvent; import java.awt.dnd.DragSourceListener; import java.awt.dnd.DropTarget; import java.awt.dnd.DropTargetDragEvent; import java.awt.dnd.DropTargetDropEvent; import java.awt.dnd.DropTargetEvent; import java.awt.dnd.DropTargetListener; import java.io.IOException; import javax.swing.DefaultListModel; import javax.swing.JList; import javax.swing.ListSelectionModel; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreePath; import org.jdesktop.swingx.decorator.SortOrder; /** * This is a JList that just defines the methods required to support DnD with * the alliance groups tree. * * @author ste */ public class AllianceList extends org.jdesktop.swingx.JXList implements DragGestureListener, DropTargetListener, DragSourceListener { DragSource ds; /** * Creates an AllianceList. */ public AllianceList() { super(new DefaultListModel()); setSelectionMode(ListSelectionModel.SINGLE_SELECTION); setLayoutOrientation(JList.HORIZONTAL_WRAP); setVisibleRowCount(-1); setFixedCellWidth(90); ds = new DragSource(); ds.createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_MOVE, this); DropTarget dropTarget = new DropTarget(this, this); } /** * Returns the selected alliance or null if no alliance is selected. * This is intended to be used also for DnD operations by the TransferHandler. * * @return the seleceted alliance or null */ public AllianceDnDInfo getSelectedAlliance() { return (AllianceDnDInfo) getSelectedValue(); } /** * Adds an alliance to the list respecting the alphabetical order. * * @param info the alliance to add in the form of a DnDable object * * @return the position the item has been inserted */ public int addAlliance(AllianceDnDInfo info) { DefaultListModel model = (DefaultListModel) getModel(); int i = 0; String alliance = null; for (; i<model.size(); ++i) { alliance = String.valueOf(model.elementAt(i)); if (alliance.compareTo(info.getName())>0) { break; } } model.add(i, info); return i; } public void dragGestureRecognized(DragGestureEvent e) { System.out.println("Drag Gesture Recognized!"); Transferable t = getSelectedAlliance(); ds.startDrag(e, DragSource.DefaultMoveDrop, t, this); } public void dragEnter(DragSourceDragEvent e) { System.out.println("Drag Enter"); } public void dragExit(DragSourceEvent e) { System.out.println("Drag Exit"); } public void dragOver(DragSourceDragEvent e) { System.out.println("Drag Over"); } public void dragDropEnd(DragSourceDropEvent e) { if (e.getDropSuccess()) { ((DefaultListModel)getModel()).removeElementAt(getSelectedIndex()); } } public void dropActionChanged(DragSourceDragEvent e) { System.out.println("Drop Action Changed"); } /** * DropTargetListener interface method - What we do when drag is released */ public void drop(DropTargetDropEvent e) { try { Transferable tr = e.getTransferable(); //flavor not supported, reject drop if (!tr.isDataFlavorSupported(AllianceDnDInfo.INFO_FLAVOR)) { e.rejectDrop(); return; } int pos = addAlliance( (AllianceDnDInfo)tr.getTransferData(AllianceDnDInfo.INFO_FLAVOR) ); setSelectedIndex(pos); ensureIndexIsVisible(pos); e.getDropTargetContext().dropComplete(true); } catch (Exception ex) { e.rejectDrop(); } } /** DropTargetListener interface method */ public void dragEnter(DropTargetDragEvent e) { } /** DropTargetListener interface method */ public void dragExit(DropTargetEvent e) { } /** DropTargetListener interface method */ public void dragOver(DropTargetDragEvent e) { e.acceptDrag(DnDConstants.ACTION_MOVE); } /** DropTargetListener interface method */ public void dropActionChanged(DropTargetDragEvent e) { } }
package xdean.jex.util.task; import static xdean.jex.util.function.FunctionAdapter.supplierToRunnable; import java.util.Optional; import java.util.function.Consumer; import java.util.function.Supplier; import lombok.AllArgsConstructor; import lombok.experimental.UtilityClass; import lombok.extern.slf4j.Slf4j; import rx.Observable; import rx.schedulers.Schedulers; import xdean.jex.extra.Either; import xdean.jex.extra.Wrapper; import xdean.jex.extra.function.RunnableThrow; import xdean.jex.extra.function.SupplierThrow; @Slf4j @UtilityClass public class TaskUtil { public void async(Runnable task) { Observable.just(task).observeOn(Schedulers.newThread()).subscribe(r -> r.run()); } public void uncheck(RunnableThrow<?> task) { try { task.run(); } catch (Throwable t) { throw new RuntimeException(t); } } public <T> T uncheck(SupplierThrow<T, ?> task) { return supplierToRunnable(task, r -> uncheck(r)); } public boolean uncatch(RunnableThrow<?> task) { try { task.run(); return true; } catch (Throwable t) { log.trace("Dont catch", t); return false; } } /** * * @param task * @return can be null */ public <T> T uncatch(SupplierThrow<T, ?> task) { return supplierToRunnable(task, r -> uncatch(r)); } @SuppressWarnings("unchecked") public <E extends Throwable> Optional<E> throwToReturn(RunnableThrow<E> task) { try { task.run(); } catch (Throwable t) { try { return Optional.of((E) t); } catch (ClassCastException cce) { throw new RuntimeException("An unexcepted exception thrown.", t); } } return Optional.empty(); } public <T, E extends Exception> Either<T, E> throwToReturn(SupplierThrow<T, E> task) { Wrapper<T> w = new Wrapper<T>(null); return Either.rightOrDefault(throwToReturn(() -> w.set(task.get())), w.get()); } public void todoAll(Runnable... tasks) { for (Runnable task : tasks) { task.run(); } } /** * Return the first NonNull result of these tasks * * @param tasks * @return can be null */ @SafeVarargs public <T> T firstSuccess(SupplierThrow<T, ?>... tasks) { for (SupplierThrow<T, ?> task : tasks) { T result = uncatch(task); if (result != null) { return result; } } return null; } /** * Run the given tasks until any exception happen * * @param tasks * @return the exception */ @SuppressWarnings("unchecked") @SafeVarargs public <T extends Throwable> Optional<T> firstFail(RunnableThrow<T>... tasks) { for (RunnableThrow<T> task : tasks) { try { task.run(); } catch (Throwable t) { try { return Optional.of((T) t); } catch (ClassCastException cce) { throw new RuntimeException("An unexcepted exception thrown.", t); } } } return Optional.empty(); } public void andFinal(Runnable task, Runnable then) { try { task.run(); } finally { then.run(); } } public <T> T andFinal(Supplier<T> task, Consumer<T> then) { T t = null; try { return t = task.get(); } finally { then.accept(t); } } @AllArgsConstructor public class IfWrapper { boolean condition; public IfWrapper todo(Runnable r) { if (condition) { r.run(); } return this; } public IfWrapper otherwise(Runnable r) { if (!condition) { r.run(); } return this; } public boolean toBoolean() { return condition; } } public IfWrapper ifThat(boolean b) { return new IfWrapper(b); } @Deprecated public boolean ifTodo(boolean b, Runnable todo) { return ifThat(b).todo(todo).toBoolean(); } @Deprecated public boolean ifTodo(boolean b, Runnable todo, Runnable elseTodo) { return ifThat(b).todo(todo).otherwise(elseTodo).toBoolean(); } }
// jTDS JDBC Driver for Microsoft SQL Server // 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 net.sourceforge.jtds.jdbc; import java.math.BigDecimal; import java.text.MessageFormat; import java.util.ResourceBundle; import java.sql.Blob; import java.sql.Clob; import java.sql.SQLException; import java.util.HashMap; import java.util.Calendar; import java.util.GregorianCalendar; import java.io.UnsupportedEncodingException; import java.lang.reflect.Method; import net.sourceforge.jtds.util.*; /** * This class contains static utility methods designed to support the * main driver classes. * <p> * Implementation notes: * <ol> * <li>The methods in this class incorporate some code from previous versions * of jTDS to handle dates, BLobs etc. * <li>This class contains routines to generate runtime messages from the resource file. * <li>The key data conversion logic used in Statements and result sets is implemented here. * <li>There is nothing here which is TDS specific. * </ol> * * @author Mike Hutchinson * @author jTDS project * @version $Id: Support.java,v 1.4 2004-07-07 17:59:56 bheineman Exp $ */ public class Support { // Constants used in datatype conversions to avoid object allocations. private static final Byte BYTE_ZERO = new Byte((byte) 0); private static final Byte BYTE_ONE = new Byte((byte) 1); private static final Short SHORT_ZERO = new Short((short) 0); private static final Short SHORT_ONE = new Short((short) 1); private static final Integer INTEGER_ZERO = new Integer(0); private static final Integer INTEGER_ONE = new Integer(1); private static final Long LONG_ZERO = new Long(0L); private static final Long LONG_ONE = new Long(1L); private static final Float FLOAT_ZERO = new Float(0.0); private static final Float FLOAT_ONE = new Float(1.0); private static final Double DOUBLE_ZERO = new Double(0.0); private static final Double DOUBLE_ONE = new Double(1.0); private static final BigDecimal BIG_DECIMAL_ZERO = new BigDecimal(0.0); private static final BigDecimal BIG_DECIMAL_ONE = new BigDecimal(1.0); private static final java.sql.Date DATE_ZERO = new java.sql.Date(0); private static final java.sql.Time TIME_ZERO = new java.sql.Time(0); /** * Convert java clases to java.sql.Type constant. */ private static final HashMap typeMap = new HashMap(); static { typeMap.put(Byte.class, new Integer(java.sql.Types.TINYINT)); typeMap.put(Short.class, new Integer(java.sql.Types.SMALLINT)); typeMap.put(Integer.class, new Integer(java.sql.Types.INTEGER)); typeMap.put(Long.class, new Integer(java.sql.Types.BIGINT)); typeMap.put(Float.class, new Integer(java.sql.Types.REAL)); typeMap.put(Double.class, new Integer(java.sql.Types.DOUBLE)); typeMap.put(BigDecimal.class, new Integer(java.sql.Types.DECIMAL)); typeMap.put(Boolean.class, new Integer(JtdsStatement.BOOLEAN)); typeMap.put(byte[].class, new Integer(java.sql.Types.VARBINARY)); typeMap.put(java.sql.Date.class, new Integer(java.sql.Types.DATE)); typeMap.put(java.sql.Time.class, new Integer(java.sql.Types.TIME)); typeMap.put(java.sql.Timestamp.class, new Integer(java.sql.Types.TIMESTAMP)); typeMap.put(BlobImpl.class, new Integer(java.sql.Types.LONGVARBINARY)); typeMap.put(ClobImpl.class, new Integer(java.sql.Types.LONGVARCHAR)); typeMap.put(String.class, new Integer(java.sql.Types.VARCHAR)); } /** * Hex constants to use in conversion routines. */ private static final char hex[] = {'0', '1', '2', '3', '4', '5', '6','7', '8', '9', 'A', 'B', 'C', 'D', 'E','F' }; /** * Static utility Calendar object. */ private static final GregorianCalendar cal = new GregorianCalendar(); /** * Default name for resource bundle containing the messages */ private static final String defaultResource = "net.sourceforge.jtds.jdbc.Messages"; /** * Get runtime message using supplied key. * * @param key The key of the message in Messages.properties * @return The selected message as a <code>String</code>. */ public static String getMessage(String key) { return getMessageText(key, null); } /** * Get runtime message using supplied key and substitute parameter * into message. * * @param key The key of the message in Messages.properties * @param param1 The object to insert into message. * @return The selected message as a <code>String</code>. */ static String getMessage(String key, Object param1) { Object args[] = {param1}; return getMessageText(key, args); } /** * Get runtime message using supplied key and substitute parameters * into message. * * @param key The key of the message in Messages.properties * @param param1 The object to insert into message. * @param param2 The object to insert into message. * @return The selected message as a <code>String</code>. */ static String getMessage(String key, Object param1, Object param2) { Object args[] = {param1, param2}; return getMessageText(key, args); } /** * Convert a byte[] object to a hex string. * * @param bytes The byte array to convert. * @return The hex equivalent as a <code>String</code>. */ static String toHex(byte[] bytes) { int len = bytes.length; if (len > 0) { StringBuffer buf = new StringBuffer(len * 2); for (int i = 0; i < len; i++) { int b1 = bytes[i] & 0xFF; buf.append(hex[b1 >> 4]); buf.append(hex[b1 & 0x0F]); } return buf.toString(); } return ""; } /** * Convert an existing data object to the specified JDBC type. * * @param x The data object to convert. * @param jdbcType The required type constant from java.sql.Types. * @return The (possibly) converted data object. * @throws SQLException if the conversion is not supported or fails. */ static Object convert(Object x, int jdbcType, String charSet) throws SQLException { try { switch (jdbcType) { case java.sql.Types.TINYINT: if (x == null) { return BYTE_ZERO; } else if (x instanceof Byte) { return x; } else if (x instanceof Number) { return new Byte(((Number) x).byteValue()); } else if (x instanceof String) { return new Byte((String) x); } else if (x instanceof Boolean) { return ((Boolean) x).booleanValue() ? BYTE_ONE : BYTE_ZERO; } break; case java.sql.Types.SMALLINT: if (x == null) { return SHORT_ZERO; } else if (x instanceof Short) { return x; } else if (x instanceof Number) { return new Short(((Number) x).shortValue()); } else if (x instanceof String) { return new Short((String) x); } else if (x instanceof Boolean) { return ((Boolean) x).booleanValue() ? SHORT_ONE : SHORT_ZERO; } break; case java.sql.Types.INTEGER: if (x == null) { return INTEGER_ZERO; } else if (x instanceof Integer) { return x; } else if (x instanceof Number) { return new Integer(((Number) x).intValue()); } else if (x instanceof String) { return new Integer((String) x); } else if (x instanceof Boolean) { return ((Boolean) x).booleanValue() ? INTEGER_ONE : INTEGER_ZERO; } break; case java.sql.Types.BIGINT: if (x == null) { return LONG_ZERO; } else if (x instanceof Long) { return x; } else if (x instanceof Number) { return new Long(((Number) x).longValue()); } else if (x instanceof String) { return new Long((String) x); } else if (x instanceof Boolean) { return ((Boolean) x).booleanValue() ? LONG_ONE : LONG_ZERO; } break; case java.sql.Types.REAL: case java.sql.Types.FLOAT: if (x == null) { return FLOAT_ZERO; } else if (x instanceof Float) { return x; } else if (x instanceof Number) { return new Float(((Number) x).floatValue()); } else if (x instanceof String) { return new Float((String) x); } else if (x instanceof Boolean) { return ((Boolean) x).booleanValue() ? FLOAT_ONE : FLOAT_ZERO; } break; case java.sql.Types.DOUBLE: if (x == null) { return DOUBLE_ZERO; } else if (x instanceof Double) { return x; } else if (x instanceof Number) { return new Double(((Number) x).doubleValue()); } else if (x instanceof String) { return new Double((String) x); } else if (x instanceof Boolean) { return ((Boolean) x).booleanValue() ? DOUBLE_ONE : DOUBLE_ZERO; } break; case java.sql.Types.NUMERIC: case java.sql.Types.DECIMAL: if (x == null) { return null; } else if (x instanceof BigDecimal) { return x; } else if (x instanceof Number) { return new BigDecimal(((Number) x).doubleValue()); } else if (x instanceof String) { return new BigDecimal((String) x); } else if (x instanceof Boolean) { return ((Boolean) x).booleanValue() ? BIG_DECIMAL_ONE : BIG_DECIMAL_ZERO; } break; case java.sql.Types.LONGVARCHAR: case java.sql.Types.VARCHAR: case java.sql.Types.CHAR: if (x == null) { return null; } else if (x instanceof String) { return x; } else if (x instanceof BigDecimal) { if (((BigDecimal) x).scale() > 0) { // Eliminate trailing zeros String tmp = x.toString(); for (int i = tmp.length() - 1; i > 0; i if (tmp.charAt(i) != '0') { if (tmp.charAt(i) == '.') { return tmp.substring(0, i); } return tmp.substring(0, i + 1); } } return tmp; } return x.toString(); } else if (x instanceof Number) { return x.toString(); } else if (x instanceof Boolean) { return((Boolean) x).booleanValue() ? "1" : "0"; } else if (x instanceof Clob) { Clob clob = (Clob) x; // FIXME - Throw exception if length() is greater than Integer.MAX_VALUE return clob.getSubString(1, (int) clob.length()); } else if (x instanceof Blob) { Blob blob = (Blob) x; // FIXME - Throw exception if length() is greater than Integer.MAX_VALUE x = blob.getBytes(1, (int) blob.length()); } if (x instanceof byte[]) { return Support.toHex((byte[]) x); } return x.toString(); // Last hope! case java.sql.Types.BIT: case JtdsStatement.BOOLEAN: if (x == null) { return Boolean.FALSE; } else if (x instanceof Boolean) { return x; } else if (x instanceof Number) { return(((Number) x).intValue() == 0) ? Boolean.FALSE : Boolean.TRUE; } else if (x instanceof String) { String tmp = ((String) x).trim(); return (tmp.equals("1") || tmp.equalsIgnoreCase("true")) ? Boolean.TRUE : Boolean.FALSE; } case java.sql.Types.LONGVARBINARY: case java.sql.Types.VARBINARY: case java.sql.Types.BINARY: if (x == null) { return null; } else if (x instanceof byte[]) { return x; } else if (x instanceof Blob) { Blob blob = (Blob) x; return blob.getBytes(1, (int) blob.length()); } else if (x instanceof Clob) { Clob clob = (Clob) x; // FIXME - Throw exception if length() is greater than Integer.MAX_VALUE x = clob.getSubString(1, (int) clob.length()); } if (x instanceof String) { if (charSet == null) { charSet = "ISO-8859-1"; } try { return ((String) x).getBytes(charSet); } catch (UnsupportedEncodingException e) { return ((String) x).getBytes(); } } else if (x instanceof UniqueIdentifier) { return ((UniqueIdentifier) x).getBytes(); } break; case java.sql.Types.TIMESTAMP: if (x == null) { return null; } else if (x instanceof java.sql.Timestamp) { return x; } else if (x instanceof java.sql.Date) { return new java.sql.Timestamp(((java.sql.Date) x).getTime()); } else if (x instanceof java.sql.Time) { return new java.sql.Timestamp(((java.sql.Time) x).getTime()); } break; case java.sql.Types.DATE: if (x == null) { return null; } else if (x instanceof java.sql.Date) { return x; } else if (x instanceof java.sql.Time) { return DATE_ZERO; } else if (x instanceof java.sql.Timestamp) { synchronized (cal) { cal.setTime((java.util.Date) x); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); // VM1.4+ only return new java.sql.Date(cal.getTimeInMillis()); return new java.sql.Date(cal.getTime().getTime()); } } break; case java.sql.Types.TIME: if (x == null) { return null; } else if (x instanceof java.sql.Time) { return x; } else if (x instanceof java.sql.Date) { return TIME_ZERO; } else if (x instanceof java.sql.Timestamp) { synchronized (cal) { cal.setTime((java.util.Date) x); cal.set(Calendar.YEAR, 0); cal.set(Calendar.MONTH, 0); cal.set(Calendar.DAY_OF_MONTH, 0); // VM 1.4+ only return new java.sql.Time(cal.getTimeInMillis()); return new java.sql.Time(cal.getTime().getTime()); } } break; case java.sql.Types.OTHER: case java.sql.Types.JAVA_OBJECT: return x; case java.sql.Types.BLOB: if (x == null) { return null; } else if (x instanceof Blob) { return x; } else if (x instanceof byte[]) { return new BlobImpl((byte[]) x); } else if (x instanceof Clob) { Clob clob = (Clob) x; x = clob.getSubString(0, (int) clob.length()); // FIXME - Use reader to populate Blob } if (x instanceof String) { BlobImpl blob = new BlobImpl(); String data = (String) x; if (charSet == null) { charSet = "ISO-8859-1"; } try { blob.setBytes(1, data.getBytes(charSet)); } catch (UnsupportedEncodingException e) { blob.setBytes(1, data.getBytes()); } return blob; } break; case java.sql.Types.CLOB: if (x == null) { return null; } else if (x instanceof Clob) { return x; } else if (x instanceof String) { return new ClobImpl((String) x); } else if (x instanceof Blob) { Blob blob = (Blob) x; x = blob.getBytes(0, (int) blob.length()); // FIXME - Use input stream to populate Clob } if (x instanceof byte[]) { ClobImpl clob = new ClobImpl(); byte[] data = (byte[]) x; if (charSet == null) { charSet = "ISO-8859-1"; } try { clob.setString(1, new String(data, charSet)); } catch (UnsupportedEncodingException e) { clob.setString(1, new String(data)); } return clob; } break; default: throw new SQLException( getMessage("error.convert.badtypeconst", getJdbcTypeName(jdbcType)), "HY004"); } throw new SQLException( getMessage("error.convert.badtypes", getJdbcTypeName(getJdbcType(x)), getJdbcTypeName(jdbcType)), "22005"); } catch (NumberFormatException nfe) { throw new SQLException( getMessage("error.convert.badnumber", getJdbcTypeName(jdbcType)), "22000"); } } /** * Get the JDBC type constant which matches the supplied Object type. * * @param value The object to analyse. * @return The JDBC type constant as an <code>int</code>. */ static int getJdbcType(Object value) { if (value == null) { return java.sql.Types.NULL; } Object type = typeMap.get(value.getClass()); if (type == null) { return java.sql.Types.OTHER; } return ((Integer) type).intValue(); } /** * Get a String describing the supplied JDBC type constant. * * @param jdbcType The constant to be decoded. * @return The text decode of the type constant as a <code>String</code>. */ static String getJdbcTypeName(int jdbcType) { switch (jdbcType) { case java.sql.Types.ARRAY: return "ARRAY"; case java.sql.Types.BIGINT: return "BIGINT"; case java.sql.Types.BINARY: return "BINARY"; case java.sql.Types.BIT: return "BIT"; case java.sql.Types.BLOB: return "BLOB"; case JtdsStatement.BOOLEAN: return "BOOLEAN"; case java.sql.Types.CHAR: return "CHAR"; case java.sql.Types.CLOB: return "CLOB"; case JtdsStatement.DATALINK: return "DATALINK"; case java.sql.Types.DATE: return "DATE"; case java.sql.Types.DECIMAL: return "DECIMAL"; case java.sql.Types.DISTINCT: return "DISTINCT"; case java.sql.Types.DOUBLE: return "DOUBLE"; case java.sql.Types.FLOAT: return "FLOAT"; case java.sql.Types.INTEGER: return "INTEGER"; case java.sql.Types.JAVA_OBJECT: return "JAVA_OBJECT"; case java.sql.Types.LONGVARBINARY: return "LONGVARBINARY"; case java.sql.Types.LONGVARCHAR: return "LONGVARCHAR"; case java.sql.Types.NULL: return "NULL"; case java.sql.Types.NUMERIC: return "NUMERIC"; case java.sql.Types.OTHER: return "OTHER"; case java.sql.Types.REAL: return "REAL"; case java.sql.Types.REF: return "REF"; case java.sql.Types.SMALLINT: return "SMALLINT"; case java.sql.Types.STRUCT: return "STRUCT"; case java.sql.Types.TIME: return "TIME"; case java.sql.Types.TIMESTAMP: return "TIMESTAMP"; case java.sql.Types.TINYINT: return "TINYINT"; case java.sql.Types.VARBINARY: return "VARBINARY"; case java.sql.Types.VARCHAR: return "VARCHAR"; default: return "ERROR"; } } /** * Retrieve the fully qualified java class name for the * supplied JDBC Types constant. * * @param jdbcType The JDBC Types constant. * @return The fully qualified java class name as a <code>String</code>. */ static String getClassName(int jdbcType) { switch (jdbcType) { case JtdsStatement.BOOLEAN: case java.sql.Types.BIT: return "java.lang.Boolean"; case java.sql.Types.TINYINT: return "java.lang.Byte"; case java.sql.Types.SMALLINT: return "java.lang.Short"; case java.sql.Types.INTEGER: return "java.lang.Integer"; case java.sql.Types.BIGINT: return "java.lang.Long"; case java.sql.Types.NUMERIC: case java.sql.Types.DECIMAL: return "java.math.BigDecimal"; case java.sql.Types.FLOAT: case java.sql.Types.DOUBLE: return "java.lang.Double"; case java.sql.Types.REAL: return "java.lang.Float"; case java.sql.Types.CHAR: case java.sql.Types.VARCHAR: case java.sql.Types.LONGVARCHAR: return "java.lang.String"; case java.sql.Types.BINARY: case java.sql.Types.VARBINARY: case java.sql.Types.LONGVARBINARY: return "byte[]"; case java.sql.Types.BLOB: return "java.sql.Blob"; case java.sql.Types.CLOB: return "java.sql.Clob"; case java.sql.Types.DATE: return "java.sql.Date"; case java.sql.Types.TIME: return "java.sql.Time"; case java.sql.Types.TIMESTAMP: return "java.sql.Timestamp"; } return "java.lang.Object"; } /** * Embed the data object as a string literal in the buffer supplied. * * @param buf The buffer in which the data will be embeded. * @param value The data object. */ static void embedData(StringBuffer buf, Object value) throws SQLException { if (value == null) { buf.append("NULL"); return; } if (value instanceof Blob) { Blob blob = (Blob) value; value = blob.getBytes(1, (int) blob.length()); } else if (value instanceof Clob) { Clob clob = (Clob) value; value = clob.getSubString(1, (int) clob.length()); } if (value instanceof byte[]) { byte[] bytes = (byte[]) value; int len = bytes.length; if (len > 0) { buf.append('0').append('x'); for (int i = 0; i < len; i++) { int b1 = bytes[i] & 0xFF; buf.append(hex[b1 >> 4]); buf.append(hex[b1 & 0x0F]); } } else { buf.append("NULL"); } } else if (value instanceof String) { String tmp = (String) value; int len = tmp.length(); buf.append('\''); for (int i = 0; i < len; i++) { char c = tmp.charAt(i); if (c == '\'') { buf.append('\''); if (i + 1 < len) { if (tmp.charAt(i + 1) == '\'') { i++; } } } buf.append(c); } buf.append('\''); } else if (value instanceof java.sql.Date) { synchronized (cal) { cal.setTime((java.sql.Date) value); buf.append('\''); long dt = cal.get(Calendar.YEAR) * 10000; dt += (cal.get(Calendar.MONTH) + 1) * 100; dt += cal.get(Calendar.DAY_OF_MONTH); buf.append(dt); buf.append(' '); int t = cal.get(Calendar.HOUR_OF_DAY); buf.append((t < 10) ? "0" + t + ":" : t + ":"); t = cal.get(Calendar.MINUTE); buf.append((t < 10) ? "0" + t + ":" : t + ":"); t = cal.get(Calendar.SECOND); buf.append((t < 10) ? "0" + t + "'" : t + "'"); } } else if (value instanceof java.sql.Time) { synchronized (cal) { cal.setTime((java.sql.Time) value); buf.append('\''); int t = cal.get(Calendar.HOUR_OF_DAY); buf.append((t < 10) ? "0" + t + ":" : t + ":"); t = cal.get(Calendar.MINUTE); buf.append((t < 10) ? "0" + t + ":" : t + ":"); t = cal.get(Calendar.SECOND); buf.append((t < 10) ? "0" + t + "'" : t + "'"); } } else if (value instanceof java.sql.Timestamp) { synchronized (cal) { cal.setTime((java.sql.Timestamp) value); buf.append('\''); long dt = cal.get(Calendar.YEAR) * 10000; dt += (cal.get(Calendar.MONTH) + 1) * 100; dt += cal.get(Calendar.DAY_OF_MONTH); buf.append(dt); buf.append(' '); int t = cal.get(Calendar.HOUR_OF_DAY); buf.append((t < 10) ? "0" + t + ":" : t + ":"); t = cal.get(Calendar.MINUTE); buf.append((t < 10) ? "0" + t + ":" : t + ":"); t = cal.get(Calendar.SECOND); buf.append((t < 10) ? "0" + t + "." : t + "."); t = (int)(cal.getTime().getTime() % 1000L); if (t < 100) { buf.append('0'); } if (t < 10) { buf.append('0'); } buf.append(t); buf.append('\''); } } else if (value instanceof Boolean) { buf.append(((Boolean) value).booleanValue() ? '1' : '0'); } else if (value instanceof BigDecimal) { BigDecimal bd = (BigDecimal) value; if (bd.scale() > 10) { // Must be a better answer than this bd = bd.setScale(10, BigDecimal.ROUND_HALF_UP); } buf.append(bd.toString()); } else { buf.append(value.toString()); } } /** * Update the SQL string and replace the &#63; markers with parameter names * eg @P0, @P1 etc. * * @param sql The SQL containing markers to substitute. * @param list The Parameter list. * @return The modified SQL as a <code>String</code>. */ static String substituteParamMarkers(String sql, ParamInfo[] list){ StringBuffer buf = new StringBuffer(sql.length() + list.length * 4); int start = 0; for (int i = 0; i < list.length; i++) { int pos = list[i].markerPos; if (pos > 0) { buf.append(sql.substring(start, list[i].markerPos)); start = pos + 1; buf.append("@P"); buf.append(i); } } if (start < sql.length()) { buf.append(sql.substring(start)); } return buf.toString(); } /** * Substitute actual data for the parameter markers to simulate * parameter substitution in a PreparedStatement. * * @param sql The SQL containing parameter markers to substitute. * @param list The parameter descriptors. * @return The modified SQL statement. */ static String substituteParameters(String sql, ParamInfo[] list) throws SQLException { int len = sql.length(); for (int i = 0; i < list.length; i++) { if (!list[i].isRetVal && !list[i].isSet && !list[i].isOutput) { throw new SQLException(Support.getMessage("error.prepare.paramnotset", Integer.toString(i+1)), "07000"); } Object value = list[i].value; if (value instanceof java.io.InputStream || value instanceof java.io.Reader) { try { if (list[i].jdbcType == java.sql.Types.LONGVARCHAR) { value = list[i].getString("US-ASCII"); } else { value = list[i].getBytes("US-ASCII"); } } catch (java.io.IOException e) { throw new SQLException(Support.getMessage("error.generic.ioerror", e.getMessage()), "HY000"); } } if (value instanceof String) { len += ((String) value).length() + 2; } else if (value instanceof byte[]) { len += ((byte[]) value).length * 2 + 2; } else { len += 10; // Default size } } StringBuffer buf = new StringBuffer(len); int start = 0; for (int i = 0; i < list.length; i++) { int pos = list[i].markerPos; if (pos > 0) { buf.append(sql.substring(start, list[i].markerPos)); start = pos + 1; Support.embedData(buf, list[i].value); } } if (start < sql.length()) { buf.append(sql.substring(start)); } return buf.toString(); } /** * Encode a string into a byte array using the specified character set. * * @param cs The Charset name. * @param value The value to encode. * @return The value of the String as a <code>byte[]</code>. */ static byte[] encodeString(String cs, String value) { try { return value.getBytes(cs); } catch (UnsupportedEncodingException e) { return value.getBytes(); } } /** * Link an the original cause exception to a SQL Exception. * <p>If running under VM 1.4+ the Exception.initCause() method * will be used to chain the exception. * Modeled after the code written by Brian Heineman. * * @param sqle The SQLException to enhance. * @param cause The child exception to link. * @return The enhanced <code>SQLException</code>. */ public static SQLException linkException(SQLException sqle, Throwable cause) { Class sqlExceptionClass = sqle.getClass(); Class[] parameterTypes = new Class[] {Throwable.class}; Object[] arguments = new Object[] {cause}; try { Method initCauseMethod = sqlExceptionClass.getMethod("initCause", parameterTypes); initCauseMethod.invoke(sqle, arguments); } catch (NoSuchMethodException e) { // Ignore; this method does not exist in older JVM's. if (Logger.isActive()) { Logger.logException((Exception) cause); // Best we can do } } catch (Exception e) { // Ignore all other exceptions, do not prevent the main exception // from being returned if reflection fails for any reason... } return sqle; } private Support() { // Prevent an instance of this class being created. } /** * Get runtime error using supplied key and substitute parameters * into message. * * @param key The key of the error message in Messages.properties * @param arguments The objects to insert into the message. * @return The selected error message as a <code>String</code>. */ private static String getMessageText(String key, Object[] arguments) { // ResourceBundle does caching so performance should be OK. ResourceBundle rb = ResourceBundle.getBundle(defaultResource); String formatString; try { formatString = rb.getString(key); } catch (java.util.MissingResourceException mre) { throw new RuntimeException("no message resource found for message property " + key); } MessageFormat formatter = new MessageFormat(formatString); return formatter.format(arguments); } }
package io.spine.server.commandbus; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.errorprone.annotations.CheckReturnValue; import com.google.errorprone.annotations.concurrent.LazyInit; import io.grpc.stub.StreamObserver; import io.spine.annotation.Internal; import io.spine.core.Ack; import io.spine.core.Command; import io.spine.core.TenantId; import io.spine.server.BoundedContextBuilder; import io.spine.server.ServerEnvironment; import io.spine.server.bus.BusBuilder; import io.spine.server.bus.BusFilter; import io.spine.server.bus.DeadMessageHandler; import io.spine.server.bus.EnvelopeValidator; import io.spine.server.bus.UnicastBus; import io.spine.server.command.CommandErrorHandler; import io.spine.server.event.EventBus; import io.spine.server.tenant.TenantIndex; import io.spine.server.type.CommandClass; import io.spine.server.type.CommandEnvelope; import io.spine.system.server.SystemWriteSide; import org.checkerframework.checker.nullness.qual.MonotonicNonNull; import org.checkerframework.checker.nullness.qual.Nullable; import java.util.Collection; import java.util.Deque; import java.util.Iterator; import java.util.Optional; import java.util.Set; import java.util.function.Consumer; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.Lists.newLinkedList; import static io.spine.server.bus.BusBuilder.FieldCheck.checkSet; import static io.spine.server.bus.BusBuilder.FieldCheck.systemNotSet; import static io.spine.server.bus.BusBuilder.FieldCheck.tenantIndexNotSet; import static io.spine.system.server.WriteSideFunction.delegatingTo; import static java.util.Optional.ofNullable; /** * Dispatches the incoming commands to the corresponding handler. */ public class CommandBus extends UnicastBus<Command, CommandEnvelope, CommandClass, CommandDispatcher<?>> { /** Consumes tenant IDs from incoming commands. */ private final Consumer<TenantId> tenantConsumer; /** Consumes commands dispatched by this bus. */ private final CommandFlowWatcher watcher; /** Callback for handling commands that failed. */ private final CommandErrorHandler errorHandler; private final CommandScheduler scheduler; private final SystemWriteSide systemWriteSide; /** * Is {@code true}, if the {@code BoundedContext} (to which this {@code CommandBus} belongs) * is multi-tenant. * * <p>If the {@code CommandBus} is multi-tenant, the commands posted must have the * {@code tenant_id} attribute defined. */ private final boolean multitenant; private final DeadCommandHandler deadCommandHandler = new DeadCommandHandler(); /** * Tha validator for the commands posted into this bus. * * <p>The value is effectively final, though should be initialized lazily. * * @see #validator() to getreive the non-null value of the validator */ @LazyInit private @MonotonicNonNull CommandValidator commandValidator; /** * Creates new instance according to the passed {@link Builder}. */ private CommandBus(Builder builder) { super(builder); this.multitenant = builder.multitenant != null ? builder.multitenant : false; this.scheduler = checkNotNull(builder.commandScheduler); this.systemWriteSide = builder.system() .orElseThrow(systemNotSet()); this.tenantConsumer = checkNotNull(builder.tenantConsumer); this.errorHandler = CommandErrorHandler.with(systemWriteSide, () -> builder.eventBus); this.watcher = checkNotNull(builder.flowWatcher); } /** * Creates a new {@link Builder} for the {@code CommandBus}. */ public static Builder newBuilder() { return new Builder(); } @Internal @VisibleForTesting public final boolean isMultitenant() { return multitenant; } @SuppressWarnings("ReturnOfCollectionOrArrayField") // OK for a protected factory method @Override protected final Collection<BusFilter<CommandEnvelope>> filterChainTail() { return ImmutableList.of(scheduler); } @Override protected Collection<BusFilter<CommandEnvelope>> filterChainHead() { BusFilter<CommandEnvelope> tap = new CommandReceivedTap(this::systemFor); Deque<BusFilter<CommandEnvelope>> result = newLinkedList(); result.push(tap); return result; } @Override protected CommandEnvelope toEnvelope(Command message) { return CommandEnvelope.of(message); } /** * {@inheritDoc} * * <p>Wraps the {@code source} observer with the {@link CommandAckMonitor}. * * @return new instance of {@link CommandAckMonitor} with the given parameters */ @Override protected StreamObserver<Ack> prepareObserver(Iterable<Command> commands, StreamObserver<Ack> source) { StreamObserver<Ack> wrappedSource = super.prepareObserver(commands, source); TenantId tenant = tenantOf(commands); StreamObserver<Ack> result = CommandAckMonitor .newBuilder() .setDelegate(wrappedSource) .setTenantId(tenant) .setPostedCommands(ImmutableSet.copyOf(commands)) .setSystemWriteSide(systemWriteSide) .build(); return result; } private static TenantId tenantOf(Iterable<Command> commands) { Iterator<Command> iterator = commands.iterator(); if (!iterator.hasNext()) { return TenantId.getDefaultInstance(); } TenantId result = iterator.next().tenant(); return result; } final SystemWriteSide systemFor(TenantId tenantId) { checkNotNull(tenantId); SystemWriteSide result = delegatingTo(systemWriteSide).get(tenantId); return result; } @Override protected void dispatch(CommandEnvelope command) { CommandDispatcher<?> dispatcher = dispatcherOf(command); watcher.onDispatchCommand(command); try { dispatcher.dispatch(command); } catch (RuntimeException exception) { errorHandler.handleAndPostIfRejection(command, exception); } } /** * Obtains the view {@code Set} of commands that are known to this {@code CommandBus}. * * <p>This set is changed when command dispatchers or handlers are registered or un-registered. * * @return a set of classes of supported commands */ public final Set<CommandClass> registeredCommandClasses() { return registry().registeredMessageClasses(); } @Override protected DeadMessageHandler<CommandEnvelope> deadMessageHandler() { return deadCommandHandler; } @Override protected EnvelopeValidator<CommandEnvelope> validator() { if (commandValidator == null) { commandValidator = new CommandValidator(this); } return commandValidator; } /** * Passes a previously scheduled command to the corresponding dispatcher. */ void postPreviouslyScheduled(Command command) { CommandEnvelope commandEnvelope = CommandEnvelope.of(command); dispatch(commandEnvelope); } @Override protected void store(Iterable<Command> commands) { TenantId tenantId = tenantOf(commands); tenantConsumer.accept(tenantId); } /** * {@inheritDoc} * * <p>Overrides for return type covariance. */ @Override protected CommandDispatcherRegistry registry() { return (CommandDispatcherRegistry) super.registry(); } /** * The {@code Builder} for {@code CommandBus}. */ @CanIgnoreReturnValue public static class Builder extends BusBuilder<Builder, Command, CommandEnvelope, CommandClass, CommandDispatcher<?>> { /** * The multi-tenancy flag for the {@code CommandBus} to build. * * <p>The value of this field should be equal to that of corresponding * {@linkplain BoundedContextBuilder BoundedContext.Builder} and is not * supposed to be {@linkplain #setMultitenant(Boolean) set directly}. * * <p>If set directly, the value would be matched to the multi-tenancy flag of * {@code BoundedContext}. */ private @Nullable Boolean multitenant; private CommandFlowWatcher flowWatcher; private Consumer<TenantId> tenantConsumer; private CommandScheduler commandScheduler; private EventBus eventBus; /** Prevents direct instantiation. */ private Builder() { super(); } @Override protected CommandDispatcherRegistry newRegistry() { return new CommandDispatcherRegistry(); } @Internal public @Nullable Boolean isMultitenant() { return multitenant; } @Internal public Builder setMultitenant(@Nullable Boolean multitenant) { this.multitenant = multitenant; return this; } /** * Inject the {@link EventBus} of the bounded context to which the built bus belongs. * * <p>This method is {@link Internal} to the framework. The name of the method starts with * {@code inject} prefix so that this method does not appear in an autocomplete hint for * {@code set} prefix. */ @Internal public Builder injectEventBus(EventBus eventBus) { checkNotNull(eventBus); this.eventBus = eventBus; return this; } Optional<EventBus> eventBus() { return ofNullable(eventBus); } @Override protected void checkFieldsSet() { super.checkFieldsSet(); checkSet(eventBus, EventBus.class, "injectEventBus"); } /** * Builds an instance of {@link CommandBus}. * * <p>This method is supposed to be called internally when building an enclosing * {@code BoundedContext}. */ @Override @Internal @CheckReturnValue public CommandBus build() { checkFieldsSet(); commandScheduler = ServerEnvironment.instance() .newCommandScheduler(); flowWatcher = createFlowWatcher(); commandScheduler.setWatcher(flowWatcher); TenantIndex tenantIndex = tenantIndex().orElseThrow(tenantIndexNotSet()); tenantConsumer = tenantIndex::keep; CommandBus commandBus = createCommandBus(); commandScheduler.setCommandBus(commandBus); return commandBus; } private CommandFlowWatcher createFlowWatcher() { return new CommandFlowWatcher((tenantId) -> { @SuppressWarnings("OptionalGetWithoutIsPresent") // ensured by checkFieldsSet() SystemWriteSide writeSide = system().get(); SystemWriteSide result = delegatingTo(writeSide).get(tenantId); return result; }); } @Override @CheckReturnValue protected Builder self() { return this; } @CheckReturnValue @SuppressWarnings("CheckReturnValue") /* Calling registry() enforces creating the registry to make spying for CommandBus instances in tests work. */ private CommandBus createCommandBus() { CommandBus commandBus = new CommandBus(this); commandBus.registry(); return commandBus; } } /** * Produces an {@link UnsupportedCommandException} upon a dead command. */ private static class DeadCommandHandler implements DeadMessageHandler<CommandEnvelope> { @Override public UnsupportedCommandException handle(CommandEnvelope message) { Command command = message.command(); UnsupportedCommandException exception = new UnsupportedCommandException(command); return exception; } } }
package net.oneandone.stool.server.api; import net.oneandone.sushi.fs.World; import org.apache.tomcat.util.codec.binary.Base64; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; public class Tunnel { public static void main(String[] args) throws NoSuchAlgorithmException, IOException { KeyPairGenerator generator; KeyPair pair; World world; generator = KeyPairGenerator.getInstance("RSA"); generator.initialize(2048); System.out.println("generating ..."); pair = generator.genKeyPair(); world = World.create(); world.file("id_rsa.pub").writeString(encodePublicRsaKey((RSAPublicKey) pair.getPublic(), "stool-tunnel")); world.file("id_rsa").writeString(encodePrivateRsaKey((RSAPrivateKey) pair.getPrivate())); System.out.println("done"); } public static String encodePublicRsaKey(RSAPublicKey rsaPublicKey, String user) { ByteArrayOutputStream dest; dest = new ByteArrayOutputStream(); try (DataOutputStream data = new DataOutputStream(dest)) { data.writeInt("ssh-rsa".getBytes().length); data.write("ssh-rsa".getBytes()); data.writeInt(rsaPublicKey.getPublicExponent().toByteArray().length); data.write(rsaPublicKey.getPublicExponent().toByteArray()); data.writeInt(rsaPublicKey.getModulus().toByteArray().length); data.write(rsaPublicKey.getModulus().toByteArray()); } catch (IOException e) { throw new IllegalStateException("ioeception on memory stream!?", e); } return "ssh-rsa " + Base64.encodeBase64String(dest.toByteArray()) + " " + user; } public static String encodePrivateRsaKey(RSAPrivateKey privateKey) { StringBuilder result; String str; int width; str = Base64.encodeBase64String(privateKey.getEncoded()); result = new StringBuilder(); result.append(" width = 0; for (int n = 0; n < str.length(); n ++) { result.append(str.charAt(n)); width++; if (width == 80) { result.append('\n'); width = 0; } } result.append("\n return result.toString(); } }
import org.opencv.core.Core; import org.opencv.imgcodecs.Imgcodecs; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.io.File; public class GUI { public static CameraFeed cf; public static EyeDetection e; public static Calibrator calibrator; public static boolean calibrated; public static void main(String[] args) { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); PatternDatabase.initialize(); cf = new CameraFeed(); cf.initialize(); e = new EyeDetection(); calibrator = new Calibrator(); JFrame frame = new JFrame("Blink"); frame.setSize(600, 800); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel(); panel.setBackground(new Color(120, 120, 120)); frame.add(panel); placeComponents(panel); frame.setVisible(true); } private static void placeComponents(JPanel panel) { panel.setLayout(null); final JLabel userLabel = new JLabel(new ImageIcon("thi.png")); userLabel.setBounds(60, 60, 480, 480); panel.add(userLabel); SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { for(int i = 0; i < 1000; i++) { cf.getFrames(GUI.e, GUI.calibrator); userLabel.setIcon( new ImageIcon(ImageIO.read( new File("thi.png") ) ) ); Thread.sleep(200); } return null; } }; JButton runButton = new JButton("Run"); runButton.setBounds(20, 580, 120, 25); runButton.addActionListener(new RunButtonListener(worker)); panel.add(runButton); JButton stopButton = new JButton("Stop"); stopButton.setBounds(160, 580, 120, 25); stopButton.addActionListener(new StopButtonListener(worker)); panel.add(stopButton); JTextArea textArea = new JTextArea(""); textArea.setBounds(20, 620, 540, 200); panel.add(textArea); JButton addScriptButton = new JButton("Add script"); addScriptButton.setBounds(440, 580, 120, 25); addScriptButton.addActionListener(new AddButtonListener(textArea)); panel.add(addScriptButton); JButton calibrateButton = new JButton("Calibrate"); calibrateButton.setBounds(300, 580, 120, 25); calibrateButton.addActionListener(new CalibrateButtonListener()); panel.add(calibrateButton); } }
package org.piwik.sdk; import android.os.Process; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicHeader; import org.apache.http.params.HttpConnectionParams; import org.apache.http.protocol.HTTP; import org.json.JSONObject; import org.piwik.sdk.tools.Logy; import java.io.UnsupportedEncodingException; import java.net.URISyntaxException; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; @SuppressWarnings("deprecation") public class Dispatcher { private static final String LOGGER_TAG = Piwik.LOGGER_PREFIX + "Dispatcher"; private final BlockingQueue<String> mDispatchQueue = new LinkedBlockingQueue<>(); private final Object mThreadControl = new Object(); private final Semaphore mSleepToken = new Semaphore(0); private final Piwik mPiwik; private final URL mApiUrl; private final String mAuthToken; private List<HttpRequestBase> mDryRunOutput = Collections.synchronizedList(new ArrayList<HttpRequestBase>()); private volatile int mTimeOut = 5 * 1000; private volatile boolean mRunning = false; private volatile long mDispatchInterval = 120 * 1000; // 120s public Dispatcher(Piwik piwik, URL apiUrl, String authToken) { mPiwik = piwik; mApiUrl = apiUrl; mAuthToken = authToken; } /** * Connection timeout in miliseconds * * @return */ public int getTimeOut() { return mTimeOut; } public void setTimeOut(int timeOut) { mTimeOut = timeOut; } public void setDispatchInterval(long dispatchInterval) { mDispatchInterval = dispatchInterval; if (mDispatchInterval != -1) launch(); } public long getDispatchInterval() { return mDispatchInterval; } private boolean launch() { synchronized (mThreadControl) { if (!mRunning) { mRunning = true; new Thread(mLoop).start(); return true; } } return false; } /** * Starts the dispatcher for one cycle if it is currently not working. * If the dispatcher is working it will skip the dispatch intervall once. */ public void forceDispatch() { if (!launch()) { mSleepToken.release(); } } public void submit(String query) { mDispatchQueue.add(query); if (mDispatchInterval != -1) launch(); } private Runnable mLoop = new Runnable() { @Override public void run() { android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); while (mRunning) { try { // Either we wait the interval or forceDispatch() granted us one free pass mSleepToken.tryAcquire(mDispatchInterval, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { e.printStackTrace(); } int count = 0; List<String> availableEvents = new ArrayList<>(); mDispatchQueue.drainTo(availableEvents); Logy.d(LOGGER_TAG, "Drained " + availableEvents.size() + " events."); TrackerBulkURLWrapper wrapper = new TrackerBulkURLWrapper(mApiUrl, availableEvents, mAuthToken); Iterator<TrackerBulkURLWrapper.Page> pageIterator = wrapper.iterator(); while (pageIterator.hasNext()) { TrackerBulkURLWrapper.Page page = pageIterator.next(); // use doGET when only event on current page if (page.elementsCount() > 1) { if (doPost(wrapper.getApiUrl(), wrapper.getEvents(page))) count += page.elementsCount(); } else { if (doGet(wrapper.getEventUrl(page))) count += 1; } } Logy.d(LOGGER_TAG, "Dispatched " + count + " events."); synchronized (mThreadControl) { // We may be done or this was a forced dispatch if (mDispatchQueue.isEmpty() || mDispatchInterval < 0) { mRunning = false; break; } } } } }; private boolean doGet(String trackingEndPointUrl) { if (trackingEndPointUrl == null) return false; HttpGet get = new HttpGet(trackingEndPointUrl); return doRequest(get); } private boolean doPost(URL url, JSONObject json) { if (url == null || json == null) return false; String jsonBody = json.toString(); try { HttpPost post = new HttpPost(url.toURI()); StringEntity se = new StringEntity(jsonBody); se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); post.setEntity(se); return doRequest(post); } catch (URISyntaxException e) { Logy.w(LOGGER_TAG, String.format("URI Syntax Error %s", url.toString()), e); } catch (UnsupportedEncodingException e) { Logy.w(LOGGER_TAG, String.format("Unsupported Encoding %s", jsonBody), e); } return false; } private boolean doRequest(HttpRequestBase requestBase) { HttpClient client = new DefaultHttpClient(); HttpConnectionParams.setConnectionTimeout(client.getParams(), mTimeOut); HttpResponse response; if (mPiwik.isDryRun()) { Logy.d(LOGGER_TAG, "DryRun, stored HttpRequest, now " + mDryRunOutput.size()); mDryRunOutput.add(requestBase); } else { if (!mDryRunOutput.isEmpty()) mDryRunOutput.clear(); try { response = client.execute(requestBase); int statusCode = response.getStatusLine().getStatusCode(); Logy.d(LOGGER_TAG, String.format("status code %s", statusCode)); return statusCode == HttpStatus.SC_NO_CONTENT || statusCode == HttpStatus.SC_OK; } catch (Exception e) { Logy.w(LOGGER_TAG, "Cannot send request", e); } } return false; } public static String urlEncodeUTF8(String param) { try { return URLEncoder.encode(param, "UTF-8").replaceAll("\\+", "%20"); } catch (UnsupportedEncodingException e) { Logy.w(LOGGER_TAG, String.format("Cannot encode %s", param), e); return ""; } catch (NullPointerException e) { return ""; } } public static String urlEncodeUTF8(Map<String, String> map) { StringBuilder sb = new StringBuilder(100); sb.append('?'); for (Map.Entry<String, String> entry : map.entrySet()) { sb.append(urlEncodeUTF8(entry.getKey())); sb.append('='); sb.append(urlEncodeUTF8(entry.getValue())); sb.append('&'); } return sb.substring(0, sb.length() - 1); } public List<HttpRequestBase> getDryRunOutput() { return mDryRunOutput; } }
package com.oracle.poco.bbhelper; import java.io.Console; import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import com.oracle.poco.bbhelper.log.BbhelperLogger; import jp.gr.java_conf.hhayakawa_jp.beehive_client.BeehiveContext; import jp.gr.java_conf.hhayakawa_jp.beehive_client.exception.Beehive4jException; @SpringBootApplication public class Application { @Autowired private BbhelperLogger logger; private static BbhelperLogger s_logger; @Autowired private ApplicationProperties properties; private static ApplicationProperties s_properties; private static boolean force = false; @PostConstruct public void init() { s_logger = logger; s_properties = properties; } public static void main(String[] args) { SpringApplication.run(Application.class); readOptions(args); if (!force) { checkConnection(); } Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { s_logger.info("shutdown."); } }); s_logger.info("started."); } private static void readOptions(String[] args) { for (String arg : args) { if ("-f".equals(arg)) { force = true; } } } private static void checkConnection() { System.out.println("Check connection with beehive..."); Console console = System.console(); String id = console.readLine("ID (email): "); String password = new String(console.readPassword("Password: ")); BeehiveContext context = null; try { context = BeehiveContext.getBeehiveContext( s_properties.getBeehiveUrl(), id, password); } catch (Beehive4jException e) { // TODO Auto-generated catch block System.exit(1); } finally { if (context == null) { // TODO log System.exit(1); } } } }
package edu.mit.csail.uid; import java.awt.*; import java.awt.event.*; import java.awt.Robot.*; import java.awt.image.*; import java.io.*; import java.nio.charset.*; import java.nio.*; import java.util.*; import javax.imageio.ImageIO; import javax.swing.*; public class SikuliScript { private OSUtil _osUtil; private boolean _showActions = false; public SikuliScript() throws AWTException{ _osUtil = Env.createOSUtil(); } public void setShowActions(boolean flag){ _showActions = flag; } public String input(String msg){ return (String)JOptionPane.showInputDialog(msg); } public int switchApp(String appName){ return _osUtil.switchApp(appName); } public int openApp(String appName){ return _osUtil.openApp(appName); } public int closeApp(String appName){ return _osUtil.closeApp(appName); } public void popup(String message){ JOptionPane.showMessageDialog(null, message, "Sikuli", JOptionPane.PLAIN_MESSAGE); } public String run(String cmdline){ String lines=""; try { String line; Process p = Runtime.getRuntime().exec(cmdline); BufferedReader input = new BufferedReader (new InputStreamReader(p.getInputStream())); while ((line = input.readLine()) != null) { lines = lines + '\n' + line; } } catch (Exception err) { err.printStackTrace(); } return lines; } public static void main(String[] args){ if(args.length == 0 ){ System.out.println("Usage: sikuli-script [file.sikuli]"); return; } for (int i = 0; i < args.length; i++) { try { ScriptRunner runner = new ScriptRunner(args); runner.runPython(args[i]); } catch(IOException e) { e.printStackTrace(); } } }
package com.atrakeur.quadripod.model; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import jssc.SerialPort; import jssc.SerialPortException; import jssc.SerialPortList; public class SerialModel { private String portName; private int bauds; private SerialPort port; private PropertyChangeSupport pcs; public SerialModel() { this(9600); } public SerialModel(int bauds) { this.bauds = bauds; String[] ports = availablePorts(); if (ports.length >= 1) { portName = ports[0]; } else { portName = ""; } this.pcs = new PropertyChangeSupport(this); } public SerialModel(String portName, int bauds) { this.portName = portName; this.bauds = bauds; this.pcs = new PropertyChangeSupport(this); } public String[] availablePorts() { return SerialPortList.getPortNames(); } public boolean isConnected() { return port != null; } public void connect() throws SerialPortException { if (isConnected()) { throw new SerialPortException(portName, "connect", "SerialCom allready connected"); } port = new SerialPort(portName); port.openPort();//Open serial port port.setParams(SerialPort.BAUDRATE_9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); pcs.firePropertyChange("connected", false, true); } public void disconnect() throws SerialPortException { if (!isConnected()) { throw new SerialPortException(port.getPortName(), "disconnect", "SerialCom not connected"); } port.closePort(); port = null; pcs.firePropertyChange("connected", true, false); } public void write(String str) throws SerialPortException { if (!isConnected()) { throw new SerialPortException(port.getPortName(), "write", "SerialCom not connected"); } port.writeString(str); } public String read() throws SerialPortException { if (!isConnected()) { throw new SerialPortException(port.getPortName(), "write", "SerialCom not connected"); } return port.readString(); } public String read(int timeout) throws SerialPortException, InterruptedException { if (!isConnected()) { throw new SerialPortException(port.getPortName(), "write", "SerialCom not connected"); } if (timeout < 10) { return read(); } String buff; StringBuilder retVal = new StringBuilder(); long end = System.currentTimeMillis() + timeout; while (System.currentTimeMillis() < end) { buff = read(); if (buff != null) { retVal.append(buff); } Thread.sleep(1); } if (retVal.length() > 0) { return retVal.toString(); } return null; } public String getPortName() { return portName; } public void setPortName(String portName) { String oldValue = this.portName; this.portName = portName; pcs.firePropertyChange("portName", oldValue, portName); } public int getBauds() { return bauds; } public void setBauds(int bauds) { int oldValue = bauds; this.bauds = bauds; pcs.firePropertyChange("bauds", oldValue, bauds); } public void addPropertyChangeListener(PropertyChangeListener listener) { pcs.addPropertyChangeListener(listener); } public void removePropertyChangeListener(PropertyChangeListener listener) { pcs.removePropertyChangeListener(listener); } }
package org.dionysus.domain; import java.util.Collection; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EntityListeners; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.Lob; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import org.hibernate.validator.constraints.NotBlank; import org.springframework.data.jpa.domain.AbstractPersistable; import org.springframework.data.jpa.domain.support.AuditingEntityListener; /** * * @author pengwang, persist courses consultant published */ @Entity @Table(name = "courses") @EntityListeners(AuditingEntityListener.class) public class Course extends AbstractPersistable<Long> { private static final long serialVersionUID = 2523934617928638918L; @Column(name = "title") @NotBlank(message = "course title is required") private String title; @Column(name = "description") private String description; //course has possible states, active, inactive, completed @Column(name = "state") private String state; //one consult can published many courses @ManyToOne(fetch = FetchType.EAGER) private Consultant consultant; /* one course has many registrations, one user can register many courses */ @ManyToMany(mappedBy = "registeredCourses") private Collection<User> registrations; }
package cgeo.geocaching; import cgeo.geocaching.activity.AbstractActionBarActivity; import cgeo.geocaching.activity.ActivityMixin; import cgeo.geocaching.connector.ConnectorFactory; import cgeo.geocaching.connector.IConnector; import cgeo.geocaching.enumerations.LoadFlags; import cgeo.geocaching.enumerations.LoadFlags.SaveFlag; import cgeo.geocaching.enumerations.WaypointType; import cgeo.geocaching.location.DistanceParser; import cgeo.geocaching.location.Geopoint; import cgeo.geocaching.location.GeopointFormatter; import cgeo.geocaching.models.CalcState; import cgeo.geocaching.models.Geocache; import cgeo.geocaching.models.Waypoint; import cgeo.geocaching.network.SmileyImage; import cgeo.geocaching.settings.Settings; import cgeo.geocaching.staticmaps.StaticMapsProvider; import cgeo.geocaching.storage.DataStore; import cgeo.geocaching.ui.WeakReferenceHandler; import cgeo.geocaching.ui.dialog.CoordinatesInputDialog; import cgeo.geocaching.ui.dialog.Dialogs; import cgeo.geocaching.utils.AndroidRxUtils; import cgeo.geocaching.utils.ClipboardUtils; import cgeo.geocaching.utils.Log; import cgeo.geocaching.utils.TextUtils; import cgeo.geocaching.utils.UnknownTagsHandler; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.annotation.NonNull; import android.support.v4.content.LocalBroadcastManager; import android.text.Html; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Spinner; import android.widget.TextView; import java.util.ArrayList; import java.util.Arrays; import java.util.EnumSet; import java.util.List; import java.util.concurrent.Callable; import io.reactivex.functions.Consumer; import io.reactivex.schedulers.Schedulers; import org.androidannotations.annotations.EActivity; import org.androidannotations.annotations.Extra; import org.androidannotations.annotations.InstanceState; import org.androidannotations.annotations.ViewById; import org.apache.commons.lang3.StringUtils; @EActivity public class EditWaypointActivity extends AbstractActionBarActivity implements CoordinatesInputDialog.CoordinateUpdate, CoordinatesInputDialog.CalculateState { public static final int SUCCESS = 0; public static final int UPLOAD_START = 1; public static final int UPLOAD_ERROR = 2; public static final int UPLOAD_NOT_POSSIBLE = 3; public static final int UPLOAD_SUCCESS = 4; public static final int SAVE_ERROR = 5; private static final String CALC_STATE_JSON = "calc_state_json"; private static final ArrayList<WaypointType> POSSIBLE_WAYPOINT_TYPES = new ArrayList<>(WaypointType.ALL_TYPES_EXCEPT_OWN_AND_ORIGINAL); @ViewById(R.id.buttonLatitude) protected Button buttonLat; @ViewById(R.id.buttonLongitude) protected Button buttonLon; @ViewById(R.id.note) protected EditText note; @ViewById(R.id.user_note) protected EditText userNote; @ViewById(R.id.wpt_visited_checkbox) protected CheckBox visitedCheckBox; @ViewById(R.id.name) protected AutoCompleteTextView waypointName; @ViewById(R.id.type) protected Spinner waypointTypeSelector; @ViewById(R.id.distance) protected EditText distanceView; @ViewById(R.id.modify_cache_coordinates_group) protected RadioGroup coordinatesGroup; @ViewById(R.id.modify_cache_coordinates_local_and_remote) protected RadioButton modifyBoth; @ViewById(R.id.distanceUnit) protected Spinner distanceUnitSelector; @ViewById(R.id.bearing) protected EditText bearing; @ViewById(R.id.modify_cache_coordinates_local) protected RadioButton modifyLocal; @ViewById(R.id.projection) protected LinearLayout projection; @Extra(Intents.EXTRA_GEOCODE) protected String geocode = null; @Extra(Intents.EXTRA_WAYPOINT_ID) protected int waypointId = -1; @Extra(Intents.EXTRA_COORDS) protected Geopoint initialCoords = null; @InstanceState protected int waypointTypeSelectorPosition = -1; private ProgressDialog waitDialog = null; private Waypoint waypoint = null; private String prefix = ""; private String lookup = " private boolean own = true; private boolean originalCoordsEmpty = false; private List<String> distanceUnits = null; /** * {@code true} if the activity is newly created, {@code false} if it is restored from an instance state */ private boolean initViews = true; /** * This is the cache that the waypoint belongs to. */ private Geocache cache; /** * State the Coordinate Calculator was last left in. */ private String calcStateJson; private final Handler loadWaypointHandler = new LoadWaypointHandler(this); private static final class LoadWaypointHandler extends WeakReferenceHandler<EditWaypointActivity> { LoadWaypointHandler(final EditWaypointActivity activity) { super(activity); } @Override public void handleMessage(final Message msg) { final EditWaypointActivity activity = getReference(); if (activity == null) { return; } try { final Waypoint waypoint = activity.waypoint; if (waypoint == null) { Log.d("No waypoint loaded to edit. id= " + activity.waypointId); activity.waypointId = -1; } else { activity.geocode = waypoint.getGeocode(); activity.prefix = waypoint.getPrefix(); activity.lookup = waypoint.getLookup(); activity.own = waypoint.isUserDefined(); activity.originalCoordsEmpty = waypoint.isOriginalCoordsEmpty(); activity.calcStateJson = waypoint.getCalcStateJson(); if (activity.initViews) { activity.visitedCheckBox.setChecked(waypoint.isVisited()); activity.updateCoordinates(waypoint.getCoords()); final AutoCompleteTextView waypointName = activity.waypointName; waypointName.setText(TextUtils.stripHtml(StringUtils.trimToEmpty(waypoint.getName()))); Dialogs.moveCursorToEnd(waypointName); activity.note.setText(Html.fromHtml(StringUtils.trimToEmpty(waypoint.getNote()), new SmileyImage(activity.geocode, activity.note), new UnknownTagsHandler()), TextView.BufferType.SPANNABLE); final EditText userNote = activity.userNote; userNote.setText(StringUtils.trimToEmpty(waypoint.getUserNote())); Dialogs.moveCursorToEnd(userNote); } AndroidRxUtils.andThenOnUi(Schedulers.io(), new Runnable() { @Override public void run() { DataStore.loadCache(activity.geocode, LoadFlags.LOAD_CACHE_ONLY); } }, new Runnable() { @Override public void run() { activity.setCoordsModificationVisibility(ConnectorFactory.getConnector(activity.geocode)); } }); } if (activity.own) { activity.initializeWaypointTypeSelector(); if (StringUtils.isNotBlank(activity.note.getText())) { activity.userNote.setText(activity.note.getText().append("\n").append(activity.userNote.getText())); activity.note.setText(""); } } else { activity.nonEditable(activity.waypointName); activity.nonEditable(activity.note); if (waypoint != null && !waypoint.isOriginalCoordsEmpty()) { activity.projection.setVisibility(View.GONE); } } if (StringUtils.isBlank(activity.note.getText().toString())) { activity.note.setVisibility(View.GONE); } } catch (final RuntimeException e) { Log.e("EditWaypointActivity.loadWaypointHandler", e); } finally { Dialogs.dismiss(activity.waitDialog); activity.waitDialog = null; } } } private void nonEditable(final TextView textView) { textView.setKeyListener(null); textView.setTextIsSelectable(true); } @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState, R.layout.editwaypoint_activity); if (StringUtils.isBlank(geocode) && waypointId <= 0) { showToast(res.getString(R.string.err_waypoint_cache_unknown)); finish(); return; } if (waypointId <= 0) { setTitle(res.getString(R.string.waypoint_add_title)); } else { setTitle(res.getString(R.string.waypoint_edit_title)); } buttonLat.setOnClickListener(new CoordDialogListener()); buttonLon.setOnClickListener(new CoordDialogListener()); final List<String> wayPointTypes = new ArrayList<>(); for (final WaypointType wpt : WaypointType.ALL_TYPES_EXCEPT_OWN_AND_ORIGINAL) { wayPointTypes.add(wpt.getL10n()); } final ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, wayPointTypes); waypointName.setAdapter(adapter); if (savedInstanceState != null) { initViews = false; calcStateJson = savedInstanceState.getString(CALC_STATE_JSON); } else { calcStateJson = null; } if (geocode != null) { cache = DataStore.loadCache(geocode, LoadFlags.LOAD_CACHE_OR_DB); setCoordsModificationVisibility(ConnectorFactory.getConnector(geocode)); } if (waypointId > 0) { // existing waypoint waitDialog = ProgressDialog.show(this, null, res.getString(R.string.waypoint_loading), true); waitDialog.setCancelable(true); (new LoadWaypointThread()).start(); } else { // new waypoint initializeWaypointTypeSelector(); note.setVisibility(View.GONE); updateCoordinates(initialCoords); } initializeDistanceUnitSelector(); disableSuggestions(distanceView); } private void setCoordsModificationVisibility(final IConnector con) { modifyBoth.setVisibility(con.supportsOwnCoordinates() ? View.VISIBLE : View.GONE); } @Override public boolean onOptionsItemSelected(final MenuItem item) { switch (item.getItemId()) { case R.id.menu_edit_waypoint_cancel: finish(); return true; case R.id.menu_edit_waypoint_save: saveWaypoint(getActivityData()); finish(); return true; case android.R.id.home: finishConfirmDiscard(); return true; } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { finishConfirmDiscard(); } @Override public boolean onCreateOptionsMenu(final Menu menu) { getMenuInflater().inflate(R.menu.edit_waypoint_options, menu); return true; } private void initializeWaypointTypeSelector() { final ArrayAdapter<WaypointType> wpAdapter = new ArrayAdapter<WaypointType>(this, android.R.layout.simple_spinner_item, POSSIBLE_WAYPOINT_TYPES.toArray(new WaypointType[POSSIBLE_WAYPOINT_TYPES.size()])) { @Override public View getView(final int position, final View convertView, final ViewGroup parent) { final View view = super.getView(position, convertView, parent); addWaypointIcon(position, view); return view; } @Override public View getDropDownView(final int position, final View convertView, final ViewGroup parent) { final View view = super.getDropDownView(position, convertView, parent); addWaypointIcon(position, view); return view; } private void addWaypointIcon(final int position, final View view) { final TextView label = (TextView) view.findViewById(android.R.id.text1); label.setCompoundDrawablesWithIntrinsicBounds(POSSIBLE_WAYPOINT_TYPES.get(position).markerId, 0, 0, 0); } }; wpAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); waypointTypeSelector.setAdapter(wpAdapter); waypointTypeSelector.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(final AdapterView<?> parent, final View v, final int pos, final long id) { final String oldDefaultName = waypointTypeSelectorPosition >= 0 ? getDefaultWaypointName(POSSIBLE_WAYPOINT_TYPES.get(waypointTypeSelectorPosition)) : StringUtils.EMPTY; waypointTypeSelectorPosition = pos; final String currentName = waypointName.getText().toString().trim(); if (StringUtils.isBlank(currentName) || oldDefaultName.equals(currentName)) { waypointName.setText(getDefaultWaypointName(getSelectedWaypointType())); } } @Override public void onNothingSelected(final AdapterView<?> parent) { } }); waypointTypeSelector.setSelection(getDefaultWaypointType()); waypointTypeSelector.setVisibility(View.VISIBLE); } private int getDefaultWaypointType() { // potentially restore saved instance state if (waypointTypeSelectorPosition >= 0) { return waypointTypeSelectorPosition; } // when editing, use the existing type if (waypoint != null) { return POSSIBLE_WAYPOINT_TYPES.indexOf(waypoint.getWaypointType()); } // make default for new waypoint depend on cache type switch (cache.getType()) { case MYSTERY: return POSSIBLE_WAYPOINT_TYPES.indexOf(WaypointType.FINAL); case MULTI: return POSSIBLE_WAYPOINT_TYPES.indexOf(WaypointType.STAGE); default: return POSSIBLE_WAYPOINT_TYPES.indexOf(WaypointType.WAYPOINT); } } private void initializeDistanceUnitSelector() { distanceUnits = new ArrayList<>(Arrays.asList(res.getStringArray(R.array.distance_units))); if (initViews) { distanceUnitSelector.setSelection(Settings.useImperialUnits() ? 2 : 0); //0:m, 2:ft } } private class LoadWaypointThread extends Thread { @Override public void run() { try { waypoint = DataStore.loadWaypoint(waypointId); if (waypoint == null) { return; } calcStateJson = waypoint.getCalcStateJson(); loadWaypointHandler.sendMessage(Message.obtain()); } catch (final Exception e) { Log.e("EditWaypointActivity.loadWaypoint.run", e); } } } private class CoordDialogListener implements View.OnClickListener { @Override public void onClick(final View view) { Geopoint gp = null; try { gp = new Geopoint(buttonLat.getText().toString(), buttonLon.getText().toString()); } catch (final Geopoint.ParseException ignored) { // button text is blank when creating new waypoint } final Geopoint geopoint = gp; AndroidRxUtils.andThenOnUi(Schedulers.io(), new Callable<Geocache>() { @Override public Geocache call() throws Exception { return DataStore.loadCache(geocode, LoadFlags.LOAD_WAYPOINTS); } }, new Consumer<Geocache>() { @Override public void accept(final Geocache geocache) throws Exception { if (waypoint == null || waypoint.isUserDefined() || waypoint.isOriginalCoordsEmpty()) { showCoordinatesInputDialog(geopoint, cache); } else { showCoordinateOptionsDialog(view, geopoint, cache); } } }); } private void showCoordinateOptionsDialog(final View view, final Geopoint geopoint, final Geocache cache) { final AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext()); builder.setTitle(res.getString(R.string.waypoint_coordinates)); builder.setItems(R.array.waypoint_coordinates_options, new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int item) { final String selectedOption = res.getStringArray(R.array.waypoint_coordinates_options)[item]; if (res.getString(R.string.waypoint_copy_coordinates).equals(selectedOption) && geopoint != null) { ClipboardUtils.copyToClipboard(GeopointFormatter.reformatForClipboard(geopoint.toString())); showToast(res.getString(R.string.clipboard_copy_ok)); } else if (res.getString(R.string.waypoint_duplicate).equals(selectedOption)) { final Waypoint copy = cache.duplicateWaypoint(waypoint); if (copy != null) { DataStore.saveCache(cache, EnumSet.of(SaveFlag.DB)); EditWaypointActivity.startActivityEditWaypoint(EditWaypointActivity.this, cache, copy.getId()); } } } }); final AlertDialog alert = builder.create(); alert.show(); } private void showCoordinatesInputDialog(final Geopoint geopoint, final Geocache cache) { final CoordinatesInputDialog coordsDialog = CoordinatesInputDialog.getInstance(cache, geopoint); coordsDialog.setCancelable(true); coordsDialog.show(getSupportFragmentManager(), "wpeditdialog"); } } @Override public void updateCoordinates(final Geopoint gp) { if (gp != null) { buttonLat.setText(gp.format(GeopointFormatter.Format.LAT_DECMINUTE)); buttonLon.setText(gp.format(GeopointFormatter.Format.LON_DECMINUTE)); setProjectionEnabled(true); } else { buttonLat.setText(R.string.waypoint_latitude_null); buttonLon.setText(R.string.waypoint_longitude_null); setProjectionEnabled(false); } } @Override public boolean supportsNullCoordinates() { return true; } private void setProjectionEnabled(final boolean enabled) { bearing.setEnabled(enabled); distanceView.setEnabled(enabled); distanceUnitSelector.setEnabled(enabled); if (!enabled) { bearing.setText(""); distanceView.setText(""); } } @Override public void saveCalculatorState(final CalcState calcState) { this.calcStateJson = calcState != null ? calcState.toJSON().toString() : null; } @Override public CalcState fetchCalculatorState() { return CalcState.fromJSON(calcStateJson); } /** * Save the current state of the calculator such that it can be restored after screen rotation (or similar) */ @Override public void onSaveInstanceState(final Bundle outState) { super.onSaveInstanceState(outState); outState.putString(CALC_STATE_JSON, calcStateJson); } /** * Suffix the waypoint type with a running number to get a default name. * * @param type * type to create a new default name for * */ private String getDefaultWaypointName(final WaypointType type) { final ArrayList<String> wpNames = new ArrayList<>(); for (final Waypoint waypoint : cache.getWaypoints()) { wpNames.add(waypoint.getName()); } // try final and trailhead without index if ((type == WaypointType.FINAL || type == WaypointType.TRAILHEAD) && !wpNames.contains(type.getL10n())) { return type.getL10n(); } // for other types add an index by default, which is highest found index + 1 int max = 0; for (int i = 0; i < 30; i++) { if (wpNames.contains(type.getL10n() + " " + i)) { max = i; } } return type.getL10n() + " " + (max + 1); } private WaypointType getSelectedWaypointType() { final int selectedTypeIndex = waypointTypeSelector.getSelectedItemPosition(); return selectedTypeIndex >= 0 ? POSSIBLE_WAYPOINT_TYPES.get(selectedTypeIndex) : waypoint.getWaypointType(); } private void finishConfirmDiscard() { final ActivityData currentState = getActivityData(); if (currentState != null && isWaypointChanged(currentState)) { Dialogs.confirm(this, R.string.confirm_unsaved_changes_title, R.string.confirm_discard_wp_changes, new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int which) { finish(); } }); } else { finish(); } } public EditText getUserNotes() { return userNote; } private boolean coordsTextsValid(final String latText, final String lonText) { return !latText.equals(getResources().getString(R.string.waypoint_latitude_null)) && !lonText.equals(getResources().getString(R.string.waypoint_longitude_null)); } private ActivityData getActivityData() { final String latText = buttonLat.getText().toString(); final String lonText = buttonLon.getText().toString(); Geopoint coords = null; if (coordsTextsValid(latText, lonText)) { try { coords = new Geopoint(latText, lonText); } catch (final Geopoint.ParseException e) { showToast(res.getString(e.resource)); return null; } } final String bearingText = bearing.getText().toString(); // combine distance from EditText and distanceUnit saved from Spinner final String distanceText = distanceView.getText().toString() + distanceUnits.get(distanceUnitSelector.getSelectedItemPosition()); if (coords != null && StringUtils.isNotBlank(bearingText) && StringUtils.isNotBlank(distanceText)) { // bearing & distance final double bearing; try { bearing = Double.parseDouble(bearingText); } catch (final NumberFormatException ignored) { Dialogs.message(this, R.string.err_point_bear_and_dist_title, R.string.err_point_bear_and_dist); return null; } final double distance; try { distance = DistanceParser.parseDistance(distanceText, !Settings.useImperialUnits()); } catch (final NumberFormatException ignored) { showToast(res.getString(R.string.err_parse_dist)); return null; } coords = coords.project(bearing, distance); } final ActivityData currentState = new ActivityData(); currentState.coords = coords; final String givenName = waypointName.getText().toString().trim(); currentState.name = StringUtils.defaultIfBlank(givenName, getDefaultWaypointName(getSelectedWaypointType())); if (own) { currentState.noteText = ""; } else { // keep original note currentState.noteText = waypoint.getNote(); } currentState.userNoteText = userNote.getText().toString().trim(); currentState.type = getSelectedWaypointType(); currentState.visited = visitedCheckBox.isChecked(); currentState.calcStateJson = calcStateJson; return currentState; } private boolean isWaypointChanged(@NonNull final ActivityData currentState) { return waypoint == null || !Geopoint.equalsFormatted(currentState.coords, waypoint.getCoords(), GeopointFormatter.Format.LAT_LON_DECMINUTE) || !StringUtils.equals(currentState.name, waypoint.getName()) || !StringUtils.equals(currentState.noteText, waypoint.getNote()) || !StringUtils.equals(currentState.userNoteText, waypoint.getUserNote()) || currentState.visited != waypoint.isVisited() || currentState.type != waypoint.getWaypointType() || !StringUtils.equals(currentState.calcStateJson, waypoint.getCalcStateJson()); } private static class FinishWaypointSaveHandler extends WeakReferenceHandler<EditWaypointActivity> { private final Geopoint coords; FinishWaypointSaveHandler(final EditWaypointActivity activity, final Geopoint coords) { super(activity); this.coords = coords != null ? new Geopoint(coords.getLatitude(), coords.getLongitude()) : null; } @Override public void handleMessage(final Message msg) { final EditWaypointActivity activity = getReference(); if (activity == null) { return; } switch (msg.what) { case UPLOAD_SUCCESS: ActivityMixin.showApplicationToast(activity.getString(R.string.waypoint_coordinates_has_been_modified_on_website, coords)); break; case SUCCESS: break; case UPLOAD_START: break; case UPLOAD_ERROR: ActivityMixin.showApplicationToast(activity.getString(R.string.waypoint_coordinates_upload_error)); break; case UPLOAD_NOT_POSSIBLE: ActivityMixin.showApplicationToast(activity.getString(R.string.waypoint_coordinates_couldnt_be_modified_on_website)); break; case SAVE_ERROR: ActivityMixin.showApplicationToast(activity.getString(R.string.err_waypoint_add_failed)); break; default: throw new IllegalStateException(); } } } private void saveWaypoint(final ActivityData currentState) { // currentState might be null here if there is a problem with the waypoints data if (currentState == null) { return; } final Handler finishHandler = new FinishWaypointSaveHandler(this, currentState.coords); AndroidRxUtils.computationScheduler.scheduleDirect(new Runnable() { @Override public void run() { saveWaypointInBackground(currentState, finishHandler); } }); } protected void saveWaypointInBackground(final ActivityData currentState, final Handler finishHandler) { final Waypoint waypoint = new Waypoint(currentState.name, currentState.type, own); waypoint.setGeocode(geocode); waypoint.setPrefix(prefix); waypoint.setLookup(lookup); waypoint.setCoords(currentState.coords); waypoint.setNote(currentState.noteText); waypoint.setUserNote(currentState.userNoteText); waypoint.setVisited(currentState.visited); waypoint.setId(waypointId); waypoint.setOriginalCoordsEmpty(originalCoordsEmpty); waypoint.setCalcStateJson(currentState.calcStateJson); final Geocache cache = DataStore.loadCache(geocode, LoadFlags.LOAD_WAYPOINTS); if (cache == null) { finishHandler.sendEmptyMessage(SAVE_ERROR); return; } final Waypoint oldWaypoint = cache.getWaypointById(waypointId); if (cache.addOrChangeWaypoint(waypoint, true)) { if (!StaticMapsProvider.hasAllStaticMapsForWaypoint(geocode, waypoint)) { StaticMapsProvider.removeWpStaticMaps(oldWaypoint, geocode); if (Settings.isStoreOfflineWpMaps()) { StaticMapsProvider.storeWaypointStaticMap(cache, waypoint).subscribe(); } } if (waypoint.getCoords() != null && (modifyLocal.isChecked() || modifyBoth.isChecked())) { if (!cache.hasUserModifiedCoords()) { final Waypoint origWaypoint = new Waypoint(CgeoApplication.getInstance().getString(R.string.cache_coordinates_original), WaypointType.ORIGINAL, false); origWaypoint.setCoords(cache.getCoords()); cache.addOrChangeWaypoint(origWaypoint, false); cache.setUserModifiedCoords(true); } cache.setCoords(waypoint.getCoords()); DataStore.saveChangedCache(cache); } if (waypoint.getCoords() != null && modifyBoth.isChecked()) { finishHandler.sendEmptyMessage(UPLOAD_START); if (cache.supportsOwnCoordinates()) { final boolean result = uploadModifiedCoords(cache, waypoint.getCoords()); finishHandler.sendEmptyMessage(result ? UPLOAD_SUCCESS : UPLOAD_ERROR); } else { ActivityMixin.showApplicationToast(getString(R.string.waypoint_coordinates_couldnt_be_modified_on_website)); finishHandler.sendEmptyMessage(UPLOAD_NOT_POSSIBLE); } } else { finishHandler.sendEmptyMessage(SUCCESS); } } else { finishHandler.sendEmptyMessage(SAVE_ERROR); } LocalBroadcastManager.getInstance(EditWaypointActivity.this).sendBroadcast(new Intent(Intents.INTENT_CACHE_CHANGED)); } private static class ActivityData { public String name; public WaypointType type; public Geopoint coords; public String noteText; public String userNoteText; public boolean visited; public String calcStateJson; } private static boolean uploadModifiedCoords(final Geocache cache, final Geopoint waypointUploaded) { final IConnector con = ConnectorFactory.getConnector(cache); return con.supportsOwnCoordinates() && con.uploadModifiedCoordinates(cache, waypointUploaded); } public static void startActivityEditWaypoint(final Context context, final Geocache cache, final int waypointId) { EditWaypointActivity_.intent(context).geocode(cache.getGeocode()).waypointId(waypointId).start(); } public static void startActivityAddWaypoint(final Context context, final Geocache cache) { EditWaypointActivity_.intent(context).geocode(cache.getGeocode()).start(); } public static void startActivityAddWaypoint(final Context context, final Geocache cache, final Geopoint initialCoords) { EditWaypointActivity_.intent(context).geocode(cache.getGeocode()).initialCoords(initialCoords).start(); } @Override public void finish() { Dialogs.dismiss(waitDialog); super.finish(); } }
package cgeo.geocaching; import butterknife.ButterKnife; import butterknife.InjectView; import cgeo.geocaching.activity.Keyboard; import cgeo.geocaching.connector.ConnectorFactory; import cgeo.geocaching.connector.LogResult; import cgeo.geocaching.connector.trackable.AbstractTrackableLoggingManager; import cgeo.geocaching.connector.trackable.TrackableConnector; import cgeo.geocaching.enumerations.LoadFlags; import cgeo.geocaching.enumerations.Loaders; import cgeo.geocaching.enumerations.LogTypeTrackable; import cgeo.geocaching.enumerations.StatusCode; import cgeo.geocaching.location.Geopoint; import cgeo.geocaching.sensors.Sensors; import cgeo.geocaching.settings.Settings; import cgeo.geocaching.settings.SettingsActivity; import cgeo.geocaching.twitter.Twitter; import cgeo.geocaching.ui.dialog.CoordinatesInputDialog; import cgeo.geocaching.ui.dialog.CoordinatesInputDialog.CoordinateUpdate; import cgeo.geocaching.ui.dialog.DateDialog; import cgeo.geocaching.ui.dialog.DateDialog.DateDialogParent; import cgeo.geocaching.ui.dialog.Dialogs; import cgeo.geocaching.ui.dialog.TimeDialog; import cgeo.geocaching.ui.dialog.TimeDialog.TimeDialogParent; import cgeo.geocaching.utils.AsyncTaskWithProgress; import cgeo.geocaching.utils.Formatter; import cgeo.geocaching.utils.Log; import cgeo.geocaching.utils.LogTemplateProvider; import cgeo.geocaching.utils.LogTemplateProvider.LogContext; import cgeo.geocaching.utils.LogTemplateProvider.LogTemplate; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import android.R.string; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.res.Configuration; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.os.Bundle; import android.support.v4.app.LoaderManager; import android.support.v4.content.Loader; import android.view.ContextMenu; import android.view.ContextThemeWrapper; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnFocusChangeListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.LinearLayout; import java.util.ArrayList; import java.util.Calendar; import java.util.List; public class LogTrackableActivity extends AbstractLoggingActivity implements DateDialogParent, TimeDialogParent, CoordinateUpdate, LoaderManager.LoaderCallbacks<List<LogTypeTrackable>> { @InjectView(R.id.type) protected Button typeButton; @InjectView(R.id.date) protected Button dateButton; @InjectView(R.id.time) protected Button timeButton; @InjectView(R.id.geocode) protected EditText geocacheEditText; @InjectView(R.id.coordinates) protected Button coordinatesButton; @InjectView(R.id.tracking) protected EditText trackingEditText; @InjectView(R.id.log) protected EditText logEditText; @InjectView(R.id.tweet) protected CheckBox tweetCheck; @InjectView(R.id.tweet_box) protected LinearLayout tweetBox; private List<LogTypeTrackable> possibleLogTypesTrackable = new ArrayList<>(); private String geocode = null; private Geopoint geopoint; private Geocache geocache = new Geocache(); /** * As long as we still fetch the current state of the trackable from the Internet, the user cannot yet send a log. */ private boolean postReady = true; private Calendar date = Calendar.getInstance(); private LogTypeTrackable typeSelected = LogTypeTrackable.getById(Settings.getTrackableAction()); private Trackable trackable; TrackableConnector connector; private AbstractTrackableLoggingManager loggingManager; /** * How many times the warning popup for geocode not set should be displayed */ final public static int MAX_SHOWN_POPUP_TRACKABLE_WITHOUT_GEOCODE = 3; final public static int LOG_TRACKABLE = 1; @Override public Loader<List<LogTypeTrackable>> onCreateLoader(final int id, final Bundle bundle) { showProgress(true); loggingManager = connector.getTrackableLoggingManager(this); if (loggingManager == null) { showToast(res.getString(R.string.err_tb_not_loggable)); finish(); return null; } if (id == Loaders.LOGGING_TRAVELBUG.getLoaderId()) { loggingManager.setGuid(trackable.getGuid()); } return loggingManager; } @Override public void onLoadFinished(final Loader<List<LogTypeTrackable>> listLoader, final List<LogTypeTrackable> logTypesTrackable) { if (CollectionUtils.isNotEmpty(logTypesTrackable)) { possibleLogTypesTrackable.clear(); possibleLogTypesTrackable.addAll(logTypesTrackable); } if (logTypesTrackable != null && !logTypesTrackable.contains(typeSelected) && !logTypesTrackable.isEmpty()) { setType(logTypesTrackable.get(0)); showToast(res.getString(R.string.info_log_type_changed)); } postReady = loggingManager.postReady(); // we're done, user can post log showProgress(false); } @Override public void onLoaderReset(final Loader<List<LogTypeTrackable>> listLoader) { // nothing } @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState, R.layout.logtrackable_activity); ButterKnife.inject(this); // get parameters final Bundle extras = getIntent().getExtras(); if (extras != null) { geocode = extras.getString(Intents.EXTRA_GEOCODE); // Load geocache if we can if (StringUtils.isNotBlank(extras.getString(Intents.EXTRA_GEOCACHE))) { final Geocache tmpGeocache = DataStore.loadCache(extras.getString(Intents.EXTRA_GEOCACHE), LoadFlags.LOAD_CACHE_OR_DB); if (tmpGeocache != null) { geocache = tmpGeocache; } } // Display tracking code if we have, and move cursor next if (StringUtils.isNotBlank(extras.getString(Intents.EXTRA_TRACKING_CODE))) { trackingEditText.setText(extras.getString(Intents.EXTRA_TRACKING_CODE)); Dialogs.moveCursorToEnd(trackingEditText); } } // Load Trackable from internal trackable = DataStore.loadTrackable(geocode); if (trackable == null) { Log.e("LogTrackableActivity.onCreate: cannot load trackable " + geocode); setResult(RESULT_CANCELED); finish(); return; } if (StringUtils.isNotBlank(trackable.getName())) { setTitle(res.getString(R.string.trackable_touch) + ": " + trackable.getName()); } else { setTitle(res.getString(R.string.trackable_touch) + ": " + trackable.getGeocode()); } // We're in LogTrackableActivity, so trackable must be loggable ;) if (!trackable.isLoggable()) { showToast(res.getString(R.string.err_tb_not_loggable)); finish(); return; } // create trackable connector connector = ConnectorFactory.getTrackableConnector(geocode); // Start loading in background getSupportLoaderManager().initLoader(connector.getTrackableLoggingManagerLoaderId(), null, this).forceLoad(); // Show retrieved infos displayTrackable(); init(); requestKeyboardForLogging(); } private void displayTrackable() { if (StringUtils.isNotBlank(trackable.getName())) { setTitle(res.getString(R.string.trackable_touch) + ": " + trackable.getName()); } else { setTitle(res.getString(R.string.trackable_touch) + ": " + trackable.getGeocode()); } } @Override protected void requestKeyboardForLogging() { if (StringUtils.isBlank(trackingEditText.getText())) { new Keyboard(this).show(trackingEditText); } else { super.requestKeyboardForLogging(); } } @Override public void onConfigurationChanged(final Configuration newConfig) { super.onConfigurationChanged(newConfig); init(); } @Override public void onCreateContextMenu(final ContextMenu menu, final View view, final ContextMenu.ContextMenuInfo info) { super.onCreateContextMenu(menu, view, info); final int viewId = view.getId(); if (viewId == R.id.type) { for (final LogTypeTrackable typeOne : possibleLogTypesTrackable) { menu.add(viewId, typeOne.id, 0, typeOne.getLabel()); } } } @Override public boolean onContextItemSelected(final MenuItem item) { final int group = item.getGroupId(); final int id = item.getItemId(); if (group == R.id.type) { setType(LogTypeTrackable.getById(id)); return true; } return false; } private void init() { registerForContextMenu(typeButton); typeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View view) { openContextMenu(view); } }); setType(typeSelected); dateButton.setOnClickListener(new DateListener()); setDate(date); // show/hide Time selector if (loggingManager.canLogTime()) { timeButton.setOnClickListener(new TimeListener()); setTime(date); timeButton.setVisibility(View.VISIBLE); } else { timeButton.setVisibility(View.GONE); } // Register Coordinates Listener if (loggingManager.canLogCoordinates()) { geocacheEditText.setOnFocusChangeListener(new LoadGeocacheListener()); geocacheEditText.setText(geocache.getGeocode()); updateCoordinates(geocache.getCoords()); coordinatesButton.setOnClickListener(new CoordinatesListener()); } initTwitter(); if (CollectionUtils.isEmpty(possibleLogTypesTrackable)) { possibleLogTypesTrackable = Trackable.getPossibleLogTypes(); } disableSuggestions(trackingEditText); } @Override public void setDate(final Calendar dateIn) { date = dateIn; dateButton.setText(Formatter.formatShortDateVerbally(date.getTime().getTime())); } @Override public void setTime(final Calendar dateIn) { date = dateIn; timeButton.setText(Formatter.formatTime(date.getTime().getTime())); } public void setType(final LogTypeTrackable type) { typeSelected = type; typeButton.setText(typeSelected.getLabel()); // show/hide Coordinate fields as Trackable needs if (LogTypeTrackable.isCoordinatesNeeded(typeSelected) && loggingManager.canLogCoordinates()) { geocacheEditText.setVisibility(View.VISIBLE); coordinatesButton.setVisibility(View.VISIBLE); } else { geocacheEditText.setVisibility(View.GONE); coordinatesButton.setVisibility(View.GONE); } // show/hide Tracking Code Field for note type if (typeSelected != LogTypeTrackable.NOTE || loggingManager.isTrackingCodeNeededToPostNote()) { trackingEditText.setVisibility(View.VISIBLE); } else { trackingEditText.setVisibility(View.GONE); } } private void initTwitter() { tweetCheck.setChecked(true); if (Settings.isUseTwitter() && Settings.isTwitterLoginValid()) { tweetBox.setVisibility(View.VISIBLE); } else { tweetBox.setVisibility(View.GONE); } } @Override public void updateCoordinates(final Geopoint geopointIn) { if (geopointIn == null) { return; } geopoint = geopointIn; coordinatesButton.setText(geopoint.toString()); geocache.setCoords(geopoint); } private class DateListener implements View.OnClickListener { @Override public void onClick(final View arg0) { final DateDialog dateDialog = DateDialog.getInstance(date); dateDialog.setCancelable(true); dateDialog.show(getSupportFragmentManager(), "date_dialog"); } } private class TimeListener implements View.OnClickListener { @Override public void onClick(final View arg0) { final TimeDialog timeDialog = TimeDialog.getInstance(date); timeDialog.setCancelable(true); timeDialog.show(getSupportFragmentManager(),"time_dialog"); } } private class CoordinatesListener implements View.OnClickListener { @Override public void onClick(final View arg0) { final CoordinatesInputDialog coordinatesDialog = CoordinatesInputDialog.getInstance(geocache, geopoint, Sensors.getInstance().currentGeo()); coordinatesDialog.setCancelable(true); coordinatesDialog.show(getSupportFragmentManager(),"coordinates_dialog"); } } // React when changing geocode private class LoadGeocacheListener implements OnFocusChangeListener { @Override public void onFocusChange(final View view, final boolean hasFocus) { if (!hasFocus && !geocacheEditText.getText().toString().isEmpty()) { final Geocache tmpGeocache = DataStore.loadCache(geocacheEditText.getText().toString(), LoadFlags.LOAD_CACHE_OR_DB); if (tmpGeocache == null) { geocache.setGeocode(geocacheEditText.getText().toString()); } else { geocache = tmpGeocache; updateCoordinates(geocache.getCoords()); } } } } private class Poster extends AsyncTaskWithProgress<String, StatusCode> { public Poster(final Activity activity, final String progressMessage) { super(activity, null, progressMessage, true); } @Override protected StatusCode doInBackgroundInternal(final String[] params) { final String logMsg = params[0]; try { // Set selected action final TrackableLog trackableLog = new TrackableLog(trackable.getGeocode(), trackable.getTrackingcode(), trackable.getName(), 0, 0, trackable.getBrand()); trackableLog.setAction(typeSelected); // Real call to post log final LogResult logResult = loggingManager.postLog(geocache, trackableLog, date, logMsg); // Now posting tweet if log is OK if (logResult.getPostLogResult() == StatusCode.NO_ERROR) { addLocalTrackableLog(logMsg); if (tweetCheck.isChecked() && tweetBox.getVisibility() == View.VISIBLE) { // TODO oldLogType as a temp workaround... final LogEntry logNow = new LogEntry(date.getTimeInMillis(), typeSelected.oldLogtype, logMsg); Twitter.postTweetTrackable(trackable.getGeocode(), logNow); } } // Display errors to the user if (StringUtils.isNoneEmpty(logResult.getLogId())) { showToast(logResult.getLogId()); } // Return request status return logResult.getPostLogResult(); } catch (final RuntimeException e) { Log.e("LogTrackableActivity.Poster.doInBackgroundInternal", e); } return StatusCode.LOG_POST_ERROR; } @Override protected void onPostExecuteInternal(final StatusCode status) { if (status == StatusCode.NO_ERROR) { showToast(res.getString(R.string.info_log_posted)); finish(); } else if (status == StatusCode.LOG_SAVED) { // is this part of code really reachable ? Dind't see StatusCode.LOG_SAVED in postLog() showToast(res.getString(R.string.info_log_saved)); finish(); } else { showToast(status.getErrorString(res)); } } /** * Adds the new log to the list of log entries for this trackable to be able to show it in the trackable * activity. * * */ private void addLocalTrackableLog(final String logText) { // TODO create a LogTrackableEntry. For now use "oldLogtype" as a temporary migration path final LogEntry logEntry = new LogEntry(date.getTimeInMillis(), typeSelected.oldLogtype, logText); final List<LogEntry> modifiedLogs = new ArrayList<>(trackable.getLogs()); modifiedLogs.add(0, logEntry); trackable.setLogs(modifiedLogs); DataStore.saveTrackable(trackable); } } public static Intent getIntent(final Context context, final Trackable trackable) { final Intent logTouchIntent = new Intent(context, LogTrackableActivity.class); logTouchIntent.putExtra(Intents.EXTRA_GEOCODE, trackable.getGeocode()); logTouchIntent.putExtra(Intents.EXTRA_TRACKING_CODE, trackable.getTrackingcode()); return logTouchIntent; } public static Intent getIntent(final Context context, final Trackable trackable, final String geocache) { final Intent logTouchIntent = getIntent(context, trackable); logTouchIntent.putExtra(Intents.EXTRA_GEOCACHE, geocache); return logTouchIntent; } @Override protected LogContext getLogContext() { return new LogContext(trackable, null); } @Override public boolean onOptionsItemSelected(final MenuItem item) { switch (item.getItemId()) { case R.id.menu_send: if (connector.isRegistered()) { sendLog(); } else { // Redirect user to concerned connector settings Dialogs.confirmYesNo(this, res.getString(R.string.settings_title_open_settings), res.getString(R.string.err_trackable_log_not_anonymous, trackable.getBrand().getLabel(), connector.getServiceTitle()), new OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int which) { if (connector.getPreferenceActivity() > 0) { SettingsActivity.openForScreen(connector.getPreferenceActivity(), LogTrackableActivity.this); } else { showToast(res.getString(R.string.err_trackable_no_preference_activity, connector.getServiceTitle())); } } }); } return true; default: break; } return super.onOptionsItemSelected(item); } /** * Do form validation then post the Log */ private void sendLog() { // Can logging? if (!postReady) { showToast(res.getString(R.string.log_post_not_possible)); return; } // Check Tracking Code existence if (loggingManager.isTrackingCodeNeededToPostNote() && trackingEditText.getText().toString().isEmpty()) { showToast(res.getString(R.string.err_log_post_missing_tracking_code)); return; } trackable.setTrackingcode(trackingEditText.getText().toString()); // Check params for trackables needing coordinates if (loggingManager.canLogCoordinates() && LogTypeTrackable.isCoordinatesNeeded(typeSelected)) { // Check Coordinates if (geopoint == null) { showToast(res.getString(R.string.err_log_post_missing_coordinates)); return; } } // Some Trackable connectors recommend logging with a Geocode. // Note: Currently, counter is shared between all connectors recommending Geocode. if (LogTypeTrackable.isCoordinatesNeeded(typeSelected) && loggingManager.canLogCoordinates() && connector.recommendLogWithGeocode() && geocacheEditText.getText().toString().isEmpty() && Settings.getLogTrackableWithoutGeocodeShowCount() < MAX_SHOWN_POPUP_TRACKABLE_WITHOUT_GEOCODE) { new LogTrackableWithoutGeocodeBuilder().create(this).show(); } else { postLog(); } } /** * Post Log in Background */ private void postLog() { new Poster(this, res.getString(R.string.log_saving)).execute(logEditText.getText().toString()); Settings.setLastTrackableLog(logEditText.getText().toString()); } @Override public boolean onCreateOptionsMenu(final Menu menu) { final boolean result = super.onCreateOptionsMenu(menu); for (final LogTemplate template : LogTemplateProvider.getTemplatesWithoutSignature()) { if (template.getTemplateString().equals("NUMBER")) { menu.findItem(R.id.menu_templates).getSubMenu().removeItem(template.getItemId()); } } return result; } @Override protected String getLastLog() { return Settings.getLastTrackableLog(); } /** * This will display a popup for confirming if Trackable Log should be send without a geocode. * It will be displayed only MAX_SHOWN_POPUP_TRACKABLE_WITHOUT_GEOCODE times. A "Do not ask me again" * checkbox is also added. */ public class LogTrackableWithoutGeocodeBuilder { private CheckBox doNotAskAgain; public AlertDialog create(final Activity activity) { final AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setTitle(R.string.trackable_title_log_without_geocode); final Context themedContext; themedContext = Settings.isLightSkin() && VERSION.SDK_INT < VERSION_CODES.HONEYCOMB ? new ContextThemeWrapper(activity, R.style.dark) : activity; final View layout = View.inflate(themedContext, R.layout.logtrackable_without_geocode, null); builder.setView(layout); doNotAskAgain = (CheckBox) layout.findViewById(R.id.logtrackable_do_not_ask_me_again); final int showCount = Settings.getLogTrackableWithoutGeocodeShowCount(); Settings.setLogTrackableWithoutGeocodeShowCount(showCount + 1); builder.setPositiveButton(string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int which) { checkDoNotAskAgain(); dialog.dismiss(); } }); builder.setNegativeButton(string.no, new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int which) { checkDoNotAskAgain(); dialog.dismiss(); // Post the log postLog(); } }); return builder.create(); } /** * Verify if doNotAskAgain is checked. * If true, set the counter to MAX_SHOWN_POPUP_TRACKABLE_WITHOUT_GEOCODE */ private void checkDoNotAskAgain() { if (doNotAskAgain.isChecked()) { Settings.setLogTrackableWithoutGeocodeShowCount(MAX_SHOWN_POPUP_TRACKABLE_WITHOUT_GEOCODE); } } } }
package com.example.fragment; import java.util.List; import android.location.Location; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.example.db.MyPlace; import com.example.db.MyPlacesDb; import com.example.demoaerisproject.R; import com.example.view.TemperatureInfoData; import com.example.view.TemperatureWindowAdapter; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.hamweather.aeris.communication.AerisCallback; import com.hamweather.aeris.communication.EndpointType; import com.hamweather.aeris.communication.fields.Fields; import com.hamweather.aeris.communication.fields.ObservationFields; import com.hamweather.aeris.communication.loaders.ObservationsTask; import com.hamweather.aeris.communication.loaders.ObservationsTaskCallback; import com.hamweather.aeris.communication.parameter.ParameterBuilder; import com.hamweather.aeris.communication.parameter.PlaceParameter; import com.hamweather.aeris.location.LocationHelper; import com.hamweather.aeris.maps.AerisMapView; import com.hamweather.aeris.maps.AerisMapView.AerisMapType; import com.hamweather.aeris.maps.MapViewFragment; import com.hamweather.aeris.maps.interfaces.OnAerisMapLongClickListener; import com.hamweather.aeris.maps.interfaces.OnAerisMarkerInfoWindowClickListener; import com.hamweather.aeris.maps.markers.AerisMarker; import com.hamweather.aeris.model.AerisError; import com.hamweather.aeris.model.AerisResponse; import com.hamweather.aeris.model.Observation; import com.hamweather.aeris.model.RelativeTo; import com.hamweather.aeris.response.EarthquakesResponse; import com.hamweather.aeris.response.FiresResponse; import com.hamweather.aeris.response.ObservationResponse; import com.hamweather.aeris.response.StormCellResponse; import com.hamweather.aeris.response.StormReportsResponse; public class MapFragment extends MapViewFragment implements OnAerisMapLongClickListener, AerisCallback, ObservationsTaskCallback, OnAerisMarkerInfoWindowClickListener, RefreshInterface { private LocationHelper locHelper; private Marker marker; private TemperatureWindowAdapter infoAdapter; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_interactive_maps, container, false); mapView = (AerisMapView) view.findViewById(R.id.aerisfragment_map); mapView.init(savedInstanceState, AerisMapType.GOOGLE); initMap(); setHasOptionsMenu(true); return view; } /** * Inits the map with specific setting */ private void initMap() { MyPlacesDb db = new MyPlacesDb(getActivity()); MyPlace place = db.getMyPlace(); if (place == null) { locHelper = new LocationHelper(getActivity()); Location myLocation = locHelper.getCurrentLocation(); mapView.moveToLocation(myLocation, 9); } else { mapView.moveToLocation(new LatLng(place.latitude, place.longitude), 9); } mapView.setOnAerisMapLongClickListener(this); // mapView.hideAnimationButton(); // setup the custom info window adapter to use infoAdapter = new TemperatureWindowAdapter(getActivity()); mapView.addWindowInfoAdapter(infoAdapter); // setup doing something when a user presses an info window // from the Aeris Point Data. mapView.setOnAerisWindowClickListener(this); } /* * (non-Javadoc) * * @see android.app.Fragment#onOptionsItemSelected(android.view.MenuItem) */ @Override public boolean onOptionsItemSelected(MenuItem item) { int itemId = item.getItemId(); if (itemId == R.id.menu_weather_layers) { mapView.startAerisMapOptionsActivity(getActivity()); /* * Alternatively you could only show the map points options like * this using the MapOptionsActivityBuilder(). See the classes * javadoc for more detail and examples of it. */ // MapOptionsActivityBuilder builder = new // MapOptionsActivityBuilder(); // builder.withAllPoints(); // mapView.startAerisMapOptionsActivity(getActivity(), builder); return false; } else { return super.onOptionsItemSelected(item); } } @Override public void onResume() { super.onResume(); } /* * (non-Javadoc) * * @see android.app.Fragment#onCreateOptionsMenu(android.view.Menu, * android.view.MenuInflater) */ @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.menu_maps_fragment, menu); super.onCreateOptionsMenu(menu, inflater); } /* * (non-Javadoc) * * @see com.hamweather.aeris.maps.AerisMapView.OnAerisMapLongClickListener# * onMapLongClick(double, double) */ @Override public void onMapLongClick(double lat, double longitude) { // AerisRequest request = new AerisRequest(new Endpoint( // EndpointType.OBSERVATIONS), Action.CLOSEST, new PlaceParameter( // lat, longitude), FieldsParameter.initWith( // ObservationFields.ICON, ObservationFields.TEMP_C, // ObservationFields.TEMP_F, Fields.RELATIVE_TO)); // AerisCommunicationTask task = new // AerisCommunicationTask(getActivity(), // this, request); // task.execute(); // the above using a specific object loader ParameterBuilder builder = new ParameterBuilder().withFields( ObservationFields.ICON, ObservationFields.TEMP_C, ObservationFields.TEMP_F, Fields.RELATIVE_TO); ObservationsTask task = new ObservationsTask(getActivity(), this); task.requestClosest(new PlaceParameter(lat, longitude), builder.build()); } /* * (non-Javadoc) * * @see * com.hamweather.aeris.communication.AerisCallback#onResult(com.hamweather * .aeris.communication.EndpointType, * com.hamweather.aeris.model.AerisResponse) */ @Override public void onResult(EndpointType type, AerisResponse response) { if (type == EndpointType.OBSERVATIONS) { if (response.isSuccessfulWithResponses()) { ObservationResponse obResponse = new ObservationResponse( response.getFirstResponse()); Observation ob = obResponse.getObservation(); RelativeTo relativeTo = obResponse.getRelativeTo(); if (marker != null) { marker.remove(); } TemperatureInfoData data = new TemperatureInfoData(ob.icon, String.valueOf(ob.tempF)); marker = infoAdapter.addGoogleMarker(mapView.getMap(), relativeTo.lat, relativeTo.lon, BitmapDescriptorFactory .fromResource(R.drawable.map_indicator_blank), data); marker.showInfoWindow(); } } } @Override public void earthquakeWindowPressed(EarthquakesResponse response, AerisMarker marker) { // do something with the response data. Toast.makeText(getActivity(), "Earthquake pressed!", Toast.LENGTH_SHORT) .show(); } @Override public void stormReportsWindowPressed(StormReportsResponse response, AerisMarker marker) { // do something with the response data. Toast.makeText(getActivity(), "Storm Report pressed!", Toast.LENGTH_SHORT).show(); } @Override public void stormCellsWindowPressed(StormCellResponse response, AerisMarker marker) { // do something with the response data. Toast.makeText(getActivity(), "Storm Cell pressed!", Toast.LENGTH_SHORT) .show(); } @Override public void wildfireWindowPressed(FiresResponse response, AerisMarker marker) { // do something with the response data. Toast.makeText(getActivity(), "Wildfire pressed!", Toast.LENGTH_SHORT) .show(); } @Override public void onObservationsFailed(AerisError arg0) { Toast.makeText(getActivity(), "Failed to load observation at that point", Toast.LENGTH_SHORT) .show(); } @Override public void onObservationsLoaded(List<ObservationResponse> responses) { ObservationResponse obResponse = responses.get(0); Observation ob = obResponse.getObservation(); RelativeTo relativeTo = obResponse.getRelativeTo(); if (marker != null) { marker.remove(); } TemperatureInfoData data = new TemperatureInfoData(ob.icon, String.valueOf(ob.tempF)); marker = infoAdapter.addGoogleMarker(mapView.getMap(), relativeTo.lat, relativeTo.lon, BitmapDescriptorFactory .fromResource(R.drawable.map_indicator_blank), data); marker.showInfoWindow(); } @Override public void refreshPressed() { MyPlacesDb db = new MyPlacesDb(getActivity()); MyPlace place = db.getMyPlace(); if (place != null) { mapView.moveToLocation(new LatLng(place.latitude, place.longitude), 9); } else { locHelper = new LocationHelper(getActivity()); Location myLocation = locHelper.getCurrentLocation(); mapView.moveToLocation(myLocation, 9); } } }
package tc.oc.pgm.payload; import com.google.common.collect.Range; import org.bukkit.util.ImVector; import org.bukkit.util.Vector; import org.jdom2.Element; import tc.oc.pgm.features.FeatureDefinitionParser; import tc.oc.pgm.features.FeatureParser; import tc.oc.pgm.filters.Filter; import tc.oc.pgm.filters.parser.FilterParser; import tc.oc.pgm.goals.ProximityMetric; import tc.oc.pgm.regions.Region; import tc.oc.pgm.regions.RegionParser; import tc.oc.pgm.teams.TeamFactory; import tc.oc.pgm.utils.MaterialPattern; import tc.oc.pgm.utils.XMLUtils; import tc.oc.pgm.xml.InvalidXMLException; import tc.oc.pgm.xml.Node; import tc.oc.pgm.xml.property.PropertyBuilderFactory; import javax.inject.Inject; import java.time.Duration; public final class PayloadParser implements FeatureDefinitionParser<PayloadDefinition> { private final FilterParser filterParser; private final FeatureParser<TeamFactory> teamParser; private final PropertyBuilderFactory<ImVector, ?> vectors; @Inject private PayloadParser(FilterParser filterParser, FeatureParser<TeamFactory> teamParser, PropertyBuilderFactory<ImVector, ?> vectors) { this.filterParser = filterParser; this.teamParser = teamParser; this.vectors = vectors; } @Override public PayloadDefinition parseElement(Element elPayload) throws InvalidXMLException { final Vector location = vectors.property(elPayload, "location").required(); final Vector spawnLocation = vectors.property(elPayload, "spawn-location").optional((ImVector)location); final float yaw = XMLUtils.parseNumber(elPayload.getAttribute("yaw"), Float.class, (Float) null); Filter captureFilter = filterParser.property(elPayload, "capture-filter").optional(null); Filter playerFilter = filterParser.property(elPayload, "player-filter").optional(null); String name = elPayload.getAttributeValue("name", "Payload"); TeamFactory initialOwner = teamParser.property(elPayload, "initial-owner").optional(null); TeamFactory owner = teamParser.property(elPayload, "owner").required(); Duration timeToCapture = XMLUtils.parseDuration(elPayload.getAttribute("capture-time"), Duration.ofSeconds(30)); double timeMultiplier = XMLUtils.parseNumber(elPayload.getAttribute("time-multiplier"), Double.class, 0D); final double recoveryRate, decayRate; final Node attrIncremental = Node.fromAttr(elPayload, "incremental"); final Node attrRecovery = Node.fromAttr(elPayload, "recovery"); final Node attrDecay = Node.fromAttr(elPayload, "decay"); double emptyDecayRate = XMLUtils.parseNumber(elPayload.getAttribute("empty-decay"), Double.class, 0D); if(attrIncremental == null) { recoveryRate = XMLUtils.parseNumber(attrRecovery, Double.class, Range.atLeast(0D), 1D); decayRate = XMLUtils.parseNumber(attrDecay, Double.class, Range.atLeast(0D), 0D); } else { if(attrRecovery != null || attrDecay != null) { throw new InvalidXMLException("Cannot combine this attribute with 'incremental'", attrRecovery != null ? attrRecovery : attrDecay); } final boolean incremental = XMLUtils.parseBoolean(attrIncremental, true); recoveryRate = incremental ? 1D : Double.POSITIVE_INFINITY; decayRate = incremental ? 0D : Double.POSITIVE_INFINITY; } boolean neutralState = XMLUtils.parseBoolean(elPayload.getAttribute("neutral-state"), false); boolean friendlyCheckpoints = XMLUtils.parseBoolean(elPayload.getAttribute("friendly-checkpoints"), false); float radius = XMLUtils.parseNumber(elPayload.getAttribute("radius"), Float.class, 5f); float height = XMLUtils.parseNumber(elPayload.getAttribute("height"), Float.class, 3f); MaterialPattern checkpointMaterial = XMLUtils.parseMaterialPattern(Node.fromAttr(elPayload, "checkpoint-material")); float friendlySpeed = XMLUtils.parseNumber(elPayload.getAttribute("friendly-speed"), Float.class, 0f); float enemySpeed = XMLUtils.parseNumber(elPayload.getAttribute("enemy-speed"), Float.class, 1f); float points = XMLUtils.parseNumber(elPayload.getAttribute("points"), Float.class, 1f); float friendlyPoints = XMLUtils.parseNumber(elPayload.getAttribute("friendly-points"), Float.class, 0f); boolean showProgress = XMLUtils.parseBoolean(elPayload.getAttribute("show-progress"), true); boolean visible = XMLUtils.parseBoolean(elPayload.getAttribute("show"), true); Boolean required = XMLUtils.parseBoolean(elPayload.getAttribute("required"), null); PayloadDefinition.CaptureCondition captureCondition = XMLUtils.parseEnum(Node.fromAttr(elPayload, "capture-rule"), PayloadDefinition.CaptureCondition.class, "capture rule", PayloadDefinition.CaptureCondition.EXCLUSIVE); return new PayloadDefinitionImpl( name, required, visible, location, spawnLocation, yaw, captureFilter, playerFilter, timeToCapture, timeMultiplier, recoveryRate, decayRate, emptyDecayRate, initialOwner, owner, captureCondition, neutralState, friendlyCheckpoints, radius, height, checkpointMaterial, friendlySpeed, enemySpeed, points, friendlyPoints, showProgress ); } }
import java.util.*; public class SkipList<E> extends AbstractSortedSet<E> { private SkipListNode head; private int maxLevel; private int size; public SkipList() { size = 0; maxLevel = 0; // a SkipListNode with value null marks the beginning head = new SkipListNode(null); // null marks the end head.nextNodes.add(null); } // Adds e to the skiplist. // Returns false if already in skiplist, true otherwise. public boolean add(E e) { if(contains(e)) return false; size++; // random number from 0 to maxLevel+1 (inclusive) int level = (new Random()).nextInt(maxLevel+2); while(level > maxLevel) { // should only happen once head.nextNodes.add(null); maxLevel++; } SkipListNode newNode = new SkipListNode(e); SkipListNode current = head; do { current = findNext(e,current,level); newNode.nextNodes.add(0,current.nextNodes.get(level)); current.nextNodes.set(level,newNode); } while (level return true; } // Returns the skiplist node with greatest value <= e private SkipListNode find(E e) { return find(e,head,maxLevel); } // Returns the skiplist node with greatest value <= e // Starts at node start and level private SkipListNode find(E e, SkipListNode current, int level) { do { current = findNext(e,current,level); } while(level return current; } // Returns the node at a given level with highest value less than e private SkipListNode findNext(E e, SkipListNode current, int level) { SkipListNode next = current.nextNodes.get(level); while(next != null) { E value = next.getValue(); if(lessThan(e,value)) // e < value break; current = next; next = current.nextNodes.get(level); } return current; } public int size() { return size; } public boolean contains(Object o) { E e = (E)o; SkipListNode node = find(e); return node != null && node.getValue() != null && equalTo(node.getValue(),e); } private boolean lessThan(E a, E b) { return ((Comparable)a).compareTo(b) < 0; } private boolean equalTo(E a, E b) { return ((Comparable)a).compareTo(b) == 0; } private boolean greaterThan(E a, E b) { return ((Comparable)a).compareTo(b) > 0; } class SkipListNode { private E value; public List<SkipListNode> nextNodes; public E getValue() { return value; } public SkipListNode(E value) { this.value = value; nextNodes = new ArrayList<SkipListNode>(); } public int level() { return nextNodes.size()-1; } public String toString() { return "SLN: " + value; } } // Testing public static void main(String[] args) { SkipList testList = new SkipList<Integer>(); testList.add(1); testList.add(4); System.out.println(testList.find(2)); //System.out.println(testList.contains(2)); testList.add(2); //SkipList.SkipListNode sln = testList.find(2); //System.out.println(sln.nextNodes.get(0)); System.out.println(testList.find(2)); //System.out.println(testList.contains(2)); } }
package br.odb; import android.media.AudioFormat; import android.media.AudioManager; import android.media.AudioTrack; import android.util.Log; import java.util.ArrayList; public class SoundSink { private ArrayList<AudioTrack> soundPool = new ArrayList<>(); private ArrayList<byte[]> soundData = new ArrayList<>(); public int bufferData( byte[] data, int sampleRate, int channels, int bits ) { int key = soundPool.size(); int formatChannels; int formatBits; if ( channels == 1 ) { formatChannels = AudioFormat.CHANNEL_OUT_MONO; } else { formatChannels = AudioFormat.CHANNEL_OUT_STEREO; } if ( bits == 8 ) { formatBits = AudioFormat.ENCODING_PCM_8BIT; } else { formatBits = AudioFormat.ENCODING_PCM_16BIT; } int bufferSize = AudioTrack.getMinBufferSize(sampleRate, formatChannels, formatBits); AudioTrack player = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRate, formatChannels, formatBits, bufferSize, AudioTrack.MODE_STREAM); soundPool.add( player ); soundData.add( data ); return key; } public void play( int id, final float volumeLeft, final float volumeRight ) { final byte[] data = soundData.get( id ); final AudioTrack player = soundPool.get( id ); Thread thread = new Thread( new Runnable(){ @Override public void run() { player.setVolume( ( volumeLeft + volumeRight ) * 0.5f ); player.play(); player.write(data, 0, data.length);; player.stop(); } } ); thread.start(); } }
package polytheque.view; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JTextField; import javax.swing.SwingConstants; import polytheque.model.pojos.Adherent; /** * Classe permettant de gerer la modification des informations liees au compte de l'utilisateur. * * @author Godefroi Roussel * */ @SuppressWarnings("serial") public class AffichageMonCompte extends JPanel implements ActionListener { private JLabel userName; private JLabel userFirstName; private JLabel userBirthday; private JLabel userPseudo; private JTextField userRue; private JTextField userCP; private JTextField userVille; private JTextField userPhone; private JTextField userMail; private JPasswordField password; private JButton boutonValider; private JButton boutonRetourAccueil; private Adherent adherentCourant; /** * Une tache d'affichage de l'application. */ private TacheDAffichage tacheDAffichageDeLApplication; /** * Creation de la page. * * @param tacheDAffichageDeLApplication * Une tache d'affichage de l'application. * @return */ public AffichageMonCompte(TacheDAffichage afficheAppli, Adherent adherent){ this.tacheDAffichageDeLApplication = afficheAppli; this.adherentCourant = adherent; ajouterChamps(); ajouterBoutons(); } /** * Fonction permettant d'afficher tous les champs de la page ainsi que les zones de saisies pour l'utilisateur */ public void ajouterChamps() { this.setLayout(null); JLabel titrePrincipal = new JLabel("Mon compte"); titrePrincipal.setHorizontalAlignment(SwingConstants.CENTER); titrePrincipal.setBounds(350, 20, 260, 30); this.add(titrePrincipal); JLabel labelUserName = new JLabel("Nom :"); labelUserName.setBounds(300, 150, 100, 30); this.add(labelUserName); this.userName = new JLabel(this.adherentCourant.getNom()); this.userName.setBounds(350, 150, 100, 30); this.add(this.userName); JLabel labelUserFirstName = new JLabel("Prenom :"); labelUserFirstName.setBounds(300, 180, 100, 30); this.add(labelUserFirstName); this.userFirstName = new JLabel(this.adherentCourant.getPrenom()); this.userFirstName.setBounds(360, 180, 100, 30); this.add(this.userFirstName); JLabel labelUserBirthday = new JLabel("Date de naissance :"); labelUserBirthday.setBounds(300, 210, 150, 30); this.add(labelUserBirthday); this.userBirthday = new JLabel(this.adherentCourant.getDateNaissance().toString()); this.userBirthday.setBounds(420, 210, 100, 30); this.add(this.userBirthday); JLabel labelUserRue = new JLabel("Rue :"); labelUserRue.setBounds(300, 240, 100, 30); this.add(labelUserRue); this.userRue = new JTextField(this.adherentCourant.getRue()); this.userRue.setBounds(350, 240, 100, 30); this.add(this.userRue); JLabel labelUserCP = new JLabel("Code Postal:"); labelUserCP.setBounds(300, 270, 100, 30); this.add(labelUserCP); this.userCP = new JTextField(this.adherentCourant.getCP()); this.userCP.setBounds(390, 270, 100, 30); this.add(this.userCP); JLabel labelUserVille = new JLabel("Ville :"); labelUserVille.setBounds(300, 300, 100, 30); this.add(labelUserVille); this.userVille = new JTextField(this.adherentCourant.getVille()); this.userVille.setBounds(350, 300, 100, 30); this.add(this.userVille); JLabel labelUserMail = new JLabel("Mail :"); labelUserMail.setBounds(300, 330, 100, 30); this.add(labelUserMail); this.userMail = new JTextField(this.adherentCourant.getMail()); this.userMail.setBounds(350, 330, 100, 30); this.add(this.userMail); JLabel labelUserTelephone = new JLabel("Telephone :"); labelUserTelephone.setBounds(300, 360, 100, 30); this.add(labelUserTelephone); this.userPhone = new JTextField(this.adherentCourant.getTelephone()); this.userPhone.setBounds(370, 360, 100, 30); this.add(this.userPhone); JLabel labelUserPseudo = new JLabel("Pseudo :"); labelUserPseudo.setBounds(300, 390, 100, 30); this.add(labelUserPseudo); this.userPseudo = new JLabel(this.adherentCourant.getPseudo()); this.userPseudo.setBounds(360, 390, 100, 30); this.add(this.userPseudo); JLabel labelpassword = new JLabel("Mot de passe :"); labelpassword.setBounds(300, 420, 100, 30); this.add(labelpassword); this.password = new JPasswordField(this.adherentCourant.getMdp()); this.password.setBounds(380, 420, 190, 30); this.password.setColumns(10); this.add(this.password); } /** * Fonction permettant d'afficher le bouton pour valider les modifications faites par l'utilisateur */ public void ajouterBoutons(){ this.boutonValider = new JButton("Valider"); this.boutonValider.setBounds(200, 500, 200, 30); this.boutonValider.addActionListener(this); this.add(this.boutonValider); } @Override /** * param event * Va se souvenir sur quoi on a clique * La fonction va vrifier si le bouton selectionne correspond au bouton pour valider les modifications. Si oui, on effectue les modifications. */ public void actionPerformed(ActionEvent event) { JButton boutonSelectionne = (JButton) event.getSource(); if (boutonSelectionne == this.boutonValider) { String password = new String(this.password.getPassword()); Adherent adherent = new Adherent(this.adherentCourant.getIdAdherent(), this.userName.getText(), this.userFirstName.getText(),this.adherentCourant.getDateNaissance(), this.userRue.getText(), this.userCP.getText(), this.userVille.getText(), this.userMail.getText(), this.userPhone.getText(), this.userPseudo.getText(), password, this.adherentCourant.isAdmin(), this.adherentCourant.estAJour(),this.adherentCourant.peutEmprunter(), this.adherentCourant.getCompteurRetard()); this.tacheDAffichageDeLApplication.afficherMessage("Vos modifications ont bien ete prises en compte !", "Modification terminée", JOptionPane.INFORMATION_MESSAGE); this.tacheDAffichageDeLApplication.modifAdherent(adherent); return; } return; } }
package com.gallatinsystems.survey.dao; import com.gallatinsystems.survey.domain.Translation; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import javax.jdo.PersistenceManager; import com.gallatinsystems.framework.dao.BaseDAO; import com.gallatinsystems.framework.exceptions.IllegalDeletionException; import com.gallatinsystems.framework.servlet.PersistenceFilter; import com.gallatinsystems.survey.domain.QuestionGroup; /** * Dao for question groups */ public class QuestionGroupDao extends BaseDAO<QuestionGroup> { private final TranslationDao translationDao; public QuestionGroupDao() { super(QuestionGroup.class); this.translationDao = new TranslationDao(); } /** * saves a question group and associates it with the survey specified * * @param item * @param surveyId * @return */ public QuestionGroup save(QuestionGroup item, Long surveyId) { if (item.getSurveyId() == null || item.getSurveyId() == 0) { item.setSurveyId(surveyId); } item = save(item); return item; } public void deleteGroupsForSurvey(Long surveyId) throws IllegalDeletionException { for (QuestionGroup group : listQuestionGroupBySurvey(surveyId)) { delete(group); } } public List<QuestionGroup> listQuestionGroupsByName(String code) { return listByProperty("name", code, "String"); } /** * lists all question groups within a survey. * All groups will have a unique order field, even if datastore is messed up. * * @param surveyId * @return */ public TreeMap<Integer, QuestionGroup> listQuestionGroupsBySurvey(Long surveyId) { List<QuestionGroup> groups = listByProperty("surveyId", surveyId, "Long"); TreeMap<Integer, QuestionGroup> map = new TreeMap<Integer, QuestionGroup>(); if (groups != null) { int i = 1; for (QuestionGroup group : groups) { List<Translation> translations = translationDao.findTranslations( group.getKey().getId(), Translation.ParentType.QUESTION_GROUP_NAME); HashMap<String, Translation> translationMap = new HashMap<>(); if (translations != null) { for (Translation t: translations) { translationMap.put(t.getLanguageCode(), t); } } group.setTranslationMap(translationMap); // TODO: Hack because we seem to have questiongroups with same // order key so put an arbitrary value there for now since it // isn't used. if (map.containsKey(group.getOrder())) { map.put(i, group); group.setOrder(i); } else { map.put(group.getOrder() != null ? group.getOrder() : i, group); } i++; } } return map; } /** * lists all question groups by survey, ordered by the order field * * @param surveyId * @return */ public List<QuestionGroup> listQuestionGroupBySurvey(Long surveyId) { return super.listByProperty("surveyId", surveyId, "Long", "order", "asc"); } /** * gets a group by its code and survey id * * @param code * @param surveyId * @return */ @SuppressWarnings("unchecked") public QuestionGroup getByParentIdandCode(String code, Long surveyId) { PersistenceManager pm = PersistenceFilter.getManager(); javax.jdo.Query query = pm.newQuery(QuestionGroup.class); query.setFilter(" code==codeParam && surveyId == surveyIdParam"); query.declareParameters("String codeParam, Long surveyIdParam"); List<QuestionGroup> results = (List<QuestionGroup>) query.execute(code, surveyId); if (results != null && results.size() > 0) { return results.get(0); } else { return null; } } /** * finds a group by code and path. Path is "surveyGroupName/surveyName" * * @param code * @param path * @return */ @SuppressWarnings("unchecked") public QuestionGroup getByPath(String code, String path) { PersistenceManager pm = PersistenceFilter.getManager(); javax.jdo.Query query = pm.newQuery(QuestionGroup.class); query.setFilter(" path == pathParam && code == codeParam"); query.declareParameters("String pathParam, String codeParam"); List<QuestionGroup> results = (List<QuestionGroup>) query.execute(path, code); if (results != null && results.size() > 0) { return results.get(0); } else { return null; } } public void delete(QuestionGroup group) throws IllegalDeletionException { QuestionDao qDao = new QuestionDao(); qDao.deleteQuestionsForGroup(group.getKey().getId()); super.delete(group); } }
package com.intellij.codeInsight.folding.impl; import com.intellij.lang.Language; import com.intellij.lang.folding.FoldingBuilder; import com.intellij.lang.folding.FoldingDescriptor; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.fileTypes.StdFileTypes; import com.intellij.psi.*; import com.intellij.psi.impl.source.SourceTreeToPsiMap; import com.intellij.psi.javadoc.PsiDocComment; import com.intellij.psi.util.PropertyUtil; import com.intellij.psi.xml.*; import com.intellij.uiDesigner.compiler.CodeGenerator; import com.intellij.xml.util.HtmlUtil; import java.util.*; class FoldingPolicy { private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.folding.impl.FoldingPolicy"); /** * Returns map from element to range to fold, elements are sorted in reverse start offset order */ public static TreeMap<PsiElement,TextRange> getElementsToFold(PsiElement file, Document document) { TreeMap<PsiElement, TextRange> map = new TreeMap<PsiElement, TextRange>(new Comparator<PsiElement>() { public int compare(PsiElement element, PsiElement element1) { int startOffsetDiff = element1.getTextRange().getStartOffset() - element.getTextRange().getStartOffset(); return startOffsetDiff != 0 ? startOffsetDiff : element1.getTextRange().getEndOffset() - element.getTextRange().getEndOffset(); } }); final Language lang = file.getLanguage(); if (lang != null) { final FoldingBuilder foldingBuilder = lang.getFoldingBuilder(); if (foldingBuilder != null) { final FoldingDescriptor[] foldingDescriptors = foldingBuilder.buildFoldRegions(file.getNode(), document); for (int i = 0; i < foldingDescriptors.length; i++) { FoldingDescriptor descriptor = foldingDescriptors[i]; map.put(SourceTreeToPsiMap.treeElementToPsi(descriptor.getElement()), descriptor.getRange()); } return map; } } if (file instanceof PsiJavaFile) { PsiImportList importList = ((PsiJavaFile) file).getImportList(); if (importList != null) { PsiImportStatementBase[] statements = importList.getAllImportStatements(); if (statements.length > 1) { final TextRange rangeToFold = getRangeToFold(importList); if (rangeToFold != null) { map.put(importList, rangeToFold); } } } PsiClass[] classes = ((PsiJavaFile) file).getClasses(); for (int i = 0; i < classes.length; i++) { ProgressManager.getInstance().checkCanceled(); addElementsToFold(map, classes[i], document, true); } TextRange range = getFileHeader((PsiJavaFile) file); if (range != null && document.getLineNumber(range.getEndOffset()) > document.getLineNumber(range.getStartOffset())) { map.put(file, range); } } return map; } private static void findClasses(PsiElement scope, Map<PsiElement,TextRange> foldElements, Document document) { final List<PsiClass> list = new ArrayList<PsiClass>(); PsiElementVisitor visitor = new PsiRecursiveElementVisitor() { public void visitClass(PsiClass aClass) { list.add(aClass); } }; scope.accept(visitor); for (Iterator<PsiClass> iterator = list.iterator(); iterator.hasNext();) { PsiClass aClass = iterator.next(); if (aClass.isValid()) { addToFold(foldElements, aClass, document, true); addElementsToFold(foldElements, aClass, document, false); } } } private static void addElementsToFold(Map<PsiElement,TextRange> map, PsiClass aClass, Document document, boolean foldJavaDocs) { if (!(aClass.getParent() instanceof PsiJavaFile) || ((PsiJavaFile) aClass.getParent()).getClasses().length > 1) { addToFold(map, aClass, document, true); } PsiDocComment docComment; if (foldJavaDocs) { docComment = aClass.getDocComment(); if (docComment != null) { addToFold(map, docComment, document, true); } } PsiElement[] children = aClass.getChildren(); for (int j = 0; j < children.length; j++) { ProgressManager.getInstance().checkCanceled(); PsiElement child = children[j]; if (child instanceof PsiMethod) { PsiMethod method = (PsiMethod) child; addToFold(map, method, document, true); if (!CodeGenerator.SETUP_METHOD_NAME.equals(method.getName())) { if (foldJavaDocs) { docComment = method.getDocComment(); if (docComment != null) { addToFold(map, docComment, document, true); } } PsiCodeBlock body = method.getBody(); if (body != null) { findClasses(body, map, document); } } } else if (child instanceof PsiField) { PsiField field = (PsiField) child; if (foldJavaDocs) { docComment = field.getDocComment(); if (docComment != null) { addToFold(map, docComment, document, true); } } PsiExpression initializer = field.getInitializer(); if (initializer != null) { findClasses(initializer, map, document); } } else if (child instanceof PsiClassInitializer) { PsiClassInitializer initializer = (PsiClassInitializer) child; addToFold(map, initializer, document, true); findClasses(initializer, map, document); } else if (child instanceof PsiClass) { addElementsToFold(map, (PsiClass) child, document, true); } } } public static TextRange getRangeToFold(PsiElement element) { if (element instanceof PsiMethod) { if (CodeGenerator.SETUP_METHOD_NAME.equals(((PsiMethod) element).getName())) { return element.getTextRange(); } else { PsiCodeBlock body = ((PsiMethod) element).getBody(); if (body == null) return null; return body.getTextRange(); } } else if (element instanceof PsiClassInitializer) { if (isGeneratedUIInitializer((PsiClassInitializer) element)) { return element.getTextRange(); } else { PsiCodeBlock body = ((PsiClassInitializer) element).getBody(); if (body == null) return null; return body.getTextRange(); } } else if (element instanceof PsiClass) { PsiClass aClass = (PsiClass) element; PsiJavaToken lBrace = aClass.getLBrace(); if (lBrace == null) return null; PsiJavaToken rBrace = aClass.getRBrace(); if (rBrace == null) return null; return new TextRange(lBrace.getTextOffset(), rBrace.getTextOffset() + 1); } else if (element instanceof PsiJavaFile) { return getFileHeader((PsiJavaFile) element); } else if (element instanceof PsiImportList) { PsiImportList list = (PsiImportList) element; PsiImportStatementBase[] statements = list.getAllImportStatements(); if (statements.length == 0) return null; final PsiElement importKeyword = statements[0].getFirstChild(); if (importKeyword == null) return null; int startOffset = importKeyword.getTextRange().getEndOffset() + 1; int endOffset = statements[statements.length - 1].getTextRange().getEndOffset(); return new TextRange(startOffset, endOffset); } else if (element instanceof PsiDocComment) { return element.getTextRange(); } else { return null; } } private static TextRange getFileHeader(PsiJavaFile file) { PsiElement first = file.getFirstChild(); if (first instanceof PsiWhiteSpace) first = first.getNextSibling(); PsiElement element = first; while (element != null && element instanceof PsiComment) { element = element.getNextSibling(); if (element instanceof PsiWhiteSpace) { element = element.getNextSibling(); } else { break; } } if (element == null) return null; if (element.getPrevSibling() instanceof PsiWhiteSpace) element = element.getPrevSibling(); if (element.equals(first)) return null; return new TextRange(first.getTextOffset(), element.getTextOffset()); } public static String getFoldingText(PsiElement element) { final Language lang = element.getLanguage(); if (lang != null) { final FoldingBuilder foldingBuilder = lang.getFoldingBuilder(); if (foldingBuilder != null) { return foldingBuilder.getPlaceholderText(element.getNode()); } } if (element instanceof PsiImportList) { return "..."; } else if ( element instanceof PsiMethod && CodeGenerator.SETUP_METHOD_NAME.equals(((PsiMethod) element).getName()) || (element instanceof PsiClassInitializer && isGeneratedUIInitializer((PsiClassInitializer) element))) { return "Automatically generated code"; } else if (element instanceof PsiMethod || element instanceof PsiClassInitializer || element instanceof PsiClass) { return "{...}"; } else if (element instanceof PsiDocComment) { return ""; } else if (element instanceof PsiFile) { return "/.../"; } else { LOG.error("Unknown element:" + element); return null; } } public static boolean isCollapseByDefault(PsiElement element) { final Language lang = element.getLanguage(); if (lang != null) { final FoldingBuilder foldingBuilder = lang.getFoldingBuilder(); if (foldingBuilder != null) { return foldingBuilder.isCollapsedByDefault(element.getNode()); } } CodeFoldingSettings settings = CodeFoldingSettings.getInstance(); if (element instanceof PsiImportList) { return settings.COLLAPSE_IMPORTS; } else if (element instanceof PsiMethod || element instanceof PsiClassInitializer) { if (element instanceof PsiMethod && isSimplePropertyAccessor((PsiMethod) element)) { return settings.COLLAPSE_ACCESSORS; } if (element instanceof PsiMethod && CodeGenerator.SETUP_METHOD_NAME.equals(((PsiMethod) element).getName()) || element instanceof PsiClassInitializer && isGeneratedUIInitializer((PsiClassInitializer)element)) { return true; } return settings.COLLAPSE_METHODS; } else if (element instanceof PsiAnonymousClass) { return settings.COLLAPSE_ANONYMOUS_CLASSES; } else if (element instanceof PsiClass) { return element.getParent() instanceof PsiFile ? false : settings.COLLAPSE_INNER_CLASSES; } else if (element instanceof PsiDocComment) { return settings.COLLAPSE_JAVADOCS; } else if (element instanceof PsiJavaFile) { return settings.COLLAPSE_FILE_HEADER; } else { LOG.error("Unknown element:" + element); return false; } } private static boolean isGeneratedUIInitializer(PsiClassInitializer initializer) { PsiCodeBlock body = initializer.getBody(); if (body.getStatements().length != 1) return false; PsiStatement statement = body.getStatements()[0]; if (!(statement instanceof PsiExpressionStatement) || !(((PsiExpressionStatement) statement).getExpression() instanceof PsiMethodCallExpression)) return false; PsiMethodCallExpression call = (PsiMethodCallExpression) ((PsiExpressionStatement) statement).getExpression(); return CodeGenerator.SETUP_METHOD_NAME.equals(call.getMethodExpression().getReferenceName()); } private static boolean isSimplePropertyAccessor(PsiMethod method) { PsiCodeBlock body = method.getBody(); if (body == null) return false; PsiStatement[] statements = body.getStatements(); if (statements == null || statements.length != 1) return false; PsiStatement statement = statements[0]; if (PropertyUtil.isSimplePropertyGetter(method)) { if (statement instanceof PsiReturnStatement) { PsiExpression returnValue = ((PsiReturnStatement) statement).getReturnValue(); if (returnValue instanceof PsiReferenceExpression) { return ((PsiReferenceExpression) returnValue).resolve() instanceof PsiField; } } } else if (PropertyUtil.isSimplePropertySetter(method)) { if (statement instanceof PsiExpressionStatement) { PsiExpression expr = ((PsiExpressionStatement) statement).getExpression(); if (expr instanceof PsiAssignmentExpression) { PsiExpression lhs = ((PsiAssignmentExpression) expr).getLExpression(), rhs = ((PsiAssignmentExpression) expr).getRExpression(); if (lhs instanceof PsiReferenceExpression && rhs instanceof PsiReferenceExpression) { return ((PsiReferenceExpression) lhs).resolve() instanceof PsiField && ((PsiReferenceExpression) rhs).resolve() instanceof PsiParameter; } } } } return false; } private static <T extends PsiNamedElement> int getChildIndex (T element, PsiElement parent, String name, Class<T> hisClass) { PsiElement[] children = parent.getChildren(); int index = 0; for (int i = 0; i < children.length; i++) { PsiElement child = children[i]; if (hisClass.isAssignableFrom(child.getClass())) { T namedChild = (T)child; if (name.equals(namedChild.getName())) { if (namedChild.equals(element)) { return index; } index++; } } } return index; } public static String getSignature(PsiElement element) { if (element instanceof PsiImportList) { PsiFile file = element.getContainingFile(); if (file instanceof PsiJavaFile && element.equals(((PsiJavaFile)file).getImportList())) { return "imports"; } else { return null; } } else if (element instanceof PsiMethod) { PsiMethod method = (PsiMethod) element; PsiElement parent = method.getParent(); StringBuffer buffer = new StringBuffer(); buffer.append("method String name = method.getName(); buffer.append(name); buffer.append(" buffer.append(getChildIndex(method, parent, name, PsiMethod.class)); if (parent instanceof PsiClass) { String parentSignature = getSignature(parent); if (parentSignature == null) return null; buffer.append(";"); buffer.append(parentSignature); } return buffer.toString(); } else if (element instanceof PsiClass) { PsiClass aClass = (PsiClass) element; PsiElement parent = aClass.getParent(); StringBuffer buffer = new StringBuffer(); buffer.append("class if (parent instanceof PsiClass || parent instanceof PsiFile) { String name = aClass.getName(); buffer.append(name); buffer.append(" buffer.append(getChildIndex(aClass, parent, name, PsiClass.class)); if (parent instanceof PsiClass) { String parentSignature = getSignature(parent); if (parentSignature == null) return null; buffer.append(";"); buffer.append(parentSignature); } } else { buffer.append(aClass.getTextRange().getStartOffset()); buffer.append(":"); buffer.append(aClass.getTextRange().getEndOffset()); } return buffer.toString(); } else if (element instanceof PsiClassInitializer) { PsiClassInitializer initializer = (PsiClassInitializer) element; PsiElement parent = initializer.getParent(); StringBuffer buffer = new StringBuffer(); buffer.append("initializer int index = 0; PsiElement[] children = parent.getChildren(); for (int i = 0; i < children.length; i++) { PsiElement child = children[i]; if (child instanceof PsiClassInitializer) { if (child.equals(initializer)) break; index++; } } buffer.append(" buffer.append(index); if (parent instanceof PsiClass) { String parentSignature = getSignature(parent); if (parentSignature == null) return null; buffer.append(";"); buffer.append(parentSignature); } return buffer.toString(); } else if (element instanceof PsiField) { // needed for doc-comments only PsiField field = (PsiField) element; PsiElement parent = field.getParent(); StringBuffer buffer = new StringBuffer(); buffer.append("field String name = field.getName(); buffer.append(name); buffer.append(" buffer.append(getChildIndex(field, parent, name, PsiField.class)); if (parent instanceof PsiClass) { String parentSignature = getSignature(parent); if (parentSignature == null) return null; buffer.append(";"); buffer.append(parentSignature); } return buffer.toString(); } else if (element instanceof PsiDocComment) { StringBuffer buffer = new StringBuffer(); buffer.append("docComment;"); PsiElement parent = element.getParent(); if (!(parent instanceof PsiClass) && !(parent instanceof PsiMethod) && !(parent instanceof PsiField)) { return null; } String parentSignature = getSignature(parent); if (parentSignature == null) return null; buffer.append(parentSignature); return buffer.toString(); } else if (element instanceof XmlTag) { XmlTag tag = (XmlTag) element; PsiElement parent = tag.getParent(); StringBuffer buffer = new StringBuffer(); buffer.append("tag String name = tag.getName(); buffer.append(name); buffer.append(" buffer.append(getChildIndex(tag, parent, name, XmlTag.class)); if (parent instanceof XmlTag) { String parentSignature = getSignature(parent); buffer.append(";"); buffer.append(parentSignature); } return buffer.toString(); } else if (element instanceof PsiJavaFile) { return null; } return null; } private static <T extends PsiNamedElement> T restoreElementInternal (PsiElement parent, String name, int index, Class<T> hisClass) { PsiElement[] children = parent.getChildren(); for (int i = 0; i < children.length; i++) { PsiElement child = children[i]; if (hisClass.isAssignableFrom(child.getClass())) { T namedChild = (T)child; if (name.equals(namedChild.getName())) { if (index == 0) { return namedChild; } index } } } return null; } public static PsiElement restoreBySignature(PsiFile file, String signature) { int semicolonIndex = signature.indexOf(";"); PsiElement parent; if (semicolonIndex >= 0) { String parentSignature = signature.substring(semicolonIndex + 1); parent = restoreBySignature(file, parentSignature); if (parent == null) return null; signature = signature.substring(0, semicolonIndex); } else { parent = file; } StringTokenizer tokenizer = new StringTokenizer(signature, " String type = tokenizer.nextToken(); if (type.equals("imports")) { if (!(file instanceof PsiJavaFile)) return null; return ((PsiJavaFile) file).getImportList(); } else if (type.equals("method")) { String name = tokenizer.nextToken(); try { int index = Integer.parseInt(tokenizer.nextToken()); return restoreElementInternal(parent, name, index, PsiMethod.class); } catch (NumberFormatException e) { LOG.error(e); return null; } } else if (type.equals("class")) { String name = tokenizer.nextToken(); PsiNameHelper nameHelper = file.getManager().getNameHelper(); if (nameHelper.isIdentifier(name)) { int index = 0; try { index = Integer.parseInt(tokenizer.nextToken()); } catch (NoSuchElementException e) { //To read previous XML versions correctly } return restoreElementInternal(parent, name, index, PsiClass.class); } else { StringTokenizer tok1 = new StringTokenizer(name, ":"); int start = Integer.parseInt(tok1.nextToken()); int end = Integer.parseInt(tok1.nextToken()); PsiElement element = file.findElementAt(start); if (element != null) { TextRange range = element.getTextRange(); while (range != null && range.getEndOffset() < end) { element = element.getParent(); range = element.getTextRange(); } if (range != null && range.getEndOffset() == end && element instanceof PsiClass) { return element; } } } return null; } else if (type.equals("initializer")) { try { int index = Integer.parseInt(tokenizer.nextToken()); PsiElement[] children = parent.getChildren(); for (int i = 0; i < children.length; i++) { PsiElement child = children[i]; if (child instanceof PsiClassInitializer) { if (index == 0) { return child; } index } } return null; } catch (NumberFormatException e) { LOG.error(e); return null; } } else if (type.equals("field")) { String name = tokenizer.nextToken(); try { int index = 0; try { index = Integer.parseInt(tokenizer.nextToken()); } catch (NoSuchElementException e) { //To read previous XML versions correctly } return restoreElementInternal(parent, name, index, PsiField.class); } catch (NumberFormatException e) { LOG.error(e); return null; } } else if (type.equals("docComment")) { if (parent instanceof PsiClass) { return ((PsiClass) parent).getDocComment(); } else if (parent instanceof PsiMethod) { return ((PsiMethod) parent).getDocComment(); } else if (parent instanceof PsiField) { return ((PsiField) parent).getDocComment(); } else { return null; } } else if (type.equals("tag")) { String name = tokenizer.nextToken(); if (parent instanceof XmlFile) { parent = ((XmlFile) parent).getDocument(); if(file.getFileType() == StdFileTypes.JSP) { //TODO: FoldingBuilder API, psi roots, etc? parent = HtmlUtil.getRealXmlDocument((XmlDocument)parent); } } try { int index = Integer.parseInt(tokenizer.nextToken()); return restoreElementInternal(parent, name, index, XmlTag.class); } catch (NumberFormatException e) { LOG.error(e); return null; } } else { return null; } } private static boolean addToFold(Map<PsiElement,TextRange> map, PsiElement elementToFold, Document document, boolean allowOneLiners) { LOG.assertTrue(elementToFold.isValid()); TextRange range = getRangeToFold(elementToFold); if (range == null) return false; LOG.assertTrue(range.getStartOffset() >= 0 && range.getEndOffset() <= elementToFold.getContainingFile().getTextRange().getEndOffset()); if (!allowOneLiners) { int startLine = document.getLineNumber(range.getStartOffset()); int endLine = document.getLineNumber(range.getEndOffset() - 1); if (startLine < endLine) { map.put(elementToFold, range); return true; } else { return false; } } else { if (range.getEndOffset() - range.getStartOffset() > getFoldingText(elementToFold).length()) { map.put(elementToFold, range); return true; } else { return false; } } } }
package autoChirp; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.BeforeClass; import org.junit.Test; public class TwitterTest { private static String dbPath = "src/test/resources/"; private static String dbFileName = "autoChirp.db"; private static String dbCreationFileName = "src/test/resources/createDatabaseFile.sql"; @BeforeClass public static void dbConnection(){ try { DBConnector.connect(dbPath + dbFileName); DBConnector.createOutputTables(dbCreationFileName); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } @Test public void twitterTest(){ //TODO : read Keys from Congfig-Datei (gitigore) int user_id = DBConnector.insertNewUser("", "", ""); Map<String, List<String>> tweetsByDate = new HashMap<String, List<String>>(); List<String> tweets = Arrays.asList("tweet1", "tweet2", "tweet3"); tweetsByDate.put("2017-01-15 12:00:00", tweets); tweets = Arrays.asList("next_tweet1", "next_tweet2"); tweetsByDate.put("2017-01-16 12:00:00", tweets); List<Integer> user_ids = new ArrayList<Integer>(); user_ids.add(user_id); DBConnector.insertTweets("test_url", tweetsByDate, user_ids, "test_title"); //getAllGropIDs to update their status try{ Statement stmt = DBConnector.connection.createStatement(); String sql = "SELECT group_id FROM groups"; ResultSet group_ids = stmt.executeQuery(sql); while(group_ids.next()){ DBConnector.updateGroupStatus(group_ids.getInt(1), true); } } catch(SQLException e){ e.printStackTrace(); } Map<Integer,Map<String,List<String>>> allNewTweets = DBConnector.getAllNewTweets(); for (Integer user : user_ids) { //TODO: Create TwitterConnection } System.out.println(allNewTweets); } }
package awesomefb.facebook; import awesomefb.facebook.Facebook; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; public class Page extends Entity { private String mName; private Facebook mFacebook; public Page(JSONObject page) { super(page); mFacebook = Facebook.getInstance(); mName = page.getString("name"); } public String getName() { return mName; } public List<Page> getLikes() { JSONObject obj = mFacebook.request(getFacebookId() + "/likes", null); if (!obj.has("data")) { return null; } List<Page> pages = new ArrayList<Page>(); JSONArray arr = obj.getJSONArray("data"); for (int i = 0, l = arr.length(); i != l; i++) { Page page = new Page(arr.getJSONObject(i)); pages.add(page); } return pages; } public JSONArray getPosts() { final int POSTS_LIMIT = 50; final int COMMENTS_LIMIT = 50; String params = "fields=id,from,message,created_time,comments.limit(" + COMMENTS_LIMIT + ")&limit=" + POSTS_LIMIT; JSONObject obj = mFacebook.request(getFacebookId() + "/feed", params); if (!obj.has("data")) { return null; } JSONArray postsJson = obj.getJSONArray("data"); while (true) { if (!obj.has("paging")) { break; } obj = mFacebook.request(obj.getJSONObject("paging").getString("next")); if (!obj.has("data")) { break; } JSONArray nextResults = obj.getJSONArray("data"); for (int i = 0, l = nextResults.length(); i < l; i++) { postsJson.put(nextResults.get(i)); } } return postsJson; } }
package io.spine.type; import com.google.common.collect.ImmutableSet; import com.google.protobuf.Message; import io.spine.value.ClassTypeValue; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Queue; import static com.google.common.base.Preconditions.checkNotNull; /** * A base class for value objects storing references to message classes. */ public abstract class MessageClass<M extends Message> extends ClassTypeValue<M> { private static final long serialVersionUID = 0L; /** The URL of the type of proto messages represented by this class. */ private final TypeUrl typeUrl; protected MessageClass(Class<? extends M> value) { super(value); this.typeUrl = TypeUrl.of(value); } protected MessageClass(Class<? extends M> value, TypeUrl typeUrl) { super(value); this.typeUrl = checkNotNull(typeUrl); } /** * Obtains the type URL of messages of this class. */ public TypeUrl typeUrl() { return typeUrl; } /** * Obtains a type name of the messages of this class. */ public TypeName typeName() { return typeUrl.toTypeName(); } /** * Gathers all interfaces (extending {@link Message}) of the passed class, * and up in the hierarchy. * * <p>The {@link Message} interface is not included in the result. */ public static ImmutableSet<Class<? extends Message>> interfacesOf(Class<? extends Message> cls) { checkNotNull(cls); ImmutableSet.Builder<Class<? extends Message>> builder = ImmutableSet.builder(); Class<?>[] interfaces = cls.getInterfaces(); Queue<Class<?>> deque = new ArrayDeque<>(Arrays.asList(interfaces)); while (!deque.isEmpty()) { Class<?> anInterface = deque.poll(); if (Message.class.isAssignableFrom(anInterface) && !anInterface.equals(Message.class)) { @SuppressWarnings("unchecked") Class<? extends Message> cast = (Class<? extends Message>) anInterface; builder.add(cast); } interfaces = anInterface.getInterfaces(); if (interfaces.length > 0) { deque.addAll(Arrays.asList(interfaces)); } } return builder.build(); } }
package nz.mega.sdk; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.net.URLConnection; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Rect; import android.media.ExifInterface; import android.media.MediaMetadataRetriever; import android.media.ThumbnailUtils; import android.net.Uri; import android.provider.BaseColumns; import android.provider.MediaStore; import mega.privacy.android.app.utils.Util; public class AndroidGfxProcessor extends MegaGfxProcessor { Rect size; int orientation; String srcPath; Bitmap bitmap; static boolean isVideo; byte[] bitmapData; static Context context = null; protected AndroidGfxProcessor() { if (context == null) { try { context = (Context) Class.forName("android.app.AppGlobals") .getMethod("getInitialApplication") .invoke(null, (Object[]) null); } catch (Exception e) { } } } public static boolean isVideoFile(String path) { try { String mimeType = URLConnection.guessContentTypeFromName(path); return mimeType != null && mimeType.startsWith("video"); } catch(Exception e){ return false; } } public static Rect getImageDimensions(String path, int orientation) { Rect rect = new Rect(); if(isVideoFile(path)){ try { MediaMetadataRetriever retriever = new MediaMetadataRetriever(); retriever.setDataSource(path); int width; int height; int interchangeOrientation = Integer.valueOf(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION)); if (interchangeOrientation == 90 || interchangeOrientation == 270) { width = Integer.valueOf(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT)); height = Integer.valueOf(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH)); } else { width = Integer.valueOf(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH)); height = Integer.valueOf(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT)); } retriever.release(); log("getImageDimensions width: "+width+" height: "+height+" orientation: "+interchangeOrientation); rect.right = width; rect.bottom = height; } catch (Exception e) { } } else{ try { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(new FileInputStream(path), null, options); if ((options.outWidth > 0) && (options.outHeight > 0)) { if ((orientation < 5) || (orientation > 8)) { rect.right = options.outWidth; rect.bottom = options.outHeight; } else { rect.bottom = options.outWidth; rect.right = options.outHeight; } } } catch (Exception e) { } } return rect; } public boolean readBitmap(String path) { if(isVideoFile(path)){ isVideo = true; srcPath = path; size = getImageDimensions(srcPath, orientation); return (size.right != 0) && (size.bottom != 0); } else{ isVideo = false; srcPath = path; orientation = getExifOrientation(path); size = getImageDimensions(srcPath, orientation); return (size.right != 0) && (size.bottom != 0); } } public int getWidth() { return size.right; } public int getHeight() { return size.bottom; } static public Bitmap getBitmap(String path, Rect rect, int orientation, int w, int h) { int width; int height; if(AndroidGfxProcessor.isVideo){ Bitmap bmThumbnail = null; try{ bmThumbnail = ThumbnailUtils.createVideoThumbnail(path, MediaStore.Video.Thumbnails.FULL_SCREEN_KIND); if(context != null && bmThumbnail == null) { String SELECTION = MediaStore.MediaColumns.DATA + "=?"; String[] PROJECTION = {BaseColumns._ID}; Uri uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; String[] selectionArgs = {path}; ContentResolver cr = context.getContentResolver(); Cursor cursor = cr.query(uri, PROJECTION, SELECTION, selectionArgs, null); if (cursor.moveToFirst()) { long videoId = cursor.getLong(0); bmThumbnail = MediaStore.Video.Thumbnails.getThumbnail(cr, videoId, MediaStore.Video.Thumbnails.FULL_SCREEN_KIND, null); } cursor.close(); } } catch(Exception e){} if(bmThumbnail==null){ MediaMetadataRetriever retriever = new MediaMetadataRetriever(); try{ retriever.setDataSource(path); bmThumbnail = retriever.getFrameAtTime(); } catch(Exception e1){ } finally { try { retriever.release(); } catch (Exception ex) {} } } if(bmThumbnail==null){ try{ bmThumbnail = ThumbnailUtils.createVideoThumbnail(path, MediaStore.Video.Thumbnails.MINI_KIND); if(context != null && bmThumbnail == null) { String SELECTION = MediaStore.MediaColumns.DATA + "=?"; String[] PROJECTION = {BaseColumns._ID}; Uri uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; String[] selectionArgs = {path}; ContentResolver cr = context.getContentResolver(); Cursor cursor = cr.query(uri, PROJECTION, SELECTION, selectionArgs, null); if (cursor.moveToFirst()) { long videoId = cursor.getLong(0); bmThumbnail = MediaStore.Video.Thumbnails.getThumbnail(cr, videoId, MediaStore.Video.Thumbnails.MINI_KIND, null); } cursor.close(); } } catch (Exception e2){} } try { if (bmThumbnail != null) { return Bitmap.createScaledBitmap(bmThumbnail, w, h, true); } }catch (Exception e){ } } else{ if ((orientation < 5) || (orientation > 8)) { width = rect.right; height = rect.bottom; } else { width = rect.bottom; height = rect.right; } try { int scale = 1; while (width / scale / 2 >= w && height / scale / 2 >= h) scale *= 2; BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = false; options.inSampleSize = scale; Bitmap tmp = BitmapFactory.decodeStream(new FileInputStream(path), null, options); tmp = fixExifOrientation(tmp, orientation); return Bitmap.createScaledBitmap(tmp, w, h, true); } catch (Exception e) { } } return null; } public static int getExifOrientation(String srcPath) { int orientation = ExifInterface.ORIENTATION_UNDEFINED; int i = 0; while ((i < 5) && (orientation == ExifInterface.ORIENTATION_UNDEFINED)) { try { ExifInterface exif = new ExifInterface(srcPath); orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, orientation); } catch (IOException e) { try { Thread.sleep(100); } catch (InterruptedException e1) {} } i++; } return orientation; } /* * Change image orientation based on EXIF image data */ public static Bitmap fixExifOrientation(Bitmap bitmap, int orientation) { if (bitmap == null) return null; if ((orientation < 2) || (orientation > 8)) { // No changes required or invalid orientation return bitmap; } Matrix matrix = new Matrix(); switch (orientation) { case ExifInterface.ORIENTATION_TRANSPOSE: case ExifInterface.ORIENTATION_ROTATE_90: matrix.postRotate(90); break; case ExifInterface.ORIENTATION_ROTATE_180: case ExifInterface.ORIENTATION_FLIP_VERTICAL: matrix.postRotate(180); break; case ExifInterface.ORIENTATION_TRANSVERSE: case ExifInterface.ORIENTATION_ROTATE_270: matrix.postRotate(270); break; default: break; } if ((orientation == ExifInterface.ORIENTATION_FLIP_HORIZONTAL) || (orientation == ExifInterface.ORIENTATION_FLIP_VERTICAL)) matrix.preScale(-1, 1); else if ((orientation == ExifInterface.ORIENTATION_TRANSPOSE) || (orientation == ExifInterface.ORIENTATION_TRANSVERSE)) matrix.preScale(1, -1); return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); } public static Bitmap extractRect(Bitmap bitmap, int px, int py, int rw, int rh) { if (bitmap == null) return null; int w = bitmap.getWidth(); int h = bitmap.getHeight(); if ((px != 0) || (py != 0) || (rw != w) || (rh != h)) { Bitmap.Config conf = Bitmap.Config.ARGB_8888; Bitmap scaled = Bitmap.createBitmap(rw, rh, conf); Canvas canvas = new Canvas(scaled); canvas.drawBitmap(bitmap, new Rect(px, py, px + rw, py + rh), new Rect(0, 0, rw, rh), null); bitmap = scaled; } return bitmap; } public static boolean saveBitmap(Bitmap bitmap, File file) { if (bitmap == null) return false; FileOutputStream stream; try { stream = new FileOutputStream(file); if (!bitmap.compress(Bitmap.CompressFormat.JPEG, 85, stream)) return false; stream.close(); return true; } catch (Exception e) { } return false; } public int getBitmapDataSize(int w, int h, int px, int py, int rw, int rh) { if (bitmap == null) bitmap = getBitmap(srcPath, size, orientation, w, h); else bitmap = Bitmap.createScaledBitmap(bitmap, w, h, true); bitmap = extractRect(bitmap, px, py, rw, rh); if (bitmap == null) return 0; try { ByteArrayOutputStream stream = new ByteArrayOutputStream(); if (!bitmap.compress(Bitmap.CompressFormat.JPEG, 85, stream)) return 0; bitmapData = stream.toByteArray(); return bitmapData.length; } catch (Exception e) { } return 0; } public boolean getBitmapData(byte[] buffer) { try { System.arraycopy(bitmapData, 0, buffer, 0, bitmapData.length); return true; } catch (Exception e) { } return false; } public void freeBitmap() { bitmap = null; bitmapData = null; size = null; srcPath = null; orientation = 0; } public static void log(String log) { Util.log("AndroidGfxProcessor", log); } }
package utils; import java.math.BigDecimal; import javax.servlet.http.HttpServletRequest; import javax.swing.JOptionPane; import javax.ws.rs.WebApplicationException; import qora.account.Account; import qora.account.PrivateKeyAccount; import qora.crypto.Crypto; import qora.transaction.Transaction; import api.ApiErrorFactory; import controller.Controller; public class APIUtils { public static String processPayment(String amount, String fee, String sender, String recipient) { // PARSE AMOUNT BigDecimal bdAmount; try { bdAmount = new BigDecimal(amount); bdAmount = bdAmount.setScale(8); } catch (Exception e) { throw ApiErrorFactory.getInstance().createError( ApiErrorFactory.ERROR_INVALID_AMOUNT); } // PARSE FEE BigDecimal bdFee; try { bdFee = new BigDecimal(fee); bdFee = bdFee.setScale(8); } catch (Exception e) { throw ApiErrorFactory.getInstance().createError( ApiErrorFactory.ERROR_INVALID_FEE); } // CHECK ADDRESS if (!Crypto.getInstance().isValidAddress(sender)) { throw ApiErrorFactory.getInstance().createError( ApiErrorFactory.ERROR_INVALID_SENDER); } // CHECK IF WALLET EXISTS if (!Controller.getInstance().doesWalletExists()) { throw ApiErrorFactory.getInstance().createError( ApiErrorFactory.ERROR_WALLET_NO_EXISTS); } // CHECK WALLET UNLOCKED if (!Controller.getInstance().isWalletUnlocked()) { throw ApiErrorFactory.getInstance().createError( ApiErrorFactory.ERROR_WALLET_LOCKED); } // GET ACCOUNT PrivateKeyAccount account = Controller.getInstance() .getPrivateKeyAccountByAddress(sender); if (account == null) { throw ApiErrorFactory.getInstance().createError( ApiErrorFactory.ERROR_INVALID_SENDER); } // SEND PAYMENT Pair<Transaction, Integer> result = Controller.getInstance() .sendPayment(account, new Account(recipient), bdAmount, bdFee); switch (result.getB()) { case Transaction.VALIDATE_OKE: return result.getA().toJson().toJSONString(); case Transaction.INVALID_NAME_LENGTH: throw ApiErrorFactory.getInstance().createError( ApiErrorFactory.ERROR_INVALID_NAME_LENGTH); case Transaction.INVALID_VALUE_LENGTH: throw ApiErrorFactory.getInstance().createError( ApiErrorFactory.ERROR_INVALID_VALUE_LENGTH); case Transaction.INVALID_ADDRESS: throw ApiErrorFactory.getInstance().createError( ApiErrorFactory.ERROR_INVALID_RECIPIENT); case Transaction.NAME_ALREADY_REGISTRED: throw ApiErrorFactory.getInstance().createError( ApiErrorFactory.ERROR_NAME_ALREADY_EXISTS); case Transaction.NEGATIVE_FEE: throw ApiErrorFactory.getInstance().createError( ApiErrorFactory.ERROR_INVALID_FEE); case Transaction.FEE_LESS_REQUIRED: throw ApiErrorFactory.getInstance().createError( ApiErrorFactory.ERROR_FEE_LESS_REQUIRED); case Transaction.NO_BALANCE: throw ApiErrorFactory.getInstance().createError( ApiErrorFactory.ERROR_NO_BALANCE); default: throw ApiErrorFactory.getInstance().createError( ApiErrorFactory.ERROR_UNKNOWN); } } public static void askAPICallAllowed(final String messageToDisplay, HttpServletRequest request) throws WebApplicationException { // CHECK API CALL ALLOWED try { if (Controller.getInstance().checkAPICallAllowed(messageToDisplay, request) != JOptionPane.YES_OPTION) { throw ApiErrorFactory .getInstance() .createError( ApiErrorFactory.ERROR_WALLET_API_CALL_FORBIDDEN_BY_USER); } } catch (Exception e) { if (e instanceof WebApplicationException) { throw (WebApplicationException) e; } e.printStackTrace(); throw ApiErrorFactory.getInstance().createError( ApiErrorFactory.ERROR_UNKNOWN); } } }
package to.etc.domui.logic; import java.util.*; import javax.annotation.*; import to.etc.domui.component.meta.*; import to.etc.domui.util.*; import to.etc.domui.util.db.*; import to.etc.util.*; public class LogiModel { @Nonnull private Set<Object> m_modelRoots = new HashSet<Object>(); /** Maps original instance to copy of the instance, if present */ @Nonnull private Map<Object, Object> m_originalToCopyMap = new HashMap<Object, Object>(); /** This maps a copy instance to it's original source. */ @Nonnull private Map<Object, Object> m_copyToOriginalMap = new HashMap<Object, Object>(); /** This contains only the mappings for the root entries, as [source, copy]. Used to see what root entries have disappeared. */ @Nonnull private Map<Object, Object> m_rootCopyMap = new HashMap<Object, Object>(); @Nullable private IModelCopier m_copyHandler; public LogiModel() {} @Nonnull public IModelCopier getCopyHandler() { if(null != m_copyHandler) return m_copyHandler; m_copyHandler = QCopy.getInstance(); if(null != m_copyHandler) return m_copyHandler; throw new IllegalStateException("No copy handler is known"); } public <T> void addRoot(@Nonnull T root) { m_modelRoots.add(root); } /** * This walks all model roots, and updates the copy to fully and properly represent the model roots. */ public void updateCopy() throws Exception { //-- 1. Create new maps, but first copy the current originalToCopy map to find existing instances long ts = System.nanoTime(); Map<Object, Object> oldOrigMap = m_originalToCopyMap; // Keep the original map m_originalToCopyMap = new HashMap<Object, Object>(); // Create a clean one, m_copyToOriginalMap.clear(); // And clean out this one m_rootCopyMap.clear(); //-- Copy all roots. for(Object root : m_modelRoots) { Object copy = createCopy(root, oldOrigMap); m_rootCopyMap.put(root, copy); } ts = System.nanoTime() - ts; System.out.println("logi: copied " + m_originalToCopyMap.size() + " instances in " + StringTool.strNanoTime(ts)); } @Nullable private <T> T createCopy(@Nullable T source, @Nonnull Map<Object, Object> oldOrigMap) throws Exception { if(null == source) return null; //-- Already mapped in this run? T copy = (T) m_originalToCopyMap.get(source); if(null != copy) return copy; // Return copy instance. //-- We need to do work... Was there a copy in the "old" instance? Class<T> clz = (Class<T>) source.getClass(); // Java generics suck. copy = (T) oldOrigMap.get(source); if(null == copy) { //-- This is new here. We need an instance. copy = DomUtil.nullChecked(clz.newInstance()); // Create uninitialized instance. } //-- Instance is known- store it in the maps, now: this allows deeper references to find "back" the new thing, even though it is not yet properly initialized. m_originalToCopyMap.put(source, copy); // Map source -> copy if(null != copy) m_copyToOriginalMap.put(copy, source); // And versa vice ;) //-- Ok, time to handle all properties. ClassMetaModel cmm = MetaManager.findClassMeta(clz); List<PropertyMetaModel< ? >> pmml = cmm.getProperties(); for(PropertyMetaModel< ? > pmm : pmml) { copyPropertyValue(source, copy, pmm, oldOrigMap); } // TODO Auto-generated method stub return null; } private <T, P> void copyPropertyValue(@Nonnull T source, @Nonnull T copy, @Nonnull PropertyMetaModel<P> pmm, @Nonnull Map<Object, Object> oldOrigMap) throws Exception { if(pmm.getReadOnly() == YesNoType.YES) return; switch(pmm.getRelationType()){ case NONE: P value = pmm.getValue(source); // Get value in source pmm.setValue(copy, value); // And set in copy return; case UP: P refval = null; if(!getCopyHandler().isUnloadedParent(source, pmm)) { //-- This parent instance is loaded- get it's copy and set it P oldval = pmm.getValue(source); // Get the loaded source refval = createCopy(oldval, oldOrigMap); // Create/get the copy of it } pmm.setValue(copy, refval); return; case DOWN: refval = null; if(!getCopyHandler().isUnloadedChildList(source, pmm)) { //-- We need to pass through all this and get copies P oldval = pmm.getValue(source); // Get original collection if(oldval == null) refval = null; else refval = createChildCollection(source, oldval, pmm, oldOrigMap); } pmm.setValue(copy, refval); return; } } private <T, P> P createChildCollection(@Nonnull T source, @Nonnull P sourcevalue, @Nonnull PropertyMetaModel<P> pmm, @Nonnull Map<Object, Object> oldOrigMap) throws Exception { if(List.class.isAssignableFrom(sourcevalue.getClass())) { ArrayList<Object> al = new ArrayList<Object>(); for(Object v : (List<Object>) sourcevalue) { Object nv = createCopy(v, oldOrigMap); al.add(nv); } return (P) al; } else throw new IllegalStateException("Child collection type: " + sourcevalue.getClass() + " not implemented, in instance " + source + " property " + pmm); } /* CODING: Compare to make a delta event. */ /** * Compare the copy with the current state of the original, and create the change event set. */ @Nonnull public LogiEventSet compareCopy() throws Exception { LogiEventSet les = new LogiEventSet(); Set<Object> doneset = new HashSet<Object>(); Map<Object, Object> rootsdone = new HashMap<Object, Object>(m_rootCopyMap); // Copy the original roots and their copies. int rix = 0; for(Object root : m_modelRoots) { les.enterRoot(rix); Object copy = rootsdone.remove(root); // Was there a previous root? if(copy == null) { les.addRootInstanceAdded(root); } else { compareInstances(les, doneset, root, copy); } les.exitRoot(rix); } //-- All that is left in rootsDone means root instances have been removed. for(Map.Entry<Object, Object> me : rootsdone.entrySet()) { les.addRootInstanceRemoved(me.getKey(), me.getValue()); } return les; } /** * Compare two instances, and add their changes. Both instances must exist and be of the same type. * @param les * @param doneset * @param source * @param copy */ private <T> void compareInstances(@Nonnull LogiEventSet les, @Nonnull Set<Object> doneset, @Nonnull T source, @Nonnull T copy) throws Exception { //-- Make very sure we pass every instance only once. if(doneset.contains(source) || doneset.contains(copy)) return; doneset.add(source); doneset.add(copy); //-- Compare all direct properties 1st. Class<T> clz = (Class<T>) source.getClass(); // Java generics suck. ClassMetaModel cmm = MetaManager.findClassMeta(clz); List<PropertyMetaModel< ? >> pmml = cmm.getProperties(); List<PropertyMetaModel< ? >> laterl = null; for(PropertyMetaModel< ? > pmm : pmml) { switch(pmm.getRelationType()){ case NONE: //-- Compare these thingies, by value, not reference. compareValues(les, pmm, source, copy); break; case UP: if(!compareUpValues(les, pmm, source, copy)) { if(laterl == null) laterl = new ArrayList<PropertyMetaModel< ? >>(); laterl.add(pmm); } break; case DOWN: if(laterl == null) laterl = new ArrayList<PropertyMetaModel< ? >>(); laterl.add(pmm); break; } } if(null != laterl) { for(PropertyMetaModel< ? > pmm : laterl) { compareChildren(les, pmm, source, copy); } } } private <T, P> boolean compareChildren(@Nonnull LogiEventSet les, PropertyMetaModel<P> pmm, @Nonnull T source, @Nonnull T copy) throws Exception { if(getCopyHandler().isUnloadedChildList(source, pmm)) { //-- Source is (now) unloaded. Compare with copy: should be null. P copyval = pmm.getValue(copy); if(copyval == null) return false; //-- Child was set to empty list... throw new IllegalStateException("ni: child set to unloaded while copy is discrete??"); // return true; } //-- We have some collection here. Handle the supported cases (List only) P sourceval = pmm.getValue(source); P copyval = pmm.getValue(copy); if(sourceval == null) { if(copyval == null) return false; //-- A collection has been emptied. Send a property changed event for it les.propertyChange(pmm, source, copy, sourceval, copyval); //-- Send "clear" event for collection and delete events for all it's members. les.addCollectionClear(pmm, source, copy, sourceval, copyval); List< ? > clist = getChildValues(copyval); for(int i = clist.size(); --i >= 0;) { Object centry = clist.get(i); if(centry != null) { Object sentry = m_copyToOriginalMap.get(centry); if(sentry == null) throw new IllegalStateException("Cannot find original for copied entry: " + centry); les.addCollectionDelete(pmm, source, copy, i, sentry); } } return true; } if(copyval == null) { //-- We have a new list that was not present @ time of the copy. Send property change, les.propertyChange(pmm, source, copy, sourceval, copyval); //-- Send "add" event for all new members. List<Object> sorigl = (List<Object>) getChildValues(sourceval); // The current list from source int i = 0; for(Object cv : sorigl) { les.addCollectionAdd(pmm, source, copy, i++, cv); } return true; } //-- We have two collections - we need to diff the instances... Get both "current collections" List< ? > sorigl = getChildValues(sourceval); // The current list from source List<Object> scopyl = new ArrayList<Object>(sorigl.size()); // This will hold the "current copies" known for each source entry. for(Object t : sorigl) { Object tcopy = m_originalToCopyMap.get(t); // Get (existing) copy; if no copy is found it means the entry changed anyway - store null for that scopyl.add(tcopy); } List<Object> copyl = (List<Object>) getChildValues(copyval);// The list of copied values return diffList(les, pmm, source, copy, scopyl, copyl); } private <T, P, I> boolean diffList(@Nonnull LogiEventSet les, PropertyMetaModel<P> pmm, @Nonnull T source, @Nonnull T copy, List<I> sourcel, List<I> copyl) throws Exception { //-- First slice off common start and end; int send = sourcel.size(); int cend = copyl.size(); int sbeg = 0; int cbeg = 0; //-- Slice common beginning while(sbeg < send && cbeg < cend) { I so = sourcel.get(sbeg); I co = copyl.get(cbeg); if(!MetaManager.areObjectsEqual(so, co)) { break; } sbeg++; cbeg++; } //-- Slice common end while(send > sbeg && cend > cbeg) { I so = sourcel.get(send - 1); I co = copyl.get(cend - 1); if(!MetaManager.areObjectsEqual(so, co)) { break; } cend send } if(sbeg >= send && cbeg >= cend) { //-- Equal arrays- no changes. return false; } //-- Ouf.. We need to do the hard bits. Find the lcs and then render the edit as the delta. int m = (send - sbeg)+1; int n = (cend - cbeg) + 1; int[][] car = new int[m][]; for(int i = 0; i < m; i++) { car[i] = new int[n]; car[m][0] = 0; } for(int i = 0; i < n; i++) { car[0][i] = 0; } for(int i = 1; i < m; i++) { for(int j = 1; j < n; j++) { I so = sourcel.get(sbeg + i - 1); I co = copyl.get(cbeg + j - 1); if(MetaManager.areObjectsEqual(so, co)) { car[i][j] = car[i - 1][j - 1] + 1; // Is length of previous subsequence + 1. } else { car[i][j] = Math.max(car[i][j - 1], car[i - 1][j]); // Is length of the so-far longest subsequence } } } //-- Now: backtrack from the end to the start to render the delta. This creates the delta in the "reverse" order. int i = m; int j = n; List<LogiEventListDelta<T, P, I>> res = new ArrayList<LogiEventListDelta<T, P, I>>(); List<String> tmp = new ArrayList<String>(); while(j > 0 || i > 0) { if(i > 0 && j > 0 && MetaManager.areObjectsEqual(sourcel.get(sbeg + i - 1), copyl.get(cbeg + j - 1))) { i j //-- part of lcs - no delta } else if(j > 0 && (i == 0 || car[i][j - 1] >= car[i - 1][j])) { //-- Addition tmp.add("+ " + copyl.get(cbeg + j - 1)); j } else if(i > 0 && (j == 0 || car[i][j - 1] < car[i - 1][j])) { //-- Deletion tmp.add("- " + sourcel.get(sbeg + i - 1)); i } } Collections.reverse(tmp); for(String s : tmp) System.out.println(" " + s); return true; } @Nonnull private List< ? > getChildValues(@Nonnull Object source) { if(List.class.isAssignableFrom(source.getClass())) { List<Object> res = new ArrayList<Object>(); for(Object v : (List<Object>) source) res.add(v); return res; } else throw new IllegalStateException(source + ": only List child sets are supported."); } private <T, P> boolean compareValues(@Nonnull LogiEventSet les, PropertyMetaModel<P> pmm, @Nonnull T source, @Nonnull T copy) throws Exception { P vals = pmm.getValue(source); P valc = pmm.getValue(copy); if(MetaManager.areObjectsEqual(vals, valc)) return false; les.propertyChange(pmm, source, copy, vals, valc); return true; } private <T, P> boolean compareUpValues(@Nonnull LogiEventSet les, PropertyMetaModel<P> pmm, @Nonnull T source, @Nonnull T copy) throws Exception { if(getCopyHandler().isUnloadedParent(source, pmm)) { //-- Source is now unloaded. Check copy; P copyval = pmm.getValue(copy); if(copyval == null) return false; // Unloaded parent and null in copy -> unchanged //-- This parent has changed. les.propertyChange(pmm, source, copy, null, copyval); return true; } //-- The model has a loaded parent... Get it, and get it's copy. P sourceval = pmm.getValue(source); P copyval = pmm.getValue(copy); if(null == sourceval) { //-- Current value is null... If copy is null too we're equal if(null == copyval) return false; // Unchanged //-- This parent has changed. les.propertyChange(pmm, source, copy, null, copyval); return true; } //-- Source has a value. Is it mapped to a copy? P ncopyval = (P) m_originalToCopyMap.get(sourceval); if(ncopyval == null) { //-- There is no copy of this source -> new assignment to parent property. les.propertyChange(pmm, source, copy, sourceval, copyval); return true; } if(ncopyval != copyval) { //-- Different instances of copy -> changes les.propertyChange(pmm, source, copy, sourceval, copyval); return true; } //-- Same value. return false; } static private <I> boolean diffList(List<I> sourcel, List<I> copyl, Comparator<I> comparator) throws Exception { //-- First slice off common start and end; int send = sourcel.size(); int cend = copyl.size(); int sbeg = 0; int cbeg = 0; //-- Slice common beginning while(sbeg < send && cbeg < cend) { I so = sourcel.get(sbeg); I co = copyl.get(cbeg); if(0 != comparator.compare(so, co)) { break; } sbeg++; cbeg++; } //-- Slice common end while(send > sbeg && cend > cbeg) { I so = sourcel.get(send - 1); I co = copyl.get(cend - 1); if(0 != comparator.compare(so, co)) { break; } cend send } if(sbeg >= send && cbeg >= cend) { //-- Equal arrays- no changes. return false; } //-- Ouf.. We need to do the hard bits. Find the lcs and then render the edit as the delta. int m = (send - sbeg) + 1; int n = (cend - cbeg) + 1; int[][] car = new int[m][]; for(int i = 0; i < m; i++) { car[i] = new int[n]; car[i][0] = 0; } for(int i = 0; i < n; i++) { car[0][i] = 0; } for(int i = 1; i < m; i++) { for(int j = 1; j < n; j++) { I so = sourcel.get(sbeg + i - 1); I co = copyl.get(cbeg + j - 1); if(0 == comparator.compare(so, co)) { car[i][j] = car[i - 1][j - 1] + 1; // Is length of previous subsequence + 1. } else { car[i][j] = Math.max(car[i][j - 1], car[i - 1][j]); // Is length of the so-far longest subsequence } } } //-- Now: backtrack from the end to the start to render the delta. This creates the delta in the "reverse" order. List<String> tmp = new ArrayList<String>(); for(int xxx = sourcel.size(); --xxx >= send;) { tmp.add(" " + sourcel.get(xxx) + " @" + xxx + " (e)"); } int sindex = 0; int i = m - 1; int j = n - 1; while(j > 0 || i > 0) { if(i > 0 && j > 0 && 0 == comparator.compare(sourcel.get(sbeg + i - 1), copyl.get(cbeg + j - 1))) { tmp.add(" " + sourcel.get(sbeg + i - 1) + " @" + (sbeg + i - 1)); i j //-- part of lcs - no delta } else if(j > 0 && (i == 0 || car[i][j - 1] >= car[i - 1][j])) { //-- Addition tmp.add("+ " + copyl.get(cbeg + j - 1) + " @" + (sbeg + i - 1)); j } else if(i > 0 && (j == 0 || car[i][j - 1] < car[i - 1][j])) { //-- Deletion tmp.add("- " + sourcel.get(sbeg + i - 1) + " @" + (sbeg + i - 1)); i } } //-- Add all unhandled @ start, for(i = sbeg; --i >= 0;) { tmp.add(" " + sourcel.get(i) + " @" + i); } Collections.reverse(tmp); for(String s : tmp) System.out.println(" " + s); return true; } public static void main(String[] args) throws Exception { List<String> a = Arrays.asList("A", "B", "B", "A", "D", "E", "A", "D"); List<String> b = Arrays.asList("B", "A", "A", "D", "E", "A", "D"); Comparator<String> cs = new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.compareTo(o2); } }; // abbadead: diff is -a @0 -b @1 +A @2 // 01234567 // bbadead (-a @0) // badead (-b @1) diffList(a, b, cs); } }
package com.cloud.configuration; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import com.cloud.agent.AgentManager; import com.cloud.consoleproxy.ConsoleProxyManager; import com.cloud.ha.HighAvailabilityManager; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.network.NetworkManager; import com.cloud.network.router.VirtualNetworkApplianceManager; import com.cloud.server.ManagementServer; import com.cloud.storage.StorageManager; import com.cloud.storage.allocator.StoragePoolAllocator; import com.cloud.storage.secondary.SecondaryStorageVmManager; import com.cloud.storage.snapshot.SnapshotManager; import com.cloud.vm.UserVmManager; public enum Config { // Alert AlertEmailAddresses("Alert", ManagementServer.class, String.class, "alert.email.addresses", null, "Comma separated list of email addresses used for sending alerts.", null), AlertEmailSender("Alert", ManagementServer.class, String.class, "alert.email.sender", null, "Sender of alert email (will be in the From header of the email).", null), AlertSMTPHost("Alert", ManagementServer.class, String.class, "alert.smtp.host", null, "SMTP hostname used for sending out email alerts.", null), AlertSMTPPassword("Alert", ManagementServer.class, String.class, "alert.smtp.password", null, "Password for SMTP authentication (applies only if alert.smtp.useAuth is true).", null), AlertSMTPPort("Alert", ManagementServer.class, Integer.class, "alert.smtp.port", "465", "Port the SMTP server is listening on.", null), AlertSMTPUseAuth("Alert", ManagementServer.class, String.class, "alert.smtp.useAuth", null, "If true, use SMTP authentication when sending emails.", null), AlertSMTPUsername("Alert", ManagementServer.class, String.class, "alert.smtp.username", null, "Username for SMTP authentication (applies only if alert.smtp.useAuth is true).", null), AlertWait("Alert", AgentManager.class, Integer.class, "alert.wait", null, "Seconds to wait before alerting on a disconnected agent", null), // Storage StorageOverprovisioningFactor("Storage", StoragePoolAllocator.class, String.class, "storage.overprovisioning.factor", "2", "Used for storage overprovisioning calculation; available storage will be (actualStorageSize * storage.overprovisioning.factor)", null), StorageStatsInterval("Storage", ManagementServer.class, String.class, "storage.stats.interval", "60000", "The interval (in milliseconds) when storage stats (per host) are retrieved from agents.", null), MaxVolumeSize("Storage", ManagementServer.class, Integer.class, "storage.max.volume.size", "2000", "The maximum size for a volume (in GB).", null), TotalRetries("Storage", AgentManager.class, Integer.class, "total.retries", "4", "The number of times each command sent to a host should be retried in case of failure.", null), // Network GuestVlanBits("Network", ManagementServer.class, Integer.class, "guest.vlan.bits", "12", "The number of bits to reserve for the VLAN identifier in the guest subnet.", null), //MulticastThrottlingRate("Network", ManagementServer.class, Integer.class, "multicast.throttling.rate", "10", "Default multicast rate in megabits per second allowed.", null), NetworkThrottlingRate("Network", ManagementServer.class, Integer.class, "network.throttling.rate", "200", "Default data transfer rate in megabits per second allowed in network.", null), GuestDomainSuffix("Network", AgentManager.class, String.class, "guest.domain.suffix", "cloud.internal", "Default domain name for vms inside virtualized networks fronted by router", null), DirectNetworkNoDefaultRoute("Network", ManagementServer.class, Boolean.class, "direct.network.no.default.route", "false", "Direct Network Dhcp Server should not send a default route", "true/false"), OvsNetwork("Network", ManagementServer.class, Boolean.class, "open.vswitch.vlan.network", "false", "enable/disable vlan remapping of open vswitch network", null), OvsTunnelNetwork("Network", ManagementServer.class, Boolean.class, "open.vswitch.tunnel.network", "false", "enable/disable open vswitch tunnel network(no vlan)", null), VmNetworkThrottlingRate("Network", ManagementServer.class, Integer.class, "vm.network.throttling.rate", "200", "Default data transfer rate in megabits per second allowed in User vm's default network.", null), //VPN RemoteAccessVpnPskLength("Network", AgentManager.class, Integer.class, "remote.access.vpn.psk.length", "24", "The length of the ipsec preshared key (minimum 8, maximum 256)", null), RemoteAccessVpnClientIpRange("Network", AgentManager.class, String.class, "remote.access.vpn.client.iprange", "10.1.2.1-10.1.2.8", "The range of ips to be allocated to remote access vpn clients. The first ip in the range is used by the VPN server", null), RemoteAccessVpnUserLimit("Network", AgentManager.class, String.class, "remote.access.vpn.user.limit", "8", "The maximum number of VPN users that can be created per account", null), // Usage CapacityCheckPeriod("Usage", ManagementServer.class, Integer.class, "capacity.check.period", "300000", "The interval in milliseconds between capacity checks", null), StorageAllocatedCapacityThreshold("Usage", ManagementServer.class, Float.class, "storage.allocated.capacity.threshold", "0.85", "Percentage (as a value between 0 and 1) of allocated storage utilization above which alerts will be sent about low storage available.", null), StorageCapacityThreshold("Usage", ManagementServer.class, Float.class, "storage.capacity.threshold", "0.85", "Percentage (as a value between 0 and 1) of storage utilization above which alerts will be sent about low storage available.", null), CPUCapacityThreshold("Usage", ManagementServer.class, Float.class, "cpu.capacity.threshold", "0.85", "Percentage (as a value between 0 and 1) of cpu utilization above which alerts will be sent about low cpu available.", null), MemoryCapacityThreshold("Usage", ManagementServer.class, Float.class, "memory.capacity.threshold", "0.85", "Percentage (as a value between 0 and 1) of memory utilization above which alerts will be sent about low memory available.", null), PublicIpCapacityThreshold("Usage", ManagementServer.class, Float.class, "public.ip.capacity.threshold", "0.85", "Percentage (as a value between 0 and 1) of public IP address space utilization above which alerts will be sent.", null), PrivateIpCapacityThreshold("Usage", ManagementServer.class, Float.class, "private.ip.capacity.threshold", "0.85", "Percentage (as a value between 0 and 1) of private IP address space utilization above which alerts will be sent.", null), // Console Proxy ConsoleProxyCapacityStandby("Console Proxy", AgentManager.class, String.class, "consoleproxy.capacity.standby", "10", "The minimal number of console proxy viewer sessions that system is able to serve immediately(standby capacity)", null), ConsoleProxyCapacityScanInterval("Console Proxy", AgentManager.class, String.class, "consoleproxy.capacityscan.interval", "30000", "The time interval(in millisecond) to scan whether or not system needs more console proxy to ensure minimal standby capacity", null), ConsoleProxyCmdPort("Console Proxy", AgentManager.class, Integer.class, "consoleproxy.cmd.port", "8001", "Console proxy command port that is used to communicate with management server", null), ConsoleProxyRestart("Console Proxy", AgentManager.class, Boolean.class, "consoleproxy.restart", "true", "Console proxy restart flag, defaulted to true", null), ConsoleProxyUrlDomain("Console Proxy", AgentManager.class, String.class, "consoleproxy.url.domain", "realhostip.com", "Console proxy url domain", null), ConsoleProxyLoadscanInterval("Console Proxy", AgentManager.class, String.class, "consoleproxy.loadscan.interval", "10000", "The time interval(in milliseconds) to scan console proxy working-load info", null), ConsoleProxyRamSize("Console Proxy", AgentManager.class, Integer.class, "consoleproxy.ram.size", String.valueOf(ConsoleProxyManager.DEFAULT_PROXY_VM_RAMSIZE), "RAM size (in MB) used to create new console proxy VMs", null), ConsoleProxyCpuMHz("Console Proxy", AgentManager.class, Integer.class, "consoleproxy.cpu.mhz", String.valueOf(ConsoleProxyManager.DEFAULT_PROXY_VM_CPUMHZ), "CPU speed (in MHz) used to create new console proxy VMs", null), ConsoleProxySessionMax("Console Proxy", AgentManager.class, Integer.class, "consoleproxy.session.max", String.valueOf(ConsoleProxyManager.DEFAULT_PROXY_CAPACITY), "The max number of viewer sessions console proxy is configured to serve for", null), ConsoleProxySessionTimeout("Console Proxy", AgentManager.class, Integer.class, "consoleproxy.session.timeout", "300000", "Timeout(in milliseconds) that console proxy tries to maintain a viewer session before it times out the session for no activity", null), ConsoleProxyDisableRpFilter("Console Proxy", AgentManager.class, Integer.class, "consoleproxy.disable.rpfilter", "true", "disable rp_filter on console proxy VM public interface", null), ConsoleProxyLaunchMax("Console Proxy", AgentManager.class, Integer.class, "consoleproxy.launch.max", "10", "maximum number of console proxy instances per zone can be launched", null), ConsoleProxyManagementState("Console Proxy", AgentManager.class, String.class, "consoleproxy.management.state", com.cloud.consoleproxy.ConsoleProxyManagementState.Auto.toString(), "console proxy service management state", null), ConsoleProxyManagementLastState("Console Proxy", AgentManager.class, String.class, "consoleproxy.management.state.last", com.cloud.consoleproxy.ConsoleProxyManagementState.Auto.toString(), "last console proxy service management state", null), // Snapshots SnapshotHourlyMax("Snapshots", SnapshotManager.class, Integer.class, "snapshot.max.hourly", "8", "Maximum hourly snapshots for a volume", null), SnapshotDailyMax("Snapshots", SnapshotManager.class, Integer.class, "snapshot.max.daily", "8", "Maximum daily snapshots for a volume", null), SnapshotWeeklyMax("Snapshots", SnapshotManager.class, Integer.class, "snapshot.max.weekly", "8", "Maximum weekly snapshots for a volume", null), SnapshotMonthlyMax("Snapshots", SnapshotManager.class, Integer.class, "snapshot.max.monthly", "8", "Maximum monthly snapshots for a volume", null), SnapshotPollInterval("Snapshots", SnapshotManager.class, Integer.class, "snapshot.poll.interval", "300", "The time interval in seconds when the management server polls for snapshots to be scheduled.", null), SnapshotDeltaMax("Snapshots", SnapshotManager.class, Integer.class, "snapshot.delta.max", "16", "max delta snapshots between two full snapshots.", null), // Advanced JobExpireMinutes("Advanced", ManagementServer.class, String.class, "job.expire.minutes", "1440", "Time (in minutes) for async-jobs to be kept in system", null), JobCancelThresholdMinutes("Advanced", ManagementServer.class, String.class, "job.cancel.threshold.minutes", "60", "Time (in minutes) for async-jobs to be forcely cancelled if it has been in process for long", null), AccountCleanupInterval("Advanced", ManagementServer.class, Integer.class, "account.cleanup.interval", "86400", "The interval (in seconds) between cleanup for removed accounts", null), AllowPublicUserTemplates("Advanced", ManagementServer.class, Integer.class, "allow.public.user.templates", "true", "If false, users will not be able to create public templates.", null), InstanceName("Advanced", AgentManager.class, String.class, "instance.name", "VM", "Name of the deployment instance.", null), ExpungeDelay("Advanced", UserVmManager.class, Integer.class, "expunge.delay", "86400", "Determines how long (in seconds) to wait before actually expunging destroyed vm. The default value = the default value of expunge.interval", null), ExpungeInterval("Advanced", UserVmManager.class, Integer.class, "expunge.interval", "86400", "The interval (in seconds) to wait before running the expunge thread.", null), ExpungeWorkers("Advanced", UserVmManager.class, Integer.class, "expunge.workers", "1", "Number of workers performing expunge ", null), ExtractURLCleanUpInterval("Advanced", ManagementServer.class, Integer.class, "extract.url.cleanup.interval", "120", "The interval (in seconds) to wait before cleaning up the extract URL's ", null), HostStatsInterval("Advanced", ManagementServer.class, Integer.class, "host.stats.interval", "60000", "The interval (in milliseconds) when host stats are retrieved from agents.", null), HostRetry("Advanced", AgentManager.class, Integer.class, "host.retry", "2", "Number of times to retry hosts for creating a volume", null), IntegrationAPIPort("Advanced", ManagementServer.class, Integer.class, "integration.api.port", "8096", "Defaul API port", null), InvestigateRetryInterval("Advanced", HighAvailabilityManager.class, Integer.class, "investigate.retry.interval", "60", "Time (in seconds) between VM pings when agent is disconnected", null), MigrateRetryInterval("Advanced", HighAvailabilityManager.class, Integer.class, "migrate.retry.interval", "120", "Time (in seconds) between migration retries", null), PingInterval("Advanced", AgentManager.class, Integer.class, "ping.interval", "60", "Ping interval in seconds", null), PingTimeout("Advanced", AgentManager.class, Float.class, "ping.timeout", "2.5", "Multiplier to ping.interval before announcing an agent has timed out", null), Port("Advanced", AgentManager.class, Integer.class, "port", "8250", "Port to listen on for agent connection.", null), RouterCpuMHz("Advanced", NetworkManager.class, Integer.class, "router.cpu.mhz", String.valueOf(VirtualNetworkApplianceManager.DEFAULT_ROUTER_CPU_MHZ), "Default CPU speed (MHz) for router VM.", null), RestartRetryInterval("Advanced", HighAvailabilityManager.class, Integer.class, "restart.retry.interval", "600", "Time (in seconds) between retries to restart a vm", null), RouterStatsInterval("Advanced", NetworkManager.class, Integer.class, "router.stats.interval", "300", "Interval (in seconds) to report router statistics.", null), RouterTemplateId("Advanced", NetworkManager.class, Long.class, "router.template.id", "1", "Default ID for template.", null), StartRetry("Advanced", AgentManager.class, Integer.class, "start.retry", "10", "Number of times to retry create and start commands", null), StopRetryInterval("Advanced", HighAvailabilityManager.class, Integer.class, "stop.retry.interval", "600", "Time in seconds between retries to stop or destroy a vm" , null), StorageCleanupInterval("Advanced", StorageManager.class, Integer.class, "storage.cleanup.interval", "86400", "The interval (in seconds) to wait before running the storage cleanup thread.", null), StorageCleanupEnabled("Advanced", StorageManager.class, Boolean.class, "storage.cleanup.enabled", "true", "Enables/disables the storage cleanup thread.", null), UpdateWait("Advanced", AgentManager.class, Integer.class, "update.wait", "600", "Time to wait (in seconds) before alerting on a updating agent", null), Wait("Advanced", AgentManager.class, Integer.class, "wait", "1800", "Time in seconds to wait for control commands to return", null), XapiWait("Advanced", AgentManager.class, Integer.class, "xapiwait", "600", "Time (in seconds) to wait for XAPI to return", null), CmdsWait("Advanced", AgentManager.class, Integer.class, "cmd.wait", "7200", "Time (in seconds) to wait for some heavy time-consuming commands", null), Workers("Advanced", AgentManager.class, Integer.class, "workers", "5", "Number of worker threads.", null), MountParent("Advanced", ManagementServer.class, String.class, "mount.parent", "/var/lib/cloud/mnt", "The mount point on the Management Server for Secondary Storage.", null), SystemVMUseLocalStorage("Advanced", ManagementServer.class, Boolean.class, "system.vm.use.local.storage", "false", "Indicates whether to use local storage pools or shared storage pools for system VMs.", null), SystemVMAutoReserveCapacity("Advanced", ManagementServer.class, Boolean.class, "system.vm.auto.reserve.capacity", "true", "Indicates whether or not to automatically reserver system VM standby capacity.", null), CPUOverprovisioningFactor("Advanced", ManagementServer.class, String.class, "cpu.overprovisioning.factor", "1", "Used for CPU overprovisioning calculation; available CPU will be (actualCpuCapacity * cpu.overprovisioning.factor)", null), LinkLocalIpNums("Advanced", ManagementServer.class, Integer.class, "linkLocalIp.nums", "10", "The number of link local ip that needed by domR(in power of 2)", null), HypervisorList("Advanced", ManagementServer.class, String.class, "hypervisor.list", HypervisorType.KVM + "," + HypervisorType.XenServer + "," + HypervisorType.VMware + "," + HypervisorType.BareMetal + "," + HypervisorType.Ovm, "The list of hypervisors that this deployment will use.", "hypervisorList"), ManagementHostIPAdr("Advanced", ManagementServer.class, String.class, "host", "localhost", "The ip address of management server", null), ManagementNetwork("Advanced", ManagementServer.class, String.class, "management.network.cidr", null, "The cidr of management server network", null), EventPurgeDelay("Advanced", ManagementServer.class, Integer.class, "event.purge.delay", "15", "Events older than specified number days will be purged. Set this value to 0 to never delete events", null), UseLocalStorage("Premium", ManagementServer.class, Boolean.class, "use.local.storage", "false", "Should we use the local storage if it's available?", null), SecStorageVmRamSize("Advanced", AgentManager.class, Integer.class, "secstorage.vm.ram.size", String.valueOf(SecondaryStorageVmManager.DEFAULT_SS_VM_RAMSIZE), "RAM size (in MB) used to create new secondary storage vms", null), SecStorageVmCpuMHz("Advanced", AgentManager.class, Integer.class, "secstorage.vm.cpu.mhz", String.valueOf(SecondaryStorageVmManager.DEFAULT_SS_VM_CPUMHZ), "CPU speed (in MHz) used to create new secondary storage vms", null), MaxTemplateAndIsoSize("Advanced", ManagementServer.class, Long.class, "max.template.iso.size", "50", "The maximum size for a downloaded template or ISO (in GB).", null), SecStorageAllowedInternalDownloadSites("Advanced", ManagementServer.class, String.class, "secstorage.allowed.internal.sites", null, "Comma separated list of cidrs internal to the datacenter that can host template download servers", null), SecStorageEncryptCopy("Advanced", ManagementServer.class, Boolean.class, "secstorage.encrypt.copy", "false", "Use SSL method used to encrypt copy traffic between zones", "true,false"), SecStorageSecureCopyCert("Advanced", ManagementServer.class, String.class, "secstorage.ssl.cert.domain", "realhostip.com", "SSL certificate used to encrypt copy traffic between zones", null), SecStorageCapacityStandby("Advanced", AgentManager.class, Integer.class, "secstorage.capacity.standby", "10", "The minimal number of command execution sessions that system is able to serve immediately(standby capacity)", null), SecStorageSessionMax("Advanced", AgentManager.class, Integer.class, "secstorage.session.max", "50", "The max number of command execution sessions that a SSVM can handle", null), SecStorageCmdExecutionTimeMax("Advanced", AgentManager.class, Integer.class, "secstorage.cmd.execution.time.max", "30", "The max command execution time in minute", null), DirectAttachNetworkEnabled("Advanced", ManagementServer.class, Boolean.class, "direct.attach.network.externalIpAllocator.enabled", "false", "Direct-attach VMs using external DHCP server", "true,false"), DirectAttachNetworkExternalAPIURL("Advanced", ManagementServer.class, String.class, "direct.attach.network.externalIpAllocator.url", null, "Direct-attach VMs using external DHCP server (API url)", null), CheckPodCIDRs("Advanced", ManagementServer.class, String.class, "check.pod.cidrs", "true", "If true, different pods must belong to different CIDR subnets.", "true,false"), NetworkGcWait("Advanced", ManagementServer.class, Integer.class, "network.gc.wait", "600", "Time (in seconds) to wait before shutting down a network that's not in used", null), NetworkGcInterval("Advanced", ManagementServer.class, Integer.class, "network.gc.interval", "600", "Seconds to wait before checking for networks to shutdown", null), HostCapacityCheckerWait("Advanced", ManagementServer.class, Integer.class, "host.capacity.checker.wait", "3600", "Time (in seconds) to wait before starting host capacity background checker", null), HostCapacityCheckerInterval("Advanced", ManagementServer.class, Integer.class, "host.capacity.checker.interval", "3600", "Time (in seconds) to wait before recalculating host's capacity", null), CapacitySkipcountingHours("Advanced", ManagementServer.class, Integer.class, "capacity.skipcounting.hours", "3600", "Time (in seconds) to wait before release VM's cpu and memory when VM in stopped state", null), VmStatsInterval("Advanced", ManagementServer.class, Integer.class, "vm.stats.interval", "60000", "The interval (in milliseconds) when vm stats are retrieved from agents.", null), VmTransitionWaitInterval("Advanced", ManagementServer.class, Integer.class, "vm.tranisition.wait.interval", "3600", "Time (in seconds) to wait before taking over a VM in transition state", null), ControlCidr("Advanced", ManagementServer.class, String.class, "control.cidr", "169.254.0.0/16", "Changes the cidr for the control network traffic. Defaults to using link local. Must be unique within pods", null), ControlGateway("Advanced", ManagementServer.class, String.class, "control.gateway", "169.254.0.1", "gateway for the control network traffic", null), UseUserConcentratedPodAllocation("Advanced", ManagementServer.class, Boolean.class, "use.user.concentrated.pod.allocation", "true", "If true, deployment planner applies the user concentration heuristic during VM resource allocation", "true,false"), HostCapacityTypeToOrderClusters("Advanced", ManagementServer.class, String.class, "host.capacityType.to.order.clusters", "CPU", "The host capacity type (CPU or RAM) is used by deployment planner to order clusters during VM resource allocation", "CPU,RAM"), EndpointeUrl("Advanced", ManagementServer.class, String.class, "endpointe.url", "http://localhost:8080/client/api", "Endpointe Url", "The endpoint callback URL"), // XenServer VmAllocationAlgorithm("Advanced", ManagementServer.class, String.class, "vm.allocation.algorithm", "random", "If 'random', hosts within a pod will be randomly considered for VM/volume allocation. If 'firstfit', they will be considered on a first-fit basis.", null), XenPublicNetwork("Network", ManagementServer.class, String.class, "xen.public.network.device", null, "[ONLY IF THE PUBLIC NETWORK IS ON A DEDICATED NIC]:The network name label of the physical device dedicated to the public network on a XenServer host", null), XenStorageNetwork1("Network", ManagementServer.class, String.class, "xen.storage.network.device1", "cloud-stor1", "Specify when there are storage networks", null), XenStorageNetwork2("Network", ManagementServer.class, String.class, "xen.storage.network.device2", "cloud-stor2", "Specify when there are storage networks", null), XenPrivateNetwork("Network", ManagementServer.class, String.class, "xen.private.network.device", null, "Specify when the private network name is different", null), NetworkGuestCidrLimit("Network", NetworkManager.class, Integer.class, "network.guest.cidr.limit", "22", "size limit for guest cidr; can't be less than this value", null), XenMinVersion("Advanced", ManagementServer.class, String.class, "xen.min.version", "3.3.1", "Minimum Xen version", null), XenProductMinVersion("Advanced", ManagementServer.class, String.class, "xen.min.product.version", "0.1.1", "Minimum XenServer version", null), XenXapiMinVersion("Advanced", ManagementServer.class, String.class, "xen.min.xapi.version", "1.3", "Minimum Xapi Tool Stack version", null), XenMaxVersion("Advanced", ManagementServer.class, String.class, "xen.max.version", "3.4.2", "Maximum Xen version", null), XenProductMaxVersion("Advanced", ManagementServer.class, String.class, "xen.max.product.version", "5.6.0", "Maximum XenServer version", null), XenXapiMaxVersion("Advanced", ManagementServer.class, String.class, "xen.max.xapi.version", "1.3", "Maximum Xapi Tool Stack version", null), XenSetupMultipath("Advanced", ManagementServer.class, String.class, "xen.setup.multipath", "false", "Setup the host to do multipath", null), XenBondStorageNic("Advanced", ManagementServer.class, String.class, "xen.bond.storage.nics", null, "Attempt to bond the two networks if found", null), XenHeartBeatInterval("Advanced", ManagementServer.class, Integer.class, "xen.heartbeat.interval", "60", "heartbeat to use when implementing XenServer Self Fencing", null), XenGuestNetwork("Advanced", ManagementServer.class, String.class, "xen.guest.network.device", null, "Specify for guest network name label", null), // VMware VmwarePrivateNetworkVSwitch("Advanced", ManagementServer.class, String.class, "vmware.private.vswitch", null, "Specify the vSwitch on host for private network", null), VmwarePublicNetworkVSwitch("Advanced", ManagementServer.class, String.class, "vmware.public.vswitch", null, "Specify the vSwitch on host for public network", null), VmwareGuestNetworkVSwitch("Advanced", ManagementServer.class, String.class, "vmware.guest.vswitch", null, "Specify the vSwitch on host for guest network", null), VmwareServiceConsole("Advanced", ManagementServer.class, String.class, "vmware.service.console", "Service Console", "Specify the service console network name (ESX host only)", null), // KVM KvmPublicNetwork("Advanced", ManagementServer.class, String.class, "kvm.public.network.device", null, "Specify the public bridge on host for public network", null), KvmPrivateNetwork("Advanced", ManagementServer.class, String.class, "kvm.private.network.device", null, "Specify the private bridge on host for private network", null), // Premium UsageExecutionTimezone("Premium", ManagementServer.class, String.class, "usage.execution.timezone", null, "The timezone to use for usage job execution time", null), UsageStatsJobAggregationRange("Premium", ManagementServer.class, Integer.class, "usage.stats.job.aggregation.range", "1440", "The range of time for aggregating the user statistics specified in minutes (e.g. 1440 for daily, 60 for hourly.", null), UsageStatsJobExecTime("Premium", ManagementServer.class, String.class, "usage.stats.job.exec.time", "00:15", "The time at which the usage statistics aggregation job will run as an HH24:MM time, e.g. 00:30 to run at 12:30am.", null), EnableUsageServer("Premium", ManagementServer.class, Boolean.class, "enable.usage.server", "true", "Flag for enabling usage", null), TrafficSentinelHostName("Premium", ManagementServer.class, String.class, "traffic.sentinel.hostname", null, "Hostname of the Traffic Sentinel in http://<hostname> format for querying direct network usage", null), // Hidden UseSecondaryStorageVm("Hidden", ManagementServer.class, Boolean.class, "secondary.storage.vm", "false", "Deploys a VM per zone to manage secondary storage if true, otherwise secondary storage is mounted on management server", null), CreatePoolsInPod("Hidden", ManagementServer.class, Boolean.class, "xen.create.pools.in.pod", "false", "Should we automatically add XenServers into pools that are inside a Pod", null), CloudIdentifier("Hidden", ManagementServer.class, String.class, "cloud.identifier", null, "A unique identifier for the cloud.", null), SSOKey("Hidden", ManagementServer.class, String.class, "security.singlesignon.key", null, "A Single Sign-On key used for logging into the cloud", null), SSOAuthTolerance("Advanced", ManagementServer.class, Long.class, "security.singlesignon.tolerance.millis", "300000", "The allowable clock difference in milliseconds between when an SSO login request is made and when it is received.", null), //NetworkType("Hidden", ManagementServer.class, String.class, "network.type", "vlan", "The type of network that this deployment will use.", "vlan,direct"), HashKey("Hidden", ManagementServer.class, String.class, "security.hash.key", null, "for generic key-ed hash", null), RouterRamSize("Hidden", NetworkManager.class, Integer.class, "router.ram.size", "128", "Default RAM for router VM (in MB).", null), VmOpWaitInterval("Advanced", ManagementServer.class, Integer.class, "vm.op.wait.interval", "120", "Time (in seconds) to wait before checking if a previous operation has succeeded", null), VmOpLockStateRetry("Advanced", ManagementServer.class, Integer.class, "vm.op.lock.state.retry", "5", "Times to retry locking the state of a VM for operations", "-1 means try forever"), VmOpCleanupInterval("Advanced", ManagementServer.class, Long.class, "vm.op.cleanup.interval", "86400", "Interval to run the thread that cleans up the vm operations (in seconds)", "Seconds"), VmOpCleanupWait("Advanced", ManagementServer.class, Long.class, "vm.op.cleanup.wait", "3600", "Time (in seconds) to wait before cleanuping up any vm work items", "Seconds"), VmOpCancelInterval("Advanced", ManagementServer.class, Long.class, "vm.op.cancel.interval", "3600", "Time (in seconds) to wait before cancelling a operation", "Seconds"), DefaultPageSize("Advanced", ManagementServer.class, Long.class, "default.page.size", "500", "Default page size for API list* commands", null), TaskCleanupRetryInterval("Advanced", ManagementServer.class, Integer.class, "task.cleanup.retry.interval", "600", "Time (in seconds) to wait before retrying cleanup of tasks if the cleanup failed previously. 0 means to never retry.", "Seconds"), // Account Default Limits DefaultMaxAccountUserVms("Account Defaults", ManagementServer.class, Long.class, "max.account.user.vms", "20", "The default maximum number of user VMs that can be deployed for an account", null), DefaultMaxAccountPublicIPs("Account Defaults", ManagementServer.class, Long.class, "max.account.public.ips", "20", "The default maximum number of public IPs that can be consumed by an account", null), DefaultMaxAccountTemplates("Account Defaults", ManagementServer.class, Long.class, "max.account.templates", "20", "The default maximum number of templates that can be deployed for an account", null), DefaultMaxAccountSnapshots("Account Defaults", ManagementServer.class, Long.class, "max.account.snapshots", "20", "The default maximum number of snapshots that can be created for an account", null), DefaultMaxAccountVolumes("Account Defaults", ManagementServer.class, Long.class, "max.account.volumes", "20", "The default maximum number of volumes that can be created for an account", null); private final String _category; private final Class<?> _componentClass; private final Class<?> _type; private final String _name; private final String _defaultValue; private final String _description; private final String _range; private static final HashMap<String, List<Config>> _configs = new HashMap<String, List<Config>>(); static { // Add categories _configs.put("Alert", new ArrayList<Config>()); _configs.put("Storage", new ArrayList<Config>()); _configs.put("Snapshots", new ArrayList<Config>()); _configs.put("Network", new ArrayList<Config>()); _configs.put("Usage", new ArrayList<Config>()); _configs.put("Console Proxy", new ArrayList<Config>()); _configs.put("Advanced", new ArrayList<Config>()); _configs.put("Premium", new ArrayList<Config>()); _configs.put("Developer", new ArrayList<Config>()); _configs.put("Hidden", new ArrayList<Config>()); _configs.put("Account Defaults", new ArrayList<Config>()); // Add values into HashMap for (Config c : Config.values()) { String category = c.getCategory(); List<Config> currentConfigs = _configs.get(category); currentConfigs.add(c); _configs.put(category, currentConfigs); } } private Config(String category, Class<?> componentClass, Class<?> type, String name, String defaultValue, String description, String range) { _category = category; _componentClass = componentClass; _type = type; _name = name; _defaultValue = defaultValue; _description = description; _range = range; } public String getCategory() { return _category; } public String key() { return _name; } public String getDescription() { return _description; } public String getDefaultValue() { return _defaultValue; } public Class<?> getType() { return _type; } public Class<?> getComponentClass() { return _componentClass; } public String getComponent() { if (_componentClass == ManagementServer.class) { return "management-server"; } else if (_componentClass == AgentManager.class) { return "AgentManager"; } else if (_componentClass == UserVmManager.class) { return "UserVmManager"; } else if (_componentClass == HighAvailabilityManager.class) { return "HighAvailabilityManager"; } else if (_componentClass == StoragePoolAllocator.class) { return "StorageAllocator"; } else { return "none"; } } public String getRange() { return _range; } @Override public String toString() { return _name; } public static List<Config> getConfigs(String category) { return _configs.get(category); } public static Config getConfig(String name) { List<String> categories = getCategories(); for (String category : categories) { List<Config> currentList = getConfigs(category); for (Config c : currentList) { if (c.key().equals(name)) { return c; } } } return null; } public static List<String> getCategories() { Object[] keys = _configs.keySet().toArray(); List<String> categories = new ArrayList<String>(); for (Object key : keys) { categories.add((String) key); } return categories; } }
package com.catglo.fakerproxy; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; import java.util.HashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.Menu; public class ProxyActivity extends Activity { public static final String API_HOST = "oep06-d.samsmk.com"; public static final int API_PORT = 80; public static final int LOCALHOST_RELAY_PORT=8081; public static final int maxBufferSizeForAudioProxy = 256; public static final int MAX_HTTP_HEADER_SIZE = 2048; public static final int MAX_HTTP_HEADERS = 40; public static final boolean CONTINUE_SENDING_AFTER_REQUEST = false; static final Pattern httpHeaderEndPattern = Pattern.compile("\r\n\r\n"); static final Pattern httpRequestFieldAndValuePattern = Pattern.compile("(.*?):(.*?)\r\n"); static final Pattern statusLineEndpointPattern = Pattern.compile("[GETPOSUDL]{3,6}\\s([\\w_\\-\\&\\?\\/\\\\\\:\\%\\(\\)\\$\\ HashMap<String,String> fakeApis = new HashMap<String,String>(); protected static final String LOG_TAG = "PROXY"; private StringBuilder headerBuilderBuffer = new StringBuilder(httpHeaderPrebufferSize); private byte[] buffer = new byte[Math.max(maxBufferSizeForAudioProxy,httpHeaderPrebufferSize)]; byte[] headerScratchBuffer = new byte[httpHeaderPrebufferSize]; static int httpHeaderPrebufferSize = MAX_HTTP_HEADER_SIZE; String headers[] = new String[MAX_HTTP_HEADERS]; private int port=LOCALHOST_RELAY_PORT; private Socket socketApiHost; private ServerSocket localhostListeningSocket; private Thread proxyThread; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // fakeApis.put("/api/tap/rewards", "rewards.json"); // fakeApis.put("/api/tap/rewards?redeemed=true", "rewards.json"); // fakeApis.put("/api/tap/rewards?redeemed=false", "rewards.json"); fakeApis.put("/services/customers/me/profile?fields","rewards.json"); proxyThread = new Thread(new Runnable(){public void run() { try { Matcher m; localhostListeningSocket = new ServerSocket(port, 0, InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 })); port = localhostListeningSocket.getLocalPort(); Log.d(LOG_TAG, "port " + port + " obtained"); do { Socket localhostConnection = localhostListeningSocket.accept(); if (localhostConnection == null) { continue; } Log.d(LOG_TAG, "FOUND client connected"); socketApiHost = new Socket(API_HOST,API_PORT); InputStream apiServerInputStream = socketApiHost.getInputStream(); OutputStream apiServerOutputStream = socketApiHost.getOutputStream(); InputStream localhostRelayInputStream = localhostConnection.getInputStream(); OutputStream localhostRelayOutputStream = localhostConnection.getOutputStream(); //Read in the HTTP header so we can determine if we need to handle the request ourselves int totalBytesRead=0; int bytesRead; String myDebug; while (totalBytesRead<httpHeaderPrebufferSize){ if (localhostRelayInputStream.available()>0){ //get back the data bytesRead = localhostRelayInputStream.read(buffer,totalBytesRead,httpHeaderPrebufferSize-totalBytesRead); totalBytesRead+=bytesRead; myDebug = new String(buffer,0,totalBytesRead); m = httpHeaderEndPattern.matcher(myDebug); if (m.find()){ httpHeaderPrebufferSize=totalBytesRead; break; } } } //Parse the status line out of the header int statusLineBufferIndex; for (statusLineBufferIndex = 0; statusLineBufferIndex < httpHeaderPrebufferSize; statusLineBufferIndex++){ headerScratchBuffer[statusLineBufferIndex] = buffer[statusLineBufferIndex]; if (headerScratchBuffer[statusLineBufferIndex]==0x0A) { break; } } statusLineBufferIndex++; String statusLine = new String(headerScratchBuffer,0,statusLineBufferIndex); Log.i(LOG_TAG,"Status Line:"+statusLine); m = statusLineEndpointPattern.matcher(statusLine); String endpoint="error"; if (m.find()){ endpoint = m.group(1); } Log.i(LOG_TAG,"Endpoint:"+endpoint); if (fakeApis.containsKey(endpoint)){ Log.i(LOG_TAG,"INTERCEPT "+endpoint); String fileName = fakeApis.get(endpoint); InputStream fakeJsonInputStream=null; byte[] buffer = new byte[2048]; bytesRead=0; try { fakeJsonInputStream=getAssets().open(fileName); while (fakeJsonInputStream.available()>0){ bytesRead = fakeJsonInputStream.available(); if (bytesRead>2048){ bytesRead=2048; } fakeJsonInputStream.read(buffer, 0, bytesRead); localhostRelayOutputStream.write(buffer, 0, bytesRead); } } catch (IOException e) { e.printStackTrace(); } continue; } //Get the HTTP headers in to an array int currentHeaderIndex = -1; int headerBufferIndex; do { currentHeaderIndex++; for (headerBufferIndex=0; statusLineBufferIndex < httpHeaderPrebufferSize; statusLineBufferIndex++,headerBufferIndex++){ headerScratchBuffer[headerBufferIndex] = buffer[statusLineBufferIndex]; if (headerScratchBuffer[headerBufferIndex]==0x0A) { break; } } statusLineBufferIndex++; headerBufferIndex++; headers[currentHeaderIndex] = new String(headerScratchBuffer,0,headerBufferIndex); } while (headers[currentHeaderIndex].length()>2); //Here we have a chance to intercept the http headers in case we need to tweak something for (int i = 0; i < currentHeaderIndex; i++){ Log.i(LOG_TAG,"Request Header:"+headers[i]); //if (headers[i].contains("Content-Type")){ } int numberOfBytesInBufferAfterHeaderBytes = httpHeaderPrebufferSize-statusLineBufferIndex; // At this point we are done reading the request and its time to forward it to the real API server //Write the HTTP status line to the api server socket apiServerOutputStream.write(statusLine.getBytes()); //Write the HTTP headers to the api server socket for (int i = 0; i < currentHeaderIndex; i++){ apiServerOutputStream.write(headers[i].getBytes()); } apiServerOutputStream.write("\r\n".getBytes()); if (numberOfBytesInBufferAfterHeaderBytes>0){ //Write the remaining bits of data we pulled in the header buffer apiServerOutputStream.write(buffer,statusLineBufferIndex,numberOfBytesInBufferAfterHeaderBytes); int zombiCount=0; boolean keepGoing=true; while (keepGoing && zombiCount<1000) { //To make sure that the thread does not spin endlessly doing nothing but eating battery and cpu //we keep a counter to end the thread if its not doing anything zombiCount++; while ((bytesRead = apiServerInputStream.available())>0 && keepGoing){ //The http spec does not have the client sending bits to the server after the initial request, but maybe we want to anyhow if (CONTINUE_SENDING_AFTER_REQUEST) { int len; if ((len = localhostRelayInputStream.available())>0){ byte[] buf = new byte[len]; localhostRelayInputStream.read(buf); apiServerOutputStream.write(buf); } } zombiCount=0; //clip the bytes read to our max chunk size if (bytesRead>maxBufferSizeForAudioProxy){ bytesRead=maxBufferSizeForAudioProxy; } apiServerInputStream.read(buffer,0,bytesRead); localhostRelayOutputStream.write(buffer,0,bytesRead); Log.i(LOG_TAG,"Relayed "+bytesRead+" bytes"); } }// End while } } while(Thread.interrupted()==false); } catch (UnknownHostException e) { Log.e(LOG_TAG, "Error initializing server", e); } catch (IOException e) { Log.e(LOG_TAG, "Error initializing server", e); } }}); proxyThread.start(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
package solace.cmd; import java.util.*; import solace.game.*; import solace.net.*; import java.io.*; import solace.util.*; import solace.cmd.play.*; /** * Main game play controller (the actual game). * @author Ryan Sandor Richards */ public class PlayController extends AbstractStateController { solace.game.Character character; static final String[] moveAliases = { "move", "go", "north", "south", "east", "west", "up", "down", "exit", "enter" }; /** * Quit command. Exits the game and returns to the main menu. * @author Ryan Sandor Richards. */ class Quit extends AbstractCommand { public Quit() { super("quit"); } public boolean run(Connection c, String []params) { Room room = character.getRoom(); room.getCharacters().remove(character); room.sendMessage(String.format("%s has left the game.", character.getName())); World.getActivePlayers().remove(c); c.setStateController( new MainMenu(c) ); return true; } } /** * Help Command. Currently only displays a list of commands available to the user. * @author Ryan Sandor Richards */ class Help extends AbstractCommand { public Help() { super("help"); } public boolean run(Connection c, String []params) { String commandText = "\n{cAvailable Commands:{x\n"; for (CommandTuple cmd : commands) { commandText += cmd.getName() + " "; } c.sendln(commandText + "\n"); return true; } } /** * Creates a new game play controller. * @param c The connection. * @param ch The character. * @throws GameException if anything goes wrong when logging the user in. */ public PlayController(Connection c, solace.game.Character ch) throws GameException { // Initialize the menu super(c, "Sorry, that is not an option. Type '{yhelp{x' to see a list."); character = ch; // Character location initialization if (ch.getRoom() == null) { Room room = World.getDefaultRoom(); room.getCharacters().add(ch); ch.setRoom(room); } // Inform other players in the room that they player has entered the game ch.getRoom().sendMessage(character.getName() + " has entered the game.", character); // Add commands addCommands(); // Place the player in the world World.getActivePlayers().add(c); c.sendln("\n\rNow playing as {y" + ch.getName() + "{x, welcome!\n\r"); c.setPrompt("{c>{x "); // Describe the room to the player c.sendln(ch.getRoom().describeTo(ch)); } /** * Adds basic gameplay commands to the controller. */ protected void addCommands() { addCommand(new Quit()); addCommand(new Help()); addCommand(moveAliases, new Move(character)); addCommand(new Look(character)); addCommand(new Say(character)); addCommand(new Scan(character)); } }
package com.itto3.itimeu; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; import com.itto3.itimeu.data.ItemContract; import com.itto3.itimeu.data.ItemDbHelper; import com.itto3.itimeu.data.SharedPreferenceUtil; import com.itto3.itimeu.data.TimerDbUtil; /** * A simple {@link Fragment} subclass. */ public class TimerFragment extends Fragment { /*Setting UI*/ public static final String WORKTIME = "worktime"; public static final String BREAKTIME = "breaktime"; public static final String LONGBREAKTIME = "longbreaktime"; public static final String SESSION = "session"; public static final String CONTINUOUS_OPTION = "continuous"; public static final String SHUTDOWN_OPTION = "shutdown"; private TextView leftTime; private TextView mItemNameText; private ProgressBar progressBar; private Button stateButton; /*timer Service Component*/ private TimerService mTimerService; boolean mServiceBound = false; private TimerHandler timerHandler; private int progressBarValue = 0; public int runTime; // minute /*timer calc*/ private Intent intent; //private ServiceConnection conn; private Thread mReadThread; /*store time count*/ private int timerCounter; // Item info come from ListView private int mId, mStatus, mUnit, mTotalUnit; private String mName; public TimerFragment() { } // Required empty public constructor BroadcastReceiver mReceiver; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View timerView = inflater.inflate(R.layout.fragment_timer, container, false); // get Timer tag and set to TimerTag String timerTag = getTag(); ((MainActivity) getActivity()).setTimerTag(timerTag); mItemNameText = timerView.findViewById(R.id.job_name_txt); /*progressBar button init*/ progressBar = (ProgressBar) timerView.findViewById(R.id.progressBar); stateButton = (Button) timerView.findViewById(R.id.state_bttn_view); stateButton.setOnClickListener(stateChecker); stateButton.setEnabled(false); /*Time Text Initialize */ leftTime = (TextView) timerView.findViewById(R.id.time_txt_view); /*progressBar button init*/ progressBar = (ProgressBar) timerView.findViewById(R.id.progressBar); progressBar.bringToFront(); // bring the progressbar to the top mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { onUnitFinish(); } }; /*init timer count */ timerCounter = 1; /*init shared prefernce*/ SharedPreferenceUtil.save(getContext(), "COUNT", timerCounter); return timerView; } public void onUnitFinish() { stopUpdateLeftTime(); // UPDATE mCountTimner range 1..8 // if Long Break Time has just finished, change to 1 timerCounter++; int sessionNumber = SharedPreferenceUtil.get(getContext(), SESSION, 4) * 2; if (timerCounter == sessionNumber + 1) timerCounter = 1; SharedPreferenceUtil.save(getContext(), "COUNT", timerCounter); stateButton.setText("start"); if (!isWorkTime()) mUnit++; setTimerTimeName(); storeUnitStatus(); //after the unit values has been updated set false to ServiceFinished TimerService.mTimerServiceFinished = false; onResume(); } public void changeScreenToList() { MainActivity mainActivity = (MainActivity) getActivity(); (mainActivity).getViewPager().setCurrentItem(0); } public void storeUnitStatus() { //store mUnit and mStatus if (isTaskComplete()) { TimerDbUtil.update(getContext(), mUnit, ItemContract.ItemEntry.STATUS_DONE, mId); if (isWorkTime()) { stateButton.setEnabled(false); changeScreenToList(); } } else { TimerDbUtil.update(getContext(), mUnit, ItemContract.ItemEntry.STATUS_TODO, mId); } } public boolean isTaskComplete() { return mUnit == mTotalUnit; } public void setTimerTimeName() { timerCounter = SharedPreferenceUtil.get(getContext(), "COUNT", 1); if (isLongBreakTime()) {// assign time by work,short & long break runTime = SharedPreferenceUtil.get(getContext(), LONGBREAKTIME, 20); mItemNameText.setText("Long Break Time"); } else if (isWorkTime()) { runTime = SharedPreferenceUtil.get(getContext(), WORKTIME, 25); mItemNameText.setText(mName); } else { runTime = SharedPreferenceUtil.get(getContext(), BREAKTIME, 5); mItemNameText.setText("Break Time"); } } @Override public void onStart() { super.onStart(); intent = new Intent(getActivity(), TimerService.class); if (TimerService.mTimerServiceFinished) { onUnitFinish(); } getActivity().bindService(intent, mConnection, Context.BIND_AUTO_CREATE); } /*Defines callbacks for service binding, passed to bindService()*/ private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder service) { // We've bound to LocalService, cast the IBinder and get LocalService instance mTimerService = ((TimerService.MyBinder) service).getService(); mServiceBound = true; } @Override public void onServiceDisconnected(ComponentName arg0) { mTimerService = null; //mTimerService.stopCountNotification(); progressBar.setProgress(0); timerHandler.removeMessages(0); mItemNameText.setText(""); stateButton.setEnabled(false); mServiceBound = false; } }; @Override public void onResume() { super.onResume(); getActivity().registerReceiver(mReceiver, new IntentFilter(mTimerService.strReceiver)); if (SharedPreferenceUtil.get(getContext(), CONTINUOUS_OPTION, false) && !isTaskComplete() && stateButton.getText().toString().equals("start")) { mTimerService.stopCountNotification(); getActivity().stopService(intent); //stop service stopUpdateLeftTime(); progressBar.setProgress(0); timerHandler.removeMessages(0); progressBarValue = 0; //must be set 0 stateButton.setText(R.string.start); /*set mStatus to TO DO(0)*/ TimerDbUtil.update(getContext(), ItemContract.ItemEntry.STATUS_TODO, mId, false); setTimerTimeName(); stateButton.performClick(); } } public void setStatusToDo() { /*set mStatus to TO DO(0)*/ if (stateButton.getText().toString().equals("stop")) { TimerDbUtil.update(getContext(), ItemContract.ItemEntry.STATUS_TODO, mId, false); } } public boolean isLongBreakTime() { int session = SharedPreferenceUtil.get(getContext(), SESSION, 4) * 2; return timerCounter % session == 0; } public boolean isWorkTime() { return timerCounter % 2 == 1; } Button.OnClickListener stateChecker = new View.OnClickListener() { @Override public void onClick(View v) { if (stateButton.getText().toString().equals("start")) { // checked //mUnit will be intialize when list item is clicked if (mServiceBound) { /* set mStatus DB to DO(1)*/ TimerDbUtil.update(getContext(), ItemContract.ItemEntry.STATUS_DO, mId, false); setTimerTimeName(); progressBar.setMax(runTime * 60 + 3); // setMax by sec timerHandler = new TimerHandler(); mTimerService.setRunTimeTaskName(runTime, mItemNameText.getText().toString()); updateLeftTime(); stateButton.setText(R.string.stop); timerHandler.sendEmptyMessage(0); } } else { mTimerService.stopCountNotification(); getActivity().stopService(intent); //stop service stopUpdateLeftTime(); progressBar.setProgress(0); timerHandler.removeMessages(0); progressBarValue = 0; //must be set 0 stateButton.setText(R.string.start); /*set mStatus to TO DO(0)*/ TimerDbUtil.update(getContext(), ItemContract.ItemEntry.STATUS_TODO, mId, false); } } }; public void updateLeftTime() { mReadThread = new Thread(new Runnable() { @Override public void run() { while (mTimerService.getRun()) { //check out if it is still available if (getActivity() == null) return; try { getActivity().runOnUiThread(new Runnable() { @Override public void run() { leftTime.setText(mTimerService.getTime()); } }); Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); //back to list } } } }); mReadThread.start(); } public void stopUpdateLeftTime() { mReadThread.interrupt(); leftTime.setText(""); } public class TimerHandler extends Handler { TimerHandler() { super(); } @Override public void handleMessage(android.os.Message msg) { if (mTimerService.getRun()) { progressBarValue++; progressBar.bringToFront(); progressBar.setProgress(progressBarValue); timerHandler.sendEmptyMessageDelayed(0, 1000); //increase by sec } else { // Timer must be finished progressBar.setProgress(0); progressBarValue = 0; } } } @Override public void onStop() { super.onStop(); setStatusToDo(); } @Override public void onDestroy() { super.onDestroy(); if (mServiceBound) { mTimerService.stopService(intent); getActivity().unbindService(mConnection); mServiceBound = false; } } public void setTimerFragment(int mId, int mStatus, int mUnit, int mTotalUnit, String mName) { this.mId = mId; this.mStatus = mStatus; this.mUnit = mUnit; this.mTotalUnit = mTotalUnit; this.mName = mName; this.stateButton.setEnabled(true); if (timerCounter % 2 == 1) { //should keep setting when the breakTimer hasn't run yet mItemNameText.setText(mName); } } public void setDeleteItemDisable(int dId) { //once the Item became deleted if (dId == mId) { /*set the button disable*/ stateButton.setEnabled(false); mItemNameText.setText("Deleted"); } } }
package com.malhartech.stram.cli; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.LinkedList; import java.util.List; import javax.ws.rs.core.MediaType; import jline.ArgumentCompletor; import jline.Completor; import jline.ConsoleReader; import jline.FileNameCompletor; import jline.History; import jline.MultiCompletor; import jline.SimpleCompletor; import org.apache.commons.lang.StringUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.yarn.api.protocolrecords.GetAllApplicationsRequest; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ApplicationReport; import org.apache.hadoop.yarn.api.records.FinalApplicationStatus; import org.apache.hadoop.yarn.api.records.YarnApplicationState; import org.apache.hadoop.yarn.exceptions.YarnRemoteException; import org.apache.hadoop.yarn.util.Records; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.malhartech.stram.cli.StramAppLauncher.AppConfig; import com.malhartech.stram.cli.StramClientUtils.ClientRMHelper; import com.malhartech.stram.cli.StramClientUtils.YarnClientHelper; import com.malhartech.stram.webapp.StramWebServices; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; /** * * Provides command line interface for a streaming application on hadoop (yarn)<p> * <br> * <table border=1 cellspacing=0> * <caption>Currently supported Commands</caption> * <thead> * <tr align=center><th width=10%><b>Command</b></th><th width=20%><b>Parameters</b></th><th width=70%><b>Description</b></th></tr> * </thead><tbody> * <tr><td><b>help</b></td><td></td><td>prints help on all cli commands</td></tr> * <tr><td><b>ls</b></td><td></td><td>lists all current running applications</td></tr> * <tr><td><b>connect</b></td><td>appId</td><td>Connects to the given application</td></tr> * <tr><td><b>listoperators</b></td><td></td><td>Lists deployed streaming operators</td></tr> * <tr><td><b>launch</b></td><td>jarFile [, topologyFile ]</td><td>Launch topology packaged in jar file</td></tr> * <tr><td><b>timeout</b></td><td>duration</td><td>Wait for completion of current application</td></tr> * <tr><td><b>kill</b></td><td></td><td>Force termination for current application</td></tr> * <tr><td><b>exit</b></td><td></td><td>Exit the app</td></tr> * </tbody> * </table> * <br> */ public class StramCli { private static final Logger LOG = LoggerFactory.getLogger(StramCli.class); private final Configuration conf = new Configuration(); private final ClientRMHelper rmClient; private ApplicationReport currentApp = null; private String currentDir = "/"; private class CliException extends RuntimeException { private static final long serialVersionUID = 1L; CliException(String msg, Throwable cause) { super(msg, cause); } CliException(String msg) { super(msg); } } public StramCli() throws Exception { YarnClientHelper yarnClient = new YarnClientHelper(conf); rmClient = new ClientRMHelper(yarnClient); } public void init() { } public void run() throws IOException { printWelcomeMessage(); ConsoleReader reader = new ConsoleReader(); reader.setBellEnabled(false); String[] commandsList = new String[]{"help", "ls", "cd", "listoperators", "shutdown", "timeout", "kill", "exit"}; List<Completor> completors = new LinkedList<Completor>(); completors.add(new SimpleCompletor(commandsList)); List<Completor> launchCompletors = new LinkedList<Completor>(); launchCompletors.add(new SimpleCompletor(new String[] {"launch", "launch-local"})); launchCompletors.add(new FileNameCompletor()); // jarFile launchCompletors.add(new FileNameCompletor()); // topology completors.add(new ArgumentCompletor(launchCompletors)); reader.addCompletor(new MultiCompletor(completors)); File historyFile = new File(StramClientUtils.getSettingsRootDir(), ".history"); historyFile.getParentFile().mkdirs(); try { History history = new History(historyFile); reader.setHistory(history); } catch (IOException exp) { System.err.printf("Unable to open %s for writing.", historyFile); } String line; PrintWriter out = new PrintWriter(System.out); while ((line = readLine(reader, "")) != null) { try { if ("help".equals(line)) { printHelp(); } else if (line.startsWith("ls")) { ls(line); } else if (line.startsWith("connect") || line.startsWith("cd")) { connect(line); } else if (line.startsWith("listoperators")) { listOperators(null); } else if (line.startsWith("launch")) { launchApp(line, reader); } else if (line.startsWith("shutdown")) { shutdownApp(line); } else if (line.startsWith("timeout")) { timeoutApp(line, reader); } else if (line.startsWith("kill")) { killApp(line); } else if ("exit".equals(line)) { System.out.println("Exiting application"); return; } else { System.err.println("Invalid command, For assistance press TAB or type \"help\" then hit ENTER."); } } catch (CliException e) { System.err.println(e.getMessage()); LOG.info("Error processing line: " + line, e); } catch (Exception e) { System.err.println("Unexpected error: " + e.getMessage()); e.printStackTrace(); } out.flush(); } } private void printWelcomeMessage() { System.out.println("Stram CLI. For assistance press TAB or type \"help\" then hit ENTER."); } private void printHelp() { System.out.println("help - Show help"); System.out.println("ls - Show running applications"); System.out.println("connect <appId> - Connect to running streaming application"); System.out.println("listoperators - List deployed streaming operators"); System.out.println("launch <jarFile> [<topologyFile>] - Launch topology packaged in jar file."); System.out.println("timeout <duration> - Wait for completion of current application."); System.out.println("kill - Force termination for current application."); System.out.println("exit - Exit the app"); } private String readLine(ConsoleReader reader, String promtMessage) throws IOException { String line = reader.readLine(promtMessage + "\nstramcli> "); return line.trim(); } private String[] assertArgs(String line, int num, String msg) { String[] args = StringUtils.splitByWholeSeparator(line, " "); if (args.length < num) { throw new CliException(msg); } return args; } private int getIntArg(String line, int argIndex, String msg) { String[] args = assertArgs(line, argIndex + 1, msg); try { int arg = Integer.parseInt(args[argIndex]); return arg; } catch (Exception e) { throw new CliException("Not a valid number: " + args[argIndex]); } } private List<ApplicationReport> getApplicationList() { try { GetAllApplicationsRequest appsReq = Records.newRecord(GetAllApplicationsRequest.class); return rmClient.clientRM.getAllApplications(appsReq).getApplicationList(); } catch (Exception e) { throw new CliException("Error getting application list from resource manager: " + e.getMessage(), e); } } private void ls(String line) throws JSONException { String[] args = StringUtils.splitByWholeSeparator(line, " "); for (int i = args.length; i args[i] = args[i].trim(); } if (args.length == 2 && args[1].equals("/") || currentDir.equals("/")) { listApplications(args); } else { listOperators(args); } } private void listApplications(String[] args) { try { List<ApplicationReport> appList = getApplicationList(); Collections.sort(appList, new Comparator<ApplicationReport>() { @Override public int compare(ApplicationReport o1, ApplicationReport o2) { return o1.getApplicationId().getId() - o2.getApplicationId().getId(); } }); System.out.println("Applications:"); int totalCnt = 0; int runningCnt = 0; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); for (ApplicationReport ar : appList) { boolean show; /* * This is inefficient, but what the heck, if this can be passed through the command line, can anyone notice slowness. */ if (args.length == 1 || args.length == 2 && (args[1].equals("/") || args[1].equals(".."))) { show = true; } else { show = false; String appid = String.valueOf(ar.getApplicationId().getId()); for (int i = args.length; i if (appid.equals(args[i])) { show = true; break; } } } if (show) { StringBuilder sb = new StringBuilder(); sb.append("startTime: ").append(sdf.format(new java.util.Date(ar.getStartTime()))). append(", id: ").append(ar.getApplicationId().getId()). append(", name: ").append(ar.getName()). append(", state: ").append(ar.getYarnApplicationState().name()). append(", trackingUrl: ").append(ar.getTrackingUrl()). append(", finalStatus: ").append(ar.getFinalApplicationStatus()); System.out.println(sb); totalCnt++; if (ar.getYarnApplicationState() == YarnApplicationState.RUNNING) { runningCnt++; } } } System.out.println(runningCnt + " active, total " + totalCnt + " applications."); } catch (Exception ex) { throw new CliException("Failed to retrieve application list", ex); } } private ApplicationReport assertRunningApp(ApplicationReport app) { ApplicationReport r; try { r = rmClient.getApplicationReport(app.getApplicationId()); if (r.getYarnApplicationState() != YarnApplicationState.RUNNING) { String msg = String.format("Application %s not running (status %s)", r.getApplicationId().getId(), r.getYarnApplicationState()); throw new CliException(msg); } } catch (YarnRemoteException rmExc) { throw new CliException("Unable to determine application status.", rmExc); } return r; } private ClientResponse getResource(String resourcePath) { if (currentApp == null) { throw new CliException("No application selected"); } if (StringUtils.isEmpty(currentApp.getTrackingUrl()) || currentApp.getFinalApplicationStatus() != FinalApplicationStatus.UNDEFINED) { currentApp = null; currentDir = "/"; throw new CliException("Application terminated."); } Client wsClient = Client.create(); wsClient.setFollowRedirects(true); WebResource r = wsClient.resource("http://" + currentApp.getTrackingUrl()).path(StramWebServices.PATH).path(resourcePath); try { ClientResponse response = r.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); if (!MediaType.APPLICATION_JSON_TYPE.equals(response.getType())) { throw new Exception("Unexpected response type " + response.getType()); } return response; } catch (Exception e) { // check the application status as above may have failed due application termination etc. currentApp = assertRunningApp(currentApp); throw new CliException("Failed to request " + r.getURI(), e); } } private void connect(String line) { String[] args = StringUtils.splitByWholeSeparator(line, " "); if (args.length != 2) { System.err.println("Invalid arguments"); return; } if ("..".equals(args[1]) || "/".equals(args[1])) { currentDir = "/"; return; } else { currentDir = args[1]; } int appSeq = Integer.parseInt(args[1]); List<ApplicationReport> appList = getApplicationList(); for (ApplicationReport ar : appList) { if (ar.getApplicationId().getId() == appSeq) { currentApp = ar; break; } } if (currentApp == null) { throw new CliException("Invalid application id: " + args[1]); } boolean connected = false; try { LOG.info("Selected {} with tracking url: ", currentApp.getApplicationId(), currentApp.getTrackingUrl()); ClientResponse rsp = getResource(StramWebServices.PATH_INFO); JSONObject json = rsp.getEntity(JSONObject.class); System.out.println(json.toString(2)); connected = true; // set as current only upon successful connection } catch (CliException e) { throw e; // pass on } catch (JSONException e) { throw new CliException("Error connecting to app " + args[1], e); } finally { if (!connected) { //currentApp = null; //currentDir = "/"; } } } private void listOperators(String[] argv) throws JSONException { ClientResponse rsp = getResource(StramWebServices.PATH_OPERATORS); JSONObject json = rsp.getEntity(JSONObject.class); if (argv.length > 1) { String singleKey = ""+json.keys().next(); JSONArray matches = new JSONArray(); // filter operators JSONArray arr = json.getJSONArray(singleKey); for (int i=0; i<arr.length(); i++) { Object val = arr.get(i); if (val.toString().matches(argv[1])) { matches.put(val); } } json.put(singleKey, matches); } System.out.println(json.toString(2)); } private void launchApp(String line, ConsoleReader reader) { String[] args = assertArgs(line, 2, "No jar file specified."); boolean localMode = "launch-local".equals(args[0]); AppConfig appConfig = null; if (args.length == 3) { File file = new File(args[2]); appConfig = new StramAppLauncher.PropertyFileAppConfig(file); } try { StramAppLauncher submitApp = new StramAppLauncher(new File(args[1])); if (appConfig == null) { List<AppConfig> cfgList = submitApp.getBundledTopologies(); if (cfgList.isEmpty()) { throw new CliException("No configurations bundled in jar, please specify one"); } else if (cfgList.size() == 1) { appConfig = cfgList.get(0); } else { for (int i = 0; i < cfgList.size(); i++) { System.out.printf("%3d. %s\n", i + 1, cfgList.get(i).getName()); } boolean useHistory = reader.getUseHistory(); reader.setUseHistory(false); @SuppressWarnings("unchecked") List<Completor> completors = new ArrayList<Completor>(reader.getCompletors()); for (Completor c : completors) { reader.removeCompletor(c); } String optionLine = reader.readLine("Pick configuration? "); reader.setUseHistory(useHistory); for (Completor c : completors) { reader.addCompletor(c); } try { int option = Integer.parseInt(optionLine); if (0 < option && option <= cfgList.size()) { appConfig = cfgList.get(option - 1); } } catch (Exception e) { // ignore } } } if (appConfig != null) { if (!localMode) { ApplicationId appId = submitApp.launchApp(appConfig); this.currentApp = rmClient.getApplicationReport(appId); this.currentDir = "" + currentApp.getApplicationId().getId(); System.out.println(appId); } else { submitApp.runLocal(appConfig); } } else { System.err.println("No topology specified."); } } catch (Exception e) { throw new CliException("Failed to launch " + args[1] + ": " + e.getMessage(), e); } } private void killApp(String line) { if (currentApp == null) { throw new CliException("No application selected"); } try { rmClient.killApplication(currentApp.getApplicationId()); currentDir = "/"; currentApp = null; } catch (YarnRemoteException e) { throw new CliException("Failed to kill " + currentApp.getApplicationId(), e); } } private void shutdownApp(String line) { if (currentApp == null) { throw new CliException("No application selected"); } // WebAppProxyServlet does not support POST - for now bypass it for this request currentApp = assertRunningApp(currentApp); // or else "N/A" might be there.. String trackingUrl = currentApp.getOriginalTrackingUrl(); Client wsClient = Client.create(); wsClient.setFollowRedirects(true); WebResource r = wsClient.resource("http://" + trackingUrl).path(StramWebServices.PATH).path(StramWebServices.PATH_SHUTDOWN); try { JSONObject response = r.accept(MediaType.APPLICATION_JSON).post(JSONObject.class); System.out.println("shutdown requested: " + response); currentDir = "/"; currentApp = null; } catch (Exception e) { throw new CliException("Failed to request " + r.getURI(), e); } } private void timeoutApp(String line, final ConsoleReader reader) { if (currentApp == null) { throw new CliException("No application selected"); } int timeout = getIntArg(line, 1, "Specify wait duration"); ClientRMHelper.AppStatusCallback cb = new ClientRMHelper.AppStatusCallback() { @Override public boolean exitLoop(ApplicationReport report) { System.out.println("current status is: " + report.getYarnApplicationState()); try { if (reader.getInput().available() > 0) { return true; } } catch (IOException e) { LOG.error("Error checking for input.", e); } return false; } }; try { boolean result = rmClient.waitForCompletion(currentApp.getApplicationId(), cb, timeout * 1000); if (!result) { System.err.println("Application terminated unsucessful."); } } catch (YarnRemoteException e) { throw new CliException("Failed to kill " + currentApp.getApplicationId(), e); } } public static void main(String[] args) throws Exception { StramCli shell = new StramCli(); shell.init(); shell.run(); } }
package org.reldb.dbrowser.ui; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Vector; import org.reldb.rel.client.Connection.ExecuteResult; import org.reldb.rel.client.Tuple; import org.reldb.rel.client.Tuples; import org.reldb.rel.client.Value; import org.reldb.rel.utilities.StringUtils; public class RevDatabase { public static final int EXPECTED_REV_VERSION = 0; public static final int QUERY_WAIT_MILLISECONDS = 5000; private DbConnection connection; public RevDatabase(DbConnection connection) { this.connection = connection; } public Value evaluate(String query) { return connection.evaluate(query); } public int hasRevExtensions() { return connection.hasRevExtensions(); } public long getUniqueNumber() { return connection.evaluate("GET_UNIQUE_NUMBER()").toLong(); } public ExecuteResult exec(String query) { return connection.execute(query); } private boolean execute(String query) { ExecuteResult result = connection.execute(query); if (result.failed()) { System.out.println("Rev: Error: " + result.getErrorMessage()); System.out.println("Rev: Query: " + query); return false; } return true; } private Tuples getTuples(String query) { return connection.getTuples(query); } public boolean installRevExtensions() { String query = "var sys.rev.Version real relation {" + " ver INTEGER" + "} INIT(relation {tuple {ver " + EXPECTED_REV_VERSION + "}}) key {ver};" + "var sys.rev.Settings real relation {" + " Name CHAR, " + " value CHAR " + "} key {Name};" + "var sys.rev.Relvar real relation {" + " Name CHAR, " + " relvarName CHAR, " + " xpos INTEGER, " + " ypos INTEGER, " + " model CHAR" + "} key {Name};" + "var sys.rev.Query real relation {" + " Name CHAR, " + " xpos INTEGER, " + " ypos INTEGER, " + " kind CHAR, " + " connections RELATION {" + " parameter INTEGER, " + " Name CHAR" + " }," + " model CHAR" + "} key {Name};" + "var sys.rev.Script real relation {" + " Name CHAR, " + " text CHAR " + "} key {Name};" + "var sys.rev.ScriptHistory real relation {" + " Name CHAR, " + " text CHAR, " + " timestamp CHAR " + "} key {Name, timestamp};" + "var sys.rev.Operator real relation {" + " Name CHAR, " + " Definition CHAR" + "} key {Name};" + "var sys.rev.Op_Update real relation {" + " Name CHAR, " + " Definition RELATION {" + " ID INTEGER," + " attribute CHAR," + " expression CHAR" + " }" + "} key {Name};" + "var sys.rev.Op_Extend real relation {" + " Name CHAR, " + " Definition RELATION {" + " ID INTEGER," + " attribute CHAR," + " expression CHAR" + " }" + "} key {Name};" + "var sys.rev.Op_Summarize real relation {" + " Name CHAR, " + " isby BOOLEAN, " + " byList CHAR, " + " Definition RELATION {" + " ID INTEGER, " + " asAttribute CHAR, " + " aggregateOp CHAR, " + " expression1 CHAR, " + " expression2 CHAR " + " }" + "} key {Name};"; return execute(query); } public boolean removeRevExtensions() { String query = "drop var sys.rev.Operator;" + "drop var sys.rev.Op_Update;" + "drop var sys.rev.Op_Extend;" + "drop var sys.rev.Op_Summarize;" + "drop var sys.rev.Script;" + "drop var sys.rev.ScriptHistory;" + "drop var sys.rev.Query;" + "drop var sys.rev.Relvar;" + "drop var sys.rev.Settings;" + "drop var sys.rev.Version;"; return execute(query); } public Tuples getRelvars() { String query = "sys.Catalog {Name, Owner}"; return getTuples(query); } public Tuples getRelvars(String model) { String query = "sys.rev.Relvar WHERE model = \"" + model + "\""; return getTuples(query); } public Tuples getQueries(String model) { String query = "sys.rev.Query WHERE model = \"" + model + "\""; return getTuples(query); } // Update relvar position public void updateRelvarPosition(String name, String relvarName, int x, int y, String model) { String query = "DELETE sys.rev.Relvar where Name=\"" + name + "\", " + "INSERT sys.rev.Relvar relation {tuple {Name \"" + name + "\", relvarName \"" + relvarName + "\", xpos " + x + ", ypos " + y + ", model \"" + model + "\"}};"; execute(query); } // Update query operator position public void updateQueryPosition(String name, int x, int y, String kind, String connections, String model) { String query = "DELETE sys.rev.Query where Name=\"" + name + "\", " + "INSERT sys.rev.Query relation {tuple {" + "Name \"" + name + "\", " + "xpos " + x + ", " + "ypos " + y + ", " + "kind \"" + kind + "\", " + "connections " + connections + ", " + "model \"" + model + "\"" + "}};"; execute(query); } // Preserved States // Most operators public Tuples getPreservedStateOperator(String name) { String query = "sys.rev.Operator WHERE Name = \"" + name + "\""; return getTuples(query); } public void updatePreservedStateOperator(String name, String definition) { String query = "DELETE sys.rev.Operator WHERE Name = \"" + name + "\", " + "INSERT sys.rev.Operator RELATION {" + "TUPLE {Name \"" + name + "\", Definition \"" + definition + "\"}" + "};"; execute(query); } // Update public Tuples getPreservedStateUpdate(String name) { String query = "(sys.rev.Op_Update WHERE Name = \"" + name + "\") UNGROUP Definition ORDER(ASC ID)"; return getTuples(query); } public void updatePreservedStateUpdate(String name, String definition) { String query = "DELETE sys.rev.Op_Update WHERE Name = \"" + name + "\", " + "INSERT sys.rev.Op_Update RELATION {" + " TUPLE {Name \"" + name + "\", Definition " + definition + "}" + "};"; execute(query); } // Extend public Tuples getPreservedStateExtend(String name) { String query = "(sys.rev.Op_Extend WHERE Name = \"" + name + "\") UNGROUP Definition ORDER(ASC ID)"; return getTuples(query); } public void updatePreservedStateExtend(String name, String definition) { String query = "DELETE sys.rev.Op_Extend WHERE Name = \"" + name + "\", " + "INSERT sys.rev.Op_Extend RELATION {" + " TUPLE {Name \"" + name + "\", Definition " + definition + "}" + "};"; execute(query); } // Summarize public Tuples getPreservedStateSummarize(String name) { String query = "(sys.rev.Op_Summarize WHERE Name = \"" + name + "\") UNGROUP Definition ORDER(ASC ID)"; return getTuples(query); } public void updatePreservedStateSummarize(String name, String definition) { String query = "DELETE sys.rev.Op_Summarize WHERE Name = \"" + name + "\", " + "INSERT sys.rev.Op_Summarize RELATION {" + " TUPLE {Name \"" + name + "\", isby false, byList \"\", Definition " + definition + "}" + "};"; execute(query); } public void updatePreservedStateSummarize(String name, String byList, String definition) { String query = "DELETE sys.rev.Op_Summarize WHERE Name = \"" + name + "\", " + "INSERT sys.rev.Op_Summarize RELATION {" + " TUPLE {Name \"" + name + "\", isby true, byList \"" + byList + "\", Definition " + definition + "}" + "};"; execute(query); } public void removeQuery(String name) { String query = "DELETE sys.rev.Query WHERE Name = \"" + name + "\";"; execute(query); } public void removeRelvar(String name) { String query = "DELETE sys.rev.Relvar WHERE Name = \"" + name + "\";"; execute(query); } public void removeOperator(String name) { String query = "DELETE sys.rev.Operator WHERE Name = \"" + name + "\";"; execute(query); } public void removeOperator_Update(String name) { String query = "DELETE sys.rev.Op_Update WHERE Name = \"" + name + "\";"; execute(query); } public void removeOperator_Extend(String name) { String query = "DELETE sys.rev.Op_Extend WHERE Name = \"" + name + "\";"; execute(query); } public void removeOperator_Summarize(String name) { String query = "DELETE sys.rev.Op_Summarize WHERE Name = \"" + name + "\";"; execute(query); } public boolean modelExists(String name) { String query = "COUNT(((sys.rev.Query {model}) UNION (sys.rev.Relvar {model})) WHERE model = \"" + name + "\") > 0"; return evaluate(query).toBoolean(); } public void modelRename(String oldName, String newName) { if (oldName.equals(newName)) return; String query = "DELETE sys.rev.Query WHERE model = \"" + newName + "\", " + "DELETE sys.rev.Relvar WHERE model = \"" + newName + "\", " + "UPDATE sys.rev.Query WHERE model = \"" + oldName + "\": {model := \"" + newName + "\"}, " + "UPDATE sys.rev.Relvar WHERE model = \"" + oldName + "\": {model := \"" + newName + "\"};"; execute(query); } public void modelCopyTo(String oldName, String newName) { if (oldName.equals(newName)) return; String query = "DELETE sys.rev.Query WHERE model = \"" + newName + "\", " + "DELETE sys.rev.Relvar WHERE model = \"" + newName + "\", " + "INSERT sys.rev.Operator UPDATE sys.rev.Operator JOIN (((sys.rev.Query WHERE model = \"" + oldName + "\") {Name}) UNION ((sys.rev.Relvar WHERE model = \"" + oldName + "\") {Name})): {Name := Name || \"copy\"}, " + "INSERT sys.rev.Op_Update UPDATE sys.rev.Op_Update JOIN (((sys.rev.Query WHERE model = \"" + oldName + "\") {Name}) UNION ((sys.rev.Relvar WHERE model = \"" + oldName + "\") {Name})): {Name := Name || \"copy\"}, " + "INSERT sys.rev.Op_Extend UPDATE sys.rev.Op_Extend JOIN (((sys.rev.Query WHERE model = \"" + oldName + "\") {Name}) UNION ((sys.rev.Relvar WHERE model = \"" + oldName + "\") {Name})): {Name := Name || \"copy\"}, " + "INSERT sys.rev.Op_Summarize UPDATE sys.rev.Op_Summarize JOIN (((sys.rev.Query WHERE model = \"" + oldName + "\") {Name}) UNION ((sys.rev.Relvar WHERE model = \"" + oldName + "\") {Name})): {Name := Name || \"copy\"}, " + "INSERT sys.rev.Query UPDATE sys.rev.Query WHERE model = \"" + oldName + "\": {model := \"" + newName + "\", Name := Name || \"copy\", connections := UPDATE connections: {Name := Name || \"copy\"}}, " + "INSERT sys.rev.Relvar UPDATE sys.rev.Relvar WHERE model = \"" + oldName + "\": {model := \"" + newName + "\", Name := Name || \"copy\"};"; execute(query); } public boolean modelDelete(String name) { String query = "DELETE sys.rev.Operator WHERE TUPLE {Name Name} IN ((sys.rev.Query WHERE model = \"" + name + "\") {Name}) UNION ((sys.rev.Relvar WHERE model = \"" + name + "\") {Name}), " + "DELETE sys.rev.Op_Update WHERE TUPLE {Name Name} IN ((sys.rev.Query WHERE model = \"" + name + "\") {Name}) UNION ((sys.rev.Relvar WHERE model = \"" + name + "\") {Name}), " + "DELETE sys.rev.Op_Extend WHERE TUPLE {Name Name} IN ((sys.rev.Query WHERE model = \"" + name + "\") {Name}) UNION ((sys.rev.Relvar WHERE model = \"" + name + "\") {Name}), " + "DELETE sys.rev.Op_Summarize WHERE TUPLE {Name Name} IN ((sys.rev.Query WHERE model = \"" + name + "\") {Name}) UNION ((sys.rev.Relvar WHERE model = \"" + name + "\") {Name}), " + "DELETE sys.rev.Query WHERE model = \"" + name + "\", " + "DELETE sys.rev.Relvar WHERE model = \"" + name + "\";"; return execute(query); } public Vector<String> getModels() { String query = "(sys.rev.Query {model}) UNION (sys.rev.Relvar {model})"; Tuples tuples = (Tuples)evaluate(query); Vector<String> models = new Vector<String>(); for (Tuple tuple: tuples) models.add(tuple.get("model").toString()); return models; } public boolean relvarExists(String name) { String query = "COUNT(sys.Catalog WHERE Name = \"" + name + "\") > 0"; Value result = (Value)evaluate(query); return result.toBoolean(); } public boolean scriptExists(String name) { String query = "COUNT(sys.rev.Script WHERE Name = \"" + name + "\") > 0"; Value result = (Value)evaluate(query); return result.toBoolean(); } public boolean createScript(String name) { String query = "INSERT sys.rev.Script RELATION {TUPLE {Name \"" + name + "\", text \"\"}};"; return execute(query); } public static class Script { private String content; private Vector<String> history; public Script(String content, Vector<String> history) { this.content = content; this.history = history; } public Vector<String> getHistory() { return history; } public String getContent() { return content; } } public Script getScript(String name) { String query = "sys.rev.Script WHERE Name=\"" + name + "\""; String content = ""; Tuples tuples = (Tuples)evaluate(query); for (Tuple tuple: tuples) { String rawContent = tuple.get("text").toString(); content = rawContent; } query = "sys.rev.ScriptHistory WHERE Name=\"" + name + "\" ORDER (ASC timestamp)"; tuples = (Tuples)evaluate(query); Vector<String> history = new Vector<String>(); for (Tuple tuple: tuples) { String rawContent = tuple.get("text").toString(); history.add(rawContent); } return new Script(content, history); } public void setScript(String name, String content) { String text = StringUtils.quote(content); String query = "IF COUNT(sys.rev.Script WHERE Name=\"" + name + "\") = 0 THEN " + " INSERT sys.rev.Script REL {TUP {Name \"" + name + "\", text \"" + text + "\"}}; " + "ELSE " + " UPDATE sys.rev.Script WHERE Name=\"" + name + "\": {text := \"" + text + "\"}; " + "END IF;"; execute(query); } public void addScriptHistory(String name, String historyItem) { String timestamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss.SSS").format(new Date()); String query = "INSERT sys.rev.ScriptHistory " + "REL {TUP {" + " Name \"" + name + "\", " + " text \"" + StringUtils.quote(historyItem) + "\", " + " timestamp \"" + timestamp + "\"" + "}};"; execute(query); } public boolean scriptDelete(String name) { String query = "DELETE sys.rev.Script WHERE Name=\"" + name + "\";"; return execute(query); } public boolean renameScript(String nameFrom, String nameTo) { String query = "UPDATE sys.rev.Script WHERE Name=\"" + nameFrom + "\": {Name := \"" + nameTo + "\"}, " + "UPDATE sys.rev.ScriptHistory WHERE Name=\"" + nameFrom + "\": {Name := \"" + nameTo + "\"};"; return execute(query); } public void setSetting(String name, String value) { String query = "IF COUNT(sys.rev.Settings WHERE Name=\"" + name + "\") = 0 THEN " + " INSERT sys.rev.Settings REL {TUP {Name \"" + name + "\", value \"" + StringUtils.quote(value) + "\"}}; " + "ELSE " + " UPDATE sys.rev.Settings WHERE Name=\"" + name + "\": {value := \"" + StringUtils.quote(value) + "\"}; " + "END IF;"; execute(query); } public String getSetting(String name) { String query = "sys.rev.Settings WHERE Name=\"" + name + "\""; Tuples tuples = (Tuples)evaluate(query); for (Tuple tuple: tuples) return tuple.get("value").toString(); return ""; } public static class Overview { private String content; private boolean revPrompt; public Overview(String content, boolean revPrompt) { this.content = content; this.revPrompt = revPrompt; } public String getContent() { return content; } public boolean getRevPrompt() { return revPrompt; } } public Overview getOverview() { String query = "pub.Overview"; Tuples tuples = (Tuples)evaluate(query); try { for (Tuple tuple: tuples) { String content = tuple.get("content").toString(); boolean revPrompt = tuple.get("revPrompt").toBoolean(); return new Overview(content, revPrompt); } } catch (Exception e) {} return new Overview("", true); } public boolean createOverview() { String query = "VAR pub.Overview REAL RELATION {content CHAR, revPrompt BOOLEAN} KEY {}; " + "INSERT pub.Overview RELATION {TUP {content \"" + StringUtils.quote( "Edit the pub.Overview variable to change this text.\n" + "The \"contents\" attribute value will appear here.\n" + "Set the \"revPrompt\" attribute to FALSE to only display this overview." ) + "\", revPrompt TRUE}};"; return execute(query); } public String[] getKeywords() { return connection.getKeywords(); } public String[] getRelvarTypes() { String query = "UNION {sys.ExternalRelvarTypes {Identifier, Description}, REL {TUP {Identifier \"REAL\", Description \"REAL relation-valued variable.\"}}} ORDER (ASC Identifier)"; Tuples tuples = (Tuples)evaluate(query); Vector<String> types = new Vector<String>(); try { for (Tuple tuple: tuples) { String identifier = tuple.get("Identifier").toString(); String description = tuple.get("Description").toString(); types.add(identifier + ": " + description); } } catch (Exception e) {} return types.toArray(new String[0]); } public Tuple getExternalRelvarTypeInfo(String variableType) { String query = "sys.ExternalRelvarTypes WHERE Identifier=\"" + variableType + "\""; Tuples tuples = (Tuples)evaluate(query); for (Tuple tuple: tuples) return tuple; return null; } }
/** * Class to interface with the SCP1000 pressure and temperature sensor. */ package test.fuyuton; import jp.nyatla.mimic.mbedjs.MbedJsException; import jp.nyatla.mimic.mbedjs.javaapi.Mcu; import jp.nyatla.mimic.mbedjs.javaapi.PinName; import jp.nyatla.mimic.mbedjs.javaapi.SPI; import jp.nyatla.mimic.mbedjs.javaapi.DigitalOut; import jp.nyatla.mimic.mbedjs.javaapi.DigitalIn; import jp.nyatla.mimic.mbedjs.javaapi.driver.DriverBaseClass; public class SCP1000 extends DriverBaseClass { private Mcu _mcu; private final SPI _spi; private final DigitalOut _cs; private final DigitalIn _drdy; private final boolean _is_attached; private final static int REG_OPERATION = 0x03; private final static int MODE_HIRESO = 0x0A; private final static int REG_RSTR = 0x06; private final static int RST_SOFTRESET = 0x01; private final static int REG_PRESSURE = 0x1F; //Pressure 3 MSB private final static int REG_PRESSURE_LSB = 0x20; //Pressure 16 LSB private final static int REG_TEMP = 0x21; //16 bit temp /** * SPI? * @param i_spi * @throws MbedJsException */ public SCP1000(SPI i_spi, int i_cs_pin, int i_drdy_pin) throws MbedJsException { this._is_attached=false; this._spi=i_spi; this._cs=new DigitalOut(_mcu, i_cs_pin); this._drdy=new DigitalIn(_mcu, i_drdy_pin); this._initDevice(); } /** * Constructor. * MCU * PDGNDPower management * @param i_mcu * @param i_mosi_pin SPI MOSI pin * @param i_miso_pin SPI MISO pin * @param i_sclk_pin SPI SCLK pin * @param i_cs_pin Chip select pin * @param i_drdy_pin DataReady pin * @param i_trig_pin Trigger pin * @throws MbedJsException */ public SCP1000(Mcu i_mcu, int i_mosi_pin, int i_miso_pin, int i_sclk_pin, int i_cs_pin, int i_drdy_pin) throws MbedJsException { this._cs=new DigitalOut(i_mcu, i_cs_pin); this._drdy=new DigitalIn(i_mcu, i_drdy_pin); this._is_attached=true; this._spi=new SPI(i_mcu, i_mosi_pin, i_miso_pin, i_sclk_pin); this._spi.frequency(500000); // the fastest of the sensor this._spi.format(8, 0); // duda son dos palabras de 8 bits? this._initDevice(); } private void _initDevice() throws MbedJsException { this._cs.write(1); this.sleep_ms(60); this.write_register(REG_RSTR,RST_SOFTRESET); this.sleep_ms(90); write_register(REG_OPERATION,MODE_HIRESO); } public void dispose() throws MbedJsException { if(this._is_attached) { this._spi.dispose(); } } /** * * @returns The pressure in pascals. */ public float readPressure() throws MbedJsException { do{ //DRDYHIGH(1) sleep_ms(1); }while(this._drdy.read() != 1); int pressure_msb = read_register(REG_PRESSURE); pressure_msb &= 0x07; int pressure_lsb = read_register16(REG_PRESSURE_LSB); pressure_lsb &= 0x0000ffff; int pressure = ((pressure_msb<<16)| pressure_lsb); float pressure_f = pressure/4.0f/100.0f; return pressure_f; } /** * * @returns The temperature in Celsius. */ public float readTemperature() throws MbedJsException { do{ //DRDYHIGH(1) sleep_ms(1); }while(this._drdy.read() != 1); float temp_in = read_register16(REG_TEMP); temp_in /= 20; return temp_in; } /** * 8bit * @param i_register_name * @throws MbedJsException */ private int read_register(int i_register_name) throws MbedJsException { i_register_name <<= 2; i_register_name &= 0xFC; this._cs.write(0); //Select SPI device this._spi.write(i_register_name); //Send register location int register_value = _spi.write(0x00); this._cs.write(1); return register_value; } /** * 8bit * @param i_register_name * @param i_register_value * @throws MbedJsException */ private void write_register(int i_register_name, int i_register_value) throws MbedJsException { i_register_name &= 0x0ff; i_register_value &= 0x0ff; i_register_name <<= 2; i_register_name |= 0x02; // Write command i_register_name &= 0x0fe; this._cs.write(0); //Select SPI device this._spi.write(i_register_name); //Send register location this._spi.write(i_register_value); //Send value to record into register this._cs.write(1); } /** * 16bit * @param i_register_name * @throws MbedJsException */ private int read_register16(int i_register_name) throws MbedJsException { i_register_name &= 0x000000ff; i_register_name <<= 2; i_register_name &= 0x0FC; //Read command this._cs.write(0); //Select SPI Device this._spi.write(i_register_name); //Write byte to device int in_byte1 = this._spi.write(0x00); int in_byte2 = this._spi.write(0x00); this._cs.write(1); int in_word= (in_byte1<<8) | (in_byte2); in_word &= 0x0000ffff; return(in_word); } /** * * @param args */ public static void main(String args[]) { try { Mcu mcu=new Mcu("192.168.1.39"); SCP1000 a=new SCP1000(mcu, PinName.p11, PinName.p12, PinName.p13, PinName.p14, PinName.p15); System.out.println("Temperature: " + a.readTemperature()+"℃"); System.out.println("Pressure: " + a.readPressure() + "hPa"); mcu.close(); System.out.println("done"); }catch(Exception e){ e.printStackTrace(); } } } /* #endif // _SCP1000_H */
package erogenousbeef.core.multiblock; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; import net.minecraft.block.material.Material; import net.minecraft.client.Minecraft; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; import erogenousbeef.core.common.CoordTriplet; /** * This class contains the base logic for "multiblock controllers". You can think of them * as meta-TileEntities. They govern the logic for an associated group of TileEntities. * * Subordinate TileEntities implement the IMultiblockPart class and, generally, should not have an update() loop. */ public abstract class MultiblockControllerBase { // Multiblock stuff - do not mess with protected World worldObj; // Disassembled -> Assembled; Assembled -> Disassembled OR Paused; Paused -> Assembled protected enum AssemblyState { Disassembled, Assembled, Paused }; protected AssemblyState assemblyState; protected Set<CoordTriplet> connectedBlocks; /** This is a deterministically-picked coordinate that identifies this * multiblock uniquely in its dimension. * Currently, this is the coord with the lowest X, Y and Z coordinates, in that order of evaluation. * i.e. If something has a lower X but higher Y/Z coordinates, it will still be the reference. * If something has the same X but a lower Y coordinate, it will be the reference. Etc. */ protected CoordTriplet referenceCoord; /** * Minimum bounding box coordinate. Blocks do not necessarily exist at this coord if your machine * is not a cube/rectangular prism. */ private CoordTriplet minimumCoord; /** * Maximum bounding box coordinate. Blocks do not necessarily exist at this coord if your machine * is not a cube/rectangular prism. */ private CoordTriplet maximumCoord; /** * Set to true when adding/removing blocks to the controller. * If true, the controller will check to see if the machine * should be assembled/disassembled on the next tick. */ private boolean blocksHaveChangedThisFrame; /** * Set to true when all blocks unloading this frame are unloading due to * chunk unloading. */ private boolean chunksHaveUnloaded; protected MultiblockControllerBase(World world) { // Multiblock stuff worldObj = world; connectedBlocks = new CopyOnWriteArraySet<CoordTriplet>(); // We need this for thread-safety referenceCoord = null; assemblyState = AssemblyState.Disassembled; minimumCoord = new CoordTriplet(0,0,0); maximumCoord = new CoordTriplet(0,0,0); blocksHaveChangedThisFrame = false; chunksHaveUnloaded = false; } /** * Call when the save delegate block finishes loading its chunk. * Immediately call attachBlock after this, or risk your multiblock * being destroyed! * @param savedData The NBT tag containing this controller's data. */ public void restore(NBTTagCompound savedData) { this.readFromNBT(savedData); MultiblockRegistry.register(this); } /** * Check if a block is being tracked by this machine. * @param blockCoord Coordinate to check. * @return True if the tile entity at blockCoord is being tracked by this machine, false otherwise. */ public boolean hasBlock(CoordTriplet blockCoord) { return connectedBlocks.contains(blockCoord); } /** * Call this to attach a block to this machine. Generally, you want to call this when * the block is added to the world. * @param part The part representing the block to attach to this machine. */ public void attachBlock(IMultiblockPart part) { IMultiblockPart candidate; CoordTriplet coord = part.getWorldLocation(); boolean firstBlock = this.connectedBlocks.isEmpty(); // No need to re-add a block if(connectedBlocks.contains(coord)) { return; } connectedBlocks.add(coord); part.onAttached(this); this.onBlockAdded(part); this.worldObj.markBlockForUpdate(coord.x, coord.y, coord.z); if(firstBlock) { MultiblockRegistry.register(this); } if(this.referenceCoord == null) { referenceCoord = coord; part.becomeMultiblockSaveDelegate(); } else if(coord.compareTo(referenceCoord) < 0) { TileEntity te = this.worldObj.getBlockTileEntity(referenceCoord.x, referenceCoord.y, referenceCoord.z); ((IMultiblockPart)te).forfeitMultiblockSaveDelegate(); referenceCoord = coord; part.becomeMultiblockSaveDelegate(); } blocksHaveChangedThisFrame = true; } /** * Called when a new part is added to the machine. Good time to register things into lists. * @param newPart The part being added. */ protected abstract void onBlockAdded(IMultiblockPart newPart); /** * Called when a part is removed from the machine. Good time to clean up lists. * @param oldPart The part being removed. */ protected abstract void onBlockRemoved(IMultiblockPart oldPart); /** * Called when a machine is assembled from a disassembled state. */ protected abstract void onMachineAssembled(); /** * Called when a machine is restored to the assembled state from a paused state. */ protected abstract void onMachineRestored(); /** * Called when a machine is paused from an assembled state * This generally only happens due to chunk-loads and other "system" events. */ protected abstract void onMachinePaused(); /** * Called when a machine is disassembled from an assembled state. * This happens due to user or in-game actions (e.g. explosions) */ protected abstract void onMachineDisassembled(); /** * Call to detach a block from this machine. Generally, this should be called * when the tile entity is being released, e.g. on block destruction. * @param part The part to detach from this machine. * @param chunkUnloading Is this entity detaching due to the chunk unloading? If true, the multiblock will be paused instead of broken. */ public void detachBlock(IMultiblockPart part, boolean chunkUnloading) { _detachBlock(part, chunkUnloading); // If we've lost blocks while disassembled, split up our machine. Can result in up to 6 new TEs. if(!chunkUnloading && this.assemblyState == AssemblyState.Disassembled) { this.revisitBlocks(); } } /** * Internal helper that can be safely called for internal use * Does not trigger fission. * @param part The part to detach from this machine. * @param chunkUnloading Is this entity detaching due to the chunk unloading? If true, the multiblock will be paused instead of broken. */ private void _detachBlock(IMultiblockPart part, boolean chunkUnloading) { CoordTriplet coord = part.getWorldLocation(); if(chunkUnloading) { if(this.assemblyState == AssemblyState.Assembled) { this.assemblyState = AssemblyState.Paused; this.pauseMachine(); } } if(connectedBlocks.contains(coord)) { part.onDetached(this); } while(connectedBlocks.contains(coord)) { connectedBlocks.remove(coord); this.onBlockRemoved(part); if(referenceCoord != null && referenceCoord.equals(coord)) { part.forfeitMultiblockSaveDelegate(); referenceCoord = null; } } if(connectedBlocks.isEmpty()) { // Destroy/unregister MultiblockRegistry.unregister(this); return; } if(!blocksHaveChangedThisFrame && chunkUnloading) { // If the first change this frame is a chunk unload, set to true. this.chunksHaveUnloaded = true; } else if(this.chunksHaveUnloaded) { // If we get multiple unloads in a frame, any one of them being false flips this false too. this.chunksHaveUnloaded = chunkUnloading; } blocksHaveChangedThisFrame = true; // Find new save delegate if we need to. if(referenceCoord == null) { // ConnectedBlocks can be empty due to chunk unloading. This is OK. We'll die next frame. if(!this.connectedBlocks.isEmpty()) { for(CoordTriplet connectedCoord : connectedBlocks) { TileEntity te = this.worldObj.getBlockTileEntity(connectedCoord.x, connectedCoord.y, connectedCoord.z); if(te == null) { continue; } // Chunk unload has removed this block. It'll get hit soon. Ignore it. if(referenceCoord == null) { referenceCoord = connectedCoord; } else if(connectedCoord.compareTo(referenceCoord) < 0) { referenceCoord = connectedCoord; } } } if(referenceCoord != null) { TileEntity te = this.worldObj.getBlockTileEntity(referenceCoord.x, referenceCoord.y, referenceCoord.z); ((IMultiblockPart)te).becomeMultiblockSaveDelegate(); } } } /** * Helper method so we don't check for a whole machine until we have enough blocks * to actually assemble it. This isn't as simple as xmax*ymax*zmax for non-cubic machines * or for machines with hollow/complex interiors. * @return The minimum number of blocks connected to the machine for it to be assembled. */ protected abstract int getMinimumNumberOfBlocksForAssembledMachine(); /** * @return True if the machine is "whole" and should be assembled. False otherwise. */ protected boolean isMachineWhole() { if(connectedBlocks.size() >= getMinimumNumberOfBlocksForAssembledMachine()) { // Now we run a simple check on each block within that volume. // Any block deviating = NO DEAL SIR TileEntity te; IMultiblockPart part; boolean dealbreaker = false; for(int x = minimumCoord.x; !dealbreaker && x <= maximumCoord.x; x++) { for(int y = minimumCoord.y; !dealbreaker && y <= maximumCoord.y; y++) { for(int z = minimumCoord.z; !dealbreaker && z <= maximumCoord.z; z++) { // Okay, figure out what sort of block this should be. te = this.worldObj.getBlockTileEntity(x, y, z); if(te != null && te instanceof IMultiblockPart) { part = (IMultiblockPart)te; } else { part = null; } // Validate block type against both part-level and material-level validators. int extremes = 0; if(x == minimumCoord.x) { extremes++; } if(y == minimumCoord.y) { extremes++; } if(z == minimumCoord.z) { extremes++; } if(x == maximumCoord.x) { extremes++; } if(y == maximumCoord.y) { extremes++; } if(z == maximumCoord.z) { extremes++; } if(extremes >= 2) { if(part != null && !part.isGoodForFrame()) { dealbreaker = true; } else if(part == null && !isBlockGoodForFrame(this.worldObj, x, y, z)) { dealbreaker = true; } } else if(extremes == 1) { if(y == maximumCoord.y) { if(part != null && !part.isGoodForTop()) { dealbreaker = true; } else if(part == null & !isBlockGoodForTop(this.worldObj, x, y, z)) { dealbreaker = true; } } else if(y == minimumCoord.y) { if(part != null && !part.isGoodForBottom()) { dealbreaker = true; } else if(part == null & !isBlockGoodForBottom(this.worldObj, x, y, z)) { dealbreaker = true; } } else { // Side if(part != null && !part.isGoodForSides()) { dealbreaker = true; } else if(part == null & !isBlockGoodForSides(this.worldObj, x, y, z)) { dealbreaker = true; } } } else { if(part != null && !part.isGoodForInterior()) { dealbreaker = true; } else if(part == null & !isBlockGoodForInterior(this.worldObj, x, y, z)) { dealbreaker = true; } } } } } return !dealbreaker; } return false; } /** * Check if the machine is whole or not. * If the machine was not whole, but now is, assemble the machine. * If the machine was whole, but no longer is, disassemble the machine. */ protected void checkIfMachineIsWhole() { AssemblyState oldState = this.assemblyState; boolean isWhole = isMachineWhole(); if(isWhole) { // This will alter assembly state this.assemblyState = AssemblyState.Assembled; assembleMachine(oldState); } else if(oldState == AssemblyState.Assembled) { // This will alter assembly state this.assemblyState = AssemblyState.Disassembled; disassembleMachine(); } // Else Paused, do nothing } /** * Called when a machine becomes "whole" and should begin * functioning as a game-logically finished machine. * Calls onMachineAssembled on all attached parts. */ private void assembleMachine(AssemblyState oldState) { TileEntity te; for(CoordTriplet coord : connectedBlocks) { te = this.worldObj.getBlockTileEntity(coord.x, coord.y, coord.z); if(te instanceof IMultiblockPart) { ((IMultiblockPart)te).onMachineAssembled(); } } if(oldState == assemblyState.Paused) { onMachineRestored(); } else { onMachineAssembled(); } } /** * Called when the machine needs to be disassembled. * It is not longer "whole" and should not be functional, usually * as a result of a block being removed. * Calls onMachineBroken on all attached parts. */ private void disassembleMachine() { TileEntity te; for(CoordTriplet coord : connectedBlocks) { te = this.worldObj.getBlockTileEntity(coord.x, coord.y, coord.z); if(te instanceof IMultiblockPart) { ((IMultiblockPart)te).onMachineBroken(); } } onMachineDisassembled(); } /** * Called when the machine is paused, generally due to chunk unloads or merges. * This should perform any machine-halt cleanup logic, but not change any user * settings. * Calls onMachineBroken on all attached parts. */ private void pauseMachine() { TileEntity te; for(CoordTriplet coord : connectedBlocks) { te = this.worldObj.getBlockTileEntity(coord.x, coord.y, coord.z); if(te instanceof IMultiblockPart) { ((IMultiblockPart)te).onMachineBroken(); } } onMachinePaused(); } /** * Called before other machines are merged into this one. */ public void beginMerging() { } /** * Merge another controller into this controller. * Acquire all of the other controller's blocks and attach them * to this machine. * * NOTE: endMerging MUST be called after 1 or more merge calls! * * @param other The controller to merge into this one. * {@link erogenousbeef.core.multiblock.MultiblockControllerBase#endMerging()} */ public void merge(MultiblockControllerBase other) { if(this.referenceCoord.compareTo(other.referenceCoord) >= 0) { throw new IllegalArgumentException("The controller with the lowest minimum-coord value must consume the one with the higher coords"); } TileEntity te; Set<CoordTriplet> blocksToAcquire = new CopyOnWriteArraySet<CoordTriplet>(other.connectedBlocks); // releases all blocks and references gently so they can be incorporated into another multiblock other.onMergedIntoOtherController(this); IMultiblockPart acquiredPart; for(CoordTriplet coord : blocksToAcquire) { // By definition, none of these can be the minimum block. this.connectedBlocks.add(coord); te = this.worldObj.getBlockTileEntity(coord.x, coord.y, coord.z); acquiredPart = (IMultiblockPart)te; acquiredPart.onMergedIntoOtherMultiblock(this); this.onBlockAdded(acquiredPart); } } /** * Called when this machine is consumed by another controller. * Essentially, forcibly tear down this object. * @param otherController The controller consuming this controller. */ private void onMergedIntoOtherController(MultiblockControllerBase otherController) { this.pauseMachine(); if(referenceCoord != null) { TileEntity te = this.worldObj.getBlockTileEntity(referenceCoord.x, referenceCoord.y, referenceCoord.z); ((IMultiblockPart)te).forfeitMultiblockSaveDelegate(); this.referenceCoord = null; } this.connectedBlocks.clear(); MultiblockRegistry.unregister(this); this.onMachineMerge(otherController); } /** * Callback. Called after this machine is consumed by another controller. * This means all blocks have been stripped out of this object and * handed over to the other controller. * @param otherMachine The machine consuming this controller. */ protected abstract void onMachineMerge(MultiblockControllerBase otherMachine); /** * Called after all multiblock machine merges have been completed for * this machine. */ public void endMerging() { this.recalculateMinMaxCoords(); } /** * The update loop! Implement the game logic you would like to execute * on every world tick here. Note that this only executes on the server, * so you will need to send updates to the client manually. */ public final void updateMultiblockEntity() { if(this.connectedBlocks.isEmpty()) { MultiblockRegistry.unregister(this); return; } if(this.blocksHaveChangedThisFrame) { // Assemble/break machine if we have to this.recalculateMinMaxCoords(); checkIfMachineIsWhole(); this.blocksHaveChangedThisFrame = false; } if(this.assemblyState == AssemblyState.Assembled) { if(update()) { // If our chunks are all loaded, then save them, because we've changed stuff. if(this.worldObj.checkChunksExist(minimumCoord.x, minimumCoord.y, minimumCoord.z, maximumCoord.x, maximumCoord.y, maximumCoord.z)) { int minChunkX = minimumCoord.x >> 4; int minChunkZ = minimumCoord.z >> 4; int maxChunkX = maximumCoord.x >> 4; int maxChunkZ = maximumCoord.z >> 4; for(int x = minChunkX; x <= maxChunkX; x++) { for(int z = minChunkZ; z <= maxChunkZ; z++) { // Ensure that we save our data, even if the our save delegate is in has no TEs. Chunk chunkToSave = this.worldObj.getChunkFromChunkCoords(x, z); chunkToSave.setChunkModified(); } } } } } } /** * The update loop! Use this similarly to a TileEntity's update loop. * You do not need to call your superclass' update() if you're directly * derived from MultiblockControllerBase. This is a callback. * Note that this will only be called when the machine is assembled. * @return True if the multiblock should save data, i.e. its internal game state has changed. False otherwise. */ protected abstract boolean update(); /** * Visits all blocks via a breadth-first walk of neighbors from the * reference coordinate. If any blocks remain unvisited after this * method is called, they are orphans and are split off the main * machine. */ private void revisitBlocks() { TileEntity te; // Ensure that our current reference coord is valid. If not, invalidate it. if(referenceCoord != null && this.worldObj.getBlockTileEntity(referenceCoord.x, referenceCoord.y, referenceCoord.z) == null) { referenceCoord = null; } // Reset visitations and find the minimum coordinate for(CoordTriplet c: connectedBlocks) { te = this.worldObj.getBlockTileEntity(c.x, c.y, c.z); if(te == null) { continue; } // This happens during chunk unload. Consider it valid, move on. ((IMultiblockPart)te).setUnvisited(); if(referenceCoord == null) { referenceCoord = c; } else if(c.compareTo(referenceCoord) < 0) { referenceCoord = c; } } if(referenceCoord == null) { // There are no valid parts remaining. This is due to a chunk unload. Halt. return; } // Now visit all connected parts, breadth-first, starting from reference coord. LinkedList<IMultiblockPart> partsToCheck = new LinkedList<IMultiblockPart>(); IMultiblockPart[] nearbyParts = null; IMultiblockPart part = (IMultiblockPart)this.worldObj.getBlockTileEntity(referenceCoord.x, referenceCoord.y, referenceCoord.z); partsToCheck.add(part); while(!partsToCheck.isEmpty()) { part = partsToCheck.removeFirst(); part.setVisited(); nearbyParts = part.getNeighboringParts(); for(IMultiblockPart nearbyPart : nearbyParts) { // Ignore different machines if(nearbyPart.getMultiblockController() != this) { continue; } if(!nearbyPart.isVisited()) { nearbyPart.setVisited(); partsToCheck.add(nearbyPart); } } } // First, remove any blocks that are still disconnected. List<IMultiblockPart> orphans = new LinkedList<IMultiblockPart>(); for(CoordTriplet c : connectedBlocks) { part = (IMultiblockPart)this.worldObj.getBlockTileEntity(c.x, c.y, c.z); if(!part.isVisited()) { orphans.add(part); } } // Remove all orphaned parts. i.e. Actually orphan them. for(IMultiblockPart orphan : orphans) { this._detachBlock(orphan, false); } // Now go through and start up as many new machines as possible. for(IMultiblockPart orphan : orphans) { if(!orphan.isConnected()) { // Creating a new multiblock should capture all other orphans connected to this orphan. orphan.onOrphaned(); } } } // Validation helpers /** * The "frame" consists of the outer edges of the machine, plus the corners. * * @param world World object for the world in which this controller is located. * @param x X coordinate of the block being tested * @param y Y coordinate of the block being tested * @param z Z coordinate of the block being tested * @return True if this block can be used as part of the frame. */ protected boolean isBlockGoodForFrame(World world, int x, int y, int z) { return false; } /** * The top consists of the top face, minus the edges. * @param world World object for the world in which this controller is located. * @param x X coordinate of the block being tested * @param y Y coordinate of the block being tested * @param z Z coordinate of the block being tested * @return True if this block can be used as part of the top face. */ protected boolean isBlockGoodForTop(World world, int x, int y, int z) { return false; } /** * The bottom consists of the bottom face, minus the edges. * @param world World object for the world in which this controller is located. * @param x X coordinate of the block being tested * @param y Y coordinate of the block being tested * @param z Z coordinate of the block being tested * @return True if this block can be used as part of the bottom face. */ protected boolean isBlockGoodForBottom(World world, int x, int y, int z) { return false; } /** * The sides consists of the N/E/S/W-facing faces, minus the edges. * @param world World object for the world in which this controller is located. * @param x X coordinate of the block being tested * @param y Y coordinate of the block being tested * @param z Z coordinate of the block being tested * @return True if this block can be used as part of the sides. */ protected boolean isBlockGoodForSides(World world, int x, int y, int z) { return false; } /** * The interior is any block that does not touch blocks outside the machine. * @param world World object for the world in which this controller is located. * @param x X coordinate of the block being tested * @param y Y coordinate of the block being tested * @param z Z coordinate of the block being tested * @return True if this block can be used as part of the sides. */ protected boolean isBlockGoodForInterior(World world, int x, int y, int z) { return false; } /** * @return The reference coordinate, the block with the lowest x, y, z coordinates, evaluated in that order. */ public CoordTriplet getReferenceCoord() { return referenceCoord; } /** * @return The number of blocks connected to this controller. */ public int getNumConnectedBlocks() { return connectedBlocks.size(); } public abstract void writeToNBT(NBTTagCompound data); public abstract void readFromNBT(NBTTagCompound data); private void recalculateMinMaxCoords() { minimumCoord.x = minimumCoord.y = minimumCoord.z = Integer.MAX_VALUE; maximumCoord.x = maximumCoord.y = maximumCoord.z = Integer.MIN_VALUE; for(CoordTriplet coord : connectedBlocks) { if(coord.x < minimumCoord.x) { minimumCoord.x = coord.x; } if(coord.x > maximumCoord.x) { maximumCoord.x = coord.x; } if(coord.y < minimumCoord.y) { minimumCoord.y = coord.y; } if(coord.y > maximumCoord.y) { maximumCoord.y = coord.y; } if(coord.z < minimumCoord.z) { minimumCoord.z = coord.z; } if(coord.z > maximumCoord.z) { maximumCoord.z = coord.z; } } } /** * @return The minimum bounding-box coordinate containing this machine's blocks. */ public CoordTriplet getMinimumCoord() { return minimumCoord.copy(); } /** * @return The maximum bounding-box coordinate containing this machine's blocks. */ public CoordTriplet getMaximumCoord() { return maximumCoord.copy(); } /** * Called when the save delegate's tile entity is being asked for its description packet * @param tag A fresh compound tag to write your multiblock data into */ public abstract void formatDescriptionPacket(NBTTagCompound data); /** * Called when the save delegate's tile entity receiving a description packet * @param tag A compound tag containing multiblock data to import */ public abstract void decodeDescriptionPacket(NBTTagCompound data); }
package jade.core; import java.io.IOException; import java.io.InterruptedIOException; import jade.util.leap.Serializable; import jade.util.leap.Iterator; import java.util.Hashtable; import java.util.Enumeration; import jade.core.behaviours.Behaviour; import jade.lang.acl.*; import jade.domain.FIPAException; import jade.content.ContentManager; import jade.security.AuthException; //#MIDP_EXCLUDE_BEGIN import java.io.InputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.OutputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import jade.util.leap.List; import jade.util.leap.ArrayList; import jade.util.leap.Map; import jade.util.leap.HashMap; import java.util.Vector; import jade.security.Authority; import jade.security.AgentPrincipal; import jade.security.DelegationCertificate; import jade.security.IdentityCertificate; import jade.security.CertificateFolder; import jade.security.PrivilegedExceptionAction; //#MIDP_EXCLUDE_END /*#MIDP_INCLUDE_BEGIN import javax.microedition.midlet.*; #MIDP_INCLUDE_END*/ /** The <code>Agent</code> class is the common superclass for user defined software agents. It provides methods to perform basic agent tasks, such as: <ul> <li> <b> Message passing using <code>ACLMessage</code> objects, both unicast and multicast with optional pattern matching. </b> <li> <b> Complete Agent Platform life cycle support, including starting, suspending and killing an agent. </b> <li> <b> Scheduling and execution of multiple concurrent activities. </b> <li> <b> Simplified interaction with <em>FIPA</em> system agents for automating common agent tasks (DF registration, etc.). </b> </ul> Application programmers must write their own agents as <code>Agent</code> subclasses, adding specific behaviours as needed and exploiting <code>Agent</code> class capabilities. @author Giovanni Rimassa - Universita' di Parma @version $Date$ $Revision$ */ public class Agent implements Runnable, Serializable, TimerListener { private static final long serialVersionUID = 3487495895819000L; // This inner class is used to force agent termination when a signal // from the outside is received private class AgentDeathError extends Error { //#MIDP_EXCLUDE_BEGIN AgentDeathError() { super("Agent " + Thread.currentThread().getName() + " has been terminated."); } //#MIDP_EXCLUDE_END } //#MIDP_EXCLUDE_BEGIN private static class AgentInMotionError extends Error { AgentInMotionError() { super("Agent " + Thread.currentThread().getName() + " is about to move or be cloned."); } } //#MIDP_EXCLUDE_END // This class manages bidirectional associations between Timer and // Behaviour objects, using hash tables. This class is fully // synchronized because is accessed both by agent internal thread // and high priority Timer Dispatcher thread. private static class AssociationTB { private Hashtable BtoT = new Hashtable(); private Hashtable TtoB = new Hashtable(); public synchronized void addPair(Behaviour b, Timer t) { BtoT.put(b, t); TtoB.put(t, b); } public synchronized void removeMapping(Behaviour b) { Timer t = (Timer)BtoT.remove(b); if(t != null) { TtoB.remove(t); } } public synchronized void removeMapping(Timer t) { Behaviour b = (Behaviour)TtoB.remove(t); if(b != null) { BtoT.remove(b); } } public synchronized Timer getPeer(Behaviour b) { return (Timer)BtoT.get(b); } public synchronized Behaviour getPeer(Timer t) { return (Behaviour)TtoB.get(t); } public synchronized Enumeration timers() { return TtoB.keys(); } } // End of AssociationTB class //#MIDP_EXCLUDE_BEGIN // A simple class for a boolean condition variable private static class CondVar { private boolean value = false; public synchronized void waitOn() throws InterruptedException { while(!value) { wait(); } } public synchronized void set() { value = true; notifyAll(); } } // End of CondVar class //#MIDP_EXCLUDE_END /** Schedules a restart for a behaviour, after a certain amount of time has passed. @param b The behaviour to restart later. @param millis The amount of time to wait before restarting <code>b</code>. @see jade.core.behaviours.Behaviour#block(long millis) */ public void restartLater(Behaviour b, long millis) { if (millis <= 0) return; Timer t = new Timer(System.currentTimeMillis() + millis, this); // The following block of code must be synchronized with the operations // carried out by the TimerDispatcher. In fact it could be the case that // 1) A behaviour blocks for a very short time --> A Timer is added // to the TimerDispatcher // 2) The Timer immediately expires and the TimerDispatcher try to // restart the behaviour before the pair (b, t) is added to the // pendingTimers of this agent. synchronized (theDispatcher) { t = theDispatcher.add(t); pendingTimers.addPair(b, t); } } /** Restarts the behaviour associated with t. This method runs within the time-critical Timer Dispatcher thread and is not intended to be called by users. It is defined public only because is part of the <code>TimerListener</code> interface. */ public void doTimeOut(Timer t) { Behaviour b = pendingTimers.getPeer(t); if(b != null) { b.restart(); } //#MIDP_EXCLUDE_BEGIN else { System.out.println("Warning: No mapping found for expired timer "+t.expirationTime()); } //#MIDP_EXCLUDE_END } /** Notifies this agent that one of its behaviours has been restarted for some reason. This method clears any timer associated with behaviour object <code>b</code>, and it is unneeded by application level code. To explicitly schedule behaviours, use <code>block()</code> and <code>restart()</code> methods. @param b The behaviour object which was restarted. @see jade.core.behaviours.Behaviour#restart() */ public void notifyRestarted(Behaviour b) { Timer t = pendingTimers.getPeer(b); if(t != null) { pendingTimers.removeMapping(b); theDispatcher.remove(t); } // Did this restart() cause the root behaviour to become runnable ? // If so, put the root behaviour back into the ready queue. Behaviour root = b.root(); if(root.isRunnable()) { myScheduler.restart(root); } } /** Out of band value for Agent Platform Life Cycle states. */ public static final int AP_MIN = 0; // Hand-made type checking /** Represents the <em>initiated</em> agent state. */ public static final int AP_INITIATED = 1; /** Represents the <em>active</em> agent state. */ public static final int AP_ACTIVE = 2; /** Represents the <em>idle</em> agent state. */ public static final int AP_IDLE = 3; /** Represents the <em>suspended</em> agent state. */ public static final int AP_SUSPENDED = 4; /** Represents the <em>waiting</em> agent state. */ public static final int AP_WAITING = 5; /** Represents the <em>deleted</em> agent state. */ public static final int AP_DELETED = 6; //#MIDP_EXCLUDE_BEGIN /** Represents the <code>transit</code> agent state. */ public static final int AP_TRANSIT = 7; // Non compliant states, used internally. Maybe report to FIPA... /** Represents the <code>copy</code> agent state. */ public static final int AP_COPY = 8; /** Represents the <code>gone</code> agent state. This is the state the original instance of an agent goes into when a migration transaction successfully commits. */ static final int AP_GONE = 9; //#MIDP_EXCLUDE_END /** Out of band value for Agent Platform Life Cycle states. */ public static final int AP_MAX = 10; // Hand-made type checking //#MIDP_EXCLUDE_BEGIN private static final AgentState[] STATES = new AgentState[] { new AgentState("Illegal MIN state"), new AgentState("Initiated"), new AgentState("Active"), new AgentState("Idle"), new AgentState("Suspended"), new AgentState("Waiting"), new AgentState("Deleted"), new AgentState("Transit"), new AgentState("Copy"), new AgentState("Gone"), new AgentState("Illegal MAX state") }; /** These constants represent the various Domain Life Cycle states */ /** Out of band value for Domain Life Cycle states. */ public static final int D_MIN = 9; // Hand-made type checking /** Represents the <em>active</em> agent state. */ public static final int D_ACTIVE = 10; /** Represents the <em>suspended</em> agent state. */ public static final int D_SUSPENDED = 20; /** Represents the <em>retired</em> agent state. */ public static final int D_RETIRED = 30; /** Represents the <em>unknown</em> agent state. */ public static final int D_UNKNOWN = 40; /** Out of band value for Domain Life Cycle states. */ public static final int D_MAX = 41; // Hand-made type checking //#MIDP_EXCLUDE_END /** Get the Agent ID for the platform AMS. @return An <code>AID</code> object, that can be used to contact the AMS of this platform. */ public final AID getAMS() { return myToolkit.getAMS(); } /** Get the Agent ID for the platform default DF. @return An <code>AID</code> object, that can be used to contact the default DF of this platform. */ public final AID getDefaultDF() { return myToolkit.getDefaultDF(); } //#MIDP_EXCLUDE_BEGIN private int msgQueueMaxSize = 0; private transient MessageQueue msgQueue = new MessageQueue(msgQueueMaxSize); private transient List o2aQueue; private int o2aQueueSize = 0; private transient Map o2aLocks = new HashMap(); private transient AgentToolkit myToolkit = DummyToolkit.instance(); //#MIDP_EXCLUDE_END /*#MIDP_INCLUDE_BEGIN private transient MessageQueue msgQueue = new MessageQueue(0); private transient AgentToolkit myToolkit; #MIDP_INCLUDE_END*/ private String myName = null; private AID myAID = null; private String myHap = null; private transient Object stateLock = new Object(); // Used to make state transitions atomic private transient Object suspendLock = new Object(); // Used for agent suspension //#MIDP_EXCLUDE_BEGIN private transient Object principalLock = new Object(); // Used to make principal transitions atomic //#MIDP_EXCLUDE_END private transient Thread myThread; private transient TimerDispatcher theDispatcher; private Scheduler myScheduler; private transient AssociationTB pendingTimers = new AssociationTB(); // Free running counter that increments by one for each message // received. private int messageCounter = 0 ; /** The <code>Behaviour</code> that is currently executing. @see jade.core.behaviours.Behaviour @serial */ protected Behaviour currentBehaviour; /** Last message received. @see jade.lang.acl.ACLMessage @serial */ protected ACLMessage currentMessage; // This variable is 'volatile' because is used as a latch to signal // agent suspension and termination from outside world. private volatile int myAPState; //#MIDP_EXCLUDE_BEGIN //private Authority authority; private String ownership = jade.security.JADEPrincipal.NONE; private AgentPrincipal principal = null; private CertificateFolder certs = new CertificateFolder(); //#MIDP_EXCLUDE_END /** This flag is used to distinguish the normal AP_ACTIVE state from the particular case in which the agent state is set to AP_ACTIVE during agent termination to allow it to deregister with the AMS. In this case in fact a call to <code>doDelete()</code>, <code>doMove()</code>, <code>doClone()</code> and <code>doSuspend()</code> should have no effect. */ private boolean terminating = false; //#MIDP_EXCLUDE_BEGIN /** When set to false (default) all behaviour-related events (such as ADDED_BEHAVIOUR or CHANGED_BEHAVIOUR_STATE) are not generated in order to improve performances. These events in facts are very frequent. */ private boolean generateBehaviourEvents = false; // These two variables are used as temporary buffers for // mobility-related parameters private transient Location myDestination; private transient String myNewName; //#MIDP_EXCLUDE_END // Temporary buffer for agent suspension private int myBufferedState = AP_MIN; /*#MIDP_INCLUDE_BEGIN public static MIDlet midlet; // Flag for agent interruption (necessary as Thread.interrupt() // is not available in MIDP) private boolean isInterrupted = false; #MIDP_INCLUDE_END*/ /** Default constructor. */ public Agent() { setState(AP_INITIATED); myScheduler = new Scheduler(this); theDispatcher = TimerDispatcher.getTimerDispatcher(); } //#MIDP_EXCLUDE_BEGIN /** Constructor to be used by special "agents" that will never powerUp. */ Agent(AID id) { myName = id.getLocalName(); myHap = id.getHap(); myAID = id; } /** Declared transient because the container changes in case * of agent migration. **/ private transient jade.wrapper.AgentContainer myContainer = null; /** * Return a controller for this agents container. * @return jade.wrapper.AgentContainer The proxy container for this agent. */ public final jade.wrapper.AgentContainer getContainerController() { if (myContainer == null) { // first time called try { myContainer = new jade.wrapper.AgentContainer((AgentContainerImpl)myToolkit, getHap()); } catch (Exception e) { throw new IllegalStateException("A ContainerController cannot be got for this agent. Probably the method has been called at an appropriate time before the complete initialization of the agent."); } } return myContainer; } //#MIDP_EXCLUDE_END private transient Object[] arguments = null; // array of arguments /** * Called by AgentContainerImpl in order to pass arguments to a * just created Agent. * <p>Usually, programmers do not need to call this method in their code. * @see #getArguments() how to get the arguments passed to an agent **/ public final void setArguments(Object args[]) { // I have declared the method final otherwise getArguments would not work! arguments=args; } /** * Get the array of arguments passed to this agent. * <p> Take care that the arguments are transient and they do not * migrate with the agent neither are cloned with the agent! * @return the array of arguments passed to this agent. * @see <a href=../../../tutorials/ArgsAndPropsPassing.htm>How to use arguments or properties to configure your agent.</a> **/ protected Object[] getArguments() { return arguments; } /** Method to query the agent local name. @return A <code>String</code> containing the local agent name (e.g. <em>peter</em>). */ public final String getLocalName() { return myName; } /** Method to query the agent complete name (<em><b>GUID</b></em>). @return A <code>String</code> containing the complete agent name (e.g. <em>peter@fipa.org:50</em>). */ public final String getName() { return myName + '@' + myHap; } /** Method to query the private Agent ID. Note that this Agent ID is <b>different</b> from the one that is registered with the platform AMS. @return An <code>Agent ID</code> object, containing the complete agent GUID, addresses and resolvers. */ public final AID getAID() { return myAID; } /** This method adds a new platform address to the AID of this Agent. It is called by the container when a new MTP is activated in the platform (in the local container - installMTP() - or in a remote container - updateRoutingTable()) to keep the Agent AID updated. */ synchronized void addPlatformAddress(String address) { // Mutual exclusion with Agent.powerUp() if (myAID != null) { // Cloning the AID is necessary as the agent may be using its AID. // If this is the case a ConcurrentModificationException would be thrown myAID = (AID)myAID.clone(); myAID.addAddresses(address); } } /** This method removes an old platform address from the AID of this Agent. It is called by the container when a new MTP is deactivated in the platform (in the local container - uninstallMTP() - or in a remote container - updateRoutingTable()) to keep the Agent AID updated. */ synchronized void removePlatformAddress(String address) { // Mutual exclusion with Agent.powerUp() if (myAID != null) { // Cloning the AID is necessary as the agent may be using its AID. // If this is the case a ConcurrentModificationException would be thrown myAID = (AID)myAID.clone(); myAID.removeAddresses(address); } } /** Method to query the agent home address. This is the address of the platform where the agent was created, and will never change during the whole lifetime of the agent. @return A <code>String</code> containing the agent home address (e.g. <em>iiop://fipa.org:50/acc</em>). */ public final String getHap() { return myHap; } /** Method to retrieve the location this agent is currently at. @return A <code>Location</code> object, describing the location where this agent is currently running. */ public Location here() { return myToolkit.here(); } //#MIDP_EXCLUDE_BEGIN public Authority getAuthority() { return myToolkit.getAuthority(); } //#MIDP_EXCLUDE_END /** * This is used by the agent container to wait for agent termination. * We have alreader called doDelete on the thread which would have * issued an interrupt on it. However, it still may decide not to exit. * So we will wait no longer than 5 seconds for it to exit and we * do not care of this zombie agent. * FIXME: we must further isolate container and agents, for instance * by using custom class loader and dynamic proxies and JDK 1.3. * FIXME: the timeout value should be got by Profile */ void join() { //#MIDP_EXCLUDE_BEGIN try { myThread.join(5000); if (myThread.isAlive()) { System.out.println("*** Warning: Agent " + myName + " did not terminate when requested to do so."); if(!myThread.equals(Thread.currentThread())) { myThread.interrupt(); System.out.println("*** Second interrupt issued."); } } } catch(InterruptedException ie) { ie.printStackTrace(); } //#MIDP_EXCLUDE_END /*#MIDP_INCLUDE_BEGIN if (myThread != null && myThread.isAlive()) { try { myThread.join(); } catch (InterruptedException ie) { ie.printStackTrace(); } } #MIDP_INCLUDE_END*/ } public void setQueueSize(int newSize) throws IllegalArgumentException { msgQueue.setMaxSize(newSize); //#MIDP_EXCLUDE_BEGIN msgQueueMaxSize = newSize; //#MIDP_EXCLUDE_END } /** * @return The number of messages that are currently stored into the * message queue. **/ public int getCurQueueSize() { return msgQueue.size(); } /** Reads message queue size. A zero value means that the message queue is unbounded (its size is limited only by amount of available memory). @return The actual size of the message queue (i.e. the max number of messages that can be stored into the queue) @see jade.core.Agent#setQueueSize(int newSize) @see jade.core.Agent#getCurQueueSize() */ public int getQueueSize() { return msgQueue.getMaxSize(); } //#MIDP_EXCLUDE_BEGIN public void setOwnership(String ownership) { this.ownership = ownership; } public static String extractUsername(String ownership) { int dot2 = ownership.indexOf(':'); return (dot2 != -1) ? ownership.substring(0, dot2) : ownership; } public static byte[] extractPassword(String ownership) { int dot2 = ownership.indexOf(':'); return (dot2 != -1 && dot2 < ownership.length() - 1) ? ownership.substring(dot2 + 1, ownership.length()).getBytes() : new byte[] {}; } public void setPrincipal(CertificateFolder certs) { AgentPrincipal old = getPrincipal(); synchronized (principalLock) { this.certs = certs; this.principal = (AgentPrincipal)certs.getIdentityCertificate().getSubject(); notifyChangedAgentPrincipal(old, certs); } } public AgentPrincipal getPrincipal() { AgentPrincipal p = null; if (!(myToolkit instanceof DummyToolkit)) { synchronized (principalLock) { Authority authority = getAuthority(); if (principal == null) { String user = extractUsername(ownership); principal = authority.createAgentPrincipal(myAID, user); } p = principal; } } return p; } public CertificateFolder getCertificateFolder() { return certs; } private void doPrivileged(PrivilegedExceptionAction action) throws Exception { getAuthority().doAsPrivileged(action, getCertificateFolder()); } //#MIDP_EXCLUDE_END private void setState(int state) { synchronized (stateLock) { int oldState = myAPState; myAPState = state; //#MIDP_EXCLUDE_BEGIN notifyChangedAgentState(oldState, myAPState); //#MIDP_EXCLUDE_END /*#MIDP_INCLUDE_BEGIN //myToolkit.handleChangedAgentState(myAID, oldState, myAPState); #MIDP_INCLUDE_END*/ } } /** Read current agent state. This method can be used to query an agent for its state from the outside. @return the Agent Platform Life Cycle state this agent is currently in. */ public int getState() { int state; synchronized(stateLock) { state = myAPState; } return state; } //#MIDP_EXCLUDE_BEGIN public AgentState getAgentState() { return STATES[getState()]; } /** This is only called by the RealNotificationManager to provide the Introspector agent with a snapshot of the behaviours currently loaded in the agent */ Scheduler getScheduler() { return myScheduler; } /** This is only called by the RealNotificationManager to provide the Introspector agent with a snapshot of the messages currently pending in the queue and by the RealMobilityManager to transfer messages in the queue */ MessageQueue getMessageQueue() { return msgQueue; } // State transition methods for Agent Platform Life-Cycle /** Make a state transition from <em>initiated</em> to <em>active</em> within Agent Platform Life Cycle. Agents are started automatically by JADE on agent creation and this method should not be used by application developers, unless creating some kind of agent factory. This method starts the embedded thread of the agent. <b> It is highly descouraged the usage of this method </b> because it does not guarantee agent autonomy. It is expected that in the next releases this method might be removed or its scope restricted. @param name The local name of the agent. */ public void doStart(String name) { myToolkit.handleStart(name, this); } /** Make a state transition from <em>active</em> to <em>transit</em> within Agent Platform Life Cycle. This method is intended to support agent mobility and is called either by the Agent Platform or by the agent itself to start a migration process. @param destination The <code>Location</code> to migrate to. */ public void doMove(Location destination) { synchronized(stateLock) { if(((myAPState == AP_ACTIVE)||(myAPState == AP_WAITING)||(myAPState == AP_IDLE)) && !terminating) { myBufferedState = myAPState; setState(AP_TRANSIT); myDestination = destination; // Real action will be executed in the embedded thread if(!myThread.equals(Thread.currentThread())) myThread.interrupt(); } } } /** Make a state transition from <em>active</em> to <em>copy</em> within Agent Platform Life Cycle. This method is intended to support agent mobility and is called either by the Agent Platform or by the agent itself to start a clonation process. @param destination The <code>Location</code> where the copy agent will start. @param newName The name that will be given to the copy agent. */ public void doClone(Location destination, String newName) { synchronized(stateLock) { if(((myAPState == AP_ACTIVE)||(myAPState == AP_WAITING)||(myAPState == AP_IDLE)) && !terminating) { myBufferedState = myAPState; setState(AP_COPY); myDestination = destination; myNewName = newName; // Real action will be executed in the embedded thread if(!myThread.equals(Thread.currentThread())) myThread.interrupt(); } } } /** Make a state transition from <em>transit</em> or <code>copy</code> to <em>active</em> within Agent Platform Life Cycle. This method is intended to support agent mobility and is called by the destination Agent Platform when a migration process completes and the mobile agent is about to be restarted on its new location. */ void doExecute() { synchronized(stateLock) { // FIXME: Hack to manage agents moving while in AP_IDLE state, // but with pending timers. The correct solution would be to // restore all pending timers. if(myBufferedState == AP_IDLE) myBufferedState = AP_ACTIVE; setState(myBufferedState); myBufferedState = AP_MIN; activateAllBehaviours(); } } /** Make a state transition from <em>transit</em> to <em>gone</em> state. This state is only used to label the original copy of a mobile agent which migrated somewhere. */ void doGone() { synchronized(stateLock) { setState(AP_GONE); } } //#MIDP_EXCLUDE_END /** Make a state transition from <em>active</em> or <em>waiting</em> to <em>suspended</em> within Agent Platform Life Cycle; the original agent state is saved and will be restored by a <code>doActivate()</code> call. This method can be called from the Agent Platform or from the agent iself and stops all agent activities. Incoming messages for a suspended agent are buffered by the Agent Platform and are delivered as soon as the agent resumes. Calling <code>doSuspend()</code> on a suspended agent has no effect. @see jade.core.Agent#doActivate() */ public void doSuspend() { synchronized(stateLock) { if(((myAPState == AP_ACTIVE)||(myAPState == AP_WAITING)||(myAPState == AP_IDLE)) && !terminating) { myBufferedState = myAPState; setState(AP_SUSPENDED); } } if(myAPState == AP_SUSPENDED) { if(myThread.equals(Thread.currentThread())) { waitUntilActivate(); } } } /** Make a state transition from <em>suspended</em> to <em>active</em> or <em>waiting</em> (whichever state the agent was in when <code>doSuspend()</code> was called) within Agent Platform Life Cycle. This method is called from the Agent Platform and resumes agent execution. Calling <code>doActivate()</code> when the agent is not suspended has no effect. @see jade.core.Agent#doSuspend() */ public void doActivate() { synchronized(stateLock) { if(myAPState == AP_SUSPENDED) { setState(myBufferedState); } } if(myAPState != AP_SUSPENDED) { switch(myBufferedState) { case AP_ACTIVE: activateAllBehaviours(); synchronized(suspendLock) { myBufferedState = AP_MIN; suspendLock.notifyAll(); } break; case AP_WAITING: doWake(); break; } } } /** Make a state transition from <em>active</em> to <em>waiting</em> within Agent Platform Life Cycle. This method can be called by the Agent Platform or by the agent itself and causes the agent to block, stopping all its activities until some event happens. A waiting agent wakes up as soon as a message arrives or when <code>doWake()</code> is called. Calling <code>doWait()</code> on a suspended or waiting agent has no effect. @see jade.core.Agent#doWake() */ public void doWait() { doWait(0); } /** Make a state transition from <em>active</em> to <em>waiting</em> within Agent Platform Life Cycle. This method adds a timeout to the other <code>doWait()</code> version. @param millis The timeout value, in milliseconds. @see jade.core.Agent#doWait() */ public void doWait(long millis) { synchronized(stateLock) { if(myAPState == AP_ACTIVE) setState(AP_WAITING); } if(myAPState == AP_WAITING) { if(myThread.equals(Thread.currentThread())) { waitUntilWake(millis); } } } /** Make a state transition from <em>waiting</em> to <em>active</em> within Agent Platform Life Cycle. This method is called from Agent Platform and resumes agent execution. Calling <code>doWake()</code> when an agent is not waiting has no effect. @see jade.core.Agent#doWait() */ public void doWake() { synchronized(stateLock) { if((myAPState == AP_WAITING) || (myAPState == AP_IDLE)) { setState(AP_ACTIVE); } } if(myAPState == AP_ACTIVE) { activateAllBehaviours(); synchronized(msgQueue) { msgQueue.notifyAll(); // Wakes up the embedded thread } } } // This method handles both the case when the agents decides to exit // and the case in which someone else kills him from outside. /** Make a state transition from <em>active</em>, <em>suspended</em> or <em>waiting</em> to <em>deleted</em> state within Agent Platform Life Cycle, thereby destroying the agent. This method can be called either from the Agent Platform or from the agent itself. Calling <code>doDelete()</code> on an already deleted agent has no effect. */ public void doDelete() { synchronized(stateLock) { if(myAPState != AP_DELETED && !terminating) { setState(AP_DELETED); if(!myThread.equals(Thread.currentThread())) interruptThread(); } } } // This is to be called only by the scheduler void doIdle() { synchronized(stateLock) { if(myAPState != AP_IDLE) setState(AP_IDLE); } } //#MIDP_EXCLUDE_BEGIN /** Write this agent to an output stream; this method can be used to record a snapshot of the agent state on a file or to send it through a network connection. Of course, the whole agent must be serializable in order to be written successfully. @param s The stream this agent will be sent to. The stream is <em>not</em> closed on exit. @exception IOException Thrown if some I/O error occurs during writing. @see jade.core.Agent#read(InputStream s) */ public void write(OutputStream s) throws IOException { ObjectOutput out = new ObjectOutputStream(s); out.writeUTF(myName); out.writeObject(this); } /** Read a previously saved agent from an input stream and restarts it under its former name. This method can realize some sort of mobility through time, where an agent is saved, then destroyed and then restarted from the saved copy. @param s The stream the agent will be read from. The stream is <em>not</em> closed on exit. @exception IOException Thrown if some I/O error occurs during stream reading. @see jade.core.Agent#write(OutputStream s) */ public static void read(InputStream s) throws IOException { try { ObjectInput in = new ObjectInputStream(s); String name = in.readUTF(); Agent a = (Agent)in.readObject(); a.doStart(name); } catch(ClassNotFoundException cnfe) { cnfe.printStackTrace(); } } /** Read a previously saved agent from an input stream and restarts it under a different name. This method can realize agent cloning through streams, where an agent is saved, then an exact copy of it is restarted as a completely separated agent, with the same state but with different identity and address. @param s The stream the agent will be read from. The stream is <em>not</em> closed on exit. @param agentName The name of the new agent, copy of the saved original one. @exception IOException Thrown if some I/O error occurs during stream reading. @see jade.core.Agent#write(OutputStream s) */ public static void read(InputStream s, String agentName) throws IOException { try { ObjectInput in = new ObjectInputStream(s); String oldName = in.readUTF(); Agent a = (Agent)in.readObject(); a.doStart(agentName); } catch(ClassNotFoundException cnfe) { cnfe.printStackTrace(); } } /** This method reads a previously saved agent, replacing the current state of this agent with the one previously saved. The stream must contain the saved state of <b>the same agent</b> that it is trying to restore itself; that is, <em>both</em> the Java object <em>and</em> the agent name must be the same. @param s The input stream the agent state will be read from. @exception IOException Thrown if some I/O error occurs during stream reading. <em>Note: This method is currently not implemented</em> */ public void restore(InputStream s) throws IOException { // FIXME: Not implemented } /** This method should not be used by application code. Use the same-named method of <code>jade.wrapper.Agent</code> instead. @see jade.wrapper.Agent#putO2AObject(Object o, boolean blocking) */ public void putO2AObject(Object o, boolean blocking) throws InterruptedException { // Drop object on the floor if object-to-agent communication is // disabled. if(o2aQueue == null) return; // If the queue has a limited capacity and it is full, discard the // first element if((o2aQueueSize != 0) && (o2aQueue.size() == o2aQueueSize)) o2aQueue.remove(0); o2aQueue.add(o); // Reactivate the agent activateAllBehaviours(); // Synchronize the calling thread on a condition associated to the // object if(blocking) { CondVar cond = new CondVar(); // Store lock for later, when getO2AObject will be called o2aLocks.put(o, cond); // Sleep on the condition cond.waitOn(); } } /** This method picks an object (if present) from the internal object-to-agent communication queue. In order for this method to work, the agent must have declared its will to accept objects from other software components running within its JVM. This can be achieved by calling the <code>jade.core.Agent.setEnabledO2ACommunication()</code> method. If the retrieved object was originally inserted by an external component using a blocking call, that call will return during the execution of this method. @return the first object in the queue, or <code>null</code> if the queue is empty. @see jade.wrapper.Agent#putO2AObject(Object o, boolean blocking) @see jade.core.Agent#setEnabledO2ACommunication(boolean enabled, int queueSize) */ public Object getO2AObject() { // Return 'null' if object-to-agent communication is disabled if(o2aQueue == null) return null; if(o2aQueue.isEmpty()) return null; // Retrieve the first object from the object-to-agent // communication queue Object result = o2aQueue.remove(0); // If some thread issued a blocking putO2AObject() call with this // object, wake it up CondVar cond = (CondVar)o2aLocks.remove(result); if(cond != null) { cond.set(); } return result; } /** This method declares this agent attitude towards object-to-agent communication, that is, whether the agent accepts to communicate with other non-JADE components living within the same JVM. @param enabled Tells whether Java objects inserted with <code>putO2AObject()</code> will be accepted. @param queueSize If the object-to-agent communication is enabled, this parameter specifiies the maximum number of Java objects that will be queued. If the passed value is 0, no maximum limit is set up for the queue. @see jade.wrapper.Agent#putO2AObject(Object o, boolean blocking) @see jade.core.Agent#getO2AObject() */ public void setEnabledO2ACommunication(boolean enabled, int queueSize) { if(enabled) { if(o2aQueue == null) o2aQueue = new ArrayList(queueSize); // Ignore a negative value if(queueSize >= 0) o2aQueueSize = queueSize; } else { // Wake up all threads blocked in putO2AObject() calls Iterator it = o2aLocks.values().iterator(); while(it.hasNext()) { CondVar cv = (CondVar)it.next(); cv.set(); } o2aQueue = null; } } //#MIDP_EXCLUDE_END /** This method is the main body of every agent. It can handle automatically <b>AMS</b> registration and deregistration and provides startup and cleanup hooks for application programmers to put their specific code into. @see jade.core.Agent#setup() @see jade.core.Agent#takeDown() */ public final void run() { try { switch(myAPState) { case AP_INITIATED: setState(AP_ACTIVE); // No 'break' statement - fall through case AP_ACTIVE: notifyStarted(); setup(); break; //#MIDP_EXCLUDE_BEGIN case AP_TRANSIT: doExecute(); afterMove(); break; case AP_COPY: doExecute(); afterClone(); break; //#MIDP_EXCLUDE_END } mainLoop(); } catch(InterruptedException ie) { // Do Nothing, since this is a killAgent from outside } catch(InterruptedIOException iioe) { // Do nothing, since this is a killAgent from outside } catch(Exception e) { System.err.println("*** Uncaught Exception for agent " + myName + " ***"); e.printStackTrace(); } catch(AgentDeathError ade) { // Do Nothing, since this is a killAgent from outside } //#MIDP_EXCLUDE_BEGIN catch(AgentInMotionError aime) { // This is a move from the outside while the agent was waiting // (blockingReceive()) outside the mainLoop(). There is nothing // we can do } //#MIDP_EXCLUDE_END finally { //#MIDP_EXCLUDE_BEGIN switch(myAPState) { case AP_TRANSIT: case AP_COPY: System.err.println("*** Agent " + myName + " moved in a forbidden situation ***"); // No break statement --> fall through case AP_DELETED: terminating = true; int savedState = getState(); setState(AP_ACTIVE); takeDown(); destroy(); setState(savedState); break; case AP_GONE: break; default: terminating = true; System.out.println("ERROR: Agent " + myName + " died without being properly terminated !!!"); System.out.println("State was " + myAPState); savedState = getState(); setState(AP_ACTIVE); takeDown(); destroy(); setState(savedState); } //#MIDP_EXCLUDE_END /*#MIDP_INCLUDE_BEGIN if (myAPState != AP_DELETED) { System.out.println("ERROR: Agent "+myName+" died without being properly terminated !!!"); System.out.println("State was "+myAPState); } terminating = true; int savedState = getState(); setState(AP_ACTIVE); takeDown(); destroy(); setState(savedState); #MIDP_INCLUDE_END*/ } } /** This protected method is an empty placeholder for application specific startup code. Agent developers can override it to provide necessary behaviour. When this method is called the agent has been already registered with the Agent Platform <b>AMS</b> and is able to send and receive messages. However, the agent execution model is still sequential and no behaviour scheduling is active yet. This method can be used for ordinary startup tasks such as <b>DF</b> registration, but is essential to add at least a <code>Behaviour</code> object to the agent, in order for it to be able to do anything. @see jade.core.Agent#addBehaviour(Behaviour b) @see jade.core.behaviours.Behaviour */ protected void setup() {} /** This protected method is an empty placeholder for application specific cleanup code. Agent developers can override it to provide necessary behaviour. When this method is called the agent has not deregistered itself with the Agent Platform <b>AMS</b> and is still able to exchange messages with other agents. However, no behaviour scheduling is active anymore and the Agent Platform Life Cycle state is already set to <em>deleted</em>. This method can be used for ordinary cleanup tasks such as <b>DF</b> deregistration, but explicit removal of all agent behaviours is not needed. */ protected void takeDown() {} //#MIDP_EXCLUDE_BEGIN /** Actions to perform before moving. This empty placeholder method can be overridden by user defined agents to execute some actions just before leaving an agent container for a migration. */ protected void beforeMove() {} /** Actions to perform after moving. This empty placeholder method can be overridden by user defined agents to execute some actions just after arriving to the destination agent container for a migration. */ protected void afterMove() {} /** Actions to perform before cloning. This empty placeholder method can be overridden by user defined agents to execute some actions just before copying an agent to another agent container. */ protected void beforeClone() {} /** Actions to perform after cloning. This empty placeholder method can be overridden by user defined agents to execute some actions just after creating an agent copy to the destination agent container. */ protected void afterClone() {} //#MIDP_EXCLUDE_END // This method is used by the Agent Container to fire up a new agent for the first time void powerUp(AID id, Thread t) { // Set this agent's name and address and start its embedded thread if ( (myAPState == AP_INITIATED) //#MIDP_EXCLUDE_BEGIN || (myAPState == AP_TRANSIT) || (myAPState == AP_COPY) //#MIDP_EXCLUDE_END ) { myName = id.getLocalName(); myHap = id.getHap(); synchronized (this) { // Mutual exclusion with Agent.addPlatformAddress() myAID = id; myToolkit.setPlatformAddresses(myAID); } //myThread = rm.getThread(ResourceManager.USER_AGENTS, getLocalName(), this); myThread = t; myThread.start(); } } //#MIDP_EXCLUDE_BEGIN private void writeObject(ObjectOutputStream out) throws IOException { // Updates the queue maximum size field, before serialising msgQueueMaxSize = msgQueue.getMaxSize(); out.defaultWriteObject(); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); // Restore transient fields (apart from myThread, which will be set by doStart()) msgQueue = new MessageQueue(msgQueueMaxSize); stateLock = new Object(); suspendLock = new Object(); principalLock = new Object(); pendingTimers = new AssociationTB(); theDispatcher = TimerDispatcher.getTimerDispatcher(); // restore O2AQueue if (o2aQueueSize > 0) o2aQueue = new ArrayList(o2aQueueSize); o2aLocks = new HashMap(); myToolkit = DummyToolkit.instance(); } //#MIDP_EXCLUDE_END private void mainLoop() throws InterruptedException, InterruptedIOException { while(myAPState != AP_DELETED) { //#MIDP_EXCLUDE_BEGIN try { //#MIDP_EXCLUDE_END // Check for Agent state changes switch(myAPState) { case AP_WAITING: waitUntilWake(0); break; case AP_SUSPENDED: waitUntilActivate(); break; //#MIDP_EXCLUDE_BEGIN case AP_TRANSIT: try { notifyMove(); } catch (Exception e) { // something went wrong setState(myBufferedState); myDestination = null; throw e; } if(myAPState == AP_GONE) { beforeMove(); return; } break; case AP_COPY: beforeClone(); try { notifyCopy(); } catch (Exception e) { // something went wrong setState(myBufferedState); myDestination = null; throw e; } doExecute(); break; //#MIDP_EXCLUDE_END case AP_ACTIVE: try { // Select the next behaviour to execute int oldState = myAPState; currentBehaviour = myScheduler.schedule(); if((myAPState != oldState) && (myAPState != AP_DELETED)) setState(oldState); // Remember how many messages arrived int oldMsgCounter = messageCounter; // Just do it! currentBehaviour.actionWrapper(); // If the current Behaviour has blocked and more messages arrived // in the meanwhile, restart the behaviour to give it another chance if((oldMsgCounter != messageCounter) && (!currentBehaviour.isRunnable())) currentBehaviour.restart(); // When it is needed no more, delete it from the behaviours queue if(currentBehaviour.done()) { currentBehaviour.onEnd(); myScheduler.remove(currentBehaviour); currentBehaviour = null; } else { synchronized(myScheduler) { // Need synchronized block (Crais Sayers, HP): What if // 1) it checks to see if its runnable, sees its not, // so it begins to enter the body of the if clause // 2) meanwhile, in another thread, a message arrives, so // the behaviour is restarted and moved to the ready list. // 3) now back in the first thread, the agent executes the // body of the if clause and, by calling block(), moves // the behaviour back to the blocked list. if(!currentBehaviour.isRunnable()) { // Remove blocked behaviour from ready behaviours queue // and put it in blocked behaviours queue myScheduler.block(currentBehaviour); currentBehaviour = null; } } } } // Someone interrupted the agent. It could be a kill or a // move/clone request... catch(InterruptedException ie) { switch(myAPState) { case AP_DELETED: throw new AgentDeathError(); //#MIDP_EXCLUDE_BEGIN case AP_TRANSIT: case AP_COPY: throw new AgentInMotionError(); //#MIDP_EXCLUDE_END case AP_ACTIVE: case AP_IDLE: System.out.println("WARNING: Spurious wakeup for agent " + getLocalName()); break; } } // end catch break; } // END of switch on agent state // Now give CPU control to other agents Thread.yield(); //#MIDP_EXCLUDE_BEGIN } catch(AgentInMotionError aime) { // Do nothing, since this is a doMove() or doClone() from the outside. } catch(AuthException e) { // FIXME: maybe should send a message to the agent System.out.println("AuthException: "+e.getMessage() ); } catch(Exception ie) { // shouuld never happen ie.printStackTrace(); } //#MIDP_EXCLUDE_END } // END of while } private void waitUntilWake(long millis) { synchronized(msgQueue) { long timeToWait = millis; while(myAPState == AP_WAITING) { try { long startTime = System.currentTimeMillis(); // Blocks on msgQueue monitor for a while waitOn(msgQueue, timeToWait); long elapsedTime = System.currentTimeMillis() - startTime; // If this was a timed wait, update time to wait; if the // total time has passed, wake up. if(millis != 0) { timeToWait -= elapsedTime; if(timeToWait <= 0) setState(AP_ACTIVE); } } catch(InterruptedException ie) { switch(myAPState) { case AP_DELETED: throw new AgentDeathError(); //#MIDP_EXCLUDE_BEGIN case AP_TRANSIT: case AP_COPY: throw new AgentInMotionError(); //#MIDP_EXCLUDE_END } } } } } private void waitUntilActivate() { synchronized(suspendLock) { while(myAPState == AP_SUSPENDED) { try { waitOn(suspendLock, 0); } catch(InterruptedException ie) { switch(myAPState) { case AP_DELETED: throw new AgentDeathError(); //#MIDP_EXCLUDE_BEGIN case AP_TRANSIT: case AP_COPY: // Undo the previous clone or move request setState(AP_SUSPENDED); //#MIDP_EXCLUDE_END } } } } } private void destroy() { // Remove all pending timers Enumeration e = pendingTimers.timers(); while (e.hasMoreElements()) { Timer t = (Timer) e.nextElement(); theDispatcher.remove(t); } notifyDestruction(); } /** This method adds a new behaviour to the agent. This behaviour will be executed concurrently with all the others, using a cooperative round robin scheduling. This method is typically called from an agent <code>setup()</code> to fire off some initial behaviour, but can also be used to spawn new behaviours dynamically. @param b The new behaviour to add to the agent. @see jade.core.Agent#setup() @see jade.core.behaviours.Behaviour */ public void addBehaviour(Behaviour b) { b.setAgent(this); myScheduler.add(b); } /** This method removes a given behaviour from the agent. This method is called automatically when a top level behaviour terminates, but can also be called from a behaviour to terminate itself or some other behaviour. @param b The behaviour to remove. @see jade.core.behaviours.Behaviour */ public void removeBehaviour(Behaviour b) { b.setAgent(null); myScheduler.remove(b); } /** Send an <b>ACL</b> message to another agent. This methods sends a message to the agent specified in <code>:receiver</code> message field (more than one agent can be specified as message receiver). @param msg An ACL message object containing the actual message to send. @see jade.lang.acl.ACLMessage */ public final void send(final ACLMessage msg) { //#MIDP_EXCLUDE_BEGIN try { doPrivileged(new jade.security.PrivilegedExceptionAction() { public Object run() throws AuthException { notifySend(msg); return null; } }); } catch (AuthException e) { System.out.println("AuthException: "+e.getMessage() );; } catch (Exception e) { e.printStackTrace(); } //#MIDP_EXCLUDE_END /*#MIDP_INCLUDE_BEGIN try { myToolkit.handleSend(msg, myAID); } catch (AuthException ae) { } #MIDP_INCLUDE_END*/ } /** Receives an <b>ACL</b> message from the agent message queue. This method is non-blocking and returns the first message in the queue, if any. Therefore, polling and busy waiting is required to wait for the next message sent using this method. @return A new ACL message, or <code>null</code> if no message is present. @see jade.lang.acl.ACLMessage */ public final ACLMessage receive() { return receive(null); } /** Receives an <b>ACL</b> message matching a given template. This method is non-blocking and returns the first matching message in the queue, if any. Therefore, polling and busy waiting is required to wait for a specific kind of message using this method. @param pattern A message template to match received messages against. @return A new ACL message matching the given template, or <code>null</code> if no such message is present. @see jade.lang.acl.ACLMessage @see jade.lang.acl.MessageTemplate */ public final ACLMessage receive(MessageTemplate pattern) { ACLMessage msg = null; synchronized (msgQueue) { for (Iterator messages = msgQueue.iterator(); messages.hasNext(); ) { final ACLMessage cursor = (ACLMessage)messages.next(); if (pattern == null || pattern.match(cursor)) { try { messages.remove(); //!!! msgQueue.remove(msg); //#MIDP_EXCLUDE_BEGIN notifyReceived(cursor); //#MIDP_EXCLUDE_END currentMessage = cursor; msg = cursor; break; // Exit while loop } catch (Exception e) { // Continue loop, discard message } } } } return msg; } /** Receives an <b>ACL</b> message from the agent message queue. This method is blocking and suspends the whole agent until a message is available in the queue. JADE provides a special behaviour named <code>ReceiverBehaviour</code> to wait for a message within a behaviour without suspending all the others and without wasting CPU time doing busy waiting. @return A new ACL message, blocking the agent until one is available. @see jade.lang.acl.ACLMessage @see jade.core.behaviours.ReceiverBehaviour */ public final ACLMessage blockingReceive() { ACLMessage msg = null; while(msg == null) { msg = blockingReceive(0); } return msg; } /** Receives an <b>ACL</b> message from the agent message queue, waiting at most a specified amount of time. @param millis The maximum amount of time to wait for the message. @return A new ACL message, or <code>null</code> if the specified amount of time passes without any message reception. */ public final ACLMessage blockingReceive(long millis) { synchronized(msgQueue) { ACLMessage msg = receive(); if(msg == null) { doWait(millis); msg = receive(); } return msg; } } /** Receives an <b>ACL</b> message matching a given message template. This method is blocking and suspends the whole agent until a message is available in the queue. JADE provides a special behaviour named <code>ReceiverBehaviour</code> to wait for a specific kind of message within a behaviour without suspending all the others and without wasting CPU time doing busy waiting. @param pattern A message template to match received messages against. @return A new ACL message matching the given template, blocking until such a message is available. @see jade.lang.acl.ACLMessage @see jade.lang.acl.MessageTemplate @see jade.core.behaviours.ReceiverBehaviour */ public final ACLMessage blockingReceive(MessageTemplate pattern) { ACLMessage msg = null; while(msg == null) { msg = blockingReceive(pattern, 0); } return msg; } /** Receives an <b>ACL</b> message matching a given message template, waiting at most a specified time. @param pattern A message template to match received messages against. @param millis The amount of time to wait for the message, in milliseconds. @return A new ACL message matching the given template, or <code>null</code> if no suitable message was received within <code>millis</code> milliseconds. @see jade.core.Agent#blockingReceive() */ public final ACLMessage blockingReceive(MessageTemplate pattern, long millis) { ACLMessage msg = null; synchronized(msgQueue) { msg = receive(pattern); long timeToWait = millis; while(msg == null) { long startTime = System.currentTimeMillis(); //#MIDP_EXCLUDE_BEGIN doWait(timeToWait); //#MIDP_EXCLUDE_END /*#MIDP_INCLUDE_BEGIN // As Thread.interrupt() is substituted by interruptThread(), // it is possible to enter this method with the agent state // equals to AP_DELETED. If this is the case the loop // lasts forever as doWait() does nothing -->the monitor // of the waitLock is not released --> even if a message arrive // the postMessage method can't be executed. // Throwing AgentDeathError is necessary to exit this infinite loop. if (myAPState == AP_ACTIVE) { doWait(timeToWait); } else { throw new AgentDeathError(); } #MIDP_INCLUDE_END*/ long elapsedTime = System.currentTimeMillis() - startTime; msg = receive(pattern); if(millis != 0) { timeToWait -= elapsedTime; if(timeToWait <= 0) break; } } } return msg; } /** Puts a received <b>ACL</b> message back into the message queue. This method can be used from an agent behaviour when it realizes it read a message of interest for some other behaviour. The message is put in front of the message queue, so it will be the first returned by a <code>receive()</code> call. @see jade.core.Agent#receive() */ public final void putBack(ACLMessage msg) { synchronized(msgQueue) { msgQueue.addFirst(msg); } } final void setToolkit(AgentToolkit at) { myToolkit = at; } final void resetToolkit() { //#MIDP_EXCLUDE_BEGIN myToolkit = DummyToolkit.instance(); //#MIDP_EXCLUDE_END /*#MIDP_INCLUDE_BEGIN myToolkit = null; #MIDP_INCLUDE_END*/ } /** This method blocks until the agent has finished its start-up phase (i.e. until just before its setup() method is called. When this method returns, the target agent is registered with the AMS and the JADE platform is aware of it. */ public synchronized void waitUntilStarted() { while(getState() == AP_INITIATED) { try { wait(); } catch(InterruptedException ie) { // Do nothing... } } } // Event firing methods // Notify creator that the start-up phase has completed private synchronized void notifyStarted() { notifyAll(); } // Notify toolkit of the destruction of the current agent private void notifyDestruction() { myToolkit.handleEnd(myAID); } //#MIDP_EXCLUDE_BEGIN // Notify toolkit that a message was posted in the message queue private void notifyPosted(ACLMessage msg) throws AuthException { myToolkit.handlePosted(myAID, msg); } // Notify toolkit that a message was extracted from the message // queue private void notifyReceived(ACLMessage msg) throws AuthException { myToolkit.handleReceived(myAID, msg); } // Notify toolkit of the need to send a message private void notifySend(ACLMessage msg) throws AuthException { myToolkit.handleSend(msg, myAID); } // Notify toolkit of the need to move the current agent private void notifyMove() throws AuthException, IMTPException, NotFoundException { myToolkit.handleMove(myAID, myDestination); } // Notify toolkit of the need to copy the current agent private void notifyCopy() throws AuthException, IMTPException, NotFoundException { myToolkit.handleClone(myAID, myDestination, myNewName); } // Notify toolkit of the added behaviour // Package scooped as it is called by the Scheduler void notifyAddBehaviour(Behaviour b) { if (generateBehaviourEvents) { myToolkit.handleBehaviourAdded(myAID, b); } } // Notify the toolkit of the removed behaviour // Package scooped as it is called by the Scheduler void notifyRemoveBehaviour(Behaviour b) { if (generateBehaviourEvents) { myToolkit.handleBehaviourRemoved(myAID, b); } } // Notify the toolkit of the change in behaviour state // Public as it is called by the Scheduler and by the Behaviour class public void notifyChangeBehaviourState(Behaviour b, String from, String to) { if (generateBehaviourEvents) { myToolkit.handleChangeBehaviourState(myAID, b, from, to); } } // Package scoped as it is called by the RealNotificationManager public void setGenerateBehaviourEvents(boolean b) { generateBehaviourEvents = b; } // Notify toolkit that the current agent has changed its state private void notifyChangedAgentState(int oldState, int newState) { AgentState from = STATES[oldState]; AgentState to = STATES[newState]; myToolkit.handleChangedAgentState(myAID, from, to); } // Notify toolkit that the current agent has changed its principal private void notifyChangedAgentPrincipal(AgentPrincipal from, CertificateFolder certs) { myToolkit.handleChangedAgentPrincipal(myAID, from, certs); } //#MIDP_EXCLUDE_END private void activateAllBehaviours() { myScheduler.restartAll(); } /** Put a received message into the agent message queue. The message is put at the back end of the queue. This method is called by JADE runtime system when a message arrives, but can also be used by an agent, and is just the same as sending a message to oneself (though slightly faster). @param msg The ACL message to put in the queue. @see jade.core.Agent#send(ACLMessage msg) */ public final void postMessage(final ACLMessage msg) { synchronized (msgQueue) { if (msg != null) { //#MIDP_EXCLUDE_BEGIN try { doPrivileged(new PrivilegedExceptionAction() { public Object run() throws AuthException { // notification appens first so, if an exception // is thrown, then message isn't appended to queue notifyPosted(msg); msgQueue.addLast(msg); return null; } }); } catch (AuthException e) { System.out.println("AuthException: "+e.getMessage() ); //e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } //#MIDP_EXCLUDE_END /*#MIDP_INCLUDE_BEGIN msgQueue.addLast(msg); #MIDP_INCLUDE_END*/ doWake(); messageCounter++; } } } private ContentManager theContentManager = null; /** * Retrieves the agent's content manager * @return The content manager. */ public ContentManager getContentManager() { if (theContentManager == null) { theContentManager = new ContentManager(); } return theContentManager; } /** Retrieve a configuration property set in the <code>Profile</code> of the local container (first) or as a System property. @param key the key that maps to the property that has to be retrieved. @param aDefault a default value to be returned if there is no mapping for <code>key</code> */ public String getProperty(String key, String aDefault) { String val = myToolkit.getProperty(key, aDefault); if (val == null || val.equals(aDefault)) { // Try among the System properties String sval = System.getProperty(key); if (sval != null) { val = sval; } } return val; } /** This method is used to interrupt the agent's thread. In J2SE/PJAVA it just calls myThread.interrupt(). In MIDP, where interrupt() is not supported the thread interruption is simulated as described below. The agent thread can be in one of the following four states: 1) Running a behaviour. 2) Sleeping on msgQueue due to a doWait() 3) Sleeping on suspendLock due to a doSuspend() 4) Sleeping on myScheduler due to a schedule() with no active behaviours The idea is: set the 'isInterrupted' flag, then wake up the thread wherever it may be */ private void interruptThread() { //#MIDP_EXCLUDE_BEGIN myThread.interrupt(); //#MIDP_EXCLUDE_END /*#MIDP_INCLUDE_BEGIN synchronized (this) { isInterrupted = true; // case 1: Nothing to do. // case 2: Signal on msgQueue. synchronized (msgQueue) {msgQueue.notifyAll();} // case 3: Signal on suspendLock object. synchronized (suspendLock) {suspendLock.notifyAll();} // case 4: Signal on the Scheduler synchronized (myScheduler) {myScheduler.notifyAll();} } #MIDP_INCLUDE_END*/ } /** Since in MIDP Thread.interrupt() does not exist and a simulated interruption is used to "interrupt" the agent's thread, we must check whether the simulated interruption happened just before and after going to sleep. */ void waitOn(Object lock, long millis) throws InterruptedException { /*#MIDP_INCLUDE_BEGIN synchronized (this) { if (isInterrupted) { isInterrupted = false; throw new InterruptedException(); } } #MIDP_INCLUDE_END*/ lock.wait(millis); /*#MIDP_INCLUDE_BEGIN synchronized (this) { if (isInterrupted) { isInterrupted = false; throw new InterruptedException(); } } #MIDP_INCLUDE_END*/ } }
package jade.core; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; import java.io.Serializable; import java.io.InterruptedIOException; import java.util.Date; import java.util.Iterator; import java.util.Vector; import jade.core.behaviours.Behaviour; import jade.lang.acl.*; import jade.domain.AgentManagementOntology; import jade.domain.FIPAException; /** The <code>Agent</code> class is the common superclass for user defined software agents. It provides methods to perform basic agent tasks, such as: <ul> <li> <b> Message passing using <code>ACLMessage</code> objects, both unicast and multicast with optional pattern matching. </b> <li> <b> Complete Agent Platform life cycle support, including starting, suspending and killing an agent. </b> <li> <b> Scheduling and execution of multiple concurrent activities. </b> <li> <b> Simplified interaction with <em>FIPA</em> system agents for automating common agent tasks (DF registration, etc.). </b> </ul> Application programmers must write their own agents as <code>Agent</code> subclasses, adding specific behaviours as needed and exploiting <code>Agent</code> class capabilities. @author Giovanni Rimassa - Universita` di Parma @version $Date$ $Revision$ */ public class Agent implements Runnable, Serializable, CommBroadcaster { // This inner class is used to force agent termination when a signal // from the outside is received private class AgentDeathError extends Error { AgentDeathError() { super("Agent " + Thread.currentThread().getName() + " has been terminated."); } } /** Out of band value for Agent Platform Life Cycle states. */ public static final int AP_MIN = 0; // Hand-made type checking /** Represents the <em>initiated</em> agent state. */ public static final int AP_INITIATED = 1; /** Represents the <em>active</em> agent state. */ public static final int AP_ACTIVE = 2; /** Represents the <em>suspended</em> agent state. */ public static final int AP_SUSPENDED = 3; /** Represents the <em>waiting</em> agent state. */ public static final int AP_WAITING = 4; /** Represents the <em>deleted</em> agent state. */ public static final int AP_DELETED = 5; /** Out of band value for Agent Platform Life Cycle states. */ public static final int AP_MAX = 6; // Hand-made type checking /** These constants represent the various Domain Life Cycle states */ /** Out of band value for Domain Life Cycle states. */ public static final int D_MIN = 9; // Hand-made type checking /** Represents the <em>active</em> agent state. */ public static final int D_ACTIVE = 10; /** Represents the <em>suspended</em> agent state. */ public static final int D_SUSPENDED = 20; /** Represents the <em>retired</em> agent state. */ public static final int D_RETIRED = 30; /** Represents the <em>unknown</em> agent state. */ public static final int D_UNKNOWN = 40; /** Out of band value for Domain Life Cycle states. */ public static final int D_MAX = 41; // Hand-made type checking /** Default value for message queue size. When the number of buffered messages exceeds this value, older messages are discarded according to a <b><em>FIFO</em></b> replacement policy. @see jade.core.Agent#setQueueSize(int newSize) @see jade.core.Agent#getQueueSize() */ public static final int MSG_QUEUE_SIZE = 100; private MessageQueue msgQueue = new MessageQueue(MSG_QUEUE_SIZE); private Vector listeners = new Vector(); private String myName = null; private String myAddress = null; private Object stateLock = new Object(); // Used to make state transitions atomic private Object waitLock = new Object(); // Used for agent waiting private Object suspendLock = new Object(); // Used for agent suspension private Thread myThread; private Scheduler myScheduler; /** The <code>Behaviour</code> that is currently executing. @see jade.core.Behaviour */ protected Behaviour currentBehaviour; /** Last message received. @see jade.lang.acl.ACLMessage */ protected ACLMessage currentMessage; // This variable is 'volatile' because is used as a latch to signal // agent suspension and termination from outside world. private volatile int myAPState; // Temporary buffer for agent suspension private int myBufferedState = AP_MIN; private int myDomainState; private Vector blockedBehaviours = new Vector(); private ACLParser myParser = ACLParser.create(); /** Default constructor. */ public Agent() { myAPState = AP_INITIATED; myDomainState = D_UNKNOWN; myScheduler = new Scheduler(this); } /** Method to query the agent local name. @return A <code>String</code> containing the local agent name (e.g. <em>peter</em>). */ public String getLocalName() { return myName; } /** Method to query the agent complete name (<em><b>GUID</b></em>). @return A <code>String</code> containing the complete agent name (e.g. <em>peter@iiop://fipa.org:50/acc</em>). */ public String getName() { return myName + '@' + myAddress; } /** Method to query the agent home address. This is the address of the platform where the agent was created, and will never change during the whole lifetime of the agent. @return A <code>String</code> containing the agent home address (e.g. <em>iiop://fipa.org:50/acc</em>). */ public String getAddress() { return myAddress; } // This is used by the agent container to wait for agent termination void join() { try { myThread.join(); } catch(InterruptedException ie) { ie.printStackTrace(); } } public void setQueueSize(int newSize) throws IllegalArgumentException { msgQueue.setMaxSize(newSize); } /** Reads message queue size. A zero value means that the message queue is unbounded (its size is limited only by amount of available memory). @return The actual size of the message queue. @see jade.core.Agent#setQueueSize(int newSize) */ public int getQueueSize() { return msgQueue.getMaxSize(); } /** Schedules a restart for a behaviour, after a certain amount of time has passed. */ public void restartLater(Behaviour b, long millis) { } /** Read current agent state. This method can be used to query an agent for its state from the outside. @return the Agent Platform Life Cycle state this agent is currently in. */ public int getState() { return myAPState; } // State transition methods for Agent Platform Life-Cycle /** Make a state transition from <em>initiated</em> to <em>active</em> within Agent Platform Life Cycle. Agents are started automatically by JADE on agent creation and should not be used by application developers, unless creating some kind of agent factory. This method starts the embedded thread of the agent. @param name The local name of the agent. */ public void doStart(String name) { AgentContainerImpl thisContainer = Starter.getContainer(); try { thisContainer.createAgent(name, this, AgentContainer.START); } catch(java.rmi.RemoteException jrre) { jrre.printStackTrace(); } } void doStart(String name, String platformAddress, ThreadGroup myGroup) { // Set this agent's name and address and start its embedded thread if(myAPState == AP_INITIATED) { myAPState = AP_ACTIVE; myName = new String(name); myAddress = new String(platformAddress); myThread = new Thread(myGroup, this); myThread.setName(myName); myThread.setPriority(myGroup.getMaxPriority()); myThread.start(); } } /** Make a state transition from <em>active</em> to <em>initiated</em> within Agent Platform Life Cycle. This method is intended to support agent mobility and is called either by the Agent Platform or by the agent itself to start migration process. <em>This method is currently not implemented.</em> */ public void doMove() { // myAPState = AP_INITIATED; // FIXME: Should do something more } /** Make a state transition from <em>active</em> or <em>waiting</em> to <em>suspended</em> within Agent Platform Life Cycle; the original agent state is saved and will be restored by a <code>doActivate()</code> call. This method can be called from the Agent Platform or from the agent iself and stops all agent activities. Incoming messages for a suspended agent are buffered by the Agent Platform and are delivered as soon as the agent resumes. Calling <code>doSuspend()</code> on a suspended agent has no effect. @see jade.core.Agent#doActivate() */ public void doSuspend() { synchronized(stateLock) { if((myAPState == AP_ACTIVE)||(myAPState == AP_WAITING)) { myBufferedState = myAPState; myAPState = AP_SUSPENDED; } } if(myAPState == AP_SUSPENDED) { if(myThread.equals(Thread.currentThread())) { waitUntilActivate(); } } } /** Make a state transition from <em>suspended</em> to <em>active</em> or <em>waiting</em> (whichever state the agent was in when <code>doSuspend()</code> was called) within Agent Platform Life Cycle. This method is called from the Agent Platform and resumes agent execution. Calling <code>doActivate()</code> when the agent is not suspended has no effect. @see jade.core.Agent#doSuspend() */ public void doActivate() { synchronized(stateLock) { if(myAPState == AP_SUSPENDED) { myAPState = myBufferedState; } } if(myAPState != AP_SUSPENDED) { switch(myBufferedState) { case AP_ACTIVE: activateAllBehaviours(); synchronized(suspendLock) { myBufferedState = AP_MIN; suspendLock.notify(); } break; case AP_WAITING: doWake(); break; } } } /** Make a state transition from <em>active</em> to <em>waiting</em> within Agent Platform Life Cycle. This method can be called by the Agent Platform or by the agent itself and causes the agent to block, stopping all its activities until some event happens. A waiting agent wakes up as soon as a message arrives or when <code>doWake()</code> is called. Calling <code>doWait()</code> on a suspended or waiting agent has no effect. @see jade.core.Agent#doWake() */ public void doWait() { doWait(0); } /** Make a state transition from <em>active</em> to <em>waiting</em> within Agent Platform Life Cycle. This method adds a timeout to the other <code>doWait()</code> version. @param millis The timeout value, in milliseconds. @see jade.core.Agent#doWait() */ public void doWait(long millis) { synchronized(stateLock) { if(myAPState == AP_ACTIVE) myAPState = AP_WAITING; } if(myAPState == AP_WAITING) { if(myThread.equals(Thread.currentThread())) { waitUntilWake(millis); } } } /** Make a state transition from <em>waiting</em> to <em>active</em> within Agent Platform Life Cycle. This method is called from Agent Platform and resumes agent execution. Calling <code>doWake()</code> when an agent is not waiting has no effect. @see jade.core.Agent#doWait() */ public void doWake() { synchronized(stateLock) { if(myAPState == AP_WAITING) { myAPState = AP_ACTIVE; } } if(myAPState == AP_ACTIVE) { activateAllBehaviours(); synchronized(waitLock) { waitLock.notify(); // Wakes up the embedded thread } } } // This method handles both the case when the agents decides to exit // and the case in which someone else kills him from outside. /** Make a state transition from <em>active</em>, <em>suspended</em> or <em>waiting</em> to <em>deleted</em> state within Agent Platform Life Cycle, thereby destroying the agent. This method can be called either from the Agent Platform or from the agent itself. Calling <code>doDelete()</code> on an already deleted agent has no effect. */ public void doDelete() { if(myAPState != AP_DELETED) { myAPState = AP_DELETED; if(!myThread.equals(Thread.currentThread())) myThread.interrupt(); } } /** This method is the main body of every agent. It can handle automatically <b>AMS</b> registration and deregistration and provides startup and cleanup hooks for application programmers to put their specific code into. @see jade.core.Agent#setup() @see jade.core.Agent#takeDown() */ public final void run() { try{ registerWithAMS(null,Agent.AP_ACTIVE,null,null,null); setup(); mainLoop(); } catch(InterruptedException ie) { // Do Nothing, since this is a killAgent from outside } catch(InterruptedIOException iioe) { // Do nothing, since this is a killAgent from outside } catch(Exception e) { System.err.println("*** Uncaught Exception for agent " + myName + " ***"); e.printStackTrace(); } catch(AgentDeathError ade) { // Do Nothing, since this is a killAgent from outside } finally { takeDown(); destroy(); } } /** This protected method is an empty placeholder for application specific startup code. Agent developers can override it to provide necessary behaviour. When this method is called the agent has been already registered with the Agent Platform <b>AMS</b> and is able to send and receive messages. However, the agent execution model is still sequential and no behaviour scheduling is active yet. This method can be used for ordinary startup tasks such as <b>DF</b> registration, but is essential to add at least a <code>Behaviour</code> object to the agent, in order for it to be able to do anything. @see jade.core.Agent#addBehaviour(Behaviour b) @see jade.core.Behaviour */ protected void setup() {} /** This protected method is an empty placeholder for application specific cleanup code. Agent developers can override it to provide necessary behaviour. When this method is called the agent has not deregistered itself with the Agent Platform <b>AMS</b> and is still able to exchange messages with other agents. However, no behaviour scheduling is active anymore and the Agent Platform Life Cycle state is already set to <em>deleted</em>. This method can be used for ordinary cleanup tasks such as <b>DF</b> deregistration, but explicit removal of all agent behaviours is not needed. */ protected void takeDown() {} private void mainLoop() throws InterruptedException, InterruptedIOException { while(myAPState != AP_DELETED) { // Select the next behaviour to execute currentBehaviour = myScheduler.schedule(); // Just do it! currentBehaviour.action(); // Check for Agent state changes switch(myAPState) { case AP_WAITING: waitUntilWake(0); break; case AP_SUSPENDED: waitUntilActivate(); break; case AP_DELETED: return; case AP_ACTIVE: break; } // When it is needed no more, delete it from the behaviours queue if(currentBehaviour.done()) { myScheduler.remove(currentBehaviour); currentBehaviour = null; } else if(!currentBehaviour.isRunnable()) { // Remove blocked behaviours from scheduling queue and put it // in blocked behaviours queue myScheduler.remove(currentBehaviour); blockedBehaviours.addElement(currentBehaviour); currentBehaviour = null; } // Now give CPU control to other agents Thread.yield(); } } private void waitUntilWake(long millis) { synchronized(waitLock) { long timeToWait = millis; while(myAPState == AP_WAITING) { try { long startTime = System.currentTimeMillis(); waitLock.wait(timeToWait); // Blocks on waiting state monitor for a while long elapsedTime = System.currentTimeMillis() - startTime; timeToWait -= elapsedTime; // If this was a timed wait and the total time has passed, wake up. if((millis != 0) && (timeToWait <= 0)) myAPState = AP_ACTIVE; } catch(InterruptedException ie) { myAPState = AP_DELETED; throw new AgentDeathError(); } } } } private void waitUntilActivate() { synchronized(suspendLock) { while(myAPState == AP_SUSPENDED) { try { suspendLock.wait(); // Blocks on suspended state monitor } catch(InterruptedException ie) { myAPState = AP_DELETED; throw new AgentDeathError(); } } } } private void destroy() { try { deregisterWithAMS(); } catch(FIPAException fe) { fe.printStackTrace(); } notifyDestruction(); } /** This method adds a new behaviour to the agent. This behaviour will be executed concurrently with all the others, using a cooperative round robin scheduling. This method is typically called from an agent <code>setup()</code> to fire off some initial behaviour, but can also be used to spawn new behaviours dynamically. @param b The new behaviour to add to the agent. @see jade.core.Agent#setup() @see jade.core.Behaviour */ public void addBehaviour(Behaviour b) { myScheduler.add(b); } /** This method removes a given behaviour from the agent. This method is called automatically when a top level behaviour terminates, but can also be called from a behaviour to terminate itself or some other behaviour. @param b The behaviour to remove. @see jade.core.Behaviour */ public void removeBehaviour(Behaviour b) { myScheduler.remove(b); } /** Send an <b>ACL</b> message to another agent. This methods sends a message to the agent specified in <code>:receiver</code> message field (more than one agent can be specified as message receiver). @param msg An ACL message object containing the actual message to send. @see jade.lang.acl.ACLMessage */ public final void send(ACLMessage msg) { if(msg.getSource() == null) msg.setSource(myName); CommEvent event = new CommEvent(this, msg); broadcastEvent(event); } /** Send an <b>ACL</b> message to the agent contained in a given <code>AgentGroup</code>. This method allows simple message multicast to be done. A similar result can be obtained putting many agent names in <code>:receiver</code> message field; the difference is that in that case every receiver agent can read all other receivers' names, whereas this method hides multicasting to receivers. @param msg An ACL message object containing the actual message to send. @param g An agent group object holding all receivers names. @see jade.lang.acl.ACLMessage @see jade.core.AgentGroup */ public final void send(ACLMessage msg, AgentGroup g) { if(msg.getSource() == null) msg.setSource(myName); CommEvent event = new CommEvent(this, msg, g); broadcastEvent(event); } /** Receives an <b>ACL</b> message from the agent message queue. This method is non-blocking and returns the first message in the queue, if any. Therefore, polling and busy waiting is required to wait for the next message sent using this method. @return A new ACL message, or <code>null</code> if no message is present. @see jade.lang.acl.ACLMessage */ public final ACLMessage receive() { synchronized(waitLock) { if(msgQueue.isEmpty()) { return null; } else { currentMessage = msgQueue.removeFirst(); return currentMessage; } } } /** Receives an <b>ACL</b> message matching a given template. This method is non-blocking and returns the first matching message in the queue, if any. Therefore, polling and busy waiting is required to wait for a specific kind of message using this method. @param pattern A message template to match received messages against. @return A new ACL message matching the given template, or <code>null</code> if no such message is present. @see jade.lang.acl.ACLMessage @see jade.lang.acl.MessageTemplate */ public final ACLMessage receive(MessageTemplate pattern) { ACLMessage msg = null; synchronized(waitLock) { Iterator messages = msgQueue.iterator(); while(messages.hasNext()) { ACLMessage cursor = (ACLMessage)messages.next(); if(pattern.match(cursor)) { msg = cursor; msgQueue.remove(cursor); currentMessage = cursor; break; // Exit while loop } } } return msg; } /** Receives an <b>ACL</b> message from the agent message queue. This method is blocking and suspends the whole agent until a message is available in the queue. JADE provides a special behaviour named <code>ReceiverBehaviour</code> to wait for a message within a behaviour without suspending all the others and without wasting CPU time doing busy waiting. @return A new ACL message, blocking the agent until one is available. @see jade.lang.acl.ACLMessage @see jade.core.ReceiverBehaviour */ public final ACLMessage blockingReceive() { ACLMessage msg = null; while(msg == null) { msg = blockingReceive(0); } return msg; } /** Receives an <b>ACL</b> message from the agent message queue, waiting at most a specified amount of time. @param millis The maximum amount of time to wait for the message. @return A new ACL message, or <code>null</code> if the specified amount of time passes without any message reception. */ public final ACLMessage blockingReceive(long millis) { ACLMessage msg = receive(); if(msg == null) { doWait(millis); msg = receive(); } return msg; } /** Receives an <b>ACL</b> message matching a given message template. This method is blocking and suspends the whole agent until a message is available in the queue. JADE provides a special behaviour named <code>ReceiverBehaviour</code> to wait for a specific kind of message within a behaviour without suspending all the others and without wasting CPU time doing busy waiting. @param pattern A message template to match received messages against. @return A new ACL message matching the given template, blocking until such a message is available. @see jade.lang.acl.ACLMessage @see jade.lang.acl.MessageTemplate @see jade.core.ReceiverBehaviour */ public final ACLMessage blockingReceive(MessageTemplate pattern) { ACLMessage msg = null; while(msg == null) { msg = blockingReceive(pattern, 0); } return msg; } /** Receives an <b>ACL</b> message matching a given message template, waiting at most a specified time. @param pattern A message template to match received messages against. @param millis The amount of time to wait for the message, in milliseconds. @return A new ACL message matching the given template, or <code>null</code> if no suitable message was received within <code>millis</code> milliseconds. @see jade.core.Agent#blockingReceive() */ public final ACLMessage blockingReceive(MessageTemplate pattern, long millis) { ACLMessage msg = receive(pattern); long timeToWait = millis; while(msg == null) { long startTime = System.currentTimeMillis(); doWait(timeToWait); long elapsedTime = System.currentTimeMillis() - startTime; timeToWait -= elapsedTime; msg = receive(pattern); if((millis != 0) && (timeToWait <= 0)) break; } return msg; } /** Puts a received <b>ACL</b> message back into the message queue. This method can be used from an agent behaviour when it realizes it read a message of interest for some other behaviour. The message is put in front of the message queue, so it will be the first returned by a <code>receive()</code> call. @see jade.core.Agent#receive() */ public final void putBack(ACLMessage msg) { synchronized(waitLock) { msgQueue.addFirst(msg); } } /** @deprecated Builds an ACL message from a character stream. Now <code>ACLMessage</code> class has this capabilities itself, through <code>fromText()</code> method. @see jade.lang.acl.ACLMessage#fromText(Reader r) */ public ACLMessage parse(Reader text) { ACLMessage msg = null; try { msg = myParser.parse(text); } catch(ParseException pe) { pe.printStackTrace(); } catch(TokenMgrError tme) { tme.printStackTrace(); } return msg; } private ACLMessage FipaRequestMessage(String dest, String replyString) { ACLMessage request = new ACLMessage("request"); request.setSource(myName); request.removeAllDests(); request.addDest(dest); request.setLanguage("SL0"); request.setOntology("fipa-agent-management"); request.setProtocol("fipa-request"); request.setReplyWith(replyString); return request; } private String doFipaRequestClient(ACLMessage request, String replyString) throws FIPAException { send(request); ACLMessage reply = blockingReceive(MessageTemplate.MatchReplyTo(replyString)); if(reply.getType().equalsIgnoreCase("agree")) { reply = blockingReceive(MessageTemplate.MatchReplyTo(replyString)); if(!reply.getType().equalsIgnoreCase("inform")) { String content = reply.getContent(); StringReader text = new StringReader(content); throw FIPAException.fromText(text); } else { String content = reply.getContent(); return content; } } else { String content = reply.getContent(); StringReader text = new StringReader(content); throw FIPAException.fromText(text); } } /** Register this agent with Agent Platform <b>AMS</b>. While this task can be accomplished with regular message passing according to <b>FIPA</b> protocols, this method is meant to ease this common duty. However, since <b>AMS</b> registration and deregistration are automatic in JADE, this method should not be used by application programmers. Some parameters here are optional, and <code>null</code> can safely be passed for them. @param signature An optional signature string, used for security reasons. @param APState The Agent Platform state of the agent; must be a valid state value (typically, <code>Agent.AP_ACTIVE</code> constant is passed). @param delegateAgent An optional delegate agent name. @param forwardAddress An optional forward address. @param ownership An optional ownership string. @exception FIPAException A suitable exception can be thrown when a <code>refuse</code> or <code>failure</code> messages are received from the AMS to indicate some error condition. */ public void registerWithAMS(String signature, int APState, String delegateAgent, String forwardAddress, String ownership) throws FIPAException { String replyString = myName + "-ams-registration-" + (new Date()).getTime(); ACLMessage request = FipaRequestMessage("ams", replyString); // Build an AMS action object for the request AgentManagementOntology.AMSAction a = new AgentManagementOntology.AMSAction(); AgentManagementOntology.AMSAgentDescriptor amsd = new AgentManagementOntology.AMSAgentDescriptor(); amsd.setName(getName()); amsd.setAddress(getAddress()); amsd.setAPState(APState); amsd.setDelegateAgentName(delegateAgent); amsd.setForwardAddress(forwardAddress); amsd.setOwnership(ownership); a.setName(AgentManagementOntology.AMSAction.REGISTERAGENT); a.setArg(amsd); // Convert it to a String and write it in content field of the request StringWriter text = new StringWriter(); a.toText(text); request.setContent(text.toString()); // Send message and collect reply doFipaRequestClient(request, replyString); } /** Authenticate this agent with Agent Platform <b>AMS</b>. While this task can be accomplished with regular message passing according to <b>FIPA</b> protocols, this method is meant to ease this common duty. Some parameters here are optional, and <code>null</code> can safely be passed for them. @param signature An optional signature string, used for security reasons. @param APState The Agent Platform state of the agent; must be a valid state value (typically, <code>Agent.AP_ACTIVE</code> constant is passed). @param delegateAgent An optional delegate agent name. @param forwardAddress An optional forward address. @param ownership An optional ownership string. @exception FIPAException A suitable exception can be thrown when a <code>refuse</code> or <code>failure</code> messages are received from the AMS to indicate some error condition. <em>This method is currently not implemented.</em> */ public void authenticateWithAMS(String signature, int APState, String delegateAgent, String forwardAddress, String ownership) throws FIPAException { // FIXME: Not implemented } /** Deregister this agent with Agent Platform <b>AMS</b>. While this task can be accomplished with regular message passing according to <b>FIPA</b> protocols, this method is meant to ease this common duty. However, since <b>AMS</b> registration and deregistration are automatic in JADE, this method should not be used by application programmers. @exception FIPAException A suitable exception can be thrown when a <code>refuse</code> or <code>failure</code> messages are received from the AMS to indicate some error condition. */ public void deregisterWithAMS() throws FIPAException { String replyString = myName + "-ams-deregistration-" + (new Date()).getTime(); // Get a semi-complete request message ACLMessage request = FipaRequestMessage("ams", replyString); // Build an AMS action object for the request AgentManagementOntology.AMSAction a = new AgentManagementOntology.AMSAction(); AgentManagementOntology.AMSAgentDescriptor amsd = new AgentManagementOntology.AMSAgentDescriptor(); amsd.setName(getName()); a.setName(AgentManagementOntology.AMSAction.DEREGISTERAGENT); a.setArg(amsd); // Convert it to a String and write it in content field of the request StringWriter text = new StringWriter(); a.toText(text); request.setContent(text.toString()); // Send message and collect reply doFipaRequestClient(request, replyString); } /** Modifies the data about this agent kept by Agent Platform <b>AMS</b>. While this task can be accomplished with regular message passing according to <b>FIPA</b> protocols, this method is meant to ease this common duty. Some parameters here are optional, and <code>null</code> can safely be passed for them. When a non null parameter is passed, it replaces the value currently stored inside <b>AMS</b> agent. @param signature An optional signature string, used for security reasons. @param APState The Agent Platform state of the agent; must be a valid state value (typically, <code>Agent.AP_ACTIVE</code> constant is passed). @param delegateAgent An optional delegate agent name. @param forwardAddress An optional forward address. @param ownership An optional ownership string. @exception FIPAException A suitable exception can be thrown when a <code>refuse</code> or <code>failure</code> messages are received from the AMS to indicate some error condition. */ public void modifyAMSRegistration(String signature, int APState, String delegateAgent, String forwardAddress, String ownership) throws FIPAException { String replyString = myName + "-ams-modify-" + (new Date()).getTime(); ACLMessage request = FipaRequestMessage("ams", replyString); // Build an AMS action object for the request AgentManagementOntology.AMSAction a = new AgentManagementOntology.AMSAction(); AgentManagementOntology.AMSAgentDescriptor amsd = new AgentManagementOntology.AMSAgentDescriptor(); amsd.setName(getName()); amsd.setAddress(getAddress()); amsd.setAPState(APState); amsd.setDelegateAgentName(delegateAgent); amsd.setForwardAddress(forwardAddress); amsd.setOwnership(ownership); a.setName(AgentManagementOntology.AMSAction.MODIFYAGENT); a.setArg(amsd); // Convert it to a String and write it in content field of the request StringWriter text = new StringWriter(); a.toText(text); request.setContent(text.toString()); // Send message and collect reply doFipaRequestClient(request, replyString); } /** This method uses Agent Platform <b>ACC</b> agent to forward an ACL message. Calling this method is exactly the same as calling <code>send()</code>, only slower, since the message is first sent to the ACC using a <code>fipa-request</code> standard protocol, and then bounced to actual destination agent. @param msg The ACL message to send. @exception FIPAException A suitable exception can be thrown when a <code>refuse</code> or <code>failure</code> messages are received from the ACC to indicate some error condition. @see jade.core.Agent#send(ACLMessage msg) */ public void forwardWithACC(ACLMessage msg) throws FIPAException { String replyString = myName + "-acc-forward-" + (new Date()).getTime(); ACLMessage request = FipaRequestMessage("acc", replyString); // Build an ACC action object for the request AgentManagementOntology.ACCAction a = new AgentManagementOntology.ACCAction(); a.setName(AgentManagementOntology.ACCAction.FORWARD); a.setArg(msg); // Convert it to a String and write it in content field of the request StringWriter text = new StringWriter(); a.toText(text); request.setContent(text.toString()); // Send message and collect reply doFipaRequestClient(request, replyString); } /** Register this agent with a <b>DF</b> agent. While this task can be accomplished with regular message passing according to <b>FIPA</b> protocols, this method is meant to ease this common duty. @param dfName The GUID of the <b>DF</b> agent to register with. @param dfd A <code>DFAgentDescriptor</code> object containing all data necessary to the registration. @exception FIPAException A suitable exception can be thrown when a <code>refuse</code> or <code>failure</code> messages are received from the DF to indicate some error condition. @see jade.domain.AgentManagementOntology.DFAgentDescriptor */ public void registerWithDF(String dfName, AgentManagementOntology.DFAgentDescriptor dfd) throws FIPAException { String replyString = myName + "-df-register-" + (new Date()).getTime(); ACLMessage request = FipaRequestMessage(dfName, replyString); // Build a DF action object for the request AgentManagementOntology.DFAction a = new AgentManagementOntology.DFAction(); a.setName(AgentManagementOntology.DFAction.REGISTER); a.setActor(dfName); a.setArg(dfd); // Convert it to a String and write it in content field of the request StringWriter text = new StringWriter(); a.toText(text); request.setContent(text.toString()); // Send message and collect reply doFipaRequestClient(request, replyString); } /** Deregister this agent from a <b>DF</b> agent. While this task can be accomplished with regular message passing according to <b>FIPA</b> protocols, this method is meant to ease this common duty. @param dfName The GUID of the <b>DF</b> agent to deregister from. @param dfd A <code>DFAgentDescriptor</code> object containing all data necessary to the deregistration. @exception FIPAException A suitable exception can be thrown when a <code>refuse</code> or <code>failure</code> messages are received from the DF to indicate some error condition. @see jade.domain.AgentManagementOntology.DFAgentDescriptor */ public void deregisterWithDF(String dfName, AgentManagementOntology.DFAgentDescriptor dfd) throws FIPAException { String replyString = myName + "-df-deregister-" + (new Date()).getTime(); ACLMessage request = FipaRequestMessage(dfName, replyString); // Build a DF action object for the request AgentManagementOntology.DFAction a = new AgentManagementOntology.DFAction(); a.setName(AgentManagementOntology.DFAction.DEREGISTER); a.setActor(dfName); a.setArg(dfd); // Convert it to a String and write it in content field of the request StringWriter text = new StringWriter(); a.toText(text); request.setContent(text.toString()); // Send message and collect reply doFipaRequestClient(request, replyString); } /** Modifies data about this agent contained within a <b>DF</b> agent. While this task can be accomplished with regular message passing according to <b>FIPA</b> protocols, this method is meant to ease this common duty. @param dfName The GUID of the <b>DF</b> agent holding the data to be changed. @param dfd A <code>DFAgentDescriptor</code> object containing all new data values; every non null slot value replaces the corresponding value held inside the <b>DF</b> agent. @exception FIPAException A suitable exception can be thrown when a <code>refuse</code> or <code>failure</code> messages are received from the DF to indicate some error condition. @see jade.domain.AgentManagementOntology.DFAgentDescriptor */ public void modifyDFData(String dfName, AgentManagementOntology.DFAgentDescriptor dfd) throws FIPAException { String replyString = myName + "-df-modify-" + (new Date()).getTime(); ACLMessage request = FipaRequestMessage(dfName, replyString); // Build a DF action object for the request AgentManagementOntology.DFAction a = new AgentManagementOntology.DFAction(); a.setName(AgentManagementOntology.DFAction.MODIFY); a.setActor(dfName); a.setArg(dfd); // Convert it to a String and write it in content field of the request StringWriter text = new StringWriter(); a.toText(text); request.setContent(text.toString()); // Send message and collect reply doFipaRequestClient(request, replyString); } /** Searches for data contained within a <b>DF</b> agent. While this task can be accomplished with regular message passing according to <b>FIPA</b> protocols, this method is meant to ease this common duty. Nevertheless, a complete, powerful search interface is provided; search constraints can be given and recursive searches are possible. The only shortcoming is that this method blocks the whole agent until the search terminates. A special <code>SearchDFBehaviour</code> can be used to perform <b>DF</b> searches without blocking. @param dfName The GUID of the <b>DF</b> agent to start search from. @param dfd A <code>DFAgentDescriptor</code> object containing data to search for; this parameter is used as a template to match data against. @param constraints A <code>Vector</code> that must be filled with all <code>Constraint</code> objects to apply to the current search. This can be <code>null</code> if no search constraints are required. @return A <code>DFSearchResult</code> object containing all found <code>DFAgentDescriptor</code> objects matching the given descriptor, subject to given search constraints for search depth and result size. @exception FIPAException A suitable exception can be thrown when a <code>refuse</code> or <code>failure</code> messages are received from the DF to indicate some error condition. @see jade.domain.AgentManagementOntology.DFAgentDescriptor @see java.util.Vector @see jade.domain.AgentManagementOntology.Constraint @see jade.domain.AgentManagementOntology.DFSearchResult */ public AgentManagementOntology.DFSearchResult searchDF(String dfName, AgentManagementOntology.DFAgentDescriptor dfd, Vector constraints) throws FIPAException { String replyString = myName + "-df-search-" + (new Date()).getTime(); ACLMessage request = FipaRequestMessage(dfName, replyString); // Build a DF action object for the request AgentManagementOntology.DFSearchAction a = new AgentManagementOntology.DFSearchAction(); a.setName(AgentManagementOntology.DFAction.SEARCH); a.setActor(dfName); a.setArg(dfd); if(constraints == null) { AgentManagementOntology.Constraint c = new AgentManagementOntology.Constraint(); c.setName(AgentManagementOntology.Constraint.DFDEPTH); c.setFn(AgentManagementOntology.Constraint.EXACTLY); c.setArg(1); a.addConstraint(c); } else { // Put constraints into action Iterator i = constraints.iterator(); while(i.hasNext()) { AgentManagementOntology.Constraint c = (AgentManagementOntology.Constraint)i.next(); a.addConstraint(c); } } // Convert it to a String and write it in content field of the request StringWriter textOut = new StringWriter(); a.toText(textOut); request.setContent(textOut.toString()); // Send message and collect reply String content = doFipaRequestClient(request, replyString); // Extract agent descriptors from reply message AgentManagementOntology.DFSearchResult found = null; StringReader textIn = new StringReader(content); try { found = AgentManagementOntology.DFSearchResult.fromText(textIn); } catch(jade.domain.ParseException jdpe) { jdpe.printStackTrace(); } catch(jade.domain.TokenMgrError jdtme) { jdtme.printStackTrace(); } return found; } // Event handling methods // Broadcast communication event to registered listeners private void broadcastEvent(CommEvent event) { Iterator i = listeners.iterator(); while(i.hasNext()) { CommListener l = (CommListener)i.next(); l.CommHandle(event); } } // Register a new listener public final void addCommListener(CommListener l) { listeners.add(l); } // Remove a registered listener public final void removeCommListener(CommListener l) { listeners.remove(l); } // Notify listeners of the destruction of the current agent private void notifyDestruction() { Iterator i = listeners.iterator(); while(i.hasNext()) { CommListener l = (CommListener)i.next(); l.endSource(myName); } } private void activateAllBehaviours() { // Put all blocked behaviours back in ready queue, // atomically with respect to the Scheduler object synchronized(myScheduler) { while(!blockedBehaviours.isEmpty()) { Behaviour b = (Behaviour)blockedBehaviours.lastElement(); blockedBehaviours.removeElementAt(blockedBehaviours.size() - 1); b.restart(); myScheduler.add(b); } } } /** Put a received message into the agent message queue. The mesage is put at the back end of the queue. This method is called by JADE runtime system when a message arrives, but can also be used by an agent, and is just the same as sending a message to oneself (though slightly faster). @param msg The ACL message to put in the queue. @see jade.core.Agent#send(ACLMessage msg) */ public final void postMessage (ACLMessage msg) { synchronized(waitLock) { if(msg != null) msgQueue.addLast(msg); doWake(); } } }
import java.util.*; import java.awt.*; import java.io.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; class nwchem_RMS extends JFrame implements ActionListener, ChangeListener, WindowListener, MouseListener { Font defaultFont; int setnumber=0; JFileChooser chooser; ExtensionFilter rmsFilter; JFrame dialogFrame; BufferedReader br; String card; Graph rmsPlot = new Graph(); Graph rmsaPlot = new Graph(); Graph rmsrPlot = new Graph(); Graph bfacaPlot = new Graph(); Graph bfacrPlot = new Graph(); JLabel systemLabel = new JLabel(); JButton doneButton = new JButton("done"); double time,rms1,rms2; public nwchem_RMS(){ super("RMS Viewer 2"); defaultFont = new Font("Dialog", Font.BOLD,12); super.getContentPane().setLayout(new GridBagLayout()); super.getContentPane().setForeground(Color.black); super.getContentPane().setBackground(Color.lightGray); super.getContentPane().setFont(defaultFont); super.addWindowListener(this); chooser = new JFileChooser("./"); rmsFilter = new ExtensionFilter(".rms"); chooser.setFileFilter(rmsFilter); dialogFrame = new JFrame(); dialogFrame.setSize(300,400); chooser.showOpenDialog(dialogFrame); JPanel header = new JPanel(); header.setLayout(new GridBagLayout()); header.setForeground(Color.black); header.setBackground(Color.lightGray); addComponent(super.getContentPane(),header,0,0,2,1,1,1, GridBagConstraints.NONE,GridBagConstraints.WEST); JLabel systemLabel = new JLabel(chooser.getSelectedFile().toString()); addComponent(header,systemLabel,2,0,10,1,1,1, GridBagConstraints.NONE,GridBagConstraints.NORTHWEST); systemLabel.setForeground(Color.black); addComponent(header,doneButton,0,0,1,1,1,1, GridBagConstraints.NONE,GridBagConstraints.NORTHWEST); doneButton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ setVisible(false); }}); rmsPlot.init(); rmsaPlot.init(); rmsrPlot.init(); bfacaPlot.init(); bfacrPlot.init(); rmsPlot.setTitle("RMS Deviation vs Time"); rmsaPlot.setTitle("Atomic RMS Deviation"); rmsrPlot.setTitle("Segment RMS Deviation"); bfacaPlot.setTitle("Atomic B factor"); bfacrPlot.setTitle("Segment B Factor"); rmsrPlot.setBars(1.0,0.0); rmsPlot.setSize(500,300); rmsaPlot.setSize(350,300); rmsrPlot.setSize(350,300); bfacaPlot.setSize(350,300); bfacrPlot.setSize(350,300); addComponent(header,rmsPlot,0,1,20,10,10,10, GridBagConstraints.NONE,GridBagConstraints.NORTHWEST); addComponent(header,rmsaPlot,0,11,10,10,10,10, GridBagConstraints.NONE,GridBagConstraints.NORTHWEST); addComponent(header,rmsrPlot,11,11,10,10,10,10, GridBagConstraints.NONE,GridBagConstraints.NORTHWEST); addComponent(header,bfacaPlot,0,21,10,10,10,10, GridBagConstraints.NONE,GridBagConstraints.NORTHWEST); addComponent(header,bfacrPlot,11,21,10,10,10,10, GridBagConstraints.NONE,GridBagConstraints.NORTHWEST); try{ BufferedReader br = new BufferedReader(new FileReader(chooser.getSelectedFile().toString())); String card; card=br.readLine(); int numt=0; boolean first=true; while(!card.startsWith("analysis")){ time=Double.valueOf(card.substring(1,12)).doubleValue(); rms1=Double.valueOf(card.substring(13,24)).doubleValue(); rms2=Double.valueOf(card.substring(25,36)).doubleValue(); rmsPlot.addData(0,time,rms1,!first,false); rmsPlot.addData(1,time,rms2,!first,false); first=false; card=br.readLine(); }; rmsPlot.fillPlot(); card=br.readLine(); int numa=0; first=true; while(!card.startsWith("analysis")){ rms1=Double.valueOf(card.substring(32,43)).doubleValue(); rms2=Double.valueOf(card.substring(44,55)).doubleValue(); rmsaPlot.addData(1,numa,rms1,!first,false); bfacaPlot.addData(1,numa,rms2,!first,false); first=false; numa++; card=br.readLine(); }; numa=0; int n; first=true; while((card=br.readLine()) != null){ rms1=Double.valueOf(card.substring(12,23)).doubleValue(); rms2=Double.valueOf(card.substring(24,35)).doubleValue(); System.out.println(rms1+" "+rms2); rmsrPlot.addData(0,numa,rms1,!first,false); bfacrPlot.addData(0,numa,rms2,!first,false); first=false; numa++; }; rmsaPlot.fillPlot(); rmsrPlot.fillPlot(); bfacaPlot.fillPlot(); bfacrPlot.fillPlot(); br.close(); } catch(Exception ee) {ee.printStackTrace();}; setLocation(25,225); setSize(900,700); setVisible(true); } void buildConstraints(GridBagConstraints gbc, int gx, int gy, int gw, int gh, int wx, int wy){ gbc.gridx = gx; gbc.gridy = gy; gbc.gridwidth = gw; gbc.gridheight = gh; gbc.weightx = wx; gbc.weighty = wy; } static void addComponent(Container container, Component component, int gridx, int gridy, int gridwidth, int gridheight, double weightx, double weighty, int fill, int anchor) { LayoutManager lm = container.getLayout(); if(!(lm instanceof GridBagLayout)){ System.out.println("Illegal layout"); System.exit(1); } else { GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx=gridx; gbc.gridy=gridy; gbc.gridwidth=gridwidth; gbc.gridheight=gridheight; gbc.weightx=weightx; gbc.weighty=weighty; gbc.fill=fill; gbc.anchor=anchor; container.add(component,gbc); } } public void actionPerformed(ActionEvent e) { } public void stateChanged(ChangeEvent e) {} public void windowClosing(WindowEvent event) {} public void windowClosed(WindowEvent event) { } public void windowDeiconified(WindowEvent event) {} public void windowIconified(WindowEvent event) {} public void windowActivated(WindowEvent event) {} public void windowDeactivated(WindowEvent e) {} public void windowOpened(WindowEvent event) {} public void mouseClicked(MouseEvent mouse) {} public void mousePressed(MouseEvent mouse){} public void mouseReleased(MouseEvent mouse){ } public void mouseEntered(MouseEvent mouse){ } public void mouseExited(MouseEvent mouse){ } }
package etomica; import etomica.integrator.Integrator; import etomica.simulation.Simulation; import etomica.space.Space; import etomica.space3d.Space3D; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.TestReporter; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.stream.Collectors; import static etomica.TestSimConstructors.SCAN; public class TestSimShortRuns { private static final ExecutorService exec = Executors.newSingleThreadExecutor(); /** * Sim classes that are excluded for various reasons causing them not to work with the reflection hacks here. */ private static final Set<Class<?>> EXCLUDED = new HashSet<>(Arrays.asList( )); static List<Arguments> getIntegrators() throws IllegalAccessException, InstantiationException, InvocationTargetException { // This beautiful method will search through constructible simulations looking for ones // with one and only one field of type Integrator (getIntegrator isn't reliable, and with // more than one we don't know which one to use), instantiate the simulations, and return the integrators. List<Class<?>> classes = SCAN.classNamesToClassRefs(SCAN.getNamesOfSubclassesOf(Simulation.class)); List<Arguments> args = new ArrayList<>(); for (Class<?> cl : classes) { if (EXCLUDED.contains(cl)) { continue; } Field[] fields = cl.getDeclaredFields(); List<Field> integratorFields = Arrays.stream(fields) .filter(f -> Integrator.class.isAssignableFrom(f.getType())) .collect(Collectors.toList()); if (integratorFields.size() == 1) { Simulation sim = null; try { sim = (Simulation) cl.getConstructor().newInstance(); } catch (NoSuchMethodException e) { try { sim = (Simulation) cl.getConstructor(Space.class).newInstance(Space3D.getInstance()); } catch (NoSuchMethodException e1) { continue; } } integratorFields.get(0).setAccessible(true); args.add(Arguments.of(cl, integratorFields.get(0).get(sim))); } } return args; } @ParameterizedTest @MethodSource("getIntegrators") void testShortRuns(Class<?> simClass, Integrator simIntegrator, TestReporter reporter) { Assertions.assertDoesNotThrow(() -> { simIntegrator.reset(); Future future = exec.submit(() -> { while (!Thread.interrupted()) { simIntegrator.doStep(); } }); Thread.sleep(400); future.cancel(true); }); reporter.publishEntry(simClass + " steps", Long.toString(simIntegrator.getStepCount())); } }
package hudson.model; import hudson.PluginWrapper; import hudson.PluginManager; import hudson.model.UpdateCenter.UpdateCenterJob; import hudson.lifecycle.Lifecycle; import hudson.util.TextFile; import hudson.util.VersionNumber; import static hudson.util.TimeUnit2.DAYS; import net.sf.json.JSONObject; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.StaplerResponse; import org.jvnet.hudson.crypto.CertificateUtil; import org.jvnet.hudson.crypto.SignatureOutputStream; import org.apache.commons.io.output.NullOutputStream; import org.apache.commons.io.output.TeeOutputStream; import java.io.File; import java.io.IOException; import java.io.ByteArrayInputStream; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.HashMap; import java.util.Set; import java.util.concurrent.Future; import java.util.logging.Level; import java.util.logging.Logger; import java.security.GeneralSecurityException; import java.security.MessageDigest; import java.security.DigestOutputStream; import java.security.Signature; import java.security.cert.X509Certificate; import java.security.cert.CertificateFactory; import java.security.cert.TrustAnchor; import com.trilead.ssh2.crypto.Base64; import javax.servlet.ServletContext; public class UpdateSite { /** * What's the time stamp of data file? */ private transient long dataTimestamp = -1; /** * When was the last time we asked a browser to check the data for us? * * <p> * There's normally some delay between when we send HTML that includes the check code, * until we get the data back, so this variable is used to avoid asking too many browseres * all at once. */ private transient volatile long lastAttempt = -1; /** * ID string for this update source. */ private final String id; private final String url; public UpdateSite(String id, String url) { this.id = id; this.url = url; } /** * When read back from XML, initialize them back to -1. */ private Object readResolve() { dataTimestamp = lastAttempt = -1; return this; } /** * Get ID string. */ public String getId() { return id; } public long getDataTimestamp() { return dataTimestamp; } /** * This is the endpoint that receives the update center data file from the browser. */ public void doPostBack(@QueryParameter String json) throws IOException, GeneralSecurityException { dataTimestamp = System.currentTimeMillis(); JSONObject o = JSONObject.fromObject(json); int v = o.getInt("updateCenterVersion"); if(v !=1) { LOGGER.warning("Unrecognized update center version: "+v); return; } if (signatureCheck) verifySignature(o); LOGGER.info("Obtained the latest update center data file for UpdateSource "+ id); getDataFile().write(json); } /** * Verifies the signature in the update center data file. */ private boolean verifySignature(JSONObject o) throws GeneralSecurityException, IOException { JSONObject signature = o.getJSONObject("signature"); if (signature.isNullObject()) { LOGGER.severe("No signature block found"); return false; } o.remove("signature"); List<X509Certificate> certs = new ArrayList<X509Certificate>(); {// load and verify certificates CertificateFactory cf = CertificateFactory.getInstance("X509"); for (Object cert : o.getJSONArray("certificates")) { X509Certificate c = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(Base64.decode(cert.toString().toCharArray()))); c.checkValidity(); certs.add(c); } // all default root CAs in JVM are trusted, plus certs bundled in Hudson Set<TrustAnchor> anchors = CertificateUtil.getDefaultRootCAs(); ServletContext context = Hudson.getInstance().servletContext; for (String cert : (Set<String>) context.getResourcePaths("/WEB-INF/update-center-rootCAs")) { if (cert.endsWith(".txt")) continue; // skip text files that are meant to be documentation anchors.add(new TrustAnchor((X509Certificate)cf.generateCertificate(context.getResourceAsStream(cert)),null)); } CertificateUtil.validatePath(certs); } // this is for computing a digest to check sanity MessageDigest sha1 = MessageDigest.getInstance("SHA1"); DigestOutputStream dos = new DigestOutputStream(new NullOutputStream(),sha1); // this is for computing a signature Signature sig = Signature.getInstance("SHA1withRSA"); sig.initVerify(certs.get(0)); SignatureOutputStream sos = new SignatureOutputStream(sig); o.writeCanonical(new OutputStreamWriter(new TeeOutputStream(dos,sos),"UTF-8")); // did the digest match? this is not a part of the signature validation, but if we have a bug in the c14n // (which is more likely than someone tampering with update center), we can tell String computedDigest = new String(Base64.encode(sha1.digest())); String providedDigest = signature.getString("digest"); if (!computedDigest.equalsIgnoreCase(providedDigest)) { LOGGER.severe("Digest mismatch: "+computedDigest+" vs "+providedDigest); return false; } if (!sig.verify(Base64.decode(signature.getString("signature").toCharArray()))) { LOGGER.severe("Signature in the update center doesn't match with the certificate"); return false; } return true; } /** * Returns true if it's time for us to check for new version. */ public boolean isDue() { if(neverUpdate) return false; if(dataTimestamp==-1) dataTimestamp = getDataFile().file.lastModified(); long now = System.currentTimeMillis(); boolean due = now - dataTimestamp > DAY && now - lastAttempt > 15000; if(due) lastAttempt = now; return due; } /** * Loads the update center data, if any. * * @return null if no data is available. */ public Data getData() { TextFile df = getDataFile(); if(df.exists()) { try { return new Data(JSONObject.fromObject(df.read())); } catch (IOException e) { LOGGER.log(Level.SEVERE,"Failed to parse "+df,e); df.delete(); // if we keep this file, it will cause repeated failures return null; } } else { return null; } } /** * Returns a list of plugins that should be shown in the "available" tab. * These are "all plugins - installed plugins". */ public List<Plugin> getAvailables() { List<Plugin> r = new ArrayList<Plugin>(); Data data = getData(); if(data==null) return Collections.emptyList(); for (Plugin p : data.plugins.values()) { if(p.getInstalled()==null) r.add(p); } return r; } /** * Gets the information about a specific plugin. * * @param artifactId * The short name of the plugin. Corresponds to {@link PluginWrapper#getShortName()}. * * @return * null if no such information is found. */ public Plugin getPlugin(String artifactId) { Data dt = getData(); if(dt==null) return null; return dt.plugins.get(artifactId); } /** * Returns an "always up" server for Internet connectivity testing, or null if we are going to skip the test. */ public String getConnectionCheckUrl() { Data dt = getData(); if(dt==null) return "http: return dt.connectionCheckUrl; } /** * This is where we store the update center data. */ private TextFile getDataFile() { return new TextFile(new File(Hudson.getInstance().getRootDir(), "updates/" + getId()+".json")); } /** * Returns the list of plugins that are updates to currently installed ones. * * @return * can be empty but never null. */ public List<Plugin> getUpdates() { Data data = getData(); if(data==null) return Collections.emptyList(); // fail to determine List<Plugin> r = new ArrayList<Plugin>(); for (PluginWrapper pw : Hudson.getInstance().getPluginManager().getPlugins()) { Plugin p = pw.getUpdateInfo(); if(p!=null) r.add(p); } return r; } /** * Does any of the plugin has updates? */ public boolean hasUpdates() { Data data = getData(); if(data==null) return false; for (PluginWrapper pw : Hudson.getInstance().getPluginManager().getPlugins()) { if(!pw.isBundled() && pw.getUpdateInfo()!=null) // do not advertize updates to bundled plugins, since we generally want users to get them // as a part of hudson.war updates. This also avoids unnecessary pinning of plugins. return true; } return false; } /** * Exposed to get rid of hardcoding of the URL that serves up update-center.json * in Javascript. */ public String getUrl() { return url; } /** * In-memory representation of the update center data. */ public final class Data { /** * The {@link UpdateSite} ID. */ public final String sourceId; /** * The latest hudson.war. */ public final Entry core; /** * Plugins in the repository, keyed by their artifact IDs. */ public final Map<String,Plugin> plugins = new TreeMap<String,Plugin>(String.CASE_INSENSITIVE_ORDER); /** * If this is non-null, Hudson is going to check the connectivity to this URL to make sure * the network connection is up. Null to skip the check. */ public final String connectionCheckUrl; Data(JSONObject o) { this.sourceId = (String)o.get("id"); if (sourceId.equals("default")) { core = new Entry(sourceId, o.getJSONObject("core")); } else { core = null; } for(Map.Entry<String,JSONObject> e : (Set<Map.Entry<String,JSONObject>>)o.getJSONObject("plugins").entrySet()) { plugins.put(e.getKey(),new Plugin(sourceId, e.getValue())); } connectionCheckUrl = (String)o.get("connectionCheckUrl"); } /** * Is there a new version of the core? */ public boolean hasCoreUpdates() { return core != null && core.isNewerThan(Hudson.VERSION); } /** * Do we support upgrade? */ public boolean canUpgrade() { return Lifecycle.get().canRewriteHudsonWar(); } } public static class Entry { /** * {@link UpdateSite} ID. */ public final String sourceId; /** * Artifact ID. */ public final String name; /** * The version. */ public final String version; /** * Download URL. */ public final String url; public Entry(String sourceId, JSONObject o) { this.sourceId = sourceId; this.name = o.getString("name"); this.version = o.getString("version"); this.url = o.getString("url"); } /** * Checks if the specified "current version" is older than the version of this entry. * * @param currentVersion * The string that represents the version number to be compared. * @return * true if the version listed in this entry is newer. * false otherwise, including the situation where the strings couldn't be parsed as version numbers. */ public boolean isNewerThan(String currentVersion) { try { return new VersionNumber(currentVersion).compareTo(new VersionNumber(version)) < 0; } catch (IllegalArgumentException e) { // couldn't parse as the version number. return false; } } } public final class Plugin extends Entry { /** * Optional URL to the Wiki page that discusses this plugin. */ public final String wiki; /** * Human readable title of the plugin, taken from Wiki page. * Can be null. * * <p> * beware of XSS vulnerability since this data comes from Wiki */ public final String title; /** * Optional excerpt string. */ public final String excerpt; /** * Optional version # from which this plugin release is configuration-compatible. */ public final String compatibleSinceVersion; /** * Version of Hudson core this plugin was compiled against. */ public final String requiredCore; /** * Categories for grouping plugins, taken from labels assigned to wiki page. * Can be null. */ public final String[] categories; /** * Dependencies of this plugin. */ public final Map<String,String> dependencies = new HashMap<String,String>(); @DataBoundConstructor public Plugin(String sourceId, JSONObject o) { super(sourceId, o); this.wiki = get(o,"wiki"); this.title = get(o,"title"); this.excerpt = get(o,"excerpt"); this.compatibleSinceVersion = get(o,"compatibleSinceVersion"); this.requiredCore = get(o,"requiredCore"); this.categories = o.has("labels") ? (String[])o.getJSONArray("labels").toArray(new String[0]) : null; for(Object jo : o.getJSONArray("dependencies")) { JSONObject depObj = (JSONObject) jo; // Make sure there's a name attribute, that that name isn't maven-plugin - we ignore that one - // and that the optional value isn't true. if (get(depObj,"name")!=null && !get(depObj,"name").equals("maven-plugin") && get(depObj,"optional").equals("false")) { dependencies.put(get(depObj,"name"), get(depObj,"version")); } } } private String get(JSONObject o, String prop) { if(o.has(prop)) return o.getString(prop); else return null; } public String getDisplayName() { if(title!=null) return title; return name; } /** * If some version of this plugin is currently installed, return {@link PluginWrapper}. * Otherwise null. */ public PluginWrapper getInstalled() { PluginManager pm = Hudson.getInstance().getPluginManager(); return pm.getPlugin(name); } /** * If the plugin is already installed, and the new version of the plugin has a "compatibleSinceVersion" * value (i.e., it's only directly compatible with that version or later), this will check to * see if the installed version is older than the compatible-since version. If it is older, it'll return false. * If it's not older, or it's not installed, or it's installed but there's no compatibleSinceVersion * specified, it'll return true. */ public boolean isCompatibleWithInstalledVersion() { PluginWrapper installedVersion = getInstalled(); if (installedVersion != null) { if (compatibleSinceVersion != null) { if (new VersionNumber(installedVersion.getVersion()) .isOlderThan(new VersionNumber(compatibleSinceVersion))) { return false; } } } return true; } /** * Returns a list of dependent plugins which need to be installed or upgraded for this plugin to work. */ public List<Plugin> getNeededDependencies() { List<Plugin> deps = new ArrayList<Plugin>(); for(Map.Entry<String,String> e : dependencies.entrySet()) { Plugin depPlugin = getPlugin(e.getKey()); VersionNumber requiredVersion = new VersionNumber(e.getValue()); // Is the plugin installed already? If not, add it. PluginWrapper current = depPlugin.getInstalled(); if (current ==null) { deps.add(depPlugin); } // If the dependency plugin is installed, is the version we depend on newer than // what's installed? If so, upgrade. else if (current.isOlderThan(requiredVersion)) { deps.add(depPlugin); } } return deps; } public boolean isForNewerHudson() { try { return requiredCore!=null && new VersionNumber(requiredCore).isNewerThan( new VersionNumber(Hudson.VERSION.replaceFirst("SHOT *\(private.*\)", "SHOT"))); } catch (NumberFormatException nfe) { return true; // If unable to parse version } } /** * @deprecated as of 1.326 * Use {@link #deploy()}. */ public void install() { deploy(); } /** * Schedules the installation of this plugin. * * <p> * This is mainly intended to be called from the UI. The actual installation work happens * asynchronously in another thread. */ public Future<UpdateCenterJob> deploy() { Hudson.getInstance().checkPermission(Hudson.ADMINISTER); UpdateCenter uc = Hudson.getInstance().getUpdateCenter(); for (Plugin dep : getNeededDependencies()) { LOGGER.log(Level.WARNING, "Adding dependent install of " + dep.name + " for plugin " + name); dep.deploy(); } return uc.addJob(uc.new InstallationJob(this, UpdateSite.this, Hudson.getAuthentication())); } /** * Making the installation web bound. */ public void doInstall(StaplerResponse rsp) throws IOException { deploy(); rsp.sendRedirect2("../.."); } } private static final long DAY = DAYS.toMillis(1); private static final Logger LOGGER = Logger.getLogger(UpdateSite.class.getName()); public static boolean neverUpdate = Boolean.getBoolean(UpdateCenter.class.getName()+".never"); /** * Off by default until we know this is reasonably working. */ public static boolean signatureCheck = Boolean.getBoolean(UpdateCenter.class.getName()+".signatureCheck"); }
package orclient.util; import java.util.HashMap; import java.util.Map; import org.json.JSONArray; import org.json.JSONObject; public class GlobalConfig { public static Map<String, String> globalConfig; static { globalConfig = new HashMap<String, String>(); JSONArray ja = new JSONArray(); globalConfig.put("txids", ja.toString()); } private static void putTXID(String txid) { JSONArray ja = new JSONArray(globalConfig.get("txids")); ja.put(txid); globalConfig.put("txids", ja.toString()); } public static JSONArray allTXID() { return new JSONArray(globalConfig.get("txids")); } public static void confirmTX(String txid, String fullSigned) { JSONObject js = getTransaction(txid); js.put("fullSigned", fullSigned); js.put("confirmed", "1"); globalConfig.put(txid, js.toString()); } public static void writeTransaction(String txid, String raw, String signed, String fullSigned, String confirmed, String python, String pyHash) { JSONObject js = new JSONObject(); js.put("txid", txid); js.put("rawTransaction", raw); js.put("partialSigned", signed); js.put("fullSigned", fullSigned); js.put("confirmed", confirmed); js.put("python", python); js.put("pythonHash", pyHash); globalConfig.put(txid, js.toString()); putTXID(txid); } public static JSONObject getTransaction(String txid) { return new JSONObject(globalConfig.get(txid)); } }
package com.bugsnag; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import com.bugsnag.callbacks.Callback; import com.bugsnag.delivery.Delivery; import com.bugsnag.delivery.HttpDelivery; import com.bugsnag.delivery.OutputStreamDelivery; import com.bugsnag.serialization.Serializer; import org.junit.Test; import javax.servlet.http.HttpServletRequest; import java.io.ByteArrayOutputStream; import java.net.InetSocketAddress; import java.net.Proxy; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.Set; public class BugsnagTest { @Test public void testNoDeliveryFails() { Bugsnag bugsnag = Bugsnag.init("apikey"); bugsnag.setDelivery(null); boolean result = bugsnag.notify(new RuntimeException()); assertFalse(result); } @Test public void testIgnoreClasses() { Bugsnag bugsnag = Bugsnag.init("apikey"); bugsnag.setDelivery(BugsnagTestUtils.generateDelivery()); // Ignore neither bugsnag.setIgnoreClasses(); assertTrue(bugsnag.notify(new RuntimeException())); assertTrue(bugsnag.notify(new TestException())); // Ignore just RuntimeException bugsnag.setIgnoreClasses(RuntimeException.class.getName()); assertFalse(bugsnag.notify(new RuntimeException())); assertTrue(bugsnag.notify(new TestException())); // Ignore both bugsnag.setIgnoreClasses(RuntimeException.class.getName(), TestException.class.getName()); assertFalse(bugsnag.notify(new RuntimeException())); assertFalse(bugsnag.notify(new TestException())); } @Test public void testNotifyReleaseStages() { Bugsnag bugsnag = Bugsnag.init("apikey"); bugsnag.setDelivery(BugsnagTestUtils.generateDelivery()); bugsnag.setReleaseStage("production"); // Never send bugsnag.setNotifyReleaseStages(); assertFalse(bugsnag.notify(new Throwable())); // Ignore 'production' bugsnag.setNotifyReleaseStages("staging", "development"); assertFalse(bugsnag.notify(new Throwable())); // Allow 'production' bugsnag.setNotifyReleaseStages("production"); assertTrue(bugsnag.notify(new Throwable())); // Allow 'production' and others bugsnag.setNotifyReleaseStages("production", "staging", "development"); assertTrue(bugsnag.notify(new Throwable())); } @Test public void testProjectPackages() { Bugsnag bugsnag = Bugsnag.init("apikey"); bugsnag.setDelivery(new Delivery() { @Override public void deliver(Serializer serializer, Object object, Map<String, String> headers) { Report report = ((Notification) object).getEvents().get(0); assertTrue(report.getExceptions().get(0).getStacktrace().get(0).isInProject()); } @Override public void close() { } }); bugsnag.setProjectPackages("com.bugsnag"); assertTrue(bugsnag.notify(new Throwable())); } @Test public void testAppVersion() { Bugsnag bugsnag = Bugsnag.init("apikey"); bugsnag.setAppVersion("1.2.3"); bugsnag.setDelivery(new Delivery() { @Override public void deliver(Serializer serializer, Object object, Map<String, String> headers) { Report report = ((Notification) object).getEvents().get(0); assertEquals("1.2.3", report.getApp().get("version")); } @Override public void close() { } }); assertTrue(bugsnag.notify(new Throwable())); } @Test public void testAppType() { Bugsnag bugsnag = Bugsnag.init("apikey"); bugsnag.setAppType("testtype"); bugsnag.setDelivery(new Delivery() { @Override public void deliver(Serializer serializer, Object object, Map<String, String> headers) { Report report = ((Notification) object).getEvents().get(0); assertEquals("testtype", report.getApp().get("type")); } @Override public void close() { } }); assertTrue(bugsnag.notify(new Throwable())); } @Test public void testSeverity() { Bugsnag bugsnag = Bugsnag.init("apikey"); bugsnag.setDelivery(new Delivery() { @Override public void deliver(Serializer serializer, Object object, Map<String, String> headers) { Report report = ((Notification) object).getEvents().get(0); assertEquals(Severity.INFO.getValue(), report.getSeverity()); } @Override public void close() { } }); assertTrue(bugsnag.notify(new Throwable(), Severity.INFO)); } @Test public void testFilters() { Bugsnag bugsnag = Bugsnag.init("apikey"); bugsnag.setFilters("testfilter1", "testfilter2"); bugsnag.setDelivery(new Delivery() { @SuppressWarnings("unchecked") @Override public void deliver(Serializer serializer, Object object, Map<String, String> headers) { Report report = ((Notification) object).getEvents().get(0); Map<String, Object> firstTab = (Map<String, Object>) report.getMetaData().get("firsttab"); final Map<String, Object> secondTab = (Map<String, Object>) report.getMetaData().get("secondtab"); assertEquals("[FILTERED]", firstTab.get("testfilter1")); assertEquals("[FILTERED]", firstTab.get("testfilter2")); assertEquals("secretpassword", firstTab.get("testfilter3")); assertEquals("[FILTERED]", secondTab.get("testfilter1")); } @Override public void close() { } }); assertTrue(bugsnag.notify(new Throwable(), new Callback() { @Override public void beforeNotify(Report report) { report.addToTab("firsttab", "testfilter1", "secretpassword"); report.addToTab("firsttab", "testfilter2", "secretpassword"); report.addToTab("firsttab", "testfilter3", "secretpassword"); report.addToTab("secondtab", "testfilter1", "secretpassword"); } })); } @Test public void testFilterHeaders() { Bugsnag bugsnag = Bugsnag.init("apikey"); bugsnag.setDelivery(new Delivery() { @SuppressWarnings("unchecked") @Override public void deliver(Serializer serializer, Object object, Map<String, String> headers) { Report report = ((Notification) object).getEvents().get(0); Map<String, Object> requestTab = (Map<String, Object>) report.getMetaData().get("request"); Map<String, Object> headersMap = (Map<String, Object>) requestTab.get("headers"); assertEquals("[FILTERED]", headersMap.get("Authorization")); assertEquals("User:Password", headersMap.get("authorization")); assertEquals("[FILTERED]", headersMap.get("Cookie")); assertEquals("123456ABCDEF", headersMap.get("cookie")); } @Override public void close() { } }); assertTrue(bugsnag.notify(new Throwable(), new Callback() { @Override public void beforeNotify(Report report) { Map<String, String> headers = new HashMap<String, String>(); headers.put("Authorization", "User:Password"); headers.put("authorization", "User:Password"); headers.put("Cookie", "123456ABCDEF"); headers.put("cookie", "123456ABCDEF"); report.addToTab("request", "headers", headers); } })); } @Test public void testUser() { Bugsnag bugsnag = Bugsnag.init("apikey"); bugsnag.setDelivery(new Delivery() { @Override public void deliver(Serializer serializer, Object object, Map<String, String> headers) { Report report = ((Notification) object).getEvents().get(0); assertEquals("123", report.getUser().get("id")); assertEquals("test@example.com", report.getUser().get("email")); assertEquals("test name", report.getUser().get("name")); } @Override public void close() { } }); assertTrue(bugsnag.notify(new Throwable(), new Callback() { @Override public void beforeNotify(Report report) { report.setUser("123", "test@example.com", "test name"); } })); } @Test public void testContext() { Bugsnag bugsnag = Bugsnag.init("apikey"); bugsnag.addCallback(new Callback() { @Override public void beforeNotify(Report report) { report.setContext("the context"); } }); bugsnag.setDelivery(new Delivery() { @Override public void deliver(Serializer serializer, Object object, Map<String, String> headers) { Report report = ((Notification) object).getEvents().get(0); assertEquals("the context", report.getContext()); } @Override public void close() { } }); assertTrue(bugsnag.notify(new Throwable())); } @Test public void testGroupingHash() { Bugsnag bugsnag = Bugsnag.init("apikey"); bugsnag.addCallback(new Callback() { @Override public void beforeNotify(Report report) { report.setGroupingHash("the grouping hash"); } }); bugsnag.setDelivery(new Delivery() { @Override public void deliver(Serializer serializer, Object object, Map<String, String> headers) { Report report = ((Notification) object).getEvents().get(0); assertEquals("the grouping hash", report.getGroupingHash()); } @Override public void close() { } }); assertTrue(bugsnag.notify(new Throwable())); } @Test public void testSingleCallback() { Bugsnag bugsnag = Bugsnag.init("apikey"); bugsnag.addCallback(new Callback() { @Override public void beforeNotify(Report report) { report.setApiKey("newapikey"); } }); bugsnag.setDelivery(new Delivery() { @Override public void deliver(Serializer serializer, Object object, Map<String, String> headers) { Report report = ((Notification) object).getEvents().get(0); assertEquals("newapikey", report.getApiKey()); } @Override public void close() { } }); assertTrue(bugsnag.notify(new Throwable())); } @Test public void testSingleCallbackInNotify() { Bugsnag bugsnag = Bugsnag.init("apikey"); bugsnag.setDelivery(new Delivery() { @Override public void deliver(Serializer serializer, Object object, Map<String, String> headers) { Report report = ((Notification) object).getEvents().get(0); assertEquals("newapikey", report.getApiKey()); } @Override public void close() { } }); assertTrue(bugsnag.notify(new Throwable(), new Callback() { @Override public void beforeNotify(Report report) { report.setApiKey("newapikey"); } })); } @Test public void testCallbackOrder() { Bugsnag bugsnag = Bugsnag.init("apikey"); bugsnag.addCallback(new Callback() { @Override public void beforeNotify(Report report) { report.setApiKey("newapikey"); } }); bugsnag.addCallback(new Callback() { @Override public void beforeNotify(Report report) { report.setApiKey("secondnewapikey"); } }); bugsnag.setDelivery(new Delivery() { @Override public void deliver(Serializer serializer, Object object, Map<String, String> headers) { Report report = ((Notification) object).getEvents().get(0); assertEquals("secondnewapikey", report.getApiKey()); } @Override public void close() { } }); assertTrue(bugsnag.notify(new Throwable())); } @Test public void testCallbackCancel() { Bugsnag bugsnag = Bugsnag.init("apikey"); bugsnag.setDelivery(BugsnagTestUtils.generateDelivery()); bugsnag.addCallback(new Callback() { @Override public void beforeNotify(Report report) { report.cancel(); } }); // Test the report is not sent assertFalse(bugsnag.notify(new Throwable())); } @SuppressWarnings("deprecation") // ensures deprecated setEndpoint method still works correctly @Test public void testEndpoint() { Bugsnag bugsnag = Bugsnag.init("apikey"); bugsnag.setDelivery(new HttpDelivery() { String endpoint; @Override public void setEndpoint(String endpoint) { this.endpoint = endpoint; } @Override public void setTimeout(int timeout) { } @Override public void setProxy(Proxy proxy) { } @Override public void deliver(Serializer serializer, Object object, Map<String, String> headers) { assertEquals("https: } @Override public void close() { } }); bugsnag.setEndpoints("https: assertTrue(bugsnag.notify(new Throwable())); } @Test public void testProxy() { Bugsnag bugsnag = Bugsnag.init("apikey"); bugsnag.setDelivery(new HttpDelivery() { Proxy proxy; @Override public void setEndpoint(String endpoint) { } @Override public void setTimeout(int timeout) { } @Override public void setProxy(Proxy proxy) { this.proxy = proxy; } @Override public void deliver(Serializer serializer, Object object, Map<String, String> headers) { assertEquals("/127.0.0.1:8080", proxy.address().toString()); } @Override public void close() { } }); Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 8080)); bugsnag.setProxy(proxy); assertTrue(bugsnag.notify(new Throwable())); } @Test public void testSendThreads() { Bugsnag bugsnag = Bugsnag.init("apikey"); bugsnag.setSendThreads(true); bugsnag.setDelivery(new Delivery() { @Override public void deliver(Serializer serializer, Object object, Map<String, String> headers) { Report report = ((Notification) object).getEvents().get(0); // There is information about at least one thread assertTrue(report.getThreads().size() > 0); } @Override public void close() { } }); assertTrue(bugsnag.notify(new Throwable())); } @Test public void testHandledIncrementNoSession() { Bugsnag bugsnag = Bugsnag.init("apikey"); bugsnag.setDelivery(new Delivery() { @Override public void deliver(Serializer serializer, Object object, Map<String, String> headers) { Report report = ((Notification) object).getEvents().get(0); assertNull(report.getSession()); } @Override public void close() { } }); assertTrue(bugsnag.notify(new Throwable())); } @Test public void testHandledIncrementWithSession() { Bugsnag bugsnag = Bugsnag.init("apikey"); bugsnag.startSession(); bugsnag.setDelivery(new Delivery() { @Override public void deliver(Serializer serializer, Object object, Map<String, String> headers) { Report report = ((Notification) object).getEvents().get(0); Map<String, Object> session = report.getSession(); assertNotNull(session); @SuppressWarnings("unchecked") Map<String, Object> handledCounts = (Map<String, Object>) session.get("events"); assertEquals(1, handledCounts.get("handled")); assertEquals(0, handledCounts.get("unhandled")); } @Override public void close() { } }); assertTrue(bugsnag.notify(new Throwable())); } @Test public void testSerialization() { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); Bugsnag bugsnag = Bugsnag.init("apikey"); bugsnag.setDelivery(new OutputStreamDelivery(byteStream)); bugsnag.notify(new RuntimeException()); // Exact content will vary with stacktrace so just check for some content assertTrue(new String(byteStream.toByteArray()).length() > 0); } @Test(expected = UnsupportedOperationException.class) public void testUncaughtHandlerModification() { Set<Bugsnag> bugsnags = Bugsnag.uncaughtExceptionClients(); bugsnags.clear(); } // Test exception class private class TestException extends RuntimeException { private static final long serialVersionUID = -458298914160798211L; } }
package org.epics.pvmanager; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; public abstract class TypeSupport<T> { /** * Internal class to improve readability. * @author bknerr * @since 20.01.2011 */ private static final class TypeSupportMap extends ConcurrentHashMap<Class, TypeSupport> { private static final long serialVersionUID = -8726785703555122582L; public TypeSupportMap() { /* EMPTY */ } } private static final Map<Class<? extends TypeSupport>, TypeSupportMap> allTypeSupports = new ConcurrentHashMap<Class<? extends TypeSupport>, TypeSupportMap>(); private static final Map<Class<? extends TypeSupport>, TypeSupportMap> allCalcTypeSupports = new ConcurrentHashMap<Class<? extends TypeSupport>, TypeSupportMap>(); private static void addTypeSupportFamilyIfNotExists(final Map<Class<? extends TypeSupport>, TypeSupportMap> map, final Class<? extends TypeSupport> typeSupportFamily) { TypeSupportMap familyMap = map.get(typeSupportFamily); if (familyMap == null) { TypeSupportMap supportMap = new TypeSupportMap(); map.put(typeSupportFamily, supportMap); } } /** * Adds type support for the given class. The type support added will apply * to the given class and all of its subclasses. Support of the same * family cannot be added twice and will cause an exception. Support for * the more specific subclass overrides support for the more abstract class. * A class cannot have two types support in the same family coming from * two different and unrelated interfaces. * * @param typeSupport the support to add */ public static void addTypeSupport(final TypeSupport<?> typeSupport) { Class<? extends TypeSupport> typeSupportFamily = typeSupport.getTypeSupportFamily(); addTypeSupportFamilyIfNotExists(allTypeSupports, typeSupportFamily); addTypeSupportFamilyIfNotExists(allCalcTypeSupports, typeSupportFamily); // Can't install support for the same type twice if (allTypeSupports.get(typeSupportFamily).get(typeSupport.getType()) != null) { throw new RuntimeException(typeSupportFamily.getSimpleName() + " was already added for type " + typeSupport.getType().getName()); } allTypeSupports.get(typeSupportFamily).put(typeSupport.getType(), typeSupport); // Need to clear all calculated supports since registering an // interface may affect all the calculated supports // of all the implementations allCalcTypeSupports.get(typeSupportFamily).clear(); } /** * Calculates and caches the type support for a particular class, so that * introspection does not occur at every call. * * First the supertypes are recursively * * @param <T> the type to retrieve support for * @param typeClass the class of the type * @return the support for the type or null * @throws RuntimeException when no support could be identified */ protected static <T> TypeSupport<T> cachedTypeSupportFor(final Class<? extends TypeSupport> supportFamily, final Class<T> typeClass) { TypeSupportMap calcSupportMap = allCalcTypeSupports.get(supportFamily); TypeSupportMap supportMap = allTypeSupports.get(supportFamily); if (supportMap == null || calcSupportMap == null) { throw new RuntimeException("No type support found for family " + supportFamily, null); } // If we get the cached support for a specific type, // we are guaranteeded that they support is for that type @SuppressWarnings("unchecked") TypeSupport<T> support = (TypeSupport<T>) calcSupportMap.get(typeClass); if (support == null) { support = calculateSupport(typeClass, supportMap); if (support == null) { // It's up to the specific support to decide what to do return null; } calcSupportMap.put(typeClass, support); } return support; } private static <T> TypeSupport<T> calculateSupport(final Class<T> typeClass, final TypeSupportMap supportMap) { // Get all super types that have a support defined on Set<Class> superTypes = new HashSet<Class>(); recursiveAddAllSuperTypes(typeClass, superTypes); superTypes.retainAll(supportMap.keySet()); // No super type found, no support for this type if (superTypes.isEmpty()) { return null; } // Super types found, make sure that there is one // type that implements everything for (Class<?> type : superTypes) { boolean assignableToEverything = true; for (Class<?> compareType : superTypes) { assignableToEverything = assignableToEverything && compareType.isAssignableFrom(type); } if (assignableToEverything) { // The introspection above guarantees that the type // support is of a compatible type @SuppressWarnings("unchecked") TypeSupport<T> support = (TypeSupport<T>) supportMap.get(type); return support; } } throw new RuntimeException("Multiple support for type " + typeClass + " through " + superTypes); } private static void recursiveAddAllSuperTypes(Class clazz, Set<Class> superClasses) { // If already visited or null , return if (clazz == null || superClasses.contains(clazz)) { return; } superClasses.add(clazz); recursiveAddAllSuperTypes(clazz.getSuperclass(), superClasses); for (Class interf : clazz.getInterfaces()) { recursiveAddAllSuperTypes(interf, superClasses); } } /** * Creates a new type support of the given type * * @param type the type on which support is defined */ public TypeSupport(Class<T> type, Class<? extends TypeSupport> typeSupportFamily) { this.type = type; this.typeSupportFamily = typeSupportFamily; } // Type on which the support is defined private final Class<T> type; // Which kind of type support is defined private final Class<? extends TypeSupport> typeSupportFamily; /** * Defines which type of support is implementing, notification or time. * * @return the support family */ private Class<? extends TypeSupport> getTypeSupportFamily() { return typeSupportFamily; } /** * Defines on which class the support is defined. */ private Class<T> getType() { return type; } }
package net.hillsdon.svnwiki.vc; import java.util.regex.Matcher; import java.util.regex.Pattern; public interface PathTranslator { Pattern ATTACHMENT_PATH = Pattern.compile(".*/(.*?)-attachments/.*"); PathTranslator RELATIVE = new PathTranslator() { public String translate(String rootPath, String path) { return path.substring(rootPath.length() + 1); } }; PathTranslator ATTACHMENT_TO_PAGE = new PathTranslator() { public String translate(String rootPath, String path) { String name = RELATIVE.translate(rootPath, path); Matcher matcher = ATTACHMENT_PATH.matcher(path); if (matcher.matches()) { name = matcher.group(1); } return name; } }; String translate(String rootPath, String path); }
package net.mcft.copy.tweaks; import java.io.File; import net.mcft.copy.core.config.Config; import net.mcft.copy.core.config.setting.Setting; import net.mcft.copy.tweaks.handlers.AnimalBreedingGrowthHandler; import net.mcft.copy.tweaks.handlers.GravelFlintDropHandler; import net.mcft.copy.tweaks.handlers.MobDropHandler; import net.mcft.copy.tweaks.recipe.ArmorRecipes; import net.mcft.copy.tweaks.recipe.FMPSawRecipes; import net.mcft.copy.tweaks.recipe.MiscRecipes; import net.mcft.copy.tweaks.recipe.ToolRecipes; import net.mcft.copy.tweaks.util.ItemUtils; import net.mcft.copy.tweaks.util.recipe.RecipeActionReplace; import net.mcft.copy.tweaks.util.recipe.RecipeIterator; import net.mcft.copy.tweaks.util.recipe.RecipeMatcherOutputItem; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraftforge.common.MinecraftForge; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.EventHandler; import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; @Mod(modid = copyVanillaTweaks.MOD_ID, version = "@VERSION@", useMetadata = false, dependencies = "required-after:copycore;required-after:betterstorage", guiFactory = "net.mcft.copy.tweaks.client.gui.VanillaTweaksGuiFactory") public class copyVanillaTweaks { public static final String MOD_ID = "copyVanillaTweaks"; public static final String MOD_NAME = "copy's Vanilla Tweaks"; public static Config config; @EventHandler public void preInit(FMLPreInitializationEvent event) { setupConfig(event.getSuggestedConfigurationFile()); registerHandlers(); } @EventHandler public void postInit(FMLPostInitializationEvent event) { adjustToolAndArmorDurability(); iterateRecipes(); addRecipes(); } private void setupConfig(File configFile) { config = new VanillaTweaksConfig(configFile); config.load(); config.save(); } private void registerHandlers() { registerHandler(VanillaTweaksConfig.enableGravelFlintDropTweak, new GravelFlintDropHandler()); registerHandler(VanillaTweaksConfig.enableMobDropTweak, new MobDropHandler()); registerHandler(VanillaTweaksConfig.enableBreedingAndGrowthTweak, new AnimalBreedingGrowthHandler()); } private void registerHandler(Setting setting, Object handler) { if (config.<Boolean>get(setting)) MinecraftForge.EVENT_BUS.register(handler); } private void adjustToolAndArmorDurability() { ItemUtils.setToolDurability( 80, Items.wooden_sword, Items.wooden_pickaxe, Items.wooden_shovel, Items.wooden_axe, Items.wooden_hoe); ItemUtils.setToolDurability( 160, Items.stone_sword, Items.stone_pickaxe, Items.stone_shovel, Items.stone_axe, Items.stone_hoe); ItemUtils.setToolDurability( 160, Items.golden_sword, Items.golden_pickaxe, Items.golden_shovel, Items.golden_axe, Items.golden_hoe); ItemUtils.setToolDurability( 320, Items.iron_sword, Items.iron_pickaxe, Items.iron_shovel, Items.iron_axe, Items.iron_hoe); ItemUtils.setToolDurability(1720, Items.diamond_sword, Items.diamond_pickaxe, Items.diamond_shovel, Items.diamond_axe, Items.diamond_hoe); ItemUtils.setArmorDurability(10, Items.leather_helmet, Items.leather_chestplate, Items.leather_leggings, Items.leather_boots); ItemUtils.setArmorDurability(12, Items.golden_helmet, Items.golden_chestplate, Items.golden_leggings, Items.golden_boots); ItemUtils.setArmorDurability(16, Items.iron_helmet, Items.iron_chestplate, Items.iron_leggings, Items.iron_boots); ItemUtils.setArmorDurability(20, Items.chainmail_helmet, Items.chainmail_chestplate, Items.chainmail_leggings, Items.chainmail_boots); ItemUtils.setArmorDurability(32, Items.diamond_helmet, Items.diamond_chestplate, Items.diamond_leggings, Items.diamond_boots); } private void iterateRecipes() { RecipeIterator iterator = new RecipeIterator(); ToolRecipes.register(iterator); ArmorRecipes.register(iterator); MiscRecipes.register(iterator); FMPSawRecipes.register(iterator); if (config.<Boolean>get(VanillaTweaksConfig.replaceCobbleWithSmoothstone)) iterator.registerAction(new RecipeMatcherOutputItem( Blocks.lever, Blocks.dispenser, Blocks.dropper, Blocks.piston, Items.brewing_stand ), new RecipeActionReplace("cobblestone", "stone")); iterator.go(); } private void addRecipes() { ToolRecipes.add(); ArmorRecipes.add(); MiscRecipes.add(); FMPSawRecipes.add(); } }
package nl.tudelft.selfcompileapp; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.PrintWriter; import java.security.PrivateKey; import java.security.cert.X509Certificate; import java.util.Locale; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.view.View; import android.widget.Button; import kellinwood.security.zipsigner.ProgressEvent; import kellinwood.security.zipsigner.ProgressListener; import com.android.dex.Dex; import com.android.dx.merge.CollisionPolicy; import com.android.dx.merge.DexMerger; import com.android.sdklib.build.ApkBuilder; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void clean(View btnClean) { btnClean.setEnabled(false); new CleanBuild().execute(); } public void aidl(View btnAidl) { btnAidl.setEnabled(false); new ConvertAidl().execute(); } public void aapt(View btnAapt) { btnAapt.setEnabled(false); new PackAssets().execute(); } public void compile(View btnCompile) { btnCompile.setEnabled(false); new CompileJava().execute(); } public void dex(View btnDex) { btnDex.setEnabled(false); new DexMerge().execute(); } public void apk(View btnPack) { btnPack.setEnabled(false); new BuildApk().execute(); } public void sign(View btnSign) { btnSign.setEnabled(false); new SignApk().execute(); } public void align(View btnAlign) { btnAlign.setEnabled(false); new AlignApk().execute(); } public void install(View btnInstall) { btnInstall.setEnabled(false); new InstallApk().execute(); } private class CleanBuild extends AsyncTask<Object, Object, Object> { @Override protected void onPostExecute(Object result) { Button btnClean = (Button) findViewById(R.id.btnClean); btnClean.setEnabled(true); } @Override protected Object doInBackground(Object... params) { try { File dirRoot = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); File dirProj = new File(dirRoot, getString(R.string.app_name)); File dirSrc = new File(dirProj, "src"); File dirRes = new File(dirProj, "res"); File dirLibs = new File(dirProj, "libs"); File dirAssets = new File(dirProj, "assets"); File dirBin = new File(dirProj, "bin"); File dirDexedLibs = new File(dirBin, "dexedLibs"); File xmlMan = new File(dirProj, "AndroidManifest.xml"); File jarAndroid = new File(dirAssets, getString(R.string.platform) + ".jar"); File jksEmbedded = new File(dirAssets, getString(R.string.keystore)); System.out.println("// DELETE PROJECT FOLDER"); Util.deleteRecursive(dirProj); System.out.println("// EXTRACT PROJECT"); dirSrc.mkdirs(); dirRes.mkdirs(); dirLibs.mkdirs(); dirAssets.mkdirs(); dirBin.mkdirs(); dirDexedLibs.mkdirs(); Util.copy(getAssets().open(xmlMan.getName()), xmlMan); Util.copy(getAssets().open(jarAndroid.getName()), jarAndroid); Util.copy(getAssets().open(jksEmbedded.getName()), jksEmbedded); InputStream zipSrc = getAssets().open("src.zip"); Util.unzip(zipSrc, dirSrc); InputStream zipRes = getAssets().open("res.zip"); Util.unzip(zipRes, dirRes); InputStream zipLibs = getAssets().open("libs.zip"); Util.unzip(zipLibs, dirLibs); InputStream zipDexedLibs = getAssets().open("dexedLibs.zip"); Util.unzip(zipDexedLibs, dirDexedLibs); } catch (Exception e) { e.printStackTrace(); } return null; } } private class ConvertAidl extends AsyncTask<Object, Object, Object> { @Override protected void onPostExecute(Object result) { Button btnAidl = (Button) findViewById(R.id.btnAidl); btnAidl.setEnabled(true); } @Override protected Object doInBackground(Object... params) { try { System.out.println("// RUN AIDL"); // TODO } catch (Exception e) { e.printStackTrace(); } return null; } } private class PackAssets extends AsyncTask<Object, Object, Object> { @Override protected void onPostExecute(Object result) { Button btnAapt = (Button) findViewById(R.id.btnAapt); btnAapt.setEnabled(true); } @Override protected Object doInBackground(Object... params) { try { File dirRoot = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); File dirProj = new File(dirRoot, getString(R.string.app_name)); File dirGen = new File(dirProj, "gen"); File dirRes = new File(dirProj, "res"); File dirAssets = new File(dirProj, "assets"); File dirBin = new File(dirProj, "bin"); // File dirBinRes = new File(dirBin, "res"); // File dirCrunch = new File(dirBinRes, "crunch"); // File xmlBinMan = new File(dirBin, "AndroidManifest.xml"); File xmlMan = new File(dirProj, "AndroidManifest.xml"); File jarAndroid = new File(dirAssets, getString(R.string.platform) + ".jar"); File ap_Resources = new File(dirBin, "resources.ap_"); dirGen.mkdirs(); System.out.println("// DELETE xxhdpi"); // TODO update aapt Util.deleteRecursive(new File(dirRes, "drawable-xxhdpi")); Aapt aapt = new Aapt(); int exitCode; System.out.println("// RUN AAPT & CREATE R.JAVA"); exitCode = aapt.fnExecute("aapt p -f -v -M " + xmlMan.getPath() + " -F " + ap_Resources.getPath() + " -I " + jarAndroid.getPath() + " -A " + dirAssets.getPath() + " -S " + dirRes.getPath() + " -J " + dirGen.getPath()); if (exitCode != 0) { throw new Exception("AAPT exit(" + exitCode + ")"); } // System.out.println("// CREATE R.JAVA"); // C:\android-sdk\build-tools\23.0.0\aapt.exe package -m -v -J // E:\AndroidEclipseWorkspace\SelfCompileApp\gen -M // E:\AndroidEclipseWorkspace\SelfCompileApp\AndroidManifest.xml // -S E:\AndroidEclipseWorkspace\SelfCompileApp\res -I // C:\android-sdk\platforms\android-18\android.jar // exitCode = aapt.fnExecute("aapt p -m -v -J " + // dirGen.getPath() // + " -M " + xmlMan.getPath() + " -S " + dirRes.getPath() // System.out.println(exitCode); // System.out.println("// CRUNCH PNG"); // C:\android-sdk\build-tools\23.0.0\aapt.exe crunch -v -S // E:\AndroidEclipseWorkspace\SelfCompileApp\res -C // E:\AndroidEclipseWorkspace\SelfCompileApp\bin\res\crunch // exitCode = aapt.fnExecute("aapt c -v -S " + dirRes.getPath() // + " -C " + dirCrunch.getPath()); // System.out.println("// RUN AAPT"); // C:\android-sdk\build-tools\23.0.0\aapt.exe package -v -S // E:\AndroidEclipseWorkspace\SelfCompileApp\bin\res\crunch -S // E:\AndroidEclipseWorkspace\SelfCompileApp\res -f --no-crunch // --auto-add-overlay --debug-mode -0 apk -M // E:\AndroidEclipseWorkspace\SelfCompileApp\bin\AndroidManifest.xml // -A E:\AndroidEclipseWorkspace\SelfCompileApp\assets -I // C:\android-sdk\platforms\android-18\android.jar -F // E:\AndroidEclipseWorkspace\SelfCompileApp\bin\resources.ap_ // exitCode = aapt // .fnExecute("aapt p -v -S " // + dirCrunch.getPath() // + dirRes.getPath() // " -f --no-crunch --auto-add-overlay --debug-mode -0 apk -M " // + xmlBinMan.getPath() + " -A " // + dirAssets.getPath() + " -I " // + jarAndroid.getPath() + " -F " // + ap_Resources.getPath()); } catch (Exception e) { e.printStackTrace(); } return null; } } private class CompileJava extends AsyncTask<Object, Object, Object> { @Override protected void onPostExecute(Object result) { Button btnCompile = (Button) findViewById(R.id.btnCompile); btnCompile.setEnabled(true); } @Override protected Object doInBackground(Object... params) { try { File dirRoot = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); File dirProj = new File(dirRoot, getString(R.string.app_name)); File dirSrc = new File(dirProj, "src"); File dirGen = new File(dirProj, "gen"); File dirLibs = new File(dirProj, "libs"); File dirAssets = new File(dirProj, "assets"); File dirBin = new File(dirProj, "bin"); File dirClasses = new File(dirBin, "classes"); File jarAndroid = new File(dirAssets, getString(R.string.platform) + ".jar"); dirClasses.mkdirs(); String strBootCP = jarAndroid.getPath(); String strClassPath = ""; for (File jarLib : dirLibs.listFiles()) { if (jarLib.isDirectory()) { continue; } strClassPath += File.pathSeparator + jarLib.getPath(); } Locale.setDefault(Locale.ROOT); System.out.println("// COMPILE SOURCE RECURSIVE"); org.eclipse.jdt.core.compiler.batch.BatchCompiler.compile( new String[] { "-1.5", "-showversion", "-verbose", "-deprecation", "-bootclasspath", strBootCP, "-cp", strClassPath, "-d", dirClasses.getPath(), dirGen.getPath(), dirSrc.getPath() }, new PrintWriter(System.out), new PrintWriter(System.err), new CompileProgress()); } catch (Exception e) { e.printStackTrace(); } return null; } } private class CompileProgress extends org.eclipse.jdt.core.compiler.CompilationProgress { @Override public void begin(int arg0) { } @Override public void done() { } @Override public boolean isCanceled() { // TODO Auto-generated method stub return false; } @Override public void setTaskName(String arg0) { } @Override public void worked(int arg0, int arg1) { } } private class DexMerge extends AsyncTask<Object, Object, Object> { @Override protected void onPostExecute(Object result) { Button btnDex = (Button) findViewById(R.id.btnDex); btnDex.setEnabled(true); } @Override protected Object doInBackground(Object... params) { try { File dirRoot = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); File dirProj = new File(dirRoot, getString(R.string.app_name)); File dirLibs = new File(dirProj, "libs"); File dirBin = new File(dirProj, "bin"); File dirClasses = new File(dirBin, "classes"); File dirDexedLibs = new File(dirBin, "dexedLibs"); File dexClasses = new File(dirBin, "classes.dex"); dirDexedLibs.mkdirs(); System.out.println("// PRE-DEX LIBS"); for (File jarLib : dirLibs.listFiles()) { // skip native libs if (jarLib.isDirectory()) { continue; } // check if jar is pre-dexed File dexLib = new File(dirDexedLibs, jarLib.getName()); if (!dexLib.exists()) { com.android.dx.command.dexer.Main .main(new String[] { "--verbose", "--output=" + dexLib.getPath(), jarLib.getPath() }); } } System.out.println("// DEX CLASSES"); com.android.dx.command.dexer.Main .main(new String[] { "--verbose", "--output=" + dexClasses.getPath(), dirClasses.getPath() }); System.out.println("// MERGE PRE-DEXED LIBS"); for (File dexLib : dirDexedLibs.listFiles()) { Dex merged = new DexMerger(new Dex(dexClasses), new Dex(dexLib), CollisionPolicy.FAIL).merge(); merged.writeTo(dexClasses); } } catch (Exception e) { e.printStackTrace(); } return null; } } private class BuildApk extends AsyncTask<Object, Object, Object> { @Override protected void onPostExecute(Object result) { Button btnApk = (Button) findViewById(R.id.btnApk); btnApk.setEnabled(true); } @Override protected Object doInBackground(Object... params) { try { File dirRoot = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); File dirProj = new File(dirRoot, getString(R.string.app_name)); File dirSrc = new File(dirProj, "src"); File dirRes = new File(dirProj, "res"); File dirLibs = new File(dirProj, "libs"); File dirAssets = new File(dirProj, "assets"); File dirBin = new File(dirProj, "bin"); File dirDexedLibs = new File(dirBin, "dexedLibs"); File dirDist = new File(dirProj, "dist"); File apkUnsigned = new File(dirDist, getString(R.string.app_name) + ".unsigned.apk"); File ap_Resources = new File(dirBin, "resources.ap_"); File dexClasses = new File(dirBin, "classes.dex"); File xmlMan = new File(dirProj, "AndroidManifest.xml"); File zipSrc = new File(dirAssets, "src.zip"); File zipRes = new File(dirAssets, "res.zip"); File zipLibs = new File(dirAssets, "libs.zip"); File zipDexedLibs = new File(dirAssets, "dexedLibs.zip"); dirDist.mkdirs(); // Do NOT use embedded JarSigner PrivateKey privateKey = null; X509Certificate x509Cert = null; System.out.println("// RUN APK BUILDER"); ApkBuilder apkbuilder = new ApkBuilder(apkUnsigned, ap_Resources, dexClasses, privateKey, x509Cert, System.out); System.out.println("// ADD NATIVE LIBS"); apkbuilder.addNativeLibraries(dirLibs); System.out.println("// ADD LIB RESOURCES"); for (File jarLib : dirLibs.listFiles()) { if (jarLib.isDirectory()) { continue; } apkbuilder.addResourcesFromJar(jarLib); } System.out.println("// ZIP & ADD ASSETS"); // android.jar already packed by aapt // Embedded.jks already packed by aapt String strAssets = "assets" + File.separator; apkbuilder.addFile(xmlMan, strAssets + xmlMan.getName()); Util.zip(dirSrc, zipSrc); apkbuilder.addFile(zipSrc, strAssets + zipSrc.getName()); Util.zip(dirRes, zipRes); apkbuilder.addFile(zipRes, strAssets + zipRes.getName()); Util.zip(dirLibs, zipLibs); apkbuilder.addFile(zipLibs, strAssets + zipLibs.getName()); Util.zip(dirDexedLibs, zipDexedLibs); apkbuilder.addFile(zipDexedLibs, strAssets + zipDexedLibs.getName()); apkbuilder.setDebugMode(true); apkbuilder.sealApk(); } catch (Exception e) { e.printStackTrace(); } return null; } } private class SignApk extends AsyncTask<Object, Object, Object> { @Override protected void onPostExecute(Object result) { Button btnSign = (Button) findViewById(R.id.btnSign); btnSign.setEnabled(true); } @Override protected Object doInBackground(Object... params) { try { File dirRoot = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); File dirProj = new File(dirRoot, getString(R.string.app_name)); File dirAssets = new File(dirProj, "assets"); File dirDist = new File(dirProj, "dist"); File apkUnsigned = new File(dirDist, getString(R.string.app_name) + ".unsigned.apk"); File apkSigned = new File(dirDist, getString(R.string.app_name) + ".unaligned.apk"); File jksEmbedded = new File(dirAssets, getString(R.string.keystore)); String keystorePath = jksEmbedded.getPath(); char[] keystorePw = "android".toCharArray(); String certAlias = "androiddebugkey"; char[] certPw = "android".toCharArray(); String signatureAlgorithm = "SHA1withRSA"; System.out.println("// RUN ZIP SIGNER"); kellinwood.security.zipsigner.ZipSigner zipsigner = new kellinwood.security.zipsigner.ZipSigner(); zipsigner.addProgressListener(new ProgressListener() { public void onProgress(ProgressEvent event) { // TODO event.getPercentDone(); } }); kellinwood.security.zipsigner.optional.CustomKeySigner.signZip(zipsigner, keystorePath, keystorePw, certAlias, certPw, signatureAlgorithm, apkUnsigned.getPath(), apkSigned.getPath()); } catch (Exception e) { e.printStackTrace(); } return null; } } private class AlignApk extends AsyncTask<Object, Object, Object> { @Override protected void onPostExecute(Object result) { Button btnAlign = (Button) findViewById(R.id.btnAlign); btnAlign.setEnabled(true); } @Override protected Object doInBackground(Object... params) { try { System.out.println("// RUN ZIP ALIGN"); // TODO } catch (Exception e) { e.printStackTrace(); } return null; } } private class InstallApk extends AsyncTask<Object, Object, Object> { Uri url; @Override protected void onPostExecute(Object result) { Button btnInstall = (Button) findViewById(R.id.btnInstall); btnInstall.setEnabled(true); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(url, "application/vnd.android.package-archive"); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } @Override protected Object doInBackground(Object... params) { try { File dirRoot = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); File dirProj = new File(dirRoot, getString(R.string.app_name)); File dirDist = new File(dirProj, "dist"); File apk = new File(dirDist, getString(R.string.app_name) + ".unaligned.apk"); File apkCopy = new File(dirRoot, getString(R.string.app_name) + ".unaligned.apk"); if (apkCopy.exists()) { apkCopy.delete(); } System.out.println("// INSTALL APK"); Util.copy(apk, new FileOutputStream(apkCopy)); url = Uri.fromFile(apkCopy); } catch (Exception e) { e.printStackTrace(); } return null; } } }
package org.basex.gui.view.scatter; import static org.basex.util.Token.*; import org.basex.data.Data; import org.basex.data.StatsKey; import org.basex.data.StatsKey.Kind; import org.basex.gui.GUI; import org.basex.util.IntList; import org.basex.util.Set; import org.basex.util.TokenList; public final class ScatterAxis { /** Text length limit for text to number transformation. */ private static final int TEXTLENGTH = 11; /** Scatter data reference. */ private final ScatterData scatterData; /** Tag reference to selected attribute. */ int attrID; /** Constant to determine whether axis attribute equals deepFS "@size". */ private static final byte[] ATSIZE = token("size"); /** True if attribute is a tag, false if attribute. */ boolean isTag; /** Number of different categories for x attribute. */ int nrCats; /** Data type. */ Kind type; /** Coordinates of items. */ double[] co = {}; /** Item values. */ byte[][] vals = {}; /** Number of captions to display. */ int nrCaptions; /** Step for axis caption. */ double captionStep; /** Calculated caption step, view size not considered for calculation. */ private double calculatedCaptionStep; /** Minimum value in case selected attribute is numerical. */ double min; /** Maximum value in case selected attribute is numerical. */ double max; /** The different categories for the x attribute. */ byte[][] cats; /** * Constructor. * @param data scatte data reference */ ScatterAxis(final ScatterData data) { scatterData = data; } /** * (Re)Initializes axis. */ private void initialize() { isTag = false; type = Kind.INT; co = new double[0]; vals = new byte[0][]; nrCats = -1; cats = new byte[0][]; nrCaptions = -1; captionStep = -1; calculatedCaptionStep = -1; min = Integer.MIN_VALUE; max = Integer.MAX_VALUE; } /** * Called if the user has changed the caption of the axis. If a new * attribute was selected the positions of the plot items are recalculated. * @param attribute attribute selected by the user * @return true if new attribute was selected */ boolean setAxis(final String attribute) { if(attribute == null) return false; initialize(); byte[] b = token(attribute); isTag = !contains(b, '@'); b = delete(b, '@'); final Data data = GUI.context.data(); attrID = isTag ? data.tags.id(b) : data.atts.id(b); refreshAxis(); return true; } /** * Refreshes item list and coordinates if the selection has changed. So far * only numerical data is considered for plotting. If the selected attribute * is of kind TEXT, it is treated as INT. */ void refreshAxis() { final Data data = GUI.context.data(); final StatsKey key = isTag ? data.tags.stat(attrID) : data.atts.stat(attrID); type = key.kind; if(type == Kind.CAT) { final TokenList tl = new TokenList(); tl.add(EMPTY); for(final byte[] k : key.cats.keys()) tl.add(k); tl.sort(true); tl.add(EMPTY); cats = tl.finish(); nrCats = cats.length; } final int[] items = scatterData.pres; co = new double[items.length]; vals = new byte[items.length][]; for(int i = 0; i < items.length; i++) { byte[] value = getValue(items[i]); if(type == Kind.TEXT && value.length > TEXTLENGTH) { value = substring(value, 0, TEXTLENGTH); } vals[i] = value; } if(type != Kind.CAT) { if(type == Kind.TEXT) { textToNum(); } else { calcExtremeValues(); } } // coordinates for TEXT already calculated in textToNum() if(type != Kind.TEXT) { for(int i = 0; i < vals.length; i++) co[i] = calcPosition(vals[i]); } vals = null; } /** * TEXT data is transformed to categories, meaning each unique string forms * a category. The text values of the items are first sorted. The coordinate * for an item is then calculated as the position of the text value of this * item in the sorted category set. */ private void textToNum() { // sort text values alphabetical (asc). Set set = new Set(); for(int i = 0; i < vals.length; i++) { set.add(vals[i]); } // 2 additional empty categories are added for layout reasons -> +2 nrCats = set.size() + 2; set = null; // get sorted indexes for values final int[] tmpI = IntList.createOrder(vals, false, true).finish(); final int vl = vals.length; int i = 0; // find first non empty value while(i < vl && vals[i].length == 0) { co[tmpI[i]] = -1; i++; } // number of current category / position of item value in ordered // text set. first category remains empty for layout reasons int p = 1; while(i < vl) { // next string category to be tested final byte[] b = vals[i]; // l: highest index in sorted array for value b int l = i; // determing highest index of value/category b while(l < vl && eq(vals[l], b)) { l++; } // calculating positions for all items with value b in current category while(i < l) { final double d = (1.0d / (nrCats - 1)) * p; co[tmpI[i]] = d; i++; } p++; } } /** * Calculates the relative position of an item in the plot for a given value. * @param value item value * @return relative x or y value of the item */ double calcPosition(final byte[] value) { if(value.length == 0) { return -1; } double percentage = 0d; if(type != Kind.CAT) { final double d = toDouble(value); final double range = max - min; if(range == 0) percentage = 0.5d; else percentage = 1 / range * (d - min); } else { for(int i = 0; i < nrCats; i++) { if(eq(value, cats[i])) { percentage = (1.0d / (nrCats - 1)) * i; } } } return percentage; } /** * Returns the value for the specified pre value. * @param pre pre value * @return item value */ byte[] getValue(final int pre) { final Data data = GUI.context.data(); final int limit = pre + data.size(pre, Data.ELEM); for(int p = pre; p < limit; p++) { final int kind = data.kind(p); if(kind == Data.ELEM && isTag && attrID == data.tagID(p)) { return data.atom(p); } if(kind == Data.ATTR && !isTag && attrID == data.attNameID(p)) { return data.atom(p); } } return EMPTY; } /** * Determines the smallest and greatest occurring values for a specific item. * Afterwards the extremes are rounded to support a decent axis * caption. */ private void calcExtremeValues() { min = Integer.MAX_VALUE; max = Integer.MIN_VALUE; for(int i = 0; i < vals.length; i++) { if(vals[i].length < 1) continue; double d = toDouble(vals[i]); if(d < min) min = d; if(d > max) max = d; } if(max - min == 0) return; // flag for deepFS @size attribute final Data data = GUI.context.data(); int fsplus = 6; final boolean fss = data.fs != null && eq(data.atts.key(attrID), ATSIZE); // final boolean fss = false; final double range = max - min; final double lmin = min - range / 2; final double lmax = max + range / 2; final double rangePow = Math.floor(fss ? Math.log(Math.pow(Math.E, Math.exp(2))) : Math.log10(range) + .5d); final double lstep = (int) (Math.pow(fss ? 2 : 10, fss ? rangePow + fsplus : rangePow)); calculatedCaptionStep = (int) (Math.pow(fss ? 2 : 10, rangePow - (fss ? -fsplus : 1))); // calculatedCaptionStep = (int) (Math.pow(10, rangePow - 1)); // find minimum axis assignment double c = Math.floor(min); double m = c - c % calculatedCaptionStep; if(m > lmin) min = m; m = c - c % lstep; if(m > lmin) min = m; // find maximum axis assignment c = Math.ceil(max); boolean f = false; while(c < lmax) { if(c % lstep == 0) { max = c; break; } if(!f && c % calculatedCaptionStep == 0 && ((c - min) / calculatedCaptionStep) % 2 == 0) { max = c; f = true; } c -= c % calculatedCaptionStep; c += calculatedCaptionStep; } } /** * Calculates axis caption depending on view width / height. * @param space space of view axis available for captions */ void calcCaption(final int space) { if(type == Kind.DBL || type == Kind.INT) { final double range = max - min; if(range == 0) { nrCaptions = 3; captionStep = 0; return; } captionStep = calculatedCaptionStep; nrCaptions = (int) (range / captionStep) + 1; if(nrCaptions * ScatterView.itemSize(false) * 2 > space) { captionStep *= 2; nrCaptions = (int) (range / captionStep) + 1; } } else if(type == Kind.CAT) { nrCaptions = nrCats; } else { if(nrCats > 20) { final int c = space / (3 * ScatterView.CAPTIONWHITESPACE); nrCaptions = c >= 2 ? c : 2; } else { nrCaptions = nrCats; } // nrCaptions = 2; } } }
/* -*- c-basic-offset: 4; indent-tabs-mode: nil -*- */ package org.biojava.bio.seq.db.biosql; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import javax.sql.DataSource; import org.biojava.bio.BioRuntimeException; //import org.biojava.utils.JDBCConnectionPool; /** * Isolates all code that is specific to a particular RDBMS. To add * support for a new RDBMS, write a new <code>DBHelper</code> subclass * and ensure that it can be found by editing the * <code>getDBHelperForURL</code> method in this class. * * @author Thomas Down * @author Matthew Pocock * @author Len Trigg */ public abstract class DBHelper { /** * Returns a DBHelper implementation suitable for a particular * database. * * @param conn a connection to the database. * @return a <code>DBHelper</code>. */ public static DBHelper getDBHelper(Connection conn) { try { String dbType = conn.getMetaData().getURL(); if (dbType.startsWith("jdbc:")) { dbType = dbType.substring(5); } if (!Character.isLetter(dbType.charAt(0))) { throw new IllegalArgumentException("URL must start with a letter: " + dbType); } int colon = dbType.indexOf(':'); if (colon > 0) { String protocol = dbType.substring(0, colon); if (protocol.indexOf("mysql") >= 0) { // Accept any string containing `mysql', to cope with Caucho driver return new MySQLDBHelper(conn); } else if (protocol.equals("postgresql")) { return new PostgreSQLDBHelper(); } else if (protocol.equals("oracle")) { return new OracleDBHelper(); } else if (protocol.equals("hsqldb")) { return new HypersonicDBHelper(); } } } catch (SQLException se) { se.printStackTrace(); } return new UnknownDBHelper(); } public static final class DeleteStyle { private final String name; private DeleteStyle(String name) { this.name = name; } public String toString() { return "DBHelper.DeleteStyle: " + name; } } public static final DeleteStyle DELETE_POSTGRESQL = new DeleteStyle("Postgresql"); public static final DeleteStyle DELETE_MYSQL4 = new DeleteStyle("Mysql 4.02 or later"); public static final DeleteStyle DELETE_GENERIC = new DeleteStyle("Portable SQL"); /** * Returns the id value created during the last insert * command. This is for tables that have an auto increment column. * * @return the last id assigned, or -1 if the id could not be * found. */ public abstract int getInsertID(Connection conn, String table, String columnName) throws SQLException; /** * Returns the an object indicating the style of deletion that * this database should employ. * * @return the preferred deletion style. */ public abstract DeleteStyle getDeleteStyle(); public boolean containsTable(DataSource ds, String tablename) { if (ds == null) { throw new NullPointerException("Require a datasource."); } if ((tablename == null) || (tablename.length() == 0)) { throw new IllegalArgumentException("Invalid table name given"); } try { boolean present; PreparedStatement ps = null; Connection conn = null; try { conn = ds.getConnection(); ps = conn.prepareStatement("select * from " + tablename + " limit 1"); ps.executeQuery(); present = true; } catch (SQLException ex) { present = false; } if (ps != null) { ps.close(); } if (conn != null) { conn.close(); } return present; } catch (SQLException ex) { throw new BioRuntimeException(ex); } } }
package org.bouncycastle.asn1; import java.io.IOException; /** * ASN.1 TaggedObject - in ASN.1 nottation this is any object proceeded by * a [n] where n is some number - these are assume to follow the construction * rules (as with sequences). */ public abstract class ASN1TaggedObject extends ASN1Object implements ASN1TaggedObjectParser { int tagNo; boolean empty = false; boolean explicit = true; DEREncodable obj = null; static public ASN1TaggedObject getInstance( ASN1TaggedObject obj, boolean explicit) { if (explicit) { return (ASN1TaggedObject)obj.getObject(); } throw new IllegalArgumentException("implicitly tagged tagged object"); } static public ASN1TaggedObject getInstance( Object obj) { if (obj == null || obj instanceof ASN1TaggedObject) { return (ASN1TaggedObject)obj; } throw new IllegalArgumentException("unknown object in getInstance"); } /** * Create a tagged object in the explicit style. * * @param tagNo the tag number for this object. * @param obj the tagged object. */ public ASN1TaggedObject( int tagNo, DEREncodable obj) { this.explicit = true; this.tagNo = tagNo; this.obj = obj; } /** * Create a tagged object with the style given by the value of explicit. * <p> * If the object implements ASN1Choice the tag style will always be changed * to explicit in accordance with the ASN.1 encoding rules. * </p> * @param explicit true if the object is explicitly tagged. * @param tagNo the tag number for this object. * @param obj the tagged object. */ public ASN1TaggedObject( boolean explicit, int tagNo, DEREncodable obj) { if (obj instanceof ASN1Choice) { this.explicit = true; } else { this.explicit = explicit; } this.tagNo = tagNo; this.obj = obj; } boolean asn1Equals( DERObject o) { if (!(o instanceof ASN1TaggedObject)) { return false; } ASN1TaggedObject other = (ASN1TaggedObject)o; if (tagNo != other.tagNo || empty != other.empty || explicit != other.explicit) { return false; } if(obj == null) { if (other.obj != null) { return false; } } else { if (!(obj.getDERObject().equals(other.obj.getDERObject()))) { return false; } } return true; } public int hashCode() { int code = tagNo; if (obj != null) { code ^= obj.hashCode(); } return code; } public int getTagNo() { return tagNo; } /** * return whether or not the object may be explicitly tagged. * <p> * Note: if the object has been read from an input stream, the only * time you can be sure if isExplicit is returning the true state of * affairs is if it returns false. An implicitly tagged object may appear * to be explicitly tagged, so you need to understand the context under * which the reading was done as well, see getObject below. */ public boolean isExplicit() { return explicit; } public boolean isEmpty() { return empty; } /** * return whatever was following the tag. * <p> * Note: tagged objects are generally context dependent if you're * trying to extract a tagged object you should be going via the * appropriate getInstance method. */ public DERObject getObject() { if (obj != null) { return obj.getDERObject(); } return null; } /** * Return the object held in this tagged object as a parser assuming it has * the type of the passed in tag. If the object doesn't have a parser * associated with it, the base object is returned. */ public DEREncodable getObjectParser( int tag, boolean isExplicit) { switch (tag) { case DERTags.SET: return ASN1Set.getInstance(this, isExplicit).parser(); case DERTags.SEQUENCE: return ASN1Sequence.getInstance(this, isExplicit).parser(); case DERTags.OCTET_STRING: return ASN1OctetString.getInstance(this, isExplicit).parser(); } if (isExplicit) { return getObject(); } throw new RuntimeException("implicit tagging not implemented for tag: " + tag); } abstract void encode(DEROutputStream out) throws IOException; public String toString() { return "[" + tagNo + "]" + obj; } }
package org.bouncycastle.crypto.tls; import org.bouncycastle.asn1.sec.SECNamedCurves; import org.bouncycastle.asn1.x9.X9ECParameters; import org.bouncycastle.crypto.params.ECDomainParameters; /** * RFC 4492 5.1.1 * * The named curves defined here are those specified in SEC 2 [13]. Note that many of * these curves are also recommended in ANSI X9.62 [7] and FIPS 186-2 [11]. Values 0xFE00 * through 0xFEFF are reserved for private use. Values 0xFF01 and 0xFF02 indicate that the * client supports arbitrary prime and characteristic-2 curves, respectively (the curve * parameters must be encoded explicitly in ECParameters). */ public class NamedCurve { public static final int sect163k1 = 1; public static final int sect163r1 = 2; public static final int sect163r2 = 3; public static final int sect193r1 = 4; public static final int sect193r2 = 5; public static final int sect233k1 = 6; public static final int sect233r1 = 7; public static final int sect239k1 = 8; public static final int sect283k1 = 9; public static final int sect283r1 = 10; public static final int sect409k1 = 11; public static final int sect409r1 = 12; public static final int sect571k1 = 13; public static final int sect571r1 = 14; public static final int secp160k1 = 15; public static final int secp160r1 = 16; public static final int secp160r2 = 17; public static final int secp192k1 = 18; public static final int secp192r1 = 19; public static final int secp224k1 = 20; public static final int secp224r1 = 21; public static final int secp256k1 = 22; public static final int secp256r1 = 23; public static final int secp384r1 = 24; public static final int secp521r1 = 25; /* * reserved (0xFE00..0xFEFF) */ public static final int arbitrary_explicit_prime_curves = 0xFF01; public static final int arbitrary_explicit_char2_curves = 0xFF02; private static final String[] curveNames = new String[] { "sect163k1", "sect163r1", "sect163r2", "sect193r1", "sect193r2", "sect233k1", "sect233r1", "sect239k1", "sect283k1", "sect283r1", "sect409k1", "sect409r1", "sect571k1", "sect571r1", "secp160k1", "secp160r1", "secp160r2", "secp192k1", "secp192r1", "secp224k1", "secp224r1", "secp256k1", "secp256r1", "secp384r1", "secp521r1", }; static ECDomainParameters getECParameters(int namedCurve) { int index = namedCurve - 1; if (index < 0 || index >= curveNames.length) { return null; } String curveName = curveNames[index]; // Lazily created the first time a particular curve is accessed X9ECParameters ecP = SECNamedCurves.getByName(curveName); if (ecP == null) { return null; } // It's a bit inefficient to do this conversion every time return new ECDomainParameters(ecP.getCurve(), ecP.getG(), ecP.getN(), ecP.getH(), ecP.getSeed()); } }
package org.broad.igv.feature.tribble; import org.apache.log4j.Logger; import org.broad.igv.Globals; import org.broad.igv.exceptions.ParserException; import org.broad.igv.feature.BasicFeature; import org.broad.igv.feature.FeatureDB; import org.broad.igv.feature.Strand; import org.broad.igv.feature.genome.Genome; import org.broad.igv.track.GFFFeatureSource; import org.broad.igv.track.TrackProperties; import org.broad.igv.ui.IGV; import org.broad.igv.ui.color.ColorUtilities; import org.broad.igv.util.ParsingUtils; import org.broad.igv.util.StringUtils; import org.broad.igv.util.collections.CI; import org.broad.igv.util.collections.MultiMap; import org.broad.tribble.AsciiFeatureCodec; import org.broad.tribble.Feature; import org.broad.tribble.exception.CodecLineParsingException; import org.broad.tribble.readers.LineReader; import java.io.IOException; import java.util.*; public class GFFCodec extends AsciiFeatureCodec<Feature> { private static Logger log = Logger.getLogger(GFFCodec.class); public static Set<String> exonTerms = new HashSet(); public static Set<String> utrTerms = new HashSet(); public static Set<String> geneParts = new HashSet(); static HashSet<String> ignoredTypes = new HashSet(); static { utrTerms.add("five_prime_UTR"); utrTerms.add("three_prime_UTR"); utrTerms.add("5'-utr"); utrTerms.add("3'-utr"); utrTerms.add("3'-UTR"); utrTerms.add("5'-UTR"); utrTerms.add("5utr"); utrTerms.add("3utr"); } static { exonTerms.addAll(utrTerms); exonTerms.add("exon"); exonTerms.add("coding_exon"); exonTerms.add("CDS"); exonTerms.add("cds"); } static { geneParts.addAll(exonTerms); geneParts.add("transcript"); geneParts.add("processed_transcript"); geneParts.add("mrna"); geneParts.add("mRNA"); geneParts.add("promoter"); geneParts.add("intron"); geneParts.add("CDS_parts"); } static { ignoredTypes.add("start_codon"); ignoredTypes.add("stop_codon"); ignoredTypes.add("Contig"); ignoredTypes.add("RealContig"); ignoredTypes.add("intron"); } private TrackProperties trackProperties = null; CI.CIHashSet featuresToHide = new CI.CIHashSet(); FeatureFileHeader header; Helper helper; Genome genome; public enum Version { GFF2, GFF3 } /** * List of know "Name" fields. Some important fields from the GFF3 spec are listed below. Note GFF3 * is case sensitive, however GFF2, GTF, and other variants might not be. * <p/> * ID Indicates the ID of the feature. * Name Display name for the feature. * Alias A secondary name for the feature. */ static String[] nameFields = {"Name", "name", "Alias", "gene", "primary_name", "locus", "alias", "systematic_id", "ID"}; public GFFCodec(Genome genome) { super(Feature.class); // Assume GFF2 until shown otherwise helper = new GFF2Helper(); this.genome = genome; } public GFFCodec(Version version, Genome genome) { super(Feature.class); this.genome = genome; if (version == Version.GFF2) { helper = new GFF2Helper(); } else { helper = new GFF3Helper(); } } public void readHeaderLine(String line) { header = new FeatureFileHeader(); if (line.startsWith("#track") || line.startsWith("##track")) { trackProperties = new TrackProperties(); ParsingUtils.parseTrackLine(line, trackProperties); header.setTrackProperties(trackProperties); } else if (line.startsWith("##gff-version") && line.endsWith("3")) { helper = new GFF3Helper(); } else if (line.startsWith("#nodecode") || line.startsWith("##nodecode")) { helper.setUrlDecoding(false); } else if (line.startsWith("#hide") || line.startsWith("##hide")) { String[] kv = line.split("="); if (kv.length > 1) { featuresToHide.addAll(Arrays.asList(kv[1].split(","))); } } else if (line.startsWith("#displayName") || line.startsWith("##displayName")) { String[] nameTokens = line.split("="); if (nameTokens.length < 2) { helper.setNameFields(null); } else { String[] fields = nameTokens[1].split(","); helper.setNameFields(fields); } } } public Object readHeader(LineReader reader) { header = new FeatureFileHeader(); String line; int nLines = 0; try { while ((line = reader.readLine()) != null) { if (line.startsWith(" nLines++; readHeaderLine(line); } else { break; } } header.setTrackProperties(trackProperties); return header; } catch (IOException e) { throw new CodecLineParsingException("Error parsing header", e); } } /** * This function returns true iff the File potentialInput can be parsed by this * codec. * <p/> * There is an assumption that there's never a situation where two different Codecs * return true for the same file. If this occurs, the recommendation would be to error out. * <p/> * Note this function must never throw an error. All errors should be trapped * and false returned. * * @param path the file to test for parsability with this codec * @return true if potentialInput can be parsed, false otherwise */ public boolean canDecode(String path) { final String pathLowerCase = path.toLowerCase(); return pathLowerCase.endsWith(".gff") || pathLowerCase.endsWith(".gff3") || pathLowerCase.endsWith(".gvf"); } public BasicFeature decodeLoc(String line) { return decode(line); } public BasicFeature decode(String line) { if (line.startsWith(" // This should not be possible as this line would be parsed as a header. But just in case return null; } String[] tokens = Globals.tabPattern.split(line, -1); int nTokens = tokens.length; // GFF3 files have 9 tokens, // TODO -- the attribute column is optional for GFF 2 and earlier (8 tokens required) if (nTokens < 9) { return null; } String chrToken = tokens[0].trim(); String featureType = tokens[2].trim(); if(ignoredTypes.contains(featureType)) { return null; } String chromosome = genome == null ? chrToken : genome.getChromosomeAlias(chrToken); // GFF coordinates are 1-based inclusive (length = end - start + 1) // IGV (UCSC) coordinates are 0-based exclusive. Adjust start and end accordingly int start; int end; int col = 3; try { start = Integer.parseInt(tokens[col]) - 1; col++; end = Integer.parseInt(tokens[col]); } catch (NumberFormatException ne) { String msg = String.format("Column %d must contain a numeric value. %s", col + 1, ne.getMessage()); throw new ParserException(msg, -1, line); } Strand strand = convertStrand(tokens[6]); String attributeString = tokens[8]; //CI.CILinkedHashMap<String> attributes = new CI.CILinkedHashMap(); MultiMap<String, String> attributes = new MultiMap<String, String>(); helper.parseAttributes(attributeString, attributes); String description = getDescription(attributes, featureType); String id = helper.getID(attributes); String[] parentIds = helper.getParentIds(attributes, attributeString); if (exonTerms.contains(featureType) && parentIds != null && parentIds.length > 0 && parentIds[0] != null && parentIds[0].length() > 0 && !parentIds[0].equals(".")) { //Somewhat tacky, but we need to store the phase somewhere in the feature String phaseString = tokens[7].trim(); //String old = attributes.put(GFFFeatureSource.PHASE_STRING, phaseString); //if(old != null){ // log.debug("phase string attribute was overwritten internally; old value was: " + old); } BasicFeature f = new BasicFeature(chromosome, start, end, strand); f.setName(getName(attributes)); f.setType(featureType); f.setDescription(description); f.setIdentifier(id); f.setParentIds(parentIds); f.setAttributes(attributes); if (attributes.containsKey("color")) { f.setColor(ColorUtilities.stringToColor(attributes.get("color"))); } if (featuresToHide.contains(featureType)) { if (IGV.hasInstance()) FeatureDB.addFeature(f); return null; } return f; } public Object getHeader() { return header; } private Strand convertStrand(String strandString) { Strand strand = Strand.NONE; if (strandString.equals("-")) { strand = Strand.NEGATIVE; } else if (strandString.equals("+")) { strand = Strand.POSITIVE; } return strand; } String getName(MultiMap<String, String> attributes) { if (attributes == null || attributes.size() == 0) { return null; } for (String nf : nameFields) { if (attributes.containsKey(nf)) { return attributes.get(nf); } } return ""; } static StringBuffer buf = new StringBuffer(); static String getDescription(MultiMap<String, String> attributes, String type) { buf.setLength(0); buf.append(type); buf.append("<br>"); attributes.printHtml(buf, 100); return buf.toString(); } protected interface Helper { String[] getParentIds(MultiMap<String, String> attributes, String attributeString); void parseAttributes(String attributeString, MultiMap<String, String> map); String getID(MultiMap<String, String> attributes); void setUrlDecoding(boolean b); String getName(MultiMap<String, String> attributes); void setNameFields(String[] fields); } public static class GFF2Helper implements Helper { //TODO Almost identical static String[] idFields = {"systematic_id", "ID", "transcript_id", "name", "primary_name", "gene", "locus", "alias"}; static String[] DEFAULT_NAME_FIELDS = {"gene", "name", "primary_name", "locus", "alias", "systematic_id", "ID"}; private String[] nameFields; GFF2Helper() { this(DEFAULT_NAME_FIELDS); } GFF2Helper(String[] nameFields) { if (nameFields != null) { this.nameFields = nameFields; } } public void setUrlDecoding(boolean b) { // Ignored, GFF2 files are never url DECODED } public void parseAttributes(String description, MultiMap<String, String> kvalues) { List<String> kvPairs = StringUtils.breakQuotedString(description.trim(), ';'); for (String kv : kvPairs) { List<String> tokens = StringUtils.breakQuotedString(kv, ' '); if (tokens.size() >= 2) { String key = tokens.get(0).trim().replaceAll("\"", ""); String value = tokens.get(1).trim().replaceAll("\"", ""); kvalues.put(key, value); } } } /** * parentIds[0] = attributes.get("id"); * if (parentIds[0] == null) { * parentIds[0] = attributes.get("mRNA"); * } * if (parentIds[0] == null) { * parentIds[0] = attributes.get("systematic_id"); * } * if (parentIds[0] == null) { * parentIds[0] = attributes.get("transcript_id"); * } * if (parentIds[0] == null) { * parentIds[0] = attributes.get("gene"); * } * if (parentIds[0] == null) { * parentIds[0] = attributes.get("transcriptId"); * } * if (parentIds[0] == null) { * parentIds[0] = attributes.get("proteinId"); * } * * @param attributes * @param attributeString * @return */ public String[] getParentIds(MultiMap<String, String> attributes, String attributeString) { String[] parentIds = new String[1]; if (attributes.size() == 0) { parentIds[0] = attributeString; } else { String[] possNames = new String[]{"id", "mRna", "systematic_id", "transcript_id", "gene", "transcriptId", "proteinId"}; for (String possName : possNames) { if (attributes.containsKey(possName)) { parentIds[0] = attributes.get(possName); break; } } } return parentIds; } public String getID(MultiMap<String, String> attributes) { for (String nf : idFields) { if (attributes.containsKey(nf)) { return attributes.get(nf); } } return getName(attributes); } public String getName(MultiMap<String, String> attributes) { if (attributes.size() > 0 && nameFields != null) { for (String nf : nameFields) { if (attributes.containsKey(nf)) { return attributes.get(nf); } } } return null; } public void setNameFields(String[] nameFields) { this.nameFields = nameFields; } } public static class GFF3Helper implements Helper { static String[] DEFAULT_NAME_FIELDS = {"Name", "Alias", "ID", "gene", "locus"}; private boolean useUrlDecoding = true; private String[] nameFields; public GFF3Helper() { this(DEFAULT_NAME_FIELDS); } GFF3Helper(String[] nameFields) { if (nameFields != null) { this.nameFields = nameFields; } } public String[] getParentIds(MultiMap<String, String> attributes, String ignored) { String parentIdString = attributes.get("Parent"); if (parentIdString != null) { return parentIdString.split(","); } else { return null; } } /** * Parse the column 9 attributes. Attributes are separated by semicolons. * * TODO -- quotes (column 9) are explicitly forbidden in GFF3 -- should breakQuotedString be used? * * @param description * @param kvalues */ public void parseAttributes(String description, MultiMap<String, String> kvalues) { List<String> kvPairs = StringUtils.breakQuotedString(description.trim(), ';'); for (String kv : kvPairs) { //int nValues = ParsingUtils.split(kv, tmp, '='); List<String> tmp = StringUtils.breakQuotedString(kv, '='); int nValues = tmp.size(); if (nValues > 0) { String key = tmp.get(0).trim(); String value = ((nValues == 1) ? "" : tmp.get(1).trim()); if (useUrlDecoding) { key = StringUtils.decodeURL(key); value = StringUtils.decodeURL(value); // Limit values to 50 characters if (value.length() > 50) { value = value.substring(0, 50) + " ..."; } } kvalues.put(key, value); } else { log.info("No attributes: " + description); } } } public void setUrlDecoding(boolean useUrlDecoding) { this.useUrlDecoding = useUrlDecoding; } public String getName(MultiMap<String, String> attributes) { if (attributes.size() > 0 && nameFields != null) { for (String nf : nameFields) { if (attributes.containsKey(nf)) { return attributes.get(nf); } } } return null; } public String getID(MultiMap<String, String> attributes) { return attributes.get("ID"); } public void setNameFields(String[] nameFields) { this.nameFields = nameFields; } } /** * Helper for GTF files * <p/> * mandatory attributes * gene_id value; A globally unique identifier for the genomic source of the transcript * transcript_id value; A globally unique identifier for the predicted transcript. * <p/> * Attributes must end in a semicolon which must then be separated from the start of any subsequent * attribute by exactly one space character (NOT a tab character). * <p/> * Textual attributes should be surrounded by doublequotes. */ public static class GTFHelper implements Helper { @Override public void parseAttributes(String description, MultiMap<String, String> kvalues) { List<String> kvPairs = StringUtils.breakQuotedString(description.trim(), ';'); for (String kv : kvPairs) { List<String> tokens = StringUtils.breakQuotedString(kv, ' '); if (tokens.size() >= 2) { String key = tokens.get(0).trim().replaceAll("\"", ""); String value = tokens.get(1).trim().replaceAll("\"", ""); kvalues.put(key, value); } } } @Override public String[] getParentIds(MultiMap<String, String> attributes, String attributeString) { return new String[0]; //To change body of implemented methods use File | Settings | File Templates. } @Override public String getID(MultiMap<String, String> attributes) { return attributes.get("transcript_id"); //To change body of implemented methods use File | Settings | File Templates. } @Override public void setUrlDecoding(boolean b) { //To change body of implemented methods use File | Settings | File Templates. } @Override public String getName(MultiMap<String, String> attributes) { return attributes.get("transcript_id"); //To change body of implemented methods use File | Settings | File Templates. } @Override public void setNameFields(String[] fields) { //To change body of implemented methods use File | Settings | File Templates. } } }
package org.eclipse.imp.pdb.facts.util; import static org.eclipse.imp.pdb.facts.util.ArrayUtils.copyAndInsert; import static org.eclipse.imp.pdb.facts.util.ArrayUtils.copyAndMoveToBack; import static org.eclipse.imp.pdb.facts.util.ArrayUtils.copyAndMoveToFront; import static org.eclipse.imp.pdb.facts.util.ArrayUtils.copyAndRemove; import static org.eclipse.imp.pdb.facts.util.ArrayUtils.copyAndSet; import java.util.AbstractSet; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.concurrent.atomic.AtomicReference; @SuppressWarnings("rawtypes") public class TrieSet<K> extends AbstractImmutableSet<K> { @SuppressWarnings("unchecked") private static final TrieSet EMPTY_INPLACE_INDEX_SET = new TrieSet( CompactSetNode.EMPTY_INPLACE_INDEX_NODE, 0, 0); private final AbstractSetNode<K> rootNode; private final int hashCode; private final int cachedSize; TrieSet(AbstractSetNode<K> rootNode, int hashCode, int cachedSize) { this.rootNode = rootNode; this.hashCode = hashCode; this.cachedSize = cachedSize; assert invariant(); } @SuppressWarnings("unchecked") public static final <K> ImmutableSet<K> of() { return TrieSet.EMPTY_INPLACE_INDEX_SET; } @SuppressWarnings("unchecked") public static final <K> ImmutableSet<K> of(K... keys) { ImmutableSet<K> result = TrieSet.EMPTY_INPLACE_INDEX_SET; for (K item : keys) { result = result.__insert(item); } return result; } @SuppressWarnings("unchecked") public static final <K> TransientSet<K> transientOf() { return TrieSet.EMPTY_INPLACE_INDEX_SET.asTransient(); } @SafeVarargs @SuppressWarnings("unchecked") public static final <K> TransientSet<K> transientOf(K... keys) { final TransientSet<K> result = TrieSet.EMPTY_INPLACE_INDEX_SET.asTransient(); for (K item : keys) { result.__insert(item); } return result; } @SuppressWarnings("unchecked") protected static final <K> Comparator<K> equalityComparator() { return EqualityUtils.getDefaultEqualityComparator(); } private boolean invariant() { int _hash = 0; int _count = 0; for (SupplierIterator<K, K> it = keyIterator(); it.hasNext();) { final K key = it.next(); _hash += key.hashCode(); _count += 1; } return this.hashCode == _hash && this.cachedSize == _count; } @Override public TrieSet<K> __insert(K k) { return __insertEquivalent(k, equalityComparator()); } @Override public TrieSet<K> __insertEquivalent(K key, Comparator<Object> cmp) { final int keyHash = key.hashCode(); final Result<K, Void, ? extends AbstractSetNode<K>> result = rootNode.updated(null, key, keyHash, null, 0, cmp); if (result.isModified()) { return new TrieSet<K>(result.getNode(), hashCode + keyHash, cachedSize + 1); } return this; } @Override public ImmutableSet<K> __insertAll(ImmutableSet<? extends K> set) { return __insertAllEquivalent(set, equalityComparator()); } @Override public ImmutableSet<K> __insertAllEquivalent(ImmutableSet<? extends K> set, Comparator<Object> cmp) { TransientSet<K> tmp = asTransient(); tmp.__insertAllEquivalent(set, cmp); return tmp.freeze(); } @Override public ImmutableSet<K> __retainAll(ImmutableSet<? extends K> set) { return __retainAllEquivalent(set, equalityComparator()); } @Override public ImmutableSet<K> __retainAllEquivalent(ImmutableSet<? extends K> set, Comparator<Object> cmp) { TransientSet<K> tmp = asTransient(); tmp.__retainAllEquivalent(set, cmp); return tmp.freeze(); } @Override public TrieSet<K> __remove(K k) { return __removeEquivalent(k, equalityComparator()); } @Override public TrieSet<K> __removeEquivalent(K key, Comparator<Object> cmp) { final int keyHash = key.hashCode(); final Result<K, Void, ? extends AbstractSetNode<K>> result = rootNode.removed(null, key, keyHash, 0, cmp); if (result.isModified()) { // TODO: carry deleted value in result // assert result.hasReplacedValue(); // final int valHash = result.getReplacedValue().hashCode(); return new TrieSet<K>(result.getNode(), hashCode - keyHash, cachedSize - 1); } return this; } @Override public ImmutableSet<K> __removeAll(ImmutableSet<? extends K> set) { return __removeAllEquivalent(set, equalityComparator()); } @Override public ImmutableSet<K> __removeAllEquivalent(ImmutableSet<? extends K> set, Comparator<Object> cmp) { TransientSet<K> tmp = asTransient(); tmp.__removeAllEquivalent(set, cmp); return tmp.freeze(); } @Override public boolean contains(Object o) { return rootNode.containsKey(o, o.hashCode(), 0, equalityComparator()); } @Override public boolean containsEquivalent(Object o, Comparator<Object> cmp) { return rootNode.containsKey(o, o.hashCode(), 0, cmp); } @Override public K get(Object key) { return getEquivalent(key, equalityComparator()); } @Override public K getEquivalent(Object key, Comparator<Object> cmp) { final Optional<K> result = rootNode.findByKey(key, key.hashCode(), 0, cmp); if (result.isPresent()) { return result.get(); } else { return null; } } @Override public int size() { return cachedSize; } @Override public Iterator<K> iterator() { return keyIterator(); } @Override public SupplierIterator<K, K> keyIterator() { return new TrieSetIteratorWithFixedWidthStack<>(rootNode); } // @Override // public SupplierIterator<K, K> keyIterator() { // return new TrieSetIteratorWithFixedWidthStack<>(rootNode); private static class TrieSetIteratorWithFixedWidthStack<K> implements SupplierIterator<K, K> { int valueIndex; int valueLength; AbstractSetNode<K> valueNode; K lastValue = null; int stackLevel; int[] indexAndLength = new int[7 * 2]; @SuppressWarnings("unchecked") AbstractSetNode<K>[] nodes = new AbstractSetNode[7]; TrieSetIteratorWithFixedWidthStack(AbstractSetNode<K> rootNode) { stackLevel = 0; valueNode = rootNode; valueIndex = 0; valueLength = rootNode.payloadArity(); nodes[0] = rootNode; indexAndLength[0] = 0; indexAndLength[1] = rootNode.nodeArity(); } @Override public boolean hasNext() { if (valueIndex < valueLength) { return true; } while (true) { final int nodeIndex = indexAndLength[2 * stackLevel]; final int nodeLength = indexAndLength[2 * stackLevel + 1]; if (nodeIndex < nodeLength) { final AbstractSetNode<K> nextNode = nodes[stackLevel].getNode(nodeIndex); indexAndLength[2 * stackLevel] = (nodeIndex + 1); final int nextNodeValueArity = nextNode.payloadArity(); final int nextNodeNodeArity = nextNode.nodeArity(); if (nextNodeNodeArity != 0) { stackLevel++; nodes[stackLevel] = nextNode; indexAndLength[2 * stackLevel] = 0; indexAndLength[2 * stackLevel + 1] = nextNode.nodeArity(); } if (nextNodeValueArity != 0) { valueNode = nextNode; valueIndex = 0; valueLength = nextNodeValueArity; return true; } } else { if (stackLevel == 0) { return false; } stackLevel } } } @Override public K next() { if (!hasNext()) { throw new NoSuchElementException(); } else { K lastKey = valueNode.getKey(valueIndex); lastValue = lastKey; valueIndex += 1; return lastKey; } } @Override public K get() { if (lastValue == null) { throw new NoSuchElementException(); } else { K tmp = lastValue; lastValue = null; return tmp; } } @Override public void remove() { throw new UnsupportedOperationException(); } } @Override public boolean isTransientSupported() { return true; } @Override public TransientSet<K> asTransient() { return new TransientTrieSet<K>(this); } static final class TransientTrieSet<K> extends AbstractSet<K> implements TransientSet<K> { final private AtomicReference<Thread> mutator; private AbstractSetNode<K> rootNode; private int hashCode; private int cachedSize; TransientTrieSet(TrieSet<K> TrieSet) { this.mutator = new AtomicReference<Thread>(Thread.currentThread()); this.rootNode = TrieSet.rootNode; this.hashCode = TrieSet.hashCode; this.cachedSize = TrieSet.cachedSize; assert invariant(); } // TODO: merge with TrieSet invariant (as function) private boolean invariant() { int _hash = 0; for (SupplierIterator<K, K> it = keyIterator(); it.hasNext();) { final K key = it.next(); _hash += key.hashCode(); } return this.hashCode == _hash; } @Override public boolean contains(Object o) { return rootNode.containsKey(o, o.hashCode(), 0, equalityComparator()); } @Override public boolean containsEquivalent(Object o, Comparator<Object> cmp) { return rootNode.containsKey(o, o.hashCode(), 0, cmp); } @Override public boolean containsAll(Collection<?> c) { for (Object item : c) { if (!contains(item)) { return false; } } return true; } @Override public boolean containsAllEquivalent(Collection<?> c, Comparator<Object> cmp) { for (Object item : c) { if (!containsEquivalent(item, cmp)) { return false; } } return true; } @Override public K get(Object key) { return getEquivalent(key, equalityComparator()); } @Override public K getEquivalent(Object key, Comparator<Object> cmp) { final Optional<K> result = rootNode.findByKey(key, key.hashCode(), 0, cmp); if (result.isPresent()) { return result.get(); } else { return null; } } @Override public boolean __insert(K k) { return __insertEquivalent(k, equalityComparator()); } @Override public boolean __insertEquivalent(K key, Comparator<Object> cmp) { if (mutator.get() == null) { throw new IllegalStateException("Transient already frozen."); } final int keyHash = key.hashCode(); final Result<K, Void, ? extends AbstractSetNode<K>> result = rootNode.updated(mutator, key, keyHash, null, 0, cmp); if (result.isModified()) { rootNode = result.getNode(); hashCode += keyHash; cachedSize += 1; assert invariant(); return true; } assert invariant(); return false; } @Override public boolean __retainAll(ImmutableSet<? extends K> set) { return __retainAllEquivalent(set, equalityComparator()); } @Override public boolean __retainAllEquivalent(ImmutableSet<? extends K> set, Comparator<Object> cmp) { boolean modified = false; Iterator<K> thisIterator = iterator(); while (thisIterator.hasNext()) { if (!set.containsEquivalent(thisIterator.next(), cmp)) { thisIterator.remove(); modified = true; } } return modified; } @Override public boolean __remove(K k) { return __removeEquivalent(k, equalityComparator()); } @Override public boolean __removeEquivalent(K key, Comparator<Object> cmp) { if (mutator.get() == null) { throw new IllegalStateException("Transient already frozen."); } final int keyHash = key.hashCode(); final Result<K, Void, ? extends AbstractSetNode<K>> result = rootNode.removed(mutator, key, keyHash, 0, cmp); if (result.isModified()) { // TODO: carry deleted value in result // assert result.hasReplacedValue(); // final int valHash = result.getReplacedValue().hashCode(); rootNode = result.getNode(); hashCode -= keyHash; cachedSize -= 1; assert invariant(); return true; } assert invariant(); return false; } @Override public boolean __removeAll(ImmutableSet<? extends K> set) { return __removeAllEquivalent(set, equalityComparator()); } @Override public boolean __removeAllEquivalent(ImmutableSet<? extends K> set, Comparator<Object> cmp) { boolean modified = false; for (K key : set) { modified |= __removeEquivalent(key, cmp); } return modified; } @Override public boolean __insertAll(ImmutableSet<? extends K> set) { return __insertAllEquivalent(set, equalityComparator()); } @Override public boolean __insertAllEquivalent(ImmutableSet<? extends K> set, Comparator<Object> cmp) { boolean modified = false; for (K key : set) { modified |= __insertEquivalent(key, cmp); } return modified; } @Override public int size() { return cachedSize; } @Override public Iterator<K> iterator() { return keyIterator(); } // TODO: test; declare in transient interface // @Override @Override public SupplierIterator<K, K> keyIterator() { return new TransientTrieSetIterator<K>(this); } /** * Iterator that first iterates over inlined-values and then continues * depth first recursively. */ // TODO: test private static class TransientTrieSetIterator<K> extends TrieSetIteratorWithFixedWidthStack<K> { final TransientTrieSet<K> transientTrieSet; K lastKey; TransientTrieSetIterator(TransientTrieSet<K> transientTrieSet) { super(transientTrieSet.rootNode); this.transientTrieSet = transientTrieSet; } @Override public K next() { lastKey = super.next(); return lastKey; } @Override public void remove() { transientTrieSet.__remove(lastKey); } } @Override public boolean equals(Object o) { return rootNode.equals(o); } @Override public int hashCode() { return hashCode; } @Override public String toString() { return rootNode.toString(); } @Override public ImmutableSet<K> freeze() { if (mutator.get() == null) { throw new IllegalStateException("Transient already frozen."); } mutator.set(null); return new TrieSet<K>(rootNode, hashCode, cachedSize); } } static final class Result<T1, T2, N extends AbstractNode<T1, T2>> { private final N result; private final T2 replacedValue; private final boolean isModified; public static <T1, T2, N extends AbstractNode<T1, T2>> Result<T1, T2, N> modified(N node) { return new Result<>(node, null, true); } public static <T1, T2, N extends AbstractNode<T1, T2>> Result<T1, T2, N> updated(N node, T2 replacedValue) { return new Result<>(node, replacedValue, true); } public static <T1, T2, N extends AbstractNode<T1, T2>> Result<T1, T2, N> unchanged(N node) { return new Result<>(node, null, false); } private Result(N node, T2 replacedValue, boolean isMutated) { this.result = node; this.replacedValue = replacedValue; this.isModified = isMutated; } public N getNode() { return result; } public boolean isModified() { return isModified; } public boolean hasReplacedValue() { return replacedValue != null; } public T2 getReplacedValue() { return replacedValue; } } abstract static class Optional<T> { private static final Optional EMPTY = new Optional() { @Override boolean isPresent() { return false; } @Override Object get() { return null; } }; @SuppressWarnings("unchecked") static <T> Optional<T> empty() { return EMPTY; } static <T> Optional<T> of(T value) { return new Value<T>(value); } abstract boolean isPresent(); abstract T get(); private static final class Value<T> extends Optional<T> { private final T value; private Value(T value) { this.value = value; } @Override boolean isPresent() { return true; } @Override T get() { return value; } } } protected static abstract class AbstractNode<K, V> { } protected static abstract class AbstractSetNode<K> extends AbstractNode<K, Void> { protected static final int BIT_PARTITION_SIZE = 5; protected static final int BIT_PARTITION_MASK = 0x1f; abstract boolean containsKey(Object key, int keyHash, int shift); abstract boolean containsKey(Object key, int keyHash, int shift, Comparator<Object> cmp); abstract Optional<K> findByKey(Object key, int keyHash, int shift); abstract Optional<K> findByKey(Object key, int keyHash, int shift, Comparator<Object> cmp); abstract Result<K, Void, ? extends AbstractSetNode<K>> updated( AtomicReference<Thread> mutator, K key, int keyHash, Void val, int shift); abstract Result<K, Void, ? extends AbstractSetNode<K>> updated( AtomicReference<Thread> mutator, K key, int keyHash, Void val, int shift, Comparator<Object> cmp); abstract Result<K, Void, ? extends AbstractSetNode<K>> removed( AtomicReference<Thread> mutator, K key, int keyHash, int shift); abstract Result<K, Void, ? extends AbstractSetNode<K>> removed( AtomicReference<Thread> mutator, K key, int keyHash, int shift, Comparator<Object> cmp); static final boolean isAllowedToEdit(AtomicReference<Thread> x, AtomicReference<Thread> y) { return x != null && y != null && (x == y || x.get() == y.get()); } abstract K getKey(int index); abstract AbstractSetNode<K> getNode(int index); abstract boolean hasNodes(); abstract Iterator<? extends AbstractSetNode<K>> nodeIterator(); abstract int nodeArity(); abstract boolean hasPayload(); abstract SupplierIterator<K, K> payloadIterator(); abstract int payloadArity(); /** * The arity of this trie node (i.e. number of values and nodes stored * on this level). * * @return sum of nodes and values stored within */ int arity() { return payloadArity() + nodeArity(); } int size() { final SupplierIterator<K, K> it = new TrieSetIteratorWithFixedWidthStack<>(this); int size = 0; while (it.hasNext()) { size += 1; it.next(); } return size; } } private static abstract class CompactSetNode<K> extends AbstractSetNode<K> { static final byte SIZE_EMPTY = 0b00; static final byte SIZE_ONE = 0b01; static final byte SIZE_MORE_THAN_ONE = 0b10; @Override abstract Result<K, Void, ? extends CompactSetNode<K>> updated( AtomicReference<Thread> mutator, K key, int keyHash, Void val, int shift); @Override abstract Result<K, Void, ? extends CompactSetNode<K>> updated(AtomicReference<Thread> mutator, K key, int keyHash, Void val, int shift, Comparator<Object> cmp); @Override abstract Result<K, Void, ? extends CompactSetNode<K>> removed(AtomicReference<Thread> mutator, K key, int hash, int shift); @Override abstract Result<K, Void, ? extends CompactSetNode<K>> removed(AtomicReference<Thread> mutator, K key, int hash, int shift, Comparator<Object> cmp); /** * Abstract predicate over a node's size. Value can be either * {@value #SIZE_EMPTY}, {@value #SIZE_ONE}, or * {@value #SIZE_MORE_THAN_ONE}. * * @return size predicate */ abstract byte sizePredicate(); /** * Returns the first key stored within this node. * * @return first key */ abstract K headKey(); boolean nodeInvariant() { boolean inv1 = (size() - payloadArity() >= 2 * (arity() - payloadArity())); boolean inv2 = (this.arity() == 0) ? sizePredicate() == SIZE_EMPTY : true; boolean inv3 = (this.arity() == 1 && payloadArity() == 1) ? sizePredicate() == SIZE_ONE : true; boolean inv4 = (this.arity() >= 2) ? sizePredicate() == SIZE_MORE_THAN_ONE : true; boolean inv5 = (this.nodeArity() >= 0) && (this.payloadArity() >= 0) && ((this.payloadArity() + this.nodeArity()) == this.arity()); return inv1 && inv2 && inv3 && inv4 && inv5; } @SuppressWarnings("unchecked") static final CompactSetNode EMPTY_INPLACE_INDEX_NODE = new Set0To0Node(null); static final <K> CompactSetNode<K> valNodeOf(AtomicReference<Thread> mutator, byte pos, CompactSetNode<K> node) { switch (pos) { case 0: return new SingletonNodeAtMask0Node<>(node); case 1: return new SingletonNodeAtMask1Node<>(node); case 2: return new SingletonNodeAtMask2Node<>(node); case 3: return new SingletonNodeAtMask3Node<>(node); case 4: return new SingletonNodeAtMask4Node<>(node); case 5: return new SingletonNodeAtMask5Node<>(node); case 6: return new SingletonNodeAtMask6Node<>(node); case 7: return new SingletonNodeAtMask7Node<>(node); case 8: return new SingletonNodeAtMask8Node<>(node); case 9: return new SingletonNodeAtMask9Node<>(node); case 10: return new SingletonNodeAtMask10Node<>(node); case 11: return new SingletonNodeAtMask11Node<>(node); case 12: return new SingletonNodeAtMask12Node<>(node); case 13: return new SingletonNodeAtMask13Node<>(node); case 14: return new SingletonNodeAtMask14Node<>(node); case 15: return new SingletonNodeAtMask15Node<>(node); case 16: return new SingletonNodeAtMask16Node<>(node); case 17: return new SingletonNodeAtMask17Node<>(node); case 18: return new SingletonNodeAtMask18Node<>(node); case 19: return new SingletonNodeAtMask19Node<>(node); case 20: return new SingletonNodeAtMask20Node<>(node); case 21: return new SingletonNodeAtMask21Node<>(node); case 22: return new SingletonNodeAtMask22Node<>(node); case 23: return new SingletonNodeAtMask23Node<>(node); case 24: return new SingletonNodeAtMask24Node<>(node); case 25: return new SingletonNodeAtMask25Node<>(node); case 26: return new SingletonNodeAtMask26Node<>(node); case 27: return new SingletonNodeAtMask27Node<>(node); case 28: return new SingletonNodeAtMask28Node<>(node); case 29: return new SingletonNodeAtMask29Node<>(node); case 30: return new SingletonNodeAtMask30Node<>(node); case 31: return new SingletonNodeAtMask31Node<>(node); default: throw new IllegalStateException("Position out of range."); } } @SuppressWarnings("unchecked") static final <K> CompactSetNode<K> valNodeOf(AtomicReference<Thread> mutator) { return EMPTY_INPLACE_INDEX_NODE; } // manually added static final <K> CompactSetNode<K> valNodeOf(AtomicReference<Thread> mutator, byte pos1, K key1, byte npos1, CompactSetNode<K> node1, byte npos2, CompactSetNode<K> node2, byte npos3, CompactSetNode<K> node3, byte npos4, CompactSetNode<K> node4) { final int bitmap = (1 << pos1) | (1 << npos1) | (1 << npos2) | (1 << npos3) | (1 << npos4); final int valmap = (1 << pos1); return new BitmapIndexedSetNode<>(mutator, bitmap, valmap, new Object[] { key1, node1, node2, node3, node4 }, (byte) 1); } // manually added static final <K> CompactSetNode<K> valNodeOf(AtomicReference<Thread> mutator, byte pos1, K key1, byte pos2, K key2, byte pos3, K key3, byte npos1, CompactSetNode<K> node1, byte npos2, CompactSetNode<K> node2) { final int bitmap = (1 << pos1) | (1 << pos2) | (1 << pos3) | (1 << npos1) | (1 << npos2); final int valmap = (1 << pos1) | (1 << pos2) | (1 << pos3); return new BitmapIndexedSetNode<>(mutator, bitmap, valmap, new Object[] { key1, key2, key3, node1, node2 }, (byte) 3); } // manually added static final <K> CompactSetNode<K> valNodeOf(AtomicReference<Thread> mutator, byte pos1, K key1, byte pos2, K key2, byte npos1, CompactSetNode<K> node1, byte npos2, CompactSetNode<K> node2, byte npos3, CompactSetNode<K> node3) { final int bitmap = (1 << pos1) | (1 << pos2) | (1 << npos1) | (1 << npos2) | (1 << npos3); final int valmap = (1 << pos1) | (1 << pos2); return new BitmapIndexedSetNode<>(mutator, bitmap, valmap, new Object[] { key1, key2, node1, node2, node3 }, (byte) 2); } // manually added static final <K> CompactSetNode<K> valNodeOf(AtomicReference<Thread> mutator, byte pos1, K key1, byte pos2, K key2, byte pos3, K key3, byte pos4, K key4, byte npos1, CompactSetNode<K> node1) { final int bitmap = (1 << pos1) | (1 << pos2) | (1 << pos3) | (1 << pos4) | (1 << npos1); final int valmap = (1 << pos1) | (1 << pos2) | (1 << pos3) | (1 << pos4); return new BitmapIndexedSetNode<>(mutator, bitmap, valmap, new Object[] { key1, key2, key3, key4, node1 }, (byte) 4); } // manually added static final <K> CompactSetNode<K> valNodeOf(AtomicReference<Thread> mutator, byte pos1, K key1, byte pos2, K key2, byte pos3, K key3, byte pos4, K key4, byte pos5, K key5) { final int valmap = (1 << pos1) | (1 << pos2) | (1 << pos3) | (1 << pos4) | (1 << pos5); return new BitmapIndexedSetNode<>(mutator, valmap, valmap, new Object[] { key1, key2, key3, key4, key5 }, (byte) 5); } static final <K> CompactSetNode<K> valNodeOf(AtomicReference<Thread> mutator, byte npos1, CompactSetNode<K> node1, byte npos2, CompactSetNode<K> node2) { return new Set0To2Node<>(mutator, npos1, node1, npos2, node2); } static final <K> CompactSetNode<K> valNodeOf(AtomicReference<Thread> mutator, byte npos1, CompactSetNode<K> node1, byte npos2, CompactSetNode<K> node2, byte npos3, CompactSetNode<K> node3) { return new Set0To3Node<>(mutator, npos1, node1, npos2, node2, npos3, node3); } static final <K> CompactSetNode<K> valNodeOf(AtomicReference<Thread> mutator, byte npos1, CompactSetNode<K> node1, byte npos2, CompactSetNode<K> node2, byte npos3, CompactSetNode<K> node3, byte npos4, CompactSetNode<K> node4) { return new Set0To4Node<>(mutator, npos1, node1, npos2, node2, npos3, node3, npos4, node4); } static final <K> CompactSetNode<K> valNodeOf(AtomicReference<Thread> mutator, byte pos1, K key1) { return new Set1To0Node<>(mutator, pos1, key1); } static final <K> CompactSetNode<K> valNodeOf(AtomicReference<Thread> mutator, byte pos1, K key1, byte npos1, CompactSetNode<K> node1) { return new Set1To1Node<>(mutator, pos1, key1, npos1, node1); } static final <K> CompactSetNode<K> valNodeOf(AtomicReference<Thread> mutator, byte pos1, K key1, byte npos1, CompactSetNode<K> node1, byte npos2, CompactSetNode<K> node2) { return new Set1To2Node<>(mutator, pos1, key1, npos1, node1, npos2, node2); } static final <K> CompactSetNode<K> valNodeOf(AtomicReference<Thread> mutator, byte pos1, K key1, byte npos1, CompactSetNode<K> node1, byte npos2, CompactSetNode<K> node2, byte npos3, CompactSetNode<K> node3) { return new Set1To3Node<>(mutator, pos1, key1, npos1, node1, npos2, node2, npos3, node3); } static final <K> CompactSetNode<K> valNodeOf(AtomicReference<Thread> mutator, byte pos1, K key1, byte pos2, K key2) { return new Set2To0Node<>(mutator, pos1, key1, pos2, key2); } static final <K> CompactSetNode<K> valNodeOf(AtomicReference<Thread> mutator, byte pos1, K key1, byte pos2, K key2, byte npos1, CompactSetNode<K> node1) { return new Set2To1Node<>(mutator, pos1, key1, pos2, key2, npos1, node1); } static final <K> CompactSetNode<K> valNodeOf(AtomicReference<Thread> mutator, byte pos1, K key1, byte pos2, K key2, byte npos1, CompactSetNode<K> node1, byte npos2, CompactSetNode<K> node2) { return new Set2To2Node<>(mutator, pos1, key1, pos2, key2, npos1, node1, npos2, node2); } static final <K> CompactSetNode<K> valNodeOf(AtomicReference<Thread> mutator, byte pos1, K key1, byte pos2, K key2, byte pos3, K key3) { return new Set3To0Node<>(mutator, pos1, key1, pos2, key2, pos3, key3); } static final <K> CompactSetNode<K> valNodeOf(AtomicReference<Thread> mutator, byte pos1, K key1, byte pos2, K key2, byte pos3, K key3, byte npos1, CompactSetNode<K> node1) { return new Set3To1Node<>(mutator, pos1, key1, pos2, key2, pos3, key3, npos1, node1); } static final <K> CompactSetNode<K> valNodeOf(AtomicReference<Thread> mutator, byte pos1, K key1, byte pos2, K key2, byte pos3, K key3, byte pos4, K key4) { return new Set4To0Node<>(mutator, pos1, key1, pos2, key2, pos3, key3, pos4, key4); } static final <K> CompactSetNode<K> valNodeOf(AtomicReference<Thread> mutator, int bitmap, int valmap, Object[] nodes, byte valueArity) { return new BitmapIndexedSetNode<>(mutator, bitmap, valmap, nodes, valueArity); } @SuppressWarnings("unchecked") static final <K> CompactSetNode<K> mergeNodes(K key0, int keyHash0, K key1, int keyHash1, int shift) { assert key0.equals(key1) == false; if (keyHash0 == keyHash1) { return new HashCollisionNode<>(keyHash0, (K[]) new Object[] { key0, key1 }); } final int mask0 = (keyHash0 >>> shift) & BIT_PARTITION_MASK; final int mask1 = (keyHash1 >>> shift) & BIT_PARTITION_MASK; if (mask0 != mask1) { // both nodes fit on same level final Object[] nodes = new Object[4]; if (mask0 < mask1) { nodes[0] = key0; nodes[1] = key1; return valNodeOf(null, (byte) mask0, key0, (byte) mask1, key1); } else { nodes[0] = key1; nodes[1] = key0; return valNodeOf(null, (byte) mask1, key1, (byte) mask0, key0); } } else { // values fit on next level final CompactSetNode<K> node = mergeNodes(key0, keyHash0, key1, keyHash1, shift + BIT_PARTITION_SIZE); return valNodeOf(null, (byte) mask0, node); } } static final <K> CompactSetNode<K> mergeNodes(CompactSetNode<K> node0, int keyHash0, K key1, int keyHash1, int shift) { final int mask0 = (keyHash0 >>> shift) & BIT_PARTITION_MASK; final int mask1 = (keyHash1 >>> shift) & BIT_PARTITION_MASK; if (mask0 != mask1) { // both nodes fit on same level final Object[] nodes = new Object[2]; // store values before node nodes[0] = key1; nodes[1] = node0; return valNodeOf(null, (byte) mask1, key1, (byte) mask0, node0); } else { // values fit on next level final CompactSetNode<K> node = mergeNodes(node0, keyHash0, key1, keyHash1, shift + BIT_PARTITION_SIZE); return valNodeOf(null, (byte) mask0, node); } } } private static final class BitmapIndexedSetNode<K> extends CompactSetNode<K> { private AtomicReference<Thread> mutator; private Object[] nodes; final private int bitmap; final private int valmap; final private byte payloadArity; BitmapIndexedSetNode(AtomicReference<Thread> mutator, int bitmap, int valmap, Object[] nodes, byte payloadArity) { assert (Integer.bitCount(valmap) + Integer.bitCount(bitmap ^ valmap) == nodes.length); this.mutator = mutator; this.nodes = nodes; this.bitmap = bitmap; this.valmap = valmap; this.payloadArity = payloadArity; assert (payloadArity == Integer.bitCount(valmap)); assert (payloadArity() >= 2 || nodeArity() >= 1); // SIZE_MORE_THAN_ONE // for (int i = 0; i < valueArity; i++) // assert ((nodes[i] instanceof CompactSetNode) == false); // for (int i = valueArity; i < nodes.length; i++) // assert ((nodes[i] instanceof CompactSetNode) == true); // assert invariant assert nodeInvariant(); } final int bitIndex(int bitpos) { return payloadArity + Integer.bitCount((bitmap ^ valmap) & (bitpos - 1)); } final int valIndex(int bitpos) { return Integer.bitCount(valmap & (bitpos - 1)); } @SuppressWarnings("unchecked") @Override boolean containsKey(Object key, int hash, int shift) { final int mask = (hash >>> shift) & BIT_PARTITION_MASK; final int bitpos = (1 << mask); if ((valmap & bitpos) != 0) { return nodes[valIndex(bitpos)].equals(key); } if ((bitmap & bitpos) != 0) { return ((AbstractSetNode<K>) nodes[bitIndex(bitpos)]).containsKey(key, hash, shift + BIT_PARTITION_SIZE); } return false; } @SuppressWarnings("unchecked") @Override boolean containsKey(Object key, int hash, int shift, Comparator<Object> cmp) { final int mask = (hash >>> shift) & BIT_PARTITION_MASK; final int bitpos = (1 << mask); if ((valmap & bitpos) != 0) { return cmp.compare(nodes[valIndex(bitpos)], key) == 0; } if ((bitmap & bitpos) != 0) { return ((AbstractSetNode<K>) nodes[bitIndex(bitpos)]).containsKey(key, hash, shift + BIT_PARTITION_SIZE, cmp); } return false; } @Override @SuppressWarnings("unchecked") Optional<K> findByKey(Object key, int keyHash, int shift) { final int mask = (keyHash >>> shift) & BIT_PARTITION_MASK; final int bitpos = (1 << mask); if ((valmap & bitpos) != 0) { // inplace value final int valIndex = valIndex(bitpos); if (nodes[valIndex].equals(key)) { final K _key = (K) nodes[valIndex]; return Optional.of(_key); } return Optional.empty(); } if ((bitmap & bitpos) != 0) { // node (not value) final AbstractSetNode<K> subNode = ((AbstractSetNode<K>) nodes[bitIndex(bitpos)]); return subNode.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE); } return Optional.empty(); } @Override @SuppressWarnings("unchecked") Optional<K> findByKey(Object key, int keyHash, int shift, Comparator<Object> cmp) { final int mask = (keyHash >>> shift) & BIT_PARTITION_MASK; final int bitpos = (1 << mask); if ((valmap & bitpos) != 0) { // inplace value final int valIndex = valIndex(bitpos); if (cmp.compare(nodes[valIndex], key) == 0) { final K _key = (K) nodes[valIndex]; return Optional.of(_key); } return Optional.empty(); } if ((bitmap & bitpos) != 0) { // node (not value) final AbstractSetNode<K> subNode = ((AbstractSetNode<K>) nodes[bitIndex(bitpos)]); return subNode.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE, cmp); } return Optional.empty(); } @SuppressWarnings("unchecked") @Override Result<K, Void, ? extends CompactSetNode<K>> updated(AtomicReference<Thread> mutator, K key, int keyHash, Void val, int shift) { final int mask = (keyHash >>> shift) & BIT_PARTITION_MASK; final int bitpos = (1 << mask); if ((valmap & bitpos) != 0) { // inplace value final int valIndex = valIndex(bitpos); final Object currentKey = nodes[valIndex]; if (currentKey.equals(key)) { return Result.unchanged(this); } else { final CompactSetNode<K> nodeNew = mergeNodes((K) nodes[valIndex], nodes[valIndex].hashCode(), key, keyHash, shift + BIT_PARTITION_SIZE); final int offset = (payloadArity - 1); final int index = Integer.bitCount(((bitmap | bitpos) ^ (valmap & ~bitpos)) & (bitpos - 1)); final Object[] editableNodes = copyAndMoveToBack(this.nodes, valIndex, offset + index, nodeNew); final CompactSetNode<K> thisNew = CompactSetNode.<K> valNodeOf(mutator, bitmap | bitpos, valmap & ~bitpos, editableNodes, (byte) (payloadArity - 1)); return Result.modified(thisNew); } } else if ((bitmap & bitpos) != 0) { // node (not value) final int bitIndex = bitIndex(bitpos); final CompactSetNode<K> subNode = (CompactSetNode<K>) nodes[bitIndex]; final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = subNode.updated( mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (!nestedResult.isModified()) { return Result.unchanged(this); } final CompactSetNode<K> thisNew; // modify current node (set replacement node) if (isAllowedToEdit(this.mutator, mutator)) { // no copying if already editable this.nodes[bitIndex] = nestedResult.getNode(); thisNew = this; } else { final Object[] editableNodes = copyAndSet(this.nodes, bitIndex, nestedResult.getNode()); thisNew = CompactSetNode.<K> valNodeOf(mutator, bitmap, valmap, editableNodes, payloadArity); } return Result.modified(thisNew); } else { // no value final Object[] editableNodes = copyAndInsert(this.nodes, valIndex(bitpos), key); final CompactSetNode<K> thisNew = CompactSetNode .<K> valNodeOf(mutator, bitmap | bitpos, valmap | bitpos, editableNodes, (byte) (payloadArity + 1)); return Result.modified(thisNew); } } @SuppressWarnings("unchecked") @Override Result<K, Void, ? extends CompactSetNode<K>> updated(AtomicReference<Thread> mutator, K key, int keyHash, Void val, int shift, Comparator<Object> cmp) { final int mask = (keyHash >>> shift) & BIT_PARTITION_MASK; final int bitpos = (1 << mask); if ((valmap & bitpos) != 0) { // inplace value final int valIndex = valIndex(bitpos); final Object currentKey = nodes[valIndex]; if (cmp.compare(currentKey, key) == 0) { return Result.unchanged(this); } else { final CompactSetNode<K> nodeNew = mergeNodes((K) nodes[valIndex], nodes[valIndex].hashCode(), key, keyHash, shift + BIT_PARTITION_SIZE); final int offset = (payloadArity - 1); final int index = Integer.bitCount(((bitmap | bitpos) ^ (valmap & ~bitpos)) & (bitpos - 1)); final Object[] editableNodes = copyAndMoveToBack(this.nodes, valIndex, offset + index, nodeNew); final CompactSetNode<K> thisNew = CompactSetNode.<K> valNodeOf(mutator, bitmap | bitpos, valmap & ~bitpos, editableNodes, (byte) (payloadArity - 1)); return Result.modified(thisNew); } } else if ((bitmap & bitpos) != 0) { // node (not value) final int bitIndex = bitIndex(bitpos); final CompactSetNode<K> subNode = (CompactSetNode<K>) nodes[bitIndex]; final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = subNode.updated( mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE, cmp); if (!nestedResult.isModified()) { return Result.unchanged(this); } final CompactSetNode<K> thisNew; // modify current node (set replacement node) if (isAllowedToEdit(this.mutator, mutator)) { // no copying if already editable this.nodes[bitIndex] = nestedResult.getNode(); thisNew = this; } else { final Object[] editableNodes = copyAndSet(this.nodes, bitIndex, nestedResult.getNode()); thisNew = CompactSetNode.<K> valNodeOf(mutator, bitmap, valmap, editableNodes, payloadArity); } return Result.modified(thisNew); } else { // no value final Object[] editableNodes = copyAndInsert(this.nodes, valIndex(bitpos), key); final CompactSetNode<K> thisNew = CompactSetNode .<K> valNodeOf(mutator, bitmap | bitpos, valmap | bitpos, editableNodes, (byte) (payloadArity + 1)); return Result.modified(thisNew); } } @SuppressWarnings("unchecked") @Override Result<K, Void, ? extends CompactSetNode<K>> removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift) { final int mask = (keyHash >>> shift) & BIT_PARTITION_MASK; final int bitpos = (1 << mask); if ((valmap & bitpos) != 0) { // inplace value final int valIndex = valIndex(bitpos); if (nodes[valIndex].equals(key)) { if (this.arity() == 5) { return Result.modified(removeInplaceValueAndConvertSpecializedNode(mask, bitpos)); } else { final Object[] editableNodes = copyAndRemove(this.nodes, valIndex); final CompactSetNode<K> thisNew = CompactSetNode.<K> valNodeOf(mutator, this.bitmap & ~bitpos, this.valmap & ~bitpos, editableNodes, (byte) (payloadArity - 1)); return Result.modified(thisNew); } } else { return Result.unchanged(this); } } else if ((bitmap & bitpos) != 0) { // node (not value) final int bitIndex = bitIndex(bitpos); final CompactSetNode<K> subNode = (CompactSetNode<K>) nodes[bitIndex]; final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = subNode.removed( mutator, key, keyHash, shift + BIT_PARTITION_SIZE); if (!nestedResult.isModified()) { return Result.unchanged(this); } final CompactSetNode<K> subNodeNew = nestedResult.getNode(); switch (subNodeNew.sizePredicate()) { case 0: { // remove node if (this.arity() == 5) { return Result.modified(removeSubNodeAndConvertSpecializedNode(mask, bitpos)); } else { final Object[] editableNodes = copyAndRemove(this.nodes, bitIndex); final CompactSetNode<K> thisNew = CompactSetNode.<K> valNodeOf(mutator, bitmap & ~bitpos, valmap, editableNodes, payloadArity); return Result.modified(thisNew); } } case 1: { // inline value (move to front) final int valIndexNew = Integer.bitCount((valmap | bitpos) & (bitpos - 1)); final Object[] editableNodes = copyAndMoveToFront(this.nodes, bitIndex, valIndexNew, subNodeNew.headKey()); final CompactSetNode<K> thisNew = CompactSetNode.<K> valNodeOf(mutator, bitmap, valmap | bitpos, editableNodes, (byte) (payloadArity + 1)); return Result.modified(thisNew); } default: { // modify current node (set replacement node) if (isAllowedToEdit(this.mutator, mutator)) { // no copying if already editable this.nodes[bitIndex] = subNodeNew; return Result.modified(this); } else { final Object[] editableNodes = copyAndSet(this.nodes, bitIndex, subNodeNew); final CompactSetNode<K> thisNew = CompactSetNode.<K> valNodeOf(mutator, bitmap, valmap, editableNodes, payloadArity); return Result.modified(thisNew); } } } } return Result.unchanged(this); } @SuppressWarnings("unchecked") @Override Result<K, Void, ? extends CompactSetNode<K>> removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift, Comparator<Object> cmp) { final int mask = (keyHash >>> shift) & BIT_PARTITION_MASK; final int bitpos = (1 << mask); if ((valmap & bitpos) != 0) { // inplace value final int valIndex = valIndex(bitpos); if (cmp.compare(nodes[valIndex], key) == 0) { if (this.arity() == 5) { return Result.modified(removeInplaceValueAndConvertSpecializedNode(mask, bitpos)); } else { final Object[] editableNodes = copyAndRemove(this.nodes, valIndex); final CompactSetNode<K> thisNew = CompactSetNode.<K> valNodeOf(mutator, this.bitmap & ~bitpos, this.valmap & ~bitpos, editableNodes, (byte) (payloadArity - 1)); return Result.modified(thisNew); } } else { return Result.unchanged(this); } } else if ((bitmap & bitpos) != 0) { // node (not value) final int bitIndex = bitIndex(bitpos); final CompactSetNode<K> subNode = (CompactSetNode<K>) nodes[bitIndex]; final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = subNode.removed( mutator, key, keyHash, shift + BIT_PARTITION_SIZE, cmp); if (!nestedResult.isModified()) { return Result.unchanged(this); } final CompactSetNode<K> subNodeNew = nestedResult.getNode(); switch (subNodeNew.sizePredicate()) { case 0: { // remove node if (this.arity() == 5) { return Result.modified(removeSubNodeAndConvertSpecializedNode(mask, bitpos)); } else { final Object[] editableNodes = copyAndRemove(this.nodes, bitIndex); final CompactSetNode<K> thisNew = CompactSetNode.<K> valNodeOf(mutator, bitmap & ~bitpos, valmap, editableNodes, payloadArity); return Result.modified(thisNew); } } case 1: { // inline value (move to front) final int valIndexNew = Integer.bitCount((valmap | bitpos) & (bitpos - 1)); final Object[] editableNodes = copyAndMoveToFront(this.nodes, bitIndex, valIndexNew, subNodeNew.headKey()); final CompactSetNode<K> thisNew = CompactSetNode.<K> valNodeOf(mutator, bitmap, valmap | bitpos, editableNodes, (byte) (payloadArity + 1)); return Result.modified(thisNew); } default: { // modify current node (set replacement node) if (isAllowedToEdit(this.mutator, mutator)) { // no copying if already editable this.nodes[bitIndex] = subNodeNew; return Result.modified(this); } else { final Object[] editableNodes = copyAndSet(this.nodes, bitIndex, subNodeNew); final CompactSetNode<K> thisNew = CompactSetNode.<K> valNodeOf(mutator, bitmap, valmap, editableNodes, payloadArity); return Result.modified(thisNew); } } } } return Result.unchanged(this); } @SuppressWarnings("unchecked") private CompactSetNode<K> removeInplaceValueAndConvertSpecializedNode(final int mask, final int bitpos) { switch (this.payloadArity) { // 0 <= payloadArity <= 5 case 1: { final int nmap = ((bitmap & ~bitpos) ^ (valmap & ~bitpos)); final byte npos1 = recoverMask(nmap, (byte) 1); final byte npos2 = recoverMask(nmap, (byte) 2); final byte npos3 = recoverMask(nmap, (byte) 3); final byte npos4 = recoverMask(nmap, (byte) 4); final CompactSetNode<K> node1 = (CompactSetNode<K>) nodes[payloadArity + 0]; final CompactSetNode<K> node2 = (CompactSetNode<K>) nodes[payloadArity + 1]; final CompactSetNode<K> node3 = (CompactSetNode<K>) nodes[payloadArity + 2]; final CompactSetNode<K> node4 = (CompactSetNode<K>) nodes[payloadArity + 3]; return valNodeOf(mutator, npos1, node1, npos2, node2, npos3, node3, npos4, node4); } case 2: { final int map = (valmap & ~bitpos); final byte pos1 = recoverMask(map, (byte) 1); final K key1; final int nmap = ((bitmap & ~bitpos) ^ (valmap & ~bitpos)); final byte npos1 = recoverMask(nmap, (byte) 1); final byte npos2 = recoverMask(nmap, (byte) 2); final byte npos3 = recoverMask(nmap, (byte) 3); final CompactSetNode<K> node1 = (CompactSetNode<K>) nodes[payloadArity + 0]; final CompactSetNode<K> node2 = (CompactSetNode<K>) nodes[payloadArity + 1]; final CompactSetNode<K> node3 = (CompactSetNode<K>) nodes[payloadArity + 2]; if (mask < pos1) { key1 = (K) nodes[1]; } else { key1 = (K) nodes[0]; } return valNodeOf(mutator, pos1, key1, npos1, node1, npos2, node2, npos3, node3); } case 3: { final int map = (valmap & ~bitpos); final byte pos1 = recoverMask(map, (byte) 1); final byte pos2 = recoverMask(map, (byte) 2); final K key1; final K key2; final int nmap = ((bitmap & ~bitpos) ^ (valmap & ~bitpos)); final byte npos1 = recoverMask(nmap, (byte) 1); final byte npos2 = recoverMask(nmap, (byte) 2); final CompactSetNode<K> node1 = (CompactSetNode<K>) nodes[payloadArity + 0]; final CompactSetNode<K> node2 = (CompactSetNode<K>) nodes[payloadArity + 1]; if (mask < pos1) { key1 = (K) nodes[1]; key2 = (K) nodes[2]; } else if (mask < pos2) { key1 = (K) nodes[0]; key2 = (K) nodes[2]; } else { key1 = (K) nodes[0]; key2 = (K) nodes[1]; } return valNodeOf(mutator, pos1, key1, pos2, key2, npos1, node1, npos2, node2); } case 4: { final int map = (valmap & ~bitpos); final byte pos1 = recoverMask(map, (byte) 1); final byte pos2 = recoverMask(map, (byte) 2); final byte pos3 = recoverMask(map, (byte) 3); final K key1; final K key2; final K key3; final int nmap = ((bitmap & ~bitpos) ^ (valmap & ~bitpos)); final byte npos1 = recoverMask(nmap, (byte) 1); final CompactSetNode<K> node1 = (CompactSetNode<K>) nodes[payloadArity + 0]; if (mask < pos1) { key1 = (K) nodes[1]; key2 = (K) nodes[2]; key3 = (K) nodes[3]; } else if (mask < pos2) { key1 = (K) nodes[0]; key2 = (K) nodes[2]; key3 = (K) nodes[3]; } else if (mask < pos3) { key1 = (K) nodes[0]; key2 = (K) nodes[1]; key3 = (K) nodes[3]; } else { key1 = (K) nodes[0]; key2 = (K) nodes[1]; key3 = (K) nodes[2]; } return valNodeOf(mutator, pos1, key1, pos2, key2, pos3, key3, npos1, node1); } case 5: { final int map = (valmap & ~bitpos); final byte pos1 = recoverMask(map, (byte) 1); final byte pos2 = recoverMask(map, (byte) 2); final byte pos3 = recoverMask(map, (byte) 3); final byte pos4 = recoverMask(map, (byte) 4); final K key1; final K key2; final K key3; final K key4; if (mask < pos1) { key1 = (K) nodes[1]; key2 = (K) nodes[2]; key3 = (K) nodes[3]; key4 = (K) nodes[4]; } else if (mask < pos2) { key1 = (K) nodes[0]; key2 = (K) nodes[2]; key3 = (K) nodes[3]; key4 = (K) nodes[4]; } else if (mask < pos3) { key1 = (K) nodes[0]; key2 = (K) nodes[1]; key3 = (K) nodes[3]; key4 = (K) nodes[4]; } else if (mask < pos4) { key1 = (K) nodes[0]; key2 = (K) nodes[1]; key3 = (K) nodes[2]; key4 = (K) nodes[4]; } else { key1 = (K) nodes[0]; key2 = (K) nodes[1]; key3 = (K) nodes[2]; key4 = (K) nodes[3]; } return valNodeOf(mutator, pos1, key1, pos2, key2, pos3, key3, pos4, key4); } default: { throw new IllegalStateException(); } } } @SuppressWarnings("unchecked") private CompactSetNode<K> removeSubNodeAndConvertSpecializedNode(final int mask, final int bitpos) { switch (this.nodeArity()) { case 1: { final int map = valmap; final byte pos1 = recoverMask(map, (byte) 1); final byte pos2 = recoverMask(map, (byte) 2); final byte pos3 = recoverMask(map, (byte) 3); final byte pos4 = recoverMask(map, (byte) 4); final K key1 = (K) nodes[0]; final K key2 = (K) nodes[1]; final K key3 = (K) nodes[2]; final K key4 = (K) nodes[3]; return valNodeOf(mutator, pos1, key1, pos2, key2, pos3, key3, pos4, key4); } case 2: { final int map = valmap; final byte pos1 = recoverMask(map, (byte) 1); final byte pos2 = recoverMask(map, (byte) 2); final byte pos3 = recoverMask(map, (byte) 3); final K key1 = (K) nodes[0]; final K key2 = (K) nodes[1]; final K key3 = (K) nodes[2]; final int nmap = ((bitmap & ~bitpos) ^ valmap); final byte npos1 = recoverMask(nmap, (byte) 1); final CompactSetNode<K> node1; if (mask < npos1) { node1 = (CompactSetNode<K>) nodes[payloadArity + 1]; } else { node1 = (CompactSetNode<K>) nodes[payloadArity + 0]; } return valNodeOf(mutator, pos1, key1, pos2, key2, pos3, key3, npos1, node1); } case 3: { final int map = valmap; final byte pos1 = recoverMask(map, (byte) 1); final byte pos2 = recoverMask(map, (byte) 2); final K key1 = (K) nodes[0]; final K key2 = (K) nodes[1]; final int nmap = ((bitmap & ~bitpos) ^ valmap); final byte npos1 = recoverMask(nmap, (byte) 1); final byte npos2 = recoverMask(nmap, (byte) 2); final CompactSetNode<K> node1; final CompactSetNode<K> node2; if (mask < npos1) { node1 = (CompactSetNode<K>) nodes[payloadArity + 1]; node2 = (CompactSetNode<K>) nodes[payloadArity + 2]; } else if (mask < npos2) { node1 = (CompactSetNode<K>) nodes[payloadArity + 0]; node2 = (CompactSetNode<K>) nodes[payloadArity + 2]; } else { node1 = (CompactSetNode<K>) nodes[payloadArity + 0]; node2 = (CompactSetNode<K>) nodes[payloadArity + 1]; } return valNodeOf(mutator, pos1, key1, pos2, key2, npos1, node1, npos2, node2); } case 4: { final int map = valmap; final byte pos1 = recoverMask(map, (byte) 1); final K key1 = (K) nodes[0]; final int nmap = ((bitmap & ~bitpos) ^ valmap); final byte npos1 = recoverMask(nmap, (byte) 1); final byte npos2 = recoverMask(nmap, (byte) 2); final byte npos3 = recoverMask(nmap, (byte) 3); final CompactSetNode<K> node1; final CompactSetNode<K> node2; final CompactSetNode<K> node3; if (mask < npos1) { node1 = (CompactSetNode<K>) nodes[payloadArity + 1]; node2 = (CompactSetNode<K>) nodes[payloadArity + 2]; node3 = (CompactSetNode<K>) nodes[payloadArity + 3]; } else if (mask < npos2) { node1 = (CompactSetNode<K>) nodes[payloadArity + 0]; node2 = (CompactSetNode<K>) nodes[payloadArity + 2]; node3 = (CompactSetNode<K>) nodes[payloadArity + 3]; } else if (mask < npos3) { node1 = (CompactSetNode<K>) nodes[payloadArity + 0]; node2 = (CompactSetNode<K>) nodes[payloadArity + 1]; node3 = (CompactSetNode<K>) nodes[payloadArity + 3]; } else { node1 = (CompactSetNode<K>) nodes[payloadArity + 0]; node2 = (CompactSetNode<K>) nodes[payloadArity + 1]; node3 = (CompactSetNode<K>) nodes[payloadArity + 2]; } return valNodeOf(mutator, pos1, key1, npos1, node1, npos2, node2, npos3, node3); } case 5: { final int nmap = ((bitmap & ~bitpos) ^ valmap); final byte npos1 = recoverMask(nmap, (byte) 1); final byte npos2 = recoverMask(nmap, (byte) 2); final byte npos3 = recoverMask(nmap, (byte) 3); final byte npos4 = recoverMask(nmap, (byte) 4); final CompactSetNode<K> node1; final CompactSetNode<K> node2; final CompactSetNode<K> node3; final CompactSetNode<K> node4; if (mask < npos1) { node1 = (CompactSetNode<K>) nodes[payloadArity + 1]; node2 = (CompactSetNode<K>) nodes[payloadArity + 2]; node3 = (CompactSetNode<K>) nodes[payloadArity + 3]; node4 = (CompactSetNode<K>) nodes[payloadArity + 4]; } else if (mask < npos2) { node1 = (CompactSetNode<K>) nodes[payloadArity + 0]; node2 = (CompactSetNode<K>) nodes[payloadArity + 2]; node3 = (CompactSetNode<K>) nodes[payloadArity + 3]; node4 = (CompactSetNode<K>) nodes[payloadArity + 4]; } else if (mask < npos3) { node1 = (CompactSetNode<K>) nodes[payloadArity + 0]; node2 = (CompactSetNode<K>) nodes[payloadArity + 1]; node3 = (CompactSetNode<K>) nodes[payloadArity + 3]; node4 = (CompactSetNode<K>) nodes[payloadArity + 4]; } else if (mask < npos4) { node1 = (CompactSetNode<K>) nodes[payloadArity + 0]; node2 = (CompactSetNode<K>) nodes[payloadArity + 1]; node3 = (CompactSetNode<K>) nodes[payloadArity + 2]; node4 = (CompactSetNode<K>) nodes[payloadArity + 4]; } else { node1 = (CompactSetNode<K>) nodes[payloadArity + 0]; node2 = (CompactSetNode<K>) nodes[payloadArity + 1]; node3 = (CompactSetNode<K>) nodes[payloadArity + 2]; node4 = (CompactSetNode<K>) nodes[payloadArity + 3]; } return valNodeOf(mutator, npos1, node1, npos2, node2, npos3, node3, npos4, node4); } default: { throw new IllegalStateException(); } } } // returns 0 <= mask <= 31 static byte recoverMask(int map, byte i_th) { assert 1 <= i_th && i_th <= 32; byte cnt1 = 0; byte mask = 0; while (mask < 32) { if ((map & 0x01) == 0x01) { cnt1 += 1; if (cnt1 == i_th) { return mask; } } map = map >> 1; mask += 1; } assert cnt1 != i_th; throw new RuntimeException("Called with invalid arguments."); } @SuppressWarnings("unchecked") @Override K getKey(int index) { return (K) nodes[index]; } @SuppressWarnings("unchecked") @Override public AbstractSetNode<K> getNode(int index) { final int offset = payloadArity; return (AbstractSetNode<K>) nodes[offset + index]; } @Override SupplierIterator<K, K> payloadIterator() { return ArrayKeyValueIterator.of(nodes, 0, payloadArity); } @SuppressWarnings("unchecked") @Override Iterator<AbstractSetNode<K>> nodeIterator() { final int offset = payloadArity; for (int i = offset; i < nodes.length - offset; i++) { assert ((nodes[i] instanceof AbstractSetNode) == true); } return (Iterator) ArrayIterator.of(nodes, offset, nodes.length - offset); } @SuppressWarnings("unchecked") @Override K headKey() { assert hasPayload(); return (K) nodes[0]; } @Override boolean hasPayload() { return payloadArity != 0; } @Override int payloadArity() { return payloadArity; } @Override boolean hasNodes() { return payloadArity != nodes.length; } @Override int nodeArity() { return nodes.length - payloadArity; } @Override public int hashCode() { final int prime = 31; int result = 0; result = prime * result + bitmap; result = prime * result + valmap; result = prime * result + Arrays.hashCode(nodes); return result; } @Override public boolean equals(Object other) { if (null == other) { return false; } if (this == other) { return true; } if (getClass() != other.getClass()) { return false; } BitmapIndexedSetNode<?> that = (BitmapIndexedSetNode<?>) other; if (bitmap != that.bitmap) { return false; } if (valmap != that.valmap) { return false; } if (!Arrays.equals(nodes, that.nodes)) { return false; } return true; } @Override public String toString() { return Arrays.toString(nodes); } @Override byte sizePredicate() { return SIZE_MORE_THAN_ONE; } } // TODO: replace by immutable cons list private static final class HashCollisionNode<K> extends CompactSetNode<K> { private final K[] keys; private final int hash; HashCollisionNode(int hash, K[] keys) { this.keys = keys; this.hash = hash; assert payloadArity() >= 2; } @Override SupplierIterator<K, K> payloadIterator() { return ArrayKeyValueIterator.of(keys); } @Override public String toString() { return Arrays.toString(keys); } @Override Iterator<CompactSetNode<K>> nodeIterator() { return Collections.emptyIterator(); } @Override K headKey() { assert hasPayload(); return keys[0]; } @Override public boolean containsKey(Object key, int keyHash, int shift) { if (this.hash == keyHash) { for (K k : keys) { if (k.equals(key)) { return true; } } } return false; } @Override public boolean containsKey(Object key, int keyHash, int shift, Comparator<Object> cmp) { if (this.hash == keyHash) { for (K k : keys) { if (cmp.compare(k, key) == 0) { return true; } } } return false; } /** * Inserts an object if not yet present. Note, that this implementation * always returns a new immutable {@link TrieSet} instance. */ @Override Result<K, Void, ? extends CompactSetNode<K>> updated(AtomicReference<Thread> mutator, K key, int keyHash, Void val, int shift, Comparator<Object> cmp) { if (this.hash != keyHash) { return Result.modified(mergeNodes(this, this.hash, key, keyHash, shift)); } if (containsKey(key, keyHash, shift, cmp)) { return Result.unchanged(this); } @SuppressWarnings("unchecked") final K[] keysNew = (K[]) copyAndInsert(keys, keys.length, key); return Result.modified(new HashCollisionNode<>(keyHash, keysNew)); } /** * Removes an object if present. Note, that this implementation always * returns a new immutable {@link TrieSet} instance. */ @SuppressWarnings("unchecked") @Override Result<K, Void, ? extends CompactSetNode<K>> removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift, Comparator<Object> cmp) { for (int i = 0; i < keys.length; i++) { if (cmp.compare(keys[i], key) == 0) { if (this.arity() == 1) { return Result.modified(CompactSetNode.<K> valNodeOf(mutator)); } else if (this.arity() == 2) { /* * Create root node with singleton element. This node * will be a) either be the new root returned, or b) * unwrapped and inlined. */ final K theOtherKey = (i == 0) ? keys[1] : keys[0]; return CompactSetNode.<K> valNodeOf(mutator).updated(mutator, theOtherKey, keyHash, null, 0, cmp); } else { return Result.modified(new HashCollisionNode<>(keyHash, (K[]) copyAndRemove(keys, i))); } } } return Result.unchanged(this); } @Override boolean hasPayload() { return true; } @Override int payloadArity() { return keys.length; } @Override boolean hasNodes() { return false; } @Override int nodeArity() { return 0; } @Override int arity() { return payloadArity(); } @Override byte sizePredicate() { return SIZE_MORE_THAN_ONE; } @Override K getKey(int index) { return keys[index]; } @Override public CompactSetNode<K> getNode(int index) { throw new IllegalStateException("Is leaf node."); } @Override public int hashCode() { final int prime = 31; int result = 0; result = prime * result + hash; result = prime * result + Arrays.hashCode(keys); return result; } @Override public boolean equals(Object other) { if (null == other) { return false; } if (this == other) { return true; } if (getClass() != other.getClass()) { return false; } HashCollisionNode<?> that = (HashCollisionNode<?>) other; if (hash != that.hash) { return false; } if (arity() != that.arity()) { return false; } /* * Linear scan for each key, because of arbitrary element order. */ outerLoop: for (SupplierIterator<?, ?> it = that.payloadIterator(); it.hasNext();) { final Object otherKey = it.next(); for (int i = 0; i < keys.length; i++) { final K key = keys[i]; if (key.equals(otherKey)) { continue outerLoop; } } return false; } return true; } @Override Optional<K> findByKey(Object key, int hash, int shift) { for (int i = 0; i < keys.length; i++) { final K _key = keys[i]; if (key.equals(_key)) { return Optional.of(_key); } } return Optional.empty(); } @Override Optional<K> findByKey(Object key, int hash, int shift, Comparator<Object> cmp) { for (int i = 0; i < keys.length; i++) { final K _key = keys[i]; if (cmp.compare(key, _key) == 0) { return Optional.of(_key); } } return Optional.empty(); } // TODO: generate instead of delegate @Override Result<K, Void, ? extends CompactSetNode<K>> updated(AtomicReference<Thread> mutator, K key, int keyHash, Void val, int shift) { return updated(mutator, key, keyHash, val, shift, EqualityUtils.getDefaultEqualityComparator()); } // TODO: generate instead of delegate @Override Result<K, Void, ? extends CompactSetNode<K>> removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift) { return removed(mutator, key, keyHash, shift, EqualityUtils.getDefaultEqualityComparator()); } } @Override public int hashCode() { return hashCode; } @Override public boolean equals(Object other) { if (other == this) { return true; } if (other == null) { return false; } if (other instanceof TrieSet) { TrieSet that = (TrieSet) other; if (this.size() != that.size()) { return false; } return rootNode.equals(that.rootNode); } return super.equals(other); } private abstract static class AbstractSingletonNode<K> extends CompactSetNode<K> { protected abstract byte npos1(); protected final CompactSetNode<K> node1; AbstractSingletonNode(CompactSetNode<K> node1) { this.node1 = node1; assert nodeInvariant(); } @Override Result<K, Void, ? extends CompactSetNode<K>> updated(AtomicReference<Thread> mutator, K key, int keyHash, Void val, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == npos1()) { final Result<K, Void, ? extends CompactSetNode<K>> subNodeResult = node1.updated( mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (!subNodeResult.isModified()) { return Result.unchanged(this); } final CompactSetNode<K> thisNew = valNodeOf(mutator, mask, subNodeResult.getNode()); return Result.modified(thisNew); } // no value final CompactSetNode<K> thisNew = valNodeOf(mutator, mask, key, npos1(), node1); return Result.modified(thisNew); } @Override Result<K, Void, ? extends CompactSetNode<K>> updated(AtomicReference<Thread> mutator, K key, int keyHash, Void val, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == npos1()) { final Result<K, Void, ? extends CompactSetNode<K>> subNodeResult = node1.updated( mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE, cmp); if (!subNodeResult.isModified()) { return Result.unchanged(this); } final CompactSetNode<K> thisNew = valNodeOf(mutator, mask, subNodeResult.getNode()); return Result.modified(thisNew); } // no value final CompactSetNode<K> thisNew = valNodeOf(mutator, mask, key, npos1(), node1); return Result.modified(thisNew); } @Override Result<K, Void, ? extends CompactSetNode<K>> removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == npos1()) { final Result<K, Void, ? extends CompactSetNode<K>> subNodeResult = node1.removed( mutator, key, keyHash, shift + BIT_PARTITION_SIZE); if (!subNodeResult.isModified()) { return Result.unchanged(this); } final CompactSetNode<K> subNodeNew = subNodeResult.getNode(); switch (subNodeNew.sizePredicate()) { case SIZE_EMPTY: case SIZE_ONE: // escalate (singleton or empty) result return subNodeResult; case SIZE_MORE_THAN_ONE: // modify current node (set replacement node) final CompactSetNode<K> thisNew = valNodeOf(mutator, mask, subNodeNew); return Result.modified(thisNew); default: throw new IllegalStateException("Invalid size state."); } } return Result.unchanged(this); } @Override Result<K, Void, ? extends CompactSetNode<K>> removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == npos1()) { final Result<K, Void, ? extends CompactSetNode<K>> subNodeResult = node1.removed( mutator, key, keyHash, shift + BIT_PARTITION_SIZE, cmp); if (!subNodeResult.isModified()) { return Result.unchanged(this); } final CompactSetNode<K> subNodeNew = subNodeResult.getNode(); switch (subNodeNew.sizePredicate()) { case SIZE_EMPTY: case SIZE_ONE: // escalate (singleton or empty) result return subNodeResult; case SIZE_MORE_THAN_ONE: // modify current node (set replacement node) final CompactSetNode<K> thisNew = valNodeOf(mutator, mask, subNodeNew); return Result.modified(thisNew); default: throw new IllegalStateException("Invalid size state."); } } return Result.unchanged(this); } @Override boolean containsKey(Object key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == npos1()) { return node1.containsKey(key, keyHash, shift + BIT_PARTITION_SIZE); } return false; } @Override boolean containsKey(Object key, int keyHash, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == npos1()) { return node1.containsKey(key, keyHash, shift + BIT_PARTITION_SIZE, cmp); } return false; } @Override Optional<K> findByKey(Object key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == npos1()) { return node1.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE); } return Optional.empty(); } @Override Optional<K> findByKey(Object key, int keyHash, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == npos1()) { return node1.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE, cmp); } return Optional.empty(); } @Override K getKey(int index) { throw new UnsupportedOperationException(); } @Override public AbstractSetNode<K> getNode(int index) { if (index == 0) { return node1; } else { throw new IndexOutOfBoundsException(); } } @SuppressWarnings("unchecked") @Override Iterator<AbstractSetNode<K>> nodeIterator() { return ArrayIterator.<AbstractSetNode<K>> of(new AbstractSetNode[] { node1 }); } @Override boolean hasNodes() { return true; } @Override int nodeArity() { return 1; } @Override SupplierIterator<K, K> payloadIterator() { return EmptySupplierIterator.emptyIterator(); } @Override boolean hasPayload() { return false; } @Override int payloadArity() { return 0; } @Override byte sizePredicate() { return SIZE_MORE_THAN_ONE; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + npos1(); result = prime * result + node1.hashCode(); return result; } @Override public boolean equals(Object other) { if (null == other) { return false; } if (this == other) { return true; } if (getClass() != other.getClass()) { return false; } AbstractSingletonNode<?> that = (AbstractSingletonNode<?>) other; if (!node1.equals(that.node1)) { return false; } return true; } @Override public String toString() { return String.format("[%s]", node1); } @Override K headKey() { throw new UnsupportedOperationException("No key in this kind of node."); } } private static final class SingletonNodeAtMask0Node<K> extends AbstractSingletonNode<K> { @Override protected byte npos1() { return 0; } SingletonNodeAtMask0Node(CompactSetNode<K> node1) { super(node1); } } private static final class SingletonNodeAtMask1Node<K> extends AbstractSingletonNode<K> { @Override protected byte npos1() { return 1; } SingletonNodeAtMask1Node(CompactSetNode<K> node1) { super(node1); } } private static final class SingletonNodeAtMask2Node<K> extends AbstractSingletonNode<K> { @Override protected byte npos1() { return 2; } SingletonNodeAtMask2Node(CompactSetNode<K> node1) { super(node1); } } private static final class SingletonNodeAtMask3Node<K> extends AbstractSingletonNode<K> { @Override protected byte npos1() { return 3; } SingletonNodeAtMask3Node(CompactSetNode<K> node1) { super(node1); } } private static final class SingletonNodeAtMask4Node<K> extends AbstractSingletonNode<K> { @Override protected byte npos1() { return 4; } SingletonNodeAtMask4Node(CompactSetNode<K> node1) { super(node1); } } private static final class SingletonNodeAtMask5Node<K> extends AbstractSingletonNode<K> { @Override protected byte npos1() { return 5; } SingletonNodeAtMask5Node(CompactSetNode<K> node1) { super(node1); } } private static final class SingletonNodeAtMask6Node<K> extends AbstractSingletonNode<K> { @Override protected byte npos1() { return 6; } SingletonNodeAtMask6Node(CompactSetNode<K> node1) { super(node1); } } private static final class SingletonNodeAtMask7Node<K> extends AbstractSingletonNode<K> { @Override protected byte npos1() { return 7; } SingletonNodeAtMask7Node(CompactSetNode<K> node1) { super(node1); } } private static final class SingletonNodeAtMask8Node<K> extends AbstractSingletonNode<K> { @Override protected byte npos1() { return 8; } SingletonNodeAtMask8Node(CompactSetNode<K> node1) { super(node1); } } private static final class SingletonNodeAtMask9Node<K> extends AbstractSingletonNode<K> { @Override protected byte npos1() { return 9; } SingletonNodeAtMask9Node(CompactSetNode<K> node1) { super(node1); } } private static final class SingletonNodeAtMask10Node<K> extends AbstractSingletonNode<K> { @Override protected byte npos1() { return 10; } SingletonNodeAtMask10Node(CompactSetNode<K> node1) { super(node1); } } private static final class SingletonNodeAtMask11Node<K> extends AbstractSingletonNode<K> { @Override protected byte npos1() { return 11; } SingletonNodeAtMask11Node(CompactSetNode<K> node1) { super(node1); } } private static final class SingletonNodeAtMask12Node<K> extends AbstractSingletonNode<K> { @Override protected byte npos1() { return 12; } SingletonNodeAtMask12Node(CompactSetNode<K> node1) { super(node1); } } private static final class SingletonNodeAtMask13Node<K> extends AbstractSingletonNode<K> { @Override protected byte npos1() { return 13; } SingletonNodeAtMask13Node(CompactSetNode<K> node1) { super(node1); } } private static final class SingletonNodeAtMask14Node<K> extends AbstractSingletonNode<K> { @Override protected byte npos1() { return 14; } SingletonNodeAtMask14Node(CompactSetNode<K> node1) { super(node1); } } private static final class SingletonNodeAtMask15Node<K> extends AbstractSingletonNode<K> { @Override protected byte npos1() { return 15; } SingletonNodeAtMask15Node(CompactSetNode<K> node1) { super(node1); } } private static final class SingletonNodeAtMask16Node<K> extends AbstractSingletonNode<K> { @Override protected byte npos1() { return 16; } SingletonNodeAtMask16Node(CompactSetNode<K> node1) { super(node1); } } private static final class SingletonNodeAtMask17Node<K> extends AbstractSingletonNode<K> { @Override protected byte npos1() { return 17; } SingletonNodeAtMask17Node(CompactSetNode<K> node1) { super(node1); } } private static final class SingletonNodeAtMask18Node<K> extends AbstractSingletonNode<K> { @Override protected byte npos1() { return 18; } SingletonNodeAtMask18Node(CompactSetNode<K> node1) { super(node1); } } private static final class SingletonNodeAtMask19Node<K> extends AbstractSingletonNode<K> { @Override protected byte npos1() { return 19; } SingletonNodeAtMask19Node(CompactSetNode<K> node1) { super(node1); } } private static final class SingletonNodeAtMask20Node<K> extends AbstractSingletonNode<K> { @Override protected byte npos1() { return 20; } SingletonNodeAtMask20Node(CompactSetNode<K> node1) { super(node1); } } private static final class SingletonNodeAtMask21Node<K> extends AbstractSingletonNode<K> { @Override protected byte npos1() { return 21; } SingletonNodeAtMask21Node(CompactSetNode<K> node1) { super(node1); } } private static final class SingletonNodeAtMask22Node<K> extends AbstractSingletonNode<K> { @Override protected byte npos1() { return 22; } SingletonNodeAtMask22Node(CompactSetNode<K> node1) { super(node1); } } private static final class SingletonNodeAtMask23Node<K> extends AbstractSingletonNode<K> { @Override protected byte npos1() { return 23; } SingletonNodeAtMask23Node(CompactSetNode<K> node1) { super(node1); } } private static final class SingletonNodeAtMask24Node<K> extends AbstractSingletonNode<K> { @Override protected byte npos1() { return 24; } SingletonNodeAtMask24Node(CompactSetNode<K> node1) { super(node1); } } private static final class SingletonNodeAtMask25Node<K> extends AbstractSingletonNode<K> { @Override protected byte npos1() { return 25; } SingletonNodeAtMask25Node(CompactSetNode<K> node1) { super(node1); } } private static final class SingletonNodeAtMask26Node<K> extends AbstractSingletonNode<K> { @Override protected byte npos1() { return 26; } SingletonNodeAtMask26Node(CompactSetNode<K> node1) { super(node1); } } private static final class SingletonNodeAtMask27Node<K> extends AbstractSingletonNode<K> { @Override protected byte npos1() { return 27; } SingletonNodeAtMask27Node(CompactSetNode<K> node1) { super(node1); } } private static final class SingletonNodeAtMask28Node<K> extends AbstractSingletonNode<K> { @Override protected byte npos1() { return 28; } SingletonNodeAtMask28Node(CompactSetNode<K> node1) { super(node1); } } private static final class SingletonNodeAtMask29Node<K> extends AbstractSingletonNode<K> { @Override protected byte npos1() { return 29; } SingletonNodeAtMask29Node(CompactSetNode<K> node1) { super(node1); } } private static final class SingletonNodeAtMask30Node<K> extends AbstractSingletonNode<K> { @Override protected byte npos1() { return 30; } SingletonNodeAtMask30Node(CompactSetNode<K> node1) { super(node1); } } private static final class SingletonNodeAtMask31Node<K> extends AbstractSingletonNode<K> { @Override protected byte npos1() { return 31; } SingletonNodeAtMask31Node(CompactSetNode<K> node1) { super(node1); } } private static final class Set0To0Node<K> extends CompactSetNode<K> { Set0To0Node(final AtomicReference<Thread> mutator) { assert nodeInvariant(); } @Override Result<K, Void, ? extends CompactSetNode<K>> updated(AtomicReference<Thread> mutator, K key, int keyHash, Void val, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); return Result.modified(valNodeOf(mutator, mask, key)); } @Override Result<K, Void, ? extends CompactSetNode<K>> updated(AtomicReference<Thread> mutator, K key, int keyHash, Void val, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); return Result.modified(valNodeOf(mutator, mask, key)); } @Override Result<K, Void, ? extends CompactSetNode<K>> removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift) { return Result.unchanged(this); } @Override Result<K, Void, ? extends CompactSetNode<K>> removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift, Comparator<Object> cmp) { return Result.unchanged(this); } @Override boolean containsKey(Object key, int keyHash, int shift) { return false; } @Override boolean containsKey(Object key, int keyHash, int shift, Comparator<Object> cmp) { return false; } @Override Optional<K> findByKey(Object key, int keyHash, int shift) { return Optional.empty(); } @Override Optional<K> findByKey(Object key, int keyHash, int shift, Comparator<Object> cmp) { return Optional.empty(); } @SuppressWarnings("unchecked") @Override Iterator<CompactSetNode<K>> nodeIterator() { return Collections.emptyIterator(); } @Override boolean hasNodes() { return false; } @Override int nodeArity() { return 0; } @Override SupplierIterator<K, K> payloadIterator() { return EmptySupplierIterator.emptyIterator(); } @Override boolean hasPayload() { return false; } @Override int payloadArity() { return 0; } @Override K headKey() { throw new UnsupportedOperationException("Node does not directly contain a key."); } @Override AbstractSetNode<K> getNode(int index) { throw new IllegalStateException("Index out of range."); } @Override K getKey(int index) { throw new IllegalStateException("Index out of range."); } @Override byte sizePredicate() { return SIZE_EMPTY; } @Override public int hashCode() { int result = 1; return result; } @Override public boolean equals(Object other) { if (null == other) { return false; } if (this == other) { return true; } if (getClass() != other.getClass()) { return false; } return true; } @Override public String toString() { return "[]"; } } private static final class Set0To2Node<K> extends CompactSetNode<K> { private final byte npos1; private final CompactSetNode<K> node1; private final byte npos2; private final CompactSetNode<K> node2; Set0To2Node(final AtomicReference<Thread> mutator, final byte npos1, final CompactSetNode<K> node1, final byte npos2, final CompactSetNode<K> node2) { this.npos1 = npos1; this.node1 = node1; this.npos2 = npos2; this.node2 = node2; assert nodeInvariant(); } @Override Result<K, Void, ? extends CompactSetNode<K>> updated(AtomicReference<Thread> mutator, K key, int keyHash, Void val, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == npos1) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node1.updated( mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactSetNode<K> thisNew = valNodeOf(mutator, mask, nestedResult.getNode(), npos2, node2); result = Result.modified(thisNew); } else { result = Result.unchanged(this); } } else if (mask == npos2) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node2.updated( mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactSetNode<K> thisNew = valNodeOf(mutator, npos1, node1, mask, nestedResult.getNode()); result = Result.modified(thisNew); } else { result = Result.unchanged(this); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key)); } return result; } @Override Result<K, Void, ? extends CompactSetNode<K>> updated(AtomicReference<Thread> mutator, K key, int keyHash, Void val, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == npos1) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node1.updated( mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactSetNode<K> thisNew = valNodeOf(mutator, mask, nestedResult.getNode(), npos2, node2); result = Result.modified(thisNew); } else { result = Result.unchanged(this); } } else if (mask == npos2) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node2.updated( mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactSetNode<K> thisNew = valNodeOf(mutator, npos1, node1, mask, nestedResult.getNode()); result = Result.modified(thisNew); } else { result = Result.unchanged(this); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key)); } return result; } @Override Result<K, Void, ? extends CompactSetNode<K>> removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == npos1) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node1.removed( mutator, key, keyHash, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactSetNode<K> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(removeNode1AndInlineValue(mutator, mask, updatedNode.headKey())); break; case SIZE_MORE_THAN_ONE: // update node1 result = Result.modified(valNodeOf(mutator, mask, updatedNode, npos2, node2)); break; default: throw new IllegalStateException("Size predicate violates node invariant."); } } else { result = Result.unchanged(this); } } else if (mask == npos2) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node2.removed( mutator, key, keyHash, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactSetNode<K> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(removeNode2AndInlineValue(mutator, mask, updatedNode.headKey())); break; case SIZE_MORE_THAN_ONE: // update node2 result = Result.modified(valNodeOf(mutator, npos1, node1, mask, updatedNode)); break; default: throw new IllegalStateException("Size predicate violates node invariant."); } } else { result = Result.unchanged(this); } } else { result = Result.unchanged(this); } return result; } @Override Result<K, Void, ? extends CompactSetNode<K>> removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == npos1) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node1.removed( mutator, key, keyHash, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactSetNode<K> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(removeNode1AndInlineValue(mutator, mask, updatedNode.headKey())); break; case SIZE_MORE_THAN_ONE: // update node1 result = Result.modified(valNodeOf(mutator, mask, updatedNode, npos2, node2)); break; default: throw new IllegalStateException("Size predicate violates node invariant."); } } else { result = Result.unchanged(this); } } else if (mask == npos2) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node2.removed( mutator, key, keyHash, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactSetNode<K> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(removeNode2AndInlineValue(mutator, mask, updatedNode.headKey())); break; case SIZE_MORE_THAN_ONE: // update node2 result = Result.modified(valNodeOf(mutator, npos1, node1, mask, updatedNode)); break; default: throw new IllegalStateException("Size predicate violates node invariant."); } } else { result = Result.unchanged(this); } } else { result = Result.unchanged(this); } return result; } private CompactSetNode<K> inlineValue(AtomicReference<Thread> mutator, byte mask, K key) { return valNodeOf(mutator, mask, key, npos1, node1, npos2, node2); } private CompactSetNode<K> removeNode1AndInlineValue(AtomicReference<Thread> mutator, byte mask, K key) { return valNodeOf(mutator, mask, key, npos2, node2); } private CompactSetNode<K> removeNode2AndInlineValue(AtomicReference<Thread> mutator, byte mask, K key) { return valNodeOf(mutator, mask, key, npos1, node1); } @Override boolean containsKey(Object key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == npos1) { return node1.containsKey(key, keyHash, shift + BIT_PARTITION_SIZE); } else if (mask == npos2) { return node2.containsKey(key, keyHash, shift + BIT_PARTITION_SIZE); } else { return false; } } @Override boolean containsKey(Object key, int keyHash, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == npos1) { return node1.containsKey(key, keyHash, shift + BIT_PARTITION_SIZE, cmp); } else if (mask == npos2) { return node2.containsKey(key, keyHash, shift + BIT_PARTITION_SIZE, cmp); } else { return false; } } @Override Optional<K> findByKey(Object key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == npos1) { return node1.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE); } else if (mask == npos2) { return node2.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE); } else { return Optional.empty(); } } @Override Optional<K> findByKey(Object key, int keyHash, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == npos1) { return node1.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE, cmp); } else if (mask == npos2) { return node2.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE, cmp); } else { return Optional.empty(); } } @SuppressWarnings("unchecked") @Override Iterator<CompactSetNode<K>> nodeIterator() { return ArrayIterator.<CompactSetNode<K>> of(new CompactSetNode[] { node1, node2 }); } @Override boolean hasNodes() { return true; } @Override int nodeArity() { return 2; } @Override SupplierIterator<K, K> payloadIterator() { return EmptySupplierIterator.emptyIterator(); } @Override boolean hasPayload() { return false; } @Override int payloadArity() { return 0; } @Override K headKey() { throw new UnsupportedOperationException("Node does not directly contain a key."); } @Override AbstractSetNode<K> getNode(int index) { switch (index) { case 0: return node1; case 1: return node2; default: throw new IllegalStateException("Index out of range."); } } @Override K getKey(int index) { throw new IllegalStateException("Index out of range."); } @Override byte sizePredicate() { return SIZE_MORE_THAN_ONE; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + npos1; result = prime * result + node1.hashCode(); result = prime * result + npos2; result = prime * result + node2.hashCode(); return result; } @Override public boolean equals(Object other) { if (null == other) { return false; } if (this == other) { return true; } if (getClass() != other.getClass()) { return false; } Set0To2Node<?> that = (Set0To2Node<?>) other; if (npos1 != that.npos1) { return false; } if (!node1.equals(that.node1)) { return false; } if (npos2 != that.npos2) { return false; } if (!node2.equals(that.node2)) { return false; } return true; } @Override public String toString() { return String.format("[@%d: %s, @%d: %s]", npos1, node1, npos2, node2); } } private static final class Set0To3Node<K> extends CompactSetNode<K> { private final byte npos1; private final CompactSetNode<K> node1; private final byte npos2; private final CompactSetNode<K> node2; private final byte npos3; private final CompactSetNode<K> node3; Set0To3Node(final AtomicReference<Thread> mutator, final byte npos1, final CompactSetNode<K> node1, final byte npos2, final CompactSetNode<K> node2, final byte npos3, final CompactSetNode<K> node3) { this.npos1 = npos1; this.node1 = node1; this.npos2 = npos2; this.node2 = node2; this.npos3 = npos3; this.node3 = node3; assert nodeInvariant(); } @Override Result<K, Void, ? extends CompactSetNode<K>> updated(AtomicReference<Thread> mutator, K key, int keyHash, Void val, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == npos1) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node1.updated( mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactSetNode<K> thisNew = valNodeOf(mutator, mask, nestedResult.getNode(), npos2, node2, npos3, node3); result = Result.modified(thisNew); } else { result = Result.unchanged(this); } } else if (mask == npos2) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node2.updated( mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactSetNode<K> thisNew = valNodeOf(mutator, npos1, node1, mask, nestedResult.getNode(), npos3, node3); result = Result.modified(thisNew); } else { result = Result.unchanged(this); } } else if (mask == npos3) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node3.updated( mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactSetNode<K> thisNew = valNodeOf(mutator, npos1, node1, npos2, node2, mask, nestedResult.getNode()); result = Result.modified(thisNew); } else { result = Result.unchanged(this); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key)); } return result; } @Override Result<K, Void, ? extends CompactSetNode<K>> updated(AtomicReference<Thread> mutator, K key, int keyHash, Void val, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == npos1) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node1.updated( mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactSetNode<K> thisNew = valNodeOf(mutator, mask, nestedResult.getNode(), npos2, node2, npos3, node3); result = Result.modified(thisNew); } else { result = Result.unchanged(this); } } else if (mask == npos2) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node2.updated( mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactSetNode<K> thisNew = valNodeOf(mutator, npos1, node1, mask, nestedResult.getNode(), npos3, node3); result = Result.modified(thisNew); } else { result = Result.unchanged(this); } } else if (mask == npos3) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node3.updated( mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactSetNode<K> thisNew = valNodeOf(mutator, npos1, node1, npos2, node2, mask, nestedResult.getNode()); result = Result.modified(thisNew); } else { result = Result.unchanged(this); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key)); } return result; } @Override Result<K, Void, ? extends CompactSetNode<K>> removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == npos1) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node1.removed( mutator, key, keyHash, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactSetNode<K> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(removeNode1AndInlineValue(mutator, mask, updatedNode.headKey())); break; case SIZE_MORE_THAN_ONE: // update node1 result = Result.modified(valNodeOf(mutator, mask, updatedNode, npos2, node2, npos3, node3)); break; default: throw new IllegalStateException("Size predicate violates node invariant."); } } else { result = Result.unchanged(this); } } else if (mask == npos2) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node2.removed( mutator, key, keyHash, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactSetNode<K> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(removeNode2AndInlineValue(mutator, mask, updatedNode.headKey())); break; case SIZE_MORE_THAN_ONE: // update node2 result = Result.modified(valNodeOf(mutator, npos1, node1, mask, updatedNode, npos3, node3)); break; default: throw new IllegalStateException("Size predicate violates node invariant."); } } else { result = Result.unchanged(this); } } else if (mask == npos3) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node3.removed( mutator, key, keyHash, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactSetNode<K> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(removeNode3AndInlineValue(mutator, mask, updatedNode.headKey())); break; case SIZE_MORE_THAN_ONE: // update node3 result = Result.modified(valNodeOf(mutator, npos1, node1, npos2, node2, mask, updatedNode)); break; default: throw new IllegalStateException("Size predicate violates node invariant."); } } else { result = Result.unchanged(this); } } else { result = Result.unchanged(this); } return result; } @Override Result<K, Void, ? extends CompactSetNode<K>> removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == npos1) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node1.removed( mutator, key, keyHash, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactSetNode<K> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(removeNode1AndInlineValue(mutator, mask, updatedNode.headKey())); break; case SIZE_MORE_THAN_ONE: // update node1 result = Result.modified(valNodeOf(mutator, mask, updatedNode, npos2, node2, npos3, node3)); break; default: throw new IllegalStateException("Size predicate violates node invariant."); } } else { result = Result.unchanged(this); } } else if (mask == npos2) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node2.removed( mutator, key, keyHash, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactSetNode<K> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(removeNode2AndInlineValue(mutator, mask, updatedNode.headKey())); break; case SIZE_MORE_THAN_ONE: // update node2 result = Result.modified(valNodeOf(mutator, npos1, node1, mask, updatedNode, npos3, node3)); break; default: throw new IllegalStateException("Size predicate violates node invariant."); } } else { result = Result.unchanged(this); } } else if (mask == npos3) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node3.removed( mutator, key, keyHash, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactSetNode<K> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(removeNode3AndInlineValue(mutator, mask, updatedNode.headKey())); break; case SIZE_MORE_THAN_ONE: // update node3 result = Result.modified(valNodeOf(mutator, npos1, node1, npos2, node2, mask, updatedNode)); break; default: throw new IllegalStateException("Size predicate violates node invariant."); } } else { result = Result.unchanged(this); } } else { result = Result.unchanged(this); } return result; } private CompactSetNode<K> inlineValue(AtomicReference<Thread> mutator, byte mask, K key) { return valNodeOf(mutator, mask, key, npos1, node1, npos2, node2, npos3, node3); } private CompactSetNode<K> removeNode1AndInlineValue(AtomicReference<Thread> mutator, byte mask, K key) { return valNodeOf(mutator, mask, key, npos2, node2, npos3, node3); } private CompactSetNode<K> removeNode2AndInlineValue(AtomicReference<Thread> mutator, byte mask, K key) { return valNodeOf(mutator, mask, key, npos1, node1, npos3, node3); } private CompactSetNode<K> removeNode3AndInlineValue(AtomicReference<Thread> mutator, byte mask, K key) { return valNodeOf(mutator, mask, key, npos1, node1, npos2, node2); } @Override boolean containsKey(Object key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == npos1) { return node1.containsKey(key, keyHash, shift + BIT_PARTITION_SIZE); } else if (mask == npos2) { return node2.containsKey(key, keyHash, shift + BIT_PARTITION_SIZE); } else if (mask == npos3) { return node3.containsKey(key, keyHash, shift + BIT_PARTITION_SIZE); } else { return false; } } @Override boolean containsKey(Object key, int keyHash, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == npos1) { return node1.containsKey(key, keyHash, shift + BIT_PARTITION_SIZE, cmp); } else if (mask == npos2) { return node2.containsKey(key, keyHash, shift + BIT_PARTITION_SIZE, cmp); } else if (mask == npos3) { return node3.containsKey(key, keyHash, shift + BIT_PARTITION_SIZE, cmp); } else { return false; } } @Override Optional<K> findByKey(Object key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == npos1) { return node1.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE); } else if (mask == npos2) { return node2.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE); } else if (mask == npos3) { return node3.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE); } else { return Optional.empty(); } } @Override Optional<K> findByKey(Object key, int keyHash, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == npos1) { return node1.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE, cmp); } else if (mask == npos2) { return node2.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE, cmp); } else if (mask == npos3) { return node3.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE, cmp); } else { return Optional.empty(); } } @SuppressWarnings("unchecked") @Override Iterator<CompactSetNode<K>> nodeIterator() { return ArrayIterator.<CompactSetNode<K>> of(new CompactSetNode[] { node1, node2, node3 }); } @Override boolean hasNodes() { return true; } @Override int nodeArity() { return 3; } @Override SupplierIterator<K, K> payloadIterator() { return EmptySupplierIterator.emptyIterator(); } @Override boolean hasPayload() { return false; } @Override int payloadArity() { return 0; } @Override K headKey() { throw new UnsupportedOperationException("Node does not directly contain a key."); } @Override AbstractSetNode<K> getNode(int index) { switch (index) { case 0: return node1; case 1: return node2; case 2: return node3; default: throw new IllegalStateException("Index out of range."); } } @Override K getKey(int index) { throw new IllegalStateException("Index out of range."); } @Override byte sizePredicate() { return SIZE_MORE_THAN_ONE; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + npos1; result = prime * result + node1.hashCode(); result = prime * result + npos2; result = prime * result + node2.hashCode(); result = prime * result + npos3; result = prime * result + node3.hashCode(); return result; } @Override public boolean equals(Object other) { if (null == other) { return false; } if (this == other) { return true; } if (getClass() != other.getClass()) { return false; } Set0To3Node<?> that = (Set0To3Node<?>) other; if (npos1 != that.npos1) { return false; } if (!node1.equals(that.node1)) { return false; } if (npos2 != that.npos2) { return false; } if (!node2.equals(that.node2)) { return false; } if (npos3 != that.npos3) { return false; } if (!node3.equals(that.node3)) { return false; } return true; } @Override public String toString() { return String.format("[@%d: %s, @%d: %s, @%d: %s]", npos1, node1, npos2, node2, npos3, node3); } } private static final class Set0To4Node<K> extends CompactSetNode<K> { private final byte npos1; private final CompactSetNode<K> node1; private final byte npos2; private final CompactSetNode<K> node2; private final byte npos3; private final CompactSetNode<K> node3; private final byte npos4; private final CompactSetNode<K> node4; Set0To4Node(final AtomicReference<Thread> mutator, final byte npos1, final CompactSetNode<K> node1, final byte npos2, final CompactSetNode<K> node2, final byte npos3, final CompactSetNode<K> node3, final byte npos4, final CompactSetNode<K> node4) { this.npos1 = npos1; this.node1 = node1; this.npos2 = npos2; this.node2 = node2; this.npos3 = npos3; this.node3 = node3; this.npos4 = npos4; this.node4 = node4; assert nodeInvariant(); } @Override Result<K, Void, ? extends CompactSetNode<K>> updated(AtomicReference<Thread> mutator, K key, int keyHash, Void val, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == npos1) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node1.updated( mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactSetNode<K> thisNew = valNodeOf(mutator, mask, nestedResult.getNode(), npos2, node2, npos3, node3, npos4, node4); result = Result.modified(thisNew); } else { result = Result.unchanged(this); } } else if (mask == npos2) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node2.updated( mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactSetNode<K> thisNew = valNodeOf(mutator, npos1, node1, mask, nestedResult.getNode(), npos3, node3, npos4, node4); result = Result.modified(thisNew); } else { result = Result.unchanged(this); } } else if (mask == npos3) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node3.updated( mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactSetNode<K> thisNew = valNodeOf(mutator, npos1, node1, npos2, node2, mask, nestedResult.getNode(), npos4, node4); result = Result.modified(thisNew); } else { result = Result.unchanged(this); } } else if (mask == npos4) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node4.updated( mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactSetNode<K> thisNew = valNodeOf(mutator, npos1, node1, npos2, node2, npos3, node3, mask, nestedResult.getNode()); result = Result.modified(thisNew); } else { result = Result.unchanged(this); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key)); } return result; } @Override Result<K, Void, ? extends CompactSetNode<K>> updated(AtomicReference<Thread> mutator, K key, int keyHash, Void val, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == npos1) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node1.updated( mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactSetNode<K> thisNew = valNodeOf(mutator, mask, nestedResult.getNode(), npos2, node2, npos3, node3, npos4, node4); result = Result.modified(thisNew); } else { result = Result.unchanged(this); } } else if (mask == npos2) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node2.updated( mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactSetNode<K> thisNew = valNodeOf(mutator, npos1, node1, mask, nestedResult.getNode(), npos3, node3, npos4, node4); result = Result.modified(thisNew); } else { result = Result.unchanged(this); } } else if (mask == npos3) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node3.updated( mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactSetNode<K> thisNew = valNodeOf(mutator, npos1, node1, npos2, node2, mask, nestedResult.getNode(), npos4, node4); result = Result.modified(thisNew); } else { result = Result.unchanged(this); } } else if (mask == npos4) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node4.updated( mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactSetNode<K> thisNew = valNodeOf(mutator, npos1, node1, npos2, node2, npos3, node3, mask, nestedResult.getNode()); result = Result.modified(thisNew); } else { result = Result.unchanged(this); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key)); } return result; } @Override Result<K, Void, ? extends CompactSetNode<K>> removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == npos1) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node1.removed( mutator, key, keyHash, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactSetNode<K> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(removeNode1AndInlineValue(mutator, mask, updatedNode.headKey())); break; case SIZE_MORE_THAN_ONE: // update node1 result = Result.modified(valNodeOf(mutator, mask, updatedNode, npos2, node2, npos3, node3, npos4, node4)); break; default: throw new IllegalStateException("Size predicate violates node invariant."); } } else { result = Result.unchanged(this); } } else if (mask == npos2) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node2.removed( mutator, key, keyHash, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactSetNode<K> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(removeNode2AndInlineValue(mutator, mask, updatedNode.headKey())); break; case SIZE_MORE_THAN_ONE: // update node2 result = Result.modified(valNodeOf(mutator, npos1, node1, mask, updatedNode, npos3, node3, npos4, node4)); break; default: throw new IllegalStateException("Size predicate violates node invariant."); } } else { result = Result.unchanged(this); } } else if (mask == npos3) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node3.removed( mutator, key, keyHash, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactSetNode<K> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(removeNode3AndInlineValue(mutator, mask, updatedNode.headKey())); break; case SIZE_MORE_THAN_ONE: // update node3 result = Result.modified(valNodeOf(mutator, npos1, node1, npos2, node2, mask, updatedNode, npos4, node4)); break; default: throw new IllegalStateException("Size predicate violates node invariant."); } } else { result = Result.unchanged(this); } } else if (mask == npos4) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node4.removed( mutator, key, keyHash, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactSetNode<K> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(removeNode4AndInlineValue(mutator, mask, updatedNode.headKey())); break; case SIZE_MORE_THAN_ONE: // update node4 result = Result.modified(valNodeOf(mutator, npos1, node1, npos2, node2, npos3, node3, mask, updatedNode)); break; default: throw new IllegalStateException("Size predicate violates node invariant."); } } else { result = Result.unchanged(this); } } else { result = Result.unchanged(this); } return result; } @Override Result<K, Void, ? extends CompactSetNode<K>> removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == npos1) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node1.removed( mutator, key, keyHash, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactSetNode<K> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(removeNode1AndInlineValue(mutator, mask, updatedNode.headKey())); break; case SIZE_MORE_THAN_ONE: // update node1 result = Result.modified(valNodeOf(mutator, mask, updatedNode, npos2, node2, npos3, node3, npos4, node4)); break; default: throw new IllegalStateException("Size predicate violates node invariant."); } } else { result = Result.unchanged(this); } } else if (mask == npos2) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node2.removed( mutator, key, keyHash, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactSetNode<K> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(removeNode2AndInlineValue(mutator, mask, updatedNode.headKey())); break; case SIZE_MORE_THAN_ONE: // update node2 result = Result.modified(valNodeOf(mutator, npos1, node1, mask, updatedNode, npos3, node3, npos4, node4)); break; default: throw new IllegalStateException("Size predicate violates node invariant."); } } else { result = Result.unchanged(this); } } else if (mask == npos3) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node3.removed( mutator, key, keyHash, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactSetNode<K> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(removeNode3AndInlineValue(mutator, mask, updatedNode.headKey())); break; case SIZE_MORE_THAN_ONE: // update node3 result = Result.modified(valNodeOf(mutator, npos1, node1, npos2, node2, mask, updatedNode, npos4, node4)); break; default: throw new IllegalStateException("Size predicate violates node invariant."); } } else { result = Result.unchanged(this); } } else if (mask == npos4) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node4.removed( mutator, key, keyHash, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactSetNode<K> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(removeNode4AndInlineValue(mutator, mask, updatedNode.headKey())); break; case SIZE_MORE_THAN_ONE: // update node4 result = Result.modified(valNodeOf(mutator, npos1, node1, npos2, node2, npos3, node3, mask, updatedNode)); break; default: throw new IllegalStateException("Size predicate violates node invariant."); } } else { result = Result.unchanged(this); } } else { result = Result.unchanged(this); } return result; } private CompactSetNode<K> inlineValue(AtomicReference<Thread> mutator, byte mask, K key) { return valNodeOf(mutator, mask, key, npos1, node1, npos2, node2, npos3, node3, npos4, node4); } private CompactSetNode<K> removeNode1AndInlineValue(AtomicReference<Thread> mutator, byte mask, K key) { return valNodeOf(mutator, mask, key, npos2, node2, npos3, node3, npos4, node4); } private CompactSetNode<K> removeNode2AndInlineValue(AtomicReference<Thread> mutator, byte mask, K key) { return valNodeOf(mutator, mask, key, npos1, node1, npos3, node3, npos4, node4); } private CompactSetNode<K> removeNode3AndInlineValue(AtomicReference<Thread> mutator, byte mask, K key) { return valNodeOf(mutator, mask, key, npos1, node1, npos2, node2, npos4, node4); } private CompactSetNode<K> removeNode4AndInlineValue(AtomicReference<Thread> mutator, byte mask, K key) { return valNodeOf(mutator, mask, key, npos1, node1, npos2, node2, npos3, node3); } @Override boolean containsKey(Object key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == npos1) { return node1.containsKey(key, keyHash, shift + BIT_PARTITION_SIZE); } else if (mask == npos2) { return node2.containsKey(key, keyHash, shift + BIT_PARTITION_SIZE); } else if (mask == npos3) { return node3.containsKey(key, keyHash, shift + BIT_PARTITION_SIZE); } else if (mask == npos4) { return node4.containsKey(key, keyHash, shift + BIT_PARTITION_SIZE); } else { return false; } } @Override boolean containsKey(Object key, int keyHash, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == npos1) { return node1.containsKey(key, keyHash, shift + BIT_PARTITION_SIZE, cmp); } else if (mask == npos2) { return node2.containsKey(key, keyHash, shift + BIT_PARTITION_SIZE, cmp); } else if (mask == npos3) { return node3.containsKey(key, keyHash, shift + BIT_PARTITION_SIZE, cmp); } else if (mask == npos4) { return node4.containsKey(key, keyHash, shift + BIT_PARTITION_SIZE, cmp); } else { return false; } } @Override Optional<K> findByKey(Object key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == npos1) { return node1.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE); } else if (mask == npos2) { return node2.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE); } else if (mask == npos3) { return node3.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE); } else if (mask == npos4) { return node4.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE); } else { return Optional.empty(); } } @Override Optional<K> findByKey(Object key, int keyHash, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == npos1) { return node1.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE, cmp); } else if (mask == npos2) { return node2.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE, cmp); } else if (mask == npos3) { return node3.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE, cmp); } else if (mask == npos4) { return node4.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE, cmp); } else { return Optional.empty(); } } @SuppressWarnings("unchecked") @Override Iterator<CompactSetNode<K>> nodeIterator() { return ArrayIterator.<CompactSetNode<K>> of(new CompactSetNode[] { node1, node2, node3, node4 }); } @Override boolean hasNodes() { return true; } @Override int nodeArity() { return 4; } @Override SupplierIterator<K, K> payloadIterator() { return EmptySupplierIterator.emptyIterator(); } @Override boolean hasPayload() { return false; } @Override int payloadArity() { return 0; } @Override K headKey() { throw new UnsupportedOperationException("Node does not directly contain a key."); } @Override AbstractSetNode<K> getNode(int index) { switch (index) { case 0: return node1; case 1: return node2; case 2: return node3; case 3: return node4; default: throw new IllegalStateException("Index out of range."); } } @Override K getKey(int index) { throw new IllegalStateException("Index out of range."); } @Override byte sizePredicate() { return SIZE_MORE_THAN_ONE; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + npos1; result = prime * result + node1.hashCode(); result = prime * result + npos2; result = prime * result + node2.hashCode(); result = prime * result + npos3; result = prime * result + node3.hashCode(); result = prime * result + npos4; result = prime * result + node4.hashCode(); return result; } @Override public boolean equals(Object other) { if (null == other) { return false; } if (this == other) { return true; } if (getClass() != other.getClass()) { return false; } Set0To4Node<?> that = (Set0To4Node<?>) other; if (npos1 != that.npos1) { return false; } if (!node1.equals(that.node1)) { return false; } if (npos2 != that.npos2) { return false; } if (!node2.equals(that.node2)) { return false; } if (npos3 != that.npos3) { return false; } if (!node3.equals(that.node3)) { return false; } if (npos4 != that.npos4) { return false; } if (!node4.equals(that.node4)) { return false; } return true; } @Override public String toString() { return String.format("[@%d: %s, @%d: %s, @%d: %s, @%d: %s]", npos1, node1, npos2, node2, npos3, node3, npos4, node4); } } private static final class Set1To0Node<K> extends CompactSetNode<K> { private final byte pos1; private final K key1; Set1To0Node(final AtomicReference<Thread> mutator, final byte pos1, final K key1) { this.pos1 = pos1; this.key1 = key1; assert nodeInvariant(); } @Override Result<K, Void, ? extends CompactSetNode<K>> updated(AtomicReference<Thread> mutator, K key, int keyHash, Void val, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == pos1) { if (key.equals(key1)) { result = Result.unchanged(this); } else { // merge into node final CompactSetNode<K> node = mergeNodes(key1, key1.hashCode(), key, keyHash, shift + BIT_PARTITION_SIZE); result = Result.modified(valNodeOf(mutator, mask, node)); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key)); } return result; } @Override Result<K, Void, ? extends CompactSetNode<K>> updated(AtomicReference<Thread> mutator, K key, int keyHash, Void val, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == pos1) { if (cmp.compare(key, key1) == 0) { result = Result.unchanged(this); } else { // merge into node final CompactSetNode<K> node = mergeNodes(key1, key1.hashCode(), key, keyHash, shift + BIT_PARTITION_SIZE); result = Result.modified(valNodeOf(mutator, mask, node)); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key)); } return result; } @Override Result<K, Void, ? extends CompactSetNode<K>> removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == pos1) { if (key.equals(key1)) { // remove key1, val1 result = Result.modified(CompactSetNode.<K> valNodeOf(mutator)); } else { result = Result.unchanged(this); } } else { result = Result.unchanged(this); } return result; } @Override Result<K, Void, ? extends CompactSetNode<K>> removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == pos1) { if (cmp.compare(key, key1) == 0) { // remove key1, val1 result = Result.modified(CompactSetNode.<K> valNodeOf(mutator)); } else { result = Result.unchanged(this); } } else { result = Result.unchanged(this); } return result; } private CompactSetNode<K> inlineValue(AtomicReference<Thread> mutator, byte mask, K key) { if (mask < pos1) { return valNodeOf(mutator, mask, key, pos1, key1); } else { return valNodeOf(mutator, pos1, key1, mask, key); } } @Override boolean containsKey(Object key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == pos1 && key.equals(key1)) { return true; } else { return false; } } @Override boolean containsKey(Object key, int keyHash, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == pos1 && cmp.compare(key, key1) == 0) { return true; } else { return false; } } @Override Optional<K> findByKey(Object key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == pos1 && key.equals(key1)) { return Optional.of(key1); } else { return Optional.empty(); } } @Override Optional<K> findByKey(Object key, int keyHash, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == pos1 && cmp.compare(key, key1) == 0) { return Optional.of(key1); } else { return Optional.empty(); } } @SuppressWarnings("unchecked") @Override Iterator<CompactSetNode<K>> nodeIterator() { return Collections.emptyIterator(); } @Override boolean hasNodes() { return false; } @Override int nodeArity() { return 0; } @Override SupplierIterator<K, K> payloadIterator() { return ArrayKeyValueIterator.of(new Object[] { key1, key1 }); } @Override boolean hasPayload() { return true; } @Override int payloadArity() { return 1; } @Override K headKey() { return key1; } @Override AbstractSetNode<K> getNode(int index) { throw new IllegalStateException("Index out of range."); } @Override K getKey(int index) { switch (index) { case 0: return key1; default: throw new IllegalStateException("Index out of range."); } } @Override byte sizePredicate() { return SIZE_ONE; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + pos1; result = prime * result + key1.hashCode(); return result; } @Override public boolean equals(Object other) { if (null == other) { return false; } if (this == other) { return true; } if (getClass() != other.getClass()) { return false; } Set1To0Node<?> that = (Set1To0Node<?>) other; if (pos1 != that.pos1) { return false; } if (!key1.equals(that.key1)) { return false; } return true; } @Override public String toString() { return String.format("[@%d: %s]", pos1, key1); } } private static final class Set1To1Node<K> extends CompactSetNode<K> { private final byte pos1; private final K key1; private final byte npos1; private final CompactSetNode<K> node1; Set1To1Node(final AtomicReference<Thread> mutator, final byte pos1, final K key1, final byte npos1, final CompactSetNode<K> node1) { this.pos1 = pos1; this.key1 = key1; this.npos1 = npos1; this.node1 = node1; assert nodeInvariant(); } @Override Result<K, Void, ? extends CompactSetNode<K>> updated(AtomicReference<Thread> mutator, K key, int keyHash, Void val, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == pos1) { if (key.equals(key1)) { result = Result.unchanged(this); } else { // merge into node final CompactSetNode<K> node = mergeNodes(key1, key1.hashCode(), key, keyHash, shift + BIT_PARTITION_SIZE); if (mask < npos1) { result = Result.modified(valNodeOf(mutator, mask, node, npos1, node1)); } else { result = Result.modified(valNodeOf(mutator, npos1, node1, mask, node)); } } } else if (mask == npos1) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node1.updated( mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactSetNode<K> thisNew = valNodeOf(mutator, pos1, key1, mask, nestedResult.getNode()); result = Result.modified(thisNew); } else { result = Result.unchanged(this); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key)); } return result; } @Override Result<K, Void, ? extends CompactSetNode<K>> updated(AtomicReference<Thread> mutator, K key, int keyHash, Void val, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == pos1) { if (cmp.compare(key, key1) == 0) { result = Result.unchanged(this); } else { // merge into node final CompactSetNode<K> node = mergeNodes(key1, key1.hashCode(), key, keyHash, shift + BIT_PARTITION_SIZE); if (mask < npos1) { result = Result.modified(valNodeOf(mutator, mask, node, npos1, node1)); } else { result = Result.modified(valNodeOf(mutator, npos1, node1, mask, node)); } } } else if (mask == npos1) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node1.updated( mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactSetNode<K> thisNew = valNodeOf(mutator, pos1, key1, mask, nestedResult.getNode()); result = Result.modified(thisNew); } else { result = Result.unchanged(this); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key)); } return result; } @Override Result<K, Void, ? extends CompactSetNode<K>> removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == pos1) { if (key.equals(key1)) { // remove key1, val1 result = Result.modified(valNodeOf(mutator, npos1, node1)); } else { result = Result.unchanged(this); } } else if (mask == npos1) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node1.removed( mutator, key, keyHash, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactSetNode<K> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(removeNode1AndInlineValue(mutator, mask, updatedNode.headKey())); break; case SIZE_MORE_THAN_ONE: // update node1 result = Result.modified(valNodeOf(mutator, pos1, key1, mask, updatedNode)); break; default: throw new IllegalStateException("Size predicate violates node invariant."); } } else { result = Result.unchanged(this); } } else { result = Result.unchanged(this); } return result; } @Override Result<K, Void, ? extends CompactSetNode<K>> removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == pos1) { if (cmp.compare(key, key1) == 0) { // remove key1, val1 result = Result.modified(valNodeOf(mutator, npos1, node1)); } else { result = Result.unchanged(this); } } else if (mask == npos1) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node1.removed( mutator, key, keyHash, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactSetNode<K> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(removeNode1AndInlineValue(mutator, mask, updatedNode.headKey())); break; case SIZE_MORE_THAN_ONE: // update node1 result = Result.modified(valNodeOf(mutator, pos1, key1, mask, updatedNode)); break; default: throw new IllegalStateException("Size predicate violates node invariant."); } } else { result = Result.unchanged(this); } } else { result = Result.unchanged(this); } return result; } private CompactSetNode<K> inlineValue(AtomicReference<Thread> mutator, byte mask, K key) { if (mask < pos1) { return valNodeOf(mutator, mask, key, pos1, key1, npos1, node1); } else { return valNodeOf(mutator, pos1, key1, mask, key, npos1, node1); } } private CompactSetNode<K> removeNode1AndInlineValue(AtomicReference<Thread> mutator, byte mask, K key) { if (mask < pos1) { return valNodeOf(mutator, mask, key, pos1, key1); } else { return valNodeOf(mutator, pos1, key1, mask, key); } } @Override boolean containsKey(Object key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == pos1 && key.equals(key1)) { return true; } else if (mask == npos1) { return node1.containsKey(key, keyHash, shift + BIT_PARTITION_SIZE); } else { return false; } } @Override boolean containsKey(Object key, int keyHash, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == pos1 && cmp.compare(key, key1) == 0) { return true; } else if (mask == npos1) { return node1.containsKey(key, keyHash, shift + BIT_PARTITION_SIZE, cmp); } else { return false; } } @Override Optional<K> findByKey(Object key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == pos1 && key.equals(key1)) { return Optional.of(key1); } else if (mask == npos1) { return node1.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE); } else { return Optional.empty(); } } @Override Optional<K> findByKey(Object key, int keyHash, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == pos1 && cmp.compare(key, key1) == 0) { return Optional.of(key1); } else if (mask == npos1) { return node1.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE, cmp); } else { return Optional.empty(); } } @SuppressWarnings("unchecked") @Override Iterator<CompactSetNode<K>> nodeIterator() { return ArrayIterator.<CompactSetNode<K>> of(new CompactSetNode[] { node1 }); } @Override boolean hasNodes() { return true; } @Override int nodeArity() { return 1; } @Override SupplierIterator<K, K> payloadIterator() { return ArrayKeyValueIterator.of(new Object[] { key1, key1 }); } @Override boolean hasPayload() { return true; } @Override int payloadArity() { return 1; } @Override K headKey() { return key1; } @Override AbstractSetNode<K> getNode(int index) { switch (index) { case 0: return node1; default: throw new IllegalStateException("Index out of range."); } } @Override K getKey(int index) { switch (index) { case 0: return key1; default: throw new IllegalStateException("Index out of range."); } } @Override byte sizePredicate() { return SIZE_MORE_THAN_ONE; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + pos1; result = prime * result + key1.hashCode(); result = prime * result + npos1; result = prime * result + node1.hashCode(); return result; } @Override public boolean equals(Object other) { if (null == other) { return false; } if (this == other) { return true; } if (getClass() != other.getClass()) { return false; } Set1To1Node<?> that = (Set1To1Node<?>) other; if (pos1 != that.pos1) { return false; } if (!key1.equals(that.key1)) { return false; } if (npos1 != that.npos1) { return false; } if (!node1.equals(that.node1)) { return false; } return true; } @Override public String toString() { return String.format("[@%d: %s, @%d: %s]", pos1, key1, npos1, node1); } } private static final class Set1To2Node<K> extends CompactSetNode<K> { private final byte pos1; private final K key1; private final byte npos1; private final CompactSetNode<K> node1; private final byte npos2; private final CompactSetNode<K> node2; Set1To2Node(final AtomicReference<Thread> mutator, final byte pos1, final K key1, final byte npos1, final CompactSetNode<K> node1, final byte npos2, final CompactSetNode<K> node2) { this.pos1 = pos1; this.key1 = key1; this.npos1 = npos1; this.node1 = node1; this.npos2 = npos2; this.node2 = node2; assert nodeInvariant(); } @Override Result<K, Void, ? extends CompactSetNode<K>> updated(AtomicReference<Thread> mutator, K key, int keyHash, Void val, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == pos1) { if (key.equals(key1)) { result = Result.unchanged(this); } else { // merge into node final CompactSetNode<K> node = mergeNodes(key1, key1.hashCode(), key, keyHash, shift + BIT_PARTITION_SIZE); if (mask < npos1) { result = Result.modified(valNodeOf(mutator, mask, node, npos1, node1, npos2, node2)); } else if (mask < npos2) { result = Result.modified(valNodeOf(mutator, npos1, node1, mask, node, npos2, node2)); } else { result = Result.modified(valNodeOf(mutator, npos1, node1, npos2, node2, mask, node)); } } } else if (mask == npos1) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node1.updated( mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactSetNode<K> thisNew = valNodeOf(mutator, pos1, key1, mask, nestedResult.getNode(), npos2, node2); result = Result.modified(thisNew); } else { result = Result.unchanged(this); } } else if (mask == npos2) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node2.updated( mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactSetNode<K> thisNew = valNodeOf(mutator, pos1, key1, npos1, node1, mask, nestedResult.getNode()); result = Result.modified(thisNew); } else { result = Result.unchanged(this); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key)); } return result; } @Override Result<K, Void, ? extends CompactSetNode<K>> updated(AtomicReference<Thread> mutator, K key, int keyHash, Void val, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == pos1) { if (cmp.compare(key, key1) == 0) { result = Result.unchanged(this); } else { // merge into node final CompactSetNode<K> node = mergeNodes(key1, key1.hashCode(), key, keyHash, shift + BIT_PARTITION_SIZE); if (mask < npos1) { result = Result.modified(valNodeOf(mutator, mask, node, npos1, node1, npos2, node2)); } else if (mask < npos2) { result = Result.modified(valNodeOf(mutator, npos1, node1, mask, node, npos2, node2)); } else { result = Result.modified(valNodeOf(mutator, npos1, node1, npos2, node2, mask, node)); } } } else if (mask == npos1) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node1.updated( mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactSetNode<K> thisNew = valNodeOf(mutator, pos1, key1, mask, nestedResult.getNode(), npos2, node2); result = Result.modified(thisNew); } else { result = Result.unchanged(this); } } else if (mask == npos2) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node2.updated( mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactSetNode<K> thisNew = valNodeOf(mutator, pos1, key1, npos1, node1, mask, nestedResult.getNode()); result = Result.modified(thisNew); } else { result = Result.unchanged(this); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key)); } return result; } @Override Result<K, Void, ? extends CompactSetNode<K>> removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == pos1) { if (key.equals(key1)) { // remove key1, val1 result = Result.modified(valNodeOf(mutator, npos1, node1, npos2, node2)); } else { result = Result.unchanged(this); } } else if (mask == npos1) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node1.removed( mutator, key, keyHash, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactSetNode<K> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(removeNode1AndInlineValue(mutator, mask, updatedNode.headKey())); break; case SIZE_MORE_THAN_ONE: // update node1 result = Result.modified(valNodeOf(mutator, pos1, key1, mask, updatedNode, npos2, node2)); break; default: throw new IllegalStateException("Size predicate violates node invariant."); } } else { result = Result.unchanged(this); } } else if (mask == npos2) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node2.removed( mutator, key, keyHash, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactSetNode<K> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(removeNode2AndInlineValue(mutator, mask, updatedNode.headKey())); break; case SIZE_MORE_THAN_ONE: // update node2 result = Result.modified(valNodeOf(mutator, pos1, key1, npos1, node1, mask, updatedNode)); break; default: throw new IllegalStateException("Size predicate violates node invariant."); } } else { result = Result.unchanged(this); } } else { result = Result.unchanged(this); } return result; } @Override Result<K, Void, ? extends CompactSetNode<K>> removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == pos1) { if (cmp.compare(key, key1) == 0) { // remove key1, val1 result = Result.modified(valNodeOf(mutator, npos1, node1, npos2, node2)); } else { result = Result.unchanged(this); } } else if (mask == npos1) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node1.removed( mutator, key, keyHash, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactSetNode<K> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(removeNode1AndInlineValue(mutator, mask, updatedNode.headKey())); break; case SIZE_MORE_THAN_ONE: // update node1 result = Result.modified(valNodeOf(mutator, pos1, key1, mask, updatedNode, npos2, node2)); break; default: throw new IllegalStateException("Size predicate violates node invariant."); } } else { result = Result.unchanged(this); } } else if (mask == npos2) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node2.removed( mutator, key, keyHash, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactSetNode<K> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(removeNode2AndInlineValue(mutator, mask, updatedNode.headKey())); break; case SIZE_MORE_THAN_ONE: // update node2 result = Result.modified(valNodeOf(mutator, pos1, key1, npos1, node1, mask, updatedNode)); break; default: throw new IllegalStateException("Size predicate violates node invariant."); } } else { result = Result.unchanged(this); } } else { result = Result.unchanged(this); } return result; } private CompactSetNode<K> inlineValue(AtomicReference<Thread> mutator, byte mask, K key) { if (mask < pos1) { return valNodeOf(mutator, mask, key, pos1, key1, npos1, node1, npos2, node2); } else { return valNodeOf(mutator, pos1, key1, mask, key, npos1, node1, npos2, node2); } } private CompactSetNode<K> removeNode1AndInlineValue(AtomicReference<Thread> mutator, byte mask, K key) { if (mask < pos1) { return valNodeOf(mutator, mask, key, pos1, key1, npos2, node2); } else { return valNodeOf(mutator, pos1, key1, mask, key, npos2, node2); } } private CompactSetNode<K> removeNode2AndInlineValue(AtomicReference<Thread> mutator, byte mask, K key) { if (mask < pos1) { return valNodeOf(mutator, mask, key, pos1, key1, npos1, node1); } else { return valNodeOf(mutator, pos1, key1, mask, key, npos1, node1); } } @Override boolean containsKey(Object key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == pos1 && key.equals(key1)) { return true; } else if (mask == npos1) { return node1.containsKey(key, keyHash, shift + BIT_PARTITION_SIZE); } else if (mask == npos2) { return node2.containsKey(key, keyHash, shift + BIT_PARTITION_SIZE); } else { return false; } } @Override boolean containsKey(Object key, int keyHash, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == pos1 && cmp.compare(key, key1) == 0) { return true; } else if (mask == npos1) { return node1.containsKey(key, keyHash, shift + BIT_PARTITION_SIZE, cmp); } else if (mask == npos2) { return node2.containsKey(key, keyHash, shift + BIT_PARTITION_SIZE, cmp); } else { return false; } } @Override Optional<K> findByKey(Object key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == pos1 && key.equals(key1)) { return Optional.of(key1); } else if (mask == npos1) { return node1.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE); } else if (mask == npos2) { return node2.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE); } else { return Optional.empty(); } } @Override Optional<K> findByKey(Object key, int keyHash, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == pos1 && cmp.compare(key, key1) == 0) { return Optional.of(key1); } else if (mask == npos1) { return node1.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE, cmp); } else if (mask == npos2) { return node2.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE, cmp); } else { return Optional.empty(); } } @SuppressWarnings("unchecked") @Override Iterator<CompactSetNode<K>> nodeIterator() { return ArrayIterator.<CompactSetNode<K>> of(new CompactSetNode[] { node1, node2 }); } @Override boolean hasNodes() { return true; } @Override int nodeArity() { return 2; } @Override SupplierIterator<K, K> payloadIterator() { return ArrayKeyValueIterator.of(new Object[] { key1, key1 }); } @Override boolean hasPayload() { return true; } @Override int payloadArity() { return 1; } @Override K headKey() { return key1; } @Override AbstractSetNode<K> getNode(int index) { switch (index) { case 0: return node1; case 1: return node2; default: throw new IllegalStateException("Index out of range."); } } @Override K getKey(int index) { switch (index) { case 0: return key1; default: throw new IllegalStateException("Index out of range."); } } @Override byte sizePredicate() { return SIZE_MORE_THAN_ONE; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + pos1; result = prime * result + key1.hashCode(); result = prime * result + npos1; result = prime * result + node1.hashCode(); result = prime * result + npos2; result = prime * result + node2.hashCode(); return result; } @Override public boolean equals(Object other) { if (null == other) { return false; } if (this == other) { return true; } if (getClass() != other.getClass()) { return false; } Set1To2Node<?> that = (Set1To2Node<?>) other; if (pos1 != that.pos1) { return false; } if (!key1.equals(that.key1)) { return false; } if (npos1 != that.npos1) { return false; } if (!node1.equals(that.node1)) { return false; } if (npos2 != that.npos2) { return false; } if (!node2.equals(that.node2)) { return false; } return true; } @Override public String toString() { return String.format("[@%d: %s, @%d: %s, @%d: %s]", pos1, key1, npos1, node1, npos2, node2); } } private static final class Set1To3Node<K> extends CompactSetNode<K> { private final byte pos1; private final K key1; private final byte npos1; private final CompactSetNode<K> node1; private final byte npos2; private final CompactSetNode<K> node2; private final byte npos3; private final CompactSetNode<K> node3; Set1To3Node(final AtomicReference<Thread> mutator, final byte pos1, final K key1, final byte npos1, final CompactSetNode<K> node1, final byte npos2, final CompactSetNode<K> node2, final byte npos3, final CompactSetNode<K> node3) { this.pos1 = pos1; this.key1 = key1; this.npos1 = npos1; this.node1 = node1; this.npos2 = npos2; this.node2 = node2; this.npos3 = npos3; this.node3 = node3; assert nodeInvariant(); } @Override Result<K, Void, ? extends CompactSetNode<K>> updated(AtomicReference<Thread> mutator, K key, int keyHash, Void val, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == pos1) { if (key.equals(key1)) { result = Result.unchanged(this); } else { // merge into node final CompactSetNode<K> node = mergeNodes(key1, key1.hashCode(), key, keyHash, shift + BIT_PARTITION_SIZE); if (mask < npos1) { result = Result.modified(valNodeOf(mutator, mask, node, npos1, node1, npos2, node2, npos3, node3)); } else if (mask < npos2) { result = Result.modified(valNodeOf(mutator, npos1, node1, mask, node, npos2, node2, npos3, node3)); } else if (mask < npos3) { result = Result.modified(valNodeOf(mutator, npos1, node1, npos2, node2, mask, node, npos3, node3)); } else { result = Result.modified(valNodeOf(mutator, npos1, node1, npos2, node2, npos3, node3, mask, node)); } } } else if (mask == npos1) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node1.updated( mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactSetNode<K> thisNew = valNodeOf(mutator, pos1, key1, mask, nestedResult.getNode(), npos2, node2, npos3, node3); result = Result.modified(thisNew); } else { result = Result.unchanged(this); } } else if (mask == npos2) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node2.updated( mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactSetNode<K> thisNew = valNodeOf(mutator, pos1, key1, npos1, node1, mask, nestedResult.getNode(), npos3, node3); result = Result.modified(thisNew); } else { result = Result.unchanged(this); } } else if (mask == npos3) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node3.updated( mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactSetNode<K> thisNew = valNodeOf(mutator, pos1, key1, npos1, node1, npos2, node2, mask, nestedResult.getNode()); result = Result.modified(thisNew); } else { result = Result.unchanged(this); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key)); } return result; } @Override Result<K, Void, ? extends CompactSetNode<K>> updated(AtomicReference<Thread> mutator, K key, int keyHash, Void val, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == pos1) { if (cmp.compare(key, key1) == 0) { result = Result.unchanged(this); } else { // merge into node final CompactSetNode<K> node = mergeNodes(key1, key1.hashCode(), key, keyHash, shift + BIT_PARTITION_SIZE); if (mask < npos1) { result = Result.modified(valNodeOf(mutator, mask, node, npos1, node1, npos2, node2, npos3, node3)); } else if (mask < npos2) { result = Result.modified(valNodeOf(mutator, npos1, node1, mask, node, npos2, node2, npos3, node3)); } else if (mask < npos3) { result = Result.modified(valNodeOf(mutator, npos1, node1, npos2, node2, mask, node, npos3, node3)); } else { result = Result.modified(valNodeOf(mutator, npos1, node1, npos2, node2, npos3, node3, mask, node)); } } } else if (mask == npos1) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node1.updated( mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactSetNode<K> thisNew = valNodeOf(mutator, pos1, key1, mask, nestedResult.getNode(), npos2, node2, npos3, node3); result = Result.modified(thisNew); } else { result = Result.unchanged(this); } } else if (mask == npos2) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node2.updated( mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactSetNode<K> thisNew = valNodeOf(mutator, pos1, key1, npos1, node1, mask, nestedResult.getNode(), npos3, node3); result = Result.modified(thisNew); } else { result = Result.unchanged(this); } } else if (mask == npos3) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node3.updated( mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactSetNode<K> thisNew = valNodeOf(mutator, pos1, key1, npos1, node1, npos2, node2, mask, nestedResult.getNode()); result = Result.modified(thisNew); } else { result = Result.unchanged(this); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key)); } return result; } @Override Result<K, Void, ? extends CompactSetNode<K>> removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == pos1) { if (key.equals(key1)) { // remove key1, val1 result = Result.modified(valNodeOf(mutator, npos1, node1, npos2, node2, npos3, node3)); } else { result = Result.unchanged(this); } } else if (mask == npos1) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node1.removed( mutator, key, keyHash, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactSetNode<K> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(removeNode1AndInlineValue(mutator, mask, updatedNode.headKey())); break; case SIZE_MORE_THAN_ONE: // update node1 result = Result.modified(valNodeOf(mutator, pos1, key1, mask, updatedNode, npos2, node2, npos3, node3)); break; default: throw new IllegalStateException("Size predicate violates node invariant."); } } else { result = Result.unchanged(this); } } else if (mask == npos2) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node2.removed( mutator, key, keyHash, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactSetNode<K> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(removeNode2AndInlineValue(mutator, mask, updatedNode.headKey())); break; case SIZE_MORE_THAN_ONE: // update node2 result = Result.modified(valNodeOf(mutator, pos1, key1, npos1, node1, mask, updatedNode, npos3, node3)); break; default: throw new IllegalStateException("Size predicate violates node invariant."); } } else { result = Result.unchanged(this); } } else if (mask == npos3) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node3.removed( mutator, key, keyHash, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactSetNode<K> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(removeNode3AndInlineValue(mutator, mask, updatedNode.headKey())); break; case SIZE_MORE_THAN_ONE: // update node3 result = Result.modified(valNodeOf(mutator, pos1, key1, npos1, node1, npos2, node2, mask, updatedNode)); break; default: throw new IllegalStateException("Size predicate violates node invariant."); } } else { result = Result.unchanged(this); } } else { result = Result.unchanged(this); } return result; } @Override Result<K, Void, ? extends CompactSetNode<K>> removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == pos1) { if (cmp.compare(key, key1) == 0) { // remove key1, val1 result = Result.modified(valNodeOf(mutator, npos1, node1, npos2, node2, npos3, node3)); } else { result = Result.unchanged(this); } } else if (mask == npos1) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node1.removed( mutator, key, keyHash, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactSetNode<K> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(removeNode1AndInlineValue(mutator, mask, updatedNode.headKey())); break; case SIZE_MORE_THAN_ONE: // update node1 result = Result.modified(valNodeOf(mutator, pos1, key1, mask, updatedNode, npos2, node2, npos3, node3)); break; default: throw new IllegalStateException("Size predicate violates node invariant."); } } else { result = Result.unchanged(this); } } else if (mask == npos2) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node2.removed( mutator, key, keyHash, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactSetNode<K> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(removeNode2AndInlineValue(mutator, mask, updatedNode.headKey())); break; case SIZE_MORE_THAN_ONE: // update node2 result = Result.modified(valNodeOf(mutator, pos1, key1, npos1, node1, mask, updatedNode, npos3, node3)); break; default: throw new IllegalStateException("Size predicate violates node invariant."); } } else { result = Result.unchanged(this); } } else if (mask == npos3) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node3.removed( mutator, key, keyHash, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactSetNode<K> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(removeNode3AndInlineValue(mutator, mask, updatedNode.headKey())); break; case SIZE_MORE_THAN_ONE: // update node3 result = Result.modified(valNodeOf(mutator, pos1, key1, npos1, node1, npos2, node2, mask, updatedNode)); break; default: throw new IllegalStateException("Size predicate violates node invariant."); } } else { result = Result.unchanged(this); } } else { result = Result.unchanged(this); } return result; } private CompactSetNode<K> inlineValue(AtomicReference<Thread> mutator, byte mask, K key) { if (mask < pos1) { return valNodeOf(mutator, mask, key, pos1, key1, npos1, node1, npos2, node2, npos3, node3); } else { return valNodeOf(mutator, pos1, key1, mask, key, npos1, node1, npos2, node2, npos3, node3); } } private CompactSetNode<K> removeNode1AndInlineValue(AtomicReference<Thread> mutator, byte mask, K key) { if (mask < pos1) { return valNodeOf(mutator, mask, key, pos1, key1, npos2, node2, npos3, node3); } else { return valNodeOf(mutator, pos1, key1, mask, key, npos2, node2, npos3, node3); } } private CompactSetNode<K> removeNode2AndInlineValue(AtomicReference<Thread> mutator, byte mask, K key) { if (mask < pos1) { return valNodeOf(mutator, mask, key, pos1, key1, npos1, node1, npos3, node3); } else { return valNodeOf(mutator, pos1, key1, mask, key, npos1, node1, npos3, node3); } } private CompactSetNode<K> removeNode3AndInlineValue(AtomicReference<Thread> mutator, byte mask, K key) { if (mask < pos1) { return valNodeOf(mutator, mask, key, pos1, key1, npos1, node1, npos2, node2); } else { return valNodeOf(mutator, pos1, key1, mask, key, npos1, node1, npos2, node2); } } @Override boolean containsKey(Object key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == pos1 && key.equals(key1)) { return true; } else if (mask == npos1) { return node1.containsKey(key, keyHash, shift + BIT_PARTITION_SIZE); } else if (mask == npos2) { return node2.containsKey(key, keyHash, shift + BIT_PARTITION_SIZE); } else if (mask == npos3) { return node3.containsKey(key, keyHash, shift + BIT_PARTITION_SIZE); } else { return false; } } @Override boolean containsKey(Object key, int keyHash, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == pos1 && cmp.compare(key, key1) == 0) { return true; } else if (mask == npos1) { return node1.containsKey(key, keyHash, shift + BIT_PARTITION_SIZE, cmp); } else if (mask == npos2) { return node2.containsKey(key, keyHash, shift + BIT_PARTITION_SIZE, cmp); } else if (mask == npos3) { return node3.containsKey(key, keyHash, shift + BIT_PARTITION_SIZE, cmp); } else { return false; } } @Override Optional<K> findByKey(Object key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == pos1 && key.equals(key1)) { return Optional.of(key1); } else if (mask == npos1) { return node1.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE); } else if (mask == npos2) { return node2.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE); } else if (mask == npos3) { return node3.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE); } else { return Optional.empty(); } } @Override Optional<K> findByKey(Object key, int keyHash, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == pos1 && cmp.compare(key, key1) == 0) { return Optional.of(key1); } else if (mask == npos1) { return node1.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE, cmp); } else if (mask == npos2) { return node2.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE, cmp); } else if (mask == npos3) { return node3.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE, cmp); } else { return Optional.empty(); } } @SuppressWarnings("unchecked") @Override Iterator<CompactSetNode<K>> nodeIterator() { return ArrayIterator.<CompactSetNode<K>> of(new CompactSetNode[] { node1, node2, node3 }); } @Override boolean hasNodes() { return true; } @Override int nodeArity() { return 3; } @Override SupplierIterator<K, K> payloadIterator() { return ArrayKeyValueIterator.of(new Object[] { key1, key1 }); } @Override boolean hasPayload() { return true; } @Override int payloadArity() { return 1; } @Override K headKey() { return key1; } @Override AbstractSetNode<K> getNode(int index) { switch (index) { case 0: return node1; case 1: return node2; case 2: return node3; default: throw new IllegalStateException("Index out of range."); } } @Override K getKey(int index) { switch (index) { case 0: return key1; default: throw new IllegalStateException("Index out of range."); } } @Override byte sizePredicate() { return SIZE_MORE_THAN_ONE; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + pos1; result = prime * result + key1.hashCode(); result = prime * result + npos1; result = prime * result + node1.hashCode(); result = prime * result + npos2; result = prime * result + node2.hashCode(); result = prime * result + npos3; result = prime * result + node3.hashCode(); return result; } @Override public boolean equals(Object other) { if (null == other) { return false; } if (this == other) { return true; } if (getClass() != other.getClass()) { return false; } Set1To3Node<?> that = (Set1To3Node<?>) other; if (pos1 != that.pos1) { return false; } if (!key1.equals(that.key1)) { return false; } if (npos1 != that.npos1) { return false; } if (!node1.equals(that.node1)) { return false; } if (npos2 != that.npos2) { return false; } if (!node2.equals(that.node2)) { return false; } if (npos3 != that.npos3) { return false; } if (!node3.equals(that.node3)) { return false; } return true; } @Override public String toString() { return String.format("[@%d: %s, @%d: %s, @%d: %s, @%d: %s]", pos1, key1, npos1, node1, npos2, node2, npos3, node3); } } private static final class Set2To0Node<K> extends CompactSetNode<K> { private final byte pos1; private final K key1; private final byte pos2; private final K key2; Set2To0Node(final AtomicReference<Thread> mutator, final byte pos1, final K key1, final byte pos2, final K key2) { this.pos1 = pos1; this.key1 = key1; this.pos2 = pos2; this.key2 = key2; assert nodeInvariant(); } @Override Result<K, Void, ? extends CompactSetNode<K>> updated(AtomicReference<Thread> mutator, K key, int keyHash, Void val, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == pos1) { if (key.equals(key1)) { result = Result.unchanged(this); } else { // merge into node final CompactSetNode<K> node = mergeNodes(key1, key1.hashCode(), key, keyHash, shift + BIT_PARTITION_SIZE); result = Result.modified(valNodeOf(mutator, pos2, key2, mask, node)); } } else if (mask == pos2) { if (key.equals(key2)) { result = Result.unchanged(this); } else { // merge into node final CompactSetNode<K> node = mergeNodes(key2, key2.hashCode(), key, keyHash, shift + BIT_PARTITION_SIZE); result = Result.modified(valNodeOf(mutator, pos1, key1, mask, node)); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key)); } return result; } @Override Result<K, Void, ? extends CompactSetNode<K>> updated(AtomicReference<Thread> mutator, K key, int keyHash, Void val, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == pos1) { if (cmp.compare(key, key1) == 0) { result = Result.unchanged(this); } else { // merge into node final CompactSetNode<K> node = mergeNodes(key1, key1.hashCode(), key, keyHash, shift + BIT_PARTITION_SIZE); result = Result.modified(valNodeOf(mutator, pos2, key2, mask, node)); } } else if (mask == pos2) { if (cmp.compare(key, key2) == 0) { result = Result.unchanged(this); } else { // merge into node final CompactSetNode<K> node = mergeNodes(key2, key2.hashCode(), key, keyHash, shift + BIT_PARTITION_SIZE); result = Result.modified(valNodeOf(mutator, pos1, key1, mask, node)); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key)); } return result; } @Override Result<K, Void, ? extends CompactSetNode<K>> removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == pos1) { if (key.equals(key1)) { /* * Create node with element key2. This node will a) either * become the new root returned, or b) unwrapped and inlined. */ final byte pos2AtShiftZero = (shift == 0) ? pos2 : (byte) (keyHash & BIT_PARTITION_MASK); result = Result.modified(valNodeOf(mutator, pos2AtShiftZero, key2)); } else { result = Result.unchanged(this); } } else if (mask == pos2) { if (key.equals(key2)) { /* * Create node with element key1. This node will a) either * become the new root returned, or b) unwrapped and inlined. */ final byte pos1AtShiftZero = (shift == 0) ? pos1 : (byte) (keyHash & BIT_PARTITION_MASK); result = Result.modified(valNodeOf(mutator, pos1AtShiftZero, key1)); } else { result = Result.unchanged(this); } } else { result = Result.unchanged(this); } return result; } @Override Result<K, Void, ? extends CompactSetNode<K>> removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == pos1) { if (cmp.compare(key, key1) == 0) { /* * Create node with element key2. This node will a) either * become the new root returned, or b) unwrapped and inlined. */ final byte pos2AtShiftZero = (shift == 0) ? pos2 : (byte) (keyHash & BIT_PARTITION_MASK); result = Result.modified(valNodeOf(mutator, pos2AtShiftZero, key2)); } else { result = Result.unchanged(this); } } else if (mask == pos2) { if (cmp.compare(key, key2) == 0) { /* * Create node with element key1. This node will a) either * become the new root returned, or b) unwrapped and inlined. */ final byte pos1AtShiftZero = (shift == 0) ? pos1 : (byte) (keyHash & BIT_PARTITION_MASK); result = Result.modified(valNodeOf(mutator, pos1AtShiftZero, key1)); } else { result = Result.unchanged(this); } } else { result = Result.unchanged(this); } return result; } private CompactSetNode<K> inlineValue(AtomicReference<Thread> mutator, byte mask, K key) { if (mask < pos1) { return valNodeOf(mutator, mask, key, pos1, key1, pos2, key2); } else if (mask < pos2) { return valNodeOf(mutator, pos1, key1, mask, key, pos2, key2); } else { return valNodeOf(mutator, pos1, key1, pos2, key2, mask, key); } } @Override boolean containsKey(Object key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == pos1 && key.equals(key1)) { return true; } else if (mask == pos2 && key.equals(key2)) { return true; } else { return false; } } @Override boolean containsKey(Object key, int keyHash, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == pos1 && cmp.compare(key, key1) == 0) { return true; } else if (mask == pos2 && cmp.compare(key, key2) == 0) { return true; } else { return false; } } @Override Optional<K> findByKey(Object key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == pos1 && key.equals(key1)) { return Optional.of(key1); } else if (mask == pos2 && key.equals(key2)) { return Optional.of(key2); } else { return Optional.empty(); } } @Override Optional<K> findByKey(Object key, int keyHash, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == pos1 && cmp.compare(key, key1) == 0) { return Optional.of(key1); } else if (mask == pos2 && cmp.compare(key, key2) == 0) { return Optional.of(key2); } else { return Optional.empty(); } } @SuppressWarnings("unchecked") @Override Iterator<CompactSetNode<K>> nodeIterator() { return Collections.emptyIterator(); } @Override boolean hasNodes() { return false; } @Override int nodeArity() { return 0; } @Override SupplierIterator<K, K> payloadIterator() { return ArrayKeyValueIterator.of(new Object[] { key1, key1, key2, key2 }); } @Override boolean hasPayload() { return true; } @Override int payloadArity() { return 2; } @Override K headKey() { return key1; } @Override AbstractSetNode<K> getNode(int index) { throw new IllegalStateException("Index out of range."); } @Override K getKey(int index) { switch (index) { case 0: return key1; case 1: return key2; default: throw new IllegalStateException("Index out of range."); } } @Override byte sizePredicate() { return SIZE_MORE_THAN_ONE; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + pos1; result = prime * result + key1.hashCode(); result = prime * result + pos2; result = prime * result + key2.hashCode(); return result; } @Override public boolean equals(Object other) { if (null == other) { return false; } if (this == other) { return true; } if (getClass() != other.getClass()) { return false; } Set2To0Node<?> that = (Set2To0Node<?>) other; if (pos1 != that.pos1) { return false; } if (!key1.equals(that.key1)) { return false; } if (pos2 != that.pos2) { return false; } if (!key2.equals(that.key2)) { return false; } return true; } @Override public String toString() { return String.format("[@%d: %s, @%d: %s]", pos1, key1, pos2, key2); } } private static final class Set2To1Node<K> extends CompactSetNode<K> { private final byte pos1; private final K key1; private final byte pos2; private final K key2; private final byte npos1; private final CompactSetNode<K> node1; Set2To1Node(final AtomicReference<Thread> mutator, final byte pos1, final K key1, final byte pos2, final K key2, final byte npos1, final CompactSetNode<K> node1) { this.pos1 = pos1; this.key1 = key1; this.pos2 = pos2; this.key2 = key2; this.npos1 = npos1; this.node1 = node1; assert nodeInvariant(); } @Override Result<K, Void, ? extends CompactSetNode<K>> updated(AtomicReference<Thread> mutator, K key, int keyHash, Void val, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == pos1) { if (key.equals(key1)) { result = Result.unchanged(this); } else { // merge into node final CompactSetNode<K> node = mergeNodes(key1, key1.hashCode(), key, keyHash, shift + BIT_PARTITION_SIZE); if (mask < npos1) { result = Result.modified(valNodeOf(mutator, pos2, key2, mask, node, npos1, node1)); } else { result = Result.modified(valNodeOf(mutator, pos2, key2, npos1, node1, mask, node)); } } } else if (mask == pos2) { if (key.equals(key2)) { result = Result.unchanged(this); } else { // merge into node final CompactSetNode<K> node = mergeNodes(key2, key2.hashCode(), key, keyHash, shift + BIT_PARTITION_SIZE); if (mask < npos1) { result = Result.modified(valNodeOf(mutator, pos1, key1, mask, node, npos1, node1)); } else { result = Result.modified(valNodeOf(mutator, pos1, key1, npos1, node1, mask, node)); } } } else if (mask == npos1) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node1.updated( mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactSetNode<K> thisNew = valNodeOf(mutator, pos1, key1, pos2, key2, mask, nestedResult.getNode()); result = Result.modified(thisNew); } else { result = Result.unchanged(this); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key)); } return result; } @Override Result<K, Void, ? extends CompactSetNode<K>> updated(AtomicReference<Thread> mutator, K key, int keyHash, Void val, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == pos1) { if (cmp.compare(key, key1) == 0) { result = Result.unchanged(this); } else { // merge into node final CompactSetNode<K> node = mergeNodes(key1, key1.hashCode(), key, keyHash, shift + BIT_PARTITION_SIZE); if (mask < npos1) { result = Result.modified(valNodeOf(mutator, pos2, key2, mask, node, npos1, node1)); } else { result = Result.modified(valNodeOf(mutator, pos2, key2, npos1, node1, mask, node)); } } } else if (mask == pos2) { if (cmp.compare(key, key2) == 0) { result = Result.unchanged(this); } else { // merge into node final CompactSetNode<K> node = mergeNodes(key2, key2.hashCode(), key, keyHash, shift + BIT_PARTITION_SIZE); if (mask < npos1) { result = Result.modified(valNodeOf(mutator, pos1, key1, mask, node, npos1, node1)); } else { result = Result.modified(valNodeOf(mutator, pos1, key1, npos1, node1, mask, node)); } } } else if (mask == npos1) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node1.updated( mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactSetNode<K> thisNew = valNodeOf(mutator, pos1, key1, pos2, key2, mask, nestedResult.getNode()); result = Result.modified(thisNew); } else { result = Result.unchanged(this); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key)); } return result; } @Override Result<K, Void, ? extends CompactSetNode<K>> removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == pos1) { if (key.equals(key1)) { // remove key1, val1 result = Result.modified(valNodeOf(mutator, pos2, key2, npos1, node1)); } else { result = Result.unchanged(this); } } else if (mask == pos2) { if (key.equals(key2)) { // remove key2, val2 result = Result.modified(valNodeOf(mutator, pos1, key1, npos1, node1)); } else { result = Result.unchanged(this); } } else if (mask == npos1) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node1.removed( mutator, key, keyHash, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactSetNode<K> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(removeNode1AndInlineValue(mutator, mask, updatedNode.headKey())); break; case SIZE_MORE_THAN_ONE: // update node1 result = Result.modified(valNodeOf(mutator, pos1, key1, pos2, key2, mask, updatedNode)); break; default: throw new IllegalStateException("Size predicate violates node invariant."); } } else { result = Result.unchanged(this); } } else { result = Result.unchanged(this); } return result; } @Override Result<K, Void, ? extends CompactSetNode<K>> removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == pos1) { if (cmp.compare(key, key1) == 0) { // remove key1, val1 result = Result.modified(valNodeOf(mutator, pos2, key2, npos1, node1)); } else { result = Result.unchanged(this); } } else if (mask == pos2) { if (cmp.compare(key, key2) == 0) { // remove key2, val2 result = Result.modified(valNodeOf(mutator, pos1, key1, npos1, node1)); } else { result = Result.unchanged(this); } } else if (mask == npos1) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node1.removed( mutator, key, keyHash, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactSetNode<K> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(removeNode1AndInlineValue(mutator, mask, updatedNode.headKey())); break; case SIZE_MORE_THAN_ONE: // update node1 result = Result.modified(valNodeOf(mutator, pos1, key1, pos2, key2, mask, updatedNode)); break; default: throw new IllegalStateException("Size predicate violates node invariant."); } } else { result = Result.unchanged(this); } } else { result = Result.unchanged(this); } return result; } private CompactSetNode<K> inlineValue(AtomicReference<Thread> mutator, byte mask, K key) { if (mask < pos1) { return valNodeOf(mutator, mask, key, pos1, key1, pos2, key2, npos1, node1); } else if (mask < pos2) { return valNodeOf(mutator, pos1, key1, mask, key, pos2, key2, npos1, node1); } else { return valNodeOf(mutator, pos1, key1, pos2, key2, mask, key, npos1, node1); } } private CompactSetNode<K> removeNode1AndInlineValue(AtomicReference<Thread> mutator, byte mask, K key) { if (mask < pos1) { return valNodeOf(mutator, mask, key, pos1, key1, pos2, key2); } else if (mask < pos2) { return valNodeOf(mutator, pos1, key1, mask, key, pos2, key2); } else { return valNodeOf(mutator, pos1, key1, pos2, key2, mask, key); } } @Override boolean containsKey(Object key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == pos1 && key.equals(key1)) { return true; } else if (mask == pos2 && key.equals(key2)) { return true; } else if (mask == npos1) { return node1.containsKey(key, keyHash, shift + BIT_PARTITION_SIZE); } else { return false; } } @Override boolean containsKey(Object key, int keyHash, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == pos1 && cmp.compare(key, key1) == 0) { return true; } else if (mask == pos2 && cmp.compare(key, key2) == 0) { return true; } else if (mask == npos1) { return node1.containsKey(key, keyHash, shift + BIT_PARTITION_SIZE, cmp); } else { return false; } } @Override Optional<K> findByKey(Object key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == pos1 && key.equals(key1)) { return Optional.of(key1); } else if (mask == pos2 && key.equals(key2)) { return Optional.of(key2); } else if (mask == npos1) { return node1.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE); } else { return Optional.empty(); } } @Override Optional<K> findByKey(Object key, int keyHash, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == pos1 && cmp.compare(key, key1) == 0) { return Optional.of(key1); } else if (mask == pos2 && cmp.compare(key, key2) == 0) { return Optional.of(key2); } else if (mask == npos1) { return node1.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE, cmp); } else { return Optional.empty(); } } @SuppressWarnings("unchecked") @Override Iterator<CompactSetNode<K>> nodeIterator() { return ArrayIterator.<CompactSetNode<K>> of(new CompactSetNode[] { node1 }); } @Override boolean hasNodes() { return true; } @Override int nodeArity() { return 1; } @Override SupplierIterator<K, K> payloadIterator() { return ArrayKeyValueIterator.of(new Object[] { key1, key1, key2, key2 }); } @Override boolean hasPayload() { return true; } @Override int payloadArity() { return 2; } @Override K headKey() { return key1; } @Override AbstractSetNode<K> getNode(int index) { switch (index) { case 0: return node1; default: throw new IllegalStateException("Index out of range."); } } @Override K getKey(int index) { switch (index) { case 0: return key1; case 1: return key2; default: throw new IllegalStateException("Index out of range."); } } @Override byte sizePredicate() { return SIZE_MORE_THAN_ONE; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + pos1; result = prime * result + key1.hashCode(); result = prime * result + pos2; result = prime * result + key2.hashCode(); result = prime * result + npos1; result = prime * result + node1.hashCode(); return result; } @Override public boolean equals(Object other) { if (null == other) { return false; } if (this == other) { return true; } if (getClass() != other.getClass()) { return false; } Set2To1Node<?> that = (Set2To1Node<?>) other; if (pos1 != that.pos1) { return false; } if (!key1.equals(that.key1)) { return false; } if (pos2 != that.pos2) { return false; } if (!key2.equals(that.key2)) { return false; } if (npos1 != that.npos1) { return false; } if (!node1.equals(that.node1)) { return false; } return true; } @Override public String toString() { return String.format("[@%d: %s, @%d: %s, @%d: %s]", pos1, key1, pos2, key2, npos1, node1); } } private static final class Set2To2Node<K> extends CompactSetNode<K> { private final byte pos1; private final K key1; private final byte pos2; private final K key2; private final byte npos1; private final CompactSetNode<K> node1; private final byte npos2; private final CompactSetNode<K> node2; Set2To2Node(final AtomicReference<Thread> mutator, final byte pos1, final K key1, final byte pos2, final K key2, final byte npos1, final CompactSetNode<K> node1, final byte npos2, final CompactSetNode<K> node2) { this.pos1 = pos1; this.key1 = key1; this.pos2 = pos2; this.key2 = key2; this.npos1 = npos1; this.node1 = node1; this.npos2 = npos2; this.node2 = node2; assert nodeInvariant(); } @Override Result<K, Void, ? extends CompactSetNode<K>> updated(AtomicReference<Thread> mutator, K key, int keyHash, Void val, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == pos1) { if (key.equals(key1)) { result = Result.unchanged(this); } else { // merge into node final CompactSetNode<K> node = mergeNodes(key1, key1.hashCode(), key, keyHash, shift + BIT_PARTITION_SIZE); if (mask < npos1) { result = Result.modified(valNodeOf(mutator, pos2, key2, mask, node, npos1, node1, npos2, node2)); } else if (mask < npos2) { result = Result.modified(valNodeOf(mutator, pos2, key2, npos1, node1, mask, node, npos2, node2)); } else { result = Result.modified(valNodeOf(mutator, pos2, key2, npos1, node1, npos2, node2, mask, node)); } } } else if (mask == pos2) { if (key.equals(key2)) { result = Result.unchanged(this); } else { // merge into node final CompactSetNode<K> node = mergeNodes(key2, key2.hashCode(), key, keyHash, shift + BIT_PARTITION_SIZE); if (mask < npos1) { result = Result.modified(valNodeOf(mutator, pos1, key1, mask, node, npos1, node1, npos2, node2)); } else if (mask < npos2) { result = Result.modified(valNodeOf(mutator, pos1, key1, npos1, node1, mask, node, npos2, node2)); } else { result = Result.modified(valNodeOf(mutator, pos1, key1, npos1, node1, npos2, node2, mask, node)); } } } else if (mask == npos1) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node1.updated( mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactSetNode<K> thisNew = valNodeOf(mutator, pos1, key1, pos2, key2, mask, nestedResult.getNode(), npos2, node2); result = Result.modified(thisNew); } else { result = Result.unchanged(this); } } else if (mask == npos2) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node2.updated( mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactSetNode<K> thisNew = valNodeOf(mutator, pos1, key1, pos2, key2, npos1, node1, mask, nestedResult.getNode()); result = Result.modified(thisNew); } else { result = Result.unchanged(this); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key)); } return result; } @Override Result<K, Void, ? extends CompactSetNode<K>> updated(AtomicReference<Thread> mutator, K key, int keyHash, Void val, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == pos1) { if (cmp.compare(key, key1) == 0) { result = Result.unchanged(this); } else { // merge into node final CompactSetNode<K> node = mergeNodes(key1, key1.hashCode(), key, keyHash, shift + BIT_PARTITION_SIZE); if (mask < npos1) { result = Result.modified(valNodeOf(mutator, pos2, key2, mask, node, npos1, node1, npos2, node2)); } else if (mask < npos2) { result = Result.modified(valNodeOf(mutator, pos2, key2, npos1, node1, mask, node, npos2, node2)); } else { result = Result.modified(valNodeOf(mutator, pos2, key2, npos1, node1, npos2, node2, mask, node)); } } } else if (mask == pos2) { if (cmp.compare(key, key2) == 0) { result = Result.unchanged(this); } else { // merge into node final CompactSetNode<K> node = mergeNodes(key2, key2.hashCode(), key, keyHash, shift + BIT_PARTITION_SIZE); if (mask < npos1) { result = Result.modified(valNodeOf(mutator, pos1, key1, mask, node, npos1, node1, npos2, node2)); } else if (mask < npos2) { result = Result.modified(valNodeOf(mutator, pos1, key1, npos1, node1, mask, node, npos2, node2)); } else { result = Result.modified(valNodeOf(mutator, pos1, key1, npos1, node1, npos2, node2, mask, node)); } } } else if (mask == npos1) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node1.updated( mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactSetNode<K> thisNew = valNodeOf(mutator, pos1, key1, pos2, key2, mask, nestedResult.getNode(), npos2, node2); result = Result.modified(thisNew); } else { result = Result.unchanged(this); } } else if (mask == npos2) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node2.updated( mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactSetNode<K> thisNew = valNodeOf(mutator, pos1, key1, pos2, key2, npos1, node1, mask, nestedResult.getNode()); result = Result.modified(thisNew); } else { result = Result.unchanged(this); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key)); } return result; } @Override Result<K, Void, ? extends CompactSetNode<K>> removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == pos1) { if (key.equals(key1)) { // remove key1, val1 result = Result.modified(valNodeOf(mutator, pos2, key2, npos1, node1, npos2, node2)); } else { result = Result.unchanged(this); } } else if (mask == pos2) { if (key.equals(key2)) { // remove key2, val2 result = Result.modified(valNodeOf(mutator, pos1, key1, npos1, node1, npos2, node2)); } else { result = Result.unchanged(this); } } else if (mask == npos1) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node1.removed( mutator, key, keyHash, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactSetNode<K> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(removeNode1AndInlineValue(mutator, mask, updatedNode.headKey())); break; case SIZE_MORE_THAN_ONE: // update node1 result = Result.modified(valNodeOf(mutator, pos1, key1, pos2, key2, mask, updatedNode, npos2, node2)); break; default: throw new IllegalStateException("Size predicate violates node invariant."); } } else { result = Result.unchanged(this); } } else if (mask == npos2) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node2.removed( mutator, key, keyHash, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactSetNode<K> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(removeNode2AndInlineValue(mutator, mask, updatedNode.headKey())); break; case SIZE_MORE_THAN_ONE: // update node2 result = Result.modified(valNodeOf(mutator, pos1, key1, pos2, key2, npos1, node1, mask, updatedNode)); break; default: throw new IllegalStateException("Size predicate violates node invariant."); } } else { result = Result.unchanged(this); } } else { result = Result.unchanged(this); } return result; } @Override Result<K, Void, ? extends CompactSetNode<K>> removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == pos1) { if (cmp.compare(key, key1) == 0) { // remove key1, val1 result = Result.modified(valNodeOf(mutator, pos2, key2, npos1, node1, npos2, node2)); } else { result = Result.unchanged(this); } } else if (mask == pos2) { if (cmp.compare(key, key2) == 0) { // remove key2, val2 result = Result.modified(valNodeOf(mutator, pos1, key1, npos1, node1, npos2, node2)); } else { result = Result.unchanged(this); } } else if (mask == npos1) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node1.removed( mutator, key, keyHash, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactSetNode<K> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(removeNode1AndInlineValue(mutator, mask, updatedNode.headKey())); break; case SIZE_MORE_THAN_ONE: // update node1 result = Result.modified(valNodeOf(mutator, pos1, key1, pos2, key2, mask, updatedNode, npos2, node2)); break; default: throw new IllegalStateException("Size predicate violates node invariant."); } } else { result = Result.unchanged(this); } } else if (mask == npos2) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node2.removed( mutator, key, keyHash, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactSetNode<K> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(removeNode2AndInlineValue(mutator, mask, updatedNode.headKey())); break; case SIZE_MORE_THAN_ONE: // update node2 result = Result.modified(valNodeOf(mutator, pos1, key1, pos2, key2, npos1, node1, mask, updatedNode)); break; default: throw new IllegalStateException("Size predicate violates node invariant."); } } else { result = Result.unchanged(this); } } else { result = Result.unchanged(this); } return result; } private CompactSetNode<K> inlineValue(AtomicReference<Thread> mutator, byte mask, K key) { if (mask < pos1) { return valNodeOf(mutator, mask, key, pos1, key1, pos2, key2, npos1, node1, npos2, node2); } else if (mask < pos2) { return valNodeOf(mutator, pos1, key1, mask, key, pos2, key2, npos1, node1, npos2, node2); } else { return valNodeOf(mutator, pos1, key1, pos2, key2, mask, key, npos1, node1, npos2, node2); } } private CompactSetNode<K> removeNode1AndInlineValue(AtomicReference<Thread> mutator, byte mask, K key) { if (mask < pos1) { return valNodeOf(mutator, mask, key, pos1, key1, pos2, key2, npos2, node2); } else if (mask < pos2) { return valNodeOf(mutator, pos1, key1, mask, key, pos2, key2, npos2, node2); } else { return valNodeOf(mutator, pos1, key1, pos2, key2, mask, key, npos2, node2); } } private CompactSetNode<K> removeNode2AndInlineValue(AtomicReference<Thread> mutator, byte mask, K key) { if (mask < pos1) { return valNodeOf(mutator, mask, key, pos1, key1, pos2, key2, npos1, node1); } else if (mask < pos2) { return valNodeOf(mutator, pos1, key1, mask, key, pos2, key2, npos1, node1); } else { return valNodeOf(mutator, pos1, key1, pos2, key2, mask, key, npos1, node1); } } @Override boolean containsKey(Object key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == pos1 && key.equals(key1)) { return true; } else if (mask == pos2 && key.equals(key2)) { return true; } else if (mask == npos1) { return node1.containsKey(key, keyHash, shift + BIT_PARTITION_SIZE); } else if (mask == npos2) { return node2.containsKey(key, keyHash, shift + BIT_PARTITION_SIZE); } else { return false; } } @Override boolean containsKey(Object key, int keyHash, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == pos1 && cmp.compare(key, key1) == 0) { return true; } else if (mask == pos2 && cmp.compare(key, key2) == 0) { return true; } else if (mask == npos1) { return node1.containsKey(key, keyHash, shift + BIT_PARTITION_SIZE, cmp); } else if (mask == npos2) { return node2.containsKey(key, keyHash, shift + BIT_PARTITION_SIZE, cmp); } else { return false; } } @Override Optional<K> findByKey(Object key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == pos1 && key.equals(key1)) { return Optional.of(key1); } else if (mask == pos2 && key.equals(key2)) { return Optional.of(key2); } else if (mask == npos1) { return node1.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE); } else if (mask == npos2) { return node2.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE); } else { return Optional.empty(); } } @Override Optional<K> findByKey(Object key, int keyHash, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == pos1 && cmp.compare(key, key1) == 0) { return Optional.of(key1); } else if (mask == pos2 && cmp.compare(key, key2) == 0) { return Optional.of(key2); } else if (mask == npos1) { return node1.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE, cmp); } else if (mask == npos2) { return node2.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE, cmp); } else { return Optional.empty(); } } @SuppressWarnings("unchecked") @Override Iterator<CompactSetNode<K>> nodeIterator() { return ArrayIterator.<CompactSetNode<K>> of(new CompactSetNode[] { node1, node2 }); } @Override boolean hasNodes() { return true; } @Override int nodeArity() { return 2; } @Override SupplierIterator<K, K> payloadIterator() { return ArrayKeyValueIterator.of(new Object[] { key1, key1, key2, key2 }); } @Override boolean hasPayload() { return true; } @Override int payloadArity() { return 2; } @Override K headKey() { return key1; } @Override AbstractSetNode<K> getNode(int index) { switch (index) { case 0: return node1; case 1: return node2; default: throw new IllegalStateException("Index out of range."); } } @Override K getKey(int index) { switch (index) { case 0: return key1; case 1: return key2; default: throw new IllegalStateException("Index out of range."); } } @Override byte sizePredicate() { return SIZE_MORE_THAN_ONE; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + pos1; result = prime * result + key1.hashCode(); result = prime * result + pos2; result = prime * result + key2.hashCode(); result = prime * result + npos1; result = prime * result + node1.hashCode(); result = prime * result + npos2; result = prime * result + node2.hashCode(); return result; } @Override public boolean equals(Object other) { if (null == other) { return false; } if (this == other) { return true; } if (getClass() != other.getClass()) { return false; } Set2To2Node<?> that = (Set2To2Node<?>) other; if (pos1 != that.pos1) { return false; } if (!key1.equals(that.key1)) { return false; } if (pos2 != that.pos2) { return false; } if (!key2.equals(that.key2)) { return false; } if (npos1 != that.npos1) { return false; } if (!node1.equals(that.node1)) { return false; } if (npos2 != that.npos2) { return false; } if (!node2.equals(that.node2)) { return false; } return true; } @Override public String toString() { return String.format("[@%d: %s, @%d: %s, @%d: %s, @%d: %s]", pos1, key1, pos2, key2, npos1, node1, npos2, node2); } } private static final class Set3To0Node<K> extends CompactSetNode<K> { private final byte pos1; private final K key1; private final byte pos2; private final K key2; private final byte pos3; private final K key3; Set3To0Node(final AtomicReference<Thread> mutator, final byte pos1, final K key1, final byte pos2, final K key2, final byte pos3, final K key3) { this.pos1 = pos1; this.key1 = key1; this.pos2 = pos2; this.key2 = key2; this.pos3 = pos3; this.key3 = key3; assert nodeInvariant(); } @Override Result<K, Void, ? extends CompactSetNode<K>> updated(AtomicReference<Thread> mutator, K key, int keyHash, Void val, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == pos1) { if (key.equals(key1)) { result = Result.unchanged(this); } else { // merge into node final CompactSetNode<K> node = mergeNodes(key1, key1.hashCode(), key, keyHash, shift + BIT_PARTITION_SIZE); result = Result.modified(valNodeOf(mutator, pos2, key2, pos3, key3, mask, node)); } } else if (mask == pos2) { if (key.equals(key2)) { result = Result.unchanged(this); } else { // merge into node final CompactSetNode<K> node = mergeNodes(key2, key2.hashCode(), key, keyHash, shift + BIT_PARTITION_SIZE); result = Result.modified(valNodeOf(mutator, pos1, key1, pos3, key3, mask, node)); } } else if (mask == pos3) { if (key.equals(key3)) { result = Result.unchanged(this); } else { // merge into node final CompactSetNode<K> node = mergeNodes(key3, key3.hashCode(), key, keyHash, shift + BIT_PARTITION_SIZE); result = Result.modified(valNodeOf(mutator, pos1, key1, pos2, key2, mask, node)); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key)); } return result; } @Override Result<K, Void, ? extends CompactSetNode<K>> updated(AtomicReference<Thread> mutator, K key, int keyHash, Void val, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == pos1) { if (cmp.compare(key, key1) == 0) { result = Result.unchanged(this); } else { // merge into node final CompactSetNode<K> node = mergeNodes(key1, key1.hashCode(), key, keyHash, shift + BIT_PARTITION_SIZE); result = Result.modified(valNodeOf(mutator, pos2, key2, pos3, key3, mask, node)); } } else if (mask == pos2) { if (cmp.compare(key, key2) == 0) { result = Result.unchanged(this); } else { // merge into node final CompactSetNode<K> node = mergeNodes(key2, key2.hashCode(), key, keyHash, shift + BIT_PARTITION_SIZE); result = Result.modified(valNodeOf(mutator, pos1, key1, pos3, key3, mask, node)); } } else if (mask == pos3) { if (cmp.compare(key, key3) == 0) { result = Result.unchanged(this); } else { // merge into node final CompactSetNode<K> node = mergeNodes(key3, key3.hashCode(), key, keyHash, shift + BIT_PARTITION_SIZE); result = Result.modified(valNodeOf(mutator, pos1, key1, pos2, key2, mask, node)); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key)); } return result; } @Override Result<K, Void, ? extends CompactSetNode<K>> removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == pos1) { if (key.equals(key1)) { // remove key1, val1 result = Result.modified(valNodeOf(mutator, pos2, key2, pos3, key3)); } else { result = Result.unchanged(this); } } else if (mask == pos2) { if (key.equals(key2)) { // remove key2, val2 result = Result.modified(valNodeOf(mutator, pos1, key1, pos3, key3)); } else { result = Result.unchanged(this); } } else if (mask == pos3) { if (key.equals(key3)) { // remove key3, val3 result = Result.modified(valNodeOf(mutator, pos1, key1, pos2, key2)); } else { result = Result.unchanged(this); } } else { result = Result.unchanged(this); } return result; } @Override Result<K, Void, ? extends CompactSetNode<K>> removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == pos1) { if (cmp.compare(key, key1) == 0) { // remove key1, val1 result = Result.modified(valNodeOf(mutator, pos2, key2, pos3, key3)); } else { result = Result.unchanged(this); } } else if (mask == pos2) { if (cmp.compare(key, key2) == 0) { // remove key2, val2 result = Result.modified(valNodeOf(mutator, pos1, key1, pos3, key3)); } else { result = Result.unchanged(this); } } else if (mask == pos3) { if (cmp.compare(key, key3) == 0) { // remove key3, val3 result = Result.modified(valNodeOf(mutator, pos1, key1, pos2, key2)); } else { result = Result.unchanged(this); } } else { result = Result.unchanged(this); } return result; } private CompactSetNode<K> inlineValue(AtomicReference<Thread> mutator, byte mask, K key) { if (mask < pos1) { return valNodeOf(mutator, mask, key, pos1, key1, pos2, key2, pos3, key3); } else if (mask < pos2) { return valNodeOf(mutator, pos1, key1, mask, key, pos2, key2, pos3, key3); } else if (mask < pos3) { return valNodeOf(mutator, pos1, key1, pos2, key2, mask, key, pos3, key3); } else { return valNodeOf(mutator, pos1, key1, pos2, key2, pos3, key3, mask, key); } } @Override boolean containsKey(Object key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == pos1 && key.equals(key1)) { return true; } else if (mask == pos2 && key.equals(key2)) { return true; } else if (mask == pos3 && key.equals(key3)) { return true; } else { return false; } } @Override boolean containsKey(Object key, int keyHash, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == pos1 && cmp.compare(key, key1) == 0) { return true; } else if (mask == pos2 && cmp.compare(key, key2) == 0) { return true; } else if (mask == pos3 && cmp.compare(key, key3) == 0) { return true; } else { return false; } } @Override Optional<K> findByKey(Object key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == pos1 && key.equals(key1)) { return Optional.of(key1); } else if (mask == pos2 && key.equals(key2)) { return Optional.of(key2); } else if (mask == pos3 && key.equals(key3)) { return Optional.of(key3); } else { return Optional.empty(); } } @Override Optional<K> findByKey(Object key, int keyHash, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == pos1 && cmp.compare(key, key1) == 0) { return Optional.of(key1); } else if (mask == pos2 && cmp.compare(key, key2) == 0) { return Optional.of(key2); } else if (mask == pos3 && cmp.compare(key, key3) == 0) { return Optional.of(key3); } else { return Optional.empty(); } } @SuppressWarnings("unchecked") @Override Iterator<CompactSetNode<K>> nodeIterator() { return Collections.emptyIterator(); } @Override boolean hasNodes() { return false; } @Override int nodeArity() { return 0; } @Override SupplierIterator<K, K> payloadIterator() { return ArrayKeyValueIterator.of(new Object[] { key1, key1, key2, key2, key3, key3 }); } @Override boolean hasPayload() { return true; } @Override int payloadArity() { return 3; } @Override K headKey() { return key1; } @Override AbstractSetNode<K> getNode(int index) { throw new IllegalStateException("Index out of range."); } @Override K getKey(int index) { switch (index) { case 0: return key1; case 1: return key2; case 2: return key3; default: throw new IllegalStateException("Index out of range."); } } @Override byte sizePredicate() { return SIZE_MORE_THAN_ONE; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + pos1; result = prime * result + key1.hashCode(); result = prime * result + pos2; result = prime * result + key2.hashCode(); result = prime * result + pos3; result = prime * result + key3.hashCode(); return result; } @Override public boolean equals(Object other) { if (null == other) { return false; } if (this == other) { return true; } if (getClass() != other.getClass()) { return false; } Set3To0Node<?> that = (Set3To0Node<?>) other; if (pos1 != that.pos1) { return false; } if (!key1.equals(that.key1)) { return false; } if (pos2 != that.pos2) { return false; } if (!key2.equals(that.key2)) { return false; } if (pos3 != that.pos3) { return false; } if (!key3.equals(that.key3)) { return false; } return true; } @Override public String toString() { return String.format("[@%d: %s, @%d: %s, @%d: %s]", pos1, key1, pos2, key2, pos3, key3); } } private static final class Set3To1Node<K> extends CompactSetNode<K> { private final byte pos1; private final K key1; private final byte pos2; private final K key2; private final byte pos3; private final K key3; private final byte npos1; private final CompactSetNode<K> node1; Set3To1Node(final AtomicReference<Thread> mutator, final byte pos1, final K key1, final byte pos2, final K key2, final byte pos3, final K key3, final byte npos1, final CompactSetNode<K> node1) { this.pos1 = pos1; this.key1 = key1; this.pos2 = pos2; this.key2 = key2; this.pos3 = pos3; this.key3 = key3; this.npos1 = npos1; this.node1 = node1; assert nodeInvariant(); } @Override Result<K, Void, ? extends CompactSetNode<K>> updated(AtomicReference<Thread> mutator, K key, int keyHash, Void val, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == pos1) { if (key.equals(key1)) { result = Result.unchanged(this); } else { // merge into node final CompactSetNode<K> node = mergeNodes(key1, key1.hashCode(), key, keyHash, shift + BIT_PARTITION_SIZE); if (mask < npos1) { result = Result.modified(valNodeOf(mutator, pos2, key2, pos3, key3, mask, node, npos1, node1)); } else { result = Result.modified(valNodeOf(mutator, pos2, key2, pos3, key3, npos1, node1, mask, node)); } } } else if (mask == pos2) { if (key.equals(key2)) { result = Result.unchanged(this); } else { // merge into node final CompactSetNode<K> node = mergeNodes(key2, key2.hashCode(), key, keyHash, shift + BIT_PARTITION_SIZE); if (mask < npos1) { result = Result.modified(valNodeOf(mutator, pos1, key1, pos3, key3, mask, node, npos1, node1)); } else { result = Result.modified(valNodeOf(mutator, pos1, key1, pos3, key3, npos1, node1, mask, node)); } } } else if (mask == pos3) { if (key.equals(key3)) { result = Result.unchanged(this); } else { // merge into node final CompactSetNode<K> node = mergeNodes(key3, key3.hashCode(), key, keyHash, shift + BIT_PARTITION_SIZE); if (mask < npos1) { result = Result.modified(valNodeOf(mutator, pos1, key1, pos2, key2, mask, node, npos1, node1)); } else { result = Result.modified(valNodeOf(mutator, pos1, key1, pos2, key2, npos1, node1, mask, node)); } } } else if (mask == npos1) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node1.updated( mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactSetNode<K> thisNew = valNodeOf(mutator, pos1, key1, pos2, key2, pos3, key3, mask, nestedResult.getNode()); result = Result.modified(thisNew); } else { result = Result.unchanged(this); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key)); } return result; } @Override Result<K, Void, ? extends CompactSetNode<K>> updated(AtomicReference<Thread> mutator, K key, int keyHash, Void val, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == pos1) { if (cmp.compare(key, key1) == 0) { result = Result.unchanged(this); } else { // merge into node final CompactSetNode<K> node = mergeNodes(key1, key1.hashCode(), key, keyHash, shift + BIT_PARTITION_SIZE); if (mask < npos1) { result = Result.modified(valNodeOf(mutator, pos2, key2, pos3, key3, mask, node, npos1, node1)); } else { result = Result.modified(valNodeOf(mutator, pos2, key2, pos3, key3, npos1, node1, mask, node)); } } } else if (mask == pos2) { if (cmp.compare(key, key2) == 0) { result = Result.unchanged(this); } else { // merge into node final CompactSetNode<K> node = mergeNodes(key2, key2.hashCode(), key, keyHash, shift + BIT_PARTITION_SIZE); if (mask < npos1) { result = Result.modified(valNodeOf(mutator, pos1, key1, pos3, key3, mask, node, npos1, node1)); } else { result = Result.modified(valNodeOf(mutator, pos1, key1, pos3, key3, npos1, node1, mask, node)); } } } else if (mask == pos3) { if (cmp.compare(key, key3) == 0) { result = Result.unchanged(this); } else { // merge into node final CompactSetNode<K> node = mergeNodes(key3, key3.hashCode(), key, keyHash, shift + BIT_PARTITION_SIZE); if (mask < npos1) { result = Result.modified(valNodeOf(mutator, pos1, key1, pos2, key2, mask, node, npos1, node1)); } else { result = Result.modified(valNodeOf(mutator, pos1, key1, pos2, key2, npos1, node1, mask, node)); } } } else if (mask == npos1) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node1.updated( mutator, key, keyHash, val, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactSetNode<K> thisNew = valNodeOf(mutator, pos1, key1, pos2, key2, pos3, key3, mask, nestedResult.getNode()); result = Result.modified(thisNew); } else { result = Result.unchanged(this); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key)); } return result; } @Override Result<K, Void, ? extends CompactSetNode<K>> removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == pos1) { if (key.equals(key1)) { // remove key1, val1 result = Result.modified(valNodeOf(mutator, pos2, key2, pos3, key3, npos1, node1)); } else { result = Result.unchanged(this); } } else if (mask == pos2) { if (key.equals(key2)) { // remove key2, val2 result = Result.modified(valNodeOf(mutator, pos1, key1, pos3, key3, npos1, node1)); } else { result = Result.unchanged(this); } } else if (mask == pos3) { if (key.equals(key3)) { // remove key3, val3 result = Result.modified(valNodeOf(mutator, pos1, key1, pos2, key2, npos1, node1)); } else { result = Result.unchanged(this); } } else if (mask == npos1) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node1.removed( mutator, key, keyHash, shift + BIT_PARTITION_SIZE); if (nestedResult.isModified()) { final CompactSetNode<K> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(removeNode1AndInlineValue(mutator, mask, updatedNode.headKey())); break; case SIZE_MORE_THAN_ONE: // update node1 result = Result.modified(valNodeOf(mutator, pos1, key1, pos2, key2, pos3, key3, mask, updatedNode)); break; default: throw new IllegalStateException("Size predicate violates node invariant."); } } else { result = Result.unchanged(this); } } else { result = Result.unchanged(this); } return result; } @Override Result<K, Void, ? extends CompactSetNode<K>> removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == pos1) { if (cmp.compare(key, key1) == 0) { // remove key1, val1 result = Result.modified(valNodeOf(mutator, pos2, key2, pos3, key3, npos1, node1)); } else { result = Result.unchanged(this); } } else if (mask == pos2) { if (cmp.compare(key, key2) == 0) { // remove key2, val2 result = Result.modified(valNodeOf(mutator, pos1, key1, pos3, key3, npos1, node1)); } else { result = Result.unchanged(this); } } else if (mask == pos3) { if (cmp.compare(key, key3) == 0) { // remove key3, val3 result = Result.modified(valNodeOf(mutator, pos1, key1, pos2, key2, npos1, node1)); } else { result = Result.unchanged(this); } } else if (mask == npos1) { final Result<K, Void, ? extends CompactSetNode<K>> nestedResult = node1.removed( mutator, key, keyHash, shift + BIT_PARTITION_SIZE, cmp); if (nestedResult.isModified()) { final CompactSetNode<K> updatedNode = nestedResult.getNode(); switch (updatedNode.sizePredicate()) { case SIZE_ONE: // inline sub-node value result = Result.modified(removeNode1AndInlineValue(mutator, mask, updatedNode.headKey())); break; case SIZE_MORE_THAN_ONE: // update node1 result = Result.modified(valNodeOf(mutator, pos1, key1, pos2, key2, pos3, key3, mask, updatedNode)); break; default: throw new IllegalStateException("Size predicate violates node invariant."); } } else { result = Result.unchanged(this); } } else { result = Result.unchanged(this); } return result; } private CompactSetNode<K> inlineValue(AtomicReference<Thread> mutator, byte mask, K key) { if (mask < pos1) { return valNodeOf(mutator, mask, key, pos1, key1, pos2, key2, pos3, key3, npos1, node1); } else if (mask < pos2) { return valNodeOf(mutator, pos1, key1, mask, key, pos2, key2, pos3, key3, npos1, node1); } else if (mask < pos3) { return valNodeOf(mutator, pos1, key1, pos2, key2, mask, key, pos3, key3, npos1, node1); } else { return valNodeOf(mutator, pos1, key1, pos2, key2, pos3, key3, mask, key, npos1, node1); } } private CompactSetNode<K> removeNode1AndInlineValue(AtomicReference<Thread> mutator, byte mask, K key) { if (mask < pos1) { return valNodeOf(mutator, mask, key, pos1, key1, pos2, key2, pos3, key3); } else if (mask < pos2) { return valNodeOf(mutator, pos1, key1, mask, key, pos2, key2, pos3, key3); } else if (mask < pos3) { return valNodeOf(mutator, pos1, key1, pos2, key2, mask, key, pos3, key3); } else { return valNodeOf(mutator, pos1, key1, pos2, key2, pos3, key3, mask, key); } } @Override boolean containsKey(Object key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == pos1 && key.equals(key1)) { return true; } else if (mask == pos2 && key.equals(key2)) { return true; } else if (mask == pos3 && key.equals(key3)) { return true; } else if (mask == npos1) { return node1.containsKey(key, keyHash, shift + BIT_PARTITION_SIZE); } else { return false; } } @Override boolean containsKey(Object key, int keyHash, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == pos1 && cmp.compare(key, key1) == 0) { return true; } else if (mask == pos2 && cmp.compare(key, key2) == 0) { return true; } else if (mask == pos3 && cmp.compare(key, key3) == 0) { return true; } else if (mask == npos1) { return node1.containsKey(key, keyHash, shift + BIT_PARTITION_SIZE, cmp); } else { return false; } } @Override Optional<K> findByKey(Object key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == pos1 && key.equals(key1)) { return Optional.of(key1); } else if (mask == pos2 && key.equals(key2)) { return Optional.of(key2); } else if (mask == pos3 && key.equals(key3)) { return Optional.of(key3); } else if (mask == npos1) { return node1.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE); } else { return Optional.empty(); } } @Override Optional<K> findByKey(Object key, int keyHash, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == pos1 && cmp.compare(key, key1) == 0) { return Optional.of(key1); } else if (mask == pos2 && cmp.compare(key, key2) == 0) { return Optional.of(key2); } else if (mask == pos3 && cmp.compare(key, key3) == 0) { return Optional.of(key3); } else if (mask == npos1) { return node1.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE, cmp); } else { return Optional.empty(); } } @SuppressWarnings("unchecked") @Override Iterator<CompactSetNode<K>> nodeIterator() { return ArrayIterator.<CompactSetNode<K>> of(new CompactSetNode[] { node1 }); } @Override boolean hasNodes() { return true; } @Override int nodeArity() { return 1; } @Override SupplierIterator<K, K> payloadIterator() { return ArrayKeyValueIterator.of(new Object[] { key1, key1, key2, key2, key3, key3 }); } @Override boolean hasPayload() { return true; } @Override int payloadArity() { return 3; } @Override K headKey() { return key1; } @Override AbstractSetNode<K> getNode(int index) { switch (index) { case 0: return node1; default: throw new IllegalStateException("Index out of range."); } } @Override K getKey(int index) { switch (index) { case 0: return key1; case 1: return key2; case 2: return key3; default: throw new IllegalStateException("Index out of range."); } } @Override byte sizePredicate() { return SIZE_MORE_THAN_ONE; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + pos1; result = prime * result + key1.hashCode(); result = prime * result + pos2; result = prime * result + key2.hashCode(); result = prime * result + pos3; result = prime * result + key3.hashCode(); result = prime * result + npos1; result = prime * result + node1.hashCode(); return result; } @Override public boolean equals(Object other) { if (null == other) { return false; } if (this == other) { return true; } if (getClass() != other.getClass()) { return false; } Set3To1Node<?> that = (Set3To1Node<?>) other; if (pos1 != that.pos1) { return false; } if (!key1.equals(that.key1)) { return false; } if (pos2 != that.pos2) { return false; } if (!key2.equals(that.key2)) { return false; } if (pos3 != that.pos3) { return false; } if (!key3.equals(that.key3)) { return false; } if (npos1 != that.npos1) { return false; } if (!node1.equals(that.node1)) { return false; } return true; } @Override public String toString() { return String.format("[@%d: %s, @%d: %s, @%d: %s, @%d: %s]", pos1, key1, pos2, key2, pos3, key3, npos1, node1); } } private static final class Set4To0Node<K> extends CompactSetNode<K> { private final byte pos1; private final K key1; private final byte pos2; private final K key2; private final byte pos3; private final K key3; private final byte pos4; private final K key4; Set4To0Node(final AtomicReference<Thread> mutator, final byte pos1, final K key1, final byte pos2, final K key2, final byte pos3, final K key3, final byte pos4, final K key4) { this.pos1 = pos1; this.key1 = key1; this.pos2 = pos2; this.key2 = key2; this.pos3 = pos3; this.key3 = key3; this.pos4 = pos4; this.key4 = key4; assert nodeInvariant(); } @Override Result<K, Void, ? extends CompactSetNode<K>> updated(AtomicReference<Thread> mutator, K key, int keyHash, Void val, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == pos1) { if (key.equals(key1)) { result = Result.unchanged(this); } else { // merge into node final CompactSetNode<K> node = mergeNodes(key1, key1.hashCode(), key, keyHash, shift + BIT_PARTITION_SIZE); result = Result.modified(valNodeOf(mutator, pos2, key2, pos3, key3, pos4, key4, mask, node)); } } else if (mask == pos2) { if (key.equals(key2)) { result = Result.unchanged(this); } else { // merge into node final CompactSetNode<K> node = mergeNodes(key2, key2.hashCode(), key, keyHash, shift + BIT_PARTITION_SIZE); result = Result.modified(valNodeOf(mutator, pos1, key1, pos3, key3, pos4, key4, mask, node)); } } else if (mask == pos3) { if (key.equals(key3)) { result = Result.unchanged(this); } else { // merge into node final CompactSetNode<K> node = mergeNodes(key3, key3.hashCode(), key, keyHash, shift + BIT_PARTITION_SIZE); result = Result.modified(valNodeOf(mutator, pos1, key1, pos2, key2, pos4, key4, mask, node)); } } else if (mask == pos4) { if (key.equals(key4)) { result = Result.unchanged(this); } else { // merge into node final CompactSetNode<K> node = mergeNodes(key4, key4.hashCode(), key, keyHash, shift + BIT_PARTITION_SIZE); result = Result.modified(valNodeOf(mutator, pos1, key1, pos2, key2, pos3, key3, mask, node)); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key)); } return result; } @Override Result<K, Void, ? extends CompactSetNode<K>> updated(AtomicReference<Thread> mutator, K key, int keyHash, Void val, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == pos1) { if (cmp.compare(key, key1) == 0) { result = Result.unchanged(this); } else { // merge into node final CompactSetNode<K> node = mergeNodes(key1, key1.hashCode(), key, keyHash, shift + BIT_PARTITION_SIZE); result = Result.modified(valNodeOf(mutator, pos2, key2, pos3, key3, pos4, key4, mask, node)); } } else if (mask == pos2) { if (cmp.compare(key, key2) == 0) { result = Result.unchanged(this); } else { // merge into node final CompactSetNode<K> node = mergeNodes(key2, key2.hashCode(), key, keyHash, shift + BIT_PARTITION_SIZE); result = Result.modified(valNodeOf(mutator, pos1, key1, pos3, key3, pos4, key4, mask, node)); } } else if (mask == pos3) { if (cmp.compare(key, key3) == 0) { result = Result.unchanged(this); } else { // merge into node final CompactSetNode<K> node = mergeNodes(key3, key3.hashCode(), key, keyHash, shift + BIT_PARTITION_SIZE); result = Result.modified(valNodeOf(mutator, pos1, key1, pos2, key2, pos4, key4, mask, node)); } } else if (mask == pos4) { if (cmp.compare(key, key4) == 0) { result = Result.unchanged(this); } else { // merge into node final CompactSetNode<K> node = mergeNodes(key4, key4.hashCode(), key, keyHash, shift + BIT_PARTITION_SIZE); result = Result.modified(valNodeOf(mutator, pos1, key1, pos2, key2, pos3, key3, mask, node)); } } else { // no value result = Result.modified(inlineValue(mutator, mask, key)); } return result; } @Override Result<K, Void, ? extends CompactSetNode<K>> removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == pos1) { if (key.equals(key1)) { // remove key1, val1 result = Result.modified(valNodeOf(mutator, pos2, key2, pos3, key3, pos4, key4)); } else { result = Result.unchanged(this); } } else if (mask == pos2) { if (key.equals(key2)) { // remove key2, val2 result = Result.modified(valNodeOf(mutator, pos1, key1, pos3, key3, pos4, key4)); } else { result = Result.unchanged(this); } } else if (mask == pos3) { if (key.equals(key3)) { // remove key3, val3 result = Result.modified(valNodeOf(mutator, pos1, key1, pos2, key2, pos4, key4)); } else { result = Result.unchanged(this); } } else if (mask == pos4) { if (key.equals(key4)) { // remove key4, val4 result = Result.modified(valNodeOf(mutator, pos1, key1, pos2, key2, pos3, key3)); } else { result = Result.unchanged(this); } } else { result = Result.unchanged(this); } return result; } @Override Result<K, Void, ? extends CompactSetNode<K>> removed(AtomicReference<Thread> mutator, K key, int keyHash, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); final Result<K, Void, ? extends CompactSetNode<K>> result; if (mask == pos1) { if (cmp.compare(key, key1) == 0) { // remove key1, val1 result = Result.modified(valNodeOf(mutator, pos2, key2, pos3, key3, pos4, key4)); } else { result = Result.unchanged(this); } } else if (mask == pos2) { if (cmp.compare(key, key2) == 0) { // remove key2, val2 result = Result.modified(valNodeOf(mutator, pos1, key1, pos3, key3, pos4, key4)); } else { result = Result.unchanged(this); } } else if (mask == pos3) { if (cmp.compare(key, key3) == 0) { // remove key3, val3 result = Result.modified(valNodeOf(mutator, pos1, key1, pos2, key2, pos4, key4)); } else { result = Result.unchanged(this); } } else if (mask == pos4) { if (cmp.compare(key, key4) == 0) { // remove key4, val4 result = Result.modified(valNodeOf(mutator, pos1, key1, pos2, key2, pos3, key3)); } else { result = Result.unchanged(this); } } else { result = Result.unchanged(this); } return result; } private CompactSetNode<K> inlineValue(AtomicReference<Thread> mutator, byte mask, K key) { if (mask < pos1) { return valNodeOf(mutator, mask, key, pos1, key1, pos2, key2, pos3, key3, pos4, key4); } else if (mask < pos2) { return valNodeOf(mutator, pos1, key1, mask, key, pos2, key2, pos3, key3, pos4, key4); } else if (mask < pos3) { return valNodeOf(mutator, pos1, key1, pos2, key2, mask, key, pos3, key3, pos4, key4); } else if (mask < pos4) { return valNodeOf(mutator, pos1, key1, pos2, key2, pos3, key3, mask, key, pos4, key4); } else { return valNodeOf(mutator, pos1, key1, pos2, key2, pos3, key3, pos4, key4, mask, key); } } @Override boolean containsKey(Object key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == pos1 && key.equals(key1)) { return true; } else if (mask == pos2 && key.equals(key2)) { return true; } else if (mask == pos3 && key.equals(key3)) { return true; } else if (mask == pos4 && key.equals(key4)) { return true; } else { return false; } } @Override boolean containsKey(Object key, int keyHash, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == pos1 && cmp.compare(key, key1) == 0) { return true; } else if (mask == pos2 && cmp.compare(key, key2) == 0) { return true; } else if (mask == pos3 && cmp.compare(key, key3) == 0) { return true; } else if (mask == pos4 && cmp.compare(key, key4) == 0) { return true; } else { return false; } } @Override Optional<K> findByKey(Object key, int keyHash, int shift) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == pos1 && key.equals(key1)) { return Optional.of(key1); } else if (mask == pos2 && key.equals(key2)) { return Optional.of(key2); } else if (mask == pos3 && key.equals(key3)) { return Optional.of(key3); } else if (mask == pos4 && key.equals(key4)) { return Optional.of(key4); } else { return Optional.empty(); } } @Override Optional<K> findByKey(Object key, int keyHash, int shift, Comparator<Object> cmp) { final byte mask = (byte) ((keyHash >>> shift) & BIT_PARTITION_MASK); if (mask == pos1 && cmp.compare(key, key1) == 0) { return Optional.of(key1); } else if (mask == pos2 && cmp.compare(key, key2) == 0) { return Optional.of(key2); } else if (mask == pos3 && cmp.compare(key, key3) == 0) { return Optional.of(key3); } else if (mask == pos4 && cmp.compare(key, key4) == 0) { return Optional.of(key4); } else { return Optional.empty(); } } @SuppressWarnings("unchecked") @Override Iterator<CompactSetNode<K>> nodeIterator() { return Collections.emptyIterator(); } @Override boolean hasNodes() { return false; } @Override int nodeArity() { return 0; } @Override SupplierIterator<K, K> payloadIterator() { return ArrayKeyValueIterator.of(new Object[] { key1, key1, key2, key2, key3, key3, key4, key4 }); } @Override boolean hasPayload() { return true; } @Override int payloadArity() { return 4; } @Override K headKey() { return key1; } @Override AbstractSetNode<K> getNode(int index) { throw new IllegalStateException("Index out of range."); } @Override K getKey(int index) { switch (index) { case 0: return key1; case 1: return key2; case 2: return key3; case 3: return key4; default: throw new IllegalStateException("Index out of range."); } } @Override byte sizePredicate() { return SIZE_MORE_THAN_ONE; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + pos1; result = prime * result + key1.hashCode(); result = prime * result + pos2; result = prime * result + key2.hashCode(); result = prime * result + pos3; result = prime * result + key3.hashCode(); result = prime * result + pos4; result = prime * result + key4.hashCode(); return result; } @Override public boolean equals(Object other) { if (null == other) { return false; } if (this == other) { return true; } if (getClass() != other.getClass()) { return false; } Set4To0Node<?> that = (Set4To0Node<?>) other; if (pos1 != that.pos1) { return false; } if (!key1.equals(that.key1)) { return false; } if (pos2 != that.pos2) { return false; } if (!key2.equals(that.key2)) { return false; } if (pos3 != that.pos3) { return false; } if (!key3.equals(that.key3)) { return false; } if (pos4 != that.pos4) { return false; } if (!key4.equals(that.key4)) { return false; } return true; } @Override public String toString() { return String.format("[@%d: %s, @%d: %s, @%d: %s, @%d: %s]", pos1, key1, pos2, key2, pos3, key3, pos4, key4); } } }
package me.benjozork.onyx.game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.Screen; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator; import com.badlogic.gdx.math.Polygon; import me.benjozork.onyx.entity.EnemyEntity; import me.benjozork.onyx.entity.Entity; import me.benjozork.onyx.entity.PlayerEntity; import me.benjozork.onyx.internal.GameManager; import me.benjozork.onyx.object.TextComponent; import me.benjozork.onyx.specialeffect.crossfade.CrossFadeColorEffect; import me.benjozork.onyx.specialeffect.crossfade.CrossFadeColorEffectConfiguration; import me.benjozork.onyx.specialeffect.zoompulse.ZoomPulseEffect; import me.benjozork.onyx.specialeffect.zoompulse.ZoomPulseEffectConfiguration; import me.benjozork.onyx.utils.PolygonHelper; import me.benjozork.onyx.utils.Utils; /** * Manages the logic when a level is being played.<br/> * Use {@link GameScreenManager} to interact with this {@link Screen}'s contents. * * @author Benjozork */ public class GameScreen implements Screen { private final Color INITIAL_BACKGROUND_COLOR = Color.RED; private float maxFrameTime; private FreeTypeFontGenerator.FreeTypeFontParameter parameter = new FreeTypeFontGenerator.FreeTypeFontParameter(); private TextComponent scoreText; private Color backgroundColor = INITIAL_BACKGROUND_COLOR.cpy(); private PlayerEntity player; private EnemyEntity enemy; private OrthographicCamera worldCam, guiCam; private Sprite background; private Sprite lifeIcon; private SpriteBatch batch; // Crossfading private CrossFadeColorEffect crossFadeBackgroundColor; // Zooming private ZoomPulseEffect zoomPulseCamera; @Override public void show() { // Setup player PlayerEntity player = new PlayerEntity(Utils.getCenterPos(78), 50); GameScreenManager.setPlayer(player); player.setMaxSpeed(600f); GameScreenManager.addEntity(player); this.player = player; this.enemy = enemy; // Setup cameras worldCam = GameManager.getWorldCamera(); guiCam = GameManager.getGuiCamera(); batch = GameManager.getBatch(); // Setup background background = new Sprite(new Texture("hud/background_base.png")); background.setPosition(0, 0); background.setColor(backgroundColor); background.setSize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); // Setup life icons lifeIcon = new Sprite(new Texture("hud/ship_silouhette.png")); lifeIcon.setScale(0.4f, 0.4f); // Setup CrossFadeColorEffect CrossFadeColorEffectConfiguration crossFadeConfig = new CrossFadeColorEffectConfiguration(); crossFadeConfig.cycleColors.addAll(Color.BLUE, Color.RED, Color.GREEN); crossFadeConfig.crossFadeTime = .5f; crossFadeConfig.crossFadeDeltaTimeStepRequirement = 32f; crossFadeConfig.fadeOutDeltaMultiplier = 3f; crossFadeBackgroundColor = new CrossFadeColorEffect(crossFadeConfig, backgroundColor); // Setup ZoomPulseEffect ZoomPulseEffectConfiguration zoomPulseConfig = new ZoomPulseEffectConfiguration(); zoomPulseConfig.maxZoomTime = 1f; zoomPulseConfig.targetZoom = 0.5f; zoomPulseCamera = new ZoomPulseEffect(zoomPulseConfig, worldCam, guiCam); scoreText = new TextComponent(String.valueOf(GameScreenManager.getScore())); } public void update(float delta) { // Update cameras worldCam.update(); guiCam.update(); // Update DrawState of player if (player.isFiring()) { player.setState(PlayerEntity.DrawState.FIRING); } if (player.getVelocity().len() != 0) { player.setState(PlayerEntity.DrawState.MOVING); if (player.isFiring()) { player.setState(PlayerEntity.DrawState.FIRING_MOVING); } } if (! player.isFiring() && player.getVelocity().len() == 0f) { player.setState(PlayerEntity.DrawState.IDLE); } // Update input if (! Gdx.input.isKeyPressed(Input.Keys.A) && ! Gdx.input.isKeyPressed(Input.Keys.D)) { player.setDirection(PlayerEntity.Direction.STRAIGHT); } if (Gdx.input.isKeyPressed(Input.Keys.D)) { player.setDirection(PlayerEntity.Direction.RIGHT); player.accelerate(100f); } if (Gdx.input.isKeyPressed(Input.Keys.A)) { player.setDirection(PlayerEntity.Direction.LEFT); player.accelerate(100f); } /*if (Gdx.input.isKeyPressed(Input.Keys.W)) { player.accelerate(100f); } if (Gdx.input.isKeyPressed(Input.Keys.S)) { player.accelerate(-100f); }*/ if (Gdx.input.isKeyPressed(Input.Keys.SPACE)) { player.fireProjectile("entity/player/bullet.png"); } if (Gdx.input.isKeyJustPressed(Input.Keys.SPACE)) { if (crossFadeBackgroundColor.isActive()) crossFadeBackgroundColor.pause(); else crossFadeBackgroundColor.resume(); } if (Gdx.input.isKeyJustPressed(Input.Keys.ALT_LEFT)) { zoomPulseCamera.toggle(); } // Update crossfade crossFadeBackgroundColor.update(); // Update zoom pulse zoomPulseCamera.update(); scoreText.setText(String.valueOf(GameScreenManager.getScore())); if (GameScreenManager.getEnemies().size == 0) GameScreenManager.generateRandomEnemyWave(5, 15, 0, 1920, 500, 1200); // Update maxFrametime if (delta > maxFrameTime) { maxFrameTime = delta; } } public void render(float delta) { // Update update(delta); // Draw background background.setColor(backgroundColor); background.setSize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); batch.disableBlending(); batch.setProjectionMatrix(guiCam.combined); background.draw(batch); // Draw life icons batch.enableBlending(); for (int i = 0; i < GameScreenManager.getMaxLives(); i++) { lifeIcon.setColor(backgroundColor); lifeIcon.setPosition(20 + i * (lifeIcon.getTexture().getWidth() * 0.5f), 0); lifeIcon.draw(batch); } // Draw score text scoreText.draw(batch, Gdx.graphics.getWidth() - 20, 20); batch.setProjectionMatrix(worldCam.combined); // Update then draw entities for (Entity e : GameScreenManager.getEntities()) { e.update(delta); // This call updates the Drawable class internally } for (Entity e : GameScreenManager.getEntities()) { e.update(); } for (Entity e : GameScreenManager.getEntities()) { e.draw(); } /* Note for all: Whenever collision seems to stop working, instead of thinking the system is broken, check for some subtle errors in your code, but just to be sure, you may uncomment the next line */ //collisionCheck(); // Remove entities that need to be GameScreenManager.flushEntities(); batch.end(); GameManager.getShapeRenderer().end(); } @Override public void resize(int width, int height) { worldCam.viewportWidth = width; worldCam.viewportHeight = height; guiCam.viewportWidth = width; guiCam.viewportHeight = height; } @Override public void pause() { } @Override public void resume() { } @Override public void hide() { } @Override public void dispose() { GameScreenManager.dispose(); scoreText.dispose(); } public EnemyEntity getEnemy() { return enemy; } private void collisionCheck() { //Collision detection test code Polygon p1 = PolygonHelper.getPolygon((float) (100+Math.random()*400),(float) (100+Math.random()*400),(float) (100+Math.random()*400),(float) (100+Math.random()*400)); Polygon p2 = PolygonHelper.getPolygon((float) (100+Math.random()*400),(float) (100+Math.random()*400),(float) (100+Math.random()*400),(float) (100+Math.random()*400)); // Polygon p1 = new Polygon(new float[]{(float) Math.random()*200f,(float) Math.random()*200f,(float) Math.random()*200f,(float) Math.random()*200f,(float) Math.random()*200f,(float) Math.random()*200f}); // Polygon p2 = new Polygon(new float[]{(float) Math.random()*200f,(float) Math.random()*200f,(float) Math.random()*200f,(float) Math.random()*200f,(float) Math.random()*200f,(float) Math.random()*200f}); GameManager.getShapeRenderer().setColor(Color.GREEN); GameManager.getShapeRenderer().polygon(p1.getTransformedVertices()); GameManager.getShapeRenderer().setColor(Color.BLUE); GameManager.getShapeRenderer().polygon(p2.getTransformedVertices()); System.out.println(PolygonHelper.collidePolygon(p1,p2)); } }
package org.exist.storage; import org.apache.log4j.Logger; import org.exist.EXistException; import org.exist.backup.ConsistencyCheck; import org.exist.backup.ErrorReport; import org.exist.backup.SystemExport; import org.exist.management.AgentFactory; import org.exist.util.Configuration; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.List; import java.util.Properties; public class ConsistencyCheckTask implements SystemTask { private static final Logger LOG = Logger.getLogger(ConsistencyCheckTask.class); private String exportDir; private boolean createBackup = false; private boolean paused = false; private boolean incremental = false; private boolean incrementalCheck = false; private int maxInc = -1; public void configure(Configuration config, Properties properties) throws EXistException { exportDir = properties.getProperty("output", "export"); File dir = new File(exportDir); if (!dir.isAbsolute()) dir = new File((String)config.getProperty(BrokerPool.PROPERTY_DATA_DIR), exportDir); dir.mkdirs(); exportDir = dir.getAbsolutePath(); if (LOG.isDebugEnabled()) LOG.debug("Using output directory " + exportDir); String backup = properties.getProperty("backup", "no"); createBackup = backup.equalsIgnoreCase("YES"); String inc = properties.getProperty("incremental", "yes"); incremental = inc.equalsIgnoreCase("YES"); String incCheck = properties.getProperty("incremental-check", "no"); incrementalCheck = incCheck.equalsIgnoreCase("YES"); String max = properties.getProperty("max", "-1"); try { maxInc = Integer.parseInt(max); } catch (NumberFormatException e) { throw new EXistException("Parameter 'max' has to be an integer"); } } public void execute(DBBroker broker) throws EXistException { if (paused) { if (LOG.isDebugEnabled()) LOG.debug("Consistency check is paused."); return; } long start = System.currentTimeMillis(); PrintWriter report = null; try { boolean doBackup = createBackup; // TODO: don't use the direct access feature for now. needs more testing List errors = null; if (!incremental || incrementalCheck) { if (LOG.isDebugEnabled()) LOG.debug("Starting consistency check..."); report = openLog(); CheckCallback cb = new CheckCallback(report); ConsistencyCheck check = new ConsistencyCheck(broker, false); errors = check.checkAll(cb); if (!errors.isEmpty()) { if (LOG.isDebugEnabled()) LOG.debug("Errors found: " + errors.size()); doBackup = true; if (fatalErrorsFound(errors)) { if (LOG.isDebugEnabled()) LOG.debug("Fatal errors were found: pausing the consistency check task."); paused = true; } } AgentFactory.getInstance().updateErrors(broker.getBrokerPool(), errors, start); } if (doBackup) { if (LOG.isDebugEnabled()) LOG.debug("Starting backup..."); SystemExport sysexport = new SystemExport(broker, null, false); File exportFile = sysexport.export(exportDir, incremental, maxInc, true, errors); if (LOG.isDebugEnabled()) LOG.debug("Created backup to file: " + exportFile.getAbsolutePath()); } } finally { if (report != null) report.close(); } } private boolean fatalErrorsFound(List errors) { for (int i = 0; i < errors.size(); i++) { ErrorReport error = (ErrorReport) errors.get(i); switch (error.getErrcode()) { // the following errors are considered fatal: export the db and stop the task case ErrorReport.CHILD_COLLECTION : case ErrorReport.RESOURCE_ACCESS_FAILED : return true; } } // no fatal errors return false; } private PrintWriter openLog() throws EXistException { try { File file = SystemExport.getUniqueFile("report", ".log", exportDir); OutputStream os = new BufferedOutputStream(new FileOutputStream(file)); return new PrintWriter(new OutputStreamWriter(os, "UTF-8")); } catch (UnsupportedEncodingException e) { throw new EXistException("ERROR: failed to create report file in " + exportDir, e); } catch (FileNotFoundException e) { throw new EXistException("ERROR: failed to create report file in " + exportDir, e); } } private class CheckCallback implements ConsistencyCheck.ProgressCallback, SystemExport.StatusCallback { private PrintWriter log; private boolean errorFound = false; private CheckCallback(PrintWriter log) { this.log = log; } public void startDocument(String path) { } public void startDocument(String name, int current, int count) { } public void startCollection(String path) { if (errorFound) log.write(" errorFound = false; log.write("COLLECTION: "); log.write(path); log.write('\n'); } public void error(ErrorReport error) { log.write(" log.write(error.toString()); log.write('\n'); } public void error(String message, Throwable exception) { log.write(" log.write("EXPORT ERROR: "); log.write(message); log.write('\n'); exception.printStackTrace(log); } } }
package org.helioviewer.jhv.layers; import org.helioviewer.jhv.base.Region; import org.helioviewer.jhv.camera.Camera; import org.helioviewer.jhv.camera.CameraHelper; import org.helioviewer.jhv.display.Display; import org.helioviewer.jhv.display.Viewport; import org.helioviewer.jhv.imagedata.ImageData; import org.helioviewer.jhv.io.APIRequest; import org.helioviewer.jhv.metadata.HelioviewerMetaData; import org.helioviewer.jhv.metadata.MetaData; import org.helioviewer.jhv.position.Position; import org.helioviewer.jhv.time.TimeUtils; import java.util.ArrayList; import java.util.HashMap; import javax.annotation.Nullable; import org.astrogrid.samp.Message; import org.astrogrid.samp.SampUtils; public class ImageLayers { public static void decode(double factor) { Camera camera = Display.getCamera(); Viewport[] vp = Display.getViewports(); Position viewpoint = camera.getViewpoint(); for (ImageLayer layer : Layers.getImageLayers()) { int i; if ((i = layer.isVisibleIdx()) != -1 && vp[i] != null) { double pixFactor = CameraHelper.getPixelFactor(camera, vp[i]); layer.getView().decode(viewpoint, pixFactor, factor); } } } public static void arrangeMultiView(boolean multiview) { if (multiview) { int ct = 0; for (ImageLayer layer : Layers.getImageLayers()) { if (layer.isEnabled()) { layer.setVisible(ct); ct++; } } } else { for (ImageLayer layer : Layers.getImageLayers()) { if (layer.isEnabled()) layer.setVisible(0); } } Display.reshapeAll(); Display.render(1); } @Nullable public static ImageLayer getImageLayerInViewport(int idx) { for (ImageLayer layer : Layers.getImageLayers()) { if (layer.isVisible(idx)) return layer; } return null; } public static int getNumEnabledImageLayers() { int ct = 0; for (ImageLayer layer : Layers.getImageLayers()) { if (layer.isEnabled()) ct++; } return ct; } public static boolean getSyncedImageLayers(Position viewpoint) { for (ImageLayer layer : Layers.getImageLayers()) { ImageData id; if (layer.isEnabled() && (id = layer.getImageData()) != null && viewpoint != id.getViewpoint() /* deliberate on reference */) return false; } return true; } public static double getLargestPhysicalHeight() { double size = 0; for (ImageLayer layer : Layers.getImageLayers()) { if (layer.isEnabled()) { double newSize = layer.getMetaData().getPhysicalRegion().height; if (newSize > size) size = newSize; } } return size; } public static double getLargestPhysicalSize() { double size = 0; for (ImageLayer layer : Layers.getImageLayers()) { if (layer.isEnabled()) { Region r = layer.getMetaData().getPhysicalRegion(); double newSize = Math.sqrt(r.height * r.height + r.width * r.width); if (newSize > size) size = newSize; } } return size; } public static void syncLayersSpan(long startTime, long endTime, int cadence) { for (ImageLayer layer : Layers.getImageLayers()) { APIRequest req = layer.getAPIRequest(); if (req != null) { layer.load(new APIRequest(req.server, req.sourceId, startTime, endTime, cadence)); } } } public static void shiftLayersSpan(long delta) { for (ImageLayer layer : Layers.getImageLayers()) { APIRequest req = layer.getAPIRequest(); if (req != null) { layer.load(new APIRequest(req.server, req.sourceId, req.startTime + delta, req.endTime + delta, req.cadence)); } } } public static String getSDOCutoutString() { StringBuilder str = new StringBuilder("&wavelengths="); for (ImageLayer layer : Layers.getImageLayers()) { MetaData m; if (layer.isEnabled() && (m = layer.getMetaData()) instanceof HelioviewerMetaData) { HelioviewerMetaData hm = (HelioviewerMetaData) m; if (hm.getObservatory().contains("SDO") && hm.getInstrument().contains("AIA")) str.append(',').append(hm.getMeasurement()); } } ImageLayer activeLayer = Layers.getActiveImageLayer(); if (activeLayer != null) { APIRequest req; if ((req = activeLayer.getAPIRequest()) != null) { str.append("&cadence=").append(req.cadence).append("&cadenceUnits=s"); } ImageData id; if ((id = activeLayer.getImageData()) != null) { Region region = Region.scale(id.getRegion(), 1 / id.getMetaData().getUnitPerArcsec()); str.append(String.format("&xCen=%.1f", region.llx + region.width / 2.)); str.append(String.format("&yCen=%.1f", -(region.lly + region.height / 2.))); str.append(String.format("&width=%.1f", region.width)); str.append(String.format("&height=%.1f", region.height)); } } long start = Movie.getStartTime(); str.append("&startDate=").append(TimeUtils.formatDate(start)); str.append("&startTime=").append(TimeUtils.formatTime(start)); long end = Movie.getEndTime(); str.append("&stopDate=").append(TimeUtils.formatDate(end)); str.append("&stopTime=").append(TimeUtils.formatTime(end)); return str.toString(); } public static void getSAMPMessage(Message msg) { ImageData id; ImageLayer activeLayer = Layers.getActiveImageLayer(); if (activeLayer == null || activeLayer.getAPIRequest() == null || (id = activeLayer.getImageData()) == null) return; msg.addParam("timestamp", Movie.getTime().toString()); msg.addParam("start", TimeUtils.format(Movie.getStartTime())); msg.addParam("end", TimeUtils.format(Movie.getEndTime())); msg.addParam("cadence", SampUtils.encodeLong(activeLayer.getAPIRequest().cadence * 1000L)); msg.addParam("cutout.set", SampUtils.encodeBoolean(true)); Region region = Region.scale(id.getRegion(), 1 / id.getMetaData().getUnitPerArcsec()); msg.addParam("cutout.x0", SampUtils.encodeFloat(region.llx + region.width / 2.)); msg.addParam("cutout.y0", SampUtils.encodeFloat(-(region.lly + region.height / 2.))); msg.addParam("cutout.w", SampUtils.encodeFloat(region.width)); msg.addParam("cutout.h", SampUtils.encodeFloat(region.height)); ArrayList<HashMap<String, String>> layersData = new ArrayList<>(); for (ImageLayer layer : Layers.getImageLayers()) { if (layer.isEnabled()) { if ((id = layer.getImageData()) == null) continue; MetaData m = id.getMetaData(); if (m instanceof HelioviewerMetaData) { HelioviewerMetaData hm = (HelioviewerMetaData) m; HashMap<String, String> layerMsg = new HashMap<>(); layerMsg.put("observatory", hm.getObservatory()); layerMsg.put("instrument", hm.getInstrument()); layerMsg.put("detector", hm.getDetector()); layerMsg.put("measurement", hm.getMeasurement()); layerMsg.put("timestamp", hm.getViewpoint().time.toString()); layersData.add(layerMsg); } } } msg.addParam("layers", layersData); } }
package org.jsapar.schema; import java.io.IOException; import java.io.Reader; import java.io.Writer; import org.jsapar.Cell; import org.jsapar.JSaParException; import org.jsapar.Cell.CellType; import org.jsapar.input.ParseException; import org.jsapar.input.ParsingEventListener; import org.jsapar.output.OutputException; /** * Describes how a cell is represented for a fixed with schema. * * @author stejon0 */ public class FixedWidthSchemaCell extends SchemaCell { /** * Describes how a cell is aligned within its allocated space. * * @author stejon0 * */ public enum Alignment { LEFT, CENTER, RIGHT }; /** * The length of the cell. */ private int length; /** * The alignment of the cell content within the allocated space. Default is Alignment.LEFT. */ private Alignment alignment = Alignment.LEFT; /** * Creates a fixed with schema cell with specified name, length and alignment. * * @param sName * The name of the cell * @param nLength * The length of the cell * @param alignment * The alignment of the cell content within the allocated space */ public FixedWidthSchemaCell(String sName, int nLength, Alignment alignment) { this(sName, nLength); this.alignment = alignment; } /** * Creates a fixed with schema cell with specified name and length. * * @param sName * The name of the cell * @param nLength * The length of the cell */ public FixedWidthSchemaCell(String sName, int nLength) { super(sName); this.length = nLength; } /** * Creates a fixed with schema cell with specified name, length and format. * * @param sName * The name of the cell * @param nLength * The length of the cell * @param cellFormat * The format of the cell */ public FixedWidthSchemaCell(String sName, int nLength, SchemaCellFormat cellFormat) { super(sName, cellFormat); this.length = nLength; } /** * Creates a fixed with schema cell with specified length. * * @param nLength * The length of the cell */ public FixedWidthSchemaCell(int nLength) { this.length = nLength; } /** * Builds a Cell from a reader input. * * @param reader * The input reader * @param trimFillCharacters * If true, fill characters are ignored while reading string values. If the cell is * of any other type, the value is trimmed any way before parsing. * @param fillCharacter * The fill character to ignore if trimFillCharacters is true. * @param nLineNumber * @param listener * @return A Cell filled with the parsed cell value and with the name of this schema cell. * @throws IOException * @throws ParseException */ Cell build(Reader reader, boolean trimFillCharacters, char fillCharacter, ParsingEventListener listener, long nLineNumber) throws IOException, ParseException { int nOffset = 0; int nLength = this.length; // The actual length char[] buffer = new char[nLength]; int nRead = reader.read(buffer, 0, nLength); if (nRead <= 0) { checkIfMandatory(listener, nLineNumber); if (this.length <= 0) return makeCell(EMPTY_STRING); else{ return null; } } nLength = nRead; if (trimFillCharacters || getCellFormat().getCellType() != CellType.STRING) { while (nOffset < nLength && buffer[nOffset] == fillCharacter) { nOffset++; } while (nLength > nOffset && buffer[nLength - 1] == fillCharacter) { nLength } nLength -= nOffset; } Cell cell = makeCell(new String(buffer, nOffset, nLength), listener, nLineNumber); return cell; } /** * @return the length */ public int getLength() { return length; } /** * @param length * the length to set */ public void setLength(int length) { this.length = length; } /** * @param writer * @param ch * @param nSize * @throws IOException */ private static void fill(Writer writer, char ch, int nSize) throws IOException { for (int i = 0; i < nSize; i++) { writer.write(ch); } } /** * Writes an empty cell. Uses the fill character to fill the space. * * @param writer * @param fillCharacter * @throws IOException * @throws JSaParException */ public void outputEmptyCell(Writer writer, char fillCharacter) throws IOException, JSaParException { FixedWidthSchemaCell.fill(writer, fillCharacter, getLength()); } /** * Writes a cell to the supplied writer using supplied fill character. * * @param cell * The cell to write * @param writer * The writer to write to. * @param fillCharacter * The fill character to fill empty spaces. * @throws IOException * @throws OutputException */ void output(Cell cell, Writer writer, char fillCharacter) throws IOException, JSaParException { String sValue = format(cell); output(sValue, writer, fillCharacter, getLength(), getAlignment()); } /** * Writes a cell to the supplied writer using supplied fill character. * * @param cell * The cell to write * @param writer * The writer to write to. * @param fillCharacter * The fill character to fill empty spaces. * @param length * The number of characters to write. * @param alignment * The alignment of the cell content if the content is smaller than the cell length. * @param format * The format to use. * @throws IOException * @throws OutputException */ static void output(String sValue, Writer writer, char fillCharacter, int length, Alignment alignment) throws IOException, OutputException { // If the cell value is larger than the cell length, we have to cut the // value. if (sValue.length() >= length) { writer.write(sValue.substring(0, length)); return; } // Otherwise use the alignment of the schema. int nToFill = length - sValue.length(); switch (alignment) { case LEFT: writer.write(sValue); fill(writer, fillCharacter, nToFill); break; case RIGHT: fill(writer, fillCharacter, nToFill); writer.write(sValue); break; case CENTER: int nLeft = nToFill / 2; fill(writer, fillCharacter, nLeft); writer.write(sValue); fill(writer, fillCharacter, nToFill - nLeft); break; default: throw new OutputException("Unknown allignment style for cell schema."); } } /** * @return the alignment */ public Alignment getAlignment() { return alignment; } /** * @param alignment * the alignment to set */ public void setAlignment(Alignment alignment) { this.alignment = alignment; } /* * (non-Javadoc) * * @see org.jsapar.schema.SchemaCell#clone() */ public FixedWidthSchemaCell clone() throws CloneNotSupportedException { return (FixedWidthSchemaCell) super.clone(); } /* * (non-Javadoc) * * @see org.jsapar.schema.SchemaCell#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(super.toString()); sb.append(" length="); sb.append(this.length); sb.append(" alignment="); sb.append(this.alignment); return sb.toString(); } }
// ZAP: 2012/03/03 Moved popups to stdmenus extension // ZAP: 2012/03/15 Changed to initiate the tree with a default model. Changed to // clear the http panels when the root node is selected. // ZAP: 2012/04/23 Added @Override annotation to all appropriate methods. // ZAP: 2012/06/13 Added custom tree cell renderer to treeSite in getTreeSite(). // ZAP: 2013/01/25 Added method for removing listener. // ZAP: 2013/11/16 Issue 886: Main pop up menu invoked twice on some components // ZAP: 2014/01/28 Issue 207: Support keyboard shortcuts // ZAP: 2014/03/23 Tidy up, removed the instance variable rootTreePath, no need to // cache the path // ZAP: 2014/03/23 Issue 609: Provide a common interface to query the state and // access the data (HttpMessage and HistoryReference) displayed in the tabs // ZAP: 2014/10/07 Issue 1357: Hide unused tabs // ZAP: 2014/12/17 Issue 1174: Support a Site filter // ZAP: 2014/12/22 Issue 1476: Display contexts in the Sites tree // ZAP: 2015/02/09 Issue 1525: Introduce a database interface layer to allow for alternative implementations // ZAP: 2015/02/10 Issue 1528: Support user defined font size // ZAP: 2015/06/01 Issue 1653: Support context menu key for trees // ZAP: 2016/04/14 Use View to display the HTTP messages // ZAP: 2016/07/01 Issue 2642: Slow mouse wheel scrolling in site tree // ZAP: 2017/03/28 Issue 3253: Facilitate exporting URLs by context (add getSelectedContext) // ZAP: 2017/09/02 Use KeyEvent instead of Event (deprecated in Java 9). // ZAP: 2017/11/01 Delete context with keyboard shortcut. // ZAP: 2017/11/16 Hide filtered nodes in macOS L&F. // ZAP: 2017/11/29 Delete site nodes with keyboard shortcut. package org.parosproxy.paros.view; import java.awt.Component; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.swing.AbstractAction; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPopupMenu; import javax.swing.JToggleButton; import javax.swing.JTree; import javax.swing.KeyStroke; import javax.swing.LookAndFeel; import javax.swing.UIManager; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; import org.apache.log4j.Logger; import org.parosproxy.paros.Constant; import org.parosproxy.paros.control.Control; import org.parosproxy.paros.db.DatabaseException; import org.parosproxy.paros.extension.AbstractPanel; import org.parosproxy.paros.extension.history.ExtensionHistory; import org.parosproxy.paros.extension.history.LogPanel; import org.parosproxy.paros.model.HistoryReference; import org.parosproxy.paros.model.Model; import org.parosproxy.paros.model.SiteMap; import org.parosproxy.paros.model.SiteNode; import org.parosproxy.paros.network.HttpMessage; import org.zaproxy.zap.extension.history.HistoryFilterPlusDialog; import org.zaproxy.zap.model.Context; import org.zaproxy.zap.model.Target; import org.zaproxy.zap.utils.DisplayUtils; import org.zaproxy.zap.view.ContextCreateDialog; import org.zaproxy.zap.view.ContextGeneralPanel; import org.zaproxy.zap.view.ContextsSitesPanel; import org.zaproxy.zap.view.ContextsTreeCellRenderer; import org.zaproxy.zap.view.DeleteContextAction; import org.zaproxy.zap.view.LayoutHelper; import org.zaproxy.zap.view.SiteMapListener; import org.zaproxy.zap.view.SiteMapTreeCellRenderer; import org.zaproxy.zap.view.SiteTreeFilter; import org.zaproxy.zap.view.ZapToggleButton; import org.zaproxy.zap.view.messagecontainer.http.DefaultSelectableHistoryReferencesContainer; import org.zaproxy.zap.view.messagecontainer.http.SelectableHistoryReferencesContainer; public class SiteMapPanel extends AbstractPanel { public static final String CONTEXT_TREE_COMPONENT_NAME = "ContextTree"; private static final long serialVersionUID = -3161729504065679088L; // ZAP: Added logger private static Logger log = Logger.getLogger(SiteMapPanel.class); private JTree treeSite = null; private JTree treeContext = null; private DefaultTreeModel contextTree = null; private View view = null; private javax.swing.JToolBar panelToolbar = null; private ZapToggleButton scopeButton = null; private JButton filterButton = null; private JLabel filterStatus = null; private HistoryFilterPlusDialog filterPlusDialog = null; private JButton createContextButton = null; private JButton importContextButton = null; private JButton exportContextButton = null; // ZAP: Added SiteMapListenners private List<SiteMapListener> listeners = new ArrayList<>(); /** * This is the default constructor */ public SiteMapPanel() { super(); initialize(); } private View getView() { if (view == null) { view = View.getSingleton(); } return view; } /** * This method initializes this */ private void initialize() { this.setHideable(false); this.setIcon(new ImageIcon(View.class.getResource("/resource/icon/16/094.png"))); this.setName(Constant.messages.getString("sites.panel.title")); this.setDefaultAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() | KeyEvent.SHIFT_DOWN_MASK, false)); this.setMnemonic(Constant.messages.getChar("sites.panel.mnemonic")); if (Model.getSingleton().getOptionsParam().getViewParam().getWmUiHandlingOption() == 0) { this.setSize(300,200); } this.setLayout(new GridBagLayout()); this.add(this.getPanelToolbar(), LayoutHelper.getGBC(0, 0, 1, 0, new Insets(2,2,2,2))); this.add(new ContextsSitesPanel(getTreeContext(), getTreeSite(), "sitesPanelScrollPane"), LayoutHelper.getGBC(0, 1, 1, 1.0, 1.0, GridBagConstraints.BOTH, new Insets(2,2,2,2))); expandRoot(); } private javax.swing.JToolBar getPanelToolbar() { if (panelToolbar == null) { panelToolbar = new javax.swing.JToolBar(); panelToolbar.setLayout(new GridBagLayout()); panelToolbar.setEnabled(true); panelToolbar.setFloatable(false); panelToolbar.setRollover(true); panelToolbar.setPreferredSize(new Dimension(800,30)); panelToolbar.setName("ScriptsListToolbar"); int i = 1; panelToolbar.add(getScopeButton(), LayoutHelper.getGBC(i++, 0, 1, 0.0D)); panelToolbar.add(getCreateContextButton(), LayoutHelper.getGBC(i++, 0, 1, 0.0D)); panelToolbar.add(getImportContextButton(), LayoutHelper.getGBC(i++, 0, 1, 0.0D)); panelToolbar.add(getExportContextButton(), LayoutHelper.getGBC(i++, 0, 1, 0.0D)); // TODO Disabled for now due to problems with scrolling with sparcely populated filtered trees //panelToolbar.add(getFilterButton(), LayoutHelper.getGBC(i++, 0, 1, 0.0D)); //panelToolbar.add(getFilterStatus(), LayoutHelper.getGBC(i++, 0, 1, 0.0D)); panelToolbar.add(new JLabel(), LayoutHelper.getGBC(20, 0, 1, 1.0D)); // spacer } return panelToolbar; } private HistoryFilterPlusDialog getFilterPlusDialog() { if (filterPlusDialog == null) { filterPlusDialog = new HistoryFilterPlusDialog(getView().getMainFrame(), true); // Override the title as we're reusing the history filter dialog filterPlusDialog.setTitle(Constant.messages.getString("sites.filter.title")); } return filterPlusDialog; } private JLabel getFilterStatus() { filterStatus = new JLabel(Constant.messages.getString("history.filter.label.filter") + Constant.messages.getString("history.filter.label.off")); return filterStatus; } private JButton getFilterButton() { if (filterButton == null) { filterButton = new JButton(); filterButton.setIcon(DisplayUtils.getScaledIcon( new ImageIcon(LogPanel.class.getResource("/resource/icon/16/054.png")))); // 'filter' icon filterButton.setToolTipText(Constant.messages.getString("history.filter.button.filter")); filterButton.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(java.awt.event.ActionEvent e) { showFilterPlusDialog(); } }); } return filterButton; } private JButton getCreateContextButton() { if (createContextButton == null) { createContextButton = new JButton(); createContextButton.setIcon(DisplayUtils.getScaledIcon(new ImageIcon( LogPanel.class.getResource("/resource/icon/fugue/application-blue-plus.png")))); createContextButton.setToolTipText(Constant.messages.getString("menu.file.context.create")); createContextButton.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(java.awt.event.ActionEvent e) { ContextCreateDialog ccd = new ContextCreateDialog(View.getSingleton().getMainFrame()); ccd.setVisible(true); } }); } return createContextButton; } private JButton getImportContextButton() { if (importContextButton == null) { importContextButton = new JButton(); importContextButton.setIcon(DisplayUtils.getScaledIcon(new ImageIcon( LogPanel.class.getResource("/resource/icon/fugue/application-blue-import.png")))); importContextButton.setToolTipText(Constant.messages.getString("menu.file.context.import")); importContextButton.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(java.awt.event.ActionEvent e) { Control.getSingleton().getMenuFileControl().importContext(); } }); } return importContextButton; } private JButton getExportContextButton() { if (exportContextButton == null) { exportContextButton = new JButton(); exportContextButton.setIcon(DisplayUtils.getScaledIcon(new ImageIcon( LogPanel.class.getResource("/resource/icon/fugue/application-blue-export.png")))); exportContextButton.setToolTipText(Constant.messages.getString("menu.file.context.export")); exportContextButton.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(java.awt.event.ActionEvent e) { Control.getSingleton().getMenuFileControl().exportContext(); } }); } return exportContextButton; } private void showFilterPlusDialog() { HistoryFilterPlusDialog dialog = getFilterPlusDialog(); dialog.setModal(true); try { dialog.setAllTags(Model.getSingleton().getDb().getTableTag().getAllTags()); } catch (DatabaseException e) { log.error(e.getMessage(), e); } int exit = dialog.showDialog(); SiteTreeFilter filter = new SiteTreeFilter(dialog.getFilter()); filter.setInScope(this.getScopeButton().isSelected()); if (exit != JOptionPane.CANCEL_OPTION) { setFilter(); } } private void setFilter() { SiteTreeFilter filter = new SiteTreeFilter(getFilterPlusDialog().getFilter()); filter.setInScope(scopeButton.isSelected()); ((SiteMap)treeSite.getModel()).setFilter(filter); ((DefaultTreeModel)treeSite.getModel()).nodeStructureChanged((SiteNode)treeSite.getModel().getRoot()); getFilterStatus().setText(filter.toShortString()); getFilterStatus().setToolTipText(filter.toLongString()); expandRoot(); // Remove any out of scope contexts too this.reloadContextTree(); } private JToggleButton getScopeButton() { if (scopeButton == null) { scopeButton = new ZapToggleButton(); scopeButton.setIcon(DisplayUtils.getScaledIcon(new ImageIcon(SiteMapPanel.class.getResource("/resource/icon/fugue/target-grey.png")))); scopeButton.setToolTipText(Constant.messages.getString("history.scope.button.unselected")); scopeButton.setSelectedIcon(DisplayUtils.getScaledIcon(new ImageIcon(SiteMapPanel.class.getResource("/resource/icon/fugue/target.png")))); scopeButton.setSelectedToolTipText(Constant.messages.getString("history.scope.button.selected")); scopeButton.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(java.awt.event.ActionEvent e) { setFilter(); } }); } return scopeButton; } /** * This method initializes treeSite * * @return javax.swing.JTree */ public JTree getTreeSite() { if (treeSite == null) { treeSite = new JTree(new DefaultTreeModel(new DefaultMutableTreeNode())); treeSite.setShowsRootHandles(true); treeSite.setName("treeSite"); treeSite.setToggleClickCount(1); // Force macOS L&F to query the row height from SiteMapTreeCellRenderer to hide the filtered nodes. // Other L&Fs hide the filtered nodes by default. LookAndFeel laf = UIManager.getLookAndFeel(); if (laf != null && Constant.isMacOsX() && UIManager.getSystemLookAndFeelClassName().equals(laf.getClass().getName())) { treeSite.setRowHeight(0); } treeSite.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() { @Override public void valueChanged(javax.swing.event.TreeSelectionEvent e) { SiteNode node = (SiteNode) treeSite.getLastSelectedPathComponent(); if (node == null) { return; } if (!node.isRoot()) { HttpMessage msg = null; try { msg = node.getHistoryReference().getHttpMessage(); } catch (Exception e1) { // ZAP: Log exceptions log.warn(e1.getMessage(), e1); return; } getView().displayMessage(msg); // ZAP: Call SiteMapListenners for (SiteMapListener listener : listeners) { listener.nodeSelected(node); } } else { // ZAP: clear the views when the root is selected getView().displayMessage(null); } } }); treeSite.setComponentPopupMenu(new SitesCustomPopupMenu()); // ZAP: Add custom tree cell renderer. DefaultTreeCellRenderer renderer = new SiteMapTreeCellRenderer(listeners); treeSite.setCellRenderer(renderer); String deleteSiteNode = "zap.delete.sitenode"; treeSite.getInputMap().put(getView().getDefaultDeleteKeyStroke(), deleteSiteNode); treeSite.getActionMap().put(deleteSiteNode, new AbstractAction() { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { ExtensionHistory extHistory = Control.getSingleton().getExtensionLoader().getExtension( ExtensionHistory.class); if (extHistory == null || treeSite.getSelectionCount() == 0) { return; } int result = View.getSingleton().showConfirmDialog(Constant.messages.getString("sites.purge.warning")); if (result != JOptionPane.YES_OPTION) { return; } SiteMap siteMap = Model.getSingleton().getSession().getSiteTree(); for (TreePath path : treeSite.getSelectionPaths()) { extHistory.purge(siteMap, (SiteNode) path.getLastPathComponent()); } } }); } return treeSite; } public void reloadContextTree() { SiteNode root; if (this.contextTree == null) { root = new SiteNode(null, -1, Constant.messages.getString("context.list")); this.contextTree = new DefaultTreeModel(root); } else { root = (SiteNode)this.contextTree.getRoot(); root.removeAllChildren(); } for (Context ctx : Model.getSingleton().getSession().getContexts()) { if (ctx.isInScope() || ! this.getScopeButton().isSelected()) { // Add all in scope contexts, and out of scope ones if scope button not pressed SiteNode node = new SiteNode(null, HistoryReference.TYPE_PROXIED, ctx.getName()); node.setUserObject(new Target(ctx)); root.add(node); } } this.contextTree.nodeStructureChanged(root); } /** * Returns the Context which is selected in the Site Map panel of the UI * or {@code null} if nothing is selected or the selection is the root node. * * @return Context the context which is selected in the UI * @since 2.7.0 */ public Context getSelectedContext() { SiteNode node = (SiteNode) treeContext.getLastSelectedPathComponent(); if (node == null || node.isRoot()) { return null; } Target target = (Target) node.getUserObject(); if (target != null) { return target.getContext(); } return null; } private JTree getTreeContext() { if (treeContext == null) { reloadContextTree(); treeContext = new JTree(this.contextTree); treeContext.setShowsRootHandles(true); treeContext.setName(CONTEXT_TREE_COMPONENT_NAME); treeContext.setToggleClickCount(1); treeContext.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); treeContext.addMouseListener(new java.awt.event.MouseAdapter() { @Override public void mousePressed(java.awt.event.MouseEvent e) { } @Override public void mouseReleased(java.awt.event.MouseEvent e) { mouseClicked(e); } @Override public void mouseClicked(java.awt.event.MouseEvent e) { if (treeSite.getLastSelectedPathComponent() != null) { // They selected a context node, deselect any context getTreeSite().clearSelection(); } if (e.getClickCount() > 1) { // Its a double click - show the relevant context dialog SiteNode node = (SiteNode) treeContext.getLastSelectedPathComponent(); if (node != null && node.getUserObject() != null) { Target target = (Target)node.getUserObject(); getView().showSessionDialog(Model.getSingleton().getSession(), ContextGeneralPanel.getPanelName(target.getContext())); } } } }); treeContext.setComponentPopupMenu(new ContextsCustomPopupMenu()); treeContext.setCellRenderer(new ContextsTreeCellRenderer()); DeleteContextAction delContextAction = new DeleteContextAction() { private static final long serialVersionUID = 1L; @Override protected Context getContext() { return getSelectedContext(); } }; treeContext.getInputMap().put( (KeyStroke) delContextAction.getValue(DeleteContextAction.ACCELERATOR_KEY), DeleteContextAction.ACTION_NAME); treeContext.getActionMap().put(DeleteContextAction.ACTION_NAME, delContextAction); } return treeContext; } public void expandRoot() { TreeNode root = (TreeNode) treeSite.getModel().getRoot(); if (root == null) { return; } final TreePath rootTreePath = new TreePath(root); if (EventQueue.isDispatchThread()) { getTreeSite().expandPath(rootTreePath); return; } try { EventQueue.invokeLater(new Runnable() { @Override public void run() { getTreeSite().expandPath(rootTreePath); } }); } catch (Exception e) { // ZAP: Log exceptions log.warn(e.getMessage(), e); } } // ZAP: Added addSiteMapListenners public void addSiteMapListener(SiteMapListener listenner) { this.listeners.add(listenner); } public void removeSiteMapListener(SiteMapListener listener) { this.listeners.remove(listener); } public void showInSites (SiteNode node) { TreeNode[] path = node.getPath(); TreePath tp = new TreePath(path); treeSite.setExpandsSelectedPaths(true); treeSite.setSelectionPath(tp); treeSite.scrollPathToVisible(tp); } public void contextChanged(Context c) { getTreeContext(); SiteNode root = (SiteNode)this.contextTree.getRoot(); for (int i=0; i < root.getChildCount(); i++) { SiteNode node = (SiteNode)root.getChildAt(i); Target target = (Target)node.getUserObject(); if (c.getIndex() == target.getContext().getIndex()) { target.setContext(c); if (node.getNodeName().equals(c.getName())) { this.contextTree.nodeChanged(node); } else { this.reloadContextTree(); } break; } } } protected class SitesCustomPopupMenu extends JPopupMenu { private static final long serialVersionUID = 1L; @Override public void show(Component invoker, int x, int y) { // ZAP: Select site list item on right click / menu key TreePath tp = treeSite.getPathForLocation( x, y ); if ( tp != null ) { boolean select = true; // Only select a new item if the current item is not // already selected - this is to allow multiple items // to be selected if (treeSite.getSelectionPaths() != null) { for (TreePath t : treeSite.getSelectionPaths()) { if (t.equals(tp)) { select = false; break; } } } if (select) { treeSite.getSelectionModel().setSelectionPath(tp); } } final int countSelectedNodes = treeSite.getSelectionCount(); final List<HistoryReference> historyReferences = new ArrayList<>(countSelectedNodes); if (countSelectedNodes > 0) { for (TreePath path : treeSite.getSelectionPaths()) { final SiteNode node = (SiteNode) path.getLastPathComponent(); final HistoryReference historyReference = node.getHistoryReference(); if (historyReference != null) { historyReferences.add(historyReference); } } } SelectableHistoryReferencesContainer messageContainer = new DefaultSelectableHistoryReferencesContainer( treeSite.getName(), treeSite, Collections.<HistoryReference> emptyList(), historyReferences); View.getSingleton().getPopupMenu().show(messageContainer, x, y); } } protected class ContextsCustomPopupMenu extends JPopupMenu { private static final long serialVersionUID = 1L; @Override public void show(Component invoker, int x, int y) { // Select context list item on right click TreePath tp = treeContext.getPathForLocation(x, y); if ( tp != null ) { boolean select = true; // Only select a new item if the current item is not // already selected - this is to allow multiple items // to be selected if (treeContext.getSelectionPaths() != null) { for (TreePath t : treeContext.getSelectionPaths()) { if (t.equals(tp)) { select = false; break; } } } if (select) { treeContext.getSelectionModel().setSelectionPath(tp); } } View.getSingleton().getPopupMenu().show(treeContext, x, y); } } }
package org.sugr.gearshift; import android.animation.Animator; import android.animation.AnimatorInflater; import android.animation.ValueAnimator; import android.app.ActionBar; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Configuration; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.preference.PreferenceManager; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.LoaderManager; import android.support.v4.content.Loader; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.text.Html; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.animation.DecelerateInterpolator; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.net.URI; import java.util.ArrayList; public class TorrentListActivity extends FragmentActivity implements TransmissionSessionInterface, TorrentListFragment.Callbacks, TorrentDetailFragment.PagerCallbacks { public static final String ARG_FILE_URI = "torrent_file_uri"; public static final String ARG_FILE_PATH = "torrent_file_path"; public final static String ACTION_OPEN = "torrent_file_open_action"; /** * Whether or not the activity is in two-pane mode, i.e. running on a tablet * device. */ private boolean twoPaneLayout; private TransmissionProfile profile; private TransmissionSession session; private boolean intentConsumed = false; private boolean dialogShown = false; private static final String STATE_INTENT_CONSUMED = "intent_consumed"; private static final String STATE_LOCATION_POSITION = "location_position"; private static final String STATE_CURRENT_PROFILE = "current_profile"; private DrawerLayout drawerLayout; private ActionBarDrawerToggle drawerToggle; private ValueAnimator detailSlideAnimator; private boolean detailPanelVisible; private int locationPosition = AdapterView.INVALID_POSITION; private int currentTorrentIndex = -1; private TransmissionProfileListAdapter profileAdapter; private boolean altSpeed = false; private boolean refreshing = false; private boolean preventRefreshIndicator; private int expecting = 0; private static class Expecting { static int ALT_SPEED_ON = 1; static int ALT_SPEED_OFF = 1 << 1; } private Menu menu; private LoaderManager.LoaderCallbacks<TransmissionProfile[]> profileLoaderCallbacks= new LoaderManager.LoaderCallbacks<TransmissionProfile[]>() { @Override public android.support.v4.content.Loader<TransmissionProfile[]> onCreateLoader( int id, Bundle args) { return new TransmissionProfileSupportLoader(TorrentListActivity.this); } @Override public void onLoadFinished( android.support.v4.content.Loader<TransmissionProfile[]> loader, TransmissionProfile[] profiles) { TransmissionProfile oldProfile = profile; profile = null; profileAdapter.clear(); if (profiles.length > 0) { profileAdapter.addAll(profiles); } else { profileAdapter.add(TransmissionProfileListAdapter.EMPTY_PROFILE); TransmissionProfile.setCurrentProfile(null, TorrentListActivity.this); setRefreshing(false); } String currentId = TransmissionProfile.getCurrentProfileId(TorrentListActivity.this); int index = 0; for (TransmissionProfile prof : profiles) { if (prof.getId().equals(currentId)) { ActionBar actionBar = getActionBar(); if (actionBar != null) actionBar.setSelectedNavigationItem(index); setProfile(prof); break; } index++; } if (profile == null) { if (profiles.length > 0) { setProfile(profiles[0]); } else { setProfile(null); getSupportLoaderManager().destroyLoader(G.TORRENTS_LOADER_ID); /* TODO: should display the message that the user hasn't created a profile yet */ } } else { /* The torrents might be loaded before the navigation * callback fires, which will cause the refresh indicator to * appear until the next server request */ preventRefreshIndicator = true; } if (profile != null && (oldProfile == null || !profile.getId().equals(oldProfile.getId()))) { /* The old cursor will probably already be closed, so start fresh */ getSupportLoaderManager().restartLoader(G.TORRENTS_LOADER_ID, null, torrentLoaderCallbacks); } TransmissionProfile.setCurrentProfile(profile, TorrentListActivity.this); } @Override public void onLoaderReset( android.support.v4.content.Loader<TransmissionProfile[]> loader) { profileAdapter.clear(); } }; private LoaderManager.LoaderCallbacks<TransmissionData> torrentLoaderCallbacks = new LoaderManager.LoaderCallbacks<TransmissionData>() { @Override public android.support.v4.content.Loader<TransmissionData> onCreateLoader( int id, Bundle args) { G.logD("Starting the torrents loader with profile " + profile); if (profile == null) return null; TransmissionDataLoader loader = new TransmissionDataLoader(TorrentListActivity.this, profile); loader.setQueryOnly(true); return loader; } @Override public void onLoadFinished( android.support.v4.content.Loader<TransmissionData> loader, TransmissionData data) { G.logD("Data loaded: " + (data.cursor == null ? 0 : data.cursor.getCount()) + " torrents, error: " + data.error + " , removed: " + data.hasRemoved + ", added: " + data.hasAdded + ", changed: " + data.hasStatusChanged + ", metadata: " + data.hasMetadataNeeded); setSession(data.session); View error = findViewById(R.id.fatal_error_layer); if (data.error == 0 && error.getVisibility() != View.GONE) { error.setVisibility(View.GONE); } if (data.error > 0) { if (data.error == TransmissionData.Errors.DUPLICATE_TORRENT) { Toast.makeText(TorrentListActivity.this, R.string.duplicate_torrent, Toast.LENGTH_SHORT).show(); } else if (data.error == TransmissionData.Errors.INVALID_TORRENT) { Toast.makeText(TorrentListActivity.this, R.string.invalid_torrent, Toast.LENGTH_SHORT).show(); } else { error.setVisibility(View.VISIBLE); TextView text = (TextView) findViewById(R.id.transmission_error); toggleRightPane(false); if (data.error == TransmissionData.Errors.NO_CONNECTIVITY) { text.setText(Html.fromHtml(getString(R.string.no_connectivity_empty_list))); } else if (data.error == TransmissionData.Errors.ACCESS_DENIED) { text.setText(Html.fromHtml(getString(R.string.access_denied_empty_list))); } else if (data.error == TransmissionData.Errors.NO_JSON) { text.setText(Html.fromHtml(getString(R.string.no_json_empty_list))); } else if (data.error == TransmissionData.Errors.NO_CONNECTION) { text.setText(Html.fromHtml(getString(R.string.no_connection_empty_list))); } else if (data.error == TransmissionData.Errors.GENERIC_HTTP) { text.setText(Html.fromHtml(String.format( getString(R.string.generic_http_empty_list), data.errorCode))); } else if (data.error == TransmissionData.Errors.THREAD_ERROR) { text.setText(Html.fromHtml(getString(R.string.thread_error_empty_list))); } else if (data.error == TransmissionData.Errors.RESPONSE_ERROR) { text.setText(Html.fromHtml(getString(R.string.response_error_empty_list))); } else if (data.error == TransmissionData.Errors.TIMEOUT) { text.setText(Html.fromHtml(getString(R.string.timeout_empty_list))); } else if (data.error == TransmissionData.Errors.OUT_OF_MEMORY) { text.setText(Html.fromHtml(getString(R.string.out_of_memory_empty_list))); } else if (data.error == TransmissionData.Errors.JSON_PARSE_ERROR) { text.setText(Html.fromHtml(getString(R.string.json_parse_empty_list))); } } } if (data.error == 0) { if (altSpeed == session.isAltSpeedLimitEnabled()) { expecting &= ~(Expecting.ALT_SPEED_ON | Expecting.ALT_SPEED_OFF); } else { if (expecting == 0 || (expecting & Expecting.ALT_SPEED_ON) > 0 && session.isAltSpeedLimitEnabled() || (expecting & Expecting.ALT_SPEED_OFF) > 0 && !session.isAltSpeedLimitEnabled()) { setAltSpeed(session.isAltSpeedLimitEnabled()); expecting &= ~(Expecting.ALT_SPEED_ON | Expecting.ALT_SPEED_OFF); } } } else { switch(data.error) { case TransmissionData.Errors.DUPLICATE_TORRENT: case TransmissionData.Errors.INVALID_TORRENT: break; default: expecting = 0; break; } } if (refreshing && !data.queryOnly) { setRefreshing(false); } FragmentManager manager = getSupportFragmentManager(); TorrentListFragment fragment = (TorrentListFragment) manager.findFragmentById(R.id.torrent_list); if (fragment != null) { fragment.notifyTorrentListChanged(data.cursor, data.error, data.hasAdded, data.hasRemoved, data.hasStatusChanged, data.hasMetadataNeeded); } if (data.queryOnly) { loader.onContentChanged(); } } @Override public void onLoaderReset( android.support.v4.content.Loader<TransmissionData> loader) { FragmentManager manager = getSupportFragmentManager(); TorrentListFragment fragment = (TorrentListFragment) manager.findFragmentById(R.id.torrent_list); if (fragment != null) { fragment.notifyTorrentListChanged(null, -1, false, false, false, false); } } }; /* The callback will get garbage collected if its a mere anon class */ private SharedPreferences.OnSharedPreferenceChangeListener profileChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged(SharedPreferences prefs, String key) { if (TorrentListActivity.this == null || profile == null) return; if (!key.endsWith(profile.getId())) return; Loader<TransmissionData> loader = getSupportLoaderManager() .getLoader(G.TORRENTS_LOADER_ID); profile.load(); TransmissionProfile.setCurrentProfile(profile, TorrentListActivity.this); setProfile(profile); if (loader != null) { ((TransmissionDataLoader) loader).setProfile(profile); } } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); G.DEBUG = prefs.getBoolean(G.PREF_DEBUG, false); setContentView(R.layout.activity_torrent_list); PreferenceManager.setDefaultValues(this, R.xml.general_preferences, false); PreferenceManager.setDefaultValues(this, R.xml.sort_preferences, false); if (findViewById(R.id.torrent_detail_panel) != null) { // The detail container view will be present only in the // large-screen layouts (res/values-large and // res/values-sw600dp). If this view is present, then the // activity should be in two-pane mode. twoPaneLayout = true; // In two-pane mode, list items should be given the // 'activated' state when touched. ((TorrentListFragment) getSupportFragmentManager() .findFragmentById(R.id.torrent_list)) .setActivateOnItemClick(true); final LinearLayout slidingLayout = (LinearLayout) findViewById(R.id.sliding_layout); final View detailPanel = findViewById(R.id.torrent_detail_panel); detailSlideAnimator = (ValueAnimator) AnimatorInflater.loadAnimator(this, R.anim.weight_animator); detailSlideAnimator.setDuration(getResources().getInteger(android.R.integer.config_shortAnimTime)); detailSlideAnimator.setInterpolator(new DecelerateInterpolator()); detailSlideAnimator.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { final FragmentManager manager=getSupportFragmentManager(); TorrentDetailFragment fragment=(TorrentDetailFragment) manager.findFragmentByTag( G.DETAIL_FRAGMENT_TAG); if (fragment == null) { fragment=new TorrentDetailFragment(); fragment.setArguments(new Bundle()); manager.beginTransaction() .replace(R.id.torrent_detail_container, fragment, G.DETAIL_FRAGMENT_TAG) .commit(); manager.executePendingTransactions(); } fragment.setCurrentTorrent(currentTorrentIndex); G.logD("Opening the detail panel"); Loader<TransmissionData> loader = getSupportLoaderManager().getLoader(G.TORRENTS_LOADER_ID); if (loader != null) { ((TransmissionDataLoader) loader).setQueryOnly(true); ((TransmissionDataLoader) loader).setDetails(true); loader.onContentChanged(); } fragment.onCreateOptionsMenu(menu, getMenuInflater()); Handler handler = new Handler(); handler.post(new Runnable() { @Override public void run() { View bg=findViewById(R.id.torrent_detail_placeholder_background); if (bg != null) { bg.setVisibility(View.GONE); } View pager=findViewById(R.id.torrent_detail_pager); pager.setVisibility(View.VISIBLE); pager.animate().alpha((float) 1.0); } }); } @Override public void onAnimationCancel(Animator animation) { } }); detailSlideAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { float value=(Float) animation.getAnimatedValue(); LinearLayout.LayoutParams params=(LinearLayout.LayoutParams) detailPanel.getLayoutParams(); params.weight=value; slidingLayout.requestLayout(); } }); } if (savedInstanceState == null) { refreshing = true; } else { if (savedInstanceState.containsKey(STATE_INTENT_CONSUMED)) { intentConsumed = savedInstanceState.getBoolean(STATE_INTENT_CONSUMED); } if (savedInstanceState.containsKey(STATE_LOCATION_POSITION)) { locationPosition = savedInstanceState.getInt(STATE_LOCATION_POSITION); } } getWindow().setBackgroundDrawable(null); drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, findViewById(R.id.sliding_menu_frame)); drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_drawer, R.string.open_drawer, R.string.close_drawer) { }; drawerLayout.setDrawerListener(drawerToggle); if (twoPaneLayout) { toggleRightPane(false); } ActionBar actionBar = getActionBar(); if (actionBar != null) { actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); profileAdapter = new TransmissionProfileListAdapter(this); actionBar.setListNavigationCallbacks(profileAdapter, new ActionBar.OnNavigationListener() { @Override public boolean onNavigationItemSelected(int pos, long id) { TransmissionProfile profile = profileAdapter.getItem(pos); if (profile != TransmissionProfileListAdapter.EMPTY_PROFILE) { final Loader<TransmissionData> loader = getSupportLoaderManager() .getLoader(G.TORRENTS_LOADER_ID); if (TorrentListActivity.this.profile != null) { SharedPreferences prefs = TransmissionProfile.getPreferences(TorrentListActivity.this); if (prefs != null) prefs.unregisterOnSharedPreferenceChangeListener(profileChangeListener); } TransmissionProfile.setCurrentProfile(profile, TorrentListActivity.this); setProfile(profile); if (loader != null) { ((TransmissionDataLoader) loader).setProfile(profile); } SharedPreferences prefs = TransmissionProfile.getPreferences(TorrentListActivity.this); if (prefs != null) prefs.registerOnSharedPreferenceChangeListener(profileChangeListener); if (preventRefreshIndicator) { preventRefreshIndicator = false; } else { setRefreshing(true); } } return false; } }); actionBar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE); } if (savedInstanceState != null && savedInstanceState.containsKey(STATE_CURRENT_PROFILE)) { profile = savedInstanceState.getParcelable(STATE_CURRENT_PROFILE); getSupportLoaderManager().restartLoader(G.TORRENTS_LOADER_ID, null, torrentLoaderCallbacks); } getSupportLoaderManager().initLoader(G.PROFILES_LOADER_ID, null, profileLoaderCallbacks); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. drawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); drawerToggle.onConfigurationChanged(newConfig); } /** * Callback method from {@link TorrentListFragment.Callbacks} * indicating that the item with the given ID was selected. */ @Override public void onItemSelected(int position) { if (twoPaneLayout) { currentTorrentIndex = position; if (!toggleRightPane(true)) { TorrentDetailFragment fragment = (TorrentDetailFragment) getSupportFragmentManager().findFragmentByTag( G.DETAIL_FRAGMENT_TAG); if (fragment != null) { fragment.setCurrentTorrent(currentTorrentIndex); } } } else { // In single-pane mode, simply start the detail activity // for the selected item ID. Intent detailIntent = new Intent(this, TorrentDetailActivity.class); detailIntent.putExtra(G.ARG_PAGE_POSITION, position); detailIntent.putExtra(G.ARG_PROFILE, profile); detailIntent.putExtra(G.ARG_SESSION, session); startActivity(detailIntent); } } @Override public void onPageSelected(int position) { if (twoPaneLayout) { ((TorrentListFragment) getSupportFragmentManager() .findFragmentById(R.id.torrent_list)) .getListView().setItemChecked(position, true); } } @Override public void onBackPressed() { TorrentListFragment fragment = ((TorrentListFragment) getSupportFragmentManager() .findFragmentById(R.id.torrent_list)); int position = fragment.getListView().getCheckedItemPosition(); if (position == ListView.INVALID_POSITION) { super.onBackPressed(); } else { toggleRightPane(false); fragment.getListView().setItemChecked(position, false); } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); this.menu = menu; getMenuInflater().inflate(R.menu.torrent_list_activity, menu); setSession(session); setRefreshing(refreshing); setAltSpeed(altSpeed); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (drawerLayout.getDrawerLockMode( findViewById(R.id.sliding_menu_frame) ) == DrawerLayout.LOCK_MODE_UNLOCKED && drawerToggle.onOptionsItemSelected(item)) { return true; } Intent intent; Loader<TransmissionData> loader; switch(item.getItemId()) { case android.R.id.home: if (!twoPaneLayout) { return super.onOptionsItemSelected(item); } TorrentListFragment fragment = ((TorrentListFragment) getSupportFragmentManager() .findFragmentById(R.id.torrent_list)); int position = fragment.getListView().getCheckedItemPosition(); if (position == ListView.INVALID_POSITION) { return true; } else { toggleRightPane(false); fragment.getListView().setItemChecked(position, false); return true; } case R.id.menu_alt_speed: loader = getSupportLoaderManager() .getLoader(G.TORRENTS_LOADER_ID); if (loader != null) { expecting&= ~(Expecting.ALT_SPEED_ON | Expecting.ALT_SPEED_OFF); if (altSpeed) { setAltSpeed(false); expecting|= Expecting.ALT_SPEED_OFF; } else { setAltSpeed(true); expecting|= Expecting.ALT_SPEED_ON; } session.setAltSpeedLimitEnabled(altSpeed); ((TransmissionDataLoader) loader).setSession(session, "alt-speed-enabled"); } return true; case R.id.menu_refresh: loader = getSupportLoaderManager() .getLoader(G.TORRENTS_LOADER_ID); if (loader != null) { loader.onContentChanged(); } setRefreshing(!refreshing); return true; case R.id.menu_session_settings: intent = new Intent(this, TransmissionSessionActivity.class); intent.putExtra(G.ARG_PROFILE, profile); intent.putExtra(G.ARG_SESSION, session); startActivity(intent); return true; case R.id.menu_settings: intent = new Intent(this, SettingsActivity.class); if (session != null) { ArrayList<String> directories = new ArrayList<String>(session.getDownloadDirectories()); directories.remove(session.getDownloadDir()); intent.putExtra(G.ARG_DIRECTORIES, directories); } if (profile != null) { intent.putExtra(G.ARG_PROFILE_ID, profile.getId()); } startActivity(intent); return true; case R.id.menu_about: intent = new Intent(this, AboutActivity.class); startActivity(intent); return true; } if (twoPaneLayout) { Fragment fragment = getSupportFragmentManager().findFragmentByTag(G.DETAIL_FRAGMENT_TAG); if (fragment.onOptionsItemSelected(item)) { return true; } } return super.onOptionsItemSelected(item); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putBoolean(STATE_INTENT_CONSUMED, intentConsumed); outState.putInt(STATE_LOCATION_POSITION, locationPosition); outState.putParcelable(STATE_CURRENT_PROFILE, profile); } @Override public void onNewIntent(Intent intent) { if (!dialogShown) { intentConsumed = false; setIntent(intent); if (session != null) { consumeIntent(); } } } public boolean isDetailPanelVisible() { return twoPaneLayout && detailPanelVisible; } private boolean toggleRightPane(boolean show) { if (!twoPaneLayout) return false; View pager = findViewById(R.id.torrent_detail_pager); if (show) { if (!detailPanelVisible) { detailPanelVisible = true; detailSlideAnimator.start(); return true; } } else { if (detailPanelVisible) { detailPanelVisible = false; LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) findViewById(R.id.torrent_detail_panel).getLayoutParams(); params.weight = 0; if (pager != null) { pager.setAlpha(0); pager.setVisibility(View.GONE); } Loader<TransmissionData> loader = getSupportLoaderManager().getLoader(G.TORRENTS_LOADER_ID); if (loader != null) { ((TransmissionDataLoader) loader).setDetails(false); } FragmentManager manager = getSupportFragmentManager(); TorrentDetailFragment fragment = (TorrentDetailFragment) manager.findFragmentByTag(G.DETAIL_FRAGMENT_TAG); if (fragment != null) { fragment.removeMenuEntries(); } return true; } } return false; } public void setProfile(TransmissionProfile profile) { if (this.profile == profile || (this.profile != null && profile != null && profile.getId().equals(this.profile.getId()))) { return; } this.profile = profile; toggleRightPane(false); } @Override public TransmissionProfile getProfile() { return profile; } @Override public void setSession(TransmissionSession session) { if (session == null) { if (this.session != null) { drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, findViewById(R.id.sliding_menu_frame)); getActionBar().setDisplayHomeAsUpEnabled(false); invalidateOptionsMenu(); } this.session = null; if (menu != null) { menu.findItem(R.id.menu_session_settings).setVisible(false); } } else { boolean initial = false; if (this.session == null) { drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, findViewById(R.id.sliding_menu_frame)); getActionBar().setDisplayHomeAsUpEnabled(true); invalidateOptionsMenu(); initial = true; } this.session = session; if (menu != null) { menu.findItem(R.id.menu_session_settings).setVisible(true); } if (initial && !intentConsumed && !dialogShown) { consumeIntent(); } } } @Override public TransmissionSession getSession() { return session; } @Override public void setRefreshing(boolean refreshing) { if (menu == null) { return; } this.refreshing = refreshing; MenuItem item = menu.findItem(R.id.menu_refresh); if (this.refreshing) item.setActionView(R.layout.action_progress_bar); else item.setActionView(null); } private void setAltSpeed(boolean alt) { if (menu == null) { return; } altSpeed = alt; MenuItem item = menu.findItem(R.id.menu_alt_speed); if (session == null) { item.setVisible(false); } else { item.setVisible(true); if (altSpeed) { item.setIcon(R.drawable.ic_action_data_usage_on); item.setTitle(R.string.alt_speed_label_off); } else { item.setIcon(R.drawable.ic_action_data_usage); item.setTitle(R.string.alt_speed_label_on); } } } private void consumeIntent() { Intent intent = getIntent(); String action = intent.getAction(); if ((intent.getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == 0 && (Intent.ACTION_VIEW.equals(action) || ACTION_OPEN.equals(action))) { dialogShown = true; final Uri data = intent.getData(); LayoutInflater inflater = getLayoutInflater(); View view = inflater.inflate(R.layout.add_torrent_dialog, null); final Loader<TransmissionData> loader = getSupportLoaderManager() .getLoader(G.TORRENTS_LOADER_ID); final AlertDialog.Builder builder = new AlertDialog.Builder(this) .setCancelable(false) .setView(view) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { intentConsumed = true; dialogShown = false; } }); TransmissionProfileDirectoryAdapter adapter = new TransmissionProfileDirectoryAdapter( this, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); adapter.addAll(getSession().getDownloadDirectories()); adapter.sort(); Spinner location = (Spinner) view.findViewById(R.id.location_choice); location.setAdapter(adapter); if (locationPosition == AdapterView.INVALID_POSITION) { if (profile != null && profile.getLastDownloadDirectory() != null) { int position = adapter.getPosition(profile.getLastDownloadDirectory()); if (position > -1) { location.setSelection(position); } } } else { location.setSelection(locationPosition); } location.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { locationPosition = i; } @Override public void onNothingSelected(AdapterView<?> adapterView) {} }); ((CheckBox) view.findViewById(R.id.start_paused)).setChecked(profile != null && profile.getStartPaused()); final CheckBox deleteLocal = ((CheckBox) view.findViewById(R.id.delete_local)); deleteLocal.setChecked(profile != null && profile.getDeleteLocal()); if (data.getScheme().equals("magnet")) { builder.setTitle(R.string.add_magnet).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { Spinner location = (Spinner) ((AlertDialog) dialog).findViewById(R.id.location_choice); CheckBox paused = (CheckBox) ((AlertDialog) dialog).findViewById(R.id.start_paused); String dir = (String) location.getSelectedItem(); ((TransmissionDataLoader) loader).addTorrent( data.toString(), null, dir, paused.isChecked(), null); setRefreshing(true); intentConsumed = true; dialogShown = false; } }); AlertDialog dialog = builder.create(); dialog.show(); } else { final String fileURI = intent.getStringExtra(ARG_FILE_URI); final String filePath = intent.getStringExtra(ARG_FILE_PATH); deleteLocal.setVisibility(View.VISIBLE); builder.setTitle(R.string.add_torrent).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, int which) { Spinner location = (Spinner) ((AlertDialog) dialog).findViewById(R.id.location_choice); CheckBox paused = (CheckBox) ((AlertDialog) dialog).findViewById(R.id.start_paused); BufferedReader reader = null; try { String dir = (String) location.getSelectedItem(); File file = new File(new URI(fileURI)); reader = new BufferedReader(new FileReader(file)); StringBuilder filedata = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { filedata.append(line).append("\n"); } if (!file.delete()) { Toast.makeText(TorrentListActivity.this, R.string.error_deleting_torrent_file, Toast.LENGTH_SHORT).show(); } String path = filePath; if (!deleteLocal.isChecked()) { path = null; } ((TransmissionDataLoader) loader).addTorrent( null, filedata.toString(), dir, paused.isChecked(), path); setRefreshing(true); } catch (Exception e) { Toast.makeText(TorrentListActivity.this, R.string.error_reading_torrent_file, Toast.LENGTH_SHORT).show(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } intentConsumed = true; dialogShown = false; } }); AlertDialog dialog = builder.create(); dialog.show(); } } else { intentConsumed = true; } } private static class TransmissionProfileListAdapter extends ArrayAdapter<TransmissionProfile> { public static final TransmissionProfile EMPTY_PROFILE = new TransmissionProfile(null); public TransmissionProfileListAdapter(Context context) { super(context, 0); add(EMPTY_PROFILE); } @Override public View getView(int position, View convertView, ViewGroup parent) { View rowView = convertView; TransmissionProfile profile = getItem(position); if (rowView == null) { LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); rowView = vi.inflate(R.layout.torrent_profile_selector, null); } TextView name = (TextView) rowView.findViewById(R.id.name); TextView summary = (TextView) rowView.findViewById(R.id.summary); if (profile == EMPTY_PROFILE) { name.setText(R.string.no_profiles); if (summary != null) summary.setText(R.string.create_profile_in_settings); } else { name.setText(profile.getName()); if (summary != null) summary.setText((profile.getUsername().length() > 0 ? profile.getUsername() + "@" : "") + profile.getHost() + ":" + profile.getPort()); } return rowView; } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View rowView = convertView; if (rowView == null) { LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); rowView = vi.inflate(R.layout.torrent_profile_selector_dropdown, null); } return getView(position, rowView, parent); } } }
package butterknife; import android.view.View; import butterknife.internal.ListenerClass; import butterknife.internal.ListenerMethod; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static android.view.View.OnTouchListener; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.CLASS; /** * Bind a method to an {@link OnTouchListener OnTouchListener} on the view for each ID specified. * <pre><code> * {@literal @}OnTouch(R.id.example) boolean onTouch() { * Toast.makeText(this, "Touched!", LENGTH_SHORT).show(); * return false; * } * </code></pre> * Any number of parameters from * {@link OnTouchListener#onTouch(android.view.View, android.view.MotionEvent) onTouch} may be used * on the method. * * @see OnTouchListener * @see Optional */ @Target(METHOD) @Retention(CLASS) @ListenerClass( targetType = "android.view.View", setter = "setOnTouchListener", type = "android.view.View.OnTouchListener", method = @ListenerMethod( name = "onTouch", parameters = { "android.view.View", "android.view.MotionEvent" }, returnType = "boolean", defaultReturn = "false" ) ) public @interface OnTouch { /** View IDs to which the method will be bound. */ int[] value() default { View.NO_ID }; }
// This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // Java from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in th future. package org.usfirst.frc330.Beachbot2013Java; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.buttons.JoystickButton; import org.usfirst.frc330.Beachbot2013Java.commands.*; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; /* * $Log: OI.java,v $ * Revision 1.19 2013-03-17 01:57:22 jdavid * Added pickup sensor * * Revision 1.18 2013-03-15 03:08:37 echan * Added the command to shoot low at full speed * * Revision 1.17 2013-03-15 02:50:16 echan * added cvs log comments * */ /** * This class is the glue that binds the controls on the physical operator * interface to the commands and command groups that allow control of the robot. */ public class OI { //// CREATING BUTTONS // One type of button is a joystick button which is any button on a joystick. // You create one by telling it which joystick it's on and which button // number it is. // Joystick stick = new Joystick(port); // Button button = new JoystickButton(stick, buttonNumber); // Another type of button you can create is a DigitalIOButton, which is // a button or switch hooked up to the cypress module. These are useful if // you want to build a customized operator interface. // Button button = new DigitalIOButton(1); // There are a few additional built in buttons you can use. Additionally, // by subclassing Button you can create custom triggers and bind those to // commands the same as any other Button. //// TRIGGERING COMMANDS WITH BUTTONS // Once you have a button, it's trivial to bind it to a button in one of // three ways: // Start the command when the button is pressed and let it run the command // until it is finished as determined by it's isFinished method. // button.whenPressed(new ExampleCommand()); // Run the command while the button is being held down and interrupt it once // the button is released. // button.whileHeld(new ExampleCommand()); // Start the command when the button is released and let it run the command // until it is finished as determined by it's isFinished method. // button.whenReleased(new ExampleCommand()); // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS public JoystickButton shiftHighButton; public Joystick leftJoystick; public JoystickButton shiftLowButton; public Joystick rightJoystick; public JoystickButton pickupDownButton; public JoystickButton pickupUpButton; public JoystickButton shootButton; public JoystickButton shootHighButton; public JoystickButton shootLowButton; public JoystickButton armClimbingButton; public JoystickButton frisbeePickupOffButton; public JoystickButton frisbeePickupOnButton; public JoystickButton slowFrisbeePickupButton; public JoystickButton reversePickupButton; public Joystick operatorJoystick; // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS public OI() { // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS operatorJoystick = new Joystick(3); reversePickupButton = new JoystickButton(operatorJoystick, 10); reversePickupButton.whenPressed(new ReversePickup()); slowFrisbeePickupButton = new JoystickButton(operatorJoystick, 3); slowFrisbeePickupButton.whenPressed(new SlowPickupFrisbees()); frisbeePickupOnButton = new JoystickButton(operatorJoystick, 9); frisbeePickupOnButton.whenPressed(new PickupOnCommandGroup()); frisbeePickupOffButton = new JoystickButton(operatorJoystick, 8); frisbeePickupOffButton.whenPressed(new PickupFrisbeesOff()); armClimbingButton = new JoystickButton(operatorJoystick, 5); armClimbingButton.whenPressed(new ArmClimbing()); shootLowButton = new JoystickButton(operatorJoystick, 2); shootLowButton.whenPressed(new ShootLowCommandGroup()); shootHighButton = new JoystickButton(operatorJoystick, 4); shootHighButton.whenPressed(new ArmHighShooting()); shootButton = new JoystickButton(operatorJoystick, 1); shootButton.whenPressed(new LaunchFrisbee()); pickupUpButton = new JoystickButton(operatorJoystick, 6); pickupUpButton.whenPressed(new PickupUp()); pickupDownButton = new JoystickButton(operatorJoystick, 7); pickupDownButton.whenPressed(new PickupDown()); rightJoystick = new Joystick(2); shiftLowButton = new JoystickButton(rightJoystick, 1); shiftLowButton.whenPressed(new ShiftLow()); leftJoystick = new Joystick(1); shiftHighButton = new JoystickButton(leftJoystick, 1); shiftHighButton.whenPressed(new ShiftHigh()); // SmartDashboard Buttons SmartDashboard.putData("AutonomousCommand", new AutonomousCommand()); SmartDashboard.putData("ShiftHigh", new ShiftHigh()); SmartDashboard.putData("ShiftLow", new ShiftLow()); SmartDashboard.putData("MarsRock", new MarsRock()); SmartDashboard.putData("PickupDown", new PickupDown()); SmartDashboard.putData("PickupUp", new PickupUp()); SmartDashboard.putData("LaunchFrisbee", new LaunchFrisbee()); SmartDashboard.putData("ShootHigh", new ShootHigh()); SmartDashboard.putData("ShootLow", new ShootLow()); SmartDashboard.putData("PickupFrisbees", new PickupFrisbees()); SmartDashboard.putData("PickupFrisbeesOn", new PickupFrisbeesOn()); SmartDashboard.putData("PickupFrisbeesOff", new PickupFrisbeesOff()); SmartDashboard.putData("ReversePickup", new ReversePickup()); SmartDashboard.putData("SlowPickupFrisbees", new SlowPickupFrisbees()); SmartDashboard.putData("ArmLowShooting", new ArmLowShooting()); SmartDashboard.putData("ArmHighShooting", new ArmHighShooting()); SmartDashboard.putData("ArmClimbing", new ArmClimbing()); SmartDashboard.putData("StopShootHigh", new StopShootHigh()); SmartDashboard.putData("StopShootLow", new StopShootLow()); SmartDashboard.putData("ControlLEDs", new ControlLEDs()); SmartDashboard.putData("TurnCamera", new TurnCamera()); SmartDashboard.putData("TurnCameraIterative", new TurnCameraIterative()); SmartDashboard.putData("ArmLowPickup", new ArmLowPickup()); SmartDashboard.putData("SetArmZero", new SetArmZero()); SmartDashboard.putData("PickupOnCommandGroup", new PickupOnCommandGroup()); // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS } // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=FUNCTIONS public Joystick getLeftJoystick() { return leftJoystick; } public Joystick getRightJoystick() { return rightJoystick; } public Joystick getOperatorJoystick() { return operatorJoystick; } // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=FUNCTIONS }
package server; import java.sql.*; import java.util.*; import common.*; public class DataBase { private static String get_defaults() { return "jdbc:mysql://localhost/test"; } public static Connection get_connection() { String connection_string = get_defaults(); try { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } Connection conn = DriverManager.getConnection(connection_string,"root","1234"); return conn; } catch (SQLException e) { e.printStackTrace(); return null; } } /** * Update current HP of monster after a fight */ public static SQLOutput UpdateMonsterHP (int ID, int damage) { try{ SQLOutput flag = SQLOutput.EXISTS; Connection con = get_connection(); CallableStatement prc = con.prepareCall("{call Update_Monster_HP(?,?,?)}"); prc.setInt(1,ID); prc.setInt(2, damage); prc.registerOutParameter(3, Types.INTEGER); prc.execute(); int result = prc.getInt(3); if(result == 0) flag = SQLOutput.NOT_FOUND; con.close(); return flag; } catch (SQLException e) { e.printStackTrace(); return SQLOutput.SQL_ERROR; } } public static SQLOutput IsMonsterDead(int ID) { try{ SQLOutput flag = SQLOutput.EXISTS; Connection con = get_connection(); CallableStatement prc = con.prepareCall("{call Is_Monster_Dead(?,?)}"); prc.setInt(1,ID); prc.registerOutParameter(2, Types.INTEGER); prc.execute(); int result = prc.getInt(2); if(result == 0) flag = SQLOutput.NOT_FOUND; else if(result == 1) flag = SQLOutput.YES; else flag = SQLOutput.NO; con.close(); return flag; } catch (SQLException e) { e.printStackTrace(); return SQLOutput.SQL_ERROR; } } public static SQLOutput RemoveMonster(int ID) { try{ SQLOutput flag = SQLOutput.EXISTS; Connection con = get_connection(); CallableStatement prc = con.prepareCall("{call Remove_Monster(?,?)}"); prc.setInt(1,ID); prc.registerOutParameter(2, Types.INTEGER); prc.execute(); int result = prc.getInt(2); if(result == 0) flag = SQLOutput.NOT_FOUND; else flag = SQLOutput.EXISTS; con.close(); return flag; } catch (SQLException e) { e.printStackTrace(); return SQLOutput.SQL_ERROR; } } public static SQLOutput AddMonster(Monster mnst) { try{ SQLOutput flag = SQLOutput.EXISTS; Connection con = get_connection(); CallableStatement prc = con.prepareCall("{call Add_Monster(?,?,?,?,?,?,?)}"); prc.setInt(1,mnst.getType()); prc.setInt(2,mnst.getMaxHP()); prc.setInt(3,(int)mnst.getCoordinate().X()); prc.setInt(4,(int)mnst.getCoordinate().Y()); prc.setInt(5,mnst.getCurrentHP()); prc.setInt(6,mnst.getHunger()); prc.registerOutParameter(7, Types.INTEGER); prc.execute(); int result = prc.getInt(7); if(result == 0) flag = SQLOutput.EXISTS; else if(result == 2) flag = SQLOutput.NO; else flag = SQLOutput.OK; con.close(); return flag; } catch (SQLException e) { e.printStackTrace(); return SQLOutput.SQL_ERROR; } } public static Monster GetMonster(int x, int y) { try{ Connection con = get_connection(); CallableStatement prc = con.prepareCall("{call Get_Monster(?,?,?,?,?,?,?)}"); prc.registerOutParameter(1, Types.INTEGER); prc.registerOutParameter(2, Types.INTEGER); prc.setInt(3,x); prc.setInt(4,y); prc.registerOutParameter(5, Types.INTEGER); prc.registerOutParameter(6, Types.INTEGER); prc.registerOutParameter(7, Types.INTEGER); prc.execute(); int result = prc.getInt(7); if(result == 0) { con.close(); return null; } else { Monster mnst = new Monster(prc.getInt(1),prc.getInt(2),x,y,prc.getInt(5),prc.getInt(6)); con.close(); return mnst; } } catch (SQLException e) { e.printStackTrace(); return null; } } public static Coordinate GetPlayerCoordinate(int ID) { try{ Coordinate crdnt = null; Connection con = get_connection(); CallableStatement prc = con.prepareCall("{call Get_Player_Coordinate(?,?,?,?)}"); prc.setInt(1,ID); prc.registerOutParameter(2, Types.INTEGER); prc.registerOutParameter(3, Types.INTEGER); prc.registerOutParameter(4, Types.INTEGER); prc.execute(); int X = prc.getInt(2); int Y = prc.getInt(3); int Result = prc.getInt(4); if(Result == 0) return null; else crdnt = new Coordinate(X,Y); con.close(); return crdnt; } catch (SQLException e) { e.printStackTrace(); return null; } } public static List<Equipment> GetEquipment(int UID) { List<Equipment> Eqp = null; try{ Connection con = get_connection(); CallableStatement prc = con.prepareCall("{call Get_Equipment_Of_Player(?,?)}"); prc.setInt(1,UID); prc.registerOutParameter(2, Types.INTEGER); prc.execute(); int Result = prc.getInt(2); ResultSet Res = prc.getResultSet(); if(Result == 0) return Eqp; else { Eqp = new ArrayList<Equipment>(); while(Res.next()) { Eqp.add(new Equipment(Res.getInt(1),Res.getString(2),Res.getString(3))); } Res.close(); } con.close(); return Eqp; } catch (SQLException e) { e.printStackTrace(); return Eqp; } } public static SQLOutput AddEqipmentToPlayer(int UID, Equipment eq) { try{ SQLOutput flag = SQLOutput.OK; Connection con = get_connection(); CallableStatement prc = con.prepareCall("{call Add_Equipment_To_Player(?,?,?)}"); prc.setInt(1,UID); prc.setInt(2, eq.getID()); prc.registerOutParameter(3, Types.INTEGER); prc.execute(); int result = prc.getInt(3); if(result == 0) flag = SQLOutput.NOT_FOUND; else if(result == 1) flag = SQLOutput.EXISTS; else flag = SQLOutput.OK; con.close(); return flag; } catch (SQLException e) { e.printStackTrace(); return SQLOutput.SQL_ERROR; } } public static SQLOutput RemoveEquipmentFromPlayer(int UID, Equipment eq) { try{ SQLOutput flag = SQLOutput.OK; Connection con = get_connection(); CallableStatement prc = con.prepareCall("{call Remove_Equipment_From_Player(?,?,?)}"); prc.setInt(1,UID); prc.setInt(2, eq.getID()); prc.registerOutParameter(3, Types.INTEGER); prc.execute(); int result = prc.getInt(3); if(result == 0) flag = SQLOutput.NOT_FOUND; else if(result == 1) flag = SQLOutput.OK; else flag = SQLOutput.NO; con.close(); return flag; } catch (SQLException e) { e.printStackTrace(); return SQLOutput.SQL_ERROR; } } public static List<FloorType> get_possible_neighbors(Tile t) { //TODO Stub for map generation List<FloorType> lst = new ArrayList<FloorType>(); lst.add(FloorType.GRASS); lst.add(FloorType.DIRT); lst.add(FloorType.STONE); return lst; } public static List<MapObjectType> get_possible_content(Tile t) { //TODO Stub for map generation List<MapObjectType> lst = new ArrayList<MapObjectType>(); lst.add(MapObjectType.BUSH); lst.add(MapObjectType.TREE); lst.add(MapObjectType.ROCK); lst.add(null); return lst; } public static SQLOutput AddUser(String UserName,String Password, String Salt, String eMail,String UserIMG, String ActivationCode) { try{ SQLOutput flag = SQLOutput.OK; Connection con = get_connection(); CallableStatement prc = con.prepareCall("{call Add_User(?,?,?,?,?,?,?)}"); prc.setString(1, UserName); prc.setString(2, Password); prc.setString(3, Salt); prc.setString(4, eMail); prc.setString(5, UserIMG); prc.setString(6, ActivationCode); prc.registerOutParameter(7, Types.INTEGER); prc.execute(); int result = prc.getInt(7); if(result == 0) flag = SQLOutput.EXISTS; con.close(); return flag; } catch (SQLException e) { e.printStackTrace(); return SQLOutput.SQL_ERROR; } } public static int LoginFun(String Username , String Password ) { try{ Connection con = get_connection(); CallableStatement prc = con.prepareCall("{call Login(?,?,?)}"); prc.setString(1, Username); prc.setString(2, Password); prc.registerOutParameter(3, Types.INTEGER); prc.execute(); int result = prc.getInt(3); if(result == 0) result = -1; else if(result == 1) result = -2; else if(result == 2) result = -3; con.close(); return result; } catch (SQLException e) { e.printStackTrace(); return -1; } } public static SQLOutput ConfirmFun(String Username, String ActivationCode) { try{ SQLOutput flag = SQLOutput.OK; Connection con = get_connection(); CallableStatement prc = con.prepareCall("{call Change_Activity(?,?,?)}"); prc.setString(1, Username); prc.setString(2, ActivationCode); prc.registerOutParameter(3, Types.INTEGER); prc.execute(); int result = prc.getInt(3); if(result == 0) flag = SQLOutput.NOT_FOUND; else if(result == 1) flag = SQLOutput.NO; con.close(); return flag; } catch (SQLException e) { e.printStackTrace(); return SQLOutput.SQL_ERROR; } } public static void SetTile(Tile tile) { try{ Connection con = get_connection(); CallableStatement prc = con.prepareCall("{call Set_Tile(?,?,?,?)}"); prc.setLong(1, tile.getCoordinate().X()); prc.setLong(2, tile.getCoordinate().Y()); prc.setInt(3,tile.getFloorType().getID()); if(tile.getMapObjectType() == null) prc.setInt(4,-1); else prc.setInt(4,tile.getMapObjectType().getID()); prc.execute(); con.close(); } catch (SQLException e) { e.printStackTrace(); } } public static String GetSalt(String Username) { try{ Connection con = get_connection(); CallableStatement prc = con.prepareCall("{call Get_Salt(?,?)}"); prc.setString(1, Username); prc.registerOutParameter(2, Types.VARCHAR); prc.execute(); String str = prc.getString(2); con.close(); if(str.length() == 0) return null; else return str; } catch (SQLException e) { e.printStackTrace(); return null; } } public static SQLOutput UpdatePlayerLocation (int PlayerID, Coordinate cor) { try{ SQLOutput flag = SQLOutput.OK; Connection con = get_connection(); CallableStatement prc = con.prepareCall("{call Update_Player_Location(?,?,?,?)}"); prc.setInt(1, PlayerID); prc.setLong(2, cor.X()); prc.setLong(3, cor.Y()); prc.registerOutParameter(4, Types.INTEGER); prc.execute(); int result = prc.getInt(4); if(result == 0) flag = SQLOutput.NOT_FOUND; con.close(); return flag; } catch (SQLException e) { e.printStackTrace(); return SQLOutput.SQL_ERROR; } } public static Tile GetTile (Coordinate cor) { try{ Tile T = new Tile(cor); Connection con = get_connection(); CallableStatement prc = con.prepareCall("{call Get_Tile(?,?,?,?)}"); prc.setLong(1, cor.X()); prc.setLong(2, cor.Y()); prc.registerOutParameter(3, Types.INTEGER); prc.registerOutParameter(4, Types.INTEGER); prc.execute(); int surface = prc.getInt(3); int object = prc.getInt(4); con.close(); T.setFloorType(FloorType.values()[surface]); if(object == -1) T.setMapObjectType(null); else T.setMapObjectType(MapObjectType.values()[object]); return T; } catch (SQLException e) { e.printStackTrace(); return null; } } }
package hello; import java.io.*; import java.sql.*; import java.util.*; import java.util.concurrent.*; import javax.annotation.*; import javax.servlet.*; import javax.servlet.http.*; import javax.sql.*; /** * Database connectivity (with a Servlet-container managed pool) test. */ @SuppressWarnings("serial") public class DbPoolServlet extends HttpServlet { // Database details. private static final String DB_QUERY = "SELECT * FROM World WHERE id = ?"; private static final int DB_ROWS = 10000; // Database connection pool. @Resource(name="jdbc/hello_world") private DataSource mysqlDataSource; @Override protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // Set content type to JSON res.setHeader(Common.HEADER_CONTENT_TYPE, Common.CONTENT_TYPE_JSON); // Reference the data source. final DataSource source = mysqlDataSource; // Get the count of queries to run. int count = 1; try { count = Integer.parseInt(req.getParameter("queries")); // Bounds check. if (count > 500) { count = 500; } if (count < 1) { count = 1; } } catch (NumberFormatException nfexc) { // Do nothing. } // Fetch some rows from the database. final World[] worlds = new World[count]; final Random random = ThreadLocalRandom.current(); try (Connection conn = source.getConnection()) { try (PreparedStatement statement = conn.prepareStatement(DB_QUERY, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)) { // Run the query the number of times requested. for (int i = 0; i < count; i++) { final int id = random.nextInt(DB_ROWS) + 1; statement.setInt(1, id); try (ResultSet results = statement.executeQuery()) { if (results.next()) { worlds[i] = new World(id, results.getInt("randomNumber")); } } } } } catch (SQLException sqlex) { System.err.println("SQL Exception: " + sqlex); } // Write JSON encoded message to the response. try { if (count == 1) { Common.MAPPER.writeValue(res.getOutputStream(), worlds[0]); } else { Common.MAPPER.writeValue(res.getOutputStream(), worlds); } } catch (IOException ioe) { // do nothing } } }
package sorcer.sml.contexts; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sorcer.test.ProjectContext; import org.sorcer.test.SorcerTestRunner; import sorcer.arithmetic.provider.impl.AdderImpl; import sorcer.arithmetic.provider.impl.MultiplierImpl; import sorcer.arithmetic.provider.impl.SubtractorImpl; import sorcer.core.context.model.par.Par; import sorcer.core.invoker.InvokeIncrementor; import sorcer.core.provider.rendezvous.ServiceJobber; import sorcer.service.Block; import sorcer.service.Context; import sorcer.service.Job; import sorcer.service.Strategy.Flow; import sorcer.service.Task; import sorcer.service.modeling.Model; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static sorcer.co.operator.*; import static sorcer.eo.operator.*; import static sorcer.mo.operator.*; import static sorcer.po.operator.*; @SuppressWarnings({ "unchecked", "rawtypes" }) @RunWith(SorcerTestRunner.class) @ProjectContext("examples/sml") public class Mograms { private final static Logger logger = LoggerFactory.getLogger(Mograms.class); @Test public void exertExertionToModelMogram() throws Exception { // usage of in and out connectors associated with model Task t4 = task( "t4", sig("multiply", MultiplierImpl.class), context("multiply", inEnt("arg/x1", 10.0), inEnt("arg/x2", 50.0), outEnt("multiply/result/y"))); Task t5 = task( "t5", sig("add", AdderImpl.class), context("add", inEnt("arg/x1", 20.0), inEnt("arg/x2", 80.0), outEnt("add/result/y"))); // in connector from exertion to model Context taskOutConnector = outConn(inEnt("add/x1", "j2/t4/multiply/result/y"), inEnt("multiply/x1", "j2/t5/add/result/y")); Job j2 = job("j2", sig("service", ServiceJobber.class), t4, t5, strategy(Flow.PAR), taskOutConnector); // out connector from model Context modelOutConnector = outConn(inEnt("y1", "add"), inEnt("y2", "multiply"), inEnt("y3", "subtract")); Model model = srvModel( inEnt("multiply/x1", 10.0), inEnt("multiply/x2", 50.0), inEnt("add/x1", 20.0), inEnt("add/x2", 80.0), srv(sig("multiply", MultiplierImpl.class, result("multiply/out", inPaths("multiply/x1", "multiply/x2")))), srv(sig("add", AdderImpl.class, result("add/out", inPaths("add/x1", "add/x2")))), srv(sig("subtract", SubtractorImpl.class, result("subtract/out", inPaths("multiply/out", "add/out"))))); // srv("z1", "multiply/x1"), srv("z2", "add/x2"), srv("z3", "subtract/out")); responseUp(model, "add", "multiply", "subtract"); dependsOn(model, ent("subtract", paths("multiply", "add"))); // specify how model connects to exertion outConn(model, modelOutConnector); Block block = block("mogram", j2, model); Context result = context(exert(block)); logger.info("result: " + result); assertTrue(value(result, "add").equals(580.0)); assertTrue(value(result, "multiply").equals(5000.0)); assertTrue(value(result, "y1").equals(580.0)); assertTrue(value(result, "y2").equals(5000.0)); assertTrue(value(result, "y3").equals(4420.0)); } @Test public void par2() throws Exception { InvokeIncrementor i = inc("x1", 200.0); Par p = par("x1", next(i)); logger.info("value: " + value(p)); logger.info("value: " + value(p)); // logger.info("value: " + next(i)); // logger.info("value: " + next(i)); // logger.info("value: " + next(i)); } @Test public void exertMstcGateSchema() throws Exception { Model model = srvModel( inEnt("x", 10.0), outEnt("y", next(inc("x", 20.0)))); responseUp(model, "y"); Context result = response(model); logger.info("result1: " + result); // Context result = response(model); // logger.info("result1: " + result); // assertTrue(value(result, "incBy200").equals(250.0)); // Block looping = block( // inEnt("multiply/x1", 10.0), inEnt("multiply/x2", 50.0), // loop(condition("{ incBy200 -> incBy200 < 1000 }", "incBy200"), // model)); // Block looping = block( // context(ent("x1", 10.0), ent("x2", 20.0), ent("z", 100.0)), // loop(condition("{ x1, x2, z -> x1 + x2 < z }", "x1", "x2", "z"), // task(par("x1", invoker("x1 + 3", pars("x1")))))); // looping = exert(looping); // logger.info("block context: " + context(looping)); // logger.info("result: " + value(context(looping), "x1")); // assertEquals(value(context(looping), "x1"), 82.00); } @Test public void exertMstcGateMogram() throws Exception { Model airCycleModel = srvModel("airCycleModel", srv(sig("getAc2HexOut", Class.class, result("ac2HexOut1", inPaths("offDesignCases")))), srv(sig("mstcGate", Class.class, result("fullEngineDeck", inPaths("ac2HexOut1")))), srv(sig("parseEngineDeck", Class.class, result("acmFile", inPaths("fullEngineDeck")))), srv(sig("executeAirCycleMachine", Class.class, result("ac2HexOut2", inPaths("acmFile"))))); responseUp(airCycleModel, "executeAirCycleMachine"); dependsOn(airCycleModel, ent("executeAirCycleMachine", paths("getAc2HexOut", "mstcGate", "parseEngineDeck"))); Block airCycleMachineMogram = block( context(ent("offDesignCases", "myInputURL")), loop(condition("{ ac2HexOut1, ac2HexOut2 -> ac2HexOut1.equals(ac2HexOut2) }", "ac2HexOut1", "ac2HexOut2"), airCycleModel)); airCycleMachineMogram = exert(airCycleMachineMogram); logger.info("block context: " + context(airCycleMachineMogram)); } }
/* * $Log: Dir2Xml.java,v $ * Revision 1.7 2006-01-05 14:52:02 europe\L190409 * improve error handling * * Revision 1.6 2005/10/20 15:20:27 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added feature to include directories * * Revision 1.5 2005/07/19 11:04:09 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * use explicit FileNameComparator * * Revision 1.4 2005/05/31 09:20:37 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added sort for files * */ package nl.nn.adapterframework.util; import java.io.File; import java.io.IOException; import java.util.Date; import java.util.Arrays; import org.apache.log4j.Logger; /** * List the contents of a directory as XML. * * @author Johan Verrips IOS * @version Id */ public class Dir2Xml { public static final String version="$RCSfile: Dir2Xml.java,v $ $Revision: 1.7 $ $Date: 2006-01-05 14:52:02 $"; protected Logger log = Logger.getLogger(this.getClass()); private String path; private String wildcard="*.*"; public String getDirList() { return getDirList(false); } public String getDirList(boolean includeDirectories) { WildCardFilter filter = new WildCardFilter(wildcard); File dir = new File(path); File files[] = dir.listFiles(filter); Arrays.sort(files, new FileNameComparator()); int count = (files == null ? 0 : files.length); XmlBuilder dirXml = new XmlBuilder("directory"); dirXml.addAttribute("name", path); if (includeDirectories) { dirXml.addSubElement(getFileAsXmlBuilder(dir.getParentFile(),"..")); } for (int i = 0; i < count; i++) { File file = files[i]; if (file.isDirectory() && !includeDirectories) { continue; } dirXml.addSubElement(getFileAsXmlBuilder(file,file.getName())); } return dirXml.toXML(); } private XmlBuilder getFileAsXmlBuilder(File file, String nameShown) { XmlBuilder fileXml = new XmlBuilder("file"); fileXml.addAttribute("name", nameShown); fileXml.addAttribute("size", "" + file.length()); fileXml.addAttribute("directory", "" + file.isDirectory()); try { fileXml.addAttribute("canonicalName", file.getCanonicalPath()); } catch (IOException e) { log.warn("cannot get canonicalName for file ["+nameShown+"]",e); fileXml.addAttribute("canonicalName", nameShown); } // Get the modification date of the file Date modificationDate = new Date(file.lastModified()); //add date String date = DateUtils.format(modificationDate, DateUtils.FORMAT_DATE); fileXml.addAttribute("modificationDate", date); // add the time String time = DateUtils.format(modificationDate, DateUtils.FORMAT_TIME_HMS); fileXml.addAttribute("modificationTime", time); return fileXml; } public void setPath(String path) { this.path = path; } /** * Set a Wildcard * @see WildCardFilter */ public void setWildCard(String wildcard) { this.wildcard = wildcard; } }
package ua.kiev.icyb.bio.alg.mixture; import java.util.Arrays; import ua.kiev.icyb.bio.alg.AbstractDistribution; import ua.kiev.icyb.bio.alg.Distribution; import ua.kiev.icyb.bio.alg.DistributionUtils; public class Mixture<T> extends AbstractDistribution<T> { private static final long serialVersionUID = 1L; private double[] weights; private Distribution<T>[] models; public Mixture() { this.weights = new double[0]; @SuppressWarnings("unchecked") Distribution<T>[] v = new Distribution[0]; this.models = v; } public Mixture(Distribution<T>[] models) { this.weights = new double[models.length]; for (int i = 0; i < models.length; i++) { this.weights[i] = 1.0 / models.length; } this.models = models.clone(); } public int size() { return this.weights.length; } public double weight(int index) { return this.weights[index]; } public double[] weights() { return this.weights.clone(); } public void setWeights(double[] weights) { if (weights.length != size()) { throw new IllegalArgumentException("Wrong number of weights"); } double sum = 0.0; for (int i = 0; i < weights.length; i++) { if (weights[i] < 0) { throw new IllegalArgumentException("Negative weight: " + weights[i]); } sum += weights[i]; } if (sum == 0.0) { throw new IllegalArgumentException("At least one weight must be positive"); } for (int i = 0; i < weights.length; i++) { this.weights[i] = weights[i] / sum; } } public Distribution<T> model(int index) { return this.models[index]; } public void delete(int index) { for (int i = index + 1; i < size(); i++) { models[i - 1] = models[i]; weights[i - 1] = weights[i]; } models = Arrays.copyOf(models, models.length - 1); weights = Arrays.copyOf(weights, weights.length - 1); double sum = 0; for (int i = 0; i < size(); i++) sum += weights[i]; for (int i = 0; i < size(); i++) weights[i] /= sum; } public void add(Distribution<T> model, double weight) { if (weight < 0.0) { throw new IllegalArgumentException("Negative weight: " + weight); } if (weight > 1.0) { throw new IllegalArgumentException("Weight exceeds 1.0: " + weight); } int oldSize = size(); models = Arrays.copyOf(models, oldSize + 1); models[oldSize] = model; weights = Arrays.copyOf(weights, oldSize + 1); for (int i = 0; i < size() - 1; i++) { weights[i] *= (1 - weight); } weights[size() - 1] = weight; } public double[] posteriors(T sample) { double[] p = new double[this.size()]; double maxP = Double.NEGATIVE_INFINITY; for (int i = 0; i < p.length; i++) { p[i] = models[i].estimate(sample) + Math.log(this.weights[i]); if (p[i] > maxP) maxP = p[i]; } double sum = 0.0; for (int i = 0; i < p.length; i++) { p[i] -= maxP; p[i] = Math.exp(p[i]); sum += p[i]; } for (int i = 0; i < p.length; i++) { p[i] /= sum; } return p; } @Override public void train(T sample, double weight) { throw new UnsupportedOperationException("Use EM algorithm"); } @Override public double estimate(T point) { double[] p = new double[this.size()]; double maxP = Double.NEGATIVE_INFINITY; for (int i = 0; i < p.length; i++) { p[i] = models[i].estimate(point) + Math.log(this.weights[i]); if (p[i] > maxP) maxP = p[i]; } double sum = 0.0; for (int i = 0; i < size(); i++) { sum += Math.exp(p[i] - maxP); } return maxP + Math.log(sum); } @Override public Mixture<T> clearClone() { Mixture<T> other = (Mixture<T>) super.clone(); other.weights = this.weights.clone(); other.models = this.models.clone(); for (int i = 0; i < this.size(); i++) { other.models[i] = this.models[i].clearClone(); } return other; } @Override public Mixture<T> clone() { Mixture<T> other = (Mixture<T>) super.clone(); other.weights = this.weights.clone(); other.models = this.models.clone(); for (int i = 0; i < this.size(); i++) { other.models[i] = this.models[i].clone(); } return other; } @Override public void reset() { for (Distribution<T> model : this.models) { model.reset(); } } @Override public T generate() { Integer[] indices = new Integer[this.size()]; for (int i = 0; i < indices.length; i++) { indices[i] = i; } int idx = DistributionUtils.choose(indices, this.weights); return this.model(idx).generate(); } }
package be.ibridge.kettle.trans.step.tableinput; import java.util.ArrayList; import java.util.Hashtable; import org.eclipse.swt.widgets.Shell; import org.w3c.dom.Node; import be.ibridge.kettle.core.CheckResult; import be.ibridge.kettle.core.Const; import be.ibridge.kettle.core.Row; import be.ibridge.kettle.core.XMLHandler; import be.ibridge.kettle.core.database.Database; import be.ibridge.kettle.core.database.DatabaseMeta; import be.ibridge.kettle.core.exception.KettleDatabaseException; import be.ibridge.kettle.core.exception.KettleException; import be.ibridge.kettle.core.exception.KettleStepException; import be.ibridge.kettle.core.exception.KettleXMLException; import be.ibridge.kettle.core.util.StringUtil; import be.ibridge.kettle.core.value.Value; import be.ibridge.kettle.repository.Repository; import be.ibridge.kettle.trans.DatabaseImpact; import be.ibridge.kettle.trans.Trans; import be.ibridge.kettle.trans.TransMeta; import be.ibridge.kettle.trans.step.BaseStepMeta; import be.ibridge.kettle.trans.step.StepDataInterface; import be.ibridge.kettle.trans.step.StepDialogInterface; import be.ibridge.kettle.trans.step.StepInterface; import be.ibridge.kettle.trans.step.StepMeta; import be.ibridge.kettle.trans.step.StepMetaInterface; public class TableInputMeta extends BaseStepMeta implements StepMetaInterface { private DatabaseMeta databaseMeta; private String sql; private int rowLimit; /** Which step is providing the date, just the name?*/ private String lookupFromStepname; /** The step to lookup from */ private StepMeta lookupFromStep; /** Should I execute once per row? */ private boolean executeEachInputRow; private boolean variableReplacementActive; public TableInputMeta() { super(); } /** * @return Returns true if the step should be run per row */ public boolean isExecuteEachInputRow() { return executeEachInputRow; } /** * @param oncePerRow true if the step should be run per row */ public void setExecuteEachInputRow(boolean oncePerRow) { this.executeEachInputRow = oncePerRow; } /** * @return Returns the database. */ public DatabaseMeta getDatabaseMeta() { return databaseMeta; } /** * @param database The database to set. */ public void setDatabaseMeta(DatabaseMeta database) { this.databaseMeta = database; } /** * @return Returns the rowLimit. */ public int getRowLimit() { return rowLimit; } /** * @param rowLimit The rowLimit to set. */ public void setRowLimit(int rowLimit) { this.rowLimit = rowLimit; } /** * @return Returns the sql. */ public String getSQL() { return sql; } /** * @param sql The sql to set. */ public void setSQL(String sql) { this.sql = sql; } /** * @return Returns the lookupFromStep. */ public StepMeta getLookupFromStep() { return lookupFromStep; } /** * @param lookupFromStep The lookupFromStep to set. */ public void setLookupFromStep(StepMeta lookupFromStep) { this.lookupFromStep = lookupFromStep; } public void loadXML(Node stepnode, ArrayList databases, Hashtable counters) throws KettleXMLException { readData(stepnode, databases); } public Object clone() { TableInputMeta retval = (TableInputMeta)super.clone(); return retval; } private void readData(Node stepnode, ArrayList databases) throws KettleXMLException { try { databaseMeta = Const.findDatabase(databases, XMLHandler.getTagValue(stepnode, "connection")); sql = XMLHandler.getTagValue(stepnode, "sql"); rowLimit = Const.toInt(XMLHandler.getTagValue(stepnode, "limit"), 0); lookupFromStepname = XMLHandler.getTagValue(stepnode, "lookup"); executeEachInputRow = "Y".equals(XMLHandler.getTagValue(stepnode, "execute_each_row")); variableReplacementActive = "Y".equals(XMLHandler.getTagValue(stepnode, "variables_active")); } catch(Exception e) { throw new KettleXMLException("Unable to load step info from XML", e); } } public void setDefault() { databaseMeta = null; sql = "SELECT <values> FROM <table name> WHERE <conditions>"; rowLimit = 0; } /** * @return the informational source steps, if any. Null is the default: none. */ public String[] getInfoSteps() { if (getLookupStepname()==null) return null; return new String[] { getLookupStepname() }; } public Row getFields(Row r, String name, Row info) throws KettleStepException { Row row; boolean param=false; if (r==null) row=new Row(); // give back values else row=r; // add to the existing row of values... if (databaseMeta==null) return row; Database db = new Database(databaseMeta); databases = new Database[] { db }; // keep track of it for cancelling purposes... // First try without connecting to the database... (can be S L O W) String sNewSQL = sql; if (isVariableReplacementActive()) sNewSQL = StringUtil.environmentSubstitute(sql); Row add=null; try { add = db.getQueryFields(sNewSQL, param, info); } catch(KettleDatabaseException dbe) { throw new KettleStepException("Unable to get queryfields for SQL: "+Const.CR+sql, dbe); } if (add!=null) { for (int i=0;i<add.size();i++) { Value v=add.getValue(i); v.setOrigin(name); } row.addRow( add ); } else { try { db.connect(); if (getLookupStepname()!=null) param=true; add = db.getQueryFields(sql, param, info); if (add==null) return row; for (int i=0;i<add.size();i++) { Value v=add.getValue(i); v.setOrigin(name); } row.addRow( add ); } catch(KettleException ke) { throw new KettleStepException("Unable to get queryfields for SQL: "+Const.CR+sql, ke); } finally { db.disconnect(); } } return row; } public String getXML() { StringBuffer retval = new StringBuffer(); retval.append(" "+XMLHandler.addTagValue("connection", databaseMeta==null?"":databaseMeta.getName())); retval.append(" "+XMLHandler.addTagValue("sql", sql)); retval.append(" "+XMLHandler.addTagValue("limit", rowLimit)); retval.append(" "+XMLHandler.addTagValue("lookup", getLookupStepname())); retval.append(" "+XMLHandler.addTagValue("execute_each_row", executeEachInputRow)); retval.append(" "+XMLHandler.addTagValue("variables_active", variableReplacementActive)); return retval.toString(); } public void readRep(Repository rep, long id_step, ArrayList databases, Hashtable counters) throws KettleException { try { long id_connection = rep.getStepAttributeInteger(id_step, "id_connection"); databaseMeta = Const.findDatabase( databases, id_connection); sql = rep.getStepAttributeString (id_step, "sql"); rowLimit = (int)rep.getStepAttributeInteger(id_step, "limit"); lookupFromStepname = rep.getStepAttributeString (id_step, "lookup"); executeEachInputRow = rep.getStepAttributeBoolean(id_step, "execute_each_row"); variableReplacementActive = rep.getStepAttributeBoolean(id_step, "variables_active"); } catch(Exception e) { throw new KettleException("Unexpected error reading step information from the repository", e); } } public void saveRep(Repository rep, long id_transformation, long id_step) throws KettleException { try { rep.saveStepAttribute(id_transformation, id_step, "id_connection", databaseMeta==null?-1:databaseMeta.getID()); rep.saveStepAttribute(id_transformation, id_step, "sql", sql); rep.saveStepAttribute(id_transformation, id_step, "limit", rowLimit); rep.saveStepAttribute(id_transformation, id_step, "lookup", getLookupStepname()); rep.saveStepAttribute(id_transformation, id_step, "execute_each_row", executeEachInputRow); rep.saveStepAttribute(id_transformation, id_step, "variables_active", variableReplacementActive); // Also, save the step-database relationship! if (databaseMeta!=null) rep.insertStepDatabase(id_transformation, id_step, databaseMeta.getID()); } catch(Exception e) { throw new KettleException("Unable to save step information to the repository for id_step="+id_step, e); } } public void check(ArrayList remarks, StepMeta stepMeta, Row prev, String input[], String output[], Row info) { CheckResult cr; if (databaseMeta!=null) { cr = new CheckResult(CheckResult.TYPE_RESULT_OK, "Connection exists", stepMeta); remarks.add(cr); Database db = new Database(databaseMeta); databases = new Database[] { db }; // keep track of it for cancelling purposes... try { db.connect(); cr = new CheckResult(CheckResult.TYPE_RESULT_OK, "Connection to database OK", stepMeta); remarks.add(cr); if (sql!=null && sql.length()!=0) { cr = new CheckResult(CheckResult.TYPE_RESULT_OK, "SQL statement is entered", stepMeta); remarks.add(cr); } else { cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, "SQL statement is missing.", stepMeta); remarks.add(cr); } } catch(KettleException e) { cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, "An error occurred: "+e.getMessage(), stepMeta); remarks.add(cr); } finally { db.disconnect(); } } else { cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, "Please select or create a connection to use", stepMeta); remarks.add(cr); } // See if we have an informative step... if (getLookupStepname()!=null) { boolean found=false; for (int i=0;i<input.length;i++) { if (getLookupStepname().equalsIgnoreCase(input[i])) found=true; } if (found) { cr = new CheckResult(CheckResult.TYPE_RESULT_OK, "Previous step to read info from ["+getLookupStepname()+"] is found.", stepMeta); remarks.add(cr); } else { cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, "Previous step to read info from ["+getLookupStepname()+"] is not found.", stepMeta); remarks.add(cr); } // Count the number of ? in the SQL string: int count=0; for (int i=0;i<sql.length();i++) { char c = sql.charAt(i); if (c=='\'') // skip to next quote! { do { i++; c = sql.charAt(i); } while (c!='\''); } if (c=='?') count++; } // Verify with the number of informative fields... if (info!=null) { if(count == info.size()) { cr = new CheckResult(CheckResult.TYPE_RESULT_OK, "This step is expecting and receiving "+info.size()+" fields of input from the previous step.", stepMeta); remarks.add(cr); } else { cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, "This step is receiving "+info.size()+" but not the expected "+count+" fields of input from the previous step.", stepMeta); remarks.add(cr); } } else { cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, "Input step name is not recognized!", stepMeta); remarks.add(cr); } } else { if (input.length>0) { cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, "Step is not expecting info from input steps.", stepMeta); remarks.add(cr); } else { cr = new CheckResult(CheckResult.TYPE_RESULT_OK, "No input expected, no input provided.", stepMeta); remarks.add(cr); } } } public String getLookupStepname() { if (lookupFromStep!=null && lookupFromStep.getName()!=null && lookupFromStep.getName().length()>0 ) return lookupFromStep.getName(); return null; } public void searchInfoAndTargetSteps(ArrayList steps) { lookupFromStep = TransMeta.findStep(steps, lookupFromStepname); } public StepDialogInterface getDialog(Shell shell, StepMetaInterface info, TransMeta transMeta, String name) { return new TableInputDialog(shell, info, transMeta, name); } public StepInterface getStep(StepMeta stepMeta, StepDataInterface stepDataInterface, int cnr, TransMeta transMeta, Trans trans) { return new TableInput(stepMeta, stepDataInterface, cnr, transMeta, trans); } public StepDataInterface getStepData() { return new TableInputData(); } public void analyseImpact(ArrayList impact, TransMeta transMeta, StepMeta stepMeta, Row prev, String input[], String output[], Row info) throws KettleStepException { // Find the lookupfields... Row out = getFields(null, stepMeta.getName(), info); if (out!=null) { for (int i=0;i<out.size();i++) { Value outvalue = out.getValue(i); DatabaseImpact ii = new DatabaseImpact( DatabaseImpact.TYPE_IMPACT_READ, transMeta.getName(), stepMeta.getName(), databaseMeta.getDatabaseName(), "", outvalue.getName(), outvalue.getName(), stepMeta.getName(), sql, "read from one or more database tables via SQL statement" ); impact.add(ii); } } } public DatabaseMeta[] getUsedDatabaseConnections() { if (databaseMeta!=null) { return new DatabaseMeta[] { databaseMeta }; } else { return super.getUsedDatabaseConnections(); } } /** * @return Returns the variableReplacementActive. */ public boolean isVariableReplacementActive() { return variableReplacementActive; } /** * @param variableReplacementActive The variableReplacementActive to set. */ public void setVariableReplacementActive(boolean variableReplacementActive) { this.variableReplacementActive = variableReplacementActive; } }
package com.anysoftkeyboard.dictionaries; import android.os.AsyncTask; import com.anysoftkeyboard.utils.Log; import com.menny.android.anysoftkeyboard.AnyApplication; import java.lang.ref.WeakReference; public class DictionaryASyncLoader extends AsyncTask<Dictionary, Void, Dictionary> { private static final String TAG = "ASK_DictionaryASyncLoader"; private final WeakReference<Listener> mListener; private Exception mException = null; public DictionaryASyncLoader(Listener listener) { mListener = new WeakReference<Listener>(listener); } @Override protected Dictionary doInBackground(Dictionary... dictionaries) { Dictionary dictionary = dictionaries[0]; if (!dictionary.isClosed()) { try { dictionary.loadDictionary(); } catch (Exception e) { Log.w(TAG, "Failed to load dictionary!", e); mException = e; } } return dictionary; } @Override protected void onPostExecute(Dictionary dictionary) { super.onPostExecute(dictionary); if (!dictionary.isClosed()) { if (mException != null) { dictionary.close(); } Listener listener = mListener.get(); if (listener == null) return; if (mException == null) { listener.onDictionaryLoadingDone(dictionary); } else { listener.onDictionaryLoadingFailed(dictionary, mException); } } } public static interface Listener { void onDictionaryLoadingDone(Dictionary dictionary); void onDictionaryLoadingFailed(Dictionary dictionary, Exception exception); } }
package com.example.connect_sdk_sampler.fragments; import java.util.List; import android.content.Context; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.ListView; import com.connectsdk.core.AppInfo; import com.connectsdk.service.capability.Launcher; import com.connectsdk.service.capability.Launcher.AppInfoListener; import com.connectsdk.service.capability.Launcher.AppLaunchListener; import com.connectsdk.service.capability.Launcher.AppListListener; import com.connectsdk.service.capability.ToastControl; import com.connectsdk.service.capability.listeners.ResponseListener; import com.connectsdk.service.command.ServiceCommandError; import com.connectsdk.service.command.ServiceSubscription; import com.connectsdk.service.sessions.LaunchSession; import com.example.connect_sdk_sampler.R; import com.example.connect_sdk_sampler.widget.AppAdapter; public class AppsFragment extends BaseFragment { // public Button smartWorldButton; public Button browserButton; public Button myAppButton; public Button netflixButton; public Button appStoreButton; public Button youtubeButton; public Button toastButton; public ListView appListView; public AppAdapter adapter; LaunchSession runningAppSession; LaunchSession appStoreSession; ServiceSubscription<AppInfoListener> runningAppSubs; public AppsFragment(Context context) { super(context); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate( R.layout.fragment_apps, container, false); browserButton = (Button) rootView.findViewById(R.id.browserButton); myAppButton = (Button) rootView.findViewById(R.id.myApp); netflixButton = (Button) rootView.findViewById(R.id.deepLinkButton); appStoreButton = (Button) rootView.findViewById(R.id.appStoreButton); youtubeButton = (Button) rootView.findViewById(R.id.youtubeButton); toastButton = (Button) rootView.findViewById(R.id.toastButton); appListView = (ListView) rootView.findViewById(R.id.appListView); adapter = new AppAdapter(getContext(), R.layout.app_item); appListView.setAdapter(adapter); buttons = new Button[] { browserButton, netflixButton, youtubeButton, toastButton, myAppButton, appStoreButton }; return rootView; } @Override public void enableButtons() { super.enableButtons(); if ( getTv().hasCapability(Launcher.Browser) || getTv().hasCapability(Launcher.Browser_Params) ) { browserButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if ( browserButton.isSelected() ) { browserButton.setSelected(false); if (runningAppSession != null) { runningAppSession.close(null); } } else { browserButton.setSelected(true); getLauncher().launchBrowser("http://connectsdk.com/", new Launcher.AppLaunchListener() { public void onSuccess(LaunchSession session) { setRunningAppInfo(session); } public void onError(ServiceCommandError error) { } }); } } }); } else { disableButton(browserButton); } if ( getTv().hasCapability(ToastControl.Show_Toast) ) { toastButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { getToastControl().showToast("Yeah, toast!", getToastIconData(), "png", null); } }); } else { disableButton(toastButton); } if ( getTv().hasCapability(Launcher.Netflix) || getTv().hasCapability(Launcher.Netflix_Params) ) { netflixButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if ( netflixButton.isSelected() ) { netflixButton.setSelected(false); if (runningAppSession != null) { runningAppSession.close(null); } } else { netflixButton.setSelected(true); getLauncher().launchNetflix("70217913", new Launcher.AppLaunchListener() { @Override public void onSuccess(LaunchSession session) { setRunningAppInfo(session); } @Override public void onError(ServiceCommandError error) { } }); } } }); } else { disableButton(netflixButton); } if ( getTv().hasCapability(Launcher.YouTube) || getTv().hasCapability(Launcher.YouTube_Params) ) { youtubeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if ( youtubeButton.isSelected() ) { youtubeButton.setSelected(false); if (runningAppSession != null) { runningAppSession.close(null); } } else { youtubeButton.setSelected(true); getLauncher().launchYouTube("eRsGyueVLvQ", new Launcher.AppLaunchListener() { @Override public void onSuccess(LaunchSession session) { setRunningAppInfo(session); } @Override public void onError(ServiceCommandError error) { } }); } } }); } else { disableButton(youtubeButton); } browserButton.setSelected(false); netflixButton.setSelected(false); youtubeButton.setSelected(false); if ( getTv().hasCapability(Launcher.RunningApp_Subscribe) ) { runningAppSubs = getLauncher().subscribeRunningApp(new AppInfoListener() { @Override public void onSuccess(AppInfo appInfo) { adapter.setRunningAppId(appInfo.getId()); adapter.notifyDataSetChanged(); } @Override public void onError(ServiceCommandError error) { } }); } if ( getTv().hasCapability(Launcher.Application_List) ) { getTv().getLauncher().getAppList(new AppListListener() { @Override public void onSuccess(List<AppInfo> appList) { adapter.clear(); for (int i = 0; i < appList.size(); i++) { final AppInfo app = appList.get(i); adapter.add(app); } adapter.sort(); } @Override public void onError(ServiceCommandError error) { } }); } appListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { AppInfo appInfo = (AppInfo) arg0.getItemAtPosition(arg2); getLauncher().launchAppWithInfo(appInfo, null, new Launcher.AppLaunchListener() { @Override public void onSuccess(LaunchSession session) { setRunningAppInfo(session); } @Override public void onError(ServiceCommandError error) { } }); } }); if ( getTv().hasCapability(Launcher.Browser) ) { if ( getTv().hasCapability(Launcher.Browser_Params) ) { browserButton.setText("Open Google"); } else { browserButton.setText("Open Browser"); } } myAppButton.setEnabled(false); myAppButton.setOnClickListener(myAppLaunch); appStoreButton.setEnabled(getTv().hasCapability(Launcher.AppStore)); appStoreButton.setOnClickListener(launchAppStore); } public View.OnClickListener myAppLaunch = new View.OnClickListener() { @Override public void onClick(View v) { // TODO: Implement this. Log.d("LG", "Implement this"); } }; public View.OnClickListener launchAppStore = new View.OnClickListener() { @Override public void onClick(View v) { if (appStoreSession != null) { appStoreSession.close(new ResponseListener<Object>() { @Override public void onError(ServiceCommandError error) { Log.d("LG", "App Store close error: " + error); } @Override public void onSuccess(Object object) { Log.d("LG", "AppStore close success"); } }); appStoreSession = null; appStoreButton.setSelected(false); } else { String appId = null; if (getTv().getServiceByName("Netcast TV") != null) appId = "4168"; else if (getTv().getServiceByName("webOS TV") != null) appId = "youtube.leanback.v4"; else if (getTv().getServiceByName("Roku") != null) appId = "13535"; getLauncher().launchAppStore(appId, new AppLaunchListener() { @Override public void onError(ServiceCommandError error) { Log.d("LG", "App Store failed: " + error); } @Override public void onSuccess(LaunchSession object) { Log.d("LG", "App Store launched!"); appStoreSession = object; appStoreButton.setSelected(true); } }); } } }; @Override public void disableButtons() { if ( runningAppSubs != null ) runningAppSubs.unsubscribe(); adapter.clear(); super.disableButtons(); } public void setRunningAppInfo(LaunchSession session) { runningAppSession = session; } protected String getToastIconData() { return "iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEgAACxIB0t1+/AABe+9JREFUeNr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+SOSgZRNvdk25dbAHDv/sBmMo5PRVZ1GI4TW1eaVI5tcnMMViRqyyUNXEK3strBmHcD/wspv/JP/3g+/yWZWDey/aAJJSp0AzVfEMXFJtXBSAJx1q6OaevlDS8YB8YdszunFQwSWpDPzFHdAkwZ6AJtoJropcvANh2Op5dpmbnbexCVNB0kDOt5oDgKPXu8GzeHTD5k2qKMCKlsd9DkAdOnJz7900S6h/zvzMUN86VLQnJPHd+GiZ+/IL7gDOGhQNd/xf3Tp70y3tcfGSggl2qBjhuMAp7KGEv1vrmyaHPnhpF7vDcwoEDLRzAL12HeqJdZ0WQgxeMpJHwgqay6PEcMBottc3+OUYYInCxwD3f2Nz34lb5eJNesA7iH72fe+7m8XV0x9Z51SVI29GmG1ONcNpWdNKBozT/7JpYB9vNas3YcO4P32X//21XdblZ3lwlTBO/3JP/hd+1itWfsFcgDWrFmzDsCaNWvWAVizZs06AGvWrFkHYM2aNesArFmzZh2ANWvWrAOwZs2adQDWrFkHYM2aNesArFmzZh2ANWvWrAOwZs2adQDWrFmzDsCaNWvWAVizZs06AGvWrFkHYM2aNesArFmzZh2ANWvWrAOwZs2adQDWrFmzDsCaNWvWAVizZs06AGvWrFkHYM2atXvG/hs8R9ptcDTwswAAAABJRU5ErkJggg=="; } }
import java.io.BufferedInputStream; import java.net.ServerSocket; import java.net.Socket; import java.io.InputStream; public class ConnectionManager { private static final int timout = 3000; private static final int port = 9100; private static final boolean whileConnected = true; private static final int bufferSize = 1024; private static InputStream inputStream = null; public static void main (String args[]){ try { ServerSocket input = new ServerSocket(port); System.out.println("Starting server..."); while (whileConnected){ try { Socket connectionSocket = input.accept(); inputStream = new BufferedInputStream(connectionSocket.getInputStream()); int read; if (connectionSocket.isConnected()){ System.out.println("Socket is connected!"); } byte[] buffer = new byte[bufferSize]; while((read = inputStream.read(buffer)) != -1){ String message = new String(buffer, "ASCII").trim(); System.out.println(message); } } catch (Exception e) { System.out.println("Error sending message: " + e); } finally { inputStream.close(); } } } catch (Exception e){ System.out.println("Error: " + e); } finally { inputStream.close(); } } }
// Connect SDK Sample App by LG Electronics // To the extent possible under law, the person who associated CC0 with // to the sample app. package com.example.connect_sdk_sampler.fragments; import java.util.List; import android.content.Context; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.ListView; import com.connectsdk.core.AppInfo; import com.connectsdk.service.capability.Launcher; import com.connectsdk.service.capability.Launcher.AppInfoListener; import com.connectsdk.service.capability.Launcher.AppLaunchListener; import com.connectsdk.service.capability.Launcher.AppListListener; import com.connectsdk.service.capability.ToastControl; import com.connectsdk.service.capability.listeners.ResponseListener; import com.connectsdk.service.command.ServiceCommandError; import com.connectsdk.service.command.ServiceSubscription; import com.connectsdk.service.sessions.LaunchSession; import com.example.connect_sdk_sampler.R; import com.example.connect_sdk_sampler.widget.AppAdapter; public class AppsFragment extends BaseFragment { // public Button smartWorldButton; public Button browserButton; public Button myAppButton; public Button netflixButton; public Button appStoreButton; public Button youtubeButton; public Button toastButton; public ListView appListView; public AppAdapter adapter; LaunchSession runningAppSession; LaunchSession appStoreSession; LaunchSession myAppSession; ServiceSubscription<AppInfoListener> runningAppSubs; public AppsFragment(Context context) { super(context); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate( R.layout.fragment_apps, container, false); browserButton = (Button) rootView.findViewById(R.id.browserButton); myAppButton = (Button) rootView.findViewById(R.id.myApp); netflixButton = (Button) rootView.findViewById(R.id.deepLinkButton); appStoreButton = (Button) rootView.findViewById(R.id.appStoreButton); youtubeButton = (Button) rootView.findViewById(R.id.youtubeButton); toastButton = (Button) rootView.findViewById(R.id.toastButton); appListView = (ListView) rootView.findViewById(R.id.appListView); adapter = new AppAdapter(getContext(), R.layout.app_item); appListView.setAdapter(adapter); buttons = new Button[] { browserButton, netflixButton, youtubeButton, toastButton, myAppButton, appStoreButton }; return rootView; } @Override public void enableButtons() { super.enableButtons(); if ( getTv().hasCapability(Launcher.Browser) || getTv().hasCapability(Launcher.Browser_Params) ) { browserButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if ( browserButton.isSelected() ) { browserButton.setSelected(false); if (runningAppSession != null) { runningAppSession.close(null); } } else { browserButton.setSelected(true); getLauncher().launchBrowser("http://connectsdk.com/", new Launcher.AppLaunchListener() { public void onSuccess(LaunchSession session) { setRunningAppInfo(session); } public void onError(ServiceCommandError error) { } }); } } }); } else { disableButton(browserButton); } if ( getTv().hasCapability(ToastControl.Show_Toast) ) { toastButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { getToastControl().showToast("Yeah, toast!", getToastIconData(), "png", null); } }); } else { disableButton(toastButton); } if ( getTv().hasCapability(Launcher.Netflix) || getTv().hasCapability(Launcher.Netflix_Params) ) { netflixButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if ( netflixButton.isSelected() ) { netflixButton.setSelected(false); if (runningAppSession != null) { runningAppSession.close(null); } } else { netflixButton.setSelected(true); getLauncher().launchNetflix("70217913", new Launcher.AppLaunchListener() { @Override public void onSuccess(LaunchSession session) { setRunningAppInfo(session); } @Override public void onError(ServiceCommandError error) { } }); } } }); } else { disableButton(netflixButton); } if ( getTv().hasCapability(Launcher.YouTube) || getTv().hasCapability(Launcher.YouTube_Params) ) { youtubeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if ( youtubeButton.isSelected() ) { youtubeButton.setSelected(false); if (runningAppSession != null) { runningAppSession.close(null); } } else { youtubeButton.setSelected(true); getLauncher().launchYouTube("eRsGyueVLvQ", new Launcher.AppLaunchListener() { @Override public void onSuccess(LaunchSession session) { setRunningAppInfo(session); } @Override public void onError(ServiceCommandError error) { } }); } } }); } else { disableButton(youtubeButton); } browserButton.setSelected(false); netflixButton.setSelected(false); youtubeButton.setSelected(false); if ( getTv().hasCapability(Launcher.RunningApp_Subscribe) ) { runningAppSubs = getLauncher().subscribeRunningApp(new AppInfoListener() { @Override public void onSuccess(AppInfo appInfo) { adapter.setRunningAppId(appInfo.getId()); adapter.notifyDataSetChanged(); } @Override public void onError(ServiceCommandError error) { } }); } if ( getTv().hasCapability(Launcher.Application_List) ) { getTv().getLauncher().getAppList(new AppListListener() { @Override public void onSuccess(List<AppInfo> appList) { adapter.clear(); for (int i = 0; i < appList.size(); i++) { final AppInfo app = appList.get(i); adapter.add(app); } adapter.sort(); } @Override public void onError(ServiceCommandError error) { } }); } appListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { if (runningAppSession != null) { runningAppSession.close(null); } AppInfo appInfo = (AppInfo) arg0.getItemAtPosition(arg2); getLauncher().launchAppWithInfo(appInfo, null, new Launcher.AppLaunchListener() { @Override public void onSuccess(LaunchSession session) { setRunningAppInfo(session); } @Override public void onError(ServiceCommandError error) { } }); } }); if ( getTv().hasCapability(Launcher.Browser) ) { if ( getTv().hasCapability(Launcher.Browser_Params) ) { browserButton.setText("Open Google"); } else { browserButton.setText("Open Browser"); } } myAppButton.setEnabled(getTv().hasCapability("Launcher.Levak")); myAppButton.setOnClickListener(myAppLaunch); appStoreButton.setEnabled(getTv().hasCapability(Launcher.AppStore)); appStoreButton.setOnClickListener(launchAppStore); } public View.OnClickListener myAppLaunch = new View.OnClickListener() { @Override public void onClick(View v) { if (myAppSession != null) { myAppSession.close(null); myAppSession = null; myAppButton.setSelected(false); } else { getLauncher().launchApp("Levak", new AppLaunchListener() { @Override public void onError(ServiceCommandError error) { Log.d("LG", "My app failed: " + error); } @Override public void onSuccess(LaunchSession object) { myAppSession = object; myAppButton.setSelected(true); } }); } } }; public View.OnClickListener launchAppStore = new View.OnClickListener() { @Override public void onClick(View v) { if (appStoreSession != null) { appStoreSession.close(new ResponseListener<Object>() { @Override public void onError(ServiceCommandError error) { Log.d("LG", "App Store close error: " + error); } @Override public void onSuccess(Object object) { Log.d("LG", "AppStore close success"); } }); appStoreSession = null; appStoreButton.setSelected(false); } else { String appId = null; if (getTv().getServiceByName("Netcast TV") != null) appId = "125071"; else if (getTv().getServiceByName("webOS TV") != null) appId = "youtube.leanback.v4"; else if (getTv().getServiceByName("Roku") != null) appId = "13535"; getLauncher().launchAppStore(appId, new AppLaunchListener() { @Override public void onError(ServiceCommandError error) { Log.d("LG", "App Store failed: " + error); } @Override public void onSuccess(LaunchSession object) { Log.d("LG", "App Store launched!"); appStoreSession = object; appStoreButton.setSelected(true); } }); } } }; @Override public void disableButtons() { if ( runningAppSubs != null ) runningAppSubs.unsubscribe(); adapter.clear(); super.disableButtons(); } public void setRunningAppInfo(LaunchSession session) { runningAppSession = session; } protected String getToastIconData() { return mContext.getString(R.string.toast_icon_data); } }
package com.valkryst.VTerminal.builder.component; import com.valkryst.VJSON.VJSONParser; import com.valkryst.VTerminal.component.Button; import com.valkryst.VTerminal.misc.ColorFunctions; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import lombok.NonNull; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import java.awt.Color; @Data @NoArgsConstructor @EqualsAndHashCode(callSuper=true) public class ButtonBuilder extends ComponentBuilder<Button> implements VJSONParser { /** The text to display on the button. */ @NonNull private String text; /** The background color for when the button is in the normal state. */ @NonNull private Color backgroundColor_normal; /** The foreground color for when the button is in the normal state. */ @NonNull private Color foregroundColor_normal; /** The background color for when the button is in the hover state. */ @NonNull private Color backgroundColor_hover; /** The foreground color for when the button is in the hover state. */ @NonNull private Color foregroundColor_hover; /** The background color for when the button is in the pressed state. */ @NonNull private Color backgroundColor_pressed; /** The foreground color for when the button is in the pressed state. */ @NonNull private Color foregroundColor_pressed; /** The function to run when the button is clicked. */ private Runnable onClickFunction; @Override public Button build() { checkState(); super.width = text.length(); super.height = 1; return new Button(this); } /** Resets the builder to it's default state. */ public void reset() { super.reset(); text = ""; backgroundColor_normal = new Color(45, 45, 45, 255); foregroundColor_normal = new Color(0xFF2DBEFF, true); backgroundColor_hover = new Color(0xFF2DFF63, true); foregroundColor_hover = ColorFunctions.shade(backgroundColor_hover, 0.5); backgroundColor_pressed = ColorFunctions.shade(backgroundColor_hover, 0.25); foregroundColor_pressed = ColorFunctions.shade(foregroundColor_hover, 0.25); onClickFunction = () -> {}; } @Override public void parse(final @NonNull JSONObject jsonObject) { reset(); super.parse(jsonObject); final String text = (String) jsonObject.get("text"); if (text != null) { this.text = text; } try { this.backgroundColor_normal = getColor((JSONArray) jsonObject.get("backgroundColor_normal")); } catch (final NullPointerException ignored) {} try { this.foregroundColor_normal = getColor((JSONArray) jsonObject.get("foregroundColor_normal")); } catch (final NullPointerException ignored) {} try { this.backgroundColor_hover = getColor((JSONArray) jsonObject.get("backgroundColor_hover")); } catch (final NullPointerException ignored) {} try { this.foregroundColor_hover = getColor((JSONArray) jsonObject.get("foregroundColor_hover")); } catch (final NullPointerException ignored) {} try { this.backgroundColor_pressed = getColor((JSONArray) jsonObject.get("backgroundColor_pressed")); } catch (final NullPointerException ignored) {} try { this.foregroundColor_pressed = getColor((JSONArray) jsonObject.get("foregroundColor_pressed")); } catch (final NullPointerException ignored) {} } }
package com.vectrace.MercurialEclipse.history; import static com.vectrace.MercurialEclipse.preferences.MercurialPreferenceConstants.*; import java.lang.reflect.InvocationTargetException; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextOperationTarget; import org.eclipse.jface.text.TextViewer; import org.eclipse.jface.text.source.SourceViewer; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Menu; import org.eclipse.team.ui.TeamOperation; import org.eclipse.team.ui.history.IHistoryPageSite; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IWorkbenchActionConstants; import org.eclipse.ui.actions.BaseSelectionListenerAction; import org.eclipse.ui.part.IPageSite; import org.eclipse.ui.texteditor.ITextEditorActionConstants; import com.vectrace.MercurialEclipse.MercurialEclipsePlugin; import com.vectrace.MercurialEclipse.commands.HgPatchClient; import com.vectrace.MercurialEclipse.exception.HgException; import com.vectrace.MercurialEclipse.model.FileStatus; import com.vectrace.MercurialEclipse.utils.ResourceUtils; import com.vectrace.MercurialEclipse.wizards.Messages; public class ChangedPathsPage { private static final String IMG_COMMENTS = "comments.gif"; //$NON-NLS-1$ private static final String IMG_DIFFS = "diffs.gif"; //$NON-NLS-1$ private static final String IMG_AFFECTED_PATHS_FLAT_MODE = "flatLayout.gif"; //$NON-NLS-1$ private SashForm mainSashForm; private SashForm innerSashForm; private boolean showComments; private boolean showAffectedPaths; private boolean showDiffs; private boolean wrapCommentsText; private ChangePathsTableProvider changePathsViewer; private TextViewer commentTextViewer; private TextViewer diffTextViewer; // TODO find a more expressive name private Object currentPath; private final IPreferenceStore store = MercurialEclipsePlugin.getDefault() .getPreferenceStore(); private ToggleAffectedPathsOptionAction[] toggleAffectedPathsLayoutActions; private final MercurialHistoryPage page; public ChangedPathsPage(MercurialHistoryPage page, Composite parent) { this.page = page; init(parent); } private void init(Composite parent) { this.showComments = store.getBoolean(PREF_SHOW_COMMENTS); this.wrapCommentsText = store.getBoolean(PREF_WRAP_COMMENTS); this.showAffectedPaths = store.getBoolean(PREF_SHOW_PATHS); this.showDiffs = store.getBoolean(PREF_SHOW_DIFFS); this.mainSashForm = new SashForm(parent, SWT.VERTICAL); this.mainSashForm.setLayoutData(new GridData( GridData.FILL_BOTH)); this.toggleAffectedPathsLayoutActions = new ToggleAffectedPathsOptionAction[] { new ToggleAffectedPathsOptionAction(this, "HistoryView.affectedPathsHorizontalLayout", //$NON-NLS-1$ PREF_AFFECTED_PATHS_LAYOUT, LAYOUT_HORIZONTAL), new ToggleAffectedPathsOptionAction(this, "HistoryView.affectedPathsVerticalLayout", //$NON-NLS-1$ PREF_AFFECTED_PATHS_LAYOUT, LAYOUT_VERTICAL), }; } public void createControl() { createAffectedPathsViewer(); addSelectionListeners(); contributeActions(); } private void addSelectionListeners() { page.getTableViewer().addSelectionChangedListener( new ISelectionChangedListener() { private Object currentLogEntry; private int currentNumberOfSelectedElements; public void selectionChanged(SelectionChangedEvent event) { ISelection selection = event.getSelection(); Object logEntry = ((IStructuredSelection) selection).getFirstElement(); int nrOfSelectedElements = ((IStructuredSelection) selection).size(); if (logEntry != currentLogEntry || nrOfSelectedElements != currentNumberOfSelectedElements) { this.currentLogEntry = logEntry; this.currentNumberOfSelectedElements = nrOfSelectedElements; updatePanels(selection); } } }); changePathsViewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { ISelection selection = event.getSelection(); FileStatus path = (FileStatus) ((IStructuredSelection) selection) .getFirstElement(); if (path != currentPath) { ChangedPathsPage.this.currentPath = path; inDiffViewerScrollTo(path); } } }); } private void inDiffViewerScrollTo(FileStatus path) { if(path == null) { return; } String pathString = path.getRootRelativePath().toPortableString(); int indexOf = diffTextViewer.getDocument().get().indexOf(pathString); if(indexOf != -1) { diffTextViewer.setSelectedRange(indexOf, pathString.length()); try { int line = diffTextViewer.getDocument().getLineOfOffset(indexOf); diffTextViewer.setTopIndex(line); } catch (BadLocationException e) { MercurialEclipsePlugin.logError(e); } } } private void createAffectedPathsViewer() { int[] weights = null; weights = mainSashForm.getWeights(); if (innerSashForm != null) { innerSashForm.dispose(); } if (changePathsViewer != null) { changePathsViewer.getControl().dispose(); } int layout = store.getInt(PREF_AFFECTED_PATHS_LAYOUT); if (layout == LAYOUT_HORIZONTAL) { innerSashForm = new SashForm(mainSashForm, SWT.HORIZONTAL); createText(innerSashForm); changePathsViewer = new ChangePathsTableProvider(innerSashForm, this); createDiffViewer(innerSashForm); } else { innerSashForm = new SashForm(mainSashForm, SWT.VERTICAL); createText(innerSashForm); changePathsViewer = new ChangePathsTableProvider(innerSashForm, this); createDiffViewer(innerSashForm); } updatePanels(page.getTableViewer().getSelection()); setViewerVisibility(); innerSashForm.layout(); if (weights != null && weights.length == 2) { mainSashForm.setWeights(weights); } mainSashForm.layout(); } private void updatePanels(ISelection selection) { if (!(selection instanceof IStructuredSelection)) { clearTextChangePathsAndDiffTextViewers(); return; } IStructuredSelection ss = (IStructuredSelection) selection; int nrOfSelectedElements = ss.size(); if (nrOfSelectedElements == 1) { MercurialRevision entry = (MercurialRevision) ss.getFirstElement(); commentTextViewer.setDocument(new Document(entry.getChangeSet().getComment())); changePathsViewer.setInput(entry); updateDiffPanelFor(entry, null); } else if (nrOfSelectedElements == 2) { Object[] selectedElememts = ss.toArray(); MercurialRevision firstEntry = (MercurialRevision) selectedElememts[1]; MercurialRevision secondEntry = (MercurialRevision) selectedElememts[0]; commentTextViewer.setDocument(new Document()); changePathsViewer.setInput(null); updateDiffPanelFor(firstEntry, secondEntry); } else { clearTextChangePathsAndDiffTextViewers(); } } private void clearTextChangePathsAndDiffTextViewers() { commentTextViewer.setDocument(new Document("")); //$NON-NLS-1$ changePathsViewer.setInput(null); diffTextViewer.setDocument(new Document("")); } private void updateDiffPanelFor(final MercurialRevision entry, final MercurialRevision secondEntry) { TeamOperation operation = new TeamOperation(page.getHistoryPageSite().getPart(), null) { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { monitor.beginTask(getJobName(), 2); try { final String diff = HgPatchClient.getDiff(entry.getChangeSet().getHgRoot() , entry, secondEntry); monitor.worked(1); page.getControl().getDisplay().syncExec(new Runnable() { public void run() { diffTextViewer.setDocument(new Document(diff)); applyLineColoringToDiffViewer(); } }); monitor.worked(1); monitor.done(); } catch (HgException e) { MercurialEclipsePlugin.logError(e); } } @Override protected String getJobName() { // TODO Replace this with from resource return "Update diff viewer"; } @Override protected boolean shouldRun() { return true; } @Override protected boolean canRunAsJob() { return true; } @Override public boolean isUserInitiated() { return false; } }; try { operation.run(); } catch (InvocationTargetException e) { MercurialEclipsePlugin.logError(e); } catch (InterruptedException e) { MercurialEclipsePlugin.logError(e); } } private void applyLineColoringToDiffViewer() { IDocument document = diffTextViewer.getDocument(); int nrOfLines = document.getNumberOfLines(); for (int i = 0; i < nrOfLines; i++) { try { IRegion lineInformation = document.getLineInformation(i); int offset = lineInformation.getOffset(); int length = lineInformation.getLength(); Color lineColor = getDiffLineColor(document.get( offset, length)); diffTextViewer.setTextColor(lineColor, offset, length, true); } catch (BadLocationException e) { MercurialEclipsePlugin.logError(e); } } } private Color getDiffLineColor(String line) { Display display = this.diffTextViewer.getControl().getDisplay(); if(line.startsWith("diff ")) { return display.getSystemColor(SWT.COLOR_BLUE); } else if(line.startsWith("+++ ")) { return display.getSystemColor(SWT.COLOR_BLUE); } else if(line.startsWith(" return display.getSystemColor(SWT.COLOR_BLUE); } else if(line.startsWith("@@ ")) { return display.getSystemColor(SWT.COLOR_BLUE); } else if(line.startsWith("new file mode")) { return display.getSystemColor(SWT.COLOR_BLUE); } else if(line.startsWith("\\ ")) { return display.getSystemColor(SWT.COLOR_BLUE); } else if(line.startsWith("+")) { return display.getSystemColor(SWT.COLOR_DARK_GREEN); } else if(line.startsWith("-")) { return display.getSystemColor(SWT.COLOR_DARK_RED); } else { return display.getSystemColor(SWT.COLOR_BLACK); } } /** * @return may return null */ MercurialRevision getCurrentRevision() { return (MercurialRevision) changePathsViewer.getInput(); } /** * Create the TextViewer for the logEntry comments */ private void createText(Composite parent) { SourceViewer result = new SourceViewer(parent, null, null, true, SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI | SWT.READ_ONLY); result.getTextWidget().setIndent(2); this.commentTextViewer = result; // Create actions for the text editor (copy and select all) final TextViewerAction copyAction = new TextViewerAction( this.commentTextViewer, ITextOperationTarget.COPY); copyAction.setText(Messages.getString("HistoryView.copy")); this.commentTextViewer .addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { copyAction.update(); } }); final TextViewerAction selectAllAction = new TextViewerAction( this.commentTextViewer, ITextOperationTarget.SELECT_ALL); selectAllAction.setText(Messages.getString("HistoryView.selectAll")); IHistoryPageSite parentSite = getHistoryPageSite(); IPageSite pageSite = parentSite.getWorkbenchPageSite(); IActionBars actionBars = pageSite.getActionBars(); actionBars.setGlobalActionHandler(ITextEditorActionConstants.COPY, copyAction); actionBars.setGlobalActionHandler( ITextEditorActionConstants.SELECT_ALL, selectAllAction); actionBars.updateActionBars(); // Contribute actions to popup menu for the comments area MenuManager menuMgr = new MenuManager(); menuMgr.setRemoveAllWhenShown(true); menuMgr.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager menuMgr1) { menuMgr1.add(copyAction); menuMgr1.add(selectAllAction); } }); StyledText text = this.commentTextViewer.getTextWidget(); Menu menu = menuMgr.createContextMenu(text); text.setMenu(menu); } private void createDiffViewer(SashForm parent) { SourceViewer sourceViewer = new SourceViewer(parent, null, null, true, SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI | SWT.READ_ONLY); sourceViewer.getTextWidget().setIndent(2); diffTextViewer = sourceViewer; diffTextViewer.setDocument(new Document()); } private void contributeActions() { Action toggleShowComments = new Action(Messages .getString("HistoryView.showComments"), //$NON-NLS-1$ MercurialEclipsePlugin.getImageDescriptor(IMG_COMMENTS)) { @Override public void run() { showComments = isChecked(); setViewerVisibility(); store.setValue(PREF_SHOW_COMMENTS, showComments); } }; toggleShowComments.setChecked(showComments); Action toggleShowDiffs = new Action(Messages // TODO create new text & image .getString("HistoryView.showDiffs"), //$NON-NLS-1$ MercurialEclipsePlugin.getImageDescriptor(IMG_DIFFS)) { @Override public void run() { showDiffs = isChecked(); setViewerVisibility(); store.setValue(PREF_SHOW_DIFFS, showDiffs); } }; toggleShowDiffs.setChecked(showDiffs); // Toggle wrap comments action Action toggleWrapCommentsAction = new Action(Messages .getString("HistoryView.wrapComments")) { @Override public void run() { wrapCommentsText = isChecked(); setViewerVisibility(); store.setValue(PREF_WRAP_COMMENTS, wrapCommentsText); } }; toggleWrapCommentsAction.setChecked(wrapCommentsText); // Toggle path visible action Action toggleShowAffectedPathsAction = new Action(Messages .getString("HistoryView.showAffectedPaths"), //$NON-NLS-1$ MercurialEclipsePlugin .getImageDescriptor(IMG_AFFECTED_PATHS_FLAT_MODE)) { @Override public void run() { showAffectedPaths = isChecked(); setViewerVisibility(); store.setValue(PREF_SHOW_PATHS, showAffectedPaths); } }; toggleShowAffectedPathsAction.setChecked(showAffectedPaths); IHistoryPageSite parentSite = getHistoryPageSite(); IPageSite pageSite = parentSite.getWorkbenchPageSite(); IActionBars actionBars = pageSite.getActionBars(); // Contribute toggle text visible to the toolbar drop-down IMenuManager actionBarsMenu = actionBars.getMenuManager(); actionBarsMenu.add(toggleWrapCommentsAction); actionBarsMenu.add(new Separator()); actionBarsMenu.add(toggleShowComments); actionBarsMenu.add(toggleShowAffectedPathsAction); actionBarsMenu.add(toggleShowDiffs); actionBarsMenu.add(new Separator()); for (int i = 0; i < toggleAffectedPathsLayoutActions.length; i++) { actionBarsMenu.add(toggleAffectedPathsLayoutActions[i]); } // Create the local tool bar IToolBarManager tbm = actionBars.getToolBarManager(); tbm.add(new Separator()); tbm.add(toggleShowComments); tbm.add(toggleShowAffectedPathsAction); tbm.add(toggleShowDiffs); tbm.update(false); actionBars.updateActionBars(); final BaseSelectionListenerAction openAction = page.getOpenAction(); final BaseSelectionListenerAction openEditorAction = page.getOpenEditorAction(); final BaseSelectionListenerAction compareWithCurrent = page.getCompareWithCurrentAction(); final BaseSelectionListenerAction compareWithPrevious = page.getCompareWithPreviousAction(); final BaseSelectionListenerAction actionRevert = page.getRevertAction(); changePathsViewer.addDoubleClickListener(new IDoubleClickListener() { public void doubleClick(DoubleClickEvent event) { FileStatus fileStatus = (FileStatus) ((IStructuredSelection) event.getSelection()).getFirstElement(); MercurialRevision derived = getDerivedRevision(fileStatus, getCurrentRevision()); if(derived == null){ return; } StructuredSelection selection = new StructuredSelection(new Object[]{derived, fileStatus}); compareWithPrevious.selectionChanged(selection); compareWithPrevious.run(); } }); // Contribute actions to popup menu final MenuManager menuMgr = new MenuManager(); menuMgr.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager menuMgr1) { IStructuredSelection selection = (IStructuredSelection) changePathsViewer.getSelection(); if(selection.isEmpty()){ return; } FileStatus fileStatus = (FileStatus) selection.getFirstElement(); MercurialRevision base = getCurrentRevision(); MercurialRevision derived = getDerivedRevision(fileStatus, base); if(derived == null){ // XXX currently files outside workspace are not supported... return; } selection = new StructuredSelection(derived); openAction.selectionChanged(selection); openEditorAction.selectionChanged(selection); compareWithCurrent.selectionChanged(selection); selection = new StructuredSelection(new Object[]{derived, fileStatus}); compareWithPrevious.selectionChanged(selection); menuMgr1.add(openAction); menuMgr1.add(openEditorAction); menuMgr1.add(new Separator(IWorkbenchActionConstants.GROUP_FILE)); menuMgr1.add(compareWithCurrent); menuMgr1.add(compareWithPrevious); menuMgr1.add(new Separator()); selection = new StructuredSelection(new Object[]{derived}); actionRevert.selectionChanged(selection); menuMgr1.add(actionRevert); } }); menuMgr.setRemoveAllWhenShown(true); changePathsViewer.getTable().setMenu(menuMgr.createContextMenu(changePathsViewer.getTable())); } private void setViewerVisibility() { boolean lowerPartVisible = showAffectedPaths || showComments || showDiffs; mainSashForm.setMaximizedControl(lowerPartVisible ? null : getChangesetsTableControl()); if(!lowerPartVisible) { return; } int[] weights = { showComments ? 1 : 0, showAffectedPaths ? 1 : 0, showDiffs ? 1 : 0 }; innerSashForm.setWeights(weights); commentTextViewer.getTextWidget().setWordWrap(wrapCommentsText); } private Composite getChangesetsTableControl() { return page.getTableViewer().getControl().getParent(); } public static class ToggleAffectedPathsOptionAction extends Action { private final ChangedPathsPage page; private final String preferenceName; private final int value; public ToggleAffectedPathsOptionAction(ChangedPathsPage page, String label, String preferenceName, int value) { super(Messages.getString(label), AS_RADIO_BUTTON); this.page = page; this.preferenceName = preferenceName; this.value = value; IPreferenceStore store = MercurialEclipsePlugin.getDefault() .getPreferenceStore(); setChecked(value == store.getInt(preferenceName)); } @Override public void run() { if (isChecked()) { MercurialEclipsePlugin.getDefault().getPreferenceStore() .setValue(preferenceName, value); page.createAffectedPathsViewer(); } } } public MercurialHistoryPage getHistoryPage() { return page; } public IHistoryPageSite getHistoryPageSite() { return page.getHistoryPageSite(); } public Composite getControl() { return mainSashForm; } public boolean isShowChangePaths() { return showAffectedPaths; } public MercurialHistory getMercurialHistory() { return page.getMercurialHistory(); } /** * @return might return null, if the file is outside Eclipse workspace */ private MercurialRevision getDerivedRevision(FileStatus fileStatus, MercurialRevision base) { IFile file = ResourceUtils.getFileHandle(fileStatus.getAbsolutePath()); if(file == null){ return null; } MercurialRevision derived = new MercurialRevision(base.getChangeSet(), base .getGChangeSet(), file, null, null); return derived; } }
package c5db.interfaces; import c5db.interfaces.server.CommandRpcRequest; import c5db.messages.generated.CommandReply; import c5db.messages.generated.ModuleType; import org.jetlang.channels.Request; @ModuleTypeBinding(value = ModuleType.ControlRpc) public interface ControlModule extends C5Module { void doMessage(Request<CommandRpcRequest<?>, CommandReply> request); }
package de.uni.freiburg.iig.telematik.wolfgang; import java.io.File; //import java.util.ArrayList; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.filechooser.FileFilter; //import com.apple.eawt.AppEvent.OpenFilesEvent; import de.invation.code.toval.graphic.misc.AbstractStartup; import de.invation.code.toval.os.OSType; import de.invation.code.toval.os.OSUtils; import de.uni.freiburg.iig.telematik.sepia.graphic.AbstractGraphicalPN; import de.uni.freiburg.iig.telematik.sepia.graphic.GraphicalCPN; import de.uni.freiburg.iig.telematik.sepia.graphic.GraphicalPTNet; import de.uni.freiburg.iig.telematik.sepia.parser.pnml.PNMLParser; import de.uni.freiburg.iig.telematik.sepia.petrinet.NetType; import de.uni.freiburg.iig.telematik.wolfgang.editor.NetTypeChooserDialog; import de.uni.freiburg.iig.telematik.wolfgang.editor.WolfgangCPN; import de.uni.freiburg.iig.telematik.wolfgang.editor.WolfgangPT; import de.uni.freiburg.iig.telematik.wolfgang.editor.properties.EditorProperties; public class WolfgangStartup extends AbstractStartup { private static final String TOOL_NAME = "Wolfgang"; private static String[] filePaths; private static WolfgangStartup wg; @Override protected String getToolName() { return TOOL_NAME; } @Override protected void startApplication() throws Exception { if (filePaths == null) { NetTypeChooserDialog dialog = new NetTypeChooserDialog(null); NetType chosenNetType = dialog.getChosenNetType(); if (chosenNetType == null) { if (dialog.openNetOption()) { tryToOpenNet(); } } else { setLookAndFeel(); switch (chosenNetType) { case CPN: new WolfgangCPN().setUpGUI(); break; case PTNet: new WolfgangPT().setUpGUI(); break; default: } } } else { tryToOpenNet(); } } private void tryToOpenNet() throws Exception { if (filePaths == null) { setLookAndFeel(); JFileChooser fc; fc = new JFileChooser(OSUtils.getUserHomeDirectory()); fc.removeChoosableFileFilter(fc.getFileFilter()); fc.addChoosableFileFilter(new FileFilter() { @Override public String getDescription() { return "PNML Documents (*.pnml)"; } @Override public boolean accept(File f) { if (f.isDirectory()) { return true; } else { return f.getName().toLowerCase().endsWith(".pnml"); } } }); fc.setDialogTitle("Load PNML"); int returnVal = fc.showDialog(null, "load PNML"); if (returnVal == JFileChooser.APPROVE_OPTION) { String filename = fc.getSelectedFile().getAbsolutePath(); System.out.println(filename); openPNMLFile(filename); } else { startApplication(); } } else { for (String path : filePaths) openPNMLFile(path); } // filePath = null; } private void openPNMLFile(String filename) throws Exception { if (!filename.toLowerCase().endsWith(".pnml")) { if(!filename.startsWith("-psn_"))//Catching OS X specific argument on the very first startup JOptionPane.showMessageDialog(null, "File \""+filename+"\" is not in .pnml format", "Open Error", JOptionPane.ERROR_MESSAGE); filePaths = null; startApplication(); } else { @SuppressWarnings("rawtypes") AbstractGraphicalPN net = new PNMLParser().parse(filename, EditorProperties.getInstance().getRequestNetType(), EditorProperties.getInstance().getPNValidation()); switch (net.getPetriNet().getNetType()) { case CPN: new WolfgangCPN((GraphicalCPN) net).setUpGUI(); break; case PTNet: new WolfgangPT((GraphicalPTNet) net).setUpGUI(); break; default: throw new Exception("Incompatible net type: " + net.getPetriNet().getNetType()); } } } private void setLookAndFeel() { if (OSUtils.getCurrentOS() == OSType.OS_LINUX) { try { UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel"); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) { } } else if (OSUtils.getCurrentOS() == OSType.OS_WINDOWS) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) { } } } public static void main(String[] args) { // com.apple.eawt.Application app = com.apple.eawt.Application.getApplication(); // app.setOpenFileHandler(new com.apple.eawt.OpenFilesHandler() { // @Override // public void openFiles(OpenFilesEvent ofe) { // if (args.length > 0) { // filePaths = args; // String[] localArgs = new String[ofe.getFiles().size()]; // for (int i = 0; ofe.getFiles().size() > i; i++) { // localArgs[i] = ofe.getFiles().get(i).getAbsolutePath(); // filePaths = localArgs; // if (wg != null) { // try { // wg.tryToOpenNet(); // } catch (Exception e) { // JOptionPane.showMessageDialog(null, "Failed to open file"); if (args.length > 0) { filePaths = args; } wg = new WolfgangStartup(); } }
package dr.evomodel.branchratemodel; import dr.evolution.tree.NodeRef; import dr.evolution.tree.Tree; import dr.evolution.tree.TreeTrait; import dr.evomodel.tree.TreeModel; import dr.evomodel.tree.TreeParameterModel; import dr.inference.markovjumps.TwoStateOccupancyMarkovReward; import dr.inference.model.AbstractModelLikelihood; import dr.inference.model.Model; import dr.inference.model.Parameter; import dr.inference.model.Variable; /** * LatentStateBranchRateModel * * @author Andrew Rambaut * @author Marc Suchard * @version $Id$ * <p/> * $HeadURL$ * <p/> * $LastChangedBy$ * $LastChangedDate$ * $LastChangedRevision$ */ public class LatentStateBranchRateModel extends AbstractModelLikelihood implements BranchRateModel { public static final String LATENT_STATE_BRANCH_RATE_MODEL = "latentStateBranchRateModel"; public static final boolean USE_CACHING = true; // seed 666, caching off: 204.69 seconds for 20000 states // state 20000 -5510.2520 // 85.7% 5202 + 6 dr.inference.markovjumps.SericolaSeriesMarkovReward.accumulatePdf // seed 666, caching on: 119.43 seconds for 20000 states // state 20000 -5510.2520 // 83.4% 3156 + 4 dr.inference.markovjumps.SericolaSeriesMarkovReward.accumulatePdf private final TreeModel tree; private final BranchRateModel nonLatentRateModel; private final Parameter latentTransitionRateParameter; private final Parameter latentTransitionFrequencyParameter; private final TreeParameterModel latentStateProportions; private final Parameter latentStateProportionParameter; private final CountableBranchCategoryProvider branchCategoryProvider; private TwoStateOccupancyMarkovReward markovReward; private TwoStateOccupancyMarkovReward storedMarkovReward; private boolean likelihoodKnown = false; private boolean storedLikelihoodKnown; private double logLikelihood; private double storedLogLikelihood; private double[] branchLikelihoods; private double[] storedbranchLikelihoods; private boolean[] updateBranch; private boolean[] storedUpdateBranch; private boolean[] updateCategory; private boolean[] storedUpdateCategory; public LatentStateBranchRateModel(String name, TreeModel treeModel, BranchRateModel nonLatentRateModel, Parameter latentTransitionRateParameter, Parameter latentTransitionFrequencyParameter, Parameter latentStateProportionParameter, CountableBranchCategoryProvider branchCategoryProvider) { super(name); this.tree = treeModel; addModel(tree); this.nonLatentRateModel = nonLatentRateModel; addModel(nonLatentRateModel); this.latentTransitionRateParameter = latentTransitionRateParameter; addVariable(latentTransitionRateParameter); this.latentTransitionFrequencyParameter = latentTransitionFrequencyParameter; addVariable(latentTransitionFrequencyParameter); if (branchCategoryProvider == null) { this.latentStateProportions = new TreeParameterModel(tree, latentStateProportionParameter, false, Intent.BRANCH); addModel(latentStateProportions); this.latentStateProportionParameter = null; this.branchCategoryProvider = null; } else { this.latentStateProportions = null; this.branchCategoryProvider = branchCategoryProvider; this.latentStateProportionParameter = latentStateProportionParameter; this.latentStateProportionParameter.setDimension(branchCategoryProvider.getCategoryCount()); if (USE_CACHING) { updateCategory = new boolean[branchCategoryProvider.getCategoryCount()]; storedUpdateCategory = new boolean[branchCategoryProvider.getCategoryCount()]; setUpdateAllCategories(); } addVariable(latentStateProportionParameter); } branchLikelihoods = new double[tree.getNodeCount()]; if (USE_CACHING) { updateBranch = new boolean[tree.getNodeCount()]; storedUpdateBranch = new boolean[tree.getNodeCount()]; storedbranchLikelihoods = new double[tree.getNodeCount()]; setUpdateAllBranches(); } } public LatentStateBranchRateModel(Parameter rate, Parameter prop) { super(LATENT_STATE_BRANCH_RATE_MODEL); tree = null; nonLatentRateModel = null; latentTransitionRateParameter = rate; latentTransitionFrequencyParameter = prop; latentStateProportions = null; this.latentStateProportionParameter = null; this.branchCategoryProvider = null; } private double[] createLatentInfinitesimalMatrix() { final double rate = latentTransitionRateParameter.getParameterValue(0); final double prop = latentTransitionFrequencyParameter.getParameterValue(0); double[] mat = new double[]{ -rate * prop, rate * prop, rate * (1.0 - prop), -rate * (1.0 - prop) }; return mat; } private static double[] createReward() { return new double[]{0.0, 1.0}; } private TwoStateOccupancyMarkovReward createMarkovReward() { TwoStateOccupancyMarkovReward markovReward = new TwoStateOccupancyMarkovReward(createLatentInfinitesimalMatrix()); return markovReward; } public TwoStateOccupancyMarkovReward getMarkovReward() { if (markovReward == null) { markovReward = createMarkovReward(); } return markovReward; } @Override public double getBranchRate(Tree tree, NodeRef node) { double nonLatentRate = nonLatentRateModel.getBranchRate(tree, node); double latentProportion = getLatentProportion(tree, node); return calculateBranchRate(nonLatentRate, latentProportion); } public double getLatentProportion(Tree tree, NodeRef node) { if (latentStateProportions != null) { return latentStateProportions.getNodeValue(tree, node); } else { return latentStateProportionParameter.getParameterValue(branchCategoryProvider.getBranchCategory(tree, node)); } } private double calculateBranchRate(double nonLatentRate, double latentProportion) { return nonLatentRate * (1.0 - latentProportion); } @Override protected void handleModelChangedEvent(Model model, Object object, int index) { if (model == tree) { likelihoodKnown = false; // node heights change elapsed times on branches, TODO could cache if (index == -1) { setUpdateAllBranches(); } else { setUpdateBranch(index); } } else if (model == nonLatentRateModel) { // rates will change but the latent proportions haven't so the density is unchanged } else if (model == latentStateProportions) { likelihoodKnown = false; // argument of density has changed if (index == -1) { setUpdateAllBranches(); } else { setUpdateBranch(index); } } fireModelChanged(); } @Override protected void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) { if (variable == latentTransitionFrequencyParameter || variable == latentTransitionRateParameter) { // markovReward computations have changed markovReward = null; setUpdateAllBranches(); likelihoodKnown = false; } else if (variable == latentStateProportionParameter) { if (index == -1) { setUpdateAllBranches(); } else { setUpdateBranchCategory(index); } likelihoodKnown = false; fireModelChanged(); } } private void setUpdateBranch(int nodeNumber) { if (USE_CACHING) { updateBranch[nodeNumber] = true; } } private void setUpdateAllBranches() { if (USE_CACHING) { for (int i = 0; i < updateBranch.length; i++) { updateBranch[i] = true; } } } private void clearUpdateAllBranches() { if (USE_CACHING) { for (int i = 0; i < updateBranch.length; i++) { updateBranch[i] = false; } } } private void setUpdateBranchCategory(int category) { if (USE_CACHING) { updateCategory[category] = true; } } private void setUpdateAllCategories() { if (USE_CACHING) { for (int i = 0; i < updateCategory.length; i++) { updateCategory[i] = true; } } } private void clearAllCategories() { if (USE_CACHING && updateCategory != null) { for (int i = 0; i < updateCategory.length; i++) { updateCategory[i] = false; } } } @Override protected void storeState() { storedMarkovReward = markovReward; storedLogLikelihood = logLikelihood; storedLikelihoodKnown = likelihoodKnown; if (USE_CACHING) { System.arraycopy(branchLikelihoods, 0, storedbranchLikelihoods, 0, branchLikelihoods.length); System.arraycopy(updateBranch, 0, storedUpdateBranch, 0, updateBranch.length); if (updateCategory != null) { System.arraycopy(updateCategory, 0, storedUpdateCategory, 0, updateCategory.length); } } } @Override protected void restoreState() { markovReward = storedMarkovReward; logLikelihood = storedLogLikelihood; likelihoodKnown = storedLikelihoodKnown; if (USE_CACHING) { double[] tmp = branchLikelihoods; branchLikelihoods = storedbranchLikelihoods; storedbranchLikelihoods = tmp; boolean[] tmp2 = updateBranch; updateBranch = storedUpdateBranch; storedUpdateBranch = tmp2; boolean[] tmp3 = updateCategory; updateCategory = storedUpdateCategory; storedUpdateCategory = tmp3; } } @Override protected void acceptState() { } @Override public Model getModel() { return this; } @Override public double getLogLikelihood() { if (!likelihoodKnown) { logLikelihood = calculateLogLikelihood(); likelihoodKnown = true; } return logLikelihood; } private double calculateLogLikelihood() { double logLike = 0.0; for (int i = 0; i < tree.getInternalNodeCount(); ++i) { NodeRef node = tree.getNode(i); if (node != tree.getRoot()) { if (updateNeededForNode(tree, node)) { double branchLength = tree.getBranchLength(node); double latentProportion = getLatentProportion(tree, node); assert(latentProportion < 1.0); double density = getBranchRewardDensity(latentProportion, branchLength); branchLikelihoods[node.getNumber()] = Math.log(density); } logLike += branchLikelihoods[node.getNumber()]; } } clearUpdateAllBranches(); clearAllCategories(); return logLike; } private boolean updateNeededForNode(Tree tree, NodeRef node) { if (USE_CACHING) { return (updateCategory != null && updateCategory[branchCategoryProvider.getBranchCategory(tree, node)]) || updateBranch[node.getNumber()]; } else { return true; } } public double getBranchRewardDensity(double proportion, double branchLength) { if (markovReward == null) { markovReward = createMarkovReward(); } // int state = 0 * 2 + 0; // just start = end = 0 entry // Reward is [0,1], and we want to track time in latent state (= 1). // Therefore all nodes are in state 0 // double joint = markovReward.computePdf(reward, branchLength)[state]; final double joint = markovReward.computePdf(proportion * branchLength, branchLength, 0, 0); final double marg = markovReward.computeConditionalProbability(branchLength, 0, 0); final double rate = latentTransitionRateParameter.getParameterValue(0) * latentTransitionFrequencyParameter.getParameterValue(0) * branchLength; final double zeroJumps = Math.exp(-rate); // Check numerical tolerance if (marg - zeroJumps <= 0.0) { return 0.0; } // TODO Overhead in creating double[] could be saved by changing signature to computePdf double density = joint / (marg - zeroJumps); // conditional on ending state and >= 2 jumps density *= branchLength; // random variable is latentProportion = reward / branchLength, so include Jacobian if (DEBUG) { if (Double.isInfinite(Math.log(density))) { System.err.println("Infinite density in LatentStateBranchRateModel:"); System.err.println("proportion = " + proportion); System.err.println("branchLength = " + branchLength); System.err.println("lTRP = " + latentTransitionRateParameter.getParameterValue(0)); System.err.println("lTFP = " + latentTransitionFrequencyParameter.getParameterValue(0)); System.err.println("rate = " + rate); System.err.println("joint = " + joint); System.err.println("marg = " + marg); System.err.println("zero = " + zeroJumps); System.err.println("Hit debugger"); final double joint2 = markovReward.computePdf(proportion * branchLength, branchLength, 0, 0); final double marg2 = markovReward.computeConditionalProbability(branchLength, 0, 0); } } return density; } @Override public void makeDirty() { likelihoodKnown = false; markovReward = null; setUpdateAllBranches(); } @Override public String getTraitName() { return BranchRateModel.RATE; } @Override public Intent getIntent() { return Intent.BRANCH; } @Override public TreeTrait getTreeTrait(final String key) { if (key.equals(BranchRateModel.RATE)) { return this; } else if (latentStateProportions != null && key.equals(latentStateProportions.getTraitName())) { return latentStateProportions; } else if (branchCategoryProvider != null && key.equals(branchCategoryProvider.getTraitName())) { return branchCategoryProvider; } else { throw new IllegalArgumentException("Unrecognised Tree Trait key, " + key); } } @Override public TreeTrait[] getTreeTraits() { return new TreeTrait[]{this, latentStateProportions, branchCategoryProvider}; } @Override public Class getTraitClass() { return Double.class; } @Override public boolean getLoggable() { return true; } @Override public Double getTrait(final Tree tree, final NodeRef node) { return getBranchRate(tree, node); } @Override public String getTraitString(final Tree tree, final NodeRef node) { return Double.toString(getBranchRate(tree, node)); } public static void main(String[] args) { Parameter rate = new Parameter.Default(4.4); Parameter prop = new Parameter.Default(0.25); LatentStateBranchRateModel model = new LatentStateBranchRateModel(rate, prop); double branchLength = 2.0; for (double reward = 0; reward < branchLength; reward += 0.01) { System.out.println(reward + ",\t" + model.getBranchRewardDensity(reward, branchLength) + ","); } System.out.println(); System.out.println(model.getMarkovReward()); } private static boolean DEBUG = true; }
package edu.psu.compbio.seqcode.projects.naomi; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import org.apache.commons.math3.analysis.polynomials.PolynomialFunction; import org.apache.commons.math3.distribution.NormalDistribution; import edu.psu.compbio.seqcode.deepseq.StrandedBaseCount; import edu.psu.compbio.seqcode.deepseq.experiments.ExperimentManager; import edu.psu.compbio.seqcode.deepseq.experiments.ExptConfig; import edu.psu.compbio.seqcode.deepseq.experiments.Sample; import edu.psu.compbio.seqcode.genome.Genome; import edu.psu.compbio.seqcode.genome.GenomeConfig; import edu.psu.compbio.seqcode.genome.location.Region; import edu.psu.compbio.seqcode.gse.gsebricks.verbs.location.ChromosomeGenerator; import edu.psu.compbio.seqcode.gse.tools.utils.Args; import edu.psu.compbio.seqcode.projects.seed.SEEDConfig; /** * DifferentialMSR: * * Methods refer to two papers * Probabilistic Multiscale Image Segmentation, Vincken et al. IEEE (1997) * * @author naomi yamada * **/ public class DifferentialMSR { protected GenomeConfig gconfig; protected ExptConfig econfig; protected SEEDConfig sconfig; protected int threePrimReadExt = 200; protected int binWidth = 1; //Map<chrm, Map<scale space, Set<segmentation>>> protected Map<Region, Map<Integer,Set<Integer>>> segmentationTree; public DifferentialMSR(GenomeConfig gcon, ExptConfig econ, SEEDConfig scon){ gconfig = gcon; econfig = econ; sconfig = scon; } public void buildMSR(){ /********************* * Gaussian scale space and window parameters */ // arbitrary number of scale int numScale= 5; double DELTA_TAU = 0.5*Math.log(2); double MINIMUM_VALUE = Math.pow(10, -100); //arbitrary minimum value; I cannot use Double.MIN_VALUE because it can become zero // I have to determine P_MIN value carefully because P_MIN will substantially affect Gaussian window size double P_MIN = Math.pow(10,-3); double K_MIN = 1/Math.sqrt(1-Math.exp(-2*DELTA_TAU)); double K_N = Math.ceil(K_MIN); /********************* * Linkage parameters */ double WEIGHT_I = 1.00; double WEIGHT_G = 0.0000001; double WEIGHT_M = 1000; /********************* * Matrices parameters */ double sigma[] = new double[numScale]; double radius[] = new double[numScale]; for (int i = 0; i<numScale;i++){ sigma[i] = 1; radius[i] = 1; } ExperimentManager manager = new ExperimentManager(econfig); Genome genome = gconfig.getGenome(); //test to print whole chromosomes System.out.println(genome.getChromList()); System.out.println("before: "+binWidth+"\t"+threePrimReadExt); //fix here to get parameters only if they are specified binWidth = sconfig.getBinWidth(); threePrimReadExt = sconfig.getTag3PrimeExtension(); //test to print binWidth and threePrimReadExt System.out.println("binWidth is: "+binWidth); System.out.println("threePrimReadExt is: "+threePrimReadExt); Iterator<Region> chroms = new ChromosomeGenerator<Genome>().execute(genome); //iterating each chromosome (each chromosome is a region). while (chroms.hasNext()) { Region currChrom = chroms.next(); //previously it was below. but I don't think I need +1 here //int currchromSize= currChrom.getWidth()+1 int currchromSize = currChrom.getWidth(); int currchromBinSize = (int) Math.ceil(currchromSize/binWidth); //primitive matrix to store signal and the subsequent convolved signals //its index correspond to the coordinates float[][] GaussianBlur = new float[currchromBinSize][2]; for (int i = 0;i<currchromBinSize;i++){ for (int j = 0; j<2;j++) GaussianBlur[i][j] = 0; } //get StrandedBaseCount list for each chromosome Map<Sample, List<StrandedBaseCount>> sampleCountsMap = new HashMap<Sample, List<StrandedBaseCount>>(); for (Sample sample : manager.getSamples()) sampleCountsMap.put(sample,sample.getBases(currChrom)); //StrandedBasedCount object contains positive and negative strand separately //store all base counts indexed by positions at column[1] //extend reads to 3' end and bin according to bin size for (Sample sample : manager.getSamples()){ List<StrandedBaseCount> currentCounts = sampleCountsMap.get(sample); for (StrandedBaseCount hits: currentCounts){ for (int i = 0; i<threePrimReadExt+1; i++){ if (hits.getStrand()=='+' && hits.getCoordinate()+i<currchromSize){ GaussianBlur[(int) Math.ceil((hits.getCoordinate()+i)/binWidth)][1]+=hits.getCount(); }else if (hits.getStrand()=='+' && hits.getCoordinate()-i >=0){ GaussianBlur[(int) Math.ceil((hits.getCoordinate()-i)/binWidth)][1]+=hits.getCount(); } } } currentCounts = null; } //testing if (currchromSize > 200000000){ System.out.println("current Chrom is: "+currChrom.getChrom()); for (int i = 0; i< 100;i++) System.out.println(GaussianBlur[(int) Math.ceil((92943501)/binWidth)+i][1]); } /********************* * Starting nodes */ //linkageMap contains index of kids and parents HashMap <Integer, Integer> linkageMap = new HashMap<Integer, Integer>(); //adding starting nodes; to qualify for the starting nodes the signal intensity needs to be different from the subsequent signal intensity //adding the starting and end positions in the kids at start and end positions //setting max & min signal intensity float DImax = 0; float DImin = (float) Integer.MAX_VALUE; List <Integer> nonzeroList = new ArrayList<Integer>(); linkageMap.put(0,0); for (int i = 0 ; i< GaussianBlur.length-1; i++){ //should I start if (GaussianBlur[i][1] != GaussianBlur[i+1][1]) linkageMap.put(i,0); if (GaussianBlur[i][1] > DImax) DImax = GaussianBlur[i][1]; if (GaussianBlur[i][1] < DImin) DImin = GaussianBlur[i][1]; if (GaussianBlur[i][1]!=0) nonzeroList.add(i); } linkageMap.put(GaussianBlur.length-1,0); //copy to segmentation tree Map<Integer,Set<Integer>> currScale =new HashMap<Integer,Set<Integer>>(); currScale.put(1, linkageMap.keySet()); //determine the first nonzero and last nonzero from signal //check here ; sometimes it produces zero for DImax, DImin, trailingZero, zeroEnd int trailingZero = 0; int zeroEnd = 0; if (!nonzeroList.isEmpty()){ trailingZero = Collections.min(nonzeroList)-1; zeroEnd = Collections.max(nonzeroList)+1; } if (trailingZero == -1) trailingZero = 0; System.out.println("DImax is: "+DImax+"\t"+"DImin is: "+DImin+ "\t"+"trailingZero: "+trailingZero+"\t"+"zeroEnd"+"\t"+zeroEnd); for (int n = 1;n < numScale; n++){ /********************* * Gaussian scale space */ double polyCoeffi[] = new double [currchromBinSize]; //first copy from column[1] to column[0];this procedure need to be repeated for each iteration of scale //also copy from column[1] to array to store polynomial coefficient for (int i = 0 ; i<currchromBinSize; i++){ GaussianBlur[i][0]=GaussianBlur[i][1]; if (GaussianBlur[i][1] != 0){ polyCoeffi[i]=GaussianBlur[i][1]; }else{ polyCoeffi[i]=MINIMUM_VALUE; } } //sigma calculation sigma[n] = Math.exp(n*DELTA_TAU); // create normal distribution with mean zero and sigma[n] NormalDistribution normDistribution = new NormalDistribution(0.00,sigma[n]); //take inverse CDF based on the normal distribution using probability double inverseCDF = normDistribution.inverseCumulativeProbability(P_MIN); int windowSize = (int) (-Math.round(inverseCDF)*2+1); //window calculation based on Gaussian(normal) distribution with sigma, mean=zero,x=X[i] double window[] = new double[windowSize]; double windowSum = 0; for (int i = 0;i<windowSize;i++){ window[i] = normDistribution.density(Math.round(inverseCDF)+i); windowSum = windowSum+window[i]; } double normalizedWindow[]=new double[windowSize]; for (int i = 0;i<windowSize;i++) normalizedWindow[i] = window[i]/windowSum; //multiplying by polynomial ; I have to test to see how this works PolynomialFunction poly1 = new PolynomialFunction(polyCoeffi); PolynomialFunction poly2 = new PolynomialFunction(normalizedWindow); PolynomialFunction polyMultiplication=poly1.multiply(poly2); double coefficients[]= polyMultiplication.getCoefficients(); //taking mid point of polynomial coefficients int polyMid = (int) Math.floor(coefficients.length/2); System.out.println("currchromBin Size is : "+currchromBinSize+"\t"+ "windowSize is: "+windowSize+"\t"+"coefficients length is: "+coefficients.length+"polyMid is: "+polyMid); //copy Gaussian blur results to the column[1] // I should check to make sure that it's not off by 1 for (int i = 0; i<currchromBinSize;i++){ if (currchromBinSize % 2 ==0 && coefficients.length/2 == 1) GaussianBlur[i][1]=(float) coefficients[polyMid-currchromBinSize/2+i+1]; else GaussianBlur[i][1]=(float) coefficients[polyMid-currchromBinSize/2+i]; } //testing if (currchromSize > 200000000){ System.out.println("current Chrom is: "+currChrom.getChrom()); for (int i = 0; i< 100;i++) System.out.println(GaussianBlur[(int) Math.ceil((92943501)/binWidth)+i][0]+" : "+GaussianBlur[(int) Math.ceil((92943501)/binWidth)+i][1]); } /*************** * Search Volume */ double tempRadius; if (n==1){ tempRadius = sigma[n]; }else{ tempRadius = Math.sqrt(Math.pow(sigma[n],2)-Math.pow(sigma[n-1], 2)); } radius[n] = Math.ceil(K_MIN*tempRadius); int DCPsize = (int) (Math.round(radius[n])*2+1); int dcp[] = new int[DCPsize]; double distanceFactor[] = new double[DCPsize]; double affectionDistance; double denom = -2*(Math.pow(sigma[n], 2)-Math.pow(sigma[n-1],2)); for (int i = 0; i<DCPsize;i++){ dcp[i] = (int) -Math.round(radius[n])+i; // applying equation 7 in Vincken(1997) affectionDistance=Math.exp(Math.pow(dcp[i], 2)/denom)/Math.exp(Math.pow(0.5*sigma[n],2)/denom); //applying equation 8 in Vincken (1997) if (Math.abs(dcp[i]) > 0.5*sigma[n]){distanceFactor[i]= affectionDistance;} else{distanceFactor[i] = 1.0000;} } //test // System.out.println("DCP size is: "+DCPsize); // for (int i = 0; i<DCPsize;i++){ // System.out.println(distanceFactor[i]); /*************** * Linkage Loop */ TreeMap<Integer, Integer> GvParents = new TreeMap<Integer,Integer>(); if (DCPsize < 50){ /*********** * Over window */ //build segmentTree //First iteration only consider intensity differences between parent and kid and connect to the ones with the least difference. //From the second iteration, we consider ground volume = number of nodes that parents are linked to the kids //From third iteration, we increase the weight of the ground volume by 1e-7. //Vincken paper said after 3-4 iteration, there would be no significant difference. double tempScore = 0; double intensityDiffScore = 0; double groundVC = 0; double groundVPmax = 0; //updating ground volume and iterating to encourage convergence for (int counter = 0; counter<5; counter++){ for (Integer kid : linkageMap.keySet()){ for (int i = 0; i<DCPsize; i++){ if (kid + dcp[i] >=1 && kid+dcp[i] <= numScale && kid+dcp[i] <currchromBinSize){ if (counter ==0){groundVC = 0.00;} else{groundVC = (WEIGHT_I+WEIGHT_G*counter)*GvParents.get(linkageMap.get(kid))/groundVPmax;} tempScore = distanceFactor[i]*((1- Math.abs(GaussianBlur[kid][0] - GaussianBlur[kid+dcp[i]][1])/DImax)+groundVC); if (tempScore > intensityDiffScore){ intensityDiffScore = tempScore; linkageMap.put(kid,kid+dcp[i]); } } } } //test for (Map.Entry<Integer, Integer> entry : linkageMap.entrySet()){ System.out.println("Key: "+entry.getKey()+" Value: "+entry.getValue()); } // Integer lastParent = 0; // for (Integer parent : linkageMap.values()){ // GvParents.put(parent, parent-lastParent); // lastParent = parent; // GvParents.put(GvParents.firstKey(), trailingZero-GvParents.firstKey()); // GvParents.put(GaussianBlur.length,GaussianBlur.length-zeroEnd); //test // for (Map.Entry<Integer, Integer> entry : GvParents.entrySet()){ // System.out.println("Key: "+entry.getKey()+" Value: "+entry.getValue()); } // }else{ /*********** * Over kids //I haven't understood this part from the matlab code * */ } //for each scaleNum, add the parents to the segmentationTree // currScale.put(n, GvParents.keySet()); }//end of scale space iteration // segmentationTree.put(currChrom, currScale); // GaussianBlur = null; }// end of chromosome iteration manager.close(); } public static void main(String[] args) { GenomeConfig gconf = new GenomeConfig(args); ExptConfig econf = new ExptConfig(gconf.getGenome(), args); SEEDConfig sconf = new SEEDConfig(gconf, args); DifferentialMSR profile = new DifferentialMSR (gconf, econf, sconf); profile.buildMSR(); } }
package edu.psu.compbio.seqcode.projects.naomi; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import org.apache.commons.math3.analysis.polynomials.PolynomialFunction; import org.apache.commons.math3.distribution.NormalDistribution; import edu.psu.compbio.seqcode.deepseq.StrandedBaseCount; import edu.psu.compbio.seqcode.deepseq.experiments.ExperimentManager; import edu.psu.compbio.seqcode.deepseq.experiments.ExptConfig; import edu.psu.compbio.seqcode.deepseq.experiments.Sample; import edu.psu.compbio.seqcode.genome.Genome; import edu.psu.compbio.seqcode.genome.GenomeConfig; import edu.psu.compbio.seqcode.genome.location.Region; import edu.psu.compbio.seqcode.gse.gsebricks.verbs.location.ChromosomeGenerator; import edu.psu.compbio.seqcode.gse.tools.utils.Args; import edu.psu.compbio.seqcode.projects.seed.SEEDConfig; /** * DifferentialMSR: * * Methods refer to two papers * Probabilistic Multiscale Image Segmentation, Vincken et al. IEEE (1997) * * @author naomi yamada * **/ public class DifferentialMSR { protected GenomeConfig gconfig; protected ExptConfig econfig; protected SEEDConfig sconfig; protected int threePrimReadExt = 200; protected int binWidth = 1; //Map<chrm, Map<scale space, Set<segmentation>>> protected Map<Region, Map<Integer,Set<Integer>>> segmentationTree; public DifferentialMSR(GenomeConfig gcon, ExptConfig econ, SEEDConfig scon){ gconfig = gcon; econfig = econ; sconfig = scon; } public void buildMSR(){ /********************* * Gaussian scale space and window parameters */ // arbitrary number of scale int numScale= 10; double DELTA_TAU = 0.5*Math.log(2); // I have to determine P_MIN value carefully because P_MIN will substantially affect Gaussian window size double P_MIN = Math.pow(10,-3); double K_MIN = 1/Math.sqrt(1-Math.exp(-2*DELTA_TAU)); double K_N = Math.ceil(K_MIN); /********************* * Linkage parameters */ double WEIGHT_I = 1.00; double WEIGHT_G = 0.0000001; double WEIGHT_M = 1000; /********************* * Matrices parameters */ double sigma[] = new double[numScale]; double radius[] = new double[numScale]; for (int i = 0; i<numScale;i++){ sigma[i] = 1; radius[i] = 1; } ExperimentManager manager = new ExperimentManager(econfig); Genome genome = gconfig.getGenome(); //test to print whole chromosomes System.out.println(genome.getChromList()); System.out.println("before: "+binWidth+"\t"+threePrimReadExt); //fix here to get parameters only if they are specified binWidth = sconfig.getBinWidth(); threePrimReadExt = sconfig.getTag3PrimeExtension(); //test to print binWidth and threePrimReadExt System.out.println("binWidth is: "+binWidth); System.out.println("threePrimReadExt is: "+threePrimReadExt); Iterator<Region> chroms = new ChromosomeGenerator<Genome>().execute(genome); //iterating each chromosome (each chromosome is a region). while (chroms.hasNext()) { Region currChrom = chroms.next(); //previously it was below. but I don't think I need +1 here //int currchromSize= currChrom.getWidth()+1 int currchromSize= currChrom.getWidth(); //primitive matrix to store signal and the subsequent convolved signals //its index correspond to the coordinates float[][] GaussianBlur = new float[(int) Math.ceil(currchromSize/binWidth)][2]; for (int i = 0;i<(int) Math.ceil(currchromSize/binWidth);i++){ for (int j = 0; j<2;j++) GaussianBlur[i][j] = 0; } //get StrandedBaseCount list for each chromosome Map<Sample, List<StrandedBaseCount>> sampleCountsMap = new HashMap<Sample, List<StrandedBaseCount>>(); for (Sample sample : manager.getSamples()) sampleCountsMap.put(sample,sample.getBases(currChrom)); //StrandedBasedCount object contains positive and negative strand separately //store all base counts indexed by positions at column[1] //extend reads to 3' end and bin according to bin size for (Sample sample : manager.getSamples()){ List<StrandedBaseCount> currentCounts = sampleCountsMap.get(sample); for (StrandedBaseCount hits: currentCounts){ for (int i = 0; i<threePrimReadExt+1; i++){ if (hits.getStrand()=='+' && hits.getCoordinate()+i<currchromSize){ GaussianBlur[(int) Math.ceil((hits.getCoordinate()+i)/binWidth)][1]+=hits.getCount(); }else if (hits.getStrand()=='+' && hits.getCoordinate()-i >=0){ GaussianBlur[(int) Math.ceil((hits.getCoordinate()-i)/binWidth)][1]+=hits.getCount(); } } } currentCounts = null; } //testing if (currchromSize > 200000000){ System.out.println("current Chrom is: "+currChrom.getChrom()); for (int i = 0; i< 100;i++) System.out.println(GaussianBlur[(int) Math.ceil((92943501)/binWidth)+i][1]); } /********************* * Starting nodes */ //linkageMap contains index of kids and parents HashMap <Integer, Integer> linkageMap = new HashMap<Integer, Integer>(); //adding starting nodes; to qualify for the starting nodes the signal intensity needs to be different from the subsequent signal intensity //adding the starting and end positions in the kids at start and end positions //setting max & min signal intensity float DImax = 0; float DImin = (float) Integer.MAX_VALUE; List <Integer> nonzeroList = new ArrayList<Integer>(); linkageMap.put(0,0); for (int i = 0 ; i< GaussianBlur.length-1; i++){ //should I start if (GaussianBlur[i][1] != GaussianBlur[i+1][1]) linkageMap.put(i,0); if (GaussianBlur[i][1] > DImax) DImax = GaussianBlur[i][1]; if (GaussianBlur[i][1] < DImin) DImin = GaussianBlur[i][1]; if (GaussianBlur[i][1]!=0) nonzeroList.add(i); } linkageMap.put(GaussianBlur.length-1,0); //copy to segmentation tree //this is working // for (Integer element :linkageMap.keySet()) // System.out.println(element+" : "+ linkageMap.get(element)); Map<Integer,Set<Integer>> currScale =new HashMap<Integer,Set<Integer>>(); currScale.put(1, linkageMap.keySet()); //determine the first nonzero and last nonzero from signal //check here int trailingZero = 0; int zeroEnd = 0; if (!nonzeroList.isEmpty()){ trailingZero = Collections.min(nonzeroList)-1; zeroEnd = Collections.max(nonzeroList)+1; } System.out.println("DImax is: "+DImax+"\t"+"DImin is: "+DImin+ "\t"+"trailingZero: "+trailingZero+"\t"+"zeroEnd"+"\t"+zeroEnd); // for (int n = 2;n < numScale+1; n++){ /*********** * Over kids //I haven't understood this part from the matlab code } //for each scaleNum, add the parents to the segmentationTree currScale.put(n, GvParents.keySet()); }//end of scale space iteration segmentationTree.put(currChrom, currScale); */ GaussianBlur = null; }// end of chromosome iteration manager.close(); } public static void main(String[] args) { GenomeConfig gconf = new GenomeConfig(args); ExptConfig econf = new ExptConfig(gconf.getGenome(), args); SEEDConfig sconf = new SEEDConfig(gconf, args); DifferentialMSR profile = new DifferentialMSR (gconf, econf, sconf); profile.buildMSR(); } }
package experimentalcode.erich.diss; import java.util.Arrays; import de.lmu.ifi.dbs.elki.math.MathUtil; import de.lmu.ifi.dbs.elki.math.statistics.distribution.DistributionEstimator; import de.lmu.ifi.dbs.elki.math.statistics.distribution.GammaDistribution; import de.lmu.ifi.dbs.elki.math.statistics.distribution.GeneralizedExtremeValueDistribution; import de.lmu.ifi.dbs.elki.utilities.datastructures.arraylike.ArrayLikeUtil; import de.lmu.ifi.dbs.elki.utilities.datastructures.arraylike.NumberArrayAdapter; import de.lmu.ifi.dbs.elki.utilities.documentation.Reference; /** * Estimate the L-Moments of a sample. * * Reference: * <p> * J. R. M. Hosking, J. R. Wallis, and E. F. Wood<br /> * Estimation of the generalized extreme-value distribution by the method of * probability-weighted moments.<br /> * Technometrics 27.3 * </p> * * Also based on: * <p> * J. R. M. Hosking<br /> * Fortran routines for use with the method of L-moments Version 3.03<br /> * IBM Research. * </p> * * @author Erich Schubert */ @Reference(authors = "J.R.M. Hosking, J. R. Wallis, and E. F. Wood", title = "Estimation of the generalized extreme-value distribution by the method of probability-weighted moments.", booktitle = "Technometrics 27.3", url = "http://dx.doi.org/10.1080/00401706.1985.10488049") public class ProbabilityWeightedMoments implements DistributionEstimator<GeneralizedExtremeValueDistribution> { /** * Compute the alpha_r factors using the method of probability-weighted * moments. * * @param sorted <b>Presorted</b> data array. * @param nmom Number of moments to compute * @return Alpha moments (0-indexed) */ public static <A> double[] alphaPWM(A data, NumberArrayAdapter<?, A> adapter, final int nmom) { final int n = adapter.size(data); final double[] xmom = new double[nmom]; double weight = 1. / n; for (int i = 0; i < n; i++) { final double val = adapter.getDouble(data, i); xmom[0] += weight * val; for (int j = 1; j < nmom; j++) { weight *= (n - i - j + 1) / (n - j + 1); xmom[j] += weight * val; } } return xmom; } /** * Compute the beta_r factors using the method of probability-weighted * moments. * * @param sorted <b>Presorted</b> data array. * @param nmom Number of moments to compute * @return Beta moments (0-indexed) */ public static <A> double[] betaPWM(A data, NumberArrayAdapter<?, A> adapter, final int nmom) { final int n = adapter.size(data); final double[] xmom = new double[nmom]; double weight = 1. / n; for (int i = 0; i < n; i++) { final double val = adapter.getDouble(data, i); xmom[0] += weight * val; for (int j = 1; j < nmom; j++) { weight *= (i - j + 1) / (n - j + 1); xmom[j] += weight * val; } } return xmom; } /** * Compute the alpha_r and beta_r factors in parallel using the method of * probability-weighted moments. Usually cheaper than computing them * separately. * * @param sorted <b>Presorted</b> data array. * @param nmom Number of moments to compute * @return Alpha and Beta moments (0-indexed, interleaved) */ public static <A> double[] alphaBetaPWM(A data, NumberArrayAdapter<?, A> adapter, final int nmom) { final int n = adapter.size(data); final double[] xmom = new double[nmom << 1]; double aweight = 1. / n, bweight = aweight; for (int i = 0; i < n; i++) { final double val = adapter.getDouble(data, i); xmom[0] += aweight * val; xmom[1] += bweight * val; for (int j = 1, k = 2; j < nmom; j++, k += 2) { aweight *= (n - i - j + 1) / (n - j + 1); bweight *= (i - j + 1) / (n - j + 1); xmom[k + 1] += aweight * val; xmom[k + 1] += bweight * val; } } return xmom; } /** * Compute the sample L-Moments using probability weighted moments. * * @param sorted <b>Presorted</b> data array. * @param nmom Number of moments to compute * @return Alpha and Beta moments (0-indexed, interleaved) */ public static <A> double[] samLMR(A sorted, NumberArrayAdapter<?, A> adapter, final int nmom) { final int n = adapter.size(sorted); final double[] sum = new double[nmom]; // Estimate probability weighted moments (unbiased) for (int i = 0; i < n; i++) { double term = adapter.getDouble(sorted, i); sum[0] += term; for (int j = 1, z = i; j < nmom; j++, z term *= z; sum[j] += term; } } // Normalize by "n choose (j + 1)" sum[0] /= n; double z = n; for (int j = 1; j < nmom; j++) { z *= n - j; sum[j] /= z; } for (int k = nmom - 1; k >= 1; --k) { double p = ((k & 1) == 0) ? +1 : -1; double temp = p * sum[0]; for (int i = 0; i < k; i++) { double ai = i + 1.; p *= -(k + ai) * (k - i) / (ai * ai); temp += p * sum[i + 1]; } sum[k] = temp; } if (nmom > 2 && !(sum[1] > 0)) { throw new ArithmeticException("Can't compute higher order moments for constant data."); } for (int i = 2; i < nmom; i++) { sum[i] /= sum[1]; } return sum; } /** * Constants for fast rational approximations. */ private final double A0 = 0.28377530, A1 = -1.21096399, A2 = -2.50728214, A3 = -1.13455566, A4 = -0.07138022, B1 = 2.06189696, B2 = 1.31912239, B3 = 0.25077104, C1 = 1.59921491, C2 = -0.48832213, C3 = 0.01573152, D1 = -0.64363929, D2 = 0.08985247; /** Maximum number of iterations. */ private int MAXIT = 20; @Override public <A> GeneralizedExtremeValueDistribution estimate(A data, NumberArrayAdapter<?, A> adapter) { // Sort: final int size = adapter.size(data); double[] sorted = new double[size]; for (int i = 0; i < size; i++) { sorted[i] = adapter.getDouble(data, i); } Arrays.sort(sorted); double[] xmom = samLMR(sorted, ArrayLikeUtil.DOUBLEARRAYADAPTER, 3); double t3 = xmom[2]; if (Math.abs(t3) < 1e-50 || (t3 >= 1.)) { throw new ArithmeticException("Invalid moment estimation."); } // Approximation for t3 between 0 and 1: double g; if (t3 > 0.) { double z = 1. - t3; g = (-1. + z * (C1 + z * (C2 + z * C3))) / (1. + z * (D1 + z * D2)); // g: Almost zero? if (Math.abs(g) < 1e-50) { double k = 0; double sigma = xmom[1] / MathUtil.LOG2; double mu = xmom[0] - Math.E * sigma; return new GeneralizedExtremeValueDistribution(mu, sigma, k); } } else { // Approximation for t3 between -.8 and 0L: g = (A0 + t3 * (A1 + t3 * (A2 + t3 * (A3 + t3 * A4)))) / (1. + t3 * (B1 + t3 * (B2 + t3 * B3))); if (t3 < -.8) { // Newton-Raphson iteration for t3 < -.8 if (t3 <= -.97) { g = 1. - Math.log(1. + t3) / MathUtil.LOG2; } double t0 = .5 * (t3 + 3.); for (int it = 1;; it++) { double x2 = Math.pow(2., -g), xx2 = 1. - x2; double x3 = Math.pow(3., -g), xx3 = 1. - x3; double t = xx3 / xx2; double deriv = (xx2 * x3 * MathUtil.LOG3 - xx3 * x2 * MathUtil.LOG2) / (xx2 * x2); double oldg = g; g -= (t - t0) / deriv; if (Math.abs(g - oldg) < 1e-20 * g) { break; } if (it >= MAXIT) { throw new ArithmeticException("Newton-Raphson did not converge."); } } } } double gam = Math.exp(GammaDistribution.logGamma(1. + g)); final double mu, sigma, k; k = g; sigma = xmom[1] * g / (gam * (1. - Math.pow(2., -g))); mu = xmom[0] - sigma * (1. - gam) / g; return new GeneralizedExtremeValueDistribution(mu, sigma, k); } @Override public Class<? super GeneralizedExtremeValueDistribution> getDistributionClass() { return GeneralizedExtremeValueDistribution.class; } }
package unicasc; import java.util.HashMap; import java.util.Map; /** * Converts between ASCII and Unicode represeantations of TLA+ symbols. * @author pron */ public final class Unicode { private Unicode() {} // Unicode/ASCII conversion table private static final String[][] table = { // The first element is the Unicode character. // The second element is the canonical ASCII representation. // Subsequent elements are alternate ASCII representations. { "\u225C", "==" }, { "\u2190", "<-" }, { "\u2192", "->" }, { "\u21A6", "|->" }, { "\u27E8", "<<" }, // MATHEMATICAL LEFT ANGLE BRACKET { "\u27E9", ">>" }, // MATHEMATICAL RIGHT ANGLE BRACKET { "\u27E9_", ">>_" }, { "\u2200\u2200", "\\AA" }, { "\u2203\u2203", "\\EE" }, { "\u25FB", "[]" }, // White medium square / \u25A1 WHITE SQUARE / \u2610 BALLOT BOX { "\u2B26", "<>" }, // WHITE MEDIUM DIAMOND / \u2662 WHITE DIAMOND SUIT { "\u2032", "'" }, { "\u2933", "~>" }, // WAVE ARROW POINTING DIRECTLY RIGHT { "\u2945", "-+->" }, { "\u2200", "\\A", "\\forall" }, { "\u2203", "\\E", "\\exists" }, { "\u00ac", "~", "\\lnot", "\\neg" }, { "\u2227", "/\\", "\\land" }, { "\u2228", "\\/", "\\lor" }, { "\u21D2", "=>" }, { "\u2263", "<=>", "\\equiv" }, { "\u2260", " { "\u2208", "\\in" }, { "\u2209", "\\notin" }, { "\u2282", "\\subset" }, { "\u2286", "\\subseteq" }, { "\u2283", "\\supset" }, { "\u2287", "\\supseteq" }, { "\u2229", "\\cap", "\\intersect" }, { "\u222A", "\\cup", "\\union" }, { "\u228E", "\\uplus" }, { "\u2264", "<=", "=<", "\\leq" }, { "\u2265", ">=", "\\geq" }, { "\u226A", "\\ll" }, { "\u226B", "\\gg" }, { "%", "%", "\\mod" }, { "\u00D7", "\\X", "\\times" }, { "\u00F7", "\\div" }, { "\u22C5", "\\cdot" }, { "\u2295", "(+)", "\\oplus" }, { "\u2296", "(-)", "\\ominus" }, { "\u2297", "(\\X)", "\\otimes" }, { "\u2298", "(/)", "\\oslash" }, { "\u2299", "(.)", "\\odot" }, { "\u25CB", "\\o", "\\circ" }, // WHITE CIRCLE { "\u25EF", "\\bigcirc" }, // LARGE CIRCLE { "\u2022", "\\bullet" }, { "\u2B51", "\\star" }, // BLACK SMALL STAR / \u2605 BLACK STAR / \u2606 WHITE STAR / \u2B50 \uFE0E White medium star { "\u227A", "\\prec" }, { "\u227C", "\\preceq" }, { "\u227B", "\\succ" }, { "\u227D", "\\succeq" }, { "\u228F", "\\sqsubset" }, { "\u2291", "\\sqsubseteq" }, { "\u2290", "\\sqsupset" }, { "\u2292", "\\sqsupseteq" }, { "\u2293", "\\sqcap" }, { "\u2294", "\\sqcup" }, { "\u224D", "\\asymp" }, { "\u2240", "\\wr" }, { "\u2245", "\\cong" }, { "\u221D", "\\propto" }, { "\u2248", "\\approx" }, { "\u2250", "\\doteq" }, { "\u2243", "\\simeq" }, { "\uFF5E", "\\sim" }, { "\u22A2", "|-" }, { "\u22A3", "-|" }, { "\u22A8", "|=" }, { "\u2AE4", "=|" }, // VERTICAL BAR DOUBLE LEFT TURNSTILE { "\u2016", "||" }, }; // Greek letters public static final char CAPITAL_GAMMA = '\u0393'; public static final char CAPITAL_DELTA = '\u0394'; public static final char CAPITAL_THETA = '\u0398'; public static final char CAPITAL_LAMBDA = '\u039B'; public static final char CAPITAL_XI = '\u039E'; public static final char CAPITAL_PI = '\u03A0'; public static final char CAPITAL_SIGMA = '\u03A3'; public static final char CAPITAL_UPSILON = '\u03A5'; public static final char CAPITAL_PHI = '\u03A6'; public static final char CAPITAL_PSI = '\u03A8'; public static final char CAPITAL_OMEGA = '\u03A9'; public static final char SMALL_ALPHA = '\u03B1'; public static final char SMALL_BETA_ = '\u03B2'; public static final char SMALL_GAMMA = '\u03B3'; public static final char SMALL_DELTA = '\u03B4'; public static final char SMALL_EPSILON = '\u03B5'; public static final char SMALL_ZETA = '\u03B6'; public static final char SMALL_ETA = '\u03B7'; public static final char SMALL_THETA = '\u03B8'; public static final char SMALL_IOTA = '\u03B9'; public static final char SMALL_KAPPA = '\u03BA'; public static final char SMALL_LAMBDA = '\u03BB'; public static final char SMALL_MU = '\u03BC'; public static final char SMALL_NU = '\u03BD'; public static final char SMALL_XI = '\u03BE'; public static final char SMALL_PI = '\u03C0'; public static final char SMALL_RHO = '\u03C1'; public static final char SMALL_SIGMA = '\u03C3'; public static final char SMALL_TAU = '\u03C4'; public static final char SMALL_UPSILON = '\u03C5'; public static final char SMALL_PHI = '\u03C6'; public static final char SMALL_PHI_1 = '\u0278'; public static final char SMALL_CHI = '\u03C7'; public static final char SMALL_PSI = '\u03C8'; public static final char SMALL_OMEGA = '\u03C9'; public static final char subscriptDigit(int num) { assert num >= 0 && num <= 9; return (char)(0x2080 + num); } public static final char SUBSCRIPT_a = '\u2090'; public static final char SUBSCRIPT_e = '\u2091'; public static final char SUBSCRIPT_h = '\u2095'; public static final char SUBSCRIPT_i = '\u1D62'; public static final char SUBSCRIPT_j = '\u2C7C'; // LATIN SUBSCRIPT SMALL LETTER J public static final char SUBSCRIPT_k = '\u2096'; public static final char SUBSCRIPT_l = '\u2097'; public static final char SUBSCRIPT_m = '\u2098'; public static final char SUBSCRIPT_n = '\u2099'; public static final char SUBSCRIPT_o = '\u2092'; public static final char SUBSCRIPT_p = '\u209A'; public static final char SUBSCRIPT_r = '\u1D63'; public static final char SUBSCRIPT_s = '\u209B'; public static final char SUBSCRIPT_t = '\u209C'; public static final char SUBSCRIPT_u = '\u1D64'; public static final char SUBSCRIPT_v = '\u1D65'; public static final char SUBSCRIPT_x = '\u2093'; public static final char SUBSCRIPT_SMALL_BETA = '\u1D66'; public static final char SUBSCRIPT_SMALL_GAMMA = '\u1D67'; public static final char SUBSCRIPT_SMALL_PHI = '\u1D69'; public static final char SUBSCRIPT_SMALL_CHI = '\u1D6A'; public static final char SUBSCRIPT_PLUS = '\u208A'; // Superscripts private static final char[] SUPERSCRIPT_DIGIT = { '\u2070', '\u00B9', '\u00B2', '\u00B3', '\u2074', '\u2075', '\u2076', '\u2077', '\u2078', '\u2079' }; public static final char superscriptDigit(int num) { assert num >= 0 && num <= 9; return SUPERSCRIPT_DIGIT[num]; } public static final char SUPERSCRIPT_PLUS = '\u207A'; public static final char SUBSCRIPT_ASTERISK = '\u204E'; // Box drawing: public static final char HORIZONTAL = '\u2500'; // BOX DRAWINGS LIGHT HORIZONTAL / \u2501 HEAVY public static final char BMODULE_BEGIN = '\u250C'; // BOX DRAWINGS LIGHT DOWN AND RIGHT / \u250F HEAVY public static final char BMODULE_END = '\u2510'; // BOX DRAWINGS LIGHT DOWN AND LEFT / \u2513 HEAVY public static final char SEPARATOR_BEGIN = '\u251C'; // BOX DRAWINGS LIGHT VERTICAL AND RIGHT / \u2523 HEAVY public static final char SEPARATOR_END = '\u2524'; // BOX DRAWINGS LIGHT VERTICAL AND LEFT / \u252B HEAVY public static final char EMODULE_BEGIN = '\u2514'; // BOX DRAWINGS LIGHT UP AND RIGHT / \u2517 HEAVY public static final char EMODULE_END = '\u2518'; // BOX DRAWINGS LIGHT UP AND LEFT / \u251B HEAVY private static final Map<String, String> u2a = new HashMap<>(); private static final Map<String, String> a2u = new HashMap<>(); private static final Map<Character, String> cu2a = new HashMap<>(); static { // initialize maps for (String[] row : table) { final String u = row[0]; // unicode u2a.put(u, row[1]); cu2a.put(u.charAt(0), row[1]); for (int i = 1; i < row.length; i++) a2u.put(row[i], u); } } /** * The canonical ASCII representation of a Unicode string * * @param u the Unicode string * @return the canonical ASCII string or {@code null} if no alternate * representation */ public static String u2a(String u) { return u2a.get(u); } /** * The canonical ASCII representation of a Unicode character * * @param u the Unicode string * @return the canonical ASCII string or {@code null} if no alternate * representation */ public static String cu2a(char u) { return cu2a.get(u); } /** * The Unicode representation of an ASCII string * * @param a * the ASCII string * @return the Unicode string or {@code null} if no alternate representation */ public static String a2u(String a) { return a2u.get(a); } /** * The Unicode representation of a canonical ASCII string * * @param a the ASCII string * @return the Unicode string or {@code null} if no alternate representation * or if {@code a} is not the canonical represeantation. */ public static String a2uc(String a) { String res = a2u.get(a); if (res != null && !u2a.get(res).equals(a)) res = null; return res; } // /** // * Convert to Unicode representation // * // * @param a the ASCII string // * @return the Unicode string or {@code a} if no alternate representation // */ // public static String toU(String a) { // return convert(a, true); //// String u; //// return ((u = a2u(a)) != null ? u : a); // /** // * Convert to ASCII representation of a string // * // * @param u the Unicode string // * @return the canonical ASCII string or {@code a} if no alternate // * representation // */ // public static String toA(String u) { // return convert(u, false); //// String a; //// return ((a = u2a(u)) != null ? a : u); // private static final String ASCII_GLYPHS = "=<>()+-\\/ // private static String convert(String in, boolean toU) { // StringBuilder out = new StringBuilder(); // StringBuilder token = new StringBuilder(); // for (int i = 0; i < in.length();) { // char c = in.charAt(i); // if (c == '\\') { // convertToken(out, token, toU); // for (; i < in.length() && Character.isLetter(in.charAt(i)); i++) // convertToken(out, token, toU); // continue; // if (i < in.length() - 1) { // final char c1 = in.charAt(i + 1); // if ((c == '<' && (in.charAt(i + 1) == '<' || in.charAt(i + 1) == '>')) // || (c == '[' && in.charAt(i + 1) == ']')) { // convertToken(out, token, toU); // convertToken(out, token, toU); // i += 2; // continue; // continue; // if (true ) { // convertToken(out, token, toU); // continue; // return out.toString(); private static void convertToken(StringBuilder out, StringBuilder token, boolean toU) { if (token.length() > 0) { String res = toU ? a2u(token.toString()) : u2a(token.toString()); out.append(res != null ? res : token); } token.setLength(0); } /** * Whether or not a string contains only BMP characters (TLA+ only supports those). */ public static boolean isBMP(String str) { return str.length() == str.codePointCount(0, str.length()); } }
package com.armandgray.taap.models; import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.NonNull; import java.util.ArrayList; public class Drill implements Parcelable { public static final String ALL = "ALL"; public static final String BALL_HANDLING = "Ball Handling"; public static final String SHOOTING = "Shooting"; public static final String PASSING = "Passing"; public static final String DRIVING = "Driving"; public static final String FUNDAMENTALS = "Fundamentals"; public static final String DEFENSE = "Defense"; public static final String OFFENSE = "Offense"; public static final String CONDITIONING = "Conditioning"; public static final String[] SHOOTING_ARRAY = {SHOOTING}; public static final String[] DEFENSE_ARRAY = {DEFENSE}; public static final String[] CONDITIONING_ARRAY = {CONDITIONING}; public static final String[] OFFENSE_ARRAY = {OFFENSE}; public static final String[] BALL_HANDLING_ARRAY = {BALL_HANDLING}; public static final String[] PASSING_ARRAY = {PASSING}; public static final String[] DRIVING_ARRAY = {DRIVING}; public static final String[] DRILL_TYPES = { BALL_HANDLING, SHOOTING, PASSING, FUNDAMENTALS, DEFENSE, OFFENSE, CONDITIONING, DRIVING}; public static final String[] DEFENSE_TYPES_ARRAY = { DEFENSE }; public static final String[] OFFENSE_TYPES_ARRAY = { OFFENSE, PASSING, DRIVING }; private String title; private int imageId; private String[] category; private int drillId; public Drill(String title, int imageId, String[] category) { this.title = title; this.imageId = imageId; this.category = category; } public int getDrillId() { return drillId; } public void setDrillId(int drillId) { this.drillId = drillId; } public String getTitle() { return title; } public int getImageId() { return imageId; } public String[] getCategory() { return category; } @NonNull public static ArrayList<Drill> getQueryResultList(ArrayList<Drill> drillsList, String query) { ArrayList<Drill> dataList = new ArrayList<>(); if (drillsList != null) { dataList.addAll(drillsList); } return getFilteredListOnQuery(query, dataList); } private static ArrayList<Drill> getFilteredListOnQuery(String query, ArrayList<Drill> dataList) { for (int i = 0; i < dataList.size(); i++) { if (!dataList.get(i).getTitle().toLowerCase().contains(query.toLowerCase())) { dataList.remove(i); i } } return dataList; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(this.title); dest.writeInt(this.imageId); dest.writeStringArray(this.category); dest.writeInt(this.drillId); } protected Drill(Parcel in) { this.title = in.readString(); this.imageId = in.readInt(); this.category = in.createStringArray(); this.drillId = in.readInt(); } public static final Parcelable.Creator<Drill> CREATOR = new Parcelable.Creator<Drill>() { @Override public Drill createFromParcel(Parcel source) { return new Drill(source); } @Override public Drill[] newArray(int size) { return new Drill[size]; } }; }
package bisq.monitor; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import lombok.extern.slf4j.Slf4j; /** * Gate pattern to help with thread synchronization * * @author Florian Reimair */ @Slf4j public class ThreadGate { private CountDownLatch lock = new CountDownLatch(0); /** * Make everyone wait until the gate is open again. */ public void engage() { lock = new CountDownLatch(1); } /** * Make everyone wait until the gate is open again. * * @param numberOfLocks how often the gate has to be unlocked until the gate * opens. */ public void engage(int numberOfLocks) { lock = new CountDownLatch(numberOfLocks); } /** * Wait for the gate to be opened. Blocks until the gate is open again. Returns * immediately if the gate is already open. */ public synchronized void await() { while (lock.getCount() > 0) try { if (!lock.await(lock.getCount(), TimeUnit.MINUTES)) { log.warn("timeout occured!"); break; // break the loop } } catch (InterruptedException ignore) { } } /** * Open the gate and let everyone proceed with their execution. */ public void proceed() { lock.countDown(); } /** * Open the gate with no regards on how many locks are still in place. */ public void unlock() { while (lock.getCount() > 0) lock.countDown(); } }
package com.example.moreapp; import android.content.Context; import android.text.TextUtils; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.toolbox.Volley; public class App{ public RequestQueue requestQueue; private static App Instance; public static Context context; public static Context getContext(){ return App.context; } public static synchronized App getInstance() { return Instance; } public RequestQueue getRequestQueue(){ if (requestQueue==null){ requestQueue = Volley.newRequestQueue(context); } return requestQueue; } public <T> void addToRequestQueue(Request<T> req, String tag) { // set the default tag if tag is empty req.setTag(TextUtils.isEmpty(tag) ? "" : tag); getRequestQueue().add(req); } public <T> void addToRequestQueue(Request<T> req) { req.setTag(""); getRequestQueue().add(req); } }
package gov.nih.nci.calab.ui.submit; /** * This class sets up input form for size characterization. * * @author pansu */ /* CVS $Id: NanoparticleFunctionAction.java,v 1.11 2007-08-01 18:25:18 pansu Exp $ */ import gov.nih.nci.calab.domain.nano.function.Function; import gov.nih.nci.calab.dto.characterization.CharacterizationBean; import gov.nih.nci.calab.dto.characterization.DerivedBioAssayDataBean; import gov.nih.nci.calab.dto.function.AgentBean; import gov.nih.nci.calab.dto.function.AgentTargetBean; import gov.nih.nci.calab.dto.function.FunctionBean; import gov.nih.nci.calab.dto.function.LinkageBean; import gov.nih.nci.calab.service.search.SearchNanoparticleService; import gov.nih.nci.calab.service.submit.SubmitNanoparticleService; import gov.nih.nci.calab.ui.core.AbstractDispatchAction; import gov.nih.nci.calab.ui.core.InitSessionSetup; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionMessages; import org.apache.struts.validator.DynaValidatorForm; public class NanoparticleFunctionAction extends AbstractDispatchAction { /** * Add or update the data to database * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward create(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionForward forward = null; DynaValidatorForm theForm = (DynaValidatorForm) form; String particleType = (String) theForm.get("particleType"); String particleName = (String) theForm.get("particleName"); FunctionBean function = (FunctionBean) theForm.get("function"); if (function.getId() == null || function.getId() == "") { function.setId((String) theForm.get("functionId")); } request.getSession().setAttribute("newFunctionCreated", "true"); // TODO save in database SubmitNanoparticleService service = new SubmitNanoparticleService(); service.addParticleFunction(particleType, particleName, function); ActionMessages msgs = new ActionMessages(); ActionMessage msg = new ActionMessage("message.addparticle.function"); msgs.add("message", msg); saveMessages(request, msgs); forward = mapping.findForward("success"); InitSessionSetup.getInstance().setSideParticleMenu(request, particleName, particleType); return forward; } /** * Set up the input forms for adding data * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward setup(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; HttpSession session = request.getSession(); // clear session data from the input forms clearMap(session, theForm, mapping); initSetup(request, theForm); return mapping.getInputForward(); } private void clearMap(HttpSession session, DynaValidatorForm theForm, ActionMapping mapping) throws Exception { String particleType = (String) theForm.get("particleType"); String particleName = (String) theForm.get("particleName"); // clear session data from the input forms theForm.getMap().clear(); theForm.set("particleName", particleName); theForm.set("particleType", particleType); theForm.set("function", new FunctionBean()); } private void initSetup(HttpServletRequest request, DynaValidatorForm theForm) throws Exception { HttpSession session = request.getSession(); String particleType = (String) theForm.get("particleType"); String particleName = (String) theForm.get("particleName"); InitSessionSetup.getInstance().setSideParticleMenu(request, particleName, particleType); InitSessionSetup.getInstance().setStaticDropdowns(session); InitSessionSetup.getInstance().setAllFunctionDropdowns(session); } /** * Set up the form for updating existing characterization * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward setupUpdate(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; initSetup(request, theForm); String functionId = (String) theForm.get("functionId"); SearchNanoparticleService service = new SearchNanoparticleService(); Function aFunc = service.getFunctionBy(functionId); HttpSession session = request.getSession(); // clear session data from the input forms clearMap(session, theForm, mapping); FunctionBean function = new FunctionBean(aFunc); theForm.set("function", function); return mapping.getInputForward(); } /** * Prepare the form for viewing existing characterization * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward setupView(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { return setupUpdate(mapping, form, request, response); } public ActionForward addLinkage(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; FunctionBean function = (FunctionBean) theForm.get("function"); List<LinkageBean> origLinkages = function.getLinkages(); int origNum = (origLinkages == null) ? 0 : origLinkages.size(); List<LinkageBean> linkages = new ArrayList<LinkageBean>(); for (int i = 0; i < origNum; i++) { linkages.add((LinkageBean) origLinkages.get(i)); } // add a new one linkages.add(new LinkageBean()); function.setLinkages(linkages); String particleName = theForm.getString("particleName"); String particleType = theForm.getString("particleType"); InitSessionSetup.getInstance().setSideParticleMenu(request, particleName, particleType); return mapping.getInputForward(); } public ActionForward removeLinkage(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String linkageIndex = (String) request.getParameter("linkageInd"); int ind = Integer.parseInt(linkageIndex); DynaValidatorForm theForm = (DynaValidatorForm) form; FunctionBean function = (FunctionBean) theForm.get("function"); List<LinkageBean> origLinkages = function.getLinkages(); int origNum = (origLinkages == null) ? 0 : origLinkages.size(); List<LinkageBean> linkages = new ArrayList<LinkageBean>(); for (int i = 0; i < origNum; i++) { linkages.add(origLinkages.get(i)); } // remove the one at the index if (origNum > 0) { linkages.remove(ind); } function.setLinkages(linkages); String particleName = theForm.getString("particleName"); String particleType = theForm.getString("particleType"); InitSessionSetup.getInstance().setSideParticleMenu(request, particleName, particleType); return mapping.getInputForward(); } public ActionForward addTarget(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String linkageIndex = (String) request.getParameter("linkageInd"); int ind = Integer.parseInt(linkageIndex); DynaValidatorForm theForm = (DynaValidatorForm) form; FunctionBean function = (FunctionBean) theForm.get("function"); AgentBean agent = function.getLinkages().get(ind).getAgent(); List<AgentTargetBean> origTargets = agent.getAgentTargets(); int origNum = (origTargets == null) ? 0 : origTargets.size(); List<AgentTargetBean> targets = new ArrayList<AgentTargetBean>(); for (int i = 0; i < origNum; i++) { targets.add(origTargets.get(i)); } // add a new one targets.add(new AgentTargetBean()); agent.setAgentTargets(targets); String particleName = theForm.getString("particleName"); String particleType = theForm.getString("particleType"); InitSessionSetup.getInstance().setSideParticleMenu(request, particleName, particleType); return mapping.getInputForward(); } public ActionForward removeTarget(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaValidatorForm theForm = (DynaValidatorForm) form; String linkageIndex = (String) request.getParameter("linkageInd"); int ind = Integer.parseInt(linkageIndex); String targetIndex = (String) request.getParameter("targetInd"); int tInd = Integer.parseInt(targetIndex); FunctionBean function = (FunctionBean) theForm.get("function"); AgentBean agent = function.getLinkages().get(ind).getAgent(); List<AgentTargetBean> origTargets = agent.getAgentTargets(); int origNum = (origTargets == null) ? 0 : origTargets.size(); List<AgentTargetBean> targets = new ArrayList<AgentTargetBean>(); for (int i = 0; i < origNum; i++) { targets.add(origTargets.get(i)); } // remove the one at the index if (origNum > 0) { targets.remove(tInd); } agent.setAgentTargets(targets); String particleName = theForm.getString("particleName"); String particleType = theForm.getString("particleType"); InitSessionSetup.getInstance().setSideParticleMenu(request, particleName, particleType); return mapping.getInputForward(); } public boolean loginRequired() { return true; } }
package gov.nih.nci.cananolab.ui.particle; import gov.nih.nci.cananolab.domain.particle.samplecomposition.base.Emulsion; import gov.nih.nci.cananolab.dto.common.LabFileBean; import gov.nih.nci.cananolab.dto.particle.composition.ChemicalAssociationBean; import gov.nih.nci.cananolab.dto.particle.composition.ComposingElementBean; import gov.nih.nci.cananolab.dto.particle.composition.FunctionBean; import gov.nih.nci.cananolab.dto.particle.composition.FunctionalizingEntityBean; import gov.nih.nci.cananolab.dto.particle.composition.NanoparticleEntityBean; import gov.nih.nci.cananolab.exception.CaNanoLabException; import gov.nih.nci.cananolab.service.common.LookupService; import gov.nih.nci.cananolab.service.particle.NanoparticleCompositionService; import gov.nih.nci.cananolab.ui.core.InitSetup; import java.util.ArrayList; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; /** * This class sets up information required for composition forms. * * @author pansu, cais * */ public class InitCompositionSetup { private NanoparticleCompositionService compService = new NanoparticleCompositionService(); public static InitCompositionSetup getInstance() { return new InitCompositionSetup(); } public void setNanoparticleEntityDropdowns(HttpServletRequest request) throws Exception { getNanoparticleEntityTypes(request); getEmulsionComposingElementTypes(request); getFunctionTypes(request); InitSetup.getInstance().getDefaultAndOtherLookupTypes(request, "biopolymerTypes", "Biopolymer", "type", "otherType", true); InitSetup.getInstance().getDefaultAndOtherLookupTypes(request, "modalityTypes", "ImagingFunction", "modality", "otherModality", true); InitSetup.getInstance().getDefaultAndOtherLookupTypes(request, "composingElementTypes", "ComposingElement", "type", "otherType", true); InitSetup.getInstance().getDefaultAndOtherLookupTypes(request, "composingElementUnits", "ComposingElement", "valueUnit", "otherValueUnit", true); InitSetup.getInstance().getDefaultAndOtherLookupTypes(request, "ceMolecularFormulaTypes", "ComposingElement", "molecularFormulaType", "otherMolecularFormulaType", true); ServletContext appContext = request.getSession().getServletContext(); InitSetup.getInstance().getServletContextDefaultLookupTypes(appContext, "wallTypes", "CarbonNanotube", "wallType"); } public void persistNanoparticleEntityDropdowns(HttpServletRequest request, NanoparticleEntityBean entityBean) throws Exception { InitSetup.getInstance().persistLookup(request, "Biopolymer", "type", "otherType", entityBean.getBiopolymer().getType()); for (ComposingElementBean elementBean : entityBean .getComposingElements()) { if (entityBean.getDomainEntity() instanceof Emulsion) { InitSetup.getInstance().persistLookup(request, "Emulsion", "composingElementType", "otherComposingElementType", elementBean.getDomainComposingElement().getType()); } else { InitSetup.getInstance().persistLookup(request, "ComposingElement", "type", "otherType", elementBean.getDomainComposingElement().getType()); } InitSetup.getInstance().persistLookup(request, "ComposingElement", "valueUnit", "otherValueUnit", elementBean.getDomainComposingElement().getValueUnit()); InitSetup.getInstance().persistLookup( request, "ComposingElement", "molecularFormulaType", "otherMolecularFormulaType", elementBean.getDomainComposingElement() .getMolecularFormulaType()); for (FunctionBean functionBean : elementBean.getInherentFunctions()) { InitSetup.getInstance().persistLookup(request, "ImagingFunction", "modality", "otherModality", functionBean.getImagingFunction().getModality()); } } for (LabFileBean fileBean : entityBean.getFiles()) { InitSetup.getInstance().persistLookup(request, "LabFile", "type", "otherType", fileBean.getDomainFile().getType()); } setNanoparticleEntityDropdowns(request); } public void setFunctionalizingEntityDropdowns(HttpServletRequest request) throws Exception { getFunctionalizingEntityTypes(request); getTargetTypes(request); InitSetup.getInstance().getDefaultAndOtherLookupTypes(request, "antibodyTypes", "Antibody", "type", "otherType", true); InitSetup.getInstance() .getDefaultAndOtherLookupTypes(request, "antibodyIsotypes", "Antibody", "isotype", "otherIsotype", true); InitSetup.getInstance().getDefaultAndOtherLookupTypes(request, "activationMethods", "ActivationMethod", "type", "otherType", true); InitSetup.getInstance().getDefaultAndOtherLookupTypes(request, "functionalizingEntityUnits", "FunctionalizingEntity", "valueUnit", "otherValueUnit", true); InitSetup.getInstance().getDefaultAndOtherLookupTypes(request, "modalityTypes", "ImagingFunction", "modality", "otherModality", true); InitSetup.getInstance().getDefaultAndOtherLookupTypes(request, "feMolecularFormulaTypes", "FunctionalizingEntity", "molecularFormulaType", "otherMolecularFormulaType", true); ServletContext appContext = request.getSession().getServletContext(); InitSetup.getInstance().getServletContextDefaultLookupTypes(appContext, "antigenSpecies", "Antigen", "species"); InitSetup.getInstance().getServletContextDefaultLookupTypes(appContext, "antibodySpecies", "Antibody", "species"); InitSetup.getInstance().getDefaultAndOtherLookupTypes(request, "biopolymerTypes", "Biopolymer", "type", "otherType", true); } public void persistFunctionalizingEntityDropdowns( HttpServletRequest request, FunctionalizingEntityBean entityBean) throws Exception { InitSetup.getInstance().persistLookup(request, "Antibody", "type", "otherType", entityBean.getAntibody().getType()); InitSetup.getInstance().persistLookup(request, "Antibody", "isotype", "otherIsoType", entityBean.getAntibody().getIsotype()); InitSetup.getInstance().persistLookup(request, "Biopolymer", "type", "otherType", entityBean.getBiopolymer().getType()); InitSetup.getInstance().persistLookup(request, "FunctionalizingEntity", "valueUnit", "otherValueUnit", entityBean.getValueUnit()); InitSetup.getInstance().persistLookup(request, "FunctionalizingEntity", "molecularFormulaType", "otherMolecularFormulaType", entityBean.getMolecularFormulaType()); InitSetup .getInstance() .persistLookup(request, "ActivationMethod", "type", "otherType", entityBean.getActivationMethod().getType()); for (FunctionBean functionBean : entityBean.getFunctions()) { InitSetup.getInstance().persistLookup(request, "ImagingFunction", "modality", "otherModality", functionBean.getImagingFunction().getModality()); } for (LabFileBean fileBean : entityBean.getFiles()) { InitSetup.getInstance().persistLookup(request, "LabFile", "type", "otherType", fileBean.getDomainFile().getType()); } setFunctionalizingEntityDropdowns(request); } public void setChemicalAssociationDropdowns(HttpServletRequest request, boolean hasFunctionalizingEntity) throws Exception { ServletContext appContext = request.getSession().getServletContext(); List<String> compositionTypes = new ArrayList<String>(); compositionTypes.add("Nanoparticle Entity"); if (hasFunctionalizingEntity) { compositionTypes.add("Functionalizing Entity"); } appContext .setAttribute("associationCompositionTypes", compositionTypes); InitSetup.getInstance().getDefaultAndOtherLookupTypes(request, "bondTypes", "Attachment", "bondType", "otherBondType", true); InitCompositionSetup.getInstance().getChemicalAssociationTypes(request); } public void persistChemicalAssociationDropdowns(HttpServletRequest request, ChemicalAssociationBean assocBean, Boolean hasFunctionalizingEntity) throws Exception { InitSetup.getInstance().persistLookup(request, "Attachment", "bondType", "otherBondType", assocBean.getAttachment().getBondType()); if (assocBean.getFiles() != null) { for (LabFileBean fileBean : assocBean.getFiles()) { InitSetup.getInstance() .persistLookup(request, "LabFile", "type", "otherType", fileBean.getDomainFile().getType()); } } setChemicalAssociationDropdowns(request, hasFunctionalizingEntity); } public void persistCompositionFileDropdowns(HttpServletRequest request, LabFileBean fileBean) throws Exception { InitSetup.getInstance().persistLookup(request, "LabFile", "type", "otherType", fileBean.getDomainFile().getType()); InitSetup.getInstance().getDefaultAndOtherLookupTypes(request, "fileTypes", "LabFile", "type", "otherType", true); } public SortedSet<String> getFunctionTypes(HttpServletRequest request) throws Exception { SortedSet<String> defaultTypes = InitSetup .getInstance() .getServletContextDefaultTypesByReflection( request.getSession().getServletContext(), "defaultFunctionTypes", "gov.nih.nci.cananolab.domain.particle.samplecomposition.Function"); SortedSet<String> otherTypes = compService.getAllOtherFunctionTypes(); SortedSet<String> types = new TreeSet<String>(defaultTypes); types.addAll(otherTypes); request.getSession().setAttribute("functionTypes", types); return types; } public SortedSet<String> getNanoparticleEntityTypes( HttpServletRequest request) throws Exception { SortedSet<String> defaultTypes = InitSetup .getInstance() .getServletContextDefaultTypesByReflection( request.getSession().getServletContext(), "defaultNanoparticleEntityTypes", "gov.nih.nci.cananolab.domain.particle.samplecomposition.base.NanoparticleEntity"); SortedSet<String> otherTypes = compService .getAllOtherNanoparticleEntityTypes(); SortedSet<String> types = new TreeSet<String>(defaultTypes); types.addAll(otherTypes); request.getSession().setAttribute("nanoparticleEntityTypes", types); return types; } public SortedSet<String> getFunctionalizingEntityTypes( HttpServletRequest request) throws Exception { SortedSet<String> defaultTypes = InitSetup .getInstance() .getServletContextDefaultTypesByReflection( request.getSession().getServletContext(), "defaultFunctionalizingEntityTypes", "gov.nih.nci.cananolab.domain.particle.samplecomposition.functionalization.FunctionalizingEntity"); SortedSet<String> otherTypes = compService .getAllOtherFunctionalizingEntityTypes(); SortedSet<String> types = new TreeSet<String>(defaultTypes); types.addAll(otherTypes); request.getSession().setAttribute("functionalizingEntityTypes", types); return types; } public SortedSet<String> getChemicalAssociationTypes( HttpServletRequest request) throws Exception { SortedSet<String> defaultTypes = InitSetup .getInstance() .getServletContextDefaultTypesByReflection( request.getSession().getServletContext(), "defaultAssociationTypes", "gov.nih.nci.cananolab.domain.particle.samplecomposition.chemicalassociation.ChemicalAssociation"); SortedSet<String> otherTypes = compService .getAllOtherChemicalAssociationTypes(); SortedSet<String> types = new TreeSet<String>(defaultTypes); types.addAll(otherTypes); request.getSession().setAttribute("chemicalAssociationTypes", types); return types; } public SortedSet<String> getEmulsionComposingElementTypes( HttpServletRequest request) throws CaNanoLabException { SortedSet<String> emulsionCETypes = LookupService .getDefaultAndOtherLookupTypes("Emulsion", "composingElementType", "otherComposingElementType"); SortedSet<String> ceTypes = LookupService .getDefaultAndOtherLookupTypes("ComposingElement", "type", "otherType"); emulsionCETypes.addAll(ceTypes); request.getSession().setAttribute("emulsionComposingElementTypes", emulsionCETypes); return emulsionCETypes; } public SortedSet<String> getTargetTypes(HttpServletRequest request) throws Exception { SortedSet<String> defaultTypes = InitSetup .getInstance() .getServletContextDefaultTypesByReflection( request.getSession().getServletContext(), "defaultTargetTypes", "gov.nih.nci.cananolab.domain.particle.samplecomposition.Target"); SortedSet<String> otherTypes = compService.getAllOtherFunctionTypes(); SortedSet<String> types = new TreeSet<String>(defaultTypes); types.addAll(otherTypes); request.getSession().setAttribute("targetTypes", types); return types; } }
package gov.nih.nci.ncicb.cadsr.loader.ui; import gov.nih.nci.ncicb.cadsr.domain.DomainObjectFactory; import gov.nih.nci.ncicb.cadsr.domain.PermissibleValue; import gov.nih.nci.ncicb.cadsr.domain.ValueDomain; import gov.nih.nci.ncicb.cadsr.loader.event.ElementChangeEvent; import gov.nih.nci.ncicb.cadsr.loader.event.ElementChangeListener; import gov.nih.nci.ncicb.cadsr.loader.ext.CadsrModule; import gov.nih.nci.ncicb.cadsr.loader.ext.CadsrModuleListener; import gov.nih.nci.ncicb.cadsr.loader.ui.tree.UMLNode; import gov.nih.nci.ncicb.cadsr.loader.ui.util.UIUtil; import gov.nih.nci.ncicb.cadsr.loader.util.ConventionUtil; import gov.nih.nci.ncicb.cadsr.loader.util.StringUtil; import javax.swing.JTextArea; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.text.DateFormat; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; public class MapToExistingVDPanel extends JPanel implements Editable, CadsrModuleListener { private JLabel vdPrefDefTitleLabel = new JLabel("VD Preferred Definition"), vdLongNameLabel = new JLabel("VD Long Name"), vdDatatypeTitleLabel = new JLabel("VD Datatype"), vdCdIdTitleLabel = new JLabel("VD CD PublicId / Version"), vdRepIdTitleLabel = new JLabel("Representation Term"), vdCdLongNameTitleLabel = new JLabel("VD CD Long Name"), vdCreatedByLabel = new JLabel("Created By"), vdCreatedDateLabel = new JLabel("Created Date"); private JLabel vdDatatypeTitleLabelValue = new JLabel(), vdLongNameLabelValue = new JLabel(), vdTypeTitleLabelValue = new JLabel(), vdCdIdTitleLabelValue = new JLabel(), vdRepIdTitleLabelValue = new JLabel(), vdCdLongNameTitleLabelValue = new JLabel(), vdCreatedByLabelValue = new JLabel(), vdCreatedDateLabelValue = new JLabel(); private JTextArea vdPrefDefValueTextField = new JTextArea(); private JButton searchButton; private JButton clearButton; private JButton lvdCadsrButton; private CadsrDialog cadsrVDDialog; private ValueDomain vd, tempVD; private UMLNode umlNode; private CadsrModule cadsrModule; public boolean applied = false; private boolean isInitialized = false; private boolean isSearched = false; private List<ElementChangeListener> changeListeners = new ArrayList<ElementChangeListener>(); private List<PropertyChangeListener> propChangeListeners = new ArrayList<PropertyChangeListener>(); private Logger logger = Logger.getLogger(MapToExistingVDPanel.class.getName()); public MapToExistingVDPanel() { if(!isInitialized) initUI(); } public void update(ValueDomain vd, UMLNode umlNode) { this.vd = vd; this.umlNode = umlNode; tempVD = DomainObjectFactory.newValueDomain(); tempVD.setConceptualDomain(vd.getConceptualDomain()); tempVD.setPreferredDefinition(vd.getPreferredDefinition()); tempVD.setRepresentation(vd.getRepresentation()); tempVD.setLongName(vd.getLongName()); tempVD.setDataType(vd.getDataType()); tempVD.setVdType(vd.getVdType()); tempVD.setPublicId(vd.getPublicId()); tempVD.setVersion(vd.getVersion()); tempVD.setAudit(vd.getAudit()); if(!isInitialized) initUI(); initValues(); } private void initUI() { isInitialized = true; applied = false; this.setLayout(new BorderLayout()); JPanel mainPanel = new JPanel(new GridBagLayout()); vdPrefDefValueTextField.setLineWrap(true); vdPrefDefValueTextField.setEnabled(false); vdPrefDefValueTextField.setWrapStyleWord(true); JScrollPane defScrollPane = new JScrollPane(vdPrefDefValueTextField); defScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); defScrollPane.setPreferredSize(new Dimension(200, 100)); searchButton = new JButton("Search Value Domains"); searchButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { cadsrVDDialog.setAlwaysOnTop(true); cadsrVDDialog.setVisible(true); ValueDomain _vd = (ValueDomain)cadsrVDDialog.getAdminComponent(); if(_vd != null){ tempVD.setPublicId(_vd.getPublicId()); tempVD.setConceptualDomain(_vd.getConceptualDomain()); tempVD.setPreferredDefinition(_vd.getPreferredDefinition()); tempVD.setRepresentation(_vd.getRepresentation()); tempVD.setLongName(_vd.getLongName()); tempVD.setDataType(_vd.getDataType()); tempVD.setVdType(_vd.getVdType()); tempVD.setVersion(_vd.getVersion()); tempVD.setAudit(_vd.getAudit()); setSearchedValues(); isSearched = true; firePropertyChangeEvent(new PropertyChangeEvent(this, ApplyButtonPanel.SAVE, null, true)); } }}); JPanel searchButtonPanel = new JPanel(); searchButtonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT)); searchButtonPanel.add(searchButton); lvdCadsrButton = new JButton("<html>Compare<br>Values</html>"); lvdCadsrButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { try { List<PermissibleValue> cadsrPVs = cadsrModule.getPermissibleValues(tempVD); List<PermissibleValue> localPVs = vd.getPermissibleValues(); PVCompareDialog pvCompareDialog = new PVCompareDialog(localPVs, cadsrPVs); pvCompareDialog.setVisible(true); pvCompareDialog.setAlwaysOnTop(true); } catch (Exception e) { logger.error(e); e.printStackTrace(); } }}); clearButton = new JButton("Clear"); clearButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { vdPrefDefValueTextField.setText(""); vdLongNameLabelValue.setText(""); vdDatatypeTitleLabelValue.setText(""); vdTypeTitleLabelValue.setText(""); vdCdIdTitleLabelValue.setText(""); vdCdLongNameTitleLabelValue.setText(""); vdRepIdTitleLabelValue.setText(""); vdCreatedByLabelValue.setText(""); vdCreatedDateLabelValue.setText(""); lvdCadsrButton.setVisible(false); tempVD.setConceptualDomain(null); tempVD.setPreferredDefinition(""); tempVD.setRepresentation(null); tempVD.setLongName(""); tempVD.setDataType(""); tempVD.setVdType(null); tempVD.setPublicId(null); if(isSearched) firePropertyChangeEvent(new PropertyChangeEvent(this, ApplyButtonPanel.SAVE, null, true)); isSearched = false; }}); JPanel clearButtonPanel = new JPanel(); clearButtonPanel.setLayout(new FlowLayout(FlowLayout.LEFT)); clearButtonPanel.add(clearButton); UIUtil.insertInBag(mainPanel, vdPrefDefTitleLabel, 0, 1); UIUtil.insertInBag(mainPanel, defScrollPane, 1, 1, 3, 2); UIUtil.insertInBag(mainPanel, lvdCadsrButton, 2, 1, 1, 10); UIUtil.insertInBag(mainPanel, vdLongNameLabel, 0, 3); UIUtil.insertInBag(mainPanel, vdLongNameLabelValue, 1, 3); UIUtil.insertInBag(mainPanel, vdDatatypeTitleLabel, 0, 5); UIUtil.insertInBag(mainPanel, vdDatatypeTitleLabelValue, 1, 5); UIUtil.insertInBag(mainPanel, vdCdIdTitleLabel, 0, 6); UIUtil.insertInBag(mainPanel, vdCdIdTitleLabelValue, 1, 6); UIUtil.insertInBag(mainPanel, vdCdLongNameTitleLabel, 0, 7); UIUtil.insertInBag(mainPanel, vdCdLongNameTitleLabelValue, 1, 7); UIUtil.insertInBag(mainPanel, vdRepIdTitleLabel, 0, 8); UIUtil.insertInBag(mainPanel, vdRepIdTitleLabelValue, 1, 8); UIUtil.insertInBag(mainPanel, vdCreatedByLabel, 0, 9); UIUtil.insertInBag(mainPanel, vdCreatedByLabelValue, 1, 9); UIUtil.insertInBag(mainPanel, vdCreatedDateLabel, 0, 10); UIUtil.insertInBag(mainPanel, vdCreatedDateLabelValue, 1, 10); UIUtil.insertInBag(mainPanel, clearButtonPanel, 0, 11); UIUtil.insertInBag(mainPanel, searchButtonPanel, 2, 11); JScrollPane mainScrollPane = new JScrollPane(mainPanel); mainScrollPane.getVerticalScrollBar().setUnitIncrement(30); this.add(mainScrollPane, BorderLayout.CENTER); } private void initValues() { if(StringUtil.isEmpty(tempVD.getPublicId())) { vdPrefDefValueTextField.setText(""); vdLongNameLabelValue.setText(""); vdDatatypeTitleLabelValue.setText(""); vdTypeTitleLabelValue.setText(""); vdCdIdTitleLabelValue.setText(""); vdCdLongNameTitleLabelValue.setText(""); vdRepIdTitleLabelValue.setText(""); vdCreatedByLabelValue.setText(""); vdCreatedDateLabelValue.setText(""); lvdCadsrButton.setVisible(false); } else { vdPrefDefValueTextField.setText(tempVD.getPreferredDefinition()); vdLongNameLabelValue.setText(tempVD.getLongName()); vdDatatypeTitleLabelValue.setText(tempVD.getDataType()); vdTypeTitleLabelValue.setText(tempVD.getVdType()); vdCdIdTitleLabelValue.setText(ConventionUtil.publicIdVersion(tempVD.getConceptualDomain())); vdCdLongNameTitleLabelValue.setText(tempVD.getConceptualDomain().getLongName()); vdRepIdTitleLabelValue.setText(ConventionUtil.publicIdVersion(tempVD.getRepresentation())); vdCreatedByLabelValue.setText(tempVD.getAudit().getCreatedBy()); vdCreatedDateLabelValue.setText(getFormatedDate(tempVD.getAudit().getCreationDate())); lvdCadsrButton.setVisible(true); } } private void setSearchedValues(){ if(tempVD != null){ if(tempVD.getConceptualDomain() != null){ vdPrefDefValueTextField.setText(tempVD.getPreferredDefinition()); vdCdIdTitleLabelValue.setText(ConventionUtil.publicIdVersion(tempVD.getConceptualDomain())); vdCdLongNameTitleLabelValue.setText(tempVD.getConceptualDomain().getLongName()); } if(tempVD.getRepresentation() != null) vdRepIdTitleLabelValue.setText(ConventionUtil.publicIdVersion(tempVD.getRepresentation())); if(tempVD.getLongName() != null && !tempVD.getLongName().equals("Unable to lookup CD Long Name")) vdLongNameLabelValue.setText(tempVD.getLongName()); if(tempVD.getDataType() != null) vdDatatypeTitleLabelValue.setText(tempVD.getDataType()); if(tempVD.getVdType() != null) vdTypeTitleLabelValue.setText(tempVD.getVdType()); if(tempVD.getAudit() != null){ vdCreatedByLabelValue.setText(tempVD.getAudit().getCreatedBy()); vdCreatedDateLabelValue.setText(getFormatedDate(tempVD.getAudit().getCreationDate())); } lvdCadsrButton.setVisible(true); } } public static void main(String args[]) { // JFrame frame = new JFrame(); // ValueDomainViewPanel vdPanel = new ValueDomainViewPanel(); // vdPanel.setVisible(true); // frame.add(vdPanel); // frame.setVisible(true); // frame.setSize(450, 350); } public void applyPressed() { applied = true; vd.setConceptualDomain(tempVD.getConceptualDomain()); vd.setRepresentation(tempVD.getRepresentation()); vd.setLongName(tempVD.getLongName()); vd.setDataType(tempVD.getDataType()); vd.setPreferredDefinition(tempVD.getPreferredDefinition()); vd.setVdType(tempVD.getVdType()); vd.setPublicId(tempVD.getPublicId()); vd.setVersion(tempVD.getVersion()); vd.setAudit(tempVD.getAudit()); vd.setId(tempVD.getId()); firePropertyChangeEvent(new PropertyChangeEvent(this, ApplyButtonPanel.SAVE, null, false)); fireElementChangeEvent(new ElementChangeEvent((Object)umlNode)); } public void setCadsrVDDialog(CadsrDialog cadsrVDDialog) { this.cadsrVDDialog = cadsrVDDialog; } public void setCadsrModule(CadsrModule cadsrModule){ this.cadsrModule = cadsrModule; } public void addElementChangeListener(ElementChangeListener listener){ changeListeners.add(listener); } private void fireElementChangeEvent(ElementChangeEvent event) { for(ElementChangeListener l : changeListeners) l.elementChanged(event); } private void firePropertyChangeEvent(PropertyChangeEvent evt) { for(PropertyChangeListener l : propChangeListeners) l.propertyChange(evt); } private String getFormatedDate(java.util.Date date){ return DateFormat.getDateTimeInstance().format(date); } public String getPubId() { return tempVD.getPublicId(); } public boolean isApplied() { return applied; } public void setApplied(boolean applied) { this.applied = applied; } public void addPropertyChangeListener(PropertyChangeListener l) { super.addPropertyChangeListener(l);; propChangeListeners.add(l); } }